Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions oxa/oxa-core/src/agent_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ pub fn run_loop(
) -> Result<RunEnd, OxaError> {
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<EventMessage> = Vec::new();
Expand Down Expand Up @@ -813,6 +817,13 @@ pub(crate) fn persist(
sink: &mut dyn EventSink,
) -> Result<Entry, OxaError> {
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);
Comment on lines +820 to +825

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the running signal across recoverable reply cuts

When a stream breaks after producing output and automatic replay is enabled, run_inner persists Shown { why: CUT } and continues the same run with another request. This clears gate.running, but neither the replay branch nor subsequent turns restore it; only a new run_loop invocation does. If the UI consumes the cut entry and enters term.poll before consuming the replay's MessageStart, both its activity and the shared signal report idle even while the replay executes. Enter consequently submits a separate prompt instead of steering, and Ctrl+C clears the editor instead of cancelling the request. Keep the foreground signal active for recoverable cuts, or restore it before continuing the request.

Useful? React with 👍 / 👎.

}
sink.emit(&AgentEvent::EntryAppended { entry: entry.clone() });
Ok(entry)
}
Expand Down
40 changes: 40 additions & 0 deletions oxa/oxa-core/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -1294,6 +1298,7 @@ fn notice(sink: &mut dyn EventSink, level: Level, text: impl Into<String>) {
#[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;
Expand Down Expand Up @@ -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]
Expand Down
119 changes: 119 additions & 0 deletions oxa/oxa-core/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<Arc<dyn crate::ProgressObserver>>>,
Expand All @@ -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<Option<Arc<dyn Fn() + Send + Sync>>>);

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<dyn Fn() + Send + Sync>) {
*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.
Expand Down Expand Up @@ -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<WrapUpReason> {
Expand All @@ -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<dyn Fn() + Send + Sync>) {
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 {
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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);
Expand Down Expand Up @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions oxa/oxa-core/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ struct BusyGuard(Arc<Shared>);

impl Drop for BusyGuard {
fn drop(&mut self) {
self.0.gate.running.store(false, Ordering::SeqCst);
self.0.busy.store(false, Ordering::SeqCst);
}
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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))
Expand Down Expand Up @@ -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<BusyGuard, OxaError> {
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;
Expand Down
Loading
Loading