diff --git a/Cargo.lock b/Cargo.lock index 1f0f2b414e..6a185657f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5508,6 +5508,7 @@ dependencies = [ "openshell-ocsf", "openshell-ocsf-validate", "openshell-sandbox-backend", + "prost-types", "rand 0.10.2", "russh", "rustix 1.1.6", diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 8fc1a33116..243a384482 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -1842,6 +1842,7 @@ enum SandboxCommands { /// Connect to a sandbox. /// /// When no name is given, reconnects to the last-used sandbox. + /// A sandbox the gateway stopped while idle is started first. /// Press Ctrl-D or Ctrl-P Ctrl-Q to disconnect without terminating the main process. #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] Connect { @@ -3800,6 +3801,8 @@ async fn run_async() -> Result<()> { } SandboxCommands::Connect { name, editor } => { let name = resolve_sandbox_name(name, &ctx.name, &cli.workspace)?; + run::start_if_idle_stopped(endpoint, &name, &cli.workspace, &tls) + .await?; if let Some(editor) = editor.map(Into::into) { run::sandbox_connect_editor( endpoint, diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index dafc10efba..d6af3cb4f4 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -4172,6 +4172,53 @@ pub async fn sandbox_start( Ok(()) } +/// Start a sandbox that the gateway stopped because its program sat idle, so +/// a connect can proceed. Any other phase is left for the connect to report. +pub async fn start_if_idle_stopped( + server: &str, + name: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let sandbox = client + .get_sandbox(GetSandboxRequest { + name: name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + workspace.to_string(), + )), + }) + .await + .into_diagnostic()? + .into_inner() + .sandbox; + let Some(mut sandbox) = sandbox else { + return Ok(()); + }; + if sandbox.idle_stopping() { + eprintln!("Sandbox {name} is stopping while idle; starting it once it stops"); + // The stop can roll back to Ready, or another client can restart the + // sandbox before this watch opens, so wait for it to leave Stopping + // rather than for Stopped. + sandbox = wait_while_lifecycle_phase(&mut client, sandbox, SandboxPhase::Stopping).await?; + match SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown) { + SandboxPhase::Ready => return Ok(()), + SandboxPhase::Starting => { + wait_for_lifecycle_phase(&mut client, sandbox, SandboxPhase::Ready).await?; + return Ok(()); + } + _ if sandbox.idle_stopped() => {} + // Any other phase is for connect to report. + _ => return Ok(()), + } + } else if sandbox.idle_stopped() { + eprintln!("Sandbox {name} was stopped while idle; starting it"); + } else { + return Ok(()); + } + sandbox_start(server, name, workspace, tls).await +} + /// Suspend a ready sandbox, retaining its memory state, and wait until it is suspended. pub async fn sandbox_suspend( server: &str, @@ -4288,7 +4335,46 @@ async fn wait_for_lifecycle_phase( if let Some(err) = lifecycle_phase_error(&sandbox, target, current) { return Err(err); } + watch_until( + client, + &sandbox, + &format!("reach {target:?}"), + |sandbox, phase| { + if phase == target { + return Ok(true); + } + lifecycle_phase_error(sandbox, target, phase).map_or(Ok(false), Err) + }, + ) + .await +} +/// Wait until the sandbox leaves `phase`, returning its first other phase. +async fn wait_while_lifecycle_phase( + client: &mut crate::tls::GrpcClient, + sandbox: Sandbox, + phase: SandboxPhase, +) -> Result { + if sandbox.phase() != phase as i32 { + return Ok(sandbox); + } + watch_until( + client, + &sandbox, + &format!("leave {phase:?}"), + |_, current| Ok(current != phase), + ) + .await +} + +/// Watch `sandbox` until `done` accepts a snapshot, within the lifecycle +/// timeout. +async fn watch_until( + client: &mut crate::tls::GrpcClient, + sandbox: &Sandbox, + goal: &str, + mut done: impl FnMut(&Sandbox, SandboxPhase) -> Result, +) -> Result { let timeout = Duration::from_secs( std::env::var("OPENSHELL_LIFECYCLE_TIMEOUT") .ok() @@ -4321,7 +4407,7 @@ async fn wait_for_lifecycle_phase( let remaining = deadline.saturating_duration_since(Instant::now()); if remaining.is_zero() { return Err(miette!( - "timed out after {}s waiting for sandbox to reach {target:?}", + "timed out after {}s waiting for sandbox to {goal}", timeout.as_secs() )); } @@ -4329,22 +4415,19 @@ async fn wait_for_lifecycle_phase( .await .map_err(|_| { miette!( - "timed out after {}s waiting for sandbox to reach {target:?}", + "timed out after {}s waiting for sandbox to {goal}", timeout.as_secs() ) })? - .ok_or_else(|| miette!("sandbox watch ended before reaching {target:?}"))? + .ok_or_else(|| miette!("sandbox watch ended before the sandbox could {goal}"))? .into_diagnostic()?; if let Some(openshell_core::proto::sandbox_stream_event::Payload::Sandbox(sandbox)) = event.payload { let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); - if phase == target { + if done(&sandbox, phase)? { return Ok(sandbox); } - if let Some(err) = lifecycle_phase_error(&sandbox, target, phase) { - return Err(err); - } } } } diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 6608e54b96..87f911a0e0 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -91,6 +91,11 @@ struct SandboxState { template_get_requests: Arc>>, template_list_requests: Arc>>, template_delete_requests: Arc>>, + /// Replace the default Ready `GetSandbox` response. + get_sandbox_response: Arc>>, + /// Replace every `WatchSandbox` stream with these status snapshots. + watch_snapshots: Arc>>>, + start_requests: Arc, } #[derive(Clone, Default)] @@ -173,6 +178,17 @@ impl OpenShell for TestOpenShell { })) } + async fn start_sandbox( + &self, + _request: tonic::Request, + ) -> Result, Status> { + self.state.start_requests.fetch_add(1, Ordering::SeqCst); + Ok(Response::new(SandboxResponse { + sandbox: Some(lifecycle_sandbox(SandboxPhase::Starting, "Starting")), + ..Default::default() + })) + } + async fn stop_sandbox( &self, _request: tonic::Request, @@ -194,6 +210,13 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { + let response = self.state.get_sandbox_response.lock().await.clone(); + if let Some(sandbox) = response { + return Ok(Response::new(SandboxResponse { + sandbox: Some(sandbox), + ..Default::default() + })); + } let request = request.into_inner(); let name = request.name; let mut sandbox = Sandbox { @@ -547,6 +570,26 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result>, Status> { + let snapshots = self.state.watch_snapshots.lock().await.clone(); + if let Some(snapshots) = snapshots { + let (tx, rx) = mpsc::channel(snapshots.len().max(1)); + tokio::spawn(async move { + for sandbox in snapshots { + let event = SandboxStreamEvent { + payload: Some(sandbox_stream_event::Payload::Sandbox(sandbox)), + ..Default::default() + }; + if tx.send(Ok(event)).await.is_err() { + return; + } + } + // Keep the stream open, as a live watch would. + tx.closed().await; + }); + return Ok(Response::new(Box::pin( + tokio_stream::wrappers::ReceiverStream::new(rx), + ))); + } let request = request.into_inner(); let sandbox_id = format!("id-{}", request.sandbox); let (tx, rx) = mpsc::channel(4); @@ -1321,6 +1364,93 @@ fn test_config() -> run::SandboxCreateConfig<'static> { } } +/// A sandbox named "idle-wake" in `phase` with Ready condition `reason`. +fn lifecycle_sandbox(phase: SandboxPhase, reason: &str) -> Sandbox { + Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "id-idle-wake".into(), + name: "idle-wake".into(), + workspace: "default".into(), + ..Default::default() + }), + status: Some(SandboxStatus { + phase: phase as i32, + conditions: vec![SandboxCondition { + r#type: "Ready".into(), + status: if phase == SandboxPhase::Ready { + "True".into() + } else { + "False".into() + }, + reason: reason.into(), + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + } +} + +/// Connect during an in-flight idle stop waits for the sandbox to leave +/// `Stopping`. It connects to a sandbox that came back `Ready` or `Starting` +/// without another start, and starts it only once it is `IdleStopped`. +#[tokio::test] +async fn connect_during_an_idle_stop_waits_for_the_stop_to_settle() { + let server = run_server().await; + let tls = test_tls(&server); + let config_dir = helpers::tempdir().unwrap(); + let stopping = lifecycle_sandbox(SandboxPhase::Stopping, "IdleStopping"); + for (snapshots, starts) in [ + // The stop rolled back, or another client already restarted it. + ( + vec![lifecycle_sandbox(SandboxPhase::Ready, "DependenciesReady")], + 0, + ), + ( + vec![ + lifecycle_sandbox(SandboxPhase::Starting, "Starting"), + lifecycle_sandbox(SandboxPhase::Ready, "DependenciesReady"), + ], + 0, + ), + // The idle stop settled; connect starts the sandbox once. + ( + vec![ + lifecycle_sandbox(SandboxPhase::Stopped, "IdleStopped"), + lifecycle_sandbox(SandboxPhase::Ready, "DependenciesReady"), + ], + 1, + ), + ] { + server + .openshell + .state + .start_requests + .store(0, Ordering::SeqCst); + *server.openshell.state.get_sandbox_response.lock().await = Some(stopping.clone()); + *server.openshell.state.watch_snapshots.lock().await = Some(snapshots); + Environment::new() + .set("XDG_CONFIG_HOME", config_dir.path()) + .run_async(async { + tokio::time::timeout( + Duration::from_secs(5), + run::start_if_idle_stopped(&server.endpoint, "idle-wake", "default", &tls), + ) + .await + .expect("connect must not wait for a phase the sandbox already left") + .expect("connect proceeds"); + assert_eq!( + server.openshell.state.start_requests.load(Ordering::SeqCst), + starts, + "starts issued for this case" + ); + }) + .await; + } + *server.openshell.state.get_sandbox_response.lock().await = None; + *server.openshell.state.watch_snapshots.lock().await = None; +} + #[tokio::test] async fn sandbox_stop_accepts_terminal_results_without_waiting_for_stopped() { let server = run_server().await; diff --git a/crates/openshell-core/src/metadata.rs b/crates/openshell-core/src/metadata.rs index 7bc4624ae3..6dc0ce8ede 100644 --- a/crates/openshell-core/src/metadata.rs +++ b/crates/openshell-core/src/metadata.rs @@ -84,7 +84,38 @@ impl ObjectWorkspace for Sandbox { } } +/// Ready condition reason of a sandbox stopped because its terminal program +/// waited on the user longer than the sandbox's idle timeout. +pub const IDLE_STOPPED_REASON: &str = "IdleStopped"; + +/// Ready condition reason of a sandbox whose idle stop is still in flight. +pub const IDLE_STOPPING_REASON: &str = "IdleStopping"; + impl Sandbox { + /// Whether the gateway stopped this sandbox for idleness, so connecting + /// may start it again. + pub fn idle_stopped(&self) -> bool { + self.status.as_ref().is_some_and(|status| { + status.phase == crate::proto::SandboxPhase::Stopped as i32 + && status + .conditions + .iter() + .any(|c| c.r#type == "Ready" && c.reason == IDLE_STOPPED_REASON) + }) + } + + /// Whether an idle stop of this sandbox is still in flight, so a connect + /// should wait for it to finish and then start the sandbox. + pub fn idle_stopping(&self) -> bool { + self.status.as_ref().is_some_and(|status| { + status.phase == crate::proto::SandboxPhase::Stopping as i32 + && status + .conditions + .iter() + .any(|c| c.r#type == "Ready" && c.reason == IDLE_STOPPING_REASON) + }) + } + pub fn phase(&self) -> i32 { self.status.as_ref().map_or(0, |s| s.phase) } @@ -418,3 +449,35 @@ impl ObjectWorkspace for ObjectForTest { false } } + +#[cfg(test)] +mod tests { + use super::{IDLE_STOPPED_REASON, IDLE_STOPPING_REASON}; + use crate::proto::{Sandbox, SandboxCondition, SandboxPhase, SandboxStatus}; + + fn sandbox(phase: SandboxPhase, reason: &str) -> Sandbox { + Sandbox { + status: Some(SandboxStatus { + phase: phase.into(), + conditions: vec![SandboxCondition { + r#type: "Ready".to_string(), + status: "False".to_string(), + reason: reason.to_string(), + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + } + } + + #[test] + fn idle_stop_predicates_need_both_phase_and_reason() { + assert!(sandbox(SandboxPhase::Stopping, IDLE_STOPPING_REASON).idle_stopping()); + assert!(sandbox(SandboxPhase::Stopped, IDLE_STOPPED_REASON).idle_stopped()); + assert!(!sandbox(SandboxPhase::Stopping, "Stopping").idle_stopping()); + assert!(!sandbox(SandboxPhase::Stopped, "Stopped").idle_stopped()); + assert!(!sandbox(SandboxPhase::Stopped, IDLE_STOPPING_REASON).idle_stopping()); + assert!(!sandbox(SandboxPhase::Ready, IDLE_STOPPED_REASON).idle_stopped()); + } +} diff --git a/crates/openshell-core/src/settings.rs b/crates/openshell-core/src/settings.rs index f819d8ab38..8076f7a1f6 100644 --- a/crates/openshell-core/src/settings.rs +++ b/crates/openshell-core/src/settings.rs @@ -106,6 +106,26 @@ pub const PROPOSAL_APPROVAL_MODE_KEY: &str = "proposal_approval_mode"; /// fail-closes on unknown persisted values for defense in depth. pub const PROPOSAL_APPROVAL_MODE_VALUES: &[&str] = &["manual", "auto"]; +/// Seconds a sandbox's terminal program may wait on the user before it stops. +/// +/// Only programs that report OSC 7501 program status, such as Claude Code, can +/// be judged idle. Unset, zero, or negative disables idle stop; values above +/// [`MAX_IDLE_STOP_AFTER_SECONDS`] are capped. Gateway scope wins over sandbox +/// scope. +pub const IDLE_STOP_AFTER_SECONDS_KEY: &str = "idle_stop_after_seconds"; + +/// Longest effective idle stop timeout: 30 days. +pub const MAX_IDLE_STOP_AFTER_SECONDS: i64 = 30 * 24 * 60 * 60; + +/// The effective idle stop timeout for a raw `idle_stop_after_seconds` value, +/// or `None` when idle stop is disabled. +#[must_use] +pub fn idle_stop_timeout(seconds: Option) -> Option { + let seconds = seconds.filter(|seconds| *seconds > 0)?; + let seconds = seconds.min(MAX_IDLE_STOP_AFTER_SECONDS); + Some(std::time::Duration::from_secs(u64::try_from(seconds).ok()?)) +} + pub const REGISTERED_SETTINGS: &[RegisteredSetting] = &[ // When true the supervisor emits OCSF-JSON records to stderr and writes // JSONL to `/var/log/openshell-ocsf*.jsonl` when file logging is available. @@ -136,6 +156,12 @@ pub const REGISTERED_SETTINGS: &[RegisteredSetting] = &[ kind: SettingValueKind::String, allowed_string_values: Some(PROPOSAL_APPROVAL_MODE_VALUES), }, + // Idle stop timeout. See IDLE_STOP_AFTER_SECONDS_KEY. Unset disables it. + RegisteredSetting { + key: IDLE_STOP_AFTER_SECONDS_KEY, + kind: SettingValueKind::Int, + allowed_string_values: None, + }, ]; /// Resolve a setting descriptor from the registry by key. @@ -171,6 +197,13 @@ mod tests { RegisteredSetting, SettingValueKind, parse_bool_like, registered_keys_csv, setting_for_key, }; + #[test] + fn idle_stop_after_seconds_is_an_int_setting() { + let setting = setting_for_key(super::IDLE_STOP_AFTER_SECONDS_KEY) + .expect("idle_stop_after_seconds should be registered"); + assert_eq!(setting.kind, SettingValueKind::Int); + } + #[test] fn setting_for_key_returns_none_for_unknown() { assert!(setting_for_key("nonexistent_key").is_none()); diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 61e458a23f..1bddf330ee 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -167,6 +167,41 @@ A provisioning timeout can be repaired by Stop after its original driver work settles and cleanup completes. Stop exposes Stopped without discarding the timeout diagnosis or storage. This lifecycle behavior also applies when updates are disabled. +## Idle stop + +The supervisor owns the idle clock and sends a `SupervisorWorkloadIdle` +proposal once its sandbox's program has waited on the user past the sandbox's +`idle_stop_after_seconds`. It retracts the proposal when input or a new turn +ends the wait. The replica that holds the supervisor session keeps the +session's latest proposal in memory; only that proposal starts an idle stop. +A proposal from a replaced session, or an older one from the current session, +is dropped. Nothing is stored, and after a gateway restart or a session change +nothing stops until the current session proposes again. Supervisors that do +not advertise `supports_idle_proposals` are never idle-stopped. + +A proposal starts one idle stop per sandbox at a time, through the ordinary +stop path. Before the `Stopping` write, under the lifecycle lock, each write +attempt requires: + +- the proposal from the same session still held; +- a `Ready` sandbox on the proposing main-process instance; +- the gateway's own effective timeout (gateway scope wins), reached by the + proposal's wait, so a supervisor still on an older, shorter setting does not + decide; +- a fresh shared owner record that names the session. + +After the write and before the driver call, the stop checks the proposal again. +A retraction or session change received in between rolls the sandbox back to +its previous state and abandons the stop. If that rollback loses a write race, +the stop goes ahead like any other in-flight stop. Recording a proposal never +waits on a store write or the sandbox lock. + +The stop records the `internal.openshell.ai/idle-stop` annotation with +`IdleStopping`. That marker survives gateway recovery and settles the stop as +`IdleStopped`. Any other lifecycle write removes it. An explicit stop, whether +the idle stop is settled or still in flight on another replica, rewrites it as +an ordinary stop. + ## Static credential delivery Existing polling and configuration-push environments keep their original wire diff --git a/crates/openshell-server/src/compute/idle_stop.rs b/crates/openshell-server/src/compute/idle_stop.rs new file mode 100644 index 0000000000..3365962aa8 --- /dev/null +++ b/crates/openshell-server/src/compute/idle_stop.rs @@ -0,0 +1,460 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Idle stop: stop a sandbox whose terminal program has waited on the user +//! longer than its `idle_stop_after_seconds` setting. +//! +//! The supervisor owns the idle clock. It applies the effective setting to +//! the OSC 7501 program status it observes and proposes a stop once the wait +//! passes the timeout, then retracts the proposal as soon as input or a new +//! turn ends the wait. The replica that holds the sandbox's supervisor +//! session keeps the session's latest proposal in memory and stops the +//! sandbox through the ordinary stop path. Just before calling the driver, +//! after the `Stopping` write, it checks that the proposal still holds and +//! rolls the sandbox back to its previous state when it does not. + +use std::time::{Duration, Instant}; + +use openshell_core::proto::{ + Sandbox, SandboxCondition, SandboxPhase, SupervisorWorkloadIdle, WorkloadProgramState, +}; +use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; +use tonic::{Code, Status}; +use tracing::{debug, info, warn}; + +use super::{ComputeRuntime, IdleStopInFlight, IdleStopSession, QuiesceCause, QuiesceOperation}; +use crate::supervisor_owner::{OWNER_TTL, SupervisorOwnerIndex}; + +pub use openshell_core::metadata::{IDLE_STOPPED_REASON, IDLE_STOPPING_REASON}; + +/// Durable marker that the in-flight stop was started by an idle proposal. +/// It survives gateway restarts and driver snapshots that rewrite conditions. +pub const IDLE_STOP_ANNOTATION: &str = "internal.openshell.ai/idle-stop"; +pub const IDLE_STOPPING_MESSAGE: &str = + "Sandbox stop requested after its program waited on the user past its idle timeout"; +pub const IDLE_STOPPED_MESSAGE: &str = "Sandbox stopped after its program waited on the user past its idle timeout; connect to start it"; +/// Reported app names are bounded by OSC 7501; bound them again here. +const MAX_APP: usize = 32; + +/// The latest idle proposal of a supervisor session, held by the replica +/// that owns the session. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdleProposal { + pub session_id: String, + pub instance_id: String, + pub proposal_id: u64, + pub state: WorkloadProgramState, + /// The reported app, reduced to safe characters for logs. + pub program: String, + /// How long the program had waited when the supervisor sent it. + pub idle_for: Duration, + /// When the proposal reached the session handler. + pub arrived: Instant, +} + +impl IdleProposal { + /// How long the program has waited by now, measured from the proposal. + #[must_use] + pub fn waited(&self) -> Duration { + self.idle_for + self.arrived.elapsed() + } +} + +/// The reported app name, reduced to safe characters for logs. +#[must_use] +pub fn program_name(app: &str) -> String { + let app: String = app + .chars() + .filter(|c| c.is_ascii_alphanumeric() || "_.+-".contains(*c)) + .take(MAX_APP) + .collect(); + if app.is_empty() { + "program".to_string() + } else { + app + } +} + +/// The effective idle timeout for a raw setting value, or `None` when idle +/// stop is disabled. +#[must_use] +pub fn timeout_from_setting(seconds: Option) -> Option { + openshell_core::settings::idle_stop_timeout(seconds) +} + +/// Whether `proposal` may stop `sandbox` under `timeout`: the sandbox is +/// `Ready`, the proposal comes from its running main-process instance, and +/// the program has waited at least the gateway's own timeout. The supervisor +/// may still hold an older, shorter setting. +#[must_use] +pub fn proposal_admits(sandbox: &Sandbox, proposal: &IdleProposal, timeout: Duration) -> bool { + let Some(status) = sandbox.status.as_ref() else { + return false; + }; + status.phase == SandboxPhase::Ready as i32 + && (status.main_process_instance_id.is_empty() + || status.main_process_instance_id == proposal.instance_id) + && proposal.waited() >= timeout +} + +/// The Ready condition of an idle-stopped sandbox. Driver snapshots of the +/// stopped runtime rewrite conditions, so the gateway reapplies it. +#[must_use] +pub fn idle_stopped_condition() -> SandboxCondition { + SandboxCondition { + r#type: "Ready".to_string(), + status: "False".to_string(), + reason: IDLE_STOPPED_REASON.to_string(), + message: IDLE_STOPPED_MESSAGE.to_string(), + transition_time: None, + } +} + +/// The Ready condition of a sandbox whose idle stop is in flight, reapplied +/// over driver snapshots so a connect can tell it apart from other stops. +#[must_use] +pub fn idle_stopping_condition() -> SandboxCondition { + SandboxCondition { + r#type: "Ready".to_string(), + status: "False".to_string(), + reason: IDLE_STOPPING_REASON.to_string(), + message: IDLE_STOPPING_MESSAGE.to_string(), + transition_time: None, + } +} + +/// Whether the stop in flight was started by an idle proposal. +#[must_use] +pub fn idle_stop_marked(sandbox: &Sandbox) -> bool { + sandbox + .metadata + .as_ref() + .is_some_and(|metadata| metadata.annotations.contains_key(IDLE_STOP_ANNOTATION)) +} + +impl ComputeRuntime { + /// Record an idle proposal or retraction from a supervisor session. + /// + /// A message from a session that is no longer current is dropped, and so + /// is an older proposal from the current session. A proposal starts an + /// idle stop on its own task unless one is already in flight; a + /// retraction removes the proposal, which cancels a stop that has not yet + /// reached the driver. + pub fn record_workload_idle( + &self, + sandbox_id: &str, + session_id: &str, + instance_id: &str, + proposes_idle: bool, + message: &SupervisorWorkloadIdle, + ) { + if self.note_workload_idle(sandbox_id, session_id, instance_id, proposes_idle, message) { + let runtime = self.clone(); + let sandbox_id = sandbox_id.to_string(); + tokio::spawn(async move { Box::pin(runtime.run_idle_stop(&sandbox_id)).await }); + } + } + + /// Update the held proposal for [`Self::record_workload_idle`]. Returns + /// whether a new proposal was recorded, which starts an idle stop. + pub(super) fn note_workload_idle( + &self, + sandbox_id: &str, + session_id: &str, + instance_id: &str, + proposes_idle: bool, + message: &SupervisorWorkloadIdle, + ) -> bool { + if !proposes_idle + || !self + .supervisor_sessions + .is_current_session(sandbox_id, session_id) + { + return false; + } + let mut proposals = self + .idle_proposals + .lock() + .expect("idle proposal lock poisoned"); + let held = proposals + .get(sandbox_id) + .filter(|held| held.session_id == session_id); + if message.idle { + if held.is_some_and(|held| held.proposal_id >= message.proposal_id) { + return false; + } + proposals.insert( + sandbox_id.to_string(), + IdleProposal { + session_id: session_id.to_string(), + instance_id: instance_id.to_string(), + proposal_id: message.proposal_id, + state: WorkloadProgramState::try_from(message.state) + .unwrap_or(WorkloadProgramState::Unspecified), + program: program_name(&message.app), + idle_for: message + .idle_for + .as_ref() + .and_then(|idle_for| openshell_core::time::duration_to_std(idle_for).ok()) + .unwrap_or_default(), + arrived: Instant::now(), + }, + ); + true + } else { + if held.is_some_and(|held| held.proposal_id <= message.proposal_id) { + proposals.remove(sandbox_id); + } + false + } + } + + /// The current session's idle proposal for `sandbox_id`. A proposal from + /// an ended session is dropped. + pub(super) fn current_idle_proposal(&self, sandbox_id: &str) -> Option { + let mut proposals = self + .idle_proposals + .lock() + .expect("idle proposal lock poisoned"); + let proposal = proposals.get(sandbox_id)?.clone(); + if self + .supervisor_sessions + .is_current_session(sandbox_id, &proposal.session_id) + { + Some(proposal) + } else { + proposals.remove(sandbox_id); + None + } + } + + /// Stop `sandbox_id` for the current idle proposal, logging the outcome. + async fn run_idle_stop(&self, sandbox_id: &str) { + match Box::pin(self.idle_stop_for_proposal(sandbox_id)).await { + Ok(Some((stopped, proposal))) => info!( + sandbox_id, + sandbox_name = %stopped.object_name(), + program = %proposal.program, + state = ?proposal.state, + idle_seconds = proposal.waited().as_secs(), + "Stopped idle sandbox" + ), + Ok(None) => {} + Err(status) if status.code() == Code::Aborted => debug!( + sandbox_id, + reason = %status.message(), + "Abandoned an idle stop" + ), + Err(status) => warn!( + sandbox_id, + error = %status.message(), + "Idle sandbox stop failed" + ), + } + } + + /// Stop `sandbox_id` for the current session's idle proposal. Returns + /// `None` when there is no proposal to act on, another idle stop is in + /// flight, or the gateway declines it. + pub(super) async fn idle_stop_for_proposal( + &self, + sandbox_id: &str, + ) -> Result, Status> { + let Some(_in_flight) = IdleStopInFlight::claim(&self.idle_stops_in_flight, sandbox_id) + else { + return Ok(None); + }; + let Some(proposal) = self.current_idle_proposal(sandbox_id) else { + return Ok(None); + }; + let Some(sandbox) = self + .store + .get_message::(sandbox_id) + .await + .map_err(|error| Status::internal(format!("fetch sandbox failed: {error}")))? + else { + return Ok(None); + }; + if !self.idle_proposal_admitted(&sandbox, &proposal).await { + debug!(sandbox_id, "Declined an idle stop proposal"); + return Ok(None); + } + let cause = QuiesceCause::Idle(IdleStopSession { + session_id: proposal.session_id.clone(), + }); + let stopped = Box::pin(self.quiesce_sandbox( + QuiesceOperation::Stop, + &cause, + sandbox.object_workspace(), + sandbox.object_name(), + )) + .await?; + Ok(Some((stopped, proposal))) + } + + /// Whether `proposal` may stop `sandbox` now: the gateway's effective + /// timeout is enabled and reached, the sandbox is `Ready` on the + /// proposing instance, and a fresh shared owner record names the + /// proposing session. + async fn idle_proposal_admitted(&self, sandbox: &Sandbox, proposal: &IdleProposal) -> bool { + let Some(timeout) = self.idle_stop_timeout(sandbox).await else { + return false; + }; + proposal_admits(sandbox, proposal, timeout) + && self + .owned_by_session(sandbox.object_id(), &proposal.session_id) + .await + } + + /// The check before an idle `Stopping` write, run under the lifecycle + /// lock: the proposing session's proposal still holds and still admits + /// the stop. + pub(super) async fn idle_stop_admitted( + &self, + sandbox: &Sandbox, + cause: &IdleStopSession, + ) -> bool { + match self.current_idle_proposal(sandbox.object_id()) { + Some(proposal) if proposal.session_id == cause.session_id => { + self.idle_proposal_admitted(sandbox, &proposal).await + } + _ => false, + } + } + + /// The check after an idle `Stopping` write and before the driver call: + /// no retraction or session change has arrived since. Everything the + /// gateway received before this check counts, including a retraction + /// sent while the write was in flight. + pub(super) fn idle_stop_still_proposed( + &self, + sandbox_id: &str, + cause: &IdleStopSession, + ) -> bool { + self.current_idle_proposal(sandbox_id) + .is_some_and(|proposal| proposal.session_id == cause.session_id) + } + + /// After an idle `Stopping` write and before the driver call: when a + /// retraction or session change arrived since the check before the + /// write, roll `transition` back to `previous` and abort. If the rollback + /// loses a write race, the stop goes ahead as any in-flight stop would. + pub(super) async fn undo_retracted_idle_stop( + &self, + cause: &IdleStopSession, + previous: &Sandbox, + transition: &Sandbox, + ) -> Result<(), Status> { + let sandbox_id = transition.object_id(); + if previous.phase() != SandboxPhase::Ready as i32 + || self.idle_stop_still_proposed(sandbox_id, cause) + { + return Ok(()); + } + if self.restore_lifecycle_snapshot(transition, previous).await { + info!(sandbox_id, "Rolled back an idle stop after new activity"); + return Err(Status::aborted( + "sandbox became active during its idle stop; restored it", + )); + } + warn!( + sandbox_id, + "Could not roll back an idle stop after new activity; stopping anyway" + ); + Ok(()) + } + + /// Whether the shared owner record is fresh and names `session_id`. + async fn owned_by_session(&self, sandbox_id: &str, session_id: &str) -> bool { + SupervisorOwnerIndex::new(self.store.clone(), OWNER_TTL) + .read(sandbox_id) + .await + .ok() + .flatten() + .is_some_and(|owner| owner.is_fresh(OWNER_TTL) && owner.session_id == session_id) + } + + /// The effective idle timeout for `sandbox`, or `None` when disabled. + /// Gateway scope wins over sandbox scope. + async fn idle_stop_timeout(&self, sandbox: &Sandbox) -> Option { + let global = crate::grpc::policy::global_idle_stop_after_seconds(&self.store) + .await + .ok()?; + let setting = crate::grpc::policy::idle_stop_after_seconds( + &self.store, + global, + sandbox.object_workspace(), + sandbox.object_name(), + ) + .await + .ok()?; + timeout_from_setting(setting) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::SandboxStatus; + + fn secs(seconds: u64) -> Duration { + Duration::from_secs(seconds) + } + + fn proposal(idle_for: u64) -> IdleProposal { + IdleProposal { + session_id: "session-1".into(), + instance_id: "instance-1".into(), + proposal_id: 1, + state: WorkloadProgramState::Done, + program: "claude-code".into(), + idle_for: secs(idle_for), + arrived: Instant::now(), + } + } + + fn ready_sandbox() -> Sandbox { + Sandbox { + status: Some(SandboxStatus { + phase: SandboxPhase::Ready.into(), + main_process_instance_id: "instance-1".into(), + ..Default::default() + }), + ..Default::default() + } + } + + #[test] + fn program_names_are_reduced_to_safe_characters() { + assert_eq!(program_name("bad app\u{1b}"), "badapp"); + assert_eq!(program_name(""), "program"); + } + + #[test] + fn setting_values_map_to_timeouts() { + assert_eq!(timeout_from_setting(None), None); + assert_eq!(timeout_from_setting(Some(0)), None); + assert_eq!(timeout_from_setting(Some(-5)), None); + assert_eq!(timeout_from_setting(Some(600)), Some(secs(600))); + assert_eq!( + timeout_from_setting(Some(i64::MAX)), + Some(secs(30 * 24 * 60 * 60)) + ); + } + + #[test] + fn proposals_admit_only_ready_sandboxes_of_their_instance_past_the_timeout() { + let sandbox = ready_sandbox(); + assert!(proposal_admits(&sandbox, &proposal(600), secs(600))); + assert!( + !proposal_admits(&sandbox, &proposal(300), secs(600)), + "a supervisor on a shorter, older setting does not decide" + ); + let mut other_instance = proposal(600); + other_instance.instance_id = "instance-old".into(); + assert!(!proposal_admits(&sandbox, &other_instance, secs(600))); + let mut stopping = ready_sandbox(); + stopping.status.as_mut().unwrap().phase = SandboxPhase::Stopping.into(); + assert!(!proposal_admits(&stopping, &proposal(600), secs(600))); + } +} diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 32641d0937..808b84ad69 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -4,6 +4,7 @@ //! Gateway-owned compute orchestration over a pluggable compute backend. pub mod driver_config; +mod idle_stop; mod image_update; pub mod lease; mod mutation_guard; @@ -389,6 +390,53 @@ enum QuiesceOperation { Suspend, } +/// Who asked for a quiesce operation. +#[derive(Debug, Clone, PartialEq, Eq)] +enum QuiesceCause { + /// A client request or gateway recovery. + Requested, + /// The sandbox's supervisor proposed an idle stop: its program waited + /// on the user past the idle timeout. + Idle(IdleStopSession), +} + +/// The supervisor session whose idle proposal started a stop. The stop goes +/// ahead only while that session's proposal still holds. +#[derive(Debug, Clone, PartialEq, Eq)] +struct IdleStopSession { + session_id: String, +} + +/// Marks one sandbox's idle stop as in flight until dropped. +struct IdleStopInFlight { + set: Arc>>, + sandbox_id: String, +} + +impl IdleStopInFlight { + fn claim( + set: &Arc>>, + sandbox_id: &str, + ) -> Option { + set.lock() + .expect("idle stop lock poisoned") + .insert(sandbox_id.to_string()) + .then(|| Self { + set: Arc::clone(set), + sandbox_id: sandbox_id.to_string(), + }) + } +} + +impl Drop for IdleStopInFlight { + fn drop(&mut self) { + self.set + .lock() + .expect("idle stop lock poisoned") + .remove(&self.sandbox_id); + } +} + /// What an explicit quiesce request does with the current durable phase. enum QuiesceAdmission { /// The requested state is already durable. @@ -421,14 +469,18 @@ impl QuiesceOperation { } } - const fn requested_condition(self) -> (&'static str, &'static str) { - match self { - Self::Stop => ("Stopping", "Sandbox stop requested"), - Self::Suspend => ("Suspending", "Sandbox suspend requested"), + const fn requested_condition(self, cause: &QuiesceCause) -> (&'static str, &'static str) { + match (self, cause) { + (Self::Stop, QuiesceCause::Idle(_)) => ( + idle_stop::IDLE_STOPPING_REASON, + idle_stop::IDLE_STOPPING_MESSAGE, + ), + (Self::Stop, QuiesceCause::Requested) => ("Stopping", "Sandbox stop requested"), + (Self::Suspend, _) => ("Suspending", "Sandbox suspend requested"), } } - const fn settled_condition(self) -> (&'static str, &'static str) { + const fn settled_condition_explicit(self) -> (&'static str, &'static str) { match self { Self::Stop => ("Stopped", "Sandbox compute is stopped"), Self::Suspend => ( @@ -438,6 +490,22 @@ impl QuiesceOperation { } } + /// The settled condition for `sandbox`, whose durable marker records + /// whether the idle sweep started the stop. + fn settled_condition(self, sandbox: &Sandbox) -> (&'static str, &'static str) { + match self { + Self::Stop if idle_stop::idle_stop_marked(sandbox) => ( + idle_stop::IDLE_STOPPED_REASON, + idle_stop::IDLE_STOPPED_MESSAGE, + ), + Self::Stop => self.settled_condition_explicit(), + Self::Suspend => ( + "Suspended", + "Sandbox is suspended; its memory state is retained for resume", + ), + } + } + fn admit(self, sandbox: &Sandbox) -> Result { let phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); match self { @@ -938,6 +1006,12 @@ pub struct ComputeRuntime { default_image: String, image_preparation_timeout_seconds: u32, provisioning_repair_window_ms: i64, + /// The latest idle proposal per sandbox from this replica's supervisor + /// sessions. Only these proposals start an idle stop. + idle_proposals: Arc>>, + /// Sandboxes with an idle stop in flight on this replica. A repeated + /// proposal does not start a second stop. + idle_stops_in_flight: Arc>>, sandbox_updates_enabled: bool, update_recovery_sweep: Arc, update_recovery_backoff: Arc>>, @@ -1061,6 +1135,8 @@ impl ComputeRuntime { default_image, image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, + idle_proposals: Arc::default(), + idle_stops_in_flight: Arc::default(), sandbox_updates_enabled: false, update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)), update_recovery_backoff: Arc::default(), @@ -2079,8 +2155,13 @@ impl ComputeRuntime { workspace: &str, name: &str, ) -> Result { - self.quiesce_sandbox(QuiesceOperation::Stop, workspace, name) - .await + self.quiesce_sandbox( + QuiesceOperation::Stop, + &QuiesceCause::Requested, + workspace, + name, + ) + .await } /// Whether the configured compute driver retains sandbox memory state @@ -2106,13 +2187,19 @@ impl ComputeRuntime { name: &str, ) -> Result { self.require_suspend_resume()?; - self.quiesce_sandbox(QuiesceOperation::Suspend, workspace, name) - .await + self.quiesce_sandbox( + QuiesceOperation::Suspend, + &QuiesceCause::Requested, + workspace, + name, + ) + .await } async fn quiesce_sandbox( &self, operation: QuiesceOperation, + cause: &QuiesceCause, workspace: &str, name: &str, ) -> Result { @@ -2144,6 +2231,29 @@ impl ComputeRuntime { provisioning_operation::ensure_operation_settled(¤t)?; match operation.admit(¤t)? { QuiesceAdmission::Settled => { + // An explicit stop overrides an idle stop, so connecting + // no longer starts the sandbox. + if operation == QuiesceOperation::Stop + && *cause == QuiesceCause::Requested + && idle_stop::idle_stop_marked(¤t) + { + let (reason, message) = QuiesceOperation::Stop.settled_condition_explicit(); + let Some(stopped) = self + .rewrite_idle_stop_as_explicit( + ¤t, + SandboxPhase::Stopped, + reason, + message, + attempt, + ) + .await? + else { + attempt += 1; + current = self.fetch_lifecycle_sandbox(&sandbox_id).await?; + continue; + }; + current = stopped; + } self.cleanup_stopped_sandbox_sessions(¤t) .await .map_err(Status::internal)?; @@ -2152,9 +2262,41 @@ impl ComputeRuntime { // Acquiring the lifecycle gate proves that no local worker // still owns this transition. Retry the idempotent driver // operation. - QuiesceAdmission::Retry => break (current.clone(), current), + QuiesceAdmission::Retry => { + // An explicit stop replaces an idle stop still in flight on + // another replica, so it cannot settle as `IdleStopped`. + if operation == QuiesceOperation::Stop + && *cause == QuiesceCause::Requested + && idle_stop::idle_stop_marked(¤t) + { + let (reason, message) = operation.requested_condition(cause); + let Some(explicit) = self + .rewrite_idle_stop_as_explicit( + ¤t, + SandboxPhase::Stopping, + reason, + message, + attempt, + ) + .await? + else { + attempt += 1; + current = self.fetch_lifecycle_sandbox(&sandbox_id).await?; + continue; + }; + current = explicit; + } + break (current.clone(), current); + } QuiesceAdmission::Begin => {} } + // Each attempt re-checks the idle proposal and the setting; a + // conflict retry checks again. + if let QuiesceCause::Idle(idle) = cause + && !Box::pin(self.idle_stop_admitted(¤t, idle)).await + { + return Err(Status::aborted("sandbox is no longer idle")); + } let reclaimed_timeout = operation == QuiesceOperation::Stop && current.phase() == SandboxPhase::Error as i32 @@ -2166,7 +2308,7 @@ impl ComputeRuntime { "Timed-out compute has been reclaimed; sandbox stopped for repair", ) } else { - let (reason, message) = operation.requested_condition(); + let (reason, message) = operation.requested_condition(cause); (operation.in_flight_phase(), reason, message) }; match self @@ -2212,6 +2354,9 @@ impl ComputeRuntime { } } }; + if let QuiesceCause::Idle(idle) = cause { + Box::pin(self.undo_retracted_idle_stop(idle, &previous, &transition)).await?; + } drop(sandbox_guard); // Once the durable transition is committed, request cancellation must @@ -2242,6 +2387,46 @@ impl ComputeRuntime { })? } + /// Rewrite an idle stop as an explicit one, so `sandbox connect` no + /// longer starts the sandbox. `Ok(None)` is a write conflict: re-read and + /// admit the request again. + async fn rewrite_idle_stop_as_explicit( + &self, + current: &Sandbox, + phase: SandboxPhase, + reason: &str, + message: &str, + attempt: usize, + ) -> Result, Status> { + match self + .write_lifecycle_phase(current, phase, reason, message) + .await + { + Ok(explicit) => { + self.sandbox_index.update_from_sandbox(&explicit); + self.sandbox_watch_bus.notify(explicit.object_id()); + Ok(Some(explicit)) + } + Err(crate::persistence::PersistenceError::Conflict { .. }) + if attempt < STOP_PHASE_CAS_RETRY_LIMIT => + { + Ok(None) + } + Err(error) => Err(crate::grpc::persistence_error_to_status( + error, + "update sandbox lifecycle", + )), + } + } + + async fn fetch_lifecycle_sandbox(&self, sandbox_id: &str) -> Result { + self.store + .get_message::(sandbox_id) + .await + .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? + .ok_or_else(|| Status::not_found("sandbox not found")) + } + async fn complete_sandbox_quiesce( &self, operation: QuiesceOperation, @@ -3227,7 +3412,7 @@ impl ComputeRuntime { operation.verb() ))); } - let (reason, message) = operation.settled_condition(); + let (reason, message) = operation.settled_condition(&latest); match self .write_lifecycle_phase(&latest, operation.settled_phase(), reason, message) .await @@ -7902,6 +8087,15 @@ fn apply_driver_snapshot( } } + // A snapshot of the stopped runtime reports why its container exited; an + // idle stop keeps its own reason so a connect can start the sandbox. + if idle_stop::idle_stop_marked(sandbox) { + if phase == SandboxPhase::Stopped { + upsert_ready_condition(&mut status, idle_stop::idle_stopped_condition()); + } else if phase == SandboxPhase::Stopping { + upsert_ready_condition(&mut status, idle_stop::idle_stopping_condition()); + } + } if let Some(metadata) = sandbox.metadata.as_mut() { metadata.name.clone_from(sandbox_name); } @@ -8325,6 +8519,17 @@ fn apply_lifecycle_phase( // intent. A resuming start records a new one after this write. if let Some(metadata) = sandbox.metadata.as_mut() { metadata.annotations.remove(RESUME_INTENT_ANNOTATION); + // The idle marker lives from the idle stop request through its + // settled stop. Any other lifecycle write, including an explicit stop + // of the stopped sandbox, removes it. + if reason == idle_stop::IDLE_STOPPING_REASON { + metadata.annotations.insert( + idle_stop::IDLE_STOP_ANNOTATION.to_string(), + "true".to_string(), + ); + } else if reason != idle_stop::IDLE_STOPPED_REASON { + metadata.annotations.remove(idle_stop::IDLE_STOP_ANNOTATION); + } } // Explicit quiesce and start requests cancel any gateway-managed // automatic restart. @@ -8815,6 +9020,8 @@ pub fn new_test_runtime_with_driver( default_image: "openshell/sandbox:test".to_string(), image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, + idle_proposals: Arc::default(), + idle_stops_in_flight: Arc::default(), sandbox_updates_enabled: false, update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)), update_recovery_backoff: Arc::default(), @@ -10114,6 +10321,8 @@ mod tests { default_image: "openshell/sandbox:test".to_string(), image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, + idle_proposals: Arc::default(), + idle_stops_in_flight: Arc::default(), sandbox_updates_enabled: false, update_recovery_sweep: Arc::new(Semaphore::new(1)), update_recovery_backoff: Arc::default(), @@ -22198,4 +22407,456 @@ endpoint = { kind = "unix", socket_path = "/run/agent-substrate/isolation.sock" assert_eq!(starting.object_id(), "sb-ttl"); assert_eq!(starting.phase(), i32::from(SandboxPhase::Starting)); } + + fn idle_ready_record(id: &str, name: &str) -> Sandbox { + let mut sandbox = sandbox_record(id, name, SandboxPhase::Ready); + let status = sandbox.status.as_mut().unwrap(); + status.main_process_instance_id = "instance-1".into(); + status.configuration_activated = Some(true); + sandbox + } + + async fn stored_sandbox(runtime: &ComputeRuntime, id: &str) -> Sandbox { + runtime + .store + .get_message::(id) + .await + .unwrap() + .unwrap() + } + + async fn set_idle_timeout(runtime: &ComputeRuntime, name: &str, seconds: i64) { + crate::grpc::policy::put_int_setting_for_test( + &runtime.store, + Some(("default", name)), + openshell_core::settings::IDLE_STOP_AFTER_SECONDS_KEY, + seconds, + ) + .await; + } + + async fn publish_owner(runtime: &ComputeRuntime, id: &str, session: &str, epoch: u64) { + SupervisorOwnerIndex::new(runtime.store.clone(), OWNER_TTL) + .publish(id, session, "instance-1", epoch, "replica-a", "") + .await + .expect("publish test owner record"); + } + + fn register_session(runtime: &ComputeRuntime, id: &str, session: &str) { + let (tx, _rx) = mpsc::channel(1); + let (shutdown_tx, _shutdown_rx) = oneshot::channel(); + runtime + .supervisor_sessions + .register(id.to_string(), session.to_string(), tx, shutdown_tx); + } + + /// An idle proposal, as the supervisor sends once its program has waited + /// `idle_secs`. + fn proposal(proposal_id: u64, idle_secs: i64) -> openshell_core::proto::SupervisorWorkloadIdle { + openshell_core::proto::SupervisorWorkloadIdle { + proposal_id, + idle: true, + state: openshell_core::proto::WorkloadProgramState::Done.into(), + app: "claude-code".into(), + idle_for: Some(prost_types::Duration { + seconds: idle_secs, + nanos: 0, + }), + ..Default::default() + } + } + + fn retraction(proposal_id: u64) -> openshell_core::proto::SupervisorWorkloadIdle { + openshell_core::proto::SupervisorWorkloadIdle { + proposal_id, + idle: false, + ..Default::default() + } + } + + /// Hold `message` from "session-1" without starting a stop task. + fn note( + runtime: &ComputeRuntime, + id: &str, + message: &openshell_core::proto::SupervisorWorkloadIdle, + ) -> bool { + runtime.note_workload_idle(id, "session-1", "instance-1", true, message) + } + + async fn idle_stop(runtime: &ComputeRuntime, id: &str) -> Option { + runtime + .idle_stop_for_proposal(id) + .await + .unwrap() + .map(|(stopped, _)| stopped) + } + + async fn wait_for_phase(runtime: &ComputeRuntime, id: &str, phase: SandboxPhase) -> Sandbox { + let mut sandbox = stored_sandbox(runtime, id).await; + for _ in 0..200 { + if sandbox.phase() == phase as i32 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + sandbox = stored_sandbox(runtime, id).await; + } + sandbox + } + + /// A Ready sandbox owned by "session-1", with a 60-second timeout and a + /// held proposal for an hour-long wait. + async fn proposed_sandbox(runtime: &ComputeRuntime, id: &str, name: &str) { + runtime + .store + .put_message(&idle_ready_record(id, name)) + .await + .unwrap(); + register_session(runtime, id, "session-1"); + publish_owner(runtime, id, "session-1", 1).await; + set_idle_timeout(runtime, name, 60).await; + assert!(note(runtime, id, &proposal(1, 3600))); + } + + #[tokio::test] + async fn a_proposal_stops_the_sandbox_and_start_clears_the_reason() { + let driver = ControlledDriver::new(); + let runtime = test_runtime(driver.clone()).await; + runtime + .store + .put_message(&idle_ready_record("sb-idle", "sandbox-idle")) + .await + .unwrap(); + register_session(&runtime, "sb-idle", "session-1"); + publish_owner(&runtime, "sb-idle", "session-1", 1).await; + set_idle_timeout(&runtime, "sandbox-idle", 60).await; + let version = sandbox_resource_version(&stored_sandbox(&runtime, "sb-idle").await); + + // A retraction with nothing to retract writes nothing. + runtime.record_workload_idle("sb-idle", "session-1", "instance-1", true, &retraction(1)); + assert_eq!( + sandbox_resource_version(&stored_sandbox(&runtime, "sb-idle").await), + version + ); + + runtime.record_workload_idle( + "sb-idle", + "session-1", + "instance-1", + true, + &proposal(1, 3600), + ); + let stopped = wait_for_phase(&runtime, "sb-idle", SandboxPhase::Stopped).await; + assert_eq!(stopped.phase(), SandboxPhase::Stopped as i32); + assert!( + stopped.idle_stopped(), + "idle stop settles with its own reason" + ); + assert_eq!(driver.stop_calls(), 1); + + // A snapshot of the exited container keeps the idle reason. + let mut exited = ready_driver_sandbox("sb-idle", "sandbox-idle"); + let condition = &mut exited.status.as_mut().unwrap().conditions[0]; + condition.status = "False".to_string(); + condition.reason = openshell_core::driver_utils::CONDITION_EXITED.to_string(); + runtime.apply_sandbox_update(exited).await.unwrap(); + let observed = stored_sandbox(&runtime, "sb-idle").await; + assert_eq!(observed.phase(), SandboxPhase::Stopped as i32); + assert!( + observed.idle_stopped(), + "driver snapshots keep the idle reason" + ); + + // A start clears the idle reason along with the durable marker. + let starting = runtime + .start_sandbox("default", "sandbox-idle") + .await + .unwrap(); + assert_eq!(starting.phase(), SandboxPhase::Starting as i32); + assert!(!starting.idle_stopped()); + assert!(!idle_stop::idle_stop_marked(&starting)); + } + + #[tokio::test] + async fn the_gateway_timeout_and_setting_decide_whether_a_proposal_stops() { + let driver = ControlledDriver::new(); + let runtime = test_runtime(driver.clone()).await; + proposed_sandbox(&runtime, "sb-short", "sandbox-short").await; + // The supervisor still holds an older, shorter timeout. + set_idle_timeout(&runtime, "sandbox-short", 7200).await; + assert!(idle_stop(&runtime, "sb-short").await.is_none()); + + set_idle_timeout(&runtime, "sandbox-short", 0).await; + assert!( + idle_stop(&runtime, "sb-short").await.is_none(), + "a disabled setting stops nothing" + ); + assert_eq!(driver.stop_calls(), 0); + assert_eq!( + stored_sandbox(&runtime, "sb-short").await.phase(), + SandboxPhase::Ready as i32 + ); + } + + #[tokio::test] + async fn retractions_older_proposals_and_other_sessions_are_handled_in_order() { + let runtime = test_runtime(ControlledDriver::new()).await; + proposed_sandbox(&runtime, "sb-order", "sandbox-order").await; + assert!(note(&runtime, "sb-order", &proposal(2, 3660)), "a repeat"); + assert!( + !note(&runtime, "sb-order", &proposal(1, 3600)), + "an older proposal is dropped" + ); + // A retraction of an earlier proposal does not end a newer one. + assert!(!note(&runtime, "sb-order", &retraction(1))); + assert_eq!( + runtime + .current_idle_proposal("sb-order") + .unwrap() + .proposal_id, + 2 + ); + assert!(!note(&runtime, "sb-order", &retraction(2))); + assert!(runtime.current_idle_proposal("sb-order").is_none()); + + // Supervisors without the capability never propose. + assert!(!runtime.note_workload_idle( + "sb-order", + "session-1", + "instance-1", + false, + &proposal(3, 3600) + )); + + // A replaced session's proposal is dropped, and so is one it holds. + assert!(note(&runtime, "sb-order", &proposal(3, 3600))); + register_session(&runtime, "sb-order", "session-2"); + assert!(runtime.current_idle_proposal("sb-order").is_none()); + assert!(!note(&runtime, "sb-order", &proposal(4, 3600))); + assert!(runtime.note_workload_idle( + "sb-order", + "session-2", + "instance-1", + true, + &proposal(1, 3600) + )); + } + + #[tokio::test] + async fn a_retraction_or_takeover_before_the_write_cancels_the_stop() { + let driver = ControlledDriver::new(); + let runtime = test_runtime(driver.clone()).await; + proposed_sandbox(&runtime, "sb-typed", "sandbox-typed").await; + let cause = QuiesceCause::Idle(IdleStopSession { + session_id: "session-1".to_string(), + }); + note(&runtime, "sb-typed", &retraction(1)); + let error = runtime + .quiesce_sandbox(QuiesceOperation::Stop, &cause, "default", "sandbox-typed") + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Aborted); + + proposed_sandbox(&runtime, "sb-takeover", "sandbox-takeover").await; + // Replica B took the session over and published a newer owner record. + publish_owner(&runtime, "sb-takeover", "session-2", 2).await; + assert!(idle_stop(&runtime, "sb-takeover").await.is_none()); + assert_eq!(driver.stop_calls(), 0); + } + + #[tokio::test] + async fn a_retraction_after_the_stopping_write_restores_the_sandbox() { + let driver = ControlledDriver::new(); + let runtime = test_runtime(driver.clone()).await; + proposed_sandbox(&runtime, "sb-late", "sandbox-late").await; + let previous = stored_sandbox(&runtime, "sb-late").await; + let transition = runtime + .write_lifecycle_phase( + &previous, + SandboxPhase::Stopping, + idle_stop::IDLE_STOPPING_REASON, + idle_stop::IDLE_STOPPING_MESSAGE, + ) + .await + .unwrap(); + let cause = IdleStopSession { + session_id: "session-1".to_string(), + }; + + // While the proposal holds, the stop goes ahead. + runtime + .undo_retracted_idle_stop(&cause, &previous, &transition) + .await + .unwrap(); + assert_eq!( + stored_sandbox(&runtime, "sb-late").await.phase(), + SandboxPhase::Stopping as i32 + ); + + // Input arrived while the write was in flight. + note(&runtime, "sb-late", &retraction(1)); + let error = runtime + .undo_retracted_idle_stop(&cause, &previous, &transition) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Aborted); + let restored = stored_sandbox(&runtime, "sb-late").await; + assert_eq!(restored.phase(), SandboxPhase::Ready as i32); + assert!(!restored.idle_stopping()); + assert!(!idle_stop::idle_stop_marked(&restored)); + assert_eq!(driver.stop_calls(), 0); + } + + #[tokio::test] + async fn a_write_conflict_readmits_the_stop() { + let directory = tempfile::tempdir().expect("temporary database directory"); + let database_url = format!("sqlite://{}", directory.path().join("gateway.db").display()); + let store = Arc::new(Store::connect(&database_url).await.expect("connect store")); + let pool = sqlx::SqlitePool::connect(&database_url) + .await + .expect("connect conflict injector"); + sqlx::query("CREATE TABLE injected_conflicts (marker TEXT PRIMARY KEY)") + .execute(&pool) + .await + .expect("create conflict marker table"); + // Another replica updates the sandbox once, between the check before + // the idle Stopping write and the write. + sqlx::query( + "CREATE TRIGGER inject_idle_stopping_conflict \ + BEFORE UPDATE OF payload ON objects \ + WHEN instr(NEW.payload, CAST('Sandbox stop requested after its program waited' AS BLOB)) > 0 \ + AND NOT EXISTS (SELECT 1 FROM injected_conflicts WHERE marker = 'idle') \ + BEGIN \ + INSERT INTO injected_conflicts (marker) VALUES ('idle'); \ + UPDATE objects SET resource_version = resource_version + 1 \ + WHERE object_type = OLD.object_type AND id = OLD.id; \ + SELECT RAISE(IGNORE); \ + END", + ) + .execute(&pool) + .await + .expect("install conflict trigger"); + let driver = ControlledDriver::new(); + let mut runtime = test_runtime(driver.clone()).await; + runtime.store = store; + proposed_sandbox(&runtime, "sb-conflict", "sandbox-conflict").await; + + let stopped = idle_stop(&runtime, "sb-conflict") + .await + .expect("the retry readmits the stop"); + assert_eq!(stopped.phase(), SandboxPhase::Stopped as i32); + assert!(stopped.idle_stopped()); + assert_eq!(driver.stop_calls(), 1); + let injected = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM injected_conflicts") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + injected, 1, + "the idle Stopping write hit the injected conflict" + ); + pool.close().await; + } + + #[tokio::test] + async fn explicit_stop_of_an_idle_stopped_sandbox_keeps_it_stopped() { + let driver = ControlledDriver::new(); + let runtime = test_runtime(driver.clone()).await; + proposed_sandbox(&runtime, "sb-explicit", "sandbox-explicit").await; + let idle_stopped = idle_stop(&runtime, "sb-explicit").await.unwrap(); + assert!(idle_stopped.idle_stopped()); + + let stopped = runtime + .stop_sandbox("default", "sandbox-explicit") + .await + .unwrap(); + assert_eq!(stopped.phase(), SandboxPhase::Stopped as i32); + assert!( + !stopped.idle_stopped(), + "connect must not wake an explicit stop" + ); + assert!(!idle_stop::idle_stop_marked(&stopped)); + assert_eq!( + driver.stop_calls(), + 1, + "the explicit stop needs no driver call" + ); + } + + #[tokio::test] + async fn explicit_stop_during_an_in_flight_idle_stop_settles_as_explicit() { + let driver = ControlledDriver::new(); + let runtime = test_runtime(driver.clone()).await; + // Another replica's idle stop committed Stopping and is waiting on + // the driver; this replica has no worker for it. + let mut sandbox = idle_ready_record("sb-inflight", "sandbox-inflight"); + apply_lifecycle_phase( + &mut sandbox, + SandboxPhase::Stopping, + idle_stop::IDLE_STOPPING_REASON, + idle_stop::IDLE_STOPPING_MESSAGE, + 1800, + 300_000, + ); + assert!(idle_stop::idle_stop_marked(&sandbox)); + runtime.store.put_message(&sandbox).await.unwrap(); + + let stopped = runtime + .stop_sandbox("default", "sandbox-inflight") + .await + .unwrap(); + assert_eq!(stopped.phase(), SandboxPhase::Stopped as i32); + assert!( + !stopped.idle_stopped(), + "the explicit stop wins over the idle one" + ); + assert!(!idle_stop::idle_stop_marked(&stopped)); + } + + #[tokio::test] + async fn overlapping_idle_stops_run_one_at_a_time() { + let driver = ControlledDriver::new(); + let runtime = test_runtime(driver.clone()).await; + proposed_sandbox(&runtime, "sb-overlap", "sandbox-overlap").await; + // A stop for an earlier proposal is still in flight. + let earlier = IdleStopInFlight::claim(&runtime.idle_stops_in_flight, "sb-overlap") + .expect("first claim succeeds"); + assert!(idle_stop(&runtime, "sb-overlap").await.is_none()); + assert_eq!( + driver.stop_calls(), + 0, + "a repeated proposal does not start a second stop" + ); + drop(earlier); + assert!( + idle_stop(&runtime, "sb-overlap").await.is_some(), + "once the earlier attempt ends, the proposal can stop it" + ); + assert_eq!(driver.stop_calls(), 1); + } + + #[tokio::test] + async fn an_in_flight_idle_stop_keeps_its_reason_through_driver_snapshots() { + let runtime = test_runtime(ControlledDriver::new()).await; + let mut sandbox = idle_ready_record("sb-stopping", "sandbox-stopping"); + apply_lifecycle_phase( + &mut sandbox, + SandboxPhase::Stopping, + idle_stop::IDLE_STOPPING_REASON, + idle_stop::IDLE_STOPPING_MESSAGE, + 1800, + 300_000, + ); + runtime.store.put_message(&sandbox).await.unwrap(); + assert!(sandbox.idle_stopping()); + runtime + .apply_sandbox_update(ready_driver_sandbox("sb-stopping", "sandbox-stopping")) + .await + .unwrap(); + let observed = stored_sandbox(&runtime, "sb-stopping").await; + assert_eq!(observed.phase(), SandboxPhase::Stopping as i32); + assert!( + observed.idle_stopping(), + "connect can still tell it is an idle stop" + ); + } } diff --git a/crates/openshell-server/src/config_delivery/session.rs b/crates/openshell-server/src/config_delivery/session.rs index f70a5d1a75..5979b49745 100644 --- a/crates/openshell-server/src/config_delivery/session.rs +++ b/crates/openshell-server/src/config_delivery/session.rs @@ -1043,6 +1043,7 @@ mod tests { supports_session_redirect: false, pushes_config: true, advertises_services: false, + proposes_idle: false, } } diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index ba6324f3a1..9f7a4ce1b4 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -1546,6 +1546,7 @@ pub mod test_support { .send(SupervisorMessage { payload: Some(supervisor_message::Payload::Hello(SupervisorHello { supports_service_advertisements: false, + supports_idle_proposals: false, sandbox_id: sandbox_id.into(), instance_id: "instance".into(), supports_config_push: features == StreamFeatures::Apply, diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 40819e7b37..f95885457a 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -8102,6 +8102,60 @@ fn upsert_setting_value( } } +/// The raw `idle_stop_after_seconds` value for a sandbox, if any scope sets +/// it. Gateway scope wins over sandbox scope, as for every runtime setting. +/// `global` lets a sweep load gateway settings once for many sandboxes. +pub async fn idle_stop_after_seconds( + store: &Store, + global: Option, + workspace: &str, + sandbox_name: &str, +) -> Result, Status> { + if global.is_some() { + return Ok(global); + } + let sandbox = load_sandbox_settings(store, workspace, sandbox_name).await?; + Ok( + match sandbox.settings.get(settings::IDLE_STOP_AFTER_SECONDS_KEY) { + Some(StoredSettingValue::Int(seconds)) => Some(*seconds), + _ => None, + }, + ) +} + +#[cfg(test)] +pub async fn put_int_setting_for_test( + store: &Store, + sandbox: Option<(&str, &str)>, + key: &str, + value: i64, +) { + let mut settings = match sandbox { + Some((workspace, name)) => load_sandbox_settings(store, workspace, name).await, + None => load_global_settings(store).await, + } + .expect("load test settings"); + settings + .settings + .insert(key.to_string(), StoredSettingValue::Int(value)); + match sandbox { + Some((workspace, name)) => save_sandbox_settings(store, workspace, name, &settings).await, + None => save_global_settings(store, &settings).await, + } + .expect("save test settings"); +} + +/// The gateway-scope `idle_stop_after_seconds` value, if set. +pub async fn global_idle_stop_after_seconds(store: &Store) -> Result, Status> { + let global = load_global_settings(store).await?; + Ok( + match global.settings.get(settings::IDLE_STOP_AFTER_SECONDS_KEY) { + Some(StoredSettingValue::Int(seconds)) => Some(*seconds), + _ => None, + }, + ) +} + pub(super) async fn load_global_settings(store: &Store) -> Result { load_settings_record(store, GLOBAL_SETTINGS_OBJECT_TYPE, "", GLOBAL_SETTINGS_NAME).await } diff --git a/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs b/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs index 883a69c498..086d947d31 100644 --- a/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs +++ b/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs @@ -1941,6 +1941,7 @@ async fn replacement_reset_timeout_invalidates_superseded_evidence() { let hello = SupervisorMessage { payload: Some(supervisor_message::Payload::Hello(SupervisorHello { supports_service_advertisements: false, + supports_idle_proposals: false, sandbox_id: sandbox_id.to_string(), instance_id: "instance-b".to_string(), connection_epoch: 1, @@ -2016,6 +2017,7 @@ async fn replacement_reset_retry_does_not_hold_gateway_shutdown() { let hello = SupervisorMessage { payload: Some(supervisor_message::Payload::Hello(SupervisorHello { supports_service_advertisements: false, + supports_idle_proposals: false, sandbox_id: sandbox_id.to_string(), instance_id: "instance-b".to_string(), connection_epoch: 1, diff --git a/crates/openshell-server/src/grpc/provider_readiness_tests.rs b/crates/openshell-server/src/grpc/provider_readiness_tests.rs index bfe729c044..af7101b8a5 100644 --- a/crates/openshell-server/src/grpc/provider_readiness_tests.rs +++ b/crates/openshell-server/src/grpc/provider_readiness_tests.rs @@ -69,6 +69,7 @@ impl TestRegistry { fn hello() -> SupervisorHello { SupervisorHello { supports_service_advertisements: false, + supports_idle_proposals: false, sandbox_id: Uuid::new_v4().to_string(), instance_id: Uuid::new_v4().to_string(), connection_epoch: 0, diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index da4b2aa977..137eb5aace 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -227,8 +227,11 @@ mod tests { // Discovery RPCs move to ServiceDiscovery. Application URL maps add two // public-only messages alongside main's public APIs; durable schemas // and the public/durable overlap remain unchanged. + // Idle stop adds SupervisorWorkloadIdle, its two enums, and + // SupervisorHello.supports_idle_proposals to supervisor control traffic, + // which is never stored, so durable schemas remain unchanged. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "ba37ee30d2e8618b947517c67fa6d336a87097978a55cfa82034366ee36a740e"; + "5c7f72660b9085ca31bf61566999c976e2e29731482a632fc1b5e77333b4c074"; const DURABLE_SCHEMA_SHA256: &str = "9a025fc84af7c71bce42a52a282d1a96a02f8d71319478bcdb0e0c6367305888"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = @@ -776,7 +779,7 @@ mod tests { overlap_hash.as_str(), ), ( - (367, 31), + (368, 33), (102, 22), (86, 22), PUBLIC_RPC_SCHEMA_SHA256, diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index 92a8ed6222..17cc4c3a02 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -680,6 +680,24 @@ impl SupervisorSessionRegistry { .map(|session| session.config.is_some()) } + /// Queue `message` on `session_id` if it is still the sandbox's current + /// session. Returns false when the session is gone or its queue is full. + pub fn send_if_current( + &self, + sandbox_id: &str, + session_id: &str, + message: GatewayMessage, + ) -> bool { + let tx = self + .sessions + .lock() + .unwrap() + .get(sandbox_id) + .filter(|session| session.session_id == session_id) + .map(|session| session.tx.clone()); + tx.is_some_and(|tx| tx.try_send(message).is_ok()) + } + pub fn is_current_session(&self, sandbox_id: &str, session_id: &str) -> bool { self.sessions .lock() @@ -2238,6 +2256,7 @@ struct ConfigPushSetup { /// session task or drops with early cleanup. struct SessionSetup { advertises_services: bool, + proposes_idle: bool, state: Arc, sandbox_id: String, instance_id: String, @@ -2257,6 +2276,7 @@ struct SessionSetup { async fn accept_supervisor_session(setup: SessionSetup) -> Result<(), Status> { let SessionSetup { advertises_services, + proposes_idle, state, sandbox_id, instance_id, @@ -2523,6 +2543,7 @@ async fn accept_supervisor_session(setup: SessionSetup) -> Result<(), Status> { supports_session_redirect, pushes_config, advertises_services, + proposes_idle, }; tokio::spawn(async move { let _session_lifetime = session_lifetime; @@ -2660,6 +2681,7 @@ pub async fn handle_connect_supervisor( let setup = SessionSetup { advertises_services: state.config.supervisor_app_listener.enabled && hello.supports_service_advertisements, + proposes_idle: hello.supports_idle_proposals, state: Arc::clone(state), sandbox_id, instance_id: hello.instance_id, @@ -2921,6 +2943,8 @@ fn queue_shutdown_redirect( } /// An accepted supervisor session, shared by the handlers for its messages. +// Each bool is an independent capability the supervisor's hello negotiated. +#[allow(clippy::struct_excessive_bools)] pub(crate) struct AcceptedSession { pub(crate) state: Arc, pub(crate) sandbox_id: String, @@ -2935,6 +2959,8 @@ pub(crate) struct AcceptedSession { /// polling. pub(crate) pushes_config: bool, pub(crate) advertises_services: bool, + /// The supervisor proposes idle stops, so its sandbox can be idle-stopped. + pub(crate) proposes_idle: bool, } async fn run_session_loop( @@ -3157,6 +3183,15 @@ async fn handle_supervisor_message( return false; } } + Some(supervisor_message::Payload::WorkloadIdle(idle)) => { + state.compute.record_workload_idle( + sandbox_id, + session_id, + &session.instance_id, + session.proposes_idle, + &idle, + ); + } _ => { warn!( sandbox_id = %sandbox_id, @@ -3376,6 +3411,7 @@ mod tests { let mut inbound = futures::stream::pending::>(); let session = AcceptedSession { advertises_services: false, + proposes_idle: false, state: Arc::clone(&state), sandbox_id: "sb-no-peer".into(), session_id: "session-no-peer".into(), @@ -5942,6 +5978,7 @@ mod tests { let mut inbound = futures::stream::iter([Ok(failure)]).chain(futures::stream::pending()); let session = AcceptedSession { advertises_services: false, + proposes_idle: false, state: Arc::clone(&state), sandbox_id: "sb-replaced".into(), session_id: "session-a".into(), @@ -6033,6 +6070,7 @@ mod tests { let mut inbound = futures::stream::iter([Ok(heartbeat)]).chain(futures::stream::pending()); let session = AcceptedSession { advertises_services: false, + proposes_idle: false, state: Arc::clone(&state), sandbox_id: "sb-moved".into(), session_id: "session-replaced".into(), diff --git a/crates/openshell-supervisor-process/Cargo.toml b/crates/openshell-supervisor-process/Cargo.toml index 5e6af570f9..91cee0212a 100644 --- a/crates/openshell-supervisor-process/Cargo.toml +++ b/crates/openshell-supervisor-process/Cargo.toml @@ -22,6 +22,7 @@ base64 = { workspace = true } bytes = { workspace = true } hex = "0.4" miette = { workspace = true } +prost-types = { workspace = true } rand = "0.10" russh = "0.65.2" serde_json = { workspace = true } diff --git a/crates/openshell-supervisor-process/README.md b/crates/openshell-supervisor-process/README.md index 1c2f728b43..5be6d17157 100644 --- a/crates/openshell-supervisor-process/README.md +++ b/crates/openshell-supervisor-process/README.md @@ -3,6 +3,44 @@ This crate manages workload processes and SSH sessions through the admitted isolation backend. +## Program status + +`program_status` scans PTY output of the canonical process and of SSH PTY +sessions for OSC 7501 program status reports. It keeps the protocol's +per-terminal records: ids, `clear`, dropping `working` and `blocked` at an OSC +133 `A` prompt, clearing every record on a full reset (RIS), and the record and +sequence limits. Reports, prompts, and resets apply in output order regardless +of how reads split them. A terminal's records end with its process. Report bytes are forwarded +unchanged; `msg` and `title` are validated and then discarded. + +The supervisor answers the support query (`OSC 7501 ; ?`) itself by writing the +reply to the program's input, and removes the query from forwarded output. +Claude Code reports only when that reply arrives before the reply to the DA1 +query it sends next. Only the bytes of a possible query are held back, and a +20 ms pause releases them. + +A sandbox-wide summary takes the most active state across terminals +(working, then blocked, error, done, idle) and the latest client input, which +outlives the terminal that received it. Every transition, including one undone +within the same read, restarts the state timer and advances a revision. +Summaries are published under the activity lock, so concurrent terminals never +republish an older one. + +The supervisor applies the sandbox's effective `idle_stop_after_seconds`, +which the configuration poller keeps current, to that summary. On each gateway +session, an idle reporter checks every second and on every summary change. +Once some program reports, none works, and the later of the state change and +the latest input is older than the timeout, it sends a `SupervisorWorkloadIdle` +proposal. It repeats the proposal with a new id every minute while the wait +continues. Input or a state change that ends the wait sends a retraction with +the last proposal's id. Each session starts its ids at 1, so a reconnect +proposes again. The reporter runs on its own task, so a full outbound queue +never stalls the session's receive loop. + +The scanner also treats `ESC c` outside an OSC as a full reset, including +inside other control strings. A terminal ends those strings at `ESC` and then +resets too, so this matches what the user sees. + ## Bounded streaming uploads The CLI's built-in uploads use the `openshell-upload-v1` SSH subsystem. Russh diff --git a/crates/openshell-supervisor-process/src/delegated.rs b/crates/openshell-supervisor-process/src/delegated.rs index 4f6edaac11..2338a4ae63 100644 --- a/crates/openshell-supervisor-process/src/delegated.rs +++ b/crates/openshell-supervisor-process/src/delegated.rs @@ -95,6 +95,7 @@ pub async fn start_boundary_access( host_key: Option, gateway_home: Option>>, app_installations: Option, + idle_timeout: crate::program_status::IdleTimeout, ) -> Result { let instance_id = uuid::Uuid::new_v4().to_string(); let terminating = Arc::new(AtomicBool::new(false)); @@ -134,6 +135,8 @@ pub async fn start_boundary_access( config_apply_tx, config_push_updates, gateway_home, + workload_activity: Some(main_session.program_activity().clone()), + idle_timeout, }, ); (Some(task), Some(accepted)) @@ -380,6 +383,7 @@ mod tests { None, None, None, + crate::program_status::IdleTimeout::new(), ) .await .expect("access without SSH is portable"); @@ -423,6 +427,7 @@ mod tests { None, None, None, + crate::program_status::IdleTimeout::new(), ) .await; assert!( diff --git a/crates/openshell-supervisor-process/src/lib.rs b/crates/openshell-supervisor-process/src/lib.rs index df0f21a519..198ffb8ec0 100644 --- a/crates/openshell-supervisor-process/src/lib.rs +++ b/crates/openshell-supervisor-process/src/lib.rs @@ -11,6 +11,7 @@ pub mod debug_rpc; pub mod delegated; pub mod log_push; pub mod main_session; +pub mod program_status; pub mod skills; #[cfg(unix)] pub mod ssh; diff --git a/crates/openshell-supervisor-process/src/main_session.rs b/crates/openshell-supervisor-process/src/main_session.rs index 5bf4879f04..eda5ecebd7 100644 --- a/crates/openshell-supervisor-process/src/main_session.rs +++ b/crates/openshell-supervisor-process/src/main_session.rs @@ -18,6 +18,8 @@ use tokio::sync::watch; use openshell_isolation_interface::contract::BoundarySignal; +use crate::program_status::{InputMarker, ProgramActivity, TerminalTap}; + const OUTPUT_BUFFER_BYTES: usize = 1024 * 1024; #[derive(Clone, Debug)] @@ -190,6 +192,9 @@ pub struct MainSession { finished: std::sync::atomic::AtomicBool, terminal_attachments: Mutex, terminal_attachments_done: Notify, + activity: Arc, + /// Records client input for the canonical terminal, when it has one. + input_marker: Option, } impl MainSession { @@ -219,6 +224,8 @@ impl MainSession { expectation: AttachmentExpectation::None, }), terminal_attachments_done: Notify::new(), + activity: ProgramActivity::new(), + input_marker: None, }); (session, input_rx) } @@ -239,6 +246,15 @@ impl MainSession { } = attachment; let terminal_mode = terminal.is_some(); let (input, mut input_rx) = tokio::sync::mpsc::channel::>(64); + let activity = ProgramActivity::new(); + let tap = terminal_mode.then(|| { + let reply = input.clone(); + activity.register(move |bytes| { + let _ = reply.try_send(bytes.to_vec()); + }) + }); + let input_marker = tap.as_ref().map(TerminalTap::input_marker); + crate::program_status::spawn_transition_log(&activity); let session = Arc::new(Self { terminal: terminal_mode, input, @@ -256,16 +272,26 @@ impl MainSession { expectation: AttachmentExpectation::None, }), terminal_attachments_done: Notify::new(), + activity, + input_marker, }); let stdout_session = Arc::clone(&session); tokio::spawn(async move { let mut stdout = stdout; let mut buffer = [0u8; 4096]; - loop { - match stdout.read(&mut buffer).await { - Ok(0) | Err(_) => break, - Ok(read) => stdout_session - .publish(MainOutput::Stdout(Bytes::copy_from_slice(&buffer[..read]))), + if let Some(mut tap) = tap { + while let Some(forward) = + crate::program_status::read_observed(&mut stdout, &mut buffer, &mut tap).await + { + stdout_session.publish(MainOutput::Stdout(Bytes::from(forward))); + } + } else { + loop { + match stdout.read(&mut buffer).await { + Ok(0) | Err(_) => break, + Ok(read) => stdout_session + .publish(MainOutput::Stdout(Bytes::copy_from_slice(&buffer[..read]))), + } } } stdout_session.reader_finished(); @@ -305,6 +331,19 @@ impl MainSession { self.output.publish(event); } + /// Program status reported by every workload terminal in this sandbox. + #[must_use] + pub fn program_activity(&self) -> &Arc { + &self.activity + } + + /// Record client input to the canonical terminal. + pub fn mark_input(&self) { + if let Some(marker) = &self.input_marker { + marker.mark(); + } + } + fn reader_finished(&self) { if self.readers_remaining.fetch_sub(1, Ordering::AcqRel) == 1 { self.readers_done.notify_waiters(); diff --git a/crates/openshell-supervisor-process/src/program_status.rs b/crates/openshell-supervisor-process/src/program_status.rs new file mode 100644 index 0000000000..42910d03f9 --- /dev/null +++ b/crates/openshell-supervisor-process/src/program_status.rs @@ -0,0 +1,1478 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Workload program status from OSC 7501 terminal reports. +//! +//! Agents such as Claude Code declare whether they are working, blocked on the +//! user, or done by writing OSC 7501 reports to their terminal. The supervisor +//! observes workload PTY output, keeps the per-terminal records the protocol +//! defines, and answers the support query itself so reporting does not depend +//! on the terminal of whichever client happens to be attached. +//! +//! Report bytes pass through unchanged. Only the support query is removed from +//! the forwarded stream, because the supervisor answers it and a second answer +//! from a supporting client terminal would reach the program as input. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use base64::Engine as _; +use tokio::sync::watch; + +const ESC: u8 = 0x1b; +const BEL: u8 = 0x07; +const CAN: u8 = 0x18; +const SUB: u8 = 0x1a; + +/// Largest legal sequence, OSC through ST. +const MAX_SEQUENCE: usize = 4096; +/// Records one terminal keeps before evicting the least recently updated. +const MAX_RECORDS: usize = 256; +const MAX_KEY: usize = 16; +const MAX_MSG_ENCODED: usize = 2732; +const MAX_TITLE_ENCODED: usize = 256; +const MAX_ID: usize = 128; +const MAX_ID_SEGMENT: usize = 32; +const MAX_ID_DEPTH: usize = 8; +const MAX_APP: usize = 32; + +const REPORT_PREFIX: &[u8] = b"7501;"; +const PROMPT_PREFIX: &[u8] = b"133;A"; +/// Both prefixes are this long, so one bounded buffer decides the sequence. +const PREFIX_LEN: usize = 5; +const QUERY_BODY: &[u8] = b"7501;?"; +const QUERY_ST: &[u8] = b"\x1b]7501;?\x1b\\"; +const QUERY_BEL: &[u8] = b"\x1b]7501;?\x07"; +// The reply lists the supported states and kinds so it never equals the query: +// a program that probes with terminal echo on reads its own echo, and a reply +// identical to the query would be answered again without end. +const REPLY_ST: &[u8] = + b"\x1b]7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth\x1b\\"; +const REPLY_BEL: &[u8] = + b"\x1b]7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth\x07"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub enum ProgramState { + Idle, + Done, + Error, + Blocked, + Working, +} + +impl ProgramState { + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Idle => "idle", + Self::Done => "done", + Self::Error => "error", + Self::Blocked => "blocked", + Self::Working => "working", + } + } + + /// Whether the program is waiting on the user rather than running. + #[must_use] + pub fn awaits_user(self) -> bool { + !matches!(self, Self::Working) + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] +pub enum BlockedKind { + Permission, + Question, + Auth, +} + +impl BlockedKind { + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Permission => "permission", + Self::Question => "question", + Self::Auth => "auth", + } + } +} + +/// One record as the protocol defines it. Free text (`msg`, `title`) is +/// validated but never retained: it is untrusted program output. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ProgramRecord { + pub state: ProgramState, + pub kind: Option, + pub app: Option, + pub progress: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Report { + /// Replace the record at `id`; the empty id is the root record. + Set { id: String, record: ProgramRecord }, + /// Remove the record at `id` and its descendants, or every record. + Clear { id: Option }, +} + +/// Terminator a query used, so the reply can match it. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Terminator { + St, + Bel, +} + +/// Something in the output stream that changes a terminal's records. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum TerminalEvent { + Report(Report), + /// The shell started a new prompt (OSC 133 `A`), ending the program that + /// ran before it. + Prompt, + /// A full terminal reset (RIS, `ESC c`) removes every record. + Reset, +} + +#[derive(Debug, Default, Eq, PartialEq)] +pub struct Scan { + /// Output to forward to attached clients. + pub forward: Vec, + /// Record changes in the order they appeared in the output. + pub events: Vec, + /// Support queries removed from `forward`, in order. + pub queries: Vec, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ScanState { + Ground, + Escape, + Osc, + OscEscape, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Tracking { + Undecided, + Report, + Prompt, + Ignore, +} + +/// Streaming OSC scanner. Sequences may span reads; only the support query is +/// held back, and at most one query's worth of bytes at a time. +#[derive(Debug)] +pub struct Scanner { + state: ScanState, + tracking: Tracking, + body: Vec, + sequence_len: usize, + held: Vec, +} + +impl Default for Scanner { + fn default() -> Self { + Self::new() + } +} + +impl Scanner { + #[must_use] + pub fn new() -> Self { + Self { + state: ScanState::Ground, + tracking: Tracking::Ignore, + body: Vec::new(), + sequence_len: 0, + held: Vec::new(), + } + } + + pub fn scan(&mut self, input: &[u8]) -> Scan { + let mut scan = Scan { + forward: Vec::with_capacity(input.len()), + ..Scan::default() + }; + for &byte in input { + self.hold(byte, &mut scan); + self.parse(byte, &mut scan); + } + scan + } + + /// Whether bytes are held back waiting to see if they form a query. + #[must_use] + pub fn has_pending(&self) -> bool { + !self.held.is_empty() + } + + /// Release held bytes when the program stops writing mid-sequence, so a + /// lone ESC is never delayed indefinitely. + pub fn flush(&mut self) -> Vec { + std::mem::take(&mut self.held) + } + + fn hold(&mut self, byte: u8, scan: &mut Scan) { + if self.held.is_empty() { + if byte == ESC { + self.held.push(byte); + } else { + scan.forward.push(byte); + } + return; + } + self.held.push(byte); + if self.held == QUERY_ST || self.held == QUERY_BEL { + scan.queries.push(if byte == BEL { + Terminator::Bel + } else { + Terminator::St + }); + self.held.clear(); + } else if !QUERY_ST.starts_with(&self.held) && !QUERY_BEL.starts_with(&self.held) { + // An ESC that broke the match may begin the next query. + let restart = byte == ESC; + if restart { + self.held.pop(); + } + scan.forward.append(&mut self.held); + if restart { + self.held.push(ESC); + } + } + } + + fn parse(&mut self, byte: u8, scan: &mut Scan) { + match self.state { + ScanState::Ground => { + if byte == ESC { + self.state = ScanState::Escape; + } + } + ScanState::Escape => self.after_escape(byte, scan), + ScanState::Osc => match byte { + BEL => self.finish(scan), + ESC => self.state = ScanState::OscEscape, + CAN | SUB => self.state = ScanState::Ground, + _ => self.accumulate(byte), + }, + ScanState::OscEscape => { + if byte == b'\\' { + self.finish(scan); + } else { + // ESC interrupted the string; it introduces what follows. + self.after_escape(byte, scan); + } + } + } + } + + fn after_escape(&mut self, byte: u8, scan: &mut Scan) { + if byte == b'c' { + scan.events.push(TerminalEvent::Reset); + } + self.state = match byte { + b']' => { + self.tracking = Tracking::Undecided; + self.body.clear(); + // OSC plus the ST that ends it count toward the limit. + self.sequence_len = 4; + ScanState::Osc + } + ESC => ScanState::Escape, + _ => ScanState::Ground, + }; + } + + fn accumulate(&mut self, byte: u8) { + self.sequence_len += 1; + if self.sequence_len > MAX_SEQUENCE { + self.tracking = Tracking::Ignore; + self.body = Vec::new(); + return; + } + match self.tracking { + Tracking::Undecided => { + self.body.push(byte); + if !REPORT_PREFIX.starts_with(&self.body) && !PROMPT_PREFIX.starts_with(&self.body) + { + self.tracking = Tracking::Ignore; + } else if self.body.len() == PREFIX_LEN { + self.tracking = if self.body == REPORT_PREFIX { + Tracking::Report + } else { + Tracking::Prompt + }; + } + } + Tracking::Report => self.body.push(byte), + Tracking::Prompt | Tracking::Ignore => {} + } + } + + fn finish(&mut self, scan: &mut Scan) { + self.state = ScanState::Ground; + match self.tracking { + Tracking::Prompt => scan.events.push(TerminalEvent::Prompt), + Tracking::Report if self.body != QUERY_BODY => { + if let Some(report) = parse_report(&self.body[REPORT_PREFIX.len()..]) { + scan.events.push(TerminalEvent::Report(report)); + } + } + _ => {} + } + self.tracking = Tracking::Ignore; + self.body.clear(); + } +} + +fn is_value_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || b"_.,+/=-".contains(&byte) +} + +fn is_name_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || b"_.+-".contains(&byte) +} + +fn valid_id(id: &str) -> bool { + let segments: Vec<&str> = id.split('/').collect(); + id.len() <= MAX_ID + && segments.len() <= MAX_ID_DEPTH + && segments.iter().all(|segment| { + (1..=MAX_ID_SEGMENT).contains(&segment.len()) && segment.bytes().all(is_name_byte) + }) +} + +/// Validate base64 free text without keeping it. +fn valid_text(value: &str, max_encoded: usize) -> bool { + if value.len() > max_encoded { + return false; + } + let engine = base64::engine::GeneralPurpose::new( + &base64::alphabet::STANDARD, + base64::engine::GeneralPurposeConfig::new() + .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent), + ); + let Ok(decoded) = engine.decode(value) else { + return false; + }; + let Ok(text) = std::str::from_utf8(&decoded) else { + return false; + }; + !text.chars().any(char::is_control) +} + +/// Parse the pairs after `7501;`. `None` means the whole report is discarded. +fn parse_report(pairs: &[u8]) -> Option { + let pairs = std::str::from_utf8(pairs).ok()?; + let mut fields: BTreeMap<&str, &str> = BTreeMap::new(); + for pair in pairs.split(':') { + let Some((key, value)) = pair.split_once('=') else { + continue; + }; + let (key, value) = (key.trim(), value.trim()); + if key.is_empty() + || key.len() > MAX_KEY + || !key.bytes().all(|byte| byte.is_ascii_lowercase()) + || !value.bytes().all(is_value_byte) + { + continue; + } + fields.insert(key, value); + } + + let id = match fields.get("id") { + Some(id) if valid_id(id) => Some((*id).to_string()), + Some(_) => return None, + None => None, + }; + if fields + .get("msg") + .is_some_and(|msg| !valid_text(msg, MAX_MSG_ENCODED)) + || fields + .get("title") + .is_some_and(|title| !valid_text(title, MAX_TITLE_ENCODED)) + { + return None; + } + let state = match *fields.get("state")? { + "clear" => return Some(Report::Clear { id }), + "idle" => ProgramState::Idle, + "working" => ProgramState::Working, + "done" => ProgramState::Done, + "blocked" => ProgramState::Blocked, + "error" => ProgramState::Error, + // A state added later must never read as an older one. + _ => return None, + }; + let kind = (state == ProgramState::Blocked) + .then(|| match *fields.get("kind")? { + "permission" => Some(BlockedKind::Permission), + "question" => Some(BlockedKind::Question), + "auth" => Some(BlockedKind::Auth), + _ => None, + }) + .flatten(); + let app = fields + .get("app") + .filter(|app| (1..=MAX_APP).contains(&app.len()) && app.bytes().all(is_name_byte)) + .map(|app| (*app).to_string()); + let progress = matches!(state, ProgramState::Working | ProgramState::Blocked) + .then(|| { + fields + .get("progress")? + .parse::() + .ok() + .filter(|p| *p <= 100) + }) + .flatten(); + Some(Report::Set { + id: id.unwrap_or_default(), + record: ProgramRecord { + state, + kind, + app, + progress, + }, + }) +} + +/// The records one terminal holds. +#[derive(Debug, Default)] +struct Records { + records: BTreeMap, + next_update: u64, +} + +impl Records { + fn apply(&mut self, report: Report) { + match report { + Report::Set { id, record } => { + let update = self.next_update; + self.next_update += 1; + self.records.insert(id, (record, update)); + while self.records.len() > MAX_RECORDS { + let oldest = self + .records + .iter() + .min_by_key(|(_, (_, update))| *update) + .map(|(id, _)| id.clone()); + if let Some(oldest) = oldest { + self.records.remove(&oldest); + } + } + } + Report::Clear { id: None } => self.records.clear(), + Report::Clear { id: Some(id) } => { + let prefix = format!("{id}/"); + self.records + .retain(|record_id, _| record_id != &id && !record_id.starts_with(&prefix)); + } + } + } + + /// A new prompt or a process exit ends the records that describe a + /// running program. + fn drop_running(&mut self) { + self.records.retain(|_, (record, _)| { + !matches!(record.state, ProgramState::Working | ProgramState::Blocked) + }); + } + + fn app_for(&self, id: &str) -> Option { + let mut current = id; + loop { + if let Some((record, _)) = self.records.get(current) + && let Some(app) = &record.app + { + return Some(app.clone()); + } + if current.is_empty() { + return None; + } + current = current.rsplit_once('/').map_or("", |(parent, _)| parent); + } + } + + /// The most active record: working, then blocked, error, done, idle. + fn dominant(&self) -> Option<(ProgramState, Option, Option)> { + self.records + .iter() + .max_by_key(|(_, (record, update))| (record.state, *update)) + .map(|(id, (record, _))| (record.state, record.kind, self.app_for(id))) + } +} + +#[derive(Debug)] +struct TerminalStatus { + records: Records, + last_output: Instant, +} + +/// Sandbox-wide status that changes only on program state transitions. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ActivitySummary { + /// Most active state across terminals; `None` until a program reports. + pub state: Option, + pub kind: Option, + pub app: Option, + /// Open workload terminals. + pub terminals: usize, + /// Terminals with a current program report. + pub reporting_terminals: usize, + /// Increments on every state transition, including one that is undone + /// within the same read, so each transition is a distinct value. + pub revision: u64, +} + +/// Point-in-time activity including timestamps that change on every byte. +#[derive(Clone, Debug)] +pub struct ActivitySnapshot { + pub summary: ActivitySummary, + pub last_output: Option, + pub last_input: Option, + /// When `summary.state` last changed. + pub state_since: Instant, +} + +#[derive(Debug)] +struct Inner { + next_terminal: u64, + terminals: BTreeMap, + state_since: Instant, + /// Latest client input to any workload terminal, kept after the terminal + /// closes so a short session still counts as recent input. + last_input: Option, + revision: u64, +} + +impl Inner { + fn dominant_state(&self) -> Option { + self.terminals + .values() + .filter_map(|terminal| terminal.records.dominant()) + .map(|(state, _, _)| state) + .max() + } + + /// Record a transition when `before` differs from the current state. + fn note_transition(&mut self, before: Option) -> Option { + let after = self.dominant_state(); + if after != before { + self.state_since = Instant::now(); + self.revision += 1; + } + after + } +} + +/// Program status across every workload terminal in one sandbox. +#[derive(Debug)] +pub struct ProgramActivity { + inner: Mutex, + changes: watch::Sender, +} + +impl ProgramActivity { + #[must_use] + pub fn new() -> Arc { + let (changes, _) = watch::channel(ActivitySummary::default()); + Arc::new(Self { + inner: Mutex::new(Inner { + next_terminal: 0, + terminals: BTreeMap::new(), + state_since: Instant::now(), + last_input: None, + revision: 0, + }), + changes, + }) + } + + /// Notified only when the summary changes. + #[must_use] + pub fn subscribe(&self) -> watch::Receiver { + self.changes.subscribe() + } + + #[must_use] + pub fn snapshot(&self) -> ActivitySnapshot { + let inner = self.inner.lock().expect("program activity lock poisoned"); + ActivitySnapshot { + summary: summarize(&inner), + last_output: inner.terminals.values().map(|t| t.last_output).max(), + last_input: inner.last_input, + state_since: inner.state_since, + } + } + + /// Track a new workload terminal. `reply` writes to the program's input. + pub fn register( + self: &Arc, + reply: impl Fn(&[u8]) + Send + Sync + 'static, + ) -> TerminalTap { + let id = self.update(|inner| { + let id = inner.next_terminal; + inner.next_terminal += 1; + inner.terminals.insert( + id, + TerminalStatus { + records: Records::default(), + last_output: Instant::now(), + }, + ); + id + }); + TerminalTap { + activity: Arc::clone(self), + id, + scanner: Scanner::new(), + reply: Box::new(reply), + } + } + + fn update(&self, change: impl FnOnce(&mut Inner) -> T) -> T { + let mut inner = self.inner.lock().expect("program activity lock poisoned"); + let before = inner.dominant_state(); + let result = change(&mut inner); + inner.note_transition(before); + self.publish(&inner); + result + } + + /// Publish while holding the lock, so summaries leave in mutation order + /// and an older one never overwrites a newer one. + fn publish(&self, inner: &Inner) { + let after = summarize(inner); + self.changes.send_if_modified(|current| { + if *current == after { + false + } else { + *current = after; + true + } + }); + } + + /// Apply a terminal's output events in order, noting every transition so + /// the timer does not depend on how reads split the output. + fn apply_events(&self, id: u64, events: Vec) { + let mut inner = self.inner.lock().expect("program activity lock poisoned"); + let mut state = inner.dominant_state(); + let Some(terminal) = inner.terminals.get_mut(&id) else { + return; + }; + terminal.last_output = Instant::now(); + for event in events { + let Some(terminal) = inner.terminals.get_mut(&id) else { + break; + }; + match event { + TerminalEvent::Report(report) => terminal.records.apply(report), + TerminalEvent::Prompt => terminal.records.drop_running(), + TerminalEvent::Reset => terminal.records.apply(Report::Clear { id: None }), + } + state = inner.note_transition(state); + } + self.publish(&inner); + } + + fn touch_input(&self, id: u64) { + // Input never changes the summary; skip the change notification. + let mut inner = self.inner.lock().expect("program activity lock poisoned"); + if inner.terminals.contains_key(&id) { + inner.last_input = Some(Instant::now()); + } + } +} + +fn summarize(inner: &Inner) -> ActivitySummary { + let dominant = inner + .terminals + .values() + .filter_map(|terminal| terminal.records.dominant()) + .max_by_key(|(state, _, _)| *state); + ActivitySummary { + state: dominant.as_ref().map(|(state, _, _)| *state), + kind: dominant.as_ref().and_then(|(_, kind, _)| *kind), + app: dominant.and_then(|(_, _, app)| app), + terminals: inner.terminals.len(), + reporting_terminals: inner + .terminals + .values() + .filter(|terminal| !terminal.records.records.is_empty()) + .count(), + revision: inner.revision, + } +} + +/// Per-terminal view of the workload output stream. Dropping it ends the +/// terminal, which removes its records as a process exit would. +pub struct TerminalTap { + activity: Arc, + id: u64, + scanner: Scanner, + reply: ReplyFn, +} + +/// Writes supervisor-generated replies to the program's input. +type ReplyFn = Box; + +impl TerminalTap { + /// Observe program output and return the bytes to forward. + pub fn output(&mut self, data: &[u8]) -> Vec { + let scan = self.scanner.scan(data); + for terminator in &scan.queries { + (self.reply)(match terminator { + Terminator::St => REPLY_ST, + Terminator::Bel => REPLY_BEL, + }); + } + // Wire order matters: a prompt ends only the reports before it. + self.activity.apply_events(self.id, scan.events); + scan.forward + } + + #[must_use] + pub fn has_pending(&self) -> bool { + self.scanner.has_pending() + } + + pub fn flush(&mut self) -> Vec { + self.scanner.flush() + } + + /// A handle that records client input for this terminal. + #[must_use] + pub fn input_marker(&self) -> InputMarker { + InputMarker { + activity: Arc::clone(&self.activity), + id: self.id, + } + } +} + +impl Drop for TerminalTap { + fn drop(&mut self) { + let id = self.id; + self.activity.update(|inner| { + inner.terminals.remove(&id); + }); + } +} + +#[derive(Clone)] +pub struct InputMarker { + activity: Arc, + id: u64, +} + +impl InputMarker { + pub fn mark(&self) { + self.activity.touch_input(self.id); + } +} + +/// How long held query bytes wait for the rest of the sequence. +pub const PENDING_FLUSH: Duration = Duration::from_millis(20); + +/// Read the next chunk to forward, observing it through `tap`. Returns `None` +/// at end of stream after releasing any held bytes. +pub async fn read_observed( + reader: &mut R, + buffer: &mut [u8], + tap: &mut TerminalTap, +) -> Option> +where + R: tokio::io::AsyncRead + Unpin, +{ + use tokio::io::AsyncReadExt as _; + loop { + let read = if tap.has_pending() { + match tokio::time::timeout(PENDING_FLUSH, reader.read(buffer)).await { + Ok(read) => read, + Err(_) => return Some(tap.flush()), + } + } else { + reader.read(buffer).await + }; + match read { + Ok(0) | Err(_) => { + let rest = tap.flush(); + return (!rest.is_empty()).then_some(rest); + } + Ok(size) => { + let forward = tap.output(&buffer[..size]); + if !forward.is_empty() { + return Some(forward); + } + } + } + } +} + +/// Log sandbox-wide program state transitions until the activity is dropped. +pub fn spawn_transition_log(activity: &Arc) -> tokio::task::JoinHandle<()> { + let mut changes = activity.subscribe(); + let activity = Arc::downgrade(activity); + tokio::spawn(async move { + let mut last_state = None; + while changes.changed().await.is_ok() { + if activity.upgrade().is_none() { + break; + } + let summary = changes.borrow_and_update().clone(); + if summary.state == last_state { + continue; + } + last_state = summary.state; + tracing::debug!( + state = summary.state.map_or("unknown", ProgramState::as_str), + kind = summary.kind.map(BlockedKind::as_str), + app = summary.app.as_deref(), + terminals = summary.terminals, + reporting_terminals = summary.reporting_terminals, + "workload program status changed" + ); + } + }) +} + +/// How often the idle reporter re-evaluates between summary changes, so new +/// input or a passed timeout is noticed within this long. +#[cfg(not(test))] +const IDLE_CHECK_INTERVAL: Duration = Duration::from_secs(1); +#[cfg(test)] +const IDLE_CHECK_INTERVAL: Duration = Duration::from_millis(10); +/// While the program keeps waiting, the proposal is repeated this often in +/// case the gateway declined it, for example under a longer gateway timeout. +#[cfg(not(test))] +const REPROPOSE_INTERVAL: Duration = Duration::from_mins(1); +#[cfg(test)] +const REPROPOSE_INTERVAL: Duration = Duration::from_millis(100); + +/// The sandbox's effective `idle_stop_after_seconds`, shared between the +/// configuration poller that writes it and the idle reporters that read it. +#[derive(Clone, Debug, Default)] +pub struct IdleTimeout(Arc); + +impl IdleTimeout { + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Set the timeout; `None` disables idle proposals. + pub fn set(&self, timeout: Option) { + let millis = timeout.map_or(0, |timeout| { + u64::try_from(timeout.as_millis()) + .unwrap_or(u64::MAX) + .max(1) + }); + self.0.store(millis, Ordering::Relaxed); + } + + #[must_use] + pub fn get(&self) -> Option { + match self.0.load(Ordering::Relaxed) { + 0 => None, + millis => Some(Duration::from_millis(millis)), + } + } +} + +/// How long the sandbox's programs have waited on the user with no client +/// input, once that reaches `timeout`. `None` while any program works, while +/// no program reports, or when idle stop is disabled. +#[must_use] +pub fn idle_past( + snapshot: &ActivitySnapshot, + timeout: Option, + now: Instant, +) -> Option { + let timeout = timeout?; + if snapshot.summary.reporting_terminals == 0 + || !snapshot + .summary + .state + .is_some_and(ProgramState::awaits_user) + { + return None; + } + let since = snapshot.last_input.map_or(snapshot.state_since, |input| { + input.max(snapshot.state_since) + }); + let waited = now.saturating_duration_since(since); + (waited >= timeout).then_some(waited) +} + +fn proto_state(state: Option) -> openshell_core::proto::WorkloadProgramState { + use openshell_core::proto::WorkloadProgramState as Proto; + match state { + None => Proto::Unspecified, + Some(ProgramState::Idle) => Proto::Idle, + Some(ProgramState::Working) => Proto::Working, + Some(ProgramState::Done) => Proto::Done, + Some(ProgramState::Blocked) => Proto::Blocked, + Some(ProgramState::Error) => Proto::Error, + } +} + +fn proto_kind(kind: Option) -> openshell_core::proto::WorkloadBlockedKind { + use openshell_core::proto::WorkloadBlockedKind as Proto; + match kind { + None => Proto::Unspecified, + Some(BlockedKind::Permission) => Proto::Permission, + Some(BlockedKind::Question) => Proto::Question, + Some(BlockedKind::Auth) => Proto::Auth, + } +} + +/// A proposal for `snapshot` that has waited `waited`, or the retraction of +/// proposal `proposal_id` when `waited` is `None`. +fn idle_message( + proposal_id: u64, + snapshot: &ActivitySnapshot, + waited: Option, +) -> openshell_core::proto::SupervisorMessage { + let idle = waited.map_or_else( + || openshell_core::proto::SupervisorWorkloadIdle { + proposal_id, + idle: false, + ..Default::default() + }, + |waited| openshell_core::proto::SupervisorWorkloadIdle { + proposal_id, + idle: true, + state: proto_state(snapshot.summary.state).into(), + blocked_kind: proto_kind(snapshot.summary.kind).into(), + app: snapshot.summary.app.clone().unwrap_or_default(), + idle_for: openshell_core::time::duration_from_std(waited).ok(), + }, + ); + openshell_core::proto::SupervisorMessage { + payload: Some(openshell_core::proto::supervisor_message::Payload::WorkloadIdle(idle)), + } +} + +/// Aborts the reporter when the session that owns it ends. +pub struct ReporterGuard(tokio::task::JoinHandle<()>); + +impl Drop for ReporterGuard { + fn drop(&mut self) { + self.0.abort(); + } +} + +/// Propose idle stops on one gateway session. +/// +/// The reporter proposes once the sandbox's programs have waited on the user +/// past `timeout`, repeats the proposal while they keep waiting, and retracts +/// it as soon as input or a state change ends the wait. +pub fn spawn_idle_reporter( + activity: &Arc, + timeout: IdleTimeout, + tx: tokio::sync::mpsc::Sender, +) -> ReporterGuard { + let activity = Arc::clone(activity); + let mut changes = activity.subscribe(); + ReporterGuard(tokio::spawn(async move { + let mut check = tokio::time::interval(IDLE_CHECK_INTERVAL); + check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut last_id = 0; + // The outstanding proposal and when it was sent. + let mut proposed: Option<(u64, Instant)> = None; + loop { + let snapshot = activity.snapshot(); + let now = Instant::now(); + let message = match (proposed, idle_past(&snapshot, timeout.get(), now)) { + (None, Some(waited)) => Some((last_id + 1, Some(waited))), + (Some((_, sent)), Some(waited)) + if now.saturating_duration_since(sent) >= REPROPOSE_INTERVAL => + { + Some((last_id + 1, Some(waited))) + } + (Some((id, _)), None) => Some((id, None)), + _ => None, + }; + if let Some((id, waited)) = message { + if tx.send(idle_message(id, &snapshot, waited)).await.is_err() { + return; + } + last_id = id; + proposed = waited.map(|_| (id, now)); + } + tokio::select! { + result = changes.changed() => { + if result.is_err() { + return; + } + changes.borrow_and_update(); + } + _ = check.tick() => {} + } + } + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex as StdMutex; + use tokio::io::AsyncWriteExt as _; + + fn set(state: ProgramState) -> Report { + Report::Set { + id: String::new(), + record: ProgramRecord { + state, + kind: None, + app: None, + progress: None, + }, + } + } + + fn report(body: &str) -> Option { + parse_report(body.as_bytes()) + } + + #[test] + fn parses_blocked_report_with_kind_app_and_message() { + let parsed = + report("state=blocked:kind=permission:app=claude-code:msg=QWxsb3cgcm0/").unwrap(); + assert_eq!( + parsed, + Report::Set { + id: String::new(), + record: ProgramRecord { + state: ProgramState::Blocked, + kind: Some(BlockedKind::Permission), + app: Some("claude-code".into()), + progress: None, + }, + } + ); + } + + #[test] + fn discards_unknown_state_missing_state_and_bad_ids() { + assert_eq!(report("state=sleeping"), None); + assert_eq!(report("app=cargo"), None); + assert_eq!(report("state=idle:id=a//b"), None); + assert_eq!(report("state=idle:id=a/b/c/d/e/f/g/h/i"), None); + } + + #[test] + fn discards_message_with_control_characters_or_bad_base64() { + // "a\nb" + assert_eq!(report("state=done:msg=YQpi"), None); + assert_eq!(report("state=done:msg=A"), None); + // Bytes outside the value alphabet make the pair malformed, not the report. + assert!(report("state=done:msg=@@@").is_some()); + assert!(report("state=done:msg=b2s").is_some()); + } + + #[test] + fn skips_malformed_pairs_and_ignores_irrelevant_fields() { + let parsed = report("bogus: state = working :progress=101:kind=auth:Key=x").unwrap(); + let Report::Set { record, .. } = parsed else { + panic!("expected set"); + }; + assert_eq!(record.state, ProgramState::Working); + assert_eq!(record.progress, None); + assert_eq!(record.kind, None); + let Report::Set { record, .. } = report("state=working:progress=42").unwrap() else { + panic!("expected set"); + }; + assert_eq!(record.progress, Some(42)); + } + + #[test] + fn clear_without_id_clears_everything() { + assert_eq!(report("state=clear"), Some(Report::Clear { id: None })); + assert_eq!( + report("state=clear:id=build"), + Some(Report::Clear { + id: Some("build".into()) + }) + ); + } + + #[test] + fn scanner_passes_reports_through_and_strips_queries() { + let mut scanner = Scanner::new(); + let input = b"hi\x1b]7501;?\x1b\\\x1b[c\x1b]7501;state=working\x07there"; + let scan = scanner.scan(input); + assert_eq!(scan.queries, vec![Terminator::St]); + assert_eq!( + scan.events, + vec![TerminalEvent::Report(set(ProgramState::Working))] + ); + assert_eq!( + scan.forward, + b"hi\x1b[c\x1b]7501;state=working\x07there".to_vec() + ); + assert!(!scanner.has_pending()); + } + + #[test] + fn scanner_handles_sequences_split_across_reads() { + let input = b"\x1b]7501;?\x07\x1b]7501;state=done\x1b\\ok"; + for split in 0..input.len() { + let mut scanner = Scanner::new(); + let first = scanner.scan(&input[..split]); + let second = scanner.scan(&input[split..]); + let mut forward = first.forward; + forward.extend(second.forward); + assert_eq!( + forward, + b"\x1b]7501;state=done\x1b\\ok".to_vec(), + "split {split}" + ); + assert_eq!( + [first.queries, second.queries].concat(), + vec![Terminator::Bel] + ); + assert_eq!( + [first.events, second.events].concat(), + vec![TerminalEvent::Report(set(ProgramState::Done))] + ); + } + } + + #[test] + fn scanner_flushes_lone_escape_and_restarts_on_new_escape() { + let mut scanner = Scanner::new(); + let scan = scanner.scan(b"a\x1b"); + assert_eq!(scan.forward, b"a".to_vec()); + assert!(scanner.has_pending()); + assert_eq!(scanner.flush(), b"\x1b".to_vec()); + + let mut scanner = Scanner::new(); + let scan = scanner.scan(b"\x1b]75\x1b]7501;?\x07"); + assert_eq!(scan.forward, b"\x1b]75".to_vec()); + assert_eq!(scan.queries, vec![Terminator::Bel]); + } + + #[test] + fn scanner_ignores_oversized_and_other_sequences() { + let mut scanner = Scanner::new(); + let mut input = b"\x1b]7501;state=working:msg=".to_vec(); + input.extend(std::iter::repeat_n(b'A', MAX_SEQUENCE)); + input.extend(b"\x1b\\\x1b]0;title\x07\x1b]133;A\x07"); + let scan = scanner.scan(&input); + assert_eq!(scan.events, vec![TerminalEvent::Prompt]); + assert_eq!(scan.forward, input); + } + + #[test] + fn records_clear_descendants_and_inherit_app() { + let mut records = Records::default(); + records.apply(report("state=working:app=cargo:id=build").unwrap()); + records.apply(report("state=done:id=build/test").unwrap()); + records.apply(report("state=idle:id=other").unwrap()); + assert_eq!( + records.dominant(), + Some((ProgramState::Working, None, Some("cargo".into()))) + ); + assert_eq!(records.app_for("build/test"), Some("cargo".into())); + records.apply(Report::Clear { + id: Some("build".into()), + }); + assert_eq!(records.dominant(), Some((ProgramState::Idle, None, None))); + records.drop_running(); + assert_eq!(records.records.len(), 1); + } + + #[test] + fn records_evict_least_recently_updated_over_cap() { + let mut records = Records::default(); + for index in 0..=MAX_RECORDS { + records.apply(report(&format!("state=idle:id=r{index}")).unwrap()); + } + assert_eq!(records.records.len(), MAX_RECORDS); + assert!(!records.records.contains_key("r0")); + } + + #[tokio::test] + async fn activity_answers_queries_and_aggregates_terminals() { + let activity = ProgramActivity::new(); + let mut changes = activity.subscribe(); + let replies = Arc::new(StdMutex::new(Vec::>::new())); + let sink = Arc::clone(&replies); + let mut main = activity.register(move |bytes| { + sink.lock().unwrap().push(bytes.to_vec()); + }); + let mut shell = activity.register(|_| {}); + + let forward = main.output(b"\x1b]7501;?\x1b\\\x1b]7501;state=done:app=claude-code\x1b\\"); + assert_eq!(replies.lock().unwrap().as_slice(), &[REPLY_ST.to_vec()]); + assert_eq!( + forward, + b"\x1b]7501;state=done:app=claude-code\x1b\\".to_vec() + ); + assert!(changes.has_changed().unwrap()); + let summary = changes.borrow_and_update().clone(); + assert_eq!(summary.state, Some(ProgramState::Done)); + assert_eq!(summary.app.as_deref(), Some("claude-code")); + assert_eq!(summary.terminals, 2); + assert_eq!(summary.reporting_terminals, 1); + + shell.output(b"\x1b]7501;state=working\x07"); + assert_eq!( + activity.snapshot().summary.state, + Some(ProgramState::Working) + ); + + shell.input_marker().mark(); + assert!(activity.snapshot().last_input.is_some()); + + // A new prompt ends the shell's running program. + shell.output(b"\x1b]133;A\x07"); + assert_eq!(activity.snapshot().summary.state, Some(ProgramState::Done)); + + drop(main); + drop(shell); + let summary = activity.snapshot().summary; + assert_eq!(summary.state, None); + assert_eq!(summary.terminals, 0); + } + + #[test] + fn prompts_and_reports_apply_in_wire_order_for_every_chunking() { + let input: &[u8] = b"\x1b]7501;state=working\x07\x1b]133;A\x07"; + let finals: Vec> = (0..=input.len()) + .map(|split| { + let activity = ProgramActivity::new(); + let mut tap = activity.register(|_| {}); + tap.output(&input[..split]); + tap.output(&input[split..]); + activity.snapshot().summary.state + }) + .collect(); + assert!( + finals.iter().all(Option::is_none), + "a prompt after a report ends it however the bytes arrive: {finals:?}" + ); + + // A report after the prompt belongs to the next program. + let activity = ProgramActivity::new(); + let mut tap = activity.register(|_| {}); + tap.output(b"\x1b]133;A\x07\x1b]7501;state=blocked\x07"); + assert_eq!( + activity.snapshot().summary.state, + Some(ProgramState::Blocked) + ); + } + + #[tokio::test] + async fn a_turn_within_one_read_restarts_the_timer_and_notifies() { + let activity = ProgramActivity::new(); + let mut tap = activity.register(|_| {}); + tap.output(b"\x1b]7501;state=done\x07"); + let mut changes = activity.subscribe(); + changes.borrow_and_update(); + let before = activity.snapshot(); + tokio::time::sleep(Duration::from_millis(5)).await; + tap.output(b"\x1b]7501;state=working\x07\x1b]7501;state=done\x07"); + let after = activity.snapshot(); + assert_eq!(after.summary.state, Some(ProgramState::Done)); + assert!( + after.state_since > before.state_since, + "the new turn restarts the wait" + ); + assert_eq!(after.summary.revision, before.summary.revision + 2); + assert!(changes.has_changed().unwrap(), "the reporter is told"); + } + + #[test] + fn concurrent_terminals_publish_every_transition_in_order() { + let activity = ProgramActivity::new(); + let mut changes = activity.subscribe(); + let mut threads = Vec::new(); + for _ in 0..4 { + let activity = Arc::clone(&activity); + threads.push(std::thread::spawn(move || { + let mut tap = activity.register(|_| {}); + for _ in 0..200 { + tap.output(b"\x1b]7501;state=working\x07"); + tap.output(b"\x1b]7501;state=done\x07"); + } + std::mem::forget(tap); + })); + } + for thread in threads { + thread.join().unwrap(); + } + // The last published summary is the final state, never an older one. + assert_eq!(*changes.borrow_and_update(), activity.snapshot().summary); + } + + #[test] + fn full_terminal_reset_clears_records() { + let activity = ProgramActivity::new(); + let mut tap = activity.register(|_| {}); + let forward = tap.output(b"\x1b]7501;state=done\x07\x1bc"); + assert_eq!(forward, b"\x1b]7501;state=done\x07\x1bc".to_vec()); + assert_eq!(activity.snapshot().summary.state, None); + // ESC c interrupting an unterminated OSC also resets. + tap.output(b"\x1b]7501;state=done\x07\x1b]7501;state=wor\x1bc"); + assert_eq!(activity.snapshot().summary.state, None); + } + + #[test] + fn reports_without_a_probe_count_and_input_outlives_its_terminal() { + let activity = ProgramActivity::new(); + let mut probing = activity.register(|_| {}); + probing.output(b"\x1b]7501;?\x07"); + let mut codex = activity.register(|_| {}); + codex.output(b"\x1b]7501;state=working:app=codex\x07"); + assert_eq!(activity.snapshot().summary.reporting_terminals, 1); + + let marker = probing.input_marker(); + marker.mark(); + let typed = activity.snapshot().last_input; + drop(probing); + assert!(typed.is_some()); + assert_eq!(activity.snapshot().last_input, typed); + } + + #[test] + fn echoed_replies_are_not_queries() { + for reply in [REPLY_ST, REPLY_BEL] { + let scan = Scanner::new().scan(reply); + assert!(scan.queries.is_empty()); + assert!(scan.events.is_empty()); + assert_eq!(scan.forward, reply.to_vec()); + } + } + + fn snapshot_waiting(state: Option, waited: Duration) -> ActivitySnapshot { + let since = Instant::now().checked_sub(waited).unwrap(); + ActivitySnapshot { + summary: ActivitySummary { + state, + reporting_terminals: usize::from(state.is_some()), + ..ActivitySummary::default() + }, + last_output: None, + last_input: None, + state_since: since, + } + } + + #[test] + fn only_a_wait_past_the_timeout_with_no_input_is_idle() { + let minute = Duration::from_mins(1); + let now = Instant::now(); + let done = snapshot_waiting(Some(ProgramState::Done), minute * 2); + assert!(idle_past(&done, Some(minute), now).is_some_and(|waited| waited > minute)); + assert_eq!(idle_past(&done, None, now), None, "disabled"); + assert_eq!(idle_past(&done, Some(minute * 3), now), None, "not yet"); + let working = snapshot_waiting(Some(ProgramState::Working), minute * 2); + assert_eq!(idle_past(&working, Some(minute), now), None); + let silent = snapshot_waiting(None, minute * 2); + assert_eq!(idle_past(&silent, Some(minute), now), None); + let mut typed = done; + typed.last_input = now.checked_sub(Duration::from_secs(5)); + assert_eq!( + idle_past(&typed, Some(minute), now), + None, + "input resets the wait" + ); + } + + #[test] + fn idle_timeouts_round_trip_and_zero_disables() { + let timeout = IdleTimeout::new(); + assert_eq!(timeout.get(), None); + timeout.set(Some(Duration::from_mins(30))); + assert_eq!(timeout.get(), Some(Duration::from_mins(30))); + timeout.set(None); + assert_eq!(timeout.get(), None); + } + + fn idle_received( + message: openshell_core::proto::SupervisorMessage, + ) -> openshell_core::proto::SupervisorWorkloadIdle { + let Some(openshell_core::proto::supervisor_message::Payload::WorkloadIdle(idle)) = + message.payload + else { + panic!("expected a workload idle message"); + }; + idle + } + + #[tokio::test] + async fn the_reporter_proposes_repeats_and_retracts_on_input() { + let activity = ProgramActivity::new(); + let mut tap = activity.register(|_| {}); + let timeout = IdleTimeout::new(); + timeout.set(Some(Duration::from_millis(30))); + let (tx, mut rx) = tokio::sync::mpsc::channel(8); + let guard = spawn_idle_reporter(&activity, timeout, tx); + let next = async |rx: &mut tokio::sync::mpsc::Receiver<_>| { + idle_received( + tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .expect("the reporter sends") + .unwrap(), + ) + }; + + tap.output(b"\x1b]7501;state=working:app=codex\x07"); + tokio::time::sleep(Duration::from_millis(60)).await; + assert!(rx.try_recv().is_err(), "a working program is never idle"); + + tap.output(b"\x1b]7501;state=done:app=codex\x07"); + let proposal = next(&mut rx).await; + assert!(proposal.idle); + assert_eq!(proposal.proposal_id, 1); + assert_eq!(proposal.app, "codex"); + assert_eq!( + proposal.state, + i32::from(openshell_core::proto::WorkloadProgramState::Done) + ); + let repeat = next(&mut rx).await; + assert!(repeat.idle); + assert_eq!(repeat.proposal_id, 2, "a repeat carries a new id"); + + tap.input_marker().mark(); + let retraction = next(&mut rx).await; + assert!(!retraction.idle); + assert_eq!(retraction.proposal_id, 2, "it retracts the last proposal"); + let again = next(&mut rx).await; + assert!(again.idle, "a new wait past the timeout proposes again"); + assert_eq!(again.proposal_id, 3); + + tap.output(b"\x1b]7501;state=working:app=codex\x07"); + let retraction = next(&mut rx).await; + assert!(!retraction.idle, "a new turn retracts"); + drop(guard); + } + + #[tokio::test] + async fn read_observed_releases_held_bytes_after_a_pause() { + let (mut writer, mut reader) = tokio::io::duplex(64); + let activity = ProgramActivity::new(); + let mut tap = activity.register(|_| {}); + let mut buffer = [0_u8; 16]; + writer.write_all(b"x\x1b").await.unwrap(); + assert_eq!( + read_observed(&mut reader, &mut buffer, &mut tap).await, + Some(b"x".to_vec()) + ); + assert_eq!( + read_observed(&mut reader, &mut buffer, &mut tap).await, + Some(b"\x1b".to_vec()) + ); + drop(writer); + assert_eq!( + read_observed(&mut reader, &mut buffer, &mut tap).await, + None + ); + } +} diff --git a/crates/openshell-supervisor-process/src/ssh.rs b/crates/openshell-supervisor-process/src/ssh.rs index a11eddbd21..9bef74d596 100644 --- a/crates/openshell-supervisor-process/src/ssh.rs +++ b/crates/openshell-supervisor-process/src/ssh.rs @@ -410,6 +410,8 @@ struct ChannelState { main_input_pending: bool, main_detach_prefix_pending: bool, main_output_task: Option, + /// Records client input for a PTY session's program status. + input_marker: Option, } enum InputSender { @@ -977,6 +979,9 @@ impl russh::server::Handler for SshHandler { return Ok(()); }; if !state.main_attached { + if let Some(marker) = &state.input_marker { + marker.mark(); + } // Russh replenishes receive credit before this callback. Waiting // for space here would block signals, close, and output credit on // the same SSH connection. Reject overflow before copying input. @@ -1023,6 +1028,12 @@ impl russh::server::Handler for SshHandler { state.main_input_pending = false; session.extended_data(channel, 1, b"openshell: input enabled\r\n".to_vec())?; } + if !forward.is_empty() + && state.main_input_owner.is_some() + && let Some(main_session) = self.main_session.as_ref() + { + main_session.mark_input(); + } let error = (!forward.is_empty()) .then(|| state.input_sender.as_ref()?.send(forward).err()) .flatten(); @@ -1362,6 +1373,10 @@ impl SshHandler { .exec(spec) .await .map_err(|error| anyhow::anyhow!(error.to_string()))?; + let activity = self + .main_session + .as_ref() + .map(|main_session| main_session.program_activity().clone()); let state = self .channels .get_mut(&channel) @@ -1395,6 +1410,19 @@ impl SshHandler { .input_task .as_ref() .map(input::InputTask::abort_handle); + // Interactive PTY programs may report their status over OSC 7501. + let tap = match (&activity, &state.terminal, &state.input_sender) { + (Some(activity), Some(_), Some(InputSender::Process(sender))) => { + let reply = sender.reply_handle(); + Some(activity.register(move |bytes| { + let _ = reply.send(bytes); + })) + } + _ => None, + }; + state.input_marker = tap + .as_ref() + .map(crate::program_status::TerminalTap::input_marker); // Upload stdout carries only credit, so extraction output uses stderr. let stdout_extended = finisher.is_some(); @@ -1402,6 +1430,14 @@ impl SshHandler { let stdout_handle = handle.clone(); let stdout_task = tokio::spawn(async move { let mut buffer = [0_u8; 4096]; + if let Some(mut tap) = tap { + while let Some(data) = + crate::program_status::read_observed(&mut stdout, &mut buffer, &mut tap).await + { + let _ = stdout_handle.data(channel, data).await; + } + return; + } loop { match stdout.read(&mut buffer).await { Ok(0) | Err(_) => break, diff --git a/crates/openshell-supervisor-process/src/ssh/input.rs b/crates/openshell-supervisor-process/src/ssh/input.rs index 46ca1dfa85..49a409cd82 100644 --- a/crates/openshell-supervisor-process/src/ssh/input.rs +++ b/crates/openshell-supervisor-process/src/ssh/input.rs @@ -4,7 +4,7 @@ //! Bounded stdin delivery without blocking the shared SSH session callback. use std::collections::VecDeque; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, Weak}; use openshell_isolation_interface::contract::BoundaryInput; use tokio::io::AsyncWriteExt; @@ -54,9 +54,9 @@ pub(super) enum SendError { Closed, } -impl InputSender { - pub(super) fn send(&self, bytes: &[u8]) -> Result<(), SendError> { - let mut buffer = self.0.buffer.lock().map_err(|_| SendError::Closed)?; +impl Shared { + fn send(&self, bytes: &[u8]) -> Result<(), SendError> { + let mut buffer = self.buffer.lock().map_err(|_| SendError::Closed)?; if buffer.closed { return Err(SendError::Closed); } @@ -65,11 +65,31 @@ impl InputSender { } buffer.bytes.extend(bytes); drop(buffer); - self.0.ready.notify_one(); + self.ready.notify_one(); Ok(()) } } +impl InputSender { + pub(super) fn send(&self, bytes: &[u8]) -> Result<(), SendError> { + self.0.send(bytes) + } + + /// A sender for supervisor-generated replies. It does not keep stdin open: + /// EOF still follows the client's sender. + pub(super) fn reply_handle(&self) -> ReplyHandle { + ReplyHandle(Arc::downgrade(&self.0)) + } +} + +pub(super) struct ReplyHandle(Weak); + +impl ReplyHandle { + pub(super) fn send(&self, bytes: &[u8]) -> Result<(), SendError> { + self.0.upgrade().ok_or(SendError::Closed)?.send(bytes) + } +} + impl Drop for InputSender { fn drop(&mut self) { if let Ok(mut buffer) = self.0.buffer.lock() { diff --git a/crates/openshell-supervisor-process/src/supervisor_session.rs b/crates/openshell-supervisor-process/src/supervisor_session.rs index a6a05638ad..d45345492b 100644 --- a/crates/openshell-supervisor-process/src/supervisor_session.rs +++ b/crates/openshell-supervisor-process/src/supervisor_session.rs @@ -136,6 +136,12 @@ pub struct SessionRuntimeContext { /// Peer endpoint of the gateway replica serving this supervisor's shared /// host. When set, sessions dial it instead of the configured address. pub gateway_home: Option>>, + /// Program status from workload terminals. Every session proposes idle + /// stops from it once it waits past `idle_timeout`. + pub workload_activity: Option>, + /// The sandbox's effective idle stop timeout, kept current by the + /// configuration poller. + pub idle_timeout: crate::program_status::IdleTimeout, } /// Parse a gRPC endpoint URI into an OCSF `Endpoint` (host + port). Falls back @@ -432,6 +438,8 @@ pub fn spawn_with_readiness( config_apply_tx: runtime.config_apply_tx, config_push_updates: runtime.config_push_updates, gateway_home: runtime.gateway_home, + workload_activity: runtime.workload_activity, + idle_timeout: runtime.idle_timeout, ready_tx, }; (tokio::spawn(run_session_loop(config)), ready_rx) @@ -453,6 +461,8 @@ struct SessionConfig { /// reconnect to a gateway that does not push resumes polling. config_push_updates: watch::Sender, gateway_home: Option>>, + workload_activity: Option>, + idle_timeout: crate::program_status::IdleTimeout, ready_tx: watch::Sender, } @@ -714,6 +724,7 @@ async fn run_single_session( supports_session_redirect: true, supports_config_push: true, supports_service_advertisements: config.app_installations.is_some(), + supports_idle_proposals: config.workload_activity.is_some(), })), }) .await @@ -793,6 +804,16 @@ async fn run_single_session( spawn_config_apply(apply_tx.clone(), bootstrap, tx.clone(), &config.sandbox_id); } + // Each session proposes idle stops on its own; the task ends with the + // session, and the next session proposes again from its own ids. + let _idle_reporter = config.workload_activity.as_ref().map(|activity| { + crate::program_status::spawn_idle_reporter( + activity, + config.idle_timeout.clone(), + tx.clone(), + ) + }); + // Main loop: receive gateway messages + send heartbeats. let mut heartbeat_interval = tokio::time::interval(Duration::from_secs(heartbeat_secs)); heartbeat_interval.tick().await; // skip immediate tick diff --git a/crates/openshell-supervisor/src/config_runtime.rs b/crates/openshell-supervisor/src/config_runtime.rs index 02736ad184..8787dd7c1a 100644 --- a/crates/openshell-supervisor/src/config_runtime.rs +++ b/crates/openshell-supervisor/src/config_runtime.rs @@ -689,6 +689,7 @@ impl ConfigRuntime { // Apply OCSF JSON toggle from the `ocsf_json_enabled` setting. apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_idle_stop_setting(&ctx.idle_timeout, &result.settings); report_deprecated_ocsf_schema_version(&ctx.ocsf_schema_version, &result.settings); // Apply the agent-proposals feature toggle. On a false→true transition @@ -1296,6 +1297,7 @@ async fn run_policy_poll_loop_with_client( runtime.applied_revision = Some(sandbox_config_revision(&result)); } apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_idle_stop_setting(&ctx.idle_timeout, &result.settings); report_deprecated_ocsf_schema_version( &ctx.ocsf_schema_version, &result.settings, @@ -1341,6 +1343,7 @@ async fn run_policy_poll_loop_with_client( } (InitialPollDisposition::TrackOnly, _) => { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_idle_stop_setting(&ctx.idle_timeout, &result.settings); report_deprecated_ocsf_schema_version( &ctx.ocsf_schema_version, &result.settings, @@ -1507,6 +1510,30 @@ fn apply_ocsf_json_setting( } } +/// Keep the sandbox's idle reporters on the effective idle stop timeout. +fn apply_idle_stop_setting( + timeout: &openshell_supervisor_process::program_status::IdleTimeout, + settings: &std::collections::HashMap, +) { + use openshell_core::proto::setting_value; + let seconds = settings + .get(openshell_core::settings::IDLE_STOP_AFTER_SECONDS_KEY) + .and_then(|setting| setting.value.as_ref()) + .and_then(|value| value.value.as_ref()) + .and_then(|value| match value { + setting_value::Value::IntValue(seconds) => Some(*seconds), + _ => None, + }); + let next = openshell_core::settings::idle_stop_timeout(seconds); + if timeout.get() != next { + info!( + idle_stop_after_seconds = next.map_or(0, |next| next.as_secs()), + "Idle stop timeout changed" + ); + timeout.set(next); + } +} + /// Extract a bool value from an effective setting, if present. fn extract_bool_setting( settings: &std::collections::HashMap, @@ -2809,6 +2836,7 @@ mod tests { entrypoint_pid: Arc::new(AtomicU32::new(0)), interval_secs: 0, ocsf_enabled: Arc::new(AtomicBool::new(false)), + idle_timeout: openshell_supervisor_process::program_status::IdleTimeout::new(), ocsf_schema_version: Arc::new(std::sync::Mutex::new(String::new())), provider_credentials, provider_readiness, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index fe1cbec6d9..dddb2e1ade 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -1647,6 +1647,10 @@ pub async fn run_sandbox_instance( .as_ref() .map(|instance| instance.routes.clone()); + // The policy poller keeps this on the sandbox's effective + // `idle_stop_after_seconds`; idle reporters on every session read it. + let idle_timeout = openshell_supervisor_process::program_status::IdleTimeout::new(); + // Spawn background policy poll task (gRPC mode only). if let (Some(id), Some(sandbox), Some(gateway), Some(engine)) = ( sandbox_id.as_deref(), @@ -1682,6 +1686,7 @@ pub async fn run_sandbox_instance( entrypoint_pid: poll_pid, interval_secs: poll_interval_secs, ocsf_enabled: poll_ocsf_enabled, + idle_timeout: idle_timeout.clone(), ocsf_schema_version: poll_ocsf_schema_version, provider_credentials: poll_provider_credentials, provider_readiness: provider_readiness.clone(), @@ -1780,6 +1785,7 @@ pub async fn run_sandbox_instance( app_routes .as_ref() .map(app_listener::Routes::installation_source), + idle_timeout, ) .instrument(tracing::info_span!(parent: &startup, "supervisor.access.start")) .await?; @@ -4347,6 +4353,8 @@ struct PolicyPollLoopContext { entrypoint_pid: Arc, interval_secs: u64, ocsf_enabled: Arc, + /// The sandbox's effective idle stop timeout, read by its idle reporters. + idle_timeout: openshell_supervisor_process::program_status::IdleTimeout, /// Last value of the deprecated `ocsf_schema_version` setting. ocsf_schema_version: Arc>, provider_credentials: ProviderCredentialState, diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 075447eec2..d4f518508e 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -1022,6 +1022,41 @@ If an infrastructure failure leaves a sandbox in `Error`, fix the reported cause For a provisioning timeout, wait for cleanup to finish, then run `sandbox start` directly. +### Stop Idle Sandboxes + +The gateway can stop a sandbox whose agent is waiting for you. Agents that +report their state with the OSC 7501 program status protocol, such as Claude +Code and Codex, tell the supervisor when a turn is working, done, or blocked +on a prompt. Set `idle_stop_after_seconds` to stop a sandbox after its +agent has waited that long with no terminal input: + +```shell +openshell settings set my-sandbox --key idle_stop_after_seconds --value 1800 +openshell settings set --global --key idle_stop_after_seconds --value 3600 +``` + +A global value overrides per-sandbox values. Zero or unset disables idle stop. +A sandbox keeps running while its agent reports `working`, and a sandbox whose +programs never report status is never stopped. Typing into the agent's +terminal resets the wait, and input that arrives while a stop is starting +cancels it before compute stops. + +A waiting report describes only the program that sent it. Idle stop does not +see other work in the same sandbox, such as a build in another terminal, a +command started with `openshell sandbox exec`, or a command you run in the +agent's shell after the agent exits. If an agent waits past the timeout while +that work runs, the sandbox stops and the work is lost. Enable idle stop only +for sandboxes where the agent is the only long-running work. + +An idle stop moves the sandbox to `Stopped` with the reason `IdleStopped`. +`openshell sandbox connect` starts such a sandbox before connecting. If the stop +is still in progress, connect waits for it to finish first. Running +`openshell sandbox stop` on it makes the stop explicit, and connect then +reports it as stopped instead. Process +memory is not retained: the canonical command starts fresh, so resume the +agent's conversation with its own option, such as `claude --continue`. Workspace +files persist as they do for any stop. + ### Update the Image of a Stopped Sandbox Use `openshell.v1.SandboxUpdates/UpdateSandbox` to change a stopped sandbox's diff --git a/proto/openshell.proto b/proto/openshell.proto index 6ad3e9e5cd..27d029e750 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -3463,9 +3463,32 @@ message SupervisorMessage { RelayClose relay_close = 4; ConfigUpdateResult config_update_result = 5; SupervisorServiceAdvertisement service_advertisement = 6; + SupervisorWorkloadIdle workload_idle = 7; } } +// The supervisor's idle proposal for its sandbox, or its retraction. +// +// The supervisor applies the sandbox's effective `idle_stop_after_seconds` +// itself. When a workload terminal's program has waited on the user, with no +// client input, for that long, it sends a proposal (`idle` true). It repeats +// the proposal with a new `proposal_id` about once a minute while the program +// keeps waiting. Any input or state change that ends the wait sends a +// retraction (`idle` false) carrying the last proposal's id. Each gateway +// session starts its own ids at 1. +message SupervisorWorkloadIdle { + // Increases with every proposal on this session. A retraction repeats the + // id of the proposal it ends. + uint64 proposal_id = 1; + bool idle = 2; + // The waiting program's state, kind, and app, for logs. Set on proposals. + WorkloadProgramState state = 3; + WorkloadBlockedKind blocked_kind = 4; + string app = 5; + // How long the program has waited, with no client input, when sent. + google.protobuf.Duration idle_for = 6; +} + // Envelope for gateway-to-supervisor messages on the ConnectSupervisor stream. message GatewayMessage { oneof payload { @@ -3506,6 +3529,9 @@ message SupervisorHello { // Gateways push configuration only to supervisors that set this. bool supports_config_push = 7; bool supports_service_advertisements = 8; + // The supervisor sends SupervisorWorkloadIdle proposals and retractions. + // Gateways idle-stop only sandboxes whose current supervisor sets this. + bool supports_idle_proposals = 10; } // Gateway accepts the supervisor session. @@ -4188,6 +4214,28 @@ enum SandboxRestartPolicy { SANDBOX_RESTART_POLICY_ALWAYS = 3; } +// Program state declared by an OSC 7501 report. Kept after existing enums so +// generated enum descriptors remain stable. +enum WorkloadProgramState { + WORKLOAD_PROGRAM_STATE_UNSPECIFIED = 0; + // At rest, waiting for the user's next instruction. + WORKLOAD_PROGRAM_STATE_IDLE = 1; + WORKLOAD_PROGRAM_STATE_WORKING = 2; + // Finished; the result is ready for the user. + WORKLOAD_PROGRAM_STATE_DONE = 3; + // Cannot continue until the user acts. + WORKLOAD_PROGRAM_STATE_BLOCKED = 4; + WORKLOAD_PROGRAM_STATE_ERROR = 5; +} + +// What a blocked program waits for. +enum WorkloadBlockedKind { + WORKLOAD_BLOCKED_KIND_UNSPECIFIED = 0; + WORKLOAD_BLOCKED_KIND_PERMISSION = 1; + WORKLOAD_BLOCKED_KIND_QUESTION = 2; + WORKLOAD_BLOCKED_KIND_AUTH = 3; +} + // Workspace membership record. message WorkspaceMember { openshell.datamodel.v1.ObjectMeta metadata = 1; diff --git a/rfc/0025-workload-idle-stop/README.md b/rfc/0025-workload-idle-stop/README.md new file mode 100644 index 0000000000..fc24232b41 --- /dev/null +++ b/rfc/0025-workload-idle-stop/README.md @@ -0,0 +1,447 @@ +--- +authors: + - "@mrunalp" +state: draft +links: + - https://github.com/ai-openshell/openshell/issues/5852 + - https://github.com/ai-openshell/openshell/pull/5856 +--- + +# RFC 0025 - Stop Idle Agent Sandboxes + +## Summary + +The supervisor reads the program status that coding agents already write to +their terminal with OSC 7501, the Program Status Protocol. When an agent has +been waiting on the user for longer than a configured timeout, the supervisor +proposes an idle stop and the gateway stops the sandbox. +A later `openshell sandbox connect` starts the sandbox again before connecting. + +Phase 1 uses the existing stop and start lifecycle. Filesystem state survives, +and the agent resumes its conversation from disk. Phase 2 reuses the same +activity signal to drive the existing `SuspendSandbox` and `ResumeSandbox` +contracts once a backend implements memory checkpoints. + +## Motivation + +Agent sandboxes spend most of their life waiting. A coding agent finishes a +turn, reports its result, and then sits at a prompt until a person comes back, +often hours later or never. The sandbox keeps its CPU and memory reservations +and its node or VM the whole time. Operators clean up by hand or not at all. + +OpenShell cannot tell an idle agent from a busy one today. The only activity +signal is the network connection summary the supervisor sends for telemetry. +An agent waiting on a person and a long build that makes no connections look +the same from outside. Screen scraping, such as matching a spinner in the +window title, is fragile and differs for every agent. + +OSC 7501 ([spec](https://www.superlogical.com/rex/docs/build/program-status), +[announcement](https://mitchellh.com/writing/program-status-osc7501)) gives +programs a standard way to declare `idle`, `working`, `done`, `blocked`, or +`error` on their own terminal. Claude Code (from v2.1.295) and Codex (0.170.0 +verified) report it natively. The workload PTY already passes through the supervisor, so OpenShell +can read these reports without agent-specific integrations or new workload +dependencies. + +The lifecycle side is partly built. `StopSandbox`, `StartSandbox`, +`SuspendSandbox`, and `ResumeSandbox` exist in the public and driver APIs, but +nothing stops a sandbox on its own and no driver implements suspend. + +## Non-goals + +- Memory checkpoints. Phase 1 stops compute and loses process memory. CRIU or + VM snapshots are phase 2 and follow the suspend contract, not this RFC. +- Detecting idleness for programs that do not report OSC 7501. A sandbox with + no reports is never stopped automatically. A waiting report describes only + its own program. Phase 1 does not see other work in the same sandbox: + - a non-reporting terminal; + - a non-PTY `sandbox exec`; + - a command run in a shell after its agent exited. + + Users can rely on idle stop only when the reporting agent is the sandbox's + only long-running work, and the docs say so. +- Showing program status to clients. Phase 1 does not expose the reported + state through `GetSandbox`, `WatchSandbox`, or `ListSandboxes`; Open + questions records how a later change could. +- Waking on inbound service traffic. Only an explicit connect or start wakes a + sandbox in phase 1. +- Interpreting the free-text `msg` and `title` fields. They are validated and + then dropped, never stored or logged. +- Agent-specific resume logic. OpenShell restarts the canonical command; the + agent's own `--continue` or `resume` flags restore its conversation. + +## Proposal + +### Observe program status in the supervisor + +The supervisor scans PTY output for OSC 7501 in two places: + +- the canonical process reader (`openshell-supervisor-process/src/main_session.rs`) +- the SSH exec loop for PTY sessions (`ssh.rs`) + +Both run on plaintext before output reaches any client, and the canonical +reader runs whether or not a client is attached. + +The scanner keeps the per-terminal records the protocol defines: + +- record ids and hierarchy; +- `clear` semantics; +- drop `working` and `blocked` records on process exit or OSC 133 `A`; +- the 256-record cap; +- the 4096-byte sequence limit. + +Report bytes pass through unchanged, so a supporting client terminal still +shows status. + +The supervisor answers the support query (`OSC 7501 ; ?`) itself by writing +the reply to the program's input, and strips the query from forwarded output. +The reply is the full form, `OSC 7501 ; ? : states=... : kinds=... ST`. A +program that probes with terminal echo on reads its own echo, and a reply +identical to the query would be answered again without end. + +Answering the probe is required, not an optimization. A prototype run against +Claude Code 2.1.327 showed: + +- It probes at startup, followed by a DA1 (`CSI c`) query. +- It reports only if the OSC 7501 reply arrives before the DA1 reply. That + follows the spec's detection rule. +- The supervisor's reply reaches the program before any client terminal's. +- Stripping the query keeps a supporting client terminal from answering a + second time into the program's input. + +The supervisor keeps the result as a sandbox-wide summary: the most active +state across terminals (working, then blocked, error, done, idle), plus its +`kind` and `app`. It also tracks when that state began and when any client +last wrote to a workload terminal. + +Observed behavior through the supervisor's scanner: + +| Event | Claude Code 2.1.327 | Codex 0.170.0 | +|-------|---------------------|---------------| +| Support query | Sent at startup | Never sent | +| Startup | `idle` | `idle` | +| Prompt submitted | `working` | `working` | +| Turn finished | `done` | `done` | +| Folder trust or approval prompt | `blocked:kind=permission` | `blocked:kind=permission` | +| Approval denied or interrupted | `clear` | `working`, then `idle` | +| Exit | `clear` | `clear` | + +Neither agent returns to `idle` after a finished turn, so the policy treats +`done` as waiting on the user. Codex reports without querying first, so the +scanner keeps records for every terminal whether or not its program asked. + +### Propose idle stops from the supervisor + +The supervisor owns the idle clock. It already tracks when the sandbox-wide +state began and when client input last arrived, and it receives runtime +settings through its configuration poller. It applies the sandbox's effective +`idle_stop_after_seconds` itself and tells the gateway only when to stop: + +```proto +message SupervisorMessage { + oneof payload { + // ... existing variants 1-6 ... + SupervisorWorkloadIdle workload_idle = 7; + } +} + +message SupervisorWorkloadIdle { + uint64 proposal_id = 1; // increases per proposal on a session + bool idle = 2; // true: proposal; false: retraction + WorkloadProgramState state = 3; // for logs + WorkloadBlockedKind blocked_kind = 4; + string app = 5; // OSC 7501 app grammar + google.protobuf.Duration idle_for = 6; // wait when sent +} +``` + +`SupervisorHello.supports_idle_proposals` (field 10) advertises it. The gateway +idle-stops only sandboxes whose current supervisor sets it, so a supervisor +too old to propose is never stopped. + +On each gateway session, an idle reporter checks every second and on every +summary change. Once some program reports, none is `working`, and the later of +the state change and the latest client input is older than the timeout, it +sends a proposal. While the wait continues it repeats the proposal with a new +id every minute, in case the gateway declined it under a longer gateway-side +setting. Input or a state change that ends the wait sends a retraction with +the last proposal's id. Each session starts its ids at 1, so a reconnect, or a +session moved to another replica, proposes again. The reporter runs on its +own task and never blocks the session's receive loop. + +The supervisor applies reports, OSC 133 `A` prompts, and full resets (RIS) in +output order, however reads split them. A prompt ends only the reports before +it, and a reset clears the terminal's records as the spec requires. The +scanner treats `ESC c` outside an OSC as a reset, including inside other +control strings; a terminal ends those strings at `ESC` and resets too. Every +transition restarts the state timer and advances a revision, including a +`working` → `done` turn within one read. The latest input time outlives the +terminal that received it. + +Proposals write nothing to the store and add no public `Sandbox` fields, so +SDK users who build exhaustive `SandboxStatus` literals still compile, as the +`sandbox_status_compatibility` fixture requires. + +### Stop idle sandboxes + +The timeout is a new runtime setting, `idle_stop_after_seconds`, set with +`openshell settings set` at gateway or sandbox scope. As with every runtime +setting, gateway scope wins over sandbox scope. It can be changed on a running +sandbox and reaches the supervisor with its next configuration update. Unset, +zero, or negative disables idle stop, and values above 30 days are capped. No +new `SandboxSpec` field or gateway TOML key is needed. + +The replica holding the supervisor session keeps that session's latest +proposal in memory. A proposal from a replaced session, or an older one from +the current session, is dropped, and a retraction removes the proposal it +names. A gateway that restarts stops nothing until the new session proposes, +so a workload that resumed work during an outage is not stopped on a stale +record. A proposal starts at most one idle stop per sandbox, through the +existing stop path with an idle cause. + +Under the lifecycle lock, each `Stopping` write attempt requires: + +- the same session's proposal still held; +- phase `Ready`, on the proposing main-process instance; +- the gateway's own effective timeout, reached by the proposal's wait, so a + supervisor still on an older, shorter setting does not decide; +- a fresh shared owner record that names the session. + +After the `Stopping` write and before the driver call, the stop checks the +proposal again. A retraction or session change received in between rolls the +sandbox back to its previous state and abandons the stop. If that rollback +loses a write race, the stop goes ahead like any other in-flight stop. No +report waits on a store write, so the session keeps reading messages +throughout. + +The stop boundary is therefore: + +- **Always counted:** input or a new turn that the supervisor sees, and whose + retraction reaches the gateway, before the check that follows the `Stopping` + write. +- **Can race the stop:** input in the last second before that check, which + the reporter has not yet noticed, and anything after it while the driver + call runs. + +A takeover by another replica is bounded the same way. The new owner publishes +ownership before it updates the sandbox record, and the new session's +proposals start over, so the old session's proposal no longer holds once the +new session registers. + +The idle request writes the internal annotation `internal.openshell.ai/idle-stop` +with the reason `IdleStopping`. The annotation survives gateway recovery and +driver snapshots that rewrite conditions. The Ready condition then settles as +`IdleStopped` instead of `Stopped`, so users and the CLI can tell an idle stop +from an explicit one. The gateway reapplies that reason when a driver snapshot +of the stopped runtime rewrites it. Any other lifecycle write removes the +annotation, including a rollback. An explicit `sandbox stop` rewrites an idle +stop as an ordinary stop, so `sandbox connect` no longer starts it. This holds +whether the idle stop has settled or is still waiting on the driver on another +replica. The gateway logs each idle stop with the sandbox, the program, and how +long it waited. + +```mermaid +sequenceDiagram + participant A as Agent (PTY) + participant S as Supervisor + participant G as Gateway + participant D as Compute driver + A->>S: OSC 7501 support query + S->>A: Support reply + A->>S: state=done:app=claude-code + Note over S: done, no input, for idle_stop_after_seconds + S->>G: SupervisorWorkloadIdle(idle, proposal_id 1) + G->>G: checks, then the Stopping write + G->>G: proposal still held + G->>D: StopSandbox + G->>G: phase Stopped, reason IdleStopped +``` + +### Wake on connect + +When the target is `Stopped` with reason `IdleStopped`, +`openshell sandbox connect` calls `StartSandbox`, waits for `Ready`, then +connects as usual, printing a one-line notice. When an idle stop is still in +flight (`Stopping` with reason `IdleStopping`, which the gateway keeps through +driver snapshots), connect first waits for the sandbox to leave `Stopping`: + +- `Ready`, as after a rolled-back stop, connects directly; +- `Starting`, as when another client already restarted it, waits for `Ready`; +- `Stopped` with `IdleStopped` starts it. An explicitly stopped +sandbox keeps today's behavior and returns an error. The wake logic lives in the +CLI; the TUI and SDK do not wake sandboxes in phase 1. + +Exec and SSH proxy paths keep their current errors in phase 1, so scripts do +not start sandboxes implicitly. + +### Security and trust + +The workload controls the signal: + +- Falsely reporting `working` only keeps its own sandbox running, which it can + already do by staying busy. +- Falsely reporting `idle` stops its own sandbox. +- Neither crosses a trust boundary. + +A stray report, such as a program printing a log file that contains OSC 7501 +bytes, can make a sandbox look idle. The input-age condition limits the damage +to sandboxes no one is typing into. + +The supervisor writes only the fixed reply bytes to program input, never +report content. `msg` and `title` are validated per the spec, then discarded. + +## Implementation plan + +1. **Supervisor observation.** Add the OSC 7501 scanner, records, probe reply, + and summary in `openshell-supervisor-process`. Wire them into the canonical + reader and SSH PTY sessions, with unit tests for parsing, chunk splits, + limits, and record semantics. A prototype harness has run Claude Code + 2.1.327 and Codex 0.170.0 through the scanner on a host PTY. +2. **Proposals.** Register the `idle_stop_after_seconds` setting, deliver it + to the supervisor's idle reporter, and add `SupervisorWorkloadIdle`. +3. **Policy.** Add the gateway handler, the checks before and after the + `Stopping` write, and the `IdleStopped` reason, and document them on the + sandbox lifecycle page. +4. **Wake on connect.** Auto-start `IdleStopped` sandboxes in + `openshell sandbox connect`. +5. **Validation.** Add the `idle_stop` conformance test, which runs a + scripted OSC 7501 agent on every driver through two sequences. + `IdleStopped`, then `sandbox connect`, starts it again. + `IdleStopped`, then an explicit stop, then `sandbox connect`, leaves it + stopped. Check Claude Code and Codex manually inside Docker + and Kubernetes sandboxes, with provider credentials. +6. **Phase 2 (separate change).** Choose `suspend` instead of `stop` when the + driver advertises `openshell.compute.suspend-resume`, and implement Podman + checkpoint and restore behind that capability. + +Idle stop is off by default, so existing users see no change until an operator +sets a gateway value or a user opts in per sandbox. + +## Risks + +- **Lost in-flight work.** A `blocked` agent loses the pending turn when + stopped. The timeout applies to all waiting states in phase 1. If users find + that too aggressive, a separate blocked timeout is an open question. +- **Agent coverage and drift.** Only agents that implement OSC 7501 benefit, + and their reporting can change between releases, as Claude Code's + probe-before-report rule shows. Unreported sandboxes are never stopped, so + drift fails safe. +- **Multiplexers.** An agent inside tmux in the sandbox probes tmux, not the + supervisor's PTY, and tmux does not forward the reports. Those sandboxes look + unreported and stay running. +- **Conversation resume depends on storage.** The agent's transcript must live + on storage that survives stop: the Docker writable layer or workspace volume, + the Kubernetes PVC, the VM overlay. Agents restarted with their plain command + start a fresh conversation unless the user runs their resume flag. +- **Residual stop race.** Input in the second before the check that follows + the `Stopping` write, or during the driver call, can still lose the + sandbox, and only one that already waited past its timeout. Closing it + fully would need the supervisor to hold input until compute stops. +- **Version skew.** Only supervisors that advertise `supports_idle_proposals` + are stopped. A gateway paired with an older supervisor leaves its sandboxes + running. + +## Alternatives + +### Screen or title scraping + +Inbox tools such as Herdr detect Claude Code state by matching the Braille +spinner in the window title. That needs a parser per agent and breaks on UI +changes. OSC 7501 is a declared contract with a published grammar. + +### Network or input inactivity only + +Stopping after no egress and no keystrokes needs no agent cooperation. But it +cannot tell a quiet long-running build from a waiting agent, and it would stop +sandboxes mid-task. It remains useful as an extra condition and may become an +opt-in policy for non-reporting workloads later. + +### Agent hooks or SDK callbacks + +Claude Code hooks and similar mechanisms can call out when a turn ends, but +each agent needs its own configuration inside the sandbox image, and the hook +runs as workload code with network access. The terminal channel needs nothing +from the image. + +### Decide idleness in the gateway + +Earlier versions had the supervisor stream every summary, with relative ages, +and the gateway rebuild the idle clock from them. A 30-second sweep found due +sandboxes, added a 15-second allowance for input reports still in flight, and +then asked the supervisor to confirm with a fresh summary. A per-sandbox gate +held reports back during the `Stopping` write. The confirmation was the only +reading that authorized a stop, so the gateway's clock only decided when to +ask. It needed input-only reports, summary sequence numbers, the sweep, and the +gate, and the gate made the session's receive loop wait on a store write. +Moving the clock to the supervisor removes all of that. + +### Show program status in this change + +Earlier versions of this change showed the report as a `ProgramStatus` +condition. Writing it to the sandbox record cost an active agent two writes +per turn even with idle stop disabled. Each write bumped the resource version +and woke watchers, and needed owner fencing, conflict retries, and +preservation across driver snapshots and phase changes. Attaching it at read +time removed the writes, but `ListSandboxes` and watchers on other replicas +could not see it, and each of their watch events cost a peer call. Idle stop +does not depend on the display, so it is left to a later change; see Open +questions. + +### Do nothing + +Operators keep deleting or stopping sandboxes by hand, and idle sandboxes keep +holding capacity. + +## Prior art + +- [Program Status Protocol (OSC 7501)](https://www.superlogical.com/rex/docs/build/program-status): + record lifetime and the detection rule shape the scanner directly. The spec + also says the program owns its state, which is why OpenShell treats reports + as untrusted input. +- [Paneflow](https://paneflow.dev/blog/agent-status-osc-7501) answers the probe + on behalf of its sessions and treats an agent's declaration as more reliable + than heuristics. That is the same position the supervisor takes. +- Kubernetes scale-to-zero (KEDA, Knative) separates the activity signal from + the lifecycle action and wakes on demand. Idle proposals and wake on connect + follow that split. +- [RFC 0018](../0018-multi-sandbox-ha-supervisors/README.md) leaves room for + backend-initiated suspend and wake (#4352). This RFC supplies the signal that + decides when. + +## Open questions + +- Should `blocked` get its own, longer timeout, or never stop? It loses the + pending turn in phase 1 but not in phase 2. +- Should an attached client with no input block idle stop? Phase 1 does not + wait for clients to detach. +- Should a sandbox whose terminals all reported `clear` (agent exited, shell + idle at a prompt) count as idle? Phase 1 treats it as unreported. +- Should the wake path also run the agent's resume command, for example via a + `SandboxSpec` resume command, or is restarting the canonical command enough? +- Should waking move into the gateway, so the TUI, the SDK, exec, and SSH proxy + wake an `IdleStopped` sandbox too, and clients stop matching condition + reasons? Phase 1 wakes only from `openshell sandbox connect`. +- Should idle stop ship behind an `unstable-idle-stop` compile flag until it is + accepted, as RFC 0014 asks of unreleased features? No crate defines such a + flag yet; phase 1 is off unless the setting is set. +- Is gateway-over-sandbox precedence right for this setting? It lets operators + enforce a fleet timeout, but it stops users from choosing a shorter or longer + one or exempting a sandbox, and a global `0` disables per-sandbox opt-in. + Sandbox-over-gateway, or `min(global, sandbox)` with the global as a ceiling, + are alternatives. +- Should other activity hold off an idle stop: a running non-PTY `exec`, an open + terminal with no report, or recent output on one? The supervisor already + tracks output time but does not report it. +- Should a new shell command (OSC 133 `C`) clear a terminal's retained `done`, + `error`, or `idle` record, so a non-reporting command started after an agent + exits is not judged by the agent's last report? The OSC 7501 spec keeps those + records across prompts. +- How should clients see program status? A later change could store it in its + own lightweight object, keyed by sandbox ID and written by the session owner + on state changes only, like `supervisor_service_installation`, and merge it + into `GetSandbox`, `WatchSandbox`, and `ListSandboxes` on read. + That works across replicas without fan-out, and because it never touches the + sandbox record it causes no compare-and-swap conflicts with lifecycle writes + and no resource-version churn. It costs a write per state change, roughly + two per turn, plus owner fencing and cleanup when a session ends, and live + activity would still be the only input to an idle stop. diff --git a/tests/suites/conformance/src/idle_stop.rs b/tests/suites/conformance/src/idle_stop.rs new file mode 100644 index 0000000000..153c5fcd59 --- /dev/null +++ b/tests/suites/conformance/src/idle_stop.rs @@ -0,0 +1,121 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Idle stop suite: the gateway stops a sandbox whose terminal program +//! reports over OSC 7501 that it is waiting on the user. + +use std::time::Duration; + +use serde_json::Value; +use testkit::sdk::SandboxPhase; +use testkit::sdk::raw::proto; +use testkit::{Context, Sandbox}; + +const KEY: &str = "idle_stop_after_seconds"; + +/// Probe for support as Claude Code does, report that the turn is done, and +/// wait at the prompt. Echo is on, so the supervisor's reply is echoed back. +const AGENT: &str = r"printf '\033]7501;?\033\\'; sleep 1; printf '\033]7501;state=done:app=e2e-agent\033\\'; exec sleep infinity"; + +/// Session setup, the setting reaching the supervisor (one configuration poll +/// at worst), the timeout, and the stop itself. +const IDLE_STOP_DEADLINE: Duration = Duration::from_secs(90); +/// Connect prints its notice, then starts the sandbox and waits for Ready. +const WAKE_DEADLINE: Duration = Duration::from_secs(60); + +/// A sandbox whose program reports `done` is stopped with reason +/// `IdleStopped` once its idle timeout passes, and `sandbox connect` starts it +/// again. After a later idle stop, an explicit `sandbox stop` keeps it +/// stopped: `sandbox connect` then fails instead of starting it. +#[testkit::test] +async fn idle_stopped_sandbox_wakes_on_connect_until_stopped_explicitly( + cx: &mut Context, +) -> testkit::Result { + let sandbox = cx + .sandbox("idle") + .command(["sh", "-c", AGENT]) + .spec(|spec| spec.tty = true) + .create_ready() + .await?; + set_idle_timeout(&sandbox, 1).await?; + expect_idle_stopped(&sandbox).await?; + + let mut connect = cx.cli_spawn(["sandbox", "connect", sandbox.name()])?; + connect + .stderr_until(WAKE_DEADLINE, |line| line.contains("stopped while idle")) + .await?; + // Connect reports the start only after the sandbox is Ready again. + connect + .stdout_until(WAKE_DEADLINE, |line| line.contains("Started sandbox")) + .await?; + sandbox.wait_ready().await?; + connect.kill().await?; + + // The restarted program reports again and is idle-stopped again. + expect_idle_stopped(&sandbox).await?; + + sandbox.stop().await?; + let reason = ready_reason(&sandbox.get_json().await?); + testkit::ensure!( + reason != "IdleStopped", + "an explicit stop kept the idle reason, so connect would start it" + ); + let connected = cx.cli(["sandbox", "connect", sandbox.name()]).await?; + testkit::ensure!( + connected.exit_code != 0, + "sandbox connect succeeded against an explicitly stopped sandbox" + ); + let phase = sandbox.get().await?.phase; + testkit::ensure!( + phase == SandboxPhase::Stopped, + "sandbox connect changed an explicitly stopped sandbox to {phase:?}" + ); + Ok(()) +} + +/// Wait for an idle stop and check that it kept its own reason. +async fn expect_idle_stopped(sandbox: &Sandbox) -> testkit::Result { + sandbox + .wait_phase(SandboxPhase::Stopped, IDLE_STOP_DEADLINE) + .await?; + let reason = ready_reason(&sandbox.get_json().await?); + testkit::ensure!( + reason == "IdleStopped", + "sandbox {} stopped with reason {reason:?}; expected IdleStopped", + sandbox.name() + ); + Ok(()) +} + +/// Set the sandbox's idle timeout and check the effective value, which a +/// global setting would override. +async fn set_idle_timeout(sandbox: &Sandbox, seconds: i64) -> testkit::Result { + sandbox + .set_setting(KEY, proto::setting_value::Value::IntValue(seconds)) + .await?; + let config = sandbox.config().await?; + let value = config + .settings + .get(KEY) + .and_then(|setting| setting.value.as_ref()) + .and_then(|value| value.value.clone()); + testkit::ensure!( + value == Some(proto::setting_value::Value::IntValue(seconds)), + "effective {KEY} is {value:?}; delete the global value with `openshell settings delete --global --key {KEY}`" + ); + Ok(()) +} + +fn condition<'a>(sandbox: &'a Value, kind: &str) -> Option<&'a Value> { + sandbox["conditions"] + .as_array()? + .iter() + .find(|condition| condition["type"] == kind) +} + +fn ready_reason(sandbox: &Value) -> String { + condition(sandbox, "Ready") + .and_then(|ready| ready["reason"].as_str()) + .unwrap_or_default() + .to_string() +} diff --git a/tests/suites/conformance/src/lib.rs b/tests/suites/conformance/src/lib.rs index 8ac23f54bc..6f33eae5e3 100644 --- a/tests/suites/conformance/src/lib.rs +++ b/tests/suites/conformance/src/lib.rs @@ -15,6 +15,7 @@ mod credential_gating; mod exec_cli; mod file_transfer; mod filesystem_policy; +mod idle_stop; mod image; mod labels; mod lifecycle;