Skip to content

Your lightweight open-source personal agent.

fix(webui): avoid remounting outgoing conversations (#6540)

chengyongruc1ed649b8190
diff --git a/webui/browser/history-boundary-fixture.tsx b/webui/browser/history-boundary-fixture.tsx
index 74c2aca66..76d316e11 100644
--- a/webui/browser/history-boundary-fixture.tsx
+++ b/webui/browser/history-boundary-fixture.tsx
@@ -26,7 +26,8 @@ export function HistoryBoundaryFixture({ local = false, navigate = false, tasks
}}>
<SubagentTasksProvider client={client} token={token} sessionKey={key} enabled={tasks} liveEvents={false}>
<ThreadViewport messages={messages} isStreaming={false} conversationKey={key}
- conversationReady={local || !history.loading} hasMoreBefore={history.hasMoreBefore}
+ messagesKey={local ? key : history.messagesKey}
+ conversationReady={local || history.messagesReady && !history.loading} hasMoreBefore={history.hasMoreBefore}
loadingOlder={history.loadingOlder} olderError={history.olderError} onLoadOlder={history.loadOlder}
navigation={navigate ? navigation : undefined} userMessageOffset={history.userMessageOffset}
composer={<div className="border-t px-4 py-6" style={{ height: 96 }}>History boundary fixture</div>} />
diff --git a/webui/browser/history-hydration.spec.ts b/webui/browser/history-hydration.spec.ts
index d53dd5dbb..4b1a1d45d 100644
--- a/webui/browser/history-hydration.spec.ts
+++ b/webui/browser/history-hydration.spec.ts
@@ -270,6 +270,102 @@ test("synthetic HTTP-first cumulative text suppresses delayed covered chunks but
backend.healthy();
});
+test("switching away from file edits does not rebuild the outgoing diff before history hands over", async ({ page }) => {
+ await page.addInitScript(() => {
+ localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({
+ activityMode: "expanded", fileEditDisplayMode: "diff",
+ }));
+ });
+ const { backend, body } = await openFixture(page);
+ const edited = history([
+ input("edited-turn", "Review these synthetic edits"),
+ { ...at("edited-turn", 1, "activity"), event: "file_edit", edits: [
+ { call_id: "edit-1", tool: "edit_file", path: "src/example.ts", phase: "end",
+ status: "done", added: 1, deleted: 1, approximate: false,
+ diff: { format: "unified", text: "--- a/src/example.ts\n+++ b/src/example.ts\n@@ -1 +1 @@\n-const previous = 1;\n+const updated = 2;\n" } },
+ ] },
+ { ...at("edited-turn", 2, "answer"), event: "message", text: "Synthetic edits complete." },
+ { ...at("edited-turn", 3, "complete"), event: "turn_end" },
+ ]);
+ await backend.release(await backend.read(), edited);
+ await expect(body.getByTestId("syntax-highlighted-diff-hunk")).toBeVisible();
+ const additions = await page.evaluateHandle(() => {
+ const state = { diffs: 0 };
+ const observer = new MutationObserver((records) => {
+ for (const record of records) for (const node of record.addedNodes) {
+ if (!(node instanceof Element)) continue;
+ state.diffs += Number(node.matches('[data-testid="file-edit-diff"]'))
+ + node.querySelectorAll('[data-testid="file-edit-diff"]').length;
+ }
+ });
+ observer.observe(document.body, { childList: true, subtree: true });
+ return { state, observer };
+ });
+ await page.getByRole("button", { name: "Conversation B", exact: true }).click();
+ const next = await backend.read(B);
+ expect(await additions.evaluate(({ state, observer }) => {
+ observer.disconnect();
+ return state.diffs;
+ })).toBe(0);
+ await additions.dispose();
+ await backend.release(next, history(closedTurn("other-turn", "Other question", "Other answer.", B), { chatId: B }));
+ await expect(body.getByText("Other answer.", { exact: true })).toBeVisible();
+ await expect(body.getByTestId("file-edit-diff")).toHaveCount(0);
+
+ await page.getByRole("button", { name: "Conversation A", exact: true }).click();
+ await backend.release(await backend.read(A, null, 1), edited);
+ await expect(body.getByTestId("syntax-highlighted-diff-hunk")).toBeVisible();
+ await expect(body.getByText("Synthetic edits complete.", { exact: true })).toBeVisible();
+ backend.healthy();
+});
+
+test("cached conversations with a shared fork prefix reset activity disclosures on message handoff", async ({ page }) => {
+ const { backend, body } = await openFixture(page);
+ const prefix: ThreadProjectionEvent[] = [
+ input("shared-turn", "Shared question"),
+ { ...at("shared-turn", 1, "activity"), event: "message", kind: "tool_hint", text: "Shared activity detail" },
+ { ...at("shared-turn", 2, "answer"), event: "message", text: "Shared answer." },
+ { ...at("shared-turn", 3, "complete"), event: "turn_end" },
+ ];
+ const source = history([...prefix, ...closedTurn("source-turn", "Source question", "Source answer.")]);
+ const fork = history([
+ ...prefix.map((event) => ({ ...event, chat_id: B })),
+ ...closedTurn("fork-turn", "Fork question", "Fork answer.", B),
+ ], { chatId: B });
+ await backend.release(await backend.read(), source);
+ await expect(body.getByText("Source answer.", { exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Conversation B", exact: true }).click();
+ await backend.release(await backend.read(B), fork);
+ await expect(body.getByText("Fork answer.", { exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Conversation A", exact: true }).click();
+ await backend.read(A, null, 1);
+ await expect(body.getByText("Source answer.", { exact: true })).toBeVisible();
+ const sharedBlock = body.locator("[data-thread-display-unit]").filter({ has: page.getByText("Shared answer.", { exact: true }) });
+ await sharedBlock.hover();
+ await sharedBlock.getByRole("button", { name: "Message actions", exact: true }).click();
+ const activity = page.locator("[data-message-block-activity-action]");
+ await expect(activity).toHaveAttribute("aria-expanded", "false");
+ await activity.click();
+ await expect(sharedBlock.getByTestId("agent-activity-content")).toBeVisible();
+
+ await page.getByRole("button", { name: "Conversation B", exact: true }).click();
+ const forkRead = await backend.read(B, null, 1);
+ await expect(body.getByText("Fork answer.", { exact: true })).toBeVisible();
+ await sharedBlock.hover();
+ await sharedBlock.getByRole("button", { name: "Message actions", exact: true }).click();
+ await expect(activity).toHaveAttribute("aria-expanded", "false");
+ await page.keyboard.press("Escape");
+ await backend.release(forkRead, fork);
+
+ await page.getByRole("button", { name: "Conversation A", exact: true }).click();
+ await backend.release(await backend.read(A, null, 2), source);
+ await expect(body.getByText("Source answer.", { exact: true })).toBeVisible();
+ await sharedBlock.hover();
+ await sharedBlock.getByRole("button", { name: "Message actions", exact: true }).click();
+ await expect(activity).toHaveAttribute("aria-expanded", "false");
+ backend.healthy();
+});
+
test("synthetic cache return retains unpainted chunks and the absent conversation's buffered wire tail", async ({ page }) => {
const { backend, body } = await openFixture(page);
const initial = history([input(TURN, "Cache question"), end(3, "Cache answer", "cache-wire", true)], { active: TURN });
diff --git a/webui/src/components/thread/SubagentTaskResults.tsx b/webui/src/components/thread/SubagentTaskResults.tsx
index 6857868fe..c755257cc 100644
--- a/webui/src/components/thread/SubagentTaskResults.tsx
+++ b/webui/src/components/thread/SubagentTaskResults.tsx
@@ -43,23 +43,24 @@ function groupResults(messages: UIMessage[], tasks: ObservedSubagentTask[]) {
export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessages>) {
const context = useSubagentTasks();
- return <ResultsThreadMessages key={context?.sessionKey} {...props} tasks={context?.tasks ?? []} />;
-}
-
-function ResultsThreadMessages({ tasks, ...props }: ComponentProps<typeof ThreadMessages> & { tasks: ObservedSubagentTask[] }) {
- const groups = useMemo(() => groupResults(props.messages, tasks), [props.messages, tasks]);
- const [expandedTaskIds, setExpandedTaskIds] = useState<Set<string>>(() => new Set());
- const expanded = (results: ObservedSubagentTask[]) => results.some(task => expandedTaskIds.has(task.task_id));
+ const sessionKey = context?.sessionKey;
+ const groups = useMemo(() => groupResults(props.messages, context?.tasks ?? []), [props.messages, context?.tasks]);
+ const [archive, setArchive] = useState(() => ({ sessionKey, expanded: new Set<string>() }));
+ // Reset only the disclosures; the outgoing transcript must not remount during handoff.
+ if (archive.sessionKey !== sessionKey) {
+ setArchive({ sessionKey, expanded: new Set<string>() });
+ }
+ const expanded = (results: ObservedSubagentTask[]) => results.some(task => archive.expanded.has(task.task_id));
const toggle = (results: ObservedSubagentTask[]) => {
props.onActivityToggle?.();
- setExpandedTaskIds(current => {
- const next = new Set(current);
- const close = results.some(task => current.has(task.task_id));
+ setArchive(current => {
+ const next = new Set(current.expanded);
+ const close = results.some(task => current.expanded.has(task.task_id));
for (const task of results) {
if (close) next.delete(task.task_id);
else next.add(task.task_id);
}
- return next;
+ return { sessionKey, expanded: next };
});
};
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 0689bbedc..01759f667 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -589,6 +589,7 @@ export function ThreadShell({
}, [chatId, onTurnEnd]);
const {
messages,
+ messagesKey,
messagesReady,
isStreaming,
runStartedAt,
@@ -1499,6 +1500,7 @@ export function ThreadShell({
<ThreadViewport
ref={viewportRef}
messages={displayMessages}
+ messagesKey={messagesKey}
navigation={promptNavigation}
navigationFrame={navigationFrame}
temporary={temporary}
diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx
index 860760334..58850abde 100644
--- a/webui/src/components/thread/ThreadViewport.tsx
+++ b/webui/src/components/thread/ThreadViewport.tsx
@@ -53,6 +53,8 @@ interface ThreadViewportProps {
activeTurnId?: string | null;
activeTurnStartedHere?: boolean;
conversationKey?: string | null;
+ /** Override when message ownership changes after the selected conversation. */
+ messagesKey?: string | null;
conversationReady?: boolean;
showScrollToBottomButton?: boolean;
cliApps?: CliAppInfo[];
@@ -264,6 +266,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
activeTurnId: liveTurnId = null,
activeTurnStartedHere = false,
conversationKey = null,
+ messagesKey = conversationKey,
conversationReady = true,
showScrollToBottomButton = true,
cliApps = [],
@@ -1192,6 +1195,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<div ref={messageContentRef} className="w-full">
<DiagramScope identity={conversationKey}>
<SubagentThreadMessages
+ key={messagesKey}
messages={visibleMessages}
topInset={PROMPT_TOP_INSET_PX}
beforeUnit={retainedHistorySlotKey ? { key: retainedHistorySlotKey, content: (
diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts
index b7f49e3d0..19c3dd045 100644
--- a/webui/src/hooks/useNanobotStream.ts
+++ b/webui/src/hooks/useNanobotStream.ts
@@ -147,6 +147,8 @@ export function useNanobotStream(
historyActiveTurnId: string | null = null,
): {
messages: UIMessage[];
+ /** Conversation owning these messages, including while a selection is handing over. */
+ messagesKey: string | null;
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
messagesReady: boolean;
isStreaming: boolean;
@@ -1073,6 +1075,7 @@ export function useNanobotStream(
return {
messages,
+ messagesKey: messageScope.historyKey ?? messageScope.chatId,
messagesReady: messageScope.chatId === chatId && messageScope.historyKey === historyKey && messageScope.client === client,
isStreaming,
runStartedAt,
diff --git a/webui/src/hooks/useSessions.ts b/webui/src/hooks/useSessions.ts
index dcd7ba8d7..78f8c2ba5 100644
--- a/webui/src/hooks/useSessions.ts
+++ b/webui/src/hooks/useSessions.ts
@@ -206,8 +206,8 @@ export function useSessions(): {
}
export function useSessionHistory(key: string | null) {
- const { messages, history, refreshHistory, loadOlder } = useNanobotStream(
+ const { messages, messagesKey, messagesReady, history, refreshHistory, loadOlder } = useNanobotStream(
null, undefined, false, undefined, undefined, undefined, { key },
);
- return { messages, ...history, refresh: refreshHistory, loadOlder };
+ return { messages, messagesKey, messagesReady, ...history, refresh: refreshHistory, loadOlder };
}
diff --git a/webui/src/tests/subagent-results.test.tsx b/webui/src/tests/subagent-results.test.tsx
index 8ab6cb30c..eca1b12af 100644
--- a/webui/src/tests/subagent-results.test.tsx
+++ b/webui/src/tests/subagent-results.test.tsx
@@ -50,13 +50,14 @@ function emitTask(snapshot: SubagentTaskSnapshot) {
function ResultsPresence() {
return <output data-testid="has-results">{useHasSubagentResults() ? "yes" : "no"}</output>;
}
-function layout({ threadMessages = messages, liveEvents = true, historyEnabled = false, onActivityToggle }: {
+function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEvents = true, historyEnabled = false, onActivityToggle }: {
threadMessages?: UIMessage[];
+ sessionKey?: string;
liveEvents?: boolean;
historyEnabled?: boolean;
onActivityToggle?: () => void;
} = {}) {
- return <SubagentTasksProvider client={client} sessionKey="websocket:a" token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled}>
+ return <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled}>
<ResultsPresence />
<div data-testid="messages"><SubagentThreadMessages messages={threadMessages} onActivityToggle={onActivityToggle} /></div>
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock /><textarea aria-label="Message" /></div>
@@ -175,6 +176,43 @@ describe("subagent result archives", () => {
expect(requestMutation).not.toHaveBeenCalled();
});
+ it("resets task disclosures across sessions without remounting the outgoing transcript", async () => {
+ vi.mocked(fetch).mockImplementation(async (input) => response([
+ task(String(input).includes("websocket%3Ab") ? { task_id: "task-b", label: "Other check" } : {}),
+ ]));
+ const user = userEvent.setup();
+ const view = render(layout());
+ const archive = await screen.findByRole("region", { name: "Subtasks" });
+ await user.click(summary(archive));
+ expect(summary(archive)).toHaveAttribute("aria-expanded", "true");
+ const outgoingPrompt = screen.getByText("Inspect config");
+
+ // The selected session changes before useNanobotStream hands over its messages.
+ view.rerender(layout({ sessionKey: "websocket:b" }));
+ expect(screen.getByText("Inspect config")).toBe(outgoingPrompt);
+ const other = await screen.findByRole("region", { name: "Subtasks" });
+ expect(summary(other)).toHaveAttribute("aria-expanded", "false");
+ await user.click(summary(other));
+ expect(within(other).getByRole("button", { name: "Other check Completed 4s" })).toBeVisible();
+
+ view.rerender(layout({ sessionKey: "websocket:b", threadMessages: [
+ { ...messages[0], id: "prompt-b", content: "Other request" },
+ { ...messages[1], id: "answer-b", content: "Other answer" },
+ ] }));
+ expect(await screen.findByText("Other answer")).toBeVisible();
+ expect(summary(screen.getByRole("region", { name: "Subtasks" }))).toHaveAttribute("aria-expanded", "true");
+
+ view.rerender(layout());
+ const restored = await screen.findByRole("region", { name: "Subtasks" });
+ expect(summary(restored)).toHaveAttribute("aria-expanded", "false");
+ await user.click(summary(restored));
+ expect(within(restored).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
+ view.rerender(layout({ sessionKey: "websocket:b" }));
+ expect(summary(await screen.findByRole("region", { name: "Subtasks" }))).toHaveAttribute("aria-expanded", "false");
+ view.rerender(layout());
+ expect(summary(await screen.findByRole("region", { name: "Subtasks" }))).toHaveAttribute("aria-expanded", "false");
+ });
+
it("prefers the exact initiating prompt and falls back once to the first user message of its turn", async () => {
vi.mocked(fetch).mockImplementation(async () => response([
task({ task_id: "exact", label: "Exact check", origin_message_id: "followup", created_at: 101 }),
diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx
index bdbc92a4b..719c71c01 100644
--- a/webui/src/tests/useNanobotStream.test.tsx
+++ b/webui/src/tests/useNanobotStream.test.tsx
@@ -1014,6 +1014,7 @@ describe("useNanobotStream", () => {
initialProps: { chatId: "chat-old" },
},
);
+ expect(result.current.messagesKey).toBe("chat-old");
act(() => {
fake.emit("chat-old", {
@@ -1024,6 +1025,7 @@ describe("useNanobotStream", () => {
});
rerender({ chatId: "chat-new" });
+ expect(result.current.messagesKey).toBe("chat-new");
act(() => {
fake.emit("chat-new", {
diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsx
index c1c75287a..724cf6a01 100644
--- a/webui/src/tests/useSessions.test.tsx
+++ b/webui/src/tests/useSessions.test.tsx
@@ -939,6 +939,7 @@ describe("useSessions", () => {
});
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.messages[0]?.id).toBe("selected-user");
+ expect(result.current.messagesKey).toBe("websocket:selected");
expect(result.current.hasMoreBefore).toBe(true);
expect(result.current.userMessageOffset).toBe(4);
expect(result.current.hasPendingToolCalls).toBe(true);
@@ -948,6 +949,7 @@ describe("useSessions", () => {
rerender({ sessionKey: null });
expect(result.current.messages).toEqual([]);
+ expect(result.current.messagesKey).toBeNull();
expect(result.current.loading).toBe(false);
expect(result.current.hasMoreBefore).toBe(false);
expect(result.current.userMessageOffset).toBe(0);