diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index bf370a7f4f..c1e3e46c8d 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -211,17 +211,18 @@ Narrower local guides already exist for some subtrees: ## Verification -For WriteStdin steering, port routing, streaming and legacy result compatibility: +For ExecCommand/WriteStdin steering, port routing, streaming and legacy result compatibility: ```bash -cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib agentic::tools::implementations::exec_command::stdin:: +cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib agentic::tools::implementations::exec_command:: cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib yieldable_tools_end_normally_for_every_non_none_round_injection_policy ``` -WriteStdin uses the same round-injection yield token as AgentWait. Only the -output wait ends; submitted stdin is not replayed and process control remains -explicit. The optional `wait_end_reason: "steered"` result is separate from -process `completion`; old results without it keep their existing meaning. +ExecCommand and WriteStdin use the same round-injection yield token as AgentWait. +Only the output wait ends; the launched command and submitted stdin are not +replayed, and process control remains explicit. Continue with the returned +session ID through WriteStdin. The optional `wait_end_reason: "steered"` result +is separate from process `completion`; old results without it keep their existing meaning. These Core fixtures cover both runtime ports with mocks, not live remote hosts. For desktop card admission, per-turn Peer origin, recovery context and subagent diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command.rs b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command.rs index 728b14a41a..a1aea9c8c2 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command.rs @@ -586,6 +586,7 @@ impl ExecCommandTool { tty, yield_time_ms: Some(yield_time_ms), max_output_chars: None, + wait_interrupt: context.round_injection_preemption_token().cloned(), lifecycle_sink: Self::start_remote_lifecycle_bridge(context, self.name()), output_sink: output_capture_tx, }; @@ -632,7 +633,7 @@ impl ExecCommandTool { } } - let data = exec_command_result_value(ExecCommandResultData { + let mut data = exec_command_result_value(ExecCommandResultData { fields: ExecCommandResultFields { chunk_id: response.chunk_id, wall_time_seconds: response.wall_time_seconds, @@ -647,6 +648,9 @@ impl ExecCommandTool { tty, shell: Self::remote_shell_metadata(&workdir, &shell, env_snapshot.is_some()), }); + if response.wait_interrupted { + data["wait_end_reason"] = json!("steered"); + } let result_for_assistant = Self::response_for_assistant(&data); Ok(vec![ToolResult::Result { @@ -687,6 +691,7 @@ TTY modes: Waiting and continuation: - yield_time_ms waits for output until the process exits or the deadline is reached. It does not stop the process. +- User steering can end the wait early and return output collected so far. The process continues running; use the returned session_id with WriteStdin instead of launching the command again. - If the process is still running after `yield_time_ms`, the result includes a numeric session_id. - Use WriteStdin to poll for more output or send input to tty=true sessions, and ExecControl to interrupt or kill it. @@ -742,6 +747,7 @@ Output: "output": {"type": "string"}, "session_id": {"anyOf": [{"type": "integer"}, {"type": "null"}]}, "exit_code": {"anyOf": [{"type": "integer"}, {"type": "null"}]}, + "wait_end_reason": {"type": "string", "enum": ["steered"]}, "completion": { "anyOf": [ {"type": "null"}, @@ -781,6 +787,10 @@ Output: true } + fn round_injection_yieldable(&self) -> bool { + true + } + async fn validate_input( &self, input: &Value, @@ -887,6 +897,7 @@ Output: tty, yield_time_ms: Some(yield_time_ms), max_output_chars: None, + wait_interrupt: context.round_injection_preemption_token().cloned(), lifecycle_sink: Self::start_local_lifecycle_bridge(context, self.name()), output_sink: output_capture_tx, }; @@ -933,7 +944,7 @@ Output: } } - let data = exec_command_result_value(ExecCommandResultData { + let mut data = exec_command_result_value(ExecCommandResultData { fields: ExecCommandResultFields { chunk_id: response.chunk_id, wall_time_seconds: response.wall_time_seconds, @@ -948,6 +959,9 @@ Output: tty, shell: Self::shell_metadata_value(&shell), }); + if response.wait_interrupted { + data["wait_end_reason"] = json!("steered"); + } let result_for_assistant = Self::response_for_assistant(&data); Ok(vec![ToolResult::Result { @@ -1083,7 +1097,7 @@ mod tests { assert!(tool.prepared_shells.lock().await.is_empty()); } - fn local_tool_context(workspace: &Path) -> ToolUseContext { + pub(super) fn local_tool_context(workspace: &Path) -> ToolUseContext { ToolUseContext { tool_call_id: None, agent_type: Some("Standard".to_string()), @@ -1100,7 +1114,7 @@ mod tests { } } - fn remote_tool_context(root: &str) -> ToolUseContext { + pub(super) fn remote_tool_context(root: &str) -> ToolUseContext { let session_identity = workspace_session_identity(root, Some("conn-1"), Some("remote-host")) .expect("remote session identity should build"); @@ -1468,3 +1482,7 @@ mod tests { #[cfg(all(test, unix))] #[path = "guard_tests.rs"] mod guard_tests; + +#[cfg(test)] +#[path = "command_steering_tests.rs"] +mod steering_tests; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command_steering_tests.rs b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command_steering_tests.rs new file mode 100644 index 0000000000..d7e95eec54 --- /dev/null +++ b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command_steering_tests.rs @@ -0,0 +1,265 @@ +use super::tests::{local_tool_context, remote_tool_context}; +use super::*; +use crate::agentic::tools::framework::ToolResult; +use openbitfun_runtime_ports::*; +use std::sync::atomic::{AtomicUsize, Ordering}; +use tokio_util::sync::CancellationToken; + +#[derive(Debug)] +struct ExecProbe { + streaming: bool, + calls: AtomicUsize, +} + +impl RuntimeServicePort for ExecProbe { + fn capability(&self) -> RuntimeServiceCapability { + RuntimeServiceCapability::Terminal + } +} + +#[async_trait::async_trait] +impl TerminalPort for ExecProbe { + async fn exec_command( + &self, + request: TerminalExecCommandRequest, + ) -> PortResult { + assert_eq!(self.streaming, false); + assert!(request.tty); + assert_eq!(request.yield_time_ms, Some(600_000)); + self.calls.fetch_add(1, Ordering::SeqCst); + assert!(request.argv.last().unwrap().contains("echo steering-probe")); + Ok(TerminalExecCommandResponse { + chunk_id: "chunk".into(), + wall_time_seconds: 0.01, + output: "partial".into(), + session_id: Some(42), + exit_code: None, + original_output_chars: 7, + completion: None, + wait_interrupted: request + .wait_interrupt + .as_ref() + .is_some_and(CancellationToken::is_cancelled), + }) + } + async fn exec_command_streaming( + &self, + request: TerminalExecCommandRequest, + sink: TerminalExecStreamingOutputSink, + ) -> PortResult { + assert_eq!(self.streaming, true); + assert!(request.tty); + assert_eq!(request.yield_time_ms, Some(600_000)); + self.calls.fetch_add(1, Ordering::SeqCst); + assert!(request.argv.last().unwrap().contains("echo steering-probe")); + sink.send("partial".into()).await.unwrap(); + Ok(TerminalExecCommandResponse { + chunk_id: "chunk".into(), + wall_time_seconds: 0.01, + output: "partial".into(), + session_id: Some(42), + exit_code: None, + original_output_chars: 7, + completion: None, + wait_interrupted: request + .wait_interrupt + .as_ref() + .is_some_and(CancellationToken::is_cancelled), + }) + } + async fn write_stdin( + &self, + _: TerminalWriteStdinRequest, + ) -> PortResult { + panic!("initial wait must not replay input or control the process") + } + async fn write_stdin_streaming( + &self, + _: TerminalWriteStdinRequest, + _: TerminalExecStreamingOutputSink, + ) -> PortResult { + panic!("initial wait must not replay input or control the process") + } + async fn send_stdin(&self, _: TerminalSendStdinRequest) -> PortResult<()> { + panic!("initial wait must not replay input or control the process") + } + async fn control_session( + &self, + _: TerminalExecControlRequest, + ) -> PortResult { + panic!("initial wait must not replay input or control the process") + } +} + +#[async_trait::async_trait] +impl RemoteExecPort for ExecProbe { + async fn exec_command_once( + &self, + _: RemoteExecOneShotCommandRequest, + ) -> PortResult { + Ok(RemoteExecOneShotCommandResponse { + stdout: "/bin/sh\n".into(), + stderr: String::new(), + exit_code: 0, + interrupted: false, + timed_out: false, + }) + } + async fn exec_command( + &self, + request: RemoteExecCommandRequest, + ) -> PortResult { + if request.max_output_chars.is_some() { + // Environment capture is a separate best-effort setup command. + assert!(request.wait_interrupt.is_none()); + return Err(PortError::new( + PortErrorKind::NotAvailable, + "no environment snapshot", + )); + } + assert_eq!(self.streaming, false); + assert!(request.tty); + assert_eq!(request.yield_time_ms, Some(600_000)); + self.calls.fetch_add(1, Ordering::SeqCst); + assert!(request.command.contains("echo steering-probe")); + Ok(RemoteExecCommandResponse { + chunk_id: "chunk".into(), + wall_time_seconds: 0.01, + output: "partial".into(), + session_id: Some(42), + exit_code: None, + original_output_chars: 7, + completion: None, + wait_interrupted: request + .wait_interrupt + .as_ref() + .is_some_and(CancellationToken::is_cancelled), + }) + } + async fn exec_command_streaming( + &self, + request: RemoteExecCommandRequest, + sink: RemoteExecStreamingOutputSink, + ) -> PortResult { + assert_eq!(self.streaming, true); + assert!(request.tty); + assert_eq!(request.yield_time_ms, Some(600_000)); + self.calls.fetch_add(1, Ordering::SeqCst); + assert!(request.command.contains("echo steering-probe")); + sink.send("partial".into()).await.unwrap(); + Ok(RemoteExecCommandResponse { + chunk_id: "chunk".into(), + wall_time_seconds: 0.01, + output: "partial".into(), + session_id: Some(42), + exit_code: None, + original_output_chars: 7, + completion: None, + wait_interrupted: request + .wait_interrupt + .as_ref() + .is_some_and(CancellationToken::is_cancelled), + }) + } + async fn write_stdin( + &self, + _: RemoteWriteStdinRequest, + ) -> PortResult { + panic!("initial wait must not replay input or control the process") + } + async fn write_stdin_streaming( + &self, + _: RemoteWriteStdinRequest, + _: RemoteExecStreamingOutputSink, + ) -> PortResult { + panic!("initial wait must not replay input or control the process") + } + async fn send_stdin(&self, _: RemoteSendStdinRequest) -> PortResult<()> { + panic!("initial wait must not replay input or control the process") + } + async fn control_session( + &self, + _: RemoteExecControlRequest, + ) -> PortResult { + panic!("initial wait must not replay input or control the process") + } +} + +#[test] +fn exec_command_owns_timeout_and_yields_to_round_injection() { + let tool = ExecCommandTool::new(); + assert!(tool.manages_own_execution_timeout()); + assert!(tool.round_injection_yieldable()); + assert!(tool.is_concurrency_safe(None)); + assert!(tool.output_schema()["properties"] + .get("wait_end_reason") + .is_some()); + assert!(!tool.output_schema()["required"] + .as_array() + .unwrap() + .contains(&json!("wait_end_reason"))); +} + +#[tokio::test] +async fn exec_command_steering_reaches_both_ports_and_preserves_legacy_results() { + let workspace = tempfile::tempdir().unwrap(); + for remote in [false, true] { + for streaming in [false, true] { + for steered in [false, true] { + let mut context = if remote { + remote_tool_context("/home/me/project") + } else { + local_tool_context(workspace.path()) + }; + context.tool_call_id = + streaming.then(|| format!("exec-steering-{remote}-{steered}")); + let probe = Arc::new(ExecProbe { + streaming, + calls: AtomicUsize::new(0), + }); + let token = CancellationToken::new(); + token.cancel(); + context.runtime_handles = context + .runtime_handles + .with_round_injection_preemption_token(steered.then_some(token)) + .with_terminal_port(Some(probe.clone())) + .with_remote_exec_port(Some(probe.clone())); + let tool = ExecCommandTool::new(); + let results = tool + .call_impl( + &json!({ + "cmd":"echo steering-probe", "tty":true, "yield_time_ms":600_000, + }), + &context, + ) + .await + .unwrap(); + assert_eq!(probe.calls.load(Ordering::SeqCst), 1); + let ToolResult::Result { + data, + result_for_assistant, + .. + } = &results[0] + else { + panic!("steering must return a normal result"); + }; + assert_eq!(data["output"], "partial"); + assert_eq!(data["session_id"], 42); + assert!(data["exit_code"].is_null()); + assert!(data["completion"].is_null()); + let assistant = result_for_assistant.as_deref().unwrap(); + if steered { + assert_eq!(data["wait_end_reason"], "steered"); + assert!(assistant.contains("user steering arrived")); + assert!(assistant.contains("do not launch the command again")); + } else { + assert!(data.get("wait_end_reason").is_none()); + assert!(!assistant.contains("user steering arrived")); + } + let restored: serde_json::Value = + serde_json::from_str(&serde_json::to_string(data).unwrap()).unwrap(); + assert_eq!(&restored, data); + } + } + } +} diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/env_snapshot.rs b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/env_snapshot.rs index a3c33b2f4c..c4fee15ebc 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/env_snapshot.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/env_snapshot.rs @@ -59,6 +59,7 @@ async fn capture_remote_env_snapshot( tty: true, yield_time_ms: Some(policy.timeout_ms), max_output_chars: Some(policy.max_output_chars), + wait_interrupt: None, lifecycle_sink: None, output_sink: None, }) diff --git a/src/crates/assembly/core/src/external_sources.rs b/src/crates/assembly/core/src/external_sources.rs index bda7e6d06b..d429e99ae8 100644 --- a/src/crates/assembly/core/src/external_sources.rs +++ b/src/crates/assembly/core/src/external_sources.rs @@ -510,6 +510,7 @@ async fn execute_prompt_command_shell_plan( tty: false, yield_time_ms: Some(PROMPT_COMMAND_SHELL_TIMEOUT_MS), max_output_chars: Some(MAX_PROMPT_COMMAND_SHELL_OUTPUT_CHARS), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) diff --git a/src/crates/contracts/runtime-ports/AGENTS.md b/src/crates/contracts/runtime-ports/AGENTS.md index bd64039a55..3cdbe41a6a 100644 --- a/src/crates/contracts/runtime-ports/AGENTS.md +++ b/src/crates/contracts/runtime-ports/AGENTS.md @@ -45,8 +45,8 @@ facts. It is an interface crate, not a runtime implementation crate. concrete behavior, product policy, permission decisions, audit outcomes, UI extension behavior, UI implementation, or UI command logic here. - Preserve serialization compatibility for persisted or cross-process DTOs. -- Terminal/remote stdin requests carry an optional in-process output-wait - interrupt token (`tokio-util`, selected by those two port features). It must +- Terminal/remote command and stdin requests carry an optional in-process + output-wait interrupt token (`tokio-util`, selected by those two port features). It must not cancel the process or cross a wire/persistence boundary. Responses acknowledge wait interruption independently from process completion. - Keep `default = []`. Select `agent-api`, `workspace-ports`, diff --git a/src/crates/contracts/runtime-ports/src/remote_exec_port.rs b/src/crates/contracts/runtime-ports/src/remote_exec_port.rs index 39f43ff118..994f96b980 100644 --- a/src/crates/contracts/runtime-ports/src/remote_exec_port.rs +++ b/src/crates/contracts/runtime-ports/src/remote_exec_port.rs @@ -8,6 +8,8 @@ pub struct RemoteExecCommandRequest { pub tty: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only the initial output wait; the launched process remains active. + pub wait_interrupt: Option, pub lifecycle_sink: Option, pub output_sink: Option, } diff --git a/src/crates/contracts/runtime-ports/src/terminal_port.rs b/src/crates/contracts/runtime-ports/src/terminal_port.rs index fbfa68eb56..6dd0477fe0 100644 --- a/src/crates/contracts/runtime-ports/src/terminal_port.rs +++ b/src/crates/contracts/runtime-ports/src/terminal_port.rs @@ -11,6 +11,8 @@ pub struct TerminalExecCommandRequest { pub tty: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only the initial output wait; the launched process remains active. + pub wait_interrupt: Option, pub lifecycle_sink: Option, pub output_sink: Option, } diff --git a/src/crates/execution/tool-execution/src/exec_command.rs b/src/crates/execution/tool-execution/src/exec_command.rs index a16b2c5cbe..51861a2202 100644 --- a/src/crates/execution/tool-execution/src/exec_command.rs +++ b/src/crates/execution/tool-execution/src/exec_command.rs @@ -843,6 +843,13 @@ pub fn render_exec_command_response_for_assistant(data: &Value) -> String { let status_lines = completion_status_lines(data); let mut note_lines = Vec::new(); + if data.get("wait_end_reason").and_then(Value::as_str) == Some("steered") { + note_lines.push( + "ExecCommand ended its wait early because user steering arrived. The process continues running. Handle the new user message before polling with WriteStdin; do not launch the command again." + .to_string(), + ); + } + if data.get("tty").and_then(Value::as_bool) == Some(false) && data .get("output") @@ -1088,6 +1095,23 @@ mod tests { ); } + #[test] + fn exec_command_legacy_and_steered_payloads_keep_process_status_separate() { + let legacy = r#"{"wall_time_seconds":0.25,"output":"partial","session_id":7,"exit_code":null,"completion":null,"tty":false}"#; + let mut data: Value = serde_json::from_str(legacy).unwrap(); + assert!(!render_exec_command_response_for_assistant(&data).contains("")); + let round_trip: Value = + serde_json::from_str(&serde_json::to_string(&data).unwrap()).unwrap(); + assert_eq!(round_trip, data); + data["wait_end_reason"] = json!("steered"); + let rendered = render_exec_command_response_for_assistant(&data); + assert!(rendered.contains("Process is still running. session_id: 7")); + assert!(rendered.contains("user steering arrived")); + assert!(rendered.contains("do not launch the command again")); + assert!(rendered.contains("\npartial\n")); + assert!(!rendered.contains("Process was interrupted externally")); + } + #[test] fn write_stdin_legacy_and_steered_payloads_keep_process_status_separate() { let legacy = r#"{"wall_time_seconds":0.25,"output":"partial","session_id":7,"exit_code":null,"completion":null}"#; diff --git a/src/crates/services/services-integrations/src/remote_ssh/disabled.rs b/src/crates/services/services-integrations/src/remote_ssh/disabled.rs index 82cc84a07c..b9cc23cb76 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/disabled.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/disabled.rs @@ -107,6 +107,8 @@ pub struct RemoteExecCommandRequest { pub tty: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only the initial output wait; the launched process remains active. + pub wait_interrupt: Option, pub lifecycle_tx: Option>, pub output_capture_tx: Option>, } diff --git a/src/crates/services/services-integrations/src/remote_ssh/remote_exec.rs b/src/crates/services/services-integrations/src/remote_ssh/remote_exec.rs index 9e20c48fcb..5b12647f4b 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/remote_exec.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/remote_exec.rs @@ -43,6 +43,8 @@ pub struct RemoteExecCommandRequest { pub tty: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only the initial output wait; the launched process remains active. + pub wait_interrupt: Option, pub lifecycle_tx: Option>, pub output_capture_tx: Option>, } @@ -316,6 +318,16 @@ impl RemoteExecProcessManager { output_tx: Option>, ) -> RemoteExecResult { let process = Arc::new(spawn_remote_process(request.clone()).await?); + self.wait_for_initial_output(process, request, output_tx) + .await + } + + async fn wait_for_initial_output( + &self, + process: Arc, + request: RemoteExecCommandRequest, + output_tx: Option>, + ) -> RemoteExecResult { let cursor = OutputCursor { next_seq: 0, pending_utf8: PendingUtf8Streams::default(), @@ -331,16 +343,22 @@ impl RemoteExecProcessManager { let started_at = Instant::now(); let collected = process .output - .collect_until( + .collect_until_interruptible( cursor, deadline_from_now(request.yield_time_ms), request.max_output_chars.unwrap_or(usize::MAX), output_tx.as_ref(), + request.wait_interrupt.as_ref(), ) .await; - let exit_code = process.output.exit_code().await; - let closed = process.output.is_closed().await; + // Keep bytes arriving after the final drain available to the next poll. + let closed = collected.closed; + let exit_code = if closed { + process.output.exit_code().await + } else { + None + }; let completion = if closed { Some(completion_for_closed_remote_process( process.out_of_band_control_action(), @@ -358,7 +376,7 @@ impl RemoteExecProcessManager { .await; Ok(RemoteExecCommandResponse { - wait_interrupted: false, + wait_interrupted: collected.wait_interrupted, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -1601,6 +1619,110 @@ mod wait_interrupt_tests { } } + fn exec_request( + directory: &std::path::Path, + token: CancellationToken, + ) -> RemoteExecCommandRequest { + RemoteExecCommandRequest { + ssh_manager: super::SSHConnectionManager::new(directory.into()), + connection_id: "simulated-ssh".into(), + command: "command".into(), + tty: true, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt: Some(token), + lifecycle_tx: None, + output_capture_tx: None, + } + } + + #[tokio::test] + async fn exec_command_wait_interrupt_commits_initial_cursor_and_preserves_process() { + for streaming in [false, true] { + let directory = tempfile::tempdir().unwrap(); + let (manager, output, mut commands) = session().await; + let process = manager.sessions.lock().await.remove(&42).unwrap().process; + output + .push_chunk(OutputStream::Stdout, b"before".to_vec()) + .await; + let bytes = "\u{1f680}".as_bytes(); + output + .push_chunk(OutputStream::Stdout, bytes[..2].to_vec()) + .await; + let token = CancellationToken::new(); + let request = exec_request(directory.path(), token.clone()); + let (tx, mut rx) = mpsc::channel(8); + if !streaming { + token.cancel(); + } + let (response, ()) = tokio::time::timeout(Duration::from_secs(2), async { + tokio::join!( + manager.wait_for_initial_output(process, request, streaming.then_some(tx)), + async { + if streaming { + assert_eq!(rx.recv().await.as_deref(), Some("before")); + token.cancel(); + } + } + ) + }) + .await + .unwrap(); + let response = response.unwrap(); + assert!(response.wait_interrupted); + assert_eq!(response.output, "before"); + assert_eq!(response.exit_code, None); + assert_eq!(response.completion, None); + let session_id = response.session_id.unwrap(); + assert!(manager.is_session_active(session_id).await); + assert!( + commands.try_recv().is_err(), + "yield must not control the process" + ); + + output + .push_chunk(OutputStream::Stdout, bytes[2..].to_vec()) + .await; + output.close(Some(0)).await; + let mut request = poll(None); + request.session_id = session_id; + let last = manager.write_stdin(request).await.unwrap(); + assert_eq!(last.output, "\u{1f680}"); + assert!(!last.wait_interrupted); + assert_eq!(last.session_id, None); + assert_eq!(last.exit_code, Some(0)); + assert_eq!( + last.completion.unwrap().status, + RemoteExecSessionCompletionStatus::Exited + ); + } + } + + #[tokio::test] + async fn exec_command_wait_interrupt_does_not_override_drained_exit() { + let directory = tempfile::tempdir().unwrap(); + let (manager, output, _commands) = session().await; + let process = manager.sessions.lock().await.remove(&42).unwrap().process; + output + .push_chunk(OutputStream::Stdout, b"final".to_vec()) + .await; + output.close(Some(7)).await; + let token = CancellationToken::new(); + token.cancel(); + let response = manager + .wait_for_initial_output(process, exec_request(directory.path(), token), None) + .await + .unwrap(); + assert!(!response.wait_interrupted); + assert_eq!(response.output, "final"); + assert_eq!(response.exit_code, Some(7)); + assert_eq!(response.session_id, None); + assert_eq!( + response.completion.unwrap().status, + RemoteExecSessionCompletionStatus::Exited + ); + } + #[tokio::test] async fn wait_interrupt_preserves_partial_output_and_split_utf8_across_polls() { let (manager, output, mut commands) = session().await; diff --git a/src/crates/services/services-integrations/src/remote_ssh/remote_exec_runtime_port.rs b/src/crates/services/services-integrations/src/remote_ssh/remote_exec_runtime_port.rs index 2204e54d18..0c140e3450 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/remote_exec_runtime_port.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/remote_exec_runtime_port.rs @@ -49,6 +49,7 @@ impl RemoteExecRuntimePort { tty: request.tty, yield_time_ms: request.yield_time_ms, max_output_chars: request.max_output_chars, + wait_interrupt: request.wait_interrupt, lifecycle_tx: bridge_lifecycle_sink(request.lifecycle_sink), output_capture_tx: request.output_sink, }) @@ -294,6 +295,40 @@ fn error_from_service(error: RemoteExecError) -> ports::PortError { mod tests { use super::*; + #[derive(Debug)] + struct ManagerProvider(std::path::PathBuf); + + #[async_trait] + impl RemoteExecSshManagerProvider for ManagerProvider { + async fn ssh_manager(&self) -> ports::PortResult { + Ok(SSHConnectionManager::new(self.0.clone())) + } + } + + #[tokio::test] + async fn exec_command_wait_interrupt_crosses_port_adapter() { + let directory = tempfile::tempdir().unwrap(); + let port = RemoteExecRuntimePort::new(Arc::new(ManagerProvider(directory.path().into()))); + let token = tokio_util::sync::CancellationToken::new(); + let request = port + .command_request(ports::RemoteExecCommandRequest { + connection_id: "simulated-ssh".into(), + command: "echo before".into(), + tty: false, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt: Some(token.clone()), + lifecycle_sink: None, + output_sink: None, + }) + .await + .unwrap(); + token.cancel(); + assert!(request.wait_interrupt.unwrap().is_cancelled()); + assert_eq!(request.command, "echo before"); + assert_eq!(request.yield_time_ms, Some(600_000)); + } + #[test] fn wait_interrupt_crosses_port_adapter_without_becoming_process_completion() { let token = tokio_util::sync::CancellationToken::new(); diff --git a/src/crates/services/services-integrations/tests/remote_ssh_contracts/remote_ssh_disabled_contracts.rs b/src/crates/services/services-integrations/tests/remote_ssh_contracts/remote_ssh_disabled_contracts.rs index e2d557bbb2..f9db5b5734 100644 --- a/src/crates/services/services-integrations/tests/remote_ssh_contracts/remote_ssh_disabled_contracts.rs +++ b/src/crates/services/services-integrations/tests/remote_ssh_contracts/remote_ssh_disabled_contracts.rs @@ -87,6 +87,7 @@ async fn remote_ssh_disabled_file_terminal_and_exec_paths_return_unsupported() { tty: false, yield_time_ms: None, max_output_chars: None, + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) diff --git a/src/crates/services/terminal/AGENTS.md b/src/crates/services/terminal/AGENTS.md index 0a193a4c5b..762b83cf0b 100644 --- a/src/crates/services/terminal/AGENTS.md +++ b/src/crates/services/terminal/AGENTS.md @@ -23,6 +23,7 @@ infrastructure, not a product command or UI layer. ```bash cargo check -p terminal-core cargo test -p terminal-core --lib exec:: # process output, encoding, polling and lifecycle +cargo test --locked -p terminal-core --lib runtime_port::tests::exec_command_wait_interrupt # initial wait steering, live process and continued output cargo test --locked -p terminal-core --lib runtime_port::tests::write_stdin_wait_interrupt # live Unix PTY steering and continued input cargo test -p terminal-core --lib workspace_origin_contract_tests # terminal response compatibility node scripts/check-core-boundaries.mjs @@ -30,8 +31,8 @@ node scripts/check-core-boundaries.mjs For documentation-only changes, run `git diff --check`. -WriteStdin's optional wait-interrupt token ends only output collection. Return -the collected bytes and commit the cursor before yielding; do not signal or +The optional wait-interrupt token for ExecCommand and WriteStdin ends only output +collection. Return the collected bytes and commit the cursor before yielding; do not signal or drop the process, replay stdin, or conflate wait interruption with completion. Session cleanup uses the closure snapshot from the final output drain so an exit immediately after that drain leaves its trailing bytes pollable. diff --git a/src/crates/services/terminal/src/exec.rs b/src/crates/services/terminal/src/exec.rs index 5c061fae32..11f7ff1bb5 100644 --- a/src/crates/services/terminal/src/exec.rs +++ b/src/crates/services/terminal/src/exec.rs @@ -57,6 +57,8 @@ pub struct ExecCommandRequest { pub tty: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only the initial output wait; the launched process remains active. + pub wait_interrupt: Option, pub lifecycle_tx: Option>, pub output_capture_tx: Option>, } @@ -334,16 +336,22 @@ impl ExecProcessManager { let started_at = tokio::time::Instant::now(); let collected = process .output - .collect_until( + .collect_until_interruptible( cursor, deadline_from_now(request.yield_time_ms), request.max_output_chars.unwrap_or(usize::MAX), output_tx.as_ref(), + request.wait_interrupt.as_ref(), ) .await; - let exit_code = process.output.exit_code().await; - let closed = process.output.is_closed().await; + // Keep bytes arriving after the final drain available to the next poll. + let closed = collected.closed; + let exit_code = if closed { + process.output.exit_code().await + } else { + None + }; let completion = if closed { Some(completion_for_closed_process( process.out_of_band_control_action(), @@ -359,7 +367,7 @@ impl ExecProcessManager { } Ok(ExecCommandResponse { - wait_interrupted: false, + wait_interrupted: collected.wait_interrupted, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -1902,6 +1910,7 @@ mod tests { tty: false, yield_time_ms: Some(5_000), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -1929,6 +1938,7 @@ mod tests { tty: false, yield_time_ms: Some(5_000), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -1977,6 +1987,7 @@ mod tests { tty: false, yield_time_ms: Some(5_000), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2007,6 +2018,7 @@ mod tests { tty: false, yield_time_ms: Some(100), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2054,6 +2066,7 @@ mod tests { tty: false, yield_time_ms: Some(100), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: Some(tx), output_capture_tx: None, }) @@ -2098,6 +2111,7 @@ mod tests { tty: false, yield_time_ms: Some(30_000), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: Some(tx), output_capture_tx: None, }) @@ -2157,6 +2171,7 @@ mod tests { tty: true, yield_time_ms: Some(100), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2214,6 +2229,7 @@ mod tests { tty: true, yield_time_ms: Some(500), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2255,6 +2271,7 @@ mod tests { tty: true, yield_time_ms: Some(500), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2309,6 +2326,7 @@ mod tests { tty: false, yield_time_ms: Some(100), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2363,6 +2381,7 @@ mod tests { tty: false, yield_time_ms: Some(500), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2438,6 +2457,7 @@ print("parent_exit", flush=True)"#; tty: false, yield_time_ms: Some(700), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2566,6 +2586,7 @@ print("parent_exit", flush=True)"#; tty: false, yield_time_ms: Some(1_500), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2631,6 +2652,7 @@ print("parent_exit", flush=True)"#; tty: false, yield_time_ms: Some(1_500), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2676,6 +2698,7 @@ print("parent_exit", flush=True)"#; tty: true, yield_time_ms: Some(500), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -2716,6 +2739,7 @@ print("parent_exit", flush=True)"#; tty: true, yield_time_ms: Some(500), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: None, }) @@ -3050,7 +3074,10 @@ mod wait_interrupt_tests { request.append_enter = true; let response = manager.write_stdin(request).await.unwrap(); assert!(response.wait_interrupted); - assert_eq!(input.recv().await.unwrap(), format!("{chars}\n").as_bytes()); + assert_eq!( + input.recv().await.unwrap(), + input_bytes_for_write(chars, true) + ); let mut next = poll(None); next.yield_time_ms = Some(0); assert!(!manager.write_stdin(next).await.unwrap().wait_interrupted); diff --git a/src/crates/services/terminal/src/exec/output_encoding_tests.rs b/src/crates/services/terminal/src/exec/output_encoding_tests.rs index 2b8b0caf37..e5fa154611 100644 --- a/src/crates/services/terminal/src/exec/output_encoding_tests.rs +++ b/src/crates/services/terminal/src/exec/output_encoding_tests.rs @@ -124,6 +124,7 @@ async fn git_bash_cat_preserves_utf8_fixture_through_exec_command() { tty: false, yield_time_ms: Some(10_000), max_output_chars: Some(10_000), + wait_interrupt: None, lifecycle_tx: None, output_capture_tx: Some(capture_tx), }, diff --git a/src/crates/services/terminal/src/runtime_port.rs b/src/crates/services/terminal/src/runtime_port.rs index a0fca6369f..ba8a42c893 100644 --- a/src/crates/services/terminal/src/runtime_port.rs +++ b/src/crates/services/terminal/src/runtime_port.rs @@ -147,6 +147,7 @@ fn local_exec_command_request(request: TerminalExecCommandRequest) -> ExecComman tty: request.tty, yield_time_ms: request.yield_time_ms, max_output_chars: request.max_output_chars, + wait_interrupt: request.wait_interrupt, lifecycle_tx: lifecycle_tx(request.lifecycle_sink), output_capture_tx: request.output_sink, } @@ -263,6 +264,140 @@ mod tests { TerminalExecSessionCompletionStatus, TerminalPort, TerminalSendStdinRequest, }; + #[tokio::test] + async fn exec_command_wait_interrupt_preserves_process_and_output_cursor() { + use openbitfun_runtime_ports::TerminalWriteStdinRequest; + use std::{sync::Arc, time::Duration}; + use tokio_util::sync::CancellationToken; + + for tty in [false, true] { + let directory = tempfile::tempdir().unwrap(); + let release = directory.path().join("release"); + #[cfg(windows)] + let argv = vec![ + "powershell.exe".into(), "-NoLogo".into(), "-NoProfile".into(), + "-NonInteractive".into(), "-Command".into(), + format!("Write-Output 'before'; while (-not (Test-Path -LiteralPath '{}')) {{ Start-Sleep -Milliseconds 20 }}; Write-Output 'after'", release.display().to_string().replace('\'', "''")), + ]; + #[cfg(not(windows))] + let argv = vec![ + "sh".into(), "-c".into(), + format!("printf 'before\\n'; while [ ! -f '{}' ]; do sleep 0.02; done; printf 'after\\n'", release.display().to_string().replace('\'', "'\\''")), + ]; + let manager = Arc::new(crate::exec::ExecProcessManager::default()); + let port = TerminalRuntimePort::new(manager.clone()); + let token = CancellationToken::new(); + let (tx, mut rx) = tokio::sync::mpsc::channel(32); + let request = TerminalExecCommandRequest { + argv, + cwd: directory.path().into(), + env: Default::default(), + tty, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt: Some(token.clone()), + lifecycle_sink: None, + output_sink: None, + }; + let (response, ()) = tokio::time::timeout(Duration::from_secs(15), async { + tokio::join!(port.exec_command_streaming(request, tx), async { + let mut output = String::new(); + while !output.contains("before") { + output.push_str(&rx.recv().await.unwrap()); + } + token.cancel(); + // Continue draining until the streaming sender is dropped. + while rx.recv().await.is_some() {} + }) + }) + .await + .unwrap(); + let response = response.unwrap(); + assert!(response.wait_interrupted); + assert!(response.output.contains("before")); + assert!(!response.output.contains("after")); + assert_eq!(response.exit_code, None); + assert_eq!(response.completion, None); + let session_id = response.session_id.unwrap(); + assert!(manager.is_session_active(session_id).await); + std::fs::write(&release, "continue").unwrap(); + let last = port + .write_stdin(TerminalWriteStdinRequest { + session_id, + chars: String::new(), + append_enter: false, + yield_time_ms: Some(10_000), + max_output_chars: None, + wait_interrupt: None, + }) + .await + .unwrap(); + assert!(!last.wait_interrupted); + assert!(last.output.contains("after")); + assert!(!last.output.contains("before")); + assert_eq!(last.exit_code, Some(0)); + assert_eq!(last.session_id, None); + assert_eq!( + last.completion.unwrap().status, + TerminalExecSessionCompletionStatus::Exited + ); + } + } + + #[tokio::test] + async fn exec_command_wait_interrupt_can_yield_before_any_output() { + use openbitfun_runtime_ports::{ + TerminalExecControlAction, TerminalExecControlOrigin, TerminalExecControlRequest, + }; + use std::{sync::Arc, time::Duration}; + use tokio_util::sync::CancellationToken; + + let manager = Arc::new(crate::exec::ExecProcessManager::default()); + let port = TerminalRuntimePort::new(manager.clone()); + let token = CancellationToken::new(); + token.cancel(); + #[cfg(windows)] + let argv = vec![ + "powershell.exe".into(), + "-NoProfile".into(), + "-NonInteractive".into(), + "-Command".into(), + "Start-Sleep -Seconds 600".into(), + ]; + #[cfg(not(windows))] + let argv = vec!["sh".into(), "-c".into(), "sleep 600".into()]; + let response = tokio::time::timeout( + Duration::from_secs(5), + port.exec_command(TerminalExecCommandRequest { + argv, + cwd: std::env::current_dir().unwrap(), + env: Default::default(), + tty: false, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt: Some(token), + lifecycle_sink: None, + output_sink: None, + }), + ) + .await + .unwrap() + .unwrap(); + assert!(response.wait_interrupted); + assert!(response.output.is_empty()); + let session_id = response.session_id.unwrap(); + assert!(manager.is_session_active(session_id).await); + port.control_session(TerminalExecControlRequest { + session_id, + action: TerminalExecControlAction::Kill, + origin: TerminalExecControlOrigin::ModelTool, + yield_time_ms: Some(5_000), + max_output_chars: None, + }) + .await + .unwrap(); + } + #[tokio::test] #[cfg(unix)] async fn write_stdin_wait_interrupt_preserves_live_pty_and_submitted_input() { @@ -276,7 +411,7 @@ mod tests { argv: vec!["sh".into(), "-c".into(), "read first; printf 'first:%s\\n' \"$first\"; read second; printf 'second:%s\\n' \"$second\"".into()], cwd: std::env::current_dir().unwrap(), env: Default::default(), tty: true, - yield_time_ms: Some(0), max_output_chars: None, + yield_time_ms: Some(0), max_output_chars: None, wait_interrupt: None, lifecycle_sink: None, output_sink: None, }).await.unwrap(); let session_id = initial.session_id.unwrap(); @@ -357,6 +492,7 @@ mod tests { tty: false, yield_time_ms: Some(30_000), max_output_chars: None, + wait_interrupt: None, lifecycle_sink: None, output_sink: None, })