From 72b03a97f617067f81966185f4ea87d6ecb5fda3 Mon Sep 17 00:00:00 2001 From: ChuanchuanSong Date: Mon, 23 Nov 2026 08:09:15 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E5=90=8E=E7=9A=84=E6=B6=88=E6=81=AF=E6=A0=87=E8=AE=B0=E5=B9=B6?= =?UTF-8?q?=E6=B8=B2=E6=9F=93=E7=8B=AC=E7=AB=8B=E5=9B=9E=E6=89=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 现象 审计缺口 1、2、3、8。历史压缩后,后台完成回执只露日志尾巴,团队投递标记消失。没有助手气泡可挂载时,后台回执和清单更新整行看不到。 ## 根因 压缩给保留的 HumanMessage 重分配 ID 时只复制了正文。主聊天系统行与用户行未消费 task_event 和 plan_update,旧任务日志被当成普通用户正文。 ## 修复 复制保留 HumanMessage 标记。主聊天支持独立后台回执及清单状态行。旧完成回执的日志尾部默认折叠,仍可按需展开。合并回传和旧版恢复信封另批处理。 ## 验证 - 4 个元数据回归在原实现全部失败,修复后通过。压缩、微压缩和历史相关 pytest 共 52 通过,Ruff 通过。 - 主聊天真实 Chromium 3 例由红转绿。用临时会话与真实 checkpoint 验证新压缩和旧格式回放,用会话 WS 注入帧验证系统行与唤醒回执行。 - tsc、全量 Vitest 2103 例、Next 静态构建通过。 --- apps/web/src/components/chat/TaskCard.tsx | 79 ++++++----- .../chat/blocks/taskEventParse.test.ts | 6 +- .../components/chat/blocks/taskEventParse.ts | 13 +- apps/web/src/components/chat/blocks/types.ts | 2 +- .../components/chat/stream/TranscriptList.tsx | 19 +++ .../runtime/src/ginno_runtime/compaction.py | 2 +- .../test_packaged_ui_transcript_event_rows.py | 131 ++++++++++++++++++ .../runtime/tests/unit/test_compaction.py | 15 ++ 8 files changed, 219 insertions(+), 48 deletions(-) create mode 100644 packages/runtime/tests/e2e/test_packaged_ui_transcript_event_rows.py diff --git a/apps/web/src/components/chat/TaskCard.tsx b/apps/web/src/components/chat/TaskCard.tsx index 5fd2ee18..ab62f1d9 100644 --- a/apps/web/src/components/chat/TaskCard.tsx +++ b/apps/web/src/components/chat/TaskCard.tsx @@ -20,6 +20,7 @@ import { TASK_TERMINAL, type TaskRecord, } from "@/lib/runtime"; +import type { Block } from "./blocks/types"; import { useChatT } from "./blocks/i18n"; /** bg_run 结果文本的机器头:``task=t_xxxxxxxx status=running pid=123``。 */ @@ -264,7 +265,7 @@ function fetchTaskOnce(tid: string): Promise { return p; } -export function TaskEventBand({ block }: { block: { taskId: string; ev: string; title?: string; exit?: number | null; dur?: string } }) { +export function TaskEventBand({ block }: { block: Extract }) { const { tc } = useChatT(); const [task, setTask] = useState(null); const [hover, setHover] = useState(false); @@ -287,41 +288,49 @@ export function TaskEventBand({ block }: { block: { taskId: string; ev: string; : block.ev; const showCard = hover && !!task?.command; return ( -
{ - setHover(true); - if (REAL_TID_RE.test(block.taskId)) { - void fetchTaskOnce(block.taskId).then((t) => { - // 缓存可能来自更早的轮询(任务那时还 running)——终态字段以 - // 事件行为准展示,这里只取 command/cwd,不覆盖行内状态。 - if (t) setTask(t); - }); - } - }} - onMouseLeave={() => setHover(false)} - > - ▸ - - {label} · {block.title || block.taskId} - {block.dur ? ` · ${block.dur}` : ""} - - {showCard && ( -
-
- $ {task!.command} -
- {task!.cwd ? ( -
- cwd: {task!.cwd} +
+
{ + setHover(true); + if (REAL_TID_RE.test(block.taskId)) { + void fetchTaskOnce(block.taskId).then((t) => { + // 缓存可能来自更早的轮询(任务那时还 running)——终态字段以 + // 事件行为准展示,这里只取 command/cwd,不覆盖行内状态。 + if (t) setTask(t); + }); + } + }} + onMouseLeave={() => setHover(false)} + > + ▸ + + {label} · {block.title || block.taskId} + {block.dur ? ` · ${block.dur}` : ""} + + {showCard && ( +
+
+ $ {task!.command}
- ) : null} -
+ {task!.cwd ? ( +
+ cwd: {task!.cwd} +
+ ) : null} +
+ )} +
+ {block.log && ( +
+ {tc("taskCard.outputTail")} +
{block.log}
+
)}
); diff --git a/apps/web/src/components/chat/blocks/taskEventParse.test.ts b/apps/web/src/components/chat/blocks/taskEventParse.test.ts index 4af16f25..ef622633 100644 --- a/apps/web/src/components/chat/blocks/taskEventParse.test.ts +++ b/apps/web/src/components/chat/blocks/taskEventParse.test.ts @@ -5,7 +5,7 @@ import { foldTaskEventBlocks } from "./taskEventParse"; // 样例取自 runtime tasks/inject.py STATUS_TEXT 的真实格式(2026-11-07 会话 // dev-swap-retry-120s 任务的 #keep 消息原文)。 describe("foldTaskEventBlocks", () => { - it("finished 带解析出 taskId/exit/dur,tail 保留为 text block", () => { + it("finished 带解析出 taskId/exit/dur,tail 作为可展开日志保留", () => { const src = [ { kind: "text" as const, @@ -13,14 +13,14 @@ describe("foldTaskEventBlocks", () => { }, ]; const out = foldTaskEventBlocks(src); - expect(out).toHaveLength(2); + expect(out).toHaveLength(1); const tev = out[0] as { kind: string; taskId: string; ev: string; exit: number; dur: string }; expect(tev.kind).toBe("task_event"); expect(tev.taskId).toBe("t_1218152f"); expect(tev.ev).toBe("finished"); expect(tev.exit).toBe(2); expect(tev.dur).toBe("2m 00s"); - expect((out[1] as { text: string }).text).toContain('{"ok":true}'); + expect(out[0]).toMatchObject({ log: expect.stringContaining('{"ok":true}') }); }); it("failed to start 带(无 exit/dur)折为 failed_to_start", () => { diff --git a/apps/web/src/components/chat/blocks/taskEventParse.ts b/apps/web/src/components/chat/blocks/taskEventParse.ts index 3cb47c6a..f8382bff 100644 --- a/apps/web/src/components/chat/blocks/taskEventParse.ts +++ b/apps/web/src/components/chat/blocks/taskEventParse.ts @@ -2,8 +2,7 @@ import type { Block } from "./types"; // 后台任务事件注入带(runtime tasks/inject.py 的原文首行)在历史重放时折成 // 极薄 task_event 标记行——与 live 侧 steer.absorbed 的 ginno_task_event 折卡 -// 对齐(handle.ts「绝不渲染 "[task finished]…" 原文带」)。tail 输出保留为 -// 后续 text block(任务 store 滚动清理后 TaskCard 不一定还在,不能丢信息)。 +// 对齐。旧记录的 tail 留在状态块里,默认折叠,任务记录清理后仍可展开。 // // 注入带两种形态(inject.py STATUS_TEXT): // [task finished] "{title}" ({tid}) exit {code} · ran {dur} @@ -50,6 +49,8 @@ export function foldTaskEventBlocks(blocks: Block[]): Block[] { const [, evRaw, title, taskId, rest = ""] = m; const exit = / exit (-?\d+)/.exec(rest)?.[1]; const dur = / · ran (.+?)(?:\n|$)/.exec(rest)?.[1]; + const nl = b.text.indexOf("\n"); + const log = nl < 0 ? "" : b.text.slice(nl + 1).trim(); out.push({ kind: "task_event", taskId, @@ -57,12 +58,8 @@ export function foldTaskEventBlocks(blocks: Block[]): Block[] { title, ...(exit != null ? { exit: Number(exit) } : {}), ...(dur != null ? { dur } : {}), - } as Block); - // tail(--- tail --- 之后的输出与 Full log 行)保留为普通 text block - const nl = b.text.indexOf("\n"); - if (nl >= 0 && b.text.slice(nl + 1).trim()) { - out.push({ kind: "text", text: b.text.slice(nl + 1) }); - } + ...(log ? { log } : {}), + }); } return out; } diff --git a/apps/web/src/components/chat/blocks/types.ts b/apps/web/src/components/chat/blocks/types.ts index d3dec62b..9f12442a 100644 --- a/apps/web/src/components/chat/blocks/types.ts +++ b/apps/web/src/components/chat/blocks/types.ts @@ -125,7 +125,7 @@ export type Block = // 同 transcript 里 bg_run 的常驻 TaskCard 承载(toolBlocks 特判渲染)。 // ev: finished|stopped|timeout|interrupted|failed_to_start|healthy|watch。 | { kind: "task_event"; taskId: string; ev: string; title?: string; - exit?: number | null; dur?: string } + exit?: number | null; dur?: string; log?: string } // 拆分方案卡片(P2 共享契约 1/2):由 subagent.plan WS 事件驱动(live 追加, // 不持久化——未确认的方案没有落 checkpoint 的意义)。组件本体在 // subagentPlanCard.tsx(本文件已超 1600 行,卡片不再往里塞)。 diff --git a/apps/web/src/components/chat/stream/TranscriptList.tsx b/apps/web/src/components/chat/stream/TranscriptList.tsx index f9d2115a..afdf5ba3 100644 --- a/apps/web/src/components/chat/stream/TranscriptList.tsx +++ b/apps/web/src/components/chat/stream/TranscriptList.tsx @@ -18,6 +18,8 @@ import { LastwordsCard, type Block, } from "@/components/chat/blocks"; +import { TaskEventBand } from "../TaskCard"; +import { PlanUpdateCard } from "../blocks/subagentCards"; import { SubagentPlanCard } from "../subagentPlanCard"; import { TeamReplyCard, requestOpenMemberWorkspace } from "../TeamReplyCard"; import { stashOpenMemberIntent } from "@/components/team/openMemberIntent"; @@ -44,6 +46,18 @@ import { sliceStart, } from "@/lib/transcriptSlices"; +function isIndependentEvent(block: Block): block is Extract { + return block.kind === "task_event" || block.kind === "plan_update"; +} + +function IndependentEvents({ blocks }: { blocks: Block[] }) { + return blocks.filter(isIndependentEvent).map((block, index) => ( + block.kind === "task_event" + ? + : + )); +} + export function TranscriptList({ messages, session, @@ -382,6 +396,7 @@ export function TranscriptList({ 任何一方的气泡,是事件驱动的系统行。subagent_spawn 卡已停渲染 (顶部 SubagentBoard 接管,见文件头注释)。 */}
+ {m.blocks .filter((b): b is Extract => b.kind === "subagent_plan") .map((b) => ( @@ -407,6 +422,10 @@ export function TranscriptList({ />
+ ) : m.role === "user" && m.blocks.every(isIndependentEvent) && m.blocks.length > 0 ? ( +
+ +
) : m.role === "user" && m.blocks.some( (b) => diff --git a/packages/runtime/src/ginno_runtime/compaction.py b/packages/runtime/src/ginno_runtime/compaction.py index 6c34176e..205e81da 100644 --- a/packages/runtime/src/ginno_runtime/compaction.py +++ b/packages/runtime/src/ginno_runtime/compaction.py @@ -196,7 +196,7 @@ def find_split_index(messages: list[BaseMessage], keep_turns: int) -> int: def _copy_with_new_id(m: BaseMessage) -> BaseMessage: new_id = f"keep_{uuid.uuid4().hex[:10]}" if isinstance(m, HumanMessage): - return HumanMessage(content=m.content, id=new_id) + return m.model_copy(update={"id": new_id, "additional_kwargs": dict(m.additional_kwargs)}) if isinstance(m, ToolMessage): return ToolMessage( content=m.content, diff --git a/packages/runtime/tests/e2e/test_packaged_ui_transcript_event_rows.py b/packages/runtime/tests/e2e/test_packaged_ui_transcript_event_rows.py new file mode 100644 index 00000000..b0107b6d --- /dev/null +++ b/packages/runtime/tests/e2e/test_packaged_ui_transcript_event_rows.py @@ -0,0 +1,131 @@ +"""Background task and plan updates stay visible as independent transcript rows.""" + +import uuid +from datetime import datetime, timezone + +import pytest +import test_packaged_ui_tasks_overview as harness +from langchain_core.messages import HumanMessage +from playwright.sync_api import expect, sync_playwright + +from ginno_runtime.checkpointer import FileCheckpointer +from ginno_runtime.compaction import _copy_with_new_id + +pytestmark = pytest.mark.e2e + + +@pytest.fixture +def app(tmp_path): + harness._require_runtime() + port = harness._free_port() + proc, log = harness._spawn(tmp_path, port) + try: + harness._wait_health(port) + session = harness._api(port, "POST", "/api/sessions", { + "project_slug": "default", "workspace": str(tmp_path), "title": "Transcript event rows", + }) + with sync_playwright() as pw: + browser, page = harness._new_page(pw) + try: + yield page, port, session["id"] + finally: + browser.close() + finally: + harness._stop(proc, log) + + +def open_session(page, port, sid): + page.goto(f"http://127.0.0.1:{port}/", wait_until="load") + page.wait_for_function('typeof window.__ginnoOpenSession === "function"') + page.evaluate("sid => window.__ginnoOpenSession(sid)", sid) + + +def save_messages(sid, messages): + FileCheckpointer("default").put( + {"configurable": {"thread_id": sid, "project_slug": "default"}}, + { + "v": 4, "id": str(uuid.uuid4()), "ts": datetime.now(timezone.utc).isoformat(), + "channel_values": {"messages": messages}, + "channel_versions": {"messages": 1}, "versions_seen": {}, + "updated_channels": ["messages"], + }, + {"source": "loop", "step": 1, "parents": {}}, + {"messages": 1}, + ) + + +@pytest.mark.parametrize("legacy", [False, True], ids=["compacted-with-metadata", "legacy"]) +def test_task_and_plan_after_reload(app, legacy): + page, port, sid = app + title = "Transcript build receipt" + log_text = "transcript-build-log-sentinel" + task = HumanMessage( + id="task-turn", content=(f'[task finished] "{title}" (t_audit1) exit 0 · ran 1s\n' + f"--- tail ---\n{log_text}\n--- end ---\nFull log: /tmp/build.log"), + additional_kwargs={"ginno_task_event": {"task": "t_audit1", "kind": "finished", "title": title, "exit": 0}}, + ) + plan = HumanMessage( + id="plan-turn", content='Plan receipt sentinel', + additional_kwargs={"ginno_subagent_result": "plan-pl_audit"}, + ) + if legacy: + # Existing checkpoints written before the fix already lack additional_kwargs. + task = HumanMessage(content=task.content, id="keep_legacy_task") + plan = HumanMessage(content=plan.content, id="keep_legacy_plan") + else: + task, plan = _copy_with_new_id(task), _copy_with_new_id(plan) + save_messages(sid, [task, plan]) + open_session(page, port, sid) + + expect(page.get_by_text(title, exact=True)).to_be_visible(timeout=15_000) + expect(page.get_by_text("Task finished · exit 0", exact=False)).to_have_count(1) + expect(page.get_by_text("Plan status update", exact=True)).to_have_count(1) + expect(page.get_by_text("Plan receipt sentinel", exact=True)).to_be_visible() + expect(page.get_by_text(log_text, exact=False)).not_to_be_visible() + if legacy: + page.locator("details", has_text=log_text).locator("summary").click() + expect(page.get_by_text(log_text, exact=False)).to_be_visible() + + +def capture_socket(page): + page.add_init_script(''' + window.__transcriptTestSockets = []; + const OriginalWebSocket = window.WebSocket; + window.WebSocket = class extends OriginalWebSocket { + constructor(...args) { + super(...args); + window.__transcriptTestSockets.push(this); + } + }; + ''') + + +def wait_for_session_socket(page, sid): + page.wait_for_function('''sid => window.__transcriptTestSockets.some(ws => + new URL(ws.url).pathname.endsWith('/' + sid) && ws.readyState === WebSocket.OPEN)''', arg=sid) + + +def send_frame(page, sid, event, **payload): + page.evaluate('''([sid, frame]) => { + const ws = window.__transcriptTestSockets.find(ws => + new URL(ws.url).pathname.endsWith('/' + sid) && ws.readyState === WebSocket.OPEN); + ws.dispatchEvent(new MessageEvent('message', {data: JSON.stringify(frame)})); + }''', [sid, {"event": event, **payload}]) + + +def test_independent_event_rows_from_stream(app): + page, port, sid = app + capture_socket(page) + open_session(page, port, sid) + wait_for_session_socket(page, sid) + send_frame(page, sid, "steer.absorbed", steer_id="bg-fixture", + task={"task": "t_live", "kind": "finished", "title": "Live background receipt", "exit": 0}) + send_frame(page, sid, "steer.absorbed", steer_id="plan-fixture", + text='Live system plan receipt') + send_frame(page, sid, "turn.start", turn_id="turn-fixture", agent_id="dev", + text='Live wake plan receipt') + + expect(page.get_by_text("Live background receipt", exact=True)).to_be_visible() + expect(page.get_by_text("Live system plan receipt", exact=True)).to_be_visible() + expect(page.get_by_text("Live wake plan receipt", exact=True)).to_be_visible() + expect(page.get_by_text("Plan status update", exact=True)).to_have_count(2) diff --git a/packages/runtime/tests/unit/test_compaction.py b/packages/runtime/tests/unit/test_compaction.py index 4214a6aa..7cf3b3b2 100644 --- a/packages/runtime/tests/unit/test_compaction.py +++ b/packages/runtime/tests/unit/test_compaction.py @@ -136,6 +136,21 @@ def test_copy_with_new_id_preserves_content_and_changes_id(): assert tm2.tool_call_id == "c1" and tm2.id != "oldt" +@pytest.mark.parametrize("key,value", [ + ("ginno_task_event", {"task": "t_compact", "kind": "finished"}), + ("ginno_subagent_result", "plan-demo"), + ("ginno_team_delivery", {"team_id": "team-demo", "instance_id": "member-demo"}), + ("ginno_steer", {"steer_id": "steer-demo"}), +]) +def test_copy_with_new_id_preserves_human_message_markers(key, value): + message = HumanMessage(content="synthetic input", id="original", additional_kwargs={key: value}) + copied = _copy_with_new_id(message) + + assert copied.id != message.id + assert copied.additional_kwargs == {key: value} + assert copied.additional_kwargs is not message.additional_kwargs + + # --------------------------------------------------------------------------- # # end-to-end (graph level, no server) # --------------------------------------------------------------------------- #