diff --git a/apps/web/src/components/chat/blocks/subagentParse.regex.test.ts b/apps/web/src/components/chat/blocks/subagentParse.regex.test.ts index fd67348d..cbe7eed1 100644 --- a/apps/web/src/components/chat/blocks/subagentParse.regex.test.ts +++ b/apps/web/src/components/chat/blocks/subagentParse.regex.test.ts @@ -60,3 +60,20 @@ describe("parseSubagentResults(正则化后)", () => { } }); }); + +it("folds plans and subagent results from a single callback in order", () => { + const text = 'Status & details\n' + + 'Result'; + expect(foldSubagentResultBlocks([{ kind: "text", text }])).toMatchObject([ + { kind: "plan_update", planId: "plan-1", text: "Status & details" }, + { kind: "subagent_result", sessionId: "s-1", summary: "Result" }, + ]); +}); + + +it("accepts legacy Worker attributes and preserves the callback message ID", () => { + const text = "Report"; + expect(foldSubagentResultBlocks([{ kind: "text", text }])).toMatchObject([ + { kind: "worker_result", sessionId: "w1", msgId: "m1", from: "Worker & Co", summary: "Report" }, + ]); +}); diff --git a/apps/web/src/components/chat/blocks/subagentParse.ts b/apps/web/src/components/chat/blocks/subagentParse.ts index 5396e3de..094e1d18 100644 --- a/apps/web/src/components/chat/blocks/subagentParse.ts +++ b/apps/web/src/components/chat/blocks/subagentParse.ts @@ -61,6 +61,32 @@ export function parseSubagentResults( return out; } +const RETURN_ENV_RE = /<(ginno_subagent_result|ginno_plan_update|ginno_worker_result)\b([^>]*)>([\s\S]*?)<\/\1>/g; + +function parseReturnCards(text: string): Block[] { + const cards: Block[] = []; + for (const match of text.matchAll(RETURN_ENV_RE)) { + const [raw, tag, attrs, body] = match; + if (tag === "ginno_plan_update") { + const status = decodeEntities(body).trim(); + cards.push({ + kind: "plan_update", + planId: decodeEntities(/plan="([^"]*)"/.exec(attrs)?.[1] ?? ""), + text: status.split("You can:", 1)[0].trim() || status, + }); + } else if (tag === "ginno_worker_result") { + for (const result of parseWorkerResults(raw)) { + cards.push({ kind: "worker_result", ...result }); + } + } else { + for (const result of parseSubagentResults(raw)) { + cards.push({ kind: "subagent_result", ...result, goal: result.goal || undefined }); + } + } + } + return cards; +} + /** 单条结果标签(非合并场景)。 */ export function parseSubagentResult( text: string, @@ -131,33 +157,25 @@ export function parseWorkerResults( viaFile: boolean; filePath: string; }> { - const doc = parseEnvelope(text); - if (!doc) return []; - const out: Array<{ - sessionId: string; - msgId: string; - from: string; - status: string; - goal: string; - summary: string; - digest: boolean; - viaFile: boolean; - filePath: string; - }> = []; - for (const el of Array.from(doc.getElementsByTagName("ginno_worker_result"))) { - out.push({ - sessionId: el.getAttribute("session") ?? "", - msgId: el.getAttribute("msg_id") ?? "", - from: el.getAttribute("from") ?? "", - status: el.getAttribute("status") ?? "", - goal: el.getAttribute("goal") ?? "", - summary: (el.textContent ?? "").trim(), - digest: el.getAttribute("kind") === "digest", - viaFile: el.getAttribute("via_file") === "1", - filePath: el.getAttribute("file") ?? "", - }); - } - return out; + return Array.from(text.matchAll(/]*)>([\s\S]*?)<\/ginno_worker_result>/g), + ([, attrs, body]) => { + const attr = (name: string) => { + const match = new RegExp(String.raw`(?:^|\s)${name}\s*=\s*(?:"([^"]*)"|'([^']*)')`).exec(attrs); + return decodeEntities(match?.[1] ?? match?.[2] ?? ""); + }; + return { + sessionId: attr("session"), + msgId: attr("msg_id"), + from: attr("from"), + status: attr("status"), + goal: attr("goal"), + summary: decodeEntities(body).trim(), + digest: attr("kind") === "digest", + viaFile: attr("via_file") === "1", + filePath: attr("file"), + }; + }, + ); } /** assign_worker 注入的 :worker 会话侧的任务简报 @@ -219,22 +237,9 @@ export function foldSubagentResultBlocks(blocks: Block[]): Block[] { out.push(b); continue; } - // 清单状态信封(plan-orchestration §4):折专用清单卡(同一注入通道, - // child key 是 plan-),与结果卡区分开。 - const planDoc = parseEnvelope(b.text); - const planEls = planDoc - ? Array.from(planDoc.getElementsByTagName("ginno_plan_update")) - : []; - if (planEls.length) { - for (const el of planEls) { - const raw = (el.textContent ?? "").trim(); - const body = raw.split("You can:", 1)[0].trim() || raw; - out.push({ - kind: "plan_update", - planId: el.getAttribute("plan") ?? "", - text: body, - }); - } + const returns = parseReturnCards(b.text); + if (returns.length) { + out.push(...returns); continue; } const brief = parseSubagentBrief(b.text); @@ -242,31 +247,12 @@ export function foldSubagentResultBlocks(blocks: Block[]): Block[] { out.push({ kind: "subagent_brief", ...brief }); continue; } - // worker 协议信封(worker-protocol-design §7):员工任务简报 / 回传 - // 折专用卡——检查在 subagent 结果信封之前(两类信封互斥)。 + // worker 协议信封(worker-protocol-design §7):员工任务简报。 const wAssign = parseWorkerAssign(b.text); if (wAssign) { out.push({ kind: "worker_assign", ...wAssign }); continue; } - const wResults = parseWorkerResults(b.text); - if (wResults.length) { - for (const r of wResults) { - out.push({ - kind: "worker_result", - sessionId: r.sessionId, - msgId: r.msgId || undefined, - from: r.from || undefined, - status: r.status || undefined, - goal: r.goal || undefined, - summary: r.summary, - digest: r.digest, - viaFile: r.viaFile || undefined, - filePath: r.filePath || undefined, - }); - } - continue; - } // 旧版委托注入(2026-10-05 信封化之前落库的):裸机器头 + delegation= // 溯源行的 HumanMessage——同样折成结果卡(sessionId 取溯源行),重载后 // 不再以原始文本气泡出现。goal 无从恢复,卡片标题退回 backend。 @@ -290,19 +276,7 @@ export function foldSubagentResultBlocks(blocks: Block[]): Block[] { }); continue; } - const results = parseSubagentResults(b.text); - if (!results.length) { - out.push(b); - continue; - } - for (const r of results) { - out.push({ - kind: "subagent_result", - sessionId: r.sessionId, - goal: r.goal || undefined, - summary: r.summary, - }); - } + out.push(b); } return out; } diff --git a/apps/web/src/components/chat/engine/handlers/02-turn-start.ts b/apps/web/src/components/chat/engine/handlers/02-turn-start.ts index 3acc0673..369f17d5 100644 --- a/apps/web/src/components/chat/engine/handlers/02-turn-start.ts +++ b/apps/web/src/components/chat/engine/handlers/02-turn-start.ts @@ -4,7 +4,7 @@ import type { EngineCtx } from "../ctx"; import type { ServerEvent } from "./types"; import { omitRepeatedResults } from "../../blocks/subagentParse"; -import { foldSubagentResultBlocks } from "@/components/chat/blocks"; +import { foldSubagentResultBlocks, type Block } from "@/components/chat/blocks"; import type { ChatMsg } from "../../streamCore"; import { mid } from "../../streamCore"; import { ensureLive, markDelivered, upsertTurnMeta } from "../liveBubble"; @@ -68,6 +68,25 @@ export function onTurnStart(ctx: EngineCtx, sid: string, ev: ServerEvent) { : msg, ); } + if (srvTurn && Array.isArray(ev.task_events)) { + const blocks: Block[] = ev.task_events.flatMap((task) => + task && typeof task.task === "string" ? [{ + kind: "task_event" as const, + taskId: task.task, + ev: String(task.kind || ""), + title: String(task.title || ""), + exit: task.exit ?? null, + dur: String(task.dur || ""), + }] : [], + ); + const eventId = `${srvTurn}-task-events`; + const store = ctx.storeRef.current[sid] ?? []; + if (blocks.length && !store.some((msg) => msg.id === eventId)) { + ctx.storeRef.current[sid] = store.flatMap((msg) => + msg.id === id ? [{ id: eventId, role: "system" as const, blocks }, msg] : [msg], + ); + } + } // 渠道轮次回显(engine 端 echo_user 标记,turn.start 带 text/images): // 桌面端没有 composer 的乐观气泡,IM 侧输入只能靠服务端回传才显示。 // id 与 turnId 同用服务端 turnId——与 history 的 user 消息 id==turnId diff --git a/apps/web/src/components/chat/stream/TranscriptList.tsx b/apps/web/src/components/chat/stream/TranscriptList.tsx index afdf5ba3..40a266b4 100644 --- a/apps/web/src/components/chat/stream/TranscriptList.tsx +++ b/apps/web/src/components/chat/stream/TranscriptList.tsx @@ -440,7 +440,8 @@ export function TranscriptList({ // (它不认识这些块,会渲染成空气泡)。worker 协议信封 // (/)同通道同处理。
-
+
+ str | None: return None -_RESULT_ENV_RE = re.compile( - r"]*)>(.*?)", re.S +_RETURN_ENV_RE = re.compile( + r"<(?Pginno_subagent_result|ginno_plan_update|ginno_worker_result)\b([^>]*)>(.*?)", re.S ) -_PLAN_ENV_RE = re.compile( - r"]*)>(.*?)", re.S -) - - -def _plan_update_blocks(content: Any) -> list[dict] | None: - """清单状态注入信封(plan-orchestration §4/§8 P3)折成专用清单卡,而非 - 子代理结果卡或裸 steering 带。与 _subagent_result_blocks 同一入口分支 - 调用(注入消息都带 ginno_subagent_result kw,child key 是 plan-)。""" - if isinstance(content, str): - text = content - elif isinstance(content, list): - text = "\n".join( - p.get("text") or "" - for p in content - if isinstance(p, dict) and p.get("type") == "text" - ) - else: - return None - out: list[dict] = [] - for m in _PLAN_ENV_RE.finditer(text): - am = re.search(r'plan="([^"]*)"', m.group(1)) - raw = html.unescape(m.group(2)).strip() - # 模型侧行动菜单("You can: …"尾段)是给主 agent 的指令,卡片只展示 - # 状态行;找不到结构分界则整段展示,宁多勿丢。 - body = raw.split("You can:", 1)[0].strip() or raw - out.append( - { - "kind": "plan_update", - "planId": html.unescape(am.group(1)) if am else "", - "text": body, - } - ) - return out or None - -def _subagent_result_blocks(content: Any) -> list[dict] | None: - """runtime 注入的子代理结果(契约 3)折成结果卡,而不是原始 XML 当 - steering 带直出(2026-10-12 真机:t17 delegation 回传整段信封裸渲染)。 - - 注入消息同时带 ginno_steer kw(steer_messages 合并盖的章),必须在 - steer 带分支【前】检查。合并注入时一条消息可带多个信封——逐个解析, - 每张一张卡;一个都解析不出则回 None(落回 steer 带渲染,防御旧形状)。 - 属性与正文的转义由 runtime 侧 _xml_attr/_xml_text 负责,这里 - html.unescape 是前端 DOMParser 解码的镜像。""" +def _return_envelope_blocks(content: Any) -> list[dict]: + """Fold all return envelopes in the order they were injected.""" if isinstance(content, str): text = content elif isinstance(content, list): text = "\n".join( - p.get("text") or "" - for p in content + p.get("text") or "" for p in content if isinstance(p, dict) and p.get("type") == "text" ) else: - return None + return [] out: list[dict] = [] - for m in _RESULT_ENV_RE.finditer(text): + for m in _RETURN_ENV_RE.finditer(text): + tag, attrs, raw = m.groups() - def attr(name: str, attrs: str = m.group(1)) -> str: - am = re.search(rf'{name}="([^"]*)"', attrs) - return html.unescape(am.group(1)) if am else "" + def attr(name: str, attrs: str = attrs) -> str: + am = re.search(rf"""(?:^|\s){name}\s*=\s*(?:"([^"]*)"|'([^']*)')""", attrs) + return html.unescape(am.group(1) or am.group(2) or "") if am else "" - out.append( - { + body = html.unescape(raw).strip() + if tag == "ginno_plan_update": + # The action menu is model scaffolding, outside the status card. + out.append({ + "kind": "plan_update", + "planId": attr("plan"), + "text": body.split("You can:", 1)[0].strip() or body, + }) + elif tag == "ginno_worker_result": + out.append({ + "kind": "worker_result", + "sessionId": attr("session"), + "msgId": attr("msg_id"), + "from": attr("from"), + "status": attr("status"), + "goal": attr("goal"), + "summary": body, + "digest": attr("kind") == "digest", + "viaFile": attr("via_file") == "1", + "filePath": attr("file"), + }) + else: + out.append({ "kind": "subagent_result", "sessionId": attr("session"), "goal": attr("goal"), - "summary": html.unescape(m.group(2)).strip(), - } - ) - return out or None + "summary": body, + }) + return out + + +def _task_event_blocks(kwargs: dict) -> list[dict]: + events = kwargs.get("ginno_task_events") + if not isinstance(events, list): + events = [kwargs.get("ginno_task_event")] + return [ + { + "kind": "task_event", + "taskId": str(event["task"]), + "ev": str(event.get("kind") or ""), + "title": str(event.get("title") or ""), + "exit": event.get("exit"), + "dur": str(event.get("dur") or ""), + } + for event in events if isinstance(event, dict) and event.get("task") + ] def _steer_band_blocks(content: Any, steer_kw: dict) -> list[dict]: @@ -1006,14 +1001,12 @@ def flush_assistant() -> None: # the assistant bubble either. One turn is ONE bubble, and the # injection point renders as a full-width band inside it (§4.2/§4.3), # so the band joins the open accumulator instead of flushing it. - steer_kw = (getattr(m, "additional_kwargs", None) or {}).get("ginno_steer") + kwargs = m.additional_kwargs + steer_kw = kwargs.get("ginno_steer") # runtime 注入的子代理结果也带 ginno_steer(steer_messages 合并), # 但它该折结果卡而非 steer 带——先于 steer 分支检查(契约 3)。 - res_kw = (getattr(m, "additional_kwargs", None) or {}).get( - "ginno_subagent_result" - ) - if res_kw: - cards = _subagent_result_blocks(content_raw) or _plan_update_blocks(content_raw) + if kwargs.get("ginno_subagent_result"): + cards = _return_envelope_blocks(content_raw) if cards: # 子代理结果与下面的 task_event 一样是**新 turn 的触发器** # (回传→父会话开新 turn),先 flush 上一泡再挂 pending—— @@ -1027,25 +1020,15 @@ def flush_assistant() -> None: # taskId 折进同 transcript 里 bg_run 的常驻卡片;找不到卡片(很老 # 的历史/卡片被清)时兜底渲染一行完成带。先于 steer 分支(steer # 路径注入的消息同时带 ginno_steer 戳)。 - task_kw = (getattr(m, "additional_kwargs", None) or {}).get( - "ginno_task_event" - ) - if isinstance(task_kw, dict) and task_kw.get("task"): - blk = { - "kind": "task_event", - "taskId": str(task_kw.get("task") or ""), - "ev": str(task_kw.get("kind") or ""), - "title": str(task_kw.get("title") or ""), - "exit": task_kw.get("exit"), - "dur": str(task_kw.get("dur") or ""), - } + task_blocks = _task_event_blocks(kwargs) + if task_blocks: # 回执是**新 turn 的触发器**(bg 完成→新 turn),live 视图里 # 下一段流式在新气泡里跑——回放必须先 flush 上一泡,否则把 # 新 turn 的内容焊进旧气泡(2026-11-18 实锤:[task finished] # 后的 PR 合并 turn 焊进上一 turn,111 块巨无霸)。flush 后 # pending_bands 让回执挂到新气泡头部。 flush_assistant() - pending_bands.append([blk]) + pending_bands.append(task_blocks) continue if steer_kw: group = _steer_band_blocks(content_raw, steer_kw) diff --git a/packages/runtime/src/ginno_runtime/api/stream/stages/run.py b/packages/runtime/src/ginno_runtime/api/stream/stages/run.py index 620f79c6..e42c1dcc 100644 --- a/packages/runtime/src/ginno_runtime/api/stream/stages/run.py +++ b/packages/runtime/src/ginno_runtime/api/stream/stages/run.py @@ -342,6 +342,9 @@ async def _emit_turn_start(ctx: StreamTurnCtx) -> None: for i in _echo_imgs if isinstance(i, dict) and i.get("data") ] + task_events = ctx._cfg_conf.get("task_events") + if task_events: + _ts_payload["task_events"] = task_events await ctx.safe_send(ctx.emit("turn.start", _ts_payload)) # Mods turn.start tap (claude-code-mods-design.md §5.3, same # position as the WS event): observe-only, zero-cost with no mod. diff --git a/packages/runtime/src/ginno_runtime/lastwords.py b/packages/runtime/src/ginno_runtime/lastwords.py index c437af03..4dccb027 100644 --- a/packages/runtime/src/ginno_runtime/lastwords.py +++ b/packages/runtime/src/ginno_runtime/lastwords.py @@ -149,7 +149,7 @@ def _is_injected(m: Any) -> bool: kw = getattr(m, "additional_kwargs", None) or {} return any( k in kw - for k in ("ginno_task_event", "ginno_steer", "ginno_lastwords", "ginno_subagent_result") + for k in ("ginno_task_event", "ginno_task_events", "ginno_steer", "ginno_lastwords", "ginno_subagent_result") ) diff --git a/packages/runtime/src/ginno_runtime/tasks/inject.py b/packages/runtime/src/ginno_runtime/tasks/inject.py index 5a8e76d5..df2f1565 100644 --- a/packages/runtime/src/ginno_runtime/tasks/inject.py +++ b/packages/runtime/src/ginno_runtime/tasks/inject.py @@ -202,17 +202,17 @@ async def _flush_after(session_id: str) -> None: return if len(entries) == 1: text = entries[0]["text"] - payload = entries[0]["payload"] + extra_kwargs = {"ginno_task_event": entries[0]["payload"]} else: text = ( f"{len(entries)} background task events arrived:\n\n" + "\n\n".join(e["text"] for e in entries) ) - payload = entries[-1]["payload"] # 带上最后一个事件的戳;文本里全量 - await _run_wake_turn(session_id, text, payload) + extra_kwargs = {"ginno_task_events": [e["payload"] for e in entries]} + await _run_wake_turn(session_id, text, extra_kwargs) -async def _run_wake_turn(session_id: str, text: str, payload: dict) -> None: +async def _run_wake_turn(session_id: str, text: str, extra_kwargs: dict) -> None: """镜像 sessions._run_goal_turn / subagent runner 的 headless turn。""" from ..api.sessions import _ensure_session, _first_agent_id from ..api.stream import _run_stream @@ -233,6 +233,7 @@ async def _run_wake_turn(session_id: str, text: str, payload: dict) -> None: "turn_id": turn_id, "user_text": text, "usage_source": "task", + "task_events": extra_kwargs.get("ginno_task_events") or [extra_kwargs["ginno_task_event"]], } } _RUNNING = shared._RUNNING_TURNS @@ -242,7 +243,7 @@ async def _run_wake_turn(session_id: str, text: str, payload: dict) -> None: try: await _run_stream( None, session["graph"], config, text, session, agent_id, - user_extra_kwargs={"ginno_task_event": payload}, + user_extra_kwargs=extra_kwargs, ) finally: reset_interactive(ask_tok) diff --git a/packages/runtime/tests/e2e/test_packaged_ui_coalesced_transcript.py b/packages/runtime/tests/e2e/test_packaged_ui_coalesced_transcript.py new file mode 100644 index 00000000..c9b475e5 --- /dev/null +++ b/packages/runtime/tests/e2e/test_packaged_ui_coalesced_transcript.py @@ -0,0 +1,51 @@ +"""Coalesced callbacks retain all visible receipts in live chat and history.""" + +import pytest +from langchain_core.messages import AIMessage, HumanMessage +from playwright.sync_api import expect +from test_packaged_ui_transcript_event_rows import ( + app as app, + capture_socket, + open_session, + save_messages, + send_frame, + wait_for_session_socket, +) + +pytestmark = pytest.mark.e2e + +PLAN = 'Coalesced plan' +RESULT = 'Result details' +WORKER = 'Final report' +COMBINED = f"Below are the returns from 3 subagents:\n\n{PLAN}\n\n{RESULT}\n\n{WORKER}" +TASKS = [ + {"task": "t_batch1", "kind": "finished", "title": "First background event", "exit": 0}, + {"task": "t_batch2", "kind": "timeout", "title": "Second background event"}, +] + + +def test_mixed_callbacks_live_and_reloaded(app): + page, port, sid = app + capture_socket(page) + open_session(page, port, sid) + wait_for_session_socket(page, sid) + send_frame(page, sid, "turn.start", turn_id="batch-turn", agent_id="dev", text=COMBINED) + expect(page.get_by_text("Coalesced plan", exact=True)).to_be_visible() + expect(page.get_by_text("Subagent result · Coalesced result", exact=True)).to_be_visible() + expect(page.get_by_text("Worker return: BatchWorker", exact=True)).to_be_visible() + send_frame(page, sid, "turn.start", turn_id="batch-tasks", agent_id="dev", task_events=TASKS) + for task in TASKS: + expect(page.get_by_text(task["title"], exact=True)).to_be_visible() + + save_messages(sid, [ + HumanMessage(content=COMBINED, id="returns", additional_kwargs={"ginno_subagent_result": "plan-pl_batch,s_batch,w_batch"}), + AIMessage(content="Returned", id="returned"), + HumanMessage(content="Two background task events", id="tasks", additional_kwargs={"ginno_task_events": TASKS}), + AIMessage(content="Acknowledged", id="ack"), + ]) + open_session(page, port, sid) + expect(page.get_by_text("Coalesced plan", exact=True)).to_have_count(1) + expect(page.get_by_text("Subagent result · Coalesced result", exact=True)).to_have_count(1) + expect(page.get_by_text("Worker return: BatchWorker", exact=True)).to_have_count(1) + for task in TASKS: + expect(page.get_by_text(task["title"], exact=True)).to_have_count(1) diff --git a/packages/runtime/tests/unit/test_messages_ui_turn_split.py b/packages/runtime/tests/unit/test_messages_ui_turn_split.py index b68bf79c..a416b270 100644 --- a/packages/runtime/tests/unit/test_messages_ui_turn_split.py +++ b/packages/runtime/tests/unit/test_messages_ui_turn_split.py @@ -93,3 +93,19 @@ def test_receipt_before_any_ai_renders_standalone_then_attaches(): bubbles = _bubbles(ui) assert len(bubbles) == 1 assert bubbles[0]["blocks"][0].get("kind") == "task_event" + + +def test_coalesced_plan_and_subagent_returns_keep_order(): + combined = HumanMessage( + id="batched-returns", + content=('Below are the returns from 2 subagents:\n\n' + 'Build done\n\n' + 'Result done'), + additional_kwargs={"ginno_subagent_result": "plan-pl_demo,s_demo"}, + ) + bubbles = _bubbles(_messages_to_ui([combined, AIMessage(content="ack")], None)) + assert bubbles[0]["blocks"] == [ + {"kind": "plan_update", "planId": "pl_demo", "text": "Build done"}, + {"kind": "subagent_result", "sessionId": "s_demo", "goal": "", "summary": "Result done"}, + {"kind": "text", "text": "ack"}, + ] diff --git a/packages/runtime/tests/unit/test_plan_orchestration.py b/packages/runtime/tests/unit/test_plan_orchestration.py index c82d320d..70a22c71 100644 --- a/packages/runtime/tests/unit/test_plan_orchestration.py +++ b/packages/runtime/tests/unit/test_plan_orchestration.py @@ -426,7 +426,9 @@ async def test_plan_command_list_and_cancel(isolated_home): def test_plan_update_envelope_blocks(isolated_home): """ 信封 → 专用 plan_update 块(区别于结果卡/裸带)。""" - from ginno_runtime.api.messages_ui import _plan_update_blocks + from langchain_core.messages import HumanMessage + + from ginno_runtime.api.messages_ui import _messages_to_ui content = ( '\n' @@ -435,13 +437,17 @@ def test_plan_update_envelope_blocks(isolated_home): "You can: verify the above results.\n" "" ) - blocks = _plan_update_blocks(content) + def blocks_for(text: str) -> list[dict]: + message = HumanMessage(content=text, additional_kwargs={"ginno_subagent_result": "plan-pl_x"}) + return _messages_to_ui([message], None)[0]["blocks"] + + blocks = blocks_for(content) assert blocks and blocks[0]["kind"] == "plan_update" assert blocks[0]["planId"] == "pl_x" assert "[done] it_1 ok" in blocks[0]["text"] # 行动菜单尾段是模型指令,不进卡片 assert "You can" not in blocks[0]["text"] - assert _plan_update_blocks("plain text") is None + assert blocks_for("plain text") == [{"kind": "text", "text": "plain text"}] async def test_do_flush_wraps_plan_envelope(isolated_home, monkeypatch): diff --git a/packages/runtime/tests/unit/test_tasks.py b/packages/runtime/tests/unit/test_tasks.py index 637895de..2414e79e 100644 --- a/packages/runtime/tests/unit/test_tasks.py +++ b/packages/runtime/tests/unit/test_tasks.py @@ -518,3 +518,38 @@ def try_get(self, task_id): with pytest.raises(HTTPException) as ei: tasks_api._task_or_404("t_gone") assert ei.value.status_code == 404 + + +async def test_idle_coalescing_projects_every_event_in_order(isolated_home, monkeypatch): + from langchain_core.messages import AIMessage, HumanMessage + + import ginno_runtime.api.sessions as sessions_api + import ginno_runtime.api.stream as stream_api + from ginno_runtime import server_shared as shared + from ginno_runtime.api.messages_ui import _messages_to_ui + + sid = "test-task-batch" + session = {"agent_id": "dev", "project_slug": "default", "graph": object()} + monkeypatch.setitem(shared._SESSIONS, sid, session) + monkeypatch.setattr(sessions_api, "_ensure_session", lambda session_id: session) + monkeypatch.setattr(task_inject, "COALESCE_S", 0) + messages = [] + stream_events = [] + + async def fake_run_stream(ws, graph, config, text, live_session, agent_id, *, user_extra_kwargs): + messages.append(HumanMessage(content=text, additional_kwargs=user_extra_kwargs)) + stream_events.extend(config["configurable"]["task_events"]) + + monkeypatch.setattr(stream_api, "_run_stream", fake_run_stream) + for tid, kind in [("t_batch1", "finished"), ("t_batch2", "timeout")]: + task_inject.on_task_event( + {"id": tid, "title": tid, "origin_session": sid, "exit_code": 0, "dur": "1s"}, kind, + ) + await task_inject._FLUSH_TASKS[sid] + assert len(messages) == 1 + assert [event["task"] for event in stream_events] == ["t_batch1", "t_batch2"] + assert "t_batch1" in messages[0].content and "t_batch2" in messages[0].content + blocks = _messages_to_ui([*messages, AIMessage(content="ack")], None)[0]["blocks"] + assert [(b["taskId"], b["ev"]) for b in blocks if b["kind"] == "task_event"] == [ + ("t_batch1", "finished"), ("t_batch2", "timeout"), + ]