From d59f21fb3b7e344450ae2fd48341b6e5690f9c31 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:26:48 +0800 Subject: [PATCH 01/20] refactor(exec): one stop entry and one terminal source for shell tasks Shell tasks now have the same owner as every other exec task: - `BackgroundExec.stop` is the only stop entry. `dyn ExecStop`, `exec_stop.rs` and the optional-service reads (`Session::service_opt`, `Branch::service_opt`, the internal `TimelineContext::public_opt`) are removed, and `session.exec.stop` calls `BackgroundExec` in every profile with one error mapping and `exec_task_read` for read failures. - ShellSession hands a background job and a foreground command that outlives its wait to `BackgroundExec.start` with the owner task id. Its own background task table, settlement and synthesized reset results are gone; the shell queue and occupancy policy stay, and the queue only waits for the occupying command's terminal. - The owner's task terminal is the only terminal source: a foreground command returns it as the tool result, a handed-off task is published once as `exec/ended`, and shell exit sweeps children to their terminals instead of the shell layer composing results. - ShellSession no longer reads shell output: its retained buffer, the private lossless shell event page and the job-marker stripping are removed. HostPlatform already parses the markers; the init command waits for its own terminal. Refs #2032 --- .../dim-agent-capabilities/src/exec_stop.rs | 26 - .../src/host_platform.rs | 225 +-- crates/dim-agent-capabilities/src/lib.rs | 3 - .../src/shell_session.rs | 1220 ++++------------- crates/dim-agent-runtime/src/agent.rs | 4 - crates/dim-agent-runtime/src/branch.rs | 3 - .../dim-agent-runtime/src/timeline_context.rs | 4 - crates/dim-app-server/src/connection.rs | 33 +- .../rust-agent/capability-event-inventory.md | 6 +- .../rust-agent/plugins/WorkspaceTools.md | 18 +- docs/design/agent-tool-modes.md | 18 +- docs/design/service-faces.md | 2 +- docs/design/shell-exec-recovery.md | 39 +- tests/integration/tests/minimal_execution.rs | 57 +- 14 files changed, 377 insertions(+), 1281 deletions(-) delete mode 100644 crates/dim-agent-capabilities/src/exec_stop.rs diff --git a/crates/dim-agent-capabilities/src/exec_stop.rs b/crates/dim-agent-capabilities/src/exec_stop.rs deleted file mode 100644 index f060a5a572..0000000000 --- a/crates/dim-agent-capabilities/src/exec_stop.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! The unified background-task stop port. -//! -//! ShellSession provides `dyn ExecStop` for stopping the minimal profile's -//! shell tasks. It depends on BackgroundExec for recovery; -//! live PTY cancellation remains owned by ShellSession. The local profile -//! uses BackgroundExec's own service and face for native-process stops. - -use dim_agent_types::ExecEndedData; -use rutis::host::BoxFuture; -use std::sync::Arc; - -/// Stop-path errors. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TaskError { - Unknown, - Closed, - Read, -} - -/// Stops a background task by id. -pub trait ExecStop: Send + Sync + 'static { - fn stop( - self: Arc, - task_id: String, - ) -> BoxFuture<'static, Result>; -} diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index a2d288f9c0..2da67e6563 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -440,21 +440,6 @@ pub struct OutputPageReply { pub reset: Option, } -#[derive(Clone, Debug, serde::Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub(crate) enum ShellEvent { - Output { cursor: u64, text: String }, - Marker { cursor: u64, line: String }, -} - -impl ShellEvent { - pub(crate) fn cursor(&self) -> u64 { - match self { - Self::Output { cursor, .. } | Self::Marker { cursor, .. } => *cursor, - } - } -} - /// A request to start a persistent PTY shell on this execution node. #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -632,20 +617,6 @@ pub struct OutputRequest { pub limit: Option, } -#[derive(serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub(crate) struct ShellEventRequest { - pub task_id: String, - pub cursor: u64, - pub wait_ms: u64, - pub limit: usize, -} - -pub(crate) struct ShellEventPage { - pub events: Vec, - pub next_cursor: u64, -} - #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct OutputPathReply { @@ -1409,13 +1380,6 @@ impl HostPlatform { } } - pub(crate) fn job_marker(&self, id: &str) -> Option { - match &self.task(id)?.kind { - TaskKind::Job(job) => Some(job.end_marker.clone()), - _ => None, - } - } - pub(crate) fn job_completion( &self, id: &str, @@ -1778,24 +1742,6 @@ impl HostPlatform { }) } - /// The private ShellSession transport: the lossless owner event page. - /// Not a public data-face operation and never exposed through TypeScript. - pub(crate) async fn shell_events( - &self, - request: ShellEventRequest, - ) -> Result { - let shell = self - .shell_task(&request.task_id) - .ok_or(HostPlatformError::TaskUnknown)?; - let page = shell - .events_page(request.cursor, Some(request.wait_ms), request.limit) - .await; - Ok(ShellEventPage { - events: page.events, - next_cursor: page.next_cursor, - }) - } - /// Writes the captured output to the task's log file and returns its path. pub async fn retain_output( &self, @@ -4029,13 +3975,12 @@ pub(crate) mod shell { OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page, }; use std::{ - collections::VecDeque, io::{self, Read, Write}, path::{Path, PathBuf}, sync::{Arc, Mutex, Weak}, - time::{Duration, Instant}, + time::Duration, }; - use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; + use tokio::sync::{Mutex as AsyncMutex, watch}; use tokio_util::sync::CancellationToken; const RETAINED: usize = 64 * 1024; @@ -4049,10 +3994,8 @@ pub(crate) mod shell { pub(crate) struct ShellTask { pty: AsyncMutex>, capture: Mutex, - events: Mutex, active_command: Mutex>>, children: Mutex>>, - event_notify: Arc, kill: CancellationToken, path: PathBuf, edition: super::ShellEdition, @@ -4263,8 +4206,6 @@ pub(crate) mod shell { } } - const EVENT_RETAIN_CHARS: usize = 1024 * 1024; - fn parse_shell_job(line: &str) -> Option<(String, u32)> { let (prefix, tail) = last_full_marker(line)?; if prefix != "__DIM_END_" { @@ -4276,13 +4217,6 @@ pub(crate) mod shell { Some((task_id.to_owned(), pid)) } - fn shell_event_len(event: &super::ShellEvent) -> usize { - match event { - super::ShellEvent::Output { text, .. } => text.len(), - super::ShellEvent::Marker { line, .. } => line.len(), - } - } - fn last_full_marker(line: &str) -> Option<(&'static str, &str)> { let mut found: Option<(usize, (&'static str, &str))> = None; for (prefix, position) in [ @@ -4313,113 +4247,6 @@ pub(crate) mod shell { found.map(|(_, marker)| marker) } - #[derive(Default)] - struct ShellEvents { - items: VecDeque, - pending: String, - base: u64, - next: u64, - chars: usize, - } - - impl ShellEvents { - fn push(&mut self, text: String) { - self.pending.push_str(&text); - while let Some(newline) = self.pending.find('\n') { - let line: String = self.pending.drain(..=newline).collect(); - let cursor = self.next; - self.next += 1; - self.chars += line.len(); - if last_full_marker(&line).is_some() { - self.items - .push_back(super::ShellEvent::Marker { cursor, line }); - } else { - self.items - .push_back(super::ShellEvent::Output { cursor, text: line }); - } - } - if self.pending.len() > 65536 { - let cursor = self.next; - self.next += 1; - let text = std::mem::take(&mut self.pending); - self.chars += text.len(); - self.items - .push_back(super::ShellEvent::Output { cursor, text }); - } - } - - fn trim(&mut self) { - let mut removed = false; - while self.chars > EVENT_RETAIN_CHARS { - let Some(front) = self.items.pop_front() else { - break; - }; - self.chars = self.chars.saturating_sub(shell_event_len(&front)); - removed = true; - } - if removed { - self.base = self - .items - .front() - .map(super::ShellEvent::cursor) - .unwrap_or(self.next); - } - } - - fn finish(&mut self) { - if self.pending.is_empty() { - return; - } - let cursor = self.next; - self.next += 1; - let text = std::mem::take(&mut self.pending); - self.chars += text.len(); - self.items - .push_back(super::ShellEvent::Output { cursor, text }); - } - - fn page(&mut self, cursor: u64, limit: usize) -> EventPage { - while let Some(front) = self.items.front() { - if front.cursor() >= cursor { - break; - } - if let Some(front) = self.items.pop_front() { - self.chars = self.chars.saturating_sub(shell_event_len(&front)); - self.base = front.cursor() + 1; - } - } - let reset = cursor < self.base; - let mut events = Vec::new(); - let mut used = 0; - for event in self.items.iter().filter(|event| event.cursor() >= cursor) { - let length = shell_event_len(event); - if !events.is_empty() && used + length > limit { - break; - } - used += length; - events.push(event.clone()); - if used >= limit { - break; - } - } - let next_cursor = events - .last() - .map(|event| event.cursor() + 1) - .unwrap_or(cursor.max(self.base)); - EventPage { - events, - next_cursor, - reset, - } - } - } - - pub(crate) struct EventPage { - pub(crate) events: Vec, - pub(crate) next_cursor: u64, - pub(crate) reset: bool, - } - #[derive(Default)] struct OutputFilter { decoder: Decoder, @@ -4608,10 +4435,8 @@ pub(crate) mod shell { let shell = Arc::new(ShellTask { pty: AsyncMutex::new(None), capture: Mutex::default(), - events: Mutex::default(), active_command: Mutex::new(None), children: Mutex::new(Vec::new()), - event_notify: Arc::new(Notify::new()), kill: CancellationToken::new(), path, edition: runtime.edition, @@ -4675,14 +4500,6 @@ pub(crate) mod shell { } } drop(capture); - { - let mut events = pump.events.lock().unwrap(); - events.trim(); - if !shell_record.is_terminal() { - events.push(chunk); - } - } - pump.event_notify.notify_waiters(); } let (raw_tail, tail) = filter.finish(); if !raw_tail.is_empty() { @@ -4710,15 +4527,11 @@ pub(crate) mod shell { let _ = file.write_all(&tail.as_bytes()[..take]); } drop(capture); - let mut events = pump.events.lock().unwrap(); - events.trim(); - events.push(tail); } - if let Some(pump) = pump.upgrade() { - if let Some(line) = splitter.finish() { - classify_line(&line, &pump, &jobs); - } - pump.events.lock().unwrap().finish(); + if let Some(pump) = pump.upgrade() + && let Some(line) = splitter.finish() + { + classify_line(&line, &pump, &jobs); } let _ = drained.send(()); }); @@ -4901,32 +4714,6 @@ pub(crate) mod shell { } } - pub(crate) async fn events_page( - &self, - cursor: u64, - wait_ms: Option, - limit: usize, - ) -> EventPage { - let wait = wait_ms.unwrap_or(0); - let deadline = Instant::now() + Duration::from_millis(wait.min(86_400_000)); - loop { - let page = { - let mut events = self.events.lock().unwrap(); - let page = events.page(cursor, limit); - drop(events); - page - }; - if !page.events.is_empty() || page.reset || wait == 0 || Instant::now() >= deadline - { - return page; - } - let remaining = deadline.saturating_duration_since(Instant::now()); - tokio::select! { - _ = self.event_notify.notified() => {} - _ = tokio::time::sleep(remaining) => {} - } - } - } pub(crate) async fn write(&self, data: &[u8]) -> io::Result<()> { self.pty .lock() diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index b07b480373..c64eabcc4f 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -12,7 +12,6 @@ pub mod context_preparation; mod context_usage; pub mod defaults; pub mod environment_clients; -pub mod exec_stop; pub mod execution_settings; pub mod file_access; pub mod file_storage; @@ -119,7 +118,6 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { register::(catalog, branch); register::(catalog, branch); register::(catalog, branch); - register::(catalog, branch); register::(catalog, branch); register::(catalog, branch); catalog.register_shared_instance("branchLine", BRANCH_GROUP); @@ -146,7 +144,6 @@ impl PublicService for input_queue::SubmitChecks {} impl PublicService for permission::Permission {} impl PublicService for workspace_tools::background::BackgroundExec {} impl PublicService for shell_session::ShellSession {} -impl PublicService for dyn exec_stop::ExecStop {} impl PublicService for workspace_tools::file_reads::FileReads {} impl PublicService for timeline_tree::BranchLine {} impl PublicService for timeline_tree::TreeCommands {} diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index b3dfdf9602..1720db4c54 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -1,50 +1,37 @@ //! Persistent shell execution capability: one long-lived PTY shell per branch. //! //! Every command runs in the same interactive shell, wrapped with runtime -//! marker pairs: the -//! command text carries the fragments only, so echoes cannot forge a full -//! marker. A dedicated OS thread owns the blocking PTY reader and forwards -//! chunks to an async consumer through a channel; no lock is held across a -//! blocking read. Commands are serialized through a queue; a foreground -//! timeout converts the call into an occupying task, and explicit -//! background jobs report completion through their own markers, ending in -//! `exec/ended`. BackgroundExec consumes terminals and owns their notices and recovery. - -use crate::workspace_tools::background::BackgroundExec; +//! marker pairs: the command text carries the fragments only, so echoes cannot +//! forge a full marker. HostPlatform owns the PTY, reads it, parses the markers +//! and records each command's and job's terminal. This part owns the queue and a +//! foreground timeout moves the running command to BackgroundExec; explicit +//! background jobs go there too. BackgroundExec publishes every shell task's +//! terminal, its completion notice and its recovery. + +use crate::workspace_tools::background::{BackgroundExec, StartError, StartRequest, WaitError}; use crate::{ - exec_stop::{ExecStop, TaskError}, host::{HostError, SessionFiles}, host_platform::{ HostPlatform, HostPlatformError, OutputRequest, ShellCommandStart, ShellEdition, - ShellEvent, ShellEventRequest, ShellJobStart, ShellRequest, ShellStatus, ShellWrite, - TaskRequest, WaitReply, WaitRequest, WaitStatus, + ShellJobStart, ShellRequest, ShellStatus, ShellWrite, TaskRequest, WaitReply, WaitRequest, + WaitStatus, }, }; use base64::{Engine, engine::general_purpose::STANDARD}; -use dim_agent_runtime::{Dispatcher, Names, SessionLifecycle, Timeline}; -use dim_agent_types::{ - EventKind, ExecEndedData, ExecStartedData, ExecStatus, JsonObject, ToolContent, ToolEffect, - ToolResult, -}; +use dim_agent_runtime::{Dispatcher, Names}; +use dim_agent_types::{ExecEndedData, JsonObject, ToolContent, ToolEffect, ToolResult}; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::json; use std::{ - collections::{HashMap, VecDeque}, + collections::VecDeque, path::{Path, PathBuf}, sync::Arc, time::Duration, }; -use tokio::sync::{Notify, oneshot}; +use tokio::sync::oneshot; use tokio_util::{sync::CancellationToken, task::TaskTracker}; -const RETAINED_BUFFER_LIMIT: usize = 64 * 1024; -/// The size `retained` must pass before it is cut back to -/// `RETAINED_BUFFER_LIMIT`. A burst arrives in thousands of small chunks, so -/// trimming at the limit itself would re-copy the buffer once per chunk; the -/// slack makes the cut amortized while the buffer stays bounded by twice the -/// limit, which is far above the longest marker line it must hold. -const RETAINED_BUFFER_TRIM: usize = 2 * RETAINED_BUFFER_LIMIT; const OUTPUT_LIMIT: usize = 16_000; const MAX_TIMEOUT_MS: u64 = 3_600_000; const DESCRIPTION_CHARS: usize = 200; @@ -83,48 +70,30 @@ struct QueuedCommand { done: oneshot::Sender>, } -/// The foreground call that outlived its timeout; the shell is occupied -/// until its end marker arrives. +/// The foreground call that outlived its timeout; the shell stays occupied +/// until its terminal record arrives. struct OccupyingTask { + /// The branch-visible id BackgroundExec answers. task_id: String, + /// The owner's task id the command's output is read by. + host_task_id: String, output_path: PathBuf, delivered: usize, - ended: Arc, - _hold: Option, -} - -struct BackgroundTask { - task_id: String, - output_path: PathBuf, - _hold: Option, } struct Inner { shell: Option, - /// Counts spawned shells; a consumer loop serves only its own shell. + /// Counts spawned shells; an exit waiter serves only its own shell. generation: u64, dialect: ShellDialect, shell_exe: Option, queue: VecDeque, queue_running: bool, - /// Raw stream tail, for the markers of commands that own no capture: - /// initialization, background jobs and their pids. - retained: String, occupying: Option, - background: HashMap, /// Note for the call that was running when the shell exited. shell_exit: Option, /// The next call after a shell death reports the reset. had_reset: bool, - /// Final snapshot of the last occupying task, for occupied-period waits. - occupy_tail: Option, - occupy_exit: Option, -} - -/// A terminal produced by the reader and its waiting caller. -struct Settlement { - data: ExecEndedData, - ended: Option>, } pub struct ShellSession { @@ -133,7 +102,6 @@ pub struct ShellSession { config: ShellSessionConfig, lifecycle: CancellationToken, host: Arc, - timeline: Arc, #[expect( dead_code, reason = "stored at composition; no shell path dispatches through it" @@ -143,20 +111,21 @@ pub struct ShellSession { /// native storage, where shell output has no owner. owner: Option>, session_id: String, - session_lifecycle: Option>, - recovery: Option>, + /// Owns every shell task's terminal, notice and recovery. + background: Arc, tasks: Arc>, } impl ShellSession { - /// The branch must mount BackgroundExec to recover exec facts and publish completion notices. + /// The branch must mount BackgroundExec: it owns every shell task's + /// terminal, completion notice and recovery. pub fn new( config: ShellSessionConfig, host: Arc, - timeline: Arc, dispatcher: Arc, owner: Option>, session_id: String, + background: Arc, ) -> Self { Self { facts: None, @@ -167,23 +136,17 @@ impl ShellSession { shell_exe: None, queue: VecDeque::new(), queue_running: false, - retained: String::new(), occupying: None, - background: HashMap::new(), shell_exit: None, had_reset: false, - occupy_tail: None, - occupy_exit: None, }), config, lifecycle: CancellationToken::new(), host, - timeline, dispatcher, owner, session_id, - session_lifecycle: None, - recovery: None, + background, tasks: Arc::new(tokio::sync::Mutex::new(TaskTracker::new())), } } @@ -278,91 +241,109 @@ impl ShellSession { Ok(result) } - /// While the shell is occupied: wait for the occupying task, then report - /// new output; the caller's command was never sent. + /// While the shell is occupied: wait for the occupying task's terminal, + /// then report its output; the caller's command was never sent. A task the + /// owner already recorded as terminal no longer occupies the shell, so the + /// caller's command runs. async fn occupied_wait( self: &Arc, queued: &QueuedCommand, ) -> Option> { - let (notify, task_id, output_path) = { + let (task_id, host_task_id, output_path, delivered) = { let inner = self.inner.lock().await; let task = inner.occupying.as_ref()?; ( - task.ended.clone(), task.task_id.clone(), + task.host_task_id.clone(), task.output_path.clone(), + task.delivered, ) }; - let notified = notify.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - let deadline = - tokio::time::Instant::now() + Duration::from_millis(queued.timeout_ms.min(86_400_000)); - let ended = tokio::select! { + match self.background.wait(task_id.clone(), 0).await { + Ok(_) => { + self.clear_occupancy(&task_id).await; + return None; + } + Err(WaitError::Timeout) => {} + Err(error) => return Some(Err(occupancy_error(&task_id, error))), + } + let wait = self + .background + .wait(task_id.clone(), queued.timeout_ms.min(86_400_000)); + tokio::pin!(wait); + let outcome = tokio::select! { _ = queued.cancel.cancelled() => { return Some(Err("command cancelled while waiting for the shell".into())); } _ = self.lifecycle.cancelled() => { return Some(Err("shell session closed while waiting for the shell".into())); } - _ = &mut notified => true, - _ = tokio::time::sleep_until(deadline) => false, + outcome = &mut wait => outcome, }; - let inner = self.inner.lock().await; - if ended || inner.occupying.is_none() { - let tail = inner.occupy_tail.clone().unwrap_or_default(); - let exit = inner.occupy_exit.clone().unwrap_or_default(); - let mut text = String::new(); - if !tail.is_empty() { - text.push_str(&tail); - if !tail.ends_with('\n') { + match outcome { + Ok(ended) => { + self.clear_occupancy(&task_id).await; + let mut text = ended_text(&ended); + if !text.is_empty() && !text.ends_with('\n') { text.push('\n'); } + text.push_str( + "The command was not executed: the shell was occupied. Resend it now.", + ); + Some(Ok(ToolResult::text(text))) } - if !exit.is_empty() { - text.push_str(&exit); - text.push('\n'); - } - text.push_str("The command was not executed: the shell was occupied. Resend it now."); - return Some(Ok(ToolResult::text(text))); - } - let delivered = inner.occupying.as_ref().expect("checked above").delivered; - drop(inner); - let page = self - .host - .output(OutputRequest { - task_id: task_id.clone(), - cursor: Some(delivered as u64), - limit: Some(OUTPUT_LIMIT as u64), - }) - .await - .ok(); - let mut text = String::new(); - if let Some(page) = page { - if !page.text.is_empty() { - text.push_str(&page.text); - if !page.text.ends_with('\n') { - text.push('\n'); + Err(WaitError::Timeout) => { + let page = self + .host + .output(OutputRequest { + task_id: host_task_id, + cursor: Some(delivered as u64), + limit: Some(OUTPUT_LIMIT as u64), + }) + .await + .ok(); + let mut text = String::new(); + if let Some(page) = page { + if !page.text.is_empty() { + text.push_str(&page.text); + if !page.text.ends_with('\n') { + text.push('\n'); + } + } + let mut inner = self.inner.lock().await; + if let Some(task) = inner + .occupying + .as_mut() + .filter(|task| task.task_id == task_id) + { + task.delivered = page + .next_cursor + .unwrap_or(task.delivered as u64 + page.bytes) + as usize; + } } + text.push_str(&format!( + "Task {} still occupies the shell. The command was not executed; resend it after the task ends.\nTask ID: {}\nOutput: {}", + task_id, + task_id, + output_path.display() + )); + Some(Ok(ToolResult::text(text))) } - let mut inner = self.inner.lock().await; - if let Some(task) = inner - .occupying - .as_mut() - .filter(|task| task.task_id == task_id) - { - task.delivered = - page.next_cursor - .unwrap_or(task.delivered as u64 + page.bytes) as usize; - } + Err(error) => Some(Err(occupancy_error(&task_id, error))), + } + } + + /// Drops the occupancy mark of a task whose terminal the owner recorded. + async fn clear_occupancy(&self, task_id: &str) { + let mut inner = self.inner.lock().await; + if inner + .occupying + .as_ref() + .is_some_and(|task| task.task_id == task_id) + { + inner.occupying = None; } - text.push_str(&format!( - "Task {} still occupies the shell. The command was not executed; resend it after the task ends.\nTask ID: {}\nOutput: {}", - task_id, - task_id, - output_path.display() - )); - Some(Ok(ToolResult::text(text))) } async fn write_shell(&self, bytes: &[u8]) -> Result<(), HostError> { @@ -516,74 +497,25 @@ impl ShellSession { inner.dialect = dialect; inner.shell_exit = None; inner.had_reset = false; - inner.occupy_tail = None; - inner.occupy_exit = None; inner.shell = Some(task_id.clone()); inner.generation }; let this = self.clone(); - let lifecycle = self.lifecycle.clone(); { let tasks = self.tasks.lock().await; tasks.spawn(async move { - let mut event_cursor = 0u64; - let wait_cancel = lifecycle.clone(); - let cancelled: crate::host::CancelledFn = std::sync::Arc::new(move || { - let cancel = wait_cancel.clone(); - Box::pin(async move { - cancel.cancelled().await; - Ok(()) - }) - }); - let wait = this.host.wait( - WaitRequest { - task_id: task_id.clone(), - timeout_ms: None, - }, - cancelled, - ); - tokio::pin!(wait); - loop { - tokio::select! { - biased; - _ = lifecycle.cancelled() => break, - page = this.host.shell_events(ShellEventRequest { - task_id: task_id.clone(), - cursor: event_cursor, - wait_ms: 100, - limit: 64 * 1024, - }) => match page { - Ok(page) => { - for event in page.events { - this.handle_event(event).await; - } - event_cursor = page.next_cursor; - } - Err(_) => break, - }, - result = &mut wait => { - let end = result.ok(); - loop { - let page = this.host.shell_events(ShellEventRequest { - task_id: task_id.clone(), - cursor: event_cursor, - wait_ms: 0, - limit: 64 * 1024, - }).await; - let Ok(page) = page else { break }; - if page.events.is_empty() { - break; - } - for event in page.events { - this.handle_event(event).await; - } - event_cursor = page.next_cursor; - } - this.handle_shell_exit(generation, end).await; - break; + let end = this + .host + .wait( + WaitRequest { + task_id, + timeout_ms: None, }, - } - } + cancelled_fn(&this.lifecycle), + ) + .await + .ok(); + this.handle_shell_exit(generation, end).await; }); } let exe_name = { @@ -615,7 +547,7 @@ impl ShellSession { Ok(reset_note) } - /// Sends the init command and waits for its markers; a timeout + /// Sends the init command and waits for its terminal; a timeout /// terminates the shell and fails the call. async fn send_initial(self: &Arc, command: &str) -> Result<(), String> { let (start, end) = marker_pair(); @@ -627,34 +559,56 @@ impl ShellSession { ShellDialect::Posix => posix_command(command, &start, &end), ShellDialect::Pwsh => pwsh_command(command, &start, &end), }; - self.write_line(&wrapped).await.map_err(|e| e.to_string())?; - let end_marker = end.full(); - let deadline = tokio::time::Instant::now() + INIT_TIMEOUT; - loop { - { - let inner = self.inner.lock().await; - if inner.retained.contains(&end_marker) { - return Ok(()); - } - if inner.shell.is_none() { - return Err("shell exited during initialization".into()); - } - } - if tokio::time::Instant::now() >= deadline { - let mut inner = self.inner.lock().await; - let task_id = inner.shell.take(); - let captured = inner.retained.clone(); - inner.had_reset = true; - drop(inner); - if let Some(task_id) = task_id { - self.stop_shell(&task_id).await; - } - return Err(format!( - "shell did not initialize; captured output: {captured}" - )); + let command_id = format!("shell-init-{}", uuid::Uuid::new_v4().simple()); + let output_path = self.config.output_dir.join(format!("{command_id}.log")); + self.start_command(&command_id, &start.full(), &end.full(), &wrapped) + .await + .map_err(|error| error.to_string())?; + let reply = self + .host + .wait( + WaitRequest { + task_id: command_id.clone(), + timeout_ms: Some(INIT_TIMEOUT.as_millis() as u64), + }, + never_cancelled(), + ) + .await + .map_err(|error| error.to_string())?; + let _ = std::fs::remove_file(&output_path); + if reply.status == WaitStatus::Running { + let mut inner = self.inner.lock().await; + let task_id = inner.shell.take(); + let captured = reply.preview.clone(); + inner.had_reset = true; + drop(inner); + if let Some(task_id) = task_id { + self.stop_shell(&task_id).await; } - tokio::time::sleep(Duration::from_millis(10)).await; + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + return Err(format!( + "shell did not initialize; captured output: {captured}" + )); + } + let _ = self + .host + .settle(TaskRequest { + task_id: command_id.clone(), + }) + .await; + if matches!( + reply.failure, + Some(crate::host_platform::TaskFailure::ShellReset) + | Some(crate::host_platform::TaskFailure::ShellExited) + ) { + return Err("shell exited during initialization".into()); } + Ok(()) } /// Writes a wrapped command and starts its owner-side capture. @@ -686,50 +640,17 @@ impl ShellSession { Ok(()) } - /// Consumes PTY output: folds it into the retained buffer and strips a - /// registered job's end marker. Terminal facts come from the host watcher. - async fn handle_event(self: &Arc, event: ShellEvent) { - match event { - ShellEvent::Output { text, .. } => self.handle_output(&text).await, - ShellEvent::Marker { line, .. } => self.handle_output(&line).await, - } - } - - async fn handle_output(self: &Arc, text: &str) { - let mut inner = self.inner.lock().await; - inner.retained.push_str(text); - let markers: Vec = inner - .background - .values() - .filter_map(|task| self.host.job_marker(&task.task_id)) - .collect(); - for marker in markers { - strip_marker(&mut inner.retained, &marker); - } - if inner.retained.len() > RETAINED_BUFFER_TRIM { - inner.retained = tail_bytes(&inner.retained, RETAINED_BUFFER_LIMIT).to_owned(); - } - } - - /// The shell of `generation` died: note the exit, settle each child from - /// the owner terminal when it is available (falling back to the reset - /// result only when the owner has no terminal), and mark the reset. + /// The shell of `generation` died: note the exit, drop the occupying mark + /// and release the owner's shell record. The owner has already swept every + /// command and job child to its terminal, so BackgroundExec publishes their + /// results and this part only waits for a new shell. async fn handle_shell_exit(self: &Arc, generation: u64, end: Option) { - let mut settled: Vec = Vec::new(); - let mut orphans: Vec<(String, PathBuf)> = Vec::new(); - let mut cleanup_unconfirmed = false; - #[allow( - unused_assignments, - reason = "the early generation return leaves the initial value unread" - )] - let mut shell_task = None; - { + let shell_task = { let mut inner = self.inner.lock().await; if inner.generation != generation { return; } let task_id = inner.shell.take(); - shell_task = task_id.clone(); if task_id.is_some() { let note = match end { Some(reply) => match (reply.signal.as_deref(), reply.exit_code) { @@ -742,95 +663,14 @@ impl ShellSession { inner.shell_exit = Some(note); } inner.had_reset = true; - if inner.dialect == ShellDialect::Posix { - orphans = inner - .background - .iter() - .map(|(id, task)| (id.clone(), task.output_path.clone())) - .collect(); - } - } - for (task_id, output_path) in orphans { - let killed = self - .host - .kill(TaskRequest { - task_id: task_id.clone(), - }) - .await - .map_err(|error| std::io::Error::other(error.to_string())); - let reply = self - .host - .wait( - WaitRequest { - task_id: task_id.clone(), - timeout_ms: Some(2_000), - }, - never_cancelled(), - ) - .await - .ok(); - if reply - .as_ref() - .is_none_or(|reply| reply.status == WaitStatus::Running) - { - cleanup_unconfirmed = true; - continue; - } - let removed = self - .inner - .lock() - .await - .background - .remove(&task_id) - .is_some(); - if !removed { - continue; - } - let reply = reply.expect("checked above"); - if killed.is_ok() { - let _ = self - .host - .settle(TaskRequest { - task_id: task_id.clone(), - }) - .await; - } - let mut data = ended_from_reply(&task_id, &reply, &output_path); - if let Err(error) = killed { - cleanup_unconfirmed = true; - if let ToolContent::Text(text) = &mut data.result.content { - text.push_str(&format!("\nJob could not be terminated: {error}")); - } - if let Some(fields) = data.result.structured_content.as_mut() { - fields.insert("code".into(), "exec_terminate_failed".into()); - } - } - settled.push(Settlement { data, ended: None }); - } + inner.occupying = None; + task_id + }; if let Some(task_id) = shell_task { - if cleanup_unconfirmed { - let _ = self - .host - .kill(TaskRequest { - task_id: task_id.clone(), - }) - .await; - } else { - self.stop_shell(&task_id).await; - } - } - for settlement in settled { - self.settle(settlement.data); - if let Some(notify) = settlement.ended { - notify.notify_waiters(); - } + self.stop_shell(&task_id).await; } } - fn settle(&self, data: ExecEndedData) { - let _ = self.timeline.append(EventKind::ExecEnded(data).into()); - } - /// One foreground call: start its owner-side capture, wait for the /// terminal record, and convert a timeout into an occupying task. async fn run_foreground( @@ -1101,7 +941,9 @@ impl ShellSession { .map_err(|failure| failure.to_string()) } - /// Registers the running command as the occupying task and reports it. + /// Hands the command that outlived its timeout to BackgroundExec and + /// reports it. BackgroundExec registers the task, publishes its terminal + /// and settles it; this part only keeps the occupancy for the queue. async fn occupy_current( self: &Arc, command: &str, @@ -1109,26 +951,9 @@ impl ShellSession { output_path: &Path, context: &CallContext, ) -> Result { - let description = describe(command); - let never = CancellationToken::new(); - let cancelled: crate::host::CancelledFn = Arc::new(move || { - let never = never.clone(); - Box::pin(async move { - never.cancelled().await; - Ok(()) - }) - }); - let reply = self - .host - .wait( - WaitRequest { - task_id: command_id.to_owned(), - timeout_ms: Some(0), - }, - cancelled, - ) - .await - .ok(); + if self.lifecycle.is_cancelled() { + return Err("shell session closed".into()); + } let page = self .host .output(OutputRequest { @@ -1142,121 +967,46 @@ impl ShellSession { .as_ref() .map(|page| page.text.clone()) .unwrap_or_default(); - let omitted = reply.as_ref().is_some_and(|reply| reply.output_truncated) - || page.as_ref().is_some_and(|page| page.truncated); + let omitted = page.as_ref().is_some_and(|page| page.truncated); + let started = self + .background + .start(StartRequest { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + call_id: context.call_id.clone(), + task_id: command_id.to_owned(), + host_task_id: command_id.to_owned(), + description: describe(command), + title: None, + output_path: output_path.to_string_lossy().into_owned(), + }) + .await + .map_err(|error| match error { + StartError::Closing => "shell session closed".to_owned(), + StartError::Timeline(error) => error.to_string(), + })?; { let mut inner = self.inner.lock().await; - if self.lifecycle.is_cancelled() { - return Err("shell session closed".into()); - } - self.timeline - .append( - EventKind::ExecStarted(ExecStartedData { - turn_id: context.turn_id.clone(), - request_id: context.request_id.clone(), - call_id: context.call_id.clone(), - task_id: command_id.to_owned(), - description, - title: None, - output_path: output_path.to_string_lossy().into_owned(), - }) - .into(), - ) - .map_err(|error| error.to_string())?; - let hold = self - .session_lifecycle - .as_ref() - .and_then(|lifecycle| lifecycle.take_hold()); - inner.occupy_tail = None; - inner.occupy_exit = None; inner.occupying = Some(OccupyingTask { - task_id: command_id.to_owned(), + task_id: started.clone(), + host_task_id: command_id.to_owned(), output_path: output_path.to_path_buf(), delivered: preview.len(), - ended: Arc::new(Notify::new()), - _hold: hold, }); } - let ended = { - let inner = self.inner.lock().await; - inner - .occupying - .as_ref() - .expect("just installed") - .ended - .clone() - }; - let this = self.clone(); - let id = command_id.to_owned(); - let path = output_path.to_path_buf(); - let tasks = self.tasks.lock().await; - tasks.spawn(async move { - let reply = this - .host - .wait( - WaitRequest { - task_id: id.clone(), - timeout_ms: None, - }, - never_cancelled(), - ) - .await; - let (result, status, preview, exit) = match reply { - Ok(reply) => { - let code = wait_code(&reply); - ( - ended_result(&id, &path, &reply.preview, &code), - exit_status(&code), - reply.preview.clone(), - exit_line(&code), - ) - } - Err(_) => ( - reset_result(&id, &path, ""), - ExecStatus::Failed, - String::new(), - "[Task failed: shell was reset]".to_owned(), - ), - }; - let published = { - let mut inner = this.inner.lock().await; - if inner - .occupying - .as_ref() - .is_some_and(|task| task.task_id == id) - { - inner.occupy_tail = Some(preview); - inner.occupy_exit = Some(exit); - inner.occupying = None; - true - } else { - false - } - }; - if !published { - return; - } - this.settle(ExecEndedData { - task_id: id.clone(), - status, - result, - }); - let _ = this.host.settle(TaskRequest { task_id: id }).await; - ended.notify_waiters(); - }); let mut text = String::new(); push_output(&mut text, &preview); if omitted { text.push_str("[Output truncated]\n"); } text.push_str(&format!( - "Command is still running and occupies the shell.\nTask ID: {command_id}\nOutput: {}", + "Command is still running and occupies the shell.\nTask ID: {started}\nOutput: {}", output_path.display() )); let mut result = ToolResult::text(text); result.structured_content = Some(structured(json!({ "type": "started", - "taskId": command_id, + "taskId": started, "outputPath": output_path.to_string_lossy(), }))); Ok(result) @@ -1309,350 +1059,49 @@ impl ShellSession { ) } }; - { - let mut inner = self.inner.lock().await; - if self.lifecycle.is_cancelled() { - return Err("shell session closed".into()); - } - self.timeline - .append( - EventKind::ExecStarted(ExecStartedData { - turn_id: context.turn_id.clone(), - request_id: context.request_id.clone(), - call_id: context.call_id.clone(), - task_id: task_id.clone(), - description: description.clone(), - title: None, - output_path: output_path_text.clone(), - }) - .into(), - ) - .map_err(|error| error.to_string())?; - let hold = self - .session_lifecycle - .as_ref() - .and_then(|lifecycle| lifecycle.take_hold()); - inner.background.insert( - task_id.clone(), - BackgroundTask { - task_id: task_id.clone(), - output_path: output_path.clone(), - _hold: hold, - }, - ); - } - if let Err(error) = self - .write_line_job( - &wrapped, - ShellJobStart { - task_id: task_id.clone(), - end_marker: completion.full(), - output_path: output_path_text, - }, - ) + self.write_line_job( + &wrapped, + ShellJobStart { + task_id: task_id.clone(), + end_marker: completion.full(), + output_path: output_path_text.clone(), + }, + ) + .await + .map_err(|error| error.to_string())?; + let started = self + .background + .start(StartRequest { + turn_id: context.turn_id.clone(), + request_id: context.request_id.clone(), + call_id: context.call_id.clone(), + task_id: task_id.clone(), + host_task_id: task_id, + description, + title: None, + output_path: output_path_text, + }) .await - { - let task = self.inner.lock().await.background.remove(&task_id); - if task.is_some() { - self.settle(ExecEndedData { - task_id: task_id.clone(), - status: ExecStatus::Failed, - result: ToolResult::error(error.to_string()), - }); - } - return Err(error.to_string()); - } - let error_path = pwsh_paths.as_ref().map(|(_, error)| error.clone()); - let this = self.clone(); - let host = self.host.clone(); - let watched = task_id.clone(); - let watched_output = output_path.clone(); - self.tasks.lock().await.spawn(async move { - let reply = host - .wait( - WaitRequest { - task_id: watched.clone(), - timeout_ms: None, - }, - never_cancelled(), - ) - .await; - if let Ok(reply) = reply { - if this - .inner - .lock() - .await - .background - .remove(&watched) - .is_none() - { - return; - } - let _ = host - .settle(TaskRequest { - task_id: watched.clone(), - }) - .await; - let mut data = ended_from_reply(&watched, &reply, &watched_output); - if let Some(error_path) = &error_path - && let ToolContent::Text(text) = &mut data.result.content - { - text.push_str(&format!("\nStandard error: {}", error_path.display())); - } - this.settle(data); - } - }); - let mut result = ToolResult::text(format!( - "Background command started.\nTask ID: {task_id}\nOutput: {}", + .map_err(|error| match error { + StartError::Closing => "shell session closed".to_owned(), + StartError::Timeline(error) => error.to_string(), + })?; + let mut text = format!( + "Background command started.\nTask ID: {started}\nOutput: {}", output_path.display() - )); + ); + if let Some((_, error_path)) = &pwsh_paths { + text.push_str(&format!("\nStandard error: {}", error_path.display())); + } + let mut result = ToolResult::text(text); result.structured_content = Some(structured(json!({ "type": "started", - "taskId": task_id, + "taskId": started, "outputPath": output_path.to_string_lossy(), }))); Ok(ran(result, command, None)) } - /// Stops a task by id. - pub async fn stop(self: &Arc, task_id: &str) -> Result { - let occupying = { - let mut inner = self.inner.lock().await; - if inner - .occupying - .as_ref() - .is_some_and(|task| task.task_id == task_id) - { - inner.occupying.take() - } else { - None - } - }; - if let Some(occ) = occupying { - { - let inner = self.inner.lock().await; - if inner.shell.is_some() { - drop(inner); - let _ = self.write_shell(b"\x03").await; - } - } - let never = CancellationToken::new(); - let cancelled: crate::host::CancelledFn = Arc::new(move || { - let never = never.clone(); - Box::pin(async move { - never.cancelled().await; - Ok(()) - }) - }); - let reply = self - .host - .wait( - WaitRequest { - task_id: task_id.to_owned(), - timeout_ms: Some(STOP_WAIT.as_millis() as u64), - }, - cancelled, - ) - .await - .ok(); - let found = reply - .as_ref() - .is_some_and(|reply| reply.status != WaitStatus::Running); - let page = self - .host - .output(OutputRequest { - task_id: task_id.to_owned(), - cursor: None, - limit: Some(OUTPUT_LIMIT as u64), - }) - .await - .ok(); - let preview = page.map(|page| page.text).unwrap_or_default(); - { - let mut inner = self.inner.lock().await; - inner.occupy_tail = Some(preview); - inner.occupy_exit = None; - if !found { - let shell = inner.shell.take(); - inner.shell_exit = Some("[shell was terminated]".into()); - inner.had_reset = true; - drop(inner); - if let Some(shell) = shell { - self.stop_shell(&shell).await; - } - } - } - let _ = self - .host - .settle(TaskRequest { - task_id: task_id.to_owned(), - }) - .await; - let data = ExecEndedData { - task_id: task_id.to_owned(), - status: ExecStatus::Cancelled, - result: ToolResult::text("Command interrupted."), - }; - self.settle(data.clone()); - occ.ended.notify_waiters(); - return Ok(data); - } - let task = { - let mut inner = self.inner.lock().await; - inner.background.remove(task_id) - }; - if let Some(task) = task { - let killed = self - .host - .kill(TaskRequest { - task_id: task.task_id.clone(), - }) - .await; - if matches!(killed, Err(HostPlatformError::TaskRunning)) { - let task_id = task.task_id.clone(); - let output_path = task.output_path.clone(); - self.inner - .lock() - .await - .background - .insert(task_id.clone(), task); - let this = self.clone(); - let host = self.host.clone(); - let watched = task_id.clone(); - self.tasks.lock().await.spawn(async move { - let reply = host - .wait( - WaitRequest { - task_id: watched.clone(), - timeout_ms: None, - }, - never_cancelled(), - ) - .await; - if let Ok(reply) = reply { - if this - .inner - .lock() - .await - .background - .remove(&watched) - .is_none() - { - return; - } - let _ = host - .settle(TaskRequest { - task_id: watched.clone(), - }) - .await; - this.settle(ended_from_reply(&watched, &reply, &output_path)); - } - }); - return Ok(ExecEndedData { - task_id, - status: ExecStatus::Cancelled, - result: ToolResult::text( - "Background command stop requested; it will end after it starts.", - ), - }); - } - let kill_failed = killed.is_err(); - let data = match killed { - Ok(()) => { - let reply = self - .host - .wait( - WaitRequest { - task_id: task.task_id.clone(), - timeout_ms: None, - }, - never_cancelled(), - ) - .await - .ok(); - let _ = self - .host - .settle(TaskRequest { - task_id: task.task_id.clone(), - }) - .await; - reply.map_or_else( - || ExecEndedData { - task_id: task_id.to_owned(), - status: ExecStatus::Cancelled, - result: ToolResult::text("Background command stopped."), - }, - |reply| ended_from_reply(task_id, &reply, &task.output_path), - ) - } - Err(error) => { - let mut result = ToolResult::error(format!( - "Background command could not be terminated: {error}\nOutput: {}", - task.output_path.display() - )); - result.structured_content = Some(structured(json!({ - "code": "exec_terminate_failed", - "taskId": task_id, - "outputPath": task.output_path.to_string_lossy(), - }))); - ExecEndedData { - task_id: task_id.to_owned(), - status: ExecStatus::Failed, - result, - } - } - }; - if kill_failed { - let watched = task.task_id.clone(); - let output_path = task.output_path.clone(); - self.inner - .lock() - .await - .background - .insert(watched.clone(), task); - let this = self.clone(); - let host = self.host.clone(); - self.tasks.lock().await.spawn(async move { - let reply = host - .wait( - WaitRequest { - task_id: watched.clone(), - timeout_ms: None, - }, - never_cancelled(), - ) - .await; - if let Ok(reply) = reply { - if this - .inner - .lock() - .await - .background - .remove(&watched) - .is_none() - { - return; - } - let _ = host - .settle(TaskRequest { - task_id: watched.clone(), - }) - .await; - this.settle(ended_from_reply(&watched, &reply, &output_path)); - } - }); - return Ok(data); - } - self.settle(data.clone()); - return Ok(data); - } - Err(TaskError::Unknown) - } - - async fn write_line(&self, line: &str) -> Result<(), HostError> { - self.write_shell(format!("{line}\n").as_bytes()).await - } - async fn write_line_job(&self, line: &str, job: ShellJobStart) -> Result<(), HostError> { let inner = self.inner.lock().await; let Some(task_id) = inner.shell.clone() else { @@ -1670,43 +1119,15 @@ impl ShellSession { } } -impl ExecStop for ShellSession { - fn stop( - self: Arc, - task_id: String, - ) -> BoxFuture<'static, Result> { - Box::pin(async move { - match ShellSession::stop(&self, &task_id).await { - Err(TaskError::Unknown) => match &self.recovery { - Some(recovery) => recovery.stop(task_id).await.map_err(|error| match error { - crate::workspace_tools::background::TaskError::Closed => TaskError::Closed, - crate::workspace_tools::background::TaskError::Unknown => { - TaskError::Unknown - } - crate::workspace_tools::background::TaskError::Read(_) => TaskError::Read, - }), - None => Err(TaskError::Unknown), - }, - other => other, - } - }) - } -} - -/// Settles the occupying task once its capture saw a complete end marker -/// line, taking the capture with it. /// The plugin. pub struct ShellSessionPlugin { - recovery: Key, + background: Key, facts: Key, session: Key, - stop: Key, - timeline: Key, dispatcher: Key, host: Key, lifecycle: Key, session_config: Key, - session_lifecycle: Key, identity: Key, config: Option, } @@ -1722,16 +1143,13 @@ impl ShellSessionPlugin { /// Derive execution settings from the owning Session. pub fn session(names: &Names<'_>) -> rutis::Result { Ok(Self { - recovery: names.key()?, + background: names.key()?, facts: names.key()?, session: names.key()?, - stop: names.key()?, - timeline: names.key()?, dispatcher: names.key()?, host: names.key()?, lifecycle: names.key()?, session_config: names.key()?, - session_lifecycle: names.key()?, identity: names.key()?, config: None, }) @@ -1744,24 +1162,20 @@ impl DynPlugin for ShellSessionPlugin { } fn injects(&self) -> Vec { vec![ - self.recovery.erase(), - self.timeline.erase(), + self.background.erase(), self.dispatcher.erase(), self.host.erase(), self.lifecycle.erase(), self.session_config.erase(), - self.session_lifecycle.erase(), self.identity.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - let timeline = ctx.require_at(&self.timeline)?; let dispatcher = ctx.require_at(&self.dispatcher)?; let host = ctx.require_at(&self.host)?; - let recovery = ctx.require_at(&self.recovery)?; + let background = ctx.require_at(&self.background)?; let config = ctx.require_at(&self.session_config)?; - let session_lifecycle = ctx.require_at(&self.session_lifecycle)?; let identity = ctx.require_at(&self.identity)?; let owner = ctx.get::(); let mut session = ShellSession::new( @@ -1776,14 +1190,12 @@ impl DynPlugin for ShellSessionPlugin { .join(&identity.branch_id), }), host, - timeline, dispatcher, owner, identity.session_id.clone(), + background, ); session.facts = Some((ctx.clone(), self.facts.clone())); - session.recovery = Some(recovery); - session.session_lifecycle = Some(session_lifecycle); let session = Arc::new(session); let service = session.clone(); ctx.effect(move || async move { @@ -1804,21 +1216,9 @@ impl DynPlugin for ShellSessionPlugin { tasks.wait().await; let generation = service.inner.lock().await.generation; service.handle_shell_exit(generation, None).await; - let remaining = service - .inner - .lock() - .await - .background - .keys() - .cloned() - .collect::>(); - for task in remaining { - let _ = ShellSession::stop(&service, &task).await; - } Ok(()) })?; - ctx.provide_at(self.session.clone(), session.clone())?; - ctx.provide_at::(self.stop.clone(), session)?; + ctx.provide_at(self.session.clone(), session)?; Ok(Effect::Done) }) } @@ -1862,24 +1262,15 @@ fn push_output(text: &mut String, output: &str) { } } -fn exit_status(code: &str) -> ExecStatus { - match code { - "0" => ExecStatus::Completed, - "cancelled" => ExecStatus::Cancelled, - _ => ExecStatus::Failed, - } -} - -fn wait_code(reply: &WaitReply) -> String { - if reply.status == WaitStatus::Cancelled { - "cancelled".to_owned() - } else { - reply - .exit_code - .map(|code| code.to_string()) - .or_else(|| reply.signal.clone()) - .unwrap_or_else(|| "failed".to_owned()) - } +fn cancelled_fn(token: &CancellationToken) -> crate::host::CancelledFn { + let token = token.clone(); + std::sync::Arc::new(move || { + let token = token.clone(); + Box::pin(async move { + token.cancelled().await; + Ok(()) + }) + }) } fn never_cancelled() -> crate::host::CancelledFn { @@ -1902,60 +1293,30 @@ fn exit_line(code: &str) -> String { } } -fn ended_from_reply(task_id: &str, reply: &WaitReply, output_path: &Path) -> ExecEndedData { - let code = wait_code(reply); - let mut result = if matches!( - reply.failure, - Some( - crate::host_platform::TaskFailure::ShellReset - | crate::host_platform::TaskFailure::ShellExited - ) - ) { - reset_result(task_id, output_path, &reply.preview) - } else { - ended_result(task_id, output_path, &reply.preview, &code) - }; - if let Some(failure) = &reply.failure - && let ToolContent::Text(text) = &mut result.content - { - text.push('\n'); - text.push_str(&failure.to_string()); - } - let status = match reply.status { - WaitStatus::Exited if reply.exit_code == Some(0) && reply.failure.is_none() => { - ExecStatus::Completed - } - WaitStatus::Cancelled => ExecStatus::Cancelled, - _ => ExecStatus::Failed, - }; - ExecEndedData { - task_id: task_id.to_owned(), - status, - result, +/// The model-readable text of a terminal record. +fn ended_text(data: &ExecEndedData) -> String { + match &data.result.content { + ToolContent::Text(text) => text.clone(), + ToolContent::Blocks(blocks) => blocks + .iter() + .filter_map(|block| match block { + dim_agent_types::ContentBlock::Text { text } => Some(text.as_str()), + dim_agent_types::ContentBlock::Image { .. } => None, + }) + .collect::>() + .join("\n"), } } -fn ended_result(task_id: &str, output_path: &Path, preview: &str, code: &str) -> ToolResult { - let status = exit_status(code); - let label = match status { - ExecStatus::Completed => "completed", - ExecStatus::Failed => "failed", - ExecStatus::Cancelled => "cancelled", - }; - let mut text = preview.to_owned(); - if !text.is_empty() && !text.ends_with('\n') { - text.push('\n'); +fn occupancy_error(task_id: &str, error: WaitError) -> String { + match error { + WaitError::Unknown => { + format!("task {task_id} still occupies the shell but has no task facts") + } + WaitError::Closed => "shell session closed while waiting for the shell".to_owned(), + WaitError::Timeout => format!("task {task_id} still occupies the shell"), + WaitError::Read(error) => error.to_string(), } - text.push_str(&exit_line(code)); - let mut result = ToolResult::text(text); - result.is_error = (status == ExecStatus::Failed).then_some(true); - result.structured_content = Some(structured(json!({ - "type": "finished", - "status": label, - "taskId": task_id, - "outputPath": output_path.to_string_lossy(), - }))); - result } fn shell_exit_note(terminal: &crate::host_platform::Terminal) -> String { @@ -1966,34 +1327,6 @@ fn shell_exit_note(terminal: &crate::host_platform::Terminal) -> String { } } -/// A shell death settles open tasks as failed with a reset note. -fn reset_result(task_id: &str, output_path: &Path, preview: &str) -> ToolResult { - let mut text = preview.to_owned(); - if !text.is_empty() && !text.ends_with('\n') { - text.push('\n'); - } - text.push_str("[Task failed: shell was reset]"); - let mut result = ToolResult::text(text); - result.is_error = Some(true); - result.structured_content = Some(structured(json!({ - "type": "finished", - "status": "failed", - "taskId": task_id, - "outputPath": output_path.to_string_lossy(), - }))); - result -} - -/// Removes a completion marker line from a capture. -fn strip_marker(text: &mut String, marker: &str) { - if let Some(pos) = text.find(marker) { - let end = text[pos..] - .find('\n') - .map_or(text.len(), |offset| pos + offset + 1); - text.replace_range(pos..end, ""); - } -} - pub(crate) fn regularize_output(bytes: &[u8]) -> String { let text = String::from_utf8_lossy(bytes); let mut out = String::new(); @@ -2045,17 +1378,6 @@ pub(crate) fn regularize_output(bytes: &[u8]) -> String { out } -fn tail_bytes(s: &str, limit: usize) -> &str { - if s.len() <= limit { - return s; - } - let mut start = s.len() - limit; - while !s.is_char_boundary(start) { - start += 1; - } - &s[start..] -} - struct MarkerPair { first: String, second: String, diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index e4f0f2bdb4..26edd54103 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -741,10 +741,6 @@ impl Session { pub fn service(&self, branch: &str) -> Result> { self.published(branch)?.service::() } - /// Reads a capability service when the loaded profile provides it. - pub fn service_opt(&self, branch: &str) -> Result>> { - self.published(branch)?.service_opt::() - } /// Observes publication progress without exposing Timeline mutation. pub fn publication(&self, branch: &str) -> Result { Ok(self.published(branch)?.publication()) diff --git a/crates/dim-agent-runtime/src/branch.rs b/crates/dim-agent-runtime/src/branch.rs index 99b49ad2b7..0a5f478472 100644 --- a/crates/dim-agent-runtime/src/branch.rs +++ b/crates/dim-agent-runtime/src/branch.rs @@ -152,9 +152,6 @@ impl Branch { pub fn service(&self) -> Result> { self.0.public::() } - pub fn service_opt(&self) -> Result>> { - self.0.public_opt::() - } /// The branch scope and the capabilities it installed. pub fn diagnostics(&self) -> rutis::host::diagnostics::RuntimeDiagnostics { self.0.diagnostics() diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index 178a2c564c..2a36fe209c 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -328,10 +328,6 @@ impl TimelineContext { crate::names::in_group::(&self.catalog, crate::BRANCH_GROUP)?; self.port::(std::any::type_name::()) } - pub(crate) fn public_opt(&self) -> Result>> { - crate::names::in_group::(&self.catalog, crate::BRANCH_GROUP)?; - Ok(self.ctx.get_at::(&self.scope.key::())) - } pub(crate) fn port(&self, name: &str) -> Result> { self.ctx .get_at::(&self.scope.key::()) diff --git a/crates/dim-app-server/src/connection.rs b/crates/dim-app-server/src/connection.rs index cccd28dcc7..04b851ad3d 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -7,7 +7,6 @@ use crate::{ skills_management::skills_error, }; use dim_agent_capabilities::{ - exec_stop::{self, ExecStop}, host::{ModelPortError, ModelSelectionRequest}, methods::{Accepted, CallSite, CallerConnection, Callers, NotifyError, RpcError}, permission::{Permission, PermissionState, PermissionUpdateError}, @@ -1629,35 +1628,21 @@ impl Connection { if p.task_id.is_empty() { return Err(RpcError::invalid("taskId must not be empty")); } - let result = if let Some(stop) = - session.service_opt::(&p.branch_id)? - { - stop.stop(p.task_id).await.map_err(|error| match error { - exec_stop::TaskError::Unknown => RpcError::app( + let result = session + .service::(&p.branch_id)? + .stop(p.task_id) + .await + .map_err(|error| match error { + TaskError::Unknown => RpcError::app( -32000, "exec_task_unknown", "Command is not a task of this branch", ), - exec_stop::TaskError::Closed => RpcError::reloading(), - exec_stop::TaskError::Read => { + TaskError::Closed => RpcError::reloading(), + TaskError::Read(_) => { RpcError::app(-32603, "exec_task_read", "Task facts could not be read") } - })? - } else { - session - .service::(&p.branch_id)? - .stop(p.task_id) - .await - .map_err(|error| match error { - TaskError::Unknown => RpcError::app( - -32000, - "exec_task_unknown", - "Command is not a task of this branch", - ), - TaskError::Closed => RpcError::reloading(), - TaskError::Read(error) => error.into(), - })? - }; + })?; Reply::ExecEnded(result) } Call::SessionSkills(p) => { diff --git a/docs/architecture/rust-agent/capability-event-inventory.md b/docs/architecture/rust-agent/capability-event-inventory.md index 70bf6beef0..a81990f892 100644 --- a/docs/architecture/rust-agent/capability-event-inventory.md +++ b/docs/architecture/rust-agent/capability-event-inventory.md @@ -34,7 +34,7 @@ | TreeTimeline | 执行分支创建、结束命令及结算 | branch/create、branch/end、turn/end;branch 结果事实 | [实现](../../../crates/dim-agent-capabilities/src/timeline_tree.rs) / [说明](plugins/TimelineTree.md) | | WaitBranch | 当前回合内的等待通知与单次等待 | input/message、turn/start、turn/end;不直接写事实 | [实现](../../../crates/dim-agent-capabilities/src/wait.rs) / [说明](plugins/Wait.md) | | HooksBranch | 按已消费事实运行 Hooks,采用有效输出 | input/message;读取 input、turn、approval、tool 等触发事实 | [实现](../../../crates/dim-agent-capabilities/src/hooks/runner.rs) / [说明](plugins/Hooks.md) | -| ShellSession | 持续 shell 执行、后台任务和完成通知 | exec/*、input/message;读取中断与回合事实 | [实现](../../../crates/dim-agent-capabilities/src/shell_session.rs) | +| ShellSession | 持续 shell 执行与命令队列,把后台任务和前台超时转后台的命令交给 BackgroundExec | 不直接写 Timeline 事实;命令终态由 BackgroundExec 发布 | [实现](../../../crates/dim-agent-capabilities/src/shell_session.rs) | ## 核心 Timeline 事件(50 个具体 key) @@ -56,8 +56,8 @@ | `approval/respond` | 对审批请求的决定 | Approval 响应入口 | Approval、HooksBranch、协作审批 | | `approval/cancelled` | 审批请求取消结算 | Approval | Approval 恢复、HooksBranch、协作审批 | | `permission/changed` | 分支权限策略变更 | Permission | Permission | -| `exec/started` | 后台执行已开始 | BackgroundExec、ShellSession | 各执行所有者恢复、GoalBranch、执行历史 | -| `exec/ended` | 后台执行终态 | BackgroundExec、ShellSession | 各执行所有者、GoalBranch;另由生产方发布唤醒输入 | +| `exec/started` | 后台执行已开始 | BackgroundExec | 各执行所有者恢复、GoalBranch、执行历史 | +| `exec/ended` | 后台执行终态 | BackgroundExec | 各执行所有者、GoalBranch;另由生产方发布唤醒输入 | | `turn/start` | 回合开始 | Loop | WaitBranch、Prompt、InputQueue、执行与协作部件 | | `turn/end` | 回合结束及结果 | Loop | WaitBranch、InputQueue、GoalBranch、HooksBranch、执行与协作部件 | | `prompt/changed` | 提示词快照已采用 | Prompt 经 ConfigurationPublisher | Prompt、ContextUsage/配置恢复 | diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index cfb5a3e8d7..0fdb9b1b4f 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -138,9 +138,8 @@ note to the result text when the shown output matches; stops, timeouts and offload failures get none. Codes and structured content are unchanged. `exec_stop {taskId}` stops a detached command owned by the calling branch. The -App Server resolves the branch's `dyn ExecStop` when the profile provides it (ShellSession in the -minimal profile) and otherwise uses BackgroundExec; both map `unknown`/`closed`/`read` to the same -RPC errors. It waits for cleanup and returns the committed terminal +App Server calls the branch's `BackgroundExec` in every profile; the operation maps +`unknown`/`closed`/`read` to the same RPC errors. It waits for cleanup and returns the committed terminal `{task_id, status, result}` in the model-readable content. An already-ended task keeps its result. Only `cancelled` confirms cancellation; `failed` remains an error, including when the process tree could not be released. An unknown task fails @@ -645,10 +644,12 @@ a filesystem lock, permission grant or cross-process compare-and-swap. ## BackgroundExec Owner: [workspace_tools/background.rs](../../../../crates/dim-agent-capabilities/src/workspace_tools/background.rs). -Owns commands transferred from foreground execution, their terminal records and -bounded completion notices on the calling branch. It also settles abandoned exec -facts and posts completion notices for ShellSession; that producer retains its live -PTY and stop port. See [Shell exec recovery](../../../design/shell-exec-recovery.md) +Owns every task it registers — a detached `exec` command, a persistent shell's +background job and a shell command that outlived its foreground wait — with their +terminal records and bounded completion notices on the calling branch. It also +settles abandoned exec facts. `ShellSession` hands its tasks to `start` and keeps +its queue and occupancy; the owner records every shell task's terminal and is the +one stop entry for both task kinds. See [Shell exec recovery](../../../design/shell-exec-recovery.md) for the profile and generation handoff. `start` carries an optional task `title` into `exec/started` alongside the unchanged command-derived `description`. `session.exec.pending` returns that same title in each `PendingExec` item. The fact and inventory field are optional strings: missing values deserialize as absent and absent values are omitted on serialization. Existing persisted facts and inventories without a title remain readable. Persistence uses [native format v48](../../../design/appserver/native-storage-format.md#v48-task-titles), a marker-only, one-way upgrade that makes older strict readers reject the store at startup; ShellInput's command facts have no supplied title. This adds no state owner or service face and changes neither execution nor cancellation. The existing `toolHost`, `treeCommands` and `backgroundExec` faces retain their operations. @@ -676,7 +677,8 @@ a running task so it ends `cancelled` and does not wake, and answers an already ended task's record without changing its wake. Cancellation is the caller dropping the call: a dropped `outputPage` drops the read and a dropped `wait` releases the watch. `start` needs the live -process, so it is the `exec` tool's own operation and is not on the face. +process, so it is the caller's own operation — the `exec` tool and `ShellSession` — +and is not on the face. Historical `outputPage`, `wait` and `stop` calls use the owner's bounded task-fact reads, without rebuilding a historical task cache. `wait` returns a historical terminal record without waiting for execution; `timeoutMs` governs the completion wait for a live task. Failed reads or inconsistent required facts answer `read`, not `unknown`. Dropping a historical call cancels its read. diff --git a/docs/design/agent-tool-modes.md b/docs/design/agent-tool-modes.md index eb32053ea4..7e7d0b3d53 100644 --- a/docs/design/agent-tool-modes.md +++ b/docs/design/agent-tool-modes.md @@ -305,14 +305,12 @@ product), and mounting `ShellTools` instead of `WorkspaceTools` for shell Sessio the client methods that part registers (`session.files` mention search, command-output paging), so a shell Session would lose client features that have nothing to do with its tools. -Stopping a task is a separate route. Today `session.exec.stop` resolves the branch's -`BackgroundExec` and stops a native process; a live persistent-shell command belongs to -`ShellSession`, which provides the branch's `dyn ExecStop`. With `execute` in the product, both -kinds exist in one Session: - -- The stop route resolves the live owner first: the branch's `ExecStop` for a live shell task, then - `BackgroundExec` for a native process. A task neither owns is read from shared history for its - terminal result; history never answers for a live task. +Stopping a task is a separate route. `session.exec.stop` resolves the branch's +`BackgroundExec` and stops the task. A live persistent-shell command is handed to the same owner +when its call converts, so both kinds exist in one Session: + +- The stop route calls `BackgroundExec` for every task kind. A task it does not own is read from + shared history for its terminal result; history never answers for a live task. - Both parts stay mounted when the mode changes, so a task started in `shell` or `codemode` can still be stopped after the Session switches to `normal`. - `session.stop` remains the turn's stop and stops no background task. @@ -475,8 +473,8 @@ force (the `effective` value) and shows the named refusal otherwise. `set`/`resume` are refused while `shell` is in force; a chosen `shell` that runs `normal` (no `execute`) neither pauses nor refuses; after leaving, the operator resumes the goal. - Flow: stop a shell task with `session.exec.stop` after switching the Session to `normal`; the - route resolves the live `ExecStop` before `BackgroundExec`, and neither answers for a live task - from history. The minimal-execution profile's Session runs `shell` and keeps `execute`. + route calls `BackgroundExec`, and history never answers for a live task. The + minimal-execution profile's Session runs `shell` and keeps `execute`. - Clients: a web component test for the composer menu and the remembered choice, and one tmux TUI case for the row and the picker. - No event type or envelope changes. The stored configuration gains an optional field that old diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 678339f473..0024c36f8b 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -157,7 +157,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou 形状与错误由所有者文档定义:[MCP Apps](appserver/mcp-apps.md#44-the-mcpsession-data-face)(`mcpSession`)和 [WorkspaceTools](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face)(`backgroundExec`)。 -`backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`BackgroundExec` 只保存 branch task id、host task id 和 output path,实时读取走 `hostPlatform.tail`/`output`。`backgroundExec.stop` 是 kill。持久 PTY 由 `HostPlatform` 拥有,`ShellSession` 持有策略;公共 PTY 操作只有 `shell`/`write`/`resize`。 +`backgroundExec.start` 需要活的进程对象,仍是调用方自己的操作——`exec` 工具和 `ShellSession`——不在数据面上;`BackgroundExec` 只保存 branch task id、host task id 和 output path,实时读取走 `hostPlatform.tail`/`output`。`backgroundExec.stop` 是唯一的停止入口,也是 kill。持久 PTY 由 `HostPlatform` 拥有,`ShellSession` 持有策略;公共 PTY 操作只有 `shell`/`write`/`resize`。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 `hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:服务本身就是公开契约;一个 service 的公开方法就是它的接口,没有单独的 face 对象,也没有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform` 的公开方法包括 `info`、`execShell`、`persistentShell`、`sandboxBackend`、`execRoot`,以及命令任务和持久 shell 的操作(见 §3.4);`toolHost`、`backgroundExec`、`sessionMethods.shell` 通过该数据面调用它们。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store services](resource-faces.md) §6)。 diff --git a/docs/design/shell-exec-recovery.md b/docs/design/shell-exec-recovery.md index 349f86c8ac..f41fa42e89 100644 --- a/docs/design/shell-exec-recovery.md +++ b/docs/design/shell-exec-recovery.md @@ -1,25 +1,26 @@ # Shell exec recovery -ShellSession owns its branch's PTY, command queue, foreground-to-background handoff and process cleanup. -It writes the existing `exec/started` and `exec/ended` facts. BackgroundExec owns recovery and completion -notices for that shared exec protocol; its [query, fork boundary and notice contract](../architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec) +ShellSession owns its branch's persistent shell, command queue and foreground-to-background handoff. +It does not write exec facts: a background job and a foreground command that outlives its wait are +handed to BackgroundExec, which registers the task, publishes its terminal and settles it. +BackgroundExec owns recovery and completion notices for that shared exec protocol; its +[query, fork boundary and notice contract](../architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec) applies to facts from either execution producer. Event types do not have an exclusive writer. ## Assembly and handoff The minimal-execution profile mounts BackgroundExec alongside ShellSession. ShellSession declares a -load-order dependency on `backgroundExec`: recovery finishes before a new shell can accept commands, -and a reload of the recovery owner first unloads its shell dependent. ShellSession releases its old -processes and writes their terminal facts before BackgroundExec is removed. A ShellSession-only reload -does not restart the recovery owner or mistake another producer's live work for abandoned history. +required dependency on `backgroundExec`: recovery finishes before a new shell can accept commands, +and a reload of the recovery owner first unloads its shell dependent. A ShellSession-only reload does +not restart the recovery owner or mistake another producer's live work for abandoned history. The local-execution profile already provides BackgroundExec, so a host adding ShellSession there reuses it. -ShellSession appends terminals but does not append wake inputs. The Dispatcher delivers terminals to -BackgroundExec, which applies the existing status and branch-closing rules and writes the tagged notice. -For a terminal without a native BackgroundExec task, it reads that task's description from its exact -`exec/started` fact; it does not build a second task table or take ownership of a live PTY. -The existing ShellSession stop port continues to stop its own live tasks. BackgroundExec's live capture -and native-process stop operations are not a new PTY control interface. +ShellSession hands a task to BackgroundExec only after HostPlatform accepted the command or job; on +handoff failure BackgroundExec terminates and settles the owner task. HostPlatform records every +shell task's terminal from its markers and sweeps a dead shell's commands and jobs to their +expected terminals. BackgroundExec then writes the one `exec/ended` per task and posts the wake +input; nobody synthesizes a result or publishes one because a wait timed out. The only stop entry is +`BackgroundExec.stop`; there is no separate shell stop port. ## Recovery cases @@ -37,11 +38,11 @@ Publication, failure handling and retry on the next generation remain the owner' ## Rule check -Both branch parts are Capabilities under principles §1. ShellSession owns I/O and terminal production; -BackgroundExec owns recovery/notification decisions for the exec protocol. This changes the profile's -assembly and removes a duplicate notification writer, not the meaning of an exec event. +Both branch parts are Capabilities under principles §1. ShellSession owns I/O policy and the command +queue; BackgroundExec owns registration, terminal facts, recovery and notification for every task it +registers. This changes who registers a shell task, not the meaning of an exec event. -- Principles §4 rules 1, 2 and 7: the terminal is the handoff; neither part mutates the other's state. +- Principles §4 rules 1, 2 and 7: the owner terminal is the handoff; neither part mutates the other's state. - Rule 3: no before callback. - Rules 4 and 8: existing Timeline queries, Dispatcher and dependency lifecycle; no mechanism change. - Rule 5: existing separate terminal/notice commits remain valid, including recovery of that gap. @@ -60,4 +61,6 @@ The minimal-execution flow restores disposable storage containing an unfinished completed end and a cancelled end. It checks failed settlement, preservation of the existing result, notice eligibility, each notice's stored command description and no duplicates on another restoration. These are committed-prefix recovery cases, not a claim that the test killed a real host process. Live background and occupying-command flows also check the completion notice. -Stop and shell-exit flows check terminal outcomes; the close flow checks one terminal per admitted task. +A shell-exit flow checks the terminal the owner records and that the swept job's process is gone; the +close flow checks one terminal per admitted task, and a recovery restart checks that the live shell +task settles before recovery inspects history. diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index a6a8129f63..053ec9efbe 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -874,6 +874,44 @@ async fn timeout_occupies_shell_and_wakes() { harness.shutdown().await; } +/// An ended command no longer occupies the shell: the next call runs its +/// command instead of asking for a resend. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_call_after_the_occupying_command_ends_runs() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "sleep 0.4 && echo occupied", "timeoutMs": 100}), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + assert!( + text(&results(&events)[0]).contains("occupies the shell"), + "{}", + text(&results(&events)[0]) + ); + until(&session, "occupying wake", |events| { + !notifications(events).is_empty() + }) + .await; + harness + .run(&session, &[("execute", json!({"command": "echo next"}))]) + .await; + let events = until(&session, "next result", |events| tool_results(events) == 2).await; + let result = &results(&events)[1]; + assert!(text(result).contains("next"), "{}", text(result)); + session.close().await.unwrap(); + harness.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn stop_background_task() { let harness = Harness::new(platform(&[]).await).await; @@ -896,10 +934,9 @@ async fn stop_background_task() { let pid = pid_in(&pid_file).await; let stop = session - .service_opt::("main") - .unwrap() - .expect("the minimal profile provides the branch stop owner"); - let ended = stop.clone().stop(task_id.clone()).await.unwrap(); + .service::("main") + .unwrap(); + let ended = stop.stop(task_id.clone()).await.unwrap(); assert_eq!(ended.status, ExecStatus::Cancelled); assert!(gone(&pid).await); let repeated = stop.stop(task_id).await.unwrap(); @@ -1167,7 +1204,7 @@ async fn a_call_that_converts_before_its_output_writes_only_the_command_output() &session, &[( "execute", - json!({"command": "echo first; echo second", "timeoutMs": 0}), + json!({"command": "sleep 0.1; echo first; echo second", "timeoutMs": 0}), )], ) .await; @@ -1213,13 +1250,13 @@ async fn shell_exit_kills_background_jobs() { assert_eq!(end.task_id, task_id); assert_eq!(end.status, ExecStatus::Failed); assert!( - text(&end.result).contains("shell was reset"), + text(&end.result).contains("shell exited"), "{}", text(&end.result) ); assert!( gone(&pid).await, - "background process {pid} survived the shell reset: result={:?}, process={:?}", + "background process {pid} survived the shell exit: result={:?}, process={:?}", end.result, std::process::Command::new("ps") .args(["-o", "pid=,ppid=,pgid=,stat=,comm=", "-p", &pid]) @@ -1492,10 +1529,12 @@ async fn restarting_exec_recovery_settles_the_live_shell_before_rebuilding() { ended(events).len() == 1 && notifications(events).len() == 1 }) .await; + assert_eq!(ended(&after)[0].1.status, ExecStatus::Failed); assert_eq!(count(&after, "exec/started"), 1); assert!( - text(&ended(&after)[0].1.result).contains("shell was reset"), - "the live shell must settle before recovery inspects history" + text(&ended(&after)[0].1.result).contains("shell reset"), + "the live shell must settle before recovery inspects history: {}", + text(&ended(&after)[0].1.result) ); { let ready = tokio::time::timeout( From 83ccfbff573676e4237e70cf3f1862a51f4bb439 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 08:05:49 +0800 Subject: [PATCH 02/20] fix(exec): confirm a shell command's stop at the owner `HostPlatform.kill` on a shell command only wrote Ctrl+C. The interrupt aborts the wrapper line before it prints the end marker, so the command never reached a terminal: `BackgroundExec.stop` waited forever, the shell stayed occupied, and its Session hold blocked an idle unload. The owner now confirms the stop: Ctrl+C, a bounded wait for the command's terminal, and, when the command cannot end inside the live shell, shell termination whose terminal sweep records the command as a reset. The stop returns a terminal in every case and settles afterwards. Also in this fix: - `ensure_shell` checks the owner record of the shell it holds, so a command that arrives after the shell ended and before its exit waiter ran spawns a new shell instead of writing into a terminal one. - `ShellSession` drops its unused `dispatcher` dependency and reuses one shell-exit note helper; the note read no longer uses a `try_lock`. - `WorkspaceTools.md` states that a stopped shell task ends failed and wakes; `HostPlatform.md` names the task owner that calls `kill` and describes the confirmation. Refs #2032 --- .../src/host_platform.rs | 20 ++++++- .../src/shell_session.rs | 52 +++++++------------ .../rust-agent/plugins/HostPlatform.md | 4 +- .../rust-agent/plugins/WorkspaceTools.md | 11 ++-- .../research/1295-host-platform-task-owner.md | 9 ++-- tests/integration/tests/minimal_execution.rs | 48 +++++++++++++++++ 6 files changed, 101 insertions(+), 43 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 2da67e6563..b542a3c499 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -47,6 +47,11 @@ pub use exec_shell_settings::{ExecShellSettings, ExecShellSettingsError, ShellCh pub const EXEC_SHELL_CONFIG_INVALID: &str = "EXEC_SHELL_CONFIG_INVALID"; pub const EXEC_SHELL_UNAVAILABLE: &str = "EXEC_SHELL_UNAVAILABLE"; +/// How long a shell command's interrupt may take to produce its end marker +/// before the shell is terminated. An interrupt aborts the whole wrapper line, +/// so a command that did not end in this window never prints one. +const SHELL_COMMAND_STOP_WAIT_MS: u64 = 2_000; + #[cfg(windows)] const WINDOWS_SANDBOX_UNAVAILABLE: &str = "The sandbox has no backend on Windows; select Off in /settings > Process isolation"; @@ -1236,7 +1241,20 @@ impl HostPlatform { .shell .write(b"\x03") .await - .map_err(|error| HostPlatformError::Io(error.to_string())) + .map_err(|error| HostPlatformError::Io(error.to_string()))?; + if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status != WaitStatus::Running { + return Ok(()); + } + // The interrupt aborted the wrapper line before its end marker + // printed, so the command cannot end inside the live shell. + // Terminating the shell sweeps the command to its terminal. + command.shell.terminate(); + if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status == WaitStatus::Running { + return Err(HostPlatformError::Failed( + "the shell did not confirm the command's end".into(), + )); + } + Ok(()) } TaskKind::Job(job) => { if !self.stopping.lock().unwrap().insert(task.id.clone()) { diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 1720db4c54..28def40208 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -18,7 +18,7 @@ use crate::{ }, }; use base64::{Engine, engine::general_purpose::STANDARD}; -use dim_agent_runtime::{Dispatcher, Names}; +use dim_agent_runtime::Names; use dim_agent_types::{ExecEndedData, JsonObject, ToolContent, ToolEffect, ToolResult}; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; @@ -102,11 +102,6 @@ pub struct ShellSession { config: ShellSessionConfig, lifecycle: CancellationToken, host: Arc, - #[expect( - dead_code, - reason = "stored at composition; no shell path dispatches through it" - )] - dispatcher: Arc, /// SessionStore's output ownership (ADR 013); absent in hosts without /// native storage, where shell output has no owner. owner: Option>, @@ -122,7 +117,6 @@ impl ShellSession { pub fn new( config: ShellSessionConfig, host: Arc, - dispatcher: Arc, owner: Option>, session_id: String, background: Arc, @@ -143,7 +137,6 @@ impl ShellSession { config, lifecycle: CancellationToken::new(), host, - dispatcher, owner, session_id, background, @@ -388,7 +381,12 @@ impl ShellSession { if self.lifecycle.is_cancelled() { return Err(HostError::Cancelled("shell session closed".into())); } - if inner.shell.is_some() { + let alive = inner.shell.as_ref().is_some_and(|id| { + self.host + .task(id) + .is_some_and(|record| !record.is_terminal()) + }); + if alive { return Ok(None); } inner.generation @@ -652,15 +650,10 @@ impl ShellSession { } let task_id = inner.shell.take(); if task_id.is_some() { - let note = match end { - Some(reply) => match (reply.signal.as_deref(), reply.exit_code) { - (Some(signal), _) => format!("[shell killed by signal: {signal}]"), - (_, Some(code)) => format!("[shell exited: code {code}]"), - _ => "[shell exited]".to_owned(), - }, - None => "[shell exited]".to_owned(), - }; - inner.shell_exit = Some(note); + inner.shell_exit = Some(end.as_ref().map_or_else( + || "[shell exited]".to_owned(), + |reply| shell_exit_note(reply.signal.as_deref(), reply.exit_code), + )); } inner.had_reset = true; inner.occupying = None; @@ -724,19 +717,19 @@ impl ShellSession { let note = match reply.failure_note.clone() { Some(note) => Some(note), None => { - let shell_id = self.inner.lock().await.shell.clone(); + let (shell_id, shell_exit) = { + let inner = self.inner.lock().await; + (inner.shell.clone(), inner.shell_exit.clone()) + }; let terminal = shell_id .as_ref() .and_then(|id| self.host.task(id)) .and_then(|record| record.terminal()); terminal - .map(|terminal| shell_exit_note(&terminal)) - .or_else(|| { - self.inner - .try_lock() - .ok() - .and_then(|inner| inner.shell_exit.clone()) + .map(|terminal| { + shell_exit_note(terminal.signal.as_deref(), terminal.exit_code) }) + .or(shell_exit) } }; if let Some(note) = note { @@ -1124,7 +1117,6 @@ pub struct ShellSessionPlugin { background: Key, facts: Key, session: Key, - dispatcher: Key, host: Key, lifecycle: Key, session_config: Key, @@ -1146,7 +1138,6 @@ impl ShellSessionPlugin { background: names.key()?, facts: names.key()?, session: names.key()?, - dispatcher: names.key()?, host: names.key()?, lifecycle: names.key()?, session_config: names.key()?, @@ -1163,7 +1154,6 @@ impl DynPlugin for ShellSessionPlugin { fn injects(&self) -> Vec { vec![ self.background.erase(), - self.dispatcher.erase(), self.host.erase(), self.lifecycle.erase(), self.session_config.erase(), @@ -1172,7 +1162,6 @@ impl DynPlugin for ShellSessionPlugin { } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - let dispatcher = ctx.require_at(&self.dispatcher)?; let host = ctx.require_at(&self.host)?; let background = ctx.require_at(&self.background)?; let config = ctx.require_at(&self.session_config)?; @@ -1190,7 +1179,6 @@ impl DynPlugin for ShellSessionPlugin { .join(&identity.branch_id), }), host, - dispatcher, owner, identity.session_id.clone(), background, @@ -1319,8 +1307,8 @@ fn occupancy_error(task_id: &str, error: WaitError) -> String { } } -fn shell_exit_note(terminal: &crate::host_platform::Terminal) -> String { - match (terminal.signal.as_deref(), terminal.exit_code) { +fn shell_exit_note(signal: Option<&str>, exit_code: Option) -> String { + match (signal, exit_code) { (Some(signal), _) => format!("[shell killed by signal: {signal}]"), (_, Some(code)) => format!("[shell exited: code {code}]"), _ => "[shell exited]".to_owned(), diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index d1a35c6930..dfac6ceee6 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,7 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table or an existing output log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a stop is pending answers `task_running`. Command and job logs stay under the output directory the caller gives the owner; the +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal; because the interrupt aborts the wrapper line before its end marker, a command that does not end within two seconds leaves the owner no way to end it inside the live shell, so `kill` terminates the shell and its terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical @@ -157,7 +157,7 @@ switches: declarations are read once, while each process start reads them. For a persistent shell, background PIDs enter through the existing PTY marker. `PtyProcessTree::job_pid` uses portable-pty's foreground-group handle and Linux's namespace/session metadata to resolve the native host identity once. `ShellJob.pid` -stores the typed PID in the owner record; `ShellSession` keeps only the task id and calls +stores the typed PID in the owner record; the calling task owner keeps only the task id and calls `host.kill` by id. A bounded native stop waits for release before the cancelled terminal fact; the public signal helper is unchanged. A running shell keeps the boundary it started with; changing the switches applies to the next diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index 0fdb9b1b4f..2f3e1a5e8b 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -672,10 +672,13 @@ the typed `BackgroundExec` serves it and stays the Rust binding. clamps to 4 MiB, `bytes` is what the page consumed, and the next cursor is `cursor + bytes`; `nextCursor` is present only for a full page. `wait` answers an ended task at once and otherwise waits for its dispatch until `timeoutMs` elapses. -For a running task, `timeoutMs = 0` answers `timeout`. `stop` is kill: it cancels -a running task so it ends `cancelled` -and does not wake, and answers an already ended task's record without changing -its wake. Cancellation is the caller dropping the call: a dropped `outputPage` +For a running task, `timeoutMs = 0` answers `timeout`. `stop` is kill: it stops +a running task and answers the owner's terminal, and an already ended task keeps +its record and wake. The terminal decides the wake: `cancelled` stays silent and +every other status posts the completion notice. A shell task is interrupted in +its persistent shell; its terminal is `failed` (the interrupted command's exit +status, or a shell reset when the shell had to be terminated), so stopping a +shell task does wake. Cancellation is the caller dropping the call: a dropped `outputPage` drops the read and a dropped `wait` releases the watch. `start` needs the live process, so it is the caller's own operation — the `exec` tool and `ShellSession` — and is not on the face. diff --git a/docs/design/research/1295-host-platform-task-owner.md b/docs/design/research/1295-host-platform-task-owner.md index aab98b04f0..2b162e0900 100644 --- a/docs/design/research/1295-host-platform-task-owner.md +++ b/docs/design/research/1295-host-platform-task-owner.md @@ -340,10 +340,11 @@ does not claim a test that is not in the tree. ### 7.3 Scope and follow-up `task_ended` is in this PR: step 2 adds it, step 4 makes `write`/`resize` return it, and `write_to_a_terminated_shell_answers_task_ended` gates it; no `connection.rs` change for -that case. `session.exec.stop` is step 6: the minimal `ShellSession` `ExecStop` provider -serves shell tasks; the local profile keeps `BackgroundExec`. `BackgroundExec` gains no -`ShellSession` dependency; `ShellSession`'s existing recovery dependency on `BackgroundExec` -stays. +that case. `session.exec.stop` is step 6: it calls the branch stop owner. `BackgroundExec` gains no +`ShellSession` dependency; `ShellSession`'s dependency on `BackgroundExec` stays. +[#2032](https://github.com/arcships/dim/issues/2032) board A replaced the two-provider route this +record describes: shell tasks are registered with `BackgroundExec`, and `BackgroundExec.stop` is the +only stop entry ([WorkspaceTools §BackgroundExec](../../architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec)). ## 8. Rule check | Rule | Application | | --- | --- | diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 053ec9efbe..7dccb458f6 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -945,6 +945,54 @@ async fn stop_background_task() { harness.shutdown().await; } +/// Stopping a command that converted to the background returns a terminal. The +/// interrupt aborts its wrapper line, so the owner terminates the shell instead +/// of waiting for an end marker that never prints; the next call runs in a new +/// shell. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn stop_an_occupying_command_returns_and_the_shell_keeps_working() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[("execute", json!({"command": "sleep 60", "timeoutMs": 100}))], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + + let stop = session + .service::("main") + .unwrap(); + let ended = tokio::time::timeout(Duration::from_secs(10), stop.stop(task_id.clone())) + .await + .expect("the stop returns once the owner confirms the terminal") + .unwrap(); + assert_eq!(ended.task_id, task_id); + assert_eq!(ended.status, ExecStatus::Failed); + assert!( + text(&ended.result).contains("shell reset"), + "{}", + text(&ended.result) + ); + + harness + .run( + &session, + &[("execute", json!({"command": "echo after-stop"}))], + ) + .await; + let events = until(&session, "next result", |events| tool_results(events) == 2).await; + let result = &results(&events)[1]; + assert!(text(result).contains("after-stop"), "{}", text(result)); + session.close().await.unwrap(); + harness.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn shell_exit_settles_tasks() { let harness = Harness::new(platform(&[]).await).await; From e21a8276fc587cffb9e3f80538011548ee0dedb6 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 08:47:20 +0800 Subject: [PATCH 03/20] docs(exec): a stopped shell command and a shell job end differently `stop` on a persistent shell's background job ends it `cancelled` and wakes nobody; only a shell command is interrupted and ends `failed`. State both, so the owner contract does not claim every shell task wakes. Refs #2032 --- docs/architecture/rust-agent/plugins/WorkspaceTools.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index 2f3e1a5e8b..8f9eac0c1b 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -675,10 +675,11 @@ ended task at once and otherwise waits for its dispatch until `timeoutMs` elapse For a running task, `timeoutMs = 0` answers `timeout`. `stop` is kill: it stops a running task and answers the owner's terminal, and an already ended task keeps its record and wake. The terminal decides the wake: `cancelled` stays silent and -every other status posts the completion notice. A shell task is interrupted in -its persistent shell; its terminal is `failed` (the interrupted command's exit -status, or a shell reset when the shell had to be terminated), so stopping a -shell task does wake. Cancellation is the caller dropping the call: a dropped `outputPage` +every other status posts the completion notice. A command that started as a +native process and a persistent shell's background job both end `cancelled`, so +neither wakes. A shell command is interrupted in its persistent shell; its +terminal is `failed` (the interrupted command's exit status, or a shell reset +when the shell had to be terminated), so stopping a shell command does wake. Cancellation is the caller dropping the call: a dropped `outputPage` drops the read and a dropped `wait` releases the watch. `start` needs the live process, so it is the caller's own operation — the `exec` tool and `ShellSession` — and is not on the face. From f40739d4795be81c497fd3677f57d7727bab64d2 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 09:12:09 +0800 Subject: [PATCH 04/20] test(exec): report the selected shell when the preference assertion fails The first-command shell selection occasionally failed on CI without showing what the tool answered. Show the result text in the assertion message. Refs #2032 --- tests/integration/tests/minimal_execution.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 7dccb458f6..8abd5bed37 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -655,7 +655,12 @@ async fn new_persistent_shells_and_environment_refresh_use_current_preferences() .await; session.idle("main").await.unwrap(); let events = local_events(&session).await; - assert!(text(results(&events).last().unwrap()).contains(&format!("selected={alternate}"))); + let call_results = results(&events); + let selected = text(call_results.last().unwrap()); + assert!( + selected.contains(&format!("selected={alternate}")), + "expected selected={alternate}: {selected}" + ); let environment = events .iter() .rev() From 71a074d6aafafc9cd045a4af2f5cd639e890cfe8 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 09:34:10 +0800 Subject: [PATCH 05/20] fix(exec): show the shell's output when its initialization times out The init command's capture is empty when the shell never runs the wrapper, so the failure reported nothing that explained it. Read the shell task's tail instead. A fresh HOME with zsh, for example, runs the new-user wizard, which consumes the wrapper line and now leaves that wizard text in the message. Refs #2032 --- .../src/shell_session.rs | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 28def40208..98ef39d5af 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -575,11 +575,22 @@ impl ShellSession { .map_err(|error| error.to_string())?; let _ = std::fs::remove_file(&output_path); if reply.status == WaitStatus::Running { - let mut inner = self.inner.lock().await; - let task_id = inner.shell.take(); - let captured = reply.preview.clone(); - inner.had_reset = true; - drop(inner); + let task_id = { + let mut inner = self.inner.lock().await; + inner.had_reset = true; + inner.shell.take() + }; + let captured = match &task_id { + Some(task_id) => self + .host + .tail(TaskRequest { + task_id: task_id.clone(), + }) + .await + .map(|tail| tail.text) + .unwrap_or_default(), + None => String::new(), + }; if let Some(task_id) = task_id { self.stop_shell(&task_id).await; } From 4af4083bc6799caf24d8f402b49c5ba6b96e6ddc Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 09:54:37 +0800 Subject: [PATCH 06/20] fix(host-platform): keep zsh's newuser wizard out of the first command zsh loads its newuser module at boot when the user has none of `.zshenv`, `.zprofile`, `.zshrc` or `.zlogin`; the module runs a startup wizard that reads the first line as its answer. A persistent shell in such a home never printed the init end marker and the first command failed with "shell did not initialize". Start zsh with `NO_RCS` only in that case: there is no user startup file to load, and skipping the global rcs is what keeps the wizard from consuming the command. A home with any of those files keeps loading them as before. The minimal-execution preference flow reproduced this deterministically with a fresh HOME and now passes. Refs #2032 --- .../dim-agent-capabilities/src/host_platform.rs | 16 +++++++++++++--- .../rust-agent/plugins/HostPlatform.md | 3 +++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index b542a3c499..067a1807d5 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -4235,6 +4235,12 @@ pub(crate) mod shell { Some((task_id.to_owned(), pid)) } + fn zsh_startup_files(home: &Path) -> bool { + [".zshenv", ".zprofile", ".zshrc", ".zlogin"] + .iter() + .any(|name| home.join(name).is_file()) + } + fn last_full_marker(line: &str) -> Option<(&'static str, &str)> { let mut found: Option<(usize, (&'static str, &str))> = None; for (prefix, position) in [ @@ -4391,11 +4397,15 @@ pub(crate) mod shell { return Err(ProcessSpecError { code, reason }); } }; - let args: &[&str] = match runtime.edition { + let args: Vec<&str> = match runtime.edition { ShellEdition::Pwsh | ShellEdition::WindowsPowershell => { - &["-NoLogo", "-NoProfile", "-Command"] + vec!["-NoLogo", "-NoProfile", "-Command"] } - _ => &["-i"], + // zsh's newuser module runs a startup wizard when the user has + // none of its startup files, and that wizard reads the first + // command as its answer. + ShellEdition::Zsh if !zsh_startup_files(&self.home) => vec!["-i", "-f"], + _ => vec!["-i"], }; let spec = ProcessSpec { executable: PathBuf::from(&runtime.executable_path), diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index dfac6ceee6..9906f97015 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -162,6 +162,9 @@ stores the typed PID in the owner record; the calling task owner keeps only the the public signal helper is unchanged. A running shell keeps the boundary it started with; changing the switches applies to the next process. macOS permits only the needed terminal ioctl commands. +A zsh whose user home has none of `.zshenv`, `.zprofile`, `.zshrc` or `.zlogin` starts with +`NO_RCS`: zsh's newuser module would otherwise run a startup wizard that reads the first command +as its answer. With any of those files the shell loads them as before. ## Command construction From 9e69c92b23e4aac0c6c58da405b773aa3bf6ed79 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 10:24:55 +0800 Subject: [PATCH 07/20] fix(exec): tolerate a shell's startup consumer and confirm job release Review round on #2206: - Shell initialization no longer depends on which home the shell reads. The init wrapper is written again until its end marker reaches the shell's tail, so a startup consumer (zsh's newuser wizard), a `ZDOTDIR` or a `platform_home`/`HOME` mismatch cannot lose it. The zsh `NO_RCS` argument and the home check that selected it are removed. - A shell's background jobs are released, and their release confirmed, before the shell records its terminal: the worker kills each live job with the SIGKILL escalation and waits for it. The terminal sweep keeps a SIGKILL backstop instead of one unconfirmed SIGTERM, and the unused `terminate_job` helper is gone. A job that ignores SIGTERM no longer outlives its terminal. - The interrupt wording matches what shells do: some print the end marker after Ctrl+C and end the command with its interrupted status; only a command still running after the two-second wait makes the owner terminate the shell and sweep it as a reset. - The converted-command stop test asserts the terminal and that the next call runs, both of which hold for either shell behavior, and a new test stops a shell with a SIGTERM-ignoring job and checks the process is gone. Refs #2032 --- .../src/host_platform.rs | 68 +++++----- .../src/shell_session.rs | 117 +++++++++--------- .../rust-agent/plugins/HostPlatform.md | 10 +- tests/integration/tests/minimal_execution.rs | 65 ++++++++-- 4 files changed, 152 insertions(+), 108 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 067a1807d5..01caab63a4 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -47,9 +47,10 @@ pub use exec_shell_settings::{ExecShellSettings, ExecShellSettingsError, ShellCh pub const EXEC_SHELL_CONFIG_INVALID: &str = "EXEC_SHELL_CONFIG_INVALID"; pub const EXEC_SHELL_UNAVAILABLE: &str = "EXEC_SHELL_UNAVAILABLE"; -/// How long a shell command's interrupt may take to produce its end marker -/// before the shell is terminated. An interrupt aborts the whole wrapper line, -/// so a command that did not end in this window never prints one. +/// How long a shell command's interrupt may take to record its terminal before +/// the shell is terminated. Some shells print the end marker after the +/// interrupt and the command ends with its interrupted status; one still +/// running after this window cannot end inside the live shell. const SHELL_COMMAND_STOP_WAIT_MS: u64 = 2_000; #[cfg(windows)] @@ -1245,9 +1246,10 @@ impl HostPlatform { if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status != WaitStatus::Running { return Ok(()); } - // The interrupt aborted the wrapper line before its end marker - // printed, so the command cannot end inside the live shell. - // Terminating the shell sweeps the command to its terminal. + // A command still running after the interrupt did not end + // inside the live shell (some shells abort the whole wrapper + // line, so no end marker can print). Terminating the shell + // sweeps the command to its terminal. command.shell.terminate(); if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status == WaitStatus::Running { return Err(HostPlatformError::Failed( @@ -3569,21 +3571,6 @@ impl Drop for PtyProcessTree { } } -/// Terminates a background job by its root pid: the process group it leads -/// on POSIX, the process tree under it on Windows. -pub fn terminate_job(pid: u32) -> io::Result<()> { - #[cfg(unix)] - { - // SAFETY: plain syscall on the addressed group. - if unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGTERM) } != 0 { - return Err(io::Error::last_os_error()); - } - Ok(()) - } - #[cfg(windows)] - native::terminate_tree(pid) -} - async fn observe_job_release( record: Arc, job: Arc, @@ -3616,9 +3603,8 @@ async fn observe_job_release( } } -/// Kills a background job that outlived its shell and confirms it is gone: -/// the process group it leads on POSIX, the process tree under it on -/// Windows. +/// Kills a background job and confirms it is gone: the process group it leads +/// on POSIX, the process tree under it on Windows. pub async fn kill_job(pid: u32, tree: Option>) -> io::Result<()> { #[cfg(unix)] { @@ -3988,7 +3974,7 @@ pub(crate) mod shell { ExecShellRuntime, HostPlatform, ProcessSpec, ProcessSpecError, PtyProcessTree, PtySize, ShellEdition, ShellStatus, }; - use super::{TaskKind, TaskRecord, terminate_job}; + use super::{TaskKind, TaskRecord, job_tree, kill_job}; use crate::workspace_tools::background::{ OutputPageError, PAGE_CHAR_TRAILING_BYTES, decode_page, }; @@ -4235,12 +4221,6 @@ pub(crate) mod shell { Some((task_id.to_owned(), pid)) } - fn zsh_startup_files(home: &Path) -> bool { - [".zshenv", ".zprofile", ".zshrc", ".zlogin"] - .iter() - .any(|name| home.join(name).is_file()) - } - fn last_full_marker(line: &str) -> Option<(&'static str, &str)> { let mut found: Option<(usize, (&'static str, &str))> = None; for (prefix, position) in [ @@ -4397,15 +4377,11 @@ pub(crate) mod shell { return Err(ProcessSpecError { code, reason }); } }; - let args: Vec<&str> = match runtime.edition { + let args: &[&str] = match runtime.edition { ShellEdition::Pwsh | ShellEdition::WindowsPowershell => { - vec!["-NoLogo", "-NoProfile", "-Command"] + &["-NoLogo", "-NoProfile", "-Command"] } - // zsh's newuser module runs a startup wizard when the user has - // none of its startup files, and that wizard reads the first - // command as its answer. - ShellEdition::Zsh if !zsh_startup_files(&self.home) => vec!["-i", "-f"], - _ => vec!["-i"], + _ => &["-i"], }; let spec = ProcessSpec { executable: PathBuf::from(&runtime.executable_path), @@ -4605,6 +4581,20 @@ pub(crate) mod shell { reader_finished, ) .await; + // A job outlives its shell only until it is released: confirm + // that before the shell's terminal sweeps it to its own. + for child in worker.children_list() { + if child.is_terminal() { + continue; + } + let pid = match &child.kind { + TaskKind::Job(job) => *job.pid.borrow(), + _ => None, + }; + if let Some(pid) = pid { + let _ = kill_job(pid, job_tree(pid)).await; + } + } let terminal = shell_terminal(&worker_record, worker.output_record(), exit, status, error); worker_record.finish(terminal); @@ -4705,7 +4695,7 @@ pub(crate) mod shell { super::TaskKind::ShellCommand(command) => command.output_record(), super::TaskKind::Job(job) => { if let Some(pid) = *job.pid.borrow() { - let _ = terminate_job(pid); + super::native::kill_tree(pid); } job.output_record().0 } diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 98ef39d5af..89c3651d80 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -36,6 +36,9 @@ const OUTPUT_LIMIT: usize = 16_000; const MAX_TIMEOUT_MS: u64 = 3_600_000; const DESCRIPTION_CHARS: usize = 200; const INIT_TIMEOUT: Duration = Duration::from_secs(10); +/// How long one init wrapper may take before another copy is written: a +/// startup consumer can eat the first one. +const INIT_RETRY: Duration = Duration::from_secs(1); const STOP_WAIT: Duration = Duration::from_secs(2); /// Configuration for the shell session. @@ -545,8 +548,13 @@ impl ShellSession { Ok(reset_note) } - /// Sends the init command and waits for its terminal; a timeout - /// terminates the shell and fails the call. + /// Writes the init wrapper until its end marker reaches the shell's tail; + /// a timeout terminates the shell and fails the call. + /// + /// A shell can spend its first input on a startup consumer — zsh's newuser + /// wizard, for example — instead of the shell prompt, so the wrapper is + /// written again until one copy runs. The typed line carries the marker + /// fragments separately, so its echo cannot satisfy the check. async fn send_initial(self: &Arc, command: &str) -> Result<(), String> { let (start, end) = marker_pair(); let dialect = { @@ -557,67 +565,64 @@ impl ShellSession { ShellDialect::Posix => posix_command(command, &start, &end), ShellDialect::Pwsh => pwsh_command(command, &start, &end), }; - let command_id = format!("shell-init-{}", uuid::Uuid::new_v4().simple()); - let output_path = self.config.output_dir.join(format!("{command_id}.log")); - self.start_command(&command_id, &start.full(), &end.full(), &wrapped) - .await - .map_err(|error| error.to_string())?; - let reply = self - .host - .wait( - WaitRequest { - task_id: command_id.clone(), - timeout_ms: Some(INIT_TIMEOUT.as_millis() as u64), - }, - never_cancelled(), - ) - .await - .map_err(|error| error.to_string())?; - let _ = std::fs::remove_file(&output_path); - if reply.status == WaitStatus::Running { + let start_marker = start.full(); + let end_marker = end.full(); + let deadline = tokio::time::Instant::now() + INIT_TIMEOUT; + let mut write_at = tokio::time::Instant::now(); + loop { let task_id = { - let mut inner = self.inner.lock().await; - inner.had_reset = true; - inner.shell.take() + let inner = self.inner.lock().await; + inner.shell.clone() }; - let captured = match &task_id { - Some(task_id) => self - .host - .tail(TaskRequest { - task_id: task_id.clone(), - }) - .await - .map(|tail| tail.text) - .unwrap_or_default(), - None => String::new(), + let Some(task_id) = task_id else { + return Err("shell exited during initialization".into()); }; - if let Some(task_id) = task_id { - self.stop_shell(&task_id).await; - } - let _ = self + let tail = self .host - .settle(TaskRequest { - task_id: command_id.clone(), + .tail(TaskRequest { + task_id: task_id.clone(), }) .await; - return Err(format!( - "shell did not initialize; captured output: {captured}" - )); - } - let _ = self - .host - .settle(TaskRequest { - task_id: command_id.clone(), - }) - .await; - if matches!( - reply.failure, - Some(crate::host_platform::TaskFailure::ShellReset) - | Some(crate::host_platform::TaskFailure::ShellExited) - ) { - return Err("shell exited during initialization".into()); + let started = match &tail { + Ok(tail) => tail.text.contains(&start_marker), + Err(_) => false, + }; + let now = tokio::time::Instant::now(); + if now >= write_at && !started { + self.write_shell(format!("{wrapped}\n").as_bytes()) + .await + .map_err(|error| error.to_string())?; + write_at = now + INIT_RETRY; + } + match &tail { + Ok(tail) if tail.text.contains(&end_marker) => return Ok(()), + Ok(_) => {} + Err(_) => { + if self + .host + .task(&task_id) + .is_none_or(|record| record.is_terminal()) + { + return Err("shell exited during initialization".into()); + } + } + } + if tokio::time::Instant::now() >= deadline { + let captured = tail.map(|tail| tail.text).unwrap_or_default(); + let taken = { + let mut inner = self.inner.lock().await; + inner.had_reset = true; + inner.shell.take() + }; + if let Some(task_id) = taken { + self.stop_shell(&task_id).await; + } + return Err(format!( + "shell did not initialize; captured output: {captured}" + )); + } + tokio::time::sleep(Duration::from_millis(50)).await; } - Ok(()) } /// Writes a wrapped command and starts its owner-side capture. diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 9906f97015..5cb1748276 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,7 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table or an existing output log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal; because the interrupt aborts the wrapper line before its end marker, a command that does not end within two seconds leaves the owner no way to end it inside the live shell, so `kill` terminates the shell and its terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command ends with its interrupted status and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` terminates the shell and its terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical @@ -162,9 +162,11 @@ stores the typed PID in the owner record; the calling task owner keeps only the the public signal helper is unchanged. A running shell keeps the boundary it started with; changing the switches applies to the next process. macOS permits only the needed terminal ioctl commands. -A zsh whose user home has none of `.zshenv`, `.zprofile`, `.zshrc` or `.zlogin` starts with -`NO_RCS`: zsh's newuser module would otherwise run a startup wizard that reads the first command -as its answer. With any of those files the shell loads them as before. +A persistent shell's first command is the init wrapper, and the shell may spend its first +input on a startup consumer instead — zsh's newuser module runs a wizard when the user has no +startup files. `ShellSession` writes that wrapper again until its end marker reaches the shell's +tail, so no startup consumer can lose the initialization; the wrapper uses the same marker +fragments as every command, so its echoed text cannot pass for the marker. ## Command construction diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 8abd5bed37..4118740ad0 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -950,10 +950,11 @@ async fn stop_background_task() { harness.shutdown().await; } -/// Stopping a command that converted to the background returns a terminal. The -/// interrupt aborts its wrapper line, so the owner terminates the shell instead -/// of waiting for an end marker that never prints; the next call runs in a new -/// shell. +/// Stopping a command that converted to the background returns a terminal and +/// leaves the shell usable. A shell may abort the wrapper line on the interrupt, +/// in which case the owner terminates the shell and the command ends as a reset; +/// a shell that prints the end marker ends it with the interrupted status. Both +/// are a failed terminal. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn stop_an_occupying_command_returns_and_the_shell_keeps_working() { let harness = Harness::new(platform(&[]).await).await; @@ -979,11 +980,6 @@ async fn stop_an_occupying_command_returns_and_the_shell_keeps_working() { .unwrap(); assert_eq!(ended.task_id, task_id); assert_eq!(ended.status, ExecStatus::Failed); - assert!( - text(&ended.result).contains("shell reset"), - "{}", - text(&ended.result) - ); harness .run( @@ -1324,6 +1320,57 @@ async fn shell_exit_kills_background_jobs() { harness.shutdown().await; } +/// A job that ignores SIGTERM is gone before its terminal is published: the +/// shell confirms each job's release while it ends, instead of a single +/// unconfirmed signal from the terminal sweep. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_term_ignoring_job_is_gone_before_its_terminal() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + let pid_file = harness.cwd.join("ignoring.pid"); + harness + .run( + &session, + &[( + "execute", + json!({ + "command": format!( + "sh -c 'trap \"\" TERM; echo $$ > {}; sleep 60'", + pid_file.display() + ), + "runInBackground": true + }), + )], + ) + .await; + let events = until(&session, "start", |events| tool_results(events) == 1).await; + let task_id = task_of(&results(&events)[0]); + let pid = pid_in(&pid_file).await; + + harness + .run(&session, &[("execute", json!({"command": "exit 7"}))]) + .await; + let events = until(&session, "job settled", |events| ended(events).len() == 1).await; + let (_, end) = &ended(&events)[0]; + assert_eq!(end.task_id, task_id); + assert_eq!(end.status, ExecStatus::Failed); + assert!( + gone(&pid).await, + "background process {pid} survived the shell exit: result={:?}, process={:?}", + end.result, + std::process::Command::new("ps") + .args(["-o", "pid=,ppid=,pgid=,stat=,comm=", "-p", &pid]) + .output() + .map(|output| ( + output.status, + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + )) + ); + session.close().await.unwrap(); + harness.shutdown().await; +} + /// An `execute` call declares the command the persistent shell ran with the /// exit status it observed, and a later compaction's digest lists it /// (ContextCompaction §5.10, acceptance 18(a)). From 43f3cf393f8874a39b6f263ad5abcebe0bbcc978 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 11:10:41 +0800 Subject: [PATCH 08/20] docs(host-platform): state the job release that precedes a shell terminal The page said only that shell exit sweeps its children. State the new promise: before the shell writes its terminal it releases each live job with a SIGKILL escalation and waits for it. The SIGTERM-ignoring job test now asserts the process is not alive at the moment its `exec/ended` is observed, so it pins release-before-terminal instead of a two-second window. Refs #2032 --- docs/architecture/rust-agent/plugins/HostPlatform.md | 5 ++++- tests/integration/tests/minimal_execution.rs | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 5cb1748276..34b74250b2 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -37,7 +37,10 @@ given their path. `ShellSession`. A shell command capture is read by its command id and records the bounded output, tail and task log. `wait`, `kill`, `output` and `tail` address shell command and job ids as well as exec tasks. A shell command ends from its marker; shell exit sweeps its command and job -children. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is +children. Before a shell writes its terminal, it releases every live job with a SIGKILL +escalation and waits for it, so a job that ignores SIGTERM is gone before the job's own terminal +exists; the sweep keeps a SIGKILL backstop. A terminal shell answers `write`/`resize` with +`task_ended`, and `settle` is idempotent. A shell `outputPath` is registered before the reply and survives settle until `removeOutputDirectory` or Session deletion; `retainOutput` is idempotent. `ShellJobStart.outputPath` is an absolute path inside the shell output directory and its file stem equals the task id; `childPath` takes UTF-8 data, while the diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 4118740ad0..97ff183533 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -20,7 +20,7 @@ use dim_agent_runtime::testing::MinimalHost; use dim_agent_runtime::testing::{branch_events, chain_events}; use dim_agent_runtime::*; use dim_agent_types::*; -use process_support::{gone, pid_in}; +use process_support::{alive, gone, pid_in}; use rutis::host::CtxHost; use rutis::{Ctx, Plugin}; use serde_json::{Value, json}; @@ -1354,6 +1354,11 @@ async fn a_term_ignoring_job_is_gone_before_its_terminal() { let (_, end) = &ended(&events)[0]; assert_eq!(end.task_id, task_id); assert_eq!(end.status, ExecStatus::Failed); + assert!( + !alive(&pid), + "process {pid} was alive when its terminal was published: result={:?}", + end.result + ); assert!( gone(&pid).await, "background process {pid} survived the shell exit: result={:?}, process={:?}", From 670f9318ae8892a8dd0799b492d4125797b09173 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 12:10:57 +0800 Subject: [PATCH 09/20] fix(exec): release a stopped command's group and require a started init Review round on #2206: - A shell command that outlives Ctrl+C runs in the terminal's foreground process group, not the shell's. `HostPlatform::kill` now signals that group with SIGKILL and waits for it before it terminates the shell, so the command itself is released on macOS, where no `/proc` tree reaches it. The shutdown keeps the shell's own group to `PtyProcessTree::terminate`. - The init accepts an end marker only after a copy's start marker reached the shell's tail. An end marker a startup consumer emitted by itself no longer counts as initialization. - The job-release wording matches the code: release is best effort, a failed kill is not reported, and a descendant that left the job's group or session can outlive its terminal. Tests: `stopping_a_command_that_ignores_the_interrupt_leaves_no_process` and `a_startup_consumer_cannot_skip_the_init`; the macOS flow selection includes the first so that path runs on macOS. Refs #2032 --- .../src/host_platform.rs | 56 ++++++++- .../src/shell_session.rs | 16 +-- .../rust-agent/plugins/HostPlatform.md | 11 +- tests/integration/tests/minimal_execution.rs | 111 +++++++++++++++++- 4 files changed, 179 insertions(+), 15 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index 01caab63a4..b90455d813 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -1248,8 +1248,11 @@ impl HostPlatform { } // A command still running after the interrupt did not end // inside the live shell (some shells abort the whole wrapper - // line, so no end marker can print). Terminating the shell - // sweeps the command to its terminal. + // line, so no end marker can print). The command runs in the + // terminal's foreground process group, which a shell that + // aborts the line leaves running; signal it before terminating + // the shell, whose sweep records the command's terminal. + command.shell.kill_foreground_group().await; command.shell.terminate(); if task.wait(Some(SHELL_COMMAND_STOP_WAIT_MS)).await.status == WaitStatus::Running { return Err(HostPlatformError::Failed( @@ -3548,6 +3551,25 @@ impl PtyProcessTree { } Ok(()) } + /// Signals the terminal's foreground process group, where an interactive + /// shell runs the command it is executing, and answers its leader when that + /// group is not the shell's own. + pub fn kill_foreground_group(&self) -> Option { + #[cfg(unix)] + { + let leader = self.master.process_group_leader()?; + if leader as u32 == self.pid { + return None; + } + // SAFETY: plain syscall on the addressed group. + unsafe { libc::kill(-leader, libc::SIGKILL) }; + Some(leader as u32) + } + #[cfg(not(unix))] + { + None + } + } /// The root exited on its own and was reaped: its descendants stay. fn released(&self) -> bool { self.reaped && !self.terminating @@ -3571,6 +3593,23 @@ impl Drop for PtyProcessTree { } } +#[cfg(unix)] +async fn wait_group_gone(leader: u32) -> bool { + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + // SAFETY: signal 0 only probes the addressed group. + if unsafe { libc::kill(-(leader as libc::pid_t), 0) } != 0 + && io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) + { + return true; + } + if tokio::time::Instant::now() >= deadline { + return false; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } +} + async fn observe_job_release( record: Arc, job: Arc, @@ -4718,6 +4757,19 @@ pub(crate) mod shell { self.kill.cancel(); } + pub(crate) async fn kill_foreground_group(&self) -> bool { + let leader = { + let pty = self.pty.lock().await; + pty.as_ref().and_then(|pty| pty.kill_foreground_group()) + }; + #[cfg(unix)] + if let Some(leader) = leader { + return super::wait_group_gone(leader).await; + } + let _ = leader; + true + } + pub(crate) fn output_record(&self) -> super::OutputRecord { let capture = self.capture.lock().unwrap(); let (preview, preview_truncated) = diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 89c3651d80..c86ebc2c3f 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -553,8 +553,10 @@ impl ShellSession { /// /// A shell can spend its first input on a startup consumer — zsh's newuser /// wizard, for example — instead of the shell prompt, so the wrapper is - /// written again until one copy runs. The typed line carries the marker - /// fragments separately, so its echo cannot satisfy the check. + /// written again until one copy runs. A copy counts only after its start + /// marker reached the tail: the typed line carries the marker fragments + /// separately, so its echo cannot satisfy the check, and an end marker a + /// consumer emitted by itself is not an initialization. async fn send_initial(self: &Arc, command: &str) -> Result<(), String> { let (start, end) = marker_pair(); let dialect = { @@ -569,6 +571,7 @@ impl ShellSession { let end_marker = end.full(); let deadline = tokio::time::Instant::now() + INIT_TIMEOUT; let mut write_at = tokio::time::Instant::now(); + let mut started = false; loop { let task_id = { let inner = self.inner.lock().await; @@ -583,10 +586,7 @@ impl ShellSession { task_id: task_id.clone(), }) .await; - let started = match &tail { - Ok(tail) => tail.text.contains(&start_marker), - Err(_) => false, - }; + started |= matches!(&tail, Ok(tail) if tail.text.contains(&start_marker)); let now = tokio::time::Instant::now(); if now >= write_at && !started { self.write_shell(format!("{wrapped}\n").as_bytes()) @@ -595,7 +595,9 @@ impl ShellSession { write_at = now + INIT_RETRY; } match &tail { - Ok(tail) if tail.text.contains(&end_marker) => return Ok(()), + // A wrapper line the shell executed printed its start marker; + // an end marker alone is text a startup consumer emitted. + Ok(tail) if started && tail.text.contains(&end_marker) => return Ok(()), Ok(_) => {} Err(_) => { if self diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 34b74250b2..bcfc210d25 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,7 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table or an existing output log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command ends with its interrupted status and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` terminates the shell and its terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command ends with its interrupted status and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical @@ -37,10 +37,11 @@ given their path. `ShellSession`. A shell command capture is read by its command id and records the bounded output, tail and task log. `wait`, `kill`, `output` and `tail` address shell command and job ids as well as exec tasks. A shell command ends from its marker; shell exit sweeps its command and job -children. Before a shell writes its terminal, it releases every live job with a SIGKILL -escalation and waits for it, so a job that ignores SIGTERM is gone before the job's own terminal -exists; the sweep keeps a SIGKILL backstop. A terminal shell answers `write`/`resize` with -`task_ended`, and `settle` is +children. Before a shell writes its terminal, it tries to release every live job — SIGKILL to the +job's group and, where the platform can enumerate them, its descendants, then a wait — so a job +that ignores SIGTERM is gone before the job's own terminal; the sweep keeps a SIGKILL backstop. +This is best effort: a failed kill is not reported, and a descendant that left the job's group or +session can outlive it. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is idempotent. A shell `outputPath` is registered before the reply and survives settle until `removeOutputDirectory` or Session deletion; `retainOutput` is idempotent. `ShellJobStart.outputPath` is an absolute path inside the shell output directory and its file stem equals the task id; `childPath` takes UTF-8 data, while the diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 97ff183533..c1aa0fd3cd 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -10,7 +10,10 @@ use dim_agent_capabilities::{ file_storage::FileStoragePlugin, history::HistoryRenderer, host::*, - host_platform::{HostPlatform, HostPlatformConfig, HostPlatformPlugin, resolve_shell}, + host_platform::{ + ExecShellRuntime, HostPlatform, HostPlatformConfig, HostPlatformPlugin, OutputEncoding, + ShellEdition, ShellSource, ShellStatus, resolve_shell, + }, model_provider::ModelProviderPlugin, permission::{CommandRules, NoCommandRules}, skill_settings::SkillSettingsHost, @@ -994,6 +997,112 @@ async fn stop_an_occupying_command_returns_and_the_shell_keeps_working() { harness.shutdown().await; } +/// A command that ignores the interrupt is released by the owner. The command +/// runs in the terminal's foreground process group, not the shell's, and macOS +/// has no `/proc` tree to walk, so the owner signals that group itself before +/// it terminates the shell. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn stopping_a_command_that_ignores_the_interrupt_leaves_no_process() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + let pid_file = harness.cwd.join("stubborn.pid"); + harness + .run( + &session, + &[( + "execute", + json!({ + "command": format!( + "sh -c 'echo $$ > {}; trap \"\" INT TERM HUP; while true; do sleep 1; done'", + pid_file.display() + ), + "timeoutMs": 100 + }), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + let pid = pid_in(&pid_file).await; + + let stop = session + .service::("main") + .unwrap(); + let ended = tokio::time::timeout(Duration::from_secs(10), stop.stop(task_id.clone())) + .await + .expect("the stop returns once the owner confirms the terminal") + .unwrap(); + assert_eq!(ended.task_id, task_id); + assert_eq!(ended.status, ExecStatus::Failed); + let path = if cfg!(target_os = "macos") { + " the foreground-group signal did not release it" + } else { + "" + }; + assert!(gone(&pid).await, "process {pid} survived the stop;{path}"); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// A startup consumer cannot skip the initialization: the shell's `.zshrc` +/// reads the first wrapper line, and the next copy must run it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_startup_consumer_cannot_skip_the_init() { + let home = scratch("zsh-consumer"); + std::fs::write( + home.join(".zshrc"), + "HISTFILE=/tmp/dim-consumer-history +read -r __dim_init_line +", + ) + .unwrap(); + let Some(platform) = zsh_platform(&home) else { + return; + }; + let harness = Harness::new(platform).await; + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "printf 'histfile=%s' \"${HISTFILE-unset}\""}), + )], + ) + .await; + let events = until(&session, "result", |events| tool_results(events) == 1).await; + let call_results = results(&events); + let result = text(&call_results[0]); + assert!(result.contains("histfile=unset"), "{result}"); + session.close().await.unwrap(); + harness.shutdown().await; +} + +fn zsh_platform(home: &Path) -> Option { + let zsh = "/bin/zsh"; + if !Path::new(zsh).is_file() { + return None; + } + let mut env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); + env.retain(|(key, _)| key != "HOME" && key != "SHELL"); + env.push((OsString::from("HOME"), home.as_os_str().to_owned())); + env.push((OsString::from("SHELL"), OsString::from(zsh))); + let runtime = ExecShellRuntime { + executable_path: zsh.into(), + edition: ShellEdition::Zsh, + source: ShellSource::Fallback, + output_encoding: OutputEncoding::Utf8, + }; + let mut platform = HostPlatform::current(ShellStatus::Available(runtime)) + .unwrap() + .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())); + platform.env = env; + Some(platform) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn shell_exit_settles_tasks() { let harness = Harness::new(platform(&[]).await).await; From a090d4ab6490ca2353fe0bf3faf89810df44d1ff Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 12:18:03 +0800 Subject: [PATCH 10/20] docs(exec): state the stopped line's status and the release attempt A stopped shell command's terminal is the interrupted wrapper line's own status: it can be `completed` when the line continues past the interrupted command (`sleep 60 || true`), `failed` for the interrupted status of a line that stops there, or a shell reset when the owner had to terminate the shell. Also match the job-release text to the code: the worker attempts to release each live job whose pid is known, by SIGKILL and a wait of up to two seconds, and drops `kill_job`'s result. Refs #2032 --- .../architecture/rust-agent/plugins/HostPlatform.md | 13 +++++++------ .../rust-agent/plugins/WorkspaceTools.md | 5 +++-- tests/integration/tests/minimal_execution.rs | 4 ++-- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index bcfc210d25..29f1aebd38 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,7 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table or an existing output log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command ends with its interrupted status and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command's terminal is the interrupted line's own exit status — which can be success when the line continues past the interrupted command — and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical @@ -37,11 +37,12 @@ given their path. `ShellSession`. A shell command capture is read by its command id and records the bounded output, tail and task log. `wait`, `kill`, `output` and `tail` address shell command and job ids as well as exec tasks. A shell command ends from its marker; shell exit sweeps its command and job -children. Before a shell writes its terminal, it tries to release every live job — SIGKILL to the -job's group and, where the platform can enumerate them, its descendants, then a wait — so a job -that ignores SIGTERM is gone before the job's own terminal; the sweep keeps a SIGKILL backstop. -This is best effort: a failed kill is not reported, and a descendant that left the job's group or -session can outlive it. A terminal shell answers `write`/`resize` with `task_ended`, and `settle` is +children. Before a shell writes its terminal, it attempts to release each live job whose pid is +known: SIGKILL to the job's group and, where the platform can enumerate them, its descendants, then +a wait of up to two seconds. The sweep keeps a SIGKILL backstop. This is best effort: `kill_job`'s +result is dropped, so a failed kill is not reported, and a descendant that left the job's group or +session can outlive the job's terminal. A terminal shell answers `write`/`resize` with +`task_ended`, and `settle` is idempotent. A shell `outputPath` is registered before the reply and survives settle until `removeOutputDirectory` or Session deletion; `retainOutput` is idempotent. `ShellJobStart.outputPath` is an absolute path inside the shell output directory and its file stem equals the task id; `childPath` takes UTF-8 data, while the diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index 8f9eac0c1b..5dab2c6c41 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -678,8 +678,9 @@ its record and wake. The terminal decides the wake: `cancelled` stays silent and every other status posts the completion notice. A command that started as a native process and a persistent shell's background job both end `cancelled`, so neither wakes. A shell command is interrupted in its persistent shell; its -terminal is `failed` (the interrupted command's exit status, or a shell reset -when the shell had to be terminated), so stopping a shell command does wake. Cancellation is the caller dropping the call: a dropped `outputPage` +terminal is the interrupted wrapper line's own status, so an interrupted command +followed by `|| true` ends `completed`, and a line the shell aborts ends with the +owner's shell reset. A stopped shell command does wake. Cancellation is the caller dropping the call: a dropped `outputPage` drops the read and a dropped `wait` releases the watch. `start` needs the live process, so it is the caller's own operation — the `exec` tool and `ShellSession` — and is not on the face. diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index c1aa0fd3cd..65fd97b199 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -956,8 +956,8 @@ async fn stop_background_task() { /// Stopping a command that converted to the background returns a terminal and /// leaves the shell usable. A shell may abort the wrapper line on the interrupt, /// in which case the owner terminates the shell and the command ends as a reset; -/// a shell that prints the end marker ends it with the interrupted status. Both -/// are a failed terminal. +/// a shell that prints the end marker ends it with the interrupted status. For +/// this command both are a failed terminal. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn stop_an_occupying_command_returns_and_the_shell_keeps_working() { let harness = Harness::new(platform(&[]).await).await; From 966d8120955c63bd606e26cef4534f69e1c881bc Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 12:46:11 +0800 Subject: [PATCH 11/20] test(exec): make the startup-consumer case consume a prefix The test wrote its `.zshrc` into a home the harness replaces, read the wrapper whole, and asserted a value an empty home produces anyway. It now writes the consumer into the shell's HOME after the harness exists, consumes the line up to the boundary before the final `printf`, and keeps `HISTFILE` set only if the init did not run. The relaxed end-marker check fails it. Also: `HostPlatform.md` says initialization waits for one copy's start marker and then its end marker, and `PtyProcessTree::kill_foreground_group` is crate-only. Refs #2032 --- .../src/host_platform.rs | 2 +- .../rust-agent/plugins/HostPlatform.md | 5 +- tests/integration/tests/minimal_execution.rs | 47 ++++++++++--------- 3 files changed, 30 insertions(+), 24 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index b90455d813..db95598dc8 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3554,7 +3554,7 @@ impl PtyProcessTree { /// Signals the terminal's foreground process group, where an interactive /// shell runs the command it is executing, and answers its leader when that /// group is not the shell's own. - pub fn kill_foreground_group(&self) -> Option { + pub(crate) fn kill_foreground_group(&self) -> Option { #[cfg(unix)] { let leader = self.master.process_group_leader()?; diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 29f1aebd38..c733220948 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -169,8 +169,9 @@ A running shell keeps the boundary it started with; changing the switches applie process. macOS permits only the needed terminal ioctl commands. A persistent shell's first command is the init wrapper, and the shell may spend its first input on a startup consumer instead — zsh's newuser module runs a wizard when the user has no -startup files. `ShellSession` writes that wrapper again until its end marker reaches the shell's -tail, so no startup consumer can lose the initialization; the wrapper uses the same marker +startup files. `ShellSession` writes that wrapper again until one copy's start marker and then +its end marker reached the shell's tail, so no startup consumer can lose the initialization; an +end marker a consumer emitted by itself does not count. The wrapper uses the same marker fragments as every command, so its echoed text cannot pass for the marker. ## Command construction diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 65fd97b199..cbb4d690b6 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -1047,22 +1047,31 @@ async fn stopping_a_command_that_ignores_the_interrupt_leaves_no_process() { harness.shutdown().await; } -/// A startup consumer cannot skip the initialization: the shell's `.zshrc` -/// reads the first wrapper line, and the next copy must run it. +/// A startup consumer cannot skip the initialization. The `.zshrc` lives in the +/// shell's home, consumes the wrapper line up to the boundary before the final +/// `printf`, and leaves the shell to run that `printf`: the end marker alone +/// reaches the tail while the init never ran. `/bin/zsh` absent skips the case. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_startup_consumer_cannot_skip_the_init() { - let home = scratch("zsh-consumer"); - std::fs::write( - home.join(".zshrc"), - "HISTFILE=/tmp/dim-consumer-history -read -r __dim_init_line -", - ) - .unwrap(); - let Some(platform) = zsh_platform(&home) else { + let Some(platform) = zsh_platform() else { return; }; let harness = Harness::new(platform).await; + // The harness makes its cwd the shell's HOME. + std::fs::write( + harness.cwd.join(".zshrc"), + r#"HISTFILE=/tmp/dim-consumer-history +__dim_buf= +while true; do + read -k 1 __dim_ch || break + __dim_buf+=$__dim_ch + if [[ $__dim_buf == *"eval $'"* && $__dim_buf == *"'; " ]]; then + break + fi +done +"#, + ) + .unwrap(); let session = harness.session().await; harness .run( @@ -1081,26 +1090,22 @@ read -r __dim_init_line harness.shutdown().await; } -fn zsh_platform(home: &Path) -> Option { +fn zsh_platform() -> Option { let zsh = "/bin/zsh"; if !Path::new(zsh).is_file() { return None; } - let mut env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); - env.retain(|(key, _)| key != "HOME" && key != "SHELL"); - env.push((OsString::from("HOME"), home.as_os_str().to_owned())); - env.push((OsString::from("SHELL"), OsString::from(zsh))); let runtime = ExecShellRuntime { executable_path: zsh.into(), edition: ShellEdition::Zsh, source: ShellSource::Fallback, output_encoding: OutputEncoding::Utf8, }; - let mut platform = HostPlatform::current(ShellStatus::Available(runtime)) - .unwrap() - .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())); - platform.env = env; - Some(platform) + Some( + HostPlatform::current(ShellStatus::Available(runtime)) + .unwrap() + .with_execution_settings(ExecutionSettingsHost::fixed(ExecutionSettings::default())), + ) } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] From 7781b57e1c60af461d3b554ee906f6b750a1b8a0 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 13:28:29 +0800 Subject: [PATCH 12/20] fix(exec): release the foreground group on shell termination and order the init MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Delta review on #2206: - Terminating a shell for any reason — a shell command's stop, a shell kill or a Session close — now signals the terminal's foreground process group and waits for it, so the command the shell was running does not outlive the shell's terminal. `PtyProcessTree::terminate` and its `Drop` both do it. - Each init attempt carries its own marker pair, and an attempt counts only when its own start marker precedes its end marker in the tail. An end marker a startup consumer printed for an earlier attempt no longer completes a later one. `init_complete` holds the order rule. Tests: `closing_a_session_releases_an_occupying_command` (Session close path, selected by the macOS flow list) and the unit test `an_init_copy_completes_only_after_its_own_start_marker`. Refs #2032 --- .../src/host_platform.rs | 7 ++ .../src/shell_session.rs | 93 ++++++++++++------- .../rust-agent/plugins/HostPlatform.md | 10 +- tests/integration/tests/minimal_execution.rs | 49 ++++++++++ 4 files changed, 120 insertions(+), 39 deletions(-) diff --git a/crates/dim-agent-capabilities/src/host_platform.rs b/crates/dim-agent-capabilities/src/host_platform.rs index db95598dc8..98da28eff4 100644 --- a/crates/dim-agent-capabilities/src/host_platform.rs +++ b/crates/dim-agent-capabilities/src/host_platform.rs @@ -3527,6 +3527,9 @@ impl PtyProcessTree { self.terminating = true; #[cfg(unix)] { + // The command an interactive shell is running leads the + // terminal's foreground group, outside the shell's own. + let foreground = self.kill_foreground_group(); native::kill_tree(self.pid); let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); while tokio::time::Instant::now() < deadline { @@ -3535,6 +3538,9 @@ impl PtyProcessTree { None => tokio::time::sleep(std::time::Duration::from_millis(20)).await, } } + if let Some(leader) = foreground { + let _ = wait_group_gone(leader).await; + } } #[cfg(windows)] { @@ -3580,6 +3586,7 @@ impl PtyProcessTree { impl Drop for PtyProcessTree { fn drop(&mut self) { if !self.terminated && !self.released() { + self.kill_foreground_group(); native::kill_tree(self.pid); } } diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index c86ebc2c3f..6cabfd6375 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -548,30 +548,24 @@ impl ShellSession { Ok(reset_note) } - /// Writes the init wrapper until its end marker reaches the shell's tail; - /// a timeout terminates the shell and fails the call. + /// Writes the init wrapper until one copy's start marker and then its end + /// marker reach the shell's tail; a timeout terminates the shell and fails + /// the call. /// /// A shell can spend its first input on a startup consumer — zsh's newuser /// wizard, for example — instead of the shell prompt, so the wrapper is - /// written again until one copy runs. A copy counts only after its start - /// marker reached the tail: the typed line carries the marker fragments - /// separately, so its echo cannot satisfy the check, and an end marker a - /// consumer emitted by itself is not an initialization. + /// written again until one copy runs. Each copy carries its own markers, so + /// an end marker a consumer printed for an earlier copy cannot complete a + /// later one, and the typed line carries the fragments separately, so its + /// echo cannot satisfy the check. async fn send_initial(self: &Arc, command: &str) -> Result<(), String> { - let (start, end) = marker_pair(); let dialect = { let inner = self.inner.lock().await; inner.dialect }; - let wrapped = match dialect { - ShellDialect::Posix => posix_command(command, &start, &end), - ShellDialect::Pwsh => pwsh_command(command, &start, &end), - }; - let start_marker = start.full(); - let end_marker = end.full(); let deadline = tokio::time::Instant::now() + INIT_TIMEOUT; let mut write_at = tokio::time::Instant::now(); - let mut started = false; + let mut current: Option<(String, String)> = None; loop { let task_id = { let inner = self.inner.lock().await; @@ -580,34 +574,37 @@ impl ShellSession { let Some(task_id) = task_id else { return Err("shell exited during initialization".into()); }; + let now = tokio::time::Instant::now(); + if now >= write_at { + let (start, end) = marker_pair(); + let wrapped = match dialect { + ShellDialect::Posix => posix_command(command, &start, &end), + ShellDialect::Pwsh => pwsh_command(command, &start, &end), + }; + self.write_shell(format!("{wrapped}\n").as_bytes()) + .await + .map_err(|error| error.to_string())?; + current = Some((start.full(), end.full())); + write_at = now + INIT_RETRY; + } let tail = self .host .tail(TaskRequest { task_id: task_id.clone(), }) .await; - started |= matches!(&tail, Ok(tail) if tail.text.contains(&start_marker)); - let now = tokio::time::Instant::now(); - if now >= write_at && !started { - self.write_shell(format!("{wrapped}\n").as_bytes()) - .await - .map_err(|error| error.to_string())?; - write_at = now + INIT_RETRY; + if let (Some((start_marker, end_marker)), Ok(tail)) = (¤t, &tail) + && init_complete(&tail.text, start_marker, end_marker) + { + return Ok(()); } - match &tail { - // A wrapper line the shell executed printed its start marker; - // an end marker alone is text a startup consumer emitted. - Ok(tail) if started && tail.text.contains(&end_marker) => return Ok(()), - Ok(_) => {} - Err(_) => { - if self - .host - .task(&task_id) - .is_none_or(|record| record.is_terminal()) - { - return Err("shell exited during initialization".into()); - } - } + if let Err(_) = &tail + && self + .host + .task(&task_id) + .is_none_or(|record| record.is_terminal()) + { + return Err("shell exited during initialization".into()); } if tokio::time::Instant::now() >= deadline { let captured = tail.map(|tail| tail.text).unwrap_or_default(); @@ -1230,6 +1227,13 @@ impl DynPlugin for ShellSessionPlugin { } } +/// Whether `tail` holds `start` and `end` after it. An end marker a consumer +/// printed for an earlier copy, or by itself, does not complete a copy. +fn init_complete(tail: &str, start: &str, end: &str) -> bool { + tail.find(start) + .is_some_and(|at| tail[at + start.len()..].contains(end)) +} + /// Declares the command the call sent to the shell (session boundary A.6): /// the exit status the end marker carried, or none while it was still /// running. @@ -1528,3 +1532,22 @@ fn base64_encode(data: &str) -> String { use base64::Engine; base64::engine::general_purpose::STANDARD.encode(data.as_bytes()) } + +#[cfg(test)] +mod tests { + use super::init_complete; + + #[test] + fn an_init_copy_completes_only_after_its_own_start_marker() { + let start = "__DIM_START_aaaaaaaa_bbbbbbbb__"; + let end = "__DIM_END_cccccccc_dddddddd__"; + assert!(init_complete( + &format!("noise\n{start}\ninit output\n{end}\n"), + start, + end + )); + assert!(!init_complete(&format!("{end}\n{start}\n"), start, end)); + assert!(!init_complete(&format!("echo {end}\n"), start, end)); + assert!(!init_complete(&format!("{start}\n"), start, end)); + } +} diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index c733220948..528cbbf545 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,7 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table or an existing output log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command's terminal is the interrupted line's own exit status — which can be success when the line continues past the interrupted command — and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Command and job logs stay under the output directory the caller gives the owner; the +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command's terminal is the interrupted line's own exit status — which can be success when the line continues past the interrupted command — and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Terminating a shell — this stop, a shell kill or a Session close — releases that foreground group the same way before the shell's terminal sweeps its children. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical @@ -170,9 +170,11 @@ process. macOS permits only the needed terminal ioctl commands. A persistent shell's first command is the init wrapper, and the shell may spend its first input on a startup consumer instead — zsh's newuser module runs a wizard when the user has no startup files. `ShellSession` writes that wrapper again until one copy's start marker and then -its end marker reached the shell's tail, so no startup consumer can lose the initialization; an -end marker a consumer emitted by itself does not count. The wrapper uses the same marker -fragments as every command, so its echoed text cannot pass for the marker. +its end marker reached the shell's tail, so no startup consumer can lose the initialization. +Each copy carries its own marker pair, and a copy counts only when its own start marker precedes +its end marker: an end marker a consumer emitted for an earlier copy or by itself does not count. +The wrapper uses the same marker fragments as every command, so its echoed text cannot pass for +the marker. ## Command construction diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index cbb4d690b6..9cea6f6616 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -1047,6 +1047,55 @@ async fn stopping_a_command_that_ignores_the_interrupt_leaves_no_process() { harness.shutdown().await; } +/// Closing a Session releases the command its shell is running, not only +/// stopping a task. macOS has no `/proc` tree to walk, so the shell's +/// termination signals the terminal's foreground process group. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn closing_a_session_releases_an_occupying_command() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + let pid_file = harness.cwd.join("closing.pid"); + harness + .run( + &session, + &[( + "execute", + json!({ + "command": format!( + "sh -c 'echo $$ > {}; trap \"\" INT TERM HUP; while true; do sleep 1; done'", + pid_file.display() + ), + "timeoutMs": 100 + }), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + let pid = pid_in(&pid_file).await; + + session.close().await.unwrap(); + let events = local_events(&session).await; + let (_, end) = ended(&events) + .into_iter() + .find(|(_, data)| data.task_id == task_id) + .expect("closing publishes the occupying task's terminal"); + assert_eq!(end.status, ExecStatus::Failed); + let path = if cfg!(target_os = "macos") { + " the foreground-group signal did not release it" + } else { + "" + }; + assert!( + gone(&pid).await, + "process {pid} survived the Session close;{path}" + ); + harness.shutdown().await; +} + /// A startup consumer cannot skip the initialization. The `.zshrc` lives in the /// shell's home, consumes the wrapper line up to the boundary before the final /// `printf`, and leaves the shell to run that `printf`: the end marker alone From c247c75dc02e5ae8368af3b18ac0769f0e9edaa2 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 14:17:05 +0800 Subject: [PATCH 13/20] fix(exec): keep the exit status of handed-off commands and detached jobs The owner records a known exit code on a `failed` terminal: a shell command that ended non-zero, or a shell job whose completion marker carried it. The background result only built a `CommandExit` for an `exited` or `signaled` wait status, so `exec/ended` for those tasks carried no `exitCode` and said "command failed". `settled_from_reply` now derives the exit from the reply's own fields, so any terminal that has one reports it, and a `CommandFailed`/`UnknownExit` summary names the exit status through `exit_failure_summary`. Also: `BackgroundExec::stop`'s doc comment no longer claims a stopped task always ends `cancelled`; a shell command ends with the interrupted line's own status and wakes, matching `WorkspaceTools.md`. Tests: `a_handed_off_command_keeps_its_exit_code` and `a_detached_job_keeps_its_exit_code`; both fail without the fix. Refs #2032 --- .../src/workspace_tools/background.rs | 8 ++- .../src/workspace_tools/exec.rs | 19 ++++-- tests/integration/tests/minimal_execution.rs | 67 +++++++++++++++++++ 3 files changed, 84 insertions(+), 10 deletions(-) diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index cdf572eb03..0c47f1ddf1 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -667,9 +667,11 @@ impl BackgroundExec { } } - /// Stops a task: cancels it while running, so it ends `cancelled` and - /// does not wake. Returns once its `exec/ended` is dispatched; a task that - /// already ended keeps its result and its wake. + /// Stops a task and answers the owner's terminal: a native command or a + /// background job ends `cancelled` and does not wake, while a shell command + /// is interrupted and ends with the interrupted line's own status, so it + /// wakes. Returns once its `exec/ended` is dispatched; a task that already + /// ended keeps its result and its wake. pub async fn stop(&self, task_id: String) -> Result { let current = { let mut state = self.state.lock().unwrap(); diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index c766275f45..55ddd86740 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -2196,11 +2196,13 @@ fn settled_from_reply(reply: &WaitReply) -> (Settled, Option) { inline: reply.text.clone().unwrap_or_default(), failure: reply.failure.clone(), }; - let exit = - matches!(reply.status, WaitStatus::Exited | WaitStatus::Signaled).then(|| CommandExit { - code: reply.exit_code, - signal: reply.signal.clone(), - }); + // The owner records a known exit even when the terminal is `failed` (a + // shell command that ended with a non-zero status, for example), so the + // exit travels with the fields, not with the wait status. + let exit = (reply.exit_code.is_some() || reply.signal.is_some()).then(|| CommandExit { + code: reply.exit_code, + signal: reply.signal.clone(), + }); (settled, exit) } @@ -2219,10 +2221,13 @@ pub(super) fn background_result(task_id: &str, reply: &WaitReply) -> (ExecStatus ), _ if settled.failure.is_some() => { let failure = settled.failure.as_ref().expect("guarded"); - let summary = match failure { - TaskFailure::OutputWriteFailed { message } => { + let summary = match (failure, &exit) { + (TaskFailure::OutputWriteFailed { message }, _) => { format!("exec output offload failed: {message}") } + (TaskFailure::CommandFailed | TaskFailure::UnknownExit, Some(exit)) => { + exit_failure_summary(exit) + } _ => failure.to_string(), }; (ExecStatus::Failed, summary, "failed") diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 9cea6f6616..5159d5872f 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -920,6 +920,73 @@ async fn a_call_after_the_occupying_command_ends_runs() { harness.shutdown().await; } +/// A command that moves to the background keeps the exit status it ended with. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_handed_off_command_keeps_its_exit_code() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "sleep 0.3; sh -c 'exit 7'", "timeoutMs": 100}), + )], + ) + .await; + let events = until(&session, "occupying admission", |events| { + count(events, "exec/started") == 1 && tool_results(events) == 1 + }) + .await; + let task_id = task_of(&results(&events)[0]); + let events = until(&session, "exec ended", |events| ended(events).len() == 1).await; + let (_, end) = &ended(&events)[0]; + assert_eq!(end.task_id, task_id); + assert_eq!(end.status, ExecStatus::Failed); + let exit = end + .result + .structured_content + .as_ref() + .unwrap() + .get("exitCode") + .and_then(Value::as_i64); + assert_eq!(exit, Some(7)); + session.close().await.unwrap(); + harness.shutdown().await; +} + +/// A detached shell job keeps the exit status it ended with. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_detached_job_keeps_its_exit_code() { + let harness = Harness::new(platform(&[]).await).await; + let session = harness.session().await; + harness + .run( + &session, + &[( + "execute", + json!({"command": "sh -c 'exit 7'", "runInBackground": true}), + )], + ) + .await; + let events = until(&session, "exec started", |events| tool_results(events) == 1).await; + let task_id = task_of(&results(&events)[0]); + let events = until(&session, "exec ended", |events| ended(events).len() == 1).await; + let (_, end) = &ended(&events)[0]; + assert_eq!(end.task_id, task_id); + assert_eq!(end.status, ExecStatus::Failed); + let exit = end + .result + .structured_content + .as_ref() + .unwrap() + .get("exitCode") + .and_then(Value::as_i64); + assert_eq!(exit, Some(7)); + session.close().await.unwrap(); + harness.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn stop_background_task() { let harness = Harness::new(platform(&[]).await).await; From 94581256b0506f5c2eb32214ebdf46aedbbcda2f Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 14:25:57 +0800 Subject: [PATCH 14/20] chore(exec): regenerate the service declarations for the stop doc `BackgroundExec::stop`'s doc comment is part of the generated TypeScript declaration; regenerate it after the wording change. Refs #2032 --- npm/branch-services.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 3c4c521e6b..b64d32e3f0 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1164,9 +1164,11 @@ export interface BackgroundExec { */ wait(taskId: string, timeoutMs: number | bigint): Promise /** - * Stops a task: cancels it while running, so it ends `cancelled` and - * does not wake. Returns once its `exec/ended` is dispatched; a task that - * already ended keeps its result and its wake. + * Stops a task and answers the owner's terminal: a native command or a + * background job ends `cancelled` and does not wake, while a shell command + * is interrupted and ends with the interrupted line's own status, so it + * wakes. Returns once its `exec/ended` is dispatched; a task that already + * ended keeps its result and its wake. * @throws {TaskErrorThrown} */ stop(taskId: string): Promise From 2aaff5ee941846cb6ef9ae3d79785efe1a4a3dc9 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 14:47:41 +0800 Subject: [PATCH 15/20] test(exec): assert the exit summary of handed-off commands and jobs The two exit-status tests only asserted `exitCode`, so reverting the summary match in `background_result` kept them green while `exec/ended` said "command failed". They now assert the `summary` field and the result text, and the detached-job case also asserts the stored record `BackgroundExec.stop` answers. Refs #2032 --- tests/integration/tests/minimal_execution.rs | 52 ++++++++++++++------ 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 5159d5872f..15feb4b430 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -943,14 +943,17 @@ async fn a_handed_off_command_keeps_its_exit_code() { let (_, end) = &ended(&events)[0]; assert_eq!(end.task_id, task_id); assert_eq!(end.status, ExecStatus::Failed); - let exit = end - .result - .structured_content - .as_ref() - .unwrap() - .get("exitCode") - .and_then(Value::as_i64); - assert_eq!(exit, Some(7)); + let fields = end.result.structured_content.as_ref().unwrap(); + assert_eq!(fields.get("exitCode").and_then(Value::as_i64), Some(7)); + assert_eq!( + fields.get("summary").and_then(Value::as_str), + Some("Command exited with code 7.") + ); + assert!( + text(&end.result).contains("Command exited with code 7."), + "{}", + text(&end.result) + ); session.close().await.unwrap(); harness.shutdown().await; } @@ -975,14 +978,31 @@ async fn a_detached_job_keeps_its_exit_code() { let (_, end) = &ended(&events)[0]; assert_eq!(end.task_id, task_id); assert_eq!(end.status, ExecStatus::Failed); - let exit = end - .result - .structured_content - .as_ref() - .unwrap() - .get("exitCode") - .and_then(Value::as_i64); - assert_eq!(exit, Some(7)); + let fields = end.result.structured_content.as_ref().unwrap(); + assert_eq!(fields.get("exitCode").and_then(Value::as_i64), Some(7)); + assert_eq!( + fields.get("summary").and_then(Value::as_str), + Some("Command exited with code 7.") + ); + assert!( + text(&end.result).contains("Command exited with code 7."), + "{}", + text(&end.result) + ); + + let stop = session + .service::("main") + .unwrap(); + let stopped = stop.stop(task_id.clone()).await.unwrap(); + let stopped_fields = stopped.result.structured_content.as_ref().unwrap(); + assert_eq!( + stopped_fields.get("exitCode").and_then(Value::as_i64), + Some(7) + ); + assert_eq!( + stopped_fields.get("summary").and_then(Value::as_str), + Some("Command exited with code 7.") + ); session.close().await.unwrap(); harness.shutdown().await; } From 0e9eb102fbe6f112b1d8b5530409915437f3c658 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 15:11:15 +0800 Subject: [PATCH 16/20] fix(exec): let a started init copy finish The retry replaced its only marker pair every second, even after that copy had started, so a copy that completed after the retry interval had its completion discarded and the shell could report a timeout after initializing. A started copy is now left to finish; a new copy is written only while the current one has not started. Each copy keeps its own markers, so an end marker from an earlier copy still cannot complete a later one. Refs #2032 --- .../src/shell_session.rs | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 6cabfd6375..1bef5f6ee7 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -574,8 +574,26 @@ impl ShellSession { let Some(task_id) = task_id else { return Err("shell exited during initialization".into()); }; + let tail = self + .host + .tail(TaskRequest { + task_id: task_id.clone(), + }) + .await; + let (started, complete) = match (¤t, &tail) { + (Some((start_marker, end_marker)), Ok(tail)) => ( + tail.text.contains(start_marker), + init_complete(&tail.text, start_marker, end_marker), + ), + _ => (false, false), + }; + if complete { + return Ok(()); + } let now = tokio::time::Instant::now(); - if now >= write_at { + // A copy that started is left to finish: replacing it would drop a + // completion that arrives after the retry interval. + if now >= write_at && !started { let (start, end) = marker_pair(); let wrapped = match dialect { ShellDialect::Posix => posix_command(command, &start, &end), @@ -587,17 +605,6 @@ impl ShellSession { current = Some((start.full(), end.full())); write_at = now + INIT_RETRY; } - let tail = self - .host - .tail(TaskRequest { - task_id: task_id.clone(), - }) - .await; - if let (Some((start_marker, end_marker)), Ok(tail)) = (¤t, &tail) - && init_complete(&tail.text, start_marker, end_marker) - { - return Ok(()); - } if let Err(_) = &tail && self .host From 929e955907d6e578c50ed0ed73e834f91cddec3b Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 15:53:24 +0800 Subject: [PATCH 17/20] fix(exec): answer a pending stop when release is unconfirmed Per the #2002 owner contract, a job whose release is unconfirmed stays running until the release or the shell sweep writes its terminal, and the stop answers a stop-requested result instead of blocking. - `BackgroundExec.stop` subscribes to a per-task pending flag. The supervisor sets it when `HostPlatform.kill` answers anything but a confirmed kill (`task_running`, a kill failure, an I/O error), and the stop answers `TaskError::Running` at once. A fallback bound keeps the reply bounded even when a confirmed kill's terminal never arrives. - The record stays running and the Session hold and cleanup stay with the supervisor, which keeps waiting; the terminal still comes only from the confirmed release or the shell sweep, so exactly one `exec/ended` follows. - `session.exec.stop` maps the pending stop to the app error `exec_task_running`, and `exec_stop` returns a failed result with code `exec_task_running` and a sentence that says the stop is not confirmed yet. - `HostPlatform.md` states the owner side: a job with no pid answers `task_running` after two seconds and keeps a watcher; a failed kill keeps the watcher; the record stays running until the release or the sweep. Test: `host_platform_flow::a_job_without_a_pid_stays_running_until_the_shell_sweep` (bounded `task_running`, record running, sweep terminal). The normal release is still `cancelled` in `stop_background_task`. Refs #2032 --- .../src/workspace_tools/background.rs | 67 ++++++++-- .../src/workspace_tools/exec.rs | 4 + .../src/workspace_tools/mod.rs | 5 + .../tests/host_platform_flow.rs | 115 ++++++++++++++++++ crates/dim-app-server/src/connection.rs | 5 + .../rust-agent/plugins/HostPlatform.md | 4 +- .../rust-agent/plugins/WorkspaceTools.md | 13 +- npm/branch-services.d.ts | 7 +- 8 files changed, 202 insertions(+), 18 deletions(-) diff --git a/crates/dim-agent-capabilities/src/workspace_tools/background.rs b/crates/dim-agent-capabilities/src/workspace_tools/background.rs index 0c47f1ddf1..8ce67bdc56 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/background.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/background.rs @@ -62,6 +62,10 @@ pub enum TaskError { /// This instance was unloaded. #[error("BackgroundExec is closed")] Closed, + /// The stop is pending: the owner has not confirmed the task's release, so + /// the task is still running and its terminal will follow. + #[error("the task is still running; the stop is pending")] + Running, } /// Why one paged read of a task's registered output file answered nothing. @@ -188,6 +192,11 @@ pub(crate) fn decode_page( }) } +/// How long `stop` waits for a terminal before it answers the pending stop: the +/// owner confirms the release first, and a terminal that cannot be confirmed +/// stays pending instead of blocking the caller. +const STOP_REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + /// How far a page may exceed its budget to hold a whole character: a UTF-8 /// character is at most four bytes, so at most three lie past the limit. pub(crate) const PAGE_CHAR_TRAILING_BYTES: usize = 3; @@ -206,6 +215,8 @@ struct Task { final_preview: Option, /// The dispatched `exec/ended`, once its wake decision is done. ended: watch::Sender>, + /// Set when the owner answered the stop as unconfirmed; the terminal follows. + pending_stop: watch::Sender, } impl Task { fn new( @@ -221,6 +232,7 @@ impl Task { output_path, final_preview: None, ended: watch::Sender::new(None), + pending_stop: watch::Sender::new(false), } } } @@ -246,6 +258,7 @@ async fn wait_owner( platform: &HostPlatform, host_task_id: &str, cancel: &CancellationToken, + pending: Option<&watch::Sender>, ) -> Option { let waited = platform .wait( @@ -259,11 +272,19 @@ async fn wait_owner( match waited { Ok(reply) => Some(reply), Err(HostPlatformError::Cancelled) => { - let _ = platform + let killed = platform .kill(TaskRequest { task_id: host_task_id.to_owned(), }) .await; + match killed { + Ok(()) | Err(HostPlatformError::TaskUnknown | HostPlatformError::TaskEnded) => {} + Err(_) => { + if let Some(pending) = pending { + pending.send_replace(true); + } + } + } platform .wait( WaitRequest { @@ -424,9 +445,10 @@ impl BackgroundExec { let platform = self.platform.clone(); let supervised = task_id.clone(); let parent = dim_agent_runtime::core::current_parent_call_id(); + let pending = self.pending_stop(&supervised); self.tasks.spawn(async move { let run = async { - let reply = wait_owner(&platform, &host_task_id, &cancel).await; + let reply = wait_owner(&platform, &host_task_id, &cancel, pending.as_ref()).await; if let Some(reply) = &reply { let mut state = owner.state.lock().unwrap(); if let Some(task) = state.tasks.get_mut(&supervised) { @@ -667,11 +689,22 @@ impl BackgroundExec { } } + fn pending_stop(&self, task_id: &str) -> Option> { + self.state + .lock() + .unwrap() + .tasks + .get(task_id) + .map(|task| task.pending_stop.clone()) + } + /// Stops a task and answers the owner's terminal: a native command or a /// background job ends `cancelled` and does not wake, while a shell command /// is interrupted and ends with the interrupted line's own status, so it /// wakes. Returns once its `exec/ended` is dispatched; a task that already - /// ended keeps its result and its wake. + /// ended keeps its result and its wake. When the owner has not confirmed the + /// release, answers `running`: the task keeps its record and hold, and its + /// terminal follows. pub async fn stop(&self, task_id: String) -> Result { let current = { let mut state = self.state.lock().unwrap(); @@ -682,10 +715,10 @@ impl BackgroundExec { if task.ended.borrow().is_none() { task.cancel.cancel(); } - task.ended.subscribe() + (task.ended.subscribe(), task.pending_stop.subscribe()) }) }; - let Some(mut ended) = current else { + let Some((mut ended, mut pending)) = current else { if self .started(&task_id, self.timeline.committed()) .await @@ -708,11 +741,25 @@ impl BackgroundExec { )) }); }; - ended - .wait_for(Option::is_some) - .await - .map(|done| done.clone().expect("waited for Some")) - .map_err(|_| TaskError::Closed) + if let Some(done) = ended.borrow().clone() { + return Ok(done); + } + if *pending.borrow() { + return Err(TaskError::Running); + } + let waited = tokio::time::timeout(STOP_REPLY_TIMEOUT, async { + tokio::select! { + result = ended.wait_for(Option::is_some) => result + .map(|done| done.clone().expect("waited for Some")) + .map_err(|_| TaskError::Closed), + _ = pending.wait_for(|pending| *pending) => Err(TaskError::Running), + } + }) + .await; + match waited { + Ok(result) => result, + Err(_) => Err(TaskError::Running), + } } fn consume( diff --git a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs index 55ddd86740..71e7e7aee0 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/exec.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/exec.rs @@ -135,6 +135,10 @@ pub(super) async fn stop( Err(super::background::TaskError::Closed) => Err(HostError::Cancelled( dim_agent_runtime::CAPABILITY_RELOADING.into(), )), + Err(super::background::TaskError::Running) => Ok(failed( + "The stop was requested; the command is still running because the owner has not confirmed its release. It is not stopped yet, and its result will follow.", + "exec_task_running", + )), } } diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index a0ac1fe108..00fae5e484 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -575,6 +575,11 @@ impl DynPlugin for WorkspaceToolsPlugin { ), background::TaskError::Closed => RpcError::reloading(), background::TaskError::Read(error) => error.into(), + background::TaskError::Running => RpcError::app( + -32000, + "exec_task_running", + "The task is still running", + ), })?; Ok(serde_json::json!({"text":text})) }) diff --git a/crates/dim-agent-capabilities/tests/host_platform_flow.rs b/crates/dim-agent-capabilities/tests/host_platform_flow.rs index cc2af05114..76408232c5 100644 --- a/crates/dim-agent-capabilities/tests/host_platform_flow.rs +++ b/crates/dim-agent-capabilities/tests/host_platform_flow.rs @@ -2384,3 +2384,118 @@ async fn a_job_write_terminalizes_and_reads_its_output() { .unwrap(); std::fs::remove_dir_all(dir).unwrap(); } + +/// A job whose pid never arrives answers a bounded `task_running` and keeps its +/// record running; the shell's sweep writes its terminal. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_job_without_a_pid_stays_running_until_the_shell_sweep() { + let dir = std::env::temp_dir().join(unique("dim-host-job-pid")); + std::fs::create_dir_all(&dir).unwrap(); + let root = rutis::Ctx::root_with(tokio::runtime::Handle::current()); + let catalog = dim_agent_capabilities::catalog(); + let build = Default::default(); + let names = dim_agent_runtime::Names::copy(&catalog, &build); + let _execution = root + .provide(ExecutionSettingsHost::fixed(Default::default())) + .unwrap(); + let _toolchain = root.provide(ToolchainSourceHost::fixed(vec![])).unwrap(); + let plugin = root.plugin( + HostPlatformPlugin::new( + &names, + HostPlatformConfig { + execution: names.key().unwrap(), + toolchain: names.key().unwrap(), + exec_shell_file: None, + home: Some(dir.clone()), + }, + ) + .unwrap(), + ); + (&plugin).await.unwrap(); + let platform = root.get::().unwrap(); + platform + .shell(ShellRequest { + task_id: "pid-shell".into(), + cwd: path_string(&dir), + workspace: path_string(&dir), + roots: Vec::new(), + output_dir: path_string(&dir), + cols: 80, + rows: 24, + }) + .await + .unwrap(); + let output_path = dir.join("job-1.log"); + platform + .write(ShellWrite { + task_id: "pid-shell".into(), + data: base64::engine::general_purpose::STANDARD.encode(b"sleep 30\n"), + command: None, + job: Some(ShellJobStart { + task_id: "job-1".into(), + end_marker: "__DIM_END_aaaabbbb_ccccdddd__".into(), + output_path: output_path.to_string_lossy().into_owned(), + }), + }) + .await + .unwrap(); + + let started = std::time::Instant::now(); + let killed = platform + .kill(TaskRequest { + task_id: "job-1".into(), + }) + .await; + assert!( + matches!(killed, Err(HostPlatformError::TaskRunning)), + "{killed:?}" + ); + assert!( + started.elapsed() >= std::time::Duration::from_millis(1_800), + "the stop must be bounded by the pid wait: {:?}", + started.elapsed() + ); + let reply = platform + .wait( + WaitRequest { + task_id: "job-1".into(), + timeout_ms: Some(0), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(reply.status, WaitStatus::Running, "{reply:?}"); + + platform + .kill(TaskRequest { + task_id: "pid-shell".into(), + }) + .await + .unwrap(); + let reply = platform + .wait( + WaitRequest { + task_id: "job-1".into(), + timeout_ms: Some(5_000), + }, + never_cancelled(), + ) + .await + .unwrap(); + assert_eq!(reply.status, WaitStatus::Failed, "{reply:?}"); + assert!( + matches!( + reply.failure, + Some(TaskFailure::ShellExited | TaskFailure::ShellReset) + ), + "{reply:?}" + ); + platform + .settle(TaskRequest { + task_id: "pid-shell".into(), + }) + .await + .unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/dim-app-server/src/connection.rs b/crates/dim-app-server/src/connection.rs index 04b851ad3d..f9c7a5dea6 100644 --- a/crates/dim-app-server/src/connection.rs +++ b/crates/dim-app-server/src/connection.rs @@ -1642,6 +1642,11 @@ impl Connection { TaskError::Read(_) => { RpcError::app(-32603, "exec_task_read", "Task facts could not be read") } + TaskError::Running => RpcError::app( + -32000, + "exec_task_running", + "The stop was requested; the command is still running and its release is not confirmed", + ), })?; Reply::ExecEnded(result) } diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 528cbbf545..281284ca1d 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -26,7 +26,9 @@ A task id is reserved by the owner before a command or background job starts. `s part of `shell.write` answer `task_exists` for an id already in the table or an existing output log, and `invalid` for a missing output parent or an output path outside the shell directory. `wait` reports the terminal record and never removes it; a timeout stops the wait and answers `running`. `settle` releases only an ended task or an exited -shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command's terminal is the interrupted line's own exit status — which can be success when the line continues past the interrupted command — and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Terminating a shell — this stop, a shell kill or a Session close — releases that foreground group the same way before the shell's terminal sweeps its children. Command and job logs stay under the output directory the caller gives the owner; the +shell and answers `task_running` otherwise; `kill` is the explicit stop, and a second kill while a job's stop is pending answers `task_running`. A job with no pid answers `task_running` after two seconds and keeps a pid watcher, and a +kill that fails keeps the watcher too: the job record stays running, and its terminal comes from +the confirmed release or from the shell's sweep. For a shell command, `kill` writes Ctrl+C and waits for the command's terminal. Some shells print the end marker after the interrupt, so the command's terminal is the interrupted line's own exit status — which can be success when the line continues past the interrupted command — and `kill` returns from that wait; a command still running after two seconds cannot end inside the live shell, so `kill` signals the terminal's foreground process group — where an interactive shell runs the command, outside the shell's own group — and terminates the shell, whose terminal sweeps the command as a reset. Terminating a shell — this stop, a shell kill or a Session close — releases that foreground group the same way before the shell's terminal sweeps its children. Command and job logs stay under the output directory the caller gives the owner; the persistent shell defaults to `execRoot`. Logs are registered by the branch when the model is given their path. `removeOutputDirectory` accepts only a persistent-shell output directory below the canonical diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index 5dab2c6c41..cec34a8250 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -142,8 +142,10 @@ App Server calls the branch's `BackgroundExec` in every profile; the operation m `unknown`/`closed`/`read` to the same RPC errors. It waits for cleanup and returns the committed terminal `{task_id, status, result}` in the model-readable content. An already-ended task keeps its result. Only `cancelled` confirms cancellation; `failed` remains an error, -including when the process tree could not be released. An unknown task fails -without stopping any command. Detached exec results name this operation and +including when the process tree could not be released. When the owner has not +confirmed the release, the operation answers `running` — an explicit pending stop: +the task stays running, keeps its cleanup and Session hold, and its terminal +follows. An unknown task fails without stopping any command. Detached exec results name this operation and distinguish their Task ID from Collaboration's Agent and Session identities. ```text @@ -519,7 +521,7 @@ stopped." The other tools' refusal codes (`invalid_input`, `not_regular_file`, `is_directory`, `file_modified_since_read`, `text_binding_required`, `permission_denied`, `write_error`, `exec_invalid_request`, -`exec_task_unknown`, `exec_terminate_failed`, `exec_wait_failed`, +`exec_task_unknown`, `exec_task_running`, `exec_terminate_failed`, `exec_wait_failed`, `exec_output_offload_failed`) reach clients and persistence in `structuredContent`; `ToolResult.content` carries the sentence the model reads, and HistoryRenderer renders the content alone, so no code reaches the model. A @@ -673,8 +675,9 @@ clamps to 4 MiB, `bytes` is what the page consumed, and the next cursor is `cursor + bytes`; `nextCursor` is present only for a full page. `wait` answers an ended task at once and otherwise waits for its dispatch until `timeoutMs` elapses. For a running task, `timeoutMs = 0` answers `timeout`. `stop` is kill: it stops -a running task and answers the owner's terminal, and an already ended task keeps -its record and wake. The terminal decides the wake: `cancelled` stays silent and +a running task and answers the owner's terminal, or `running` when the owner has +not confirmed the release (the task keeps its record and cleanup, and the terminal +follows); an already ended task keeps its record and wake. The terminal decides the wake: `cancelled` stays silent and every other status posts the completion notice. A command that started as a native process and a persistent shell's background job both end `cancelled`, so neither wakes. A shell command is interrupted in its persistent shell; its diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index b64d32e3f0..e03ce36b8c 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1092,6 +1092,7 @@ export type TaskError = | /** Required task facts could not be read. */ { read: [] } | /** No matching task or live output on this branch. */ "unknown" | /** This instance was unloaded. */ "closed" + | /** The stop is pending: the owner has not confirmed the task's release, so the task is still running and its terminal will follow. */ "running" /** * One page of a task's registered output file, as @@ -1168,7 +1169,9 @@ export interface BackgroundExec { * background job ends `cancelled` and does not wake, while a shell command * is interrupted and ends with the interrupted line's own status, so it * wakes. Returns once its `exec/ended` is dispatched; a task that already - * ended keeps its result and its wake. + * ended keeps its result and its wake. When the owner has not confirmed the + * release, answers `running`: the task keeps its record and hold, and its + * terminal follows. * @throws {TaskErrorThrown} */ stop(taskId: string): Promise @@ -1827,7 +1830,7 @@ export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Crea export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "no_session" | "session_closing" | "session_reloading" | "session_unavailable" | "no_line" | "not_data_face" | "method_not_routable" | "wrong_scope" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> /** What a method returning `Err(TaskError)` throws. */ -export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> +export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed" | "running", TaskError> /** What a method returning `Err(WaitCallError)` throws. */ export type WaitCallErrorThrown = RustError<"WaitCallError", "AlreadyWaiting" | "Reloading", undefined> From 8ad765b25870b1a6df2ab575e7ec623948cf41fa Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 16:29:36 +0800 Subject: [PATCH 18/20] fix(exec): watch every written init copy The retry only checked its newest marker pair, so a copy still executing when the next one was written could never complete the initialization: a shell slower than the retry interval (a `preexec` that sleeps, for example) printed every copy's end marker within the deadline and was still reported as uninitialized. Every written copy keeps its markers until the deadline and any copy whose own start marker precedes its own end marker completes the initialization. A copy that started is still not replaced, so copies no longer queue behind each other once the shell runs one. Test: `a_slow_shell_still_initializes` (zsh `preexec` sleeping 1.5 s); it fails on the previous loop with `shell did not initialize`. Refs #2032 --- .../src/shell_session.rs | 33 +++++++++---------- .../rust-agent/plugins/HostPlatform.md | 10 +++--- tests/integration/tests/minimal_execution.rs | 24 ++++++++++++++ 3 files changed, 46 insertions(+), 21 deletions(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 1bef5f6ee7..8060a271d7 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -554,10 +554,10 @@ impl ShellSession { /// /// A shell can spend its first input on a startup consumer — zsh's newuser /// wizard, for example — instead of the shell prompt, so the wrapper is - /// written again until one copy runs. Each copy carries its own markers, so - /// an end marker a consumer printed for an earlier copy cannot complete a - /// later one, and the typed line carries the fragments separately, so its - /// echo cannot satisfy the check. + /// written again until one copy runs. Each copy carries its own markers, and + /// every copy is watched until the deadline, so an end marker from another + /// copy cannot complete one and a slow copy still counts; the typed line + /// carries the fragments separately, so its echo cannot satisfy the check. async fn send_initial(self: &Arc, command: &str) -> Result<(), String> { let dialect = { let inner = self.inner.lock().await; @@ -565,7 +565,9 @@ impl ShellSession { }; let deadline = tokio::time::Instant::now() + INIT_TIMEOUT; let mut write_at = tokio::time::Instant::now(); - let mut current: Option<(String, String)> = None; + // Every written copy keeps its markers until the deadline: a copy + // slower than the retry interval still completes the initialization. + let mut copies: Vec<(String, String)> = Vec::new(); loop { let task_id = { let inner = self.inner.lock().await; @@ -580,19 +582,16 @@ impl ShellSession { task_id: task_id.clone(), }) .await; - let (started, complete) = match (¤t, &tail) { - (Some((start_marker, end_marker)), Ok(tail)) => ( - tail.text.contains(start_marker), - init_complete(&tail.text, start_marker, end_marker), - ), - _ => (false, false), - }; - if complete { - return Ok(()); + if let Ok(tail) = &tail { + for (start_marker, end_marker) in &copies { + if init_complete(&tail.text, start_marker, end_marker) { + return Ok(()); + } + } } + let started = matches!(&tail, Ok(tail) if copies.iter().any(|(start, _)| tail.text.contains(start))); let now = tokio::time::Instant::now(); - // A copy that started is left to finish: replacing it would drop a - // completion that arrives after the retry interval. + // A started copy is left to finish: another would only queue behind it. if now >= write_at && !started { let (start, end) = marker_pair(); let wrapped = match dialect { @@ -602,7 +601,7 @@ impl ShellSession { self.write_shell(format!("{wrapped}\n").as_bytes()) .await .map_err(|error| error.to_string())?; - current = Some((start.full(), end.full())); + copies.push((start.full(), end.full())); write_at = now + INIT_RETRY; } if let Err(_) = &tail diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index 281284ca1d..50a32f76c3 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -171,10 +171,12 @@ A running shell keeps the boundary it started with; changing the switches applie process. macOS permits only the needed terminal ioctl commands. A persistent shell's first command is the init wrapper, and the shell may spend its first input on a startup consumer instead — zsh's newuser module runs a wizard when the user has no -startup files. `ShellSession` writes that wrapper again until one copy's start marker and then -its end marker reached the shell's tail, so no startup consumer can lose the initialization. -Each copy carries its own marker pair, and a copy counts only when its own start marker precedes -its end marker: an end marker a consumer emitted for an earlier copy or by itself does not count. +startup files. `ShellSession` writes that wrapper again until a copy's own start marker and then +its end marker reached the shell's tail, and it watches every written copy until the init +deadline, so neither a startup consumer nor a shell slower than the retry interval can lose the +initialization. Each copy carries its own marker pair, and a copy counts only when its own start +marker precedes its end marker: an end marker a consumer emitted for another copy or by itself +does not count. A copy that started is not replaced, because another would only queue behind it. The wrapper uses the same marker fragments as every command, so its echoed text cannot pass for the marker. diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index 15feb4b430..83b6571a8c 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -1134,6 +1134,30 @@ async fn stopping_a_command_that_ignores_the_interrupt_leaves_no_process() { harness.shutdown().await; } +/// A shell slower than the init retry still initializes: every written copy is +/// watched until the deadline, not only the newest. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_slow_shell_still_initializes() { + let Some(platform) = zsh_platform() else { + return; + }; + let harness = Harness::new(platform).await; + std::fs::write(harness.cwd.join(".zshrc"), "preexec() { sleep 1.5; }\n").unwrap(); + let session = harness.session().await; + harness + .run( + &session, + &[("execute", json!({"command": "printf 'ready'"}))], + ) + .await; + let events = until(&session, "result", |events| tool_results(events) == 1).await; + let call_results = results(&events); + let result = text(&call_results[0]); + assert!(result.contains("ready"), "{result}"); + session.close().await.unwrap(); + harness.shutdown().await; +} + /// Closing a Session releases the command its shell is running, not only /// stopping a task. macOS has no `/proc` tree to walk, so the shell's /// termination signals the terminal's foreground process group. From 50d24c236a4b18fe5cc33c11c85884dd43f8ab21 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 16:39:17 +0800 Subject: [PATCH 19/20] style(exec): fit the init started check on one line Refs #2032 --- crates/dim-agent-capabilities/src/shell_session.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/src/shell_session.rs b/crates/dim-agent-capabilities/src/shell_session.rs index 8060a271d7..b4823a38a2 100644 --- a/crates/dim-agent-capabilities/src/shell_session.rs +++ b/crates/dim-agent-capabilities/src/shell_session.rs @@ -589,7 +589,10 @@ impl ShellSession { } } } - let started = matches!(&tail, Ok(tail) if copies.iter().any(|(start, _)| tail.text.contains(start))); + let started = match &tail { + Ok(tail) => copies.iter().any(|(start, _)| tail.text.contains(start)), + Err(_) => false, + }; let now = tokio::time::Instant::now(); // A started copy is left to finish: another would only queue behind it. if now >= write_at && !started { From 4037ca7598418c9ae578ed8d3c83e504938bd7e4 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 20:00:16 +0800 Subject: [PATCH 20/20] chore(exec): drop the service_opt access-layer entry Base-1 (#2174) landed `xtask/access-layer.json`, and this branch removes `Session::service_opt`; the listed entry no longer has a definition, so `xtask-check` would report it as listed one and found none. Refs #2032 --- xtask/access-layer.json | 5 ----- 1 file changed, 5 deletions(-) diff --git a/xtask/access-layer.json b/xtask/access-layer.json index c397d34865..0e1879d54e 100644 --- a/xtask/access-layer.json +++ b/xtask/access-layer.json @@ -520,11 +520,6 @@ "file": "crates/dim-agent-runtime/src/agent.rs", "item": "Session::service" }, - { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::service_opt" - }, { "kind": "session-forwarding", "file": "crates/dim-agent-runtime/src/agent.rs",