From ae26978a7fad45db48c5648db144a0244250e403 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 17:57:09 -0500 Subject: [PATCH 01/11] feat(session): support kiro-cli v3 engine and Kiro workflows over ACP All changes are opt-in; with the new keys unset behaviour is unchanged. - [agent] session_new_meta: table sent verbatim as `_meta` in session/new (e.g. kiro.settings.workflows.enabled = true). - [pool] strict_default_config_options (default false): after each session/set_config_option compare the returned currentValue with the requested value and fail session creation on a mismatch or error. Responses without that option and name aliases are accepted. - With workflows enabled, drop session/update frames whose params.sessionId differs from the served session (workflow step sessions). - With workflows enabled, keep reading after the prompt response and post late workflow output as a follow-up message in the thread ([pool] workflow_tail_quiet_secs=20, workflow_tail_max_secs=900, 0 = off). - docs/kiro-v3.md, config reference and config.toml.example. Refs #1607 Verified on macOS (cargo, workspace): - cargo clippy --workspace -- -D warnings: clean - cargo clippy --workspace --features unified -- -D warnings: clean - cargo test --workspace --no-fail-fast: all pass, including the new tests, except secrets::tests::resolve_exec_nonzero_exit, which fails on macOS without these changes too (it execs /bin/false, which is /usr/bin/false there). - Touched hunks are rustfmt-clean; the repo is not fmt-clean on main, so unrelated files were not reformatted. --- config.toml.example | 12 + crates/openab-core/src/acp/connection.rs | 276 +++++++++++++++++++- crates/openab-core/src/acp/mod.rs | 5 +- crates/openab-core/src/acp/pool.rs | 137 +++++++++- crates/openab-core/src/acp/protocol.rs | 98 +++++++ crates/openab-core/src/adapter.rs | 69 ++++- crates/openab-core/src/config.rs | 126 +++++++++ crates/openab-core/src/dispatch.rs | 1 + crates/openab-core/src/lib.rs | 1 + crates/openab-core/src/workflow_tail.rs | 312 +++++++++++++++++++++++ docs/config-reference.md | 4 + docs/kiro-v3.md | 99 +++++++ docs/kiro.md | 2 + src/main.rs | 45 ++-- 14 files changed, 1162 insertions(+), 25 deletions(-) create mode 100644 crates/openab-core/src/workflow_tail.rs create mode 100644 docs/kiro-v3.md diff --git a/config.toml.example b/config.toml.example index c3d1df7b2..428576127 100644 --- a/config.toml.example +++ b/config.toml.example @@ -207,6 +207,12 @@ working_dir = "/home/agent" # [pool] # default_config_options = { mode = "agent-full-access" } +# [agent] +# kiro-cli v3 engine with Kiro workflows (see docs/kiro-v3.md): +# command = "kiro-cli" +# args = ["acp", "--agent-engine=v3"] +# session_new_meta = { kiro = { settings = { workflows = { enabled = true } } } } + # [agent] # command = "gemini" # args = ["--acp"] @@ -271,6 +277,12 @@ session_ttl_hours = 24 # Grace (sec) past prompt_hard_timeout_secs before a hung in-flight session is # force-evicted from the pool. Default: 120. # hung_grace_secs = 120 +# kiro-cli v3 (see docs/kiro-v3.md): select the agent mode and fail fast when it is missing. +# default_config_options = { mode = "openab-bot" } +# strict_default_config_options = true +# Late Kiro workflow output relay (needs [agent].session_new_meta below). +# workflow_tail_quiet_secs = 20 +# workflow_tail_max_secs = 900 [markdown] tables = "code" # "code" (default) | "bullets" | "off" diff --git a/crates/openab-core/src/acp/connection.rs b/crates/openab-core/src/acp/connection.rs index d98a07713..743df9ed9 100644 --- a/crates/openab-core/src/acp/connection.rs +++ b/crates/openab-core/src/acp/connection.rs @@ -239,6 +239,48 @@ where } } +/// Params for `session/new`. `_meta` is added only when configured, so the +/// default request is byte-identical to the legacy one. +pub(crate) fn build_session_new_params(cwd: &str, meta: Option<&Value>) -> Value { + let mut params = json!({"cwd": cwd, "mcpServers": []}); + if let Some(meta) = meta { + params["_meta"] = meta.clone(); + } + params +} + +/// Check that `session/set_config_option` really applied `requested` for +/// `config_id`, using the option list the agent returned. +/// +/// Lenient where the response is silent: no option with that id (or an empty +/// list) is accepted. A different `currentValue` is accepted only when the +/// returned option lists a value whose display `name` equals `requested` and +/// whose `value` is the current one (agents that normalize aliases). +pub(crate) fn verify_config_option_applied( + options: &[ConfigOption], + config_id: &str, + requested: &str, +) -> std::result::Result<(), String> { + let Some(opt) = options.iter().find(|o| o.id == config_id) else { + return Ok(()); + }; + if opt.current_value == requested { + return Ok(()); + } + if opt + .options + .iter() + .any(|v| v.name == requested && v.value == opt.current_value) + { + return Ok(()); + } + Err(format!( + "default_config_options `{config_id}` = `{requested}` was not applied: the agent reports `{}`. \ + Check that the value exists for this agent (for kiro v3, that `~/.kiro/agents/{requested}.md` is present in the bot's HOME).", + opt.current_value + )) +} + /// Reader loop body: reads JSON-RPC messages from `reader`, auto-replies /// `session/request_permission` via `writer`, resolves pending responses, /// and forwards notifications + stale id-bearing messages to the active @@ -604,8 +646,17 @@ impl AcpConnection { } pub async fn session_new(&mut self, cwd: &str) -> Result { + self.session_new_with_meta(cwd, None).await + } + + /// `session/new` with an optional `_meta` object (`[agent].session_new_meta`). + pub async fn session_new_with_meta( + &mut self, + cwd: &str, + meta: Option<&Value>, + ) -> Result { let resp = self - .send_request("session/new", Some(json!({"cwd": cwd, "mcpServers": []}))) + .send_request("session/new", Some(build_session_new_params(cwd, meta))) .await?; let session_id = resp @@ -770,6 +821,16 @@ impl AcpConnection { Ok((rx, id)) } + /// Like [`Self::prompt_done`] but leaves the notify subscriber installed so + /// the caller can keep reading late frames from the receiver returned by + /// `session_prompt` (Kiro workflow output). The next `session_prompt` + /// replaces the subscriber, which closes the old receiver. + pub async fn prompt_done_keep_subscriber(&mut self) { + self.activity.touch(); + self.activity.set_in_flight(false); + self.last_active = Instant::now(); + } + /// Call after prompt streaming is done to clean up subscriber. pub async fn prompt_done(&mut self) { *self.notify_tx.lock().await = None; @@ -1344,3 +1405,216 @@ mod reader_loop_tests { assert!(!activity.in_flight()); } } + +/// `sh -c` stand-in for an ACP agent, with fixed request ids +/// (initialize = 1, session/new = 2, first set_config_option = 3, and the +/// slash-command fallback prompt = 4), shared with the pool tests. +#[cfg(all(test, unix))] +pub(crate) mod mock_agent { + /// `set_cfg_reply` is the full JSON-RPC line answering the first + /// `session/set_config_option` (it must contain no single quote). When + /// `require_meta` is set, `session/new` fails unless the request carries + /// `"workflows":{"enabled":true}`. + pub(crate) fn script(set_cfg_reply: &str, require_meta: bool) -> String { + let new_ok = r#"echo '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"s-1"}}'"#; + let new_err = + r#"echo '{"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"missing _meta"}}'"#; + let session_new = if require_meta { + format!( + r#"case "$l" in *'"workflows":{{"enabled":true}}'*) {new_ok};; *) {new_err};; esac"# + ) + } else { + new_ok.to_string() + }; + format!( + r#"while IFS= read -r l; do +case "$l" in +*'"method":"initialize"'*) echo '{{"jsonrpc":"2.0","id":1,"result":{{"agentInfo":{{"name":"mock"}}}}}}';; +*'"method":"session/new"'*) {session_new};; +*'"method":"session/set_config_option"'*) echo '{set_cfg_reply}';; +*'"method":"session/prompt"'*) echo '{{"jsonrpc":"2.0","id":4,"error":{{"code":-32000,"message":"unsupported"}}}}';; +esac +done"# + ) + } + + pub(crate) fn args(script: String) -> Vec { + vec!["-c".to_string(), script] + } + + /// A `set_config_option` reply whose `mode` option reports `current`. + pub(crate) fn mode_reply(current: &str) -> String { + format!( + r#"{{"jsonrpc":"2.0","id":3,"result":{{"configOptions":[{{"type":"select","id":"mode","name":"Mode","currentValue":"{current}","options":[{{"value":"vibe","name":"Default"}},{{"value":"e2e","name":"e2e"}}]}}]}}}}"# + ) + } +} + +#[cfg(test)] +mod workflow_meta_tests { + use super::*; + use crate::acp::protocol::ConfigOptionValue; + + fn opt(id: &str, current: &str, values: &[(&str, &str)]) -> ConfigOption { + ConfigOption { + id: id.into(), + name: id.into(), + description: None, + category: None, + option_type: "select".into(), + current_value: current.into(), + options: values + .iter() + .map(|(value, name)| ConfigOptionValue { + value: (*value).into(), + name: (*name).into(), + description: None, + }) + .collect(), + } + } + + #[test] + fn session_new_params_without_meta_match_legacy_shape() { + assert_eq!( + build_session_new_params("/w", None), + json!({"cwd": "/w", "mcpServers": []}) + ); + } + + #[test] + fn session_new_params_with_meta_carry_underscore_meta() { + let meta = json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); + let params = build_session_new_params("/w", Some(&meta)); + assert_eq!( + params["_meta"]["kiro"]["settings"]["workflows"]["enabled"], + true + ); + assert_eq!(params["cwd"], "/w"); + assert_eq!(params["mcpServers"], json!([])); + } + + #[test] + fn verify_accepts_equal_value() { + let o = [opt("mode", "e2e", &[("vibe", "Default"), ("e2e", "e2e")])]; + assert!(verify_config_option_applied(&o, "mode", "e2e").is_ok()); + } + + #[test] + fn verify_rejects_different_value_with_clear_error() { + let o = [opt("mode", "vibe", &[("vibe", "Default"), ("e2e", "e2e")])]; + let err = verify_config_option_applied(&o, "mode", "e2e").unwrap_err(); + assert!(err.contains("`mode`"), "{err}"); + assert!(err.contains("`e2e`"), "{err}"); + assert!(err.contains("`vibe`"), "{err}"); + assert!(err.contains("was not applied"), "{err}"); + } + + #[test] + fn verify_accepts_missing_option_or_empty_list() { + assert!(verify_config_option_applied(&[], "mode", "e2e").is_ok()); + let o = [opt("model", "x", &[])]; + assert!(verify_config_option_applied(&o, "mode", "e2e").is_ok()); + } + + #[test] + fn verify_accepts_alias_by_option_name() { + // agy-acp style: the row name is requested, the id is reported. + let o = [opt( + "model", + "gemini-3.8-flash-high", + &[("gemini-3.8-flash-high", "Gemini 3.8 Flash (High)")], + )]; + assert!(verify_config_option_applied(&o, "model", "Gemini 3.8 Flash (High)").is_ok()); + assert!(verify_config_option_applied(&o, "model", "something-else").is_err()); + } + + #[test] + fn verify_ignores_kiro_v2_agent_option_for_mode_key() { + // kiro v2 reports modes under id `agent`, so `mode` is simply absent. + let o = [opt("agent", "kiro_default", &[("kiro_default", "default")])]; + assert!(verify_config_option_applied(&o, "mode", "openab-bot").is_ok()); + } + + /// Step sessions ask for permission too; the answer goes out by request id + /// regardless of the `sessionId` the request carries. + #[tokio::test] + async fn permission_request_from_another_session_is_still_answered() { + use tokio::io::{duplex, AsyncWriteExt}; + let (mut agent_out, agent_out_r) = duplex(8 * 1024); + let (agent_in_w, agent_in_r) = duplex(8 * 1024); + let pending = Arc::new(Mutex::new(HashMap::new())); + let notify_tx = Arc::new(Mutex::new(None)); + let handle = tokio::spawn(run_reader_loop( + agent_out_r, + Arc::new(Mutex::new(agent_in_w)), + pending, + notify_tx, + )); + let req = json!({"jsonrpc": "2.0", "id": 9, "method": "session/request_permission", + "params": {"sessionId": "step-session", + "toolCall": {"title": "run"}, + "options": [{"optionId": "ao", "kind": "allow_once"}, + {"optionId": "aa", "kind": "allow_always"}]}}); + agent_out + .write_all(format!("{req}\n").as_bytes()) + .await + .unwrap(); + agent_out.flush().await.unwrap(); + let mut line = String::new(); + tokio::time::timeout( + std::time::Duration::from_secs(2), + BufReader::new(agent_in_r).read_line(&mut line), + ) + .await + .expect("permission request must be answered") + .unwrap(); + let reply: Value = serde_json::from_str(line.trim()).unwrap(); + assert_eq!(reply["id"], 9); + assert_eq!(reply["result"]["outcome"]["optionId"], "aa"); + drop(agent_out); + handle.await.unwrap(); + } + + #[cfg(unix)] + async fn spawn_mock(script: String) -> AcpConnection { + let mut conn = AcpConnection::spawn( + "sh", + &mock_agent::args(script), + "/tmp", + &HashMap::new(), + &[], + ) + .await + .expect("spawn mock agent"); + conn.initialize().await.expect("initialize"); + conn + } + + #[cfg(unix)] + #[tokio::test] + async fn session_new_with_meta_sends_underscore_meta() { + let script = mock_agent::script(&mock_agent::mode_reply("vibe"), true); + let meta = json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); + let mut conn = spawn_mock(script.clone()).await; + assert_eq!( + conn.session_new_with_meta("/tmp", Some(&meta)) + .await + .unwrap(), + "s-1" + ); + // Without meta the mock (which requires it) refuses: nothing is sent. + let mut conn = spawn_mock(script).await; + assert!(conn.session_new("/tmp").await.is_err()); + } + + #[cfg(unix)] + #[tokio::test] + async fn set_config_option_returns_agent_reported_value() { + let script = mock_agent::script(&mock_agent::mode_reply("vibe"), false); + let mut conn = spawn_mock(script).await; + conn.session_new("/tmp").await.unwrap(); + let opts = conn.set_config_option("mode", "e2e").await.unwrap(); + assert!(verify_config_option_applied(&opts, "mode", "e2e").is_err()); + } +} diff --git a/crates/openab-core/src/acp/mod.rs b/crates/openab-core/src/acp/mod.rs index 7919c6d3d..0972ae731 100644 --- a/crates/openab-core/src/acp/mod.rs +++ b/crates/openab-core/src/acp/mod.rs @@ -6,4 +6,7 @@ pub mod protocol; pub use connection::ContentBlock; pub use pool::SessionPool; -pub use protocol::{classify_notification, parse_turn_result, AcpEvent, TurnResult}; +pub use protocol::{ + classify_notification, classify_workflow_signal, is_foreign_session_update, parse_turn_result, + AcpEvent, TurnResult, WorkflowSignal, +}; diff --git a/crates/openab-core/src/acp/pool.rs b/crates/openab-core/src/acp/pool.rs index a3a28f87c..7db163da3 100644 --- a/crates/openab-core/src/acp/pool.rs +++ b/crates/openab-core/src/acp/pool.rs @@ -63,6 +63,8 @@ pub struct SessionPool { mapping_path: PathBuf, meta_path: PathBuf, default_config_options: HashMap, + /// Fail session creation when a default config option is not applied. + strict_default_config_options: bool, #[cfg(feature = "acp-mcp")] session_registrar: Option>, #[cfg(feature = "acp-mcp")] @@ -334,6 +336,7 @@ impl SessionPool { mapping_path, meta_path, default_config_options, + strict_default_config_options: false, #[cfg(feature = "acp-mcp")] session_registrar: None, #[cfg(feature = "acp-mcp")] @@ -341,6 +344,18 @@ impl SessionPool { } } + /// Verify `default_config_options` after `session/set_config_option` + /// (`[pool] strict_default_config_options`). Default: off. + pub fn with_strict_default_config_options(mut self, strict: bool) -> Self { + self.strict_default_config_options = strict; + self + } + + /// True when `[agent].session_new_meta` enables Kiro workflows. + pub fn workflows_enabled(&self) -> bool { + crate::config::meta_enables_workflows(self.config.session_new_meta.as_ref()) + } + /// Wire the facade session-token registrar + facade URL, set by the root /// when `[mcp]` is running. With both present the pool does its half: mints /// one token per session, injects it as `OPENAB_SESSION_TOKEN` in the agent @@ -627,12 +642,30 @@ impl SessionPool { } if !resumed { - new_conn.session_new(&effective_workdir).await?; + new_conn + .session_new_with_meta(&effective_workdir, self.config.session_new_meta.as_ref()) + .await?; // Apply default config options (e.g. mode=bypass, model=swe-1-6) for (config_id, value) in &self.default_config_options { - if let Err(e) = new_conn.set_config_option(config_id, value).await { - warn!(config_id, value, error = %e, "failed to set default config option"); + match new_conn.set_config_option(config_id, value).await { + Ok(opts) => { + if self.strict_default_config_options { + // Returning drops `new_conn`, which kills the agent process group. + super::connection::verify_config_option_applied( + &opts, config_id, value, + ) + .map_err(|msg| anyhow!(msg))?; + } + } + Err(e) => { + if self.strict_default_config_options { + return Err(anyhow!( + "failed to set default config option `{config_id}`: {e}" + )); + } + warn!(config_id, value, error = %e, "failed to set default config option"); + } } } @@ -1559,3 +1592,101 @@ mod tests { ); } } + +#[cfg(all(test, unix))] +mod config_option_tests { + use super::SessionPool; + use crate::acp::connection::mock_agent; + use crate::config::AgentConfig; + use std::collections::HashMap; + + fn pool( + dir: &std::path::Path, + set_cfg_reply: &str, + require_meta: bool, + meta: Option, + strict: bool, + ) -> SessionPool { + let agent = AgentConfig { + command: "sh".into(), + args: mock_agent::args(mock_agent::script(set_cfg_reply, require_meta)), + working_dir: "/tmp".into(), + env: HashMap::new(), + inherit_env: vec![], + command_explicit: true, + session_new_meta: meta, + }; + SessionPool::new_in( + agent, + 1, + 60, + HashMap::from([("mode".to_string(), "e2e".to_string())]), + dir.to_path_buf(), + ) + .with_strict_default_config_options(strict) + } + + #[tokio::test] + async fn mismatch_is_ignored_by_default() { + let dir = tempfile::tempdir().unwrap(); + let p = pool(dir.path(), &mock_agent::mode_reply("vibe"), false, None, false); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn strict_mismatch_fails_session_creation() { + let dir = tempfile::tempdir().unwrap(); + let p = pool(dir.path(), &mock_agent::mode_reply("vibe"), false, None, true); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("was not applied"), "{err}"); + assert!(err.contains("`e2e`") && err.contains("`vibe`"), "{err}"); + assert!(p.state.read().await.active.is_empty()); + } + + #[tokio::test] + async fn strict_match_succeeds() { + let dir = tempfile::tempdir().unwrap(); + let p = pool(dir.path(), &mock_agent::mode_reply("e2e"), false, None, true); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn strict_response_without_options_keeps_legacy_behaviour() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; + let p = pool(dir.path(), reply, false, None, true); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn strict_error_response_fails_session_creation() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; + let p = pool(dir.path(), reply, false, None, true); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("failed to set default config option"), "{err}"); + } + + #[tokio::test] + async fn non_strict_error_response_is_only_a_warning() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; + let p = pool(dir.path(), reply, false, None, false); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn session_new_meta_is_sent_when_configured() { + let dir = tempfile::tempdir().unwrap(); + let meta = serde_json::json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); + let reply = mock_agent::mode_reply("e2e"); + // The mock refuses session/new without the meta. + let with = pool(dir.path(), &reply, true, Some(meta), true); + assert!(with.workflows_enabled()); + assert!(with.get_or_create("t", None).await.is_ok()); + let dir2 = tempfile::tempdir().unwrap(); + let without = pool(dir2.path(), &reply, true, None, true); + assert!(!without.workflows_enabled()); + assert!(without.get_or_create("t", None).await.is_err()); + } +} diff --git a/crates/openab-core/src/acp/protocol.rs b/crates/openab-core/src/acp/protocol.rs index 456245cae..0c6f36fc0 100644 --- a/crates/openab-core/src/acp/protocol.rs +++ b/crates/openab-core/src/acp/protocol.rs @@ -409,6 +409,50 @@ pub enum AcpEvent { Status, } +/// True only for a `session/update` notification that carries a string +/// `params.sessionId` different from `expected_session_id`. Such frames come +/// from another session of the same agent process (e.g. Kiro workflow step +/// sessions). Frames without a `sessionId`, other methods and responses are +/// never foreign. +pub fn is_foreign_session_update(msg: &JsonRpcMessage, expected_session_id: &str) -> bool { + if msg.id.is_some() || msg.method.as_deref() != Some("session/update") { + return false; + } + msg.params + .as_ref() + .and_then(|p| p.get("sessionId")) + .and_then(Value::as_str) + .is_some_and(|sid| sid != expected_session_id) +} + +/// Kiro workflow lifecycle signal relevant to the served (parent) session. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WorkflowSignal { + RunStart { workflow_id: String }, + RunComplete { workflow_id: String }, +} + +/// Classify `_kiro/workflow/run_start` (only when its `parentSessionId` is +/// `parent_session_id`) and `_kiro/workflow/run_complete` notifications. +pub fn classify_workflow_signal( + msg: &JsonRpcMessage, + parent_session_id: &str, +) -> Option { + if msg.id.is_some() { + return None; + } + let params = msg.params.as_ref()?; + let workflow_id = params.get("workflowId")?.as_str()?.to_string(); + match msg.method.as_deref()? { + "_kiro/workflow/run_start" => { + let parent = params.get("parentSessionId")?.as_str()?; + (parent == parent_session_id).then_some(WorkflowSignal::RunStart { workflow_id }) + } + "_kiro/workflow/run_complete" => Some(WorkflowSignal::RunComplete { workflow_id }), + _ => None, + } +} + pub fn classify_notification(msg: &JsonRpcMessage) -> Option { let params = msg.params.as_ref()?; let update = params.get("update")?; @@ -476,6 +520,60 @@ mod tests { use super::*; use serde_json::json; + fn msg(v: Value) -> JsonRpcMessage { + serde_json::from_value(v).unwrap() + } + + fn chunk(session_id: Option<&str>, text: &str) -> JsonRpcMessage { + let mut params = json!({"update": {"sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": text}}}); + if let Some(sid) = session_id { + params["sessionId"] = json!(sid); + } + msg(json!({"jsonrpc": "2.0", "method": "session/update", "params": params})) + } + + #[test] + fn foreign_session_update_detection() { + assert!(!is_foreign_session_update(&chunk(Some("p"), "x"), "p")); + assert!(is_foreign_session_update(&chunk(Some("step"), "x"), "p")); + assert!(!is_foreign_session_update(&chunk(None, "x"), "p")); + let other_method = msg(json!({"method": "_kiro/other", + "params": {"sessionId": "step"}})); + assert!(!is_foreign_session_update(&other_method, "p")); + let response = msg(json!({"id": 3, "result": {"sessionId": "step"}})); + assert!(!is_foreign_session_update(&response, "p")); + let non_string = msg(json!({"method": "session/update", + "params": {"sessionId": 7, "update": {}}})); + assert!(!is_foreign_session_update(&non_string, "p")); + } + + #[test] + fn workflow_signal_classification() { + let start = msg( + json!({"jsonrpc": "2.0", "method": "_kiro/workflow/run_start", + "params": {"workflowId": "wf_1", "workflowName": "w", "parentSessionId": "p"}}), + ); + assert_eq!( + classify_workflow_signal(&start, "p"), + Some(WorkflowSignal::RunStart { + workflow_id: "wf_1".into() + }) + ); + assert_eq!(classify_workflow_signal(&start, "other"), None); + let done = msg(json!({"method": "_kiro/workflow/run_complete", + "params": {"workflowId": "wf_1", "status": "completed"}})); + assert_eq!( + classify_workflow_signal(&done, "p"), + Some(WorkflowSignal::RunComplete { + workflow_id: "wf_1".into() + }) + ); + let unrelated = msg(json!({"method": "_kiro/workflow/node_start", + "params": {"workflowId": "wf_1"}})); + assert_eq!(classify_workflow_signal(&unrelated, "p"), None); + } + #[test] fn json_rpc_ids_preserve_all_supported_integer_ranges() { for value in [0, i64::MAX as u64, (i64::MAX as u64) + 1, u64::MAX] { diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 7d9841070..3c7b7ecee 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -5,7 +5,8 @@ use std::sync::Arc; use tracing::{error, warn}; use crate::acp::{ - classify_notification, parse_turn_result, AcpEvent, ContentBlock, SessionPool, TurnResult, + classify_notification, is_foreign_session_update, parse_turn_result, AcpEvent, ContentBlock, + SessionPool, TurnResult, }; use crate::config::{ReactionsConfig, ToolDisplay}; use crate::error_display::{format_coded_error, format_user_error}; @@ -490,6 +491,10 @@ pub struct AdapterRouter { /// [`AdapterRouter::with_trust`]; empty default = deny-all per platform /// (only consulted by paths wired to the gate — currently the gateway path). trust: crate::trust::PlatformTrustConfigs, + /// Set only when `[agent].session_new_meta` enables Kiro workflows. Turns on + /// the step-session frame filter and, unless `tail_max` is zero, the relay + /// of late workflow output. `None` = legacy behaviour. + workflow_relay: Option, } impl AdapterRouter { @@ -520,9 +525,18 @@ impl AdapterRouter { workspace_aliases, bot_home, trust: crate::trust::PlatformTrustConfigs::default(), + workflow_relay: None, } } + /// Enable Kiro workflow handling (builder style, before `Arc`-wrapping): + /// drop `session/update` frames of other sessions and relay late workflow + /// output. Only call when workflows are enabled in `session/new` meta. + pub fn with_workflow_relay(mut self, cfg: crate::workflow_tail::WorkflowRelayConfig) -> Self { + self.workflow_relay = Some(cfg); + self + } + /// Attach the per-platform trust registry (builder style, before `Arc`-wrapping). /// Keeps `new()`'s signature stable across its many call sites. pub fn with_trust(mut self, trust: crate::trust::PlatformTrustConfigs) -> Self { @@ -759,6 +773,7 @@ impl AdapterRouter { let platform_is_acp = thread_channel.platform == "acp"; let prompt_hard_timeout = self.prompt_hard_timeout; let liveness_check_interval = self.liveness_check_interval; + let relay = self.workflow_relay; self.pool .with_connection(thread_key, |conn| { @@ -768,6 +783,8 @@ impl AdapterRouter { conn.session_reset = false; let (mut rx, request_id) = conn.session_prompt(content_blocks).await?; + let parent_sid = conn.acp_session_id.clone(); + let mut wf_state = crate::workflow_tail::TurnWorkflowState::default(); if assistant_status { let _ = adapter.set_status(&thread_channel, "Thinking…").await; } else { @@ -897,6 +914,15 @@ impl AdapterRouter { break; } + if let (Some(_), Some(sid)) = (relay, parent_sid.as_deref()) { + // Workflow step sessions share this agent process; their + // frames must not reach the parent's reply. + if is_foreign_session_update(¬ification, sid) { + continue; + } + wf_state.observe(¬ification, sid); + } + if let Some(event) = classify_notification(¬ification) { match event { AcpEvent::Text(t) => { @@ -1039,7 +1065,21 @@ impl AdapterRouter { } } - conn.prompt_done().await; + // Late workflow output: keep the subscriber and hand the + // receiver to a detached tail after the reply is delivered. + let tail_cfg = relay.filter(|c| { + !c.tail_max.is_zero() + && response_error.is_none() + && !platform_is_acp + && wf_state.armed() + }); + let tail_rx = if tail_cfg.is_some() { + conn.prompt_done_keep_subscriber().await; + Some(rx) + } else { + conn.prompt_done().await; + None + }; // Stop the cosmetic edit loop and let any in-flight edit // finish before the authoritative finalize write, so in the // normal case a stale preview does not overwrite it. Dropping @@ -1303,6 +1343,31 @@ impl AdapterRouter { } } + if let (Some(cfg), Some(rx), Some(sid)) = (tail_cfg, tail_rx, parent_sid) { + let tail_adapter = adapter.clone(); + let tail_channel = thread_channel.clone(); + tokio::spawn(crate::workflow_tail::run_tail( + rx, + sid, + wf_state.into_open(), + cfg, + move |text| { + let adapter = tail_adapter.clone(); + let channel = tail_channel.clone(); + async move { + let text = format!("_Workflow update:_\n\n{text}"); + for chunk in format::split_message(&text, message_limit) { + if let Err(e) = adapter.send_message(&channel, &chunk).await + { + warn!(error = ?e, "workflow tail delivery failed"); + break; + } + } + } + }, + )); + } + if delivery_failed { Err(anyhow::anyhow!( "streaming finalization had delivery failures; user view is incomplete" diff --git a/crates/openab-core/src/config.rs b/crates/openab-core/src/config.rs index fdd89dcb3..e9062eb3f 100644 --- a/crates/openab-core/src/config.rs +++ b/crates/openab-core/src/config.rs @@ -1668,6 +1668,7 @@ struct AgentConfigRaw { working_dir: String, env: HashMap, inherit_env: Vec, + session_new_meta: Option, } impl Default for AgentConfigRaw { @@ -1678,6 +1679,7 @@ impl Default for AgentConfigRaw { working_dir: default_working_dir(), env: HashMap::new(), inherit_env: Vec::new(), + session_new_meta: None, } } } @@ -1691,6 +1693,18 @@ pub struct AgentConfig { pub inherit_env: Vec, /// Whether the command was explicitly set in config (vs defaulted from env/fallback). pub command_explicit: bool, + /// Optional `_meta` object sent verbatim in every `session/new` request. + /// Default: none (nothing is added to the request). Example for kiro-cli v3: + /// `{ kiro = { settings = { workflows = { enabled = true } } } }`. + pub session_new_meta: Option, +} + +/// True when `meta` (the `[agent].session_new_meta` table) switches on Kiro +/// workflows (`kiro.settings.workflows.enabled = true`). +pub fn meta_enables_workflows(meta: Option<&serde_json::Value>) -> bool { + meta.and_then(|m| m.pointer("/kiro/settings/workflows/enabled")) + .and_then(serde_json::Value::as_bool) + == Some(true) } impl Default for AgentConfig { @@ -1702,6 +1716,7 @@ impl Default for AgentConfig { env: HashMap::new(), inherit_env: Vec::new(), command_explicit: false, + session_new_meta: None, } } } @@ -1721,6 +1736,13 @@ impl<'de> serde::Deserialize<'de> for AgentConfig { (true, None) => Vec::new(), // command set, args omitted → empty (false, None) => default_agent_args(), // neither set → env var }; + if let Some(meta) = &raw.session_new_meta { + if !meta.is_object() { + return Err(serde::de::Error::custom( + "[agent].session_new_meta must be a table", + )); + } + } Ok(AgentConfig { command, args, @@ -1728,6 +1750,7 @@ impl<'de> serde::Deserialize<'de> for AgentConfig { env: raw.env, inherit_env: raw.inherit_env, command_explicit: cmd_explicit, + session_new_meta: raw.session_new_meta, }) } } @@ -1762,6 +1785,28 @@ pub struct PoolConfig { /// Sent via `session/set_config_option` after each `session/new`. #[serde(default)] pub default_config_options: HashMap, + /// When true, `default_config_options` entries are verified: after each + /// `session/set_config_option` the returned `currentValue` must equal the + /// requested value (or be the value behind a matching option name), else + /// session creation fails. Default false (legacy: mismatches are ignored). + #[serde(default)] + pub strict_default_config_options: bool, + /// Seconds without agent output after which late workflow output is + /// flushed to the thread (only with `[agent].session_new_meta` enabling + /// Kiro workflows). Must be > 0 when `workflow_tail_max_secs` > 0. + #[serde(default = "default_workflow_tail_quiet_secs")] + pub workflow_tail_quiet_secs: u64, + /// Hard cap (seconds, from the prompt response) on how long openab keeps + /// relaying late workflow output. 0 disables the relay. + #[serde(default = "default_workflow_tail_max_secs")] + pub workflow_tail_max_secs: u64, +} + +fn default_workflow_tail_quiet_secs() -> u64 { + 20 +} +fn default_workflow_tail_max_secs() -> u64 { + 900 } #[derive(Debug, Clone, Deserialize)] @@ -1994,6 +2039,9 @@ impl Default for PoolConfig { liveness_check_secs: default_liveness_check_secs(), hung_grace_secs: default_hung_grace_secs(), default_config_options: HashMap::new(), + strict_default_config_options: false, + workflow_tail_quiet_secs: default_workflow_tail_quiet_secs(), + workflow_tail_max_secs: default_workflow_tail_max_secs(), } } } @@ -2307,10 +2355,16 @@ fn parse_config_inner(expanded: &str, source: &str) -> anyhow::Result { env: config.agent.env.clone(), inherit_env: config.agent.inherit_env.clone(), command_explicit: true, // synthesized counts as explicit + session_new_meta: config.agent.session_new_meta.clone(), }; } } + anyhow::ensure!( + config.pool.workflow_tail_max_secs == 0 || config.pool.workflow_tail_quiet_secs > 0, + "pool.workflow_tail_quiet_secs must be > 0 when pool.workflow_tail_max_secs > 0" + ); + // Validate max_buffered_messages > 0 (tokio::sync::mpsc::channel panics on 0) // and max_batch_tokens > 0 (otherwise the consumer's token-cap check forces every // batch to size 1 — functionally per-message via a confusing path). @@ -2502,6 +2556,78 @@ fn default_ambient_context_flushes() -> usize { mod tests { use super::*; + const DISCORD_STUB: &str = "[discord]\nbot_token = \"x\"\n"; + + #[test] + fn session_new_meta_defaults_to_none() { + let cfg = parse_config_str(DISCORD_STUB, "test").unwrap(); + assert!(cfg.agent.session_new_meta.is_none()); + assert!(!meta_enables_workflows(cfg.agent.session_new_meta.as_ref())); + } + + #[test] + fn session_new_meta_table_parses() { + let toml_str = format!( + "{DISCORD_STUB}[agent]\ncommand = \"kiro-cli\"\n\ + session_new_meta = {{ kiro = {{ settings = {{ workflows = {{ enabled = true }} }} }} }}\n" + ); + let cfg = parse_config_str(&toml_str, "test").unwrap(); + assert_eq!( + cfg.agent.session_new_meta, + Some(serde_json::json!({"kiro": {"settings": {"workflows": {"enabled": true}}}})) + ); + assert!(meta_enables_workflows(cfg.agent.session_new_meta.as_ref())); + } + + #[test] + fn session_new_meta_must_be_a_table() { + let toml_str = format!("{DISCORD_STUB}[agent]\nsession_new_meta = \"x\"\n"); + let err = parse_config_str(&toml_str, "test").unwrap_err(); + assert!(format!("{err:#}").contains("session_new_meta must be a table")); + } + + #[test] + fn meta_enables_workflows_requires_boolean_true() { + use serde_json::json; + assert!(meta_enables_workflows(Some( + &json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}) + ))); + assert!(!meta_enables_workflows(Some( + &json!({"kiro": {"settings": {"workflows": {"enabled": false}}}}) + ))); + assert!(!meta_enables_workflows(Some( + &json!({"kiro": {"settings": {"workflows": {"enabled": "true"}}}}) + ))); + assert!(!meta_enables_workflows(Some(&json!({"other": 1})))); + assert!(!meta_enables_workflows(None)); + } + + #[test] + fn pool_workflow_and_strict_defaults() { + let cfg = parse_config_str(DISCORD_STUB, "test").unwrap(); + assert!(!cfg.pool.strict_default_config_options); + assert_eq!(cfg.pool.workflow_tail_quiet_secs, 20); + assert_eq!(cfg.pool.workflow_tail_max_secs, 900); + let toml_str = format!( + "{DISCORD_STUB}[pool]\nstrict_default_config_options = true\n\ + workflow_tail_quiet_secs = 5\nworkflow_tail_max_secs = 60\n" + ); + let cfg = parse_config_str(&toml_str, "test").unwrap(); + assert!(cfg.pool.strict_default_config_options); + assert_eq!(cfg.pool.workflow_tail_quiet_secs, 5); + assert_eq!(cfg.pool.workflow_tail_max_secs, 60); + } + + #[test] + fn workflow_tail_quiet_zero_is_rejected_unless_tail_disabled() { + let bad = format!("{DISCORD_STUB}[pool]\nworkflow_tail_quiet_secs = 0\n"); + assert!(parse_config_str(&bad, "test").is_err()); + let ok = format!( + "{DISCORD_STUB}[pool]\nworkflow_tail_quiet_secs = 0\nworkflow_tail_max_secs = 0\n" + ); + assert!(parse_config_str(&ok, "test").is_ok()); + } + #[test] fn mcp_facade_absent_by_default() { // Backward compat: no [mcp] section → no facade, no listener. diff --git a/crates/openab-core/src/dispatch.rs b/crates/openab-core/src/dispatch.rs index c3a20d263..d405287db 100644 --- a/crates/openab-core/src/dispatch.rs +++ b/crates/openab-core/src/dispatch.rs @@ -1197,6 +1197,7 @@ mod tests { env: std::collections::HashMap::new(), inherit_env: vec![], command_explicit: true, + session_new_meta: None, }; let pool = Arc::new(SessionPool::new( agent_cfg, diff --git a/crates/openab-core/src/lib.rs b/crates/openab-core/src/lib.rs index 0e61e7cb2..7c226f40c 100644 --- a/crates/openab-core/src/lib.rs +++ b/crates/openab-core/src/lib.rs @@ -27,6 +27,7 @@ pub mod setup; pub mod stt; pub mod timestamp; pub mod trust; +pub mod workflow_tail; #[cfg(feature = "discord")] pub mod discord; diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs new file mode 100644 index 000000000..af5651a66 --- /dev/null +++ b/crates/openab-core/src/workflow_tail.rs @@ -0,0 +1,312 @@ +//! Relay of late Kiro workflow output. +//! +//! With `[agent].session_new_meta` enabling Kiro workflows, `session/prompt` +//! can return before a workflow finishes. The workflow's summary then arrives +//! later as unsolicited `agent_message_chunk` frames of the parent session +//! (no request id). The adapter keeps the notify receiver after the reply is +//! delivered and hands it to [`run_tail`], which buffers that text and posts +//! it as a follow-up message. +//! +//! The tail holds no connection lock. The next prompt on the same session +//! replaces the subscriber, which closes the receiver and ends the tail. + +use crate::acp::protocol::JsonRpcMessage; +use crate::acp::{ + classify_notification, classify_workflow_signal, is_foreign_session_update, AcpEvent, + WorkflowSignal, +}; +use std::collections::HashSet; +use std::future::Future; +use std::time::Duration; +use tokio::sync::mpsc::UnboundedReceiver; +use tokio::time::{sleep_until, Instant}; + +/// Bounds for the late-output relay (`[pool] workflow_tail_*`). +#[derive(Debug, Clone, Copy)] +pub struct WorkflowRelayConfig { + /// Flush buffered text after this long without relevant frames. + pub tail_quiet: Duration, + /// Hard cap from the prompt response. Zero disables the relay (the + /// session-id filter stays on). + pub tail_max: Duration, +} + +/// Workflow bookkeeping for one turn, fed with every frame of the turn. +#[derive(Debug, Default)] +pub struct TurnWorkflowState { + open: HashSet, + seen: bool, +} + +impl TurnWorkflowState { + pub fn observe(&mut self, msg: &JsonRpcMessage, parent_session_id: &str) { + match classify_workflow_signal(msg, parent_session_id) { + Some(WorkflowSignal::RunStart { workflow_id }) => { + self.seen = true; + self.open.insert(workflow_id); + } + Some(WorkflowSignal::RunComplete { workflow_id }) => { + self.open.remove(&workflow_id); + } + None => {} + } + } + + /// A workflow started for this session during the turn. + pub fn armed(&self) -> bool { + self.seen + } + + pub fn into_open(self) -> HashSet { + self.open + } +} + +/// Read late frames from `rx` and hand text to `deliver`. +/// +/// Ends when the channel closes (flushing what is buffered), when nothing is +/// running and the quiet time has passed, or at `cfg.tail_max` (flushing, and +/// reporting through `deliver` if a run is still open). +pub async fn run_tail( + mut rx: UnboundedReceiver, + parent_session_id: String, + mut open: HashSet, + cfg: WorkflowRelayConfig, + mut deliver: F, +) where + F: FnMut(String) -> Fut, + Fut: Future, +{ + let start = Instant::now(); + let hard = start + cfg.tail_max; + let mut last_event = start; + let mut buf = String::new(); + loop { + let quiet_applies = !buf.is_empty() || open.is_empty(); + let deadline = if quiet_applies { + (last_event + cfg.tail_quiet).min(hard) + } else { + hard + }; + tokio::select! { + msg = rx.recv() => { + let Some(msg) = msg else { + flush(&mut buf, &mut deliver).await; + return; + }; + if is_foreign_session_update(&msg, &parent_session_id) { + continue; + } + match classify_workflow_signal(&msg, &parent_session_id) { + Some(WorkflowSignal::RunStart { workflow_id }) => { + open.insert(workflow_id); + last_event = Instant::now(); + continue; + } + Some(WorkflowSignal::RunComplete { workflow_id }) => { + open.remove(&workflow_id); + last_event = Instant::now(); + continue; + } + None => {} + } + if msg.id.is_none() { + if let Some(AcpEvent::Text(t)) = classify_notification(&msg) { + buf.push_str(&t); + last_event = Instant::now(); + } + } + } + _ = sleep_until(deadline) => { + flush(&mut buf, &mut deliver).await; + if Instant::now() >= hard { + if !open.is_empty() { + deliver(format!( + "⚠ workflow still running after {}s; further output is not relayed", + cfg.tail_max.as_secs() + )) + .await; + } + return; + } + last_event = Instant::now(); + if open.is_empty() { + return; + } + } + } + } +} + +async fn flush(buf: &mut String, deliver: &mut F) +where + F: FnMut(String) -> Fut, + Fut: Future, +{ + let text = std::mem::take(buf); + if !text.trim().is_empty() { + deliver(text).await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::sync::{Arc, Mutex}; + use tokio::sync::mpsc::unbounded_channel; + + const PARENT: &str = "parent"; + + fn cfg() -> WorkflowRelayConfig { + WorkflowRelayConfig { + tail_quiet: Duration::from_secs(20), + tail_max: Duration::from_secs(900), + } + } + + fn frame(v: serde_json::Value) -> JsonRpcMessage { + serde_json::from_value(v).unwrap() + } + + fn run_start(parent: &str) -> JsonRpcMessage { + frame(json!({"method": "_kiro/workflow/run_start", + "params": {"workflowId": "wf_1", "parentSessionId": parent}})) + } + + fn run_complete() -> JsonRpcMessage { + frame(json!({"method": "_kiro/workflow/run_complete", + "params": {"workflowId": "wf_1", "status": "completed"}})) + } + + fn chunk(session: &str, text: &str) -> JsonRpcMessage { + frame( + json!({"method": "session/update", "params": {"sessionId": session, + "update": {"sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": text}}}}), + ) + } + + fn collector() -> ( + Arc>>, + impl FnMut(String) -> std::future::Ready<()>, + ) { + let out = Arc::new(Mutex::new(Vec::new())); + let sink = out.clone(); + (out, move |t| { + sink.lock().unwrap().push(t); + std::future::ready(()) + }) + } + + fn open_set(ids: &[&str]) -> HashSet { + ids.iter().map(|s| s.to_string()).collect() + } + + #[tokio::test(start_paused = true)] + async fn late_parent_text_is_delivered_after_run_complete_and_quiet() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "all ")).unwrap(); + tx.send(chunk(PARENT, "done")).unwrap(); + run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + assert_eq!(*out.lock().unwrap(), vec!["all done".to_string()]); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn step_session_text_is_dropped() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + tx.send(run_complete()).unwrap(); + tx.send(chunk("step-1", "internal")).unwrap(); + tx.send(chunk(PARENT, "summary")).unwrap(); + run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + assert_eq!(*out.lock().unwrap(), vec!["summary".to_string()]); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn replaced_subscriber_flushes_buffer_and_ends() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + tx.send(chunk(PARENT, "partial")).unwrap(); + drop(tx); + run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + assert_eq!(*out.lock().unwrap(), vec!["partial".to_string()]); + } + + #[tokio::test(start_paused = true)] + async fn run_that_never_completes_reports_at_the_cap() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + let started = Instant::now(); + run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + assert_eq!(started.elapsed(), Duration::from_secs(900)); + let got = out.lock().unwrap().clone(); + assert_eq!(got.len(), 1); + assert!(got[0].contains("still running after 900s"), "{got:?}"); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn text_during_open_run_is_flushed_after_quiet_and_tail_continues() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + deliver, + )); + tx.send(chunk(PARENT, "first")).unwrap(); + tokio::time::sleep(Duration::from_secs(25)).await; + assert_eq!(*out.lock().unwrap(), vec!["first".to_string()]); + assert!(!handle.is_finished(), "run is still open"); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "second")).unwrap(); + handle.await.unwrap(); + assert_eq!( + *out.lock().unwrap(), + vec!["first".to_string(), "second".to_string()] + ); + } + + #[tokio::test(start_paused = true)] + async fn idle_tail_without_open_run_ends_after_quiet_with_no_delivery() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + let started = Instant::now(); + run_tail(rx, PARENT.into(), HashSet::new(), cfg(), deliver).await; + assert_eq!(started.elapsed(), Duration::from_secs(20)); + assert!(out.lock().unwrap().is_empty()); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn closed_channel_with_empty_buffer_ends_without_delivery() { + let (tx, rx) = unbounded_channel::(); + drop(tx); + let (out, deliver) = collector(); + run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + assert!(out.lock().unwrap().is_empty()); + } + + #[test] + fn turn_state_arms_only_for_own_session() { + let mut state = TurnWorkflowState::default(); + state.observe(&run_start("someone-else"), PARENT); + assert!(!state.armed()); + state.observe(&run_start(PARENT), PARENT); + assert!(state.armed()); + assert_eq!(state.into_open(), open_set(&["wf_1"])); + + let mut state = TurnWorkflowState::default(); + state.observe(&run_start(PARENT), PARENT); + state.observe(&run_complete(), PARENT); + assert!(state.armed()); + assert!(state.into_open().is_empty()); + } +} diff --git a/docs/config-reference.md b/docs/config-reference.md index 0d3362076..22ed10493 100644 --- a/docs/config-reference.md +++ b/docs/config-reference.md @@ -338,6 +338,7 @@ The AI agent subprocess that OpenAB spawns to handle messages via ACP. | `working_dir` | string | `$HOME` | Working directory for the agent process. Optional — defaults to container's `$HOME`. | | `env` | map | `{}` | Extra environment variables (e.g. `{ OPENAI_API_KEY = "${OPENAI_API_KEY}" }`). | | `inherit_env` | string[] | `[]` | Env var names to inherit from the OAB process (e.g. vars injected via K8s `envFrom`). Keys in `env` take precedence. | +| `session_new_meta` | table | none | Optional `_meta` object sent verbatim in every `session/new` request. For Kiro workflows: `{ kiro = { settings = { workflows = { enabled = true } } } }`. Enabling workflows also turns on the step-session frame filter and the late-output relay (see [kiro-v3.md](kiro-v3.md)). Must be a table. | > **Default inherited vars:** After `env_clear()`, the agent always receives `HOME`, `PATH`, and `USER` (on Windows: `USERPROFILE`, `USERNAME`, `PATH`, `SystemRoot`, `SystemDrive`). Use `inherit_env` to pass additional vars beyond this baseline. @@ -429,6 +430,9 @@ Session pool settings for managing concurrent agent sessions. | `session_ttl_hours` | u64 | `4` | Session time-to-live in hours. Idle sessions are reclaimed after this period. The example config uses `24`. | | `hung_grace_secs` | u64 | `120` | Grace period after `prompt_hard_timeout_secs` before a session stuck with its connection mutex held (in-flight prompt) is force-evicted from the pool. Eviction threshold: `prompt_hard_timeout_secs + hung_grace_secs`. | | `default_config_options` | map | `{}` | Config options to set automatically after session creation. Keys are config option IDs (e.g. `mode`, `model`), values are the desired values (e.g. `bypass`, `swe-1-6`). Sent via ACP `session/set_config_option` after each `session/new`. | +| `strict_default_config_options` | bool | `false` | When `true`, session creation fails if the agent's `session/set_config_option` response reports a `currentValue` different from the requested value (an alias given as the option's display name is accepted), or if the call errors. Responses without that option are accepted. Recommended for kiro-cli v3, which answers success for an unknown agent. Not applied when a session is resumed via `session/load`. | +| `workflow_tail_quiet_secs` | u64 | `20` | Only with Kiro workflows enabled in `[agent].session_new_meta`. Seconds without agent output after which buffered late workflow text is posted to the thread. Must be `> 0` unless `workflow_tail_max_secs = 0`. | +| `workflow_tail_max_secs` | u64 | `900` | Only with Kiro workflows enabled. Hard cap (seconds from the prompt response) on relaying late workflow output. `0` disables the relay. | **Example** — force Devin to bypass mode and use a specific model: diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md new file mode 100644 index 000000000..62f8329d5 --- /dev/null +++ b/docs/kiro-v3.md @@ -0,0 +1,99 @@ +# Kiro CLI v3 engine and Kiro workflows + +kiro-cli 3.x ships a second engine, selected with `--agent-engine=v3`. It changes how agents are +selected and adds Kiro workflows over ACP. openab supports both, and every setting below is +opt-in: with none of them set, a kiro-cli v2 bot behaves as before. + +## What changes with v3 + +- Agents appear as ACP **modes**. The flags `--agent`, `--trust-all-tools` and `--model` are + rejected, and v2 JSON agents (`~/.kiro/agents/*.json`) are not read. +- A custom agent is a Markdown file `~/.kiro/agents/.md`. Select it with + `[pool] default_config_options = { mode = "" }`. +- A session is created in the default mode (`vibe`) and then switched. An unknown mode name is + **not** an error: kiro-cli answers success and the session stays in `vibe` with its default tool + set. Turn on `strict_default_config_options` so openab refuses such a session. +- Each `kiro-cli` process uses about 0.5 GB of memory, and openab starts one per session. Size + the container and `[pool] max_sessions` for the peak (about 2 GiB for 4 sessions plus openab). + +## Configuration + +```toml +[agent] +command = "kiro-cli" +args = ["acp", "--agent-engine=v3"] +# Optional, only for Kiro workflows: +session_new_meta = { kiro = { settings = { workflows = { enabled = true } } } } + +[pool] +max_sessions = 2 +default_config_options = { mode = "openab-bot" } +strict_default_config_options = true +``` + +Agent file `~/.kiro/agents/openab-bot.md` (in the bot's `HOME`): + +```markdown +--- +name: openab-bot +description: Chat bot agent +tools: ["*"] +includeMcpJson: false +--- + +You are a helpful assistant in a chat thread. +``` + +Restrict `tools` to what the bot needs. openab auto-approves every permission request, so the +tool list is the only limit on what the agent can do. + +Create an empty user MCP config, `~/.kiro/settings/mcp.json`: + +```json +{"mcpServers": {}} +``` + +`includeMcpJson: false` does not stop user-level MCP servers from starting at `session/new`, so +an empty file is the reliable way to run without them. + +## What the openab settings do + +| Setting | Effect | +|---------|--------| +| `[agent] session_new_meta` | Sent as `_meta` in `session/new`. kiro-cli only honours the workflows switch there (not in `initialize`). Not sent on `session/load`. | +| `[pool] strict_default_config_options` | After each `session/set_config_option`, compares the returned `currentValue` with the requested value and fails session creation on a mismatch or an error. A response without that option is accepted, as is an alias given as the option's display name. Default `false`. | +| `[pool] workflow_tail_quiet_secs` / `workflow_tail_max_secs` | Bounds of the late-output relay below. | + +## Workflows + +With workflows enabled, a prompt can start a workflow and `session/prompt` returns **before** the +workflow ends. The summary arrives later as unsolicited message chunks of the same session. When +workflows are enabled openab: + +1. **Filters step sessions.** Each workflow step runs in its own ACP session and streams + `session/update` frames with a different `params.sessionId`. Those frames are dropped from + the reply. Frames without a `sessionId` are never dropped. Permission requests from step + sessions are still auto-answered. +2. **Relays the late summary.** If a workflow started for the session during the turn, openab + keeps reading after delivering the reply and posts the late text as a new message in the same + thread, prefixed `_Workflow update:_`. It ends when the workflow is complete and no output + has arrived for `workflow_tail_quiet_secs`, when the next prompt on the session starts, when + the connection closes, or at `workflow_tail_max_secs`. If a run is still open at the cap, a + warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` + disables the relay and keeps the filter. + +Limits: one summary can be split in two messages if the agent pauses longer than the quiet time. +Late text that arrives after the next prompt started is part of that prompt's reply. The relay is +not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are +applied after `session/new` only, not when a session is restored with `session/load`. + +## Security notes + +- Workflow steps run shell commands, and openab answers every permission request with + "allow always". Each step session asks two to three times per command. +- Text from the chat reaches workflow steps as user text. Allow only fixed, reviewed workflow + files, use a private channel, and keep step agents (`.md` files) to the minimum tool set. +- Custom agent `resources` are not loaded inside workflow steps. +- Upstream issues to know about: a workflow result can be lost when the parent session is busy, + and a run can hang if a permission request is never answered. openab bounds the wait but does + not fix either. diff --git a/docs/kiro.md b/docs/kiro.md index 60813272d..40737f716 100644 --- a/docs/kiro.md +++ b/docs/kiro.md @@ -41,6 +41,8 @@ To override a single agent's image instead of the global tag: > ⚠️ There is no `latest` tag. Use `beta` or `stable`, or pin to an exact version. +> Using kiro-cli 3.x (`--agent-engine=v3`) or Kiro workflows? See [kiro-v3.md](kiro-v3.md). + ## Manual config.toml ```toml diff --git a/src/main.rs b/src/main.rs index f49879778..0356e42fa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -566,7 +566,8 @@ async fn main() -> anyhow::Result<()> { .prompt_hard_timeout_secs .saturating_add(cfg.pool.hung_grace_secs), cfg.pool.default_config_options, - ); + ) + .with_strict_default_config_options(cfg.pool.strict_default_config_options); // Facade session wiring: only when the facade is actually serving. With no `[mcp]` there is // no registrar and no facade url, and the pool simply starts sessions without browser // capabilities — there is no longer a proxy path for it to fall back to. @@ -855,24 +856,32 @@ async fn main() -> anyhow::Result<()> { reg }; - let router = Arc::new( - AdapterRouter::new( - pool.clone(), - cfg.reactions, - cfg.markdown.tables, - cfg.pool.prompt_hard_timeout_secs, - cfg.pool.liveness_check_secs, - cfg.workspace.aliases, - std::path::PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| { - tracing::warn!( - "HOME environment variable is not set — falling back to /tmp as bot_home. \ + let workflow_relay = + pool.workflows_enabled() + .then(|| openab_core::workflow_tail::WorkflowRelayConfig { + tail_quiet: std::time::Duration::from_secs(cfg.pool.workflow_tail_quiet_secs), + tail_max: std::time::Duration::from_secs(cfg.pool.workflow_tail_max_secs), + }); + let router = AdapterRouter::new( + pool.clone(), + cfg.reactions, + cfg.markdown.tables, + cfg.pool.prompt_hard_timeout_secs, + cfg.pool.liveness_check_secs, + cfg.workspace.aliases, + std::path::PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| { + tracing::warn!( + "HOME environment variable is not set — falling back to /tmp as bot_home. \ This weakens the workspace security boundary." - ); - "/tmp".into() - })), - ) - .with_trust(gateway_trust), - ); + ); + "/tmp".into() + })), + ) + .with_trust(gateway_trust); + let router = Arc::new(match workflow_relay { + Some(relay) => router.with_workflow_relay(relay), + None => router, + }); // Shutdown signal for Slack adapter let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false); From ae26e26625a3a352b75165f4c30677b7246acc3d Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 18:30:53 -0500 Subject: [PATCH 02/11] fix(session): bound the workflow tail, keep strict mode honest, move subprocess tests to ignored Review fixes for #1609 (Refs #1607). - Workflow tail: starts draining right after the prompt response and posts only once the original reply is delivered (oneshot gate); hard cap is measured from the prompt response; buffer capped at 256 KiB with a truncation note; each post bounded to 30 s so a stalled platform call cannot hold the task. - Strict default_config_options no longer uses the slash-command fallback (set_config_option_reported), so a locally synthesized value cannot confirm an option; warn when the agent does not report the option. - Subprocess/filesystem tests are now #[ignore]d integration tests; new tests for buffer cap, gate, cap-from-response, stalled delivery, fallback-masking, and the subscriber swap through AcpConnection::session_prompt. - Docs: wording fixes, per-turn workflow tracking limit. Verified on macOS (macOS (aarch64) builder): - cargo clippy --workspace [--features unified] -- -D warnings: clean - cargo test --workspace --no-fail-fast: all pass except the pre-existing secrets::tests::resolve_exec_nonzero_exit (/bin/false path on macOS) - cargo test -p openab-core --lib -- --ignored config_option_tests workflow_meta_tests: 11 passed --- config.toml.example | 2 +- crates/openab-core/src/acp/connection.rs | 140 ++++++++++++- crates/openab-core/src/acp/pool.rs | 206 +++++++++++++++---- crates/openab-core/src/adapter.rs | 59 +++--- crates/openab-core/src/workflow_tail.rs | 248 +++++++++++++++++++++-- docs/kiro-v3.md | 10 +- 6 files changed, 579 insertions(+), 86 deletions(-) diff --git a/config.toml.example b/config.toml.example index 428576127..f6a25469f 100644 --- a/config.toml.example +++ b/config.toml.example @@ -280,7 +280,7 @@ session_ttl_hours = 24 # kiro-cli v3 (see docs/kiro-v3.md): select the agent mode and fail fast when it is missing. # default_config_options = { mode = "openab-bot" } # strict_default_config_options = true -# Late Kiro workflow output relay (needs [agent].session_new_meta below). +# Late Kiro workflow output relay (needs [agent].session_new_meta above). # workflow_tail_quiet_secs = 20 # workflow_tail_max_secs = 900 diff --git a/crates/openab-core/src/acp/connection.rs b/crates/openab-core/src/acp/connection.rs index 743df9ed9..2858a8ef9 100644 --- a/crates/openab-core/src/acp/connection.rs +++ b/crates/openab-core/src/acp/connection.rs @@ -684,6 +684,28 @@ impl AcpConnection { &mut self, config_id: &str, value: &str, + ) -> Result> { + self.set_config_option_inner(config_id, value, true).await + } + + /// Like [`Self::set_config_option`] but without the slash-command + /// fallback: an error from `session/set_config_option` is returned, and + /// the option list is exactly what the agent reported. Used by + /// `[pool] strict_default_config_options`, where a locally synthesized + /// value must not count as confirmation. + pub async fn set_config_option_reported( + &mut self, + config_id: &str, + value: &str, + ) -> Result> { + self.set_config_option_inner(config_id, value, false).await + } + + async fn set_config_option_inner( + &mut self, + config_id: &str, + value: &str, + allow_fallback: bool, ) -> Result> { let session_id = self .acp_session_id @@ -709,6 +731,7 @@ impl AcpConnection { } info!(config_id, value, "config option set"); } + Err(e) if !allow_fallback => return Err(e), Err(_) => { // Fall back: send as a slash command (e.g. "/model claude-sonnet-4") let cmd = format!("/{config_id} {value}"); @@ -1416,6 +1439,21 @@ pub(crate) mod mock_agent { /// `require_meta` is set, `session/new` fails unless the request carries /// `"workflows":{"enabled":true}`. pub(crate) fn script(set_cfg_reply: &str, require_meta: bool) -> String { + script_with_prompt(set_cfg_reply, require_meta, false) + } + + /// Like [`script`]; `prompt_ok` makes the slash-command fallback prompt + /// (id 4) succeed instead of failing. + pub(crate) fn script_with_prompt( + set_cfg_reply: &str, + require_meta: bool, + prompt_ok: bool, + ) -> String { + let prompt_reply = if prompt_ok { + r#"{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}}"# + } else { + r#"{"jsonrpc":"2.0","id":4,"error":{"code":-32000,"message":"unsupported"}}"# + }; let new_ok = r#"echo '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"s-1"}}'"#; let new_err = r#"echo '{"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"missing _meta"}}'"#; @@ -1432,7 +1470,7 @@ case "$l" in *'"method":"initialize"'*) echo '{{"jsonrpc":"2.0","id":1,"result":{{"agentInfo":{{"name":"mock"}}}}}}';; *'"method":"session/new"'*) {session_new};; *'"method":"session/set_config_option"'*) echo '{set_cfg_reply}';; -*'"method":"session/prompt"'*) echo '{{"jsonrpc":"2.0","id":4,"error":{{"code":-32000,"message":"unsupported"}}}}';; +*'"method":"session/prompt"'*) echo '{prompt_reply}';; esac done"# ) @@ -1593,6 +1631,7 @@ mod workflow_meta_tests { #[cfg(unix)] #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess"] async fn session_new_with_meta_sends_underscore_meta() { let script = mock_agent::script(&mock_agent::mode_reply("vibe"), true); let meta = json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); @@ -1610,6 +1649,7 @@ mod workflow_meta_tests { #[cfg(unix)] #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess"] async fn set_config_option_returns_agent_reported_value() { let script = mock_agent::script(&mock_agent::mode_reply("vibe"), false); let mut conn = spawn_mock(script).await; @@ -1617,4 +1657,102 @@ mod workflow_meta_tests { let opts = conn.set_config_option("mode", "e2e").await.unwrap(); assert!(verify_config_option_applied(&opts, "mode", "e2e").is_err()); } + + /// Mock agent for the subscriber hand-off: each `session/prompt` is answered + /// by a response (ids 3, 4, ...) followed by a late `agent_message_chunk` + /// of the parent session `s-1` ("late-"). + #[cfg(unix)] + fn late_chunk_script() -> String { + r#"n=3 +while IFS= read -r l; do +case "$l" in +*'"method":"initialize"'*) echo '{"jsonrpc":"2.0","id":1,"result":{"agentInfo":{"name":"mock"}}}';; +*'"method":"session/new"'*) echo '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"s-1"}}';; +*'"method":"session/prompt"'*) +echo '{"jsonrpc":"2.0","id":'$n',"result":{"stopReason":"end_turn"}}' +echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late-'$n'"}}}}' +n=$((n+1));; +esac +done"# + .to_string() + } + + /// The next `session_prompt` replaces the subscriber: the running tail + /// flushes what it buffered and ends, and the new receiver sees only the + /// new turn's frames. + #[cfg(unix)] + #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess"] + async fn next_prompt_replaces_subscriber_and_ends_the_tail() { + use super::ContentBlock; + use crate::workflow_tail::{run_tail, WorkflowRelayConfig}; + use std::time::Duration; + + let mut conn = spawn_mock(late_chunk_script()).await; + conn.session_new("/tmp").await.unwrap(); + + let (mut rx1, id1) = conn + .session_prompt(vec![ContentBlock::Text { text: "one".into() }]) + .await + .unwrap(); + loop { + let m = tokio::time::timeout(Duration::from_secs(5), rx1.recv()) + .await + .expect("response") + .expect("open"); + if m.id.as_ref().and_then(|i| i.as_u64()) == Some(id1) { + break; + } + } + conn.prompt_done_keep_subscriber().await; + + let out = Arc::new(std::sync::Mutex::new(Vec::::new())); + let sink = out.clone(); + let (gate_tx, gate_rx) = tokio::sync::oneshot::channel(); + gate_tx.send(()).unwrap(); + let tail = tokio::spawn(run_tail( + rx1, + "s-1".to_string(), + ["wf".to_string()].into_iter().collect(), + WorkflowRelayConfig { + tail_quiet: Duration::from_secs(60), + tail_max: Duration::from_secs(60), + }, + tokio::time::Instant::now(), + gate_rx, + move |t| { + sink.lock().unwrap().push(t); + std::future::ready(()) + }, + )); + // Let late-3 reach the tail's buffer before the swap. + tokio::time::sleep(Duration::from_millis(500)).await; + + let (mut rx2, id2) = conn + .session_prompt(vec![ContentBlock::Text { text: "two".into() }]) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), tail) + .await + .expect("tail must end when the subscriber is replaced") + .unwrap(); + assert_eq!(*out.lock().unwrap(), vec!["late-3".to_string()]); + + let mut texts = Vec::new(); + let mut got_response = false; + while !(got_response && !texts.is_empty()) { + let m = tokio::time::timeout(Duration::from_secs(5), rx2.recv()) + .await + .expect("frame") + .expect("open"); + if m.id.as_ref().and_then(|i| i.as_u64()) == Some(id2) { + got_response = true; + } else if let Some(crate::acp::AcpEvent::Text(t)) = + crate::acp::classify_notification(&m) + { + texts.push(t); + } + } + assert_eq!(texts, vec!["late-4".to_string()]); + } } diff --git a/crates/openab-core/src/acp/pool.rs b/crates/openab-core/src/acp/pool.rs index 7db163da3..661f2b94d 100644 --- a/crates/openab-core/src/acp/pool.rs +++ b/crates/openab-core/src/acp/pool.rs @@ -116,7 +116,12 @@ fn classify_hung( /// either resumes the session, so both are credentials. Extracted from the loop in `cleanup_idle` /// so the redaction can be exercised by a test for real — R1 redacted the sites it enumerated and /// this force-evict site was outside that list, logging both ids raw. -fn warn_force_evicting_hung(key: &str, session_id: Option<&str>, age_secs: u64, threshold_secs: u64) { +fn warn_force_evicting_hung( + key: &str, + session_id: Option<&str>, + age_secs: u64, + threshold_secs: u64, +) { warn!( thread_id = %crate::redact::redact_session_ids(key), session_id = %session_id.map(crate::redact::redact_session_ids).unwrap_or_default(), @@ -648,9 +653,23 @@ impl SessionPool { // Apply default config options (e.g. mode=bypass, model=swe-1-6) for (config_id, value) in &self.default_config_options { - match new_conn.set_config_option(config_id, value).await { + let result = if self.strict_default_config_options { + // No slash-command fallback: only a value the agent + // reports counts as applied. + new_conn.set_config_option_reported(config_id, value).await + } else { + new_conn.set_config_option(config_id, value).await + }; + match result { Ok(opts) => { if self.strict_default_config_options { + if !opts.iter().any(|o| o.id == *config_id) { + warn!( + config_id, + value, + "strict_default_config_options: the agent did not report this option, so it could not be verified" + ); + } // Returning drops `new_conn`, which kills the agent process group. super::connection::verify_config_option_applied( &opts, config_id, value, @@ -760,7 +779,12 @@ impl SessionPool { // supersedes under the same key (its guard cannot fire if that predecessor is hung). F3. #[cfg(feature = "acp-mcp")] if let Some(token) = session_token { - install_facade_token(&mut state, thread_id, token, self.session_registrar.as_ref()); + install_facade_token( + &mut state, + thread_id, + token, + self.session_registrar.as_ref(), + ); } self.save_mapping(&state.persisted); @@ -795,11 +819,12 @@ impl SessionPool { { let conn = { let state = self.state.read().await; - state - .active - .get(thread_id) - .cloned() - .ok_or_else(|| anyhow!("no connection for thread {}", crate::redact::redact_session_ids(thread_id)))? + state.active.get(thread_id).cloned().ok_or_else(|| { + anyhow!( + "no connection for thread {}", + crate::redact::redact_session_ids(thread_id) + ) + })? }; let mut conn = conn.lock().await; @@ -827,11 +852,12 @@ impl SessionPool { ) -> Result> { let conn = { let state = self.state.read().await; - state - .active - .get(thread_id) - .cloned() - .ok_or_else(|| anyhow!("no connection for thread {}", crate::redact::redact_session_ids(thread_id)))? + state.active.get(thread_id).cloned().ok_or_else(|| { + anyhow!( + "no connection for thread {}", + crate::redact::redact_session_ids(thread_id) + ) + })? }; let mut conn = conn.lock().await; conn.set_config_option(config_id, value).await @@ -843,11 +869,12 @@ impl SessionPool { pub async fn get_usage(&self, thread_id: &str) -> Result { let conn = { let state = self.state.read().await; - state - .active - .get(thread_id) - .cloned() - .ok_or_else(|| anyhow!("no connection for thread {}", crate::redact::redact_session_ids(thread_id)))? + state.active.get(thread_id).cloned().ok_or_else(|| { + anyhow!( + "no connection for thread {}", + crate::redact::redact_session_ids(thread_id) + ) + })? }; let mut conn = conn.lock().await; conn.get_usage().await @@ -862,7 +889,12 @@ impl SessionPool { .cancel_handles .get(thread_id) .cloned() - .ok_or_else(|| anyhow!("no session for thread {}", crate::redact::redact_session_ids(thread_id)))? + .ok_or_else(|| { + anyhow!( + "no session for thread {}", + crate::redact::redact_session_ids(thread_id) + ) + })? }; let data = serde_json::to_string(&serde_json::json!({ "jsonrpc": "2.0", @@ -887,7 +919,10 @@ impl SessionPool { info!(thread_id = %crate::redact::redact_session_ids(thread_id), "session reset"); Ok(()) } else { - Err(anyhow!("no session for thread {}", crate::redact::redact_session_ids(thread_id))) + Err(anyhow!( + "no session for thread {}", + crate::redact::redact_session_ids(thread_id) + )) } } @@ -1178,11 +1213,28 @@ mod tests { let mut state = empty_pool_state(); // Predecessor registers, then a successor takes over the SAME key. - super::install_facade_token(&mut state, "discord:acp_x", "T_pred".into(), Some(®istrar)); - assert!(reg.revoked().is_empty(), "nothing to revoke on the first install"); - super::install_facade_token(&mut state, "discord:acp_x", "T_succ".into(), Some(®istrar)); + super::install_facade_token( + &mut state, + "discord:acp_x", + "T_pred".into(), + Some(®istrar), + ); + assert!( + reg.revoked().is_empty(), + "nothing to revoke on the first install" + ); + super::install_facade_token( + &mut state, + "discord:acp_x", + "T_succ".into(), + Some(®istrar), + ); - assert_eq!(reg.revoked(), vec!["T_pred"], "the predecessor token must be revoked"); + assert_eq!( + reg.revoked(), + vec!["T_pred"], + "the predecessor token must be revoked" + ); assert_eq!( state.facade_tokens.get("discord:acp_x").map(String::as_str), Some("T_succ"), @@ -1199,14 +1251,25 @@ mod tests { let reg = Arc::new(CountingRegistrar::default()); let registrar: Arc = reg.clone(); let mut state = empty_pool_state(); - state.facade_tokens.insert("discord:acp_x".into(), "T_hung".into()); + state + .facade_tokens + .insert("discord:acp_x".into(), "T_hung".into()); // A different session's token must be untouched. - state.facade_tokens.insert("discord:acp_y".into(), "T_other".into()); + state + .facade_tokens + .insert("discord:acp_y".into(), "T_other".into()); super::revoke_facade_token_for_key(&mut state, "discord:acp_x", Some(®istrar)); - assert_eq!(reg.revoked(), vec!["T_hung"], "only the evicted session's token is revoked"); - assert!(!state.facade_tokens.contains_key("discord:acp_x"), "and it is forgotten"); + assert_eq!( + reg.revoked(), + vec!["T_hung"], + "only the evicted session's token is revoked" + ); + assert!( + !state.facade_tokens.contains_key("discord:acp_x"), + "and it is forgotten" + ); assert_eq!( state.facade_tokens.get("discord:acp_y").map(String::as_str), Some("T_other"), @@ -1413,11 +1476,23 @@ mod tests { }); let out = String::from_utf8(buf.lock().unwrap().clone()).unwrap(); - assert!(out.contains("force-evicting hung session"), "the warning must fire: {out}"); + assert!( + out.contains("force-evicting hung session"), + "the warning must fire: {out}" + ); assert!(!out.contains(uuid), "no raw uuid may reach the log: {out}"); - assert!(!out.contains("acp_") && !out.contains("sess_"), "no raw id prefix either: {out}"); - assert!(out.contains('#'), "the redaction tag must be present: {out}"); - assert!(out.contains("discord"), "the readable platform half must survive: {out}"); + assert!( + !out.contains("acp_") && !out.contains("sess_"), + "no raw id prefix either: {out}" + ); + assert!( + out.contains('#'), + "the redaction tag must be present: {out}" + ); + assert!( + out.contains("discord"), + "the readable platform half must survive: {out}" + ); } #[test] @@ -1606,10 +1681,25 @@ mod config_option_tests { require_meta: bool, meta: Option, strict: bool, + ) -> SessionPool { + pool_with_prompt(dir, set_cfg_reply, require_meta, meta, strict, false) + } + + fn pool_with_prompt( + dir: &std::path::Path, + set_cfg_reply: &str, + require_meta: bool, + meta: Option, + strict: bool, + prompt_ok: bool, ) -> SessionPool { let agent = AgentConfig { command: "sh".into(), - args: mock_agent::args(mock_agent::script(set_cfg_reply, require_meta)), + args: mock_agent::args(mock_agent::script_with_prompt( + set_cfg_reply, + require_meta, + prompt_ok, + )), working_dir: "/tmp".into(), env: HashMap::new(), inherit_env: vec![], @@ -1627,16 +1717,30 @@ mod config_option_tests { } #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn mismatch_is_ignored_by_default() { let dir = tempfile::tempdir().unwrap(); - let p = pool(dir.path(), &mock_agent::mode_reply("vibe"), false, None, false); + let p = pool( + dir.path(), + &mock_agent::mode_reply("vibe"), + false, + None, + false, + ); assert!(p.get_or_create("t", None).await.is_ok()); } #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_mismatch_fails_session_creation() { let dir = tempfile::tempdir().unwrap(); - let p = pool(dir.path(), &mock_agent::mode_reply("vibe"), false, None, true); + let p = pool( + dir.path(), + &mock_agent::mode_reply("vibe"), + false, + None, + true, + ); let err = p.get_or_create("t", None).await.unwrap_err().to_string(); assert!(err.contains("was not applied"), "{err}"); assert!(err.contains("`e2e`") && err.contains("`vibe`"), "{err}"); @@ -1644,13 +1748,21 @@ mod config_option_tests { } #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_match_succeeds() { let dir = tempfile::tempdir().unwrap(); - let p = pool(dir.path(), &mock_agent::mode_reply("e2e"), false, None, true); + let p = pool( + dir.path(), + &mock_agent::mode_reply("e2e"), + false, + None, + true, + ); assert!(p.get_or_create("t", None).await.is_ok()); } #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_response_without_options_keeps_legacy_behaviour() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; @@ -1659,6 +1771,7 @@ mod config_option_tests { } #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_error_response_fails_session_creation() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; @@ -1668,6 +1781,7 @@ mod config_option_tests { } #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn non_strict_error_response_is_only_a_warning() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; @@ -1676,6 +1790,7 @@ mod config_option_tests { } #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn session_new_meta_is_sent_when_configured() { let dir = tempfile::tempdir().unwrap(); let meta = serde_json::json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); @@ -1689,4 +1804,23 @@ mod config_option_tests { assert!(!without.workflows_enabled()); assert!(without.get_or_create("t", None).await.is_err()); } + + #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] + async fn strict_error_is_not_masked_by_a_successful_slash_fallback() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; + // The fallback prompt (id 4) succeeds, yet strict mode must still fail. + let strict = pool_with_prompt(dir.path(), reply, false, None, true, true); + let err = strict + .get_or_create("t", None) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("failed to set default config option"), "{err}"); + // Non-strict keeps the legacy fallback behaviour. + let dir2 = tempfile::tempdir().unwrap(); + let lenient = pool_with_prompt(dir2.path(), reply, false, None, false, true); + assert!(lenient.get_or_create("t", None).await.is_ok()); + } } diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 3c7b7ecee..990392a97 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -1073,6 +1073,10 @@ impl AdapterRouter { && !platform_is_acp && wf_state.armed() }); + let tail_started = tokio::time::Instant::now(); + // Hand the receiver to the tail right away so it drains + // frames while the original reply is finalized; it posts + // only after `gate_tx` fires below. let tail_rx = if tail_cfg.is_some() { conn.prompt_done_keep_subscriber().await; Some(rx) @@ -1080,6 +1084,35 @@ impl AdapterRouter { conn.prompt_done().await; None }; + let mut gate_tx = None; + if let (Some(cfg), Some(rx), Some(sid)) = (tail_cfg, tail_rx, parent_sid) { + let (g_tx, gate_rx) = tokio::sync::oneshot::channel::<()>(); + gate_tx = Some(g_tx); + let tail_adapter = adapter.clone(); + let tail_channel = thread_channel.clone(); + tokio::spawn(crate::workflow_tail::run_tail( + rx, + sid, + std::mem::take(&mut wf_state).into_open(), + cfg, + tail_started, + gate_rx, + move |text| { + let adapter = tail_adapter.clone(); + let channel = tail_channel.clone(); + async move { + let text = format!("_Workflow update:_\n\n{text}"); + for chunk in format::split_message(&text, message_limit) { + if let Err(e) = adapter.send_message(&channel, &chunk).await + { + warn!(error = ?e, "workflow tail delivery failed"); + break; + } + } + } + }, + )); + } // Stop the cosmetic edit loop and let any in-flight edit // finish before the authoritative finalize write, so in the // normal case a stale preview does not overwrite it. Dropping @@ -1343,29 +1376,9 @@ impl AdapterRouter { } } - if let (Some(cfg), Some(rx), Some(sid)) = (tail_cfg, tail_rx, parent_sid) { - let tail_adapter = adapter.clone(); - let tail_channel = thread_channel.clone(); - tokio::spawn(crate::workflow_tail::run_tail( - rx, - sid, - wf_state.into_open(), - cfg, - move |text| { - let adapter = tail_adapter.clone(); - let channel = tail_channel.clone(); - async move { - let text = format!("_Workflow update:_\n\n{text}"); - for chunk in format::split_message(&text, message_limit) { - if let Err(e) = adapter.send_message(&channel, &chunk).await - { - warn!(error = ?e, "workflow tail delivery failed"); - break; - } - } - } - }, - )); + // Original reply is out: let the tail start posting. + if let Some(g) = gate_tx.take() { + let _ = g.send(()); } if delivery_failed { diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index af5651a66..357246227 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -19,7 +19,8 @@ use std::collections::HashSet; use std::future::Future; use std::time::Duration; use tokio::sync::mpsc::UnboundedReceiver; -use tokio::time::{sleep_until, Instant}; +use tokio::sync::oneshot; +use tokio::time::{sleep_until, timeout_at, Instant}; /// Bounds for the late-output relay (`[pool] workflow_tail_*`). #[derive(Debug, Clone, Copy)] @@ -62,25 +63,44 @@ impl TurnWorkflowState { } } +/// Most text the tail buffers between flushes. Further text is dropped and a +/// truncation note is appended to the flushed message. +pub const MAX_BUFFER_BYTES: usize = 256 * 1024; + +/// Bound on one `deliver` call, so a stalled platform call cannot keep the +/// tail (and its deadline checks) blocked. +pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); + /// Read late frames from `rx` and hand text to `deliver`. /// +/// `started` is when the prompt response arrived: the hard cap is measured +/// from it, not from when this task starts. `gate` resolves once the original +/// reply has been delivered; the tail starts draining `rx` immediately (so the +/// queue does not grow while the reply is finalized) but posts nothing before +/// the gate opens. A dropped gate counts as open. +/// /// Ends when the channel closes (flushing what is buffered), when nothing is -/// running and the quiet time has passed, or at `cfg.tail_max` (flushing, and -/// reporting through `deliver` if a run is still open). +/// running and the quiet time has passed, or at the hard cap (flushing, and +/// reporting through `deliver` if a run is still open). Buffered text is +/// limited to [`MAX_BUFFER_BYTES`] and each `deliver` to [`DELIVER_TIMEOUT`]. pub async fn run_tail( mut rx: UnboundedReceiver, parent_session_id: String, mut open: HashSet, cfg: WorkflowRelayConfig, + started: Instant, + gate: oneshot::Receiver<()>, mut deliver: F, ) where F: FnMut(String) -> Fut, Fut: Future, { - let start = Instant::now(); - let hard = start + cfg.tail_max; - let mut last_event = start; + let mut gate = gate; + let mut gated = true; + let hard = started + cfg.tail_max; + let mut last_event = Instant::now(); let mut buf = String::new(); + let mut truncated = false; loop { let quiet_applies = !buf.is_empty() || open.is_empty(); let deadline = if quiet_applies { @@ -89,9 +109,16 @@ pub async fn run_tail( hard }; tokio::select! { + _ = &mut gate, if gated => { + gated = false; + } msg = rx.recv() => { let Some(msg) = msg else { - flush(&mut buf, &mut deliver).await; + if gated { + // Wait for the original reply, but not past the cap. + let _ = timeout_at(hard, &mut gate).await; + } + flush(&mut buf, &mut truncated, &mut deliver).await; return; }; if is_foreign_session_update(&msg, &parent_session_id) { @@ -112,16 +139,30 @@ pub async fn run_tail( } if msg.id.is_none() { if let Some(AcpEvent::Text(t)) = classify_notification(&msg) { - buf.push_str(&t); + if buf.len() + t.len() <= MAX_BUFFER_BYTES { + buf.push_str(&t); + } else { + truncated = true; + } last_event = Instant::now(); } } } _ = sleep_until(deadline) => { - flush(&mut buf, &mut deliver).await; - if Instant::now() >= hard { + let at_cap = Instant::now() >= hard; + if gated && !at_cap { + // Reply still being delivered: keep buffering. + last_event = Instant::now(); + continue; + } + if gated { + // Cap reached before the reply was delivered; drop. + return; + } + flush(&mut buf, &mut truncated, &mut deliver).await; + if at_cap || Instant::now() >= hard { if !open.is_empty() { - deliver(format!( + send(&mut deliver, format!( "⚠ workflow still running after {}s; further output is not relayed", cfg.tail_max.as_secs() )) @@ -138,14 +179,25 @@ pub async fn run_tail( } } -async fn flush(buf: &mut String, deliver: &mut F) +async fn send(deliver: &mut F, text: String) where F: FnMut(String) -> Fut, Fut: Future, { - let text = std::mem::take(buf); + let _ = tokio::time::timeout(DELIVER_TIMEOUT, deliver(text)).await; +} + +async fn flush(buf: &mut String, truncated: &mut bool, deliver: &mut F) +where + F: FnMut(String) -> Fut, + Fut: Future, +{ + let mut text = std::mem::take(buf); + if std::mem::take(truncated) { + text.push_str("\n\n…(output truncated)"); + } if !text.trim().is_empty() { - deliver(text).await; + send(deliver, text).await; } } @@ -155,6 +207,7 @@ mod tests { use serde_json::json; use std::sync::{Arc, Mutex}; use tokio::sync::mpsc::unbounded_channel; + use tokio::sync::oneshot; const PARENT: &str = "parent"; @@ -199,6 +252,12 @@ mod tests { }) } + fn open_gate() -> oneshot::Receiver<()> { + let (tx, rx) = oneshot::channel(); + tx.send(()).unwrap(); + rx + } + fn open_set(ids: &[&str]) -> HashSet { ids.iter().map(|s| s.to_string()).collect() } @@ -210,7 +269,16 @@ mod tests { tx.send(run_complete()).unwrap(); tx.send(chunk(PARENT, "all ")).unwrap(); tx.send(chunk(PARENT, "done")).unwrap(); - run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; assert_eq!(*out.lock().unwrap(), vec!["all done".to_string()]); drop(tx); } @@ -222,7 +290,16 @@ mod tests { tx.send(run_complete()).unwrap(); tx.send(chunk("step-1", "internal")).unwrap(); tx.send(chunk(PARENT, "summary")).unwrap(); - run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; assert_eq!(*out.lock().unwrap(), vec!["summary".to_string()]); drop(tx); } @@ -233,7 +310,16 @@ mod tests { let (out, deliver) = collector(); tx.send(chunk(PARENT, "partial")).unwrap(); drop(tx); - run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; assert_eq!(*out.lock().unwrap(), vec!["partial".to_string()]); } @@ -242,7 +328,16 @@ mod tests { let (tx, rx) = unbounded_channel(); let (out, deliver) = collector(); let started = Instant::now(); - run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; assert_eq!(started.elapsed(), Duration::from_secs(900)); let got = out.lock().unwrap().clone(); assert_eq!(got.len(), 1); @@ -259,6 +354,8 @@ mod tests { PARENT.into(), open_set(&["wf_1"]), cfg(), + Instant::now(), + open_gate(), deliver, )); tx.send(chunk(PARENT, "first")).unwrap(); @@ -279,7 +376,16 @@ mod tests { let (tx, rx) = unbounded_channel(); let (out, deliver) = collector(); let started = Instant::now(); - run_tail(rx, PARENT.into(), HashSet::new(), cfg(), deliver).await; + run_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; assert_eq!(started.elapsed(), Duration::from_secs(20)); assert!(out.lock().unwrap().is_empty()); drop(tx); @@ -290,10 +396,112 @@ mod tests { let (tx, rx) = unbounded_channel::(); drop(tx); let (out, deliver) = collector(); - run_tail(rx, PARENT.into(), open_set(&["wf_1"]), cfg(), deliver).await; + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; assert!(out.lock().unwrap().is_empty()); } + #[tokio::test(start_paused = true)] + async fn buffered_text_is_capped_and_marked_truncated() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + let big = "x".repeat(MAX_BUFFER_BYTES / 2 + 1); + tx.send(chunk(PARENT, &big)).unwrap(); + tx.send(chunk(PARENT, &big)).unwrap(); + tx.send(chunk(PARENT, &big)).unwrap(); + drop(tx); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; + let got = out.lock().unwrap().clone(); + assert_eq!(got.len(), 1); + assert!(got[0].len() <= MAX_BUFFER_BYTES + 64, "{}", got[0].len()); + assert!(got[0].ends_with("…(output truncated)")); + } + + #[tokio::test(start_paused = true)] + async fn hard_cap_counts_from_the_prompt_response() { + let (tx, rx) = unbounded_channel::(); + let (out, deliver) = collector(); + // The prompt response arrived 800 s ago (original reply was slow). + let started = Instant::now(); + tokio::time::advance(Duration::from_secs(800)).await; + let t0 = Instant::now(); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + started, + open_gate(), + deliver, + ) + .await; + assert_eq!(t0.elapsed(), Duration::from_secs(100)); + assert!(out.lock().unwrap()[0].contains("still running")); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn nothing_is_posted_before_the_original_reply_is_delivered() { + let (tx, rx) = unbounded_channel(); + let (gate_tx, gate_rx) = oneshot::channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + gate_rx, + deliver, + )); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "late")).unwrap(); + tokio::time::sleep(Duration::from_secs(60)).await; + assert!(out.lock().unwrap().is_empty(), "gate still closed"); + assert!(!handle.is_finished()); + gate_tx.send(()).unwrap(); + handle.await.unwrap(); + assert_eq!(*out.lock().unwrap(), vec!["late".to_string()]); + } + + #[tokio::test(start_paused = true)] + async fn stalled_delivery_does_not_hold_the_tail_forever() { + let (tx, rx) = unbounded_channel(); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "late")).unwrap(); + let started = Instant::now(); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + started, + open_gate(), + |_t| std::future::pending::<()>(), + ) + .await; + // quiet (20 s) + one delivery timeout, not forever. + assert_eq!(started.elapsed(), Duration::from_secs(20) + DELIVER_TIMEOUT); + drop(tx); + } + #[test] fn turn_state_arms_only_for_own_session() { let mut state = TurnWorkflowState::default(); diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index 62f8329d5..572087f20 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -60,8 +60,8 @@ an empty file is the reliable way to run without them. | Setting | Effect | |---------|--------| -| `[agent] session_new_meta` | Sent as `_meta` in `session/new`. kiro-cli only honours the workflows switch there (not in `initialize`). Not sent on `session/load`. | -| `[pool] strict_default_config_options` | After each `session/set_config_option`, compares the returned `currentValue` with the requested value and fails session creation on a mismatch or an error. A response without that option is accepted, as is an alias given as the option's display name. Default `false`. | +| `[agent] session_new_meta` | Sent as the `_meta` field of the `session/new` request. kiro-cli only honours the workflows switch there (not in `initialize`). Not sent on `session/load`. | +| `[pool] strict_default_config_options` | After each `session/set_config_option`, compares the returned `currentValue` with the requested value and fails session creation on a mismatch or an error. In this mode the legacy slash-command fallback is not used, so only a value the agent reports counts. A response without that option is accepted, as is an alias given as the option's display name. Default `false`. | | `[pool] workflow_tail_quiet_secs` / `workflow_tail_max_secs` | Bounds of the late-output relay below. | ## Workflows @@ -78,14 +78,14 @@ workflows are enabled openab: keeps reading after delivering the reply and posts the late text as a new message in the same thread, prefixed `_Workflow update:_`. It ends when the workflow is complete and no output has arrived for `workflow_tail_quiet_secs`, when the next prompt on the session starts, when - the connection closes, or at `workflow_tail_max_secs`. If a run is still open at the cap, a + the connection closes, or at `workflow_tail_max_secs`, measured from the prompt response. If a run is still open at the cap, a warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. -Limits: one summary can be split in two messages if the agent pauses longer than the quiet time. +Limits: openab buffers at most 256 KiB of late text per message (the rest is dropped with a note), and each post is bounded to 30 s. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. One summary can be split in two messages if the agent pauses longer than the quiet time. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are -applied after `session/new` only, not when a session is restored with `session/load`. +applied when a session is created with `session/new` only, not when a session is restored with `session/load`. ## Security notes From ee3bea191009d3b90e30e07ccb7182c65814ea18 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 19:06:58 -0500 Subject: [PATCH 03/11] fix(session): keep draining the workflow tail queue while a delivery is pending Review finding: the notify channel was unbounded and run_tail stopped receiving while awaiting a platform delivery (up to 30s), so late frames piled up outside the 256 KiB text cap. send() now selects over the delivery future and rx, ingesting frames into the capped buffer; text collected during a delivery is flushed afterwards. Added a flood test. Validation (macOS (aarch64) builder): clippy --workspace and --features unified -D warnings clean; cargo test --workspace --no-fail-fast all pass except the pre-existing macOS secrets::resolve_exec_nonzero_exit (/bin/false); --ignored config_option_tests workflow_meta_tests: 11 passed. --- crates/openab-core/src/workflow_tail.rs | 184 ++++++++++++++++++------ 1 file changed, 137 insertions(+), 47 deletions(-) diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index 357246227..44c578366 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -86,7 +86,7 @@ pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); pub async fn run_tail( mut rx: UnboundedReceiver, parent_session_id: String, - mut open: HashSet, + open: HashSet, cfg: WorkflowRelayConfig, started: Instant, gate: oneshot::Receiver<()>, @@ -98,13 +98,18 @@ pub async fn run_tail( let mut gate = gate; let mut gated = true; let hard = started + cfg.tail_max; - let mut last_event = Instant::now(); - let mut buf = String::new(); - let mut truncated = false; + let mut st = TailState { + parent: parent_session_id, + open, + buf: String::new(), + truncated: false, + last_event: Instant::now(), + closed: false, + }; loop { - let quiet_applies = !buf.is_empty() || open.is_empty(); + let quiet_applies = !st.buf.is_empty() || st.open.is_empty(); let deadline = if quiet_applies { - (last_event + cfg.tail_quiet).min(hard) + (st.last_event + cfg.tail_quiet).min(hard) } else { hard }; @@ -118,51 +123,26 @@ pub async fn run_tail( // Wait for the original reply, but not past the cap. let _ = timeout_at(hard, &mut gate).await; } - flush(&mut buf, &mut truncated, &mut deliver).await; + flush(&mut st, &mut rx, &mut deliver).await; return; }; - if is_foreign_session_update(&msg, &parent_session_id) { - continue; - } - match classify_workflow_signal(&msg, &parent_session_id) { - Some(WorkflowSignal::RunStart { workflow_id }) => { - open.insert(workflow_id); - last_event = Instant::now(); - continue; - } - Some(WorkflowSignal::RunComplete { workflow_id }) => { - open.remove(&workflow_id); - last_event = Instant::now(); - continue; - } - None => {} - } - if msg.id.is_none() { - if let Some(AcpEvent::Text(t)) = classify_notification(&msg) { - if buf.len() + t.len() <= MAX_BUFFER_BYTES { - buf.push_str(&t); - } else { - truncated = true; - } - last_event = Instant::now(); - } - } + st.ingest(msg); } _ = sleep_until(deadline) => { let at_cap = Instant::now() >= hard; if gated && !at_cap { // Reply still being delivered: keep buffering. - last_event = Instant::now(); + st.last_event = Instant::now(); continue; } if gated { // Cap reached before the reply was delivered; drop. return; } - flush(&mut buf, &mut truncated, &mut deliver).await; + flush(&mut st, &mut rx, &mut deliver).await; if at_cap || Instant::now() >= hard { - if !open.is_empty() { - send(&mut deliver, format!( + if !st.open.is_empty() { + send(&mut st, &mut rx, &mut deliver, format!( "⚠ workflow still running after {}s; further output is not relayed", cfg.tail_max.as_secs() )) @@ -170,8 +150,8 @@ pub async fn run_tail( } return; } - last_event = Instant::now(); - if open.is_empty() { + st.last_event = Instant::now(); + if (st.open.is_empty() || st.closed) && st.buf.is_empty() { return; } } @@ -179,25 +159,87 @@ pub async fn run_tail( } } -async fn send(deliver: &mut F, text: String) -where +/// Mutable bookkeeping of one tail. +struct TailState { + parent: String, + open: HashSet, + buf: String, + truncated: bool, + last_event: Instant, + /// The sender side closed while a delivery was pending. + closed: bool, +} + +impl TailState { + fn ingest(&mut self, msg: JsonRpcMessage) { + if is_foreign_session_update(&msg, &self.parent) { + return; + } + match classify_workflow_signal(&msg, &self.parent) { + Some(WorkflowSignal::RunStart { workflow_id }) => { + self.open.insert(workflow_id); + self.last_event = Instant::now(); + return; + } + Some(WorkflowSignal::RunComplete { workflow_id }) => { + self.open.remove(&workflow_id); + self.last_event = Instant::now(); + return; + } + None => {} + } + if msg.id.is_none() { + if let Some(AcpEvent::Text(t)) = classify_notification(&msg) { + if self.buf.len() + t.len() <= MAX_BUFFER_BYTES { + self.buf.push_str(&t); + } else { + self.truncated = true; + } + self.last_event = Instant::now(); + } + } + } +} + +/// Run one delivery (bounded by [`DELIVER_TIMEOUT`]) while still draining +/// `rx` into the capped buffer, so the notification queue cannot grow while +/// the platform call is pending. +async fn send( + st: &mut TailState, + rx: &mut UnboundedReceiver, + deliver: &mut F, + text: String, +) where F: FnMut(String) -> Fut, Fut: Future, { - let _ = tokio::time::timeout(DELIVER_TIMEOUT, deliver(text)).await; + let fut = tokio::time::timeout(DELIVER_TIMEOUT, deliver(text)); + tokio::pin!(fut); + loop { + tokio::select! { + _ = &mut fut => return, + msg = rx.recv(), if !st.closed => match msg { + Some(m) => st.ingest(m), + None => st.closed = true, + }, + } + } } -async fn flush(buf: &mut String, truncated: &mut bool, deliver: &mut F) -where +async fn flush( + st: &mut TailState, + rx: &mut UnboundedReceiver, + deliver: &mut F, +) where F: FnMut(String) -> Fut, Fut: Future, { - let mut text = std::mem::take(buf); - if std::mem::take(truncated) { + let mut text = std::mem::take(&mut st.buf); + if std::mem::take(&mut st.truncated) { text.push_str("\n\n…(output truncated)"); } if !text.trim().is_empty() { - send(deliver, text).await; + send(st, rx, deliver, text).await; } } @@ -502,6 +544,54 @@ mod tests { drop(tx); } + #[tokio::test(start_paused = true)] + async fn frames_sent_during_a_pending_delivery_are_drained_and_capped() { + let (tx, rx) = unbounded_channel(); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "first")).unwrap(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + // Platform call that hangs until the delivery timeout. + std::future::pending::<()>().await; + } + } + }; + let flood = async move { + // Quiet period (20 s) has passed; the first delivery is pending. + tokio::time::sleep(Duration::from_secs(25)).await; + let big = "x".repeat(MAX_BUFFER_BYTES / 2 + 1); + for _ in 0..50 { + tx.send(chunk(PARENT, &big)).unwrap(); + } + // Let the tail drain the queue while the delivery is pending. + tokio::task::yield_now().await; + drop(tx); + }; + let tail = run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ); + tokio::join!(tail, flood); + let got = calls.lock().unwrap().clone(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0], "first"); + assert!(got[1].len() <= MAX_BUFFER_BYTES + 64, "{}", got[1].len()); + assert!(got[1].ends_with("…(output truncated)")); + } + #[test] fn turn_state_arms_only_for_own_session() { let mut state = TurnWorkflowState::default(); From b2b344a11cb2ba11373a8c4c3dbf340805358741 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 20:48:11 -0500 Subject: [PATCH 04/11] fix(session): flush buffered workflow output when a delivery crosses the hard cap - run_tail: after the delivery that crosses the hard cap, do one bounded final flush of frames drained during it before the "still running" note (review: output lost at the cap boundary). Frames arriving during that final flush are dropped. - strict mode: a set_config_option reply without a result no longer falls back to the cached pre-switch options. - test: text_buffered_while_a_delivery_crosses_the_hard_cap_is_flushed (paused time). Validation (Linux x86_64 builder; the macOS builder was unreachable): - cargo clippy --workspace -- -D warnings: clean - cargo clippy --workspace --features unified -- -D warnings: clean - cargo test --workspace --no-fail-fast: all pass (openab-core 775 passed, 11 ignored) - cargo test -p openab-core --lib -- --ignored config_option_tests workflow_meta_tests: 11 passed - cargo fmt --check: only my touched file is clean; other files differ on that toolchain's rustfmt version (pre-existing, untouched). --- crates/openab-core/src/acp/connection.rs | 3 ++ crates/openab-core/src/workflow_tail.rs | 51 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/crates/openab-core/src/acp/connection.rs b/crates/openab-core/src/acp/connection.rs index 2858a8ef9..3fbc1a986 100644 --- a/crates/openab-core/src/acp/connection.rs +++ b/crates/openab-core/src/acp/connection.rs @@ -728,6 +728,9 @@ impl AcpConnection { Ok(r) => { if let Some(result) = r.result.as_ref() { self.config_options = parse_config_options(result); + } else if !allow_fallback { + // Strict path: never compare against pre-switch cached options. + self.config_options.clear(); } info!(config_id, value, "config option set"); } diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index 44c578366..4bc1ba7de 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -141,6 +141,11 @@ pub async fn run_tail( } flush(&mut st, &mut rx, &mut deliver).await; if at_cap || Instant::now() >= hard { + // Frames drained while that delivery was pending are still + // buffered: one bounded final flush (frames arriving during + // it are dropped, the tail ends here). + st.closed = true; + flush(&mut st, &mut rx, &mut deliver).await; if !st.open.is_empty() { send(&mut st, &mut rx, &mut deliver, format!( "⚠ workflow still running after {}s; further output is not relayed", @@ -592,6 +597,52 @@ mod tests { assert!(got[1].ends_with("…(output truncated)")); } + #[tokio::test(start_paused = true)] + async fn text_buffered_while_a_delivery_crosses_the_hard_cap_is_flushed() { + let (tx, rx) = unbounded_channel(); + tx.send(chunk(PARENT, "first")).unwrap(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + // Hangs until DELIVER_TIMEOUT, which ends after the cap. + std::future::pending::<()>().await; + } + } + }; + let late = async move { + // Delivery started at the 20 s quiet mark and is still pending. + tokio::time::sleep(Duration::from_secs(25)).await; + tx.send(chunk(PARENT, "late")).unwrap(); + tokio::time::sleep(Duration::from_secs(1000)).await; + drop(tx); + }; + let mut c = cfg(); + c.tail_max = Duration::from_secs(40); + let tail = run_tail( + rx, + PARENT.into(), + HashSet::new(), + c, + Instant::now(), + open_gate(), + deliver, + ); + tokio::join!(tail, late); + let got = calls.lock().unwrap().clone(); + assert_eq!( + got, + vec!["first".to_string(), "late".to_string()], + "{got:?}" + ); + } + #[test] fn turn_state_arms_only_for_own_session() { let mut state = TurnWorkflowState::default(); From 3a34469e5af6045779b7df2faf786861a34d670f Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 21:40:31 -0500 Subject: [PATCH 05/11] fix(session): keep the late workflow relay open after a quiet gap The tail ended at its first quiet flush when no run was open, so a summary that arrived after more than workflow_tail_quiet_secs was dropped. Thinking and tool frames also did not restart the quiet timer, so a pause inside a summary split it into two messages. - The tail now ends on channel close, at the hard cap, or when the next prompt replaces its subscriber. Quiet time only decides when text is posted. - Any parent-session session/update restarts the quiet timer. Those frames are not posted. - The 256 KiB buffer cap and the 30 s delivery timeout are unchanged. - Tests: a summary after a 25 s gap is delivered; thought and tool frames keep a summary in one message; an idle tail ends at the cap with nothing posted; a stalled delivery no longer stops later output. - docs/kiro-v3.md describes the behaviour as implemented. Refs #1607 Checks run on the remote macOS build host, from an rsync of this worktree (target and .git excluded): - rustfmt --check --edition 2021 crates/openab-core/src/workflow_tail.rs: pass - cargo fmt --check (workspace): fails on 666 files this change does not touch; root CI runs no workspace fmt, so this is pre-existing - cargo clippy --workspace -- -D warnings: pass - cargo clippy --workspace --features unified -- -D warnings: pass - cargo test --workspace: 776 passed, 1 failed, 11 ignored. The failure is secrets::tests::resolve_exec_nonzero_exit, which also fails on the committed base on the same host. - Negative check (scratch copy): with the quiet-timer refresh removed, thought_and_tool_frames_keep_a_summary_in_one_message fails. --- crates/openab-core/src/workflow_tail.rs | 114 ++++++++++++++++++++---- docs/kiro-v3.md | 15 ++-- 2 files changed, 106 insertions(+), 23 deletions(-) diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index 4bc1ba7de..0417a6cfd 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -79,9 +79,11 @@ pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); /// queue does not grow while the reply is finalized) but posts nothing before /// the gate opens. A dropped gate counts as open. /// -/// Ends when the channel closes (flushing what is buffered), when nothing is -/// running and the quiet time has passed, or at the hard cap (flushing, and -/// reporting through `deliver` if a run is still open). Buffered text is +/// Quiet time only decides when buffered text is posted. The tail does not end +/// on quiet, so output that arrives after a gap is still delivered. It ends +/// when the channel closes (flushing what is buffered) or at the hard cap +/// (flushing, and reporting through `deliver` if a run is still open). Any +/// parent-session `session/update` restarts the quiet timer. Buffered text is /// limited to [`MAX_BUFFER_BYTES`] and each `deliver` to [`DELIVER_TIMEOUT`]. pub async fn run_tail( mut rx: UnboundedReceiver, @@ -156,9 +158,6 @@ pub async fn run_tail( return; } st.last_event = Instant::now(); - if (st.open.is_empty() || st.closed) && st.buf.is_empty() { - return; - } } } } @@ -180,6 +179,11 @@ impl TailState { if is_foreign_session_update(&msg, &self.parent) { return; } + if msg.id.is_none() && msg.method.as_deref() == Some("session/update") { + // Thinking and tool frames are not relayed, but they count as + // activity so a pause inside a summary does not split it. + self.last_event = Instant::now(); + } match classify_workflow_signal(&msg, &self.parent) { Some(WorkflowSignal::RunStart { workflow_id }) => { self.open.insert(workflow_id); @@ -419,7 +423,7 @@ mod tests { } #[tokio::test(start_paused = true)] - async fn idle_tail_without_open_run_ends_after_quiet_with_no_delivery() { + async fn idle_tail_without_open_run_ends_at_cap_with_no_delivery() { let (tx, rx) = unbounded_channel(); let (out, deliver) = collector(); let started = Instant::now(); @@ -433,11 +437,69 @@ mod tests { deliver, ) .await; - assert_eq!(started.elapsed(), Duration::from_secs(20)); + assert_eq!(started.elapsed(), Duration::from_secs(900)); assert!(out.lock().unwrap().is_empty()); drop(tx); } + #[tokio::test(start_paused = true)] + async fn summary_after_a_quiet_gap_is_delivered() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + open_gate(), + deliver, + )); + tx.send(run_complete()).unwrap(); + tokio::time::sleep(Duration::from_secs(25)).await; + tx.send(chunk(PARENT, "summary")).unwrap(); + tokio::time::sleep(Duration::from_secs(25)).await; + assert_eq!(*out.lock().unwrap(), vec!["summary".to_string()]); + drop(tx); + handle.await.unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn thought_and_tool_frames_keep_a_summary_in_one_message() { + let (tx, rx) = unbounded_channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + )); + tx.send(chunk(PARENT, "A")).unwrap(); + // Thinking and tool calls arrive every 15 s, each inside the quiet + // window, so "A" and "B" stay in one message. + tokio::time::sleep(Duration::from_secs(15)).await; + tx.send(frame(json!({"method": "session/update", "params": { + "sessionId": PARENT, + "update": {"sessionUpdate": "agent_thought_chunk", + "content": {"type": "text", "text": "thinking"}}}}))) + .unwrap(); + tokio::time::sleep(Duration::from_secs(15)).await; + tx.send(frame(json!({"method": "session/update", "params": { + "sessionId": PARENT, + "update": {"sessionUpdate": "tool_call", "toolCallId": "t1", + "title": "read"}}}))) + .unwrap(); + tokio::time::sleep(Duration::from_secs(10)).await; + tx.send(chunk(PARENT, "B")).unwrap(); + tokio::time::sleep(Duration::from_secs(40)).await; + assert_eq!(*out.lock().unwrap(), vec!["AB".to_string()]); + drop(tx); + handle.await.unwrap(); + } + #[tokio::test(start_paused = true)] async fn closed_channel_with_empty_buffer_ends_without_delivery() { let (tx, rx) = unbounded_channel::(); @@ -531,22 +593,42 @@ mod tests { #[tokio::test(start_paused = true)] async fn stalled_delivery_does_not_hold_the_tail_forever() { let (tx, rx) = unbounded_channel(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + std::future::pending::<()>().await; + } + } + }; tx.send(run_complete()).unwrap(); tx.send(chunk(PARENT, "late")).unwrap(); - let started = Instant::now(); - run_tail( + let handle = tokio::spawn(run_tail( rx, PARENT.into(), open_set(&["wf_1"]), cfg(), - started, + Instant::now(), open_gate(), - |_t| std::future::pending::<()>(), - ) - .await; - // quiet (20 s) + one delivery timeout, not forever. - assert_eq!(started.elapsed(), Duration::from_secs(20) + DELIVER_TIMEOUT); + deliver, + )); + // Quiet (20 s) plus one delivery timeout (30 s); the tail must still + // post output that arrives after that. + tokio::time::sleep(Duration::from_secs(60)).await; + tx.send(chunk(PARENT, "later")).unwrap(); + tokio::time::sleep(Duration::from_secs(40)).await; drop(tx); + handle.await.unwrap(); + assert_eq!( + *calls.lock().unwrap(), + vec!["late".to_string(), "later".to_string()] + ); } #[tokio::test(start_paused = true)] diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index 572087f20..d2a85b2c6 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -76,13 +76,14 @@ workflows are enabled openab: sessions are still auto-answered. 2. **Relays the late summary.** If a workflow started for the session during the turn, openab keeps reading after delivering the reply and posts the late text as a new message in the same - thread, prefixed `_Workflow update:_`. It ends when the workflow is complete and no output - has arrived for `workflow_tail_quiet_secs`, when the next prompt on the session starts, when - the connection closes, or at `workflow_tail_max_secs`, measured from the prompt response. If a run is still open at the cap, a - warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` - disables the relay and keeps the filter. - -Limits: openab buffers at most 256 KiB of late text per message (the rest is dropped with a note), and each post is bounded to 30 s. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. One summary can be split in two messages if the agent pauses longer than the quiet time. + thread, prefixed `_Workflow update:_`. Text is posted after `workflow_tail_quiet_secs` without + new output, so text that arrives after a long pause is still delivered. Thinking and tool + activity count as output for this timer but are not posted. The relay ends when the connection + closes, when the next prompt on the session starts, or at `workflow_tail_max_secs`, measured from + the prompt response. If a run is still open at the cap, a warning message says that further + output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. + +Limits: openab buffers at most 256 KiB of late text per message (the rest is dropped with a note), and each post is bounded to 30 s. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. If the agent pauses for longer than the quiet time while a run is still open, the text before the pause is posted as its own message and later text starts a new one. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are applied when a session is created with `session/new` only, not when a session is restored with `session/load`. From 069124ca819c86bef590f046963f6257eda0cb0e Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 21:49:36 -0500 Subject: [PATCH 06/11] fix(session): bound the workflow relay queue and keep the tail draining Gate F1: the relay queue between the connection reader and the tail was an unbounded channel, and the cap epilogue stopped reading it. The relay queue is now a bounded channel of 1024 frames. A full queue drops the newest frame, and the next flush is marked "output truncated". Foreground prompts keep the unbounded queue. Frames still queued for the foreground receiver move to the relay queue under the subscriber lock, so their order is kept. The cap epilogue now reads queued frames and discards them, so the queue keeps draining until the tail returns. Gate F2 and R3/P2: quiet-gap splitting applies whether or not a run is open. Once text is cut at 256 KiB, later text is dropped too, so the posted text is a contiguous prefix before the truncation note. docs/kiro-v3.md now describes this, the queue limit, and the parent-session traffic note (R6/N2). Regression tests: - queue_overflow_while_delivery_is_stalled_is_bounded_and_marked - text_after_a_cut_is_not_appended_out_of_order - summary_after_a_quiet_gap_is_delivered (R1, already present, unchanged) Validation on remote macOS build host (aarch64, rust stable): - rustfmt --check on workflow_tail.rs, acp/connection.rs, adapter.rs: pass (repo CI has no fmt step; 666 untouched files differ under cargo fmt) - cargo clippy --workspace -- -D warnings: pass - cargo clippy --workspace --features unified -- -D warnings: pass - cargo test --workspace --no-fail-fast: 778 passed, 1 failed, 11 ignored. The failure is secrets::tests::resolve_exec_nonzero_exit, which the recorded results of earlier commits also show failing on the base. - cargo test -p openab-core --lib -- --ignored: 11 passed, 0 failed. Refs #1607 --- crates/openab-core/src/acp/connection.rs | 80 +++++--- crates/openab-core/src/adapter.rs | 3 +- crates/openab-core/src/workflow_tail.rs | 221 +++++++++++++++++++---- docs/kiro-v3.md | 2 +- 4 files changed, 246 insertions(+), 60 deletions(-) diff --git a/crates/openab-core/src/acp/connection.rs b/crates/openab-core/src/acp/connection.rs index 3fbc1a986..94012e7f8 100644 --- a/crates/openab-core/src/acp/connection.rs +++ b/crates/openab-core/src/acp/connection.rs @@ -2,6 +2,7 @@ use crate::acp::protocol::{ parse_config_options, parse_usage_report, ConfigOption, JsonRpcErrorResponse, JsonRpcId, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse, UsageReport, }; +use crate::workflow_tail::{relay_channel, RelayReceiver, RelaySender}; use anyhow::{anyhow, Result}; use serde::Serialize; use serde_json::{json, Value}; @@ -171,6 +172,27 @@ impl SessionActivity { } } +/// Where the reader loop forwards notifications. `Prompt` is the foreground +/// prompt's unbounded queue. `Relay` is the bounded queue that takes over +/// after the reply for late workflow output (see `prompt_done_keep_subscriber`). +pub(crate) enum NotifySink { + Prompt(mpsc::UnboundedSender), + Relay(RelaySender), +} + +impl NotifySink { + fn push(&self, msg: JsonRpcMessage) { + match self { + Self::Prompt(tx) => { + let _ = tx.send(msg); + } + Self::Relay(tx) => { + let _ = tx.send(msg); + } + } + } +} + pub struct AcpConnection { _proc: Child, /// PID of the direct child, used as the process group ID for cleanup. @@ -178,7 +200,7 @@ pub struct AcpConnection { stdin: Arc>, next_id: AtomicU64, pending: Arc>>>, - notify_tx: Arc>>>, + notify_tx: Arc>>, pub acp_session_id: Option, pub supports_load_session: bool, /// Agent name from `initialize` (`agentInfo.name`), e.g. "Kiro CLI Agent". @@ -290,7 +312,7 @@ pub(crate) async fn run_reader_loop( reader: R, writer: Arc>, pending: Arc>>>, - notify_tx: Arc>>>, + notify_tx: Arc>>, ) where R: AsyncRead + Unpin + Send + 'static, W: AsyncWrite + Unpin + Send + 'static, @@ -355,7 +377,7 @@ pub(crate) async fn run_reader_loop( let sub = notify_tx.lock().await; if let Some(ntx) = sub.as_ref() { // Clone the essential fields for the subscriber - let _ = ntx.send(JsonRpcMessage { + ntx.push(JsonRpcMessage { id: msg.id.clone(), method: None, result: msg.result.clone(), @@ -375,7 +397,7 @@ pub(crate) async fn run_reader_loop( // Notification → forward to subscriber let sub = notify_tx.lock().await; if let Some(tx) = sub.as_ref() { - let _ = tx.send(msg); + tx.push(msg); } } @@ -532,8 +554,7 @@ impl AcpConnection { let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let reader_handle = tokio::spawn(run_reader_loop( stdout, @@ -823,7 +844,7 @@ impl AcpConnection { .ok_or_else(|| anyhow!("no session"))?; let (tx, rx) = mpsc::unbounded_channel(); - *self.notify_tx.lock().await = Some(tx); + *self.notify_tx.lock().await = Some(NotifySink::Prompt(tx)); let id = self.next_id(); @@ -847,14 +868,28 @@ impl AcpConnection { Ok((rx, id)) } - /// Like [`Self::prompt_done`] but leaves the notify subscriber installed so - /// the caller can keep reading late frames from the receiver returned by - /// `session_prompt` (Kiro workflow output). The next `session_prompt` - /// replaces the subscriber, which closes the old receiver. - pub async fn prompt_done_keep_subscriber(&mut self) { + /// Like [`Self::prompt_done`] but keeps a subscriber installed so late + /// frames (Kiro workflow output) keep arriving. The foreground `prompt_rx` + /// (from `session_prompt`) is replaced by a bounded relay queue: frames + /// still queued in `prompt_rx` move to the new queue first, under the + /// subscriber lock, so their order is kept. The next `session_prompt` + /// replaces the subscriber, which closes the relay receiver. + pub async fn prompt_done_keep_subscriber( + &mut self, + prompt_rx: &mut mpsc::UnboundedReceiver, + ) -> RelayReceiver { + let (tx, rx) = relay_channel(); + { + let mut sub = self.notify_tx.lock().await; + while let Ok(msg) = prompt_rx.try_recv() { + let _ = tx.send(msg); + } + *sub = Some(NotifySink::Relay(tx)); + } self.activity.touch(); self.activity.set_in_flight(false); self.last_active = Instant::now(); + rx } /// Call after prompt streaming is done to clean up subscriber. @@ -1119,11 +1154,10 @@ mod reader_loop_tests { let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let (sub_tx, mut sub_rx) = mpsc::unbounded_channel(); - *notify_tx.lock().await = Some(sub_tx); + *notify_tx.lock().await = Some(NotifySink::Prompt(sub_tx)); let writer = Arc::new(Mutex::new(agent_stdin_writer)); let handle = tokio::spawn(run_reader_loop( @@ -1159,14 +1193,13 @@ mod reader_loop_tests { let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let (resp_tx, resp_rx) = oneshot::channel(); pending.lock().await.insert(7, resp_tx); let (sub_tx, mut sub_rx) = mpsc::unbounded_channel(); - *notify_tx.lock().await = Some(sub_tx); + *notify_tx.lock().await = Some(NotifySink::Prompt(sub_tx)); let writer = Arc::new(Mutex::new(agent_stdin_writer)); let handle = tokio::spawn(run_reader_loop( @@ -1206,8 +1239,7 @@ mod reader_loop_tests { Arc::new(Mutex::new(HashMap::new())); let (resp_tx, mut resp_rx) = oneshot::channel(); pending.lock().await.insert(7, resp_tx); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let handle = tokio::spawn(run_reader_loop( agent_stdout_reader, @@ -1251,7 +1283,7 @@ mod reader_loop_tests { let (resp_tx, mut resp_rx) = oneshot::channel(); pending.lock().await.insert(u64::MAX, resp_tx); let (sub_tx, mut sub_rx) = mpsc::unbounded_channel(); - let notify_tx = Arc::new(Mutex::new(Some(sub_tx))); + let notify_tx = Arc::new(Mutex::new(Some(NotifySink::Prompt(sub_tx)))); let handle = tokio::spawn(run_reader_loop( agent_stdout_reader, @@ -1694,12 +1726,12 @@ done"# let mut conn = spawn_mock(late_chunk_script()).await; conn.session_new("/tmp").await.unwrap(); - let (mut rx1, id1) = conn + let (mut prompt_rx, id1) = conn .session_prompt(vec![ContentBlock::Text { text: "one".into() }]) .await .unwrap(); loop { - let m = tokio::time::timeout(Duration::from_secs(5), rx1.recv()) + let m = tokio::time::timeout(Duration::from_secs(5), prompt_rx.recv()) .await .expect("response") .expect("open"); @@ -1707,7 +1739,7 @@ done"# break; } } - conn.prompt_done_keep_subscriber().await; + let rx1 = conn.prompt_done_keep_subscriber(&mut prompt_rx).await; let out = Arc::new(std::sync::Mutex::new(Vec::::new())); let sink = out.clone(); diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 990392a97..0d63c29d2 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -1078,8 +1078,7 @@ impl AdapterRouter { // frames while the original reply is finalized; it posts // only after `gate_tx` fires below. let tail_rx = if tail_cfg.is_some() { - conn.prompt_done_keep_subscriber().await; - Some(rx) + Some(conn.prompt_done_keep_subscriber(&mut rx).await) } else { conn.prompt_done().await; None diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index 0417a6cfd..f93fdcac4 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -17,8 +17,10 @@ use crate::acp::{ }; use std::collections::HashSet; use std::future::Future; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; use std::time::Duration; -use tokio::sync::mpsc::UnboundedReceiver; +use tokio::sync::mpsc::{self, error::TrySendError}; use tokio::sync::oneshot; use tokio::time::{sleep_until, timeout_at, Instant}; @@ -63,6 +65,69 @@ impl TurnWorkflowState { } } +/// Most frames queued between the connection reader and the tail. A full queue +/// drops the newest frame and marks the next flush as truncated. +pub const RELAY_QUEUE_CAPACITY: usize = 1024; + +/// Producer side of the relay queue. `send` never waits. +#[derive(Debug, Clone)] +pub struct RelaySender { + tx: mpsc::Sender, + overflow: Arc, +} + +/// A frame was not queued: the queue was full or the tail has ended. +#[derive(Debug)] +pub struct RelayDropped; + +impl RelaySender { + pub fn send(&self, msg: JsonRpcMessage) -> Result<(), RelayDropped> { + match self.tx.try_send(msg) { + Ok(()) => Ok(()), + Err(TrySendError::Full(_)) => { + self.overflow.store(true, Ordering::Relaxed); + Err(RelayDropped) + } + Err(TrySendError::Closed(_)) => Err(RelayDropped), + } + } +} + +/// Consumer side of the relay queue, read by [`run_tail`]. +#[derive(Debug)] +pub struct RelayReceiver { + rx: mpsc::Receiver, + overflow: Arc, +} + +impl RelayReceiver { + pub async fn recv(&mut self) -> Option { + self.rx.recv().await + } + + pub fn try_recv(&mut self) -> Option { + self.rx.try_recv().ok() + } + + /// True once if a frame was dropped on a full queue since the last call. + fn take_overflow(&self) -> bool { + self.overflow.swap(false, Ordering::Relaxed) + } +} + +/// A bounded relay queue of [`RELAY_QUEUE_CAPACITY`] frames. +pub fn relay_channel() -> (RelaySender, RelayReceiver) { + let (tx, rx) = mpsc::channel(RELAY_QUEUE_CAPACITY); + let overflow = Arc::new(AtomicBool::new(false)); + ( + RelaySender { + tx, + overflow: overflow.clone(), + }, + RelayReceiver { rx, overflow }, + ) +} + /// Most text the tail buffers between flushes. Further text is dropped and a /// truncation note is appended to the flushed message. pub const MAX_BUFFER_BYTES: usize = 256 * 1024; @@ -85,8 +150,10 @@ pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); /// (flushing, and reporting through `deliver` if a run is still open). Any /// parent-session `session/update` restarts the quiet timer. Buffered text is /// limited to [`MAX_BUFFER_BYTES`] and each `deliver` to [`DELIVER_TIMEOUT`]. +/// Frames dropped on a full queue ([`RELAY_QUEUE_CAPACITY`]) mark the flushed +/// text as truncated. pub async fn run_tail( - mut rx: UnboundedReceiver, + mut rx: RelayReceiver, parent_session_id: String, open: HashSet, cfg: WorkflowRelayConfig, @@ -107,6 +174,7 @@ pub async fn run_tail( truncated: false, last_event: Instant::now(), closed: false, + ending: false, }; loop { let quiet_applies = !st.buf.is_empty() || st.open.is_empty(); @@ -146,7 +214,7 @@ pub async fn run_tail( // Frames drained while that delivery was pending are still // buffered: one bounded final flush (frames arriving during // it are dropped, the tail ends here). - st.closed = true; + st.ending = true; flush(&mut st, &mut rx, &mut deliver).await; if !st.open.is_empty() { send(&mut st, &mut rx, &mut deliver, format!( @@ -172,6 +240,9 @@ struct TailState { last_event: Instant, /// The sender side closed while a delivery was pending. closed: bool, + /// The final delivery is running: queued frames are read and dropped so + /// the queue keeps draining until the tail returns. + ending: bool, } impl TailState { @@ -199,7 +270,9 @@ impl TailState { } if msg.id.is_none() { if let Some(AcpEvent::Text(t)) = classify_notification(&msg) { - if self.buf.len() + t.len() <= MAX_BUFFER_BYTES { + // Once text is cut, later text is dropped too, so the flushed + // message stays a contiguous prefix before the truncation note. + if !self.truncated && self.buf.len() + t.len() <= MAX_BUFFER_BYTES { self.buf.push_str(&t); } else { self.truncated = true; @@ -213,12 +286,8 @@ impl TailState { /// Run one delivery (bounded by [`DELIVER_TIMEOUT`]) while still draining /// `rx` into the capped buffer, so the notification queue cannot grow while /// the platform call is pending. -async fn send( - st: &mut TailState, - rx: &mut UnboundedReceiver, - deliver: &mut F, - text: String, -) where +async fn send(st: &mut TailState, rx: &mut RelayReceiver, deliver: &mut F, text: String) +where F: FnMut(String) -> Fut, Fut: Future, { @@ -228,23 +297,25 @@ async fn send( tokio::select! { _ = &mut fut => return, msg = rx.recv(), if !st.closed => match msg { - Some(m) => st.ingest(m), + Some(m) => { + if !st.ending { + st.ingest(m); + } + } None => st.closed = true, }, } } } -async fn flush( - st: &mut TailState, - rx: &mut UnboundedReceiver, - deliver: &mut F, -) where +async fn flush(st: &mut TailState, rx: &mut RelayReceiver, deliver: &mut F) +where F: FnMut(String) -> Fut, Fut: Future, { let mut text = std::mem::take(&mut st.buf); - if std::mem::take(&mut st.truncated) { + let dropped = rx.take_overflow(); + if std::mem::take(&mut st.truncated) || dropped { text.push_str("\n\n…(output truncated)"); } if !text.trim().is_empty() { @@ -257,7 +328,6 @@ mod tests { use super::*; use serde_json::json; use std::sync::{Arc, Mutex}; - use tokio::sync::mpsc::unbounded_channel; use tokio::sync::oneshot; const PARENT: &str = "parent"; @@ -315,7 +385,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn late_parent_text_is_delivered_after_run_complete_and_quiet() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); tx.send(run_complete()).unwrap(); tx.send(chunk(PARENT, "all ")).unwrap(); @@ -336,7 +406,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn step_session_text_is_dropped() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); tx.send(run_complete()).unwrap(); tx.send(chunk("step-1", "internal")).unwrap(); @@ -357,7 +427,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn replaced_subscriber_flushes_buffer_and_ends() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); tx.send(chunk(PARENT, "partial")).unwrap(); drop(tx); @@ -376,7 +446,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn run_that_never_completes_reports_at_the_cap() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); let started = Instant::now(); run_tail( @@ -398,7 +468,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn text_during_open_run_is_flushed_after_quiet_and_tail_continues() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); let handle = tokio::spawn(run_tail( rx, @@ -424,7 +494,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn idle_tail_without_open_run_ends_at_cap_with_no_delivery() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); let started = Instant::now(); run_tail( @@ -444,7 +514,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn summary_after_a_quiet_gap_is_delivered() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); let handle = tokio::spawn(run_tail( rx, @@ -466,7 +536,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn thought_and_tool_frames_keep_a_summary_in_one_message() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); let handle = tokio::spawn(run_tail( rx, @@ -502,7 +572,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn closed_channel_with_empty_buffer_ends_without_delivery() { - let (tx, rx) = unbounded_channel::(); + let (tx, rx) = relay_channel(); drop(tx); let (out, deliver) = collector(); run_tail( @@ -520,7 +590,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn buffered_text_is_capped_and_marked_truncated() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); let big = "x".repeat(MAX_BUFFER_BYTES / 2 + 1); tx.send(chunk(PARENT, &big)).unwrap(); @@ -543,9 +613,39 @@ mod tests { assert!(got[0].ends_with("…(output truncated)")); } + #[tokio::test(start_paused = true)] + async fn text_after_a_cut_is_not_appended_out_of_order() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + tx.send(chunk(PARENT, &"a".repeat(MAX_BUFFER_BYTES - 10))) + .unwrap(); + // Does not fit: the buffer is cut here. + tx.send(chunk(PARENT, &"b".repeat(100))).unwrap(); + // Would fit in the 10 bytes left, but must not follow the cut. + tx.send(chunk(PARENT, "ccccc")).unwrap(); + drop(tx); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ) + .await; + assert_eq!( + *out.lock().unwrap(), + vec![format!( + "{}\n\n…(output truncated)", + "a".repeat(MAX_BUFFER_BYTES - 10) + )] + ); + } + #[tokio::test(start_paused = true)] async fn hard_cap_counts_from_the_prompt_response() { - let (tx, rx) = unbounded_channel::(); + let (tx, rx) = relay_channel(); let (out, deliver) = collector(); // The prompt response arrived 800 s ago (original reply was slow). let started = Instant::now(); @@ -568,7 +668,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn nothing_is_posted_before_the_original_reply_is_delivered() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let (gate_tx, gate_rx) = oneshot::channel(); let (out, deliver) = collector(); let handle = tokio::spawn(run_tail( @@ -592,7 +692,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn stalled_delivery_does_not_hold_the_tail_forever() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); let calls = Arc::new(Mutex::new(Vec::::new())); let sink = calls.clone(); let deliver = move |t: String| { @@ -633,7 +733,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn frames_sent_during_a_pending_delivery_are_drained_and_capped() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); tx.send(run_complete()).unwrap(); tx.send(chunk(PARENT, "first")).unwrap(); let calls = Arc::new(Mutex::new(Vec::::new())); @@ -679,9 +779,64 @@ mod tests { assert!(got[1].ends_with("…(output truncated)")); } + #[tokio::test(start_paused = true)] + async fn queue_overflow_while_delivery_is_stalled_is_bounded_and_marked() { + let (tx, rx) = relay_channel(); + tx.send(chunk(PARENT, "first")).unwrap(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + std::future::pending::<()>().await; + } + } + }; + let flood = async move { + // The first delivery is pending from the 20 s quiet mark. + tokio::time::sleep(Duration::from_secs(25)).await; + // One synchronous burst: the tail cannot drain until this task + // yields, so the queue fills and the surplus is dropped. + let mut dropped = 0; + for _ in 0..RELAY_QUEUE_CAPACITY + 500 { + if tx.send(chunk(PARENT, "x")).is_err() { + dropped += 1; + } + } + assert_eq!(dropped, 500); + tokio::task::yield_now().await; + drop(tx); + }; + let tail = run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_gate(), + deliver, + ); + tokio::join!(tail, flood); + let got = calls.lock().unwrap().clone(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0], "first"); + assert_eq!( + got[1], + format!( + "{}\n\n…(output truncated)", + "x".repeat(RELAY_QUEUE_CAPACITY) + ) + ); + } + #[tokio::test(start_paused = true)] async fn text_buffered_while_a_delivery_crosses_the_hard_cap_is_flushed() { - let (tx, rx) = unbounded_channel(); + let (tx, rx) = relay_channel(); tx.send(chunk(PARENT, "first")).unwrap(); let calls = Arc::new(Mutex::new(Vec::::new())); let sink = calls.clone(); diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index d2a85b2c6..7a36a4e8e 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -83,7 +83,7 @@ workflows are enabled openab: the prompt response. If a run is still open at the cap, a warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. -Limits: openab buffers at most 256 KiB of late text per message (the rest is dropped with a note), and each post is bounded to 30 s. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. If the agent pauses for longer than the quiet time while a run is still open, the text before the pause is posted as its own message and later text starts a new one. +Limits: openab buffers at most 256 KiB of late text per message. Text past that cap is dropped and the posted message ends with `…(output truncated)`, so the posted text is always a contiguous prefix. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next message as truncated. Each post is bounded to 30 s. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are applied when a session is created with `session/new` only, not when a session is restored with `session/load`. From 615a3f9677b8e7c6dfd15968676b87c7b9759c54 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 22:06:20 -0500 Subject: [PATCH 07/11] fix(session): cap one late-output flush at 16 platform messages Gate R2/P1, decided by council (option b): a 256 KiB late flush split to the platform limit becomes about 130 messages, and the 30 s deliver timeout could cut it off before the truncation note. A flush now posts at most 16 platform messages. When the text needs more, the first 15 are posted and the 16th is a truncation note, so dropped output is always announced. The split still uses each platform's message_limit. The queue bound (1024 frames) and the 256 KiB buffer cap are unchanged. Limits that remain: one flush has a 30 s budget in total. A slow platform can stop it before the note is posted. Messages are sent one at a time, and rate limiting is left to the platform client. Neither was tested against a live platform. Tests: flush_messages_are_capped_with_a_note_in_the_last_slot and full_buffer_splits_into_at_most_the_cap_on_a_discord_sized_limit. Validation on remote macOS build host: - rustfmt --check on workflow_tail.rs, acp/connection.rs, adapter.rs: pass - cargo clippy --workspace -- -D warnings: pass - cargo clippy --workspace --features unified -- -D warnings: pass - cargo test --workspace --no-fail-fast: 780 passed, 1 failed, 11 ignored. The failure is secrets::tests::resolve_exec_nonzero_exit, which also fails on the base. - cargo test -p openab-core --lib -- --ignored: 11 passed, 0 failed. Refs #1607 --- crates/openab-core/src/adapter.rs | 7 ++- crates/openab-core/src/workflow_tail.rs | 58 +++++++++++++++++++++++++ docs/kiro-v3.md | 2 +- 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 0d63c29d2..391c91839 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -1101,7 +1101,12 @@ impl AdapterRouter { let channel = tail_channel.clone(); async move { let text = format!("_Workflow update:_\n\n{text}"); - for chunk in format::split_message(&text, message_limit) { + let chunks = crate::workflow_tail::limit_flush_messages( + format::split_message(&text, message_limit), + crate::workflow_tail::MAX_FLUSH_MESSAGES, + crate::workflow_tail::TRUNCATED_NOTE, + ); + for chunk in chunks { if let Err(e) = adapter.send_message(&channel, &chunk).await { warn!(error = ?e, "workflow tail delivery failed"); diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index f93fdcac4..d064519a1 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -136,6 +136,24 @@ pub const MAX_BUFFER_BYTES: usize = 256 * 1024; /// tail (and its deadline checks) blocked. pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); +/// Most platform messages one late-output flush may post. When the text needs +/// more, the last message is [`TRUNCATED_NOTE`] and the rest is not posted. +pub const MAX_FLUSH_MESSAGES: usize = 16; + +/// Posted in place of the chunks that do not fit into [`MAX_FLUSH_MESSAGES`]. +pub const TRUNCATED_NOTE: &str = "…(output truncated: further workflow output is not relayed)"; + +/// Apply the per-flush message cap to already platform-split `chunks`. The +/// note takes the last slot, so it is always posted when anything is dropped. +pub fn limit_flush_messages(mut chunks: Vec, max: usize, note: &str) -> Vec { + if chunks.len() <= max { + return chunks; + } + chunks.truncate(max.saturating_sub(1)); + chunks.push(note.to_string()); + chunks +} + /// Read late frames from `rx` and hand text to `deliver`. /// /// `started` is when the prompt response arrived: the hard cap is measured @@ -880,6 +898,46 @@ mod tests { ); } + #[test] + fn flush_messages_are_capped_with_a_note_in_the_last_slot() { + let short = vec!["a".to_string(), "b".to_string()]; + assert_eq!( + limit_flush_messages(short.clone(), MAX_FLUSH_MESSAGES, TRUNCATED_NOTE), + short + ); + + // Exactly the cap: nothing is dropped, so no note. + let exact: Vec = (0..MAX_FLUSH_MESSAGES).map(|i| i.to_string()).collect(); + assert_eq!( + limit_flush_messages(exact.clone(), MAX_FLUSH_MESSAGES, TRUNCATED_NOTE), + exact + ); + + let long: Vec = (0..100).map(|i| i.to_string()).collect(); + let got = limit_flush_messages(long, MAX_FLUSH_MESSAGES, TRUNCATED_NOTE); + assert_eq!(got.len(), MAX_FLUSH_MESSAGES); + assert_eq!( + got[MAX_FLUSH_MESSAGES - 2], + (MAX_FLUSH_MESSAGES - 2).to_string() + ); + assert_eq!(got[MAX_FLUSH_MESSAGES - 1], TRUNCATED_NOTE); + } + + #[test] + fn full_buffer_splits_into_at_most_the_cap_on_a_discord_sized_limit() { + // 256 KiB of text at Discord's 2000-character message limit would be + // about 130 messages; the cap keeps 15 of them plus the note. + let text = "line of late output\n".repeat(MAX_BUFFER_BYTES / 20); + let chunks = crate::format::split_message(&text, 2000); + assert!(chunks.len() > MAX_FLUSH_MESSAGES); + let got = limit_flush_messages(chunks, MAX_FLUSH_MESSAGES, TRUNCATED_NOTE); + assert_eq!(got.len(), MAX_FLUSH_MESSAGES); + assert_eq!(got.last().unwrap(), TRUNCATED_NOTE); + assert!(got[..MAX_FLUSH_MESSAGES - 1] + .iter() + .all(|c| c.chars().count() <= 2000)); + } + #[test] fn turn_state_arms_only_for_own_session() { let mut state = TurnWorkflowState::default(); diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index 7a36a4e8e..984a24777 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -83,7 +83,7 @@ workflows are enabled openab: the prompt response. If a run is still open at the cap, a warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. -Limits: openab buffers at most 256 KiB of late text per message. Text past that cap is dropped and the posted message ends with `…(output truncated)`, so the posted text is always a contiguous prefix. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next message as truncated. Each post is bounded to 30 s. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. +Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that further workflow output is not relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are applied when a session is created with `session/new` only, not when a session is restored with `session/load`. From 37227b4fcdb53621f711bf24ca3908208f734536 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Wed, 18 Nov 2026 22:53:44 -0500 Subject: [PATCH 08/11] fix(session): state only what the cap note means Gate F1 (Sol, blocking; Opus F1 non-blocking): TRUNCATED_NOTE said further workflow output is not relayed, but a flush is capped at 16 messages and later flushes are still relayed. The note now says this update stopped at 16 messages, the rest was not posted, and later output is still relayed. docs/kiro-v3.md is updated to match. Gate F2 (Opus, low, one line): when the channel closed while the original reply's gate was still closed at the hard cap, run_tail flushed buffered text before the reply. It now returns without posting, like the cap branch does. Unit test: flush_messages_are_capped_with_a_note_in_the_last_slot asserts the exact note text. Validation on macmini (~/scratch/openab-kiro-v3, rsynced from this worktree): - cargo clippy --workspace -- -D warnings: exit 0 - cargo clippy --workspace --features unified -- -D warnings: exit 0 (manifest lint warnings only: unused clap, tracing-subscriber, and rmcp under unified; pre-existing, not touched) - cargo test -p openab-core workflow_tail: 21 passed, 0 failed Not run: cargo fmt (per task). Known pre-existing failures not touched: fmt diff on main, secrets::tests::resolve_exec_nonzero_exit on macOS. --- crates/openab-core/src/workflow_tail.rs | 10 ++++++++-- docs/kiro-v3.md | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index d064519a1..79c6359e1 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -141,7 +141,7 @@ pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); pub const MAX_FLUSH_MESSAGES: usize = 16; /// Posted in place of the chunks that do not fit into [`MAX_FLUSH_MESSAGES`]. -pub const TRUNCATED_NOTE: &str = "…(output truncated: further workflow output is not relayed)"; +pub const TRUNCATED_NOTE: &str = "…(output truncated: this update stopped at 16 messages and the rest was not posted; later output is still relayed)"; /// Apply the per-flush message cap to already platform-split `chunks`. The /// note takes the last slot, so it is always posted when anything is dropped. @@ -209,7 +209,9 @@ pub async fn run_tail( let Some(msg) = msg else { if gated { // Wait for the original reply, but not past the cap. - let _ = timeout_at(hard, &mut gate).await; + if timeout_at(hard, &mut gate).await.is_err() { + return; + } } flush(&mut st, &mut rx, &mut deliver).await; return; @@ -921,6 +923,10 @@ mod tests { (MAX_FLUSH_MESSAGES - 2).to_string() ); assert_eq!(got[MAX_FLUSH_MESSAGES - 1], TRUNCATED_NOTE); + assert_eq!( + TRUNCATED_NOTE, + "…(output truncated: this update stopped at 16 messages and the rest was not posted; later output is still relayed)" + ); } #[test] diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index 984a24777..d44c4e9fc 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -83,7 +83,7 @@ workflows are enabled openab: the prompt response. If a run is still open at the cap, a warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. -Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that further workflow output is not relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. +Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that this update stopped at 16 messages and the rest was not posted, while later output is still relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are applied when a session is created with `session/new` only, not when a session is restored with `session/load`. From 0c2ab18f3c40e9ec19b35d374f1ea83dd1d26c2d Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Thu, 19 Nov 2026 00:26:11 -0500 Subject: [PATCH 09/11] fix(session): cap note says this flush was cut, not the whole update Gate F1 (Sol, blocking): the cap note must be flush-scoped. The note now reads "this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed". docs/kiro-v3.md and the unit test flush_messages_are_capped_with_a_note_in_the_last_slot assert the same text. The PR body is updated to match. Validation on macmini (~/scratch/openab-kiro-v3, rsynced from this worktree): - cargo clippy --workspace -- -D warnings: exit 0 - cargo clippy --workspace --features unified -- -D warnings: exit 0 (manifest lint warnings only, pre-existing) - cargo test -p openab-core workflow_tail: 21 passed, 0 failed Not run: cargo fmt. Known pre-existing failures not touched: fmt diff on main, secrets::tests::resolve_exec_nonzero_exit on macOS. --- crates/openab-core/src/workflow_tail.rs | 4 ++-- docs/kiro-v3.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index 79c6359e1..8e80e0ca0 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -141,7 +141,7 @@ pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); pub const MAX_FLUSH_MESSAGES: usize = 16; /// Posted in place of the chunks that do not fit into [`MAX_FLUSH_MESSAGES`]. -pub const TRUNCATED_NOTE: &str = "…(output truncated: this update stopped at 16 messages and the rest was not posted; later output is still relayed)"; +pub const TRUNCATED_NOTE: &str = "…(output truncated: this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed)"; /// Apply the per-flush message cap to already platform-split `chunks`. The /// note takes the last slot, so it is always posted when anything is dropped. @@ -925,7 +925,7 @@ mod tests { assert_eq!(got[MAX_FLUSH_MESSAGES - 1], TRUNCATED_NOTE); assert_eq!( TRUNCATED_NOTE, - "…(output truncated: this update stopped at 16 messages and the rest was not posted; later output is still relayed)" + "…(output truncated: this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed)" ); } diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index d44c4e9fc..8eed62ef7 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -83,7 +83,7 @@ workflows are enabled openab: the prompt response. If a run is still open at the cap, a warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. -Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that this update stopped at 16 messages and the rest was not posted, while later output is still relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. +Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are applied when a session is created with `session/new` only, not when a session is restored with `session/load`. From 618fcdfa0fb30ca944b86c7065e9f4dba4d2b483 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Thu, 19 Nov 2026 06:59:36 -0500 Subject: [PATCH 10/11] fix(kiro): address PR #1609 review findings F1-F4 F1 strict_default_config_options: a set_config_option response that does not list the requested option id now fails session creation (it used to pass). verify_config_option_applied returns an error with "the agent did not report the `` option"; the non-strict path is unchanged. Files: acp/connection.rs, acp/pool.rs. F2 session/update filter: while workflows are enabled, a session/update is kept only when params.sessionId is the served session's string id. Missing, null and non-string ids are dropped. Responses and other methods are untouched. No kiro-cli fixture omits sessionId; the repo's ACP schema requires it on SessionNotification, so this is a code change, not a documented exception. Files: acp/protocol.rs (is_foreign_session_update, test), adapter.rs call site unchanged in behaviour. F3 tail ordering: spawn_tail returns a completion receiver stored on the connection (conn.tail_done). The next turn waits for it right after session_prompt, bounded by DELIVER_TIMEOUT (30 s), before posting. New test next_reply_waits_for_the_previous_tail_final_flush. Files: workflow_tail.rs, adapter.rs, acp/connection.rs, docs/kiro-v3.md. F4 formatting churn: reverted rustfmt-only hunks in warn_force_evicting_hung, with_connection, set_config_option, get_usage, cancel, reset_session, the facade-token tests and the redaction test. git diff origin/main -- pool.rs now contains only PR hunks. Docs (docs/kiro-v3.md): strict-mode failure rule, sessionId rule, and the tail-ordering rule with its 30 s bound. Validation (macmini, worktree synced to ~/oab-verify-kiro-v3-fix2, DEVELOPER_DIR=/Library/Developer/CommandLineTools because the Xcode license is not accepted on macmini): - cargo clippy --workspace -- -D warnings: pass - cargo clippy --workspace --features unified -- -D warnings: pass - cargo test -p openab-core --no-fail-fast: 743 passed, 1 failed (known: secrets::tests::resolve_exec_nonzero_exit on macOS), 13 ignored - cargo test -p openab-core --lib config_option_tests -- --ignored: 10 passed (includes strict_response_without_options_fails_session_creation and strict_response_lacking_the_requested_option_fails_session_creation) - named: acp::protocol::tests::foreign_session_update_detection, acp::connection::workflow_meta_tests::verify_rejects_missing_option_or_empty_list, acp::connection::workflow_meta_tests::verify_rejects_kiro_v2_agent_option_for_mode_key, workflow_tail::tests::next_reply_waits_for_the_previous_tail_final_flush: all pass Known pre-existing, not changed: cargo fmt --check drift on main; the rustfmt drift in untouched lines of the changed files. --- crates/openab-core/src/acp/connection.rs | 35 ++++-- crates/openab-core/src/acp/pool.rs | 153 ++++++++--------------- crates/openab-core/src/acp/protocol.rs | 31 +++-- crates/openab-core/src/adapter.rs | 7 +- crates/openab-core/src/workflow_tail.rs | 68 +++++++++- docs/kiro-v3.md | 16 ++- 6 files changed, 179 insertions(+), 131 deletions(-) diff --git a/crates/openab-core/src/acp/connection.rs b/crates/openab-core/src/acp/connection.rs index 94012e7f8..006d64738 100644 --- a/crates/openab-core/src/acp/connection.rs +++ b/crates/openab-core/src/acp/connection.rs @@ -210,8 +210,10 @@ pub struct AcpConnection { pub last_active: Instant, pub activity: Arc, pub session_reset: bool, - _reader_handle: JoinHandle<()>, - _stderr_handle: Option>, + /// Completion of the workflow tail that took over the previous turn's late + /// output. The next turn waits for it before posting its own reply. + pub tail_done: Option>, + _reader_handle: JoinHandle<()>, _stderr_handle: Option>, /// Revokes this session's facade token when the connection is dropped, on any evict path. /// Held only for its `Drop` side effect (never read). /// @@ -274,17 +276,21 @@ pub(crate) fn build_session_new_params(cwd: &str, meta: Option<&Value>) -> Value /// Check that `session/set_config_option` really applied `requested` for /// `config_id`, using the option list the agent returned. /// -/// Lenient where the response is silent: no option with that id (or an empty -/// list) is accepted. A different `currentValue` is accepted only when the -/// returned option lists a value whose display `name` equals `requested` and -/// whose `value` is the current one (agents that normalize aliases). +/// An option list without `config_id` (including an empty list, which is what +/// a response with no `result` yields) is an error: the agent did not report +/// the option, so nothing confirms it. A different `currentValue` is accepted +/// only when the returned option lists a value whose display `name` equals +/// `requested` and whose `value` is the current one (agents that normalize +/// aliases). pub(crate) fn verify_config_option_applied( options: &[ConfigOption], config_id: &str, requested: &str, ) -> std::result::Result<(), String> { let Some(opt) = options.iter().find(|o| o.id == config_id) else { - return Ok(()); + return Err(format!( + "default_config_options `{config_id}` = `{requested}` was not verified: the agent did not report the `{config_id}` option in its response" + )); }; if opt.current_value == requested { return Ok(()); @@ -579,6 +585,7 @@ impl AcpConnection { last_active: Instant::now(), activity, session_reset: false, + tail_done: None, _reader_handle: reader_handle, _stderr_handle: stderr_handle, #[cfg(feature = "acp-mcp")] @@ -1584,10 +1591,12 @@ mod workflow_meta_tests { } #[test] - fn verify_accepts_missing_option_or_empty_list() { - assert!(verify_config_option_applied(&[], "mode", "e2e").is_ok()); + fn verify_rejects_missing_option_or_empty_list() { + let err = verify_config_option_applied(&[], "mode", "e2e").unwrap_err(); + assert!(err.contains("did not report the `mode` option"), "{err}"); let o = [opt("model", "x", &[])]; - assert!(verify_config_option_applied(&o, "mode", "e2e").is_ok()); + let err = verify_config_option_applied(&o, "mode", "e2e").unwrap_err(); + assert!(err.contains("did not report the `mode` option"), "{err}"); } #[test] @@ -1603,10 +1612,10 @@ mod workflow_meta_tests { } #[test] - fn verify_ignores_kiro_v2_agent_option_for_mode_key() { - // kiro v2 reports modes under id `agent`, so `mode` is simply absent. + fn verify_rejects_kiro_v2_agent_option_for_mode_key() { + // kiro v2 reports modes under id `agent`, so `mode` is absent: not verified. let o = [opt("agent", "kiro_default", &[("kiro_default", "default")])]; - assert!(verify_config_option_applied(&o, "mode", "openab-bot").is_ok()); + assert!(verify_config_option_applied(&o, "mode", "openab-bot").is_err()); } /// Step sessions ask for permission too; the answer goes out by request id diff --git a/crates/openab-core/src/acp/pool.rs b/crates/openab-core/src/acp/pool.rs index 661f2b94d..8a6617c31 100644 --- a/crates/openab-core/src/acp/pool.rs +++ b/crates/openab-core/src/acp/pool.rs @@ -116,12 +116,7 @@ fn classify_hung( /// either resumes the session, so both are credentials. Extracted from the loop in `cleanup_idle` /// so the redaction can be exercised by a test for real — R1 redacted the sites it enumerated and /// this force-evict site was outside that list, logging both ids raw. -fn warn_force_evicting_hung( - key: &str, - session_id: Option<&str>, - age_secs: u64, - threshold_secs: u64, -) { +fn warn_force_evicting_hung(key: &str, session_id: Option<&str>, age_secs: u64, threshold_secs: u64) { warn!( thread_id = %crate::redact::redact_session_ids(key), session_id = %session_id.map(crate::redact::redact_session_ids).unwrap_or_default(), @@ -663,13 +658,6 @@ impl SessionPool { match result { Ok(opts) => { if self.strict_default_config_options { - if !opts.iter().any(|o| o.id == *config_id) { - warn!( - config_id, - value, - "strict_default_config_options: the agent did not report this option, so it could not be verified" - ); - } // Returning drops `new_conn`, which kills the agent process group. super::connection::verify_config_option_applied( &opts, config_id, value, @@ -779,12 +767,7 @@ impl SessionPool { // supersedes under the same key (its guard cannot fire if that predecessor is hung). F3. #[cfg(feature = "acp-mcp")] if let Some(token) = session_token { - install_facade_token( - &mut state, - thread_id, - token, - self.session_registrar.as_ref(), - ); + install_facade_token(&mut state, thread_id, token, self.session_registrar.as_ref()); } self.save_mapping(&state.persisted); @@ -819,12 +802,11 @@ impl SessionPool { { let conn = { let state = self.state.read().await; - state.active.get(thread_id).cloned().ok_or_else(|| { - anyhow!( - "no connection for thread {}", - crate::redact::redact_session_ids(thread_id) - ) - })? + state + .active + .get(thread_id) + .cloned() + .ok_or_else(|| anyhow!("no connection for thread {}", crate::redact::redact_session_ids(thread_id)))? }; let mut conn = conn.lock().await; @@ -852,12 +834,11 @@ impl SessionPool { ) -> Result> { let conn = { let state = self.state.read().await; - state.active.get(thread_id).cloned().ok_or_else(|| { - anyhow!( - "no connection for thread {}", - crate::redact::redact_session_ids(thread_id) - ) - })? + state + .active + .get(thread_id) + .cloned() + .ok_or_else(|| anyhow!("no connection for thread {}", crate::redact::redact_session_ids(thread_id)))? }; let mut conn = conn.lock().await; conn.set_config_option(config_id, value).await @@ -869,12 +850,11 @@ impl SessionPool { pub async fn get_usage(&self, thread_id: &str) -> Result { let conn = { let state = self.state.read().await; - state.active.get(thread_id).cloned().ok_or_else(|| { - anyhow!( - "no connection for thread {}", - crate::redact::redact_session_ids(thread_id) - ) - })? + state + .active + .get(thread_id) + .cloned() + .ok_or_else(|| anyhow!("no connection for thread {}", crate::redact::redact_session_ids(thread_id)))? }; let mut conn = conn.lock().await; conn.get_usage().await @@ -889,12 +869,7 @@ impl SessionPool { .cancel_handles .get(thread_id) .cloned() - .ok_or_else(|| { - anyhow!( - "no session for thread {}", - crate::redact::redact_session_ids(thread_id) - ) - })? + .ok_or_else(|| anyhow!("no session for thread {}", crate::redact::redact_session_ids(thread_id)))? }; let data = serde_json::to_string(&serde_json::json!({ "jsonrpc": "2.0", @@ -919,10 +894,7 @@ impl SessionPool { info!(thread_id = %crate::redact::redact_session_ids(thread_id), "session reset"); Ok(()) } else { - Err(anyhow!( - "no session for thread {}", - crate::redact::redact_session_ids(thread_id) - )) + Err(anyhow!("no session for thread {}", crate::redact::redact_session_ids(thread_id))) } } @@ -1213,28 +1185,11 @@ mod tests { let mut state = empty_pool_state(); // Predecessor registers, then a successor takes over the SAME key. - super::install_facade_token( - &mut state, - "discord:acp_x", - "T_pred".into(), - Some(®istrar), - ); - assert!( - reg.revoked().is_empty(), - "nothing to revoke on the first install" - ); - super::install_facade_token( - &mut state, - "discord:acp_x", - "T_succ".into(), - Some(®istrar), - ); + super::install_facade_token(&mut state, "discord:acp_x", "T_pred".into(), Some(®istrar)); + assert!(reg.revoked().is_empty(), "nothing to revoke on the first install"); + super::install_facade_token(&mut state, "discord:acp_x", "T_succ".into(), Some(®istrar)); - assert_eq!( - reg.revoked(), - vec!["T_pred"], - "the predecessor token must be revoked" - ); + assert_eq!(reg.revoked(), vec!["T_pred"], "the predecessor token must be revoked"); assert_eq!( state.facade_tokens.get("discord:acp_x").map(String::as_str), Some("T_succ"), @@ -1251,25 +1206,14 @@ mod tests { let reg = Arc::new(CountingRegistrar::default()); let registrar: Arc = reg.clone(); let mut state = empty_pool_state(); - state - .facade_tokens - .insert("discord:acp_x".into(), "T_hung".into()); + state.facade_tokens.insert("discord:acp_x".into(), "T_hung".into()); // A different session's token must be untouched. - state - .facade_tokens - .insert("discord:acp_y".into(), "T_other".into()); + state.facade_tokens.insert("discord:acp_y".into(), "T_other".into()); super::revoke_facade_token_for_key(&mut state, "discord:acp_x", Some(®istrar)); - assert_eq!( - reg.revoked(), - vec!["T_hung"], - "only the evicted session's token is revoked" - ); - assert!( - !state.facade_tokens.contains_key("discord:acp_x"), - "and it is forgotten" - ); + assert_eq!(reg.revoked(), vec!["T_hung"], "only the evicted session's token is revoked"); + assert!(!state.facade_tokens.contains_key("discord:acp_x"), "and it is forgotten"); assert_eq!( state.facade_tokens.get("discord:acp_y").map(String::as_str), Some("T_other"), @@ -1476,23 +1420,11 @@ mod tests { }); let out = String::from_utf8(buf.lock().unwrap().clone()).unwrap(); - assert!( - out.contains("force-evicting hung session"), - "the warning must fire: {out}" - ); + assert!(out.contains("force-evicting hung session"), "the warning must fire: {out}"); assert!(!out.contains(uuid), "no raw uuid may reach the log: {out}"); - assert!( - !out.contains("acp_") && !out.contains("sess_"), - "no raw id prefix either: {out}" - ); - assert!( - out.contains('#'), - "the redaction tag must be present: {out}" - ); - assert!( - out.contains("discord"), - "the readable platform half must survive: {out}" - ); + assert!(!out.contains("acp_") && !out.contains("sess_"), "no raw id prefix either: {out}"); + assert!(out.contains('#'), "the redaction tag must be present: {out}"); + assert!(out.contains("discord"), "the readable platform half must survive: {out}"); } #[test] @@ -1763,10 +1695,31 @@ mod config_option_tests { #[tokio::test] #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] - async fn strict_response_without_options_keeps_legacy_behaviour() { + async fn strict_response_without_options_fails_session_creation() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; let p = pool(dir.path(), reply, false, None, true); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("did not report the `mode` option"), "{err}"); + assert!(p.state.read().await.active.is_empty()); + } + + #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] + async fn strict_response_lacking_the_requested_option_fails_session_creation() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"type":"select","id":"model","name":"Model","currentValue":"x","options":[]}]}}"#; + let p = pool(dir.path(), reply, false, None, true); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("did not report the `mode` option"), "{err}"); + } + + #[tokio::test] + #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] + async fn non_strict_response_without_options_is_accepted() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; + let p = pool(dir.path(), reply, false, None, false); assert!(p.get_or_create("t", None).await.is_ok()); } diff --git a/crates/openab-core/src/acp/protocol.rs b/crates/openab-core/src/acp/protocol.rs index 0c6f36fc0..88d3733f0 100644 --- a/crates/openab-core/src/acp/protocol.rs +++ b/crates/openab-core/src/acp/protocol.rs @@ -409,20 +409,21 @@ pub enum AcpEvent { Status, } -/// True only for a `session/update` notification that carries a string -/// `params.sessionId` different from `expected_session_id`. Such frames come -/// from another session of the same agent process (e.g. Kiro workflow step -/// sessions). Frames without a `sessionId`, other methods and responses are -/// never foreign. +/// True for a `session/update` notification whose `params.sessionId` is not the +/// string `expected_session_id`. Such frames come from another session of the +/// same agent process (e.g. Kiro workflow step sessions), or cannot be tied to +/// the served session: a missing, null or non-string `sessionId` also counts. +/// Other methods and responses are never foreign. pub fn is_foreign_session_update(msg: &JsonRpcMessage, expected_session_id: &str) -> bool { if msg.id.is_some() || msg.method.as_deref() != Some("session/update") { return false; } - msg.params + let session_id = msg + .params .as_ref() .and_then(|p| p.get("sessionId")) - .and_then(Value::as_str) - .is_some_and(|sid| sid != expected_session_id) + .and_then(Value::as_str); + session_id != Some(expected_session_id) } /// Kiro workflow lifecycle signal relevant to the served (parent) session. @@ -537,15 +538,21 @@ mod tests { fn foreign_session_update_detection() { assert!(!is_foreign_session_update(&chunk(Some("p"), "x"), "p")); assert!(is_foreign_session_update(&chunk(Some("step"), "x"), "p")); - assert!(!is_foreign_session_update(&chunk(None, "x"), "p")); + // A frame that cannot be tied to the parent session is not parent traffic. + assert!(is_foreign_session_update(&chunk(None, "x"), "p")); + let null_id = msg(json!({"method": "session/update", + "params": {"sessionId": null, "update": {}}})); + assert!(is_foreign_session_update(&null_id, "p")); + let numeric_id = msg(json!({"method": "session/update", + "params": {"sessionId": 7, "update": {}}})); + assert!(is_foreign_session_update(&numeric_id, "p")); + let no_params = msg(json!({"method": "session/update"})); + assert!(is_foreign_session_update(&no_params, "p")); let other_method = msg(json!({"method": "_kiro/other", "params": {"sessionId": "step"}})); assert!(!is_foreign_session_update(&other_method, "p")); let response = msg(json!({"id": 3, "result": {"sessionId": "step"}})); assert!(!is_foreign_session_update(&response, "p")); - let non_string = msg(json!({"method": "session/update", - "params": {"sessionId": 7, "update": {}}})); - assert!(!is_foreign_session_update(&non_string, "p")); } #[test] diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 391c91839..2bce5ea30 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -783,6 +783,11 @@ impl AdapterRouter { conn.session_reset = false; let (mut rx, request_id) = conn.session_prompt(content_blocks).await?; + // The previous turn's tail ends when this prompt replaced its + // subscriber. Let its final flush post before this reply does. + if let Some(done) = conn.tail_done.take() { + crate::workflow_tail::wait_for_previous_tail(done).await; + } let parent_sid = conn.acp_session_id.clone(); let mut wf_state = crate::workflow_tail::TurnWorkflowState::default(); if assistant_status { @@ -1089,7 +1094,7 @@ impl AdapterRouter { gate_tx = Some(g_tx); let tail_adapter = adapter.clone(); let tail_channel = thread_channel.clone(); - tokio::spawn(crate::workflow_tail::run_tail( + conn.tail_done = Some(crate::workflow_tail::spawn_tail( rx, sid, std::mem::take(&mut wf_state).into_open(), diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index 8e80e0ca0..09249f357 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use std::time::Duration; use tokio::sync::mpsc::{self, error::TrySendError}; use tokio::sync::oneshot; -use tokio::time::{sleep_until, timeout_at, Instant}; +use tokio::time::{sleep_until, timeout, timeout_at, Instant}; /// Bounds for the late-output relay (`[pool] workflow_tail_*`). #[derive(Debug, Clone, Copy)] @@ -251,6 +251,39 @@ pub async fn run_tail( } } +/// Start [`run_tail`] on a detached task. The returned receiver resolves once +/// the tail has returned, after its final flush. The next turn on the same +/// connection waits on it with [`wait_for_previous_tail`] before posting. +pub fn spawn_tail( + rx: RelayReceiver, + parent_session_id: String, + open: HashSet, + cfg: WorkflowRelayConfig, + started: Instant, + gate: oneshot::Receiver<()>, + deliver: F, +) -> oneshot::Receiver<()> +where + F: FnMut(String) -> Fut + Send + 'static, + Fut: Future + Send + 'static, +{ + let (done_tx, done_rx) = oneshot::channel(); + tokio::spawn(async move { + run_tail(rx, parent_session_id, open, cfg, started, gate, deliver).await; + let _ = done_tx.send(()); + }); + done_rx +} + +/// Wait until a previous tail has finished its final flush, so the next reply +/// is not posted into the middle of it. Gives up after [`DELIVER_TIMEOUT`]; a +/// tail still delivering then may overlap the reply. +pub async fn wait_for_previous_tail(done: oneshot::Receiver<()>) { + if timeout(DELIVER_TIMEOUT, done).await.is_err() { + tracing::warn!("previous workflow tail still delivering; starting the next reply anyway"); + } +} + /// Mutable bookkeeping of one tail. struct TailState { parent: String, @@ -710,6 +743,39 @@ mod tests { assert_eq!(*out.lock().unwrap(), vec!["late".to_string()]); } + #[tokio::test(start_paused = true)] + async fn next_reply_waits_for_the_previous_tail_final_flush() { + let (tx, rx) = relay_channel(); + let log = Arc::new(Mutex::new(Vec::::new())); + let sink = log.clone(); + // The tail's delivery takes 5 s and records itself only when it completes. + let deliver = move |t: String| { + let sink = sink.clone(); + async move { + tokio::time::sleep(Duration::from_secs(5)).await; + sink.lock().unwrap().push(format!("tail: {t}")); + } + }; + tx.send(chunk(PARENT, "late")).unwrap(); + // The next prompt on the session replaces the subscriber: the tail ends. + drop(tx); + let done = spawn_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + open_gate(), + deliver, + ); + wait_for_previous_tail(done).await; + log.lock().unwrap().push("next reply".into()); + assert_eq!( + *log.lock().unwrap(), + vec!["tail: late".to_string(), "next reply".to_string()] + ); + } + #[tokio::test(start_paused = true)] async fn stalled_delivery_does_not_hold_the_tail_forever() { let (tx, rx) = relay_channel(); diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index 8eed62ef7..3d4e2834d 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -61,7 +61,7 @@ an empty file is the reliable way to run without them. | Setting | Effect | |---------|--------| | `[agent] session_new_meta` | Sent as the `_meta` field of the `session/new` request. kiro-cli only honours the workflows switch there (not in `initialize`). Not sent on `session/load`. | -| `[pool] strict_default_config_options` | After each `session/set_config_option`, compares the returned `currentValue` with the requested value and fails session creation on a mismatch or an error. In this mode the legacy slash-command fallback is not used, so only a value the agent reports counts. A response without that option is accepted, as is an alias given as the option's display name. Default `false`. | +| `[pool] strict_default_config_options` | After each `session/set_config_option`, compares the returned `currentValue` with the requested value. Session creation fails when the agent returns an error, when the response does not list the requested option id (including a response with no result), or when the value does not match. The error says the agent did not report the option, or that the value was not applied. In this mode the legacy slash-command fallback is not used, so only a value the agent reports counts. An alias given as the option's display name is accepted. Default `false`. Without strict mode, an error from `set_config_option` is logged as a warning and the session is created anyway; the returned value is not checked. | `[pool] workflow_tail_quiet_secs` / `workflow_tail_max_secs` | Bounds of the late-output relay below. | ## Workflows @@ -71,9 +71,14 @@ workflow ends. The summary arrives later as unsolicited message chunks of the sa workflows are enabled openab: 1. **Filters step sessions.** Each workflow step runs in its own ACP session and streams - `session/update` frames with a different `params.sessionId`. Those frames are dropped from - the reply. Frames without a `sessionId` are never dropped. Permission requests from step - sessions are still auto-answered. + `session/update` frames with a different `params.sessionId`. openab accepts a `session/update` + only when its `params.sessionId` is the string id of the served session, and drops every other + one: another id, or a missing, null or non-string `sessionId`. The check applies to + notifications only; responses and other methods are not affected. The ACP schema in this repo + (`crates/openab-gateway/schemas/acp-v1.schema.json`) requires `sessionId` on + `SessionNotification`, and the existing mock agents and tests send it. No kiro-cli frame is known + to omit it. If a kiro-cli release starts omitting it, parent text is dropped and this rule needs + revisiting. Permission requests from step sessions are still auto-answered. 2. **Relays the late summary.** If a workflow started for the session during the turn, openab keeps reading after delivering the reply and posts the late text as a new message in the same thread, prefixed `_Workflow update:_`. Text is posted after `workflow_tail_quiet_secs` without @@ -82,6 +87,9 @@ workflows are enabled openab: closes, when the next prompt on the session starts, or at `workflow_tail_max_secs`, measured from the prompt response. If a run is still open at the cap, a warning message says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. + Ordering: the next prompt's reply is not posted until the previous relay has finished its final + flush. That wait lasts at most 30 s (the delivery timeout). If the previous flush is still + posting after that, the two can overlap. Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is From 5011eabb89be094c34036b182cb8191983a5497d Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Thu, 19 Nov 2026 18:49:40 -0500 Subject: [PATCH 11/11] fix(kiro): cancel the late workflow tail on teardown, run lifecycle tests in CI F1: the next reply no longer gives up on the previous workflow tail after DELIVER_TIMEOUT. wait_for_previous_tail (workflow_tail.rs) waits with no timeout. The connection cancels a tail before the next prompt replaces its subscriber (AcpConnection::session_prompt drops tail_cancel), and on teardown (dropping the connection drops tail_cancel). A cancelled tail discards buffered text, drops an in-flight deliver, and signals completion, so nothing posts after the cancel and the wait cannot hang. TailControl {gate, cancel} replaces the bare gate in run_tail and spawn_tail; adapter.rs creates the cancel channel. docs/kiro-v3.md documents the cancel path. Tests (workflow_tail.rs): next reply waits for a slow previous flush and is not interleaved; teardown cancels an in-progress tail and nothing posts after the next reply starts; a cancelled tail does not post buffered text. The connection test next_prompt_replaces_subscriber_and_ends_the_tail now expects buffered text to be discarded on the next prompt. F2: removed #[ignore] from the 13 lifecycle tests (connection.rs workflow_meta_tests, pool.rs config_option_tests). They run in the required CI check job, in the cargo test --workspace step. They use a local sh mock agent and tempdirs, need no network, and passed on three repeats. Validation (macmini, rsync of this worktree): - cargo clippy --workspace -- -D warnings: pass - cargo clippy --workspace --features unified -- -D warnings: pass - cargo test -p openab-core: 758 passed, 1 failed (secrets::tests::resolve_exec_nonzero_exit, pre-existing on macOS) - cargo test -p openab-core -- --include-ignored (900 s bound): 758 passed, 1 failed (same pre-existing test) - lifecycle and workflow_tail tests, 3 repeats: 44 passed each run --- crates/openab-core/src/acp/connection.rs | 36 ++-- crates/openab-core/src/acp/pool.rs | 10 - crates/openab-core/src/adapter.rs | 12 +- crates/openab-core/src/workflow_tail.rs | 235 ++++++++++++++++++----- docs/kiro-v3.md | 25 ++- 5 files changed, 244 insertions(+), 74 deletions(-) diff --git a/crates/openab-core/src/acp/connection.rs b/crates/openab-core/src/acp/connection.rs index 006d64738..38e6c1ccb 100644 --- a/crates/openab-core/src/acp/connection.rs +++ b/crates/openab-core/src/acp/connection.rs @@ -213,6 +213,10 @@ pub struct AcpConnection { /// Completion of the workflow tail that took over the previous turn's late /// output. The next turn waits for it before posting its own reply. pub tail_done: Option>, + /// Cancel signal of that tail. Dropping the sender cancels the tail: it discards + /// buffered text and ends. `session_prompt` drops it before the next prompt replaces + /// the subscriber, and dropping the connection drops it on teardown. + pub tail_cancel: Option>, _reader_handle: JoinHandle<()>, _stderr_handle: Option>, /// Revokes this session's facade token when the connection is dropped, on any evict path. /// Held only for its `Drop` side effect (never read). @@ -586,6 +590,7 @@ impl AcpConnection { activity, session_reset: false, tail_done: None, + tail_cancel: None, _reader_handle: reader_handle, _stderr_handle: stderr_handle, #[cfg(feature = "acp-mcp")] @@ -850,6 +855,9 @@ impl AcpConnection { .as_ref() .ok_or_else(|| anyhow!("no session"))?; + // Cancel the previous turn's tail before its subscriber is replaced, so it posts + // nothing from this point on. Its buffered text is discarded. + self.tail_cancel.take(); let (tx, rx) = mpsc::unbounded_channel(); *self.notify_tx.lock().await = Some(NotifySink::Prompt(tx)); @@ -1675,7 +1683,6 @@ mod workflow_meta_tests { #[cfg(unix)] #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess"] async fn session_new_with_meta_sends_underscore_meta() { let script = mock_agent::script(&mock_agent::mode_reply("vibe"), true); let meta = json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); @@ -1693,7 +1700,6 @@ mod workflow_meta_tests { #[cfg(unix)] #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess"] async fn set_config_option_returns_agent_reported_value() { let script = mock_agent::script(&mock_agent::mode_reply("vibe"), false); let mut conn = spawn_mock(script).await; @@ -1721,15 +1727,14 @@ done"# .to_string() } - /// The next `session_prompt` replaces the subscriber: the running tail - /// flushes what it buffered and ends, and the new receiver sees only the - /// new turn's frames. + /// The next `session_prompt` cancels the running tail: it posts nothing, + /// its buffered text is discarded, and the new receiver sees only the new + /// turn's frames. #[cfg(unix)] #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess"] async fn next_prompt_replaces_subscriber_and_ends_the_tail() { use super::ContentBlock; - use crate::workflow_tail::{run_tail, WorkflowRelayConfig}; + use crate::workflow_tail::{run_tail, TailControl, WorkflowRelayConfig}; use std::time::Duration; let mut conn = spawn_mock(late_chunk_script()).await; @@ -1754,6 +1759,8 @@ done"# let sink = out.clone(); let (gate_tx, gate_rx) = tokio::sync::oneshot::channel(); gate_tx.send(()).unwrap(); + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); + conn.tail_cancel = Some(cancel_tx); let tail = tokio::spawn(run_tail( rx1, "s-1".to_string(), @@ -1763,13 +1770,17 @@ done"# tail_max: Duration::from_secs(60), }, tokio::time::Instant::now(), - gate_rx, + TailControl { + gate: gate_rx, + cancel: cancel_rx, + }, move |t| { sink.lock().unwrap().push(t); std::future::ready(()) }, )); - // Let late-3 reach the tail's buffer before the swap. + // Let late-3 reach the tail's buffer before the cancel. The assertion + // below holds whether or not it got there. tokio::time::sleep(Duration::from_millis(500)).await; let (mut rx2, id2) = conn @@ -1778,9 +1789,12 @@ done"# .unwrap(); tokio::time::timeout(Duration::from_secs(5), tail) .await - .expect("tail must end when the subscriber is replaced") + .expect("tail must end when the next prompt cancels it") .unwrap(); - assert_eq!(*out.lock().unwrap(), vec!["late-3".to_string()]); + assert!( + out.lock().unwrap().is_empty(), + "a cancelled tail posts nothing" + ); let mut texts = Vec::new(); let mut got_response = false; diff --git a/crates/openab-core/src/acp/pool.rs b/crates/openab-core/src/acp/pool.rs index 8a6617c31..f8d6d679c 100644 --- a/crates/openab-core/src/acp/pool.rs +++ b/crates/openab-core/src/acp/pool.rs @@ -1649,7 +1649,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn mismatch_is_ignored_by_default() { let dir = tempfile::tempdir().unwrap(); let p = pool( @@ -1663,7 +1662,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_mismatch_fails_session_creation() { let dir = tempfile::tempdir().unwrap(); let p = pool( @@ -1680,7 +1678,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_match_succeeds() { let dir = tempfile::tempdir().unwrap(); let p = pool( @@ -1694,7 +1691,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_response_without_options_fails_session_creation() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; @@ -1705,7 +1701,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_response_lacking_the_requested_option_fails_session_creation() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"type":"select","id":"model","name":"Model","currentValue":"x","options":[]}]}}"#; @@ -1715,7 +1710,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn non_strict_response_without_options_is_accepted() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; @@ -1724,7 +1718,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_error_response_fails_session_creation() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; @@ -1734,7 +1727,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn non_strict_error_response_is_only_a_warning() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; @@ -1743,7 +1735,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn session_new_meta_is_sent_when_configured() { let dir = tempfile::tempdir().unwrap(); let meta = serde_json::json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); @@ -1759,7 +1750,6 @@ mod config_option_tests { } #[tokio::test] - #[ignore = "integration: spawns a mock agent subprocess and uses the filesystem"] async fn strict_error_is_not_masked_by_a_successful_slash_fallback() { let dir = tempfile::tempdir().unwrap(); let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 2bce5ea30..e4a0d23c5 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -783,8 +783,8 @@ impl AdapterRouter { conn.session_reset = false; let (mut rx, request_id) = conn.session_prompt(content_blocks).await?; - // The previous turn's tail ends when this prompt replaced its - // subscriber. Let its final flush post before this reply does. + // This prompt cancelled the previous turn's tail (see + // `session_prompt`). Let its final post, if any, land before this reply. if let Some(done) = conn.tail_done.take() { crate::workflow_tail::wait_for_previous_tail(done).await; } @@ -1092,6 +1092,9 @@ impl AdapterRouter { if let (Some(cfg), Some(rx), Some(sid)) = (tail_cfg, tail_rx, parent_sid) { let (g_tx, gate_rx) = tokio::sync::oneshot::channel::<()>(); gate_tx = Some(g_tx); + // Dropping `cancel_tx` (next prompt or connection teardown) cancels the tail. + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); + conn.tail_cancel = Some(cancel_tx); let tail_adapter = adapter.clone(); let tail_channel = thread_channel.clone(); conn.tail_done = Some(crate::workflow_tail::spawn_tail( @@ -1100,7 +1103,10 @@ impl AdapterRouter { std::mem::take(&mut wf_state).into_open(), cfg, tail_started, - gate_rx, + crate::workflow_tail::TailControl { + gate: gate_rx, + cancel: cancel_rx, + }, move |text| { let adapter = tail_adapter.clone(); let channel = tail_channel.clone(); diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs index 09249f357..4a36b404a 100644 --- a/crates/openab-core/src/workflow_tail.rs +++ b/crates/openab-core/src/workflow_tail.rs @@ -7,8 +7,10 @@ //! delivered and hands it to [`run_tail`], which buffers that text and posts //! it as a follow-up message. //! -//! The tail holds no connection lock. The next prompt on the same session -//! replaces the subscriber, which closes the receiver and ends the tail. +//! The tail holds no connection lock. The connection cancels the tail before +//! the next prompt on the same session replaces the subscriber, and when the +//! connection is torn down (see [`TailControl`]). A cancelled tail discards +//! its buffered text and posts nothing more. use crate::acp::protocol::JsonRpcMessage; use crate::acp::{ @@ -22,7 +24,7 @@ use std::sync::Arc; use std::time::Duration; use tokio::sync::mpsc::{self, error::TrySendError}; use tokio::sync::oneshot; -use tokio::time::{sleep_until, timeout, timeout_at, Instant}; +use tokio::time::{sleep_until, timeout_at, Instant}; /// Bounds for the late-output relay (`[pool] workflow_tail_*`). #[derive(Debug, Clone, Copy)] @@ -154,18 +156,31 @@ pub fn limit_flush_messages(mut chunks: Vec, max: usize, note: &str) -> chunks } +/// Gate and cancel signals of one tail. +/// +/// `gate` resolves once the original reply has been delivered. `cancel` ends +/// the tail: it is cancelled when its sender is dropped, which the connection +/// does before the next prompt on the session and on teardown. Both a sent +/// value and a dropped sender count as a signal for `cancel`, and a dropped +/// `gate` counts as open. +pub struct TailControl { + pub gate: oneshot::Receiver<()>, + pub cancel: oneshot::Receiver<()>, +} + /// Read late frames from `rx` and hand text to `deliver`. /// /// `started` is when the prompt response arrived: the hard cap is measured -/// from it, not from when this task starts. `gate` resolves once the original -/// reply has been delivered; the tail starts draining `rx` immediately (so the -/// queue does not grow while the reply is finalized) but posts nothing before -/// the gate opens. A dropped gate counts as open. +/// from it, not from when this task starts. The tail starts draining `rx` +/// immediately (so the queue does not grow while the reply is finalized) but +/// posts nothing before `control.gate` opens. /// /// Quiet time only decides when buffered text is posted. The tail does not end /// on quiet, so output that arrives after a gap is still delivered. It ends -/// when the channel closes (flushing what is buffered) or at the hard cap -/// (flushing, and reporting through `deliver` if a run is still open). Any +/// when the channel closes (flushing what is buffered), at the hard cap +/// (flushing, and reporting through `deliver` if a run is still open), or when +/// `control.cancel` fires. A cancel discards buffered text, drops an in-flight +/// `deliver`, and posts nothing afterwards; it does not flush. Any /// parent-session `session/update` restarts the quiet timer. Buffered text is /// limited to [`MAX_BUFFER_BYTES`] and each `deliver` to [`DELIVER_TIMEOUT`]. /// Frames dropped on a full queue ([`RELAY_QUEUE_CAPACITY`]) mark the flushed @@ -176,13 +191,13 @@ pub async fn run_tail( open: HashSet, cfg: WorkflowRelayConfig, started: Instant, - gate: oneshot::Receiver<()>, + control: TailControl, mut deliver: F, ) where F: FnMut(String) -> Fut, Fut: Future, { - let mut gate = gate; + let TailControl { mut gate, cancel } = control; let mut gated = true; let hard = started + cfg.tail_max; let mut st = TailState { @@ -193,6 +208,8 @@ pub async fn run_tail( last_event: Instant::now(), closed: false, ending: false, + cancel, + cancelled: false, }; loop { let quiet_applies = !st.buf.is_empty() || st.open.is_empty(); @@ -202,15 +219,31 @@ pub async fn run_tail( hard }; tokio::select! { + biased; + _ = &mut st.cancel => { + // Discard what is buffered and end. Nothing is posted. + st.cancelled = true; + return; + } _ = &mut gate, if gated => { gated = false; } msg = rx.recv() => { let Some(msg) = msg else { if gated { - // Wait for the original reply, but not past the cap. - if timeout_at(hard, &mut gate).await.is_err() { - return; + // Wait for the original reply, but not past the cap or + // a cancel. + tokio::select! { + biased; + _ = &mut st.cancel => { + st.cancelled = true; + return; + } + r = timeout_at(hard, &mut gate) => { + if r.is_err() { + return; + } + } } } flush(&mut st, &mut rx, &mut deliver).await; @@ -230,12 +263,18 @@ pub async fn run_tail( return; } flush(&mut st, &mut rx, &mut deliver).await; + if st.cancelled { + return; + } if at_cap || Instant::now() >= hard { // Frames drained while that delivery was pending are still // buffered: one bounded final flush (frames arriving during // it are dropped, the tail ends here). st.ending = true; flush(&mut st, &mut rx, &mut deliver).await; + if st.cancelled { + return; + } if !st.open.is_empty() { send(&mut st, &mut rx, &mut deliver, format!( "⚠ workflow still running after {}s; further output is not relayed", @@ -252,15 +291,16 @@ pub async fn run_tail( } /// Start [`run_tail`] on a detached task. The returned receiver resolves once -/// the tail has returned, after its final flush. The next turn on the same -/// connection waits on it with [`wait_for_previous_tail`] before posting. +/// the tail has returned: after its final flush, or right after a cancel. The +/// next turn on the same connection waits on it with +/// [`wait_for_previous_tail`] before posting. pub fn spawn_tail( rx: RelayReceiver, parent_session_id: String, open: HashSet, cfg: WorkflowRelayConfig, started: Instant, - gate: oneshot::Receiver<()>, + control: TailControl, deliver: F, ) -> oneshot::Receiver<()> where @@ -269,19 +309,20 @@ where { let (done_tx, done_rx) = oneshot::channel(); tokio::spawn(async move { - run_tail(rx, parent_session_id, open, cfg, started, gate, deliver).await; + run_tail(rx, parent_session_id, open, cfg, started, control, deliver).await; let _ = done_tx.send(()); }); done_rx } -/// Wait until a previous tail has finished its final flush, so the next reply -/// is not posted into the middle of it. Gives up after [`DELIVER_TIMEOUT`]; a -/// tail still delivering then may overlap the reply. +/// Wait until a previous tail has finished, so the next reply is not posted +/// into the middle of it. There is no timeout. The connection cancels the +/// previous tail before the next prompt, and a cancelled tail returns as soon +/// as its in-flight delivery is dropped, so this wait cannot hang on a stalled +/// platform call. A tail that is not cancelled is still running and this +/// waits for it. pub async fn wait_for_previous_tail(done: oneshot::Receiver<()>) { - if timeout(DELIVER_TIMEOUT, done).await.is_err() { - tracing::warn!("previous workflow tail still delivering; starting the next reply anyway"); - } + let _ = done.await; } /// Mutable bookkeeping of one tail. @@ -296,6 +337,10 @@ struct TailState { /// The final delivery is running: queued frames are read and dropped so /// the queue keeps draining until the tail returns. ending: bool, + /// Fires when the connection cancels this tail. Polled by every wait. + cancel: oneshot::Receiver<()>, + /// Set once a cancel was observed. Nothing is posted afterwards. + cancelled: bool, } impl TailState { @@ -344,10 +389,20 @@ where F: FnMut(String) -> Fut, Fut: Future, { + if st.cancelled { + return; + } let fut = tokio::time::timeout(DELIVER_TIMEOUT, deliver(text)); tokio::pin!(fut); loop { tokio::select! { + biased; + _ = &mut st.cancel => { + // Drops the in-flight delivery: the platform call stops at its + // next await, and nothing else is posted. + st.cancelled = true; + return; + } _ = &mut fut => return, msg = rx.recv(), if !st.closed => match msg { Some(m) => { @@ -432,6 +487,21 @@ mod tests { rx } + /// A cancel signal that never fires. Its sender is leaked on purpose so the + /// receiver stays open for the whole test. + fn never_cancelled() -> oneshot::Receiver<()> { + let (tx, rx) = oneshot::channel(); + std::mem::forget(tx); + rx + } + + fn open_control() -> TailControl { + TailControl { + gate: open_gate(), + cancel: never_cancelled(), + } + } + fn open_set(ids: &[&str]) -> HashSet { ids.iter().map(|s| s.to_string()).collect() } @@ -449,7 +519,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -470,7 +540,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -479,7 +549,7 @@ mod tests { } #[tokio::test(start_paused = true)] - async fn replaced_subscriber_flushes_buffer_and_ends() { + async fn closed_channel_flushes_buffer_and_ends() { let (tx, rx) = relay_channel(); let (out, deliver) = collector(); tx.send(chunk(PARENT, "partial")).unwrap(); @@ -490,7 +560,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -508,7 +578,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -529,7 +599,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, )); tx.send(chunk(PARENT, "first")).unwrap(); @@ -556,7 +626,7 @@ mod tests { HashSet::new(), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -575,7 +645,7 @@ mod tests { HashSet::new(), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, )); tx.send(run_complete()).unwrap(); @@ -597,7 +667,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, )); tx.send(chunk(PARENT, "A")).unwrap(); @@ -634,7 +704,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -656,7 +726,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -683,7 +753,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ) .await; @@ -710,7 +780,7 @@ mod tests { open_set(&["wf_1"]), cfg(), started, - open_gate(), + open_control(), deliver, ) .await; @@ -730,7 +800,10 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - gate_rx, + TailControl { + gate: gate_rx, + cancel: never_cancelled(), + }, deliver, )); tx.send(run_complete()).unwrap(); @@ -765,7 +838,7 @@ mod tests { HashSet::new(), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ); wait_for_previous_tail(done).await; @@ -776,6 +849,82 @@ mod tests { ); } + #[tokio::test(start_paused = true)] + async fn cancelled_tail_discards_buffered_text() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let (cancel_tx, cancel_rx) = oneshot::channel(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + TailControl { + gate: open_gate(), + cancel: cancel_rx, + }, + deliver, + )); + tx.send(chunk(PARENT, "buffered")).unwrap(); + // Buffered, but the 20 s quiet mark has not come yet. + tokio::time::sleep(Duration::from_secs(5)).await; + drop(cancel_tx); + handle.await.unwrap(); + assert!(out.lock().unwrap().is_empty()); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn teardown_cancels_an_in_progress_tail_and_nothing_posts_after_the_next_reply() { + let (tx, rx) = relay_channel(); + let log = Arc::new(Mutex::new(Vec::::new())); + let sink = log.clone(); + // The platform call for the flush never returns on its own. + let deliver = move |t: String| { + let sink = sink.clone(); + async move { + sink.lock().unwrap().push(format!("post: {t}")); + std::future::pending::<()>().await; + } + }; + tx.send(chunk(PARENT, "late")).unwrap(); + let (cancel_tx, cancel_rx) = oneshot::channel(); + let done = spawn_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + TailControl { + gate: open_gate(), + cancel: cancel_rx, + }, + deliver, + ); + // Quiet mark (20 s) passed: the flush is in flight and blocked. + tokio::time::sleep(Duration::from_secs(25)).await; + assert_eq!(*log.lock().unwrap(), vec!["post: late".to_string()]); + + // Teardown: the connection drops its cancel sender. + drop(cancel_tx); + let waited = Instant::now(); + wait_for_previous_tail(done).await; + assert!( + waited.elapsed() < DELIVER_TIMEOUT, + "the wait must end on cancel, not after the delivery timeout" + ); + log.lock().unwrap().push("next reply".into()); + + // Well past the delivery timeout, the cancelled tail still posts nothing. + tokio::time::sleep(Duration::from_secs(120)).await; + drop(tx); + assert_eq!( + *log.lock().unwrap(), + vec!["post: late".to_string(), "next reply".to_string()] + ); + } + #[tokio::test(start_paused = true)] async fn stalled_delivery_does_not_hold_the_tail_forever() { let (tx, rx) = relay_channel(); @@ -801,7 +950,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, )); // Quiet (20 s) plus one delivery timeout (30 s); the tail must still @@ -854,7 +1003,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ); tokio::join!(tail, flood); @@ -904,7 +1053,7 @@ mod tests { open_set(&["wf_1"]), cfg(), Instant::now(), - open_gate(), + open_control(), deliver, ); tokio::join!(tail, flood); @@ -954,7 +1103,7 @@ mod tests { HashSet::new(), c, Instant::now(), - open_gate(), + open_control(), deliver, ); tokio::join!(tail, late); diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md index 3d4e2834d..820098c9f 100644 --- a/docs/kiro-v3.md +++ b/docs/kiro-v3.md @@ -83,13 +83,24 @@ workflows are enabled openab: keeps reading after delivering the reply and posts the late text as a new message in the same thread, prefixed `_Workflow update:_`. Text is posted after `workflow_tail_quiet_secs` without new output, so text that arrives after a long pause is still delivered. Thinking and tool - activity count as output for this timer but are not posted. The relay ends when the connection - closes, when the next prompt on the session starts, or at `workflow_tail_max_secs`, measured from - the prompt response. If a run is still open at the cap, a warning message says that further - output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay and keeps the filter. - Ordering: the next prompt's reply is not posted until the previous relay has finished its final - flush. That wait lasts at most 30 s (the delivery timeout). If the previous flush is still - posting after that, the two can overlap. + activity count as output for this timer but are not posted. The relay ends when the channel closes + (flushing what it holds), at `workflow_tail_max_secs`, measured from the prompt response, or when + it is cancelled (see the cancel path below). If a run is still open at the cap, a warning message + says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay + and keeps the filter. + Ordering: the next prompt's reply is not posted until the previous relay has finished. That wait + has no timeout. The next prompt cancels the previous relay first, so the wait ends as soon as the + relay drops its in-flight post. + + **Cancel path.** A relay is cancelled by two events. The first is the next `session/prompt` on + the same connection: `session_prompt` drops the connection's cancel sender before it replaces the + subscriber. The second is teardown of the connection (reset, idle cleanup, pool eviction, or + shutdown): dropping the connection drops the same sender. A cancelled relay discards its + buffered, unposted text, drops any platform call still in flight at its next await, and returns. + It posts nothing after the cancel, and it signals completion so the next reply can start. A + cancel does not flush. Buffered text is therefore lost when the user sends another message before + the quiet time has passed. A connection whose streaming task is stuck still holds its + connection, so its relay is cancelled only when that task releases it. Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. Late text that arrives after the next prompt started is part of that prompt's reply. The relay is