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

* fix(webui): avoid remounting outgoing conversations

Reset subtask disclosure state within its session scope instead of keying the entire transcript before the stream message handoff. Cover the outgoing DOM lifecycle and disclosure reset with unit and browser regressions.

Resolves NAN-396

* fix(webui): reset transcript UI on message ownership changes

Keep the selected conversation separate from the owner of currently rendered messages. Reset the message subtree only when its owner changes, so cached and forked conversations get fresh UI state without remounting outgoing diffs.

Extend the history-only caller and cover cached fork activity isolation while retaining the outgoing-DOM regression.
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-02 17:42:16 +08:00
1 parent 8b37976d36
commit c1ed649b81
10 files changed
+165 -16

No files matched your search

+2 -1
View File
@@ -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>} />
+96
View File
@@ -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 });
@@ -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 };
});
};
@@ -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}
@@ -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: (
+3
View File
@@ -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,
+2 -2
View File
@@ -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 };
}
+40 -2
View File
@@ -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 }),
@@ -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", {
+2
View File
@@ -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);