From 145eb7efb048ffe175103e23be36fe9e49f158a9 Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:03:01 +0100 Subject: [PATCH 01/10] oxa: wait with a deadline and wake on real attention instead of polling The interactive worker waited 50 ms for a command and then served the session host (timers, MCP callbacks, `sendMessage` with `triggerTurn`); the RPC session thread waited 20 ms for a job. Both are idle spin rates on a front end that is doing nothing, and both were the only way state that does not travel through the worker's own channel was noticed. The wait is now a deadline with an explicit wake. A session registers one attention waker (`Handle::set_attention_waker`), called after the state the front end re-checks is already in place: - `CoreHost::post` wakes once the request is in the channel the front end serves; - `Handle::request_wrap_up` and `Handle::interrupt` wake once the flag is set. The interactive worker takes the wake as `SessionCmd::Wake` on its own command channel and serves the host at once (`WORKER_IDLE_TICK` 50 -> 250 ms as the deadline); the RPC session thread takes it as `Job::Wake` and re-checks its stop flags, its supervisory loop now waiting on a condvar (`RPC_IDLE_TICK` 20 -> 250 ms). One wake in flight per front end is enough: the waker coalesces on a pending flag that the front end clears when it serves, so a wake raised while one is served is not lost. A panic in the waker is contained, like other front-end callbacks. Idle wakeups fall from 20/s to 4/s per thread; nothing waits longer than the tick for one of these events, and no command, inbox follow-up, cancellation or shutdown path needs the tick at all. Refs #877. --- oxa/oxa-core/src/host.rs | 40 ++++++++ oxa/oxa-core/src/queue.rs | 87 ++++++++++++++++++ oxa/oxa-interactive/src/app.rs | 52 ++++++++++- oxa/oxa-interactive/src/model.rs | 5 + oxa/oxa-interactive/tests/eint_interactive.rs | 92 ++++++++++++++++++- oxa/oxa-interactive/tests/h_panic.rs | 3 +- .../tests/v020_prefill_paste.rs | 6 +- oxa/oxa-rpc/src/server.rs | 68 +++++++++++++- .../c10_rpc_server_run_control_commands.rs | 30 ++++++ 9 files changed, 370 insertions(+), 13 deletions(-) diff --git a/oxa/oxa-core/src/host.rs b/oxa/oxa-core/src/host.rs index 68fcbafd8..a6b7033e9 100644 --- a/oxa/oxa-core/src/host.rs +++ b/oxa/oxa-core/src/host.rs @@ -183,6 +183,10 @@ impl CoreHost { let (reply, answer) = mpsc::channel(); let tx = self.tx.lock().unwrap_or_else(|p| p.into_inner()); tx.send(HostRequest { action, reply }).map_err(|_| gone())?; + drop(tx); + // The request is in the channel before the wake: a front end that waits instead of + // polling (see `Handle::set_attention_waker`) finds it when it serves the host. + self.shared.gate.attention.notify(); Ok(answer) } @@ -1294,6 +1298,7 @@ fn notice(sink: &mut dyn EventSink, level: Level, text: impl Into) { #[cfg(test)] mod tests { use super::*; + use crate::Handle; use oxa_config::{Dirs, Settings}; use oxa_proto::{Engine, FrozenPrefix, HeadlessUi, Mode, ThinkingLevel, VecSink}; use oxa_sandbox::NoSandbox; @@ -1403,6 +1408,41 @@ mod tests { handle.join().expect("caller thread") } + /// O-386: a host request posted while the front end waits (instead of polling) wakes it, so + /// the request is served at once and not at the front end's next idle tick. The request is + /// in the channel before the wake, so a woken front end finds it. + #[test] + fn a_posted_host_request_wakes_the_front_end() { + let f = fixture(); + let fired = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = fired.clone(); + let handle = Handle { + shared: f.st.shared.clone(), + }; + handle.set_attention_waker(Arc::new(move || { + count.fetch_add(1, Ordering::SeqCst); + })); + f.host + .call(HostAction::SendMessage { + custom_type: "test".into(), + content: "wake".into(), + display: true, + details: Value::Null, + deliver: Delivery::FollowUp, + trigger_turn: true, + }) + .expect("accepted"); + assert_eq!( + fired.load(Ordering::SeqCst), + 1, + "the posted request wakes the front end" + ); + assert!( + f.rx.try_recv().is_ok(), + "the request is in the channel the front end serves" + ); + } + /// #554 / #557: host writes use the same truthful unattended refusal as built-in tools, /// without promising workarounds that Ask mode or protected paths would refuse too. #[test] diff --git a/oxa/oxa-core/src/queue.rs b/oxa/oxa-core/src/queue.rs index ebbdd3b18..b45aa836d 100644 --- a/oxa/oxa-core/src/queue.rs +++ b/oxa/oxa-core/src/queue.rs @@ -124,6 +124,39 @@ pub struct Gate { /// `true` once a front end polls `Session::take_swap_request`; without it the two /// extension calls answer `unsupported_in_oxa`. pub swap_enabled: std::sync::atomic::AtomicBool, + /// The wake a front end registered for state it cannot poll (see + /// [`Handle::set_attention_waker`]). + pub attention: Attention, +} + +/// The wake a front end registered for state it cannot see through its own channels: a host +/// request posted while its worker waits ([`CoreHost::post`]) and a wrap-up or interruption +/// request. A front end that would otherwise poll a channel waits with a deadline and is +/// woken here instead. One waker per session; the closure must be cheap and must not block. +#[derive(Default)] +pub struct Attention(Mutex>>); + +impl std::fmt::Debug for Attention { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // The closure is not printable; its presence is enough for a `{:?}` of the state. + f.write_str("Attention(..)") + } +} + +impl Attention { + fn set(&self, waker: Arc) { + *lock(&self.0) = Some(waker); + } + + /// Wake the front end, if one registered. Called after the state the front end will look + /// at is in place (the host request is in its channel, the wrap-up flag is set), so a + /// woken front end that re-checks sees it. A panic in the waker is contained here. + pub(crate) fn notify(&self) { + let waker = lock(&self.0).clone(); + if let Some(waker) = waker { + let _ = oxa_proto::panic::contain(|| waker()); + } + } } /// Holds [`Gate::in_flight`] for one request; dropping it opens the gate. @@ -389,6 +422,9 @@ impl Handle { .compare_exchange(0, reason as u8, Ordering::SeqCst, Ordering::SeqCst); self.cancel_background(); self.shared.cancel_retry.cancel(); + // The flag is set: a front end that waits instead of polling (see + // [`Handle::set_attention_waker`]) must re-check it now. + self.notify_attention(); } pub fn wrap_up_reason(&self) -> Option { @@ -412,6 +448,21 @@ impl Handle { self.abort(); self.abort_retry(); self.cancel_background(); + // Set before the wake, so a woken front end sees it (see `set_attention_waker`). + self.notify_attention(); + } + + /// Register the wake this session gives a front end that waits instead of polling: a host + /// request posted while the front end waits ([`CoreHost::post`]) and a wrap-up or + /// interruption request ([`Handle::request_wrap_up`], [`Handle::interrupt`]). One waker + /// per session; the closure must be cheap and must not block. + pub fn set_attention_waker(&self, waker: Arc) { + self.shared.gate.attention.set(waker); + } + + /// Wake the registered front end, if any (see [`Handle::set_attention_waker`]). + pub(crate) fn notify_attention(&self) { + self.shared.gate.attention.notify(); } pub fn interrupted(&self) -> bool { @@ -476,6 +527,7 @@ impl Handle { #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::AtomicUsize; fn handle(steer: QueueMode, follow: QueueMode) -> Handle { Handle { @@ -502,6 +554,41 @@ mod tests { assert_eq!(h.wrap_up_reason(), Some(WrapUpReason::TimeLimit)); } + /// O-386: a front end that waits instead of polling is woken when the state it cannot see + /// through its own channels changes: a wrap-up request and an interruption. + #[test] + fn the_attention_waker_fires_on_wrap_up_and_interrupt() { + let h = handle(QueueMode::All, QueueMode::All); + let fired = Arc::new(AtomicUsize::new(0)); + let count = fired.clone(); + h.set_attention_waker(Arc::new(move || { + count.fetch_add(1, Ordering::SeqCst); + })); + h.request_wrap_up(WrapUpReason::TimeLimit); + assert_eq!(fired.load(Ordering::SeqCst), 1, "the wrap-up wakes the front end"); + h.interrupt(); + assert_eq!( + fired.load(Ordering::SeqCst), + 2, + "the interruption wakes the front end" + ); + // The state is set before the wake, so a woken front end that re-checks sees it. + assert!(h.interrupted()); + assert_eq!(h.wrap_up_reason(), Some(WrapUpReason::TimeLimit)); + } + + /// A waker is front-end code: a panic in it must not unwind into the session that set the + /// state (the state is already in place and the front end re-checks it). + #[test] + fn a_panicking_attention_waker_is_contained() { + let h = handle(QueueMode::All, QueueMode::All); + h.set_attention_waker(Arc::new(|| panic!("injected waker panic"))); + h.request_wrap_up(WrapUpReason::Signal); + assert_eq!(h.wrap_up_reason(), Some(WrapUpReason::Signal)); + h.interrupt(); + assert!(h.interrupted()); + } + #[test] fn inbox_wakes_coalesce_even_when_model_drains_input_between_admissions() { let h = handle(QueueMode::All, QueueMode::All); diff --git a/oxa/oxa-interactive/src/app.rs b/oxa/oxa-interactive/src/app.rs index 02f803662..3fb0e2165 100644 --- a/oxa/oxa-interactive/src/app.rs +++ b/oxa/oxa-interactive/src/app.rs @@ -181,9 +181,13 @@ pub fn run_session( ); let stop = WorkerStop::new(); let worker_stop = stop.clone(); + // The worker's own wake sender: the session's attention waker sends `SessionCmd::Wake` + // through it (see `install_wake`), so a host request posted while the worker waits is + // served at once instead of at the next idle tick. + let wake = cmd_tx.clone(); let spawned = thread::Builder::new() .name("oxa-worker".to_string()) - .spawn(move || worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop)); + .spawn(move || worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop, wake)); let worker = match spawned { Ok(w) => w, Err(_) => return (1, None), @@ -351,7 +355,27 @@ impl WorkerStop { /// How long the worker waits for a command before its idle tick serves the session's host /// (`Session::serve_host`: timers, MCP callbacks, `sendMessage` with `triggerTurn`). -pub const WORKER_IDLE_TICK: Duration = Duration::from_millis(50); +/// +/// The wait is not the only wake: a host request posted while the worker waits calls the +/// session's attention waker (`Handle::set_attention_waker`), which sends one +/// [`SessionCmd::Wake`], so the host is served at once. This is the deadline for the tick +/// itself, and a session without hook sets posts no host request at all. +pub const WORKER_IDLE_TICK: Duration = Duration::from_millis(250); + +/// Install the worker's idle wake on `handle`: the session calls it when something the worker +/// cannot see through `cmds` happens (a host request posted while it waits, a wrap-up +/// request), and one coalesced [`SessionCmd::Wake`] is sent so the host is served at once +/// instead of at the next idle tick. One wake in flight is enough: the worker clears the flag +/// when it serves. +fn install_wake(handle: &Handle, wake: &Sender, pending: &Arc) { + let tx = wake.clone(); + let pending = pending.clone(); + handle.set_attention_waker(Arc::new(move || { + if !pending.swap(true, Ordering::SeqCst) { + let _ = tx.send(SessionCmd::Wake); + } + })); +} /// The UI loop over an arbitrary terminal (tests pass `oxa_tui::TestTerminal` and scripted /// channels). Ends when an [`AppAction::Quit`] was carried out or `worker` disconnects. @@ -463,14 +487,17 @@ pub fn worker_loop( cmds: Receiver, out: Sender, ui: Sender, + wake: Sender, ) -> Option { - worker_loop_with(session, reopen, cmds, out, ui, WorkerStop::new()) + worker_loop_with(session, reopen, cmds, out, ui, WorkerStop::new(), wake) } /// [`worker_loop`] with the worker's stop signal (see [`WorkerStop`]). Between commands the /// worker waits at most [`WORKER_IDLE_TICK`] and then serves the session's host, so host /// requests made while idle are answered and a turn an extension triggered runs, its events -/// reaching the UI like a prompt's. +/// reaching the UI like a prompt's. `wake` is a sender on the same channel as `cmds`, used to +/// send the worker its own [`SessionCmd::Wake`] when a host request arrives (see +/// [`install_wake`]): the tick is the deadline, not the only wake. pub fn worker_loop_with( session: Session, mut reopen: ReopenFn, @@ -478,10 +505,14 @@ pub fn worker_loop_with( out: Sender, ui: Sender, stop: WorkerStop, + wake: Sender, ) -> Option { let mut ui_proxy = UiProxy::new(ui.clone()); let mut last = StatusModel::default(); stop.enter(session.handle()); + // One wake in flight is enough; the flag is shared with the waker of the session in force. + let pending = Arc::new(AtomicBool::new(false)); + install_wake(&session.handle(), &wake, &pending); let _ = out.send(WorkerMsg::Session(session_info(&session))); let mut session = Some(session); // Commands are taken through a backlog so a `Shutdown` anywhere behind queued work is @@ -548,6 +579,16 @@ pub fn worker_loop_with( } match cmd { SessionCmd::Shutdown => break, + // The session's attention waker (see [`install_wake`]): something the worker cannot + // see through `cmds` happened while it waited — a host request was posted, or a + // wrap-up was requested. Serve the host now instead of at the next idle tick. The + // flag is cleared first, so a wake arriving while the host is served is not lost. + SessionCmd::Wake => { + pending.store(false, Ordering::SeqCst); + if let Some(s) = session.as_mut() { + idle_tick(s, &out, &mut ui_proxy, &mut last, &stop); + } + } SessionCmd::Reopen(how) => { // The session to return to when the new one cannot be opened (an unreadable // file): the old one is already shut down by then. @@ -576,6 +617,7 @@ pub fn worker_loop_with( match reopen(how, carry) { Ok(new) => { stop.enter(new.handle()); + install_wake(&new.handle(), &wake, &pending); session = Some(new); opened = true; } @@ -591,6 +633,7 @@ pub fn worker_loop_with( match again { Ok(s) => { stop.enter(s.handle()); + install_wake(&s.handle(), &wake, &pending); session = Some(s); } Err(e) => { @@ -1575,6 +1618,7 @@ fn execute( SessionCmd::Reopen(_) | SessionCmd::Snapshot | SessionCmd::Shutdown + | SessionCmd::Wake | SessionCmd::PrefillDraft { .. } => (Ok(()), false), } } diff --git a/oxa/oxa-interactive/src/model.rs b/oxa/oxa-interactive/src/model.rs index ca7b376b5..47ebbe9ad 100644 --- a/oxa/oxa-interactive/src/model.rs +++ b/oxa/oxa-interactive/src/model.rs @@ -446,6 +446,11 @@ pub enum SessionCmd { Inbox { session_id: String, }, + /// The worker's own wake, sent by the session's attention waker + /// (`Handle::set_attention_waker`): a host request was posted while the worker waited, or + /// a wrap-up was requested. No command runs; the worker serves the host now instead of at + /// its next idle tick. + Wake, /// `Session::prompt`. Slash commands that are templates, `/skill:name` or extension /// commands are sent as a prompt and expanded by the core. Prompt { diff --git a/oxa/oxa-interactive/tests/eint_interactive.rs b/oxa/oxa-interactive/tests/eint_interactive.rs index fe401e1e0..9956c8d68 100644 --- a/oxa/oxa-interactive/tests/eint_interactive.rs +++ b/oxa/oxa-interactive/tests/eint_interactive.rs @@ -201,8 +201,9 @@ fn spawn_worker(session: Session, reopen: ReopenFn) -> Worker { let (done_tx, done_rx) = mpsc::channel(); let stop = WorkerStop::new(); let worker_stop = stop.clone(); + let wake = cmd_tx.clone(); std::thread::spawn(move || { - let last = worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop); + let last = worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop, wake); let _ = done_tx.send(last); }); Worker { @@ -288,6 +289,95 @@ fn idle_tick_runs_a_triggered_turn() { }); } +/// O-386: the worker's idle wait is the tick (250 ms), not a busy poll. A host request posted +/// before the worker installs its wake can only be served by the tick, so the time to the +/// triggered turn's settlement is the tick. Before O-386 the tick was 50 ms and this fails. +#[test] +fn an_idle_worker_waits_the_tick_before_it_serves_the_host() { + bounded(30, || { + let env = TestEnv::new(); + let hooks = Arc::new(TestHooks::default()); + let engine = Arc::new(ScriptedEngine::new(vec![ScriptTurn::text("pong")])); + let session = Session::open( + deps( + &env, + Arc::new(MemStore::new()), + engine.clone(), + vec![hooks.clone()], + ), + Open::New, + ) + .expect("open"); + // Posted before the worker exists: no waker is registered yet, so only the tick can + // serve it. + let host = hooks.host.lock().unwrap().clone().expect("attached"); + host.call(trigger("ping")).expect("accepted"); + let w = spawn_worker(session, no_reopen()); + let start = Instant::now(); + let events = events_until(&w, |e| matches!(e, AgentEvent::AgentSettled { .. })); + let waited = start.elapsed(); + assert!(events.iter().any(|e| matches!(e, AgentEvent::AgentStart))); + assert!( + waited >= Duration::from_millis(100), + "the idle wait is the tick, not a busy poll: served after {waited:?}" + ); + assert!( + waited <= Duration::from_secs(1), + "the tick is the deadline: served after {waited:?}" + ); + let _ = w.cmds.send(SessionCmd::Shutdown); + w.done + .recv_timeout(Duration::from_secs(10)) + .expect("worker ended"); + }); +} + +/// O-386: a host request posted while the worker waits is served at once by the session's +/// attention waker, not at the next idle tick. With the tick at 250 ms this can only pass +/// through the wake; before O-386 it passed on the 50 ms tick, so it is the regression guard +/// for the wake, not a failing-before test. +#[test] +fn a_host_request_posted_while_the_worker_waits_is_served_at_once() { + bounded(30, || { + let env = TestEnv::new(); + let hooks = Arc::new(TestHooks::default()); + let engine = Arc::new(ScriptedEngine::new(vec![ScriptTurn::text("pong")])); + let session = Session::open( + deps( + &env, + Arc::new(MemStore::new()), + engine.clone(), + vec![hooks.clone()], + ), + Open::New, + ) + .expect("open"); + let w = spawn_worker(session, no_reopen()); + // The worker announced its session: it is in its wait now. + assert!( + matches!( + w.msgs.recv_timeout(Duration::from_secs(10)), + Ok(WorkerMsg::Session(_)) + ), + "the worker announces its session before it waits" + ); + let host = hooks.host.lock().unwrap().clone().expect("attached"); + let start = Instant::now(); + host.call(trigger("ping")).expect("accepted"); + let events = events_until(&w, |e| matches!(e, AgentEvent::AgentSettled { .. })); + let waited = start.elapsed(); + assert!(events.iter().any(|e| matches!(e, AgentEvent::AgentStart))); + assert!( + waited < Duration::from_millis(100), + "the wake serves the host before the tick: served after {waited:?}" + ); + let _ = w.cmds.send(SessionCmd::Shutdown); + w.done + .recv_timeout(Duration::from_secs(10)) + .expect("worker ended"); + }); +} + /// Item 3: `SessionCmd::Shortcut` runs the extension's handler through `Session::run_shortcut`; /// a turn it triggers runs right after it. The worker announces the bound keys. #[test] diff --git a/oxa/oxa-interactive/tests/h_panic.rs b/oxa/oxa-interactive/tests/h_panic.rs index dd75c4a19..b5565106d 100644 --- a/oxa/oxa-interactive/tests/h_panic.rs +++ b/oxa/oxa-interactive/tests/h_panic.rs @@ -123,8 +123,9 @@ fn a_panicking_command_is_its_error_and_the_worker_goes_on() { let (msg_tx, msg_rx) = mpsc::channel(); let (ui_tx, _ui_rx) = mpsc::channel(); let reopen: ReopenFn = Box::new(|_, _| Err(OxaError::new("invalid", "no reopen in this test"))); + let wake = cmd_tx.clone(); let worker = std::thread::spawn(move || { - worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, WorkerStop::new()) + worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, WorkerStop::new(), wake) }); let prompt = |text: &str| SessionCmd::Prompt { diff --git a/oxa/oxa-interactive/tests/v020_prefill_paste.rs b/oxa/oxa-interactive/tests/v020_prefill_paste.rs index 74acd7c75..efb78df68 100644 --- a/oxa/oxa-interactive/tests/v020_prefill_paste.rs +++ b/oxa/oxa-interactive/tests/v020_prefill_paste.rs @@ -83,8 +83,10 @@ fn worker_prefills_the_current_draft_only() { let (ui_tx, _ui_rx) = mpsc::channel(); let reopen: ReopenFn = Box::new(|_, _| Err(OxaError::new("invalid", "no reopen in this test"))); let worker_stop = stop.clone(); - let worker = - std::thread::spawn(move || worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop)); + let wake = cmd_tx.clone(); + let worker = std::thread::spawn(move || { + worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop, wake) + }); let draft = "fn main() { println!(\"pasted\"); }\n".repeat(80); // Taken at an old generation: the user typed since, so it is skipped. diff --git a/oxa/oxa-rpc/src/server.rs b/oxa/oxa-rpc/src/server.rs index 6a60255bb..506a0ba4b 100644 --- a/oxa/oxa-rpc/src/server.rs +++ b/oxa/oxa-rpc/src/server.rs @@ -23,8 +23,18 @@ use std::collections::HashSet; use std::io::BufRead; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, Sender}; -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::thread; +use std::time::Duration; + +/// How long the session thread waits for a job before it re-checks the stop flags +/// (`wrap_up_requested`, `interrupted`). +/// +/// The wait is not the only wake: the session's attention waker (see +/// [`Handle::set_attention_waker`]) sends [`Job::Wake`] when a wrap-up or an interruption is +/// requested, so a stop is served at once instead of at the next tick. A job (a command, an +/// inbox follow-up, a shutdown) wakes the wait by itself. +const RPC_IDLE_TICK: Duration = Duration::from_millis(250); /// One parsed command line. #[derive(Debug, Clone, PartialEq)] @@ -144,6 +154,9 @@ enum Job { Outcome(RunOutcome), /// A follow-up is already in Handle's queue; wake the session even with stdin idle. Inbox(String), + /// The session's attention waker: a wrap-up or an interruption was requested. The session + /// thread re-checks the flags at the top of its loop; the job carries no work. + Wake, Shutdown, } @@ -413,6 +426,7 @@ fn session_loop( gate: Arc>, bash_running: Arc, tx: Sender, + wake_pending: Arc, ) -> RunOutcome { let mut outcome = RunOutcome::NothingToDo; let mut inbox = None; @@ -473,7 +487,7 @@ fn session_loop( } } } else { - match rx.recv_timeout(std::time::Duration::from_millis(20)) { + match rx.recv_timeout(RPC_IDLE_TICK) { Ok(job) => job, Err(mpsc::RecvTimeoutError::Timeout) => continue, Err(mpsc::RecvTimeoutError::Disconnected) => break, @@ -498,6 +512,13 @@ fn session_loop( false, ) } + // The session's attention waker: a wrap-up or an interruption was requested. The + // flags are re-checked at the top of the loop; the job carries no work. The flag is + // cleared first, so a wake arriving while this one is served is not lost. + Job::Wake => { + wake_pending.store(false, Ordering::SeqCst); + continue; + } Job::Shutdown => break, }; // Join the old watcher before any explicit session transition. Already admitted @@ -678,14 +699,41 @@ pub fn serve_outcome( dirs, }; let cache = Arc::new(Mutex::new(publish(&cx))); + // The wake the session thread and the supervisory loop share. The session's attention + // waker (see `Handle::set_attention_waker`) sends one `Job::Wake` per pending wake, so the + // session thread's wait ends at once when a wrap-up or an interruption is requested, and + // signals the supervisory loop, which otherwise waits on the session thread's exit. + let wake_pending = Arc::new(AtomicBool::new(false)); + let done = Arc::new((Mutex::new(false), Condvar::new())); + { + let wake_tx = tx.clone(); + let wake_pending = wake_pending.clone(); + let done = done.clone(); + handle.set_attention_waker(Arc::new(move || { + if !wake_pending.swap(true, Ordering::SeqCst) { + let _ = wake_tx.send(Job::Wake); + } + let (lock, wake) = &*done; + drop(lock.lock().unwrap_or_else(|p| p.into_inner())); + wake.notify_all(); + })); + } let worker = { let cache = cache.clone(); let gate = gate.clone(); let bash_flag = bash_running.clone(); let tx = tx.clone(); + let wake_pending = wake_pending.clone(); + let done = done.clone(); thread::Builder::new() .name("oxa-rpc-session".to_string()) - .spawn(move || session_loop(cx, rx, cache, gate, bash_flag, tx)) + .spawn(move || { + let outcome = session_loop(cx, rx, cache, gate, bash_flag, tx, wake_pending); + let (lock, wake) = &*done; + *lock.lock().unwrap_or_else(|p| p.into_inner()) = true; + wake.notify_all(); + outcome + }) .map_err(|e| OxaError::io("cannot start the session thread", &e))? }; let control = handle.clone(); @@ -723,12 +771,22 @@ pub fn serve_outcome( return Err(OxaError::io("cannot start the RPC input thread", &error)); } }; - while !worker.is_finished() { + // The supervisory wait: the session thread signals `done` when it returns, and the + // attention waker signals it when a wrap-up or an interruption is requested (the router is + // closed then, so a dialog the run waits on is answered). The tick is the deadline, not the + // only wake. + let (done_lock, done_wake) = &*done; + let mut finished = done_lock.lock().unwrap_or_else(|p| p.into_inner()); + while !*finished && !worker.is_finished() { if control.wrap_up_requested() || control.interrupted() { router.close(); } - thread::sleep(std::time::Duration::from_millis(20)); + finished = done_wake + .wait_timeout(finished, RPC_IDLE_TICK) + .unwrap_or_else(|p| p.into_inner()) + .0; } + drop(finished); router.close(); if reader.is_finished() { let _ = reader.join(); diff --git a/oxa/oxa-rpc/tests/c10_rpc_server_run_control_commands.rs b/oxa/oxa-rpc/tests/c10_rpc_server_run_control_commands.rs index ea22496e0..d60edb2c6 100644 --- a/oxa/oxa-rpc/tests/c10_rpc_server_run_control_commands.rs +++ b/oxa/oxa-rpc/tests/c10_rpc_server_run_control_commands.rs @@ -896,6 +896,36 @@ fn wrap_up_retains_queued_errors_without_running_later_commands() { } } +#[test] +fn a_wrap_up_while_the_session_thread_waits_is_served_before_the_tick() { + // O-386: the session thread waits up to RPC_IDLE_TICK (250 ms) for a job. A wrap-up + // requested while it waits is served at once by the session's attention waker, not at the + // tick: the server returns without any job being sent and without stdin closing. Before + // O-386 the tick was 20 ms, so this is the regression guard for the wake, not a + // failing-before test. + let env = TestEnv::new(); + let engine = Arc::new(ScriptedEngine::new(Vec::new())); + let session = open_session(&env, engine); + let handle = session.handle(); + let mut rpc = Rpc::start(session, &env); + // No command is sent: the session thread is in its wait. + let start = Instant::now(); + handle.request_wrap_up(oxa_core::WrapUpReason::Signal); + let outcome = rpc + .thread + .take() + .expect("the server thread") + .join() + .expect("the server thread does not panic") + .expect("serve returns Ok"); + let waited = start.elapsed(); + assert_eq!(outcome, RunOutcome::Interrupted); + assert!( + waited < Duration::from_millis(100), + "the wrap-up is served at once, not at the tick: {waited:?}" + ); +} + #[test] fn stdin_close_drains_work_and_keeps_the_late_commands_outcome() { for (kind, accepted, expected_code) in [("get_state", true, 0), ("get_commands", false, 1)] { From 88285d26e8ed7c55ba839af281f7921f16db54b7 Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:18:16 +0100 Subject: [PATCH 02/10] oxa: run the boot preload when a session is ready, not on the idle tick The boot preload (O-152) was triggered by the worker's first idle tick. With the tick at 50 ms that also made it run before a user's first prompt in practice; at 250 ms the worker is still waiting when the first prompt arrives, so the preload never ran for that session (the wire is no longer empty after the first turn) and `keys_settings::set_011` failed in CI. The preload is not an idle wait: it is now attempted on the first pass in which the worker would otherwise wait, for the session it started with and for every session a reopen gives it. `idle_tick` still tries it, so a session whose hook set had requests pending at that instant is retried on a tick, as before. Refs #877. --- oxa/oxa-interactive/src/app.rs | 54 ++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/oxa/oxa-interactive/src/app.rs b/oxa/oxa-interactive/src/app.rs index 3fb0e2165..55fb6f641 100644 --- a/oxa/oxa-interactive/src/app.rs +++ b/oxa/oxa-interactive/src/app.rs @@ -519,6 +519,9 @@ pub fn worker_loop_with( // seen before that work starts: stop takes precedence (a prompt queued before the quit // must not begin after it). let mut backlog: VecDeque = VecDeque::new(); + // O-152: the boot preload is due as soon as a session is ready, not at the next idle tick. + // Set again when a reopen gives the worker a new session. + let mut preload_due = true; loop { // An extension's `ctx.newSession()` / `ctx.switchSession()` is applied as a reopen // before the next command (the commands queued behind it run in the new session). @@ -562,16 +565,28 @@ pub fn worker_loop_with( } let cmd = match backlog.pop_front() { Some(cmd) => cmd, - None => match cmds.recv_timeout(WORKER_IDLE_TICK) { - Ok(cmd) => cmd, - Err(mpsc::RecvTimeoutError::Timeout) => { + None => { + // O-152 / O-386: with nothing queued the worker is about to wait, and a session + // in force that has not preloaded its prefix yet does so now — the boot preload + // must not wait for the idle tick, which is now 250 ms and serves the host + // (a hook request pending at this instant still defers it to `idle_tick`). + if preload_due { + preload_due = false; if let Some(s) = session.as_mut() { - idle_tick(s, &out, &mut ui_proxy, &mut last, &stop); + run_boot_preload(s, &out, &mut ui_proxy, &stop); } - continue; } - Err(mpsc::RecvTimeoutError::Disconnected) => break, - }, + match cmds.recv_timeout(WORKER_IDLE_TICK) { + Ok(cmd) => cmd, + Err(mpsc::RecvTimeoutError::Timeout) => { + if let Some(s) = session.as_mut() { + idle_tick(s, &out, &mut ui_proxy, &mut last, &stop); + } + continue; + } + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } }; // A command taken in the same instant as the stop does not start. if stop.is_stopped() { @@ -618,6 +633,7 @@ pub fn worker_loop_with( Ok(new) => { stop.enter(new.handle()); install_wake(&new.handle(), &wake, &pending); + preload_due = true; session = Some(new); opened = true; } @@ -634,6 +650,7 @@ pub fn worker_loop_with( Ok(s) => { stop.enter(s.handle()); install_wake(&s.handle(), &wake, &pending); + preload_due = true; session = Some(s); } Err(e) => { @@ -726,6 +743,18 @@ pub fn worker_loop_with( ended } +/// O-152: the boot preload of the session in force while its wire is still empty: prefill its +/// frozen prefix (H6, background) so the first prompt starts warm. Once per entered session, +/// and only if no host request is pending (then it is retried on a tick). The preload is +/// invisible: its progress events are not shown (they would set the foreground activity and +/// make the UI treat the next prompt as steering), and the UI cancels it on input +/// (`WorkerStop::is_preloading`). +fn run_boot_preload(s: &mut Session, out: &Sender, ui: &mut UiProxy, stop: &WorkerStop) { + stop.set_preloading(true); + s.preload_prefix(&mut PreloadSink(ChanSink(out.clone())), ui); + stop.set_preloading(false); +} + /// The worker's idle tick: serve what hook sets asked for while the session was idle. A turn /// an extension triggered runs here (its events go out like a prompt's); a fresh status /// follows whenever something was reported. @@ -736,14 +765,9 @@ fn idle_tick( last: &mut StatusModel, stop: &WorkerStop, ) { - // O-152: the first idle tick of a session with an empty wire prefills its frozen prefix - // (H6, background), so the first prompt starts warm. Once per entered session. The preload - // is invisible: its progress events are not shown (they would set the foreground activity - // and make the UI treat the next prompt as steering), and the UI cancels it on input - // (`WorkerStop::is_preloading`). - stop.set_preloading(true); - s.preload_prefix(&mut PreloadSink(ChanSink(out.clone())), ui); - stop.set_preloading(false); + // O-386: the preload is due before the worker's first wait (see `worker_loop_with`); this + // call is the retry for a session whose hook set had requests pending then. + run_boot_preload(s, out, ui, stop); let mut sink = CountingSink { inner: ChanSink(out.clone()), count: 0, From fd662ea74b00bb635ead85a7800f4b0df7db861a Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:21:58 +0100 Subject: [PATCH 03/10] oxa: end the turn's activity when the run is dropped or aborted (#699) A prompt typed after Ctrl+C was sent as steering on a run that had already ended, so the core dropped it and the next answer never came. The activity state, not the session's claim, decides whether a run is active: the claim is held past the end of the run for the settle work (hooks, the status file). - A dropped reply (aborted, failed, cut) clears the activity at once; a run that continues sets it again on its next turn. - After the user aborts, input is a new prompt until the run reports a new turn: an aborted run ends without delivering steering, so steering there would be lost. Fixes the i699_interrupt PTY checks for both the generation and the tool abort paths. --- oxa/oxa-interactive/src/app.rs | 8 ++++++++ oxa/oxa-interactive/src/driver.rs | 27 ++++++++++++++++++++++----- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/oxa/oxa-interactive/src/app.rs b/oxa/oxa-interactive/src/app.rs index 55fb6f641..4459eeb9d 100644 --- a/oxa/oxa-interactive/src/app.rs +++ b/oxa/oxa-interactive/src/app.rs @@ -1131,6 +1131,14 @@ pub fn apply_event(vm: &mut ViewModel, e: &AgentEvent) { EntryBody::Shown { text, why } => { if [shown_why::ABORTED, shown_why::FAILED, shown_why::CUT].contains(why) { shown_reply(vm, text, why); + // The reply was dropped: the turn is over, whatever the session is still + // claimed for (the settle work, including the front end's status file). + // Leaving the activity at `Thinking` made the UI treat a prompt typed + // after the dropped reply as steering on a run that had already ended + // (#699). A run that continues (a wrap-up turn, a replay after a cut) + // reports its next turn and sets the activity again. + vm.status.activity = Activity::Idle; + vm.status.activity_ms = 0; } } EntryBody::Msg { wire, parts, .. } if wire.role == Role::User => { diff --git a/oxa/oxa-interactive/src/driver.rs b/oxa/oxa-interactive/src/driver.rs index a385d5363..d2ae49f5b 100644 --- a/oxa/oxa-interactive/src/driver.rs +++ b/oxa/oxa-interactive/src/driver.rs @@ -317,6 +317,10 @@ pub(crate) struct Loop<'a> { /// Assume focus until the terminal reports otherwise (unsupported terminals stay quiet). focused: bool, run_finished: bool, + /// The user aborted the run and it has not reported a new turn since. Input typed in that + /// window is a new prompt, not steering: the run is ending and would drop the steering + /// message (#699). Cleared when a run starts a turn. + abort_requested: bool, pub(crate) dirty: bool, /// Ctrl+C was pressed on an empty editor; a second press within two seconds quits. armed: bool, @@ -449,6 +453,7 @@ impl<'a> Loop<'a> { sent_title: None, focused: true, run_finished: false, + abort_requested: false, dirty: true, armed: false, armed_at: None, @@ -683,12 +688,17 @@ impl<'a> Loop<'a> { } } - /// A run is active: the worker reported a non-idle activity or the handle says busy. The - /// boot preload (O-152) claims the session too, but is not a run: input is a prompt. - /// V020-OPTIMIZE #13: so is a draft prefill. + /// A run is active: the worker reported a non-idle activity. The boot preload (O-152) + /// claims the session too, but is not a run: input is a prompt. V020-OPTIMIZE #13: so is a + /// draft prefill. Both keep the activity idle (their progress events are dropped), so the + /// activity alone answers the question. + /// + /// The session's claim is not the signal: it is held past the end of the run, for the + /// settle work (hooks, the front end's status file). A reply the core dropped (an abort, a + /// failure, a cut) ends the run and clears the activity at once, so a prompt typed after + /// the dropped reply is a prompt and not steering on a run that has already ended (#699). fn running(&self) -> bool { self.vm.status.activity != Activity::Idle - || (self.handle.is_busy() && !self.worker.is_preloading() && !self.worker.is_drafting()) } pub(crate) fn animating(&self) -> bool { @@ -739,6 +749,10 @@ impl<'a> Loop<'a> { } } WorkerMsg::Event(e) => { + // A turn started: the run goes on, so input is steering again. + if matches!(e, AgentEvent::AgentStart) { + self.abort_requested = false; + } // AgentEnd can occur between tool/follow-up turns; only settled ends a run. if matches!(e, AgentEvent::AgentSettled { .. }) { if let Some(inbox) = &self.inbox { @@ -1306,6 +1320,9 @@ impl<'a> Loop<'a> { { self.handle.abort(); self.handle.abort_retry(); + // The run is ending: a prompt typed before it settles is a new prompt, not + // steering on a run that will drop it (#699). + self.abort_requested = true; self.dialogs.key(&key, &self.opts.keymap); self.restore_queue(); return; @@ -1681,7 +1698,7 @@ impl<'a> Loop<'a> { if self.fullscreen { self.viewport.scroll_to_bottom(); } - if self.running() { + if self.running() && !self.abort_requested { self.handle.steer(trimmed); self.sync_queue(); } else { From b7cf424388b24abeee06e4543c525f7e27808a4c Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:21:20 +0100 Subject: [PATCH 04/10] oxa: wait for the foreground turn in the interrupt pty check The boot preload (O-152) is sent as soon as a session is ready, before the worker's first wait, so the first request the fake sees in `generation_pty_ctrl_c_cancels_and_keeps_prompt_usable` is the `max_tokens: 0` preload. The check waited for "any request", then sent the Ctrl+C at the preload: it cancelled the background request and not the run it means to cancel. Wait for the request of the foreground turn itself (`max_tokens > 0`), which is the activity the interrupt must land on. Refs #877. --- oxa/oxa-cli/tests/i699_interrupt.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/oxa/oxa-cli/tests/i699_interrupt.rs b/oxa/oxa-cli/tests/i699_interrupt.rs index 3bb767d46..e94c93418 100644 --- a/oxa/oxa-cli/tests/i699_interrupt.rs +++ b/oxa/oxa-cli/tests/i699_interrupt.rs @@ -168,7 +168,10 @@ fn generation_pty_ctrl_c_cancels_and_keeps_prompt_usable() { let mut p = Process::start(&env, &server, "tui"); p.wait_text("READY"); p.send(b"synthetic cancellation check\r"); - p.wait_for(|| !server.requests().is_empty()); + // O-152: the boot preload (H6, `max_tokens: 0`) is on the wire before the first prompt, so + // wait for the foreground turn itself: the Ctrl+C must land on the run, not on the + // background prefill (which is not the activity the interrupt cancels). + p.wait_for(|| server.requests().iter().any(|r| r.max_tokens > 0)); p.send(b"\x03"); p.wait_text("partial reply dropped; your prompt stays"); // A fresh prompt proves the first Ctrl+C did not arm exit or poison the next turn. From efd09578ac4fcb9465e491b4d8adc8af68192be8 Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:52:23 +0100 Subject: [PATCH 05/10] oxa: start a new run for input typed while an abort unwinds (#906) An aborted run returns from the agent loop before `deliver_steering`, so a message queued in the moment between the aborted tool result and `AgentSettled` was never delivered and never handed back: the run ended with the message stuck in the steering queue. `oxa-cli::i699_interrupt tool_pty_ctrl_c_stops_tool_without_exiting` timed out waiting for the reply to the message typed after `Command aborted`. `Handle::is_aborting()` reports the run that holds the session while it winds down (claimed with `cancel` set: a front-end abort or the run's own loop guard), so a message queued there would never be taken. Enter/Alt+Enter now queue text only when a run is active, still takes a tool batch and the user has not aborted it ([`Loop::accepts_steering`]); otherwise the text starts a new run. Ctrl+C is unchanged. Tests: oxa-interactive d1 `enter_while_the_run_is_aborting_starts_a_new_run` (fails before the fix with `["x"]` stuck in the steering queue) and the oxa-core queue unit test for the new accessor. Refs #699, #906. --- oxa/oxa-core/src/queue.rs | 26 ++++ oxa/oxa-interactive/src/driver.rs | 15 ++- .../tests/d1_main_loop_and_regular_mode.rs | 126 +++++++++++++++++- 3 files changed, 160 insertions(+), 7 deletions(-) diff --git a/oxa/oxa-core/src/queue.rs b/oxa/oxa-core/src/queue.rs index bf8e6d304..12c894d99 100644 --- a/oxa/oxa-core/src/queue.rs +++ b/oxa/oxa-core/src/queue.rs @@ -528,6 +528,14 @@ impl Handle { pub fn is_busy(&self) -> bool { self.shared.busy.load(Ordering::SeqCst) } + /// Whether the run that holds the session is winding down: an abort ([`Handle::abort`]) or + /// the run's own loop guard set `cancel`, so the run takes no further tool batch and leaves + /// the queue undrained. A front end must send input typed now as a new prompt, never as a + /// steering message ([`Handle::steer`]) that nothing would deliver. `false` while the + /// session is idle: the next claim resets the token. + pub fn is_aborting(&self) -> bool { + self.shared.busy.load(Ordering::SeqCst) && self.shared.cancel.is_cancelled() + } /// The queues (steering, follow-up) when they changed since the last report, and clear the /// change mark. A front end that changed the queue from another thread reports the change /// itself this way, at once (pi emits `queue_update` when a message is queued); the session @@ -704,6 +712,24 @@ mod tests { assert_eq!(h.dequeue(), vec!["s1"]); } + /// `is_aborting` is the run the front end must not steer: a claimed session whose run was + /// cancelled. Idle, or busy with a clear token, is a run that still takes input. + #[test] + fn is_aborting_needs_a_claimed_cancelled_run() { + let h = handle(QueueMode::All, QueueMode::All); + assert!(!h.is_aborting(), "idle"); + h.shared.busy.store(true, Ordering::SeqCst); + assert!(!h.is_aborting(), "a run that was not cancelled takes input"); + h.abort(); + assert!(h.is_aborting()); + // The run ends and the next claim resets the token (`Session::begin`). + h.shared.busy.store(false, Ordering::SeqCst); + assert!(!h.is_aborting(), "a stale abort is not the next run"); + h.shared.busy.store(true, Ordering::SeqCst); + h.shared.cancel.reset(); + assert!(!h.is_aborting()); + } + /// A background cancel never reaches the user's run: `cancel` stays clear, and a run /// claimed after it (`Session::begin` resets `bg_cancel` and `bg_abort`) starts clean. /// A background request that has claimed but not armed yet sees it. diff --git a/oxa/oxa-interactive/src/driver.rs b/oxa/oxa-interactive/src/driver.rs index c7bd1d6c5..cddb01a35 100644 --- a/oxa/oxa-interactive/src/driver.rs +++ b/oxa/oxa-interactive/src/driver.rs @@ -701,6 +701,17 @@ impl<'a> Loop<'a> { self.vm.status.activity != Activity::Idle } + /// Whether Enter / Alt+Enter queue the text (steering / follow-up) rather than start a run: + /// a run is active, the user has not aborted it, and it still takes a tool batch. A run + /// that is winding down after an abort (#906) takes no further batch, so a queued message + /// would never be delivered; input typed in that window starts a new run instead. The + /// abort the user asked for is the same window seen before the worker reports it + /// ([`Self::abort_requested`]), so both are checked. Only what Enter does changes: Ctrl+C + /// still aborts, and the footer hint still reads "steer" for that moment. + fn accepts_steering(&self) -> bool { + self.running() && !self.abort_requested && !self.handle.is_aborting() + } + pub(crate) fn animating(&self) -> bool { self.running() || self.dialogs.is_open() @@ -1428,7 +1439,7 @@ impl<'a> Loop<'a> { } self.editor.set_text(""); self.editor.add_history(&text); - if self.running() { + if self.accepts_steering() { self.handle.follow_up(text); self.wake_queued(); self.sync_queue(); @@ -1699,7 +1710,7 @@ impl<'a> Loop<'a> { if self.fullscreen { self.viewport.scroll_to_bottom(); } - if self.running() && !self.abort_requested { + if self.accepts_steering() { self.handle.steer(trimmed); self.wake_queued(); self.sync_queue(); diff --git a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs index 2f82b7a11..c50202e42 100644 --- a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs +++ b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs @@ -12,15 +12,16 @@ use oxa_interactive::{ ViewSettings, WorkerMsg, }; use oxa_proto::{ - codes, Access, AgentEvent, CancelToken, Decision, Engine, Entry, EntryBody, EventMessage, ExecResult, - ExecSpec, Level, Mode, OxaError, Part, Policy, Sandbox, StopReason, ToolOutput, WireMsg, + codes, Access, AgentEvent, AssistantTurn, CancelToken, ChatRequest, Decision, Engine, EngineInfo, Entry, + EntryBody, EventMessage, ExecResult, ExecSpec, Level, Mode, OxaError, Part, Policy, Sandbox, StopReason, + StreamEvent, ToolOutput, WireMsg, }; use oxa_resources::Resources; use oxa_session::{MemStore, SessionStore}; use oxa_tui::{visible_width, InputEvent, Key, TermCaps, TestTerminal, Theme}; use std::path::Path; use std::sync::mpsc::{self, Receiver, Sender}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; // --------------------------------------------------------------------------------------------- // Harness @@ -70,8 +71,18 @@ fn session_open( store: Arc, open: Open, ) -> Session { + session_deps( + env, + Arc::new(ScriptedEngine::new(turns)) as Arc, + store, + open, + ) +} + +/// A session on an engine of the test's choosing, in the test's own directories. +fn session_deps(env: &TestEnv, engine: Arc, store: Arc, open: Open) -> Session { let deps = Deps { - engine: Arc::new(ScriptedEngine::new(turns)) as Arc, + engine, store, tools: Vec::new(), hooks: Vec::new(), @@ -91,6 +102,48 @@ fn session_open( Session::open(deps, open).expect("open the test session") } +/// An engine whose first `chat` blocks until the test releases it (or drops the sender): the +/// session stays claimed (`Handle::is_busy`) while the test drives the loop against a run that +/// is unwinding. Later requests pass through to the scripted turns. +struct HeldEngine { + inner: ScriptedEngine, + /// Taken by the first `chat`; dropping it (a failing test) releases the run too. + release: Mutex>>, + /// Signalled as the first `chat` starts, so the test knows the run is in the engine. + entered: Sender<()>, +} + +impl HeldEngine { + fn new(turns: Vec, release: Receiver<()>, entered: Sender<()>) -> HeldEngine { + HeldEngine { + inner: ScriptedEngine::new(turns), + release: Mutex::new(Some(release)), + entered, + } + } +} + +impl Engine for HeldEngine { + fn info(&self, target: Option<&str>) -> Result { + self.inner.info(target) + } + fn count_tokens(&self, text: &str) -> Result { + self.inner.count_tokens(text) + } + fn chat( + &self, + r: &ChatRequest, + cancel: &CancelToken, + on: &mut dyn FnMut(StreamEvent), + ) -> Result { + if let Some(release) = self.release.lock().unwrap().take() { + let _ = self.entered.send(()); + let _ = release.recv(); + } + self.inner.chat(r, cancel, on) + } +} + fn interactive_opts(env: &TestEnv) -> InteractiveOpts { InteractiveOpts { fullscreen: false, @@ -132,6 +185,16 @@ struct Driven { /// Run the loop with scripted input batches (one batch per poll) and scripted worker messages /// queued before it starts. Every script must end with Ctrl+D on an empty editor. fn drive(session: &Session, env: &TestEnv, batches: Vec>, worker: Vec) -> Driven { + drive_handle(session.handle(), env, batches, worker) +} + +/// [`drive`] on a handle alone, for a session that another thread is running. +fn drive_handle( + handle: oxa_core::Handle, + env: &TestEnv, + batches: Vec>, + worker: Vec, +) -> Driven { let mut term = TestTerminal::new(80, 24); for b in batches { term.push_input(b); @@ -146,7 +209,7 @@ fn drive(session: &Session, env: &TestEnv, batches: Vec>, worker let code = run_loop( &mut term, &mut opts, - session.handle(), + handle, cmd_tx, msg_rx, ui_rx, @@ -498,6 +561,59 @@ fn escape_aborts_and_restores_queue() { ); } +/// #906: Enter while an aborted run is still unwinding starts a new run. The aborted run takes +/// no further tool batch, so a steering message would sit in a queue nothing drains (the flaky +/// `oxa-cli::i699_interrupt::tool_pty_ctrl_c_stops_tool_without_exiting` caught it: the reply to +/// the message typed after `Command aborted` never came). +#[test] +fn enter_while_the_run_is_aborting_starts_a_new_run() { + let env = TestEnv::new(); + let (release_tx, release_rx) = mpsc::channel::<()>(); + let (entered_tx, entered_rx) = mpsc::channel::<()>(); + let mut s = session_deps( + &env, + Arc::new(HeldEngine::new( + vec![oxa_fake::ScriptTurn::text("recovered")], + release_rx, + entered_tx, + )), + Arc::new(MemStore::new()), + Open::Ephemeral, + ); + let handle = s.handle(); + let run = std::thread::spawn(move || { + let mut sink = oxa_proto::VecSink(Vec::new()); + let mut ui = oxa_proto::HeadlessUi::default(); + s.prompt("first".to_string(), Vec::new(), &mut sink, &mut ui) + }); + entered_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("the run reaches the engine"); + handle.abort(); + assert!( + handle.is_aborting(), + "Ctrl+C cancels the run that holds the session" + ); + let d = drive_handle( + handle.clone(), + &env, + vec![vec![ch('x'), key("enter")], vec![key("ctrl+d")]], + Vec::new(), + ); + assert_eq!(d.code, 0); + let (steering, follow_up) = handle.queued(); + assert!( + steering.is_empty() && follow_up.is_empty(), + "nothing waits in a queue the aborted run will never drain: {steering:?} {follow_up:?}" + ); + match d.cmds.as_slice() { + [SessionCmd::Prompt { text, .. }] => assert_eq!(text.as_str(), "x"), + _ => panic!("the input must start a run, not steer"), + } + drop(release_tx); + run.join().expect("the run ends").expect("the run settles"); +} + /// ! and !! #[test] fn bang_commands_dispatch() { From b08c8ffa2cd800fb6d72742a28dcb7e638a1e373 Mon Sep 17 00:00:00 2001 From: codex-integ Date: Tue, 17 Nov 2026 19:06:14 +0100 Subject: [PATCH 06/10] test(interactive): require worker exit when front end disconnects --- .../tests/d1_main_loop_and_regular_mode.rs | 2 +- oxa/oxa-interactive/tests/eint_interactive.rs | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs index 36cc8f223..9cf590bd1 100644 --- a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs +++ b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs @@ -598,7 +598,7 @@ fn enter_while_the_run_is_aborting_starts_a_new_run() { handle.clone(), &env, vec![vec![ch('x'), key("enter")], vec![key("ctrl+d")]], - Vec::new(), + vec![WorkerMsg::Event(AgentEvent::AgentStart)], ); assert_eq!(d.code, 0); let (steering, follow_up) = handle.queued(); diff --git a/oxa/oxa-interactive/tests/eint_interactive.rs b/oxa/oxa-interactive/tests/eint_interactive.rs index 2cb646dc3..88e094492 100644 --- a/oxa/oxa-interactive/tests/eint_interactive.rs +++ b/oxa/oxa-interactive/tests/eint_interactive.rs @@ -215,6 +215,36 @@ fn spawn_worker(session: Session, reopen: ReopenFn) -> Worker { } } +#[test] +fn dropping_front_end_senders_disconnects_the_idle_worker() { + let env = TestEnv::new(); + let session = Session::open( + deps( + &env, + Arc::new(MemStore::new()), + Arc::new(ScriptedEngine::new(Vec::new())), + Vec::new(), + ), + Open::Ephemeral, + ) + .expect("open"); + let w = spawn_worker(session, no_reopen()); + assert!(matches!( + w.msgs.recv_timeout(Duration::from_secs(3)), + Ok(WorkerMsg::Session(_)) + )); + drop(w.cmds); + let ended = w.done.recv_timeout(Duration::from_secs(3)); + if ended.is_err() { + w.stop.stop(); + let _ = w.done.recv_timeout(Duration::from_secs(3)); + } + assert!( + ended.is_ok(), + "the worker must not retain its own command channel" + ); +} + /// Collect worker messages until `until` holds for an event (or 10 s pass). fn events_until(w: &Worker, until: impl Fn(&AgentEvent) -> bool) -> Vec { let end = Instant::now() + Duration::from_secs(10); From 0c9d146ef3c34c292bbb9855330523c5d866dd26 Mon Sep 17 00:00:00 2001 From: codex-integ Date: Tue, 17 Nov 2026 19:06:49 +0100 Subject: [PATCH 07/10] fix(interactive): keep worker attention sender weakly owned --- oxa/oxa-interactive/src/app.rs | 22 ++++++++++--------- oxa/oxa-interactive/tests/eint_interactive.rs | 5 +++-- oxa/oxa-interactive/tests/h_panic.rs | 3 ++- .../tests/v020_prefill_paste.rs | 3 ++- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/oxa/oxa-interactive/src/app.rs b/oxa/oxa-interactive/src/app.rs index e71b64d07..c97d23cc3 100644 --- a/oxa/oxa-interactive/src/app.rs +++ b/oxa/oxa-interactive/src/app.rs @@ -21,7 +21,7 @@ use std::collections::VecDeque; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, Weak}; use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -154,6 +154,7 @@ pub fn run_session( vm.status = status_from(&state, &stats, &prev); let (cmd_tx, cmd_rx) = mpsc::channel::(); + let cmd_tx = Arc::new(cmd_tx); let (msg_tx, msg_rx) = mpsc::channel::(); let (ui_tx, ui_rx) = mpsc::channel::(); let handle = session.handle(); @@ -182,10 +183,9 @@ pub fn run_session( ); let stop = WorkerStop::new(); let worker_stop = stop.clone(); - // The worker's own wake sender: the session's attention waker sends `SessionCmd::Wake` - // through it (see `install_wake`), so a host request posted while the worker waits is - // served at once instead of at the next idle tick. - let wake = cmd_tx.clone(); + // The front end owns the wake sender. The worker keeps only a weak reference, so + // dropping all front-end senders still disconnects its receiver. + let wake = Arc::downgrade(&cmd_tx); let spawned = thread::Builder::new() .name("oxa-worker".to_string()) .spawn(move || worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop, wake)); @@ -198,7 +198,7 @@ pub fn run_session( term, opts, handle, - cmd_tx.clone(), + cmd_tx.as_ref().clone(), &msg_rx, &ui_rx, vm, @@ -368,12 +368,14 @@ pub const WORKER_IDLE_TICK: Duration = Duration::from_millis(250); /// request), and one coalesced [`SessionCmd::Wake`] is sent so the host is served at once /// instead of at the next idle tick. One wake in flight is enough: the worker clears the flag /// when it serves. -fn install_wake(handle: &Handle, wake: &Sender, pending: &Arc) { +fn install_wake(handle: &Handle, wake: &Weak>, pending: &Arc) { let tx = wake.clone(); let pending = pending.clone(); handle.set_attention_waker(Arc::new(move || { if !pending.swap(true, Ordering::SeqCst) { - let _ = tx.send(SessionCmd::Wake); + if let Some(tx) = tx.upgrade() { + let _ = tx.send(SessionCmd::Wake); + } } })); } @@ -488,7 +490,7 @@ pub fn worker_loop( cmds: Receiver, out: Sender, ui: Sender, - wake: Sender, + wake: Weak>, ) -> Option { worker_loop_with(session, reopen, cmds, out, ui, WorkerStop::new(), wake) } @@ -497,7 +499,7 @@ pub fn worker_loop( /// worker waits at most [`WORKER_IDLE_TICK`] and then serves the session's host, so host /// requests made while idle are answered and a turn an extension triggered runs, its events /// reaching the UI like a prompt's. `wake` is a sender on the same channel as `cmds`, used to -/// send the worker its own [`SessionCmd::Wake`] when a host request arrives (see +/// weakly borrow the front-end sender for [`SessionCmd::Wake`] when a host request arrives (see /// [`install_wake`]): the tick is the deadline, not the only wake. pub fn worker_loop_with( session: Session, diff --git a/oxa/oxa-interactive/tests/eint_interactive.rs b/oxa/oxa-interactive/tests/eint_interactive.rs index 88e094492..5dd0184e9 100644 --- a/oxa/oxa-interactive/tests/eint_interactive.rs +++ b/oxa/oxa-interactive/tests/eint_interactive.rs @@ -183,7 +183,7 @@ impl Hooks for TestHooks { } struct Worker { - cmds: Sender, + cmds: Arc>, msgs: Receiver, _ui: Receiver, done: Receiver>, @@ -201,7 +201,8 @@ fn spawn_worker(session: Session, reopen: ReopenFn) -> Worker { let (done_tx, done_rx) = mpsc::channel(); let stop = WorkerStop::new(); let worker_stop = stop.clone(); - let wake = cmd_tx.clone(); + let cmd_tx = Arc::new(cmd_tx); + let wake = Arc::downgrade(&cmd_tx); std::thread::spawn(move || { let last = worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop, wake); let _ = done_tx.send(last); diff --git a/oxa/oxa-interactive/tests/h_panic.rs b/oxa/oxa-interactive/tests/h_panic.rs index b5565106d..1b42db8fc 100644 --- a/oxa/oxa-interactive/tests/h_panic.rs +++ b/oxa/oxa-interactive/tests/h_panic.rs @@ -123,7 +123,8 @@ fn a_panicking_command_is_its_error_and_the_worker_goes_on() { let (msg_tx, msg_rx) = mpsc::channel(); let (ui_tx, _ui_rx) = mpsc::channel(); let reopen: ReopenFn = Box::new(|_, _| Err(OxaError::new("invalid", "no reopen in this test"))); - let wake = cmd_tx.clone(); + let cmd_tx = Arc::new(cmd_tx); + let wake = Arc::downgrade(&cmd_tx); let worker = std::thread::spawn(move || { worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, WorkerStop::new(), wake) }); diff --git a/oxa/oxa-interactive/tests/v020_prefill_paste.rs b/oxa/oxa-interactive/tests/v020_prefill_paste.rs index efb78df68..d03f9ebe1 100644 --- a/oxa/oxa-interactive/tests/v020_prefill_paste.rs +++ b/oxa/oxa-interactive/tests/v020_prefill_paste.rs @@ -83,7 +83,8 @@ fn worker_prefills_the_current_draft_only() { let (ui_tx, _ui_rx) = mpsc::channel(); let reopen: ReopenFn = Box::new(|_, _| Err(OxaError::new("invalid", "no reopen in this test"))); let worker_stop = stop.clone(); - let wake = cmd_tx.clone(); + let cmd_tx = Arc::new(cmd_tx); + let wake = Arc::downgrade(&cmd_tx); let worker = std::thread::spawn(move || { worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop, wake) }); From 62cf43c3978b952d8e27f6f7c50984a6b0b35134 Mon Sep 17 00:00:00 2001 From: codex-integ Date: Tue, 17 Nov 2026 19:14:54 +0100 Subject: [PATCH 08/10] fix(interactive): align worker entry point with weak wake ownership --- oxa/oxa-interactive/src/app.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/oxa/oxa-interactive/src/app.rs b/oxa/oxa-interactive/src/app.rs index c97d23cc3..343ef751b 100644 --- a/oxa/oxa-interactive/src/app.rs +++ b/oxa/oxa-interactive/src/app.rs @@ -508,7 +508,7 @@ pub fn worker_loop_with( out: Sender, ui: Sender, stop: WorkerStop, - wake: Sender, + wake: Weak>, ) -> Option { let mut ui_proxy = UiProxy::new(ui.clone()); let mut last = StatusModel::default(); From fec4cf8cec7be3d546c68e9c99dbfd5e8306a29a Mon Sep 17 00:00:00 2001 From: codex-integ Date: Tue, 17 Nov 2026 19:30:16 +0100 Subject: [PATCH 09/10] test(interactive): cover unconsumed start and settled Escape windows --- .../tests/d1_main_loop_and_regular_mode.rs | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs index 9cf590bd1..6fd4fbf0d 100644 --- a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs +++ b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs @@ -561,6 +561,75 @@ fn escape_aborts_and_restores_queue() { ); } +#[test] +fn input_before_agent_start_is_consumed_steers_the_claimed_run() { + let env = TestEnv::new(); + let (release_tx, release_rx) = mpsc::channel(); + let (entered_tx, entered_rx) = mpsc::channel(); + let mut s = session_deps( + &env, + Arc::new(HeldEngine::new( + vec![oxa_fake::ScriptTurn::text("done")], + release_rx, + entered_tx, + )), + Arc::new(MemStore::new()), + Open::Ephemeral, + ); + let handle = s.handle(); + let run = std::thread::spawn(move || { + s.prompt( + "first".into(), + Vec::new(), + &mut oxa_proto::VecSink(Vec::new()), + &mut oxa_proto::HeadlessUi::default(), + ) + }); + entered_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("foreground request entered"); + assert!(handle.is_busy()); + // The core has started, while the front end has not consumed AgentStart yet. + let d = drive_handle( + handle.clone(), + &env, + vec![vec![ch('x'), key("enter")], vec![key("ctrl+d")]], + Vec::new(), + ); + let queued = handle.queued(); + handle.abort(); + drop(release_tx); + let _ = run.join().expect("run thread"); + assert_eq!(queued.0, vec!["x".to_string()]); + assert!( + matches!(d.cmds.as_slice(), [SessionCmd::QueuedInput(owner)] if owner.same_instance(&handle)), + "a claimed foreground request must not be mistaken for an idle prompt" + ); +} + +#[test] +fn escape_after_claim_release_keeps_input_out_of_the_stale_run_queue() { + let env = TestEnv::new(); + let s = session(&env); + assert!(!s.handle().is_busy()); + let d = drive( + &s, + &env, + vec![ + vec![key("escape")], + vec![ch('x'), key("enter")], + vec![key("ctrl+d")], + ], + vec![WorkerMsg::Event(AgentEvent::AgentStart)], + ); + assert_eq!(s.handle().queued(), (Vec::new(), Vec::new())); + assert!( + matches!(d.cmds.as_slice(), [SessionCmd::RecoveryPrompt { handle, text, .. }] + if handle.same_instance(&s.handle()) && text == "x"), + "Escape must retain the explicit recovery boundary until the next input" + ); +} + /// #906: Enter while an aborted run is still unwinding starts a new run. The aborted run takes /// no further tool batch, so a steering message would sit in a queue nothing drains (the flaky /// `oxa-cli::i699_interrupt::tool_pty_ctrl_c_stops_tool_without_exiting` caught it: the reply to From 4177d9abe45b192236b794c44d18ffe5cf536e86 Mon Sep 17 00:00:00 2001 From: codex-integ Date: Tue, 17 Nov 2026 19:37:36 +0100 Subject: [PATCH 10/10] fix(interactive): preserve active and canceled input boundaries --- oxa/oxa-core/src/agent_loop.rs | 11 +++ oxa/oxa-core/src/queue.rs | 6 ++ oxa/oxa-core/src/session.rs | 17 ++++ oxa/oxa-interactive/src/app.rs | 52 +++++++++--- oxa/oxa-interactive/src/driver.rs | 21 ++--- .../tests/d1_main_loop_and_regular_mode.rs | 79 +++++++++++++++++-- 6 files changed, 160 insertions(+), 26 deletions(-) diff --git a/oxa/oxa-core/src/agent_loop.rs b/oxa/oxa-core/src/agent_loop.rs index 5c13341c9..e6a031f28 100644 --- a/oxa/oxa-core/src/agent_loop.rs +++ b/oxa/oxa-core/src/agent_loop.rs @@ -69,6 +69,10 @@ pub fn run_loop( ) -> Result { crate::goal::ensure_begin(st); crate::goal::checkpoint(st, false, sink)?; + st.shared + .gate + .running + .store(true, std::sync::atomic::Ordering::SeqCst); sink.emit(&AgentEvent::AgentStart); observe_hooks(st, HookPoint::AgentStart, &Value::Null, sink, ui); let mut run_msgs: Vec = Vec::new(); @@ -813,6 +817,13 @@ pub(crate) fn persist( sink: &mut dyn EventSink, ) -> Result { let entry = append_entry(st, body)?; + if matches!(&entry.body, EntryBody::Shown { why, .. } if [shown_why::ABORTED, shown_why::FAILED, shown_why::CUT].contains(why)) + { + st.shared + .gate + .running + .store(false, std::sync::atomic::Ordering::SeqCst); + } sink.emit(&AgentEvent::EntryAppended { entry: entry.clone() }); Ok(entry) } diff --git a/oxa/oxa-core/src/queue.rs b/oxa/oxa-core/src/queue.rs index 12c894d99..53f7fc987 100644 --- a/oxa/oxa-core/src/queue.rs +++ b/oxa/oxa-core/src/queue.rs @@ -102,6 +102,8 @@ impl WrapUpReason { pub struct Gate { /// Coalesce frontend inbox wakes while a model run drains follow-ups internally. pub inbox_wake_pending: std::sync::atomic::AtomicBool, + /// Foreground work, excluding settlement after a dropped reply. + pub running: std::sync::atomic::AtomicBool, /// Coalesce worker wakes for ordinary editor queues, independently of bound inbox wakes. pub queued_wake_pending: std::sync::atomic::AtomicBool, pub progress: Mutex>>, @@ -525,6 +527,10 @@ impl Handle { pub fn abort_retry(&self) { self.shared.cancel_retry.cancel(); } + /// A foreground operation still accepts input, even before its start event is consumed. + pub fn is_running(&self) -> bool { + self.shared.gate.running.load(Ordering::SeqCst) + } pub fn is_busy(&self) -> bool { self.shared.busy.load(Ordering::SeqCst) } diff --git a/oxa/oxa-core/src/session.rs b/oxa/oxa-core/src/session.rs index 7fc5c873b..ea3fa0d75 100644 --- a/oxa/oxa-core/src/session.rs +++ b/oxa/oxa-core/src/session.rs @@ -165,6 +165,7 @@ struct BusyGuard(Arc); impl Drop for BusyGuard { fn drop(&mut self) { + self.0.gate.running.store(false, Ordering::SeqCst); self.0.busy.store(false, Ordering::SeqCst); } } @@ -807,6 +808,17 @@ impl Session { /// only while its wire is empty. Front ends call it from their idle tick before the first /// prompt; it claims the session like a run, so a busy session is skipped (`false`). pub fn preload_prefix(&mut self, sink: &mut dyn EventSink, ui: &mut dyn Ui) -> bool { + self.preload_prefix_if(sink, ui, || true) + } + + /// Recheck front-end admission after claiming background work and before any engine call. + /// The caller arms cancellation before this call, then checks its existing command queue. + pub fn preload_prefix_if( + &mut self, + sink: &mut dyn EventSink, + ui: &mut dyn Ui, + should_start: impl FnOnce() -> bool, + ) -> bool { if self.preloaded { return false; } @@ -821,6 +833,10 @@ impl Session { let Ok(_guard) = self.begin() else { return false; }; + if !should_start() { + self.preloaded = false; + return false; + } // A turn an extension triggers while the preload request runs waits for the next idle // tick (`serve_host`) instead of being queued into a run that never comes. crate::host::holding_triggers(|| crate::compaction::boot_preload(&mut self.st, sink, ui)) @@ -950,6 +966,7 @@ impl Session { /// New prompt/extension work gets fresh run-local flags; prefill-only claims do not. fn begin_run(&mut self) -> Result { let guard = self.begin()?; + self.st.shared.gate.running.store(true, Ordering::SeqCst); crate::progress::notify(&self.st, crate::Progress::RunStart); self.st.stats.done_failed = false; self.st.stats.output_truncated = false; diff --git a/oxa/oxa-interactive/src/app.rs b/oxa/oxa-interactive/src/app.rs index 343ef751b..2c06be174 100644 --- a/oxa/oxa-interactive/src/app.rs +++ b/oxa/oxa-interactive/src/app.rs @@ -584,18 +584,25 @@ pub fn worker_loop_with( if preload_due { preload_due = false; if let Some(s) = session.as_mut() { - run_boot_preload(s, &out, &mut ui_proxy, &stop); + run_boot_preload(s, &out, &mut ui_proxy, &stop, &cmds, &mut backlog); } } - match cmds.recv_timeout(WORKER_IDLE_TICK) { - Ok(cmd) => cmd, - Err(mpsc::RecvTimeoutError::Timeout) => { - if let Some(s) = session.as_mut() { - idle_tick(s, &out, &mut ui_proxy, &mut last, &stop); + if stop.is_stopped() || backlog.iter().any(|c| matches!(c, SessionCmd::Shutdown)) { + break; + } + if let Some(cmd) = backlog.pop_front() { + cmd + } else { + match cmds.recv_timeout(WORKER_IDLE_TICK) { + Ok(cmd) => cmd, + Err(mpsc::RecvTimeoutError::Timeout) => { + if let Some(s) = session.as_mut() { + idle_tick(s, &out, &mut ui_proxy, &mut last, &stop, &cmds, &mut backlog); + } + continue; } - continue; + Err(mpsc::RecvTimeoutError::Disconnected) => break, } - Err(mpsc::RecvTimeoutError::Disconnected) => break, } } }; @@ -612,7 +619,7 @@ pub fn worker_loop_with( SessionCmd::Wake => { pending.store(false, Ordering::SeqCst); if let Some(s) = session.as_mut() { - idle_tick(s, &out, &mut ui_proxy, &mut last, &stop); + idle_tick(s, &out, &mut ui_proxy, &mut last, &stop, &cmds, &mut backlog); } } SessionCmd::Reopen(how) => { @@ -760,9 +767,25 @@ pub fn worker_loop_with( /// invisible: its progress events are not shown (they would set the foreground activity and /// make the UI treat the next prompt as steering), and the UI cancels it on input /// (`WorkerStop::is_preloading`). -fn run_boot_preload(s: &mut Session, out: &Sender, ui: &mut UiProxy, stop: &WorkerStop) { +fn run_boot_preload( + s: &mut Session, + out: &Sender, + ui: &mut UiProxy, + stop: &WorkerStop, + cmds: &Receiver, + backlog: &mut VecDeque, +) { stop.set_preloading(true); - s.preload_prefix(&mut PreloadSink(ChanSink(out.clone())), ui); + s.preload_prefix_if(&mut PreloadSink(ChanSink(out.clone())), ui, || { + loop { + match cmds.try_recv() { + Ok(cmd) => backlog.push_back(cmd), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => return false, + } + } + backlog.is_empty() && !stop.is_stopped() + }); stop.set_preloading(false); } @@ -775,10 +798,15 @@ fn idle_tick( ui: &mut UiProxy, last: &mut StatusModel, stop: &WorkerStop, + cmds: &Receiver, + backlog: &mut VecDeque, ) { // O-386: the preload is due before the worker's first wait (see `worker_loop_with`); this // call is the retry for a session whose hook set had requests pending then. - run_boot_preload(s, out, ui, stop); + run_boot_preload(s, out, ui, stop, cmds, backlog); + if !backlog.is_empty() || stop.is_stopped() { + return; + } let mut sink = CountingSink { inner: ChanSink(out.clone()), count: 0, diff --git a/oxa/oxa-interactive/src/driver.rs b/oxa/oxa-interactive/src/driver.rs index 03d717686..4df9dd1d9 100644 --- a/oxa/oxa-interactive/src/driver.rs +++ b/oxa/oxa-interactive/src/driver.rs @@ -686,17 +686,13 @@ impl<'a> Loop<'a> { } } - /// A run is active: the worker reported a non-idle activity. The boot preload (O-152) - /// claims the session too, but is not a run: input is a prompt. V020-OPTIMIZE #13: so is a - /// draft prefill. Both keep the activity idle (their progress events are dropped), so the - /// activity alone answers the question. - /// - /// The session's claim is not the signal: it is held past the end of the run, for the - /// settle work (hooks, the front end's status file). A reply the core dropped (an abort, a - /// failure, a cut) ends the run and clears the activity at once, so a prompt typed after - /// the dropped reply is a prompt and not steering on a run that has already ended (#699). + /// Foreground activity, including the interval before its start event reaches the UI. + /// Background prefix/draft claims are excluded. The shared foreground signal ends when + /// a failed, aborted or cut reply is persisted, so settlement's remaining busy claim does + /// not turn later input into steering for a finished turn. fn running(&self) -> bool { self.vm.status.activity != Activity::Idle + || (self.handle.is_running() && !self.worker.is_preloading() && !self.worker.is_drafting()) } /// Whether Enter / Alt+Enter queue the text (steering / follow-up) rather than start a run: @@ -730,6 +726,12 @@ impl<'a> Loop<'a> { if self.cmds.send(cmd).is_err() { self.quit = Some(1); } + // A background claim may have reset its tokens between the first cancellation + // and publication. Once the command is visible, cancel any still-armed background + // work again; this never cancels the foreground command itself. + if self.worker.is_preloading() || self.worker.is_drafting() { + self.handle.cancel_background(); + } } fn push_notice(&mut self, level: Level, text: String) { @@ -1438,6 +1440,7 @@ impl<'a> Loop<'a> { return; } if self.running() { + self.abort_requested = true; self.handle.abort(); } if matches!(self.vm.status.activity, Activity::Retrying { .. }) { diff --git a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs index 6fd4fbf0d..00d63247d 100644 --- a/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs +++ b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs @@ -547,17 +547,17 @@ fn escape_aborts_and_restores_queue() { vec![WorkerMsg::Event(AgentEvent::AgentStart)], ); assert_eq!(d.code, 0); - // Escape took the queued message back into the editor; Enter sent it again as a steer. + // Escape restores queued input; explicit resubmission is a new recovery prompt. let (steering, follow_up) = s.handle().queued(); assert_eq!( steering, - vec!["q1".to_string()], - "the queued message is back in the editor and resubmitted" + Vec::::new(), + "restored input must not return to the canceled run queue" ); assert!(follow_up.is_empty()); assert!( - matches!(d.cmds.as_slice(), [SessionCmd::QueuedInput(handle)] if handle.same_instance(&s.handle())), - "resubmitting restored input retains one consumer on its original handle" + matches!(d.cmds.as_slice(), [SessionCmd::RecoveryPrompt { handle, text, .. }] if handle.same_instance(&s.handle()) && text == "q1"), + "restored input retains its original handle and explicit recovery boundary" ); } @@ -607,6 +607,75 @@ fn input_before_agent_start_is_consumed_steers_the_claimed_run() { ); } +#[test] +fn dropped_failure_does_not_reactivate_the_busy_settlement_claim() { + struct HeldFailure { + entered: Sender<()>, + release: Receiver<()>, + } + impl oxa_proto::EventSink for HeldFailure { + fn emit(&mut self, event: &AgentEvent) { + if matches!(event, AgentEvent::EntryAppended { entry } + if matches!(&entry.body, EntryBody::Shown { why, .. } if *why == oxa_proto::shown_why::FAILED)) + { + let _ = self.entered.send(()); + let _ = self.release.recv(); + } + } + } + let env = TestEnv::new(); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let mut s = session_deps( + &env, + Arc::new(ScriptedEngine::new(vec![oxa_fake::ScriptTurn::fault( + oxa_fake::Fault::Http { + status: 400, + body: "synthetic failure".into(), + }, + )])), + Arc::new(MemStore::new()), + Open::Ephemeral, + ); + let handle = s.handle(); + let run = std::thread::spawn(move || { + s.prompt( + "first".into(), + Vec::new(), + &mut HeldFailure { + entered: entered_tx, + release: release_rx, + }, + &mut oxa_proto::HeadlessUi::default(), + ) + }); + entered_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("failed reply persisted"); + assert!( + handle.is_busy(), + "hold the original operation through its terminal event" + ); + assert!( + !handle.is_aborting(), + "this is a failure, not the cancellation-token guard" + ); + let d = drive_handle( + handle.clone(), + &env, + vec![vec![ch('x'), key("enter")], vec![key("ctrl+d")]], + Vec::new(), + ); + let queued = handle.queued(); + drop(release_tx); + let _ = run.join().expect("run thread"); + assert_eq!(queued, (Vec::new(), Vec::new())); + assert!( + matches!(d.cmds.as_slice(), [SessionCmd::Prompt { text, .. }] if text == "x"), + "the busy settlement claim must not take new input as steering" + ); +} + #[test] fn escape_after_claim_release_keeps_input_out_of_the_stale_run_queue() { let env = TestEnv::new();