From f09d51bd49ff60fcffaaa38b9658ea8f4fdef106 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 3 Dec 2026 15:12:27 +0800 Subject: [PATCH] fix(agents): track and stop Codex background terminals (#7722) A command Codex leaves running after its turn was invisible to the task, so the idle release stopped the app-server and the command kept running in its own process group. The Codex adapter now lists background terminals (thread/backgroundTerminals/list) after each turn until none runs and reports them as background tasks, which the idle release waits for; stop_task maps to terminate; session close and connection close run clean first. Older Codex versions report none. Fixes #7655 --- crates/ide-agent/src/native/codex/mod.rs | 157 ++++++++++++++++- crates/ide-agent/src/native/codex/tests.rs | 161 +++++++++++++++++- .../ide-agent/src/native/codex/translate.rs | 14 ++ 3 files changed, 327 insertions(+), 5 deletions(-) diff --git a/crates/ide-agent/src/native/codex/mod.rs b/crates/ide-agent/src/native/codex/mod.rs index 2d69fadbf..55c0a6376 100644 --- a/crates/ide-agent/src/native/codex/mod.rs +++ b/crates/ide-agent/src/native/codex/mod.rs @@ -34,6 +34,14 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200); const EARLY_CANCEL: Duration = Duration::from_secs(1); /// How long the client's connection outlives codex. const EXIT_GRACE: Duration = Duration::from_millis(100); +/// How often running background terminals are listed again: codex announces neither a +/// terminal that outlives its turn nor its end. +#[cfg(not(test))] +const TERMINAL_POLL: Duration = Duration::from_secs(3); +#[cfg(test)] +const TERMINAL_POLL: Duration = Duration::from_millis(20); +/// How long closing the connection waits for codex to stop the background terminals. +const TERMINAL_CLEAN: Duration = Duration::from_secs(3); /// What a thread's name is asked for with, after its first turn. const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \ language the user writes in. Reply with the title only, without quotes or a closing period."; @@ -187,6 +195,10 @@ fn attach( } tokio::spawn(async move { to_client.closed().await; + // Background terminals run in process groups of their own: stopping codex alone + // would leave them running with nothing left to report or stop them. + let threads: Vec = shim.state.lock().threads.keys().cloned().collect(); + shim.clean_terminals(&threads).await; codex.kill(); }); Ok(ours) @@ -248,6 +260,14 @@ struct Thread { token_usage: Option, /// The thread has a name. named: bool, + /// Running background terminals of this session and its subagents, by task id: + /// `(thread, processId)`. + terminals: HashMap, + /// The background tasks reported last. + shown_tasks: Vec, + /// The background terminals are being followed; `relist` asks for another listing. + watching: bool, + relist: bool, /// A name is being asked for. naming: bool, } @@ -416,6 +436,7 @@ impl CodexShim { "session/prompt" => self.prompt(¶ms).await, "_openidea/steer" => self.steer(¶ms).await, "_openidea/rollback" => self.rollback(¶ms).await, + "_openidea/stop_task" => self.stop_task(¶ms).await, "session/close" => self.close(¶ms).await, _ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))), } @@ -439,7 +460,7 @@ impl CodexShim { "promptCapabilities": { "image": true, "audio": false, "embeddedContext": true }, "mcpCapabilities": { "http": false, "sse": false, "stdio": true }, "sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} }, - "_meta": { "openidea": { "rollback": true, "steer": true } }, + "_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } }, }, "agentInfo": { "name": "codex", "title": "Codex", "version": version }, "authMethods": [], @@ -915,6 +936,16 @@ impl CodexShim { /// Stops following the session's thread (codex unloads it once nothing follows it). async fn close(&self, params: &Value) -> Result { let session = str_param(params, "sessionId")?; + let threads: Vec = { + let state = self.state.lock(); + state + .threads + .iter() + .filter(|(id, t)| *id == session || t.parent.as_deref() == Some(session)) + .map(|(id, _)| id.clone()) + .collect() + }; + self.clean_terminals(&threads).await; let known = self.state.lock().threads.remove(session).is_some(); if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await { tracing::debug!("codex: unsubscribing from {session}: {}", e.message); @@ -922,6 +953,129 @@ impl CodexShim { Ok(json!({})) } + /// Follows the background terminals of `session` and its subagents until none runs: + /// codex keeps them running after the turn that started them. + fn watch_terminals(self: &Arc, session: &str) { + { + let mut state = self.state.lock(); + if state.gone { + return; + } + let Some(t) = state.threads.get_mut(session) else { return }; + if t.watching { + t.relist = true; + return; + } + t.watching = true; + } + let (shim, session) = (self.clone(), session.to_owned()); + self.runtime.spawn(async move { + loop { + let running = shim.list_terminals(&session).await; + let relist = { + let mut state = shim.state.lock(); + let Some(t) = state.threads.get_mut(&session) else { return }; + let relist = std::mem::take(&mut t.relist); + if !relist && !running { + t.watching = false; + return; + } + relist + }; + if !relist { + tokio::time::sleep(TERMINAL_POLL).await; + } + } + }); + } + + /// Reports the running background terminals of `session` and its subagents as the + /// session's background tasks; whether any runs. A codex without the (experimental) + /// listing has none to report. + async fn list_terminals(&self, session: &str) -> bool { + let threads: Vec = { + let state = self.state.lock(); + let children = state.threads.iter().filter(|(_, t)| t.parent.as_deref() == Some(session)); + std::iter::once(session.to_owned()).chain(children.map(|(id, _)| id.clone())).collect() + }; + let mut terminals = HashMap::new(); + let mut tasks = Vec::new(); + for thread in &threads { + let listed = match self.terminals_of(thread).await { + Ok(listed) => listed, + Err(e) => { + tracing::debug!("codex: listing the background terminals of {thread}: {}", e.message); + continue; + } + }; + for (process, description) in listed { + let id = if thread == session { process.clone() } else { format!("{thread}:{process}") }; + tasks.push(json!({ "task_id": id, "task_type": "local_bash", "description": description })); + terminals.insert(id, (thread.clone(), process)); + } + } + let running = !tasks.is_empty(); + let changed = { + let mut state = self.state.lock(); + let Some(t) = state.threads.get_mut(session) else { return false }; + t.terminals = terminals; + let changed = t.shown_tasks != tasks; + if changed { + t.shown_tasks = tasks.clone(); + } + changed + }; + if changed { + self.emit(session, json!({ "sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks })); + } + running + } + + /// The running background terminals of `thread`, as `(processId, description)`. + async fn terminals_of(&self, thread: &str) -> Result, ResponseError> { + let mut all = Vec::new(); + let mut cursor = Value::Null; + let mut seen = HashSet::new(); + loop { + let page = + self.call("thread/backgroundTerminals/list", json!({ "threadId": thread, "cursor": cursor })).await?; + all.extend(translate::background_terminals(&page)); + match page.get("nextCursor").and_then(Value::as_str) { + Some(next) if !next.is_empty() && seen.insert(next.to_owned()) => cursor = json!(next), + _ => return Ok(all), + } + } + } + + /// `_openidea/stop_task`: stops one background terminal. + async fn stop_task(&self, params: &Value) -> Result { + let session = str_param(params, "sessionId")?; + let task = str_param(params, "taskId")?; + let known = self.state.lock().threads.get(session).and_then(|t| t.terminals.get(task).cloned()); + let (thread, process) = known.unwrap_or_else(|| (session.to_owned(), task.to_owned())); + self.call("thread/backgroundTerminals/terminate", json!({ "threadId": thread, "processId": process })).await?; + self.list_terminals(session).await; + Ok(json!({})) + } + + /// Stops the background terminals of `threads`; a codex without the (experimental) + /// method has none. + async fn clean_terminals(&self, threads: &[String]) { + if threads.is_empty() || self.state.lock().gone { + return; + } + let clean = async { + for thread in threads { + if let Err(e) = self.call("thread/backgroundTerminals/clean", json!({ "threadId": thread })).await { + tracing::debug!("codex: stopping the background terminals of {thread}: {}", e.message); + } + } + }; + if tokio::time::timeout(TERMINAL_CLEAN, clean).await.is_err() { + tracing::warn!("codex: stopping the background terminals timed out"); + } + } + /// `session/cancel`: interrupts the session's turn, or the one about to start. fn cancel(&self, session: &str) { let mut state = self.state.lock(); @@ -1275,6 +1429,7 @@ impl CodexShim { t.naming |= name; (t.parent.clone(), (answer, error), name) }; + self.watch_terminals(parent.as_deref().unwrap_or(thread)); if name { let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned()); self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await }); diff --git a/crates/ide-agent/src/native/codex/tests.rs b/crates/ide-agent/src/native/codex/tests.rs index 71b74273c..6b4c67571 100644 --- a/crates/ide-agent/src/native/codex/tests.rs +++ b/crates/ide-agent/src/native/codex/tests.rs @@ -1020,10 +1020,12 @@ async fn play( .unwrap() .unwrap_or_else(|| panic!("the shim closed before {frame}")); let actual: Value = serde_json::from_str(&line).unwrap(); - // Older recordings predate config inspection, skill discovery and thread naming; play an - // unsupported server. + // Older recordings predate config inspection, skill discovery, thread naming and + // background terminals; play an unsupported server. let method = actual["method"].as_str().unwrap_or_default(); - if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method { + let unrecorded = matches!(method, "config/read" | "skills/list" | "thread/sample") + || method.starts_with("thread/backgroundTerminals/"); + if unrecorded && frame["method"] != method { let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } }); write.write_all(format!("{reply}\n").as_bytes()).await.unwrap(); continue; @@ -1244,7 +1246,10 @@ async fn auth_failure_names_auth() { let (results, _client, frames, _) = replay(Scenario::AuthFailure).await; let init = result(&results, "initialize").as_ref().unwrap(); assert_eq!(init["agentCapabilities"]["loadSession"], true); - assert_eq!(init["agentCapabilities"]["_meta"]["openidea"], json!({"rollback": true, "steer": true})); + assert_eq!( + init["agentCapabilities"]["_meta"]["openidea"], + json!({"rollback": true, "steer": true, "backgroundTasks": true}) + ); assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object()); let new = result(&results, "new").as_ref().unwrap(); let categories: Vec<&str> = @@ -2216,3 +2221,151 @@ async fn an_ephemeral_session_starts_an_ephemeral_thread() { native.kill(); } } + +/// A codex whose background terminals listings come from `pages` (an empty list after +/// them); `None` answers like a codex without the method. +struct TerminalServer { + pages: Mutex>, + supported: bool, + calls: Mutex>, +} + +impl TerminalServer { + fn new(pages: Vec, supported: bool) -> Arc { + Arc::new(Self { pages: Mutex::new(pages.into()), supported, calls: Mutex::default() }) + } + + fn calls_of(&self, method: &str) -> Vec { + self.calls.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect() + } +} + +impl Handler for TerminalServer { + fn on_notification(&self, _: &str, _: Value) {} + + fn on_request(&self, method: &str, params: Value) -> Result { + self.calls.lock().push((method.to_owned(), params)); + match method { + "initialize" => Ok(json!({})), + "model/list" => Ok(json!({"data": []})), + "config/read" => Ok(json!({"layers": []})), + "thread/start" => Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": "/w"})), + "skills/list" => Ok(json!({"data": []})), + "thread/unsubscribe" => Ok(json!({})), + m if m.starts_with("thread/backgroundTerminals/") && !self.supported => { + Err((codes::INVALID_REQUEST, format!("Invalid request: unknown variant `{m}`"))) + } + "thread/backgroundTerminals/list" => { + Ok(self.pages.lock().pop_front().unwrap_or_else(|| json!({"data": [], "nextCursor": null}))) + } + "thread/backgroundTerminals/terminate" => Ok(json!({"terminated": true})), + "thread/backgroundTerminals/clean" => Ok(json!({})), + _ => Err((codes::METHOD_NOT_FOUND, method.to_owned())), + } + } +} + +fn terminal(process: &str, command: &str) -> Value { + json!({"itemId": format!("item-{process}"), "processId": process, "command": command, "cwd": "/w", "osPid": 4242}) +} + +/// A session over a codex playing `server`; the codex peer and the ACP peer. +async fn terminal_session(server: Arc, client: Arc) -> (Peer, Peer) { + let (ours, theirs) = tokio::io::duplex(1 << 16); + let (read, write) = tokio::io::split(theirs); + let native = Peer::connect_framed(read, write, server, Framing::Lines); + let acp = attach(client, |events| { + let (read, write) = tokio::io::split(ours); + Ok(Peer::connect_framed(read, write, events, Framing::Lines)) + }) + .unwrap(); + let init = request(&acp, "initialize", json!({})).await.unwrap(); + assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true); + request(&acp, "session/new", json!({"cwd": "/w", "mcpServers": []})).await.unwrap(); + (native, acp) +} + +fn shown_tasks(client: &Client) -> Vec { + client + .of("s") + .into_iter() + .filter(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE) + .map(|u| u["tasks"].clone()) + .collect() +} + +async fn until(what: &str, mut done: impl FnMut() -> bool) { + for _ in 0..200 { + if done() { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("timed out waiting for {what}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn background_terminals_outlive_their_turn_as_background_tasks_until_they_end() { + let running = json!({"data": [terminal("p1", "/bin/zsh -lc 'sleep 600; echo done'")], "nextCursor": null}); + let server = TerminalServer::new(vec![running.clone(), running.clone(), running], true); + let client = Arc::new(Client::default()); + let (native, acp) = terminal_session(server.clone(), client.clone()).await; + native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap(); + until("the terminal to end", || shown_tasks(&client).len() == 2).await; + assert_eq!( + shown_tasks(&client), + [json!([{"task_id": "p1", "task_type": "local_bash", "description": "sleep 600; echo done"}]), json!([])] + ); + let listed = server.calls_of("thread/backgroundTerminals/list").len(); + assert!(listed >= 4, "listed until none ran, got {listed}"); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), listed, "stops listing once none runs"); + acp.kill(); + native.kill(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_background_terminal_stops_on_request_and_all_stop_with_the_connection() { + let running = json!({"data": [terminal("p1", "cargo nextest run")], "nextCursor": null}); + let server = TerminalServer::new(vec![running; 1000], true); + let client = Arc::new(Client::default()); + let (native, acp) = terminal_session(server.clone(), client.clone()).await; + native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap(); + until("the terminal to show", || !shown_tasks(&client).is_empty()).await; + request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.unwrap(); + assert_eq!(server.calls_of("thread/backgroundTerminals/terminate"), [json!({"threadId": "s", "processId": "p1"})]); + assert!(server.calls_of("thread/backgroundTerminals/clean").is_empty()); + acp.kill(); + until("the terminals to be cleaned", || !server.calls_of("thread/backgroundTerminals/clean").is_empty()).await; + assert_eq!(server.calls_of("thread/backgroundTerminals/clean"), [json!({"threadId": "s"})]); + native.kill(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn closing_a_session_stops_its_background_terminals() { + let server = TerminalServer::new(Vec::new(), true); + let client = Arc::new(Client::default()); + let (native, acp) = terminal_session(server.clone(), client).await; + request(&acp, "session/close", json!({"sessionId": "s"})).await.unwrap(); + let calls: Vec = server.calls.lock().iter().map(|(m, _)| m.clone()).collect(); + let clean = calls.iter().position(|m| m == "thread/backgroundTerminals/clean").expect("cleaned"); + let unsubscribe = calls.iter().position(|m| m == "thread/unsubscribe").expect("unsubscribed"); + assert!(clean < unsubscribe); + acp.kill(); + native.kill(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_codex_without_background_terminals_reports_none() { + let server = TerminalServer::new(Vec::new(), false); + let client = Arc::new(Client::default()); + let (native, acp) = terminal_session(server.clone(), client.clone()).await; + native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap(); + until("the listing", || !server.calls_of("thread/backgroundTerminals/list").is_empty()).await; + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), 1); + assert!(shown_tasks(&client).is_empty()); + assert!(request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.is_err()); + acp.kill(); + native.kill(); +} diff --git a/crates/ide-agent/src/native/codex/translate.rs b/crates/ide-agent/src/native/codex/translate.rs index c2a63ea4c..2bc9277af 100644 --- a/crates/ide-agent/src/native/codex/translate.rs +++ b/crates/ide-agent/src/native/codex/translate.rs @@ -881,6 +881,20 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec { out } +/// One page of `thread/backgroundTerminals/list`: the running terminals as +/// `(processId, description)`. +pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> { + let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + data.iter() + .filter_map(|t| { + let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?; + let command = t.get("command").and_then(Value::as_str).unwrap_or_default(); + let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned()); + Some((process.to_owned(), description)) + }) + .collect() +} + /// A command prefix as typed: the script of a ` -lc