fix(webui): clarify command session activity

This commit is contained in:
chengyongru authored and chengyongru committed 2026-11-13 22:30:27 +08:00
1 parent c80ae65746
commit de9cce45b4
28 files changed
+1174 -68

No files matched your search

@@ -2,6 +2,7 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"
import { afterEach, describe, expect, it, vi } from "vitest";
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context";
import { preloadMarkdownText } from "@/components/MarkdownText";
import { setAppLanguage } from "@/i18n";
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
@@ -106,6 +107,129 @@ function installReducedMotion() {
describe("AgentActivityCluster", () => {
afterEach(() => { localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); });
it("keeps repeated session observations in call order and shows their original command", () => {
const id = "012345abcdef";
const sessionLine = `exec_session(${JSON.stringify({ session_id: id })})`;
const readLine = 'read_file({"path":"README.md"})';
const messages: UIMessage[] = [{
id: "session-activity", role: "tool", kind: "trace", content: sessionLine,
traces: [sessionLine, readLine], createdAt: 1,
toolEvents: [
{ name: "exec_session", call_id: "poll-1", arguments: { session_id: id }, phase: "end", result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s` },
{ name: "read_file", call_id: "read-1", arguments: { path: "README.md" }, phase: "end" },
{ name: "exec_session", call_id: "poll-2", arguments: { session_id: id }, phase: "end", result: "Exit code: 7\nElapsed: 2.0s" },
],
}];
const commands = new Map([[id, "npm test --token secret-value"]]);
const { container } = render(
<ExecSessionCommandsContext.Provider value={commands}>
<AgentActivityCluster messages={messages} isTurnStreaming hasBodyBelow={false} />
</ExecSessionCommandsContext.Provider>,
);
const rows = screen.getAllByTestId("activity-step").map((row) => row.textContent);
expect(rows).toEqual([
"Command was still running at the last check npm test --token ••••",
"Read file README.md",
"Command failed (exit code 7) npm test --token ••••",
]);
expect(container.innerHTML).not.toContain(id);
expect(container.innerHTML).not.toContain("secret-value");
});
it("preserves the order of a structured session check followed by text-only activity", () => {
const id = "012345abcdef";
const line = `exec_session(${JSON.stringify({ session_id: id })})`;
const legacy = 'read_file({"path":"later.txt"})';
const message: UIMessage = { id: "mixed-activity", role: "tool", kind: "trace", content: legacy,
traces: [line, legacy], createdAt: 1, toolEvents: [{ name: "exec_session", call_id: "check",
arguments: { session_id: id }, phase: "end", result: "Exit code: 0\nElapsed: 2.0s" }] };
render(<AgentActivityCluster messages={[message]} isTurnStreaming hasBodyBelow={false} />);
expect(screen.getAllByTestId("activity-step").map((row) => row.textContent)).toEqual([
"Command completed", "Reading file later.txt",
]);
});
it("keeps text-only activity after every repeated structured check preceding it", () => {
const id = "012345abcdef";
const line = `exec_session(${JSON.stringify({ session_id: id })})`;
const legacy = 'read_file({"path":"later.txt"})';
const message: UIMessage = { id: "mixed-repeats", role: "tool", kind: "trace", content: legacy,
traces: [line, line, legacy], createdAt: 1, toolEvents: [
{ name: "exec_session", call_id: "check-1", arguments: { session_id: id }, phase: "end",
result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s` },
{ name: "exec_session", call_id: "check-2", arguments: { session_id: id }, phase: "end", result: "Exit code: 0\nElapsed: 2.0s" },
] };
render(<AgentActivityCluster messages={[message]} isTurnStreaming hasBodyBelow={false} />);
expect(screen.getAllByTestId("activity-step").map((row) => row.textContent)).toEqual([
"Command was still running at the last check", "Command completed", "Reading file later.txt",
]);
});
it("does not claim text-only session input succeeded without an observation", () => {
const line = 'exec_session({"session_id":"012345abcdef","input":"private-stdin"})';
const message: UIMessage = { id: "legacy-session", role: "tool", kind: "trace", content: line, traces: [line], createdAt: 1 };
const { container } = render(<AgentActivityCluster messages={[message]} isTurnStreaming={false} hasBodyBelow={false} expanded />);
expect(container).toHaveTextContent("Command status unknown");
expect(container).not.toHaveTextContent("Sent input");
expect(container).not.toHaveTextContent("private-stdin");
});
it("folds only long consecutive passive checks and lets users inspect every observation", () => {
const a = "012345abcdef";
const b = "fedcba543210";
const running = (id: string) => `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s`;
const view = (checks: number) => {
const events: NonNullable<UIMessage["toolEvents"]> = [
...Array.from({ length: checks }, (_, index) => ({ name: "exec_session", call_id: `a-${index}`,
arguments: { session_id: a }, phase: "end" as const, result: running(a) })),
{ name: "exec_session", call_id: "input", arguments: { session_id: a, input: "private" }, phase: "end", result: running(a) },
...Array.from({ length: 7 }, (_, index) => ({ name: "exec_session", call_id: `b-${index}`,
arguments: { session_id: b }, phase: "end" as const, result: running(b) })),
{ name: "exec_session", call_id: "failed", arguments: { session_id: b }, phase: "error", error: "query failed" },
{ name: "exec_session", call_id: "finished", arguments: { session_id: a }, phase: "end", result: "Exit code: 0\nElapsed: 1.0s" },
];
const message: UIMessage = { id: "many-checks", role: "tool", kind: "trace", content: "exec_session()",
traces: events.map((event) => `exec_session(${JSON.stringify(event.arguments)})`), toolEvents: events, createdAt: 1 };
return <ExecSessionCommandsContext.Provider value={new Map([[a, "test-a"], [b, "test-b"]])}>
<AgentActivityCluster messages={[message]} isTurnStreaming hasBodyBelow={false} />
</ExecSessionCommandsContext.Provider>;
};
const { rerender, container } = render(view(10));
expect(screen.getAllByTestId("activity-step")).toHaveLength(5);
expect(container).toHaveTextContent("Sent input test-a");
expect(container).toHaveTextContent("Could not check command test-b");
expect(container).toHaveTextContent("Command completed test-a");
expect(container).not.toHaveTextContent("private");
fireEvent.click(screen.getByRole("button", { name: "Show earlier command checks (9)" }));
expect(screen.getAllByTestId("activity-step")).toHaveLength(14);
expect(screen.getByRole("button", { name: "Hide earlier command checks (9)" })).toHaveAttribute("aria-expanded", "true");
rerender(view(11));
expect(screen.getAllByTestId("activity-step")).toHaveLength(15);
fireEvent.click(screen.getByRole("button", { name: "Hide earlier command checks (10)" }));
expect(screen.getAllByTestId("activity-step")).toHaveLength(5);
expect(screen.getByRole("button", { name: "Show earlier command checks (6)" })).toBeInTheDocument();
});
it("shows a generic session label until its source command becomes available", () => {
const id = "012345abcdef";
const line = `exec_session(${JSON.stringify({ session_id: id })})`;
const messages: UIMessage[] = [{
id: "session-activity", role: "tool", kind: "trace", content: line, traces: [line], createdAt: 1,
toolEvents: [{ name: "exec_session", call_id: "poll", arguments: { session_id: id }, phase: "end", result: "Exit code: 0\nElapsed: 2.0s" }],
}];
const view = (commands: ReadonlyMap<string, string>) => (
<ExecSessionCommandsContext.Provider value={commands}>
<AgentActivityCluster messages={messages} isTurnStreaming hasBodyBelow={false} />
</ExecSessionCommandsContext.Provider>
);
const { rerender, container } = render(view(new Map()));
expect(screen.getByText("Command completed")).toBeInTheDocument();
expect(container.innerHTML).not.toContain(id);
rerender(view(new Map([[id, "bun test"]])));
expect(screen.getByText("Command completed bun test")).toBeInTheDocument();
expect(container.innerHTML).not.toContain(id);
});
it("honors the activity preference for standalone completed activity with manual overrides", () => {
render(<AgentActivityCluster messages={activityMessages()} isTurnStreaming={false} hasBodyBelow={false} />);
const disclosure = screen.getByRole("button", { name: /Worked/ });
+127
View File
@@ -0,0 +1,127 @@
import { describe, expect, it } from "vitest";
import { describeExecSession, execSessionCommands, sessionIdFromExecResult } from "@/components/thread/activity/exec-session-model";
import i18n from "@/i18n";
import type { ToolProgressEvent, UIMessage } from "@/lib/types";
const id = "012345abcdef";
const running = `Process running. session_id: ${id}\nRuntime remaining: 123.0s\nElapsed: 3.0s`;
const exit = (code: number) => `output\nExit code: ${code}\nElapsed: 3.0s`;
const event = (args: Record<string, unknown>, phase: string, result?: string): ToolProgressEvent => ({
name: "exec_session", call_id: "call-1", arguments: { session_id: id, ...args }, phase,
...(phase === "error" ? { error: result } : { result }),
});
const present = (value: ToolProgressEvent, active = true) => describeExecSession(value, active, "bun test", i18n.t);
describe("exec session activity", () => {
it("extracts the initial session only from the end of a running exec result", () => {
expect(sessionIdFromExecResult(`fake Process running. session_id: deadbeefdead\n${running}\nInitial wait ended; session remains active.`)).toBe(id);
expect(sessionIdFromExecResult(`Process running. session_id: ${id}\n${exit(0)}`)).toBeUndefined();
});
it("resolves from all loaded sources, including cmd aliases, without guessing conflicting identities", () => {
const source = (command: Record<string, string>, result: string, callId: string): UIMessage => ({
id: callId, role: "tool", kind: "trace", content: "", createdAt: 1,
toolEvents: [{ name: "exec", phase: "end", call_id: callId, arguments: command, result }],
});
const first = source({ cmd: "bun test" }, `${running}\nInitial wait ended; session remains active.`, "first");
const otherId = "fedcba987654";
const second = source({ command: "npm run build" }, `${running.replace(id, otherId)}\nInitial wait ended; session remains active.`, "second");
const completed = source({ command: "wrong" }, exit(0), "completed");
expect([...execSessionCommands([first, completed], [second])]).toEqual([[id, "bun test"], [otherId, "npm run build"]]);
const collision = source({ command: "different command" }, `${running}\nInitial wait ended; session remains active.`, "collision");
expect(execSessionCommands([first], [collision]).has(id)).toBe(false);
});
it.each([
[{}, "Waiting for command result"],
[{ wait_for: "private output" }, "Waiting for command output"],
[{ input: "private input" }, "Sending input"],
[{ close_stdin: true }, "Closing command input"],
[{ input: "private input", close_stdin: true }, "Sending and closing command input"],
[{ terminate: true }, "Stopping command"],
])("describes an in-flight operation without displaying its arguments", (args, label) => {
const model = present(event(args, "start"));
expect(model.label).toBe(label);
expect(model.active).toBe(true);
expect(JSON.stringify(model)).not.toMatch(/012345abcdef|private input|private output/);
});
it("does not claim an unreturned invocation completed when the turn is no longer active", () => {
expect(present(event({}, "start"), false)).toMatchObject({ label: "Command status unknown", active: false });
});
it.each([
[running, "Command was still running at the last check"],
[`${running}\nWait timed out after 1s; session remains active.`, "Wait timed out; command was still running at the last check"],
[exit(0), "Command completed"],
[exit(7), "Command failed (exit code 7)"],
[`Session terminated. Reason: cancelled.\nExit code: -15\nElapsed: 3.0s`, "Command exited (exit code -15)"],
])("shows the observed command state rather than tool-return success", (result, label) => {
expect(present(event({}, "end", result))).toMatchObject({ label, active: false });
});
it("reports a naturally completed process as completed even when terminate was requested", () => {
expect(present(event({ terminate: true }, "end", exit(0))).label).toBe("Command completed");
});
it("keeps a wait target private and does not say it was observed when the process exits", () => {
const result = `${exit(0)}\nWait target not observed: 'private output'`;
const model = present(event({ wait_for: "private output" }, "end", result));
expect(model.label).toBe("Command completed");
expect(JSON.stringify(model)).not.toContain("private output");
});
it.each([
["Error: Command timed out; session was terminated. Reason: max_runtime.\nExit code: -9\nElapsed: 3.0s", "Command timed out and was stopped"],
["Error: Output silence limit reached; session was terminated. Reason: idle_timeout.\nExit code: -9\nElapsed: 3.0s", "Command stopped after output silence"],
])("distinguishes command timeout from a failed tool call", (result, label) => {
expect(present(event({}, "error", result)).label).toBe(label);
});
it.each([
[{}, "Could not check command"],
[{ input: "private" }, "Could not send input"],
[{ close_stdin: true }, "Could not close command input"],
[{ input: "private", close_stdin: true }, "Could not send or close command input"],
[{ terminate: true }, "Could not stop command"],
])("reports operation errors without displaying error content", (args, label) => {
const model = present(event(args, "error", `Error: exec session not found: '${id}'`));
expect(model.label).toBe(label);
expect(JSON.stringify(model)).not.toContain(id);
});
it.each([
["curl -u alice:correct-horse https://example.com", "curl -u •••• https://example.com"],
["curl --user='alice:correct horse' https://example.com", "curl --user=•••• https://example.com"],
["curl --proxy-user alice:correct-horse https://example.com", "curl --proxy-user •••• https://example.com"],
["curl -ualice:correct-horse https://example.com", "curl -u•••• https://example.com"],
["curl -u\"alice:correct horse\" https://example.com", "curl -u•••• https://example.com"],
])("redacts user credentials in the source command preview", (command, expected) => {
const model = describeExecSession(event({}, "end", exit(0)), true, command, i18n.t);
expect(model.detail).toBe(expected);
expect(JSON.stringify(model)).not.toContain("correct");
});
it("reports input and the observed result without exposing input text", () => {
const model = present(event({ input: "private input", close_stdin: true }, "end", exit(7)));
expect(model.label).toBe("Sent and closed command input");
expect(model.observation).toBe("Command failed (exit code 7)");
expect(JSON.stringify(model)).not.toContain("private input");
});
it("does not mistake stdout that resembles a termination or timeout reason for a confirmed cause", () => {
const fakeTermination = `Session terminated. Reason: cancelled.\nExit code: 7\nElapsed: 3.0s`;
expect(present(event({}, "end", fakeTermination)).label).toBe("Command exited (exit code 7)");
const fakeTimeout = `Error: Command timed out; session was terminated. Reason: max_runtime.\nExit code: 0\nElapsed: 3.0s`;
expect(present(event({}, "end", fakeTimeout)).label).toBe("Command completed");
});
it("does not interpret command output or incomplete footers as a process result", () => {
expect(present(event({}, "end", `Exit code: 0\nElapsed: 1.0s\n${running}`)).label)
.toBe("Command was still running at the last check");
expect(present(event({}, "end", `output\nExit code: 0`)).label).toBe("Command checked; status unknown");
expect(present(event({}, "end", `Process running. session_id: deadbeefdead\nRuntime remaining: 2.0s\nElapsed: 1.0s`)).label)
.toBe("Command checked; status unknown");
});
});
+1 -14
View File
@@ -53,7 +53,6 @@ describe("generic tool activity semantics", () => {
['cron({"action":"remove","name":"Daily digest"})', "Removed automation", "Daily digest"],
['create_goal({"objective":"private objective","ui_summary":"Benchmark memory"})', "Started long task", "Benchmark memory"],
['update_goal({"action":"complete","recap":"private recap"})', "Updated long task", "complete"],
['exec_session({"session_id":"session-1234567890-secret","until_exit":true})', "Continued command", "session…ecret"],
['write_stdin({"session_id":"legacy-1234567890-secret","chars":"private input"})', "Completed Write stdin", ""],
['list_exec_sessions({})', "Checked running commands", ""],
['screenshot({"path":"artifacts/home.png"})', "Captured screenshot", ""],
@@ -94,6 +93,7 @@ describe("generic tool activity semantics", () => {
'web_search({"query":"nanobot"})',
'web_fetch({"url":"https://example.com"})',
'exec({"command":"date"})',
'exec_session({"session_id":"012345abcdef"})',
'write_file({"path":"README.md"})',
'edit_file({"path":"README.md"})',
'apply_patch({"patch":"private"})',
@@ -118,19 +118,6 @@ describe("generic tool activity semantics", () => {
});
});
it("localizes command continuation events", async () => {
await setAppLanguage("zh-CN");
const line = 'exec_session({"session_id":"session-1234567890-secret"})';
for (const status of ["running", "done", "error"] as const) {
const key = status === "running" ? "continuingCommand"
: status === "done" ? "continuedCommand" : "continueCommandFailed";
expect(describeRun(line, status)).toMatchObject({
label: i18n.t(`message.agentActivity.${key}`),
detail: "session…ecret",
});
}
});
it("keeps different subtask actions separate while grouping repeated status checks", () => {
const item = (action: string) => ({ trace: parseGenericToolTrace(`subagent("${action}")`)!, status: "done" as const });
expect(canGroupGenericToolRuns(item("create"), item("check"))).toBe(false);
+89 -9
View File
@@ -818,6 +818,34 @@ describe("ThreadShell", () => {
await act(async () => {});
});
it("resolves a session command from loaded history outside the visible window", async () => {
const client = makeClient();
const id = "012345abcdef";
const command = { cmd: "bun run test --token secret-value" };
const sessionArgs = { session_id: id, until_exit: true };
const events = [
{ event: "message", chat_id: "command-history", projection_id: "initial-exec", kind: "progress",
text: `exec(${JSON.stringify(command)})`, tool_events: [{ name: "exec", phase: "end", call_id: "exec-1", arguments: command,
result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s\nInitial wait ended; session remains active.` }] },
...Array.from({ length: 150 }, (_, index) => ({ event: "user_message", chat_id: "command-history",
projection_id: `old-${index}`, text: `older question ${index}`, starts_turn: true })),
{ event: "message", chat_id: "command-history", projection_id: "session-call", kind: "progress",
text: `exec_session(${JSON.stringify(sessionArgs)})`, tool_events: [{ name: "exec_session", phase: "end",
call_id: "poll-1", arguments: sessionArgs, result: "Exit code: 0\nElapsed: 2.0s" }] },
{ event: "message", chat_id: "command-history", projection_id: "final-answer", text: "Command answer" },
];
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => String(input).includes("/webui-thread")
? Promise.resolve(httpJson({ schemaVersion: 3, projection: "events", events }))
: Promise.resolve({ ok: false, status: 404, json: async () => ({}) })));
render(wrap(client, <ThreadShell session={session("command-history")} title="Command history" onToggleSidebar={() => {}} />));
const menu = await openMessageActions("Command answer");
fireEvent.click(within(menu).getByRole("button", { name: /Worked/ }));
await waitFor(() => expect(document.body).toHaveTextContent("Command completed bun run test --token ••••"));
expect(document.body).not.toHaveTextContent(id);
expect(document.body).not.toHaveTextContent("secret-value");
expect(screen.queryByText("older question 0")).not.toBeInTheDocument();
});
it("surfaces and retries a deferred trace-detail request failure", async () => {
const client = makeClient();
let detailCalls = 0;
@@ -893,27 +921,40 @@ describe("ThreadShell", () => {
expect(detailCalls).toBe(2);
});
it("hydrates deferred activity in an independently paged navigation window", async () => {
it.each([false, true])("hydrates deferred activity in an independently paged navigation window (fragment=%s)", async (fragment) => {
const client = makeClient();
const id = "012345abcdef";
let detailCalls = 0;
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/prompts")) return Promise.resolve(httpJson({ prompts: [{
id: "old-user", preview: "Old question", answerPreview: "old answer", createdAt: 1,
cursor: "0", turnId: "old-turn",
}] }));
if (url.includes("/trace-detail?")) return Promise.resolve(httpJson({
message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{
event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress",
text: 'exec({"command":"echo historical"})',
}],
}));
if (url.includes("/trace-detail?")) {
detailCalls += 1;
return Promise.resolve(httpJson({
message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{
event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress",
text: 'exec({"command":"echo historical"})',
tool_events: [{ name: "exec", phase: "end", call_id: "navigation-exec",
arguments: { command: "echo historical" },
result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s\nInitial wait ended; session remains active.` }],
}],
}));
}
if (url.includes("after=0")) return Promise.resolve(httpJson({
schemaVersion: 3, projection: "events", events: [
{ event: "user_message", chat_id: "trace-navigation", projection_id: "old-user", text: "Old question", starts_turn: true },
{ event: "message", chat_id: "trace-navigation", projection_id: "old-trace", kind: "progress", text: "exec(…)",
trace_detail: { ref: "1.history-aaaaaaaaaaaaaaaaaaaa", bytes: 40_000, traceCount: 1 } },
{ event: "message", chat_id: "trace-navigation", projection_id: "old-check", kind: "progress",
text: `exec_session({"session_id":"${id}"})`,
tool_events: [{ name: "exec_session", phase: "end", call_id: "navigation-check",
arguments: { session_id: id }, result: "Exit code: 0\nElapsed: 2.0s" }] },
{ event: "message", chat_id: "trace-navigation", projection_id: "old-answer", text: "old answer" },
], page: { user_message_offset: 0, has_more_before: false, has_more_after: true, after_cursor: "1" },
], page: { user_message_offset: 0, has_more_before: false, has_more_after: true, after_cursor: "1",
...(fragment ? { history_generation: "generation-a", record_range: { turn: 0, start: 0, end: 4 } } : {}) },
}));
if (url.includes("/webui-thread")) return Promise.resolve(httpJson({
schemaVersion: 3, messages: [{ id: "latest-answer", role: "assistant", content: "latest answer", createdAt: 100 }],
@@ -928,12 +969,51 @@ describe("ThreadShell", () => {
await screen.findByText("old answer");
const menu = await openMessageActions("old answer");
fireEvent.click(within(menu).getByRole("button", { name: /Worked/ }));
await waitFor(() => expect(document.body).toHaveTextContent("echo historical"));
await waitFor(() => expect(document.body).toHaveTextContent("Command completed echo historical"));
expect(detailCalls).toBe(1);
expect(document.body).not.toHaveTextContent(id);
fireEvent.click(screen.getByRole("button", { name: "Scroll to bottom" }));
await screen.findByText("latest answer");
expect(screen.queryByText("old answer")).not.toBeInTheDocument();
});
it("starts a fresh trace-detail read after leaving and returning to the same chat", async () => {
const client = makeClient();
let resolveOld!: (response: Response) => void;
const oldRequest = new Promise<Response>((resolve) => { resolveOld = resolve; });
let detailCalls = 0;
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/webui-thread/trace-detail?")) {
detailCalls += 1;
if (detailCalls === 1) return oldRequest;
return Promise.resolve(httpJson({ message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{
event: "message", chat_id: "detail-return-a", projection_id: "trace-shared", kind: "progress",
text: 'exec({"command":"echo fresh"})',
}] }));
}
if (url.includes("websocket%3Adetail-return-a/webui-thread")) return Promise.resolve(httpJson(traceDetailThread(true, "answer-a")));
if (url.includes("websocket%3Adetail-return-b/webui-thread")) return Promise.resolve(httpJson(traceDetailThread(false, "answer-b")));
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
}));
const view = (chatId: string) => wrap(client,
<ThreadShell session={session(chatId)} title="Detail return" onToggleSidebar={() => {}} />);
const { rerender } = render(view("detail-return-a"));
fireEvent.click(within(await openMessageActions("answer-a")).getByRole("button", { name: /Worked/ }));
await waitFor(() => expect(detailCalls).toBe(1));
rerender(view("detail-return-b"));
await screen.findByText("answer-b");
rerender(view("detail-return-a"));
fireEvent.click(within(await openMessageActions("answer-a")).getByRole("button", { name: /Worked/ }));
await waitFor(() => expect(detailCalls).toBe(2));
await waitFor(() => expect(document.body).toHaveTextContent("echo fresh"));
await act(async () => resolveOld(httpJson({ message_id: "history-aaaaaaaaaaaaaaaaaaaa", events: [{
event: "message", chat_id: "detail-return-a", projection_id: "trace-shared", kind: "progress",
text: 'exec({"command":"echo stale"})',
}] })));
expect(document.body).not.toHaveTextContent("echo stale");
});
it("ignores a deferred trace-detail failure after switching sessions", async () => {
const client = makeClient();
const detailUrls: string[] = [];
+3 -3
View File
@@ -2257,7 +2257,7 @@ describe("ThreadViewport", () => {
const navigation = { prompts: [{ id: "u1", label: "hello", preview: "hello", answerPreview: "", createdAt: 1, index: 0 }],
window: { messages: [{ id: "old", role: "user" as const, content: "old question", createdAt: 0 }],
userMessageOffset: 0, hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },
target: null, operation: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() };
target: null, operation: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), expandTraceDetail: vi.fn() };
const view = render(<ThreadViewport ref={viewportRef} messages={messages} isStreaming={false} composer={<div />} navigation={navigation} />);
act(() => viewportRef.current?.jumpToUserPrompt("u1"));
expect(latest).toHaveBeenCalledOnce();
@@ -2272,7 +2272,7 @@ describe("ThreadViewport", () => {
prompts: [], window: { messages: history, userMessageOffset: 0,
hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },
target: null, operation: null, loading: false, error: null,
jump: vi.fn(), older: vi.fn(), newer, cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn(),
jump: vi.fn(), older: vi.fn(), newer, cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), expandTraceDetail: vi.fn(),
};
const view = render(<ThreadViewport messages={messages} isStreaming={false} composer={<div />} navigation={navigation} />);
await flushAnimationFrame();
@@ -2324,7 +2324,7 @@ describe("ThreadViewport", () => {
navigation={{ prompts: [], window: { messages: history, userMessageOffset: 0,
hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },
target: { id: "old-user", sequence: 1 }, operation: null, loading: false, error: null,
jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn() }} />);
jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), expandTraceDetail: vi.fn() }} />);
await waitFor(() => expect(screen.getByText("Large old turn")).toBeInTheDocument());
});
+32
View File
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest";
import { useNanobotStream } from "@/hooks/useNanobotStream";
import { userPromptAnchors } from "@/components/thread/promptNavigation";
import { execSessionCommands } from "@/components/thread/activity/exec-session-model";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
import { composerUsageSnapshots } from "@/lib/model-request";
@@ -159,6 +160,37 @@ async function flushStreamFrame() {
}
describe("useNanobotStream", () => {
it("updates the command source on exec results, not on streamed text, and scopes it to the chat", async () => {
const fake = fakeClient();
const initial: UIMessage[] = Array.from({ length: 500 }, (_, index) => ({
id: `history-${index}`, role: "user", content: `Earlier ${index}`, createdAt: index,
}));
const { result, rerender } = renderHook(({ chat }: { chat: string }) => useNanobotStream(chat, initial), {
wrapper: wrap(fake.client), initialProps: { chat: "chat-a" },
});
const id = "012345abcdef";
const args = { command: "bun run test" };
act(() => {
fake.emit("chat-a", { event: "message", chat_id: "chat-a", turn_id: "turn", turn_seq: 1, kind: "tool_hint",
text: `exec(${JSON.stringify(args)})`, tool_events: [{ name: "exec", call_id: "exec-1", phase: "start", arguments: args }] });
fake.emit("chat-a", { event: "message", chat_id: "chat-a", turn_id: "turn", turn_seq: 2, kind: "tool_hint",
text: `exec(${JSON.stringify(args)})`, tool_events: [{ name: "exec", call_id: "exec-1", phase: "end", arguments: args,
result: `Process running. session_id: ${id}\nRuntime remaining: 100.0s\nElapsed: 1.0s\nInitial wait ended; session remains active.` }] });
});
const snapshot = result.current.execSourceMessages;
expect(execSessionCommands(snapshot).get(id)).toBe("bun run test");
act(() => {
for (let index = 0; index < 100; index++) fake.emit("chat-a", {
event: "delta", chat_id: "chat-a", turn_id: "turn", turn_seq: index + 3, stream_id: "answer", text: "x",
});
});
await flushStreamFrame();
expect(result.current.messages.at(-1)?.content).toBe("x".repeat(100));
expect(result.current.execSourceMessages).toBe(snapshot);
rerender({ chat: "chat-b" });
expect(execSessionCommands(result.current.execSourceMessages).has(id)).toBe(false);
});
it.each([true, false])("keeps temporary and new persistent streams separate when the history key is absent (temporary=%s)", (temporary) => {
const fake = fakeClient();
const cache = new ThreadMessageCache(() => temporary);