diff --git a/apps/web/src/components/chat/TaskCard.tsx b/apps/web/src/components/chat/TaskCard.tsx index ab62f1d9..c4770c04 100644 --- a/apps/web/src/components/chat/TaskCard.tsx +++ b/apps/web/src/components/chat/TaskCard.tsx @@ -284,6 +284,9 @@ export function TaskEventBand({ block }: { block: Extract { expect(out).toHaveLength(1); }); - // 遗言恢复带(runtime lastwords.py render_band):首行折成 ev:"lastwords" - // 的 task_event 块(taskId 合成、title 取首行余下),正文保留为 text。 - describe("lastwords band", () => { - it("折为 ev=lastwords 的 task_event,title 带摘要", () => { - const out = foldTaskEventBlocks([ - { - kind: "text" as const, - text: "[lastwords] dev-swap 重启恢复:帮我跑一遍 dev-swap 验证遗言模式 · 旧指纹 abcdef123456 · 后台任务 2 个可收割(bg_logs)", - }, - ]); - expect(out).toHaveLength(1); - const tev = out[0] as { kind: string; taskId: string; ev: string; title: string }; - expect(tev.kind).toBe("task_event"); - expect(tev.ev).toBe("lastwords"); - expect(tev.taskId).toBe("lastwords"); - expect(tev.title).toContain("dev-swap 重启恢复"); - expect(tev.title).toContain("旧指纹 abcdef123456"); - }); - - it("auto 续跑模板多行:首行折带、正文保留", () => { - const src = [ - "[lastwords] dev-swap 重启恢复:修复构建 · 旧指纹 abc", - "", - "原始请求:修复构建", - "最后进展:跑到单测阶段", - ].join("\n"); - const out = foldTaskEventBlocks([{ kind: "text" as const, text: src }]); - expect(out).toHaveLength(2); - expect((out[0] as { ev: string }).ev).toBe("lastwords"); - expect((out[1] as { text: string }).text).toContain("原始请求:修复构建"); - }); + it("preserves the complete legacy lastwords envelope for LastwordsCard", () => { + const src = [{ kind: "text" as const, text: "[lastwords] Recovery\n\n原始请求:修复构建\n最后进展:跑到单测阶段" }]; + expect(foldTaskEventBlocks(src)).toEqual(src); + }); - it("不在行首的 [lastwords] 不折叠(正则不锚 $ 的同族坑)", () => { - const src = [ - { kind: "text" as const, text: "普通消息中间出现 [lastwords] 字样不该折" }, - ]; - expect(foldTaskEventBlocks(src)).toEqual(src); - }); + it.each([ + ["timeout", "timeout"], ["stopped by user", "stopped"], + ["interrupted by app quit", "interrupted"], ["watch", "watch"], + ["watch muted", "watch_muted"], ["healthy", "healthy"], + ])("folds the legacy %s event", (header, ev) => { + const text = `[task ${header}] "run \"build\"" (t_legacy) after 2m 05s`; + expect(foldTaskEventBlocks([{ kind: "text", text }])).toMatchObject([ + { kind: "task_event", taskId: "t_legacy", ev, title: 'run "build"' }, + ]); + }); - it("task 带优先于 lastwords 带(互不串扰)", () => { - const out = foldTaskEventBlocks([ - { kind: "text" as const, text: '[task finished] "x" (t_ab12) exit 0 · ran 1s' }, - ]); - expect((out[0] as { ev: string }).ev).toBe("finished"); - }); + it("recovers every legacy batched event and preserves unmatched text", () => { + const text = '[task timeout] "first" (t_first) after 1s — killed\n--- tail ---\nfirst log\n\n' + + '[task finished] "second" (t_second) exit 0 · ran 2s\n--- tail ---\nsecond log'; + const source = { kind: "text" as const, text: `2 background task events arrived:\n\n${text}` }; + expect(foldTaskEventBlocks([source])).toMatchObject([ + { kind: "task_event", taskId: "t_first", ev: "timeout", log: expect.stringContaining("first log") }, + { kind: "task_event", taskId: "t_second", ev: "finished", log: expect.stringContaining("second log") }, + ]); + const incomplete = { ...source, text: source.text.replace(/^2 /, "3 ") }; + expect(foldTaskEventBlocks([incomplete])).toEqual([incomplete]); }); }); diff --git a/apps/web/src/components/chat/blocks/taskEventParse.ts b/apps/web/src/components/chat/blocks/taskEventParse.ts index f8382bff..50470c0a 100644 --- a/apps/web/src/components/chat/blocks/taskEventParse.ts +++ b/apps/web/src/components/chat/blocks/taskEventParse.ts @@ -1,65 +1,54 @@ import type { Block } from "./types"; -// 后台任务事件注入带(runtime tasks/inject.py 的原文首行)在历史重放时折成 -// 极薄 task_event 标记行——与 live 侧 steer.absorbed 的 ginno_task_event 折卡 -// 对齐。旧记录的 tail 留在状态块里,默认折叠,任务记录清理后仍可展开。 -// -// 注入带两种形态(inject.py STATUS_TEXT): -// [task finished] "{title}" ({tid}) exit {code} · ran {dur} -// [task failed to start] "{title}" ({tid}) {note} -// 注:不带 m-flag 的 JS `$` 只匹配绝对串尾——注入带是多行(tail 在后), -// 故不锚 `$`;`(.*)` 不跨行,恰好吸收首行余下部分。 -const TASK_EVENT_BAND_RE = - /^\[task (finished|failed to start)\] "([^"]*)" \((t_[0-9a-zA-Z]+)\)(.*)/; +// Legacy checkpoints use the exact header templates from tasks/inject.py. +const STATUS = { + finished: "finished", + "failed to start": "failed_to_start", + "stopped by user": "stopped", + timeout: "timeout", + "interrupted by app quit": "interrupted", + healthy: "healthy", + watch: "watch", + "watch muted": "watch_muted", +} as const; +const statusPattern = Object.keys(STATUS).join("|"); +const taskHeader = String.raw`\[task (${statusPattern})\] "([^\r\n]*)" \((t_[0-9a-zA-Z]+)\)([^\r\n]*)`; +const TASK_HEADER_RE = new RegExp(`^${taskHeader}`); +const LEGACY_BATCH_RE = /^([2-9]|[1-9]\d+) background task events arrived:\n\n/; +const LEGACY_BATCH_SEPARATOR = new RegExp(String.raw`\n\n(?=\[task (?:${statusPattern})\] ")`); -// 遗言恢复带(runtime lastwords.py render_band 首行族): -// [lastwords] dev-swap 重启恢复:{摘要} · 旧指纹 abc123 · 后台任务 2 个可收割(bg_logs) -// 与 [task …] 族同构(首行前缀标记 + 余下摘要),折成 ev:"lastwords" 的 -// task_event 块;taskId 合成 "lastwords"(无 tid),title 取首行余下全文 -// (TaskEventBand 显示 title || taskId)。多行正文(auto 续跑模板)同样 -// 保留首行余下部分之后的正文为 text block——重放不露长原文由首行折叠保证。 -const LASTWORDS_BAND_RE = /^\[lastwords\] (.*)/; +function parseTaskEvent(text: string): Extract | undefined { + const match = TASK_HEADER_RE.exec(text); + if (!match) return; + const [, status, title, taskId, rest] = match; + const ev = STATUS[status as keyof typeof STATUS]; + const exit = / exit (-?\d+)/.exec(rest)?.[1]; + const dur = / · ran (.+)$| after (\d+(?:h|m|s)(?: \d+(?:m|s))?)(?= —|$)/.exec(rest); + const note = ["healthy", "watch", "watch_muted", "failed_to_start"].includes(ev) ? rest.trim() : ""; + const tail = text.slice(match[0].length).trim(); + const log = [note, tail].filter(Boolean).join("\n"); + return { + kind: "task_event", + taskId, + ev, + title, + ...(exit != null ? { exit: Number(exit) } : {}), + ...(dur ? { dur: dur[1] ?? dur[2] } : {}), + ...(log ? { log } : {}), + }; +} export function foldTaskEventBlocks(blocks: Block[]): Block[] { - const out: Block[] = []; - for (const b of blocks) { - if (b.kind !== "text" || typeof b.text !== "string") { - out.push(b); - continue; - } - const m = TASK_EVENT_BAND_RE.exec(b.text); - if (!m) { - const lw = LASTWORDS_BAND_RE.exec(b.text); - if (lw) { - out.push({ - kind: "task_event", - taskId: "lastwords", - ev: "lastwords", - title: lw[1], - } as 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) }); - } - continue; - } - out.push(b); - continue; + return blocks.flatMap((block): Block[] => { + if (block.kind !== "text") return [block]; + // Keep [lastwords] intact so TranscriptList can render the whole recovery receipt. + const batch = LEGACY_BATCH_RE.exec(block.text); + if (batch) { + const events = block.text.slice(batch[0].length).split(LEGACY_BATCH_SEPARATOR).map(parseTaskEvent); + if (events.length === Number(batch[1]) && events.every((event) => event !== undefined)) return events; + return [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, - ev: evRaw === "finished" ? "finished" : "failed_to_start", - title, - ...(exit != null ? { exit: Number(exit) } : {}), - ...(dur != null ? { dur } : {}), - ...(log ? { log } : {}), - }); - } - return out; + const event = parseTaskEvent(block.text); + return event ? [event] : [block]; + }); } diff --git a/packages/runtime/src/ginno_runtime/api/messages_ui.py b/packages/runtime/src/ginno_runtime/api/messages_ui.py index 29273d76..249681fb 100644 --- a/packages/runtime/src/ginno_runtime/api/messages_ui.py +++ b/packages/runtime/src/ginno_runtime/api/messages_ui.py @@ -1001,6 +1001,18 @@ def flush_assistant() -> None: for m in messages: if isinstance(m, HumanMessage): content_raw = getattr(m, "content", "") + # Old idle batches only stamped the last event. The legacy + # renderer needs the original headers to recover every receipt. + if ( + m.additional_kwargs.get("ginno_task_event") + and isinstance(content_raw, str) + and re.match(r"^(?:[2-9]|[1-9]\d+) background task events arrived:\n\n", content_raw) + ): + flush_assistant() + ui.append({ + "id": m.id, "role": "user", "blocks": [{"kind": "text", "text": content_raw}], + }) + continue # Mid-turn steered message (docs/steering-design.md §3.5): a REAL user # message — never folded into a context row — but it must not break # the assistant bubble either. One turn is ONE bubble, and the diff --git a/packages/runtime/tests/e2e/test_packaged_ui_legacy_transcript_receipts.py b/packages/runtime/tests/e2e/test_packaged_ui_legacy_transcript_receipts.py new file mode 100644 index 00000000..8bda0e2b --- /dev/null +++ b/packages/runtime/tests/e2e/test_packaged_ui_legacy_transcript_receipts.py @@ -0,0 +1,49 @@ +"""Legacy recovery and task callbacks replay as readable rows.""" + +import pytest +from langchain_core.messages import HumanMessage +from playwright.sync_api import expect +from test_packaged_ui_transcript_event_rows import app as app, open_session, save_messages + +pytestmark = pytest.mark.e2e + + +def test_legacy_lastwords_and_timeout(app): + page, port, sid = app + save_messages(sid, [ + HumanMessage( + id="keep_lastwords_legacy", + content="[lastwords] Legacy recovery header\n\n原始请求:Legacy request detail\n最后进展:Legacy progress detail", + ), + HumanMessage( + id="keep_timeout_legacy", + content='[task timeout] "Legacy timeout" (t_audit9) after 20s — killed\n' + "--- tail ---\nLegacy timeout log\n--- end ---\nFull log: /tmp/task-output", + ), + ]) + open_session(page, port, sid) + expect(page.get_by_text("Legacy recovery header", exact=True)).to_be_visible() + expect(page.get_by_text("Legacy request detail", exact=True)).to_be_visible() + expect(page.get_by_text("Legacy progress detail", exact=True)).to_be_visible() + expect(page.get_by_text("Legacy timeout", exact=True)).to_be_visible() + expect(page.get_by_text("Task timed out", exact=False)).to_have_count(1) + expect(page.get_by_text("Legacy timeout log", exact=False)).not_to_be_visible() + page.locator("details", has_text="Legacy timeout log").locator("summary").click() + expect(page.get_by_text("Legacy timeout log", exact=False)).to_be_visible() + + +def test_legacy_batch_recovers_receipts_before_last_marked_event(app): + page, port, sid = app + save_messages(sid, [HumanMessage( + id="legacy-batch", + content='2 background task events arrived:\n\n' + '[task finished] "Legacy batch first" (t_audit1) exit 0 · ran 1s\n\n' + '[task timeout] "Legacy batch second" (t_audit2) after 3s — killed', + additional_kwargs={"ginno_task_event": { + "task": "t_audit2", "kind": "timeout", "title": "Legacy batch second", "dur": "3s", + }}, + )]) + open_session(page, port, sid) + expect(page.get_by_text("Legacy batch first", exact=True)).to_have_count(1) + expect(page.get_by_text("Legacy batch second", exact=True)).to_have_count(1) + expect(page.get_by_text("2 background task events arrived", exact=False)).to_have_count(0)