Skip to main content

magi/
omp_rpc.rs

1//! Chat over `omp --mode rpc`.
2//!
3//! A chat turn whose agent is `kind = "omp"` keeps one RPC process instead of
4//! a single `omp -p` call. That gives the web Chat what the operator gets in
5//! 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//! - with [`Resident`] hooks the process outlives the turn: every answer is
15//!   published as the agent yields, the next message is prompted into the same
16//!   process, and an answer the agent gives on its own (a background job
17//!   finished) reaches the chat too. The driver leaves after an idle period.
18//!   Without them, the turn ends once the session is settled.
19//!
20//! The wire is omp's JSONL RPC protocol (`omp://rpc.md`), protocol version 1.
21//! Every frame the answer extraction in `agent` reads (`message_end`,
22//! `turn_end`, `agent_end`, `tool_execution_start`) is appended to the seat's
23//! stdout log, behind a synthesized `{"type":"session"}` line from
24//! `get_state`, so the stored `<stem>.out` reads exactly like an `omp -p
25//! --mode=json` stream.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::time::{Duration, Instant};
31
32use anyhow::{Context, Result, bail};
33use jiff::Timestamp;
34use serde::{Deserialize, Serialize};
35use serde_json::{Value, json};
36use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
37
38use crate::agent::Captured;
39
40/// How often queued input, the stop file and the live snapshot are checked.
41const TICK: Duration = Duration::from_millis(500);
42
43/// Longest tool summary shown in the live snapshot.
44const ACTIVITY_CHARS: usize = 160;
45
46/// Commit the durable draft after RPC prompt admission.
47pub type AdmissionCallback = Box<dyn FnOnce() -> Result<()> + Send>;
48
49/// Input that arrived while the session was open.
50pub struct Input {
51    /// The prompt text for the agent.
52    pub text: String,
53    /// Steer the running agent (operator input) rather than queue it after the
54    /// current run (automatic notices). Ignored while the session is idle.
55    pub steer: bool,
56    /// Commit the durable draft only after omp admits the prompt.
57    pub accepted: Option<AdmissionCallback>,
58}
59
60/// What a poll for queued input found.
61pub enum Poll {
62    /// Nothing to deliver now.
63    Nothing,
64    /// Deliver this input.
65    Input(Input),
66    /// The conversation changed under the session (closed, deleted, another
67    /// agent or persona): leave as soon as it is idle.
68    Exit,
69}
70
71/// Receives each finished answer of a resident session, in order, as the
72/// agent yields, with the context size the last model call reported.
73pub type Publish = Box<dyn Fn(&str, Option<u64>, &crate::agent::SeatState) + Send + Sync>;
74
75/// Keep the session open after it settles.
76pub struct Resident {
77    /// See [`Publish`].
78    pub publish: Publish,
79    /// Leave after the session has been idle this long.
80    pub idle_exit: Duration,
81    /// Take no new work once the session is this old; leave when idle.
82    pub max_age: Duration,
83}
84
85/// Connection between a chat and its RPC driver.
86pub struct Hooks {
87    /// Where the in-progress reply is published.
88    pub live: PathBuf,
89    /// A file whose appearance asks the driver to abort the agent.
90    pub stop: PathBuf,
91    /// Takes input queued since the last call; called on every tick with
92    /// whether the session is idle (no prompt owed and settled).
93    pub input: Box<dyn Fn(bool) -> Result<Poll> + Send + Sync>,
94    /// Outlive the turn; `None` ends it once the session is settled.
95    pub resident: Option<Resident>,
96    stopped: AtomicBool,
97}
98
99impl Hooks {
100    /// Hooks publishing to `live`, watching `stop`, and pulling `input`.
101    pub fn new(
102        live: PathBuf,
103        stop: PathBuf,
104        input: Box<dyn Fn(bool) -> Result<Poll> + Send + Sync>,
105    ) -> Self {
106        Self {
107            live,
108            stop,
109            input,
110            resident: None,
111            stopped: AtomicBool::new(false),
112        }
113    }
114
115    /// Keep the session after it settles.
116    pub fn resident(mut self, resident: Resident) -> Self {
117        self.resident = Some(resident);
118        self
119    }
120
121    /// Did the operator stop running work?
122    pub fn stopped(&self) -> bool {
123        self.stopped.load(Ordering::SeqCst)
124    }
125}
126
127tokio::task_local! {
128    static HOOKS: Arc<Hooks>;
129}
130
131/// Run `fut` with `hooks` available to the omp RPC driver it spawns.
132pub async fn with_hooks<F: Future>(hooks: Arc<Hooks>, fut: F) -> F::Output {
133    HOOKS.scope(hooks, fut).await
134}
135
136/// The hooks of the chat turn this task belongs to, if any.
137pub(crate) fn current() -> Option<Arc<Hooks>> {
138    HOOKS.try_with(Arc::clone).ok()
139}
140
141/// The in-progress reply, as the web Chat shows it.
142#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
143pub struct Live {
144    /// Identifies this RPC invocation, including across fallback attempts.
145    #[serde(default)]
146    pub turn: String,
147    /// The assistant text streamed so far (the latest message with text).
148    pub text: String,
149    /// The tool currently running, summarized.
150    pub activity: Option<String>,
151    /// The operator asked to stop and the abort was sent.
152    pub stopping: bool,
153    /// Messages delivered into the running session.
154    pub steered: u32,
155    /// The agent is working: a prompt is owed or the session is not settled.
156    #[serde(default)]
157    pub busy: bool,
158    /// The process stays after the turn ([`Resident`]).
159    #[serde(default)]
160    pub resident: bool,
161    /// When this snapshot was written.
162    pub at: Option<Timestamp>,
163}
164
165/// Read a live snapshot; `None` when absent or unreadable.
166pub fn read_live(path: &Path) -> Option<Live> {
167    serde_json::from_slice(&std::fs::read(path).ok()?).ok()
168}
169
170fn stop_lock(stop: &Path) -> Result<std::fs::File> {
171    let file = std::fs::OpenOptions::new()
172        .create(true)
173        .truncate(false)
174        .read(true)
175        .write(true)
176        .open(stop.with_extension("lock"))?;
177    crate::pr_head::lock_file(&file)?;
178    Ok(file)
179}
180
181/// Accept a stop only while the identified driver is taking commands.
182pub fn request_stop(live: &Path, stop: &Path) -> Result<bool> {
183    let Some(snapshot) = read_live(live) else {
184        return Ok(false);
185    };
186    let _lock = stop_lock(stop)?;
187    if !read_live(live).is_some_and(|current| current.turn == snapshot.turn) {
188        return Ok(false);
189    }
190    std::fs::write(stop, snapshot.turn.as_bytes())?;
191    Ok(true)
192}
193
194/// Ask the identified idle session to relinquish its lease without aborting
195/// work that might start before it sees the request.
196pub(crate) fn request_leave(live: &Path, stop: &Path) -> Result<bool> {
197    let Some(snapshot) = read_live(live).filter(|live| live.resident && !live.busy) else {
198        return Ok(false);
199    };
200    let _lock = stop_lock(stop)?;
201    if !read_live(live).is_some_and(|current| current.turn == snapshot.turn) {
202        return Ok(false);
203    }
204    std::fs::write(stop.with_extension("leave"), snapshot.turn.as_bytes())?;
205    Ok(true)
206}
207
208struct LiveGuard<'a> {
209    hooks: &'a Hooks,
210    turn: String,
211}
212
213impl LiveGuard<'_> {
214    /// Consume a stop request addressed to this driver.
215    fn take_stop(&self) -> Result<bool> {
216        let _lock = stop_lock(&self.hooks.stop)?;
217        let requested = std::fs::read_to_string(&self.hooks.stop).is_ok_and(|id| id == self.turn);
218        if requested {
219            let _ = std::fs::remove_file(&self.hooks.stop);
220        }
221        Ok(requested)
222    }
223
224    fn take_leave(&self) -> Result<bool> {
225        let path = self.hooks.stop.with_extension("leave");
226        if !path.exists() {
227            return Ok(false);
228        }
229        let _lock = stop_lock(&self.hooks.stop)?;
230        let requested = std::fs::read_to_string(&path).is_ok_and(|id| id == self.turn);
231        if requested {
232            let _ = std::fs::remove_file(path);
233        }
234        Ok(requested)
235    }
236
237    /// Withdraw the snapshot under the stop fence, so no stop is accepted
238    /// once the driver stopped taking commands.
239    fn retire(&self) {
240        let lock = stop_lock(&self.hooks.stop);
241        if std::fs::read_to_string(&self.hooks.stop).is_ok_and(|id| id == self.turn) {
242            let _ = std::fs::remove_file(&self.hooks.stop);
243        }
244        let leave = self.hooks.stop.with_extension("leave");
245        if std::fs::read_to_string(&leave).is_ok_and(|id| id == self.turn) {
246            let _ = std::fs::remove_file(leave);
247        }
248        let _ = std::fs::remove_file(&self.hooks.live);
249        drop(lock);
250    }
251}
252
253impl Drop for LiveGuard<'_> {
254    fn drop(&mut self) {
255        self.retire();
256    }
257}
258
259fn write_live(path: &Path, live: &Live) {
260    let Ok(body) = serde_json::to_vec(live) else {
261        return;
262    };
263    let tmp = path.with_extension("json.tmp");
264    if std::fs::write(&tmp, body).is_ok() && std::fs::rename(&tmp, path).is_err() {
265        // A reader may hold the old snapshot open on Windows; the next tick
266        // writes again.
267        let _ = std::fs::remove_file(&tmp);
268    }
269}
270
271/// A prompt omp finished with an error.
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub(crate) struct PromptError {
274    pub message: String,
275    pub http_status: Option<u64>,
276    pub code: Option<String>,
277}
278
279/// How a driven turn ended.
280#[derive(Debug, Default)]
281pub(crate) struct Ended {
282    /// The last error any prompt of the turn reported.
283    pub error: Option<PromptError>,
284    /// Error notices omp sent outside any prompt.
285    pub notices: Vec<String>,
286    /// The operator stopped the turn.
287    pub stopped: bool,
288    /// The final text of each answer the agent gave in this turn, in order;
289    /// more than one when input was steered into the running session.
290    pub answers: Vec<String>,
291}
292
293fn push_answer(answers: &mut Vec<String>, text: &str) {
294    let text = text.trim();
295    if !text.is_empty() && answers.last().is_none_or(|last| last != text) {
296        answers.push(text.to_owned());
297    }
298}
299
300/// How long to keep reading omp's stdout after closing its stdin.
301const EXIT_DRAIN: Duration = Duration::from_secs(15);
302
303fn summarize(tool: &str, args: &Value) -> String {
304    let detail = ["i", "command", "path", "pattern", "query", "url", "task"]
305        .iter()
306        .find_map(|key| args.get(key).and_then(Value::as_str))
307        .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" "));
308    let mut out = match detail {
309        Some(detail) if !detail.is_empty() => format!("{tool}: {detail}"),
310        _ => tool.to_owned(),
311    };
312    if out.chars().count() > ACTIVITY_CHARS {
313        out = out.chars().take(ACTIVITY_CHARS).collect::<String>() + "…";
314    }
315    out
316}
317
318fn prompt_error(value: &Value) -> PromptError {
319    match value {
320        Value::String(message) => PromptError {
321            message: message.clone(),
322            http_status: None,
323            code: None,
324        },
325        _ => PromptError {
326            message: value
327                .get("message")
328                .and_then(Value::as_str)
329                .unwrap_or("omp reported an error")
330                .to_owned(),
331            http_status: value.get("httpStatus").and_then(Value::as_u64),
332            code: value.get("code").and_then(Value::as_str).map(str::to_owned),
333        },
334    }
335}
336
337struct Driver<W> {
338    writer: W,
339    log: Captured,
340    live: Live,
341    /// Text of the assistant message streaming now.
342    current: String,
343    /// Text of the last assistant message that had any.
344    last: String,
345    /// Assistant messages with text seen so far, and how many of them were
346    /// already handed to [`Resident::publish`].
347    seen: u64,
348    published: u64,
349    /// Input-side context the last assistant message reported.
350    context: Option<u64>,
351    session: Option<String>,
352    dirty: bool,
353}
354
355impl<W: AsyncWrite + Unpin> Driver<W> {
356    async fn send(&mut self, frame: Value) -> Result<()> {
357        let mut line = serde_json::to_vec(&frame)?;
358        line.push(b'\n');
359        self.writer
360            .write_all(&line)
361            .await
362            .context("write to omp rpc")?;
363        self.writer.flush().await.context("flush omp rpc")
364    }
365
366    fn record(&self, line: &str) {
367        if let Ok(mut log) = self.log.lock() {
368            log.extend_from_slice(line.as_bytes());
369            log.push(b'\n');
370        }
371    }
372
373    fn refresh(&mut self) {
374        let text = if self.current.trim().is_empty() {
375            &self.last
376        } else {
377            &self.current
378        };
379        if self.live.text != *text {
380            self.live.text.clone_from(text);
381            self.dirty = true;
382        }
383    }
384
385    fn publish(&mut self, hooks: Option<&Hooks>) {
386        if !self.dirty {
387            return;
388        }
389        if let Some(hooks) = hooks {
390            self.live.at = Some(Timestamp::now());
391            write_live(&hooks.live, &self.live);
392        }
393        self.dirty = false;
394    }
395
396    /// Mark the session working or idle. Idle clears the streamed text: it
397    /// is in the transcript by then.
398    fn set_busy(&mut self, busy: bool) {
399        if self.live.busy != busy {
400            self.live.busy = busy;
401            if !busy {
402                self.live.text.clear();
403                self.live.activity = None;
404            }
405            self.dirty = true;
406        }
407    }
408
409    /// The last answer and the context the session had reached, once, if
410    /// the agent gave a new answer since the last call.
411    fn take_answer(&mut self) -> Option<(String, Option<u64>)> {
412        let text = self.last.trim();
413        (self.seen > self.published && !text.is_empty()).then(|| {
414            self.published = self.seen;
415            (text.to_owned(), self.context)
416        })
417    }
418}
419
420/// The agent yielded (a prompt answered, or the session settled on its own):
421/// hand a resident chat the new answer. The idle snapshot goes out first, so
422/// a reader that sees the reply in the transcript never sees a busy session.
423fn deliver<W: AsyncWrite + Unpin>(
424    driver: &mut Driver<W>,
425    hooks: Option<&Hooks>,
426    resident: Option<&Resident>,
427    idle: bool,
428    checkpoint: &impl Fn(Option<String>) -> Result<crate::agent::SeatState>,
429) -> Result<()> {
430    let Some(resident) = resident else {
431        return Ok(());
432    };
433    let Some((text, context)) = driver.take_answer() else {
434        return Ok(());
435    };
436    if idle {
437        driver.set_busy(false);
438        driver.publish(hooks);
439    }
440    let seat = checkpoint(driver.session.clone())?;
441    (resident.publish)(&text, context, &seat);
442    Ok(())
443}
444
445/// Drive a chat session: send `prompt`, deliver input the hooks hand over,
446/// honour a stop request, and return once every prompt has finished and the
447/// session is settled - or, for a [`Resident`] session, once it has been idle
448/// long enough or was asked to leave. Dropping `writer` on return closes omp's
449/// stdin, which ends the process.
450pub(crate) async fn drive<W, R>(
451    writer: W,
452    reader: R,
453    prompt: String,
454    hooks: Option<Arc<Hooks>>,
455    log: Captured,
456    checkpoint: impl Fn(Option<String>) -> Result<crate::agent::SeatState>,
457) -> Result<Ended>
458where
459    W: AsyncWrite + Unpin,
460    R: AsyncRead + Unpin,
461{
462    let hooks = hooks.as_deref();
463    let resident = hooks.and_then(|hooks| hooks.resident.as_ref());
464    let mut lines = BufReader::new(reader).lines();
465    loop {
466        let line = lines
467            .next_line()
468            .await
469            .context("read omp rpc")?
470            .context("omp exited before it was ready")?;
471        if serde_json::from_str::<Value>(&line)
472            .is_ok_and(|frame| frame.get("type").and_then(Value::as_str) == Some("ready"))
473        {
474            break;
475        }
476    }
477
478    let mut driver = Driver {
479        writer,
480        log,
481        live: Live {
482            busy: true,
483            resident: resident.is_some(),
484            ..Live::default()
485        },
486        current: String::new(),
487        last: String::new(),
488        seen: 0,
489        published: 0,
490        context: None,
491        session: None,
492        // Publish at once: the snapshot's presence tells the web a stop can
493        // still be honoured.
494        dirty: true,
495    };
496    driver
497        .send(json!({"id": "filter", "type": "set_event_filter", "events": null, "messageUpdates": "delta"}))
498        .await?;
499    driver
500        .send(json!({"id": "state", "type": "get_state"}))
501        .await?;
502    driver
503        .send(json!({"id": "p0", "type": "prompt", "message": prompt}))
504        .await?;
505
506    let guard = hooks.map(|hooks| LiveGuard {
507        hooks,
508        turn: format!("{}-{}", std::process::id(), Timestamp::now()),
509    });
510    if let Some(guard) = &guard {
511        let _lock = stop_lock(&guard.hooks.stop)?;
512        driver.live.turn.clone_from(&guard.turn);
513        driver.publish(hooks);
514    }
515    let started = Instant::now();
516    let mut idle_since: Option<Instant> = None;
517    let mut leaving = false;
518    let mut admission: Option<(String, Option<AdmissionCallback>)> = None;
519    let mut outstanding = vec!["p0".to_owned()];
520    let mut settled = false;
521    let mut sent = 0u32;
522    let mut ended = Ended::default();
523    let mut tick = tokio::time::interval(TICK);
524    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
525    loop {
526        let idle = outstanding.is_empty() && settled;
527        if idle {
528            idle_since.get_or_insert_with(Instant::now);
529        } else {
530            idle_since = None;
531        }
532        driver.set_busy(!idle);
533        if !leaving
534            && let Some(guard) = &guard
535            && guard.take_leave()?
536        {
537            leaving = true;
538        }
539        // A stopped turn ends as soon as its prompts answered: closing stdin
540        // disposes the session, which cancels whatever was still running.
541        let done = if ended.stopped {
542            outstanding.is_empty()
543        } else {
544            match resident {
545                Some(resident) => {
546                    idle && (leaving
547                        || ended.error.is_some()
548                        || idle_since.is_some_and(|since| since.elapsed() >= resident.idle_exit)
549                        || started.elapsed() >= resident.max_age)
550                }
551                None => idle,
552            }
553        };
554        if done {
555            break;
556        }
557        if let Some(guard) = &guard
558            && !ended.stopped
559            && guard.hooks.stop.exists()
560            && guard.take_stop()?
561        {
562            if idle {
563                // Nothing is running: a stop only ends the residency.
564                leaving = true;
565            } else {
566                guard.hooks.stopped.store(true, Ordering::SeqCst);
567                ended.stopped = true;
568                driver.live.stopping = true;
569                driver.dirty = true;
570                driver.send(json!({"id": "abort", "type": "abort"})).await?;
571            }
572            continue;
573        }
574        tokio::select! {
575            line = lines.next_line() => {
576                let Some(line) = line.context("read omp rpc")? else {
577                    bail!("omp exited before the turn finished");
578                };
579                let Ok(frame) = serde_json::from_str::<Value>(&line) else {
580                    continue;
581                };
582                match frame.get("type").and_then(Value::as_str).unwrap_or_default() {
583                    "response" => {
584                        let id = frame.get("id").and_then(Value::as_str).unwrap_or_default();
585                        let ok = frame.get("success").and_then(Value::as_bool).unwrap_or(false);
586                        if admission.as_ref().is_some_and(|(pending, _)| pending == id) {
587                            let (_, accepted) = admission.take().expect("matching admission");
588                            if ok && let Some(accepted) = accepted {
589                                accepted()?;
590                            }
591                        }
592                        if id == "state" {
593                            if let Some(session) = frame
594                                .pointer("/data/sessionId")
595                                .and_then(Value::as_str)
596                            {
597                                driver.record(&json!({"type": "session", "id": session}).to_string());
598                                driver.session = Some(session.to_owned());
599                            }
600                        } else if !ok && outstanding.iter().any(|p| p == id) {
601                            // Refused before admission: no prompt_result follows.
602                            outstanding.retain(|p| p != id);
603                            ended.error = Some(prompt_error(
604                                frame.get("error").unwrap_or(&Value::Null),
605                            ));
606                        }
607                    }
608                    "prompt_result" => {
609                        let id = frame.get("id").and_then(Value::as_str).unwrap_or_default();
610                        if admission.as_ref().is_some_and(|(pending, _)| pending == id) {
611                            let (_, accepted) = admission.take().expect("matching admission");
612                            if let Some(accepted) = accepted {
613                                accepted()?;
614                            }
615                        }
616                        outstanding.retain(|p| p != id);
617                        let status = frame.get("status").and_then(Value::as_str);
618                        if status == Some("error") {
619                            ended.error = Some(prompt_error(
620                                frame.get("error").unwrap_or(&Value::Null),
621                            ));
622                        }
623                        settled = frame
624                            .get("sessionSettled")
625                            .and_then(Value::as_bool)
626                            .unwrap_or(false);
627                        // Each prompt the agent answered: a steered turn
628                        // replies to every message, not only the last one.
629                        push_answer(&mut ended.answers, &driver.last);
630                        if status != Some("aborted") && !ended.stopped {
631                            let idle = outstanding.is_empty() && settled;
632                            deliver(&mut driver, hooks, resident, idle, &checkpoint)?;
633                        }
634                    }
635                    "session_settled" => {
636                        settled = true;
637                        if !ended.stopped {
638                            // An answer the agent gave on its own, after a
639                            // background job woke it, settles here.
640                            push_answer(&mut ended.answers, &driver.last);
641                            let idle = outstanding.is_empty();
642                            deliver(&mut driver, hooks, resident, idle, &checkpoint)?;
643                        }
644                    }
645                    "message_start" => {
646                        if frame.pointer("/message/role").and_then(Value::as_str) == Some("assistant") {
647                            driver.current.clear();
648                            driver.set_busy(true);
649                        }
650                    }
651                    "message_update" => {
652                        let event = frame.get("assistantMessageEvent");
653                        if event.and_then(|e| e.get("type")).and_then(Value::as_str) == Some("text_delta")
654                            && let Some(delta) = event.and_then(|e| e.get("delta")).and_then(Value::as_str)
655                        {
656                            driver.current.push_str(delta);
657                            driver.refresh();
658                        }
659                    }
660                    "agent_start" => {
661                        // The agent woke without a prompt (a background job
662                        // delivered its result): the session is busy again.
663                        settled = false;
664                    }
665                    "message_end" | "turn_end" | "agent_end" => {
666                        if frame.get("type").and_then(Value::as_str) == Some("message_end")
667                            && frame.pointer("/message/role").and_then(Value::as_str) == Some("assistant")
668                        {
669                            let text: String = frame
670                                .pointer("/message/content")
671                                .and_then(Value::as_array)
672                                .into_iter()
673                                .flatten()
674                                .filter(|part| part.get("type").and_then(Value::as_str) == Some("text"))
675                                .filter_map(|part| part.get("text").and_then(Value::as_str))
676                                .collect();
677                            if let Some(context) =
678                                frame.get("message").and_then(crate::agent::omp_message_context)
679                            {
680                                driver.context = Some(context);
681                            }
682                            if !text.trim().is_empty() {
683                                driver.last = text;
684                                driver.seen += 1;
685                            }
686                            driver.current.clear();
687                            driver.refresh();
688                        }
689                        driver.record(&line);
690                    }
691                    "tool_execution_start" => {
692                        let tool = frame.get("toolName").and_then(Value::as_str).unwrap_or("tool");
693                        driver.live.activity =
694                            Some(summarize(tool, frame.get("args").unwrap_or(&Value::Null)));
695                        driver.dirty = true;
696                        driver.record(&line);
697                    }
698                    "tool_execution_end" => {
699                        driver.live.activity = None;
700                        driver.dirty = true;
701                    }
702                    "notice" => {
703                        if let Some(notice) = error_notice(&line) {
704                            ended.notices.push(notice);
705                        }
706                    }
707                    _ => {}
708                }
709            }
710            _ = tick.tick() => {
711                if let Some(hooks) = hooks
712                    && !ended.stopped
713                    && !leaving
714                    && ended.error.is_none()
715                    && resident.is_none_or(|resident| started.elapsed() < resident.max_age)
716                    && admission.is_none()
717                {
718                    match (hooks.input)(idle) {
719                        Ok(Poll::Input(input)) => {
720                            sent += 1;
721                            let id = format!("p{sent}");
722                            let mut frame = json!({"id": id, "type": "prompt", "message": input.text});
723                            if !idle {
724                                frame["streamingBehavior"] =
725                                    json!(if input.steer { "steer" } else { "followUp" });
726                            }
727                            driver.send(frame).await?;
728                            admission = Some((id.clone(), input.accepted));
729                            outstanding.push(id);
730                            settled = false;
731                            driver.set_busy(true);
732                            driver.live.steered = sent;
733                            driver.dirty = true;
734                        }
735                        Ok(Poll::Exit) => leaving = true,
736                        Ok(_) => {}
737                        Err(error) => tracing::warn!("chat input for the running session: {error:#}"),
738                    }
739                }
740                if !ended.stopped {
741                    driver.publish(hooks);
742                }
743            }
744        }
745    }
746    // Earlier answers are already in the transcript. Hand over any new
747    // completed assistant text from an aborted prompt before the stop note.
748    if ended.stopped && driver.published > 0 {
749        deliver(&mut driver, hooks, resident, false, &checkpoint)?;
750    }
751    drop(guard);
752    push_answer(&mut ended.answers, &driver.last);
753    // omp keeps writing after the turn (UI updates, shutdown notices) and
754    // exits 1 when its stdout breaks, so close stdin and read to EOF.
755    let Driver { writer, .. } = driver;
756    drop(writer);
757    let drained = tokio::time::timeout(EXIT_DRAIN, async {
758        while let Ok(Some(line)) = lines.next_line().await {
759            if let Some(notice) = error_notice(&line) {
760                ended.notices.push(notice);
761            }
762        }
763    })
764    .await;
765    if drained.is_err() {
766        tracing::warn!("omp kept its stdout open after the turn ended");
767    }
768    Ok(ended)
769}
770
771/// An error `notice` frame's message: omp reports persistence and restore
772/// failures that way, outside any prompt.
773fn error_notice(line: &str) -> Option<String> {
774    let frame: Value = serde_json::from_str(line).ok()?;
775    (frame.get("type").and_then(Value::as_str) == Some("notice")
776        && frame.get("level").and_then(Value::as_str) == Some("error"))
777    .then(|| {
778        frame
779            .get("message")
780            .and_then(Value::as_str)
781            .unwrap_or("omp reported an error")
782            .to_owned()
783    })
784}
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789    use std::sync::Mutex;
790    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, duplex};
791
792    async fn drive(
793        writer: DuplexStream,
794        reader: DuplexStream,
795        prompt: String,
796        hooks: Option<Arc<Hooks>>,
797        log: Captured,
798    ) -> Result<Ended> {
799        super::drive(writer, reader, prompt, hooks, log, |session| {
800            let mut seat = crate::agent::SeatState::new("chat", "test", 0);
801            seat.captured_session = session;
802            seat.turns = 1;
803            Ok(seat)
804        })
805        .await
806    }
807
808    /// The test plays omp: reads the driver's commands, answers with frames.
809    /// One pipe per direction, like a child's stdin and stdout, so the driver
810    /// closing its stdin is visible while its stdout stays readable.
811    struct Server {
812        lines: tokio::io::Lines<BufReader<DuplexStream>>,
813        out: DuplexStream,
814    }
815
816    impl Server {
817        async fn emit(&mut self, frame: Value) {
818            let mut line = frame.to_string().into_bytes();
819            line.push(b'\n');
820            self.out.write_all(&line).await.unwrap();
821        }
822
823        async fn command(&mut self) -> Value {
824            let line = self.lines.next_line().await.unwrap().expect("a command");
825            serde_json::from_str(&line).unwrap()
826        }
827
828        async fn handshake(&mut self) {
829            self.emit(json!({"type": "ready", "protocolVersion": 1}))
830                .await;
831            assert_eq!(self.command().await["type"], "set_event_filter");
832            assert_eq!(self.command().await["type"], "get_state");
833            self.emit(json!({"type": "response", "id": "state", "command": "get_state", "success": true, "data": {"sessionId": "s-1"}})).await;
834        }
835
836        async fn answer(&mut self, text: &str) {
837            self.emit(
838                json!({"type": "message_start", "message": {"role": "assistant", "content": []}}),
839            )
840            .await;
841            self.emit(json!({"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "delta": text}})).await;
842            self.emit(json!({"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": text}]}})).await;
843        }
844    }
845
846    fn pair() -> (Server, DuplexStream, DuplexStream) {
847        let (stdin_driver, stdin_server) = duplex(1 << 16);
848        let (stdout_server, stdout_driver) = duplex(1 << 16);
849        (
850            Server {
851                lines: BufReader::new(stdin_server).lines(),
852                out: stdout_server,
853            },
854            stdin_driver,
855            stdout_driver,
856        )
857    }
858
859    impl Server {
860        /// Wait for the driver to close stdin, then write more output the
861        /// way omp does at shutdown, which must still be read, and exit.
862        async fn finish(mut self, notice: Option<&str>) {
863            assert!(
864                self.lines.next_line().await.unwrap().is_none(),
865                "stdin closed"
866            );
867            self.emit(json!({"type": "extension_ui_request", "method": "setWidget"}))
868                .await;
869            if let Some(message) = notice {
870                self.emit(json!({"type": "notice", "level": "error", "message": message}))
871                    .await;
872            }
873        }
874    }
875
876    fn hooks(dir: &Path, queued: Arc<Mutex<Vec<Input>>>) -> Arc<Hooks> {
877        Arc::new(Hooks::new(
878            dir.join("live.json"),
879            dir.join("stop"),
880            Box::new(move |_idle| {
881                Ok(queued
882                    .lock()
883                    .unwrap()
884                    .pop()
885                    .map_or(Poll::Nothing, Poll::Input))
886            }),
887        ))
888    }
889
890    #[tokio::test]
891    async fn waits_for_settle_and_logs_an_extractable_stream() {
892        let (mut server, w, r) = pair();
893        let log: Captured = Arc::default();
894        let driven = tokio::spawn(drive(w, r, "hello".into(), None, Arc::clone(&log)));
895        server.handshake().await;
896        let prompt = server.command().await;
897        assert_eq!(prompt["message"], "hello");
898        server.answer("working on it").await;
899        // The agent yielded but a background job is still running.
900        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": false})).await;
901        server.answer("all done").await;
902        tokio::time::sleep(Duration::from_millis(50)).await;
903        assert!(
904            !driven.is_finished(),
905            "an unsettled session keeps the turn open"
906        );
907        server.emit(json!({"type": "session_settled"})).await;
908        // omp keeps writing after the turn; a reader that went away would
909        // break its stdout and make it exit 1.
910        server.finish(Some("session file could not be saved")).await;
911        let ended = driven.await.unwrap().unwrap();
912        assert!(ended.error.is_none() && !ended.stopped);
913        assert_eq!(ended.notices, ["session file could not be saved"]);
914        assert_eq!(ended.answers, ["working on it", "all done"]);
915        let stdout = String::from_utf8(log.lock().unwrap().clone()).unwrap();
916        assert!(stdout.contains(r#""type":"session""#) && stdout.contains("s-1"));
917        assert_eq!(
918            crate::agent::answer_text(crate::config::AgentKind::Omp, &stdout),
919            "all done"
920        );
921    }
922
923    #[tokio::test]
924    async fn steers_queued_input_and_publishes_the_live_reply() {
925        let dir = tempfile::tempdir().unwrap();
926        let queued = Arc::new(Mutex::new(Vec::new()));
927        let hooks = hooks(dir.path(), Arc::clone(&queued));
928        let (mut server, w, r) = pair();
929        let driven = tokio::spawn(drive(
930            w,
931            r,
932            "first".into(),
933            Some(Arc::clone(&hooks)),
934            Arc::default(),
935        ));
936        server.handshake().await;
937        server.command().await;
938        server
939            .emit(json!({"type": "message_start", "message": {"role": "assistant", "content": []}}))
940            .await;
941        server.emit(json!({"type": "message_update", "assistantMessageEvent": {"type": "text_delta", "delta": "partial"}})).await;
942        server.emit(json!({"type": "tool_execution_start", "toolName": "bash", "args": {"command": "cargo   test"}})).await;
943        let admitted = Arc::new(AtomicBool::new(false));
944        let acknowledged = Arc::clone(&admitted);
945        queued.lock().unwrap().push(Input {
946            text: "also check docs".into(),
947            steer: true,
948            accepted: Some(Box::new(move || {
949                acknowledged.store(true, Ordering::SeqCst);
950                Ok(())
951            })),
952        });
953        let steer = server.command().await;
954        assert_eq!(steer["message"], "also check docs");
955        assert_eq!(steer["streamingBehavior"], "steer");
956        tokio::time::sleep(TICK * 2).await;
957        let live = read_live(&dir.path().join("live.json")).expect("a live snapshot");
958        assert_eq!(live.text, "partial");
959        assert_eq!(live.activity.as_deref(), Some("bash: cargo test"));
960        assert_eq!(live.steered, 1);
961        assert!(!admitted.load(Ordering::SeqCst));
962        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": false})).await;
963        tokio::time::sleep(Duration::from_millis(50)).await;
964        assert!(
965            !driven.is_finished(),
966            "the steered prompt is still owed an answer"
967        );
968        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "completed", "sessionSettled": true})).await;
969        server.finish(None).await;
970        driven.await.unwrap().unwrap();
971        assert!(admitted.load(Ordering::SeqCst));
972        assert!(
973            !dir.path().join("live.json").exists(),
974            "no stop can be honoured once the commands ended"
975        );
976    }
977
978    #[test]
979    fn stop_admission_and_settlement_share_a_fence() {
980        let dir = tempfile::tempdir().unwrap();
981        let hooks = hooks(dir.path(), Arc::default());
982        let guard = LiveGuard {
983            hooks: &hooks,
984            turn: "first".into(),
985        };
986        write_live(
987            &hooks.live,
988            &Live {
989                turn: guard.turn.clone(),
990                ..Live::default()
991            },
992        );
993        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
994        assert!(guard.take_stop().unwrap());
995        guard.retire();
996        assert!(
997            !request_stop(&hooks.live, &hooks.stop).unwrap(),
998            "a retired driver accepts no stop"
999        );
1000    }
1001
1002    fn resident_hooks(
1003        dir: &Path,
1004        queued: Arc<Mutex<Vec<Poll>>>,
1005        published: Arc<Mutex<Vec<String>>>,
1006        idle_exit: Duration,
1007    ) -> Arc<Hooks> {
1008        Arc::new(
1009            Hooks::new(
1010                dir.join("live.json"),
1011                dir.join("stop"),
1012                Box::new(move |_idle| Ok(queued.lock().unwrap().pop().unwrap_or(Poll::Nothing))),
1013            )
1014            .resident(Resident {
1015                publish: Box::new(move |text, _, seat| {
1016                    assert_eq!(seat.captured_session.as_deref(), Some("s-1"));
1017                    published.lock().unwrap().push(text.to_owned());
1018                }),
1019                idle_exit,
1020                max_age: Duration::from_secs(3600),
1021            }),
1022        )
1023    }
1024
1025    async fn until(mut done: impl FnMut() -> bool) {
1026        let deadline = Instant::now() + Duration::from_secs(10);
1027        while !done() {
1028            assert!(Instant::now() < deadline, "condition never held");
1029            tokio::time::sleep(Duration::from_millis(10)).await;
1030        }
1031    }
1032
1033    #[tokio::test]
1034    async fn a_resident_session_answers_each_message_and_its_own_wakeups() {
1035        let dir = tempfile::tempdir().unwrap();
1036        let queued = Arc::new(Mutex::new(Vec::new()));
1037        let published = Arc::new(Mutex::new(Vec::new()));
1038        let hooks = resident_hooks(
1039            dir.path(),
1040            Arc::clone(&queued),
1041            Arc::clone(&published),
1042            Duration::from_secs(3600),
1043        );
1044        let (mut server, w, r) = pair();
1045        let driven = tokio::spawn(drive(
1046            w,
1047            r,
1048            "first".into(),
1049            Some(Arc::clone(&hooks)),
1050            Arc::default(),
1051        ));
1052        server.handshake().await;
1053        server.command().await;
1054        server.answer("first answer").await;
1055        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1056        until(|| published.lock().unwrap().len() == 1).await;
1057        let live = read_live(&hooks.live).expect("a resident session keeps its snapshot");
1058        assert!(live.resident && !live.busy && live.text.is_empty());
1059        assert!(!driven.is_finished(), "a settled resident session stays");
1060
1061        // The next message is a fresh prompt into the same process.
1062        queued.lock().unwrap().push(Poll::Input(Input {
1063            text: "second".into(),
1064            steer: true,
1065            accepted: None,
1066        }));
1067        let next = server.command().await;
1068        assert_eq!(next["message"], "second");
1069        assert!(
1070            next.get("streamingBehavior").is_none(),
1071            "idle input starts a run"
1072        );
1073        server.answer("second answer").await;
1074        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "completed", "sessionSettled": true})).await;
1075
1076        // A background job wakes the agent without any prompt.
1077        server.emit(json!({"type": "agent_start"})).await;
1078        server.answer("the build finished").await;
1079        server.emit(json!({"type": "session_settled"})).await;
1080        until(|| published.lock().unwrap().len() == 3).await;
1081        assert_eq!(
1082            *published.lock().unwrap(),
1083            ["first answer", "second answer", "the build finished"]
1084        );
1085
1086        // A stop while nothing runs only ends the residency.
1087        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
1088        server.finish(None).await;
1089        let ended = driven.await.unwrap().unwrap();
1090        assert!(!ended.stopped && !hooks.stopped());
1091        assert!(!hooks.live.exists());
1092    }
1093
1094    #[tokio::test]
1095    async fn a_resident_session_leaves_when_idle_or_asked() {
1096        let dir = tempfile::tempdir().unwrap();
1097        let published = Arc::new(Mutex::new(Vec::new()));
1098        let hooks = resident_hooks(
1099            dir.path(),
1100            Arc::default(),
1101            Arc::clone(&published),
1102            Duration::from_millis(200),
1103        );
1104        let (mut server, w, r) = pair();
1105        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
1106        server.handshake().await;
1107        server.command().await;
1108        server.answer("done").await;
1109        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1110        server.finish(None).await;
1111        driven.await.unwrap().unwrap();
1112        assert_eq!(*published.lock().unwrap(), ["done"]);
1113
1114        let queued = Arc::new(Mutex::new(vec![Poll::Exit]));
1115        let hooks = resident_hooks(
1116            dir.path(),
1117            queued,
1118            Arc::default(),
1119            Duration::from_secs(3600),
1120        );
1121        let (mut server, w, r) = pair();
1122        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
1123        server.handshake().await;
1124        server.command().await;
1125        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1126        server.finish(None).await;
1127        driven.await.unwrap().unwrap();
1128    }
1129
1130    #[tokio::test]
1131    async fn resident_leave_releases_the_session_without_a_stop() {
1132        let dir = tempfile::tempdir().unwrap();
1133        let published = Arc::new(Mutex::new(Vec::new()));
1134        let hooks = resident_hooks(
1135            dir.path(),
1136            Arc::default(),
1137            Arc::clone(&published),
1138            Duration::from_secs(3600),
1139        );
1140        let (mut server, w, r) = pair();
1141        let driven = tokio::spawn(drive(
1142            w,
1143            r,
1144            "x".into(),
1145            Some(Arc::clone(&hooks)),
1146            Arc::default(),
1147        ));
1148        server.handshake().await;
1149        server.command().await;
1150        assert!(!request_leave(&hooks.live, &hooks.stop).unwrap());
1151        server.answer("done").await;
1152        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1153        until(|| published.lock().unwrap().len() == 1).await;
1154        assert!(request_leave(&hooks.live, &hooks.stop).unwrap());
1155        tokio::time::timeout(Duration::from_secs(5), server.finish(None))
1156            .await
1157            .unwrap();
1158        assert!(!driven.await.unwrap().unwrap().stopped);
1159        assert!(!hooks.live.exists());
1160        assert!(!hooks.stop.with_extension("leave").exists());
1161    }
1162
1163    #[tokio::test]
1164    async fn expired_resident_does_not_poll_busy_input() {
1165        let dir = tempfile::tempdir().unwrap();
1166        let polled = Arc::new(AtomicBool::new(false));
1167        let observed = Arc::clone(&polled);
1168        let hooks = Arc::new(
1169            Hooks::new(
1170                dir.path().join("live.json"),
1171                dir.path().join("stop"),
1172                Box::new(move |_| {
1173                    observed.store(true, Ordering::SeqCst);
1174                    Ok(Poll::Input(Input {
1175                        text: "next".into(),
1176                        steer: true,
1177                        accepted: None,
1178                    }))
1179                }),
1180            )
1181            .resident(Resident {
1182                publish: Box::new(|_, _, _| {}),
1183                idle_exit: Duration::from_secs(3600),
1184                max_age: Duration::ZERO,
1185            }),
1186        );
1187        let (mut server, w, r) = pair();
1188        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
1189        server.handshake().await;
1190        server.command().await;
1191        tokio::time::sleep(TICK * 2).await;
1192        assert!(!polled.load(Ordering::SeqCst));
1193        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1194        server.finish(None).await;
1195        driven.await.unwrap().unwrap();
1196    }
1197
1198    #[tokio::test]
1199    async fn a_resident_answer_carries_the_context_it_reached() {
1200        let dir = tempfile::tempdir().unwrap();
1201        let got = Arc::new(Mutex::new(Vec::new()));
1202        let sink = Arc::clone(&got);
1203        let hooks = Arc::new(
1204            Hooks::new(
1205                dir.path().join("live.json"),
1206                dir.path().join("stop"),
1207                Box::new(|_| Ok(Poll::Nothing)),
1208            )
1209            .resident(Resident {
1210                publish: Box::new(move |text, context, _| {
1211                    sink.lock().unwrap().push((text.to_owned(), context));
1212                }),
1213                idle_exit: Duration::ZERO,
1214                max_age: Duration::from_secs(3600),
1215            }),
1216        );
1217        let (mut server, w, r) = pair();
1218        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
1219        server.handshake().await;
1220        server.command().await;
1221        server.emit(json!({"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "answer"}], "usage": {"input": 1200, "cacheRead": 800}}})).await;
1222        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1223        server.finish(None).await;
1224        driven.await.unwrap().unwrap();
1225        assert_eq!(*got.lock().unwrap(), [("answer".to_owned(), Some(2000))]);
1226    }
1227
1228    #[tokio::test]
1229    async fn resident_stop_keeps_only_the_new_answer() {
1230        let dir = tempfile::tempdir().unwrap();
1231        let queued = Arc::new(Mutex::new(Vec::new()));
1232        let published = Arc::new(Mutex::new(Vec::new()));
1233        let hooks = resident_hooks(
1234            dir.path(),
1235            Arc::clone(&queued),
1236            Arc::clone(&published),
1237            Duration::from_secs(3600),
1238        );
1239        let (mut server, w, r) = pair();
1240        let driven = tokio::spawn(drive(
1241            w,
1242            r,
1243            "x".into(),
1244            Some(Arc::clone(&hooks)),
1245            Arc::default(),
1246        ));
1247        server.handshake().await;
1248        server.command().await;
1249        server.answer("first answer").await;
1250        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1251        until(|| published.lock().unwrap().len() == 1).await;
1252        queued.lock().unwrap().push(Poll::Input(Input {
1253            text: "second".into(),
1254            steer: true,
1255            accepted: None,
1256        }));
1257        assert_eq!(server.command().await["id"], "p1");
1258        server.answer("second answer").await;
1259        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
1260        assert_eq!(server.command().await["type"], "abort");
1261        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "aborted", "sessionSettled": false})).await;
1262        server.finish(None).await;
1263        assert!(driven.await.unwrap().unwrap().stopped);
1264        assert_eq!(
1265            *published.lock().unwrap(),
1266            ["first answer", "second answer"]
1267        );
1268    }
1269
1270    #[tokio::test]
1271    async fn resident_error_after_an_answer_preserves_the_error() {
1272        let dir = tempfile::tempdir().unwrap();
1273        let queued = Arc::new(Mutex::new(Vec::new()));
1274        let published = Arc::new(Mutex::new(Vec::new()));
1275        let hooks = resident_hooks(
1276            dir.path(),
1277            Arc::clone(&queued),
1278            Arc::clone(&published),
1279            Duration::from_secs(3600),
1280        );
1281        let (mut server, w, r) = pair();
1282        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
1283        server.handshake().await;
1284        server.command().await;
1285        server.answer("first answer").await;
1286        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "completed", "sessionSettled": true})).await;
1287        until(|| published.lock().unwrap().len() == 1).await;
1288        queued.lock().unwrap().push(Poll::Input(Input {
1289            text: "second".into(),
1290            steer: true,
1291            accepted: None,
1292        }));
1293        assert_eq!(server.command().await["id"], "p1");
1294        server.emit(json!({"type": "prompt_result", "id": "p1", "status": "error", "sessionSettled": true, "error": "second failed"})).await;
1295        server.finish(None).await;
1296        let ended = driven.await.unwrap().unwrap();
1297        assert_eq!(ended.error.unwrap().message, "second failed");
1298        assert_eq!(*published.lock().unwrap(), ["first answer"]);
1299    }
1300
1301    #[tokio::test]
1302    async fn a_stop_request_aborts_and_ends_without_waiting_for_background_work() {
1303        let dir = tempfile::tempdir().unwrap();
1304        let hooks = hooks(dir.path(), Arc::default());
1305        let (mut server, w, r) = pair();
1306        let driven = tokio::spawn(drive(
1307            w,
1308            r,
1309            "long job".into(),
1310            Some(Arc::clone(&hooks)),
1311            Arc::default(),
1312        ));
1313        server.handshake().await;
1314        server.command().await;
1315        while !hooks.live.exists() {
1316            tokio::time::sleep(Duration::from_millis(10)).await;
1317        }
1318        assert!(request_stop(&hooks.live, &hooks.stop).unwrap());
1319        assert_eq!(server.command().await["type"], "abort");
1320        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "aborted", "sessionSettled": false})).await;
1321        server.finish(None).await;
1322        let ended = driven.await.unwrap().unwrap();
1323        assert!(ended.stopped && hooks.stopped());
1324        assert!(!hooks.stop.exists(), "the request is consumed");
1325    }
1326
1327    #[tokio::test]
1328    async fn reports_prompt_errors_and_early_exit() {
1329        let (mut server, w, r) = pair();
1330        let dir = tempfile::tempdir().unwrap();
1331        let hooks = resident_hooks(
1332            dir.path(),
1333            Arc::default(),
1334            Arc::default(),
1335            Duration::from_secs(3600),
1336        );
1337        let driven = tokio::spawn(drive(w, r, "x".into(), Some(hooks), Arc::default()));
1338        server.handshake().await;
1339        server.command().await;
1340        server.emit(json!({"type": "prompt_result", "id": "p0", "status": "error", "sessionSettled": true,
1341            "error": {"message": "rate limited", "httpStatus": 429, "retryable": true}})).await;
1342        tokio::time::timeout(Duration::from_secs(5), server.finish(None))
1343            .await
1344            .expect("a failed resident session exits promptly");
1345        let ended = driven.await.unwrap().unwrap();
1346        let error = ended.error.unwrap();
1347        assert_eq!(
1348            (error.message.as_str(), error.http_status),
1349            ("rate limited", Some(429))
1350        );
1351
1352        let (mut server, w, r) = pair();
1353        let driven = tokio::spawn(drive(w, r, "x".into(), None, Arc::default()));
1354        server.handshake().await;
1355        server.command().await;
1356        drop(server);
1357        let error = driven.await.unwrap().unwrap_err();
1358        assert!(format!("{error:#}").contains("exited before the turn finished"));
1359    }
1360}