Skip to main content

magi/
omp_rpc.rs

1//! Chat turns over `omp --mode rpc`.
2//!
3//! A chat turn whose agent is `kind = "omp"` keeps one RPC process for the
4//! whole turn instead of a single `omp -p` call. That gives the web Chat what
5//! the operator gets in their own terminal:
6//!
7//! - the reply streams: the driver publishes the in-progress text and the tool
8//!   it is running to [`Hooks::live`], which `GET /api/talks/{id}/live` serves;
9//! - a message sent while the agent works is delivered into the running
10//!   session (`prompt` with `streamingBehavior: "steer"`), not parked for the
11//!   next turn;
12//! - the operator can stop the agent: the stop file makes the driver send
13//!   `abort`;
14//! - the turn ends only when the session is settled - no run, no queued input,
15//!   no background job left - so work the agent started in the background
16//!   finishes inside the turn.
17//!
18//! The wire is omp's JSONL RPC protocol (`omp://rpc.md`), protocol version 1.
19//! Every frame the answer extraction in `agent` reads (`message_end`,
20//! `turn_end`, `agent_end`, `tool_execution_start`) is appended to the seat's
21//! stdout log, behind a synthesized `{"type":"session"}` line from
22//! `get_state`, so the stored `<stem>.out` reads exactly like an `omp -p
23//! --mode=json` stream.
24
25use std::path::{Path, PathBuf};
26use std::sync::Arc;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::time::Duration;
29
30use anyhow::{Context, Result, bail};
31use jiff::Timestamp;
32use serde::{Deserialize, Serialize};
33use serde_json::{Value, json};
34use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
35
36use crate::agent::Captured;
37
38/// How often queued input, the stop file and the live snapshot are checked.
39const TICK: Duration = Duration::from_millis(500);
40
41/// Longest tool summary shown in the live snapshot.
42const ACTIVITY_CHARS: usize = 160;
43
44/// Commit the durable draft after RPC prompt admission.
45pub type AdmissionCallback = Box<dyn FnOnce() -> Result<()> + Send>;
46
47/// Input that arrived while a turn was running.
48pub struct Input {
49    /// The prompt text for the agent.
50    pub text: String,
51    /// Steer the running agent (operator input) rather than queue it after the
52    /// current run (automatic notices).
53    pub steer: bool,
54    /// Commit the durable draft only after omp admits the prompt.
55    pub accepted: Option<AdmissionCallback>,
56}
57
58/// Turn-scoped connection between a chat turn and its RPC driver.
59pub struct Hooks {
60    /// Where the in-progress reply is published.
61    pub live: PathBuf,
62    /// A file whose appearance asks the driver to abort the agent.
63    pub stop: PathBuf,
64    /// Takes input queued since the last call; called on every tick.
65    pub input: Box<dyn Fn() -> Result<Option<Input>> + Send + Sync>,
66    stopped: AtomicBool,
67}
68
69impl Hooks {
70    /// Hooks publishing to `live`, watching `stop`, and pulling `input`.
71    pub fn new(
72        live: PathBuf,
73        stop: PathBuf,
74        input: Box<dyn Fn() -> Result<Option<Input>> + Send + Sync>,
75    ) -> Self {
76        Self {
77            live,
78            stop,
79            input,
80            stopped: AtomicBool::new(false),
81        }
82    }
83
84    /// Did the operator stop this turn?
85    pub fn stopped(&self) -> bool {
86        self.stopped.load(Ordering::SeqCst)
87    }
88}
89
90tokio::task_local! {
91    static HOOKS: Arc<Hooks>;
92}
93
94/// Run `fut` with `hooks` available to the omp RPC driver it spawns.
95pub async fn with_hooks<F: Future>(hooks: Arc<Hooks>, fut: F) -> F::Output {
96    HOOKS.scope(hooks, fut).await
97}
98
99/// The hooks of the chat turn this task belongs to, if any.
100pub(crate) fn current() -> Option<Arc<Hooks>> {
101    HOOKS.try_with(Arc::clone).ok()
102}
103
104/// The in-progress reply, as the web Chat shows it.
105#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
106pub struct Live {
107    /// Identifies this RPC invocation, including across fallback attempts.
108    #[serde(default)]
109    pub turn: String,
110    /// The assistant text streamed so far (the latest message with text).
111    pub text: String,
112    /// The tool currently running, summarized.
113    pub activity: Option<String>,
114    /// The operator asked to stop and the abort was sent.
115    pub stopping: bool,
116    /// Messages delivered into the running session.
117    pub steered: u32,
118    /// When this snapshot was written.
119    pub at: Option<Timestamp>,
120}
121
122/// Read a live snapshot; `None` when absent or unreadable.
123pub fn read_live(path: &Path) -> Option<Live> {
124    serde_json::from_slice(&std::fs::read(path).ok()?).ok()
125}
126
127fn stop_lock(stop: &Path) -> Result<std::fs::File> {
128    let file = std::fs::OpenOptions::new()
129        .create(true)
130        .truncate(false)
131        .read(true)
132        .write(true)
133        .open(stop.with_extension("lock"))?;
134    crate::pr_head::lock_file(&file)?;
135    Ok(file)
136}
137
138/// Accept a stop only while the identified driver is taking commands.
139pub fn request_stop(live: &Path, stop: &Path) -> Result<bool> {
140    let Some(snapshot) = read_live(live) else {
141        return Ok(false);
142    };
143    let _lock = stop_lock(stop)?;
144    if !read_live(live).is_some_and(|current| current.turn == snapshot.turn) {
145        return Ok(false);
146    }
147    std::fs::write(stop, snapshot.turn.as_bytes())?;
148    Ok(true)
149}
150
151struct LiveGuard<'a> {
152    hooks: &'a Hooks,
153    turn: String,
154}
155
156impl LiveGuard<'_> {
157    fn check_stop(&self, settled: bool) -> Result<bool> {
158        let _lock = stop_lock(&self.hooks.stop)?;
159        let requested = std::fs::read_to_string(&self.hooks.stop).is_ok_and(|id| id == self.turn);
160        if requested {
161            self.hooks.stopped.store(true, Ordering::SeqCst);
162            let _ = std::fs::remove_file(&self.hooks.stop);
163        }
164        if settled || requested {
165            let _ = std::fs::remove_file(&self.hooks.live);
166        }
167        Ok(requested)
168    }
169}
170
171impl Drop for LiveGuard<'_> {
172    fn drop(&mut self) {
173        let _ = self.check_stop(true);
174    }
175}
176
177fn write_live(path: &Path, live: &Live) {
178    let Ok(body) = serde_json::to_vec(live) else {
179        return;
180    };
181    let tmp = path.with_extension("json.tmp");
182    if std::fs::write(&tmp, body).is_ok() && std::fs::rename(&tmp, path).is_err() {
183        // A reader may hold the old snapshot open on Windows; the next tick
184        // writes again.
185        let _ = std::fs::remove_file(&tmp);
186    }
187}
188
189/// A prompt omp finished with an error.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub(crate) struct PromptError {
192    pub message: String,
193    pub http_status: Option<u64>,
194    pub code: Option<String>,
195}
196
197/// How a driven turn ended.
198#[derive(Debug, Default)]
199pub(crate) struct Ended {
200    /// The last error any prompt of the turn reported.
201    pub error: Option<PromptError>,
202    /// Error notices omp sent outside any prompt.
203    pub notices: Vec<String>,
204    /// The operator stopped the turn.
205    pub stopped: bool,
206    /// The final text of each answer the agent gave in this turn, in order;
207    /// more than one when input was steered into the running session.
208    pub answers: Vec<String>,
209}
210
211fn push_answer(answers: &mut Vec<String>, text: &str) {
212    let text = text.trim();
213    if !text.is_empty() && answers.last().is_none_or(|last| last != text) {
214        answers.push(text.to_owned());
215    }
216}
217
218/// How long to keep reading omp's stdout after closing its stdin.
219const EXIT_DRAIN: Duration = Duration::from_secs(15);
220
221fn summarize(tool: &str, args: &Value) -> String {
222    let detail = ["i", "command", "path", "pattern", "query", "url", "task"]
223        .iter()
224        .find_map(|key| args.get(key).and_then(Value::as_str))
225        .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" "));
226    let mut out = match detail {
227        Some(detail) if !detail.is_empty() => format!("{tool}: {detail}"),
228        _ => tool.to_owned(),
229    };
230    if out.chars().count() > ACTIVITY_CHARS {
231        out = out.chars().take(ACTIVITY_CHARS).collect::<String>() + "…";
232    }
233    out
234}
235
236fn prompt_error(value: &Value) -> PromptError {
237    match value {
238        Value::String(message) => PromptError {
239            message: message.clone(),
240            http_status: None,
241            code: None,
242        },
243        _ => PromptError {
244            message: value
245                .get("message")
246                .and_then(Value::as_str)
247                .unwrap_or("omp reported an error")
248                .to_owned(),
249            http_status: value.get("httpStatus").and_then(Value::as_u64),
250            code: value.get("code").and_then(Value::as_str).map(str::to_owned),
251        },
252    }
253}
254
255struct Driver<W> {
256    writer: W,
257    log: Captured,
258    live: Live,
259    /// Text of the assistant message streaming now.
260    current: String,
261    /// Text of the last assistant message that had any.
262    last: String,
263    dirty: bool,
264}
265
266impl<W: AsyncWrite + Unpin> Driver<W> {
267    async fn send(&mut self, frame: Value) -> Result<()> {
268        let mut line = serde_json::to_vec(&frame)?;
269        line.push(b'\n');
270        self.writer
271            .write_all(&line)
272            .await
273            .context("write to omp rpc")?;
274        self.writer.flush().await.context("flush omp rpc")
275    }
276
277    fn record(&self, line: &str) {
278        if let Ok(mut log) = self.log.lock() {
279            log.extend_from_slice(line.as_bytes());
280            log.push(b'\n');
281        }
282    }
283
284    fn refresh(&mut self) {
285        let text = if self.current.trim().is_empty() {
286            &self.last
287        } else {
288            &self.current
289        };
290        if self.live.text != *text {
291            self.live.text.clone_from(text);
292            self.dirty = true;
293        }
294    }
295
296    fn publish(&mut self, hooks: Option<&Hooks>) {
297        if !self.dirty {
298            return;
299        }
300        if let Some(hooks) = hooks {
301            self.live.at = Some(Timestamp::now());
302            write_live(&hooks.live, &self.live);
303        }
304        self.dirty = false;
305    }
306}
307
308/// Drive one chat turn: send `prompt`, deliver input the hooks hand over,
309/// honour a stop request, and return once every prompt has finished and the
310/// session is settled. Dropping `writer` on return closes omp's stdin, which
311/// ends the process.
312pub(crate) async fn drive<W, R>(
313    writer: W,
314    reader: R,
315    prompt: String,
316    hooks: Option<Arc<Hooks>>,
317    log: Captured,
318) -> Result<Ended>
319where
320    W: AsyncWrite + Unpin,
321    R: AsyncRead + Unpin,
322{
323    let hooks = hooks.as_deref();
324    let mut lines = BufReader::new(reader).lines();
325    loop {
326        let line = lines
327            .next_line()
328            .await
329            .context("read omp rpc")?
330            .context("omp exited before it was ready")?;
331        if serde_json::from_str::<Value>(&line)
332            .is_ok_and(|frame| frame.get("type").and_then(Value::as_str) == Some("ready"))
333        {
334            break;
335        }
336    }
337
338    let mut driver = Driver {
339        writer,
340        log,
341        live: Live::default(),
342        current: String::new(),
343        last: String::new(),
344        // Publish at once: the snapshot's presence tells the web a stop can
345        // still be honoured.
346        dirty: true,
347    };
348    driver
349        .send(json!({"id": "filter", "type": "set_event_filter", "events": null, "messageUpdates": "delta"}))
350        .await?;
351    driver
352        .send(json!({"id": "state", "type": "get_state"}))
353        .await?;
354    driver
355        .send(json!({"id": "p0", "type": "prompt", "message": prompt}))
356        .await?;
357
358    let guard = hooks.map(|hooks| LiveGuard {
359        hooks,
360        turn: format!("{}-{}", std::process::id(), Timestamp::now()),
361    });
362    if let Some(guard) = &guard {
363        let _lock = stop_lock(&guard.hooks.stop)?;
364        driver.live.turn.clone_from(&guard.turn);
365        driver.publish(hooks);
366    }
367    let mut admission: Option<(String, Option<AdmissionCallback>)> = None;
368    let mut outstanding = vec!["p0".to_owned()];
369    let mut settled = false;
370    let mut sent = 0u32;
371    let mut ended = Ended::default();
372    let mut tick = tokio::time::interval(TICK);
373    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
374    loop {
375        // A stopped turn ends as soon as its prompts answered: closing stdin
376        // disposes the session, which cancels whatever was still running.
377        let finishing = outstanding.is_empty() && (settled || ended.stopped);
378        if let Some(guard) = &guard
379            && !ended.stopped
380            && (finishing || guard.hooks.stop.exists())
381            && guard.check_stop(finishing)?
382        {
383            ended.stopped = true;
384            driver.live.stopping = true;
385            driver.send(json!({"id": "abort", "type": "abort"})).await?;
386        }
387        if finishing {
388            break;
389        }
390        tokio::select! {
391            line = lines.next_line() => {
392                let Some(line) = line.context("read omp rpc")? else {
393                    bail!("omp exited before the turn finished");
394                };
395                let Ok(frame) = serde_json::from_str::<Value>(&line) else {
396                    continue;
397                };
398                match frame.get("type").and_then(Value::as_str).unwrap_or_default() {
399                    "response" => {
400                        let id = frame.get("id").and_then(Value::as_str).unwrap_or_default();
401                        let ok = frame.get("success").and_then(Value::as_bool).unwrap_or(false);
402                        if admission.as_ref().is_some_and(|(pending, _)| pending == id) {
403                            let (_, accepted) = admission.take().expect("matching admission");
404                            if ok && let Some(accepted) = accepted {
405                                accepted()?;
406                            }
407                        }
408                        if id == "state" {
409                            if let Some(session) = frame
410                                .pointer("/data/sessionId")
411                                .and_then(Value::as_str)
412                            {
413                                driver.record(&json!({"type": "session", "id": session}).to_string());
414                            }
415                        } else if !ok && outstanding.iter().any(|p| p == id) {
416                            // Refused before admission: no prompt_result follows.
417                            outstanding.retain(|p| p != id);
418                            ended.error = Some(prompt_error(
419                                frame.get("error").unwrap_or(&Value::Null),
420                            ));
421                        }
422                    }
423                    "prompt_result" => {
424                        let id = frame.get("id").and_then(Value::as_str).unwrap_or_default();
425                        if admission.as_ref().is_some_and(|(pending, _)| pending == id) {
426                            let (_, accepted) = admission.take().expect("matching admission");
427                            if let Some(accepted) = accepted {
428                                accepted()?;
429                            }
430                        }
431                        outstanding.retain(|p| p != id);
432                        if frame.get("status").and_then(Value::as_str) == Some("error") {
433                            ended.error = Some(prompt_error(
434                                frame.get("error").unwrap_or(&Value::Null),
435                            ));
436                        }
437                        settled = frame
438                            .get("sessionSettled")
439                            .and_then(Value::as_bool)
440                            .unwrap_or(false);
441                        // Each prompt the agent answered: a steered turn
442                        // replies to every message, not only the last one.
443                        push_answer(&mut ended.answers, &driver.last);
444                    }
445                    "session_settled" => settled = true,
446                    "message_start" => {
447                        if frame.pointer("/message/role").and_then(Value::as_str) == Some("assistant") {
448                            driver.current.clear();
449                        }
450                    }
451                    "message_update" => {
452                        let event = frame.get("assistantMessageEvent");
453                        if event.and_then(|e| e.get("type")).and_then(Value::as_str) == Some("text_delta")
454                            && let Some(delta) = event.and_then(|e| e.get("delta")).and_then(Value::as_str)
455                        {
456                            driver.current.push_str(delta);
457                            driver.refresh();
458                        }
459                    }
460                    "message_end" | "turn_end" | "agent_end" => {
461                        if frame.get("type").and_then(Value::as_str) == Some("message_end")
462                            && frame.pointer("/message/role").and_then(Value::as_str) == Some("assistant")
463                        {
464                            let text: String = frame
465                                .pointer("/message/content")
466                                .and_then(Value::as_array)
467                                .into_iter()
468                                .flatten()
469                                .filter(|part| part.get("type").and_then(Value::as_str) == Some("text"))
470                                .filter_map(|part| part.get("text").and_then(Value::as_str))
471                                .collect();
472                            if !text.trim().is_empty() {
473                                driver.last = text;
474                            }
475                            driver.current.clear();
476                            driver.refresh();
477                        }
478                        driver.record(&line);
479                    }
480                    "tool_execution_start" => {
481                        let tool = frame.get("toolName").and_then(Value::as_str).unwrap_or("tool");
482                        driver.live.activity =
483                            Some(summarize(tool, frame.get("args").unwrap_or(&Value::Null)));
484                        driver.dirty = true;
485                        driver.record(&line);
486                    }
487                    "tool_execution_end" => {
488                        driver.live.activity = None;
489                        driver.dirty = true;
490                    }
491                    "notice" => {
492                        if let Some(notice) = error_notice(&line) {
493                            ended.notices.push(notice);
494                        }
495                    }
496                    _ => {}
497                }
498            }
499            _ = tick.tick() => {
500                if let Some(hooks) = hooks {
501                    if !ended.stopped && admission.is_none() {
502                        match (hooks.input)() {
503                            Ok(Some(input)) => {
504                                sent += 1;
505                                let id = format!("p{sent}");
506                                let behavior = if input.steer { "steer" } else { "followUp" };
507                                driver
508                                    .send(json!({
509                                        "id": id, "type": "prompt", "message": input.text,
510                                        "streamingBehavior": behavior,
511                                    }))
512                                    .await?;
513                                admission = Some((id.clone(), input.accepted));
514                                outstanding.push(id);
515                                settled = false;
516                                driver.live.steered = sent;
517                                driver.dirty = true;
518                            }
519                            Ok(None) => {}
520                            Err(error) => tracing::warn!("chat input for the running turn: {error:#}"),
521                        }
522                    }
523                }
524                if !ended.stopped {
525                    driver.publish(hooks);
526                }
527            }
528        }
529    }
530    drop(guard);
531    push_answer(&mut ended.answers, &driver.last);
532    // omp keeps writing after the turn (UI updates, shutdown notices) and
533    // exits 1 when its stdout breaks, so close stdin and read to EOF.
534    let Driver { writer, .. } = driver;
535    drop(writer);
536    let drained = tokio::time::timeout(EXIT_DRAIN, async {
537        while let Ok(Some(line)) = lines.next_line().await {
538            if let Some(notice) = error_notice(&line) {
539                ended.notices.push(notice);
540            }
541        }
542    })
543    .await;
544    if drained.is_err() {
545        tracing::warn!("omp kept its stdout open after the turn ended");
546    }
547    Ok(ended)
548}
549
550/// An error `notice` frame's message: omp reports persistence and restore
551/// failures that way, outside any prompt.
552fn error_notice(line: &str) -> Option<String> {
553    let frame: Value = serde_json::from_str(line).ok()?;
554    (frame.get("type").and_then(Value::as_str) == Some("notice")
555        && frame.get("level").and_then(Value::as_str) == Some("error"))
556    .then(|| {
557        frame
558            .get("message")
559            .and_then(Value::as_str)
560            .unwrap_or("omp reported an error")
561            .to_owned()
562    })
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568    use std::sync::Mutex;
569    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, duplex};
570
571    /// The test plays omp: reads the driver's commands, answers with frames.
572    /// One pipe per direction, like a child's stdin and stdout, so the driver
573    /// closing its stdin is visible while its stdout stays readable.
574    struct Server {
575        lines: tokio::io::Lines<BufReader<DuplexStream>>,
576        out: DuplexStream,
577    }
578
579    impl Server {
580        async fn emit(&mut self, frame: Value) {
581            let mut line = frame.to_string().into_bytes();
582            line.push(b'\n');
583            self.out.write_all(&line).await.unwrap();
584        }
585
586        async fn command(&mut self) -> Value {
587            let line = self.lines.next_line().await.unwrap().expect("a command");
588            serde_json::from_str(&line).unwrap()
589        }
590
591        async fn handshake(&mut self) {
592            self.emit(json!({"type": "ready", "protocolVersion": 1}))
593                .await;
594            assert_eq!(self.command().await["type"], "set_event_filter");
595            assert_eq!(self.command().await["type"], "get_state");
596            self.emit(json!({"type": "response", "id": "state", "command": "get_state", "success": true, "data": {"sessionId": "s-1"}})).await;
597        }
598
599        async fn answer(&mut self, text: &str) {
600            self.emit(
601                json!({"type": "message_start", "message": {"role": "assistant", "content": []}}),
602            )
603            .await;
604            self.emit(json!({"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "delta": text}})).await;
605            self.emit(json!({"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": text}]}})).await;
606        }
607    }
608
609    fn pair() -> (Server, DuplexStream, DuplexStream) {
610        let (stdin_driver, stdin_server) = duplex(1 << 16);
611        let (stdout_server, stdout_driver) = duplex(1 << 16);
612        (
613            Server {
614                lines: BufReader::new(stdin_server).lines(),
615                out: stdout_server,
616            },
617            stdin_driver,
618            stdout_driver,
619        )
620    }
621
622    impl Server {
623        /// Wait for the driver to close stdin, then write more output the
624        /// way omp does at shutdown, which must still be read, and exit.
625        async fn finish(mut self, notice: Option<&str>) {
626            assert!(
627                self.lines.next_line().await.unwrap().is_none(),
628                "stdin closed"
629            );
630            self.emit(json!({"type": "extension_ui_request", "method": "setWidget"}))
631                .await;
632            if let Some(message) = notice {
633                self.emit(json!({"type": "notice", "level": "error", "message": message}))
634                    .await;
635            }
636        }
637    }
638
639    fn hooks(dir: &Path, queued: Arc<Mutex<Vec<Input>>>) -> Arc<Hooks> {
640        Arc::new(Hooks::new(
641            dir.join("live.json"),
642            dir.join("stop"),
643            Box::new(move || Ok(queued.lock().unwrap().pop())),
644        ))
645    }
646
647    #[tokio::test]
648    async fn waits_for_settle_and_logs_an_extractable_stream() {
649        let (mut server, w, r) = pair();
650        let log: Captured = Arc::default();
651        let driven = tokio::spawn(drive(w, r, "hello".into(), None, Arc::clone(&log)));
652        server.handshake().await;
653        let prompt = server.command().await;
654        assert_eq!(prompt["message"], "hello");
655        server.answer("working on it").await;
656        // The agent yielded but a background job is still running.
657        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": false})).await;
658        server.answer("all done").await;
659        tokio::time::sleep(Duration::from_millis(50)).await;
660        assert!(
661            !driven.is_finished(),
662            "an unsettled session keeps the turn open"
663        );
664        server.emit(json!({"type": "session_settled"})).await;
665        // omp keeps writing after the turn; a reader that went away would
666        // break its stdout and make it exit 1.
667        server.finish(Some("session file could not be saved")).await;
668        let ended = driven.await.unwrap().unwrap();
669        assert!(ended.error.is_none() && !ended.stopped);
670        assert_eq!(ended.notices, ["session file could not be saved"]);
671        assert_eq!(ended.answers, ["working on it", "all done"]);
672        let stdout = String::from_utf8(log.lock().unwrap().clone()).unwrap();
673        assert!(stdout.contains(r#""type":"session""#) && stdout.contains("s-1"));
674        assert_eq!(
675            crate::agent::answer_text(crate::config::AgentKind::Omp, &stdout),
676            "all done"
677        );
678    }
679
680    #[tokio::test]
681    async fn steers_queued_input_and_publishes_the_live_reply() {
682        let dir = tempfile::tempdir().unwrap();
683        let queued = Arc::new(Mutex::new(Vec::new()));
684        let hooks = hooks(dir.path(), Arc::clone(&queued));
685        let (mut server, w, r) = pair();
686        let driven = tokio::spawn(drive(
687            w,
688            r,
689            "first".into(),
690            Some(Arc::clone(&hooks)),
691            Arc::default(),
692        ));
693        server.handshake().await;
694        server.command().await;
695        server
696            .emit(json!({"type": "message_start", "message": {"role": "assistant", "content": []}}))
697            .await;
698        server.emit(json!({"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "delta": "partial"}})).await;
699        server.emit(json!({"type": "tool_execution_start", "toolName": "bash", "args": {"command": "cargo   test"}})).await;
700        let admitted = Arc::new(AtomicBool::new(false));
701        let acknowledged = Arc::clone(&admitted);
702        queued.lock().unwrap().push(Input {
703            text: "also check docs".into(),
704            steer: true,
705            accepted: Some(Box::new(move || {
706                acknowledged.store(true, Ordering::SeqCst);
707                Ok(())
708            })),
709        });
710        let steer = server.command().await;
711        assert_eq!(steer["message"], "also check docs");
712        assert_eq!(steer["streamingBehavior"], "steer");
713        tokio::time::sleep(TICK * 2).await;
714        let live = read_live(&dir.path().join("live.json")).expect("a live snapshot");
715        assert_eq!(live.text, "partial");
716        assert_eq!(live.activity.as_deref(), Some("bash: cargo test"));
717        assert_eq!(live.steered, 1);
718        assert!(!admitted.load(Ordering::SeqCst));
719        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": false})).await;
720        tokio::time::sleep(Duration::from_millis(50)).await;
721        assert!(
722            !driven.is_finished(),
723            "the steered prompt is still owed an answer"
724        );
725        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "completed", "sessionSettled": true})).await;
726        server.finish(None).await;
727        driven.await.unwrap().unwrap();
728        assert!(admitted.load(Ordering::SeqCst));
729        assert!(
730            !dir.path().join("live.json").exists(),
731            "no stop can be honoured once the commands ended"
732        );
733    }
734
735    #[test]
736    fn stop_admission_and_settlement_share_a_fence() {
737        let dir = tempfile::tempdir().unwrap();
738        let hooks = hooks(dir.path(), Arc::default());
739        let guard = LiveGuard {
740            hooks: &hooks,
741            turn: "first".into(),
742        };
743        write_live(
744            &hooks.live,
745            &Live {
746                turn: guard.turn.clone(),
747                ..Live::default()
748            },
749        );
750        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
751        assert!(guard.check_stop(true).unwrap());
752        assert!(hooks.stopped());
753        assert!(!request_stop(&hooks.live, &hooks.stop).unwrap());
754    }
755
756    #[tokio::test]
757    async fn a_stop_request_aborts_and_ends_without_waiting_for_background_work() {
758        let dir = tempfile::tempdir().unwrap();
759        let hooks = hooks(dir.path(), Arc::default());
760        let (mut server, w, r) = pair();
761        let driven = tokio::spawn(drive(
762            w,
763            r,
764            "long job".into(),
765            Some(Arc::clone(&hooks)),
766            Arc::default(),
767        ));
768        server.handshake().await;
769        server.command().await;
770        while !hooks.live.exists() {
771            tokio::time::sleep(Duration::from_millis(10)).await;
772        }
773        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
774        assert_eq!(server.command().await["type"], "abort");
775        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "aborted", "sessionSettled": false})).await;
776        server.finish(None).await;
777        let ended = driven.await.unwrap().unwrap();
778        assert!(ended.stopped && hooks.stopped());
779        assert!(!hooks.stop.exists(), "the request is consumed");
780    }
781
782    #[tokio::test]
783    async fn reports_prompt_errors_and_early_exit() {
784        let (mut server, w, r) = pair();
785        let driven = tokio::spawn(drive(w, r, "x".into(), None, Arc::default()));
786        server.handshake().await;
787        server.command().await;
788        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "error", "sessionSettled": true,
789            "error": {"message": "rate limited", "httpStatus": 429, "retryable": true}})).await;
790        server.finish(None).await;
791        let ended = driven.await.unwrap().unwrap();
792        let error = ended.error.unwrap();
793        assert_eq!(
794            (error.message.as_str(), error.http_status),
795            ("rate limited", Some(429))
796        );
797
798        let (mut server, w, r) = pair();
799        let driven = tokio::spawn(drive(w, r, "x".into(), None, Arc::default()));
800        server.handshake().await;
801        server.command().await;
802        drop(server);
803        let error = driven.await.unwrap().unwrap_err();
804        assert!(format!("{error:#}").contains("exited before the turn finished"));
805    }
806}