diff --git a/Cargo.lock b/Cargo.lock index fb406e33f..a5d0da602 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -834,6 +834,7 @@ dependencies = [ name = "cccc-pair-runtime" version = "0.4.63" dependencies = [ + "base64 0.22.1", "cccc-pair-contracts", "cccc-windows-process", "dunce", diff --git a/crates/cccc-daemon/src/ops/actor_delivery_worker.rs b/crates/cccc-daemon/src/ops/actor_delivery_worker.rs index 8a3ffd19f..2b886c5ae 100644 --- a/crates/cccc-daemon/src/ops/actor_delivery_worker.rs +++ b/crates/cccc-daemon/src/ops/actor_delivery_worker.rs @@ -284,7 +284,7 @@ pub(super) fn process_batch_tracked( } let events = jobs.iter().map(|job| job.event.clone()).collect::>(); if crate::ops::local_headless::held_batch(&events, chrono::Utc::now()) - && !crate::ops::working_state::antigravity_hook_idle_for_status( + && !crate::ops::agent_status::turn_ended_for_session( &job.home, ¤t_group.group_id, ¤t_actor.id, @@ -374,7 +374,7 @@ pub(super) fn process_batch_tracked( // Recheck immediately before writing: startup input-mode / settle waits can // span seconds during which PreInvocation may transition the Actor to working. if crate::ops::local_headless::held_batch(&events, chrono::Utc::now()) - && !crate::ops::working_state::antigravity_hook_idle_for_status( + && !crate::ops::agent_status::turn_ended_for_session( &job.home, ¤t_group.group_id, ¤t_actor.id, @@ -435,7 +435,7 @@ fn process_owned_pty_batch( ) -> BatchOutcome { let events = jobs.iter().map(|job| job.event.clone()).collect::>(); if crate::ops::local_headless::held_batch(&events, chrono::Utc::now()) - && !crate::ops::working_state::antigravity_hook_idle_for_status( + && !crate::ops::agent_status::turn_ended_for_session( home, &group.group_id, &actor.id, diff --git a/crates/cccc-daemon/src/ops/agent_status/antigravity_hook.rs b/crates/cccc-daemon/src/ops/agent_status/antigravity_hook.rs new file mode 100644 index 000000000..68a980728 --- /dev/null +++ b/crates/cccc-daemon/src/ops/agent_status/antigravity_hook.rs @@ -0,0 +1,84 @@ +//! Antigravity native lifecycle hooks bound to one PTY launch. + +use super::{AgentState, AgentStatus, StatusSource}; +use crate::session_owner::runtime as cccc_runtime; +use cccc_contracts::ActorRuntime; +use cccc_core::HomeLayout; +use cccc_core::antigravity_hook::HookState; + +fn launched_runtime( + group_id: &str, + actor_id: &str, + session: &cccc_runtime::SessionStatus, +) -> Option { + #[cfg(unix)] + let launch = crate::session_owner::snapshot(group_id, actor_id) + .ok() + .flatten() + .and_then(|snapshot| snapshot.terminal_launch) + .or(session.launch); + #[cfg(not(unix))] + let launch = { + let _ = (group_id, actor_id); + session.launch + }; + launch.map(|launch| launch.runtime) +} + +fn live_state( + home: &HomeLayout, + group_id: &str, + actor_id: &str, + session: &cccc_runtime::SessionStatus, +) -> Option { + cccc_core::antigravity_hook::read_live_state( + home, + group_id, + actor_id, + session.pid, + &session.started_at, + ) +} + +/// The hook state of a running Antigravity PTY. With a configured runtime, +/// either that configuration or the actual launch must be Antigravity. +pub(super) fn status( + home: &HomeLayout, + group_id: &str, + actor_id: &str, + configured_runtime: Option, +) -> Option { + let session = cccc_runtime::status(group_id, actor_id).ok()?; + if !session.running { + return None; + } + let launched = launched_runtime(group_id, actor_id, &session); + if launched.is_some_and(|runtime| runtime != ActorRuntime::Antigravity) { + return None; + } + if let Some(configured) = configured_runtime + && configured != ActorRuntime::Antigravity + && launched != Some(ActorRuntime::Antigravity) + { + return None; + } + let hook = live_state(home, group_id, actor_id, &session)?; + let mut status = AgentStatus::new( + AgentState::parse(&hook.status), + "antigravity_hook", + StatusSource::AntigravityHook, + ); + status.turn_ended = hook.status == "idle"; + status.updated_at = Some(hook.updated_at); + Some(status) +} + +/// Whether that launch's hooks report idle; `None` without a hook binding. +pub(super) fn turn_ended_for_session( + home: &HomeLayout, + group_id: &str, + actor_id: &str, + session: &cccc_runtime::SessionStatus, +) -> Option { + live_state(home, group_id, actor_id, session).map(|hook| hook.status == "idle") +} diff --git a/crates/cccc-daemon/src/ops/agent_status/dots.rs b/crates/cccc-daemon/src/ops/agent_status/dots.rs new file mode 100644 index 000000000..503b0a6ee --- /dev/null +++ b/crates/cccc-daemon/src/ops/agent_status/dots.rs @@ -0,0 +1,34 @@ +//! ChatGPT Dots event turns. + +use super::{AgentState, AgentStatus, StatusSource}; +use cccc_contracts::{Actor, ActorRuntime}; +use cccc_core::HomeLayout; + +pub(super) fn status(home: &HomeLayout, group_id: &str, actor: &Actor) -> Option { + if actor.runtime != ActorRuntime::ChatgptDots { + return None; + } + let Ok(runtime) = crate::ops::runtime_state::actor_state(home, group_id, &actor.id) else { + return Some(AgentStatus::new( + AgentState::Waiting, + "dots_state_unavailable", + StatusSource::Dots, + )); + }; + let active_turn = runtime["active_turn_id"] + .as_str() + .filter(|id| !id.is_empty()) + .map(str::to_owned); + let mut status = AgentStatus::new( + if active_turn.is_some() { + AgentState::Working + } else { + AgentState::Waiting + }, + "dots_event_turn", + StatusSource::Dots, + ); + status.updated_at = runtime["updated_at"].as_str().map(str::to_owned); + status.active_task_id = active_turn; + Some(status) +} diff --git a/crates/cccc-daemon/src/ops/agent_status/managed.rs b/crates/cccc-daemon/src/ops/agent_status/managed.rs new file mode 100644 index 000000000..128f47ba7 --- /dev/null +++ b/crates/cccc-daemon/src/ops/agent_status/managed.rs @@ -0,0 +1,40 @@ +//! Managed agent sessions (CCCC-hosted app-server, ACP or RPC sessions). + +use super::{AgentState, AgentStatus, StatusSource}; +use cccc_contracts::Actor; + +/// The live managed session's own state, or its pending registration. +pub(super) fn live(group_id: &str, actor_id: &str, pty: bool) -> Option { + if let Some(local) = crate::ops::local_headless::status(group_id, actor_id) { + let reason = local.reason.unwrap_or_else(|| { + if pty { + "managed_agent_session".to_owned() + } else { + "provider_headless_session".to_owned() + } + }); + let mut status = AgentStatus::new( + AgentState::parse(&local.status), + &reason, + StatusSource::ManagedSession, + ); + status.updated_at = Some(local.updated_at); + status.active_task_id = local.task_id; + return Some(status); + } + crate::ops::local_headless::running(group_id, actor_id).then(pending) +} + +/// An Actor configured for a managed session whose session has not +/// registered yet. +pub(super) fn configured_pending(actor: &Actor) -> Option { + crate::ops::local_headless::uses_managed_session(actor).then(pending) +} + +fn pending() -> AgentStatus { + AgentStatus::new( + AgentState::Waiting, + "managed_agent_session_pending", + StatusSource::ManagedSession, + ) +} diff --git a/crates/cccc-daemon/src/ops/agent_status/mod.rs b/crates/cccc-daemon/src/ops/agent_status/mod.rs new file mode 100644 index 000000000..a45775a4e --- /dev/null +++ b/crates/cccc-daemon/src/ops/agent_status/mod.rs @@ -0,0 +1,237 @@ +//! One runtime-agnostic agent status model. +//! +//! Each source of structured state is a provider that knows its runtime and +//! returns `Option`. [`resolve`] applies the precedence in one +//! place: managed session > Antigravity lifecycle hook > OSC 7501 program +//! status > fallbacks. Callers above the resolver read only [`AgentStatus`] +//! and never branch on the Actor's runtime. + +mod antigravity_hook; +mod dots; +mod managed; +mod program_status; +#[cfg(test)] +mod tests; + +use crate::session_owner::runtime as cccc_runtime; +use cccc_contracts::Actor; +use cccc_core::HomeLayout; +use serde_json::{Map, Value, json}; + +/// The working state vocabulary of `effective_working_state`. A provider's +/// own spelling that is not listed here is kept verbatim. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum AgentState { + Stopped, + Idle, + Working, + Waiting, + Blocked, + Error, + Unknown, + Other(String), +} + +impl AgentState { + pub(crate) fn parse(value: &str) -> Self { + match value { + "stopped" => Self::Stopped, + "idle" => Self::Idle, + "working" => Self::Working, + "waiting" => Self::Waiting, + "blocked" => Self::Blocked, + "error" => Self::Error, + "unknown" => Self::Unknown, + other => Self::Other(other.to_owned()), + } + } + + pub(crate) fn as_str(&self) -> &str { + match self { + Self::Stopped => "stopped", + Self::Idle => "idle", + Self::Working => "working", + Self::Waiting => "waiting", + Self::Blocked => "blocked", + Self::Error => "error", + Self::Unknown => "unknown", + Self::Other(value) => value, + } + } +} + +/// Which source established the status (`effective_status_source`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum StatusSource { + ManagedSession, + AntigravityHook, + ProgramStatus, + Dots, + /// No structured source: the state is a conservative fallback. + None, +} + +impl StatusSource { + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::ManagedSession => "managed_session", + Self::AntigravityHook => "antigravity_hook", + Self::ProgramStatus => "program_status", + Self::Dots => "dots", + Self::None => "none", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct AgentStatus { + pub state: AgentState, + /// `effective_working_reason`: the source's detail for this state. + pub reason: String, + pub source: StatusSource, + pub updated_at: Option, + pub active_task_id: Option, + /// `permission`, `question` or `auth`, only while blocked. + pub blocked_kind: Option, + pub message: Option, + pub progress: Option, + /// The source positively reports that the current turn ended, so an early + /// Mail notice cannot interrupt work. + pub turn_ended: bool, +} + +impl AgentStatus { + fn new(state: AgentState, reason: &str, source: StatusSource) -> Self { + Self { + state, + reason: reason.to_owned(), + source, + updated_at: None, + active_task_id: None, + blocked_kind: None, + message: None, + progress: None, + turn_ended: false, + } + } + + /// The `effective_*` fields of an Actor projection. + pub(crate) fn fields(&self) -> Map { + Map::from_iter([ + ("effective_working_state".into(), json!(self.state.as_str())), + ("effective_working_reason".into(), json!(self.reason)), + ( + "effective_working_updated_at".into(), + json!(self.updated_at), + ), + ( + "effective_active_task_id".into(), + json!(self.active_task_id), + ), + ( + "effective_status_source".into(), + json!(self.source.as_str()), + ), + ("effective_blocked_kind".into(), json!(self.blocked_kind)), + ("effective_status_message".into(), json!(self.message)), + ("effective_progress".into(), json!(self.progress)), + ]) + } +} + +/// What the resolver knows about the Actor being projected. +pub(crate) struct StatusQuery<'a> { + pub home: &'a HomeLayout, + pub actor: &'a Actor, + pub group_id: &'a str, + pub running: bool, + /// `pty` or `headless`: the surface actually running. + pub runner_effective: &'a str, +} + +/// The one precedence rule for an Actor's working state. +pub(crate) fn resolve(query: &StatusQuery<'_>) -> AgentStatus { + if !query.running { + return AgentStatus::new( + AgentState::Stopped, + "runner_not_running", + StatusSource::None, + ); + } + let pty = query.runner_effective == "pty"; + let actor_id = query.actor.id.as_str(); + managed::live(query.group_id, actor_id, pty) + .or_else(|| { + pty.then(|| { + antigravity_hook::status( + query.home, + query.group_id, + actor_id, + Some(query.actor.runtime), + ) + }) + .flatten() + }) + .or_else(|| { + pty.then(|| program_status::status(query.group_id, actor_id)) + .flatten() + }) + .or_else(|| managed::configured_pending(query.actor)) + .or_else(|| dots::status(query.home, query.group_id, query.actor)) + .unwrap_or_else(|| { + if pty { + AgentStatus::new( + AgentState::Waiting, + "pty_running_state_unknown", + StatusSource::None, + ) + } else { + // A running process alone proves neither an idle turn nor its age. + AgentStatus::new( + AgentState::Unknown, + "headless_running_state_unknown", + StatusSource::None, + ) + } + }) +} + +/// True when a running Actor positively reports that its turn ended, which +/// admits early Mail notices without interrupting active work. A managed +/// session decides through its own notice gate; it outranks terminal reports. +pub(crate) fn ready_for_mail_notice(home: &HomeLayout, group_id: &str, actor_id: &str) -> bool { + if super::local_headless::ready_for_mail_notice(group_id, actor_id) { + return true; + } + if managed::live(group_id, actor_id, true).is_some() { + return false; + } + terminal_status(home, group_id, actor_id).is_some_and(|status| status.turn_ended) +} + +/// The terminal-reported status of a live PTY whose Actor is not loaded. +fn terminal_status(home: &HomeLayout, group_id: &str, actor_id: &str) -> Option { + if !cccc_runtime::status(group_id, actor_id).is_ok_and(|status| status.running) { + return None; + } + antigravity_hook::status(home, group_id, actor_id, None) + .or_else(|| program_status::status(group_id, actor_id)) +} + +/// Recheck before handing an early Mail notice to one specific PTY launch: +/// true only when that launch still reports that its turn ended. +pub(crate) fn turn_ended_for_session( + home: &HomeLayout, + group_id: &str, + actor_id: &str, + session: &cccc_runtime::SessionStatus, +) -> bool { + if !session.running { + return false; + } + if let Some(ended) = antigravity_hook::turn_ended_for_session(home, group_id, actor_id, session) + { + return ended; + } + program_status::turn_ended_for_session(group_id, actor_id, session) +} diff --git a/crates/cccc-daemon/src/ops/agent_status/program_status.rs b/crates/cccc-daemon/src/ops/agent_status/program_status.rs new file mode 100644 index 000000000..22d50985b --- /dev/null +++ b/crates/cccc-daemon/src/ops/agent_status/program_status.rs @@ -0,0 +1,55 @@ +//! OSC 7501 Program Status Protocol: the program in the PTY reports its own +//! state in its terminal output. Any runtime that speaks it is covered. + +use super::{AgentState, AgentStatus, StatusSource}; +use crate::session_owner::runtime as cccc_runtime; +use cccc_runtime::{ProgramBlockedKind, ProgramState, ProgramStatus}; + +pub(super) fn project(report: ProgramStatus) -> AgentStatus { + let (state, turn_ended) = match report.state { + ProgramState::Working => (AgentState::Working, false), + ProgramState::Blocked => (AgentState::Blocked, false), + // `done` ends the turn exactly like `idle`; the vocabulary has no + // separate state for it. + ProgramState::Idle | ProgramState::Done => (AgentState::Idle, true), + ProgramState::Error => (AgentState::Error, true), + }; + let mut status = AgentStatus::new(state, "program_status", StatusSource::ProgramStatus); + status.turn_ended = turn_ended; + status.updated_at = Some( + chrono::DateTime::::from(report.reported_at) + .to_rfc3339_opts(chrono::SecondsFormat::Micros, true), + ); + status.blocked_kind = report.kind.map(|kind| { + match kind { + ProgramBlockedKind::Permission => "permission", + ProgramBlockedKind::Question => "question", + ProgramBlockedKind::Auth => "auth", + } + .to_owned() + }); + status.message = report.message; + status.progress = report.progress; + status +} + +/// The live PTY program's latest report. An owner that predates this read +/// rejects it, and the Actor then has no program status. +pub(super) fn status(group_id: &str, actor_id: &str) -> Option { + cccc_runtime::program_status(group_id, actor_id) + .ok() + .flatten() + .map(project) +} + +/// Whether that exact launch still reports that its turn ended. +pub(super) fn turn_ended_for_session( + group_id: &str, + actor_id: &str, + session: &cccc_runtime::SessionStatus, +) -> bool { + let same_launch = cccc_runtime::status(group_id, actor_id).is_ok_and(|current| { + current.running && current.pid == session.pid && current.started_at == session.started_at + }); + same_launch && status(group_id, actor_id).is_some_and(|status| status.turn_ended) +} diff --git a/crates/cccc-daemon/src/ops/agent_status/tests.rs b/crates/cccc-daemon/src/ops/agent_status/tests.rs new file mode 100644 index 000000000..02b3f30ee --- /dev/null +++ b/crates/cccc-daemon/src/ops/agent_status/tests.rs @@ -0,0 +1,195 @@ +use super::{AgentState, StatusQuery, StatusSource, ready_for_mail_notice, resolve}; +use cccc_contracts::{Actor, ActorRuntime, RunnerKind}; +use cccc_core::HomeLayout; +use cccc_runtime::{ProgramBlockedKind, ProgramState, ProgramStatus}; +use std::time::{Duration, SystemTime}; + +fn report(state: ProgramState) -> ProgramStatus { + ProgramStatus { + state, + kind: None, + progress: None, + app: None, + title: None, + message: None, + reported_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000), + } +} + +#[test] +fn program_reports_map_onto_the_working_state_vocabulary() { + for (state, expected, turn_ended) in [ + (ProgramState::Working, AgentState::Working, false), + (ProgramState::Blocked, AgentState::Blocked, false), + (ProgramState::Idle, AgentState::Idle, true), + (ProgramState::Done, AgentState::Idle, true), + (ProgramState::Error, AgentState::Error, true), + ] { + let status = super::program_status::project(report(state)); + assert_eq!(status.state, expected, "{state:?}"); + assert_eq!(status.turn_ended, turn_ended, "{state:?}"); + assert_eq!(status.reason, "program_status"); + assert_eq!(status.source, StatusSource::ProgramStatus); + assert_eq!( + status.updated_at.as_deref(), + Some("2023-11-14T22:13:20.000000Z") + ); + } + let mut blocked = report(ProgramState::Blocked); + blocked.kind = Some(ProgramBlockedKind::Auth); + blocked.message = Some("Sign in required".into()); + blocked.progress = Some(30); + let fields = super::program_status::project(blocked).fields(); + assert_eq!(fields["effective_working_state"], "blocked"); + assert_eq!(fields["effective_status_source"], "program_status"); + assert_eq!(fields["effective_blocked_kind"], "auth"); + assert_eq!(fields["effective_status_message"], "Sign in required"); + assert_eq!(fields["effective_progress"], 30); +} + +#[test] +fn a_stopped_actor_has_no_source() { + let temp = tempfile::tempdir().expect("tempdir"); + let home = HomeLayout::from_path(temp.path()).expect("home"); + let actor = Actor::new("peer1"); + let status = resolve(&StatusQuery { + home: &home, + actor: &actor, + group_id: "g_stopped_status", + running: false, + runner_effective: "pty", + }); + assert_eq!(status.state, AgentState::Stopped); + assert_eq!(status.reason, "runner_not_running"); + assert_eq!(status.source, StatusSource::None); +} + +/// Precedence among sources, observed on a real PTY whose program reports +/// over OSC 7501. +#[cfg(unix)] +mod precedence { + use super::*; + use std::path::Path; + use std::time::Instant; + + const ACTOR_ID: &str = "peer1"; + const REPORTS_WORKING: &str = + "printf '\\033]7501;state=working:app=test\\033\\\\'; exec sleep 30"; + + struct StopOnDrop(String); + + impl Drop for StopOnDrop { + fn drop(&mut self) { + let _ = cccc_runtime::stop(&self.0, ACTOR_ID); + } + } + + fn start(group_id: &str, cwd: &Path, script: &str) -> StopOnDrop { + cccc_runtime::start(cccc_runtime::LaunchSpec { + group_id: group_id.into(), + actor_id: ACTOR_ID.into(), + runner: RunnerKind::Pty, + command: vec!["sh".into(), "-c".into(), script.into()], + cwd: cwd.into(), + env: Default::default(), + cols: 80, + rows: 24, + }) + .expect("start terminal"); + StopOnDrop(group_id.into()) + } + + fn wait_for_report(group_id: &str) { + let deadline = Instant::now() + Duration::from_secs(10); + while cccc_runtime::program_status(group_id, ACTOR_ID) + .ok() + .flatten() + .is_none() + { + assert!(Instant::now() < deadline, "program never reported"); + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn resolve_for(home: &HomeLayout, actor: &Actor, group_id: &str, runner: &str) -> AgentStatus { + resolve(&StatusQuery { + home, + actor, + group_id, + running: true, + runner_effective: runner, + }) + } + + use super::super::AgentStatus; + + #[test] + fn program_status_outranks_the_terminal_fallbacks_only_on_a_pty() { + let temp = tempfile::tempdir().expect("tempdir"); + let home = HomeLayout::from_path(temp.path()).expect("home"); + let group_id = "g_status_over_fallback"; + let _stop = start(group_id, temp.path(), REPORTS_WORKING); + wait_for_report(group_id); + + let mut custom = Actor::new(ACTOR_ID); + custom.runtime = ActorRuntime::Custom; + let status = resolve_for(&home, &custom, group_id, "pty"); + assert_eq!(status.state, AgentState::Working); + assert_eq!(status.source, StatusSource::ProgramStatus); + + // A configured managed session that has not registered is a fallback. + let mut claude = Actor::new(ACTOR_ID); + claude.runtime = ActorRuntime::Claude; + let status = resolve_for(&home, &claude, group_id, "pty"); + assert_eq!(status.reason, "program_status"); + + // A headless surface never reads terminal reports. + let status = resolve_for(&home, &custom, group_id, "headless"); + assert_eq!(status.state, AgentState::Unknown); + assert_eq!(status.reason, "headless_running_state_unknown"); + assert_eq!(status.source, StatusSource::None); + } + + #[test] + fn the_antigravity_hook_outranks_program_status() { + let temp = tempfile::tempdir().expect("tempdir"); + let home = HomeLayout::from_path(temp.path().join("home")).expect("home"); + home.initialize().expect("init home"); + let group_id = "g_hook_over_program_status"; + let _stop = start(group_id, temp.path(), REPORTS_WORKING); + wait_for_report(group_id); + let mut actor = Actor::new(ACTOR_ID); + actor.runtime = ActorRuntime::Antigravity; + assert_eq!( + resolve_for(&home, &actor, group_id, "pty").source, + StatusSource::ProgramStatus + ); + assert!(!ready_for_mail_notice(&home, group_id, ACTOR_ID)); + + let session = cccc_runtime::status(group_id, ACTOR_ID).expect("status"); + let launch_id = "agy-launch-1"; + cccc_core::antigravity_hook::record_launch( + &home, + group_id, + ACTOR_ID, + launch_id, + session.pid, + &session.started_at, + ) + .expect("record launch"); + cccc_core::antigravity_hook::apply_hook_payload( + &cccc_core::antigravity_hook::state_file_path(&home, group_id, ACTOR_ID, launch_id), + launch_id, + group_id, + ACTOR_ID, + &serde_json::json!({"hookEventName":"SessionStart","conversationId":"c1"}), + ) + .expect("session start"); + + let status = resolve_for(&home, &actor, group_id, "pty"); + assert_eq!(status.state, AgentState::Idle); + assert_eq!(status.reason, "antigravity_hook"); + assert_eq!(status.source, StatusSource::AntigravityHook); + assert!(ready_for_mail_notice(&home, group_id, ACTOR_ID)); + } +} diff --git a/crates/cccc-daemon/src/ops/mod.rs b/crates/cccc-daemon/src/ops/mod.rs index 6af370866..ce5fbdd4d 100644 --- a/crates/cccc-daemon/src/ops/mod.rs +++ b/crates/cccc-daemon/src/ops/mod.rs @@ -73,6 +73,7 @@ mod message_metadata; mod message_pins; mod messaging; pub(crate) use messaging::reply_crosses_groups; +pub(crate) mod agent_status; mod messaging_inbox; mod messaging_query; mod messaging_query_status; diff --git a/crates/cccc-daemon/src/ops/working_state.rs b/crates/cccc-daemon/src/ops/working_state.rs index e0151db63..0146735ee 100644 --- a/crates/cccc-daemon/src/ops/working_state.rs +++ b/crates/cccc-daemon/src/ops/working_state.rs @@ -1,5 +1,5 @@ use crate::session_owner::runtime as cccc_runtime; -use cccc_contracts::{Actor, ActorRuntime, RunnerKind}; +use cccc_contracts::{Actor, RunnerKind}; use cccc_core::HomeLayout; use serde_json::{Map, Value, json}; @@ -17,85 +17,10 @@ fn pty_output_observation(group_id: &str, actor_id: &str) -> (Value, Value) { (Value::String(last_output_at), json!(quiet_seconds)) } -fn live_antigravity_terminal( - group_id: &str, - actor_id: &str, -) -> Option { - let status = cccc_runtime::status(group_id, actor_id).ok()?; - if !status.running { - return None; - } - #[cfg(unix)] - let launched_runtime = crate::session_owner::snapshot(group_id, actor_id) - .ok() - .flatten() - .and_then(|snapshot| snapshot.terminal_launch) - .or(status.launch) - .map(|launch| launch.runtime); - #[cfg(not(unix))] - let launched_runtime = status.launch.map(|launch| launch.runtime); - if launched_runtime.is_some_and(|runtime| runtime != ActorRuntime::Antigravity) { - return None; - } - Some(status) -} - -pub(crate) fn antigravity_hook_idle_for_status( - home: &HomeLayout, - group_id: &str, - actor_id: &str, - status: &cccc_runtime::SessionStatus, -) -> bool { - status.running - && cccc_core::antigravity_hook::read_live_state( - home, - group_id, - actor_id, - status.pid, - &status.started_at, - ) - .is_some_and(|state| state.status == "idle") -} - -/// True when a running Actor reports idle state through either a managed -/// session or Antigravity's native lifecycle hooks, admitting early Mail -/// notices without interrupting active work. +/// True when a running Actor positively reports that its turn ended, +/// admitting early Mail notices without interrupting active work. pub(crate) fn ready_for_mail_notice(home: &HomeLayout, group_id: &str, actor_id: &str) -> bool { - if super::local_headless::ready_for_mail_notice(group_id, actor_id) { - return true; - } - live_antigravity_terminal(group_id, actor_id) - .is_some_and(|status| antigravity_hook_idle_for_status(home, group_id, actor_id, &status)) -} - -fn live_antigravity_hook_state( - home: &HomeLayout, - group_id: &str, - actor_id: &str, - configured_runtime: ActorRuntime, -) -> Option { - let status = live_antigravity_terminal(group_id, actor_id)?; - #[cfg(unix)] - let launched_runtime = crate::session_owner::snapshot(group_id, actor_id) - .ok() - .flatten() - .and_then(|snapshot| snapshot.terminal_launch) - .or(status.launch) - .map(|launch| launch.runtime); - #[cfg(not(unix))] - let launched_runtime = status.launch.map(|launch| launch.runtime); - if configured_runtime != ActorRuntime::Antigravity - && launched_runtime != Some(ActorRuntime::Antigravity) - { - return None; - } - cccc_core::antigravity_hook::read_live_state( - home, - group_id, - actor_id, - status.pid, - &status.started_at, - ) + super::agent_status::ready_for_mail_notice(home, group_id, actor_id) } pub fn runtime_actor_fields( @@ -122,6 +47,10 @@ fn runtime_actor_snapshot( "effective_working_reason":"runtime_owner_unavailable", "effective_working_updated_at":null, "effective_active_task_id":null, + "effective_status_source":"none", + "effective_blocked_kind":null, + "effective_status_message":null, + "effective_progress":null, "runtime_observation_error":error.to_string() }) .as_object() @@ -152,110 +81,24 @@ pub(super) fn fields( running: bool, runner_effective: &str, ) -> Map { - let live_managed = super::local_headless::running(group_id, &actor.id); - let configured_managed = super::local_headless::uses_managed_session(actor); - let local_state = running - .then(|| super::local_headless::status(group_id, &actor.id)) - .flatten(); - let (state, reason, updated_at, active_task_id) = if !running { - ( - "stopped".to_owned(), - "runner_not_running".to_owned(), - None, - None, - ) - } else if let Some(local_state) = local_state { - ( - local_state.status, - local_state.reason.unwrap_or_else(|| { - if runner_effective == "pty" { - "managed_agent_session".to_owned() - } else { - "provider_headless_session".to_owned() - } - }), - Some(local_state.updated_at), - local_state.task_id, - ) - } else if live_managed { - ( - "waiting".to_owned(), - "managed_agent_session_pending".to_owned(), - None, - None, - ) - } else if runner_effective == "pty" - && let Some(hook) = live_antigravity_hook_state(home, group_id, &actor.id, actor.runtime) - { - ( - hook.status, - "antigravity_hook".to_owned(), - Some(hook.updated_at), - None, - ) - } else if configured_managed { - ( - "waiting".to_owned(), - "managed_agent_session_pending".to_owned(), - None, - None, - ) - } else if actor.runtime == ActorRuntime::ChatgptDots { - match super::runtime_state::actor_state(home, group_id, &actor.id) { - Ok(runtime) => ( - if runtime["active_turn_id"] - .as_str() - .is_some_and(|id| !id.is_empty()) - { - "working" - } else { - "waiting" - } - .to_owned(), - "dots_event_turn".to_owned(), - runtime["updated_at"].as_str().map(str::to_owned), - runtime["active_turn_id"] - .as_str() - .filter(|id| !id.is_empty()) - .map(str::to_owned), - ), - Err(_) => ( - "waiting".to_owned(), - "dots_state_unavailable".to_owned(), - None, - None, - ), - } - } else if runner_effective == "headless" { - // A running process alone proves neither an idle turn nor its age. - ( - "unknown".to_owned(), - "headless_running_state_unknown".to_owned(), - None, - None, - ) - } else { - ( - "waiting".to_owned(), - "pty_running_state_unknown".to_owned(), - None, - None, - ) - }; + let status = super::agent_status::resolve(&super::agent_status::StatusQuery { + home, + actor, + group_id, + running, + runner_effective, + }); let (pty_last_output_at, pty_quiet_seconds) = if running && runner_effective == "pty" { pty_output_observation(group_id, &actor.id) } else { (Value::Null, Value::Null) }; - - Map::from_iter([ + let mut fields = Map::from_iter([ ("idle_seconds".into(), Value::Null), ("runner_effective".into(), json!(runner_effective)), - ("effective_working_state".into(), json!(state)), - ("effective_working_reason".into(), json!(reason)), - ("effective_working_updated_at".into(), json!(updated_at)), - ("effective_active_task_id".into(), json!(active_task_id)), ("pty_last_output_at".into(), pty_last_output_at), ("pty_quiet_seconds".into(), pty_quiet_seconds), - ]) + ]); + fields.extend(status.fields()); + fields } diff --git a/crates/cccc-daemon/src/ops/working_state_tests.rs b/crates/cccc-daemon/src/ops/working_state_tests.rs index 99dc3a435..e9f7da0fb 100644 --- a/crates/cccc-daemon/src/ops/working_state_tests.rs +++ b/crates/cccc-daemon/src/ops/working_state_tests.rs @@ -378,6 +378,81 @@ mod terminal_output { assert!(state["pty_last_output_at"].is_string(), "{state:?}"); } + /// Reports over OSC 7501, advancing to the next report when the test + /// creates the named file. + const PROGRAM_STATUS_STEPS: &str = "step() { while [ ! -f \"$1\" ]; do sleep 0.02; done; }; \ + printf '\\033]7501;state=working:app=test\\033\\\\'; step blocked; \ + printf '\\033]7501;state=blocked:kind=permission:msg=VHJ1c3QgdGhpcyBmb2xkZXI/\\007'; step done; \ + printf '\\033]7501;state=done\\033\\\\'; step prompt; \ + printf '\\033]133;A\\007'; exec sleep 30"; + + fn wait_for_state( + home: &HomeLayout, + actor: &Actor, + group_id: &str, + state: &str, + ) -> Map { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let fields = fields(home, actor, group_id, true, "pty"); + if fields["effective_working_state"] == state || Instant::now() >= deadline { + return fields; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + + #[test] + fn pty_program_status_reports_drive_working_state_and_mail_notices() { + let temp = tempfile::tempdir().expect("tempdir"); + let home = HomeLayout::from_path(temp.path().join("home")).expect("home"); + home.initialize().expect("init home"); + let group_id = "g_program_status_working_state"; + let _stop = start_terminal(group_id, temp.path(), PROGRAM_STATUS_STEPS); + let actor = custom_actor(); + let ready = + || super::super::working_state::ready_for_mail_notice(&home, group_id, ACTOR_ID); + let session = cccc_runtime::status(group_id, ACTOR_ID).expect("session"); + let session_ready = || { + super::super::agent_status::turn_ended_for_session(&home, group_id, ACTOR_ID, &session) + }; + + let working = wait_for_state(&home, &actor, group_id, "working"); + assert_eq!(working["effective_working_state"], "working", "{working:?}"); + assert_eq!(working["effective_working_reason"], "program_status"); + assert_eq!(working["effective_status_source"], "program_status"); + assert!(working["effective_blocked_kind"].is_null()); + chrono::DateTime::parse_from_rfc3339( + working["effective_working_updated_at"] + .as_str() + .expect("report time"), + ) + .expect("RFC 3339 report time"); + assert!(!ready() && !session_ready()); + + std::fs::write(temp.path().join("blocked"), "").expect("advance"); + let blocked = wait_for_state(&home, &actor, group_id, "blocked"); + assert_eq!(blocked["effective_working_state"], "blocked", "{blocked:?}"); + assert_eq!(blocked["effective_blocked_kind"], "permission"); + assert_eq!(blocked["effective_status_message"], "Trust this folder?"); + assert!(!ready() && !session_ready()); + + std::fs::write(temp.path().join("done"), "").expect("advance"); + let done = wait_for_state(&home, &actor, group_id, "idle"); + assert_eq!(done["effective_working_state"], "idle", "{done:?}"); + assert_eq!(done["effective_working_reason"], "program_status"); + assert!(done["effective_blocked_kind"].is_null()); + assert!(done["effective_status_message"].is_null()); + assert!(ready() && session_ready()); + + // A new shell prompt means the reporting program ended. + std::fs::write(temp.path().join("prompt"), "").expect("advance"); + let ended = wait_for_state(&home, &actor, group_id, "waiting"); + assert_unknown_state(&ended); + assert_eq!(ended["effective_status_source"], "none"); + assert!(!ready() && !session_ready()); + } + #[test] fn antigravity_pty_projects_hook_working_and_idle_state_for_mail_notices() { let temp = tempfile::tempdir().expect("tempdir"); diff --git a/crates/cccc-daemon/src/session_owner/backend.rs b/crates/cccc-daemon/src/session_owner/backend.rs index 82c105245..6b7876a16 100644 --- a/crates/cccc-daemon/src/session_owner/backend.rs +++ b/crates/cccc-daemon/src/session_owner/backend.rs @@ -761,7 +761,7 @@ impl Backend { } } if crate::ops::local_headless::held_batch(&events, chrono::Utc::now()) - && !crate::ops::working_state::antigravity_hook_idle_for_status( + && !crate::ops::agent_status::turn_ended_for_session( home, &group.group_id, &actor.id, @@ -1188,6 +1188,7 @@ impl Backend { cccc_runtime::attachment_writable(group, id, attachment_id).map(json) } TerminalRead::Size => cccc_runtime::terminal_size(group, id).map(json), + TerminalRead::ProgramStatus => cccc_runtime::program_status(group, id).map(json), }; value.map_err(runtime_failure) } diff --git a/crates/cccc-daemon/src/session_owner/mod.rs b/crates/cccc-daemon/src/session_owner/mod.rs index 47fdefc2e..adb693e62 100644 --- a/crates/cccc-daemon/src/session_owner/mod.rs +++ b/crates/cccc-daemon/src/session_owner/mod.rs @@ -27,6 +27,8 @@ mod installer; mod mcp; #[cfg(unix)] mod preservation; +#[cfg(all(test, unix))] +mod program_status_tests; #[cfg(unix)] mod projection; #[cfg(unix)] diff --git a/crates/cccc-daemon/src/session_owner/program_status_tests.rs b/crates/cccc-daemon/src/session_owner/program_status_tests.rs new file mode 100644 index 000000000..ede4b3bab --- /dev/null +++ b/crates/cccc-daemon/src/session_owner/program_status_tests.rs @@ -0,0 +1,145 @@ +//! OSC 7501 program status read from a PTY held by a separate session owner. + +use super::{ShutdownMode, controller, protocol::*}; +use cccc_contracts::{Actor, ActorRuntime, ActorSubmit, Event, RunnerKind}; +use cccc_core::{GroupStore, HomeLayout}; +use std::sync::atomic::AtomicBool; +use std::time::{Duration, Instant}; + +fn wait_until(what: &str, mut check: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(10); + while !check() { + assert!(Instant::now() < deadline, "{what} did not happen"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn owner_held_pty_reports_program_status_and_gates_early_mail_notices() { + let temp = tempfile::tempdir().expect("isolated home"); + let home = HomeLayout::from_path(temp.path().join("home")).expect("home"); + home.initialize().expect("init home"); + let store = GroupStore::new(home.clone()).expect("store"); + let mut group = store.create("Program status owner", "").expect("group"); + let mut actor = Actor::new("member"); + actor.runtime = ActorRuntime::Custom; + actor.runner = RunnerKind::Pty; + group.actors.push(actor.clone()); + store.save(&group).expect("save actor"); + let _lock = cccc_core::fs::try_exclusive_lock(&home.daemon_dir().join("ccccd.lock")) + .expect("home lock") + .expect("private home is unlocked"); + controller::initialize(&home).expect("controller"); + + let received = temp.path().join("received"); + let script = format!( + "stty raw -echo; \ + printf '\\033]7501;state=blocked:kind=question:app=test\\033\\\\'; \ + while [ ! -f idle ]; do sleep 0.02; done; \ + printf '\\033]7501;state=idle:app=test\\007'; \ + exec cat > {}", + received.display() + ); + controller::start( + &home, + ActorRef { + group_id: group.group_id.clone(), + actor_id: actor.id.clone(), + actor_created_at: actor.created_at.clone(), + generation: None, + }, + PreparedLaunch::Pty { + spec: cccc_runtime::LaunchSpec { + group_id: group.group_id.clone(), + actor_id: actor.id.clone(), + runner: RunnerKind::Pty, + command: vec!["/bin/sh".into(), "-c".into(), script], + cwd: temp.path().into(), + env: Default::default(), + cols: 80, + rows: 24, + }, + history: cccc_runtime::HistoryConfig { + path: temp.path().join("terminal.pty"), + max_bytes: 65536, + hot_bytes: 8192, + persist: false, + }, + launch: cccc_runtime::ActorLaunch { + runtime: ActorRuntime::Custom, + submit: ActorSubmit::Newline, + }, + preamble: "startup context".into(), + }, + ) + .expect("start owned terminal") + .terminal + .expect("owned terminal"); + // The PTY lives in the owner process, not in this one. + assert!(matches!( + ::cccc_runtime::program_status(&group.group_id, &actor.id), + Err(::cccc_runtime::RuntimeError::NotFound(_, _)) + )); + + let projected = + || crate::ops::working_state::runtime_actor_fields(&home, &actor, &group.group_id, true); + wait_until("blocked report", || { + projected()["effective_working_state"] == "blocked" + }); + let blocked = projected(); + assert_eq!(blocked["effective_working_reason"], "program_status"); + assert_eq!(blocked["effective_blocked_kind"], "question"); + let ready = + || crate::ops::working_state::ready_for_mail_notice(&home, &group.group_id, &actor.id); + assert!(!ready(), "a blocked program must not admit early Mail"); + + let deliver_by = (chrono::Utc::now() + chrono::Duration::minutes(30)).to_rfc3339(); + let notice = |source: &str| { + let mut notice = Event::new("system.notify", &group.group_id); + notice.by = "system".into(); + notice.data = serde_json::json!({ + "kind":"mail_notice","target_actor_id":actor.id, + "context":{"actor_id":actor.id,"source_event_ids":[source],"deliver_by":deliver_by} + }) + .as_object() + .cloned() + .expect("notice"); + cccc_core::ledger::append( + &store.ledger_path(&group.group_id).expect("ledger"), + ¬ice, + ) + .expect("append notice"); + notice + }; + let submit = |event: &Event| { + controller::submit( + &home, + &group, + &actor, + std::slice::from_ref(event), + "mail waiting", + &AtomicBool::new(false), + &AtomicBool::new(false), + None, + ) + .expect("submit early notice") + }; + let held = notice("mail-1"); + let outcome = submit(&held); + assert_eq!(outcome["outcome"], "withheld", "{outcome}"); + + std::fs::write(temp.path().join("idle"), "").expect("advance to idle"); + wait_until("idle report", || { + projected()["effective_working_state"] == "idle" + }); + assert_eq!(projected()["effective_working_reason"], "program_status"); + assert!(ready(), "an idle program admits early Mail"); + let admitted = notice("mail-2"); + assert_eq!(submit(&admitted)["outcome"], "accepted"); + wait_until("notice written to the PTY", || { + std::fs::read_to_string(&received).is_ok_and(|text| text.contains("mail waiting")) + }); + + super::runtime::stop(&group.group_id, &actor.id).expect("stop"); + controller::finish(&home, ShutdownMode::Stop, "stop".into()).expect("stop owner"); +} diff --git a/crates/cccc-daemon/src/session_owner/protocol.rs b/crates/cccc-daemon/src/session_owner/protocol.rs index d13dccbc0..dfd9b3486 100644 --- a/crates/cccc-daemon/src/session_owner/protocol.rs +++ b/crates/cccc-daemon/src/session_owner/protocol.rs @@ -291,6 +291,9 @@ pub(super) enum TerminalRead { /// The PTY's `(cols, rows)`, which every attachment shows. An older owner /// rejects it, and callers then report no size. Size, + /// The program's latest OSC 7501 self-report. An older owner rejects it, + /// and callers then report no program status. + ProgramStatus, } #[derive(Serialize, Deserialize)] diff --git a/crates/cccc-daemon/src/session_owner/runtime.rs b/crates/cccc-daemon/src/session_owner/runtime.rs index 15e732a17..1c0439cfe 100644 --- a/crates/cccc-daemon/src/session_owner/runtime.rs +++ b/crates/cccc-daemon/src/session_owner/runtime.rs @@ -42,6 +42,7 @@ observe!(last_output() -> Option, super::protocol::TerminalRe observe!(bracketed_paste_enabled() -> bool, super::protocol::TerminalRead::BracketedPaste); observe!(attachment_writable(attachment_id: u64) -> bool, super::protocol::TerminalRead::Writable { attachment_id }); observe!(terminal_size() -> (u16, u16), super::protocol::TerminalRead::Size); +observe!(program_status() -> Option, super::protocol::TerminalRead::ProgramStatus); macro_rules! change { ($name:ident ($($argument:ident : $kind:ty),*) -> $result:ty, $action:expr) => { diff --git a/crates/cccc-runtime/Cargo.toml b/crates/cccc-runtime/Cargo.toml index eca974942..aff3e3d68 100644 --- a/crates/cccc-runtime/Cargo.toml +++ b/crates/cccc-runtime/Cargo.toml @@ -9,6 +9,7 @@ description = "Process and terminal runtime management for CCCC" publish = false [dependencies] +base64.workspace = true cccc-contracts = { package = "cccc-pair-contracts", version = "=0.4.63", path = "../cccc-contracts" } dunce.workspace = true portable-pty.workspace = true diff --git a/crates/cccc-runtime/src/history_access.rs b/crates/cccc-runtime/src/history_access.rs index 11d05723e..2185f412f 100644 --- a/crates/cccc-runtime/src/history_access.rs +++ b/crates/cccc-runtime/src/history_access.rs @@ -1,5 +1,6 @@ use crate::RuntimeError; use crate::output::HistoryPage; +use crate::program_status::ProgramStatus; use crate::registry::{completed_history, lookup, with_session}; use crate::session_history::OutputObservation; @@ -80,6 +81,19 @@ pub fn last_output( .last_output() } +/// What the live session's program last reported about itself over OSC 7501, +/// or `None` before its first report. A new session starts without one. +pub fn program_status( + group_id: &str, + actor_id: &str, +) -> Result, RuntimeError> { + lookup(group_id, actor_id)? + .lock() + .map_err(|_| RuntimeError::Poisoned)? + .history_handle() + .program_status() +} + pub fn active_history_replay( group_id: &str, actor_id: &str, diff --git a/crates/cccc-runtime/src/lib.rs b/crates/cccc-runtime/src/lib.rs index 1e44b81a8..4b8f5dba8 100644 --- a/crates/cccc-runtime/src/lib.rs +++ b/crates/cccc-runtime/src/lib.rs @@ -15,6 +15,9 @@ mod manager; mod native_codex; pub mod process_children; pub mod process_recovery; +mod program_status; +#[cfg(test)] +mod program_status_tests; pub use native_codex::{ NativeCodexSessionInfo, NativeCodexSteerOutcome, native_codex_can_receive, native_codex_receive_state, native_codex_session_info, native_codex_try_steer, @@ -67,7 +70,7 @@ pub use command_session::CommandSession; pub use executable::{prepare_pty_command, resolve_command_executable, resolve_executable_in_path}; pub use history_access::{ active_history_replay, active_history_since, bracketed_paste_enabled, clear, history, - history_since, last_output, retained_history, retained_history_tail, + history_since, last_output, program_status, retained_history, retained_history_tail, }; pub use manager::{ PtyHandoff, PtyHandoffReason, reap, release_startup_input, reset_exited_startup_input, resize, @@ -87,6 +90,7 @@ pub use process_tree::{ background_tokio_command, force_terminate_owned, owned_process_recovery_pending, run_process_watchdog_from_args, }; +pub use program_status::{ProgramBlockedKind, ProgramState, ProgramStatus}; #[cfg(test)] crate::process_watchdog_test_entry!(); diff --git a/crates/cccc-runtime/src/output_reader.rs b/crates/cccc-runtime/src/output_reader.rs index f92eebba6..3b95705ca 100644 --- a/crates/cccc-runtime/src/output_reader.rs +++ b/crates/cccc-runtime/src/output_reader.rs @@ -124,6 +124,23 @@ mod tests { chunks: VecDeque>, } + /// Yields its chunks, then holds the stream open until released. + struct ChunksThenHold { + chunks: VecDeque>, + release: std::sync::mpsc::Receiver<()>, + } + + impl Read for ChunksThenHold { + fn read(&mut self, buffer: &mut [u8]) -> std::io::Result { + let Some(chunk) = self.chunks.pop_front() else { + let _ = self.release.recv(); + return Ok(0); + }; + buffer[..chunk.len()].copy_from_slice(&chunk); + Ok(chunk.len()) + } + } + struct RecordingWriter { bytes: Arc>>, fail: bool, @@ -253,6 +270,49 @@ mod tests { assert_eq!(*written.lock().expect("written"), b"\x1b[5;10R"); } + #[test] + fn program_status_query_is_answered_and_reports_are_recorded() { + let history = SessionHistory::new(None).expect("history"); + let written = Arc::new(Mutex::new(Vec::new())); + let (release, released) = std::sync::mpsc::channel(); + let reader = OutputReader::start( + "program-status-reader".into(), + Box::new(ChunksThenHold { + release: released, + chunks: VecDeque::from([ + b"\x1b]7501;".to_vec(), + b"?\x1b\\\x1b]7501;state=blocked:kind=question".to_vec(), + b":app=claude-code\x07".to_vec(), + ]), + }), + history.clone(), + shared_writer(&written, false), + Arc::new(Mutex::new(())), + ) + .expect("reader"); + + let deadline = Instant::now() + Duration::from_secs(1); + let status = loop { + if let Some(status) = history.program_status().expect("status") { + break status; + } + assert!(Instant::now() < deadline, "report not recorded"); + std::thread::yield_now(); + }; + assert_eq!(status.state, crate::ProgramState::Blocked); + assert_eq!(status.kind, Some(crate::ProgramBlockedKind::Question)); + assert_eq!(status.app.as_deref(), Some("claude-code")); + + release.send(()).expect("release"); + assert!(reader.finish().expect("finish")); + assert_eq!( + *written.lock().expect("written"), + b"\x1b]7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth\x1b\\" + ); + // The launch ended with its output: its program no longer reports. + assert_eq!(history.program_status().expect("status"), None); + } + #[test] fn contended_terminal_response_does_not_block_output_drain() { let history = SessionHistory::new(None).expect("history"); diff --git a/crates/cccc-runtime/src/program_status.rs b/crates/cccc-runtime/src/program_status.rs new file mode 100644 index 000000000..70ec1f47d --- /dev/null +++ b/crates/cccc-runtime/src/program_status.rs @@ -0,0 +1,443 @@ +//! OSC 7501 Program Status Protocol: a program in the terminal reports its own +//! state (idle, working, done, blocked, error) as an escape sequence in its +//! output. This module parses those reports and keeps the latest root record of +//! one PTY launch. It never infers state from any other output. +//! +//! Wire grammar ported from Orca (MIT, Copyright (c) 2026 Lovecast Inc.), +//! `src/shared/program-status/{protocol,osc-scanner}.ts`; specification: +//! . + +use base64::Engine as _; +use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; +use serde::{Deserialize, Serialize}; +use std::time::SystemTime; + +/// The bytes a supporting terminal answers to the `OSC 7501 ; ?` query. The +/// explicit lists let a later-revision program see which values this terminal +/// accepts. +pub(crate) const QUERY_REPLY: &[u8] = + b"\x1b]7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth\x1b\\"; + +const OSC_PREFIX: &[u8] = b"7501;"; +const PROMPT_START: &[u8] = b"133;A"; +/// The whole sequence is capped at 4096 bytes; `ESC ] 7501 ;` and `ESC \` +/// take 9 of them. +const MAX_BODY_BYTES: usize = 4087; +/// Longest OSC payload (between `ESC ]` and its terminator) worth buffering. +const MAX_PAYLOAD_BYTES: usize = OSC_PREFIX.len() + MAX_BODY_BYTES; +const MAX_KEY_BYTES: usize = 16; +const MAX_APP_BYTES: usize = 32; +const MAX_MSG_ENCODED: usize = 2732; +const MAX_MSG_DECODED: usize = 2048; +const MAX_TITLE_ENCODED: usize = 256; +const MAX_TITLE_DECODED: usize = 192; +const MAX_ID_LENGTH: usize = 128; +const MAX_ID_DEPTH: usize = 8; +const MAX_ID_SEGMENT: usize = 32; + +/// What a program last reported about itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProgramState { + Idle, + Working, + Done, + Blocked, + Error, +} + +/// Why a blocked program waits for the user. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProgramBlockedKind { + Permission, + Question, + Auth, +} + +/// The latest root record a program reported in the current PTY launch. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProgramStatus { + pub state: ProgramState, + /// Only for `blocked`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, + /// 0-100, only for `working` and `blocked`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub progress: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub app: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Decoded single-line message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, + /// Wall-clock time CCCC read the report. + pub reported_at: SystemTime, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ReportState { + Set(ProgramState), + Clear, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Report { + /// `None` addresses the root record. + pub(crate) id: Option, + pub(crate) state: ReportState, + pub(crate) kind: Option, + pub(crate) progress: Option, + pub(crate) app: Option, + pub(crate) title: Option, + pub(crate) message: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Message { + Query, + Report(Report), +} + +/// True when an OSC payload (between `ESC ]` and its terminator) is the +/// capability query `7501;?`. +pub(crate) fn is_query_payload(payload: &[u8]) -> bool { + payload + .strip_prefix(OSC_PREFIX) + .is_some_and(|body| body.trim_ascii() == b"?") +} + +fn is_value_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b',' | b'+' | b'/' | b'=' | b'-') +} + +fn is_name_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'+' | b'-') +} + +fn valid_id(id: &str) -> bool { + if id.len() > MAX_ID_LENGTH { + return false; + } + let segments = id.split('/').collect::>(); + segments.len() <= MAX_ID_DEPTH + && segments.iter().all(|segment| { + (1..=MAX_ID_SEGMENT).contains(&segment.len()) && segment.bytes().all(is_name_byte) + }) +} + +/// Decoded single-line text, or `None` when the whole report must be dropped. +fn decode_text(encoded: &str, max_decoded: usize) -> Option { + let unpadded = encoded.trim_end_matches('='); + if encoded.len() - unpadded.len() > 2 + || !unpadded + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/')) + || unpadded.len() % 4 == 1 + { + return None; + } + let engine = GeneralPurpose::new( + &base64::alphabet::STANDARD, + GeneralPurposeConfig::new() + .with_decode_padding_mode(DecodePaddingMode::RequireNone) + .with_decode_allow_trailing_bits(true), + ); + let bytes = engine.decode(unpadded).ok()?; + if bytes.len() > max_decoded { + return None; + } + let text = String::from_utf8(bytes).ok()?; + (!text + .chars() + .any(|ch| ch <= '\u{1f}' || ('\u{7f}'..='\u{9f}').contains(&ch))) + .then_some(text) +} + +fn parse_state(value: &str) -> Option { + Some(match value { + "idle" => ReportState::Set(ProgramState::Idle), + "working" => ReportState::Set(ProgramState::Working), + "done" => ReportState::Set(ProgramState::Done), + "blocked" => ReportState::Set(ProgramState::Blocked), + "error" => ReportState::Set(ProgramState::Error), + "clear" => ReportState::Clear, + _ => return None, + }) +} + +fn parse_kind(value: &str) -> Option { + Some(match value { + "permission" => ProgramBlockedKind::Permission, + "question" => ProgramBlockedKind::Question, + "auth" => ProgramBlockedKind::Auth, + _ => return None, + }) +} + +fn parse_progress(value: &str) -> Option { + let digits = value.trim_start_matches('0'); + let digits = if digits.is_empty() && !value.is_empty() { + "0" + } else { + digits + }; + if digits.is_empty() || digits.len() > 3 || !digits.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + digits.parse::().ok().filter(|value| *value <= 100) +} + +/// Parse the body between `OSC 7501 ;` and its terminator. `None` means the +/// sequence is ignored (no state, malformed id, a broken limit). +pub(crate) fn parse_body(body: &[u8]) -> Option { + if body.len() > MAX_BODY_BYTES { + return None; + } + let body = std::str::from_utf8(body).ok()?; + if body.trim() == "?" { + return Some(Message::Query); + } + let mut state = None; + let mut id = None; + let mut kind = None; + let mut progress = None; + let mut app = None; + let mut title = None; + let mut message = None; + for pair in body.split(':') { + let Some((key, value)) = pair.split_once('=') else { + continue; + }; + let (key, value) = (key.trim(), value.trim()); + // A broken cap voids the whole report, even if a valid duplicate follows. + if key.len() > MAX_KEY_BYTES + || (key == "app" && value.len() > MAX_APP_BYTES) + || (key == "msg" && value.len() > MAX_MSG_ENCODED) + || (key == "title" && value.len() > MAX_TITLE_ENCODED) + || (key == "id" && !valid_id(value)) + { + return None; + } + // Malformed pairs are skipped; the rest of the report still applies. + if key.is_empty() + || !key.bytes().all(|byte| byte.is_ascii_lowercase()) + || !value.bytes().all(is_value_byte) + { + continue; + } + match key { + "msg" => message = Some(decode_text(value, MAX_MSG_DECODED)?), + "title" => title = Some(decode_text(value, MAX_TITLE_DECODED)?), + "state" => state = Some(value), + "id" => id = Some(value), + "kind" => kind = Some(value), + "progress" => progress = Some(value), + "app" => app = Some(value), + _ => {} + } + } + let state = parse_state(state?)?; + let live = matches!( + state, + ReportState::Set(ProgramState::Working | ProgramState::Blocked) + ); + Some(Message::Report(Report { + id: id.map(str::to_owned), + kind: (state == ReportState::Set(ProgramState::Blocked)) + .then(|| kind.and_then(parse_kind)) + .flatten(), + progress: live.then(|| progress.and_then(parse_progress)).flatten(), + app: app + .filter(|app| !app.is_empty() && app.bytes().all(is_name_byte)) + .map(str::to_owned), + title: title.filter(|text| !text.is_empty()), + message: message.filter(|text| !text.is_empty()), + state, + })) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum StreamEvent { + Message(Message), + /// A new shell prompt (`OSC 133 ; A`) or a full reset (`ESC c`): the + /// program that reported has ended. + Reset, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ScanState { + Ground, + Escape, + Osc, + OscEscape, + Discard, + DiscardEscape, +} + +/// Stateful scanner over one PTY output stream. Sequences may be split across +/// reads. It only observes; it never alters the stream. +#[derive(Debug)] +pub(crate) struct Scanner { + state: ScanState, + payload: Vec, +} + +impl Default for Scanner { + fn default() -> Self { + Self { + state: ScanState::Ground, + payload: Vec::new(), + } + } +} + +fn may_become_relevant(payload: &[u8]) -> bool { + [OSC_PREFIX, b"133;".as_slice()] + .iter() + .any(|marker| marker.starts_with(payload) || payload.starts_with(marker)) +} + +impl Scanner { + pub(crate) fn process(&mut self, data: &[u8]) -> Vec { + let mut events = Vec::new(); + let mut index = 0; + while index < data.len() { + if self.state == ScanState::Ground { + match data[index..].iter().position(|byte| *byte == 0x1b) { + Some(offset) => index += offset, + None => break, + } + } + self.advance(data[index], &mut events); + index += 1; + } + events + } + + fn advance(&mut self, byte: u8, events: &mut Vec) { + match self.state { + ScanState::Ground => { + if byte == 0x1b { + self.state = ScanState::Escape; + } + } + ScanState::Escape => match byte { + b']' => { + self.payload.clear(); + self.state = ScanState::Osc; + } + b'c' => { + events.push(StreamEvent::Reset); + self.state = ScanState::Ground; + } + 0x1b => {} + _ => self.state = ScanState::Ground, + }, + ScanState::Osc => match byte { + 0x07 => self.finish(events), + 0x1b => self.state = ScanState::OscEscape, + // CAN and SUB abort the sequence. + 0x18 | 0x1a => self.reset(), + _ => { + if self.payload.len() >= MAX_PAYLOAD_BYTES { + self.payload.clear(); + self.state = ScanState::Discard; + return; + } + self.payload.push(byte); + if self.payload.len() <= OSC_PREFIX.len() && !may_become_relevant(&self.payload) + { + self.payload.clear(); + self.state = ScanState::Discard; + } + } + }, + ScanState::OscEscape => { + // As in xterm, an ESC that does not start ST still ends the + // sequence, and then begins the next one. + self.finish(events); + if byte != b'\\' { + self.state = ScanState::Escape; + self.advance(byte, events); + } + } + ScanState::Discard => match byte { + 0x07 | 0x18 | 0x1a => self.reset(), + 0x1b => self.state = ScanState::DiscardEscape, + _ => {} + }, + ScanState::DiscardEscape => { + if byte == b'\\' { + self.reset(); + } else { + self.state = ScanState::Escape; + self.advance(byte, events); + } + } + } + } + + fn finish(&mut self, events: &mut Vec) { + let payload = std::mem::take(&mut self.payload); + self.state = ScanState::Ground; + if let Some(body) = payload.strip_prefix(OSC_PREFIX) { + if let Some(message) = parse_body(body) { + events.push(StreamEvent::Message(message)); + } + } else if payload + .strip_prefix(PROMPT_START) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(b";")) + { + events.push(StreamEvent::Reset); + } + } + + fn reset(&mut self) { + self.payload.clear(); + self.state = ScanState::Ground; + } +} + +/// The root record of one PTY launch, updated from its output. +#[derive(Debug, Default)] +pub(crate) struct ProgramStatusTracker { + scanner: Scanner, + current: Option, +} + +impl ProgramStatusTracker { + pub(crate) fn process(&mut self, data: &[u8], now: SystemTime) { + for event in self.scanner.process(data) { + match event { + StreamEvent::Reset => self.current = None, + StreamEvent::Message(Message::Query) => {} + // Child records do not describe the program itself. + StreamEvent::Message(Message::Report(report)) if report.id.is_some() => {} + StreamEvent::Message(Message::Report(report)) => { + self.current = match report.state { + ReportState::Clear => None, + ReportState::Set(state) => Some(ProgramStatus { + state, + kind: report.kind, + progress: report.progress, + app: report.app, + title: report.title, + message: report.message, + reported_at: now, + }), + }; + } + } + } + } + + pub(crate) fn current(&self) -> Option { + self.current.clone() + } + + pub(crate) fn clear(&mut self) { + self.current = None; + } +} diff --git a/crates/cccc-runtime/src/program_status_tests.rs b/crates/cccc-runtime/src/program_status_tests.rs new file mode 100644 index 000000000..09c682f27 --- /dev/null +++ b/crates/cccc-runtime/src/program_status_tests.rs @@ -0,0 +1,182 @@ +use crate::program_status::{ + Message, ProgramBlockedKind, ProgramState, ProgramStatusTracker, ReportState, parse_body, +}; +use std::time::{Duration, SystemTime}; + +fn track(chunks: &[&[u8]]) -> ProgramStatusTracker { + let mut tracker = ProgramStatusTracker::default(); + for chunk in chunks { + tracker.process(chunk, SystemTime::UNIX_EPOCH); + } + tracker +} + +fn state(chunks: &[&[u8]]) -> Option { + track(chunks).current().map(|status| status.state) +} + +#[test] +fn reports_end_with_bel_or_st() { + assert_eq!( + state(&[b"text\x1b]7501;state=working:app=codex\x07more"]), + Some(ProgramState::Working) + ); + let status = track(&[b"\x1b]7501;state=idle:app=claude-code\x1b\\"]) + .current() + .expect("status"); + assert_eq!(status.state, ProgramState::Idle); + assert_eq!(status.app.as_deref(), Some("claude-code")); + assert_eq!(status.reported_at, SystemTime::UNIX_EPOCH); +} + +#[test] +fn the_latest_report_wins_and_carries_its_report_time() { + let mut tracker = track(&[b"\x1b]7501;state=working\x07"]); + let later = SystemTime::UNIX_EPOCH + Duration::from_secs(60); + tracker.process(b"\x1b]7501;state=done\x1b\\", later); + let status = tracker.current().expect("status"); + assert_eq!(status.state, ProgramState::Done); + assert_eq!(status.reported_at, later); +} + +#[test] +fn a_report_split_across_reads_is_assembled() { + assert_eq!( + state(&[b"\x1b", b"]75", b"01;state=wor", b"king\x1b", b"\\"]), + Some(ProgramState::Working) + ); +} + +#[test] +fn blocked_reports_keep_kind_progress_and_decoded_message() { + // "Trust this folder?" in base64. + let status = track(&[ + b"\x1b]7501;state=blocked:kind=permission:progress=040:app=antigravity:msg=VHJ1c3QgdGhpcyBmb2xkZXI/\x1b\\", + ]) + .current() + .expect("status"); + assert_eq!(status.state, ProgramState::Blocked); + assert_eq!(status.kind, Some(ProgramBlockedKind::Permission)); + assert_eq!(status.progress, Some(40)); + assert_eq!(status.message.as_deref(), Some("Trust this folder?")); + + // Unpadded base64 decodes too ("Sign in required"). + let auth = track(&[b"\x1b]7501;state=blocked:kind=auth:msg=U2lnbiBpbiByZXF1aXJlZA\x07"]) + .current() + .expect("status"); + assert_eq!(auth.kind, Some(ProgramBlockedKind::Auth)); + assert_eq!(auth.message.as_deref(), Some("Sign in required")); +} + +#[test] +fn kind_and_progress_only_apply_to_their_states() { + let status = track(&[b"\x1b]7501;state=idle:kind=auth:progress=50\x07"]) + .current() + .expect("status"); + assert_eq!(status.kind, None); + assert_eq!(status.progress, None); + let over = track(&[b"\x1b]7501;state=working:progress=101\x07"]) + .current() + .expect("status"); + assert_eq!(over.progress, None); +} + +#[test] +fn malformed_reports_are_discarded() { + let working: &[u8] = b"\x1b]7501;state=working\x07"; + for bad in [ + b"\x1b]7501;app=codex\x07".as_slice(), + b"\x1b]7501;state=sleeping\x07", + // Decoded control character (a newline). + b"\x1b]7501;state=idle:msg=YQpi\x07", + // Within the value grammar but not base64. + b"\x1b]7501;state=idle:msg=YQ,b\x07", + // Padding inside the text. + b"\x1b]7501;state=idle:msg=YQ==YQ\x07", + // An impossible base64 length. + b"\x1b]7501;state=idle:msg=QUJDR\x07", + b"\x1b]7501;state=idle:id=a//b\x07", + // CAN aborts the sequence. + b"\x1b]7501;state=idle\x18", + ] { + assert_eq!( + state(&[working, bad]), + Some(ProgramState::Working), + "{}", + String::from_utf8_lossy(bad) + ); + } +} + +#[test] +fn a_sequence_over_the_cap_is_discarded_whole() { + let mut oversize = b"\x1b]7501;state=idle:pad=".to_vec(); + oversize.extend(std::iter::repeat_n(b'a', 4096)); + oversize.push(0x07); + assert_eq!( + state(&[b"\x1b]7501;state=working\x07", &oversize]), + Some(ProgramState::Working) + ); + + let mut at_cap = b"\x1b]7501;state=idle:pad=".to_vec(); + at_cap.extend(std::iter::repeat_n(b'a', 4087 - "state=idle:pad=".len())); + at_cap.extend(b"\x1b\\"); + assert_eq!(at_cap.len(), 4096); + assert_eq!(state(&[&at_cap]), Some(ProgramState::Idle)); +} + +#[test] +fn child_records_do_not_change_the_root_record() { + assert_eq!( + state(&[ + b"\x1b]7501;state=idle\x07", + b"\x1b]7501;state=working:id=agents/reviewer\x07" + ]), + Some(ProgramState::Idle) + ); +} + +#[test] +fn clear_prompt_start_and_full_reset_end_the_record() { + let working: &[u8] = b"\x1b]7501;state=working\x07"; + assert_eq!(state(&[working, b"\x1b]7501;state=clear\x07"]), None); + assert_eq!(state(&[working, b"$ \x1b]133;A\x07"]), None); + assert_eq!(state(&[working, b"\x1b]133;A;cl=m\x1b\\"]), None); + assert_eq!(state(&[working, b"\x1b", b"c"]), None); + // Another semantic mark is not a new prompt. + assert_eq!( + state(&[working, b"\x1b]133;B\x07\x1b]133;AB\x07"]), + Some(ProgramState::Working) + ); +} + +#[test] +fn other_escape_sequences_and_queries_leave_the_record_alone() { + assert_eq!( + state(&[ + b"\x1b]7501;state=idle\x07", + b"\x1b[31mred\x1b]0;title\x07\x1b]8;;https://x\x1b\\link\x1b]7501;?\x1b\\" + ]), + Some(ProgramState::Idle) + ); +} + +#[test] +fn an_unterminated_osc_ends_at_the_next_escape_sequence() { + // As in xterm, ESC that does not start ST ends the OSC. + assert_eq!( + state(&[b"\x1b]7501;state=working\x1b]7501;state=done\x07"]), + Some(ProgramState::Done) + ); +} + +#[test] +fn parser_matches_the_query_and_skips_malformed_pairs() { + assert_eq!(parse_body(b" ? "), Some(Message::Query)); + let Some(Message::Report(report)) = parse_body(b"junk:state=done:BAD=x:app=co dex") else { + panic!("report"); + }; + assert_eq!(report.state, ReportState::Set(ProgramState::Done)); + assert_eq!(report.app, None); + assert_eq!(report.id, None); +} diff --git a/crates/cccc-runtime/src/session_history.rs b/crates/cccc-runtime/src/session_history.rs index 6a4e697c7..c6e67f807 100644 --- a/crates/cccc-runtime/src/session_history.rs +++ b/crates/cccc-runtime/src/session_history.rs @@ -1,5 +1,6 @@ use crate::RuntimeError; use crate::output::{HistoryPage, OutputBuffer}; +use crate::program_status::{ProgramStatus, ProgramStatusTracker}; use crate::terminal_snapshot::TerminalStateMirror; use crate::transcript_archive::{HistoryConfig, TranscriptArchive}; use std::sync::{Arc, Mutex, TryLockError}; @@ -33,6 +34,8 @@ pub struct OutputObservation { #[derive(Clone)] pub(crate) struct SessionHistory { state: Arc>, + /// Kept apart from `state` so status reads never wait behind transcript I/O. + program_status: Arc>, changes: watch::Sender, } @@ -94,6 +97,7 @@ impl SessionHistory { last_output: None, startup_mirror_warning: false, })), + program_status: Arc::default(), changes, }) } @@ -126,7 +130,12 @@ impl SessionHistory { }); } if !data.is_empty() { - state.last_output = Some((Instant::now(), SystemTime::now())); + let now = SystemTime::now(); + state.last_output = Some((Instant::now(), now)); + self.program_status + .lock() + .map_err(|_| RuntimeError::Poisoned)? + .process(data, now); } let responses = state.terminal.process(data); state.output.push(data); @@ -269,6 +278,11 @@ impl SessionHistory { pub(crate) fn seal_output(&self) -> Result<(), RuntimeError> { let mut state = self.state.lock().map_err(|_| RuntimeError::Poisoned)?; state.accepting_output = false; + // The program that reported its status has ended with this launch. + self.program_status + .lock() + .map_err(|_| RuntimeError::Poisoned)? + .clear(); self.changes.send_replace(OutputState { end_cursor: state.output.end_cursor(), closed: true, @@ -292,6 +306,15 @@ impl SessionHistory { })) } + /// The latest root record the program reported over OSC 7501 in this + /// launch, or `None` before its first report and after it ended. + pub(crate) fn program_status(&self) -> Result, RuntimeError> { + self.program_status + .lock() + .map_err(|_| RuntimeError::Poisoned) + .map(|tracker| tracker.current()) + } + pub(crate) fn bracketed_paste_enabled(&self) -> Result { self.state .lock() diff --git a/crates/cccc-runtime/src/terminal_query_responder.rs b/crates/cccc-runtime/src/terminal_query_responder.rs index 8bcce0323..8803f2cb2 100644 --- a/crates/cccc-runtime/src/terminal_query_responder.rs +++ b/crates/cccc-runtime/src/terminal_query_responder.rs @@ -159,6 +159,14 @@ impl TerminalQueryResponder { } fn finish_osc(&mut self, end_offset: usize, responses: &mut Vec) { + if crate::program_status::is_query_payload(&self.osc_payload) + && responses.len() < MAX_RESPONSES_PER_READ + { + responses.push(TerminalQueryResponse { + end_offset, + reply: TerminalQueryReply::Bytes(crate::program_status::QUERY_REPLY.to_vec()), + }); + } append_color_query_responses(&self.osc_payload, end_offset, responses); self.reset(); } @@ -251,6 +259,27 @@ mod tests { ); } + #[test] + fn answers_a_split_program_status_query_with_both_terminators() { + let mut responder = TerminalQueryResponder::default(); + let reply = crate::program_status::QUERY_REPLY.to_vec(); + + assert!(responder.process(b"\x1b]7501").is_empty()); + assert_eq!( + response_data(responder.process(b";?\x1b\\")), + std::slice::from_ref(&reply) + ); + assert_eq!( + response_data(responder.process(b"\x1b]7501;?\x07")), + [reply] + ); + assert!( + responder + .process(b"\x1b]7501;state=idle\x07\x1b]7501;??\x07") + .is_empty() + ); + } + #[test] fn detects_a_split_private_cursor_position_query() { let mut responder = TerminalQueryResponder::default(); diff --git a/docs/guide/runtimes.md b/docs/guide/runtimes.md index 720d56461..8e0d751ca 100644 --- a/docs/guide/runtimes.md +++ b/docs/guide/runtimes.md @@ -935,9 +935,29 @@ The global entry uses `cccc mcp` on the agent's PATH and inherits instance and agent identity, so different installations do not pin each other to one launcher. New Antigravity native PTY launches do not install lifecycle hooks into the -user's global Antigravity hooks configuration and use the ordinary Mail notice -delay. A retained PTY that already carries a matching hook binding continues -reporting its hook state until its process restarts. +user's global Antigravity hooks configuration. Antigravity reports its working, +idle and blocked state through the OSC 7501 Program Status Protocol instead, so +an idle report admits early Mail notices like any other PTY agent that speaks it. +A retained PTY that already carries a matching hook binding continues reporting +its hook state until its process restarts. + +### Terminal agents that report their own state (OSC 7501) + +Terminal agents that speak the Program Status Protocol (OSC 7501) report +whether they are working, idle, done, blocked on a permission, question or +sign-in, or failed, in their own terminal output. Claude Code (2.1.295 and +later), Codex and Antigravity do; any other program that speaks it works the +same way. CCCC answers the protocol's capability query for every terminal and +shows the reported state without any configuration: the agent reads as working, +idle or "needs input" (with the agent's own message), and an idle or finished +agent receives early Mail notices just like an idle managed session. A blocked +agent does not. + +The state belongs to one launch: a restarted agent starts without one, and a +new shell prompt in the terminal clears it. Without these reports, terminal +agents keep the conservative "waiting" state, because CCCC never infers idle +from what a terminal prints. A managed session or Antigravity hook binding, +when present, takes precedence over the terminal report. The complete CCCC bootstrap accompanies the first native task in one submission, including after a process restart. Antigravity allows a brief, cancellable diff --git a/docs/standards/CCCC_DAEMON_IPC_V1.md b/docs/standards/CCCC_DAEMON_IPC_V1.md index 2cbd9d9ef..52f7ecfab 100644 --- a/docs/standards/CCCC_DAEMON_IPC_V1.md +++ b/docs/standards/CCCC_DAEMON_IPC_V1.md @@ -4663,6 +4663,73 @@ Process liveness or a last message timestamp MUST NOT establish idle state or its duration. Existing managed-session and Dots execution observations keep precedence over this fallback. +##### Normalized agent status + +Every Actor projection (`actor_list`, `actor.activity`, Group runtime status) +carries one runtime-agnostic status. Consumers (Web, MCP, IM) MUST be able to +present it without knowing the Actor's runtime: + +```ts +{ + effective_working_state: "stopped" | "idle" | "working" | "waiting" | "blocked" | "error" | "unknown" | string; + effective_working_reason: string; // the source's detail, e.g. "program_status" + effective_working_updated_at: string | null; // when the source last reported + effective_active_task_id: string | null; + effective_status_source: "managed_session" | "antigravity_hook" | "program_status" | "dots" | "none"; + effective_blocked_kind: "permission" | "question" | "auth" | null; // only while blocked + effective_status_message: string | null; // the agent's own one-line message + effective_progress: number | null; // 0-100, only while working or blocked +} +``` + +`effective_status_source="none"` means no structured source reported and the +state is a conservative fallback (`stopped`, `pty_running_state_unknown`, +`headless_running_state_unknown`, `runtime_owner_unavailable`). Any other source +is authoritative: clients MUST NOT override it with terminal-output heuristics. +A source's own state spelling outside the listed vocabulary is passed through +verbatim. The daemon resolves the status in one place, in this precedence: + +1. not running: `stopped` / `runner_not_running`; +2. a live managed session's state, or `managed_agent_session_pending` while it registers; +3. a retained Antigravity PTY's lifecycle hook (`antigravity_hook`); +4. the PTY program's own OSC 7501 report (`program_status`, below); +5. `managed_agent_session_pending` for an Actor configured for a managed session; +6. Dots event turns (`dots_event_turn` / `dots_state_unavailable`); +7. `unknown` / `headless_running_state_unknown` for a headless surface, else + `waiting` / `pty_running_state_unknown`. + +The new normalized fields are additive. A client that predates them reads the +same `effective_working_state` / `effective_working_reason` as before. + +##### PTY program status (OSC 7501) + +A program in a primary PTY MAY report its own state with the Program Status +Protocol (`ESC ] 7501 ; :… ST`, ST being `ESC \` or +BEL; specification: superlogical.com/rex/docs/build/program-status). This is +the program's explicit self-report, not an inference from output; ordinary +output still never establishes idle state. The runtime that holds the PTY (the +session owner when one holds it) MUST: + +- answer the query `ESC ] 7501 ; ? ST` with exactly + `ESC ] 7501 ; ?:states=idle,working,done,blocked,error:kinds=permission,question,auth ESC \`, + without a browser attachment, within the per-read terminal response limit; +- keep only the latest root record (a report without `id`); child records + (`id=…`) do not change it; `state=clear`, a new shell prompt + (`ESC ] 133 ; A`) or a full reset (`ESC c`) removes it; +- discard a sequence over 4096 bytes, without a valid `state`, with a malformed + `id`, or whose base64 `msg`/`title` is not single-line UTF-8 text; +- keep the record per PTY launch: a new launch starts without one, and it ends + with the launch's output. + +The projection maps `working` to `working`, `blocked` to `blocked` (with +`effective_blocked_kind` and the decoded `msg` as `effective_status_message`), +`idle` and `done` to `idle`, and `error` to `error`; +`effective_working_reason="program_status"` and `effective_working_updated_at` +is the time the runtime read the report. `progress` is exposed as +`effective_progress`. The daemon reads the record through the owner's +`terminal_read` with `read.kind="program_status"`; an owner that predates this +read rejects it, and the Actor then has no program status. + A primary PTY for a runtime with a startup input gate may publish `runtime_startup_input: { generation: string; manual_release?: true }` while its first automatic input is waiting for the native chat input region. The generation identifies the @@ -7190,7 +7257,9 @@ earliest eligible deadline. New Mail does not reset it. Broadcast-like Mail remains visible in the Inbox but does not start an active runtime notice timer. An enabled running actor whose managed Runtime or existing Antigravity lifecycle -binding positively reports idle may receive one content-free +binding positively reports idle, or whose PTY program reports over OSC 7501 that +its turn ended (`idle`, `done` or `error`; never `working` or `blocked`), may +receive one content-free `system.notify(kind="mail_notice")` after `min(mail_notice_idle_after_seconds, mail_notice_after_seconds)`. When Mail is written while a concrete recipient reports idle, that notice is issued @@ -7199,11 +7268,14 @@ tick, rather than after the idle delay or at the next tick; the write issues only Mail notices, and only for that Mail's recipients. Working or unknown Runtime states use `mail_notice_after_seconds`; native PTY output is not an idle detector. New Antigravity PTY launches skip lifecycle hook installation -and launch binding and use ordinary Mail timing. A retained Antigravity PTY +and launch binding; their idle state comes from OSC 7501 reports +(`effective_working_reason="program_status"`). A retained Antigravity PTY with an existing matching binding can still report `effective_working_reason="antigravity_hook"` until the process restarts. Before PTY or managed submission, early Mail notices whose `deliver_by` deadline -has not elapsed are withheld if the recipient is no longer idle. Zero for the +has not elapsed are withheld if the recipient is no longer idle; for a PTY this +recheck reads the hook binding or program status of the exact launch that would +receive the notice. Zero for the idle delay disables this early notice, including the one issued as Mail is written; zero for the ordinary delay disables all Mail notices. Both timers retain the batch's diff --git a/web/src/components/AgentTab.tsx b/web/src/components/AgentTab.tsx index e72037594..ac5a740bf 100644 --- a/web/src/components/AgentTab.tsx +++ b/web/src/components/AgentTab.tsx @@ -457,6 +457,10 @@ export function AgentTab({ if (workingState === UNOBSERVABLE_WORKING_STATE) return t("statusUnknown"); if (!isRunning) return t("stopped"); if (workingState === "error") return t("common:error"); + if (workingState === "blocked") + return actor.effective_blocked_kind + ? t(`blockedKind.${actor.effective_blocked_kind}`, { defaultValue: t("blocked") }) + : t("blocked"); if (workingState === "working" || workingState === "waiting" || workingState === "stuck") return t(workingState); return t("running"); @@ -480,6 +484,7 @@ export function AgentTab({ // Why the status is what it is; the daemon's diagnostic names the next step when it // could not observe the agent. const runtimeStatusDetail = [ + !isEventActor && actor.effective_status_message, !isEventActor && actor.effective_working_reason, !isEventActor && actor.runtime_observation_error, ] @@ -798,7 +803,10 @@ export function AgentTab({ ? runtimeStatusText : !isHeadless && connectionStatus !== "connected" ? t(connectionStatus === "disconnected" ? "connectionLost" : "chat:workView.connecting") - : workingState === "waiting" || workingState === "stuck" || workingState === "error" + : workingState === "waiting" || + workingState === "blocked" || + workingState === "stuck" || + workingState === "error" ? runtimeStatusText : !isHeadless && terminalReady && !terminalWritable ? t("readOnlyConnection") diff --git a/web/src/i18n/locales/en/actors.json b/web/src/i18n/locales/en/actors.json index 0e94d16b6..be7ee07e6 100644 --- a/web/src/i18n/locales/en/actors.json +++ b/web/src/i18n/locales/en/actors.json @@ -6,6 +6,12 @@ "working": "Working", "waiting": "Waiting", "stuck": "Stuck", + "blocked": "Needs input", + "blockedKind": { + "permission": "Needs permission", + "question": "Has a question", + "auth": "Needs sign-in" + }, "stopped": "Stopped", "statusUnknown": "Unknown", "custom": "Custom", diff --git a/web/src/i18n/locales/ja/actors.json b/web/src/i18n/locales/ja/actors.json index af1d605b0..c3fce2bee 100644 --- a/web/src/i18n/locales/ja/actors.json +++ b/web/src/i18n/locales/ja/actors.json @@ -6,6 +6,8 @@ "working": "作業中", "waiting": "待機中", "stuck": "停止気味", + "blocked": "入力待ち", + "blockedKind": { "permission": "許可待ち", "question": "質問待ち", "auth": "サインインが必要" }, "stopped": "停止済み", "statusUnknown": "状態不明", "custom": "カスタム", diff --git a/web/src/i18n/locales/zh/actors.json b/web/src/i18n/locales/zh/actors.json index 65dbfd85d..a820cd279 100644 --- a/web/src/i18n/locales/zh/actors.json +++ b/web/src/i18n/locales/zh/actors.json @@ -6,6 +6,8 @@ "working": "工作中", "waiting": "等待中", "stuck": "卡住了", + "blocked": "等待输入", + "blockedKind": { "permission": "等待授权", "question": "等待回答", "auth": "需要登录" }, "stopped": "已停止", "statusUnknown": "状态未知", "custom": "自定义", diff --git a/web/src/stores/groupStoreTypes.ts b/web/src/stores/groupStoreTypes.ts index 45c26d351..2d4e012ad 100644 --- a/web/src/stores/groupStoreTypes.ts +++ b/web/src/stores/groupStoreTypes.ts @@ -118,6 +118,10 @@ export interface GroupState { effective_working_reason?: string; effective_working_updated_at?: string | null; effective_active_task_id?: string | null; + effective_status_source?: string; + effective_blocked_kind?: string | null; + effective_status_message?: string | null; + effective_progress?: number | null; runtime_session_status?: string | null; runtime_session_resume_eligible?: boolean | null; runtime_session_last_resume_error?: string | null; diff --git a/web/src/stores/useGroupStore.ts b/web/src/stores/useGroupStore.ts index f3107ae5e..0c0836cc1 100644 --- a/web/src/stores/useGroupStore.ts +++ b/web/src/stores/useGroupStore.ts @@ -682,6 +682,8 @@ export const useGroupStore = create((set, get) => ({ !!u && Object.prototype.hasOwnProperty.call(u, "runtime_session_resume_eligible"); const hasRuntimeSessionLastResumeError = !!u && Object.prototype.hasOwnProperty.call(u, "runtime_session_last_resume_error"); + const hasNormalizedStatus = + !!u && Object.prototype.hasOwnProperty.call(u, "effective_status_source"); if ( u && (a.idle_seconds !== (u.idle_seconds ?? null) || @@ -690,6 +692,11 @@ export const useGroupStore = create((set, get) => ({ a.effective_working_reason !== u.effective_working_reason || a.effective_working_updated_at !== (u.effective_working_updated_at ?? null) || a.effective_active_task_id !== (u.effective_active_task_id ?? null) || + (hasNormalizedStatus && + (a.effective_status_source !== u.effective_status_source || + (a.effective_blocked_kind ?? null) !== (u.effective_blocked_kind ?? null) || + (a.effective_status_message ?? null) !== (u.effective_status_message ?? null) || + (a.effective_progress ?? null) !== (u.effective_progress ?? null))) || (hasRuntimeSessionStatus && (a.runtime_session_status ?? null) !== (u.runtime_session_status ?? null)) || (hasRuntimeSessionResumeEligible && @@ -709,6 +716,15 @@ export const useGroupStore = create((set, get) => ({ effective_working_reason: u.effective_working_reason, effective_working_updated_at: u.effective_working_updated_at ?? null, effective_active_task_id: u.effective_active_task_id ?? null, + // The normalized status fields arrive together from daemons that publish them. + ...(hasNormalizedStatus + ? { + effective_status_source: u.effective_status_source, + effective_blocked_kind: u.effective_blocked_kind ?? null, + effective_status_message: u.effective_status_message ?? null, + effective_progress: u.effective_progress ?? null, + } + : {}), // Present only while the daemon cannot observe the agent; cleared otherwise. runtime_observation_error: u.runtime_observation_error, ...(hasRuntimeSessionStatus diff --git a/web/src/types.ts b/web/src/types.ts index 248ecbf80..f6699827f 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -387,10 +387,24 @@ export type Actor = { /** The configured runtime or a retained running session uses a retired runtime. */ runtime_retired?: true; idle_seconds?: number | null; // Legacy idle duration, independent of terminal output activity. - effective_working_state?: "stopped" | "idle" | "working" | "waiting" | "stuck" | string; + effective_working_state?: + | "stopped" + | "idle" + | "working" + | "waiting" + | "blocked" + | "stuck" + | string; effective_working_reason?: string; effective_working_updated_at?: string | null; effective_active_task_id?: string | null; + /** Source of the working state: "managed_session", "antigravity_hook", "program_status", "dots" or "none" (a fallback). */ + effective_status_source?: string; + /** While blocked: "permission", "question" or "auth". */ + effective_blocked_kind?: string | null; + /** The agent's own one-line status message, when it reported one. */ + effective_status_message?: string | null; + effective_progress?: number | null; /** Set when the daemon could not observe this agent ("unknown" working state, no `running`). */ runtime_observation_error?: string; command?: string[]; @@ -722,10 +736,24 @@ export type ActorRuntimeState = { runner_effective?: string; running?: boolean; idle_seconds?: number | null; - effective_working_state?: "stopped" | "idle" | "working" | "waiting" | "stuck" | string; + effective_working_state?: + | "stopped" + | "idle" + | "working" + | "waiting" + | "blocked" + | "stuck" + | string; effective_working_reason?: string; effective_working_updated_at?: string | null; effective_active_task_id?: string | null; + /** Source of the working state: "managed_session", "antigravity_hook", "program_status", "dots" or "none" (a fallback). */ + effective_status_source?: string; + /** While blocked: "permission", "question" or "auth". */ + effective_blocked_kind?: string | null; + /** The agent's own one-line status message, when it reported one. */ + effective_status_message?: string | null; + effective_progress?: number | null; }; export type RuntimeInfo = { diff --git a/web/src/utils/runtimeRingTone.test.ts b/web/src/utils/runtimeRingTone.test.ts new file mode 100644 index 000000000..34609cb0a --- /dev/null +++ b/web/src/utils/runtimeRingTone.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { getRuntimeRingTone } from "./runtimeRingTone"; + +describe("runtime ring tone", () => { + it("asks for attention while a running agent reports that it is blocked", () => { + const actor = { id: "peer1", runtime: "custom", runner: "pty", runner_effective: "pty" }; + expect(getRuntimeRingTone({ actor }, true, "blocked")).toBe("attention"); + expect(getRuntimeRingTone({ actor }, true, "idle")).toBe("idle"); + expect(getRuntimeRingTone({ actor }, false, "blocked")).toBe("stopped"); + }); +}); diff --git a/web/src/utils/runtimeRingTone.ts b/web/src/utils/runtimeRingTone.ts index e3d772484..a5eb39129 100644 --- a/web/src/utils/runtimeRingTone.ts +++ b/web/src/utils/runtimeRingTone.ts @@ -31,6 +31,8 @@ export function getRuntimeRingTone( .toLowerCase(); // The daemon could not observe this agent: neither running nor stopped. if (actorState === UNOBSERVABLE_WORKING_STATE) return "attention"; + // The agent itself reported that it waits for the user. + if (isRunning && actorState === "blocked") return "attention"; // Managed runtimes expose the current daemon-owned state. Task history can // retain an older outcome after recovery and must not override this ring. if (hasManagedRuntimeOutput(item.actor)) { diff --git a/web/src/utils/terminalWorkingState.test.ts b/web/src/utils/terminalWorkingState.test.ts index 26dbe700b..cca79e76f 100644 --- a/web/src/utils/terminalWorkingState.test.ts +++ b/web/src/utils/terminalWorkingState.test.ts @@ -67,6 +67,27 @@ describe("terminal working state", () => { ).toBe("working"); }); + it("keeps a state the agent reported itself over terminal output heuristics", () => { + const now = Date.now(); + const reported = (state: string, source: string) => ({ + running: true, + runner: "pty", + effective_working_state: state, + effective_working_reason: source === "none" ? "pty_running_state_unknown" : "program_status", + effective_status_source: source, + }); + const working = { kind: "working_output" as const, updatedAt: now }; + const prompt = { kind: "idle_prompt" as const, updatedAt: now }; + expect(getActorDisplayWorkingState(reported("idle", "program_status"), working, now)).toBe( + "idle", + ); + expect(getActorDisplayWorkingState(reported("blocked", "program_status"), prompt, now)).toBe( + "blocked", + ); + // A fallback state still yields to what the terminal shows. + expect(getActorDisplayWorkingState(reported("waiting", "none"), working, now)).toBe("working"); + }); + it("detects a prompt when a terminal status line follows it", () => { expect( isTerminalPromptVisible( diff --git a/web/src/utils/terminalWorkingState.ts b/web/src/utils/terminalWorkingState.ts index 55fbd8414..13e5f6210 100644 --- a/web/src/utils/terminalWorkingState.ts +++ b/web/src/utils/terminalWorkingState.ts @@ -214,8 +214,18 @@ export type ActorWorkingStateInput = { runtime_state_source?: string; effective_working_state?: string; effective_working_reason?: string; + effective_status_source?: string; }; +/** True when a structured source (not a fallback) established the daemon's working state, + * so terminal output heuristics must not override it. */ +export function hasObservedWorkingState(actor: { effective_status_source?: string }): boolean { + const source = String(actor.effective_status_source || "") + .trim() + .toLowerCase(); + return source !== "" && source !== "none"; +} + /** Display state of an agent the daemon could not observe at all, because the process that * holds it was unavailable. Unlike the daemon's "unknown" turn state of a running agent, it * says neither running nor stopped. */ @@ -250,7 +260,8 @@ export function getActorDisplayWorkingState( effectiveRunner === "headless" || stateSource === "managed_session" || stateSource === "app_server" || - workingReason === "antigravity_hook" + workingReason === "antigravity_hook" || + hasObservedWorkingState(actor) ) { return backendState; } diff --git a/web/tests/stores/useGroupStore.test.ts b/web/tests/stores/useGroupStore.test.ts index 1810d4164..b785d4be9 100644 --- a/web/tests/stores/useGroupStore.test.ts +++ b/web/tests/stores/useGroupStore.test.ts @@ -718,6 +718,40 @@ describe("useGroupStore actors fetch policy", () => { ]); }); + it("updateActorActivity follows a blocked kind and message the agent reported", () => { + const reported = (kind: string | null, message: string | null) => ({ + id: "peer-1", + running: true, + idle_seconds: null, + effective_working_state: "blocked", + effective_working_reason: "program_status", + effective_working_updated_at: "2026-11-30T00:00:00Z", + effective_active_task_id: null, + effective_status_source: "program_status", + effective_blocked_kind: kind, + effective_status_message: message, + effective_progress: null, + }); + useGroupStore.setState({ actors: [{ id: "peer-1", running: true }] }); + + useGroupStore.getState().updateActorActivity([reported("auth", "Sign in required")], "g-demo"); + expect(useGroupStore.getState().actors[0]).toMatchObject({ + effective_working_state: "blocked", + effective_status_source: "program_status", + effective_blocked_kind: "auth", + effective_status_message: "Sign in required", + }); + + // Only the kind and message change; the state and reason stay the same. + useGroupStore + .getState() + .updateActorActivity([reported("permission", "Trust this folder?")], "g-demo"); + expect(useGroupStore.getState().actors[0]).toMatchObject({ + effective_blocked_kind: "permission", + effective_status_message: "Trust this folder?", + }); + }); + it("updateActorActivity merges internal runtime actor state", () => { useGroupStore.setState({ selectedGroupId: "g-demo",