perf(webui): reduce repeated work and bound history rendering (#5703)

* perf(webui): reduce repeated work and bound history rendering

* fix(webui): keep continuation reasoning with its answer

* refactor(webui): reuse answer buffers and prepared copy text

* perf(webui): restore conditional replay buffer initialization

* fix(webui): remove code block pagination
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-09 14:02:26 +08:00
1 parent 1c451b5b5f
commit 1469d4811c
32 files changed
+1156 -361

No files matched your search

@@ -18,6 +18,39 @@ function progressMessage(id: string, phase: "start" | "end" | "error"): UIMessag
}
describe("activity message coalescing", () => {
it("keeps reused call IDs isolated by turn and picks the latest compatible legacy row", () => {
const call = (id: string, turnId?: string): UIMessage => ({
...progressMessage(id, "start"), turnId,
toolEvents: [{ call_id: "shared", phase: "start", name: "web_search" }],
});
const complete = (id: string, turnId?: string): UIMessage => ({
...call(id, turnId), toolEvents: [{ call_id: "shared", phase: "end", name: "web_search" }],
});
const result = coalesceActivityMessages([
call("first", "a"), call("second", "b"), complete("finish-a", "a"),
]);
expect(result.map((row) => [row.id, row.toolEvents?.[0].phase])).toEqual([
["first", "end"], ["second", "start"],
]);
expect(coalesceActivityMessages([
call("first", "a"), call("second", "b"), complete("legacy"),
]).map((row) => [row.id, row.toolEvents?.[0].phase])).toEqual([
["first", "start"], ["second", "end"],
]);
});
it("processes independent calls with a linear event-read budget", () => {
let reads = 0;
const messages: UIMessage[] = Array.from({ length: 1000 }, (_, index) => ({
id: `${index}`, role: "tool", kind: "trace", content: `tool${index}()`, createdAt: index,
get toolEvents() {
reads++;
return [{ call_id: `${index}`, phase: "end" as const, name: `tool${index}` }];
},
}));
expect(coalesceActivityMessages(messages)).toEqual(messages);
expect(reads).toBeLessThanOrEqual(messages.length * 4);
});
it("folds persisted start and terminal progress into one activity", () => {
const result = coalesceActivityMessages([
progressMessage("start", "start"),
@@ -563,6 +563,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.queryByText("Edited files")).not.toBeInTheDocument();
const fileRef = screen.getByTestId("activity-file-reference");
@@ -679,15 +680,28 @@ describe("AgentActivityCluster", () => {
}
const assertIndependentDiff = () => {
const diff = screen.getByTestId("file-edit-diff");
expect(diff).toBeVisible();
expect(diff.closest('[aria-hidden="true"], [inert], [data-testid="agent-activity-scroll"]'))
.toBeNull();
expect(screen.getAllByTestId("activity-file-reference")).toHaveLength(1);
};
const assertExpandedOrder = () => {
for (const toggle of document.querySelectorAll<HTMLButtonElement>(
'[data-thread-disclosure][aria-expanded="false"]',
)) {
fireEvent.click(toggle);
}
const diff = screen.getByTestId("file-edit-diff");
expect(screen.getByText("Before edit")).toBeVisible();
expect(screen.getByText("After edit")).toBeVisible();
expect(screen.getByText("Before edit").compareDocumentPosition(diff)
& Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(diff.compareDocumentPosition(screen.getByText("After edit"))
& Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(screen.getAllByTestId("activity-file-reference")).toHaveLength(1);
assertIndependentDiff();
};
assertIndependentDiff();
assertExpandedOrder();
for (const toggle of document.querySelectorAll<HTMLButtonElement>("[data-thread-disclosure]")) {
fireEvent.click(toggle);
assertIndependentDiff();
@@ -710,6 +724,7 @@ describe("AgentActivityCluster", () => {
fireEvent.click(screen.getByTestId("file-edit-diff-toggle"));
}
assertIndependentDiff();
assertExpandedOrder();
} finally {
localStorage.removeItem("nanobot-webui.settings-preferences");
}
@@ -1051,6 +1066,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.getByText("Deleted")).toBeInTheDocument();
expect(screen.queryByText("Edited")).not.toBeInTheDocument();
@@ -1308,6 +1324,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.getByText("Searched X · nanobot oauth")).toBeInTheDocument();
expect(screen.queryByText(/Completed X search/i)).not.toBeInTheDocument();
@@ -1341,6 +1358,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.queryByText(/signed-secret|secret1234|url-secret/)).not.toBeInTheDocument();
expect(screen.getByText("Searched release notes access_token=<redacted>")).toBeInTheDocument();
@@ -1557,6 +1575,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
const title = screen.getByText("Example documentation");
const url = screen.getByText("example.com/docs");
@@ -1638,6 +1657,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
const run = screen.getByText(/Reviewed sources.*2 files/).closest('[data-testid="activity-step"]');
expect(run).toBeInTheDocument();
@@ -1678,6 +1698,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
const row = screen.getByText("Could not search files “needle”").closest(
'[data-testid="activity-step"]',
@@ -1706,6 +1727,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.queryByText(/password|signed-secret/)).not.toBeInTheDocument();
expect(screen.getByText("Completed Download asset")).toBeInTheDocument();
@@ -1792,6 +1814,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.getByText("Edited")).toBeInTheDocument();
expect(screen.queryByText("+0")).not.toBeInTheDocument();
@@ -1886,6 +1909,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
const row = screen.getByText("Could not edit").closest('[data-testid="activity-step"]');
expect(row).toBeInTheDocument();
@@ -1919,6 +1943,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
const row = screen.getByText("Could not edit").closest('[data-testid="activity-step"]');
expect(row).toBeInTheDocument();
@@ -1986,6 +2011,7 @@ describe("AgentActivityCluster", () => {
"-const fps = 30;",
"+const fps = 60;",
" start();",
]),
},
],
@@ -1995,6 +2021,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
const fileRefs = screen.getAllByTestId("activity-file-reference");
expect(fileRefs).toHaveLength(3);
@@ -2055,6 +2082,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.getByText("Edited")).toBeInTheDocument();
expect(screen.getByText("Could not edit")).toBeInTheDocument();
@@ -2162,6 +2190,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
expect(screen.getByText("Could not generate image")).toBeInTheDocument();
const row = screen.getByText("Could not generate image").closest(
@@ -2234,6 +2263,7 @@ describe("AgentActivityCluster", () => {
hasBodyBelow={false}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
const steps = screen.getAllByTestId("activity-step");
expect(steps.length).toBeGreaterThanOrEqual(3);
+27
View File
@@ -39,6 +39,33 @@ vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-light", () => ({
}));
describe("CodeBlock", () => {
it("renders and copies a large code block in full without pagination", async () => {
const user = userEvent.setup();
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText },
});
const source = Array.from({ length: 1200 }, (_, i) => `const value${i} = ${i};`).join("\n");
try {
render(<CodeBlock code={source} language="typescript" showLineNumbers />);
expect((await screen.findByTestId("highlighted-code")).textContent).toBe(source);
expect(screen.getAllByRole("button")).toHaveLength(1);
await user.click(screen.getByRole("button", { name: "Copy code" }));
expect(writeText).toHaveBeenCalledWith(source);
} finally {
Reflect.deleteProperty(navigator, "clipboard");
}
});
it("renders long plain text with Unicode in full", () => {
const source = "x".repeat(23999) + "😀tail";
render(<CodeBlock code={source} highlight={false} />);
expect(screen.getByTestId("plain-code-fallback").textContent).toBe(source);
expect(screen.getAllByRole("button")).toHaveLength(1);
});
it("renders plain code without mounting the highlighter when highlighting is disabled", () => {
render(
<ThemeProvider theme="dark">
@@ -757,6 +757,276 @@
"turnSeq": 6
}
]
},
{
"name": "length_continuation_reasoning_then_new_recovery_turn",
"chat_id": "fixture-length-recovery",
"initial_messages": [
{
"role": "user",
"content": "Write long code.",
"turnId": "long-turn",
"turnPhase": "user",
"turnSeq": 1,
"id": "length-user"
}
],
"live_events": [
{
"event": "reasoning_delta",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 2,
"text": "Plan."
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 3
},
{
"event": "delta",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 4,
"text": "```python\nfirst"
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 5,
"text": "```python\nfirst",
"resuming": true,
"merge_next": true
},
{
"event": "reasoning_delta",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 6,
"text": "Continue "
},
{
"event": "reasoning_delta",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 7,
"text": "code."
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 8
},
{
"event": "delta",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 9,
"text": "\nsecond"
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 10,
"text": "```python\nfirst\nsecond",
"resuming": true,
"merge_next": true
},
{
"event": "reasoning_delta",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 11,
"text": "Finish code."
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 12
},
{
"event": "reasoning_delta",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 1,
"text": "Recover."
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 2
},
{
"event": "delta",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 3,
"text": "Recovered "
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 4,
"text": "Recovered ",
"resuming": true,
"merge_next": true
},
{
"event": "reasoning_delta",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 5,
"text": "Continue recovery."
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 6
},
{
"event": "delta",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 7,
"text": "answer."
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 8,
"text": "Recovered answer."
},
{
"event": "turn_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 9,
"latency_ms": 50
}
],
"transcript": [
{
"event": "user",
"chat_id": "fixture-length-recovery",
"text": "Write long code.",
"turn_id": "long-turn",
"turn_seq": 1
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 3,
"text": "Plan."
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 5,
"text": "```python\nfirst",
"resuming": true,
"merge_next": true
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 8,
"text": "Continue code."
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 10,
"text": "```python\nfirst\nsecond",
"resuming": true,
"merge_next": true
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "long-turn",
"turn_seq": 12,
"text": "Finish code."
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 2,
"text": "Recover."
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 4,
"text": "Recovered ",
"resuming": true,
"merge_next": true
},
{
"event": "reasoning_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 6,
"text": "Continue recovery."
},
{
"event": "stream_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 8,
"text": "Recovered answer."
},
{
"event": "turn_end",
"chat_id": "fixture-length-recovery",
"turn_id": "recovery-turn",
"turn_seq": 9,
"latency_ms": 50
}
],
"expected": [
{
"role": "user",
"content": "Write long code.",
"turnId": "long-turn",
"turnPhase": "user",
"turnSeq": 1
},
{
"role": "assistant",
"content": "```python\nfirst\nsecond",
"reasoning": "Plan.\n\nContinue code.\n\nFinish code.",
"turnId": "long-turn",
"turnPhase": "answer",
"turnSeq": 10,
"activitySegmentId": "segment-1"
},
{
"role": "assistant",
"content": "Recovered answer.",
"reasoning": "Recover.\n\nContinue recovery.",
"turnId": "recovery-turn",
"turnPhase": "answer",
"turnSeq": 8,
"activitySegmentId": "segment-2",
"latencyMs": 50
}
]
}
]
}
@@ -1,9 +1,17 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { beforeAll, describe, expect, it, vi } from "vitest";
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
import MarkdownTextRenderer from "@/components/MarkdownTextRenderer";
// Exercise the asynchronous math boundary once, then test the loaded grammar cases.
beforeAll(async () => {
const view = render(<MarkdownTextRenderer>{"$$x^2$$"}</MarkdownTextRenderer>);
await waitFor(() => expect(view.container.querySelector(".katex")).toBeInTheDocument());
view.unmount();
});
describe("MarkdownTextRenderer", () => {
it("renders clickable markdown links in blue", () => {
render(<MarkdownTextRenderer>[local server](http://127.0.0.1:7891/)</MarkdownTextRenderer>);
@@ -17,6 +17,17 @@ function session(index: number): ChatSummary {
}
describe("SessionSearchDialog", () => {
it("windows large result sets and selects an item reached beyond the first window", () => {
const onSelect = vi.fn();
render(<SessionSearchDialog open sessions={Array.from({ length: 1000 }, (_, i) => session(i))}
activeKey={null} loading={false} onOpenChange={() => {}} onSelect={onSelect} />);
expect(screen.getAllByRole("button").length).toBeLessThanOrEqual(24);
const input = screen.getByRole("textbox", { name: "Search" });
for (let i = 0; i < 40; i++) fireEvent.keyDown(input, { key: "ArrowDown" });
fireEvent.keyDown(input, { key: "Enter" });
expect(onSelect).toHaveBeenCalledWith("websocket:chat-40");
expect(screen.getAllByRole("button").length).toBeLessThanOrEqual(24);
});
afterEach(() => {
vi.restoreAllMocks();
});
@@ -1,4 +1,5 @@
import { render, screen } from "@testing-library/react";
import { fireEvent, render, screen } from "@testing-library/react";
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { ThinkingReasoningShell } from "@/components/thread/activity/ThinkingReasoningShell";
@@ -22,6 +23,26 @@ function renderShell(expanded: boolean) {
}
describe("ThinkingReasoningShell", () => {
it("mounts details on first expansion and preserves their state across folding", () => {
const mounted = vi.fn();
function Details() {
const [count, setCount] = useState(() => { mounted(); return 0; });
return <button onClick={() => setCount(count + 1)}>Count {count}</button>;
}
const shell = (expanded: boolean) => (
<ThinkingReasoningShell active={false} expanded={expanded} label="Thought"
viewportRef={null} contentRef={null} fadeTop={false} fadeBottom={false}
onToggle={() => {}} onScroll={() => {}}><Details /></ThinkingReasoningShell>
);
const view = render(shell(false));
expect(mounted).toHaveBeenCalledTimes(0);
view.rerender(shell(true));
fireEvent.click(screen.getByText("Count 0"));
view.rerender(shell(false));
view.rerender(shell(true));
expect(screen.getByRole("button", { name: "Count 1" })).toBeVisible();
expect(mounted).toHaveBeenCalledTimes(1);
});
it("makes collapsed descendants inert as well as visually hidden", () => {
const { rerender } = renderShell(false);
const disclosure = screen.getByRole("button", { name: "Thought" });
@@ -9,6 +9,15 @@ import type { UIMessage } from "@/lib/types";
const STARTED_AT = Date.UTC(2026, 6, 25, 12, 34, 0);
it("reuses completed historical rows across streaming updates and recalculates changed start times", () => {
const prompt: UIMessage = { id: "u", role: "user", content: "hello", createdAt: 100 };
const answer: UIMessage = { id: "a", role: "assistant", content: "world", latencyMs: 50, createdAt: 120 };
const first = projectWebuiThreadMessages([prompt, answer]);
const second = projectWebuiThreadMessages([prompt, answer, { id: "next", role: "user", content: "next", createdAt: 200 }]);
expect(second[1]).toBe(first[1]);
expect(projectWebuiThreadMessages([{ ...prompt, createdAt: 200 }, answer])[1].completedAt).toBe(250);
});
function message(
role: UIMessage["role"],
overrides: Partial<Omit<UIMessage, "role">> = {},
@@ -0,0 +1,24 @@
import { expect, it } from "vitest";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import type { UIMessage } from "@/lib/types";
const rows: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }];
it("keeps recently visited chats within the entry budget", () => {
const cache = new ThreadMessageCache(() => false, 10000, 2);
cache.set("a", rows); cache.set("b", rows);
expect(cache.get("a")).toBe(rows);
cache.set("c", rows);
expect([cache.get("a"), cache.get("b"), cache.get("c")]).toEqual([rows, undefined, rows]);
});
it("bounds large replay snapshots while retaining temporary chats", () => {
const cache = new ThreadMessageCache((key) => key === "temporary", 1000, 2);
cache.set("temporary", rows);
cache.set("large", [{ ...rows[0], content: "x".repeat(1000) }]);
expect(cache.get("large")).toBeUndefined();
expect(cache.get("temporary")).toBe(rows);
cache.delete("temporary");
cache.set("small", rows);
expect(cache.get("small")).toBe(rows);
});
+21 -13
View File
@@ -12,6 +12,7 @@ import type { UIMessage } from "@/lib/types";
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.useRealTimers();
});
@@ -125,19 +126,26 @@ describe("ThreadMessages", () => {
expect(screen.getByText("latest answer").closest(".thread-render-unit")).toBeNull();
});
it("still defers historical non-tail answers on their initial render", () => {
render(
<ThreadMessages
messages={[
{ id: "u1", role: "user", content: "old question", createdAt: 1 },
{ id: "a1", role: "assistant", content: "historical answer", createdAt: 2 },
{ id: "u2", role: "user", content: "latest question", createdAt: 3 },
]}
isStreaming={false}
/>,
);
expect(screen.getByText("historical answer").closest(".thread-render-unit")).not.toBeNull();
it("recycles offscreen historical content while preserving its measured space", () => {
let notify: (entries: Array<{ isIntersecting: boolean }>) => void = () => {};
vi.stubGlobal("IntersectionObserver", class {
constructor(callback: typeof notify) { notify = callback; }
observe() {}
disconnect() {}
});
const view = render(<ThreadMessages messages={[
{ id: "u1", role: "user", content: "old question", createdAt: 1 },
{ id: "a1", role: "assistant", content: "historical answer", createdAt: 2 },
{ id: "u2", role: "user", content: "latest question", createdAt: 3 },
]} isStreaming={false} />);
const unit = screen.getByText("historical answer").closest<HTMLElement>("[data-thread-display-unit]")!;
vi.spyOn(unit, "getBoundingClientRect").mockReturnValue({ height: 240 } as DOMRect);
act(() => notify([{ isIntersecting: false }]));
expect(unit.style.height).toBe("240px");
expect(unit.childElementCount).toBe(0);
act(() => notify([{ isIntersecting: true }]));
expect(screen.getByText("historical answer")).toBeVisible();
expect(view.container).toHaveTextContent("old question");
});
it("preserves an answer's markdown tree across completion and the next prompt", async () => {
+66 -6
View File
@@ -3,6 +3,7 @@ import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
import { useNanobotStream } from "@/hooks/useNanobotStream";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
import type { StreamError } from "@/lib/nanobot-client";
import type {
@@ -344,6 +345,30 @@ describe("useNanobotStream", () => {
}
});
it("buffers a hidden chat view and flushes its ordered deltas on return", () => {
vi.useFakeTimers();
const fake = fakeClient();
const Client = wrap(fake.client);
let visible = false;
const { result, rerender, unmount } = renderHook(() => useNanobotStream("hidden-view", EMPTY_MESSAGES), {
wrapper: ({ children }) => <Client><ThreadVisibilityContext.Provider value={visible}>{children}</ThreadVisibilityContext.Provider></Client>,
});
try {
act(() => {
for (let seq = 1; seq <= 100; seq++) fake.emit("hidden-view", {
event: "delta", chat_id: "hidden-view", text: "x", turn_id: "turn", turn_seq: seq,
});
});
expect(result.current.messages).toHaveLength(0);
visible = true;
rerender();
expect(result.current.messages[0]).toMatchObject({ content: "x".repeat(100), turnSeq: 100 });
} finally {
unmount();
vi.useRealTimers();
}
});
it("keeps the turn pending on disconnect without breaking a resumed stream", async () => {
const fake = fakeClient();
const { result } = renderHook(
@@ -3409,18 +3434,53 @@ describe("useNanobotStream", () => {
describe("live/replay projection before canonical-event revision migration", () => {
it.each(PROJECTION_FIXTURE_CASES)("matches the shared $name fixture", (fixtureCase) => {
// Keep client-only elapsed-time estimates out of the transport contract.
const clock = vi.spyOn(Date, "now").mockReturnValue(0);
try {
const fake = fakeClient();
const { result } = renderHook(
() => useNanobotStream(fixtureCase.chat_id, fixtureCase.initial_messages),
{ wrapper: wrap(fake.client) },
);
for (const event of fixtureCase.live_events) {
act(() => {
fake.emit(fixtureCase.chat_id, event);
});
}
expect(normalizeProjection(result.current.messages)).toEqual(fixtureCase.expected);
} finally {
clock.mockRestore();
}
});
it.each([true, false])("keeps continuation reasoning before its answer across frames (text snapshots: %s)", async (snapshots) => {
const fixture = PROJECTION_FIXTURE_CASES.find(
(candidate) => candidate.name === "length_continuation_reasoning_then_new_recovery_turn",
)!;
const fake = fakeClient();
const { result } = renderHook(
() => useNanobotStream(fixtureCase.chat_id, fixtureCase.initial_messages),
() => useNanobotStream(fixture.chat_id, fixture.initial_messages),
{ wrapper: wrap(fake.client) },
);
for (const event of fixtureCase.live_events) {
for (const event of fixture.live_events) {
act(() => {
fake.emit(fixtureCase.chat_id, event);
fake.emit(fixture.chat_id, event.event === "stream_end" && !snapshots
? { ...event, text: undefined }
: event);
});
await flushStreamFrame();
}
expect(normalizeProjection(result.current.messages)).toEqual(fixtureCase.expected);
const units = normalizeActivityTimeline(result.current.messages);
expect(units.map((unit) => unit.type === "activity"
? unit.messages.map((message) => message.reasoning).join("")
: unit.message.content)).toEqual([
"Write long code.",
"Plan.\n\nContinue code.\n\nFinish code.",
"```python\nfirst\nsecond",
"Recover.\n\nContinue recovery.",
"Recovered answer.",
]);
});
});
+31 -2
View File
@@ -60,6 +60,35 @@ function wrap(
}
describe("useSessions", () => {
it("coalesces a burst across tasks and preserves unchanged session identities", async () => {
const row = { key: "websocket:burst", channel: "websocket", chatId: "burst",
createdAt: "2026-09-08", updatedAt: "2026-09-08", preview: "Stable" };
vi.mocked(api.listSessions).mockImplementation(async () => [{ ...row }]);
const client = fakeClient();
const { result, unmount } = renderHook(() => useSessions(), { wrapper: wrap(client) });
await waitFor(() => expect(result.current.sessions).toHaveLength(1));
const original = result.current.sessions;
vi.useFakeTimers();
try {
for (let index = 0; index < 20; index++) {
await act(async () => {
client.emitSessionUpdate("burst");
await vi.advanceTimersByTimeAsync(10);
});
}
expect(api.listSessions).toHaveBeenCalledTimes(1);
await act(async () => { await vi.advanceTimersByTimeAsync(50); });
expect(api.listSessions).toHaveBeenCalledTimes(2);
expect(result.current.sessions).toBe(original);
client.emitSessionUpdate("burst");
unmount();
await vi.advanceTimersByTimeAsync(250);
expect(api.listSessions).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
}
});
beforeEach(() => {
vi.mocked(api.listSessions).mockReset();
vi.mocked(api.deleteSession).mockReset();
@@ -266,8 +295,8 @@ describe("useSessions", () => {
await Promise.resolve();
});
await waitFor(() => expect(result.current.loading).toBe(false));
expect(api.listSessions).toHaveBeenCalledTimes(2);
await waitFor(() => expect(api.listSessions).toHaveBeenCalledTimes(2));
expect(result.current.loading).toBe(false);
});
it("runs one trailing refresh when an update arrives during a session request", async () => {
+11 -2
View File
@@ -51,6 +51,15 @@ describe("entryLazyFeatureImports", () => {
});
describe("webuiManualChunk", () => {
it("groups common and channel translations into one request per locale", () => {
expect(webuiManualChunk("/repo/webui/src/i18n/locales/en/common.json")).toBe("locale-en");
expect(webuiManualChunk("/repo/nanobot/channels/slack/webui/locales/en.json")).toBe("locale-en");
expect(webuiManualChunk("/repo/nanobot/channels/slack/webui/locales/zh-CN.json")).toBe("locale-zh-CN");
expect(webuiManualChunk("/repo/node_modules/rehype-katex/index.js")).toBe("markdown-math");
expect(webuiManualChunk("/repo/webui/src/lib/markdown-math.ts")).toBe("markdown-math");
expect(webuiManualChunk("/repo/node_modules/micromark-extension-math/lib/html.js")).toBe("markdown-math");
expect(webuiManualChunk("/repo/webui/src/lib/clipboard.ts")).toBe("clipboard");
});
it("keeps the React runtime outside lazy feature chunks", () => {
expect(webuiManualChunk("/repo/node_modules/react/index.js")).toBe("react-vendor");
expect(webuiManualChunk("/repo/node_modules/react-dom/client.js")).toBe("react-vendor");
@@ -83,10 +92,10 @@ describe("webuiManualChunk", () => {
it("leaves Streamdown's optional renderers as lazy chunks", () => {
expect(
webuiManualChunk("/repo/node_modules/streamdown/dist/mermaid-ABC.js"),
).toBeUndefined();
).toBe("markdown-diagrams");
expect(
webuiManualChunk("/repo/node_modules/streamdown/dist/highlighted-body-ABC.js"),
).toBeUndefined();
).toBe("markdown-code");
});
it("leaves language grammars as independently loaded chunks", () => {