From 23e325670b5070ab7c86ab6382e7ad9327d2364b Mon Sep 17 00:00:00 2001 From: wsp Date: Tue, 17 Nov 2026 19:44:57 +0800 Subject: [PATCH] feat(tools): Let WriteStdin yield to user steering Return collected output when steering ends a local or SSH stdin wait. Keep the process alive, preserve output cursors, and avoid replaying submitted input. Report wait interruption separately from completion. Cover streaming, UTF-8 continuation, exit races, legacy results, and continued input through a live local PTY. All 82 focused Rust tests and 159 boundary contract tests pass. Live remote end-to-end scenarios remain untested. --- Cargo.lock | 1 + scripts/check-core-boundaries.test.mjs | 10 +- .../core-boundaries/rules/feature-rules.mjs | 7 +- src/crates/assembly/core/AGENTS.md | 13 + .../exec_command/guard_tests.rs | 1 + .../implementations/exec_command/stdin.rs | 250 ++++++++++++++++- src/crates/contracts/runtime-ports/AGENTS.md | 4 + src/crates/contracts/runtime-ports/Cargo.toml | 4 +- .../runtime-ports/src/remote_exec_port.rs | 4 + .../runtime-ports/src/terminal_port.rs | 4 + .../tool-execution/src/exec_command.rs | 27 +- .../services/services-integrations/AGENTS.md | 13 + .../src/remote_ssh/disabled.rs | 4 + .../src/remote_ssh/remote_exec.rs | 254 +++++++++++++++++- .../remote_ssh/remote_exec_runtime_port.rs | 33 +++ src/crates/services/terminal/AGENTS.md | 8 + src/crates/services/terminal/Cargo.toml | 1 + src/crates/services/terminal/src/exec.rs | 221 ++++++++++++++- .../services/terminal/src/runtime_port.rs | 65 +++++ 19 files changed, 888 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 75691eb2e7..7bf5755779 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10590,6 +10590,7 @@ dependencies = [ "thiserror 2.0.19", "tokio", "tokio-stream", + "tokio-util", "uuid", "win32job", ] diff --git a/scripts/check-core-boundaries.test.mjs b/scripts/check-core-boundaries.test.mjs index 58988f5872..42f8265084 100644 --- a/scripts/check-core-boundaries.test.mjs +++ b/scripts/check-core-boundaries.test.mjs @@ -579,8 +579,8 @@ test('portable contract crates expose only capability-local feature slices', asy // Workspace byte readers expose AsyncRead/AsyncSeek without selecting a // process, network, scheduler, or full Tokio runtime at the contract layer. assert.deepEqual(new Set(runtimePortFeatures['workspace-ports']), new Set(['dep:anyhow', 'dep:tokio-util', 'dep:tokio', 'tokio/io-util'])); - assert.deepEqual(runtimePortFeatures['terminal-port'], ['dep:tokio']); - assert.deepEqual(runtimePortFeatures['remote-exec-port'], ['dep:tokio']); + assert.deepEqual(runtimePortFeatures['terminal-port'], ['dep:tokio', 'dep:tokio-util']); + assert.deepEqual(runtimePortFeatures['remote-exec-port'], ['dep:tokio', 'dep:tokio-util']); assert.deepEqual( new Set(runtimePortFeatures['tool-runtime-handles']), new Set([ @@ -640,7 +640,7 @@ test('runtime-ports async dependencies stay behind their exact port owners', () ); assert.deepEqual( ownersByDependency.get('tokio-util'), - new Set(['permission', 'ts', 'workspace-ports']), + new Set(['permission', 'remote-exec-port', 'terminal-port', 'ts', 'workspace-ports']), ); assert.deepEqual( ownersByDependency.get('tokio'), @@ -819,11 +819,11 @@ const RUNTIME_PORT_FEATURE_PROFILES = { 'plugin-runtime': [], 'product-search': ['dep:openbitfun-product-domains'], 'ptc-runtime': [], - 'remote-exec-port': ['dep:tokio'], + 'remote-exec-port': ['dep:tokio', 'dep:tokio-util'], 'remote-workspace-ports': ['dep:openbitfun-core-types'], 'runtime-event-port': [], 'script-tool-runtime': [], - 'terminal-port': ['dep:tokio'], + 'terminal-port': ['dep:tokio', 'dep:tokio-util'], 'tool-runtime-handles': ['workspace-ports', 'terminal-port', 'remote-exec-port'], ts: [ 'dep:ts-rs', diff --git a/scripts/core-boundaries/rules/feature-rules.mjs b/scripts/core-boundaries/rules/feature-rules.mjs index 3f66681752..e469abea3e 100644 --- a/scripts/core-boundaries/rules/feature-rules.mjs +++ b/scripts/core-boundaries/rules/feature-rules.mjs @@ -127,7 +127,8 @@ export const optionalDependencyFeatureOwnerRules = [ { depName: 'openbitfun-core-types', ownerFeatures: ['agent-api', 'remote-workspace-ports', 'ts'] }, { depName: 'openbitfun-product-domains', ownerFeatures: ['permission', 'product-search', 'ts'] }, { depName: 'tokio', ownerFeatures: ['remote-exec-port', 'terminal-port', 'workspace-ports'] }, - { depName: 'tokio-util', ownerFeatures: ['permission', 'ts', 'workspace-ports'] }, + // Exec stdin ports carry an in-process cooperative output-wait token. + { depName: 'tokio-util', ownerFeatures: ['permission', 'remote-exec-port', 'terminal-port', 'ts', 'workspace-ports'] }, { depName: 'ts-rs', ownerFeatures: ['ts'] }, ], }, @@ -409,11 +410,11 @@ export const capabilityContractDependencyRules = [ 'plugin-runtime': [], 'product-search': ['dep:openbitfun-product-domains'], 'ptc-runtime': [], - 'remote-exec-port': ['dep:tokio'], + 'remote-exec-port': ['dep:tokio', 'dep:tokio-util'], 'remote-workspace-ports': ['dep:openbitfun-core-types'], 'runtime-event-port': [], 'script-tool-runtime': [], - 'terminal-port': ['dep:tokio'], + 'terminal-port': ['dep:tokio', 'dep:tokio-util'], 'tool-runtime-handles': ['workspace-ports', 'terminal-port', 'remote-exec-port'], 'web-search-port': [], ts: [ diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index 9e753d8609..37b204da96 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -211,6 +211,19 @@ Narrower local guides already exist for some subtrees: ## Verification +For 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 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. +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 propagation: diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/guard_tests.rs b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/guard_tests.rs index 23304aa680..d98cd15731 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/guard_tests.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/guard_tests.rs @@ -31,6 +31,7 @@ struct FixtureTerminal { } fn response(output: String, code: i32) -> TerminalExecCommandResponse { TerminalExecCommandResponse { + wait_interrupted: false, chunk_id: "fixture".into(), wall_time_seconds: 0.0, original_output_chars: output.chars().count(), diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/stdin.rs b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/stdin.rs index 1dd0cdacd2..9f32f4ce14 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/stdin.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/exec_command/stdin.rs @@ -53,6 +53,7 @@ impl WriteStdinTool { append_enter: parsed_input.append_enter, yield_time_ms: Some(parsed_input.yield_time_ms), max_output_chars: None, + wait_interrupt: context.round_injection_preemption_token().cloned(), }; let remote_exec_port = context.remote_exec_port().ok_or_else(|| { OpenBitFunError::tool( @@ -83,7 +84,7 @@ impl WriteStdinTool { } }; - let data = write_stdin_result_value(ExecCommandResultFields { + let mut data = write_stdin_result_value(ExecCommandResultFields { chunk_id: response.chunk_id, wall_time_seconds: response.wall_time_seconds, output: response.output, @@ -93,6 +94,9 @@ impl WriteStdinTool { completion: response.completion.map(exec_command_remote_completion), remote: true, }); + if response.wait_interrupted { + data["wait_end_reason"] = json!("steered"); + } let result_for_assistant = Self::response_for_assistant(&data); Ok(vec![ToolResult::Result { @@ -114,6 +118,7 @@ impl Tool for WriteStdinTool { Pass the session_id returned by ExecCommand. Leave chars empty or omit it to poll for new output. When waiting for a long-running command to finish, explicitly set a longer yield_time_ms, such as 600000 ms, to avoid frequent polling. Use shorter waits when you need to respond to interactive prompts or inspect intermediate output. +User steering can end the wait early and return output collected so far. The process continues running; already submitted input is not undone. Use the returned session_id to poll again without resending input. chars is sent only to sessions started with tty=true. For tty=false sessions, this tool only polls. Use append_enter=true to submit a line after chars. Use this for line-oriented interactive prompts instead of trying to encode \\r or \\n manually. Output is only what was produced during this tool call's wait window."# @@ -158,6 +163,7 @@ Output is only what was produced during this tool call's wait window."# "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": "object", "properties": {"source": {"type": "string"}, "status": {"type": "string"}}, "additionalProperties": false}, {"type": "null"}]} }, "required": ["wall_time_seconds", "output", "session_id", "exit_code", "completion"], @@ -177,6 +183,10 @@ Output is only what was produced during this tool call's wait window."# true } + fn round_injection_yieldable(&self) -> bool { + true + } + async fn validate_input( &self, input: &Value, @@ -239,6 +249,7 @@ Output is only what was produced during this tool call's wait window."# append_enter: parsed_input.append_enter, yield_time_ms: Some(parsed_input.yield_time_ms), max_output_chars: None, + wait_interrupt: context.round_injection_preemption_token().cloned(), }; let terminal_port = context.terminal_port().ok_or_else(|| { OpenBitFunError::tool("terminal runtime service is required for WriteStdin".to_string()) @@ -267,7 +278,7 @@ Output is only what was produced during this tool call's wait window."# } }; - let data = write_stdin_result_value(ExecCommandResultFields { + let mut data = write_stdin_result_value(ExecCommandResultFields { chunk_id: response.chunk_id, wall_time_seconds: response.wall_time_seconds, output: response.output, @@ -277,6 +288,9 @@ Output is only what was produced during this tool call's wait window."# completion: response.completion.map(exec_command_local_completion), remote: false, }); + if response.wait_interrupted { + data["wait_end_reason"] = json!("steered"); + } let result_for_assistant = Self::response_for_assistant(&data); Ok(vec![ToolResult::Result { @@ -319,3 +333,235 @@ mod tests { assert!(!assistant.contains("")); } } + +#[cfg(test)] +mod steering_tests { + use super::*; + use openbitfun_runtime_ports::*; + use std::sync::Arc; + use tokio_util::sync::CancellationToken; + + #[test] + fn write_stdin_owns_timeout_and_yields_to_round_injection() { + let tool = WriteStdinTool::new(); + assert!(tool.manages_own_execution_timeout()); + assert!(tool.round_injection_yieldable()); + assert!(!tool.is_concurrency_safe(None)); + } + + #[derive(Debug)] + struct TerminalProbe { + streaming: bool, + } + + impl RuntimeServicePort for TerminalProbe { + fn capability(&self) -> RuntimeServiceCapability { + RuntimeServiceCapability::Terminal + } + } + + #[async_trait] + impl TerminalPort for TerminalProbe { + async fn exec_command( + &self, + _: TerminalExecCommandRequest, + ) -> PortResult { + panic!("unexpected exec") + } + async fn exec_command_streaming( + &self, + _: TerminalExecCommandRequest, + _: TerminalExecStreamingOutputSink, + ) -> PortResult { + panic!("unexpected exec") + } + async fn send_stdin(&self, _: TerminalSendStdinRequest) -> PortResult<()> { + panic!("input must not be replayed") + } + async fn control_session( + &self, + _: TerminalExecControlRequest, + ) -> PortResult { + panic!("steering must not control the process") + } + + async fn write_stdin( + &self, + request: TerminalWriteStdinRequest, + ) -> PortResult { + assert!(!self.streaming); + Ok(self.response(request)) + } + + async fn write_stdin_streaming( + &self, + request: TerminalWriteStdinRequest, + sink: TerminalExecStreamingOutputSink, + ) -> PortResult { + assert!(self.streaming); + sink.send("partial".into()).await.unwrap(); + Ok(self.response(request)) + } + } + + impl TerminalProbe { + fn response(&self, request: TerminalWriteStdinRequest) -> TerminalExecCommandResponse { + assert_eq!(request.session_id, 42); + assert_eq!(request.chars, "answer"); + assert!(request.append_enter); + assert_eq!(request.yield_time_ms, Some(600_000)); + let wait_interrupted = request + .wait_interrupt + .as_ref() + .is_some_and(CancellationToken::is_cancelled); + 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, + } + } + } + + #[derive(Debug)] + struct RemoteProbe { + streaming: bool, + } + + impl RuntimeServicePort for RemoteProbe { + fn capability(&self) -> RuntimeServiceCapability { + RuntimeServiceCapability::RemoteExec + } + } + + #[async_trait] + impl RemoteExecPort for RemoteProbe { + async fn exec_command_once( + &self, + _: RemoteExecOneShotCommandRequest, + ) -> PortResult { + panic!("unexpected exec") + } + async fn exec_command( + &self, + _: RemoteExecCommandRequest, + ) -> PortResult { + panic!("unexpected exec") + } + async fn exec_command_streaming( + &self, + _: RemoteExecCommandRequest, + _: RemoteExecStreamingOutputSink, + ) -> PortResult { + panic!("unexpected exec") + } + async fn send_stdin(&self, _: RemoteSendStdinRequest) -> PortResult<()> { + panic!("input must not be replayed") + } + async fn control_session( + &self, + _: RemoteExecControlRequest, + ) -> PortResult { + panic!("steering must not control the process") + } + + async fn write_stdin( + &self, + request: RemoteWriteStdinRequest, + ) -> PortResult { + assert!(!self.streaming); + Ok(self.response(request)) + } + + async fn write_stdin_streaming( + &self, + request: RemoteWriteStdinRequest, + sink: RemoteExecStreamingOutputSink, + ) -> PortResult { + assert!(self.streaming); + sink.send("partial".into()).await.unwrap(); + Ok(self.response(request)) + } + } + + impl RemoteProbe { + fn response(&self, request: RemoteWriteStdinRequest) -> RemoteExecCommandResponse { + assert_eq!(request.session_id, 42); + assert_eq!(request.chars, "answer"); + assert!(request.append_enter); + assert_eq!(request.yield_time_ms, Some(600_000)); + let wait_interrupted = request + .wait_interrupt + .as_ref() + .is_some_and(CancellationToken::is_cancelled); + 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, + } + } + } + + #[tokio::test] + async fn write_stdin_steering_reaches_both_ports_and_preserves_legacy_results() { + for remote in [false, true] { + for streaming in [false, true] { + for steered in [false, true] { + let mut context = ToolUseContext::for_tool_listing(None, None); + context.tool_call_id = streaming.then(|| "stdin-test".to_string()); + 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(Arc::new(TerminalProbe { streaming }))) + .with_remote_exec_port(Some(Arc::new(RemoteProbe { streaming }))); + let input = json!({"session_id":42, "chars":"answer", "append_enter":true, "yield_time_ms":600_000}); + let tool = WriteStdinTool::new(); + let results = if remote { + tool.call_remote_pipe(&input, &context).await + } else { + tool.call_impl(&input, &context).await + } + .unwrap(); + 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()); + if steered { + assert_eq!(data["wait_end_reason"], "steered"); + assert!(result_for_assistant + .as_ref() + .unwrap() + .contains("user steering arrived")); + } else { + assert!(data.get("wait_end_reason").is_none()); + assert!(!result_for_assistant.as_ref().unwrap().contains("steering")); + } + // Tool results remain ordinary JSON, including older payloads + // which have no wait_end_reason field. + let restored: Value = + serde_json::from_str(&serde_json::to_string(data).unwrap()).unwrap(); + assert_eq!(&restored, data); + } + } + } + } +} diff --git a/src/crates/contracts/runtime-ports/AGENTS.md b/src/crates/contracts/runtime-ports/AGENTS.md index bc96587114..bd64039a55 100644 --- a/src/crates/contracts/runtime-ports/AGENTS.md +++ b/src/crates/contracts/runtime-ports/AGENTS.md @@ -45,6 +45,10 @@ 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 + 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`, `terminal-port`, `remote-exec-port`, `remote-workspace-ports`, `git-port`, `runtime-event-port`, `plugin-runtime`, or `script-tool-runtime` only from diff --git a/src/crates/contracts/runtime-ports/Cargo.toml b/src/crates/contracts/runtime-ports/Cargo.toml index 58b9e65ed0..af51f53a16 100644 --- a/src/crates/contracts/runtime-ports/Cargo.toml +++ b/src/crates/contracts/runtime-ports/Cargo.toml @@ -60,8 +60,8 @@ script-tool-runtime = [] ptc-runtime = [] web-search-port = [] workspace-ports = ["dep:anyhow", "dep:tokio-util", "dep:tokio", "tokio/io-util"] -terminal-port = ["dep:tokio"] -remote-exec-port = ["dep:tokio"] +terminal-port = ["dep:tokio", "dep:tokio-util"] +remote-exec-port = ["dep:tokio", "dep:tokio-util"] tool-runtime-handles = [ "workspace-ports", "terminal-port", 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 0b73b83d72..39f43ff118 100644 --- a/src/crates/contracts/runtime-ports/src/remote_exec_port.rs +++ b/src/crates/contracts/runtime-ports/src/remote_exec_port.rs @@ -35,6 +35,8 @@ pub struct RemoteWriteStdinRequest { pub append_enter: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only this output wait; submitted input and the process remain active. + pub wait_interrupt: Option, } #[derive(Debug, Clone)] @@ -94,6 +96,8 @@ pub struct RemoteExecCommandResponse { pub exit_code: Option, pub original_output_chars: usize, pub completion: Option, + /// The output wait yielded cooperatively, independently of process completion. + pub wait_interrupted: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/src/crates/contracts/runtime-ports/src/terminal_port.rs b/src/crates/contracts/runtime-ports/src/terminal_port.rs index a5c2ad7a27..fbfa68eb56 100644 --- a/src/crates/contracts/runtime-ports/src/terminal_port.rs +++ b/src/crates/contracts/runtime-ports/src/terminal_port.rs @@ -22,6 +22,8 @@ pub struct TerminalWriteStdinRequest { pub append_enter: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only this output wait; submitted input and the process remain active. + pub wait_interrupt: Option, } #[derive(Debug, Clone)] @@ -81,6 +83,8 @@ pub struct TerminalExecCommandResponse { pub exit_code: Option, pub original_output_chars: usize, pub completion: Option, + /// The output wait yielded cooperatively, independently of process completion. + pub wait_interrupted: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/src/crates/execution/tool-execution/src/exec_command.rs b/src/crates/execution/tool-execution/src/exec_command.rs index 52db3d31f4..a16b2c5cbe 100644 --- a/src/crates/execution/tool-execution/src/exec_command.rs +++ b/src/crates/execution/tool-execution/src/exec_command.rs @@ -860,7 +860,14 @@ pub fn render_exec_command_response_for_assistant(data: &Value) -> String { } pub fn render_write_stdin_response_for_assistant(data: &Value) -> String { - render_exec_response_for_assistant(data, completion_status_lines(data), 4) + let mut notes = Vec::new(); + if data.get("wait_end_reason").and_then(Value::as_str) == Some("steered") { + notes.push( + "WriteStdin ended its wait early because user steering arrived. The wait did not stop the process or undo submitted input. Handle the new user message before polling again; do not resend already submitted input." + .to_string(), + ); + } + render_exec_response_for_assistant_with_notes(data, completion_status_lines(data), notes, 4) } pub fn render_exec_control_response_for_assistant( @@ -1081,6 +1088,24 @@ mod tests { ); } + #[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}"#; + let mut data: Value = serde_json::from_str(legacy).unwrap(); + let original = render_write_stdin_response_for_assistant(&data); + assert!(!original.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_write_stdin_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 resend already submitted input")); + assert!(rendered.contains("\npartial\n")); + assert!(!rendered.contains("Process was interrupted externally")); + } + #[test] fn write_stdin_response_reports_external_interrupt() { let data = json!({ diff --git a/src/crates/services/services-integrations/AGENTS.md b/src/crates/services/services-integrations/AGENTS.md index 75f8d71d28..1c674cc418 100644 --- a/src/crates/services/services-integrations/AGENTS.md +++ b/src/crates/services/services-integrations/AGENTS.md @@ -179,6 +179,19 @@ they do not prove live SSH/Peer/relay behavior. ## Verification +For remote ExecCommand/WriteStdin output waits, steering, split UTF-8 cursors +and runtime-port conversion: + +```bash +cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-ssh-concrete --lib remote_ssh::remote_exec +``` + +Wait interruption commits the output cursor and leaves the remote process and +already submitted input intact. Preserve partial UTF-8 bytes across polls and +use the drained closure snapshot for session cleanup. These fixtures use the +remote manager with simulated transport and local process owners; they do not +establish live SSH, Peer Device, relay or Detached Dispatch behavior. + Select one integration family and its minimum feature set. Remote SSH uses a grouped target for tests within the same boundary; use `--test ::` for a single source module instead of 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 d6c8f06ebb..013a073a39 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/disabled.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/disabled.rs @@ -167,6 +167,8 @@ pub struct RemoteWriteStdinRequest { pub append_enter: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only this output wait; submitted input and the process remain active. + pub wait_interrupt: Option, } #[derive(Debug, Clone)] @@ -226,6 +228,8 @@ pub struct RemoteExecCommandResponse { pub exit_code: Option, pub original_output_chars: usize, pub completion: Option, + /// The output wait yielded cooperatively, independently of process completion. + pub wait_interrupted: bool, } pub type RemoteExecResult = std::result::Result; 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 960d89749f..9e20c48fcb 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 @@ -54,6 +54,8 @@ pub struct RemoteWriteStdinRequest { pub append_enter: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only this output wait; submitted input and the process remain active. + pub wait_interrupt: Option, } #[derive(Debug, Clone)] @@ -113,6 +115,8 @@ pub struct RemoteExecCommandResponse { pub exit_code: Option, pub original_output_chars: usize, pub completion: Option, + /// The output wait yielded cooperatively, independently of process completion. + pub wait_interrupted: bool, } pub type RemoteExecResult = std::result::Result; @@ -261,6 +265,8 @@ struct CollectedOutput { output: String, original_output_chars: usize, cursor: OutputCursor, + closed: bool, + wait_interrupted: bool, } struct HeadTailText { @@ -344,7 +350,7 @@ impl RemoteExecProcessManager { }; self.update_or_remove_session( session_id, - &process, + closed, collected.cursor.clone(), None, exit_code, @@ -352,6 +358,7 @@ impl RemoteExecProcessManager { .await; Ok(RemoteExecCommandResponse { + wait_interrupted: false, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -415,6 +422,7 @@ impl RemoteExecProcessManager { if request.chars.is_empty() { if let Some(completed) = self.take_completed_session(request.session_id).await { return Ok(RemoteExecCommandResponse { + wait_interrupted: false, chunk_id: new_chunk_id(), wall_time_seconds: 0.0, output: completed.output, @@ -443,16 +451,23 @@ 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 closed = process.output.is_closed().await; - let exit_code = process.output.exit_code().await; + // Use the same closure snapshot as the final drain. A later exit must + // remain pollable so its final bytes cannot be lost during cleanup. + 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(), @@ -462,7 +477,7 @@ impl RemoteExecProcessManager { }; self.update_or_remove_session( request.session_id, - &process, + closed, collected.cursor.clone(), completion.map(|completion| lifecycle_status_for_completion(completion.status)), exit_code, @@ -470,6 +485,7 @@ impl RemoteExecProcessManager { .await; Ok(RemoteExecCommandResponse { + wait_interrupted: collected.wait_interrupted, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -528,7 +544,7 @@ impl RemoteExecProcessManager { completion.map(|completion| lifecycle_status_for_completion(completion.status)); self.update_or_remove_session( request.session_id, - &process, + closed, if request.origin == RemoteExecControlOrigin::ModelTool { collected.cursor.clone() } else { @@ -553,6 +569,7 @@ impl RemoteExecProcessManager { } Ok(RemoteExecCommandResponse { + wait_interrupted: false, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -624,12 +641,12 @@ impl RemoteExecProcessManager { async fn update_or_remove_session( &self, session_id: i32, - process: &RemoteExecProcess, + closed: bool, cursor: OutputCursor, lifecycle_status: Option, exit_code: Option, ) { - if process.output.is_closed().await { + if closed { let mut sessions = self.sessions.lock().await; if let Some(entry) = sessions.remove(&session_id) { if let Some(status) = lifecycle_status { @@ -1219,33 +1236,61 @@ impl OutputState { } async fn collect_until( + &self, + cursor: OutputCursor, + deadline: Instant, + max_output_chars: usize, + output_tx: Option<&mpsc::Sender>, + ) -> CollectedOutput { + self.collect_until_interruptible(cursor, deadline, max_output_chars, output_tx, None) + .await + } + + async fn collect_until_interruptible( &self, mut cursor: OutputCursor, deadline: Instant, max_output_chars: usize, output_tx: Option<&mpsc::Sender>, + wait_interrupt: Option<&tokio_util::sync::CancellationToken>, ) -> CollectedOutput { let mut sink = HeadTailText::new(max_output_chars); - loop { + let (closed, wait_interrupted) = loop { + // Register before draining so output/exit notifications cannot be + // lost between inspecting the buffer and going to sleep. + let notified = self.notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + let interrupted = wait_interrupt.is_some_and(|token| token.is_cancelled()); let closed = self .drain_since_with_output(&mut cursor, &mut sink, output_tx) .await; - if closed || Instant::now() >= deadline { - break; + if closed || interrupted || tokio::time::Instant::now() >= deadline { + // A fully drained process exit wins over a simultaneous yield. + break (closed, interrupted && !closed); } tokio::select! { - _ = self.notify.notified() => {} - _ = tokio::time::sleep_until(deadline) => break, + _ = &mut notified => {} + _ = tokio::time::sleep_until(deadline) => {} + _ = async { + match wait_interrupt { + Some(token) => token.cancelled().await, + None => std::future::pending::<()>().await, + } + } => {} } - } + // Every wake, including interruption/timeout, gets a final drain. + }; let original_output_chars = sink.total_chars; CollectedOutput { output: sink.render(), original_output_chars, cursor, + closed, + wait_interrupted, } } } @@ -1511,3 +1556,184 @@ mod tests { ); } } + +#[cfg(test)] +mod wait_interrupt_tests { + use super::*; + use tokio_util::sync::CancellationToken; + + async fn session() -> ( + Arc, + Arc, + mpsc::Receiver, + ) { + let manager = Arc::new(RemoteExecProcessManager::default()); + let output = Arc::new(OutputState::new(None)); + let (command_tx, rx) = mpsc::channel(8); + manager.sessions.lock().await.insert( + 42, + RemoteExecSessionEntry { + process: Arc::new(RemoteExecProcess { + output: output.clone(), + command_tx, + out_of_band_control_action: StdMutex::new(None), + }), + tty: true, + cursor: OutputCursor { + next_seq: 0, + pending_utf8: PendingUtf8Streams::default(), + }, + last_used: Instant::now(), + lifecycle_tx: None, + }, + ); + (manager, output, rx) + } + + fn poll(wait_interrupt: Option) -> RemoteWriteStdinRequest { + RemoteWriteStdinRequest { + session_id: 42, + chars: String::new(), + append_enter: false, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt, + } + } + + #[tokio::test] + async fn wait_interrupt_preserves_partial_output_and_split_utf8_across_polls() { + let (manager, output, mut commands) = session().await; + output + .push_chunk(OutputStream::Stdout, b"before".to_vec()) + .await; + let token = CancellationToken::new(); + let (tx, mut rx) = mpsc::channel(8); + let waiting_manager = manager.clone(); + let request = poll(Some(token.clone())); + let wait = + tokio::spawn(async move { waiting_manager.write_stdin_streaming(request, tx).await }); + assert_eq!(rx.recv().await.as_deref(), Some("before")); + let bytes = "\u{1f680}".as_bytes(); + output + .push_chunk(OutputStream::Stdout, bytes[..2].to_vec()) + .await; + output + .push_chunk(OutputStream::Stderr, b"-tail".to_vec()) + .await; + token.cancel(); + let response = tokio::time::timeout(Duration::from_secs(2), wait) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(response.output, "before-tail"); + assert_eq!(response.original_output_chars, 11); + assert!(response.wait_interrupted); + assert_eq!(response.session_id, Some(42)); + assert_eq!(response.exit_code, None); + assert_eq!(response.completion, None); + assert!(manager.is_session_active(42).await); + assert!( + commands.try_recv().is_err(), + "yield must not send a process control command" + ); + assert_eq!(rx.recv().await.as_deref(), Some("-tail")); + assert!(rx.recv().await.is_none()); + + output + .push_chunk(OutputStream::Stdout, bytes[2..].to_vec()) + .await; + output.close(Some(0)).await; + let next = manager.write_stdin(poll(None)).await.unwrap(); + assert_eq!(next.output, "\u{1f680}"); + assert_eq!(next.original_output_chars, 1); + assert!(!next.wait_interrupted); + assert_eq!(next.session_id, None); + assert_eq!(next.exit_code, Some(0)); + assert_eq!( + next.completion.unwrap().status, + RemoteExecSessionCompletionStatus::Exited + ); + assert!(!manager.sessions.lock().await.contains_key(&42)); + } + + #[tokio::test] + async fn wait_interrupt_wakes_without_output() { + let (manager, _, _commands) = session().await; + let token = CancellationToken::new(); + let request = poll(Some(token.clone())); + let (response, ()) = tokio::time::timeout(Duration::from_secs(2), async { + tokio::join!(manager.write_stdin(request), async { + tokio::task::yield_now().await; + token.cancel(); + }) + }) + .await + .unwrap(); + let response = response.unwrap(); + assert!(response.wait_interrupted); + assert!(response.output.is_empty()); + assert!(manager.is_session_active(42).await); + } + + #[tokio::test] + async fn wait_interrupt_keeps_submitted_input_exactly_once_including_enter_only() { + for chars in ["answer", ""] { + let (manager, _, mut commands) = session().await; + let token = CancellationToken::new(); + token.cancel(); + let mut request = poll(Some(token)); + request.chars = chars.into(); + request.append_enter = true; + assert!(manager.write_stdin(request).await.unwrap().wait_interrupted); + let RemoteExecProcessCommand::Write(bytes) = commands.recv().await.unwrap() else { + panic!("expected input, not a process control command"); + }; + assert_eq!(bytes, format!("{chars}\n").as_bytes()); + let mut next = poll(None); + next.yield_time_ms = Some(0); + assert!(!manager.write_stdin(next).await.unwrap().wait_interrupted); + assert!(commands.try_recv().is_err()); + assert!(manager.is_session_active(42).await); + } + } + + #[tokio::test] + async fn wait_interrupt_does_not_override_drained_process_exit() { + let (manager, output, _commands) = session().await; + output + .push_chunk(OutputStream::Stdout, b"final".to_vec()) + .await; + output.close(Some(7)).await; + let token = CancellationToken::new(); + token.cancel(); + let response = manager.write_stdin(poll(Some(token))).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_exit_after_drain_keeps_final_bytes_pollable() { + let (manager, output, _commands) = session().await; + let cursor = manager.sessions.lock().await[&42].cursor.clone(); + output + .push_chunk(OutputStream::Stdout, b"last bytes".to_vec()) + .await; + output.close(Some(0)).await; + // The wait had observed an open process; closure after that snapshot + // must not remove the session before another poll drains the new bytes. + manager + .update_or_remove_session(42, false, cursor, None, None) + .await; + let response = manager.write_stdin(poll(None)).await.unwrap(); + assert_eq!(response.output, "last bytes"); + assert_eq!(response.exit_code, Some(0)); + } +} 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 38638290c2..2204e54d18 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 @@ -185,6 +185,7 @@ fn stdin_request_to_service(request: ports::RemoteWriteStdinRequest) -> ServiceS append_enter: request.append_enter, yield_time_ms: request.yield_time_ms, max_output_chars: request.max_output_chars, + wait_interrupt: request.wait_interrupt, } } @@ -208,6 +209,7 @@ fn response_from_service(response: ServiceCommandResponse) -> ports::RemoteExecC session_id: response.session_id, exit_code: response.exit_code, original_output_chars: response.original_output_chars, + wait_interrupted: response.wait_interrupted, completion: response.completion.map(completion_from_service), } } @@ -292,6 +294,37 @@ fn error_from_service(error: RemoteExecError) -> ports::PortError { mod tests { use super::*; + #[test] + fn wait_interrupt_crosses_port_adapter_without_becoming_process_completion() { + let token = tokio_util::sync::CancellationToken::new(); + let request = stdin_request_to_service(ports::RemoteWriteStdinRequest { + session_id: 42, + chars: "answer".into(), + append_enter: true, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt: Some(token.clone()), + }); + token.cancel(); + assert!(request.wait_interrupt.unwrap().is_cancelled()); + assert_eq!(request.chars, "answer"); + assert!(request.append_enter); + let response = response_from_service(ServiceCommandResponse { + chunk_id: "chunk".into(), + wall_time_seconds: 0.1, + output: "partial".into(), + session_id: Some(42), + exit_code: None, + original_output_chars: 7, + completion: None, + wait_interrupted: true, + }); + assert!(response.wait_interrupted); + assert_eq!(response.session_id, Some(42)); + assert_eq!(response.completion, None); + assert_eq!(response.exit_code, None); + } + #[test] fn one_shot_response_preserves_stdout_stderr_and_timeout_flags() { let response = one_shot_response_from_service(SSHCommandResult { diff --git a/src/crates/services/terminal/AGENTS.md b/src/crates/services/terminal/AGENTS.md index b1e383bac2..0a193a4c5b 100644 --- a/src/crates/services/terminal/AGENTS.md +++ b/src/crates/services/terminal/AGENTS.md @@ -23,12 +23,20 @@ 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::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 ``` 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 +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. +The live PTY fixture is Unix-only; these tests do not establish remote behavior. + For natural PTY exit, output draining, confirmed shutdown and Unix hangup escalation, run `cargo test -p terminal-core --lib pty::process::tests` and `cargo check -p terminal-core`. These local child-process tests do not establish diff --git a/src/crates/services/terminal/Cargo.toml b/src/crates/services/terminal/Cargo.toml index ce2f002c21..c7c34bd1a8 100644 --- a/src/crates/services/terminal/Cargo.toml +++ b/src/crates/services/terminal/Cargo.toml @@ -15,6 +15,7 @@ openbitfun-runtime-ports = { path = "../../contracts/runtime-ports", features = # Async runtime tokio = { workspace = true, features = ["io-util", "macros", "process", "rt", "sync", "time"] } tokio-stream = { workspace = true } +tokio-util = { workspace = true } futures = { workspace = true } # Serialization diff --git a/src/crates/services/terminal/src/exec.rs b/src/crates/services/terminal/src/exec.rs index 5f3b94503d..5c061fae32 100644 --- a/src/crates/services/terminal/src/exec.rs +++ b/src/crates/services/terminal/src/exec.rs @@ -68,6 +68,8 @@ pub struct WriteStdinRequest { pub append_enter: bool, pub yield_time_ms: Option, pub max_output_chars: Option, + /// End only this output wait; submitted input and the process remain active. + pub wait_interrupt: Option, } #[derive(Debug, Clone)] @@ -127,6 +129,8 @@ pub struct ExecCommandResponse { pub exit_code: Option, pub original_output_chars: usize, pub completion: Option, + /// The output wait yielded cooperatively, independently of process completion. + pub wait_interrupted: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -355,6 +359,7 @@ impl ExecProcessManager { } Ok(ExecCommandResponse { + wait_interrupted: false, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -415,6 +420,7 @@ impl ExecProcessManager { if request.chars.is_empty() { if let Some(completed) = self.take_completed_session(request.session_id).await { return Ok(ExecCommandResponse { + wait_interrupted: false, chunk_id: new_chunk_id(), wall_time_seconds: 0.0, output: completed.output, @@ -453,16 +459,23 @@ 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 closed = process.output.is_closed().await; - let exit_code = process.output.exit_code().await; + // Use the same closure snapshot as the final drain. A later exit must + // remain pollable so its final bytes cannot be lost during cleanup. + 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(), @@ -492,6 +505,7 @@ impl ExecProcessManager { } Ok(ExecCommandResponse { + wait_interrupted: collected.wait_interrupted, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -590,6 +604,7 @@ impl ExecProcessManager { } Ok(ExecCommandResponse { + wait_interrupted: false, chunk_id: new_chunk_id(), wall_time_seconds: started_at.elapsed().as_secs_f64(), output: collected.output, @@ -862,28 +877,54 @@ impl OutputState { } async fn collect_until( + &self, + cursor: OutputCursor, + deadline: tokio::time::Instant, + max_output_chars: usize, + output_tx: Option<&mpsc::Sender>, + ) -> CollectedOutput { + self.collect_until_interruptible(cursor, deadline, max_output_chars, output_tx, None) + .await + } + + async fn collect_until_interruptible( &self, mut cursor: OutputCursor, deadline: tokio::time::Instant, max_output_chars: usize, output_tx: Option<&mpsc::Sender>, + wait_interrupt: Option<&tokio_util::sync::CancellationToken>, ) -> CollectedOutput { let mut sink = HeadTailText::new(max_output_chars); let initial_output_chars = cursor.observed_output_chars; - loop { + let (closed, wait_interrupted) = loop { + // Register before draining so output/exit notifications cannot be + // lost between inspecting the buffer and going to sleep. + let notified = self.notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + let interrupted = wait_interrupt.is_some_and(|token| token.is_cancelled()); let closed = self .drain_since_with_output(&mut cursor, &mut sink, output_tx) .await; - if closed || tokio::time::Instant::now() >= deadline { - break; + if closed || interrupted || tokio::time::Instant::now() >= deadline { + // A fully drained process exit wins over a simultaneous yield. + break (closed, interrupted && !closed); } tokio::select! { - _ = self.notify.notified() => {} - _ = tokio::time::sleep_until(deadline) => break, + _ = &mut notified => {} + _ = tokio::time::sleep_until(deadline) => {} + _ = async { + match wait_interrupt { + Some(token) => token.cancelled().await, + None => std::future::pending::<()>().await, + } + } => {} } - } + // Every wake, including interruption/timeout, gets a final drain. + }; let original_output_chars = cursor .observed_output_chars @@ -892,6 +933,8 @@ impl OutputState { output: sink.render(), original_output_chars, cursor, + closed, + wait_interrupted, } } } @@ -966,6 +1009,8 @@ struct CollectedOutput { output: String, original_output_chars: usize, cursor: OutputCursor, + closed: bool, + wait_interrupted: bool, } impl HeadTailText { @@ -1977,6 +2022,7 @@ mod tests { let second = manager .write_stdin(WriteStdinRequest { + wait_interrupt: None, session_id, chars: String::new(), append_enter: false, @@ -2125,6 +2171,7 @@ mod tests { let second = manager .write_stdin(WriteStdinRequest { + wait_interrupt: None, session_id, chars: String::new(), append_enter: false, @@ -2140,6 +2187,7 @@ mod tests { let missing = manager .write_stdin(WriteStdinRequest { + wait_interrupt: None, session_id, chars: String::new(), append_enter: false, @@ -2178,6 +2226,7 @@ mod tests { let second = manager .write_stdin(WriteStdinRequest { + wait_interrupt: None, session_id, chars: "hello".to_string(), append_enter: true, @@ -2228,6 +2277,7 @@ mod tests { let poll = manager .write_stdin(WriteStdinRequest { + wait_interrupt: None, session_id, chars: String::new(), append_enter: false, @@ -2691,6 +2741,7 @@ print("parent_exit", flush=True)"#; let poll = manager .write_stdin(WriteStdinRequest { + wait_interrupt: None, session_id, chars: String::new(), append_enter: false, @@ -2713,6 +2764,7 @@ print("parent_exit", flush=True)"#; let missing = manager .write_stdin(WriteStdinRequest { + wait_interrupt: None, session_id, chars: String::new(), append_enter: false, @@ -2874,3 +2926,154 @@ print("parent_exit", flush=True)"#; .unwrap_or(0) } } + +#[cfg(test)] +mod wait_interrupt_tests { + use super::*; + use tokio_util::sync::CancellationToken; + + async fn session() -> ( + Arc, + Arc, + mpsc::Receiver>, + ) { + let manager = Arc::new(ExecProcessManager::default()); + let output = Arc::new(OutputState::new(None)); + let (writer, rx) = mpsc::channel(8); + manager.sessions.lock().await.insert( + 42, + ExecSessionEntry { + process: Arc::new(ExecProcess { + output: output.clone(), + writer: Some(writer), + terminator: StdMutex::new(None), + out_of_band_control_action: StdMutex::new(None), + helper_tasks: StdMutex::new(Vec::new()), + pty_handles: Arc::new(StdMutex::new(None)), + #[cfg(windows)] + pipe_job: None, + }), + tty: true, + cursor: OutputCursor { + next_seq: 0, + observed_output_chars: 0, + }, + last_used: tokio::time::Instant::now(), + lifecycle_tx: None, + }, + ); + (manager, output, rx) + } + + fn poll(wait_interrupt: Option) -> WriteStdinRequest { + WriteStdinRequest { + session_id: 42, + chars: String::new(), + append_enter: false, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt, + } + } + + #[tokio::test] + async fn wait_interrupt_returns_partial_output_and_resumes_at_committed_cursor() { + let (manager, output, mut input) = session().await; + output.push_text("before".into()).await; + let token = CancellationToken::new(); + let (tx, mut rx) = mpsc::channel(8); + let waiting_manager = manager.clone(); + let request = poll(Some(token.clone())); + let wait = + tokio::spawn(async move { waiting_manager.write_stdin_streaming(request, tx).await }); + assert_eq!(rx.recv().await.as_deref(), Some("before")); + output.push_text("-tail".into()).await; + token.cancel(); + let response = tokio::time::timeout(Duration::from_secs(2), wait) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(response.output, "before-tail"); + assert_eq!(response.original_output_chars, 11); + assert!(response.wait_interrupted); + assert_eq!(response.session_id, Some(42)); + assert_eq!(response.exit_code, None); + assert_eq!(response.completion, None); + assert!(manager.is_session_active(42).await); + assert!(input.try_recv().is_err()); + assert_eq!(rx.recv().await.as_deref(), Some("-tail")); + assert!(rx.recv().await.is_none()); + + output.push_text("after".into()).await; + output.close(Some(0)).await; + let next = manager.write_stdin(poll(None)).await.unwrap(); + assert_eq!(next.output, "after"); + assert_eq!(next.original_output_chars, 5); + assert!(!next.wait_interrupted); + assert_eq!(next.session_id, None); + assert_eq!(next.exit_code, Some(0)); + assert_eq!( + next.completion.unwrap().status, + ExecSessionCompletionStatus::Exited + ); + assert!(!manager.sessions.lock().await.contains_key(&42)); + } + + #[tokio::test] + async fn wait_interrupt_wakes_without_output() { + let (manager, _, _input) = session().await; + let token = CancellationToken::new(); + let request = poll(Some(token.clone())); + let (response, ()) = tokio::time::timeout(Duration::from_secs(2), async { + tokio::join!(manager.write_stdin(request), async { + tokio::task::yield_now().await; + token.cancel(); + }) + }) + .await + .unwrap(); + let response = response.unwrap(); + assert!(response.wait_interrupted); + assert!(response.output.is_empty()); + assert!(manager.is_session_active(42).await); + } + + #[tokio::test] + async fn wait_interrupt_keeps_submitted_input_exactly_once_including_enter_only() { + for chars in ["answer", ""] { + let (manager, _, mut input) = session().await; + let token = CancellationToken::new(); + token.cancel(); + let mut request = poll(Some(token)); + request.chars = chars.into(); + 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()); + let mut next = poll(None); + next.yield_time_ms = Some(0); + assert!(!manager.write_stdin(next).await.unwrap().wait_interrupted); + assert!(input.try_recv().is_err()); + assert!(manager.is_session_active(42).await); + } + } + + #[tokio::test] + async fn wait_interrupt_does_not_override_drained_process_exit() { + let (manager, output, _input) = session().await; + output.push_text("final".into()).await; + output.close(Some(7)).await; + let token = CancellationToken::new(); + token.cancel(); + let response = manager.write_stdin(poll(Some(token))).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, + ExecSessionCompletionStatus::Exited + ); + } +} diff --git a/src/crates/services/terminal/src/runtime_port.rs b/src/crates/services/terminal/src/runtime_port.rs index bb97e86596..a0fca6369f 100644 --- a/src/crates/services/terminal/src/runtime_port.rs +++ b/src/crates/services/terminal/src/runtime_port.rs @@ -159,6 +159,7 @@ fn local_write_stdin_request(request: TerminalWriteStdinRequest) -> WriteStdinRe append_enter: request.append_enter, yield_time_ms: request.yield_time_ms, max_output_chars: request.max_output_chars, + wait_interrupt: request.wait_interrupt, } } @@ -183,6 +184,7 @@ fn terminal_exec_command_response(response: ExecCommandResponse) -> TerminalExec session_id: response.session_id, exit_code: response.exit_code, original_output_chars: response.original_output_chars, + wait_interrupted: response.wait_interrupted, completion: response.completion.map(terminal_completion), } } @@ -261,6 +263,69 @@ mod tests { TerminalExecSessionCompletionStatus, TerminalPort, TerminalSendStdinRequest, }; + #[tokio::test] + #[cfg(unix)] + async fn write_stdin_wait_interrupt_preserves_live_pty_and_submitted_input() { + use openbitfun_runtime_ports::TerminalWriteStdinRequest; + 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 initial = port.exec_command(TerminalExecCommandRequest { + 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, + lifecycle_sink: None, output_sink: None, + }).await.unwrap(); + let session_id = initial.session_id.unwrap(); + let token = CancellationToken::new(); + let (tx, mut rx) = tokio::sync::mpsc::channel(8); + let request = TerminalWriteStdinRequest { + session_id, + chars: "one".into(), + append_enter: true, + yield_time_ms: Some(600_000), + max_output_chars: None, + wait_interrupt: Some(token.clone()), + }; + let (response, ()) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(port.write_stdin_streaming(request, tx), async { + let mut output = String::new(); + while !output.contains("first:one") { + output.push_str(&rx.recv().await.unwrap()); + } + token.cancel(); + }) + }) + .await + .unwrap(); + let response = response.unwrap(); + assert!(response.wait_interrupted); + assert!(response.output.contains("first:one")); + assert_eq!(response.session_id, Some(session_id)); + assert_eq!(response.exit_code, None); + assert!(manager.is_session_active(session_id).await); + + let last = port + .write_stdin(TerminalWriteStdinRequest { + session_id, + chars: "two".into(), + append_enter: true, + yield_time_ms: Some(5_000), + max_output_chars: None, + wait_interrupt: None, + }) + .await + .unwrap(); + assert!(!last.wait_interrupted); + assert!(last.output.contains("second:two")); + assert!(!last.output.contains("first:one")); + assert_eq!(last.exit_code, Some(0)); + assert_eq!(last.session_id, None); + } + #[test] fn terminal_runtime_port_reports_terminal_capability() { let port = TerminalRuntimePort::default();