diff --git a/crates/acp/src/client/lifecycle_tests.rs b/crates/acp/src/client/lifecycle_tests.rs index e3d7e373..8b5570b5 100644 --- a/crates/acp/src/client/lifecycle_tests.rs +++ b/crates/acp/src/client/lifecycle_tests.rs @@ -8,6 +8,8 @@ from pathlib import Path mode = sys.argv[1] def update(text): return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':text}}}} +def activity(state): + return {'jsonrpc':'2.0','method':'session/update','params':{'sessionId':'s1','update':{'sessionUpdate':'session_info_update','_meta':{'codex':{'threadStatus':{'type':state}}}}}} pause_next_read = False prompts = [] while True: @@ -41,6 +43,14 @@ while True: assert isinstance(replies, list) and len(replies) == 2, replies assert {reply['id']: reply['error']['code'] for reply in replies} == {'first':-32601,'second':-32601}, replies result = {'stopReason':'end_turn'} + elif method == 'session/prompt' and mode == 'autonomous': + print(json.dumps(activity('active')), flush=True) + print(json.dumps(activity('idle')), flush=True) + print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':{'stopReason':'end_turn'}}),flush=True) + print(json.dumps(activity('active')), flush=True) + print(json.dumps(update('continuation')), flush=True) + print(json.dumps(activity('idle')), flush=True) + continue elif method == 'session/prompt' and mode == 'bench-text': assert request['params']['prompt'] == [{'type':'text','text':'latency fixture'}] result = {'stopReason':'end_turn'} @@ -129,6 +139,66 @@ fn subprocess_batches_keep_update_order_and_group_replies() { }); } +#[test] +fn subprocess_activity_arrives_even_after_the_prompt_response() { + use nocterm_ai::model::session::{SessionActivity, StopReason}; + + let exercise = async { + let directory = tempfile::tempdir().unwrap(); + let connection = connection("autonomous", directory.path()).await; + let session = connection + .commands + .new_session(SessionOpen { + working_directory: directory.path().to_path_buf(), + endpoints: Vec::new(), + }) + .await + .unwrap(); + let result = connection + .commands + .prompt(PromptRequest { + session: session.session.clone(), + content: vec![nocterm_ai::model::content::Content::text("work")], + }) + .await + .unwrap(); + assert_eq!(result.stop_reason, StopReason::EndTurn); + for expected in [ + Some(SessionActivity::Active), + Some(SessionActivity::Idle), + Some(SessionActivity::Active), + None, + Some(SessionActivity::Idle), + ] { + let AgentEvent::Session(event) = connection.events.recv().await.unwrap() else { + panic!("expected an ACP session update"); + }; + assert_eq!(event.session, session.session); + match (expected, event.update) { + (Some(activity), SessionUpdate::SessionInfoUpdate(info)) => { + assert_eq!(info.activity, Some(activity)) + } + (None, SessionUpdate::AgentMessageChunk(content)) => assert_eq!( + content, + nocterm_ai::model::content::Content::text("continuation") + ), + _ => panic!("unexpected update"), + } + } + connection.commands.shutdown_gracefully().await.unwrap(); + }; + futures::executor::block_on(async { + assert!(matches!( + select( + Box::pin(exercise), + Box::pin(async_io::Timer::after(Duration::from_secs(5))) + ) + .await, + Either::Left(_) + )); + }); +} + #[test] fn sends_a_full_composer_image_budget_to_the_agent() { use nocterm_ai::model::session::StopReason; diff --git a/crates/acp/src/mapping/session.rs b/crates/acp/src/mapping/session.rs index 6270e226..e885ab4f 100644 --- a/crates/acp/src/mapping/session.rs +++ b/crates/acp/src/mapping/session.rs @@ -10,7 +10,7 @@ use nocterm_ai::model::{ diagnostic::ModelError, ids::{ModeId, SessionId}, plan::{Plan, PlanEntry, PlanPriority, PlanStatus}, - session::{SessionInfo, SessionNotice, SessionUpdate}, + session::{SessionActivity, SessionInfo, SessionNotice, SessionUpdate}, usage::{ContextUsage, Cost}, }; @@ -55,6 +55,21 @@ fn title(value: MaybeUndefined) -> Change { _ => Change::Keep, } } +// codex-acp reports autonomous app-server turns through this session-info extension. +// Other provider metadata remains inert; unknown or malformed statuses do not change liveness. +fn session_activity(meta: Option<&wire::Meta>) -> Option { + match meta? + .get("codex")? + .get("threadStatus")? + .get("type")? + .as_str()? + { + "active" => Some(SessionActivity::Active), + "idle" => Some(SessionActivity::Idle), + _ => None, + } +} + fn update(value: wire::SessionUpdate) -> Result { Ok(match value { wire::SessionUpdate::UserMessageChunk(chunk) => { @@ -85,6 +100,7 @@ fn update(value: wire::SessionUpdate) -> Result { wire::SessionUpdate::SessionInfoUpdate(value) => { SessionUpdate::SessionInfoUpdate(SessionInfo { title: title(value.title), + activity: session_activity(value.meta.as_ref()), meta: extensions(value.meta), }) } diff --git a/crates/acp/src/mapping/session_tests.rs b/crates/acp/src/mapping/session_tests.rs index 559559b6..a6a5f507 100644 --- a/crates/acp/src/mapping/session_tests.rs +++ b/crates/acp/src/mapping/session_tests.rs @@ -236,3 +236,30 @@ fn agent_introductions_keep_images_and_sign_in_methods() { assert_eq!(setup.args, ["login"]); assert_eq!(methods[1].label, "Setup"); } + +#[test] +fn codex_thread_status_is_a_typed_activity_without_losing_the_title() { + for (status, expected) in [ + ( + json!({"type":"active","activeFlags":[]}), + Some(SessionActivity::Active), + ), + (json!({"type":"idle"}), Some(SessionActivity::Idle)), + (json!({"type":"notLoaded"}), None), + (json!({"type":"future"}), None), + (json!("active"), None), + (json!(null), None), + ] { + let notice = notice(update(json!({"update":{ + "sessionUpdate":"session_info_update", + "title":"Still my chat", + "_meta":{"codex":{"threadStatus":status}} + }}))) + .unwrap(); + let SessionUpdate::SessionInfoUpdate(info) = notice.update else { + panic!("session info expected"); + }; + assert_eq!(info.title, Change::Set("Still my chat".into())); + assert_eq!(info.activity, expected); + } +} diff --git a/crates/agent-chat/src/thread/client.rs b/crates/agent-chat/src/thread/client.rs index 6db1bf1b..e4658aae 100644 --- a/crates/agent-chat/src/thread/client.rs +++ b/crates/agent-chat/src/thread/client.rs @@ -331,6 +331,7 @@ impl AgentThread { self.state.set_pending_history(false, self.deps.timestamp()); self.persist(cx); } + self.resume_observed_turn(); self.dispatch_next(cx); cx.notify(); } @@ -349,13 +350,6 @@ impl AgentThread { } } - pub(super) fn clear_settled_disabled_document(&mut self, cx: &gpui::App) { - if !self.deps.enabled(cx) && self.state.release_disabled() { - self.config.disabled(); - self.composer.reset_after_disable(); - } - } - /// The chat's connection stopped. With AI turned off, the chat also /// forgets its transcript and what was attached. pub fn connection_stopped(&mut self, message: &str, cx: &mut Context) { @@ -370,14 +364,22 @@ impl AgentThread { self.config .keep_control(self.session.ticket(), notification); } + if self.session().as_ref() != Some(¬ification.session) { + return; + } if let SessionUpdate::Turn(activity) = ¬ification.update { - if self.session().as_ref() == Some(¬ification.session) { - self.external_turn(activity, cx); - } + self.external_turn(activity, cx); return; } - if self.session().as_ref() != Some(¬ification.session) - || !self.session.accepts_updates() + if let SessionUpdate::SessionInfoUpdate(info) = ¬ification.update + && let Some(activity) = info.activity + { + self.observe_session_activity(activity, cx); + if matches!(info.title, nocterm_ai::model::controls::Change::Keep) { + return; + } + } + if !self.session.accepts_updates() || matches!(notification.update, SessionUpdate::UserMessageChunk(_)) { return; diff --git a/crates/agent-chat/src/thread/document/tests.rs b/crates/agent-chat/src/thread/document/tests.rs index bcfaca68..b5b15353 100644 --- a/crates/agent-chat/src/thread/document/tests.rs +++ b/crates/agent-chat/src/thread/document/tests.rs @@ -55,6 +55,7 @@ fn update(value: serde_json::Value) -> SessionUpdate { }), "session_info_update" => SessionUpdate::SessionInfoUpdate(SessionInfo { title: Change::Set(value["title"].as_str().unwrap().into()), + activity: None, meta: None, }), "usage_update" => SessionUpdate::UsageUpdate(ContextUsage::new( diff --git a/crates/agent-chat/src/thread/queue.rs b/crates/agent-chat/src/thread/queue.rs index 6069351a..2706eab8 100644 --- a/crates/agent-chat/src/thread/queue.rs +++ b/crates/agent-chat/src/thread/queue.rs @@ -8,8 +8,8 @@ use super::{ execution::WaitSubject, }; use gpui::{App, Context, EntityId, Task}; -use nocterm_ai::history::{SavedAttachment, SavedPrompt}; -use nocterm_ai::model::content::Content; +use nocterm_ai::history::SavedAttachment; +use nocterm_ai::model::{content::Content, session::SessionActivity}; use nocterm_ai::{BridgeCall, TerminalCall, ToolFailure}; use nocterm_workspace_ports::{ExpectedSession, TerminalEntry, TerminalStatus}; @@ -20,48 +20,8 @@ use super::{AgentThread, Attachment}; mod submit_error; pub(super) use submit_error::SubmitError; -#[derive(Clone)] -pub struct QueuedPrompt { - saved: Arc, - attachments: Vec, - encoded_len: usize, - memory_len: usize, -} - -impl QueuedPrompt { - #[cfg(any(test, feature = "test-support"))] - pub fn new(saved: SavedPrompt, attachments: Vec) -> Self { - Self::prepared(saved, attachments, None) - } - pub fn prepared( - saved: SavedPrompt, - attachments: Vec, - encoded_len: Option, - ) -> Self { - let encoded_len = encoded_len - .unwrap_or_else(|| nocterm_ai::history::prompt_size(&saved).unwrap_or(usize::MAX)); - let memory_len = nocterm_ai::history::prompt_memory(&saved).unwrap_or(usize::MAX); - Self { - memory_len, - saved: Arc::new(saved), - attachments, - encoded_len, - } - } - pub fn saved(&self) -> &Arc { - &self.saved - } - /// What the prompt was written about, captured when it was queued. - pub fn attachments(&self) -> &[Attachment] { - &self.attachments - } - pub fn encoded_len(&self) -> usize { - self.encoded_len - } - pub fn memory_len(&self) -> usize { - self.memory_len - } -} +mod prompt; +pub use prompt::QueuedPrompt; impl AgentThread { pub(super) fn start_execution_watch(&mut self, cx: &mut Context) { @@ -681,8 +641,8 @@ impl AgentThread { } self.state.validate_candidate( &metadata, - queue.iter().map(|prompt| prompt.encoded_len), - queue.iter().map(|prompt| prompt.memory_len), + queue.iter().map(QueuedPrompt::encoded_len), + queue.iter().map(QueuedPrompt::memory_len), )?; self.composer.commit_prompt_change(candidate); self.accept_document_inputs(cx, false); @@ -719,15 +679,46 @@ impl AgentThread { if !self.session.finish_external_turn() { return; } - self.finalize_tool_displays(); - self.notice.present("Ready".into()); - self.persist(cx); - self.dispatch_next(cx); + self.settle_external_turn(cx); } } cx.notify(); } + /// Provider status is an observation, not a new user prompt or a tool grant. + pub(super) fn observe_session_activity( + &mut self, + activity: SessionActivity, + cx: &mut Context, + ) { + if !self.session.observe_activity(activity) { + return; + } + if self.session.generating() { + self.notice.present("Working…".into()); + } else { + self.settle_external_turn(cx); + } + cx.notify(); + } + + pub(super) fn resume_observed_turn(&mut self) { + if self.session.resume_observed_turn() { + self.notice.present("Working…".into()); + } + } + + fn settle_external_turn(&mut self, cx: &mut Context) { + self.finalize_tool_displays(); + self.notice.present(if self.session.stopped() { + "Stopped".into() + } else { + "Ready".into() + }); + self.persist(cx); + self.dispatch_next(cx); + } + pub fn dispatch_next(&mut self, cx: &mut Context) { if !self.queue_dispatchable() || self.session.generating() @@ -751,8 +742,9 @@ impl AgentThread { return; }; // Context is fixed for this turn, including terminal tool access. - self.tools.capture_scope(prompt.attachments); - let saved = Arc::unwrap_or_clone(prompt.saved); + let (attachments, saved) = prompt.into_parts(); + self.tools.capture_scope(attachments); + let saved = Arc::unwrap_or_clone(saved); self.start_prompt(saved.text, saved.images, cx); } } @@ -767,33 +759,3 @@ pub(super) fn restore_attachments(values: &[SavedAttachment]) -> Vec }) .collect() } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn rendering_snapshot_shares_immutable_image_payload() { - let prompt = QueuedPrompt::new( - SavedPrompt { - id: 1, - text: "image".into(), - images: vec![Content::Image(nocterm_ai::model::content::Image::new( - "a".repeat(2 * 1024 * 1024), - "image/png", - ))], - attachments: Vec::new(), - }, - Vec::new(), - ); - let copy = prompt.clone(); - assert!(Arc::ptr_eq(prompt.saved(), copy.saved())); - let Content::Image(original) = &prompt.saved().images[0] else { - panic!("image"); - }; - let Content::Image(cloned) = ©.saved().images[0] else { - panic!("image"); - }; - assert_eq!(original.data.as_ptr(), cloned.data.as_ptr()); - assert_eq!(cloned.data.len(), 2 * 1024 * 1024); - } -} diff --git a/crates/agent-chat/src/thread/queue/prompt.rs b/crates/agent-chat/src/thread/queue/prompt.rs new file mode 100644 index 00000000..e5213dbb --- /dev/null +++ b/crates/agent-chat/src/thread/queue/prompt.rs @@ -0,0 +1,81 @@ +//! Immutable queued prompt and its accounted snapshot; clones share the encoded payload. +use super::Attachment; +use nocterm_ai::history::SavedPrompt; +use std::sync::Arc; + +#[derive(Clone)] +pub struct QueuedPrompt { + saved: Arc, + attachments: Vec, + encoded_len: usize, + memory_len: usize, +} + +impl QueuedPrompt { + #[cfg(any(test, feature = "test-support"))] + pub fn new(saved: SavedPrompt, attachments: Vec) -> Self { + Self::prepared(saved, attachments, None) + } + pub fn prepared( + saved: SavedPrompt, + attachments: Vec, + encoded_len: Option, + ) -> Self { + let encoded_len = encoded_len + .unwrap_or_else(|| nocterm_ai::history::prompt_size(&saved).unwrap_or(usize::MAX)); + let memory_len = nocterm_ai::history::prompt_memory(&saved).unwrap_or(usize::MAX); + Self { + memory_len, + saved: Arc::new(saved), + attachments, + encoded_len, + } + } + pub(super) fn into_parts(self) -> (Vec, Arc) { + (self.attachments, self.saved) + } + pub fn saved(&self) -> &Arc { + &self.saved + } + /// What the prompt was written about, captured when it was queued. + pub fn attachments(&self) -> &[Attachment] { + &self.attachments + } + pub fn encoded_len(&self) -> usize { + self.encoded_len + } + pub fn memory_len(&self) -> usize { + self.memory_len + } +} + +#[cfg(test)] +mod tests { + use super::*; + use nocterm_ai::model::content::Content; + #[test] + fn rendering_snapshot_shares_immutable_image_payload() { + let prompt = QueuedPrompt::new( + SavedPrompt { + id: 1, + text: "image".into(), + images: vec![Content::Image(nocterm_ai::model::content::Image::new( + "a".repeat(2 * 1024 * 1024), + "image/png", + ))], + attachments: Vec::new(), + }, + Vec::new(), + ); + let copy = prompt.clone(); + assert!(Arc::ptr_eq(prompt.saved(), copy.saved())); + let Content::Image(original) = &prompt.saved().images[0] else { + panic!("image"); + }; + let Content::Image(cloned) = ©.saved().images[0] else { + panic!("image"); + }; + assert_eq!(original.data.as_ptr(), cloned.data.as_ptr()); + assert_eq!(cloned.data.len(), 2 * 1024 * 1024); + } +} diff --git a/crates/agent-chat/src/thread/saved.rs b/crates/agent-chat/src/thread/saved.rs index 5accaacb..b3595691 100644 --- a/crates/agent-chat/src/thread/saved.rs +++ b/crates/agent-chat/src/thread/saved.rs @@ -126,10 +126,18 @@ impl AgentThread { cx.notify(); } + pub(super) fn clear_settled_disabled_document(&mut self, cx: &gpui::App) { + if !self.deps.enabled(cx) && self.state.release_disabled() { + self.config.disabled(); + self.composer.reset_after_disable(); + } + } + pub(super) fn configured(&mut self, cx: &mut Context) { self.session.opened(); self.sync_config(true, cx); self.remember_options(cx); + self.resume_observed_turn(); self.dispatch_next(cx); cx.notify(); } diff --git a/crates/agent-chat/src/thread/session_driver.rs b/crates/agent-chat/src/thread/session_driver.rs index dc7558b0..3fe3bf8a 100644 --- a/crates/agent-chat/src/thread/session_driver.rs +++ b/crates/agent-chat/src/thread/session_driver.rs @@ -1,7 +1,7 @@ //! Session and lease transitions retain their original connection and operation identity. use super::Restore; use crate::runtime::SessionLease; -use nocterm_ai::model::ids::SessionId; +use nocterm_ai::model::{ids::SessionId, session::SessionActivity}; use nocterm_ai::{ AgentCommands, AgentInfo, BridgeRegistration, session::{SessionPhase, SessionState, Ticket}, @@ -228,6 +228,12 @@ impl SessionDriver { pub(super) fn finish_external_turn(&mut self) -> bool { self.phase.finish_external_turn() } + pub(super) fn observe_activity(&mut self, activity: SessionActivity) -> bool { + self.phase.observe_activity(activity) + } + pub(super) fn resume_observed_turn(&mut self) -> bool { + self.phase.resume_observed_turn() + } pub(super) fn opened(&mut self) { self.phase.opened() } diff --git a/crates/agent/src/panel/tests/authentication.rs b/crates/agent/src/panel/tests/authentication.rs index 20a92291..6900dfb1 100644 --- a/crates/agent/src/panel/tests/authentication.rs +++ b/crates/agent/src/panel/tests/authentication.rs @@ -236,3 +236,105 @@ fn terminal_authentication_uses_host_callback_and_retries_after_cancel_or_failur .ends_with(&["--setup".into(), "$(literal_argument)".into()]) ); } + +fn report_activity( + f: &Fixture, + session: SessionId, + activity: nocterm_ai::model::session::SessionActivity, + cx: &mut TestAppContext, +) { + f.events + .try_send(AgentEvent::Session(SessionNotice::new( + session, + SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { + activity: Some(activity), + ..Default::default() + }), + ))) + .unwrap(); + cx.run_until_parked(); +} + +#[gpui_kit::test] +fn autonomous_agent_activity_shows_stop_and_returns_to_idle(cx: &mut TestAppContext) { + use nocterm_ai::model::session::SessionActivity::{Active, Idle}; + let f = fixture(cx); + new_chat(&f, cx); + let session = cx.update(|cx| { + f.panel + .read(cx) + .current() + .unwrap() + .read(cx) + .session() + .clone() + .unwrap() + }); + report_activity(&f, SessionId::new("another-session"), Active, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_none()); + }) + .unwrap(); + report_activity(&f, session.clone(), Active, cx); + report_activity(&f, session.clone(), Active, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + window.click("agent-send", cx); + }) + .unwrap(); + assert_eq!(f.commands.cancels.load(Ordering::SeqCst), 1); + assert!(f.commands.prompts.lock().unwrap().is_empty()); + report_activity(&f, session, Idle, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + // Stopped remains a status notice, but the busy indicator and stop action are gone. + assert!(window.try_find("agent-thinking").is_none()); + let thread = f.panel.read(cx).current().unwrap(); + assert_eq!(thread.read(cx).status(), "Stopped"); + assert!(!thread.read(cx).session_generating()); + window.click("agent-send", cx); + }) + .unwrap(); + assert_eq!(f.commands.cancels.load(Ordering::SeqCst), 1); +} + +#[gpui_kit::test] +fn autonomous_continuation_keeps_the_composer_busy_and_queues_the_next_message( + cx: &mut TestAppContext, +) { + use nocterm_ai::model::session::{ + PromptOutcome, + SessionActivity::{Active, Idle}, + StopReason, + }; + let f = fixture(cx); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let session = thread.read_with(cx, |thread, _| thread.session().clone().unwrap()); + thread.update(cx, |thread, cx| thread.send("first".into(), cx)); + cx.run_until_parked(); + report_activity(&f, session.clone(), Active, cx); + report_activity(&f, session.clone(), Idle, cx); + report_activity(&f, session.clone(), Active, cx); + f.commands + .pending + .lock() + .unwrap() + .take() + .unwrap() + .send(PromptOutcome::new(StopReason::EndTurn)) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + }) + .unwrap(); + thread.update(cx, |thread, cx| thread.send("second".into(), cx)); + cx.run_until_parked(); + assert_eq!(f.commands.prompts.lock().unwrap().len(), 1); + report_activity(&f, session, Idle, cx); + assert_eq!(f.commands.prompts.lock().unwrap().len(), 2); +} diff --git a/crates/agent/src/panel/tests/history.rs b/crates/agent/src/panel/tests/history.rs index 8bf6ec3c..f5a79f1a 100644 --- a/crates/agent/src/panel/tests/history.rs +++ b/crates/agent/src/panel/tests/history.rs @@ -311,6 +311,7 @@ fn history_records_only_accepted_prompts_and_keeps_model_snapshot(cx: &mut TestA thread, SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { title: nocterm_ai::model::controls::Change::Set("Updated title".into()), + activity: None, meta: None, }), cx, diff --git a/crates/agent/src/panel/tests/labels.rs b/crates/agent/src/panel/tests/labels.rs index 5bd968a8..9a21f7cb 100644 --- a/crates/agent/src/panel/tests/labels.rs +++ b/crates/agent/src/panel/tests/labels.rs @@ -77,6 +77,7 @@ fn chat_header_and_history_keep_multiline_titles_on_one_line(cx: &mut TestAppCon session, SessionUpdate::SessionInfoUpdate(nocterm_ai::model::session::SessionInfo { title: nocterm_ai::model::controls::Change::Set(agent_title.into()), + activity: None, meta: None, }), ))) diff --git a/crates/ai/src/model/session.rs b/crates/ai/src/model/session.rs index 735c7a21..ad2d893a 100644 --- a/crates/ai/src/model/session.rs +++ b/crates/ai/src/model/session.rs @@ -155,9 +155,17 @@ pub enum TurnActivity { Ended, } +/// A provider's explicit observation of whether the session is running work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SessionActivity { + Active, + Idle, +} + #[derive(Clone, Debug, Default, PartialEq)] pub struct SessionInfo { pub title: Change, + pub activity: Option, pub meta: Option, } diff --git a/crates/ai/src/session.rs b/crates/ai/src/session.rs index 0bee37ab..9df9d9b4 100644 --- a/crates/ai/src/session.rs +++ b/crates/ai/src/session.rs @@ -5,7 +5,7 @@ //! session" or "failed but still accepting updates" cannot be built. The //! transitions only decide; the chat performs the side effects they ask for //! and drops async results whose [`Ticket`] is no longer current. -use crate::AgentError; +use crate::{AgentError, model::session::SessionActivity}; /// Where a chat's agent session is. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -69,6 +69,8 @@ pub struct SessionState { failures: u32, /// The running turn was started by the agent for another device. external: bool, + /// Latest explicit provider activity, including events racing a prompt response. + observed_active: bool, } impl SessionState { @@ -216,6 +218,31 @@ impl SessionState { self.phase = SessionPhase::Ready; true } + /// Observe session-wide activity without completing a client-owned prompt. + /// Returns whether the visible turn changed; duplicate observations do not redraw. + pub fn observe_activity(&mut self, activity: SessionActivity) -> bool { + if !matches!( + self.phase, + SessionPhase::Opening + | SessionPhase::Ready + | SessionPhase::Prompting + | SessionPhase::Cancelling + ) { + return false; + } + let was_active = self.observed_active; + self.observed_active = activity == SessionActivity::Active; + if self.observed_active { + self.resume_observed_turn() + } else { + was_active && self.finish_external_turn() + } + } + /// A provider may start another turn before the preceding prompt response arrives. + /// Reconcile after the client has settled its own turn and its tool bookkeeping. + pub fn resume_observed_turn(&mut self) -> bool { + self.observed_active && self.start_external_turn() + } /// The running turn is the agent's own, not one of this chat's prompts. pub fn external_turn(&self) -> bool { self.external && self.generating() @@ -234,19 +261,22 @@ impl SessionState { /// The turn of `ticket` finished. Returns whether it was the running /// one; a stale result changes nothing. pub fn finish_turn(&mut self, ticket: Ticket, completed: bool) -> bool { - if !self.turn_current(ticket) || !self.generating() { + if !self.turn_current(ticket) || !self.generating() || self.external { return false; } self.external = false; self.phase = SessionPhase::Ready; if completed { self.failures = 0; + } else { + self.observed_active = false; } true } /// The agent asks the user to sign in. pub fn require_sign_in(&mut self) { self.phase = SessionPhase::SignInRequired; + self.observed_active = false; } /// Returns whether signing in may start. pub fn begin_sign_in(&mut self) -> bool { @@ -271,6 +301,7 @@ impl SessionState { /// The session ended with an error. Results of its requests are dropped. pub fn fail(&mut self) { self.external = false; + self.observed_active = false; self.phase = SessionPhase::Failed; self.epoch += 1; self.stopped = false; @@ -280,6 +311,8 @@ impl SessionState { /// The chat let its connection go. A failed chat stays failed, so the /// user still sees why; otherwise it is detached until needed again. pub fn detach(&mut self) { + self.external = false; + self.observed_active = false; self.epoch += 1; self.closing = true; if self.phase != SessionPhase::Failed { @@ -288,6 +321,8 @@ impl SessionState { } /// The chat released everything it held, a failure included. pub fn release(&mut self) { + self.external = false; + self.observed_active = false; self.phase = SessionPhase::Detached; self.stopped = false; self.discarding = false; diff --git a/crates/ai/src/session/tests.rs b/crates/ai/src/session/tests.rs index 386e1f7c..b7adae18 100644 --- a/crates/ai/src/session/tests.rs +++ b/crates/ai/src/session/tests.rs @@ -173,3 +173,60 @@ fn a_turn_the_agent_runs_for_another_device_shows_and_ends_on_its_own() { ); assert!(state.finish_turn(ticket, true)); } + +#[test] +fn reported_activity_survives_an_earlier_prompt_response() { + let mut state = ready(); + let local = state.start_turn().unwrap(); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(!state.observe_activity(SessionActivity::Idle)); + assert!( + state.generating(), + "idle never completes the client's request" + ); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.finish_turn(local, true)); + assert!(state.resume_observed_turn()); + assert!(state.generating() && state.busy() && state.external_turn()); + assert!(!state.finish_turn(local, true)); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.start_turn().is_none()); + assert!(state.observe_activity(SessionActivity::Idle)); + assert!(!state.generating()); + assert!(!state.observe_activity(SessionActivity::Idle)); + assert!(state.start_turn().is_some()); +} + +#[test] +fn reported_activity_can_be_cancelled_and_cannot_survive_session_replacement() { + let mut state = ready(); + assert!(state.observe_activity(SessionActivity::Active)); + assert!(state.stop()); + assert!(!state.observe_activity(SessionActivity::Active)); + assert!(state.observe_activity(SessionActivity::Idle)); + assert!(!state.generating() && state.stopped()); + assert!(state.observe_activity(SessionActivity::Active)); + state.detach(); + assert!(!state.observe_activity(SessionActivity::Active)); + state.closed(); + assert!(state.queue()); + state.leased(); + state.opened(); + assert!(!state.resume_observed_turn()); + assert!(!state.generating()); +} + +#[test] +fn normal_prompt_completion_and_cancel_do_not_invent_a_continuation() { + let mut state = ready(); + let turn = state.start_turn().unwrap(); + state.observe_activity(SessionActivity::Active); + state.observe_activity(SessionActivity::Idle); + assert!(state.finish_turn(turn, true)); + assert!(!state.resume_observed_turn()); + let turn = state.start_turn().unwrap(); + state.observe_activity(SessionActivity::Active); + assert!(state.stop()); + assert!(state.finish_turn(turn, false)); + assert!(!state.resume_observed_turn()); +} diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs index f91707f4..9016a61c 100644 --- a/crates/ai/src/tests.rs +++ b/crates/ai/src/tests.rs @@ -82,6 +82,7 @@ fn update(value: serde_json::Value) -> SessionUpdate { Some(serde_json::Value::Null) => Change::Clear, Some(title) => Change::Set(title.as_str().unwrap().into()), }, + activity: None, meta: None, }), "usage_update" => SessionUpdate::UsageUpdate(ContextUsage::new( diff --git a/crates/ai/src/thread/live.rs b/crates/ai/src/thread/live.rs index d7f32e3c..c746976a 100644 --- a/crates/ai/src/thread/live.rs +++ b/crates/ai/src/thread/live.rs @@ -280,6 +280,7 @@ mod tests { SessionUpdate::AgentMessageChunk(Content::text("λ")), SessionUpdate::SessionInfoUpdate(SessionInfo { title: Change::Set("Provider title".into()), + activity: None, meta: None, }), SessionUpdate::AgentMessageChunk(Content::text("中")), diff --git a/crates/hub-io/src/chats/watch.rs b/crates/hub-io/src/chats/watch.rs index f2d3cab3..e3af6caf 100644 --- a/crates/hub-io/src/chats/watch.rs +++ b/crates/hub-io/src/chats/watch.rs @@ -218,6 +218,7 @@ impl Follow { outputs.push(Output::notice(SessionUpdate::SessionInfoUpdate( SessionInfo { title: Change::Set(chat.title.clone()), + activity: None, meta: None, }, ))); diff --git a/docs/architecture/adapter.md b/docs/architecture/adapter.md index 24ca65c5..5ef6f085 100644 --- a/docs/architecture/adapter.md +++ b/docs/architecture/adapter.md @@ -358,9 +358,11 @@ authentication, EOF, registration revocation and bridge shutdown without recordi tokens or protocol contents. The ACP adapter maps the connected agent's context usage, token totals and usage -metadata into AI's neutral records. No adapter in Nocterm reads provider sign-in -tokens or session logs, or requests private provider account endpoints. The agent -owns its authentication, requests and state files +metadata into AI's neutral records. The Codex ACP session-info extension +`_meta.codex.threadStatus` is mapped to an optional typed active/idle observation; +other metadata and unknown status values do not decide activity. No adapter in +Nocterm reads provider sign-in tokens or session logs, or requests private +provider account endpoints. The agent owns its authentication, requests and state files ([ADR 0105](../adr/0105-provider-usage-through-acp-only.md)). ## Agent workspace and sandbox diff --git a/docs/architecture/service.md b/docs/architecture/service.md index e4544f51..87087642 100644 --- a/docs/architecture/service.md +++ b/docs/architecture/service.md @@ -103,6 +103,13 @@ and the footer, without changing remembered docked widths. `ConnectionDirectory` methods take the workspace as a weak handle and are called outside workspace updates, because opening a connection updates the workspace. +A session's explicit activity observation can start or end an autonomous turn +without inserting a user prompt or granting a tool scope. A client-owned prompt +still settles on its own response; the latest observed activity is reconciled +before dispatching the next queued message. Repeated activity observations +without a phase change do not trigger a redraw. Session replacement clears the +observation. + Saved history starts as a catalogue of at most 200 metadata rows, with transcript files as the source of truth. Obsolete metadata sidecars are ignored. Opening or editing a row loads its document in the background. A shared loading permit