Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 44 additions & 35 deletions apps/web/src/components/chat/TaskCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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``。 */
Expand Down Expand Up @@ -264,7 +265,7 @@ function fetchTaskOnce(tid: string): Promise<TaskRecord | null> {
return p;
}

export function TaskEventBand({ block }: { block: { taskId: string; ev: string; title?: string; exit?: number | null; dur?: string } }) {
export function TaskEventBand({ block }: { block: Extract<Block, { kind: "task_event" }> }) {
const { tc } = useChatT();
const [task, setTask] = useState<TaskRecord | null>(null);
const [hover, setHover] = useState(false);
Expand All @@ -287,41 +288,49 @@ export function TaskEventBand({ block }: { block: { taskId: string; ev: string;
: block.ev;
const showCard = hover && !!task?.command;
return (
<div
ref={cardRef}
className="relative my-1 flex items-center gap-1.5 border-l-2 py-0.5 pl-2 text-[11px]"
style={{ borderColor: color, color: "rgb(var(--muted))", background: "color-mix(in srgb, currentColor 4%, transparent)" }}
onMouseEnter={() => {
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)}
>
<span style={{ color }}>▸</span>
<span className="truncate">
{label} · <span className="font-mono">{block.title || block.taskId}</span>
{block.dur ? ` · ${block.dur}` : ""}
</span>
{showCard && (
<div
className="absolute left-2 top-full z-30 mt-1 w-max max-w-xl overflow-hidden rounded-lg border border-line bg-card shadow-lg"
data-testid={`task-event-cmd-${block.taskId}`}
>
<div className="select-text whitespace-pre-wrap break-all px-3 py-2 font-mono text-[11px] leading-relaxed text-txt">
$ {task!.command}
</div>
{task!.cwd ? (
<div className="border-t border-line px-3 py-1.5 font-mono text-[10px] text-faint">
cwd: {task!.cwd}
<div>
<div
ref={cardRef}
className="relative my-1 flex items-center gap-1.5 border-l-2 py-0.5 pl-2 text-[11px]"
style={{ borderColor: color, color: "rgb(var(--muted))", background: "color-mix(in srgb, currentColor 4%, transparent)" }}
onMouseEnter={() => {
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)}
>
<span style={{ color }}>▸</span>
<span className="truncate">
{label} · <span className="font-mono">{block.title || block.taskId}</span>
{block.dur ? ` · ${block.dur}` : ""}
</span>
{showCard && (
<div
className="absolute left-2 top-full z-30 mt-1 w-max max-w-xl overflow-hidden rounded-lg border border-line bg-card shadow-lg"
data-testid={`task-event-cmd-${block.taskId}`}
>
<div className="select-text whitespace-pre-wrap break-all px-3 py-2 font-mono text-[11px] leading-relaxed text-txt">
$ {task!.command}
</div>
) : null}
</div>
{task!.cwd ? (
<div className="border-t border-line px-3 py-1.5 font-mono text-[10px] text-faint">
cwd: {task!.cwd}
</div>
) : null}
</div>
)}
</div>
{block.log && (
<details className="mb-1 ml-2 text-xs text-muted">
<summary className="cursor-pointer">{tc("taskCard.outputTail")}</summary>
<pre className="selectable max-h-48 overflow-auto whitespace-pre-wrap break-words">{block.log}</pre>
</details>
)}
</div>
);
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/components/chat/blocks/taskEventParse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,22 @@ 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,
text: '[task finished] "dev-swap-retry-120s" (t_1218152f) exit 2 · ran 2m 00s\n--- tail ---\n{"ok":true}\n--- end ---',
},
];
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", () => {
Expand Down
13 changes: 5 additions & 8 deletions apps/web/src/components/chat/blocks/taskEventParse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -50,19 +49,17 @@ 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,
ev: evRaw === "finished" ? "finished" : "failed_to_start",
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;
}
2 changes: 1 addition & 1 deletion apps/web/src/components/chat/blocks/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 行,卡片不再往里塞)。
Expand Down
19 changes: 19 additions & 0 deletions apps/web/src/components/chat/stream/TranscriptList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -44,6 +46,18 @@ import {
sliceStart,
} from "@/lib/transcriptSlices";

function isIndependentEvent(block: Block): block is Extract<Block, { kind: "task_event" | "plan_update" }> {
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"
? <TaskEventBand key={`task-${block.taskId}-${index}`} block={block} />
: <PlanUpdateCard key={`plan-${block.planId}-${index}`} block={block} />
));
}

export function TranscriptList({
messages,
session,
Expand Down Expand Up @@ -382,6 +396,7 @@ export function TranscriptList({
任何一方的气泡,是事件驱动的系统行。subagent_spawn 卡已停渲染
(顶部 SubagentBoard 接管,见文件头注释)。 */}
<div className="flex w-full max-w-[85%] flex-col gap-2">
<IndependentEvents blocks={m.blocks} />
{m.blocks
.filter((b): b is Extract<Block, { kind: "subagent_plan" }> => b.kind === "subagent_plan")
.map((b) => (
Expand All @@ -407,6 +422,10 @@ export function TranscriptList({
/>
</div>
</div>
) : m.role === "user" && m.blocks.every(isIndependentEvent) && m.blocks.length > 0 ? (
<div key={m.id} className="mx-auto flex w-full max-w-[85%] flex-col gap-2">
<IndependentEvents blocks={m.blocks} />
</div>
) : m.role === "user" &&
m.blocks.some(
(b) =>
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/src/ginno_runtime/compaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
131 changes: 131 additions & 0 deletions packages/runtime/tests/e2e/test_packaged_ui_transcript_event_rows.py
Original file line number Diff line number Diff line change
@@ -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='<ginno_plan_update plan="pl_audit">Plan receipt sentinel</ginno_plan_update>',
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='<ginno_plan_update plan="pl_live">Live system plan receipt</ginno_plan_update>')
send_frame(page, sid, "turn.start", turn_id="turn-fixture", agent_id="dev",
text='<ginno_plan_update plan="pl_wake">Live wake plan receipt</ginno_plan_update>')

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)
15 changes: 15 additions & 0 deletions packages/runtime/tests/unit/test_compaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
# --------------------------------------------------------------------------- #
Expand Down
Loading