mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-12-01 00:59:02 +08:00
fix(desktop): 后台子代理三症状——async_launched 友好态 + 路由保活 + 通知不搅正文
用户实测:同步子代理超时转后台后,Agent 卡灌原始 JSON、📌 通知 Result
正文丢失、主/子消息交织。真实引擎复现事件序列(ground truth 入档
ohmy_tests):后台路径不发 agent_result,唯一收尾信号是 task_notification,
超时后戳记事件仍全量转发。
- normalize:tool_result 先分流 status==async_launched → 友好文案闭卡
(不算失败),不再走 .content 兜底解析;task_notification 改走
background_agent_finished,兜底剥 <task-notification> 包装标签
- subagent:background_agents 登记表(agent_id→父卡),async_launched
不关路由(子代理还活着,查看子会话全程可用);完成通知按 agent_id
反查父卡回填终态帧(error→failed),子会话按状态收尾;turn/stopped
放过后台子会话,引擎和解时才全关
- frame:task_note 独立系统行;reduce:task_notification 不再并进
流式正文气泡,闭合卡接受后台直播/迟到终态覆写(语义注释入档)
- 测试:E2E 超时 1s 真实复现整链路 + driver 3 单测 + reduce 3 用例;
64/64 零警告,UI tsc + 69/69;引擎零改动,3 条上游提案入档注释
This commit is contained in:
1 parent
e25eddb4bd
commit
f28aff89cc
9 files changed
+555
-20
No files matched your search
@@ -244,6 +244,12 @@ pub fn compact_status(status: &str, seq: u64) -> Value {
|
||||
acp(json!({ "sessionUpdate": "compact_status", "status": status }), seq)
|
||||
}
|
||||
|
||||
/// 后台子代理完成通知(📌):独立系统行。不复用 agent_text——它会被
|
||||
/// reduce.ts 并进正在流式的模型正文气泡,通知与模型的话混作一团。
|
||||
pub fn task_note(text: &str, seq: u64) -> Value {
|
||||
acp(json!({ "sessionUpdate": "task_notification", "text": text }), seq)
|
||||
}
|
||||
|
||||
pub fn model_update(model: &str, seq: u64) -> Value {
|
||||
acp(json!({ "sessionUpdate": "model_update", "model": model }), seq)
|
||||
}
|
||||
|
||||
@@ -103,8 +103,9 @@ impl Inner {
|
||||
ar.remove(tc);
|
||||
}
|
||||
}
|
||||
// 轮次收尾:残留子代理(未随工具闭合)按中断收尾
|
||||
self.close_children_of_session(&sid, SessionStatus::Interrupted);
|
||||
// 轮次收尾:残留子代理(未随工具闭合)按中断收尾;后台代理
|
||||
// 除外——其子循环跨轮存活,收尾归 task_notification
|
||||
self.close_children_of_session(&sid, SessionStatus::Interrupted, false);
|
||||
if !was_running {
|
||||
// 已本地和解(取消超时/引擎重启)后迟到的收尾,忽略防重复帧
|
||||
return;
|
||||
@@ -309,12 +310,25 @@ impl Inner {
|
||||
content.starts_with("Error: ")
|
||||
};
|
||||
// Agent 工具结果:agent_result 暂存(全量,不截断)为权威;
|
||||
// 无暂存时(旧引擎/后台代理的 async_launched 应答)退回解析
|
||||
// 截断 500 字符的 {status,…,content} JSON——可能破损,
|
||||
// 解析失败原样退回(兼容尾巴)
|
||||
// 无暂存时先分流 async_launched(超时转后台/显式后台的应答,
|
||||
// 引擎 subagent.go asyncLaunchedResult——**没有 content 字段**,
|
||||
// 走下面的退回解析会 unwrap_or 把整段原始 JSON 灌进卡),
|
||||
// 其余退回解析截断 500 字符的 {status,…,content} JSON——
|
||||
// 可能破损,解析失败原样退回(兼容尾巴)
|
||||
let stashed =
|
||||
if tc_id.is_empty() { None } else { self.sub.agent_results.lock().unwrap().remove(&tc_id) };
|
||||
let content: String = if name.as_deref() == Some("Agent") {
|
||||
let is_agent = name.as_deref() == Some("Agent");
|
||||
if is_agent && stashed.is_none() && !is_error {
|
||||
if let Some(resp) = serde_json::from_str::<Value>(content)
|
||||
.ok()
|
||||
.filter(|v| v.get("status").and_then(|s| s.as_str()) == Some("async_launched"))
|
||||
{
|
||||
// 子代理还活着:不关路由,登记后台,友好文案闭卡
|
||||
self.background_agent_launched(&sid, &tc_id, &resp);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let content: String = if is_agent {
|
||||
match stashed {
|
||||
Some((status, full)) => {
|
||||
if status == "error" {
|
||||
@@ -336,7 +350,7 @@ impl Inner {
|
||||
};
|
||||
let content = content.as_str();
|
||||
// Agent 工具闭合:清对应子代理路由(残留行缓冲先冲洗成尾行)
|
||||
self.close_subagents_of(&sid, &tc_id);
|
||||
self.close_subagents_of(&sid, &tc_id, SessionStatus::Finished);
|
||||
if is_error {
|
||||
// 失败工具 → failed 帧,否则 UI 渲染成绿勾
|
||||
self.push_frame(&sid, |seq| frame::tool_call_failed(&tc_id, content, seq));
|
||||
@@ -357,8 +371,21 @@ impl Inner {
|
||||
if msg.is_empty() {
|
||||
return;
|
||||
}
|
||||
let text = if etype == "task_notification" { format!("\n📌 {msg}\n") } else { msg };
|
||||
self.push_frame(&sid, |seq| frame::agent_text(&text, seq));
|
||||
if etype == "task_notification" {
|
||||
// 后台代理完成:登记在案 → Result 正文回填父 Agent 卡 +
|
||||
// 📌 系统行(独立渲染项)。旧行为把整段渲染消息当
|
||||
// agent_text 混进模型正文气泡——<task-notification>
|
||||
// 标签行被 markdown 当 HTML 块吞掉,Result 正文散落
|
||||
// 主流,看着像主/子代理消息交织
|
||||
if !self.background_agent_finished(&data, &msg) {
|
||||
// 反查不到(壳重启丢登记/SendMessage 续跑的二次完成/
|
||||
// 旧引擎):整段外显兜底,剥包装标签防 markdown 吞块
|
||||
let inner = super::subagent::strip_notification_tags(&msg);
|
||||
self.push_frame(&sid, |seq| frame::agent_text(&format!("\n\n📌 {inner}\n\n"), seq));
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.push_frame(&sid, |seq| frame::agent_text(&msg, seq));
|
||||
}
|
||||
// TodoWrite 全量清单:引擎专发 todo_update 事件供 host 渲染实时
|
||||
// 勾选卡(tool_result 只有截断 500 字符的纯文本,不能用来渲染)
|
||||
@@ -383,7 +410,7 @@ impl Inner {
|
||||
/// 工具标题:「名称 主参数」(「动词 目标」的可读形态)。
|
||||
/// 从工具结果文本提取工作区上传路径(.monkeycode/uploads/…):
|
||||
/// 浏览器截图等壳内生成物经文本路径外显,驱动转成工具卡 images。
|
||||
fn extract_upload_paths(content: &str) -> Vec<String> {
|
||||
pub(super) fn extract_upload_paths(content: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = content;
|
||||
while let Some(i) = rest.find(".monkeycode/uploads/") {
|
||||
|
||||
@@ -137,6 +137,16 @@ fn e2e_setup(tag: &str, llm_delay_ms: u64) -> (OhmyDriver, PathBuf) {
|
||||
}
|
||||
|
||||
fn e2e_setup_steps(tag: &str, llm_delay_ms: u64, steps: Vec<String>) -> (OhmyDriver, PathBuf) {
|
||||
e2e_setup_cfg(tag, llm_delay_ms, steps, json!({}))
|
||||
}
|
||||
|
||||
/// extra_settings:并进引擎 settings.json 的顶层键(如 subagent_timeout)。
|
||||
fn e2e_setup_cfg(
|
||||
tag: &str,
|
||||
llm_delay_ms: u64,
|
||||
steps: Vec<String>,
|
||||
extra_settings: Value,
|
||||
) -> (OhmyDriver, PathBuf) {
|
||||
let home = std::env::temp_dir().join(format!("ohmy-e2e-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
// 引擎配置写进壳私有目录(driver 会以 OHMYAGENT_CONFIG_DIR 注入)
|
||||
@@ -145,13 +155,18 @@ fn e2e_setup_steps(tag: &str, llm_delay_ms: u64, steps: Vec<String>) -> (OhmyDri
|
||||
std::env::set_var("XDG_CONFIG_HOME", home.join("xdg"));
|
||||
|
||||
let llm = fake_anthropic_steps(llm_delay_ms, steps);
|
||||
let settings = json!({
|
||||
let mut settings = json!({
|
||||
"default_model": "测试模型",
|
||||
"permission_mode": "default",
|
||||
"models": { "测试模型": { "type": "anthropic", "model": "test-model",
|
||||
"api_key": "sk-fake", "base_url": format!("{llm}/api/anthropic"),
|
||||
"context_window": 200000 } },
|
||||
});
|
||||
if let Some(extra) = extra_settings.as_object() {
|
||||
for (k, v) in extra {
|
||||
settings[k] = v.clone();
|
||||
}
|
||||
}
|
||||
std::fs::write(
|
||||
home.join("shellcfg/ohmyagent/settings.json"),
|
||||
serde_json::to_vec_pretty(&settings).unwrap(),
|
||||
@@ -405,6 +420,7 @@ fn bare_inner(tag: &str) -> Arc<Inner> {
|
||||
subagents: StdMutex::new(HashMap::new()),
|
||||
agent_results: StdMutex::new(HashMap::new()),
|
||||
agent_inputs: StdMutex::new(HashMap::new()),
|
||||
background_agents: StdMutex::new(HashMap::new()),
|
||||
},
|
||||
models: vec![],
|
||||
data_dir,
|
||||
@@ -761,3 +777,311 @@ fn unstamped_subagent_event_not_claimed() {
|
||||
Some("tc1".into())
|
||||
);
|
||||
}
|
||||
|
||||
// ==================== 超时转后台的子代理(async_launched) ====================
|
||||
//
|
||||
// 事件序列 ground truth(真实引擎 35ba211 实测,subagent_timeout=1s +
|
||||
// 假 LLM 每请求延迟 2s;超时前已流式的情形子代理事件在 tool_result 之前):
|
||||
// tool_call(Agent tu_1)
|
||||
// tool_result(tu_1){content=async_launched JSON:{agentId,agentType,
|
||||
// description,name,note,reason,status:"async_launched"}——**无 content
|
||||
// 字段**,is_error=false;后台路径不发 agent_result}
|
||||
// (父轮继续;子代理事件带 parent_session_id/parent_tool_call_id/
|
||||
// parent_description 戳记,model_delta/model_done 全量转发)
|
||||
// task_notification{data:{agent_id,agent_type,name,description,status,
|
||||
// message:"<task-notification>\n…\nResult:\n{全量结果}\n</task-notification>"}}
|
||||
// (父轮收尾 turn/stopped;子代理无终止事件转发,收尾信号只有通知)
|
||||
|
||||
/// async_launched 应答的 JSON(形状对表引擎 subagent.go asyncLaunchedResult)。
|
||||
fn async_launched_json(agent_id: &str, name: &str, desc: &str) -> String {
|
||||
serde_json::to_string_pretty(&json!({
|
||||
"agentId": agent_id,
|
||||
"agentType": "plan",
|
||||
"description": desc,
|
||||
"name": name,
|
||||
"note": "The agent will notify you with a <task-notification> when it finishes.",
|
||||
"reason": "still running after 2m0s; moved to the background",
|
||||
"status": "async_launched",
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn notification_message(agent_id: &str, name: &str, desc: &str, status: &str, result: &str) -> String {
|
||||
format!(
|
||||
"<task-notification>\nBackground agent {agent_id} (name: {name}) [plan] finished with status: {status}\nTask: {desc}\nResult:\n{result}\n</task-notification>"
|
||||
)
|
||||
}
|
||||
|
||||
fn journal_frames(inner: &Inner, sid: &str) -> Vec<Value> {
|
||||
inner.journal_barrier();
|
||||
std::fs::read_to_string(inner.data_dir.join(sid).join("events.jsonl"))
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter_map(|l| serde_json::from_str::<Value>(l).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 用户实测回归(超时前子代理已流式认领):async_launched 不把原始 JSON
|
||||
/// 灌卡、不关活着的子代理路由;turn/stopped 放过后台子会话(跨轮存活);
|
||||
/// task_notification 以 Result 正文回填父卡终态 + 📌 系统行 + 子会话收尾;
|
||||
/// 通知全文不再以 agent_text 混进模型正文气泡。
|
||||
#[test]
|
||||
fn backgrounded_subagent_survives_and_backfills() {
|
||||
let inner = bare_inner("bg");
|
||||
inner.transport.engine_caps.lock().unwrap().insert("structuredToolResult".into());
|
||||
inner.sess.sessions.lock().unwrap().insert("s1".into(), bare_session("s1"));
|
||||
let ev = |t: &str, tc: &str, data: Value| {
|
||||
json!({ "type": t, "session_id": "s1", "tool_call_id": tc, "data": data })
|
||||
};
|
||||
inner.handle_event(ev(
|
||||
"tool_call",
|
||||
"tc1",
|
||||
json!({ "name": "Agent", "input": { "description": "设计解耦接口方案", "prompt": "去设计", "name": "bd" } }),
|
||||
));
|
||||
// 超时前子代理已流式(带戳记)→ 认领并投喂父卡
|
||||
inner.handle_event(json!({ "type": "model_delta", "session_id": "child1",
|
||||
"parent_session_id": "s1", "parent_tool_call_id": "tc1",
|
||||
"parent_description": "设计解耦接口方案", "data": { "text": "调查中…\n" } }));
|
||||
assert!(inner.sess.sessions.lock().unwrap().contains_key("child1"), "子代理未认领");
|
||||
// 超时转后台:tool_result 回 async_launched JSON(无 content 字段)
|
||||
inner.handle_event(ev(
|
||||
"tool_result",
|
||||
"tc1",
|
||||
json!({ "tool": "Agent", "content": async_launched_json("a1", "bd", "设计解耦接口方案"), "is_error": false }),
|
||||
));
|
||||
{
|
||||
let subs = inner.sub.subagents.lock().unwrap();
|
||||
let r = subs.get("child1").expect("async_launched 不得清掉活着的子代理路由");
|
||||
assert!(r.background, "路由未标记后台");
|
||||
}
|
||||
assert!(
|
||||
inner.sub.background_agents.lock().unwrap().contains_key("a1"),
|
||||
"后台代理未登记"
|
||||
);
|
||||
// 父轮收尾:后台子会话跨轮存活,不得按中断收尾
|
||||
inner.handle_notification("turn/stopped", json!({ "session_id": "s1", "stop_reason": "complete" }));
|
||||
assert!(
|
||||
inner.sub.subagents.lock().unwrap().contains_key("child1"),
|
||||
"turn/stopped 不得收掉后台子代理路由"
|
||||
);
|
||||
assert!(
|
||||
inner.sess.sessions.lock().unwrap().get("child1").map(|s| s.running).unwrap_or(false),
|
||||
"后台子会话应保持 running"
|
||||
);
|
||||
// 后台期间子代理继续流式 → 仍投喂父卡进度窗
|
||||
inner.handle_event(json!({ "type": "model_delta", "session_id": "child1",
|
||||
"parent_session_id": "s1", "parent_tool_call_id": "tc1",
|
||||
"parent_description": "设计解耦接口方案", "data": { "text": "结论已成\n" } }));
|
||||
// 完成通知:结果回填 + 收尾
|
||||
inner.handle_event(json!({ "type": "task_notification", "session_id": "s1", "data": {
|
||||
"agent_id": "a1", "agent_type": "plan", "name": "bd", "description": "设计解耦接口方案",
|
||||
"status": "completed",
|
||||
"message": notification_message("a1", "bd", "设计解耦接口方案", "completed", "最终结论正文"),
|
||||
}}));
|
||||
assert!(inner.sub.background_agents.lock().unwrap().is_empty(), "登记未消费");
|
||||
assert!(inner.sub.subagents.lock().unwrap().is_empty(), "通知后路由未清");
|
||||
|
||||
let frames = journal_frames(&inner, "s1");
|
||||
let tc1_finals: Vec<Value> = frames
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.filter(|u| {
|
||||
u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("tool_call_update")
|
||||
&& u.get("toolCallId").and_then(|v| v.as_str()) == Some("tc1")
|
||||
&& u.get("status").and_then(|v| v.as_str()) != Some("in_progress")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(tc1_finals.len(), 2, "应有两次终态帧(转后台文案 + 结果回填): {tc1_finals:?}");
|
||||
let first = tc1_finals[0].get("rawOutput").and_then(|v| v.as_str()).unwrap_or("");
|
||||
assert!(first.contains("已转入后台"), "async_launched 卡应是友好文案: {first}");
|
||||
assert!(!first.contains("async_launched"), "原始 JSON 不得灌卡: {first}");
|
||||
assert_eq!(tc1_finals[1].get("status").and_then(|v| v.as_str()), Some("completed"));
|
||||
assert_eq!(
|
||||
tc1_finals[1].get("rawOutput").and_then(|v| v.as_str()),
|
||||
Some("最终结论正文"),
|
||||
"Result 正文未回填父卡"
|
||||
);
|
||||
// 📌 系统行(task_notification 帧,独立渲染项)
|
||||
let note = frames
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.find(|u| u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("task_notification"))
|
||||
.expect("缺 📌 系统行帧");
|
||||
let note_text = note.get("text").and_then(|v| v.as_str()).unwrap_or("");
|
||||
assert!(note_text.contains("bd") && note_text.contains("已完成"), "📌 文案不符: {note_text}");
|
||||
// 通知全文不得以 agent_text 混进模型正文气泡
|
||||
let leaked = frames.iter().filter_map(acp_update).any(|u| {
|
||||
u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("agent_message_chunk")
|
||||
&& u["content"]["text"].as_str().map(|t| t.contains("Background agent")).unwrap_or(false)
|
||||
});
|
||||
assert!(!leaked, "通知全文混进了正文气泡");
|
||||
// 后台期间的流式行仍进父卡进度窗
|
||||
let fed = frames.iter().filter_map(acp_update).any(|u| {
|
||||
u.get("toolCallId").and_then(|v| v.as_str()) == Some("tc1")
|
||||
&& u["progress"]["line"].as_str().map(|l| l.contains("结论已成")).unwrap_or(false)
|
||||
});
|
||||
assert!(fed, "后台期间的子代理进度未进父卡");
|
||||
// 子会话按 Finished 收尾
|
||||
let ctypes: Vec<String> = journal_frames(&inner, "child1")
|
||||
.iter()
|
||||
.filter_map(|f| f.get("type").and_then(|v| v.as_str()).map(String::from))
|
||||
.collect();
|
||||
assert!(ctypes.iter().any(|t| t == "task-ended"), "子会话未收尾: {ctypes:?}");
|
||||
assert_eq!(
|
||||
inner.read_sidecar("child1").get("status").and_then(|v| v.as_str()),
|
||||
Some("finished"),
|
||||
"子会话 sidecar 未落 finished"
|
||||
);
|
||||
}
|
||||
|
||||
/// 后台代理失败(status=error)→ 父卡 failed 帧回填错误详情,📌 行报失败,
|
||||
/// 子会话按 error 收尾。
|
||||
#[test]
|
||||
fn backgrounded_subagent_error_marks_card_failed() {
|
||||
let inner = bare_inner("bgerr");
|
||||
inner.transport.engine_caps.lock().unwrap().insert("structuredToolResult".into());
|
||||
inner.sess.sessions.lock().unwrap().insert("s1".into(), bare_session("s1"));
|
||||
let ev = |t: &str, tc: &str, data: Value| {
|
||||
json!({ "type": t, "session_id": "s1", "tool_call_id": tc, "data": data })
|
||||
};
|
||||
inner.handle_event(ev("tool_call", "tc1", json!({ "name": "Agent", "input": { "description": "d", "prompt": "p" } })));
|
||||
inner.handle_event(ev(
|
||||
"tool_result",
|
||||
"tc1",
|
||||
json!({ "tool": "Agent", "content": async_launched_json("a2", "", "d"), "is_error": false }),
|
||||
));
|
||||
inner.handle_event(json!({ "type": "task_notification", "session_id": "s1", "data": {
|
||||
"agent_id": "a2", "name": "", "description": "d", "status": "error",
|
||||
"message": notification_message("a2", "", "d", "error", "provider 炸了"),
|
||||
}}));
|
||||
let frames = journal_frames(&inner, "s1");
|
||||
let failed = frames
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.find(|u| {
|
||||
u.get("toolCallId").and_then(|v| v.as_str()) == Some("tc1")
|
||||
&& u.get("status").and_then(|v| v.as_str()) == Some("failed")
|
||||
})
|
||||
.expect("缺 failed 回填帧");
|
||||
assert_eq!(failed.get("rawOutput").and_then(|v| v.as_str()), Some("provider 炸了"));
|
||||
let note = frames
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.find(|u| u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("task_notification"))
|
||||
.expect("缺 📌 系统行帧");
|
||||
assert!(note.get("text").and_then(|v| v.as_str()).unwrap_or("").contains("执行失败"));
|
||||
}
|
||||
|
||||
/// 反查不到登记(壳重启丢内存/SendMessage 续跑二次完成)的 task_notification:
|
||||
/// 退回整段外显,但剥 <task-notification> 包装标签——markdown 会把标签行
|
||||
/// 当 HTML 块吞掉后半段(用户实测症状:Result: 后面正文丢失)。
|
||||
#[test]
|
||||
fn task_notification_without_registry_falls_back_stripped() {
|
||||
let inner = bare_inner("bgfb");
|
||||
inner.sess.sessions.lock().unwrap().insert("s1".into(), bare_session("s1"));
|
||||
inner.handle_event(json!({ "type": "task_notification", "session_id": "s1", "data": {
|
||||
"agent_id": "unknown", "status": "completed",
|
||||
"message": notification_message("unknown", "x", "d", "completed", "正文内容"),
|
||||
}}));
|
||||
let frames = journal_frames(&inner, "s1");
|
||||
let text = frames
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.filter(|u| u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("agent_message_chunk"))
|
||||
.filter_map(|u| u["content"]["text"].as_str().map(String::from))
|
||||
.next()
|
||||
.expect("缺兜底外显帧");
|
||||
assert!(text.contains("📌") && text.contains("正文内容"), "兜底外显不完整: {text}");
|
||||
assert!(!text.contains("<task-notification>"), "包装标签未剥: {text}");
|
||||
}
|
||||
|
||||
/// E2E:真实引擎 subagent_timeout=1s + 假 LLM 每请求 2s——Agent 同步调用
|
||||
/// 超时转后台,整条链路(async_launched 卡文案 → 后台完成通知回填 →
|
||||
/// 📌 系统行 → 子会话收尾)对着真实事件序列验证。
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn e2e_subagent_timeout_backgrounded() {
|
||||
if find_ohmyagent().is_none() {
|
||||
eprintln!("skip: 未找到 ohmyagent 二进制");
|
||||
return;
|
||||
}
|
||||
let _g = E2E_LOCK.lock().unwrap();
|
||||
let steps = vec![
|
||||
// req0 父轮:派 Agent;req1 子代理应答(延迟 2s > 超时 1s → 转后台);
|
||||
// req2 父轮继续(Bash 给循环一次迭代机会,好在轮内排空通知);
|
||||
// req3 父轮收尾(模型已看到 <task-notification>)
|
||||
sse_tool_use("tu_1", "Agent", &json!({ "prompt": "深入调查并汇报", "description": "后台调查任务", "name": "bg-worker" })),
|
||||
sse_text("子代理最终结论:一切正常\n"),
|
||||
sse_tool_use("tu_2", "Bash", &json!({ "command": "echo ok" })),
|
||||
sse_text("父任务收尾完成"),
|
||||
];
|
||||
let (driver, home) = e2e_setup_cfg("bg", 2000, steps, json!({ "subagent_timeout": 1000 }));
|
||||
let workdir = home.to_string_lossy().into_owned();
|
||||
let meta = driver.session_create(&workdir, "测试模型", false).await.expect("建会话");
|
||||
let sid = meta.get("id").and_then(|v| v.as_str()).unwrap().to_string();
|
||||
driver.session_open(&sid).await.expect("打开会话");
|
||||
driver.session_call(&sid, "session_set_mode", json!({ "mode": "yolo" })).await.expect("yolo");
|
||||
driver
|
||||
.session_send(&sid, "user-input", json!({ "content": frame::b64_text("派个子代理") }))
|
||||
.await
|
||||
.expect("发送");
|
||||
|
||||
let journal = wait_journal(&driver, &sid, |j| {
|
||||
j.iter().any(|f| f.get("type").and_then(|v| v.as_str()) == Some("task-ended"))
|
||||
})
|
||||
.await;
|
||||
let tu1_finals: Vec<Value> = journal
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.filter(|u| {
|
||||
u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("tool_call_update")
|
||||
&& u.get("toolCallId").and_then(|v| v.as_str()) == Some("tu_1")
|
||||
&& u.get("status").and_then(|v| v.as_str()) != Some("in_progress")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(tu1_finals.len(), 2, "应有转后台 + 回填两次终态帧: {journal:?}");
|
||||
let first = tu1_finals[0].get("rawOutput").and_then(|v| v.as_str()).unwrap_or("");
|
||||
assert!(
|
||||
first.contains("已转入后台") && first.contains("bg-worker") && !first.contains("async_launched"),
|
||||
"async_launched 卡文案不符: {first}"
|
||||
);
|
||||
assert_eq!(tu1_finals[1].get("status").and_then(|v| v.as_str()), Some("completed"));
|
||||
assert!(
|
||||
tu1_finals[1].get("rawOutput").and_then(|v| v.as_str()).unwrap_or("").contains("子代理最终结论"),
|
||||
"后台完成结果未回填父卡: {tu1_finals:?}"
|
||||
);
|
||||
// 📌 系统行帧
|
||||
let note = journal
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.find(|u| u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("task_notification"))
|
||||
.expect("缺 📌 系统行帧");
|
||||
assert!(note.get("text").and_then(|v| v.as_str()).unwrap_or("").contains("bg-worker"));
|
||||
// 通知全文不得混进正文气泡
|
||||
let leaked = journal.iter().filter_map(acp_update).any(|u| {
|
||||
u.get("sessionUpdate").and_then(|v| v.as_str()) == Some("agent_message_chunk")
|
||||
&& u["content"]["text"].as_str().map(|t| t.contains("Background agent")).unwrap_or(false)
|
||||
});
|
||||
assert!(!leaked, "通知全文混进正文气泡");
|
||||
// 子会话物化 + 收尾(认领晚于 async_launched 的顺序也要能闭合)
|
||||
let child_id = journal
|
||||
.iter()
|
||||
.filter_map(acp_update)
|
||||
.find_map(|u| {
|
||||
if u.get("toolCallId").and_then(|v| v.as_str()) != Some("tu_1") {
|
||||
return None;
|
||||
}
|
||||
let p = u.get("progress")?;
|
||||
if p.get("kind").and_then(|v| v.as_str()) != Some("child_session") {
|
||||
return None;
|
||||
}
|
||||
p.get("childSessionId").and_then(|v| v.as_str()).map(String::from)
|
||||
})
|
||||
.expect("缺 child_session 链接");
|
||||
let ctypes: Vec<String> = driver
|
||||
.read_journal(&child_id)
|
||||
.iter()
|
||||
.filter_map(|f| f.get("type").and_then(|v| v.as_str()).map(String::from))
|
||||
.collect();
|
||||
assert!(ctypes.iter().any(|t| t == "task-ended"), "后台子会话未收尾: {ctypes:?}");
|
||||
driver.stop();
|
||||
}
|
||||
@@ -1017,7 +1017,8 @@ impl Inner {
|
||||
ar.remove(tc);
|
||||
}
|
||||
}
|
||||
self.close_children_of_session(sid, SessionStatus::Interrupted);
|
||||
// 引擎不再服务:后台代理连同子循环一起没了,一并收尾(含后台登记)
|
||||
self.close_children_of_session(sid, SessionStatus::Interrupted, true);
|
||||
for (tc, _name) in open {
|
||||
self.push_frame(sid, |seq| frame::tool_call_failed(&tc, "已中断", seq));
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ pub(super) struct SubagentRoute {
|
||||
pub(super) parent_tc: String,
|
||||
/// model_delta 行缓冲:凑整行再出 subagent_text(防每 token 一帧)
|
||||
pub(super) line_buf: String,
|
||||
/// 后台代理(Agent 工具回了 async_launched):子循环跨轮存活,
|
||||
/// turn/stopped 不得收尾,等 task_notification 才闭合
|
||||
pub(super) background: bool,
|
||||
}
|
||||
|
||||
/// 子代理态锁组:子会话路由与 Agent 工具入参/结果暂存。
|
||||
@@ -41,6 +44,10 @@ pub(super) struct SubagentState {
|
||||
/// 父会话 Agent 工具入参暂存(tc_id → (description, prompt)),
|
||||
/// 子会话物化时作标题与首条输入
|
||||
pub(super) agent_inputs: StdMutex<HashMap<String, (String, String)>>,
|
||||
/// 后台代理登记(agent_id → (父 sid, 父 Agent tc_id)):Agent 工具回
|
||||
/// async_launched(超时转后台/显式后台)时登记,task_notification 按
|
||||
/// agent_id 反查父卡回填最终结果并收尾;引擎不再服务时随会话和解清除
|
||||
pub(super) background_agents: StdMutex<HashMap<String, (String, String)>>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
@@ -133,9 +140,17 @@ impl Inner {
|
||||
m["title"] = json!(title);
|
||||
m["status"] = json!(SessionStatus::Running.as_str());
|
||||
});
|
||||
// 认领晚于 async_launched 的情形(子代理首个转发事件在超时之后才到):
|
||||
// 登记表已有该父工具的后台标记,路由生来即后台,跨轮存活
|
||||
let background = self
|
||||
.sub.background_agents
|
||||
.lock()
|
||||
.unwrap()
|
||||
.values()
|
||||
.any(|(s, tc)| s == &psid && tc == &ptc);
|
||||
self.sub.subagents.lock().unwrap().insert(
|
||||
child_sid.to_string(),
|
||||
SubagentRoute { parent_sid: psid.clone(), parent_tc: ptc.clone(), line_buf: String::new() },
|
||||
SubagentRoute { parent_sid: psid.clone(), parent_tc: ptc.clone(), line_buf: String::new(), background },
|
||||
);
|
||||
// 子会话回放形状与主会话一致:user-input(任务)→ task-started → …
|
||||
if !prompt.is_empty() {
|
||||
@@ -249,8 +264,9 @@ impl Inner {
|
||||
self.write_sidecar(child_sid, |m| m["status"] = json!(status.as_str()));
|
||||
}
|
||||
|
||||
/// 父会话某工具闭合:冲洗子代理残留行缓冲、关闭对应子会话、删路由。
|
||||
pub(super) fn close_subagents_of(&self, sid: &str, tc_id: &str) {
|
||||
/// 父会话某工具闭合:冲洗子代理残留行缓冲、按 status 关闭对应子会话、
|
||||
/// 删路由(同步完成 Finished;后台代理经 task_notification 按其终态)。
|
||||
pub(super) fn close_subagents_of(&self, sid: &str, tc_id: &str, status: SessionStatus) {
|
||||
let closing: Vec<(String, String)> = {
|
||||
let mut subs = self.sub.subagents.lock().unwrap();
|
||||
let closing = subs
|
||||
@@ -267,25 +283,129 @@ impl Inner {
|
||||
frame::tool_call_progress(tc_id, json!({ "kind": "subagent_text", "line": tail }), seq)
|
||||
});
|
||||
}
|
||||
self.close_child(&child, SessionStatus::Finished);
|
||||
self.close_child(&child, status);
|
||||
}
|
||||
self.sub.agent_inputs.lock().unwrap().remove(tc_id);
|
||||
}
|
||||
|
||||
/// 会话轮次结束/和解:其子代理路由全部失效,残留子会话按 status 收尾。
|
||||
pub(super) fn close_children_of_session(&self, sid: &str, status: SessionStatus) {
|
||||
/// 会话轮次结束/和解:子代理路由失效,残留子会话按 status 收尾。
|
||||
/// include_background=false(turn/stopped)放过后台代理——它们的子循环
|
||||
/// 跨轮存活,收尾归 task_notification;true(引擎不再服务的和解)全关,
|
||||
/// 后台登记一并清除(通知永远不会来了)。
|
||||
pub(super) fn close_children_of_session(&self, sid: &str, status: SessionStatus, include_background: bool) {
|
||||
let children: Vec<String> = {
|
||||
let mut subs = self.sub.subagents.lock().unwrap();
|
||||
let children = subs
|
||||
.iter()
|
||||
.filter(|(_, r)| r.parent_sid == sid)
|
||||
.filter(|(_, r)| r.parent_sid == sid && (include_background || !r.background))
|
||||
.map(|(child, _)| child.clone())
|
||||
.collect();
|
||||
subs.retain(|_, r| r.parent_sid != sid);
|
||||
subs.retain(|_, r| !(r.parent_sid == sid && (include_background || !r.background)));
|
||||
children
|
||||
};
|
||||
for child in children {
|
||||
self.close_child(&child, status);
|
||||
}
|
||||
if include_background {
|
||||
self.sub.background_agents.lock().unwrap().retain(|_, (s, _)| s != sid);
|
||||
}
|
||||
}
|
||||
|
||||
/// Agent 工具应答 async_launched(同步超时转后台/显式 run_in_background):
|
||||
/// 子代理还活着——不关路由,登记 agent_id → 父卡供 task_notification
|
||||
/// 反查,已认领路由补后台标记(超时前已流式认领的情形;认领在后的
|
||||
/// 情形由 claim_subagent 查登记表)。工具卡以友好文案按 completed
|
||||
/// 收尾:调用本身成功返回,子代理成败等 task_notification 终态回填。
|
||||
pub(super) fn background_agent_launched(&self, sid: &str, tc_id: &str, resp: &Value) {
|
||||
let get = |k: &str| resp.get(k).and_then(|v| v.as_str()).unwrap_or("");
|
||||
let agent_id = get("agentId");
|
||||
if !agent_id.is_empty() {
|
||||
self.sub.background_agents
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(agent_id.to_string(), (sid.to_string(), tc_id.to_string()));
|
||||
}
|
||||
if let Some(r) = self
|
||||
.sub.subagents
|
||||
.lock()
|
||||
.unwrap()
|
||||
.values_mut()
|
||||
.find(|r| r.parent_sid == sid && r.parent_tc == tc_id)
|
||||
{
|
||||
r.background = true;
|
||||
}
|
||||
let label = agent_label(get("name"), get("description"), agent_id);
|
||||
let text =
|
||||
format!("⏳ 子代理已转入后台继续执行({label}),完成后结果将回填此卡,并在对话流以 📌 通知");
|
||||
self.push_frame(sid, |seq| frame::tool_call_completed(tc_id, &text, &[], seq));
|
||||
}
|
||||
|
||||
/// task_notification 收尾后台代理:按 agent_id 反查父卡,Result 正文
|
||||
/// 回填工具卡终态(error → failed 帧),子会话按终态关闭,对话流落
|
||||
/// 一条 📌 系统行(task_note 帧,独立渲染项不混模型气泡)。反查不到
|
||||
/// (壳重启丢登记/SendMessage 续跑的二次完成/旧引擎)返回 false,
|
||||
/// 调用方整段外显兜底。
|
||||
pub(super) fn background_agent_finished(&self, data: &Value, msg: &str) -> bool {
|
||||
let get = |k: &str| data.get(k).and_then(|v| v.as_str()).unwrap_or("");
|
||||
let agent_id = get("agent_id");
|
||||
if agent_id.is_empty() {
|
||||
return false;
|
||||
}
|
||||
// 帧一律落在登记的父会话(通知本就发在父会话,psid 即 sid;
|
||||
// 万一不符也以卡所在会话为准,不把结果写岔)
|
||||
let Some((psid, ptc)) = self.sub.background_agents.lock().unwrap().remove(agent_id) else {
|
||||
return false;
|
||||
};
|
||||
let status = get("status");
|
||||
let result = notification_result(msg).unwrap_or_else(|| msg.to_string());
|
||||
let child_status = match status {
|
||||
"error" => SessionStatus::Error,
|
||||
"stopped" => SessionStatus::Interrupted,
|
||||
_ => SessionStatus::Finished,
|
||||
};
|
||||
// 先冲洗行缓冲/关子会话(残留尾行在终态帧之前落卡),再回填终态
|
||||
self.close_subagents_of(&psid, &ptc, child_status);
|
||||
if status == "error" {
|
||||
self.push_frame(&psid, |seq| frame::tool_call_failed(&ptc, &result, seq));
|
||||
} else {
|
||||
let images = super::normalize::extract_upload_paths(&result);
|
||||
self.push_frame(&psid, |seq| frame::tool_call_completed(&ptc, &result, &images, seq));
|
||||
}
|
||||
let label = agent_label(get("name"), get("description"), agent_id);
|
||||
let note = match status {
|
||||
"error" => format!("📌 后台代理 {label} 执行失败,详情见其任务卡"),
|
||||
"stopped" => format!("📌 后台代理 {label} 已停止"),
|
||||
_ => format!("📌 后台代理 {label} 已完成,结果已回填其任务卡"),
|
||||
};
|
||||
self.push_frame(&psid, |seq| frame::task_note(¬e, seq));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// 后台代理的人话标签:「name(description)」按有啥用啥,全空退 agent_id。
|
||||
fn agent_label(name: &str, desc: &str, agent_id: &str) -> String {
|
||||
match (name.is_empty(), desc.is_empty()) {
|
||||
(false, false) => format!("{name}({desc})"),
|
||||
(false, true) => name.to_string(),
|
||||
(true, false) => desc.to_string(),
|
||||
(true, true) => agent_id.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 从 task_notification 渲染消息里取 Result 正文。形状对表引擎
|
||||
/// notification.go::Render(固定:<task-notification>\n…\nResult:\n{正文}
|
||||
/// \n</task-notification>);解析不出返回 None,调用方退回全文。
|
||||
fn notification_result(msg: &str) -> Option<String> {
|
||||
let body = strip_notification_tags(msg);
|
||||
let idx = body.find("\nResult:\n")?;
|
||||
Some(body[idx + "\nResult:\n".len()..].trim().to_string())
|
||||
}
|
||||
|
||||
/// 剥掉 <task-notification> 包装标签(markdown 会把标签行当 HTML 块,
|
||||
/// DOMPurify 再剥标签,块内文本与后续正文的分界随之错乱——外显前去壳)。
|
||||
pub(super) fn strip_notification_tags(msg: &str) -> String {
|
||||
let body = msg.trim();
|
||||
let body = body.strip_prefix("<task-notification>").unwrap_or(body);
|
||||
let body = body.strip_suffix("</task-notification>").unwrap_or(body);
|
||||
body.trim().to_string()
|
||||
}
|
||||
@@ -216,6 +216,7 @@ impl OhmyDriver {
|
||||
subagents: StdMutex::new(HashMap::new()),
|
||||
agent_results: StdMutex::new(HashMap::new()),
|
||||
agent_inputs: StdMutex::new(HashMap::new()),
|
||||
background_agents: StdMutex::new(HashMap::new()),
|
||||
},
|
||||
models,
|
||||
data_dir,
|
||||
|
||||
@@ -147,6 +147,52 @@ describe("执行期进度(in_progress progress)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("后台子代理(Agent 超时转后台)", () => {
|
||||
const open = acp({ sessionUpdate: "tool_call", toolCallId: "t1", title: "Agent 后台调查" });
|
||||
// 驱动侧 async_launched 的友好文案闭卡
|
||||
const launched = acp({
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "t1",
|
||||
status: "completed",
|
||||
rawOutput: "⏳ 子代理已转入后台继续执行(bd),完成后结果将回填此卡",
|
||||
});
|
||||
|
||||
it("task_notification 渲染独立系统行,不并入流式中的正文气泡", () => {
|
||||
const s = run([
|
||||
acp({ sessionUpdate: "agent_message_chunk", content: { text: "我先做别的" } }),
|
||||
acp({ sessionUpdate: "task_notification", text: "📌 后台代理 bd 已完成,结果已回填其任务卡" }),
|
||||
acp({ sessionUpdate: "agent_message_chunk", content: { text: ",继续" } }),
|
||||
]);
|
||||
expect(s.items.map((it) => it.kind)).toEqual(["agent", "sys", "agent"]);
|
||||
expect((s.items[1] as Extract<LogItem, { kind: "sys" }>).text).toContain("bd");
|
||||
// 缺 text 忽略
|
||||
expect(reduceFrame(s, acp({ sessionUpdate: "task_notification" })).items).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("已闭合的 Agent 卡继续接受后台代理的进度直播", () => {
|
||||
const s = run([
|
||||
open,
|
||||
launched,
|
||||
acp({ sessionUpdate: "tool_call_update", toolCallId: "t1", status: "in_progress", progress: { kind: "subagent_text", line: "后台仍在跑" } }),
|
||||
acp({ sessionUpdate: "tool_call_update", toolCallId: "t1", status: "in_progress", progress: { kind: "child_session", childSessionId: "c1" } }),
|
||||
]);
|
||||
expect(toolItem(s, "t1")).toMatchObject({ status: "ok", childSessionId: "c1" });
|
||||
expect(toolItem(s, "t1").feed).toEqual([{ kind: "text", text: "后台仍在跑" }]);
|
||||
});
|
||||
|
||||
it("终态帧可重复回写:task_notification 迟到的真实结果覆写转后台文案", () => {
|
||||
const s = run([
|
||||
open,
|
||||
launched,
|
||||
acp({ sessionUpdate: "tool_call_update", toolCallId: "t1", status: "completed", rawOutput: "最终结论正文" }),
|
||||
]);
|
||||
expect(toolItem(s, "t1")).toMatchObject({ status: "ok", result: "最终结论正文" });
|
||||
// 失败终态同样覆写(后台代理 error 收尾)
|
||||
const f = reduceFrame(s, acp({ sessionUpdate: "tool_call_update", toolCallId: "t1", status: "failed", rawOutput: "炸了" }));
|
||||
expect(toolItem(f, "t1")).toMatchObject({ status: "fail", result: "炸了" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("计划卡片", () => {
|
||||
it("plan 不进对话流,面板状态整卡更新", () => {
|
||||
const s = reduceBatch(initialChat, [
|
||||
|
||||
@@ -237,8 +237,12 @@ function reduceAcp(s: ChatState, u: AcpUpdate): ChatState {
|
||||
};
|
||||
}
|
||||
if (u.status === "in_progress") {
|
||||
// 注:已闭合卡也接受 progress——超时转后台的 Agent 卡先以
|
||||
// "已转入后台"文案 completed,后台代理继续流式,进度窗照常直播
|
||||
return u.progress ? applyProgress(s, u.toolCallId ?? "", u.progress) : s;
|
||||
}
|
||||
// 终态可重复回写:后台 Agent 卡的真实结果随 task_notification 迟到,
|
||||
// 驱动补发终态帧回填——后到者权威,直接覆写
|
||||
const items = s.items.slice();
|
||||
for (let i = items.length - 1; i >= 0; i--) {
|
||||
const it = items[i];
|
||||
@@ -261,6 +265,10 @@ function reduceAcp(s: ChatState, u: AcpUpdate): ChatState {
|
||||
return { ...s, plan: u.entries ?? [] };
|
||||
case "llm_call_retry":
|
||||
return push(s, { kind: "sys", text: `模型调用重试 #${u.attempt ?? "?"}: ${u.message ?? ""}` });
|
||||
case "task_notification":
|
||||
// 后台子代理完成通知(📌):独立系统行。不能走 agent_text——
|
||||
// appendStream 会把它并进正在流式的模型正文气泡
|
||||
return u.text ? push(s, { kind: "sys", text: u.text }) : s;
|
||||
case "usage_update":
|
||||
return { ...s, usage: { used: u.used ?? 0, size: u.size ?? 0 } };
|
||||
case "compact_status":
|
||||
|
||||
@@ -100,6 +100,8 @@ export interface AcpUpdate {
|
||||
entries?: PlanEntry[];
|
||||
attempt?: number;
|
||||
message?: string;
|
||||
/** task_notification(后台子代理完成 📌 系统行)的通知文本 */
|
||||
text?: string;
|
||||
used?: number;
|
||||
size?: number;
|
||||
progress?: ToolProgress;
|
||||
|
||||
Reference in new issue
Block a user