From fe2d7c9d2a2e182f078be1281f0ea622bcb333f2 Mon Sep 17 00:00:00 2001 From: ClanEver <562211524@qq.com> Date: Sun, 6 Dec 2026 00:51:59 +0800 Subject: [PATCH 1/3] Antigravity: fix native subagent lifecycle, surface full-history native subagents, model switches, and collapsible plan cards --- crates/agent/src/antigravity.rs | 79 +- crates/agent/src/antigravity/record.rs | 369 ++++- crates/agent/src/antigravity/subagents.rs | 1417 +++++++++++++++++-- crates/protocol/src/event.rs | 31 + crates/protocol/src/lib.rs | 9 +- crates/runtime/src/app/events.rs | 4 +- crates/runtime/src/app/lifecycle.rs | 13 +- crates/runtime/src/app/send.rs | 27 +- crates/runtime/src/app/snapshots.rs | 64 +- crates/runtime/src/app/subagents.rs | 48 +- crates/runtime/src/app/tests/mirrors.rs | 128 ++ crates/ui/src/agents_panel.rs | 154 +- crates/ui/src/agents_panel/tests.rs | 209 +++ crates/ui/src/chat/components/plan.rs | 107 +- crates/ui/src/chat/timeline/render.rs | 36 +- crates/ui/src/chat/timeline/render/tests.rs | 82 ++ crates/ui/src/shell/tests/mod.rs | 1 + crates/ui/src/store/snapshots.rs | 1 + 18 files changed, 2519 insertions(+), 260 deletions(-) diff --git a/crates/agent/src/antigravity.rs b/crates/agent/src/antigravity.rs index ce87ca255..bcddfc51d 100644 --- a/crates/agent/src/antigravity.rs +++ b/crates/agent/src/antigravity.rs @@ -465,6 +465,9 @@ pub(super) fn normalize_mcp_tool_name(raw: &str, mcp_servers: &[String]) -> Opti struct Antigravity { /// The agent's own record of the session (`conversations/.db`). record: Mutex>, + /// Incremental tailer of the session's `transcript.jsonl` to surface + /// mid-session served-model switches (e.g. Orchestrator planner <-> worker). + model_tailer: Mutex>, /// Tracks the last seen step index and any open autonomous (proactive) /// turn so both `session_update` and the background watcher stay in sync. proactive: Arc>, @@ -596,6 +599,14 @@ impl Antigravity { .clone() } + fn poll_served_models(&self) -> Vec { + let mut guard = self + .model_tailer + .lock() + .unwrap_or_else(|held| held.into_inner()); + guard.as_mut().map_or_else(Vec::new, |t| t.poll()) + } + /// Whether `update` begins autonomous (proactive) work when no turn is /// open. Late `tool_call_update`s for a tool from an earlier turn (such as /// a `schedule` timer completing) stay on that tool and do not open a new @@ -902,17 +913,38 @@ impl Dialect for Antigravity { if let Some(state_dir) = state_dirs(&opts.launch_env).into_iter().next() { let path = record::path(&state_dir, &session_id.0); + let transcript = record::transcript_path(&state_dir, &session_id.0); + let initial_model = opts.model.clone().or_else(|| { + crate::acp_session::model_config_option(&config_options).and_then(|option| { + match &option.kind { + acp::SessionConfigKind::Select(select) => { + Some(select.current_value.0.to_string()) + } + _ => None, + } + }) + }); // A session that goes on has steps already; a new one has none. - let seen = if resumed && !anew { + let (seen, model_tailer) = { let path = path.clone(); - crate::process::unblock(move || record::last_step(&path)) - .await - .map(|step| step.index) - } else { - Some(-1) + let seed_db = resumed && !anew; + crate::process::unblock(move || { + let seen = if seed_db { + record::last_step(&path).map(|step| step.index) + } else { + Some(-1) + }; + let tailer = record::ParentModelTailer::open(transcript, initial_model); + (seen, tailer) + }) + .await }; *self.record.lock().unwrap_or_else(|held| held.into_inner()) = Some(SessionRecord { path }); + *self + .model_tailer + .lock() + .unwrap_or_else(|held| held.into_inner()) = Some(model_tailer); self.proactive .lock() .unwrap_or_else(|held| held.into_inner()) @@ -923,6 +955,7 @@ impl Dialect for Antigravity { let watcher = subagents::run_watcher(subagents::WatcherContext { state_dir, session_id: session_id.0.to_string(), + parent_cwd: opts.cwd.clone(), acp_state: setup.state.clone(), proactive: self.proactive.clone(), mcp_servers: self.mcp_servers.clone(), @@ -1008,6 +1041,11 @@ impl Dialect for Antigravity { match ¬ification.update { acp::SessionUpdate::ToolCall(call) => { + let served = self.poll_served_models(); + if !served.is_empty() { + events.extend(state.flush_text()); + events.extend(served); + } if let Some(spawn) = subagents::parse_spawn(call) { events.extend(state.flush_text()); if call.status == acp::ToolCallStatus::Failed { @@ -1027,11 +1065,23 @@ impl Dialect for Antigravity { })); } else { events.extend(subagents::spawn_events(&spawn)); + let tool_call_id = spawn.tool_call_id.clone(); self.spawned_subagents .lock() .unwrap_or_else(|held| held.into_inner()) - .insert(spawn.tool_call_id.clone(), spawn.clone()); + .insert(tool_call_id.clone(), spawn.clone()); self.send_watcher(subagents::WatcherCommand::Spawned(spawn)); + if call.status == acp::ToolCallStatus::Completed + && let Some(ack) = subagents::parse_spawn_ack( + Some(&call.content), + call.raw_output.as_ref(), + ) + { + self.send_watcher(subagents::WatcherCommand::SpawnBound { + tool_call_id, + ack, + }); + } } return events; } @@ -1105,6 +1155,16 @@ impl Dialect for Antigravity { effort: None, }, })); + } else if update.fields.status == Some(acp::ToolCallStatus::Completed) + && let Some(ack) = subagents::parse_spawn_ack( + update.fields.content.as_deref(), + update.fields.raw_output.as_ref(), + ) + { + self.send_watcher(subagents::WatcherCommand::SpawnBound { + tool_call_id: spawn.tool_call_id, + ack, + }); } // The immediate `completed` update on `invoke_subagent` // only acknowledges the async spawn; the watcher settles @@ -1204,6 +1264,11 @@ impl Dialect for Antigravity { } if is_usage_update { + let served = self.poll_served_models(); + if !served.is_empty() { + events.extend(state.flush_text()); + events.extend(served); + } let mut tracker = self .proactive .lock() diff --git a/crates/agent/src/antigravity/record.rs b/crates/agent/src/antigravity/record.rs index caedc7151..d3171498e 100644 --- a/crates/agent/src/antigravity/record.rs +++ b/crates/agent/src/antigravity/record.rs @@ -10,18 +10,27 @@ //! `session/update` with no `session/prompt` response; the step log and record //! say when the final reply step completed and what tokens it used. +use std::collections::HashSet; +use std::fs::File; +use std::io::{BufRead, BufReader, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use serde::Deserialize; use turso::Value; -use crate::{ContextFreshness, TokenUsage, TurnStatus}; +use crate::{AgentEvent, ContextFreshness, TokenUsage, TurnStatus}; /// The type of the step a turn ends on when its upstream request failed: the /// last step of every such turn in the records agy 1.5.14 wrote for prompts /// its API refused. const ERROR_STEP: i64 = 17; +/// Step statuses observed in agy 1.5.25 `conversations/.db`: +/// `3` = DONE, `6` = RUNNING (background task), `7` = ERROR, +/// `8` = GENERATING (in-flight planner response), `9` = CANCELED. +const STEP_STATUS_RUNNING: i64 = 6; +const STEP_STATUS_GENERATING: i64 = 8; + /// The last step a session's record holds. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct LastStep { @@ -29,6 +38,23 @@ pub(super) struct LastStep { pub(super) error: bool, } +/// Snapshot of a session's SQLite step table: its latest step plus any +/// still-active (`RUNNING` or `GENERATING`) steps. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(super) struct RecordState { + pub(super) last: Option, + /// True while any step in the database is `GENERATING` (8). + pub(super) has_generating_step: bool, + /// Step indices currently marked `RUNNING` (6) in the database. + pub(super) running_steps: HashSet, +} + +impl RecordState { + pub(super) fn has_active_step(&self) -> bool { + self.has_generating_step || !self.running_steps.is_empty() + } +} + /// The completion of an agent-initiated (proactive) turn, read from the /// session's database and transcript log. #[derive(Debug, Clone, PartialEq)] @@ -74,13 +100,11 @@ pub(super) fn transcript_path(state_dir: &Path, session_id: &str) -> PathBuf { .join("transcript.jsonl") } -/// The last step in the record at `record`; `None` where it holds none yet -/// or cannot be read. The agent has the file open while the session lives, as -/// SQLite shares it; it is opened read-only, which takes no lock on it and -/// reads the steps still in its write-ahead log. -pub(super) fn last_step(record: &Path) -> Option { - match read_last_step(record) { - Ok(step) => step, +/// Read the latest step and any active (`RUNNING` / `GENERATING`) steps from +/// `record`; `None` when the file is absent or cannot be read. +pub(super) fn record_state(record: &Path) -> Option { + match read_record_state(record) { + Ok(state) => state, Err(err) => { log::debug!( "antigravity: the session record {} was not read: {err}", @@ -91,9 +115,18 @@ pub(super) fn last_step(record: &Path) -> Option { } } +/// The last step in the record at `record`; `None` where it holds none yet +/// or cannot be read. The agent has the file open while the session lives, as +/// SQLite shares it; it is opened read-only, which takes no lock on it and +/// reads the steps still in its write-ahead log. +pub(super) fn last_step(record: &Path) -> Option { + record_state(record)?.last +} + /// Whether the autonomous (proactive) work that began after `after_step` has /// reached a terminal step: either an `ERROR_STEP` in the session database or -/// a completed `PLANNER_RESPONSE` with no `tool_calls` in `transcript.jsonl`. +/// a completed `PLANNER_RESPONSE` with no `tool_calls` in `transcript.jsonl`, +/// provided no step is currently `RUNNING` or `GENERATING` in the database. /// When `after_step` is unknown (`None`), token summation across earlier steps /// is skipped and only `context` is returned. pub(super) fn proactive_turn_end( @@ -102,15 +135,20 @@ pub(super) fn proactive_turn_end( after_step: Option, context: Option, ) -> Option { - if let Some(last) = last_step(record) - && last.error - && after_step.is_none_or(|seen| last.index > seen) - { - return Some(ProactiveEnd { - step_index: last.index, - status: TurnStatus::Failed, - usage: context, - }); + if let Some(state) = record_state(record) { + if state.has_generating_step { + return None; + } + if let Some(last) = state.last + && last.error + && after_step.is_none_or(|seen| last.index > seen) + { + return Some(ProactiveEnd { + step_index: last.index, + status: TurnStatus::Failed, + usage: context, + }); + } } let text = std::fs::read_to_string(transcript).ok()?; @@ -186,7 +224,10 @@ pub(super) fn proactive_turn_end( }) } -fn read_last_step(record: &Path) -> Result, String> { +fn read_record_state(record: &Path) -> Result, String> { + if !record.exists() { + return Ok(None); + } // Turso's API is async and drives its own I/O. smol::future::block_on(async { let failed = |err: turso::Error| err.to_string(); @@ -203,19 +244,161 @@ fn read_last_step(record: &Path) -> Result, String> { .await .map_err(failed)?; let mut rows = statement.query(()).await.map_err(failed)?; - let Some(row) = rows.next().await.map_err(failed)? else { - return Ok(None); + let last = match rows.next().await.map_err(failed)? { + None => None, + Some(row) => match (row.get_value(0), row.get_value(1)) { + (Ok(Value::Integer(index)), Ok(Value::Integer(kind))) => Some(LastStep { + index, + error: kind == ERROR_STEP, + }), + other => return Err(format!("a step row read as {other:?}")), + }, }; - match (row.get_value(0), row.get_value(1)) { - (Ok(Value::Integer(index)), Ok(Value::Integer(kind))) => Ok(Some(LastStep { - index, - error: kind == ERROR_STEP, - })), - other => Err(format!("a step row read as {other:?}")), + let mut has_generating_step = false; + let mut running_steps = HashSet::new(); + // Older test fixtures omit the `status` column; degrade cleanly when absent. + if let Ok(mut active_stmt) = connection + .prepare(&format!( + "SELECT idx, status FROM steps WHERE status IN ({STEP_STATUS_RUNNING}, {STEP_STATUS_GENERATING})" + )) + .await + && let Ok(mut active_rows) = active_stmt.query(()).await + { + while let Ok(Some(row)) = active_rows.next().await { + if let (Ok(Value::Integer(index)), Ok(Value::Integer(status))) = + (row.get_value(0), row.get_value(1)) + { + if status == STEP_STATUS_GENERATING { + has_generating_step = true; + } else if status == STEP_STATUS_RUNNING { + running_steps.insert(index); + } + } + } } + Ok(Some(RecordState { + last, + has_generating_step, + running_steps, + })) }) } +/// Strip Antigravity's per-step thought-level suffix (`-minimal`, `-low`, +/// `-medium`, `-high`, `-max`) from a `transcript.jsonl` model id so +/// `gemini-4-neon-high` compares equal to the catalog id `gemini-4-neon` and +/// thought-level changes do not emit false model switches. +pub(super) fn normalize_served_model(raw: &str) -> String { + let trimmed = raw.trim(); + for suffix in ["-minimal", "-low", "-medium", "-high", "-max"] { + if let Some(base) = trimmed.strip_suffix(suffix) + && !base.is_empty() + { + return base.to_owned(); + } + } + trimmed.to_owned() +} + +#[derive(Deserialize)] +struct ModelStepLine { + #[serde(rename = "type")] + kind: String, + #[serde(default)] + model: Option, +} + +/// Incremental reader for a session's `transcript.jsonl` that reports +/// [`AgentEvent::ServedModel`] whenever Antigravity switches the model serving +/// `PLANNER_RESPONSE` steps (e.g. Orchestrator handing off between its +/// planning model and execution model, where `agy acp` emits no wire model +/// change update). +pub(super) struct ParentModelTailer { + path: PathBuf, + offset: u64, + last_model: Option, +} + +impl ParentModelTailer { + /// Seed from any existing transcript lines (without emitting historical + /// changes), falling back to `initial_model` for a fresh session. + pub(super) fn open(path: PathBuf, initial_model: Option) -> Self { + let mut tailer = Self { + path, + offset: 0, + last_model: initial_model + .as_deref() + .map(normalize_served_model) + .filter(|m| !m.is_empty()), + }; + let _ = tailer.drain_models(false); + tailer + } + + /// Read any newly appended complete lines from `transcript.jsonl` and emit + /// [`AgentEvent::ServedModel`] for each observed model transition. + pub(super) fn poll(&mut self) -> Vec { + self.drain_models(true) + } + + fn drain_models(&mut self, emit: bool) -> Vec { + let Ok(meta) = std::fs::metadata(&self.path) else { + return Vec::new(); + }; + if meta.len() <= self.offset { + return Vec::new(); + } + let Ok(mut file) = File::open(&self.path) else { + return Vec::new(); + }; + if file.seek(SeekFrom::Start(self.offset)).is_err() { + return Vec::new(); + } + let mut reader = BufReader::new(file); + let mut events = Vec::new(); + loop { + let mut line = String::new(); + let Ok(read) = reader.read_line(&mut line) else { + break; + }; + if read == 0 || !line.ends_with('\n') { + break; + } + self.offset += read as u64; + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + let Ok(step) = serde_json::from_str::(trimmed) else { + continue; + }; + if step.kind != "PLANNER_RESPONSE" { + continue; + } + let Some(model) = step + .model + .as_deref() + .map(normalize_served_model) + .filter(|m| !m.is_empty()) + else { + continue; + }; + if self.last_model.as_deref() == Some(model.as_str()) { + continue; + } + let from = self.last_model.replace(model.clone()); + if emit && from.is_some() { + events.push(AgentEvent::ServedModel { + model, + from, + reason: None, + }); + } + } + events + } +} + #[cfg(test)] mod tests { use super::*; @@ -351,8 +534,138 @@ mod tests { assert_eq!(end.step_index, 3); assert_eq!(end.status, TurnStatus::Failed); - for path in [db, db_done, db_err] { + // While SQLite reports an in-flight `GENERATING` step (status 8), the + // proactive turn is still running even if earlier steps ended. + let dir_gen = + std::env::temp_dir().join(format!("tcode-agy-record-gen-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir_gen).unwrap(); + let db_gen = dir_gen.join("session.db"); + smol::future::block_on(async { + let database = turso::Builder::new_local(&db_gen.to_string_lossy()) + .build() + .await + .unwrap(); + let connection = database.connect().unwrap(); + connection + .execute( + "CREATE TABLE steps (idx integer, step_type integer NOT NULL DEFAULT 0, status integer NOT NULL DEFAULT 3, PRIMARY KEY (idx))", + (), + ) + .await + .unwrap(); + for (idx, kind, status) in [ + (1_i64, 15_i64, 3_i64), + (2, 132, STEP_STATUS_RUNNING), + (3, ERROR_STEP, 3), + (4, 15, STEP_STATUS_GENERATING), + ] { + connection + .execute( + "INSERT INTO steps (idx, step_type, status) VALUES (?, ?, ?)", + (idx, kind, status), + ) + .await + .unwrap(); + } + }); + let state = record_state(&db_gen).unwrap(); + assert!(state.has_generating_step); + assert!(state.running_steps.contains(&2)); + assert!(state.has_active_step()); + assert_eq!( + proactive_turn_end(&db_gen, &transcript, Some(1), context), + None + ); + + for path in [db, db_done, db_err, db_gen] { std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); } } + + /// Orchestrator turns switch models in `transcript.jsonl` + /// (`gemini-pro-orchestrator-neon` <-> `gemini-flash-worker-agy`) without + /// emitting ACP config updates; `ParentModelTailer` emits `ServedModel` on + /// real switches while ignoring thought-level suffixes and historical lines. + #[test] + fn parent_model_tailer_tracks_orchestrator_switches_and_ignores_thought_suffixes() { + let dir = + std::env::temp_dir().join(format!("tcode-agy-model-tail-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let transcript = dir.join("transcript.jsonl"); + + // Fresh non-orchestrator session: `-high` suffix matches requested base model. + let mut plain = + ParentModelTailer::open(transcript.clone(), Some("gemini-4-neon".to_owned())); + std::fs::write( + &transcript, + concat!( + r#"{"step_index":1,"type":"PLANNER_RESPONSE","model":"gemini-4-neon-high"}"#, + "\n", + r#"{"step_index":2,"type":"PLANNER_RESPONSE","model":"gemini-4-neon-low"}"#, + "\n", + ), + ) + .unwrap(); + assert!(plain.poll().is_empty()); + + // Orchestrator session seeded from existing transcript does not replay + // old lines, then reports planner <-> worker switches as they append. + let orch_transcript = dir.join("orch.jsonl"); + std::fs::write( + &orch_transcript, + concat!( + r#"{"step_index":1,"type":"PLANNER_RESPONSE","model":"gemini-pro-orchestrator-neon"}"#, + "\n", + ), + ) + .unwrap(); + let mut orch = ParentModelTailer::open( + orch_transcript.clone(), + Some("gemini-pro-orchestrator-neon".to_owned()), + ); + assert!(orch.poll().is_empty()); + + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&orch_transcript) + .unwrap(); + use std::io::Write as _; + writeln!( + file, + r#"{{"step_index":64,"type":"PLANNER_RESPONSE","model":"gemini-flash-worker-agy"}}"# + ) + .unwrap(); + assert_eq!( + orch.poll(), + vec![AgentEvent::ServedModel { + model: "gemini-flash-worker-agy".to_owned(), + from: Some("gemini-pro-orchestrator-neon".to_owned()), + reason: None, + }] + ); + // Repeating the same worker model emits nothing. + writeln!( + file, + r#"{{"step_index":66,"type":"PLANNER_RESPONSE","model":"gemini-flash-worker-agy"}}"# + ) + .unwrap(); + assert!(orch.poll().is_empty()); + + // Switching back to the planning model emits the return transition. + writeln!( + file, + r#"{{"step_index":121,"type":"PLANNER_RESPONSE","model":"gemini-pro-orchestrator-neon"}}"# + ) + .unwrap(); + assert_eq!( + orch.poll(), + vec![AgentEvent::ServedModel { + model: "gemini-pro-orchestrator-neon".to_owned(), + from: Some("gemini-flash-worker-agy".to_owned()), + reason: None, + }] + ); + + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/agent/src/antigravity/subagents.rs b/crates/agent/src/antigravity/subagents.rs index 37d42c14c..d33dcef4f 100644 --- a/crates/agent/src/antigravity/subagents.rs +++ b/crates/agent/src/antigravity/subagents.rs @@ -43,11 +43,21 @@ pub(super) struct SpawnedSubagent { pub(super) model: Option, } +/// Concrete child identity returned in `invoke_subagent`'s completion update. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct SpawnAck { + pub(super) conversation_id: String, + pub(super) workspace_dir: Option, +} + /// Control messages sent from `Antigravity` callbacks to its background /// watcher task. pub(super) enum WatcherCommand { /// A new `invoke_subagent` call was observed on the ACP wire. Spawned(SpawnedSubagent), + /// The `invoke_subagent` completion update reported the child's exact id + /// and workspace path. + SpawnBound { tool_call_id: String, ack: SpawnAck }, /// An `invoke_subagent` call failed before matching a child file. SpawnFailed(String), /// A parent `send_message` call targeted `recipient` (possibly a subagent). @@ -136,7 +146,11 @@ pub(super) fn parse_spawn(call: &acp::ToolCall) -> Option { if call.title != "Run invoke_subagent" { return None; } - let input = call.raw_input.as_ref()?.as_object()?; + parse_spawn_input(&call.tool_call_id.0, call.raw_input.as_ref()?) +} + +fn parse_spawn_input(tool_call_id: &str, raw_input: &Value) -> Option { + let input = raw_input.as_object()?; let agent_type = input .get("TypeName") .and_then(Value::as_str) @@ -151,7 +165,7 @@ pub(super) fn parse_spawn(call: &acp::ToolCall) -> Option { .get("Role") .and_then(Value::as_str) .filter(|value| !value.trim().is_empty()) - .map(str::to_owned); + .map(|value| value.trim().to_owned()); let description = role .or_else(|| { prompt @@ -166,7 +180,7 @@ pub(super) fn parse_spawn(call: &acp::ToolCall) -> Option { .filter(|value| !value.trim().is_empty() && *value != "inherit") .map(str::to_owned); Some(SpawnedSubagent { - tool_call_id: call.tool_call_id.0.to_string(), + tool_call_id: tool_call_id.to_owned(), agent_type, description, prompt, @@ -174,12 +188,92 @@ pub(super) fn parse_spawn(call: &acp::ToolCall) -> Option { }) } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct SpawnAckPayload { + conversation_id: String, + #[serde(default)] + workspace_uris: Vec, +} + +/// Extract the spawned child's `conversationId` and workspace path from an +/// `invoke_subagent` completion update (ACP `content` / `raw_output`). +pub(super) fn parse_spawn_ack( + content: Option<&[acp::ToolCallContent]>, + raw_output: Option<&Value>, +) -> Option { + if let Some(raw) = raw_output { + if let Some(ack) = parse_spawn_ack_value(raw) { + return Some(ack); + } + if let Some(text) = raw.as_str() + && let Some(ack) = parse_spawn_ack_text(text) + { + return Some(ack); + } + } + for block in content.into_iter().flatten() { + let acp::ToolCallContent::Content(content) = block else { + continue; + }; + if let acp::ContentBlock::Text(text) = &content.content + && let Some(ack) = parse_spawn_ack_text(&text.text) + { + return Some(ack); + } + } + None +} + +fn parse_spawn_ack_value(value: &Value) -> Option { + let payload: SpawnAckPayload = serde_json::from_value(value.clone()).ok()?; + let conversation_id = payload.conversation_id.trim().to_owned(); + if conversation_id.is_empty() { + return None; + } + let workspace_dir = first_workspace_dir(&payload.workspace_uris); + Some(SpawnAck { + conversation_id, + workspace_dir, + }) +} + +fn parse_spawn_ack_text(text: &str) -> Option { + let start = text.find('{')?; + let end = text.rfind('}')?; + if end <= start { + return None; + } + let payload: SpawnAckPayload = serde_json::from_str(&text[start..=end]).ok()?; + let conversation_id = payload.conversation_id.trim().to_owned(); + if conversation_id.is_empty() { + return None; + } + let workspace_dir = first_workspace_dir(&payload.workspace_uris); + Some(SpawnAck { + conversation_id, + workspace_dir, + }) +} + +fn first_workspace_dir(uris: &[String]) -> Option { + uris.iter().find_map(|uri| { + url::Url::parse(uri) + .ok() + .and_then(|url| url.to_file_path().ok()) + }) +} + /// Extract `(recipient, message)` from a parent `send_message` ACP tool call. pub(super) fn parse_send_message(call: &acp::ToolCall) -> Option<(String, Option)> { if call.title != "Run send_message" { return None; } - let input = call.raw_input.as_ref()?.as_object()?; + parse_send_message_input(call.raw_input.as_ref()?) +} + +pub(super) fn parse_send_message_input(raw_input: &Value) -> Option<(String, Option)> { + let input = raw_input.as_object()?; let recipient = input .get("Recipient") .and_then(Value::as_str) @@ -201,9 +295,16 @@ pub(super) fn is_manage_subagents(call: &acp::ToolCall) -> bool { /// Initial canonical `Subagent` item emitted when `invoke_subagent` starts, /// plus the child's opening `UserMessage` item carrying the spawn prompt. pub(super) fn spawn_events(spawn: &SpawnedSubagent) -> Vec { + spawn_events_with_owner(spawn, None) +} + +fn spawn_events_with_owner( + spawn: &SpawnedSubagent, + owner_item_id: Option, +) -> Vec { let mut events = vec![AgentEvent::ItemStarted(ThreadItem { id: spawn.tool_call_id.clone(), - parent_item_id: None, + parent_item_id: owner_item_id, content: ItemContent::Subagent { agent_type: spawn.agent_type.clone(), description: spawn.description.clone(), @@ -236,6 +337,8 @@ struct SubagentFile { state: String, #[serde(default)] spawn_step_index: u64, + #[serde(default)] + workspace_uris: Vec, } #[derive(Debug, Default, Deserialize)] @@ -261,6 +364,8 @@ struct ChildStep { #[serde(default)] content: Option, #[serde(default)] + error: Option, + #[serde(default)] tool_calls: Option>, #[serde(default)] media: Vec, @@ -281,10 +386,22 @@ struct ChildToolCall { args: Value, } +enum PendingChildToolKind { + Tool { name: String, input: Value }, + NestedSubagent(SpawnedSubagent), +} + struct PendingChildTool { id: String, - name: String, - input: Value, + kind: PendingChildToolKind, +} + +struct BackgroundChildTool { + tool: PendingChildTool, + /// Set once SQLite no longer reports this step as `RUNNING`; a second poll + /// without a transcript completion message settles it (e.g. killed via + /// `manage_task`). + db_settled_once: bool, } impl PendingChildTool { @@ -294,43 +411,71 @@ impl PendingChildTool { output: Option, image_reads: Vec, ) -> ItemContent { - if self.name == "run_command" { - let command = self - .input - .get("CommandLine") - .and_then(Value::as_str) - .unwrap_or("run_command") - .to_owned(); - return ItemContent::CommandExecution { - command, - input: Vec::new(), - output: output.unwrap_or_default(), - exit_code: None, + match &self.kind { + PendingChildToolKind::Tool { name, input } => { + if name == "run_command" { + let command = input + .get("CommandLine") + .and_then(Value::as_str) + .unwrap_or("run_command") + .to_owned(); + let exit_code = output.as_deref().and_then(parse_exit_code); + return ItemContent::CommandExecution { + command, + input: Vec::new(), + output: output.unwrap_or_default(), + exit_code, + status, + }; + } + let family = if name == "read_file" { + input.get("Path").and_then(Value::as_str).map(|path| { + Box::new(ToolFamily::Read { + path: path.to_owned(), + first_line: input.get("StartLine").and_then(Value::as_u64), + note: None, + }) + }) + } else { + None + }; + ItemContent::ToolCall { + name: name.clone(), + input: input.clone(), + output, + status, + image_reads, + family, + } + } + PendingChildToolKind::NestedSubagent(spawn) => ItemContent::Subagent { + agent_type: spawn.agent_type.clone(), + description: spawn.description.clone(), status, - }; - } - let family = if self.name == "read_file" { - self.input.get("Path").and_then(Value::as_str).map(|path| { - Box::new(ToolFamily::Read { - path: path.to_owned(), - first_line: self.input.get("StartLine").and_then(Value::as_u64), - note: None, - }) - }) - } else { - None - }; - ItemContent::ToolCall { - name: self.name.clone(), - input: self.input.clone(), - output, - status, - image_reads, - family, + summary: output, + model: spawn.model.clone(), + effort: None, + }, } } } +struct NestedSpawnBinding { + spawn: SpawnedSubagent, + ack: SpawnAck, +} + +fn parse_exit_code(output: &str) -> Option { + let rest = output.split("Command exited with code ").nth(1)?; + let digits: String = rest + .chars() + .enumerate() + .take_while(|&(i, c)| (i == 0 && c == '-') || c.is_ascii_digit()) + .map(|(_, c)| c) + .collect(); + digits.parse().ok() +} + fn read_child_media(media: &ChildMedia) -> Option { if let Some(mime) = media.mime_type.as_deref() && !mime.starts_with("image/") @@ -344,6 +489,46 @@ fn read_child_media(media: &ChildMedia) -> Option { super::read_image_file(&path, media.mime_type.as_deref()) } +struct ParsedSystemMessage { + sender: String, + content: String, +} + +/// Parse an Antigravity `` step carrying a `[Message] ... +/// sender= ... content=` envelope. +fn parse_system_message(raw: &str) -> Option { + let body = raw + .split_once("") + .map(|(_, after)| after) + .unwrap_or(raw); + let body = body + .rsplit_once("") + .map(|(before, _)| before) + .unwrap_or(body) + .trim(); + let msg_line = body.strip_prefix("[Message]")?.trim_start(); + let after_sender = msg_line.split("sender=").nth(1)?; + let sender = after_sender.split_whitespace().next()?.to_owned(); + let content = after_sender.split_once("content=")?.1.trim_end().to_owned(); + Some(ParsedSystemMessage { sender, content }) +} + +fn parse_task_step_index(sender: &str, child_id: &str) -> Option { + sender + .strip_prefix(child_id)? + .strip_prefix("/task-")? + .parse() + .ok() +} + +fn is_transient_retry_error(message: Option<&str>) -> bool { + let Some(message) = message else { + return false; + }; + message.starts_with("A response attempt was discarded") + || message.starts_with("A response attempt was blocked") +} + /// Incremental JSONL tailer and canonical mapper for one Antigravity subagent. pub(super) struct ChildTailer { parent_item_id: String, @@ -353,12 +538,21 @@ pub(super) struct ChildTailer { mcp_servers: Arc>>, offset: u64, pending_tools: VecDeque, + background_tasks: HashMap, + pending_parent_messages: VecDeque, + discovered_nested_spawns: Vec, model: Option, last_reported: Option, last_assistant: Option, + last_error: Option, + last_error_transient: bool, last_step_index: i64, last_error_step: Option, - turn_done: bool, + /// True when the latest `PLANNER_RESPONSE` completed with no `tool_calls` + /// and no subsequent wakeup has arrived; combined with background-task and + /// SQLite checks by `WatcherState::poll` to decide completion. + planner_yielded: bool, + saw_activity: bool, } impl ChildTailer { @@ -377,17 +571,40 @@ impl ChildTailer { mcp_servers, offset: 0, pending_tools: VecDeque::new(), + background_tasks: HashMap::new(), + pending_parent_messages: VecDeque::new(), + discovered_nested_spawns: Vec::new(), model: initial_model, last_reported: None, last_assistant: None, + last_error: None, + last_error_transient: false, last_step_index: -1, last_error_step: None, - turn_done: false, + planner_yielded: false, + saw_activity: false, } } + fn note_parent_message(&mut self, text: String) { + self.pending_parent_messages.push_back(text); + } + + fn reset_for_new_turn(&mut self) { + self.planner_yielded = false; + self.last_reported = None; + self.last_assistant = None; + self.last_error = None; + self.last_error_transient = false; + } + + fn has_running_background_tasks(&self) -> bool { + !self.background_tasks.is_empty() + } + /// Read any newly appended complete lines from the child's `transcript.jsonl`. pub(super) fn poll(&mut self) -> Vec { + self.saw_activity = false; let Ok(mut file) = File::open(&self.transcript_path) else { return Vec::new(); }; @@ -427,6 +644,9 @@ impl ChildTailer { let mut events = Vec::new(); match step.kind.as_str() { "PLANNER_RESPONSE" => { + self.saw_activity = true; + self.last_error = None; + self.last_error_transient = false; if let Some(model) = step.model.filter(|m| !m.trim().is_empty()) { self.model = Some(model); } @@ -439,9 +659,23 @@ impl ChildTailer { let tool_calls = step.tool_calls.unwrap_or_default(); let has_new_tools = !tool_calls.is_empty(); if has_new_tools { - self.turn_done = false; + self.planner_yielded = false; for (index, call) in tool_calls.into_iter().enumerate() { let input = decode_transcript_args(&call.args); + let id = format!("{}:s{}:t{}", self.child_id, step.step_index, index); + if call.name == "invoke_subagent" + && let Some(spawn) = parse_spawn_input(&id, &input) + { + events.extend(spawn_events_with_owner( + &spawn, + Some(self.parent_item_id.clone()), + )); + self.pending_tools.push_back(PendingChildTool { + id, + kind: PendingChildToolKind::NestedSubagent(spawn), + }); + continue; + } if call.name == "send_message" && let Some(msg) = input .get("Message") @@ -459,12 +693,10 @@ impl ChildTailer { .unwrap_or(call.name) }; let tool = PendingChildTool { - id: format!("{}:s{}:t{}", self.child_id, step.step_index, index), - name, - input, + id: id.clone(), + kind: PendingChildToolKind::Tool { name, input }, }; let content = tool.content(ItemStatus::InProgress, None, Vec::new()); - let id = tool.id.clone(); self.pending_tools.push_back(tool); events.push(AgentEvent::ItemStarted(self.child_item(id, content))); } @@ -481,26 +713,184 @@ impl ChildTailer { } if step.status == "DONE" && !has_new_tools { while let Some(tool) = self.pending_tools.pop_front() { + if matches!(tool.kind, PendingChildToolKind::NestedSubagent(_)) { + continue; + } let content = tool.content(ItemStatus::Completed, None, Vec::new()); events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); } - self.turn_done = true; + self.planner_yielded = true; } } "GENERIC" => { + self.saw_activity = true; if let Some(tool) = self.pending_tools.pop_front() { - let output = step.content.filter(|c| !c.trim().is_empty()); + let output = step + .content + .filter(|c| !c.trim().is_empty()) + .or_else(|| step.error.filter(|e| !e.trim().is_empty())); + if let PendingChildToolKind::NestedSubagent(spawn) = tool.kind { + if step.status == "ERROR" { + let failed = PendingChildTool { + id: tool.id.clone(), + kind: PendingChildToolKind::NestedSubagent(spawn), + }; + let content = failed.content(ItemStatus::Failed, output, Vec::new()); + events + .push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); + } else if let Some(ack) = output.as_deref().and_then(parse_spawn_ack_text) { + self.discovered_nested_spawns + .push(NestedSpawnBinding { spawn, ack }); + } + return events; + } let image_reads: Vec = step.media.iter().filter_map(read_child_media).collect(); - let content = tool.content(ItemStatus::Completed, output, image_reads); - events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); + if step.status == "RUNNING" { + let content = tool.content(ItemStatus::InProgress, output, image_reads); + let item_id = tool.id.clone(); + events.push(AgentEvent::ItemUpdated( + self.child_item(item_id.clone(), content), + )); + events.push(AgentEvent::ItemBackgrounded { + item_id, + parent_item_id: Some(self.parent_item_id.clone()), + }); + self.background_tasks.insert( + step.step_index, + BackgroundChildTool { + tool, + db_settled_once: false, + }, + ); + } else { + let status = if step.status == "ERROR" { + ItemStatus::Failed + } else { + ItemStatus::Completed + }; + let content = tool.content(status, output, image_reads); + events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); + } } } + "SYSTEM_MESSAGE" => { + if step.step_index == 0 { + return events; + } + let Some(parsed) = step.content.as_deref().and_then(parse_system_message) else { + return events; + }; + if let Some(task_step) = parse_task_step_index(&parsed.sender, &self.child_id) { + self.saw_activity = true; + self.planner_yielded = false; + if let Some((_, result_body)) = + parsed.content.split_once("finished with result:") + && let Some(bg) = self.background_tasks.remove(&task_step) + { + let trimmed = result_body.trim(); + let output = (!trimmed.is_empty()).then(|| trimmed.to_owned()); + let content = bg.tool.content(ItemStatus::Completed, output, Vec::new()); + events.push(AgentEvent::ItemCompleted( + self.child_item(bg.tool.id, content), + )); + } + } else if !parsed.content.trim().is_empty() { + // A wakeup message from the parent or a peer subagent + // begins a new turn of work. + self.saw_activity = true; + self.reset_for_new_turn(); + let duplicate = self + .pending_parent_messages + .front() + .is_some_and(|expected| expected.trim() == parsed.content.trim()); + if duplicate { + self.pending_parent_messages.pop_front(); + } else { + events.push(AgentEvent::ItemCompleted(self.child_item( + format!("{}:s{}:msg-in", self.child_id, step.step_index), + ItemContent::UserMessage { + text: parsed.content, + attachments: Vec::new(), + }, + ))); + } + } + } + "ERROR_MESSAGE" => { + let message = step + .error + .filter(|e| !e.trim().is_empty()) + .or_else(|| step.content.filter(|c| !c.trim().is_empty())); + self.last_error_transient = is_transient_retry_error(message.as_deref()); + self.last_error = message; + } _ => {} } events } + /// Reconcile tracked background tasks with SQLite step status so tasks + /// stopped without a `finished with result:` message (e.g. via + /// `manage_task` kill) do not keep the child in progress indefinitely. + fn reconcile_background_tasks(&mut self, db: Option<&record::RecordState>) -> Vec { + let Some(state) = db else { + return Vec::new(); + }; + let Some(last) = state.last else { + return Vec::new(); + }; + if last.index < self.last_step_index { + return Vec::new(); + } + let mut settled_keys = Vec::new(); + for (&step_idx, bg) in &mut self.background_tasks { + if step_idx <= last.index && !state.running_steps.contains(&step_idx) { + if bg.db_settled_once { + settled_keys.push(step_idx); + } else { + // Wait one poll cycle so a trailing `SYSTEM_MESSAGE` with + // the task output can land before settling from SQLite. + bg.db_settled_once = true; + } + } else { + bg.db_settled_once = false; + } + } + let mut events = Vec::new(); + for key in settled_keys { + if let Some(bg) = self.background_tasks.remove(&key) { + let content = bg.tool.content(ItemStatus::Completed, None, Vec::new()); + events.push(AgentEvent::ItemCompleted( + self.child_item(bg.tool.id, content), + )); + } + } + events + } + + fn finish_open_tools_interrupted(&mut self) -> Vec { + let mut events = Vec::new(); + while let Some(tool) = self.pending_tools.pop_front() { + if matches!(tool.kind, PendingChildToolKind::NestedSubagent(_)) { + continue; + } + let content = tool.content(ItemStatus::Interrupted, None, Vec::new()); + events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); + } + let mut bg_keys: Vec = self.background_tasks.keys().copied().collect(); + bg_keys.sort_unstable(); + for key in bg_keys { + if let Some(bg) = self.background_tasks.remove(&key) { + let content = bg.tool.content(ItemStatus::Interrupted, None, Vec::new()); + events.push(AgentEvent::ItemCompleted( + self.child_item(bg.tool.id, content), + )); + } + } + events + } + fn child_item(&self, id: String, content: ItemContent) -> ThreadItem { ThreadItem { id, @@ -515,8 +905,12 @@ impl ChildTailer { .or_else(|| self.last_assistant.clone()) } - fn failed_in_db(&mut self) -> bool { - let Some(last) = record::last_step(&self.db_path) else { + fn failure_summary(&self) -> Option { + self.last_error.clone().or_else(|| self.summary()) + } + + fn failed_in_db(&mut self, db: Option<&record::RecordState>) -> bool { + let Some(last) = db.and_then(|state| state.last) else { return false; }; if last.error @@ -533,16 +927,19 @@ impl ChildTailer { /// `agy` 1.5.14 serializes each tool argument in `transcript.jsonl` as a /// JSON-encoded string (e.g. `{"Path": "\"/repo/a.txt\""}`, `{"DurationSeconds": "10"}`). -/// Unwrap JSON-encoded strings back into structured values for display. +/// Unwrap JSON-encoded strings back into structured values for display, +/// including strings truncated mid-value by `transcript.jsonl` with a trailing +/// `\n` marker. fn decode_transcript_args(raw: &Value) -> Value { match raw { Value::Object(map) => Value::Object( map.iter() .map(|(key, value)| { let decoded = match value.as_str() { - Some(text) => { - serde_json::from_str::(text).unwrap_or_else(|_| value.clone()) - } + Some(text) => serde_json::from_str::(text) + .ok() + .or_else(|| decode_truncated_json_string(text).map(Value::String)) + .unwrap_or_else(|| value.clone()), None => value.clone(), }; (key.clone(), decoded) @@ -553,12 +950,82 @@ fn decode_transcript_args(raw: &Value) -> Value { } } +fn decode_truncated_json_string(text: &str) -> Option { + let rest = text.strip_prefix('"')?; + let (body, suffix) = rest.split_once("\n out.push('"'), + '\\' => out.push('\\'), + '/' => out.push('/'), + 'b' => out.push('\u{0008}'), + 'f' => out.push('\u{000C}'), + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + 'u' => { + let mut hex = String::with_capacity(4); + for _ in 0..4 { + if let Some(digit) = chars.next() { + hex.push(digit); + } + } + if hex.len() < 4 { + break; + } + let Ok(code) = u16::from_str_radix(&hex, 16) else { + break; + }; + if (0xD800..=0xDBFF).contains(&code) { + if chars.next() == Some('\\') && chars.next() == Some('u') { + let mut low_hex = String::with_capacity(4); + for _ in 0..4 { + if let Some(digit) = chars.next() { + low_hex.push(digit); + } + } + if low_hex.len() == 4 + && let Ok(low) = u16::from_str_radix(&low_hex, 16) + && let Some(decoded) = + char::decode_utf16([code, low]).next().and_then(Result::ok) + { + out.push(decoded); + } + } + } else if let Some(decoded) = char::from_u32(u32::from(code)) { + out.push(decoded); + } + } + other => out.push(other), + } + } + out.push_str("\n, + owner_conversation_id: String, agent_type: String, description: String, status: ItemStatus, + alive_on_disk: bool, model: Option, + cwd: PathBuf, + worktree_announced: bool, tailer: ChildTailer, followup_seq: u64, } @@ -567,7 +1034,7 @@ impl TrackedSubagent { fn snapshot(&self, status: ItemStatus, summary: Option) -> ThreadItem { ThreadItem { id: self.tool_call_id.clone(), - parent_item_id: None, + parent_item_id: self.owner_item_id.clone(), content: ItemContent::Subagent { agent_type: self.agent_type.clone(), description: self.description.clone(), @@ -584,11 +1051,13 @@ impl TrackedSubagent { pub(super) struct WatcherState { state_dir: PathBuf, parent_session_id: String, + parent_cwd: PathBuf, mcp_servers: Arc>>, /// Child conversation ids already present on disk when the session started, /// so a resumed session does not pair historical subagents with new spawns. ignored_children: HashSet, - /// Parent `invoke_subagent` calls waiting for their `.json` to appear. + /// Parent `invoke_subagent` calls waiting for their `.json` or + /// completion ack to bind a child conversation id. unmatched_spawns: VecDeque, /// Active or completed tracked subagents keyed by child conversation id. children: HashMap, @@ -597,12 +1066,18 @@ pub(super) struct WatcherState { impl WatcherState { #[cfg(test)] pub(super) fn new(state_dir: PathBuf, parent_session_id: String) -> Self { - Self::with_mcp_servers(state_dir, parent_session_id, Arc::default()) + Self::with_mcp_servers( + state_dir, + parent_session_id, + PathBuf::from("/repo"), + Arc::default(), + ) } pub(super) fn with_mcp_servers( state_dir: PathBuf, parent_session_id: String, + parent_cwd: PathBuf, mcp_servers: Arc>>, ) -> Self { let ignored_children = read_subagent_files(&state_dir, &parent_session_id) @@ -612,6 +1087,7 @@ impl WatcherState { Self { state_dir, parent_session_id, + parent_cwd, mcp_servers, ignored_children, unmatched_spawns: VecDeque::new(), @@ -627,21 +1103,112 @@ impl WatcherState { .any(|child| child.status == ItemStatus::InProgress) } + /// Whether any tracked subagent has not been killed on disk, so a parent + /// turn waiting on background/peer wakeups keeps polling for reactivations. + pub(super) fn has_alive_subagents(&self) -> bool { + self.children.values().any(|child| child.alive_on_disk) + } + pub(super) fn on_spawn(&mut self, spawn: SpawnedSubagent) { self.unmatched_spawns.push_back(spawn); } + /// Bind an `invoke_subagent` call to the exact `conversationId` returned in + /// its completion update, announcing any worktree move immediately. + pub(super) fn on_spawn_bound(&mut self, tool_call_id: &str, ack: SpawnAck) -> Vec { + let mut events = Vec::new(); + if let Some(child) = self.children.get_mut(&ack.conversation_id) { + if let Some(dir) = ack.workspace_dir { + events.extend(Self::maybe_announce_worktree(child, dir)); + } + return events; + } + let Some(index) = self + .unmatched_spawns + .iter() + .position(|spawn| spawn.tool_call_id == tool_call_id) + else { + return events; + }; + let Some(spawn) = self.unmatched_spawns.remove(index) else { + return events; + }; + let owner_cwd = self.parent_cwd.clone(); + let owner_conv = self.parent_session_id.clone(); + events.extend(self.register_child( + ack.conversation_id, + spawn, + None, + owner_conv, + owner_cwd, + ack.workspace_dir, + )); + events + } + pub(super) fn on_spawn_failed(&mut self, tool_call_id: &str) { self.unmatched_spawns .retain(|spawn| spawn.tool_call_id != tool_call_id); } + fn register_child( + &mut self, + conversation_id: String, + spawn: SpawnedSubagent, + owner_item_id: Option, + owner_conversation_id: String, + owner_cwd: PathBuf, + workspace_dir: Option, + ) -> Vec { + let tailer = ChildTailer::new( + spawn.tool_call_id.clone(), + conversation_id.clone(), + &self.state_dir, + spawn.model.clone(), + self.mcp_servers.clone(), + ); + let mut child = TrackedSubagent { + tool_call_id: spawn.tool_call_id, + owner_item_id, + owner_conversation_id, + agent_type: spawn.agent_type, + description: spawn.description, + status: ItemStatus::InProgress, + alive_on_disk: true, + model: spawn.model, + cwd: owner_cwd, + worktree_announced: false, + tailer, + followup_seq: 0, + }; + let events = workspace_dir + .map(|dir| Self::maybe_announce_worktree(&mut child, dir)) + .unwrap_or_default(); + self.children.insert(conversation_id, child); + events + } + + fn maybe_announce_worktree(child: &mut TrackedSubagent, dir: PathBuf) -> Vec { + if child.worktree_announced || dir == child.cwd { + return Vec::new(); + } + let from = child.cwd.clone(); + child.cwd = dir.clone(); + child.worktree_announced = true; + vec![AgentEvent::SessionMoved { + from, + to: dir, + parent_item_id: Some(child.tool_call_id.clone()), + }] + } + /// Close any still-running matched subagents and unmatched spawns as /// interrupted when the session closes so their mirrors do not stay open. pub(super) fn finish_all_interrupted(&mut self) -> Vec { let mut events = Vec::new(); for child in self.children.values_mut() { if child.status == ItemStatus::InProgress { + events.extend(child.tailer.finish_open_tools_interrupted()); child.status = ItemStatus::Interrupted; let summary = child.tailer.summary(); events.push(AgentEvent::ItemCompleted( @@ -677,13 +1244,13 @@ impl WatcherState { let mut events = Vec::new(); if child.status != ItemStatus::InProgress { child.status = ItemStatus::InProgress; - child.tailer.turn_done = false; - child.tailer.last_reported = None; + child.tailer.reset_for_new_turn(); events.push(AgentEvent::ItemUpdated( child.snapshot(ItemStatus::InProgress, None), )); } if let Some(text) = message { + child.tailer.note_parent_message(text.clone()); child.followup_seq += 1; events.push(AgentEvent::ItemCompleted(ThreadItem { id: format!("{}:followup-{}", child.tool_call_id, child.followup_seq), @@ -701,74 +1268,177 @@ impl WatcherState { /// events followed by any parent `Subagent` status transitions. pub(super) fn poll(&mut self) -> Vec { let mut events = Vec::new(); - let files = read_subagent_files(&self.state_dir, &self.parent_session_id); let mut states_by_id: HashMap = HashMap::new(); + let mut workspaces_by_id: HashMap = HashMap::new(); + + // Scan the root session's subagents directory plus any tracked child's + // subagents directory (for nested subagent state updates). + let mut scan_parents = vec![self.parent_session_id.clone()]; + scan_parents.extend(self.children.keys().cloned()); + + for parent_id in scan_parents { + let is_root = parent_id == self.parent_session_id; + for file in read_subagent_files(&self.state_dir, &parent_id) { + states_by_id.insert(file.conversation_id.clone(), file.state.clone()); + if let Some(dir) = first_workspace_dir(&file.workspace_uris) { + workspaces_by_id.insert(file.conversation_id.clone(), dir); + } + if !is_root + || self.ignored_children.contains(&file.conversation_id) + || self.children.contains_key(&file.conversation_id) + { + continue; + } + if let Some(spawn) = self.take_matching_spawn(&file) { + let workspace_dir = first_workspace_dir(&file.workspace_uris); + let owner_cwd = self.parent_cwd.clone(); + let owner_conv = self.parent_session_id.clone(); + events.extend(self.register_child( + file.conversation_id, + spawn, + None, + owner_conv, + owner_cwd, + workspace_dir, + )); + } + } + } - for file in files { - states_by_id.insert(file.conversation_id.clone(), file.state.clone()); - if self.ignored_children.contains(&file.conversation_id) - || self.children.contains_key(&file.conversation_id) - { + // First pass: poll transcripts, reconcile SQLite state, and collect any + // newly discovered nested subagent spawns. + let mut nested_to_register = Vec::new(); + let mut db_states: HashMap> = HashMap::new(); + let mut child_ids: Vec = self.children.keys().cloned().collect(); + child_ids.sort(); + + for child_id in &child_ids { + let Some(child) = self.children.get_mut(child_id) else { continue; + }; + if let Some(dir) = workspaces_by_id.get(child_id).cloned() { + events.extend(Self::maybe_announce_worktree(child, dir)); } - if let Some(spawn) = self.take_matching_spawn(&file) { - let tailer = ChildTailer::new( - spawn.tool_call_id.clone(), - file.conversation_id.clone(), - &self.state_dir, - spawn.model.clone(), - self.mcp_servers.clone(), - ); - self.children.insert( - file.conversation_id, - TrackedSubagent { - tool_call_id: spawn.tool_call_id, - agent_type: spawn.agent_type, - description: spawn.description, - status: ItemStatus::InProgress, - model: spawn.model, - tailer, - followup_seq: 0, - }, - ); + if let Some(file_state) = states_by_id.get(child_id) { + child.alive_on_disk = file_state != "SUBAGENT_STATE_KILLED"; } - } - for (child_id, child) in &mut self.children { let model_before = child.tailer.model.clone(); - let child_events = child.tailer.poll(); + let mut child_events = child.tailer.poll(); + let db_state = record::record_state(&child.tailer.db_path); + child_events.extend(child.tailer.reconcile_background_tasks(db_state.as_ref())); let model_changed = child.tailer.model != model_before; + + let owner_item_id = Some(child.tool_call_id.clone()); + let owner_cwd = child.cwd.clone(); + for binding in child.tailer.discovered_nested_spawns.drain(..) { + nested_to_register.push(( + binding.ack.conversation_id, + binding.spawn, + owner_item_id.clone(), + child_id.clone(), + owner_cwd.clone(), + binding.ack.workspace_dir, + )); + } + + let killed = !child.alive_on_disk; + let db_active = db_state + .as_ref() + .is_some_and(record::RecordState::has_active_step); + let reactivated = child.status != ItemStatus::InProgress + && !killed + && (child.tailer.saw_activity + || child.tailer.has_running_background_tasks() + || db_active); + if reactivated { + child.status = ItemStatus::InProgress; + if !child.tailer.saw_activity { + // Reactivation from SQLite before the new transcript lines + // flush must clear any stale completion marker from the + // previous turn. + child.tailer.planner_yielded = false; + } + // Emit `ItemUpdated(InProgress)` before the new child events so + // the mirror reopens its turn before recording them. + events.push(AgentEvent::ItemUpdated( + child.snapshot(ItemStatus::InProgress, None), + )); + } + events.extend(child_events); + if model_changed && child.status == ItemStatus::InProgress && !reactivated { + events.push(AgentEvent::ItemUpdated( + child.snapshot(ItemStatus::InProgress, None), + )); + } + + db_states.insert(child_id.clone(), db_state); + } + + for (conv_id, spawn, owner_item_id, owner_conv, owner_cwd, workspace_dir) in + nested_to_register + { + if !self.children.contains_key(&conv_id) { + events.extend(self.register_child( + conv_id, + spawn, + owner_item_id, + owner_conv, + owner_cwd, + workspace_dir, + )); + } + } + + // Compute which parent conversations still have an active nested child + // before deciding terminal transitions. + let active_nested_owners: HashSet = self + .children + .values() + .filter(|child| child.owner_item_id.is_some() && child.status == ItemStatus::InProgress) + .map(|child| child.owner_conversation_id.clone()) + .collect(); + + // Second pass: evaluate terminal transitions for `InProgress` children. + for child_id in &child_ids { + let has_active_nested = active_nested_owners.contains(child_id); + let db_state = db_states.get(child_id).and_then(|s| s.as_ref()); + let Some(child) = self.children.get_mut(child_id) else { + continue; + }; if child.status != ItemStatus::InProgress { continue; } - let killed = states_by_id - .get(child_id) - .is_some_and(|state| state == "SUBAGENT_STATE_KILLED"); - if child.tailer.turn_done { - child.status = ItemStatus::Completed; + let killed = !child.alive_on_disk; + let has_running_work = child.tailer.has_running_background_tasks() + || db_state.is_some_and(record::RecordState::has_active_step) + || has_active_nested; + + if killed { + events.extend(child.tailer.finish_open_tools_interrupted()); + child.status = ItemStatus::Interrupted; let summary = child.tailer.summary(); events.push(AgentEvent::ItemCompleted( - child.snapshot(ItemStatus::Completed, summary), + child.snapshot(ItemStatus::Interrupted, summary), )); - } else if killed { - child.status = ItemStatus::Interrupted; + } else if child.tailer.planner_yielded && !has_running_work { + child.status = ItemStatus::Completed; let summary = child.tailer.summary(); events.push(AgentEvent::ItemCompleted( - child.snapshot(ItemStatus::Interrupted, summary), + child.snapshot(ItemStatus::Completed, summary), )); - } else if child.tailer.failed_in_db() { + } else if !has_running_work + && !child.tailer.last_error_transient + && child.tailer.failed_in_db(db_state) + { child.status = ItemStatus::Failed; - let summary = child.tailer.summary(); + let summary = child.tailer.failure_summary(); events.push(AgentEvent::ItemCompleted( child.snapshot(ItemStatus::Failed, summary), )); - } else if model_changed { - events.push(AgentEvent::ItemUpdated( - child.snapshot(ItemStatus::InProgress, None), - )); } } @@ -776,12 +1446,12 @@ impl WatcherState { } fn take_matching_spawn(&mut self, file: &SubagentFile) -> Option { + let role = file.subagent_descriptor.role.trim(); let exact = self.unmatched_spawns.iter().position(|spawn| { - spawn.agent_type == file.subagent_descriptor.type_name - && spawn.description == file.subagent_descriptor.role + spawn.agent_type == file.subagent_descriptor.type_name && spawn.description == role }); let index = exact.or_else(|| { - file.subagent_descriptor.role.is_empty().then(|| { + role.is_empty().then(|| { self.unmatched_spawns .iter() .position(|spawn| spawn.agent_type == file.subagent_descriptor.type_name) @@ -818,6 +1488,7 @@ fn read_subagent_files(state_dir: &Path, parent_session_id: &str) -> Vec>, pub(super) proactive: Arc>, pub(super) mcp_servers: Arc>>, @@ -838,6 +1509,7 @@ pub(super) async fn run_watcher(ctx: WatcherContext) { let WatcherContext { state_dir, session_id, + parent_cwd, acp_state, proactive, mcp_servers, @@ -848,7 +1520,7 @@ pub(super) async fn run_watcher(ctx: WatcherContext) { let mut watcher = { let (state_dir, session_id) = (state_dir.clone(), session_id.clone()); crate::process::unblock(move || { - WatcherState::with_mcp_servers(state_dir, session_id, mcp_servers) + WatcherState::with_mcp_servers(state_dir, session_id, parent_cwd, mcp_servers) }) .await }; @@ -857,12 +1529,14 @@ pub(super) async fn run_watcher(ctx: WatcherContext) { let mut closing = false; loop { + let (parent_turn_open, proactive_active) = { + let state = acp_state.lock().unwrap_or_else(|held| held.into_inner()); + let tracker = proactive.lock().unwrap_or_else(|held| held.into_inner()); + (state.turn().is_some(), tracker.active.is_some()) + }; let need_poll = watcher.has_active_subagents() - || proactive - .lock() - .unwrap_or_else(|held| held.into_inner()) - .active - .is_some(); + || proactive_active + || (parent_turn_open && watcher.has_alive_subagents()); let next_command = if closing { None @@ -885,6 +1559,9 @@ pub(super) async fn run_watcher(ctx: WatcherContext) { { match cmd { Ok(WatcherCommand::Spawned(spawn)) => watcher.on_spawn(spawn), + Ok(WatcherCommand::SpawnBound { tool_call_id, ack }) => { + immediate_events.extend(watcher.on_spawn_bound(&tool_call_id, ack)); + } Ok(WatcherCommand::SpawnFailed(id)) => watcher.on_spawn_failed(&id), Ok(WatcherCommand::MessageSent { recipient, message }) => { immediate_events.extend(watcher.on_message_sent(&recipient, message)); @@ -897,18 +1574,17 @@ pub(super) async fn run_watcher(ctx: WatcherContext) { } } - // Release `proactive` before locking `acp_state` so the watcher and - // notification callbacks never invert lock order (`acp_state` -> `proactive`). - let proactive_check = proactive - .lock() - .unwrap_or_else(|held| held.into_inner()) - .active - .as_ref() - .map(|active| (active.turn_id.clone(), active.since, active.usage_seen)); - let context = acp_state - .lock() - .unwrap_or_else(|held| held.into_inner()) - .usage(); + let (context, proactive_check) = { + let state = acp_state.lock().unwrap_or_else(|held| held.into_inner()); + let tracker = proactive.lock().unwrap_or_else(|held| held.into_inner()); + ( + state.usage(), + tracker + .active + .as_ref() + .map(|active| (active.turn_id.clone(), active.since, active.usage_seen)), + ) + }; let (db, transcript) = (db_path.clone(), transcript_path.clone()); let (polled_watcher, polled, ended, synced_step) = crate::process::unblock(move || { let polled = watcher.poll(); @@ -916,7 +1592,9 @@ pub(super) async fn run_watcher(ctx: WatcherContext) { let end = if usage_seen { record::proactive_turn_end(&db, &transcript, since, context) } else { - record::last_step(&db) + record::record_state(&db) + .filter(|state| !state.has_generating_step) + .and_then(|state| state.last) .filter(|last| last.error && since.is_none_or(|seen| last.index > seen)) .map(|last| record::ProactiveEnd { step_index: last.index, @@ -1457,4 +2135,489 @@ mod tests { && image_reads[0].data_base64 == PNG_B64 ))); } + + /// A subagent that backgrounds a long command (`GENERIC` `status: "RUNNING"`) + /// and yields its planner turn stays `InProgress` until the background task + /// wakes it up and the child finishes its final turn; truncated `send_message` + /// arguments still decode cleanly into the summary. + #[test] + fn background_task_keeps_subagent_in_progress_until_wakeup_finishes() { + let scratch = Scratch::new(); + let mut watcher = WatcherState::new(scratch.0.clone(), "parent-bg".into()); + watcher.on_spawn(SpawnedSubagent { + tool_call_id: "call_bg_sub".into(), + agent_type: "worker".into(), + description: "Run test suite".into(), + prompt: None, + model: None, + }); + scratch.write_subagent( + "parent-bg", + "child-bg", + "worker", + "Run test suite", + "SUBAGENT_STATE_ALIVE", + 1, + ); + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 1, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "tool_calls": [{ + "name": "run_command", + "args": { "CommandLine": "\"cargo test\"" } + }] + }), + ); + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 2, + "type": "GENERIC", + "status": "RUNNING", + "content": "Created At: 2026-12-05T20:57:59+08:00\nTool is running as a background task with task id: child-bg/task-2\nTask Description: cargo test" + }), + ); + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 3, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "content": "Waiting for cargo test to finish." + }), + ); + + let first = watcher.poll(); + assert!(watcher.has_active_subagents()); + assert!(first.iter().any(|event| matches!( + event, + AgentEvent::ItemBackgrounded { + item_id, + parent_item_id: Some(parent), + } if item_id == "child-bg:s1:t0" && parent == "call_bg_sub" + ))); + assert!( + !first.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { id, .. }) if id == "call_bg_sub" + )), + "yielding while a background command runs must not complete the subagent" + ); + + // Progress notice keeps both the background command and subagent open. + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 4, + "type": "SYSTEM_MESSAGE", + "status": "DONE", + "content": "\n[Message] timestamp=2026-12-05T13:00:00Z sender=child-bg/task-2 priority=MESSAGE_PRIORITY_HIGH content=Background command is still running after 300s: cargo test\n" + }), + ); + let progress = watcher.poll(); + assert!(watcher.has_active_subagents()); + assert!(!progress.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { id, .. }) + if id == "child-bg:s1:t0" || id == "call_bg_sub" + ))); + + // Task completion settles the command with its exit code, wakes the + // subagent, and the final planner response completes the subagent with + // the decoded (even if truncated) send_message summary. + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 5, + "type": "SYSTEM_MESSAGE", + "status": "DONE", + "content": "\n[Message] timestamp=2026-12-05T13:01:00Z sender=child-bg/task-2 priority=MESSAGE_PRIORITY_HIGH content=Task id \"child-bg/task-2\" finished with result:\nDuration: 61s\nCommand exited with code 0.\n\nCommand output:\nall tests passed\n" + }), + ); + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 6, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "tool_calls": [{ + "name": "send_message", + "args": { + "Recipient": "\"parent-bg\"", + "Message": "\"All tests passed.\\nDetails: ok\n" + } + }] + }), + ); + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 7, + "type": "GENERIC", + "status": "DONE", + "content": "Message sent" + }), + ); + scratch.append_transcript( + "child-bg", + &json!({ + "step_index": 8, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "content": "Reported to parent." + }), + ); + + let second = watcher.poll(); + assert!(second.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + id, + parent_item_id: Some(parent), + content: ItemContent::CommandExecution { + exit_code: Some(0), + status: ItemStatus::Completed, + output, + .. + }, + }) if id == "child-bg:s1:t0" && parent == "call_bg_sub" && output.contains("all tests passed") + ))); + assert!(matches!( + second.last(), + Some(AgentEvent::ItemCompleted(ThreadItem { + id, + parent_item_id: None, + content: ItemContent::Subagent { + status: ItemStatus::Completed, + summary: Some(summary), + .. + }, + })) if id == "call_bg_sub" + && summary == "All tests passed.\nDetails: ok\n" + )); + assert!(!watcher.has_active_subagents()); + } + + /// `invoke_subagent`'s completion ack binds identical-role parallel spawns + /// to their exact conversation ids, announces worktree `SessionMoved`, and + /// nested `invoke_subagent` calls inside a child keep the child active + /// until the grandchild completes. + #[test] + fn spawn_bound_binds_exact_child_id_announces_worktree_and_tracks_nested_subagent() { + let scratch = Scratch::new(); + let mut watcher = WatcherState::new(scratch.0.clone(), "parent-nest".into()); + watcher.on_spawn(SpawnedSubagent { + tool_call_id: "call_1".into(), + agent_type: "worker".into(), + description: "Same Role".into(), + prompt: None, + model: None, + }); + watcher.on_spawn(SpawnedSubagent { + tool_call_id: "call_2".into(), + agent_type: "worker".into(), + description: "Same Role".into(), + prompt: None, + model: None, + }); + + let ack_text = "Created the following subagent:\n{\n \"conversationId\": \"child-two\",\n \"workspaceUris\": [\"file:///tmp/wt-two\"]\n}\nThe subagent will send you a message."; + let ack = parse_spawn_ack(None, Some(&Value::String(ack_text.into()))).unwrap(); + let bound = watcher.on_spawn_bound("call_2", ack); + assert!(matches!( + bound.as_slice(), + [AgentEvent::SessionMoved { + from, + to, + parent_item_id: Some(parent), + }] if from == Path::new("/repo") && to == Path::new("/tmp/wt-two") && parent == "call_2" + )); + + // Child spawns a grandchild and yields waiting for it. + scratch.append_transcript( + "child-two", + &json!({ + "step_index": 1, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "tool_calls": [{ + "name": "invoke_subagent", + "args": { + "TypeName": "\"research\"", + "Role": "\"Deep Check\"", + "Prompt": "\"Inspect schema\"" + } + }] + }), + ); + scratch.append_transcript( + "child-two", + &json!({ + "step_index": 2, + "type": "GENERIC", + "status": "DONE", + "content": "Created the following subagent:\n{\n \"conversationId\": \"grandchild-1\",\n \"workspaceUris\": [\"file:///tmp/wt-two\"]\n}" + }), + ); + scratch.append_transcript( + "child-two", + &json!({ + "step_index": 3, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "content": "Waiting on Deep Check." + }), + ); + + let first = watcher.poll(); + assert!(first.iter().any(|event| matches!( + event, + AgentEvent::ItemStarted(ThreadItem { + id, + parent_item_id: Some(parent), + content: ItemContent::Subagent { + agent_type, + description, + status: ItemStatus::InProgress, + .. + }, + }) if id == "child-two:s1:t0" + && parent == "call_2" + && agent_type == "research" + && description == "Deep Check" + ))); + assert!( + !first.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { id, .. }) if id == "call_2" + )), + "child must stay InProgress while its grandchild runs" + ); + + // Once the grandchild finishes and wakes the child, both settle in order. + scratch.append_transcript( + "grandchild-1", + &json!({ + "step_index": 1, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "content": "Schema looks good." + }), + ); + let second = watcher.poll(); + assert!(second.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + id, + parent_item_id: Some(parent), + content: ItemContent::Subagent { + status: ItemStatus::Completed, + summary: Some(summary), + .. + }, + }) if id == "child-two:s1:t0" && parent == "call_2" && summary == "Schema looks good." + ))); + let third = watcher.poll(); + assert!(third.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + id, + parent_item_id: None, + content: ItemContent::Subagent { + status: ItemStatus::Completed, + .. + }, + }) if id == "call_2" + ))); + } + + /// Failed tool steps report `ItemStatus::Failed`, transient retry errors + /// do not fail the subagent, and a child that failed on an API error + /// reactivates cleanly (reopening its mirror before emitting new items) + /// once Antigravity retries and succeeds. + #[test] + fn tool_error_transient_retry_and_reactivation_update_subagent_state() { + let scratch = Scratch::new(); + let mut watcher = WatcherState::new(scratch.0.clone(), "parent-err".into()); + watcher.on_spawn(SpawnedSubagent { + tool_call_id: "call_err".into(), + agent_type: "worker".into(), + description: "Resilient Worker".into(), + prompt: None, + model: None, + }); + scratch.write_subagent( + "parent-err", + "child-err", + "worker", + "Resilient Worker", + "SUBAGENT_STATE_ALIVE", + 1, + ); + let write_db = |rows: &[(i64, i64, i64)]| { + let db = record::path(&scratch.0, "child-err"); + std::fs::create_dir_all(db.parent().unwrap()).unwrap(); + let _ = std::fs::remove_file(&db); + smol::future::block_on(async { + let database = turso::Builder::new_local(&db.to_string_lossy()) + .build() + .await + .unwrap(); + let conn = database.connect().unwrap(); + conn.execute( + "CREATE TABLE steps (idx integer, step_type integer NOT NULL DEFAULT 0, status integer NOT NULL DEFAULT 3, PRIMARY KEY (idx))", + (), + ) + .await + .unwrap(); + for &(idx, step_type, status) in rows { + conn.execute( + "INSERT INTO steps (idx, step_type, status) VALUES (?, ?, ?)", + (idx, step_type, status), + ) + .await + .unwrap(); + } + }); + }; + + // Tool call fails (`GENERIC` `ERROR`) + transient malformed-call retry. + scratch.append_transcript( + "child-err", + &json!({ + "step_index": 1, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "tool_calls": [{ "name": "read_file", "args": { "Path": "\"/missing\"" } }] + }), + ); + scratch.append_transcript( + "child-err", + &json!({ + "step_index": 2, + "type": "GENERIC", + "status": "ERROR", + "content": "file does not exist" + }), + ); + scratch.append_transcript( + "child-err", + &json!({ + "step_index": 3, + "type": "ERROR_MESSAGE", + "status": "DONE", + "error": "A response attempt was discarded because it contained an improperly formatted function call" + }), + ); + write_db(&[(1, 15, 3), (2, 132, 7), (3, 17, 3)]); + + let first = watcher.poll(); + assert!(first.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + id, + parent_item_id: Some(parent), + content: ItemContent::ToolCall { + status: ItemStatus::Failed, + output: Some(output), + .. + }, + }) if id == "child-err:s1:t0" && parent == "call_err" && output == "file does not exist" + ))); + assert!( + watcher.has_active_subagents(), + "transient discarded response error must not mark the subagent failed" + ); + + // An API error step with no active generation marks the subagent Failed + // with the real error message. + scratch.append_transcript( + "child-err", + &json!({ + "step_index": 4, + "type": "ERROR_MESSAGE", + "status": "DONE", + "error": "API error (attempt 1): TLS handshake timeout" + }), + ); + write_db(&[(1, 15, 3), (2, 132, 7), (3, 17, 3), (4, 17, 3)]); + let failed = watcher.poll(); + assert!(failed.iter().any(|event| matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + id, + content: ItemContent::Subagent { + status: ItemStatus::Failed, + summary: Some(summary), + .. + }, + .. + }) if id == "call_err" && summary.contains("TLS handshake timeout") + ))); + assert!(!watcher.has_active_subagents()); + + // When the retry later succeeds, the subagent reopens (`ItemUpdated(InProgress)`) + // before emitting the recovered message and finally settles `Completed`. + scratch.append_transcript( + "child-err", + &json!({ + "step_index": 5, + "type": "PLANNER_RESPONSE", + "status": "DONE", + "content": "Recovered and finished." + }), + ); + write_db(&[(1, 15, 3), (2, 132, 7), (3, 17, 3), (4, 17, 3), (5, 15, 3)]); + let recovered = watcher.poll(); + let reopen_pos = recovered + .iter() + .position(|event| { + matches!( + event, + AgentEvent::ItemUpdated(ThreadItem { + id, + content: ItemContent::Subagent { + status: ItemStatus::InProgress, + .. + }, + .. + }) if id == "call_err" + ) + }) + .expect("subagent should reopen on retry recovery"); + let msg_pos = recovered + .iter() + .position(|event| { + matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + parent_item_id: Some(parent), + content: ItemContent::AssistantMessage { text, .. }, + .. + }) if parent == "call_err" && text == "Recovered and finished." + ) + }) + .expect("recovered message should be emitted"); + let done_pos = recovered + .iter() + .position(|event| { + matches!( + event, + AgentEvent::ItemCompleted(ThreadItem { + id, + content: ItemContent::Subagent { + status: ItemStatus::Completed, + summary: Some(summary), + .. + }, + .. + }) if id == "call_err" && summary == "Recovered and finished." + ) + }) + .expect("subagent should settle completed after recovery"); + assert!(reopen_pos < msg_pos && msg_pos < done_pos); + } } diff --git a/crates/protocol/src/event.rs b/crates/protocol/src/event.rs index fdfc36e05..4cb0ba379 100644 --- a/crates/protocol/src/event.rs +++ b/crates/protocol/src/event.rs @@ -894,6 +894,32 @@ impl ThreadWakes { } } +/// One provider-native subagent recorded in a thread's full history, as its +/// host reports it independently of any paginated history window. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NativeSubagentStatus { + /// The spawn item's id in the parent transcript (also the reattach key on + /// its mirror session's `native_subagent` field). + pub item_id: String, + pub agent_type: String, + pub description: String, + pub status: agent::ItemStatus, + /// True once the spawn call returned to the model while the subagent kept + /// running in the background (`AgentEvent::ItemBackgrounded`). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub background: bool, + /// Compact single-line preview of the subagent's summary, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preview: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effort: Option, + /// Wall-clock time (unix ms) when the spawn item was first observed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub started_at: Option, +} + /// One piece of a thread's background work as its host lists it: what the /// harness lists, and calls going on in the background that it does not. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -955,6 +981,11 @@ pub struct SessionStatus { /// going on in the background that it does not. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub background_tasks: Vec, + /// Provider-native subagents recorded across the thread's full history, + /// oldest first: clients hold only a paginated window of entries and + /// cannot discover spawns outside it from the timeline alone. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub native_subagents: Vec, /// Backend-owned drafts used by provider-bound send-path assembly. pub review_comment_drafts: Vec, pub terminals: Vec, diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index e7e5a29f6..71c793e96 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -50,8 +50,8 @@ pub use event::{ EventEnvelope, ExternalImportState, ExternalImportStatus, ForkAvailability, ForkStatus, GitActionRequest, GitStatusStatus, HarnessDescription, HarnessPermission, ImportFailure, IndexSnapshot, IndexSummary, InjectedChannel, InjectedInstructions, InjectedServer, - InjectedTools, LeftOrphan, MergeWorktreeFailure, NoticeSeverity, PendingRewind, - PluginCatalogState, PluginChallenge, PluginChallengeKind, PluginOperationTarget, + InjectedTools, LeftOrphan, MergeWorktreeFailure, NativeSubagentStatus, NoticeSeverity, + PendingRewind, PluginCatalogState, PluginChallenge, PluginChallengeKind, PluginOperationTarget, PluginStaleReason, PluginsDescription, ProviderDiskUsage, ProviderPluginCatalog, ProviderUpdateAvailable, ProviderUpdateRun, ProviderVersionStatus, ProvidersStatus, QueuedMessageStatus, RewindBlocked, RewindStatus, RuntimeEffect, RuntimeError, RuntimeNotice, @@ -447,6 +447,11 @@ pub use wire::{ // Version 36 (v0.5.5): ItemContent gains PlanModeEntered (`plan_mode_entered`) // with an optional `reason`. The RefreshModels command lists one native // harness's models again. +// +// Unreleased: SessionStatus gains native_subagents (NativeSubagentStatus), +// carrying every provider-native subagent from the thread's full history so +// clients need not load older timeline pages to list earlier or still-running +// spawns. pub const PROTOCOL_VERSION: u32 = 36; #[cfg(test)] diff --git a/crates/runtime/src/app/events.rs b/crates/runtime/src/app/events.rs index 8efc48a9d..c34b95061 100644 --- a/crates/runtime/src/app/events.rs +++ b/crates/runtime/src/app/events.rs @@ -632,6 +632,7 @@ impl AppState { let mut restart = false; // A restart would drop the answer of a rewind that stopped this turn. let rewinding = self.rewind_requests.contains_key(session_id); + let native_subagents_running = self.has_running_native_subagents(session_id); let is_active = if let Some(active) = self .residents .live @@ -639,7 +640,8 @@ impl AppState { .filter(|active| active.meta.id == session_id) { active.turn_in_flight = false; - let restartable = active.background_task_count == 0 && !rewinding; + let restartable = + active.background_task_count == 0 && !native_subagents_running && !rewinding; restart = restartable && !active.queue.is_empty() && !active.queue_held diff --git a/crates/runtime/src/app/lifecycle.rs b/crates/runtime/src/app/lifecycle.rs index 44c0dfa8a..128a69dbe 100644 --- a/crates/runtime/src/app/lifecycle.rs +++ b/crates/runtime/src/app/lifecycle.rs @@ -560,10 +560,12 @@ impl AppState { } self.park_terminal_workspace(&mut active); let native_rewind_pending = self.rewind_requests.contains_key(&active.meta.id); + let native_subagents_running = self.has_running_native_subagents(&active.meta.id); let has_work = active.turn_in_flight || active.delivery_in_flight.is_some() || !active.queue.is_empty() || active.background_task_count > 0 + || native_subagents_running || native_rewind_pending; let parkable = active.draft || has_work @@ -589,9 +591,13 @@ impl AppState { /// extend its process's life. pub(super) fn mark_resident_idle(&mut self, session_id: &str, cx: &mut HostCx) { let rewind_pending = self.rewind_requests.contains_key(session_id); + let native_subagents_running = self.has_running_native_subagents(session_id); // A draft holding text exists nowhere but here, so it never idles out. let Some(session) = self.residents.resident_mut(session_id).filter(|session| { - !rewind_pending && session.fully_idle() && !session.holds_draft_text() + !rewind_pending + && !native_subagents_running + && session.fully_idle() + && !session.holds_draft_text() }) else { return; }; @@ -606,7 +612,9 @@ impl AppState { .parked .iter() .filter(|(id, session)| { - session.fully_idle() && !self.rewind_requests.contains_key(id.as_str()) + session.fully_idle() + && !self.rewind_requests.contains_key(id.as_str()) + && !self.has_running_native_subagents(id.as_str()) }) .filter_map(|(id, session)| { session.idle_since.map(|idle| { @@ -670,6 +678,7 @@ impl AppState { cx: &mut HostCx, ) { let still_idle = !self.rewind_requests.contains_key(session_id) + && !self.has_running_native_subagents(session_id) && self.residents.resident(session_id).is_some_and(|session| { session.idle_since == Some(idle_since) && session.fully_idle() }); diff --git a/crates/runtime/src/app/send.rs b/crates/runtime/src/app/send.rs index b6b8e519a..10efdb2ef 100644 --- a/crates/runtime/src/app/send.rs +++ b/crates/runtime/src/app/send.rs @@ -165,13 +165,16 @@ impl AppState { continue; } + let native_subagents_running = self.has_running_native_subagents(&session_id); let (restart, is_live, has_queue) = self .residents .parked .get(&session_id) .map(|parked| { ( - parked.restart_required() && parked.background_task_count == 0, + parked.restart_required() + && parked.background_task_count == 0 + && !native_subagents_running, matches!(parked.runtime, Runtime::Live(_)), !parked.queue.is_empty(), ) @@ -224,6 +227,7 @@ impl AppState { let rewinding = self .resident(target_id) .is_some_and(|active| self.rewind_requests.contains_key(&active.meta.id)); + let native_subagents_running = self.has_running_native_subagents(target_id); let Some(active) = self.resident_mut(target_id) else { return; }; @@ -256,8 +260,9 @@ impl AppState { } let model_changed = active.model_changed_while_live(); - // A restart would drop the rewind's answer. - let restart_deferred = active.settings_restart_deferred() || rewinding; + // A restart would drop the rewind's answer or running native subagents. + let restart_deferred = + active.settings_restart_deferred() || native_subagents_running || rewinding; if active.restart_required() { if restart_deferred { log::info!( @@ -757,23 +762,31 @@ impl AppState { /// A parked session finished a turn: keep working through its queue, then /// retain its provider for the bounded resident-idle grace period. pub(super) fn on_background_turn_completed(&mut self, session_id: &str, cx: &mut HostCx) { + let native_subagents_running = self.has_running_native_subagents(session_id); let Some(parked) = self.residents.parked.get_mut(session_id) else { return; }; parked.turn_in_flight = false; let waiting = !parked.queue.is_empty() && !parked.queue_held; - if waiting && parked.restart_required() && parked.background_task_count == 0 { + if waiting + && parked.restart_required() + && parked.background_task_count == 0 + && !native_subagents_running + { parked.restart_to_idle(); self.ensure_session_started(session_id, cx); return; } if !waiting { - if parked.cwd_changed_while_live() && parked.background_task_count == 0 { + if parked.cwd_changed_while_live() + && parked.background_task_count == 0 + && !native_subagents_running + { parked.restart_to_idle(); } - if parked.background_task_count > 0 { + if parked.background_task_count > 0 || native_subagents_running { log::info!( - "retaining parked session {session_id} for {} background task(s)", + "retaining parked session {session_id} for {} background task(s) / running native subagents", parked.background_task_count ); return; diff --git a/crates/runtime/src/app/snapshots.rs b/crates/runtime/src/app/snapshots.rs index f6e8d0b22..ac2b9ce68 100644 --- a/crates/runtime/src/app/snapshots.rs +++ b/crates/runtime/src/app/snapshots.rs @@ -1,6 +1,8 @@ use super::*; use tcode_core::settlement::{AgentDelivery, AgentExecution}; -use tcode_protocol::{AgentStatus, BackgroundActivity, BackgroundTaskStatus, ThreadWakes}; +use tcode_protocol::{ + AgentStatus, BackgroundActivity, BackgroundTaskStatus, NativeSubagentStatus, ThreadWakes, +}; pub(crate) struct DomainDiff { subscriptions: HashSet, @@ -1628,6 +1630,7 @@ impl AppState { acp_agent_id: meta.acp_agent_id.clone(), project_id: meta.project_id.clone(), background_tasks: session.background.statuses(&session.timeline), + native_subagents: native_subagents(&session.timeline), queued_messages: session .queue .iter() @@ -1775,3 +1778,62 @@ impl AppState { barrier } } + +/// Cap single-line subagent previews in `SessionStatus` so large reports do not +/// bloat every status push; the UI shows one elided line. +const MAX_NATIVE_SUBAGENT_PREVIEW_CHARS: usize = 240; + +fn compact_preview(text: &str) -> Option { + let mut out = String::new(); + let mut chars = 0usize; + for word in text.split_whitespace() { + if chars > 0 { + if chars >= MAX_NATIVE_SUBAGENT_PREVIEW_CHARS { + out.push('…'); + break; + } + out.push(' '); + chars += 1; + } + for ch in word.chars() { + if chars >= MAX_NATIVE_SUBAGENT_PREVIEW_CHARS { + out.push('…'); + return Some(out); + } + out.push(ch); + chars += 1; + } + } + (!out.is_empty()).then_some(out) +} + +fn native_subagents(timeline: &Timeline) -> Vec { + timeline + .entries + .iter() + .filter_map(|entry| { + let EntryContent::Item(ItemContent::Subagent { + agent_type, + description, + status, + summary, + model, + effort, + }) = &entry.content + else { + return None; + }; + Some(NativeSubagentStatus { + item_id: entry.id.clone(), + agent_type: agent_type.clone(), + description: description.clone(), + status: *status, + background: entry.background, + preview: summary.as_deref().and_then(compact_preview), + model: model.clone(), + effort: effort.clone(), + started_at: entry.ts, + }) + }) + .collect() +} diff --git a/crates/runtime/src/app/subagents.rs b/crates/runtime/src/app/subagents.rs index 477fcad8d..1649d9b79 100644 --- a/crates/runtime/src/app/subagents.rs +++ b/crates/runtime/src/app/subagents.rs @@ -237,6 +237,11 @@ impl AppState { mirror.turn_in_flight = running; } if running && !open { + if let Some(owner_id) = self.native_subagent_owner_id(mirror_id) + && let Some(owner) = self.resident_mut(&owner_id) + { + owner.idle_since = None; + } self.record_event( mirror_id, &AgentEvent::TurnStarted { @@ -255,18 +260,40 @@ impl AppState { cx, ); // The mirror no longer holds the thread whose provider runs it. - let mut owner = self.find_meta(mirror_id); - while let Some(meta) = owner.take_if(|meta| meta.native_subagent.is_some()) { - owner = meta - .parent_session_id - .and_then(|parent| self.find_meta(&parent)); - } - if let Some(owner) = owner { - self.evaluate_thread_settlement(&owner.id, cx); + if let Some(owner_id) = self.native_subagent_owner_id(mirror_id) { + self.evaluate_thread_settlement(&owner_id, cx); + if !self.has_running_native_subagents(&owner_id) { + self.mark_resident_idle(&owner_id, cx); + } } } } + /// The root session whose provider process owns `mirror_id`. + fn native_subagent_owner_id(&self, mirror_id: &str) -> Option { + let mut owner = self.find_meta(mirror_id); + while let Some(meta) = owner.take_if(|meta| meta.native_subagent.is_some()) { + owner = meta + .parent_session_id + .and_then(|parent| self.find_meta(&parent)); + } + owner.map(|meta| meta.id) + } + + /// Whether any provider-native subagent mirror under `session_id` (nested + /// mirrors included) still has an open turn running in its provider process. + pub(super) fn has_running_native_subagents(&self, session_id: &str) -> bool { + if self.native_subagent_turns.values().all(|running| !*running) { + return false; + } + let descendants = descendant_session_ids(&self.sessions, session_id); + self.sessions.iter().any(|meta| { + meta.native_subagent.is_some() + && descendants.contains(&meta.id) + && self.native_subagent_turns.get(&meta.id) == Some(&true) + }) + } + /// The existing mirror for `subagent_item_id` anywhere under `session_id`: /// a direct child, or a nested spawn's mirror under another mirror. fn find_native_subagent_mirror( @@ -277,6 +304,11 @@ impl AppState { ) -> Option { let key = (session_id.to_string(), subagent_item_id.to_string()); if let Some(id) = self.native_subagent_sessions.get(&key).cloned() { + if self.resident(&id).is_none() + && let Some(meta) = self.find_meta(&id) + { + self.load_background_session(meta, cx); + } return Some(id); } let descendants = descendant_session_ids(&self.sessions, session_id); diff --git a/crates/runtime/src/app/tests/mirrors.rs b/crates/runtime/src/app/tests/mirrors.rs index bf5216f43..2b3c24dda 100644 --- a/crates/runtime/src/app/tests/mirrors.rs +++ b/crates/runtime/src/app/tests/mirrors.rs @@ -893,3 +893,131 @@ fn loading_a_mirror_with_an_open_turn_and_no_live_parent_ends_it() { assert_eq!(timeline.turns[0].status, Some(TurnStatus::Interrupted)); assert!(!cx.seen().status("mirror").activity.turn_running); } + +/// A live parent whose turn has ended keeps its provider process while a +/// provider-native subagent mirror is still running, and reaps normally once +/// that subagent finishes. +#[test] +fn running_native_subagent_holds_idle_reap_until_done() { + let cx = &mut TestAppContext::default(); + let test_store = TestStore::new("tcode-native-subagent-idle-reap"); + stored_thread( + &test_store, + "parent", + ProviderKind::Antigravity, + &test_store.root().join("parent"), + |_| {}, + ); + let (state, providers) = played_host(cx, &test_store); + state.subscribe(cx, Topic::Index); + let provider = first_turn(&state, cx, &providers, "parent", 0); + + provider.play([ + AgentEvent::ItemStarted(subagent_item( + "call_sub", + None, + "worker", + "Long running worker", + ItemStatus::InProgress, + )), + completed_turn("turn-0"), + ]); + cx.run_until_seen(|view| { + view.mirror("call_sub").is_some() && has_record(view, "parent", is_turn_end) + }); + + // Advancing past the idle grace must not kill the parent process while the + // native subagent still runs. + cx.clock + .advance(RESIDENT_IDLE_GRACE + Duration::from_secs(60)); + provider.fence(cx, "parent"); + assert!( + next_command(&provider.commands).is_err(), + "parent provider must stay alive while its native subagent runs" + ); + + // Once the subagent completes, the idle grace starts and reaps the process. + provider.play([AgentEvent::ItemCompleted(subagent_item( + "call_sub", + None, + "worker", + "Long running worker", + ItemStatus::Completed, + ))]); + cx.run_until_seen(|view| { + let mirror_id = &view.mirror("call_sub").unwrap().id; + has_record(view, mirror_id, is_turn_end) + }); + cx.clock + .advance(RESIDENT_IDLE_GRACE + Duration::from_secs(60)); + assert!(matches!( + provider.next_command(cx), + SessionCommand::Shutdown + )); +} + +/// `SessionStatus::native_subagents` reports every provider-native subagent in +/// the thread's full history (including earlier still-running background +/// spawns), so clients with a paginated timeline window never miss them. +#[test] +fn session_status_lists_all_native_subagents_from_full_history() { + let cx = &mut TestAppContext::default(); + let test_store = TestStore::new("tcode-native-subagent-status-list"); + stored_thread( + &test_store, + "parent", + ProviderKind::ClaudeCode, + &test_store.root().join("parent"), + |_| {}, + ); + let (state, providers) = played_host(cx, &test_store); + state.subscribe(cx, Topic::Index); + state.subscribe( + cx, + Topic::SessionStatus { + session_id: "parent".into(), + }, + ); + let provider = first_turn(&state, cx, &providers, "parent", 0); + + provider.play([ + AgentEvent::ItemStarted(subagent_item( + "call_early", + None, + "Explore", + "Long background scan", + ItemStatus::InProgress, + )), + AgentEvent::ItemBackgrounded { + item_id: "call_early".into(), + parent_item_id: None, + }, + AgentEvent::ItemCompleted(ThreadItem { + id: "call_recent".into(), + parent_item_id: None, + content: ItemContent::Subagent { + agent_type: "general".into(), + description: "Quick check".into(), + status: ItemStatus::Completed, + summary: Some("Line 1\n\n Line 2".into()), + model: Some("claude-sonnet".into()), + effort: Some("high".into()), + }, + }), + completed_turn("turn-0"), + ]); + cx.run_until_seen(|view| { + view.has_status("parent") && view.status("parent").native_subagents.len() == 2 + }); + + let subs = &cx.seen().status("parent").native_subagents; + assert_eq!(subs[0].item_id, "call_early"); + assert_eq!(subs[0].status, ItemStatus::InProgress); + assert!(subs[0].background); + assert_eq!(subs[1].item_id, "call_recent"); + assert_eq!(subs[1].status, ItemStatus::Completed); + assert!(!subs[1].background); + assert_eq!(subs[1].preview.as_deref(), Some("Line 1 Line 2")); + assert_eq!(subs[1].model.as_deref(), Some("claude-sonnet")); + assert_eq!(subs[1].effort.as_deref(), Some("high")); +} diff --git a/crates/ui/src/agents_panel.rs b/crates/ui/src/agents_panel.rs index f8417dd33..89a737fff 100644 --- a/crates/ui/src/agents_panel.rs +++ b/crates/ui/src/agents_panel.rs @@ -256,8 +256,94 @@ impl Agents { }) .map(|row| row.task.id.clone()) }; + struct NativeRowInput<'a> { + item_id: &'a str, + agent_type: &'a str, + description: &'a str, + status: ItemStatus, + background: bool, + preview: Option<&'a str>, + model: Option<&'a str>, + effort: Option<&'a str>, + started_at: Option, + } let mut native = Vec::new(); let mut settled_native = Vec::new(); + let mut seen_native = std::collections::HashSet::new(); + let provider = parent.map(|parent| parent.provider); + let profile_id = parent.and_then(|parent| parent.profile_id.clone()); + let mut push_native = |sub: NativeRowInput<'_>| { + if !seen_native.insert(sub.item_id.to_owned()) { + return; + } + let mirror = live.iter().find(|meta| { + meta.parent_session_id.as_deref() == Some(parent_id) + && meta.native_subagent.as_deref() == Some(sub.item_id) + }); + let execution = match sub.status { + ItemStatus::InProgress if sub.background => AgentExecution::Background, + ItemStatus::InProgress => AgentExecution::Working, + ItemStatus::Completed => AgentExecution::Finished, + ItemStatus::Interrupted => AgentExecution::Interrupted, + ItemStatus::Failed | ItemStatus::Declined => AgentExecution::Failed, + }; + let group = if mirror.is_some_and(|meta| meta.is_settled()) { + &mut settled_native + } else { + &mut native + }; + group.push(AgentRow { + key: sub.item_id.to_owned(), + title: Some(compact(sub.description)) + .filter(|title| !title.is_empty()) + .unwrap_or_else(|| sub.agent_type.to_owned()), + provider, + profile_id: profile_id.clone(), + model: sub.model.map(str::to_owned), + effort: sub.effort.map(str::to_owned), + execution: Some(execution), + attention: attention(mirror.map(|meta| meta.id.as_str())), + // It runs in its lead's process, on its lead's checkout. + branch: None, + delivery: None, + report: AgentReport::None, + archived: false, + activity: running_activity(mirror.map(|meta| meta.id.as_str()), execution), + preview: sub.preview.map(compact).filter(|s| !s.is_empty()), + open: mirror.map(|meta| meta.id.clone()), + agent: None, + stop_task: execution + .running() + .then(|| stop_task(sub.item_id)) + .flatten(), + managed_by: provider.map(|provider| provider.display_name()), + agent_type: Some(sub.agent_type.to_owned()), + // A native subagent's end is not reported, only its start. + started_at: sub.started_at.filter(|_| execution.running()), + ended_at: None, + machine: None, + standing: None, + note: None, + elsewhere: None, + closed: None, + remote: None, + }); + }; + if let Some(status) = status { + for sub in &status.native_subagents { + push_native(NativeRowInput { + item_id: &sub.item_id, + agent_type: &sub.agent_type, + description: &sub.description, + status: sub.status, + background: sub.background, + preview: sub.preview.as_deref(), + model: sub.model.as_deref(), + effort: sub.effort.as_deref(), + started_at: sub.started_at, + }); + } + } store.with_entries_for( Some(parent_id), |timeline| { @@ -273,61 +359,23 @@ impl Agents { else { continue; }; - let mirror = live.iter().find(|meta| { - meta.parent_session_id.as_deref() == Some(parent_id) - && meta.native_subagent.as_deref() == Some(entry.id.as_str()) - }); - let provider = parent.map(|parent| parent.provider); - let execution = match status { - ItemStatus::InProgress if entry.background => AgentExecution::Background, - ItemStatus::InProgress => AgentExecution::Working, - ItemStatus::Completed => AgentExecution::Finished, - ItemStatus::Interrupted => AgentExecution::Interrupted, - ItemStatus::Failed | ItemStatus::Declined => AgentExecution::Failed, - }; - let group = if mirror.is_some_and(|meta| meta.is_settled()) { - &mut settled_native - } else { - &mut native - }; - group.push(AgentRow { - key: entry.id.clone(), - title: Some(compact(description)) - .filter(|title| !title.is_empty()) - .unwrap_or_else(|| agent_type.clone()), - provider, - profile_id: parent.and_then(|parent| parent.profile_id.clone()), - model: model.clone(), - effort: effort.clone(), - execution: Some(execution), - attention: attention(mirror.map(|meta| meta.id.as_str())), - // It runs in its lead's process, on its lead's checkout. - branch: None, - delivery: None, - report: AgentReport::None, - archived: false, - activity: running_activity(mirror.map(|meta| meta.id.as_str()), execution), - preview: summary.as_deref().map(compact).filter(|s| !s.is_empty()), - open: mirror.map(|meta| meta.id.clone()), - agent: None, - stop_task: execution.running().then(|| stop_task(&entry.id)).flatten(), - managed_by: provider.map(|provider| provider.display_name()), - agent_type: Some(agent_type.clone()), - // A native subagent's end is not reported, only its start. - started_at: entry.ts.filter(|_| execution.running()), - ended_at: None, - machine: None, - standing: None, - note: None, - elsewhere: None, - closed: None, - remote: None, + push_native(NativeRowInput { + item_id: &entry.id, + agent_type, + description, + status: *status, + background: entry.background, + preview: summary.as_deref(), + model: model.as_deref(), + effort: effort.as_deref(), + started_at: entry.ts, }); } }, cx, ); native.reverse(); + native.sort_by_key(|row| !row.execution.is_some_and(AgentExecution::running)); settled_native.reverse(); let mut dispatched: Vec<_> = live @@ -547,7 +595,13 @@ impl Agents { 1 => parts.push(crate::tr!("agents.summary_answer_one").into_owned()), count => parts.push(crate::tr!("agents.summary_answer", count = count).into_owned()), } - match self.running.len() { + let running = self.running.len() + + self + .native + .iter() + .filter(|row| row.execution.is_some_and(AgentExecution::running)) + .count(); + match running { 0 => {} 1 => parts.push(crate::tr!("agents.summary_running_one").into_owned()), count => parts.push(crate::tr!("agents.summary_running", count = count).into_owned()), diff --git a/crates/ui/src/agents_panel/tests.rs b/crates/ui/src/agents_panel/tests.rs index d10d1d4a5..76b6d97fb 100644 --- a/crates/ui/src/agents_panel/tests.rs +++ b/crates/ui/src/agents_panel/tests.rs @@ -298,6 +298,10 @@ fn a_running_agents_activity_gives_way_to_its_result(cx: &mut TestAppContext) { (Some(LatestActivity::Thinking), None) ] ); + assert_eq!( + store.read_with(cx, |store, cx| Agents::of(store, "lead", cx).summary()), + Some(crate::tr!("agents.summary_running", count = 2).into_owned()), + ); let (_, cx) = cx.add_window_view(|window, cx| { let panel = cx.new(|cx| super::AgentsPanel::new(store.clone(), Some("lead".into()), cx)); @@ -475,3 +479,208 @@ fn settle_all_button_sends_the_lead_command(cx: &mut TestAppContext) { ); link.close(); } + +/// Native subagents spawned before the client's loaded timeline page still +/// appear in `Agents::of` via `SessionStatus::native_subagents`, keep running +/// spawns ahead of finished ones, and do not duplicate once older history loads. +#[gpui::test] +fn native_subagents_outside_loaded_history_window_stay_visible_and_do_not_duplicate( + cx: &mut TestAppContext, +) { + use agent::{AgentEvent, ItemContent, ItemStatus, ThreadItem}; + use tcode_core::settlement::AgentExecution; + use tcode_protocol::NativeSubagentStatus; + + let (to_host, _requests) = async_channel::unbounded(); + let (incoming, from_host) = async_channel::unbounded(); + let link = tcode_client::HostLink::new(to_host, from_host); + let store = cx.new(|cx| { + WorkspaceStore::new_attached(link.clone(), WorkspaceAttachment::Local, None, None, cx) + }); + let thread = |id: &str, parent: Option<&str>, native: Option<&str>| { + let mut meta = SessionMeta::new(ProviderKind::ClaudeCode, "/project".into(), None); + meta.id = id.into(); + meta.title = id.into(); + meta.parent_session_id = parent.map(str::to_owned); + meta.native_subagent = native.map(str::to_owned); + meta + }; + let line = |topic, event| { + tcode_protocol::encode_line(&HostMessage::Event(EventEnvelope { + request_id: None, + topic, + event, + })) + .unwrap() + }; + let index = IndexSnapshot { + sessions: vec![ + thread("lead", None, None), + thread("mirror_early", Some("lead"), Some("spawn_early")), + thread("mirror_recent", Some("lead"), Some("spawn_recent")), + ], + projects: vec![], + summary: Default::default(), + }; + crate::store::tests::seed_full_scope( + &store, + &incoming, + vec![line(Topic::Index, ServerEvent::IndexSnapshot(index))], + cx, + ); + let mut driver = crate::store::tests::LocalHostDriver::from_link(link.clone()); + store.update(cx, |store, cx| store.show_alone("lead".into(), cx)); + + let mut status = crate::store::tests::draft_status(); + status.session_id = "lead".into(); + status.provider = ProviderKind::ClaudeCode; + status.draft = false; + status.native_subagents = vec![ + NativeSubagentStatus { + item_id: "spawn_early".into(), + agent_type: "Explore".into(), + description: "Earlier background worker".into(), + status: ItemStatus::InProgress, + background: true, + preview: None, + model: Some("claude-sonnet".into()), + effort: None, + started_at: Some(1_000), + }, + NativeSubagentStatus { + item_id: "spawn_recent".into(), + agent_type: "Explore".into(), + description: "Recent finished worker".into(), + status: ItemStatus::Completed, + background: false, + preview: Some("Done".into()), + model: None, + effort: None, + started_at: Some(2_000), + }, + ]; + let recent_spawn = ThreadItem { + id: "spawn_recent".into(), + parent_item_id: None, + content: ItemContent::Subagent { + agent_type: "Explore".into(), + description: "Recent finished worker".into(), + status: ItemStatus::Completed, + summary: Some("Done".into()), + model: None, + effort: None, + }, + }; + let events_topic = Topic::SessionEvents { + session_id: "lead".into(), + }; + // Tail page only contains `spawn_recent`; `spawn_early` is above the window. + for msg in [ + line( + Topic::SessionStatus { + session_id: "lead".into(), + }, + ServerEvent::SessionStatusReplaced(Box::new(status)), + ), + line( + events_topic.clone(), + ServerEvent::SessionSnapshot { + total: 100, + total_turns: 10, + truncated: true, + from: 98, + end: 100, + records: vec![ + AgentEvent::TurnStarted { + turn_id: "turn-9".into(), + } + .into(), + AgentEvent::ItemCompleted(recent_spawn.clone()).into(), + ], + }, + ), + ] { + incoming.try_send(msg).unwrap(); + } + driver.wait_until(cx, "lead status and tail page", |cx| { + store.read_with(cx, |store, cx| { + store + .session_status_for(Some("lead"), cx) + .is_some_and(|s| s.native_subagents.len() == 2) + }) + }); + + let assert_consistent = |cx: &mut TestAppContext| { + store.read_with(cx, |store, cx| { + let agents = Agents::of(store, "lead", cx); + assert_eq!(agents.count(), 2); + assert_eq!( + agents.summary(), + Some(crate::tr!("agents.summary_running_one").into_owned()), + ); + let lines = agents.lines(); + assert_eq!( + lines.iter().map(|l| l.key.as_str()).collect::>(), + vec!["spawn_early", "spawn_recent"] + ); + assert_eq!(lines[0].execution, Some(AgentExecution::Background)); + assert_eq!(lines[0].open.as_deref(), Some("mirror_early")); + assert_eq!(lines[1].execution, Some(AgentExecution::Finished)); + assert_eq!(lines[1].preview.as_deref(), Some("Done")); + }); + }; + assert_consistent(cx); + + // Loading the full history window containing `spawn_early` must keep the + // exact same list and count without duplicating rows. + let early_spawn = ThreadItem { + id: "spawn_early".into(), + parent_item_id: None, + content: ItemContent::Subagent { + agent_type: "Explore".into(), + description: "Earlier background worker".into(), + status: ItemStatus::InProgress, + summary: None, + model: Some("claude-sonnet".into()), + effort: None, + }, + }; + incoming + .try_send(line( + events_topic, + ServerEvent::SessionSnapshot { + total: 100, + total_turns: 10, + truncated: false, + from: 0, + end: 100, + records: vec![ + AgentEvent::TurnStarted { + turn_id: "turn-0".into(), + } + .into(), + AgentEvent::ItemStarted(early_spawn).into(), + AgentEvent::ItemBackgrounded { + item_id: "spawn_early".into(), + parent_item_id: None, + } + .into(), + AgentEvent::TurnStarted { + turn_id: "turn-9".into(), + } + .into(), + AgentEvent::ItemCompleted(recent_spawn).into(), + ], + }, + )) + .unwrap(); + driver.wait_until(cx, "full history loaded", |cx| { + store.read_with(cx, |store, cx| { + store + .with_entries_for(Some("lead"), |timeline| timeline.entries.len(), cx) + .is_some_and(|n| n >= 2) + }) + }); + assert_consistent(cx); + link.close(); +} diff --git a/crates/ui/src/chat/components/plan.rs b/crates/ui/src/chat/components/plan.rs index 8815ba646..5cc4af0a4 100644 --- a/crates/ui/src/chat/components/plan.rs +++ b/crates/ui/src/chat/components/plan.rs @@ -2,9 +2,10 @@ use std::path::Path; use std::rc::Rc; use std::sync::Arc; -use crate::icon::IconName; +use crate::icon::{Icon, IconName}; use crate::markdown::{MarkdownState, MarkdownView}; use crate::material::event_card::{self, CardTone}; +use crate::sizing::Sizable as _; use crate::theme::ActiveTheme as _; use crate::typography::TextRole as _; use crate::widgets::button::{Button, ButtonVariants as _}; @@ -13,7 +14,8 @@ use crate::widgets::menu::{ContextMenuExt as _, PopupMenu}; use agent::{ApprovalOption, ApprovalOptionKind}; use gpui::{ AnyElement, App, ClickEvent, Context, Entity, InteractiveElement as _, IntoElement as _, - ParentElement as _, SharedString, Styled as _, Window, div, prelude::FluentBuilder as _, + ParentElement as _, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, + prelude::FluentBuilder as _, px, }; use gpui_base::h_flex; @@ -41,6 +43,7 @@ pub(crate) struct PlanData<'a> { pub(crate) markdown: Option>, pub(crate) compact: bool, pub(crate) copied: bool, + pub(crate) expanded: bool, pub(crate) decision: Option>, /// The chat's motion, which keeps the plan's buttons' clocks. pub(crate) motion: crate::motion::owned::Owned, @@ -51,6 +54,7 @@ pub(crate) struct PlanData<'a> { /// waits on along its foot. pub(crate) fn plan_block( data: PlanData<'_>, + on_toggle: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, on_copy: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, cx: &App, ) -> AnyElement { @@ -63,35 +67,61 @@ pub(crate) fn plan_block( markdown, compact, copied, + expanded, decision, motion, } = data; let theme = cx.theme(); let menu_items = copy_message_items(copy_text); - let body = markdown.map_or_else( - || div().child(text.to_string()).into_any_element(), - |markdown| { - MarkdownView::new(&markdown) - .compact_headings(true) - .selectable(true) - .image_host(image_host) - .base_dir(cwd) - .menu_extension(menu_items.clone()) - .into_any_element() - }, - ); + let body = expanded.then(|| { + markdown.map_or_else( + || div().child(text.to_string()).into_any_element(), + |markdown| { + MarkdownView::new(&markdown) + .compact_headings(true) + .selectable(true) + .image_host(image_host) + .base_dir(cwd) + .menu_extension(menu_items.clone()) + .into_any_element() + }, + ) + }); let tone = if decision.is_some() { CardTone::Waiting } else { CardTone::Neutral }; - let header = event_card::header(true, cx) - .child(event_card::icon_tile(IconName::Map, cx)) - .child(event_card::header_text( - crate::tr!("chat.plan_title").into_owned(), - None, - cx, - )) + let subtitle = (!expanded).then(|| plan_preview(text)).flatten(); + let toggle_id = SharedString::from(format!("plan-toggle-{id}")); + let toggle_selector = format!("plan-toggle-{id}"); + let chevron = Icon::new(if expanded { + IconName::ChevronDown + } else { + IconName::ChevronRight + }) + .small() + .flex_none() + .text_color(theme.muted_foreground); + let header = event_card::header(subtitle.is_none(), cx) + .child( + h_flex() + .id(toggle_id) + .debug_selector(move || toggle_selector) + .flex_1() + .min_w_0() + .items_center() + .gap(px(10.)) + .cursor_pointer() + .on_click(on_toggle) + .child(event_card::icon_tile(IconName::Map, cx)) + .child(event_card::header_text( + crate::tr!("chat.plan_title").into_owned(), + subtitle, + cx, + )) + .child(chevron), + ) .child(copy_button(&format!("plan:{id}"), copied, compact, on_copy, cx).motion(&motion)); let footer = decision.map(|decision| { let mut choices = h_flex().gap_2().items_center().flex_wrap(); @@ -139,12 +169,37 @@ pub(crate) fn plan_block( }) .flex_none() .child(header) - .child( - event_card::section(cx) - .text_token(&theme.tokens.typography.md) - .child(body), - ) + .when_some(body, |card, body| { + card.child( + event_card::section(cx) + .text_token(&theme.tokens.typography.md) + .child(body), + ) + }) .children(footer) .context_menu(margin_menu) .into_any_element() } + +/// First non-empty line of a plan's Markdown stripped of leading block markers, +/// shown as the header's subtitle while the card is collapsed. +fn plan_preview(markdown: &str) -> Option { + for line in markdown.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() + || trimmed.chars().all(|c| c == '-' || c == '=' || c == '*') + || trimmed.starts_with("```") + { + continue; + } + let cleaned = trimmed + .trim_start_matches('#') + .trim_start() + .trim_start_matches(['>', '-', '*']) + .trim_start(); + if !cleaned.is_empty() { + return Some(SharedString::from(crate::chat::model::one_line(cleaned))); + } + } + None +} diff --git a/crates/ui/src/chat/timeline/render.rs b/crates/ui/src/chat/timeline/render.rs index 1358ed0ba..4e1461444 100644 --- a/crates/ui/src/chat/timeline/render.rs +++ b/crates/ui/src/chat/timeline/render.rs @@ -254,7 +254,7 @@ impl TimelineView { )); } Segment::Plan(entry) => { - column = column.child(self.compose_plan(entry, cwd, cx)); + column = column.child(self.compose_plan(index, entry, cwd, cx)); } Segment::PlanModeEntered(entry) => { let EntryContent::Item(ItemContent::PlanModeEntered { reason }) = @@ -1257,6 +1257,7 @@ impl TimelineView { /// A proposed plan's block, carrying the decision its agent waits on. fn compose_plan( &self, + turn: usize, entry: &TimelineEntry, cwd: &Path, cx: &mut Context, @@ -1292,6 +1293,10 @@ impl TimelineView { ) }); }); + let default_collapsed = request.is_none() && self.plan_default_collapsed(cx); + let toggle_key = format!("plan-expand:{}", entry.id); + let toggled = self.expanded.contains(&toggle_key); + let expanded = if default_collapsed { toggled } else { !toggled }; let copy_key = format!("plan:{}", entry.id); let copied = self.copied.is(©_key); components::plan::plan_block( @@ -1304,6 +1309,7 @@ impl TimelineView { markdown, compact: self.window_state.read(cx).compact, copied, + expanded, decision: request .as_ref() .map(|request| components::plan::PlanDecision { @@ -1313,6 +1319,7 @@ impl TimelineView { }), motion: self.motion.clone(), }, + cx.listener(move |this, _, _, cx| this.toggle_expanded(turn, &toggle_key, cx)), cx.listener(move |this, _, _, cx| { cx.write_to_clipboard(ClipboardItem::new_string(copy_text.to_string())); this.mark_copied(copy_key.clone(), cx); @@ -1321,6 +1328,33 @@ impl TimelineView { ) } + /// Antigravity Orchestrator emits frequent internal plan handoffs between + /// its planning and execution models, so collapse its plan cards by default + /// unless a card awaits user approval. + fn plan_default_collapsed(&self, cx: &App) -> bool { + let store = self.workspace_store.read(cx); + let Some(session_id) = self.session_id.as_deref() else { + return false; + }; + let status = store.session_status_for(Some(session_id), cx); + let meta = store.thread_meta(session_id); + let provider = status + .map(|status| status.provider) + .or_else(|| meta.map(|meta| meta.provider)); + if provider != Some(agent::ProviderKind::Antigravity) { + return false; + } + let model = status + .and_then(|status| { + status + .running_model + .as_deref() + .or(status.requested_model.as_deref()) + }) + .or_else(|| meta.and_then(|meta| meta.model.as_deref())); + model.is_some_and(|model| model.to_ascii_lowercase().contains("orchestrator")) + } + pub(in crate::chat) fn sync_deciding_plan(&mut self, cx: &mut Context) { let deciding = self .workspace_store diff --git a/crates/ui/src/chat/timeline/render/tests.rs b/crates/ui/src/chat/timeline/render/tests.rs index 2d351e304..6ea46a366 100644 --- a/crates/ui/src/chat/timeline/render/tests.rs +++ b/crates/ui/src/chat/timeline/render/tests.rs @@ -1309,3 +1309,85 @@ fn a_rewind_divider_offers_what_its_harness_keeps(cx: &mut TestAppContext) { ); } } + +#[gpui::test] +fn plan_card_collapses_on_click_and_defaults_collapsed_for_antigravity_orchestrator( + cx: &mut TestAppContext, +) { + use gpui::{Modifiers, VisualTestContext, px, size}; + + let make_timeline = || { + let mut timeline = Timeline::default(); + timeline.turns = vec![TurnMeta::default()]; + timeline.entries.extend([ + entry("user-0", user_item("Run the roadmap")), + entry( + "plan-0", + EntryContent::Item(ItemContent::Plan { + markdown: "# Implementation Plan\n\n1. First step\n2. Second step\n3. Third step\n4. Fourth step\n5. Fifth step" + .into(), + }), + ), + ]); + timeline + }; + + // Non-orchestrator threads default to expanded and collapse on header click. + { + let timeline = make_timeline(); + let thread = ScriptedThread::new(cx, log_of(&timeline), 0, false); + cx.update(|cx| cx.set_reduce_motion(true)); + let (_view, cx) = thread.open(cx); + let cx: &mut VisualTestContext = cx; + cx.simulate_resize(size(px(900.), px(900.))); + thread.deliver(cx); + draw_settled(cx); + + let expanded = cx + .debug_bounds("plan-card-plan-0") + .expect("plan card renders expanded by default"); + let toggle = cx + .debug_bounds("plan-toggle-plan-0") + .expect("plan toggle renders"); + cx.simulate_click(toggle.center(), Modifiers::default()); + draw_settled(cx); + let collapsed = cx + .debug_bounds("plan-card-plan-0") + .expect("plan card stays visible when collapsed"); + assert!( + collapsed.size.height < expanded.size.height, + "clicking plan header collapses the card ({expanded:?} -> {collapsed:?})" + ); + } + + // Antigravity Orchestrator defaults to collapsed and expands on header click. + { + let timeline = make_timeline(); + let mut thread = ScriptedThread::new(cx, log_of(&timeline), 0, false); + thread.status.provider = agent::ProviderKind::Antigravity; + thread.status.requested_model = Some("gemini-pro-orchestrator-neon".into()); + thread.set_running(false); + cx.update(|cx| cx.set_reduce_motion(true)); + let (_view, cx) = thread.open(cx); + let cx: &mut VisualTestContext = cx; + cx.simulate_resize(size(px(900.), px(900.))); + thread.deliver(cx); + draw_settled(cx); + + let collapsed = cx + .debug_bounds("plan-card-plan-0") + .expect("orchestrator plan card renders collapsed by default"); + let toggle = cx + .debug_bounds("plan-toggle-plan-0") + .expect("orchestrator plan toggle renders"); + cx.simulate_click(toggle.center(), Modifiers::default()); + draw_settled(cx); + let expanded = cx + .debug_bounds("plan-card-plan-0") + .expect("orchestrator plan card expands on click"); + assert!( + expanded.size.height > collapsed.size.height, + "clicking collapsed orchestrator plan header expands the card ({collapsed:?} -> {expanded:?})" + ); + } +} diff --git a/crates/ui/src/shell/tests/mod.rs b/crates/ui/src/shell/tests/mod.rs index c50d746db..c365b31b2 100644 --- a/crates/ui/src/shell/tests/mod.rs +++ b/crates/ui/src/shell/tests/mod.rs @@ -1975,6 +1975,7 @@ fn session_status(session: &str, cwd: &std::path::Path) -> tcode_protocol::Sessi project_id: None, queued_messages: Vec::new(), background_tasks: Vec::new(), + native_subagents: Vec::new(), review_comment_drafts: Vec::new(), terminals: Vec::new(), active_terminal_id: None, diff --git a/crates/ui/src/store/snapshots.rs b/crates/ui/src/store/snapshots.rs index eec6f1ebf..a40047354 100644 --- a/crates/ui/src/store/snapshots.rs +++ b/crates/ui/src/store/snapshots.rs @@ -297,6 +297,7 @@ mod tests { project_id: Some("project-1".into()), queued_messages: Vec::new(), background_tasks: Vec::new(), + native_subagents: Vec::new(), review_comment_drafts: Vec::new(), terminals: Vec::new(), active_terminal_id: None, From 39b834151cf252b5ece7a1dc9b835a3ca7eae56a Mon Sep 17 00:00:00 2001 From: Tryanks Date: Sun, 6 Dec 2026 01:03:36 +0800 Subject: [PATCH 2/3] Review fixes: keep the UI provider-agnostic and settle every spawn - Plan cards no longer default to collapsed by testing for Antigravity and an "orchestrator" model name in the UI (Principle 4). Every plan opens expanded and collapses from its header; the test covers that contract. - The active-step query in the Antigravity record now propagates its errors like the last-step query does. A failed read had counted as "nothing running", which settled background tasks early. Fixtures use the real `status` column, which agy 1.5.25 writes. - A nested invoke_subagent whose child cannot be named, and nested spawns still open when a turn yields or the session closes, now end with a terminal status. Left open, they held their lead's process alive. --- crates/agent/src/antigravity.rs | 2 +- crates/agent/src/antigravity/record.rs | 26 ++--- crates/agent/src/antigravity/subagents.rs | 33 +++--- crates/ui/src/chat/timeline/render.rs | 34 +----- crates/ui/src/chat/timeline/render/tests.rs | 119 ++++++++------------ 5 files changed, 78 insertions(+), 136 deletions(-) diff --git a/crates/agent/src/antigravity.rs b/crates/agent/src/antigravity.rs index bcddfc51d..7051443b8 100644 --- a/crates/agent/src/antigravity.rs +++ b/crates/agent/src/antigravity.rs @@ -1541,7 +1541,7 @@ mod tests { let connection = database.connect().unwrap(); connection .execute( - "CREATE TABLE steps (idx integer, step_type integer NOT NULL DEFAULT 0, PRIMARY KEY (idx))", + "CREATE TABLE steps (idx integer, step_type integer NOT NULL DEFAULT 0, status integer NOT NULL DEFAULT 3, PRIMARY KEY (idx))", (), ) .await diff --git a/crates/agent/src/antigravity/record.rs b/crates/agent/src/antigravity/record.rs index d3171498e..68e9852c9 100644 --- a/crates/agent/src/antigravity/record.rs +++ b/crates/agent/src/antigravity/record.rs @@ -256,24 +256,22 @@ fn read_record_state(record: &Path) -> Result, String> { }; let mut has_generating_step = false; let mut running_steps = HashSet::new(); - // Older test fixtures omit the `status` column; degrade cleanly when absent. - if let Ok(mut active_stmt) = connection + let mut active = connection .prepare(&format!( "SELECT idx, status FROM steps WHERE status IN ({STEP_STATUS_RUNNING}, {STEP_STATUS_GENERATING})" )) .await - && let Ok(mut active_rows) = active_stmt.query(()).await - { - while let Ok(Some(row)) = active_rows.next().await { - if let (Ok(Value::Integer(index)), Ok(Value::Integer(status))) = - (row.get_value(0), row.get_value(1)) - { - if status == STEP_STATUS_GENERATING { - has_generating_step = true; - } else if status == STEP_STATUS_RUNNING { - running_steps.insert(index); - } + .map_err(failed)?; + let mut active_rows = active.query(()).await.map_err(failed)?; + while let Some(row) = active_rows.next().await.map_err(failed)? { + match (row.get_value(0), row.get_value(1)) { + (Ok(Value::Integer(_)), Ok(Value::Integer(STEP_STATUS_GENERATING))) => { + has_generating_step = true; + } + (Ok(Value::Integer(index)), Ok(Value::Integer(_))) => { + running_steps.insert(index); } + other => return Err(format!("an active step row read as {other:?}")), } } Ok(Some(RecordState { @@ -421,7 +419,7 @@ mod tests { connection .execute( "CREATE TABLE steps (idx integer, step_type integer NOT NULL DEFAULT 0, \ - PRIMARY KEY (idx))", + status integer NOT NULL DEFAULT 3, PRIMARY KEY (idx))", (), ) .await diff --git a/crates/agent/src/antigravity/subagents.rs b/crates/agent/src/antigravity/subagents.rs index d33dcef4f..e6db2d0b0 100644 --- a/crates/agent/src/antigravity/subagents.rs +++ b/crates/agent/src/antigravity/subagents.rs @@ -713,9 +713,6 @@ impl ChildTailer { } if step.status == "DONE" && !has_new_tools { while let Some(tool) = self.pending_tools.pop_front() { - if matches!(tool.kind, PendingChildToolKind::NestedSubagent(_)) { - continue; - } let content = tool.content(ItemStatus::Completed, None, Vec::new()); events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); } @@ -729,18 +726,27 @@ impl ChildTailer { .content .filter(|c| !c.trim().is_empty()) .or_else(|| step.error.filter(|e| !e.trim().is_empty())); - if let PendingChildToolKind::NestedSubagent(spawn) = tool.kind { - if step.status == "ERROR" { - let failed = PendingChildTool { - id: tool.id.clone(), - kind: PendingChildToolKind::NestedSubagent(spawn), + if let PendingChildToolKind::NestedSubagent(spawn) = &tool.kind { + let ack = (step.status != "ERROR") + .then(|| output.as_deref().and_then(parse_spawn_ack_text)) + .flatten(); + if let Some(ack) = ack { + self.discovered_nested_spawns.push(NestedSpawnBinding { + spawn: spawn.clone(), + ack, + }); + } else { + // A spawn that failed, or whose child cannot be + // named, has no transcript to follow; left open it + // would hold its lead's process alive. + let status = if step.status == "ERROR" { + ItemStatus::Failed + } else { + ItemStatus::Completed }; - let content = failed.content(ItemStatus::Failed, output, Vec::new()); + let content = tool.content(status, output, Vec::new()); events .push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); - } else if let Some(ack) = output.as_deref().and_then(parse_spawn_ack_text) { - self.discovered_nested_spawns - .push(NestedSpawnBinding { spawn, ack }); } return events; } @@ -872,9 +878,6 @@ impl ChildTailer { fn finish_open_tools_interrupted(&mut self) -> Vec { let mut events = Vec::new(); while let Some(tool) = self.pending_tools.pop_front() { - if matches!(tool.kind, PendingChildToolKind::NestedSubagent(_)) { - continue; - } let content = tool.content(ItemStatus::Interrupted, None, Vec::new()); events.push(AgentEvent::ItemCompleted(self.child_item(tool.id, content))); } diff --git a/crates/ui/src/chat/timeline/render.rs b/crates/ui/src/chat/timeline/render.rs index 4e1461444..ffd30d12c 100644 --- a/crates/ui/src/chat/timeline/render.rs +++ b/crates/ui/src/chat/timeline/render.rs @@ -1293,10 +1293,9 @@ impl TimelineView { ) }); }); - let default_collapsed = request.is_none() && self.plan_default_collapsed(cx); - let toggle_key = format!("plan-expand:{}", entry.id); - let toggled = self.expanded.contains(&toggle_key); - let expanded = if default_collapsed { toggled } else { !toggled }; + // A plan opens expanded; the key marks one the user collapsed. + let toggle_key = format!("plan-collapsed:{}", entry.id); + let expanded = !self.expanded.contains(&toggle_key); let copy_key = format!("plan:{}", entry.id); let copied = self.copied.is(©_key); components::plan::plan_block( @@ -1328,33 +1327,6 @@ impl TimelineView { ) } - /// Antigravity Orchestrator emits frequent internal plan handoffs between - /// its planning and execution models, so collapse its plan cards by default - /// unless a card awaits user approval. - fn plan_default_collapsed(&self, cx: &App) -> bool { - let store = self.workspace_store.read(cx); - let Some(session_id) = self.session_id.as_deref() else { - return false; - }; - let status = store.session_status_for(Some(session_id), cx); - let meta = store.thread_meta(session_id); - let provider = status - .map(|status| status.provider) - .or_else(|| meta.map(|meta| meta.provider)); - if provider != Some(agent::ProviderKind::Antigravity) { - return false; - } - let model = status - .and_then(|status| { - status - .running_model - .as_deref() - .or(status.requested_model.as_deref()) - }) - .or_else(|| meta.and_then(|meta| meta.model.as_deref())); - model.is_some_and(|model| model.to_ascii_lowercase().contains("orchestrator")) - } - pub(in crate::chat) fn sync_deciding_plan(&mut self, cx: &mut Context) { let deciding = self .workspace_store diff --git a/crates/ui/src/chat/timeline/render/tests.rs b/crates/ui/src/chat/timeline/render/tests.rs index 6ea46a366..d270c08b9 100644 --- a/crates/ui/src/chat/timeline/render/tests.rs +++ b/crates/ui/src/chat/timeline/render/tests.rs @@ -1311,83 +1311,52 @@ fn a_rewind_divider_offers_what_its_harness_keeps(cx: &mut TestAppContext) { } #[gpui::test] -fn plan_card_collapses_on_click_and_defaults_collapsed_for_antigravity_orchestrator( - cx: &mut TestAppContext, -) { +fn a_plan_card_collapses_and_expands_from_its_header(cx: &mut TestAppContext) { use gpui::{Modifiers, VisualTestContext, px, size}; - let make_timeline = || { - let mut timeline = Timeline::default(); - timeline.turns = vec![TurnMeta::default()]; - timeline.entries.extend([ - entry("user-0", user_item("Run the roadmap")), - entry( - "plan-0", - EntryContent::Item(ItemContent::Plan { - markdown: "# Implementation Plan\n\n1. First step\n2. Second step\n3. Third step\n4. Fourth step\n5. Fifth step" - .into(), - }), - ), - ]); - timeline - }; - - // Non-orchestrator threads default to expanded and collapse on header click. - { - let timeline = make_timeline(); - let thread = ScriptedThread::new(cx, log_of(&timeline), 0, false); - cx.update(|cx| cx.set_reduce_motion(true)); - let (_view, cx) = thread.open(cx); - let cx: &mut VisualTestContext = cx; - cx.simulate_resize(size(px(900.), px(900.))); - thread.deliver(cx); - draw_settled(cx); - - let expanded = cx - .debug_bounds("plan-card-plan-0") - .expect("plan card renders expanded by default"); - let toggle = cx - .debug_bounds("plan-toggle-plan-0") - .expect("plan toggle renders"); - cx.simulate_click(toggle.center(), Modifiers::default()); - draw_settled(cx); - let collapsed = cx - .debug_bounds("plan-card-plan-0") - .expect("plan card stays visible when collapsed"); - assert!( - collapsed.size.height < expanded.size.height, - "clicking plan header collapses the card ({expanded:?} -> {collapsed:?})" - ); - } + let mut timeline = Timeline::default(); + timeline.turns = vec![TurnMeta::default()]; + timeline.entries.extend([ + entry("user-0", user_item("Run the roadmap")), + entry( + "plan-0", + EntryContent::Item(ItemContent::Plan { + markdown: "# Implementation Plan\n\n1. First step\n2. Second step\n3. Third step\n4. Fourth step\n5. Fifth step" + .into(), + }), + ), + ]); + let thread = ScriptedThread::new(cx, log_of(&timeline), 0, false); + cx.update(|cx| cx.set_reduce_motion(true)); + let (_view, cx) = thread.open(cx); + let cx: &mut VisualTestContext = cx; + cx.simulate_resize(size(px(900.), px(900.))); + thread.deliver(cx); + draw_settled(cx); - // Antigravity Orchestrator defaults to collapsed and expands on header click. - { - let timeline = make_timeline(); - let mut thread = ScriptedThread::new(cx, log_of(&timeline), 0, false); - thread.status.provider = agent::ProviderKind::Antigravity; - thread.status.requested_model = Some("gemini-pro-orchestrator-neon".into()); - thread.set_running(false); - cx.update(|cx| cx.set_reduce_motion(true)); - let (_view, cx) = thread.open(cx); - let cx: &mut VisualTestContext = cx; - cx.simulate_resize(size(px(900.), px(900.))); - thread.deliver(cx); - draw_settled(cx); + let expanded = cx + .debug_bounds("plan-card-plan-0") + .expect("plan card renders expanded"); + let toggle = cx + .debug_bounds("plan-toggle-plan-0") + .expect("plan toggle renders"); + cx.simulate_click(toggle.center(), Modifiers::default()); + draw_settled(cx); + let collapsed = cx + .debug_bounds("plan-card-plan-0") + .expect("plan card stays visible when collapsed"); + assert!( + collapsed.size.height < expanded.size.height, + "clicking the plan header collapses the card ({expanded:?} -> {collapsed:?})" + ); - let collapsed = cx - .debug_bounds("plan-card-plan-0") - .expect("orchestrator plan card renders collapsed by default"); - let toggle = cx - .debug_bounds("plan-toggle-plan-0") - .expect("orchestrator plan toggle renders"); - cx.simulate_click(toggle.center(), Modifiers::default()); - draw_settled(cx); - let expanded = cx - .debug_bounds("plan-card-plan-0") - .expect("orchestrator plan card expands on click"); - assert!( - expanded.size.height > collapsed.size.height, - "clicking collapsed orchestrator plan header expands the card ({collapsed:?} -> {expanded:?})" - ); - } + let toggle = cx + .debug_bounds("plan-toggle-plan-0") + .expect("plan toggle renders while collapsed"); + cx.simulate_click(toggle.center(), Modifiers::default()); + draw_settled(cx); + let reopened = cx + .debug_bounds("plan-card-plan-0") + .expect("plan card renders after expanding"); + assert_eq!(reopened.size.height, expanded.size.height); } From e0c4b49a9ed39b1490fcbdb0e9483e253634a699 Mon Sep 17 00:00:00 2001 From: Tryanks Date: Sun, 6 Dec 2026 01:19:18 +0800 Subject: [PATCH 3/3] Antigravity test: build the worktree URI from a real platform path file:///tmp/wt-two names no file path on Windows, so the ack carried no worktree and no SessionMoved was announced there. The test now uses a directory under its scratch dir, which every platform can round-trip. --- crates/agent/src/antigravity/subagents.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/agent/src/antigravity/subagents.rs b/crates/agent/src/antigravity/subagents.rs index e6db2d0b0..b93a843c1 100644 --- a/crates/agent/src/antigravity/subagents.rs +++ b/crates/agent/src/antigravity/subagents.rs @@ -2327,8 +2327,13 @@ mod tests { model: None, }); - let ack_text = "Created the following subagent:\n{\n \"conversationId\": \"child-two\",\n \"workspaceUris\": [\"file:///tmp/wt-two\"]\n}\nThe subagent will send you a message."; - let ack = parse_spawn_ack(None, Some(&Value::String(ack_text.into()))).unwrap(); + let worktree = scratch.0.join("wt-two"); + let worktree_uri = url::Url::from_file_path(&worktree).unwrap().to_string(); + let ack_text = format!( + "Created the following subagent:\n{}\nThe subagent will send you a message.", + json!({"conversationId": "child-two", "workspaceUris": [worktree_uri]}) + ); + let ack = parse_spawn_ack(None, Some(&Value::String(ack_text))).unwrap(); let bound = watcher.on_spawn_bound("call_2", ack); assert!(matches!( bound.as_slice(), @@ -2336,7 +2341,7 @@ mod tests { from, to, parent_item_id: Some(parent), - }] if from == Path::new("/repo") && to == Path::new("/tmp/wt-two") && parent == "call_2" + }] if from == Path::new("/repo") && *to == worktree && parent == "call_2" )); // Child spawns a grandchild and yields waiting for it. @@ -2362,7 +2367,10 @@ mod tests { "step_index": 2, "type": "GENERIC", "status": "DONE", - "content": "Created the following subagent:\n{\n \"conversationId\": \"grandchild-1\",\n \"workspaceUris\": [\"file:///tmp/wt-two\"]\n}" + "content": format!( + "Created the following subagent:\n{}", + json!({"conversationId": "grandchild-1", "workspaceUris": [worktree_uri]}) + ) }), ); scratch.append_transcript(