From 9d3d3b68e3185bfc2499d558707fbdfe0d557769 Mon Sep 17 00:00:00 2001 From: axb Date: Tue, 30 Jun 2026 18:57:28 +0800 Subject: [PATCH] fix(wework): isolate codex subagent stream state --- executor/src/agents/codex.rs | 216 ++++- .../src/runtime_work/codex_notifications.rs | 118 ++- executor/src/runtime_work/codex_rollout.rs | 92 ++ executor/src/runtime_work/events.rs | 912 +++++++++++++++++- executor/src/runtime_work/handler.rs | 58 +- .../runtime_work/runtime_handle_messages.rs | 514 +++++++++- executor/src/runtime_work/transcript.rs | 147 +++ executor/tests/process_manager_contract.rs | 6 +- .../layout/DesktopWorkbenchMain.tsx | 12 +- .../layout/MobileWorkbenchLayout.tsx | 6 + .../layout/SubagentStatusIndicator.test.tsx | 39 + .../layout/SubagentStatusIndicator.tsx | 119 +++ .../layout/useWorkbenchPaneSession.ts | 98 +- .../features/workbench/runtimePaneMessages.ts | 18 +- wework/src/i18n/locales/en/common.json | 6 + wework/src/i18n/locales/zh-CN/common.json | 6 + wework/src/stream/chatStream.ts | 2 + wework/src/stream/responseApiStream.test.ts | 41 + wework/src/stream/responseApiStream.ts | 26 + wework/src/types/api.ts | 15 + wework/src/types/workbench.ts | 12 + 21 files changed, 2439 insertions(+), 24 deletions(-) create mode 100644 wework/src/components/layout/SubagentStatusIndicator.test.tsx create mode 100644 wework/src/components/layout/SubagentStatusIndicator.tsx create mode 100644 wework/src/stream/responseApiStream.test.ts diff --git a/executor/src/agents/codex.rs b/executor/src/agents/codex.rs index 1c2642dac33..9410044ad58 100644 --- a/executor/src/agents/codex.rs +++ b/executor/src/agents/codex.rs @@ -339,6 +339,7 @@ pub async fn run_codex_app_server_turn( .and_then(Value::as_str) .ok_or_else(|| format!("codex app-server {thread_operation} did not return thread.id"))? .to_owned(); + state.set_root_thread_id(thread_id.clone()); thread_fields.push(("thread_id", thread_id.clone())); log_executor_event("codex thread request finished", &thread_fields); if let Some(sender) = ¬ifications { @@ -590,27 +591,55 @@ struct CodexRunState { final_text: String, saw_delta: bool, agent_message_phases: CodexAgentMessagePhaseTracker, + root_thread_id: Option, } impl CodexRunState { + fn set_root_thread_id(&mut self, thread_id: impl Into) { + self.root_thread_id = Some(thread_id.into()); + } + fn handle_message(&mut self, message: &Value) -> Option { match message.get("method").and_then(Value::as_str) { + Some("thread/started") => { + if self.root_thread_id.is_none() { + if let Some(thread_id) = stream_thread_id(message_params(message)) { + self.root_thread_id = Some(thread_id); + } + } + None + } Some("item/started") => { + if self.is_subagent_message(message_params(message)) { + return None; + } self.agent_message_phases .observe_item(message_params(message)); None } Some("item/agentMessage/delta") => { + if self.is_subagent_message(message_params(message)) { + return None; + } self.append_delta(message_params(message)); None } Some("item/completed") => { let params = message_params(message); + if self.is_subagent_message(params) { + return None; + } self.append_completed_message(params); self.agent_message_phases.forget_item(params); None } - Some("turn/completed") => Some(self.completed(message_params(message))), + Some("turn/completed") + if !self.is_subagent_message(message_params(message)) + && is_root_codex_turn_event(message_params(message)) => + { + Some(self.completed(message_params(message))) + } + Some("turn/completed") => None, Some("error") => { let params = message_params(message); log_codex_run_state_error(params); @@ -622,6 +651,18 @@ impl CodexRunState { } } + fn is_subagent_message(&self, params: &Value) -> bool { + codex_agent_path(params) + .or_else(|| params.get("item").and_then(codex_agent_path)) + .is_some_and(|agent_path| agent_path != "/root") + || self + .root_thread_id + .as_deref() + .is_some_and(|root_thread_id| { + stream_thread_id(params).is_some_and(|thread_id| thread_id != root_thread_id) + }) + } + fn append_delta(&mut self, params: &Value) { let text = params.get("delta").and_then(Value::as_str).unwrap_or(""); let phase = self.agent_message_phases.phase_for_delta(params); @@ -737,6 +778,39 @@ impl CodexRunState { } } +fn is_root_codex_turn_event(params: &Value) -> bool { + let turn = params.get("turn").unwrap_or(params); + codex_agent_path(turn) + .or_else(|| codex_agent_path(params)) + .map_or(true, |agent_path| agent_path == "/root") +} + +fn stream_thread_id(value: &Value) -> Option { + value + .get("threadId") + .or_else(|| value.get("thread_id")) + .and_then(Value::as_str) + .or_else(|| { + value + .get("thread") + .and_then(|thread| thread.get("id")) + .and_then(Value::as_str) + }) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +fn codex_agent_path(value: &Value) -> Option { + value + .get("agent_path") + .or_else(|| value.get("agentPath")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + fn log_codex_run_state_text( source: &str, action: &str, @@ -2271,4 +2345,144 @@ mod tests { } ); } + + #[test] + fn codex_run_state_ignores_subagent_turn_completion() { + let mut state = CodexRunState::default(); + + assert!(state + .handle_message(&json!({ + "method": "item/agentMessage/delta", + "params": { + "delta": "Still working" + } + })) + .is_none()); + assert!(state + .handle_message(&json!({ + "method": "turn/completed", + "params": { + "turn": { + "status": "completed", + "agent_path": "/root/worker" + } + } + })) + .is_none()); + + let outcome = state + .handle_message(&json!({ + "method": "turn/completed", + "params": { + "turn": { + "status": "completed", + "agent_path": "/root" + } + } + })) + .expect("root turn completion should produce an outcome"); + + assert_eq!( + outcome, + ExecutionOutcome::Completed { + content: "Still working".to_owned() + } + ); + } + + #[test] + fn codex_run_state_ignores_cross_thread_final_deltas() { + let mut state = CodexRunState::default(); + state.set_root_thread_id("root-thread"); + + assert!(state + .handle_message(&json!({ + "method": "item/agentMessage/delta", + "params": { + "threadId": "child-thread", + "turnId": "child-turn", + "itemId": "msg-child", + "delta": "child" + } + })) + .is_none()); + assert!(state + .handle_message(&json!({ + "method": "item/agentMessage/delta", + "params": { + "threadId": "root-thread", + "turnId": "root-turn", + "itemId": "msg-root", + "delta": "root" + } + })) + .is_none()); + + let outcome = state + .handle_message(&json!({ + "method": "turn/completed", + "params": { + "threadId": "root-thread", + "turn": { + "status": "completed" + } + } + })) + .expect("root turn completion should produce an outcome"); + + assert_eq!( + outcome, + ExecutionOutcome::Completed { + content: "root".to_owned() + } + ); + } + + #[test] + fn codex_run_state_ignores_cross_thread_turn_completion() { + let mut state = CodexRunState::default(); + state.set_root_thread_id("root-thread"); + + assert!(state + .handle_message(&json!({ + "method": "item/agentMessage/delta", + "params": { + "threadId": "root-thread", + "turnId": "root-turn", + "itemId": "msg-root", + "delta": "root" + } + })) + .is_none()); + assert!(state + .handle_message(&json!({ + "method": "turn/completed", + "params": { + "threadId": "child-thread", + "turn": { + "status": "completed" + } + } + })) + .is_none()); + + let outcome = state + .handle_message(&json!({ + "method": "turn/completed", + "params": { + "threadId": "root-thread", + "turn": { + "status": "completed" + } + } + })) + .expect("root turn completion should produce an outcome"); + + assert_eq!( + outcome, + ExecutionOutcome::Completed { + content: "root".to_owned() + } + ); + } } diff --git a/executor/src/runtime_work/codex_notifications.rs b/executor/src/runtime_work/codex_notifications.rs index a8ceb71f674..b5113d90e58 100644 --- a/executor/src/runtime_work/codex_notifications.rs +++ b/executor/src/runtime_work/codex_notifications.rs @@ -16,9 +16,32 @@ pub(crate) struct CodexNotification<'a> { pub(crate) fn codex_notification(message: &Value) -> CodexNotification<'_> { if let Some(method) = message.get("method").and_then(Value::as_str) { + let params = message.get("params").unwrap_or(message); + if matches!(method, "item/started" | "item/completed") + && notification_item_type(params) == "subagentactivity" + { + return CodexNotification { + method: "subagent/activity".to_owned(), + params, + }; + } + if matches!(method, "item/started" | "item/completed") + && notification_item_type(params) == "collabagenttoolcall" + { + return CodexNotification { + method: "collab-agent/activity".to_owned(), + params, + }; + } + if method == "turn/completed" && !is_root_codex_turn_event(params) { + return CodexNotification { + method: "subagent/activity".to_owned(), + params, + }; + } return CodexNotification { method: method.to_owned(), - params: message.get("params").unwrap_or(message), + params, }; } @@ -54,6 +77,12 @@ fn wrapped_item_method(wrapper_type: &str, payload_type: &str) -> Option<&'stati ("eventmsg", "agentmessage") | ("responseitem", "message") => { Some("item/agentMessage/delta") } + ("eventmsg", "subagentactivity") | ("responseitem", "subagentactivity") => { + Some("subagent/activity") + } + ("eventmsg", "collabagenttoolcall") | ("responseitem", "collabagenttoolcall") => { + Some("collab-agent/activity") + } ("responseitem", "reasoning") => Some("item/reasoningSummary/delta"), ("responseitem", payload_type) if is_codex_tool_item_type(payload_type) => { Some("item/started") @@ -78,6 +107,24 @@ fn wrapped_item_method(wrapper_type: &str, payload_type: &str) -> Option<&'stati } } +fn is_root_codex_turn_event(params: &Value) -> bool { + codex_agent_path(params) + .or_else(|| params.get("turn").and_then(codex_agent_path)) + .map_or(true, |agent_path| agent_path == "/root") +} + +fn codex_agent_path(value: &Value) -> Option { + super::util::string_field(value, "agent_path") + .or_else(|| super::util::string_field(value, "agentPath")) +} + +fn notification_item_type(params: &Value) -> String { + params + .get("item") + .map(super::util::item_type) + .unwrap_or_else(|| super::util::item_type(params)) +} + fn runtime_work_debug_enabled() -> bool { std::env::var("WEGENT_RUNTIME_WORK_DEBUG") .ok() @@ -173,4 +220,73 @@ mod tests { let notification = codex_notification(&message); assert_eq!(notification.method, "item/completed"); } + + #[test] + fn maps_codex_subagent_activity_to_stream_method() { + let message = json!({ + "type": "event_msg", + "payload": { + "type": "sub_agent_activity", + "agent_path": "/root/worker", + "kind": "started" + } + }); + let notification = codex_notification(&message); + assert_eq!(notification.method, "subagent/activity"); + assert_eq!(notification.params["agent_path"], "/root/worker"); + } + + #[test] + fn maps_child_turn_completion_to_subagent_activity() { + let message = json!({ + "method": "turn/completed", + "params": { + "turn": { + "agent_path": "/root/worker" + } + } + }); + let notification = codex_notification(&message); + assert_eq!(notification.method, "subagent/activity"); + } + + #[test] + fn maps_explicit_subagent_activity_item_to_stream_method() { + let message = json!({ + "method": "item/completed", + "params": { + "item": { + "type": "subAgentActivity", + "agentPath": "/root/worker", + "agentThreadId": "thread-worker", + "kind": "interacted" + } + } + }); + let notification = codex_notification(&message); + assert_eq!(notification.method, "subagent/activity"); + assert_eq!(notification.params["item"]["agentPath"], "/root/worker"); + } + + #[test] + fn maps_explicit_collab_agent_tool_call_to_stream_method() { + let message = json!({ + "method": "item/completed", + "params": { + "item": { + "type": "collabAgentToolCall", + "tool": "spawnAgent", + "receiverThreadIds": ["thread-worker"], + "agentsStates": { + "thread-worker": { + "status": "pendingInit", + "message": null + } + } + } + } + }); + let notification = codex_notification(&message); + assert_eq!(notification.method, "collab-agent/activity"); + } } diff --git a/executor/src/runtime_work/codex_rollout.rs b/executor/src/runtime_work/codex_rollout.rs index 179878a604e..6c5087fc3e7 100644 --- a/executor/src/runtime_work/codex_rollout.rs +++ b/executor/src/runtime_work/codex_rollout.rs @@ -282,6 +282,9 @@ fn apply_rollout_item_to_turns( item: Value, fallback_started_at: i64, ) { + if !is_root_turn_marker(&item) { + return; + } if is_turn_start_item(&item) { let index = turns.len(); turns.push(new_rollout_turn( @@ -503,6 +506,7 @@ fn is_turn_start_item(item: &Value) -> bool { codex_payload_type(item) .as_deref() .is_some_and(|payload_type| matches!(payload_type, "taskstarted")) + && is_root_turn_marker(item) } fn is_turn_completion_item(item: &Value) -> bool { @@ -514,6 +518,18 @@ fn is_turn_completion_item(item: &Value) -> bool { "taskcomplete" | "turncomplete" | "turncompleted" | "turnaborted" ) }) + && is_root_turn_marker(item) +} + +fn is_root_turn_marker(item: &Value) -> bool { + let payload = codex_wrapped_item_payload(item).unwrap_or(item); + codex_agent_path(payload) + .or_else(|| codex_agent_path(item)) + .map_or(true, |agent_path| agent_path == "/root") +} + +fn codex_agent_path(value: &Value) -> Option { + string_field(value, "agent_path").or_else(|| string_field(value, "agentPath")) } fn rollout_completion_status(item: &Value) -> String { @@ -860,6 +876,82 @@ mod tests { let _ = fs::remove_file(path); } + #[test] + fn ignores_subagent_turn_completion_for_root_rollout_status() { + let path = temp_rollout_path("subagent-complete"); + fs::write( + &path, + [ + json!({"type":"event_msg","payload":{"type":"task_started","turn_id":"root-turn"}}) + .to_string(), + json!({"type":"response_item","payload":{"type":"function_call","call_id":"call-1","name":"spawn_agent"}}) + .to_string(), + json!({"type":"event_msg","payload":{"type":"task_complete","turn_id":"child-turn","agent_path":"/root/worker"}}) + .to_string(), + ] + .join("\n"), + ) + .unwrap(); + + let thread = thread_with_path(&path); + let hydrated = thread_with_rollout_turns(&thread).expect("rollout should hydrate thread"); + + assert_eq!(hydrated["turns"][0]["status"], "running"); + let _ = fs::remove_file(path); + } + + #[test] + fn ignores_subagent_rollout_message_items() { + let path = temp_rollout_path("subagent-message"); + fs::write( + &path, + [ + json!({"type":"event_msg","payload":{"type":"task_started","turn_id":"root-turn","agent_path":"/root"}}) + .to_string(), + json!({"type":"response_item","payload":{"type":"message","role":"assistant","agent_path":"/root/worker","content":[{"type":"output_text","text":"child"}]}}) + .to_string(), + json!({"type":"response_item","payload":{"type":"message","role":"assistant","agent_path":"/root","content":[{"type":"output_text","text":"root"}]}}) + .to_string(), + ] + .join("\n"), + ) + .unwrap(); + + let thread = thread_with_path(&path); + let hydrated = thread_with_rollout_turns(&thread).expect("rollout should hydrate thread"); + let items = hydrated["turns"][0]["items"] + .as_array() + .expect("items should exist"); + + assert_eq!(items.len(), 2); + assert_eq!(items[1]["payload"]["content"][0]["text"], "root"); + let _ = fs::remove_file(path); + } + + #[test] + fn running_status_ignores_subagent_turn_completion_tail() { + let path = temp_rollout_path("running-status-subagent-complete"); + fs::write( + &path, + [ + json!({"type":"event_msg","payload":{"type":"task_started","turn_id":"root-turn"}}) + .to_string(), + json!({"type":"response_item","payload":{"type":"function_call","call_id":"call-1","name":"spawn_agent"}}) + .to_string(), + json!({"type":"event_msg","payload":{"type":"task_complete","turn_id":"child-turn","agent_path":"/root/worker"}}) + .to_string(), + ] + .join("\n"), + ) + .unwrap(); + + let thread = thread_with_path(&path); + let state = thread_with_rollout_running_status(&thread); + + assert_eq!(state["status"], "running"); + let _ = fs::remove_file(path); + } + #[test] fn append_rollout_turns_extends_cached_running_turn() { let path = temp_rollout_path("append-running"); diff --git a/executor/src/runtime_work/events.rs b/executor/src/runtime_work/events.rs index 46669668c35..bbd21fbb442 100644 --- a/executor/src/runtime_work/events.rs +++ b/executor/src/runtime_work/events.rs @@ -2,11 +2,15 @@ // // SPDX-License-Identifier: Apache-2.0 -use serde_json::{json, Value}; +use std::collections::BTreeSet; + +use serde_json::{json, Map, Value}; use tokio::sync::broadcast; use crate::{ - codex_phase::{codex_phase_is_process, codex_phase_name, CodexAgentMessagePhaseTracker}, + codex_phase::{ + codex_item_id, codex_phase_is_process, codex_phase_name, CodexAgentMessagePhaseTracker, + }, logging::log_executor_event, protocol::ExecutionRequest, }; @@ -71,6 +75,8 @@ fn map_codex_notification( #[derive(Default)] pub(crate) struct CodexNotificationEventMapper { agent_message_phases: CodexAgentMessagePhaseTracker, + subagent_item_ids: BTreeSet, + root_thread_id: Option, process_text: Option, process_text_count: usize, } @@ -92,6 +98,9 @@ impl CodexNotificationEventMapper { let notification = codex_notification(&message); match notification.method.as_str() { "item/agentMessage/delta" => { + if self.is_subagent_delta(notification.params) { + return; + } let phase = self .agent_message_phases .phase_for_delta(notification.params); @@ -129,6 +138,9 @@ impl CodexNotificationEventMapper { } } "item/reasoning/delta" | "item/reasoningSummary/delta" => { + if self.is_subagent_delta(notification.params) { + return; + } emit_reasoning_delta( event_tx, device_id, @@ -138,6 +150,11 @@ impl CodexNotificationEventMapper { ); } "item/started" => { + self.observe_root_thread(notification.params); + if self.is_subagent_delta(notification.params) { + self.remember_subagent_item(notification.params); + return; + } self.agent_message_phases.observe_item(notification.params); self.reset_process_text(); emit_tool_start( @@ -149,6 +166,12 @@ impl CodexNotificationEventMapper { ); } "item/completed" => { + self.observe_root_thread(notification.params); + if self.is_subagent_delta(notification.params) { + self.forget_subagent_item(notification.params); + self.agent_message_phases.forget_item(notification.params); + return; + } emit_tool_done( event_tx, device_id, @@ -158,6 +181,27 @@ impl CodexNotificationEventMapper { ); self.agent_message_phases.forget_item(notification.params); } + "subagent/activity" => { + emit_subagent_activity( + event_tx, + device_id, + local_task_id, + request, + notification.params, + ); + } + "collab-agent/activity" => { + emit_collab_agent_activity( + event_tx, + device_id, + local_task_id, + request, + notification.params, + ); + } + "thread/started" => { + self.observe_root_thread(notification.params); + } _ => { debug_ignored_codex_notification( &message, @@ -229,6 +273,101 @@ impl CodexNotificationEventMapper { fn reset_process_text(&mut self) { self.process_text = None; } + + fn remember_subagent_item(&mut self, params: &Value) { + if let Some(item_id) = notification_item_id(params) { + self.subagent_item_ids.insert(item_id); + } + } + + fn forget_subagent_item(&mut self, params: &Value) { + if let Some(item_id) = notification_item_id(params) { + self.subagent_item_ids.remove(&item_id); + } + } + + fn is_subagent_delta(&self, params: &Value) -> bool { + is_non_root_codex_stream_event(params) + || self.is_subagent_thread(params) + || notification_item_id(params) + .is_some_and(|item_id| self.subagent_item_ids.contains(&item_id)) + } + + fn observe_root_thread(&mut self, params: &Value) { + if self.root_thread_id.is_none() && is_explicit_root_codex_stream_event(params) { + self.root_thread_id = stream_thread_id(params); + } + } + + fn is_subagent_thread(&self, params: &Value) -> bool { + let Some(root_thread_id) = self.root_thread_id.as_deref() else { + return false; + }; + stream_thread_id(params).is_some_and(|thread_id| thread_id != root_thread_id) + } +} + +fn notification_item_id(params: &Value) -> Option { + params + .get("item") + .and_then(codex_item_id) + .or_else(|| string_field(params, "itemId")) + .or_else(|| string_field(params, "item_id")) + .or_else(|| codex_item_id(params)) +} + +fn is_non_root_codex_stream_event(params: &Value) -> bool { + codex_stream_agent_path(params).is_some_and(|agent_path| agent_path != "/root") +} + +fn is_explicit_root_codex_stream_event(params: &Value) -> bool { + params + .get("thread") + .and_then(|thread| string_field(thread, "id")) + .is_some() + || codex_stream_agent_path(params).is_some_and(|agent_path| agent_path == "/root") +} + +fn codex_stream_agent_path(value: &Value) -> Option { + string_field(value, "agent_path") + .or_else(|| string_field(value, "agentPath")) + .or_else(|| { + value.get("item").and_then(|item| { + string_field(item, "agent_path").or_else(|| string_field(item, "agentPath")) + }) + }) + .or_else(|| { + value.get("payload").and_then(|payload| { + string_field(payload, "agent_path").or_else(|| string_field(payload, "agentPath")) + }) + }) + .or_else(|| { + value.get("turn").and_then(|turn| { + string_field(turn, "agent_path").or_else(|| string_field(turn, "agentPath")) + }) + }) +} + +fn stream_thread_id(value: &Value) -> Option { + string_field(value, "threadId") + .or_else(|| string_field(value, "thread_id")) + .or_else(|| { + value.get("item").and_then(|item| { + string_field(item, "threadId").or_else(|| string_field(item, "thread_id")) + }) + }) + .or_else(|| { + value.get("payload").and_then(|payload| { + string_field(payload, "threadId").or_else(|| string_field(payload, "thread_id")) + }) + }) + .or_else(|| { + value.get("thread").and_then(|thread| { + string_field(thread, "id") + .or_else(|| string_field(thread, "threadId")) + .or_else(|| string_field(thread, "thread_id")) + }) + }) } fn log_codex_event_mapper_text( @@ -386,6 +525,351 @@ fn emit_tool_done( } } +fn emit_subagent_activity( + event_tx: &Option>, + device_id: &str, + local_task_id: &str, + request: &ExecutionRequest, + params: &Value, +) { + let Some(agent_path) = subagent_path(params) else { + return; + }; + if agent_path == "/root" { + return; + } + + let kind = subagent_kind(params); + let agent_thread_id = subagent_thread_id(params); + let agent_id = agent_thread_id + .clone() + .unwrap_or_else(|| agent_path.clone()); + let mut data = Map::new(); + data.insert("agent_path".to_owned(), Value::String(agent_path)); + data.insert("agent_id".to_owned(), Value::String(agent_id.clone())); + data.insert( + "agent_thread_id".to_owned(), + agent_thread_id.map(Value::String).unwrap_or(Value::Null), + ); + if let Some(agent_name) = explicit_subagent_name(params) { + data.insert("agent_name".to_owned(), Value::String(agent_name)); + } + data.insert("kind".to_owned(), Value::String(kind.clone())); + data.insert( + "status".to_owned(), + Value::String(subagent_status(&kind).to_owned()), + ); + data.insert( + "occurred_at_ms".to_owned(), + Value::Number(subagent_occurred_at_ms(params).into()), + ); + emit_response_event( + event_tx, + device_id, + "response.subagent.activity", + local_task_id, + request, + Value::Object(data), + ); + emit_subagent_block_update( + event_tx, + device_id, + local_task_id, + request, + &agent_id, + subagent_status(&kind), + ); +} + +fn emit_collab_agent_activity( + event_tx: &Option>, + device_id: &str, + local_task_id: &str, + request: &ExecutionRequest, + params: &Value, +) { + let item = params.get("item").unwrap_or(params); + if item_type_name(item) != "collabagenttoolcall" { + return; + } + + let agent_ids = collab_agent_ids(item); + if agent_ids.is_empty() { + return; + } + + let tool = string_field(item, "tool").unwrap_or_else(|| "collabAgent".to_owned()); + let has_agent_states = item + .get("agentsStates") + .and_then(Value::as_object) + .is_some_and(|states| !states.is_empty()); + if tool == "wait" && !has_agent_states { + return; + } + for agent_thread_id in agent_ids { + let collab_status = collab_agent_state_status(item, &agent_thread_id) + .or_else(|| string_field(item, "status")) + .unwrap_or_else(|| "running".to_owned()); + let status = collab_agent_status(&collab_status); + let mut data = Map::new(); + data.insert( + "agent_path".to_owned(), + Value::String(format!("thread:{agent_thread_id}")), + ); + data.insert( + "agent_id".to_owned(), + Value::String(agent_thread_id.clone()), + ); + data.insert( + "agent_thread_id".to_owned(), + Value::String(agent_thread_id.clone()), + ); + data.insert("kind".to_owned(), Value::String(tool.clone())); + data.insert("status".to_owned(), Value::String(status.to_owned())); + data.insert( + "occurred_at_ms".to_owned(), + Value::Number(subagent_occurred_at_ms(params).into()), + ); + emit_response_event( + event_tx, + device_id, + "response.subagent.activity", + local_task_id, + request, + Value::Object(data), + ); + if tool == "spawnAgent" { + emit_subagent_block_created( + event_tx, + device_id, + local_task_id, + request, + SubagentBlockCreated { + agent_id: &agent_thread_id, + tool: &tool, + status, + timestamp: subagent_occurred_at_ms(params), + }, + ); + } else { + emit_subagent_block_update( + event_tx, + device_id, + local_task_id, + request, + &agent_thread_id, + status, + ); + } + } +} + +struct SubagentBlockCreated<'a> { + agent_id: &'a str, + tool: &'a str, + status: &'a str, + timestamp: i64, +} + +fn emit_subagent_block_created( + event_tx: &Option>, + device_id: &str, + local_task_id: &str, + request: &ExecutionRequest, + block: SubagentBlockCreated<'_>, +) { + emit_response_event( + event_tx, + device_id, + "response.block.created", + local_task_id, + request, + json!({ + "block": { + "id": subagent_block_id(block.agent_id), + "type": "tool", + "tool_use_id": subagent_block_id(block.agent_id), + "tool_name": block.tool, + "tool_input": { + "agent_id": block.agent_id, + "agent_thread_id": block.agent_id, + }, + "status": block.status, + "timestamp": block.timestamp, + } + }), + ); +} + +fn emit_subagent_block_update( + event_tx: &Option>, + device_id: &str, + local_task_id: &str, + request: &ExecutionRequest, + agent_id: &str, + status: &str, +) { + emit_response_event( + event_tx, + device_id, + "response.block.updated", + local_task_id, + request, + json!({ + "block_id": subagent_block_id(agent_id), + "updates": { + "status": status, + } + }), + ); +} + +fn subagent_block_id(agent_id: &str) -> String { + format!("subagent-{agent_id}") +} + +fn subagent_path(params: &Value) -> Option { + string_field(params, "agent_path") + .or_else(|| string_field(params, "agentPath")) + .or_else(|| { + params.get("item").and_then(|item| { + string_field(item, "agent_path").or_else(|| string_field(item, "agentPath")) + }) + }) + .or_else(|| { + params.get("turn").and_then(|turn| { + string_field(turn, "agent_path").or_else(|| string_field(turn, "agentPath")) + }) + }) +} + +fn subagent_kind(params: &Value) -> String { + string_field(params, "kind") + .or_else(|| { + params + .get("item") + .and_then(|item| string_field(item, "kind")) + }) + .or_else(|| { + params.get("turn").and_then(|turn| { + string_field(turn, "kind") + .or_else(|| string_field(turn, "status")) + .or_else(|| string_field(turn, "type")) + }) + }) + .unwrap_or_else(|| "completed".to_owned()) +} + +fn subagent_status(kind: &str) -> &'static str { + match kind.replace('_', "").to_ascii_lowercase().as_str() { + "completed" | "done" | "taskcomplete" => "done", + "interrupted" | "cancelled" | "canceled" => "interrupted", + _ => "running", + } +} + +fn subagent_thread_id(params: &Value) -> Option { + string_field(params, "agent_thread_id") + .or_else(|| string_field(params, "agentThreadId")) + .or_else(|| string_field(params, "thread_id")) + .or_else(|| string_field(params, "threadId")) + .or_else(|| string_field(params, "turn_id")) + .or_else(|| string_field(params, "turnId")) + .or_else(|| { + params.get("item").and_then(|item| { + string_field(item, "agent_thread_id") + .or_else(|| string_field(item, "agentThreadId")) + .or_else(|| string_field(item, "thread_id")) + .or_else(|| string_field(item, "threadId")) + .or_else(|| string_field(item, "turn_id")) + .or_else(|| string_field(item, "turnId")) + }) + }) + .or_else(|| { + params.get("turn").and_then(|turn| { + string_field(turn, "agent_thread_id") + .or_else(|| string_field(turn, "agentThreadId")) + .or_else(|| string_field(turn, "thread_id")) + .or_else(|| string_field(turn, "threadId")) + .or_else(|| string_field(turn, "turn_id")) + .or_else(|| string_field(turn, "turnId")) + }) + }) +} + +fn explicit_subagent_name(params: &Value) -> Option { + string_field(params, "agent_name") + .or_else(|| string_field(params, "agentName")) + .or_else(|| { + params.get("item").and_then(|item| { + string_field(item, "agent_name").or_else(|| string_field(item, "agentName")) + }) + }) +} + +fn subagent_occurred_at_ms(params: &Value) -> i64 { + params + .get("occurred_at_ms") + .or_else(|| params.get("occurredAtMs")) + .or_else(|| params.get("completedAtMs")) + .or_else(|| params.get("startedAtMs")) + .or_else(|| { + params + .get("item") + .and_then(|item| item.get("occurred_at_ms")) + }) + .or_else(|| params.get("item").and_then(|item| item.get("occurredAtMs"))) + .or_else(|| { + params + .get("turn") + .and_then(|turn| turn.get("occurred_at_ms")) + }) + .or_else(|| params.get("turn").and_then(|turn| turn.get("occurredAtMs"))) + .and_then(Value::as_i64) + .unwrap_or_else(now_ms) +} + +fn item_type_name(item: &Value) -> String { + item.get("type") + .and_then(Value::as_str) + .unwrap_or_default() + .replace('_', "") + .to_ascii_lowercase() +} + +fn collab_agent_ids(item: &Value) -> Vec { + let mut ids = Vec::new(); + if let Some(receiver_thread_ids) = item.get("receiverThreadIds").and_then(Value::as_array) { + for thread_id in receiver_thread_ids { + if let Some(thread_id) = thread_id.as_str().filter(|value| !value.trim().is_empty()) { + ids.push(thread_id.to_owned()); + } + } + } + if let Some(agents_states) = item.get("agentsStates").and_then(Value::as_object) { + for thread_id in agents_states.keys() { + if !ids.iter().any(|id| id == thread_id) { + ids.push(thread_id.to_owned()); + } + } + } + ids +} + +fn collab_agent_state_status(item: &Value, agent_thread_id: &str) -> Option { + item.get("agentsStates") + .and_then(|states| states.get(agent_thread_id)) + .and_then(|state| string_field(state, "status")) +} + +fn collab_agent_status(status: &str) -> &'static str { + match status.replace('_', "").to_ascii_lowercase().as_str() { + "completed" | "shutdown" | "done" => "done", + "interrupted" | "errored" | "notfound" | "failed" => "interrupted", + _ => "running", + } +} + #[cfg(test)] mod tests { use serde_json::json; @@ -471,6 +955,20 @@ mod tests { }; let mut mapper = CodexNotificationEventMapper::default(); + mapper.map( + &Some(event_tx.clone()), + "device-1", + "local-1", + &request, + json!({ + "method": "thread/started", + "params": { + "thread": { + "id": "root-thread" + } + } + }), + ); mapper.map( &Some(event_tx.clone()), "device-1", @@ -507,6 +1005,169 @@ mod tests { assert_eq!(event["payload"]["data"]["delta"], "Done."); } + #[test] + fn ignores_subagent_agent_message_deltas() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + let mut mapper = CodexNotificationEventMapper::default(); + + mapper.map( + &Some(event_tx.clone()), + "device-1", + "local-1", + &request, + json!({ + "method": "item/started", + "params": { + "item": { + "id": "msg-child", + "type": "agentMessage", + "phase": "final_answer", + "agent_path": "/root/worker", + "text": "" + } + } + }), + ); + mapper.map( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "method": "item/agentMessage/delta", + "params": { + "itemId": "msg-child", + "delta": "child output" + } + }), + ); + + assert!(event_rx.try_recv().is_err()); + } + + #[test] + fn ignores_cross_thread_agent_message_deltas() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + let mut mapper = CodexNotificationEventMapper::default(); + + mapper.map( + &Some(event_tx.clone()), + "device-1", + "local-1", + &request, + json!({ + "method": "thread/started", + "params": { + "thread": { + "id": "root-thread" + } + } + }), + ); + mapper.map( + &Some(event_tx.clone()), + "device-1", + "local-1", + &request, + json!({ + "method": "item/started", + "params": { + "threadId": "root-thread", + "turnId": "root-turn", + "item": { + "id": "msg-root", + "type": "agentMessage", + "phase": "final_answer", + "text": "" + } + } + }), + ); + mapper.map( + &Some(event_tx.clone()), + "device-1", + "local-1", + &request, + json!({ + "method": "item/started", + "params": { + "threadId": "child-thread", + "turnId": "child-turn", + "item": { + "id": "call-child", + "type": "commandExecution", + "command": "rg child", + "status": "inProgress" + } + } + }), + ); + mapper.map( + &Some(event_tx.clone()), + "device-1", + "local-1", + &request, + json!({ + "method": "item/started", + "params": { + "threadId": "child-thread", + "turnId": "child-turn", + "item": { + "id": "msg-child", + "type": "agentMessage", + "phase": "final_answer", + "text": "" + } + } + }), + ); + mapper.map( + &Some(event_tx.clone()), + "device-1", + "local-1", + &request, + json!({ + "method": "item/agentMessage/delta", + "params": { + "threadId": "child-thread", + "turnId": "child-turn", + "itemId": "msg-child", + "delta": "child" + } + }), + ); + mapper.map( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "method": "item/agentMessage/delta", + "params": { + "threadId": "root-thread", + "turnId": "root-turn", + "itemId": "msg-root", + "delta": "root" + } + }), + ); + + let event = event_rx.try_recv().expect("root event should be emitted"); + assert_eq!(event["event"], "response.output_text.delta"); + assert_eq!(event["payload"]["data"]["delta"], "root"); + assert!(event_rx.try_recv().is_err()); + } + #[test] fn maps_codex_process_text_deltas_to_one_block_stream() { let (event_tx, mut event_rx) = broadcast::channel(4); @@ -610,6 +1271,253 @@ mod tests { assert_eq!(event["payload"]["data"]["delta"], "Done."); } + #[test] + fn emits_codex_subagent_activity_events() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + + map_codex_notification( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "type": "event_msg", + "payload": { + "type": "sub_agent_activity", + "agent_path": "/root/worker", + "agent_thread_id": "thread-worker", + "kind": "started", + "occurred_at_ms": 12345 + } + }), + ); + + let event = event_rx.try_recv().expect("event should be emitted"); + assert_eq!(event["event"], "response.subagent.activity"); + assert_eq!(event["payload"]["data"]["agent_path"], "/root/worker"); + assert_eq!(event["payload"]["data"]["agent_id"], "thread-worker"); + assert!(event["payload"]["data"].get("agent_name").is_none()); + assert_eq!(event["payload"]["data"]["agent_thread_id"], "thread-worker"); + assert_eq!(event["payload"]["data"]["kind"], "started"); + assert_eq!(event["payload"]["data"]["status"], "running"); + assert_eq!(event["payload"]["data"]["occurred_at_ms"], 12345); + } + + #[test] + fn emits_child_turn_completion_as_done_subagent_activity() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + + map_codex_notification( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "method": "turn/completed", + "params": { + "threadId": "thread-worker", + "turn": { + "turn_id": "child-turn", + "agent_path": "/root/worker" + } + } + }), + ); + + let event = event_rx.try_recv().expect("event should be emitted"); + assert_eq!(event["event"], "response.subagent.activity"); + assert_eq!(event["payload"]["data"]["agent_id"], "thread-worker"); + assert_eq!(event["payload"]["data"]["agent_thread_id"], "thread-worker"); + assert_eq!(event["payload"]["data"]["status"], "done"); + assert_eq!(event["payload"]["data"]["kind"], "completed"); + + let update = event_rx.try_recv().expect("block update should be emitted"); + assert_eq!(update["event"], "response.block.updated"); + assert_eq!( + update["payload"]["data"]["block_id"], + "subagent-thread-worker" + ); + assert_eq!(update["payload"]["data"]["updates"]["status"], "done"); + } + + #[test] + fn emits_explicit_subagent_activity_items() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + + map_codex_notification( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "method": "item/completed", + "params": { + "item": { + "type": "subAgentActivity", + "agentPath": "/root/worker", + "agentThreadId": "thread-worker", + "kind": "interacted" + } + } + }), + ); + + let event = event_rx.try_recv().expect("event should be emitted"); + assert_eq!(event["event"], "response.subagent.activity"); + assert_eq!(event["payload"]["data"]["agent_path"], "/root/worker"); + assert_eq!(event["payload"]["data"]["agent_id"], "thread-worker"); + assert_eq!(event["payload"]["data"]["agent_thread_id"], "thread-worker"); + assert_eq!(event["payload"]["data"]["kind"], "interacted"); + assert_eq!(event["payload"]["data"]["status"], "running"); + } + + #[test] + fn emits_collab_agent_tool_call_subagent_status() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + + map_codex_notification( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "method": "item/completed", + "params": { + "completedAtMs": 12345, + "item": { + "type": "collabAgentToolCall", + "tool": "spawnAgent", + "prompt": "你是一个只读代码库分析 subagent。请聚焦 Backend 模块,不要修改文件。", + "receiverThreadIds": ["thread-worker"], + "agentsStates": { + "thread-worker": { + "status": "pendingInit", + "message": null + } + }, + "status": "completed" + } + } + }), + ); + + let event = event_rx.try_recv().expect("event should be emitted"); + assert_eq!(event["event"], "response.subagent.activity"); + assert_eq!( + event["payload"]["data"]["agent_path"], + "thread:thread-worker" + ); + assert_eq!(event["payload"]["data"]["agent_id"], "thread-worker"); + assert_eq!(event["payload"]["data"]["agent_thread_id"], "thread-worker"); + assert!(event["payload"]["data"].get("agent_name").is_none()); + assert_eq!(event["payload"]["data"]["kind"], "spawnAgent"); + assert_eq!(event["payload"]["data"]["status"], "running"); + assert_eq!(event["payload"]["data"]["occurred_at_ms"], 12345); + + let block = event_rx.try_recv().expect("block should be emitted"); + assert_eq!(block["event"], "response.block.created"); + assert_eq!( + block["payload"]["data"]["block"]["id"], + "subagent-thread-worker" + ); + assert_eq!( + block["payload"]["data"]["block"]["tool_use_id"], + "subagent-thread-worker" + ); + assert_eq!(block["payload"]["data"]["block"]["tool_name"], "spawnAgent"); + assert_eq!(block["payload"]["data"]["block"]["status"], "running"); + } + + #[test] + fn emits_explicit_subagent_name_when_field_exists() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + + map_codex_notification( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "method": "item/completed", + "params": { + "item": { + "type": "subAgentActivity", + "agentPath": "/root/worker", + "agentThreadId": "thread-worker", + "agentName": "Frontend reviewer", + "kind": "interacted" + } + } + }), + ); + + let event = event_rx.try_recv().expect("event should be emitted"); + assert_eq!(event["payload"]["data"]["agent_name"], "Frontend reviewer"); + } + + #[test] + fn emits_collab_agent_id_without_inventing_name_from_prompt() { + let (event_tx, mut event_rx) = broadcast::channel(4); + let request = ExecutionRequest { + task_id: 7, + subtask_id: 8, + ..ExecutionRequest::default() + }; + + map_codex_notification( + &Some(event_tx), + "device-1", + "local-1", + &request, + json!({ + "method": "item/completed", + "params": { + "item": { + "type": "collabAgentToolCall", + "tool": "spawnAgent", + "prompt": "在 /repo 分析前端部分,重点是 frontend/ 与 wework/。只读分析。", + "receiverThreadIds": ["thread-worker"], + "agentsStates": { + "thread-worker": { + "status": "running" + } + }, + "status": "completed" + } + } + }), + ); + + let event = event_rx.try_recv().expect("event should be emitted"); + assert_eq!(event["payload"]["data"]["agent_id"], "thread-worker"); + assert!(event["payload"]["data"].get("agent_name").is_none()); + } + #[test] fn maps_codex_commentary_then_tool_then_unphased_final_without_duplication() { let (event_tx, mut event_rx) = broadcast::channel(8); diff --git a/executor/src/runtime_work/handler.rs b/executor/src/runtime_work/handler.rs index 43c0b4696c4..91fbfc17dca 100644 --- a/executor/src/runtime_work/handler.rs +++ b/executor/src/runtime_work/handler.rs @@ -315,6 +315,11 @@ impl RuntimeWorkRpcHandler { .as_ref() .map(|link| merge_cached_messages(cached.messages.clone(), cached_messages(link))) .unwrap_or_else(|| cached.messages.clone()); + let running = transcript_running( + local_link.as_ref(), + running_hint || cached.running, + &messages, + ); log_runtime_transcript_finished(RuntimeTranscriptLog { started_at, local_task_id: &local_task_id, @@ -326,7 +331,7 @@ impl RuntimeWorkRpcHandler { before_cursor: before_cursor.as_deref(), after_cursor: after_cursor.as_deref(), message_count: messages.len(), - running: cached.running, + running, }); return Ok(transcript_response( &local_task_id, @@ -410,7 +415,7 @@ impl RuntimeWorkRpcHandler { ) }) .unwrap_or_else(|| transcript_messages(&transcript_thread, &self.device_id)); - let running = running_hint || messages.iter().any(runtime_message_running); + let running = transcript_running(local_link.as_ref(), running_hint, &messages); let message_count = messages.len(); self.transcript_cache.insert( thread_id.clone(), @@ -1318,7 +1323,7 @@ impl RuntimeWorkRpcHandler { &self.device_id, ) }); - let running = running_hint || messages.iter().any(runtime_message_running); + let running = transcript_running(local_link, running_hint, &messages); Some( CachedTranscript::new( workspace_path.to_owned(), @@ -1825,6 +1830,28 @@ fn runtime_message_running(message: &Value) -> bool { .unwrap_or(false) } +fn transcript_running( + local_link: Option<&RuntimeTaskLink>, + running_hint: bool, + messages: &[Value], +) -> bool { + if local_link.is_some_and(local_task_finished) { + return false; + } + running_hint || messages.iter().any(runtime_message_running) +} + +fn local_task_finished(link: &RuntimeTaskLink) -> bool { + !link.running + && matches!( + link.status + .replace(['_', '-'], "") + .to_ascii_lowercase() + .as_str(), + "done" | "complete" | "completed" | "failed" | "error" | "cancelled" | "canceled" + ) +} + fn transcript_source_signature(thread: &Value) -> Option { string_field(thread, "path").and_then(|path| TranscriptSourceSignature::from_path(&path)) } @@ -2361,6 +2388,31 @@ mod tests { assert_eq!(messages[1]["turnId"], "turn-2"); } + #[test] + fn terminal_local_task_prevents_transcript_running_state() { + let mut link = RuntimeTaskLink::new_pending( + "local-1".to_owned(), + "/tmp/project".to_owned(), + "Task".to_owned(), + ); + link.status = "done".to_owned(); + link.running = false; + let messages = vec![json!({ + "id": "assistant-1", + "role": "assistant", + "status": "streaming", + "blocks": [ + { + "id": "tool-1", + "type": "tool", + "status": "pending" + } + ] + })]; + + assert!(!transcript_running(Some(&link), true, &messages)); + } + #[test] fn incremental_transcript_rejects_changed_rollout_path() { let old_path = std::env::temp_dir().join(format!( diff --git a/executor/src/runtime_work/runtime_handle_messages.rs b/executor/src/runtime_work/runtime_handle_messages.rs index 4c3ea837d4c..17582d82b32 100644 --- a/executor/src/runtime_work/runtime_handle_messages.rs +++ b/executor/src/runtime_work/runtime_handle_messages.rs @@ -2,10 +2,14 @@ // // SPDX-License-Identifier: Apache-2.0 +use std::collections::BTreeSet; + use serde_json::{json, Map, Value}; use crate::{ - codex_phase::{codex_phase_is_process, codex_phase_name, CodexAgentMessagePhaseTracker}, + codex_phase::{ + codex_item_id, codex_phase_is_process, codex_phase_name, CodexAgentMessagePhaseTracker, + }, logging::log_executor_event, protocol::ExecutionRequest, }; @@ -60,6 +64,8 @@ fn cache_codex_notification( #[derive(Default)] pub(crate) struct CodexNotificationCacheMapper { agent_message_phases: CodexAgentMessagePhaseTracker, + subagent_item_ids: BTreeSet, + root_thread_id: Option, } impl CodexNotificationCacheMapper { @@ -74,6 +80,9 @@ impl CodexNotificationCacheMapper { let params = notification.params; match notification.method.as_str() { "item/reasoning/delta" | "item/reasoningSummary/delta" => { + if self.is_subagent_delta(params) { + return; + } if let Some(delta) = string_field(params, "delta") .or_else(|| reasoning_content(params)) .filter(|delta| !delta.is_empty()) @@ -84,11 +93,15 @@ impl CodexNotificationCacheMapper { request, "reasoning", "thinking", + None, delta, ); } } "item/agentMessage/delta" => { + if self.is_subagent_delta(params) { + return; + } if let Some(delta) = agent_text(params).filter(|delta| !delta.is_empty()) { let phase = self.agent_message_phases.phase_for_delta(params); if codex_phase_is_process(phase.as_deref()) { @@ -106,6 +119,7 @@ impl CodexNotificationCacheMapper { request, "assistant_message", "text", + notification_item_id(params), delta, ); } else { @@ -127,12 +141,23 @@ impl CodexNotificationCacheMapper { } } "item/started" => { + self.observe_root_thread(params); + if self.is_subagent_delta(params) { + self.remember_subagent_item(params); + return; + } self.agent_message_phases.observe_item(params); if let Some(block) = tool_block_from_notification(params, "pending") { cache_runtime_assistant_block(store, local_task_id, request, block); } } "item/completed" => { + self.observe_root_thread(params); + if self.is_subagent_delta(params) { + self.forget_subagent_item(params); + self.agent_message_phases.forget_item(params); + return; + } if let Some((block_id, updates)) = tool_update_from_notification(params) { update_runtime_assistant_block( store, @@ -144,11 +169,121 @@ impl CodexNotificationCacheMapper { } self.agent_message_phases.forget_item(params); } - "thread/started" => cache_runtime_thread_id(store, local_task_id, params), - "turn/completed" => complete_runtime_assistant_message(store, local_task_id, request), + "thread/started" => { + self.observe_root_thread(params); + cache_runtime_thread_id(store, local_task_id, params); + } + "turn/completed" if is_root_codex_turn_event(params) => { + complete_runtime_assistant_message(store, local_task_id, request) + } + "turn/completed" => {} _ => debug_ignored_codex_notification(message, ¬ification.method, params), } } + + fn remember_subagent_item(&mut self, params: &Value) { + if let Some(item_id) = notification_item_id(params) { + self.subagent_item_ids.insert(item_id); + } + } + + fn forget_subagent_item(&mut self, params: &Value) { + if let Some(item_id) = notification_item_id(params) { + self.subagent_item_ids.remove(&item_id); + } + } + + fn is_subagent_delta(&self, params: &Value) -> bool { + is_non_root_codex_stream_event(params) + || self.is_subagent_thread(params) + || notification_item_id(params) + .is_some_and(|item_id| self.subagent_item_ids.contains(&item_id)) + } + + fn observe_root_thread(&mut self, params: &Value) { + if self.root_thread_id.is_none() && is_explicit_root_codex_stream_event(params) { + self.root_thread_id = stream_thread_id(params); + } + } + + fn is_subagent_thread(&self, params: &Value) -> bool { + let Some(root_thread_id) = self.root_thread_id.as_deref() else { + return false; + }; + stream_thread_id(params).is_some_and(|thread_id| thread_id != root_thread_id) + } +} + +fn notification_item_id(params: &Value) -> Option { + params + .get("item") + .and_then(codex_item_id) + .or_else(|| string_field(params, "itemId")) + .or_else(|| string_field(params, "item_id")) + .or_else(|| codex_item_id(params)) +} + +fn is_non_root_codex_stream_event(params: &Value) -> bool { + codex_stream_agent_path(params).is_some_and(|agent_path| agent_path != "/root") +} + +fn is_explicit_root_codex_stream_event(params: &Value) -> bool { + params + .get("thread") + .and_then(|thread| string_field(thread, "id")) + .is_some() + || codex_stream_agent_path(params).is_some_and(|agent_path| agent_path == "/root") +} + +fn codex_stream_agent_path(value: &Value) -> Option { + string_field(value, "agent_path") + .or_else(|| string_field(value, "agentPath")) + .or_else(|| { + value.get("item").and_then(|item| { + string_field(item, "agent_path").or_else(|| string_field(item, "agentPath")) + }) + }) + .or_else(|| { + value.get("payload").and_then(|payload| { + string_field(payload, "agent_path").or_else(|| string_field(payload, "agentPath")) + }) + }) + .or_else(|| { + value.get("turn").and_then(|turn| { + string_field(turn, "agent_path").or_else(|| string_field(turn, "agentPath")) + }) + }) +} + +fn stream_thread_id(value: &Value) -> Option { + string_field(value, "threadId") + .or_else(|| string_field(value, "thread_id")) + .or_else(|| { + value.get("item").and_then(|item| { + string_field(item, "threadId").or_else(|| string_field(item, "thread_id")) + }) + }) + .or_else(|| { + value.get("payload").and_then(|payload| { + string_field(payload, "threadId").or_else(|| string_field(payload, "thread_id")) + }) + }) + .or_else(|| { + value.get("thread").and_then(|thread| { + string_field(thread, "id") + .or_else(|| string_field(thread, "threadId")) + .or_else(|| string_field(thread, "thread_id")) + }) + }) +} + +fn is_root_codex_turn_event(params: &Value) -> bool { + let turn = params.get("turn").unwrap_or(params); + string_field(turn, "agent_path") + .or_else(|| string_field(turn, "agentPath")) + .or_else(|| string_field(params, "agent_path")) + .or_else(|| string_field(params, "agentPath")) + .map_or(true, |agent_path| agent_path == "/root") } fn agent_text(params: &Value) -> Option { @@ -289,6 +424,7 @@ fn append_runtime_assistant_process_delta( request: &ExecutionRequest, process_kind: &str, block_type: &str, + process_item_id: Option, delta: String, ) { mutate_cached_assistant_blocks(store, local_task_id, request, |blocks| { @@ -298,6 +434,7 @@ fn append_runtime_assistant_process_delta( request.subtask_id, process_kind, block_type, + process_item_id, delta, ); }); @@ -684,12 +821,17 @@ fn append_process_block_delta( subtask_id: i64, process_kind: &str, block_type: &str, + process_item_id: Option, delta: String, ) { - if let Some(block) = blocks - .last_mut() - .filter(|block| process_block_accepts_delta_with_kind(block, block_type, process_kind)) - { + if let Some(block) = blocks.iter_mut().rev().find(|block| { + process_block_accepts_delta_for_item( + block, + block_type, + process_kind, + process_item_id.as_deref(), + ) + }) { append_block_content_delta(block, delta); return; } @@ -703,6 +845,7 @@ fn append_process_block_delta( "id": format!("{block_type}-{local_task_id}-{subtask_id}-{block_index}"), "type": block_type, "process_kind": process_kind, + "process_item_id": process_item_id, "content": delta, "status": "streaming", "timestamp": now_ms(), @@ -752,13 +895,22 @@ fn process_block_accepts_delta(block: &Value, block_type: &str) -> bool { ) } -fn process_block_accepts_delta_with_kind( +fn process_block_accepts_delta_for_item( block: &Value, block_type: &str, process_kind: &str, + process_item_id: Option<&str>, ) -> bool { - process_block_accepts_delta(block, block_type) - && string_field(block, "process_kind").as_deref() == Some(process_kind) + if string_field(block, "type").as_deref() != Some(block_type) + || string_field(block, "process_kind").as_deref() != Some(process_kind) + { + return false; + } + + match process_item_id { + Some(item_id) => string_field(block, "process_item_id").as_deref() == Some(item_id), + None => process_block_accepts_delta(block, block_type), + } } fn complete_open_process_blocks(blocks: &mut Vec) { @@ -929,6 +1081,97 @@ mod tests { let _ = fs::remove_file(index_path); } + #[test] + fn cache_codex_notification_merges_commentary_text_across_tool_blocks() { + let index_path = temp_index_path("commentary-text-across-tool"); + let store = RuntimeWorkStore::new(index_path.clone()); + let local_task_id = "runtime-cache"; + store.upsert_task(RuntimeTaskLink::new_pending( + local_task_id.to_owned(), + "/tmp/project".to_owned(), + "Runtime cache".to_owned(), + )); + let request = ExecutionRequest { + task_id: 1, + subtask_id: 42, + ..ExecutionRequest::default() + }; + + let mut mapper = CodexNotificationCacheMapper::default(); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/started", + "params": { + "item": { + "id": "msg-commentary", + "type": "agentMessage", + "phase": "commentary", + "text": "" + } + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/agentMessage/delta", + "params": { + "itemId": "msg-commentary", + "delta": "I already " + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "type": "response_item", + "payload": { + "id": "call-1", + "type": "function_call", + "call_id": "call-1", + "name": "exec_command", + "arguments": "{\"cmd\":\"pwd\"}" + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/agentMessage/delta", + "params": { + "itemId": "msg-commentary", + "delta": "started explorers." + } + }), + ); + + let link = store + .get_task(local_task_id) + .expect("runtime task should exist"); + let messages = cached_messages(&link); + let blocks = messages[0]["blocks"] + .as_array() + .expect("blocks should be an array"); + let text_blocks: Vec<&Value> = blocks + .iter() + .filter(|block| block["type"].as_str() == Some("text")) + .collect(); + assert_eq!(text_blocks.len(), 1); + assert_eq!(text_blocks[0]["content"], "I already started explorers."); + assert_eq!(blocks[1]["type"], "tool"); + + let _ = fs::remove_file(index_path); + } + #[test] fn cache_codex_notification_keeps_commentary_channel_delta_out_of_content() { let index_path = temp_index_path("commentary-channel-agent-delta"); @@ -1009,6 +1252,257 @@ mod tests { let _ = fs::remove_file(index_path); } + #[test] + fn cache_codex_notification_ignores_subagent_agent_message_deltas() { + let index_path = temp_index_path("subagent-agent-delta"); + let store = RuntimeWorkStore::new(index_path.clone()); + let local_task_id = "runtime-cache"; + store.upsert_task(RuntimeTaskLink::new_pending( + local_task_id.to_owned(), + "/tmp/project".to_owned(), + "Runtime cache".to_owned(), + )); + let request = ExecutionRequest { + task_id: 1, + subtask_id: 42, + ..ExecutionRequest::default() + }; + let mut mapper = CodexNotificationCacheMapper::default(); + + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/started", + "params": { + "item": { + "id": "msg-child", + "type": "agentMessage", + "phase": "final_answer", + "agent_path": "/root/worker", + "text": "" + } + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/agentMessage/delta", + "params": { + "itemId": "msg-child", + "delta": "child output" + } + }), + ); + + let link = store + .get_task(local_task_id) + .expect("runtime task should exist"); + assert!(cached_messages(&link).is_empty()); + + let _ = fs::remove_file(index_path); + } + + #[test] + fn cache_codex_notification_ignores_cross_thread_agent_message_deltas() { + let index_path = temp_index_path("cross-thread-agent-delta"); + let store = RuntimeWorkStore::new(index_path.clone()); + let local_task_id = "runtime-cache"; + store.upsert_task(RuntimeTaskLink::new_pending( + local_task_id.to_owned(), + "/tmp/project".to_owned(), + "Runtime cache".to_owned(), + )); + let request = ExecutionRequest { + task_id: 1, + subtask_id: 42, + ..ExecutionRequest::default() + }; + let mut mapper = CodexNotificationCacheMapper::default(); + + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "thread/started", + "params": { + "thread": { + "id": "root-thread" + } + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/started", + "params": { + "threadId": "root-thread", + "turnId": "root-turn", + "item": { + "id": "msg-root", + "type": "agentMessage", + "phase": "final_answer", + "text": "" + } + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/started", + "params": { + "threadId": "child-thread", + "turnId": "child-turn", + "item": { + "id": "msg-child", + "type": "agentMessage", + "phase": "final_answer", + "text": "" + } + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/started", + "params": { + "threadId": "child-thread", + "turnId": "child-turn", + "item": { + "id": "call-child", + "type": "commandExecution", + "command": "rg child", + "status": "inProgress" + } + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/agentMessage/delta", + "params": { + "threadId": "child-thread", + "turnId": "child-turn", + "itemId": "msg-child", + "delta": "child" + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/agentMessage/delta", + "params": { + "threadId": "root-thread", + "turnId": "root-turn", + "itemId": "msg-root", + "delta": "root" + } + }), + ); + + let link = store + .get_task(local_task_id) + .expect("runtime task should exist"); + let messages = cached_messages(&link); + assert_eq!(messages.len(), 1); + assert_eq!(messages[0]["content"], "root"); + + let _ = fs::remove_file(index_path); + } + + #[test] + fn cache_codex_notification_ignores_subagent_turn_completion() { + let index_path = temp_index_path("subagent-turn-complete"); + let store = RuntimeWorkStore::new(index_path.clone()); + let local_task_id = "runtime-cache"; + store.upsert_task(RuntimeTaskLink::new_pending( + local_task_id.to_owned(), + "/tmp/project".to_owned(), + "Runtime cache".to_owned(), + )); + let request = ExecutionRequest { + task_id: 1, + subtask_id: 42, + ..ExecutionRequest::default() + }; + let mut mapper = CodexNotificationCacheMapper::default(); + + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "item/agentMessage/delta", + "params": { + "delta": "Still working" + } + }), + ); + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "turn/completed", + "params": { + "turn": { + "status": "completed", + "agent_path": "/root/worker" + } + } + }), + ); + + let link = store + .get_task(local_task_id) + .expect("runtime task should exist"); + let messages = cached_messages(&link); + assert_eq!(messages[0]["status"], "streaming"); + + mapper.map( + &store, + local_task_id, + &request, + &json!({ + "method": "turn/completed", + "params": { + "turn": { + "status": "completed", + "agent_path": "/root" + } + } + }), + ); + + let link = store + .get_task(local_task_id) + .expect("runtime task should exist"); + let messages = cached_messages(&link); + assert_eq!(messages[0]["status"], "done"); + + let _ = fs::remove_file(index_path); + } + fn temp_index_path(label: &str) -> PathBuf { std::env::temp_dir().join(format!( "wegent-runtime-work-{label}-{}-{}.json", diff --git a/executor/src/runtime_work/transcript.rs b/executor/src/runtime_work/transcript.rs index 1995bfe1ce7..52ea4b85946 100644 --- a/executor/src/runtime_work/transcript.rs +++ b/executor/src/runtime_work/transcript.rs @@ -16,6 +16,7 @@ use super::util::{ pub(crate) fn transcript_messages(thread: &Value, device_id: &str) -> Vec { let mut messages = Vec::new(); let workspace_path = string_field(thread, "cwd").unwrap_or_default(); + let root_thread_id = string_field(thread, "id"); for (turn_index, turn) in thread .get("turns") .and_then(Value::as_array) @@ -23,6 +24,11 @@ pub(crate) fn transcript_messages(thread: &Value, device_id: &str) -> Vec .flatten() .enumerate() { + if !is_root_transcript_item(turn) + || !is_root_thread_transcript_item(turn, root_thread_id.as_deref()) + { + continue; + } let created_at = turn_started_at(turn); let completed_at = turn_completed_at(turn, created_at); let turn_file_changes = file_changes(turn); @@ -43,6 +49,11 @@ pub(crate) fn transcript_messages(thread: &Value, device_id: &str) -> Vec .enumerate() { let item = transcript_item_with_stable_id(raw_item, &turn_id, item_index); + if !is_root_transcript_item(raw_item) + || !is_root_thread_transcript_item(raw_item, root_thread_id.as_deref()) + { + continue; + } match item_type(&item).as_str() { "usermessage" => { if is_internal_turn_abort_message(&item) { @@ -349,6 +360,29 @@ fn transcript_item(item: &Value) -> Value { Value::Object(object) } +fn is_root_transcript_item(item: &Value) -> bool { + transcript_agent_path(item) + .or_else(|| codex_wrapped_item_payload(item).and_then(transcript_agent_path)) + .map_or(true, |agent_path| agent_path == "/root") +} + +fn transcript_agent_path(value: &Value) -> Option { + string_field(value, "agent_path").or_else(|| string_field(value, "agentPath")) +} + +fn is_root_thread_transcript_item(item: &Value, root_thread_id: Option<&str>) -> bool { + let Some(root_thread_id) = root_thread_id else { + return true; + }; + transcript_thread_id(item) + .or_else(|| codex_wrapped_item_payload(item).and_then(transcript_thread_id)) + .map_or(true, |thread_id| thread_id == root_thread_id) +} + +fn transcript_thread_id(value: &Value) -> Option { + string_field(value, "threadId").or_else(|| string_field(value, "thread_id")) +} + fn transcript_item_with_stable_id(item: &Value, turn_id: &str, item_index: usize) -> Value { let mut normalized = transcript_item(item); if string_field(&normalized, "id").is_some() { @@ -2320,6 +2354,119 @@ mod tests { ); } + #[test] + fn transcript_ignores_subagent_items() { + let thread = json!({ + "turns": [ + { + "id": "turn-1", + "status": "completed", + "items": [ + { + "type": "response_item", + "payload": { + "type": "message", + "role": "assistant", + "agent_path": "/root/worker", + "content": [{"type": "output_text", "text": "child output"}] + } + }, + { + "type": "response_item", + "payload": { + "type": "message", + "role": "assistant", + "agent_path": "/root", + "content": [{"type": "output_text", "text": "root output"}] + } + } + ] + } + ] + }); + + let messages = transcript_messages(&thread, "device"); + + assert_eq!(messages.len(), 1); + assert_eq!(messages[0]["content"], "root output"); + } + + #[test] + fn transcript_ignores_cross_thread_items() { + let thread = json!({ + "id": "root-thread", + "turns": [ + { + "id": "turn-1", + "status": "completed", + "items": [ + { + "type": "response_item", + "payload": { + "type": "message", + "role": "assistant", + "threadId": "child-thread", + "content": [{"type": "output_text", "text": "child output"}] + } + }, + { + "type": "response_item", + "payload": { + "type": "message", + "role": "assistant", + "threadId": "root-thread", + "content": [{"type": "output_text", "text": "root output"}] + } + } + ] + } + ] + }); + + let messages = transcript_messages(&thread, "device"); + + assert_eq!(messages.len(), 1); + assert_eq!(messages[0]["content"], "root output"); + } + + #[test] + fn transcript_ignores_cross_thread_turns() { + let thread = json!({ + "id": "root-thread", + "turns": [ + { + "id": "child-turn", + "threadId": "child-thread", + "status": "completed", + "items": [ + { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": "child output"}] + } + ] + }, + { + "id": "root-turn", + "threadId": "root-thread", + "status": "completed", + "items": [ + { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": "root output"}] + } + ] + } + ] + }); + + let messages = transcript_messages(&thread, "device"); + + assert_eq!(messages.len(), 1); + assert_eq!(messages[0]["content"], "root output"); + } + #[test] fn running_turn_stays_streaming_without_final_file_changes_card() { let thread = json!({ diff --git a/executor/tests/process_manager_contract.rs b/executor/tests/process_manager_contract.rs index f62391ac6bc..a54ce731122 100644 --- a/executor/tests/process_manager_contract.rs +++ b/executor/tests/process_manager_contract.rs @@ -148,7 +148,11 @@ fn spawn_restart_runs_restart_plan_command() { }; assert!(manager.spawn_restart(&plan)); - wait_until(|| marker.is_file()); + wait_until(|| { + fs::read_to_string(&marker) + .map(|content| content == "started") + .unwrap_or(false) + }); assert_eq!(fs::read_to_string(marker).unwrap(), "started"); } diff --git a/wework/src/components/layout/DesktopWorkbenchMain.tsx b/wework/src/components/layout/DesktopWorkbenchMain.tsx index 56c45b91af2..a8d2110427d 100644 --- a/wework/src/components/layout/DesktopWorkbenchMain.tsx +++ b/wework/src/components/layout/DesktopWorkbenchMain.tsx @@ -56,6 +56,7 @@ import { useWorkbenchPaneEnvironment } from './useWorkbenchPaneEnvironment' import { useWorkbenchProjectWorkControls } from './useWorkbenchProjectWorkControls' import { useRuntimeTaskContinueInIm } from './useRuntimeTaskContinueInIm' import { requestOpenCloudDeviceSettings } from './workbenchShellEvents' +import { SubagentStatusIndicator } from './SubagentStatusIndicator' const DESKTOP_CHAT_CONTENT_BASE_CLASS = 'mx-auto min-w-0 px-0 transition-[width,max-width] duration-[300ms] ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none will-change-[width,max-width]' @@ -760,12 +761,21 @@ const DesktopWorkbenchPane = memo(function DesktopWorkbenchPane({ 0 ? ( + + ) : null + } + rightClassName="gap-2" /> )} diff --git a/wework/src/components/layout/MobileWorkbenchLayout.tsx b/wework/src/components/layout/MobileWorkbenchLayout.tsx index 921614df0e4..ea11ce5b6a0 100644 --- a/wework/src/components/layout/MobileWorkbenchLayout.tsx +++ b/wework/src/components/layout/MobileWorkbenchLayout.tsx @@ -31,6 +31,7 @@ import { useWorkbenchPaneSession } from './useWorkbenchPaneSession' import { useWorkbenchPaneEnvironment } from './useWorkbenchPaneEnvironment' import { useWorkbenchProjectWorkControls } from './useWorkbenchProjectWorkControls' import { useRuntimeTaskContinueInIm } from './useRuntimeTaskContinueInIm' +import { SubagentStatusIndicator } from './SubagentStatusIndicator' export function MobileWorkbenchLayout() { const { state } = useWorkbench() @@ -243,6 +244,11 @@ const MobileWorkbenchPane = memo(function MobileWorkbenchPane({ {currentRuntimeTask ? (
+ + + {panelVisible && ( +
+
+ {t('workbench.subagents_status')} + {statuses.length} +
+
+ {visibleStatuses.map(status => ( +
+ + + + {status.agentName} + + + {shortSubagentId(status.agentId)} + + + + {statusLabel(status.status)} + +
+ ))} +
+
+ )} +
+ ) +} + +function SubagentStatusIcon({ status }: { status: RuntimeSubagentStatus['status'] }) { + if (status === 'done') { + return + } + if (status === 'interrupted') { + return + } + return +} + +function shortSubagentId(agentId: string): string { + const normalized = agentId.replace(/^thread:/, '').trim() + if (!normalized) return 'subagent' + return normalized.length > 8 ? normalized.slice(-8) : normalized +} diff --git a/wework/src/components/layout/useWorkbenchPaneSession.ts b/wework/src/components/layout/useWorkbenchPaneSession.ts index e97ee2bc1dd..1c978bb4802 100644 --- a/wework/src/components/layout/useWorkbenchPaneSession.ts +++ b/wework/src/components/layout/useWorkbenchPaneSession.ts @@ -12,6 +12,7 @@ import { localRuntimeAttachments, remoteAttachmentIds } from '@/lib/runtime-atta import type { Attachment, ModelOptions, + RuntimeSubagentActivityPayload, RuntimeSendRequest, RuntimeTaskAddress, RuntimeTurnNavigationItem, @@ -21,6 +22,7 @@ import type { GuidanceWorkbenchMessage, QueuedWorkbenchMessage, RuntimePaneTranscript, + RuntimeSubagentStatus, WorkbenchMessage, } from '@/types/workbench' import type { CodeCommentContext } from '@/types/workspace-files' @@ -68,6 +70,7 @@ export function useWorkbenchPaneSession({ currentRuntimeTask }: WorkbenchPaneSes const [transcriptLoadingMoreBefore, setTranscriptLoadingMoreBefore] = useState(false) const [loadedTranscriptRanges, setLoadedTranscriptRanges] = useState([]) const [turnNavigation, setTurnNavigation] = useState([]) + const [subagentStatuses, setSubagentStatuses] = useState([]) const loadedRuntimeTranscriptKeyRef = useRef(null) const loadRuntimeTranscriptForPaneRef = useRef(loadRuntimeTranscriptForPane) const subscribeRuntimeTaskStreamRef = useRef(subscribeRuntimeTaskStream) @@ -139,6 +142,7 @@ export function useWorkbenchPaneSession({ currentRuntimeTask }: WorkbenchPaneSes setTranscriptLoadingMoreBefore(false) setLoadedTranscriptRanges([]) setTurnNavigation([]) + setSubagentStatuses([]) return } @@ -162,6 +166,7 @@ export function useWorkbenchPaneSession({ currentRuntimeTask }: WorkbenchPaneSes setTranscriptLoadingMoreBefore(false) setLoadedTranscriptRanges([]) setTurnNavigation([]) + setSubagentStatuses([]) void loadRuntimeTranscriptForPaneRef .current(address, { limit: RUNTIME_TRANSCRIPT_PAGE_SIZE }) .then(transcript => { @@ -226,10 +231,16 @@ export function useWorkbenchPaneSession({ currentRuntimeTask }: WorkbenchPaneSes const unsubscribe = subscribeRuntimeTaskStreamRef.current(address, { onMessageAction: dispatchMessages, onAssistantStart: () => setWaitingForAssistant(false), - onAssistantSettled: () => setWaitingForAssistant(false), + onAssistantSettled: () => { + setWaitingForAssistant(false) + setSubagentStatuses(markRuntimeSubagentsSettled) + }, onRefreshWorkLists: () => { void refreshWorkListsRef.current().catch(() => undefined) }, + onSubagentActivity: activity => { + setSubagentStatuses(current => updateRuntimeSubagentStatuses(current, activity)) + }, }) return unsubscribe }, [dispatchMessages, runtimeTaskLoadTarget]) @@ -607,6 +618,7 @@ export function useWorkbenchPaneSession({ currentRuntimeTask }: WorkbenchPaneSes transcriptHasMoreBefore, transcriptLoadingMoreBefore, turnNavigation, + subagentStatuses, loadMoreTranscriptBefore, loadTranscriptTurnNavigationItem, loadTranscriptGap, @@ -823,6 +835,90 @@ function runtimeTurnNavigationLoadOptions( } } +function updateRuntimeSubagentStatuses( + current: RuntimeSubagentStatus[], + activity: RuntimeSubagentActivityPayload +): RuntimeSubagentStatus[] { + const agentPath = activity.agent_path.trim() + if (!agentPath) return current + + const agentId = runtimeSubagentId(activity) + const status = normalizeRuntimeSubagentStatus(activity.status ?? activity.kind) + const previousStatus = current.find(item => item.id === agentId) + const nextStatus: RuntimeSubagentStatus = { + id: agentId, + agentId, + agentPath, + agentName: + activity.agent_name?.trim() || previousStatus?.agentName || runtimeSubagentName(agentId), + status, + kind: activity.kind, + updatedAtMs: activity.occurred_at_ms ?? Date.now(), + } + + const withoutCurrent = current.filter(item => item.id !== agentId) + return [...withoutCurrent, nextStatus].sort((left, right) => { + const leftTime = left.updatedAtMs ?? 0 + const rightTime = right.updatedAtMs ?? 0 + return rightTime - leftTime + }) +} + +function markRuntimeSubagentsSettled(current: RuntimeSubagentStatus[]): RuntimeSubagentStatus[] { + let changed = false + const settled = current.map(status => { + if (status.status !== 'running') return status + changed = true + return { + ...status, + status: 'done' as const, + updatedAtMs: Date.now(), + } + }) + return changed ? settled : current +} + +function normalizeRuntimeSubagentStatus( + value: string | undefined +): RuntimeSubagentStatus['status'] { + const normalized = value?.replace(/_/g, '').toLowerCase() + if (normalized === 'done' || normalized === 'completed' || normalized === 'taskcomplete') { + return 'done' + } + if (normalized === 'interrupted' || normalized === 'cancelled' || normalized === 'canceled') { + return 'interrupted' + } + return 'running' +} + +function runtimeSubagentId(activity: RuntimeSubagentActivityPayload): string { + const agentId = activity.agent_id?.trim() + if (agentId) return agentId + + const threadId = activity.agent_thread_id?.trim() + if (threadId) return threadId + + const agentPath = activity.agent_path.trim() + if (agentPath.startsWith('thread:')) { + return agentPath.slice('thread:'.length).trim() || agentPath + } + return agentPath +} + +function runtimeSubagentName(agentId: string): string { + const parts = agentId.split('/').filter(Boolean) + const lastPart = parts[parts.length - 1] ?? agentId + if (!lastPart || lastPart.startsWith('019') || lastPart.length > 16) { + return `Agent ${shortRuntimeAgentId(agentId)}` + } + return lastPart +} + +function shortRuntimeAgentId(agentId: string): string { + const normalized = agentId.replace(/^thread:/, '').trim() + return normalized.length > 8 ? normalized.slice(-8) : normalized || 'subagent' +} + function isRuntimeTaskAddress(value: unknown): value is RuntimeTaskAddress { if (!value || typeof value !== 'object') return false const candidate = value as Partial diff --git a/wework/src/features/workbench/runtimePaneMessages.ts b/wework/src/features/workbench/runtimePaneMessages.ts index 178f592b573..b97893b5844 100644 --- a/wework/src/features/workbench/runtimePaneMessages.ts +++ b/wework/src/features/workbench/runtimePaneMessages.ts @@ -8,6 +8,7 @@ import type { ChatStartPayload, ChatBlockCreatedPayload, ChatBlockUpdatedPayload, + RuntimeSubagentActivityPayload, NormalizedRuntimeMessage, RuntimeTaskAddress, TurnFileChangesSummary, @@ -25,6 +26,7 @@ export interface RuntimeTaskStreamHandlers { onAssistantStart?: () => void onAssistantSettled?: () => void onRefreshWorkLists?: () => void + onSubagentActivity?: (payload: RuntimeSubagentActivityPayload) => void } export function createRuntimeTaskStreamHandlers( @@ -137,6 +139,15 @@ export function createRuntimeTaskStreamHandlers( }, }) }, + onSubagentActivity: payload => { + if (!isRuntimeTaskStreamPayload(address, payload)) return + debugRuntimeStreamEvent('subagent:activity', address, payload, true, { + agentPath: payload.agent_path, + status: payload.status ?? null, + kind: payload.kind ?? null, + }) + handlers.onSubagentActivity?.(payload) + }, } } @@ -203,6 +214,7 @@ function isRuntimeTaskStreamPayload( | ChatErrorPayload | ChatBlockCreatedPayload | ChatBlockUpdatedPayload + | RuntimeSubagentActivityPayload ): boolean { if (!payload.local_task_id) return false return ( @@ -219,6 +231,7 @@ function runtimeStreamMessageId( | ChatErrorPayload | ChatBlockCreatedPayload | ChatBlockUpdatedPayload + | RuntimeSubagentActivityPayload ): string { const rawMessageId = typeof payload.message_id === 'number' ? payload.message_id : null if (rawMessageId !== null) { @@ -283,10 +296,7 @@ function runtimeMessageToWorkbenchMessage(message: NormalizedRuntimeMessage): Wo } } -function getRuntimeMessageBlockTurnId( - message: NormalizedRuntimeMessage, - turnId?: number -): number { +function getRuntimeMessageBlockTurnId(message: NormalizedRuntimeMessage, turnId?: number): number { if (typeof turnId === 'number') return turnId let hash = 0 diff --git a/wework/src/i18n/locales/en/common.json b/wework/src/i18n/locales/en/common.json index 8b2cd530e43..b3fe590a394 100644 --- a/wework/src/i18n/locales/en/common.json +++ b/wework/src/i18n/locales/en/common.json @@ -71,6 +71,12 @@ "archive_runtime_task_remove_failed": "Task archived, but failed to remove the worktree", "archive_runtime_task_remove_failed_detail": "Task archived, but failed to remove the worktree: {{message}}", "runtime_task_running": "Running", + "subagents_status": "Subagent status", + "subagents_running": "{{count}} running", + "subagents_count": "{{count}} subagents", + "subagent_running": "Running", + "subagent_done": "Done", + "subagent_interrupted": "Interrupted", "runtime_task_close_confirm_title": "A task is still running", "runtime_task_close_confirm_description": "Exiting the app will interrupt the running task. Exit anyway?", "runtime_task_close_confirm_action": "Exit app", diff --git a/wework/src/i18n/locales/zh-CN/common.json b/wework/src/i18n/locales/zh-CN/common.json index 7b1e79cfffd..fdd377f154b 100644 --- a/wework/src/i18n/locales/zh-CN/common.json +++ b/wework/src/i18n/locales/zh-CN/common.json @@ -71,6 +71,12 @@ "archive_runtime_task_remove_failed": "任务已归档,但删除工作树失败", "archive_runtime_task_remove_failed_detail": "任务已归档,但删除工作树失败:{{message}}", "runtime_task_running": "运行中", + "subagents_status": "子智能体状态", + "subagents_running": "{{count}} 个运行中", + "subagents_count": "{{count}} 个子智能体", + "subagent_running": "运行中", + "subagent_done": "完成", + "subagent_interrupted": "已中断", "runtime_task_close_confirm_title": "仍有任务正在进行", "runtime_task_close_confirm_description": "退出应用会中断正在进行的任务。确定要退出吗?", "runtime_task_close_confirm_action": "退出应用", diff --git a/wework/src/stream/chatStream.ts b/wework/src/stream/chatStream.ts index ed13b90e605..48adc6f5429 100644 --- a/wework/src/stream/chatStream.ts +++ b/wework/src/stream/chatStream.ts @@ -5,6 +5,7 @@ import type { ChatDonePayload, ChatErrorPayload, ChatStartPayload, + RuntimeSubagentActivityPayload, } from '@/types/api' import type { DeviceSlotUpdatePayload, DeviceUpgradeStatusPayload } from '@/types/device-events' import type { SocketClientSocket } from '@wegent/chat-core' @@ -23,6 +24,7 @@ export interface ChatStreamHandlers { onChatError?: (payload: ChatErrorPayload) => void onBlockCreated?: (payload: ChatBlockCreatedPayload) => void onBlockUpdated?: (payload: ChatBlockUpdatedPayload) => void + onSubagentActivity?: (payload: RuntimeSubagentActivityPayload) => void onDeviceOnline?: (payload: unknown) => void onDeviceOffline?: (payload: unknown) => void onDeviceStatus?: (payload: unknown) => void diff --git a/wework/src/stream/responseApiStream.test.ts b/wework/src/stream/responseApiStream.test.ts new file mode 100644 index 00000000000..dabf4cc4f8e --- /dev/null +++ b/wework/src/stream/responseApiStream.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test, vi } from 'vitest' +import { createResponseApiStreamState, emitResponseApiEvent } from './responseApiStream' + +describe('emitResponseApiEvent', () => { + test('emits subagent activity payloads', () => { + const onSubagentActivity = vi.fn() + + emitResponseApiEvent( + { onSubagentActivity }, + 'response.subagent.activity', + { + task_id: 1, + subtask_id: 2, + device_id: 'device-1', + local_task_id: 'local-1', + data: { + agent_path: '/root/worker', + agent_name: 'worker', + agent_thread_id: 'thread-1', + kind: 'started', + status: 'running', + occurred_at_ms: 12345, + }, + }, + createResponseApiStreamState() + ) + + expect(onSubagentActivity).toHaveBeenCalledWith({ + task_id: 1, + subtask_id: 2, + device_id: 'device-1', + local_task_id: 'local-1', + agent_path: '/root/worker', + agent_name: 'worker', + agent_thread_id: 'thread-1', + kind: 'started', + status: 'running', + occurred_at_ms: 12345, + }) + }) +}) diff --git a/wework/src/stream/responseApiStream.ts b/wework/src/stream/responseApiStream.ts index 9bc984887cf..b5d92ed2696 100644 --- a/wework/src/stream/responseApiStream.ts +++ b/wework/src/stream/responseApiStream.ts @@ -37,6 +37,7 @@ export const RESPONSE_API_STREAM_EVENTS = [ 'image_generation.partial_image', 'response.block.created', 'response.block.updated', + 'response.subagent.activity', 'response.status.updated', 'error', ] as const @@ -373,6 +374,26 @@ function emitResponseBlockUpdated( }) } +function emitSubagentActivity( + handlers: ChatStreamHandlers, + base: ReturnType, + data: Record +): void { + const agentPath = stringField(data, 'agent_path') ?? stringField(data, 'agentPath') + if (!agentPath) return + + handlers.onSubagentActivity?.({ + ...base, + agent_path: agentPath, + agent_name: stringField(data, 'agent_name') ?? stringField(data, 'agentName'), + agent_thread_id: stringField(data, 'agent_thread_id') ?? stringField(data, 'agentThreadId'), + kind: stringField(data, 'kind'), + status: stringField(data, 'status'), + occurred_at_ms: + optionalNumberField(data, 'occurred_at_ms') ?? optionalNumberField(data, 'occurredAtMs'), + }) +} + function errorMessage(payload: Record, data: Record): string { const error = data.error if (typeof error === 'string') return error @@ -439,6 +460,11 @@ export function emitResponseApiEvent( return } + if (eventName === 'response.subagent.activity') { + emitSubagentActivity(handlers, base, data) + return + } + if (eventName === 'response.output_item.added') { emitBlockCreated(handlers, base, data, state) return diff --git a/wework/src/types/api.ts b/wework/src/types/api.ts index 68a07a6efe7..02b1c33feb4 100644 --- a/wework/src/types/api.ts +++ b/wework/src/types/api.ts @@ -1478,6 +1478,21 @@ export interface ChatBlockUpdatedPayload { local_task_id?: string } +export interface RuntimeSubagentActivityPayload { + task_id?: number + subtask_id: number + message_id?: number + device_id?: string + local_task_id?: string + agent_path: string + agent_id?: string + agent_name?: string + agent_thread_id?: string + kind?: string + status?: string + occurred_at_ms?: number +} + export interface ChatGuidanceQueuedPayload { task_id: number subtask_id: number diff --git a/wework/src/types/workbench.ts b/wework/src/types/workbench.ts index 55549e30cc4..2128bffa59f 100644 --- a/wework/src/types/workbench.ts +++ b/wework/src/types/workbench.ts @@ -46,6 +46,18 @@ export type MessageSource = NonNullable export type RuntimeWorkbenchMessageStatus = WorkbenchMessageStatus | 'cancelled' +export type RuntimeSubagentStatusState = 'running' | 'done' | 'interrupted' + +export interface RuntimeSubagentStatus { + id: string + agentId: string + agentPath: string + agentName: string + status: RuntimeSubagentStatusState + kind?: string + updatedAtMs?: number | null +} + export type WorkbenchMessage = Omit< CoreWorkbenchMessage, 'blocks'