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/host.rs b/oxa/oxa-core/src/host.rs index d5d342e6a..4d3f0451c 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; @@ -1404,6 +1409,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 c9d8d4358..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>>, @@ -126,6 +128,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. @@ -412,6 +447,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 { @@ -435,6 +473,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 { @@ -474,9 +527,21 @@ 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) } + /// 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 @@ -499,6 +564,7 @@ impl Handle { #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::AtomicUsize; fn handle(steer: QueueMode, follow: QueueMode) -> Handle { Handle { @@ -525,6 +591,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); @@ -617,6 +718,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-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 c8224e0ff..2c06be174 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,9 +183,12 @@ pub fn run_session( ); let stop = WorkerStop::new(); let worker_stop = stop.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)); + .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), @@ -194,7 +198,7 @@ pub fn run_session( term, opts, handle, - cmd_tx.clone(), + cmd_tx.as_ref().clone(), &msg_rx, &ui_rx, vm, @@ -352,7 +356,29 @@ 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: &Weak>, pending: &Arc) { + let tx = wake.clone(); + let pending = pending.clone(); + handle.set_attention_waker(Arc::new(move || { + if !pending.swap(true, Ordering::SeqCst) { + if let Some(tx) = tx.upgrade() { + 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. @@ -464,14 +490,17 @@ pub fn worker_loop( cmds: Receiver, out: Sender, ui: Sender, + wake: Weak>, ) -> 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 +/// 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, mut reopen: ReopenFn, @@ -479,10 +508,14 @@ pub fn worker_loop_with( out: Sender, ui: Sender, stop: WorkerStop, + wake: Weak>, ) -> 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 mut memory_status = session.inner().engine.local_memory_status(&session.state().model); let _ = out.send(WorkerMsg::Session(session_info(&session))); let mut session = Some(session); @@ -490,6 +523,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). @@ -540,16 +576,35 @@ 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, &cmds, &mut backlog); } - continue; } - Err(mpsc::RecvTimeoutError::Disconnected) => break, - }, + 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; + } + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + } }; // A command taken in the same instant as the stop does not start. if stop.is_stopped() { @@ -557,6 +612,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, &cmds, &mut backlog); + } + } 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. @@ -585,6 +650,8 @@ pub fn worker_loop_with( match reopen(how, carry) { Ok(new) => { stop.enter(new.handle()); + install_wake(&new.handle(), &wake, &pending); + preload_due = true; session = Some(new); opened = true; } @@ -600,6 +667,8 @@ pub fn worker_loop_with( match again { Ok(s) => { stop.enter(s.handle()); + install_wake(&s.handle(), &wake, &pending); + preload_due = true; session = Some(s); } Err(e) => { @@ -692,6 +761,34 @@ 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, + cmds: &Receiver, + backlog: &mut VecDeque, +) { + stop.set_preloading(true); + 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); +} + /// 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. @@ -701,15 +798,15 @@ fn idle_tick( ui: &mut UiProxy, last: &mut StatusModel, stop: &WorkerStop, + cmds: &Receiver, + backlog: &mut VecDeque, ) { - // 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, cmds, backlog); + if !backlog.is_empty() || stop.is_stopped() { + return; + } let mut sink = CountingSink { inner: ChanSink(out.clone()), count: 0, @@ -1078,6 +1175,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 => { @@ -1616,6 +1721,7 @@ fn execute( SessionCmd::Reopen(_) | SessionCmd::Snapshot | SessionCmd::Shutdown + | SessionCmd::Wake | SessionCmd::PrefillDraft { .. } => (Ok(()), false), } } diff --git a/oxa/oxa-interactive/src/driver.rs b/oxa/oxa-interactive/src/driver.rs index 3a9aa3a2f..5348307e6 100644 --- a/oxa/oxa-interactive/src/driver.rs +++ b/oxa/oxa-interactive/src/driver.rs @@ -688,12 +688,24 @@ 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. + /// 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_busy() && !self.worker.is_preloading() && !self.worker.is_drafting()) + || (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: + /// 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 { @@ -716,6 +728,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) { @@ -744,6 +762,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 { @@ -1445,7 +1467,7 @@ impl<'a> Loop<'a> { } self.editor.set_text(""); self.editor.add_history(&text); - if self.running() && !self.abort_requested { + if self.accepts_steering() { self.handle.follow_up(text); self.wake_queued(); self.sync_queue(); @@ -1718,7 +1740,7 @@ impl<'a> Loop<'a> { // Explicit input after a cancel key (Ctrl+C or Escape) is a new prompt, not steering // for the canceled run. The worker channel runs it after that operation releases the // session. Ordinary queued input still uses the existing unsuccessful-outcome guard. - 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/src/model.rs b/oxa/oxa-interactive/src/model.rs index df38d03cc..35ac4f2db 100644 --- a/oxa/oxa-interactive/src/model.rs +++ b/oxa/oxa-interactive/src/model.rs @@ -455,6 +455,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/d1_main_loop_and_regular_mode.rs b/oxa/oxa-interactive/tests/d1_main_loop_and_regular_mode.rs index 013f97ee1..2f07909ee 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,197 @@ 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 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(); + 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 +/// 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![WorkerMsg::Event(AgentEvent::AgentStart)], + ); + 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() { diff --git a/oxa/oxa-interactive/tests/eint_interactive.rs b/oxa/oxa-interactive/tests/eint_interactive.rs index 2b4706562..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,8 +201,10 @@ 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 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); + let last = worker_loop_with(session, reopen, cmd_rx, msg_tx, ui_tx, worker_stop, wake); let _ = done_tx.send(last); }); Worker { @@ -214,6 +216,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); @@ -288,6 +320,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..1b42db8fc 100644 --- a/oxa/oxa-interactive/tests/h_panic.rs +++ b/oxa/oxa-interactive/tests/h_panic.rs @@ -123,8 +123,10 @@ 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 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()) + 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..d03f9ebe1 100644 --- a/oxa/oxa-interactive/tests/v020_prefill_paste.rs +++ b/oxa/oxa-interactive/tests/v020_prefill_paste.rs @@ -83,8 +83,11 @@ 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 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) + }); 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)] {