Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
perf(webui): reduce repeated work and bound history rendering (#5703)
chengyongru1469d4811c3b
diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.pyindex de0f8a0b5..82addef10 100644--- a/nanobot/webui/transcript.py+++ b/nanobot/webui/transcript.py@@ -1720,6 +1720,7 @@ def replay_transcript_to_ui_messages(messages: list[dict[str, Any]] = []buffer_message_id: str | None = Nonebuffer_parts: list[str] = []+ merge_reasoning_message_id: str | None = Nonesuppress_until_turn_end = Falseactive_activity_segment_id: str | None = Noneactive_file_edit_segment_id: str | None = None@@ -1816,6 +1817,26 @@ def replay_transcript_to_ui_messages(created_at_ms: int | None = None,) -> None:turn_fields = turn_fields or {}+ if buffer_message_id is not None and buffer_message_id == merge_reasoning_message_id:+ for i in range(len(prev) - 1, -1, -1):+ candidate = prev[i]+ if candidate.get("id") != buffer_message_id:+ continue+ if _same_turn(candidate, turn_fields):+ # A length continuation shares the same Markdown answer.+ # Keep its reasoning with that answer, including on replay.+ reasoning = str(candidate.get("reasoning") or "")+ separator = "\n\n" if reasoning and not candidate.get("reasoningStreaming") else ""+ prev[i] = {+ **candidate,+ "reasoning": reasoning + separator + chunk,+ "reasoningStreaming": True,+ }+ return+ break+ if buffer_message_id is not None:+ close_interrupted_assistant()+ close_activity_for_answer()for i in range(len(prev) - 1, -1, -1):candidate = prev[i]if candidate.get("role") == "user":@@ -1882,7 +1903,7 @@ def replay_transcript_to_ui_messages(return str(last.get("id"))def close_interrupted_assistant() -> None:- """Close an answer segment before tool activity without changing its semantics.+ """Close an answer before a new activity phase without changing its semantics.The wire protocol already marks answer, reasoning, and activity phases.A later tool event does not turn previously emitted answer text into@@ -1910,6 +1931,20 @@ def replay_transcript_to_ui_messages(buffer_parts = []return+ def close_buffer_from_other_turn(turn_fields: dict[str, Any]) -> None:+ nonlocal buffer_message_id, buffer_parts+ if buffer_message_id is None:+ return+ for message in reversed(messages):+ if message.get("id") != buffer_message_id:+ continue+ if not _same_turn(message, turn_fields):+ message["isStreaming"] = False+ buffer_message_id = None+ buffer_parts = []+ close_activity_for_answer()+ return+def close_reasoning(prev: list[dict[str, Any]]) -> None:for i in range(len(prev) - 1, -1, -1):if prev[i].get("reasoningStreaming"):@@ -2211,6 +2246,7 @@ def replay_transcript_to_ui_messages(close_activity_for_answer()turn_fields = _turn_fields(rec, "answer")source_fields = _source_fields(rec)+ close_buffer_from_other_turn(turn_fields)adopted = find_active_placeholder(messages, turn_fields) if buffer_message_id is None else Noneif buffer_message_id is None:if adopted:@@ -2251,6 +2287,7 @@ def replay_transcript_to_ui_messages(final_text = rec.get("text")turn_fields = _turn_fields(rec, "answer")source_fields = _source_fields(rec)+ close_buffer_from_other_turn(turn_fields)if isinstance(final_text, str):if buffer_message_id is None:buffer_message_id = find_active_placeholder(messages, turn_fields)@@ -2287,6 +2324,7 @@ def replay_transcript_to_ui_messages(if not merge_next:buffer_message_id = Nonebuffer_parts = []+ merge_reasoning_message_id = buffer_message_id if merge_next else Nonecontinueif ev == "reasoning_delta":diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.pyindex a331b3a7e..ac87b7759 100644--- a/tests/utils/test_webui_transcript.py+++ b/tests/utils/test_webui_transcript.py@@ -4,6 +4,8 @@ from __future__ import annotationsfrom pathlib import Path+import pytest+import nanobot.webui.transcript as transcript_modulefrom nanobot.session.history_visibility import HIDDEN_HISTORY_METAfrom nanobot.webui.transcript import (@@ -1700,6 +1702,34 @@ def test_replay_merges_length_recovery_segments_into_one_assistant_message() ->assert msgs[0]["content"] == "first second"[email protected]("event", ["delta", "stream_end"])+def test_replay_recovery_answer_does_not_overwrite_an_unfinished_turn(event: str) -> None:+ msgs = replay_transcript_to_ui_messages([+ {+ "event": "stream_end", "text": "Original answer", "turn_id": "original",+ "resuming": True, "merge_next": True,+ },+ {"event": event, "text": "Recovered answer", "turn_id": "recovery"},+ {"event": "turn_end", "turn_id": "recovery"},+ ])++ assert [(m["turnId"], m["content"]) for m in msgs] == [+ ("original", "Original answer"), ("recovery", "Recovered answer"),+ ]+++def test_replay_reasoning_after_an_ordinary_answer_preserves_the_answer_boundary() -> None:+ msgs = replay_transcript_to_ui_messages([+ {"event": "delta", "text": "First answer"},+ {"event": "reasoning_end", "text": "Consider the next answer"},+ {"event": "stream_end", "text": "Next answer"},+ {"event": "turn_end"},+ ])++ assert [m["content"] for m in msgs] == ["First answer", "Next answer"]+ assert msgs[1]["reasoning"] == "Consider the next answer"++def test_replay_tool_events_dedupes_finish_after_start() -> None:msgs = replay_transcript_to_ui_messages([{diff --git a/webui/src/App.tsx b/webui/src/App.tsxindex a84fa754e..6cd0facee 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -14,7 +14,7 @@ import { channelUiPresentation } from "@/channel-plugins/registry";import { Sidebar } from "@/components/Sidebar";import type { SidebarDeleteItem } from "@/components/ChatList";import type { SettingsSectionKey } from "@/components/settings/SettingsView";-import { ThreadShell } from "@/components/thread/ThreadShell";+import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";import {MAX_WORKBENCH_PANES,@@ -123,6 +123,9 @@ type ShellRoute = {settingsSection: SettingsSectionKey;temporary?: boolean;};+const ThreadShell = lazy(() => import("@/components/thread/ThreadShell").then(+ (module) => ({ default: module.ThreadShell }),+));const loadSettingsView = () => import("@/components/settings/SettingsView");const SettingsView = lazy(async () => {const module = await loadSettingsView();@@ -141,14 +144,14 @@ const RenameChatDialog = lazy(async () => {return { default: module.RenameChatDialog };});-function SurfaceLoadingFallback() {+function SurfaceLoadingFallback({ label }: { label?: string }) {const { t } = useTranslation();return (<divaria-busy="true"className="flex h-full w-full flex-col gap-5 px-5 py-8 sm:px-8 lg:px-12">- <span className="sr-only">{t("settings.status.loading")}</span>+ <span className="sr-only">{label ?? t("settings.status.loading")}</span><div className="h-4 w-20 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" /><div className="h-9 w-48 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" /><div className="mt-4 h-12 w-full max-w-3xl animate-pulse rounded-md bg-muted/55 motion-reduce:animate-none" />@@ -2617,133 +2620,137 @@ function Shell({view !== "chat" && "hidden",)}>- <PaneWorkbench- panes={renderedWorkbenchPanes}- activePaneKey={renderedActivePaneKey}- layout={renderedWorkbenchLayout}- splitRatios={renderedWorkbenchSplitRatios}- chrome={paneChromeEnabled}- showLayoutControl={activeTabVisible}- addPaneDisabled={creatingPane || activePaneLimitReached}- addPaneDisabledLabel={activePaneLimitReached- ? t("workbench.paneLimit", {- count: MAX_WORKBENCH_PANES,- })- : undefined}- onActivatePane={onActivateWorkbenchPane}- onAddPane={onAddPane}- onLayoutChange={(layout) => {- if (!activeTabKey) return;- updateWorkbenchState((current) => (- setWorkbenchLayout(current, activeTabKey, layout)- ));- }}- onPaneOrderChange={(paneKeys) => {- if (!activeTabKey) return;- updateWorkbenchState((current) => (- setWorkbenchPaneLayoutOrder(current, activeTabKey, paneKeys)- ));- }}- onSplitRatiosChange={(splitRatios) => {- if (!activeTabKey) return;- updateWorkbenchState((current) => (- setWorkbenchSplitRatios(current, activeTabKey, splitRatios)- ));- }}- renderPane={(pane, context) => {- if (!paneChromeEnabled) {- return (- <ThreadShell- session={activeSession}- sessions={sessions}- title={headerTitle}- temporary={temporaryChatRequested}- temporaryChatIds={temporaryChatIds}- temporaryChatEnabled={temporaryChatEnabled}- onTemporaryChatEnabledChange={- !activeKey ? onTemporaryChatEnabledChange : undefined- }- onToggleSidebar={toggleSidebar}- onNewChat={onNewChat}- onCreateChat={- temporaryChatEnabled ? onCreateTemporaryChat : onCreateChat- }- onForkChat={temporaryChatActive ? undefined : onForkChat}- onTurnEnd={onTurnEnd}- theme={theme}- onToggleTheme={toggle}- hideSidebarToggleForHostChrome- hideHeader={false}- workspaceScope={activeWorkspaceScope}- workspaceDefaultScope={workspaces?.default_scope ?? null}- workspaceControls={workspaces?.controls ?? null}- workspaceScopeDisabled={activeChatRunning}- workspaceError={workspaceError}- onWorkspaceScopeChange={applyWorkspaceScope}- settingsSnapshot={settingsSnapshot}- onOpenModelSettings={onOpenModelSettings}- skills={skills}- />- );- }-- const paneSession = workbenchPaneSessions.find(- (session) => session.key === pane.key,- );- if (!paneSession) return null;- const paneScope = workspaceOverrides[paneSession.chatId]- ?? paneSession.workspaceScope- ?? workspaces?.default_scope- ?? null;- const paneRunning = runningChatIds.has(paneSession.chatId);- return (- <ThreadShell- session={paneSession}- sessions={sessions}- title={pane.title}- onToggleSidebar={toggleSidebar}- onNewChat={onNewChat}- onCreateChat={onCreateChat}- onForkChat={onForkChat}- onTurnEnd={context.active ? onTurnEnd : () => void refresh()}- theme={theme}- onToggleTheme={toggle}- hideSidebarToggle={!context.active}- hideSidebarToggleForHostChrome={context.active}- hideThemeButton={!context.active}- hideHeaderTitle- inlineHandle={workbenchPaneSessions.length > 1}- headerActions={context.headerActions}- headerPortalTarget={context.headerPortalTarget}- headerActive={context.active}- composerPortalTarget={context.composerPortalTarget}- composerActive={context.active}- composerInputAriaLabel={t("workbench.composerAria", {- title: pane.title,- })}- emptyComposerVariant="thread"- workspaceScope={paneScope}- workspaceDefaultScope={workspaces?.default_scope ?? null}- workspaceControls={workspaces?.controls ?? null}- workspaceScopeDisabled={paneRunning}- workspaceError={context.active ? workspaceError : null}- onWorkspaceScopeChange={(scope) => {- if (paneRunning) return;- const next = normalizeWorkspaceScope(scope);- setWorkspaceError(null);- setWorkspaceOverrides((current) => ({- ...current,- [paneSession.chatId]: next,- }));- client.setWorkspaceScope(paneSession.chatId, next);- }}- settingsSnapshot={settingsSnapshot}- onOpenModelSettings={onOpenModelSettings}- skills={skills}- />- );- }}- />+ <ThreadVisibilityContext.Provider value={view === "chat"}>+ <Suspense fallback={<SurfaceLoadingFallback label={t("chat.loading")} />}>+ <PaneWorkbench+ panes={renderedWorkbenchPanes}+ activePaneKey={renderedActivePaneKey}+ layout={renderedWorkbenchLayout}+ splitRatios={renderedWorkbenchSplitRatios}+ chrome={paneChromeEnabled}+ showLayoutControl={activeTabVisible}+ addPaneDisabled={creatingPane || activePaneLimitReached}+ addPaneDisabledLabel={activePaneLimitReached+ ? t("workbench.paneLimit", {+ count: MAX_WORKBENCH_PANES,+ })+ : undefined}+ onActivatePane={onActivateWorkbenchPane}+ onAddPane={onAddPane}+ onLayoutChange={(layout) => {+ if (!activeTabKey) return;+ updateWorkbenchState((current) => (+ setWorkbenchLayout(current, activeTabKey, layout)+ ));+ }}+ onPaneOrderChange={(paneKeys) => {+ if (!activeTabKey) return;+ updateWorkbenchState((current) => (+ setWorkbenchPaneLayoutOrder(current, activeTabKey, paneKeys)+ ));+ }}+ onSplitRatiosChange={(splitRatios) => {+ if (!activeTabKey) return;+ updateWorkbenchState((current) => (+ setWorkbenchSplitRatios(current, activeTabKey, splitRatios)+ ));+ }}+ renderPane={(pane, context) => {+ if (!paneChromeEnabled) {+ return (+ <ThreadShell+ session={activeSession}+ sessions={sessions}+ title={headerTitle}+ temporary={temporaryChatRequested}+ temporaryChatIds={temporaryChatIds}+ temporaryChatEnabled={temporaryChatEnabled}+ onTemporaryChatEnabledChange={+ !activeKey ? onTemporaryChatEnabledChange : undefined+ }+ onToggleSidebar={toggleSidebar}+ onNewChat={onNewChat}+ onCreateChat={+ temporaryChatEnabled ? onCreateTemporaryChat : onCreateChat+ }+ onForkChat={temporaryChatActive ? undefined : onForkChat}+ onTurnEnd={onTurnEnd}+ theme={theme}+ onToggleTheme={toggle}+ hideSidebarToggleForHostChrome+ hideHeader={false}+ workspaceScope={activeWorkspaceScope}+ workspaceDefaultScope={workspaces?.default_scope ?? null}+ workspaceControls={workspaces?.controls ?? null}+ workspaceScopeDisabled={activeChatRunning}+ workspaceError={workspaceError}+ onWorkspaceScopeChange={applyWorkspaceScope}+ settingsSnapshot={settingsSnapshot}+ onOpenModelSettings={onOpenModelSettings}+ skills={skills}+ />+ );+ }++ const paneSession = workbenchPaneSessions.find(+ (session) => session.key === pane.key,+ );+ if (!paneSession) return null;+ const paneScope = workspaceOverrides[paneSession.chatId]+ ?? paneSession.workspaceScope+ ?? workspaces?.default_scope+ ?? null;+ const paneRunning = runningChatIds.has(paneSession.chatId);+ return (+ <ThreadShell+ session={paneSession}+ sessions={sessions}+ title={pane.title}+ onToggleSidebar={toggleSidebar}+ onNewChat={onNewChat}+ onCreateChat={onCreateChat}+ onForkChat={onForkChat}+ onTurnEnd={context.active ? onTurnEnd : () => void refresh()}+ theme={theme}+ onToggleTheme={toggle}+ hideSidebarToggle={!context.active}+ hideSidebarToggleForHostChrome={context.active}+ hideThemeButton={!context.active}+ hideHeaderTitle+ inlineHandle={workbenchPaneSessions.length > 1}+ headerActions={context.headerActions}+ headerPortalTarget={context.headerPortalTarget}+ headerActive={context.active}+ composerPortalTarget={context.composerPortalTarget}+ composerActive={context.active}+ composerInputAriaLabel={t("workbench.composerAria", {+ title: pane.title,+ })}+ emptyComposerVariant="thread"+ workspaceScope={paneScope}+ workspaceDefaultScope={workspaces?.default_scope ?? null}+ workspaceControls={workspaces?.controls ?? null}+ workspaceScopeDisabled={paneRunning}+ workspaceError={context.active ? workspaceError : null}+ onWorkspaceScopeChange={(scope) => {+ if (paneRunning) return;+ const next = normalizeWorkspaceScope(scope);+ setWorkspaceError(null);+ setWorkspaceOverrides((current) => ({+ ...current,+ [paneSession.chatId]: next,+ }));+ client.setWorkspaceScope(paneSession.chatId, next);+ }}+ settingsSnapshot={settingsSnapshot}+ onOpenModelSettings={onOpenModelSettings}+ skills={skills}+ />+ );+ }}+ />+ </Suspense>+ </ThreadVisibilityContext.Provider></div>{view !== "chat" && (<div className="absolute inset-0 flex flex-col">diff --git a/webui/src/components/CodeBlock.tsx b/webui/src/components/CodeBlock.tsxindex 309200b88..fe385ba4c 100644--- a/webui/src/components/CodeBlock.tsx+++ b/webui/src/components/CodeBlock.tsx@@ -1,4 +1,4 @@-import { Suspense, lazy, useCallback, useState, type ReactNode } from "react";+import { Suspense, lazy, useCallback, useMemo, useState, type ReactNode } from "react";import { Check, Copy } from "lucide-react";import { useTranslation } from "react-i18next";@@ -138,7 +138,7 @@ function CodeTextBlock({className?: string;renderText?: (value: string) => ReactNode;}) {- const lines = code.split("\n");+ const lines = showLineNumbers ? code.split("\n") : [];return (<preclassName={cn(@@ -184,19 +184,20 @@ export function CodeBlock({}: CodeBlockProps) {const { t } = useTranslation();const [copied, setCopied] = useState(false);+ const renderAnsi = useMemo(() => shouldRenderAnsi(language, code), [language, code]);+ const plainCode = useMemo(() => renderAnsi ? stripAnsi(code) : code, [renderAnsi, code]);const isDark = useThemeValue() === "dark";const hasChrome = chrome === "default";- const renderAnsi = shouldRenderAnsi(language, code);const syntaxLanguage = normalizeCodeLanguage(language);const copyLabel = copied ? t("code.copied") : t("code.copyAria");const onCopy = useCallback(() => {- void copyTextToClipboard(renderAnsi ? stripAnsi(code) : code).then((ok) => {+ void copyTextToClipboard(plainCode).then((ok) => {if (!ok) return;setCopied(true);setTimeout(() => setCopied(false), 1_500);});- }, [code, renderAnsi]);+ }, [plainCode]);return (<divdiff --git a/webui/src/components/MarkdownTextRenderer.tsx b/webui/src/components/MarkdownTextRenderer.tsxindex 7a87a60ca..9c5019d43 100644--- a/webui/src/components/MarkdownTextRenderer.tsx+++ b/webui/src/components/MarkdownTextRenderer.tsx@@ -7,7 +7,6 @@ import {type ReactNode,} from "react";import { useTranslation } from "react-i18next";-import rehypeKatex from "rehype-katex";import { Check, Globe2 } from "lucide-react";import remarkBreaks from "remark-breaks";import remarkGfm from "remark-gfm";@@ -35,7 +34,6 @@ import { browserSafeFaviconUrls } from "@/lib/provider-brand";import { remarkTexMath } from "@/lib/remark-tex-math";import { cn } from "@/lib/utils";-import "katex/dist/katex.min.css";import "streamdown/styles.css";interface MarkdownTextRendererProps {@@ -285,7 +283,19 @@ const remarkPlugins: NonNullable<StreamdownProps["remarkPlugins"]> = [remarkCjkStrongBoundaries,remarkSafeHtmlSubset,];-const rehypePlugins: NonNullable<StreamdownProps["rehypePlugins"]> = [rehypeKatex];+type MathPlugin = typeof import("@/lib/markdown-math").default;+let loadedMathPlugin: MathPlugin | undefined;+let mathPluginPromise: Promise<MathPlugin> | undefined;++function loadMathPlugin(): Promise<MathPlugin> {+ return mathPluginPromise ??= import("@/lib/markdown-math").then((module) => {+ loadedMathPlugin = module.default;+ return module.default;+ }).catch((error) => {+ mathPluginPromise = undefined;+ throw error;+ });+}// Remend mistakes math comparisons like `j<i` for incomplete HTML and truncates// the remaining text. HTML is handled by remarkSafeHtmlSubset, not raw rendering.@@ -522,6 +532,20 @@ export default function MarkdownTextRenderer({onOpenFilePreview,}: MarkdownTextRendererProps) {const { t } = useTranslation();+ const [mathPlugin, setMathPlugin] = useState(() => loadedMathPlugin);+ const needsMath = /\$|\\[([]/.test(children);+ useEffect(() => {+ if (!needsMath || mathPlugin) return;+ let cancelled = false;+ void loadMathPlugin().then((plugin) => {+ if (!cancelled) setMathPlugin(() => plugin);+ }).catch(() => {});+ return () => { cancelled = true; };+ }, [needsMath, mathPlugin]);+ const rehypePlugins = useMemo<NonNullable<StreamdownProps["rehypePlugins"]>>(+ () => needsMath && mathPlugin ? [mathPlugin] : [],+ [needsMath, mathPlugin],+ );const components = useMemo<Components>(() => ({code({ className: cls, children: kids, node: _node, ...props }) {@@ -798,6 +822,7 @@ export default function MarkdownTextRenderer({return (<Streamdown+ key={needsMath && mathPlugin ? "math" : "text"}mode={streaming ? "streaming" : "static"}parseIncompleteMarkdownremend={REMEND_OPTIONS}diff --git a/webui/src/components/SessionSearchDialog.tsx b/webui/src/components/SessionSearchDialog.tsxindex dd72b4e8c..6692c97a6 100644--- a/webui/src/components/SessionSearchDialog.tsx+++ b/webui/src/components/SessionSearchDialog.tsx@@ -22,31 +22,42 @@ interface SessionSearchDialogProps {onSelect: (key: string) => void;}+const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};+export function SessionSearchDialog({open,sessions,activeKey,loading,- titleOverrides = {},+ titleOverrides = EMPTY_TITLE_OVERRIDES,onOpenChange,onSelect,}: SessionSearchDialogProps) {const { t } = useTranslation();const inputRef = useRef<HTMLInputElement>(null);+ const scrollRef = useRef<HTMLDivElement>(null);+ const [scrollTop, setScrollTop] = useState(0);const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);const [query, setQuery] = useState("");const [highlightedIndex, setHighlightedIndex] = useState(0);const normalizedQuery = query.trim().toLowerCase();+ const searchableSessions = useMemo(() => sessions.map((session) => ({+ session,+ text: [titleOverrides[session.key], session.title, visibleSessionPreview(session.preview)]+ .filter(Boolean).join(" ").toLowerCase(),+ })), [sessions, titleOverrides]);const sessionResults = useMemo(() => {if (!open) return [];if (!normalizedQuery) return sessions;const terms = normalizedQuery.split(/\s+/).filter(Boolean);- return sessions.filter((session) =>- sessionMatchesTerms(session, terms, titleOverrides[session.key]),- );- }, [normalizedQuery, open, sessions, titleOverrides]);+ return searchableSessions.filter(({ text }) => terms.every((term) => text.includes(term)))+ .map(({ session }) => session);+ }, [normalizedQuery, open, sessions, searchableSessions]);const itemCount = sessionResults.length;+ const rowHeight = 64;+ const windowStart = Math.max(0, Math.min(itemCount - 1, Math.floor(scrollTop / rowHeight) - 4));+ const windowEnd = Math.min(itemCount, windowStart + 24);useEffect(() => {if (!open) return;@@ -57,6 +68,8 @@ export function SessionSearchDialog({useEffect(() => {setHighlightedIndex(0);+ setScrollTop(0);+ if (scrollRef.current) scrollRef.current.scrollTop = 0;}, [normalizedQuery]);useEffect(() => {@@ -71,6 +84,14 @@ export function SessionSearchDialog({useEffect(() => {if (!open) return;+ const scroller = scrollRef.current;+ if (scroller) {+ const top = highlightedIndex * rowHeight;+ if (top < scroller.scrollTop || top + rowHeight > scroller.scrollTop + scroller.clientHeight) {+ scroller.scrollTop = top;+ setScrollTop(top);+ }+ }itemRefs.current[highlightedIndex]?.scrollIntoView({block: "nearest",inline: "nearest",@@ -143,6 +164,8 @@ export function SessionSearchDialog({</div><div+ ref={scrollRef}+ onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}data-testid="session-search-scroll"className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent">@@ -160,8 +183,10 @@ export function SessionSearchDialog({{emptyLabel}</div>) : (- <ul className="space-y-0.5">- {sessionResults.map((session, index) => {+ <ul>+ <li aria-hidden style={{ height: windowStart * rowHeight }} />+ {sessionResults.slice(windowStart, windowEnd).map((session, offset) => {+ const index = windowStart + offset;const title = titleOverrides[session.key]?.trim() ||session.title?.trim() ||deriveTitle(session.preview, t("chat.newChat"));@@ -172,7 +197,7 @@ export function SessionSearchDialog({const highlighted = index === highlightedIndex;const active = session.key === activeKey;return (- <li key={session.key}>+ <li key={session.key} style={{ height: rowHeight }}><buttonref={(node) => {itemRefs.current[index] = node;@@ -182,7 +207,7 @@ export function SessionSearchDialog({onMouseEnter={() => setHighlightedIndex(index)}aria-current={active ? "page" : undefined}className={cn(- "grid min-h-[54px] w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-control px-3 py-2 text-left transition-colors",+ "grid h-full w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-control px-3 py-2 text-left transition-colors",highlighted? "bg-muted text-foreground": "text-foreground hover:bg-muted",@@ -209,6 +234,7 @@ export function SessionSearchDialog({</li>);})}+ <li aria-hidden style={{ height: (itemCount - windowEnd) * rowHeight }} /></ul>)}</section>@@ -217,20 +243,3 @@ export function SessionSearchDialog({</Dialog>);}--function sessionMatchesTerms(- session: ChatSummary,- terms: string[],- titleOverride?: string,-) {- const haystack = [- titleOverride,- session.title,- visibleSessionPreview(session.preview),- ]- .filter(Boolean)- .join(" ")- .toLowerCase();-- return terms.every((term) => haystack.includes(term));-}diff --git a/webui/src/components/thread/AgentActivityCluster.tsx b/webui/src/components/thread/AgentActivityCluster.tsxindex d204ca3b8..1c74c27ab 100644--- a/webui/src/components/thread/AgentActivityCluster.tsx+++ b/webui/src/components/thread/AgentActivityCluster.tsx@@ -1,5 +1,6 @@import {Fragment,+ memo,useCallback,useEffect,useLayoutEffect,@@ -53,6 +54,7 @@ import {import { useFileEditDisplayMode } from "@/hooks/useFileEditDisplayMode";import { useLogoFallback } from "@/hooks/useLogoFallback";import { usePageVisibility } from "@/hooks/usePageVisibility";+import { useThreadVisibility } from "@/hooks/useThreadVisibility";import type { FileEditDisplayMode } from "@/lib/local-preferences";import { logoFallbackUrls } from "@/lib/provider-brand";import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";@@ -67,6 +69,8 @@ import type {} from "@/lib/types";const ACTIVITY_SCROLL_NEAR_BOTTOM_PX = 24;+const EMPTY_CLI_APPS: CliAppInfo[] = [];+const EMPTY_MCP_PRESETS: McpPresetInfo[] = [];export { isAgentActivityMember };@@ -222,13 +226,14 @@ function FoldedAgentActivity({turnLatencyMs,startedAtMs,retryStatus = null,- cliApps = [],- mcpPresets = [],+ cliApps = EMPTY_CLI_APPS,+ mcpPresets = EMPTY_MCP_PRESETS,onOpenFilePreview,}: AgentActivityClusterProps) {const { t } = useTranslation();const fileEditDisplayMode = useFileEditDisplayMode();const pageVisible = usePageVisibility();+ const threadVisible = useThreadVisibility();const activityMessages = useMemo(() => coalesceActivityMessages(messages), [messages]);const fileEditsByMessage = useMemo(() => summarizeFileEditsByMessage(activityMessages, isTurnStreaming),@@ -393,11 +398,11 @@ function FoldedAgentActivity({useEffect(() => cancelActivityScrollFrame, [cancelActivityScrollFrame]);useEffect(() => {- if (!isTurnStreaming || !pageVisible) return undefined;+ if (!isTurnStreaming || !pageVisible || !threadVisible) return undefined;setNow(Date.now());const interval = window.setInterval(() => setNow(Date.now()), 1_000);return () => window.clearInterval(interval);- }, [isTurnStreaming, pageVisible]);+ }, [isTurnStreaming, pageVisible, threadVisible]);useEffect(() => {const wasStreaming = wasTurnStreamingRef.current;@@ -509,7 +514,7 @@ function traceLines(message: UIMessage): string[] {return message.content.trim() ? [message.content] : [];}-function ActivityMessageTimeline({+const ActivityMessageTimeline = memo(function ActivityMessageTimeline({messages,active,cliAppsByName,@@ -570,7 +575,7 @@ function ActivityMessageTimeline({}});return <>{items}</>;-}+});/*** Keep an intermediate assistant segment as normal Markdown. The activitydiff --git a/webui/src/components/thread/PromptRail.tsx b/webui/src/components/thread/PromptRail.tsxindex 2f254fcb1..07e8a0a8a 100644--- a/webui/src/components/thread/PromptRail.tsx+++ b/webui/src/components/thread/PromptRail.tsx@@ -14,7 +14,6 @@ import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surfimport { cn } from "@/lib/utils";import type { UIMessage } from "@/lib/types";import {- findPromptElement,type PromptAnchor,promptTop,userPromptAnchors,@@ -51,7 +50,6 @@ const MARKER_MIN_GAP_PX = 9;const MARKER_BASE_WIDTH_PX = 9;const MARKER_STACK_GAP_PX = 16;const RAIL_FALLBACK_HEIGHT_PX = 300;-const MEASURE_RETRY_FRAMES = 4;const HOVER_MARKER_WIDTHS_PX = [28, 22, 16, 11];export function PromptRail({@@ -101,20 +99,7 @@ export function PromptRail({setActivePromptId((current) => current === next ? current : next);}, [scrollRef]);- useEffect(() => {- let frame = 0;- let remainingFrames = MEASURE_RETRY_FRAMES;- const measure = () => {- updateMarkers();- remainingFrames -= 1;- if (remainingFrames > 0) {- frame = window.requestAnimationFrame(measure);- }- };- measure();- return () => window.cancelAnimationFrame(frame);- }, [bottomOffset, updateMarkers]);-+ const railVisible = markers.length > 0;useEffect(() => {const scrollEl = scrollRef.current;if (!scrollEl) return undefined;@@ -126,28 +111,30 @@ export function PromptRail({scrollFrame = window.requestAnimationFrame(updateActivePrompt);};const scheduleMeasurement = () => {- window.cancelAnimationFrame(resizeFrame);- resizeFrame = window.requestAnimationFrame(updateMarkers);+ if (resizeFrame) return;+ resizeFrame = window.requestAnimationFrame(() => {+ resizeFrame = 0;+ updateMarkers();+ });};+ scheduleMeasurement();+ const observer = typeof ResizeObserver === "undefined"+ ? null+ : new ResizeObserver(scheduleMeasurement);+ observer?.observe(scrollEl);+ if (scrollEl.firstElementChild) observer?.observe(scrollEl.firstElementChild);+ if (railRef.current) observer?.observe(railRef.current);scrollEl.addEventListener("scroll", scheduleActivePrompt, { passive: true });window.addEventListener("resize", scheduleMeasurement);return () => {window.cancelAnimationFrame(scrollFrame);window.cancelAnimationFrame(resizeFrame);+ observer?.disconnect();scrollEl.removeEventListener("scroll", scheduleActivePrompt);window.removeEventListener("resize", scheduleMeasurement);};- }, [scrollRef, updateActivePrompt, updateMarkers]);-- useEffect(() => {- const scrollEl = scrollRef.current;- if (!scrollEl || typeof ResizeObserver === "undefined") return undefined;- const observer = new ResizeObserver(() => updateMarkers());- observer.observe(scrollEl);- if (scrollEl.firstElementChild) observer.observe(scrollEl.firstElementChild);- return () => observer.disconnect();- }, [scrollRef, updateMarkers]);+ }, [bottomOffset, railVisible, scrollRef, updateActivePrompt, updateMarkers]);if (markers.length === 0) return null;@@ -250,8 +237,13 @@ function measurePrompts(anchors: PromptAnchor[],scrollRange: number,): MeasuredPrompt[] {+ const elements = new Map<string, HTMLElement>();+ for (const element of scrollEl.querySelectorAll<HTMLElement>("[data-user-prompt-id]")) {+ const id = element.dataset.userPromptId;+ if (id !== undefined && !elements.has(id)) elements.set(id, element);+ }return anchors.flatMap((anchor) => {- const target = findPromptElement(scrollEl, anchor.id);+ const target = elements.get(anchor.id);if (!target) return [];const top = Math.max(0, Math.min(scrollRange, promptTop(scrollEl, target) - 16));return [{diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsxindex 24211c5da..77f1ab359 100644--- a/webui/src/components/thread/ThreadMessages.tsx+++ b/webui/src/components/thread/ThreadMessages.tsx@@ -1,4 +1,4 @@-import { memo, useCallback, useMemo, useRef } from "react";+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { MessageBubble } from "@/components/MessageBubble";import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";@@ -281,24 +281,41 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({onOpenFilePreview,onForkFromMessage,}: ThreadDisplayUnitProps) {- // Introducing content-visibility after a unit has painted can move the- // browser's scroll anchor. Only units deferred on their first render may- // remain deferred.- const hasRenderedEagerlyRef = useRef(!deferOffscreenRender);- if (!deferOffscreenRender) hasRenderedEagerlyRef.current = true;- const stableDeferOffscreenRender =- deferOffscreenRender && !hasRenderedEagerlyRef.current;+ const elementRef = useRef<HTMLDivElement>(null);+ const heightRef = useRef(0);+ const [nearViewport, setNearViewport] = useState(true);+ const [interacted, setInteracted] = useState(false);+ const retainContent = !deferOffscreenRender || interacted || nearViewport;+ useEffect(() => {+ const element = elementRef.current;+ if (!element || !deferOffscreenRender || interacted || typeof IntersectionObserver === "undefined") return;+ const observer = new IntersectionObserver(([entry]) => {+ if (!entry) return;+ if (!entry.isIntersecting) {+ const height = element.getBoundingClientRect().height;+ if (height <= 0) return;+ heightRef.current = height;+ }+ setNearViewport(entry.isIntersecting);+ }, { rootMargin: "1000px 0px" });+ observer.observe(element);+ return () => observer.disconnect();+ }, [deferOffscreenRender, interacted]);const onForkFromHere = useCallback(() => {if (forkIndex !== undefined) onForkFromMessage?.(forkIndex);}, [forkIndex, onForkFromMessage]);return (<><div- className={`${marginTop}${stableDeferOffscreenRender ? " thread-render-unit" : ""}`}+ ref={elementRef}+ className={marginTop}+ style={retainContent ? undefined : { height: heightRef.current }}+ onPointerDownCapture={() => setInteracted(true)}+ onFocusCapture={() => setInteracted(true)}data-thread-display-unit={unitKey}data-user-prompt-id={userPromptId}>- {unit.type === "activity" ? (+ {retainContent ? unit.type === "activity" ? (<AgentActivityClustermessages={unit.messages}isTurnStreaming={isTurnStreaming}@@ -321,7 +338,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({onOpenFilePreview={onOpenFilePreview}onForkFromHere={forkIndex !== undefined ? onForkFromHere : undefined}/>- )}+ ) : null}</div>{showForkBoundary ? <ForkBoundaryDivider label={forkBoundaryLabel} /> : null}</>diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsxindex 9c1caaf4e..a7f2c34d9 100644--- a/webui/src/components/thread/ThreadShell.tsx+++ b/webui/src/components/thread/ThreadShell.tsx@@ -51,6 +51,7 @@ import type {WorkspacesPayload,} from "@/lib/types";import { projectWebuiThreadMessages } from "@/lib/thread-display-compat";+import { ThreadMessageCache } from "@/lib/thread-message-cache";import { useClient } from "@/providers/ClientProvider";type MessageShape = Pick<UIMessage, "role" | "kind" | "content" | "isStreaming" | "turnId">;@@ -789,8 +790,10 @@ export function ThreadShell({const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);const viewportRef = useRef<ThreadViewportHandle | null>(null);const activeViewportTurnByChatIdRef = useRef<Map<string, string>>(new Map());- const messageCacheRef = useRef<Map<string, UIMessage[]>>(new Map());const knownTemporaryChatIdsRef = useRef(new Set<string>());+ const messageCacheRef = useRef(new ThreadMessageCache(+ (key) => knownTemporaryChatIdsRef.current.has(key),+ ));/** Last chatId we associated with the in-memory thread (for cache-on-switch). */const prevChatIdForCacheRef = useRef<string | null>(null);/** Skip one message-cache write right after chatId changes (messages may not match yet). */diff --git a/webui/src/components/thread/activity/ThinkingReasoningShell.tsx b/webui/src/components/thread/activity/ThinkingReasoningShell.tsxindex 275bf52c4..769233212 100644--- a/webui/src/components/thread/activity/ThinkingReasoningShell.tsx+++ b/webui/src/components/thread/activity/ThinkingReasoningShell.tsx@@ -1,5 +1,5 @@import { ChevronDown } from "lucide-react";-import type { ReactNode, Ref } from "react";+import { useState, type ReactNode, type Ref } from "react";import { cn } from "@/lib/utils";@@ -30,6 +30,8 @@ export function ThinkingReasoningShell({onToggle,onScroll,}: ThinkingReasoningShellProps) {+ const [hasExpanded, setHasExpanded] = useState(expanded);+ if (expanded && !hasExpanded) setHasExpanded(true);return (<divclassName="flex w-full max-w-[45rem] animate-in flex-col fade-in duration-300 motion-reduce:animate-none"@@ -109,7 +111,7 @@ export function ThinkingReasoningShell({className="mt-1.5 max-h-[180px] overflow-y-auto pr-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"><div ref={contentRef} className="flex flex-col gap-0.5">- {children}+ {hasExpanded ? children : null}</div></div>{fadeTop ? (diff --git a/webui/src/components/thread/activity/activity-message-model.ts b/webui/src/components/thread/activity/activity-message-model.tsindex ec7d13da2..be14d1a02 100644--- a/webui/src/components/thread/activity/activity-message-model.ts+++ b/webui/src/components/thread/activity/activity-message-model.ts@@ -13,33 +13,48 @@ import type { UIMediaAttachment, UIMessage } from "@/lib/types";*/export function coalesceActivityMessages(messages: UIMessage[]): UIMessage[] {const normalized: UIMessage[] = [];+ const calls = new Map<string, { latest: number; byTurn: Map<string, number> }>();for (const message of messages) {- const targetIndex = findMergeTarget(normalized, message);+ let targetIndex = -1;+ if (message.kind === "trace") {+ for (const event of message.toolEvents ?? []) {+ if (!event.call_id) continue;+ const call = calls.get(event.call_id);+ if (!call) continue;+ const index = message.turnId+ ? Math.max(call.byTurn.get(message.turnId) ?? -1, call.byTurn.get("") ?? -1)+ : call.latest;+ targetIndex = Math.max(targetIndex, index);+ }+ if (targetIndex < 0 && canMergeAdjacentProgress(normalized.at(-1), message)) {+ targetIndex = normalized.length - 1;+ }+ }if (targetIndex < 0) {+ targetIndex = normalized.length;normalized.push(message);- continue;+ } else {+ normalized[targetIndex] = mergeTraceMessages(normalized[targetIndex], message);+ }+ if (message.kind !== "trace") continue;+ // Merging preserves the target's turn. Legacy rows without a turn match any turn.+ const turn = normalized[targetIndex].turnId || "";+ for (const event of message.toolEvents ?? []) {+ if (!event.call_id) continue;+ let call = calls.get(event.call_id);+ if (!call) {+ call = { latest: targetIndex, byTurn: new Map() };+ calls.set(event.call_id, call);+ }+ call.latest = Math.max(call.latest, targetIndex);+ call.byTurn.set(turn, Math.max(call.byTurn.get(turn) ?? -1, targetIndex));}- normalized[targetIndex] = mergeTraceMessages(normalized[targetIndex], message);}return normalized;}-function findMergeTarget(messages: UIMessage[], incoming: UIMessage): number {- if (incoming.kind !== "trace") return -1;-- for (let index = messages.length - 1; index >= 0; index -= 1) {- const previous = messages[index];- if (previous.kind !== "trace") continue;- if (hasSharedToolCall(previous, incoming) && sameTurn(previous, incoming)) return index;- }-- const adjacentIndex = messages.length - 1;- const adjacent = messages[adjacentIndex];- return canMergeAdjacentProgress(adjacent, incoming) ? adjacentIndex : -1;-}-function canMergeAdjacentProgress(previous: UIMessage | undefined,incoming: UIMessage,@@ -87,15 +102,6 @@ function messageTraces(message: UIMessage): string[] {return message.content.trim() ? [message.content] : [];}-function hasSharedToolCall(previous: UIMessage, incoming: UIMessage): boolean {- const previousCallIds = new Set(- (previous.toolEvents ?? []).map((event) => event.call_id).filter(Boolean),- );- return (incoming.toolEvents ?? []).some((event) => (- !!event.call_id && previousCallIds.has(event.call_id)- ));-}-function hasSharedTrace(previous: UIMessage, incoming: UIMessage): boolean {const previousTraces = new Set(messageTraces(previous).map(canonicalToolTrace));return messageTraces(incoming).some((trace) => previousTraces.has(canonicalToolTrace(trace)));diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.tsindex 8cba3dbec..88e05e972 100644--- a/webui/src/hooks/useNanobotStream.ts+++ b/webui/src/hooks/useNanobotStream.ts@@ -1,6 +1,7 @@import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import { useThreadVisibility } from "@/hooks/useThreadVisibility";import { useClient } from "@/providers/ClientProvider";import { toMediaAttachment } from "@/lib/media";@@ -49,6 +50,7 @@ import type {interface StreamBuffer {/** ID of the assistant message currently receiving deltas (cleared when its segment closes). */messageId: string;+ mergeReasoning?: boolean;}interface ActiveAssistantCursor {@@ -274,6 +276,9 @@ export function useNanobotStream(dismissStreamError: () => void;} {const { client } = useClient();+ const threadVisible = useThreadVisibility();+ const threadVisibleRef = useRef(threadVisible);+ threadVisibleRef.current = threadVisible;const { t } = useTranslation();const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;const [messages, setMessages] = useState<UIMessage[]>(initialMessages);@@ -509,7 +514,7 @@ export function useNanobotStream(};closedAssistantStreamIdsRef.current.delete(merged.id);activeAssistantRef.current = { id: merged.id, index: targetIndex };- buffer.current = { messageId: merged.id };+ if (buffer.current?.messageId !== merged.id) buffer.current = { messageId: merged.id };return replaceMessageAt(next, targetIndex, merged);},[resolveActiveAssistantIndex],@@ -518,26 +523,59 @@ export function useNanobotStream(const applyPendingStreamEvents = useCallback((prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => {let next = prev;- for (const event of events) {+ for (let index = 0; index < events.length; index++) {+ const event = events[index];+ const chunks = [event.text];+ let turn = event.turn;+ while (index + 1 < events.length) {+ const nextEvent = events[index + 1];+ if (nextEvent.kind !== event.kind+ || nextEvent.turn.turnId !== event.turn.turnId+ || nextEvent.turn.turnPhase !== event.turn.turnPhase+ || (nextEvent.kind === "delta" && event.kind === "delta" && nextEvent.source !== event.source)) break;+ chunks.push(nextEvent.text);+ turn = { ...turn, ...nextEvent.turn };+ index++;+ }+ const text = chunks.join("");if (event.kind === "delta") {- next = appendAnswerChunk(next, event.text, event.turn, event.source);+ next = appendAnswerChunk(next, text, turn, event.source);} else {+ const continuationIndex = buffer.current?.mergeReasoning+ ? resolveActiveAssistantIndex(next, turn)+ : null;+ if (continuationIndex !== null) {+ // Length continuation keeps one Markdown answer and its reasoning+ // together. Ordinary reasoning still opens a new activity surface.+ const target = next[continuationIndex];+ const separator = target.reasoning && !target.reasoningStreaming ? "\n\n" : "";+ next = replaceMessageAt(next, continuationIndex, {+ ...target,+ reasoning: (target.reasoning ?? "") + separator + text,+ reasoningStreaming: true,+ });+ continue;+ }if (closeActiveAssistantStream()) clearActivitySegment();next = attachReasoningChunk(next,- event.text,+ text,{ ensure: ensureActivitySegmentId },- event.turn,+ turn,);}}return next;},- [appendAnswerChunk, clearActivitySegment, closeActiveAssistantStream, ensureActivitySegmentId],+ [+ appendAnswerChunk, clearActivitySegment, closeActiveAssistantStream,+ ensureActivitySegmentId, resolveActiveAssistantIndex,+ ],);const flushPendingStreamEvents = useCallback((options?: {closeAnswerSegment?: boolean;+ mergeReasoning?: boolean;finalAnswerText?: string;turn?: UIMessageTurnFields;source?: UIMessage["source"];@@ -554,7 +592,8 @@ export function useNanobotStream(const finalAnswerText = options?.finalAnswerText;const turn = options?.turn ?? {};const source = options?.source;- if (events.length === 0 && finalAnswerText === undefined && source === undefined) {+ if (events.length === 0 && finalAnswerText === undefined && source === undefined+ && !options?.mergeReasoning) {if (options?.closeAnswerSegment) closeActiveAssistantStream();return;}@@ -614,6 +653,7 @@ export function useNanobotStream(});}}+ if (options?.mergeReasoning && buffer.current) buffer.current.mergeReasoning = true;if (options?.closeAnswerSegment) closeActiveAssistantStream();return next;});@@ -621,7 +661,7 @@ export function useNanobotStream(const schedulePendingStreamFlush = useCallback(() => {if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;- if (document.visibilityState === "hidden") {+ if (document.visibilityState === "hidden" || !threadVisibleRef.current) {streamTimerRef.current = window.setTimeout(() => {streamTimerRef.current = null;const events = pendingStreamEventsRef.current;@@ -640,9 +680,19 @@ export function useNanobotStream(});}, [applyPendingStreamEvents]);+ useEffect(() => {+ if (threadVisible) {+ flushPendingStreamEvents();+ } else if (streamFrameRef.current !== null) {+ window.cancelAnimationFrame(streamFrameRef.current);+ streamFrameRef.current = null;+ schedulePendingStreamFlush();+ }+ }, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]);+useEffect(() => {const flushOnReturn = () => {- if (document.visibilityState !== "visible") return;+ if (document.visibilityState !== "visible" || !threadVisibleRef.current) return;if (pendingStreamEventsRef.current.length === 0) return;flushPendingStreamEvents();};@@ -852,6 +902,7 @@ export function useNanobotStream(const mergeNext = ev.resuming === true && ev.merge_next === true;flushPendingStreamEvents({closeAnswerSegment: !mergeNext,+ mergeReasoning: mergeNext,...(typeof ev.text === "string" ? { finalAnswerText: ev.text } : {}),turn,source: ev.source,diff --git a/webui/src/hooks/useSessions.ts b/webui/src/hooks/useSessions.tsindex 60a461f69..d5991263e 100644--- a/webui/src/hooks/useSessions.ts+++ b/webui/src/hooks/useSessions.ts@@ -159,14 +159,21 @@ export function useSessions(): {try {const rows = await listSessions(tokenRef.current);const serverKeys = new Set(rows.map((row) => row.key));- setSessions((prev) => [- ...rows,- ...prev.filter(- (session) =>- optimisticKeysRef.current.has(session.key)- && !serverKeys.has(session.key),- ),- ]);+ setSessions((prev) => {+ const byKey = new Map(prev.map((row) => [row.key, row]));+ const next = [+ ...rows.map((row) => {+ const previous = byKey.get(row.key);+ return previous && JSON.stringify(previous) === JSON.stringify(row) ? previous : row;+ }),+ ...prev.filter(+ (session) =>+ optimisticKeysRef.current.has(session.key)+ && !serverKeys.has(session.key),+ ),+ ];+ return next.length === prev.length && next.every((row, index) => row === prev[index]) ? prev : next;+ });for (const key of Array.from(optimisticKeysRef.current)) {if (serverKeys.has(key)) optimisticKeysRef.current.delete(key);}@@ -191,18 +198,16 @@ export function useSessions(): {}, [refresh]);useEffect(() => {- let disposed = false;- let refreshQueued = false;+ let timer: ReturnType<typeof setTimeout> | undefined;const unsubscribe = client.onSessionUpdate(() => {- if (refreshQueued) return;- refreshQueued = true;- queueMicrotask(() => {- refreshQueued = false;- if (!disposed) void refresh();- });+ if (timer !== undefined) return;+ timer = setTimeout(() => {+ timer = undefined;+ void refresh();+ }, 250);});return () => {- disposed = true;+ clearTimeout(timer);unsubscribe();};}, [client, refresh]);diff --git a/webui/src/hooks/useThreadVisibility.ts b/webui/src/hooks/useThreadVisibility.tsnew file mode 100644index 000000000..f06d3ee05--- /dev/null+++ b/webui/src/hooks/useThreadVisibility.ts@@ -0,0 +1,6 @@+import { createContext, useContext } from "react";++export const ThreadVisibilityContext = createContext(true);+export function useThreadVisibility(): boolean {+ return useContext(ThreadVisibilityContext);+}diff --git a/webui/src/lib/markdown-math.ts b/webui/src/lib/markdown-math.tsnew file mode 100644index 000000000..d52baf0fb--- /dev/null+++ b/webui/src/lib/markdown-math.ts@@ -0,0 +1,2 @@+import "katex/dist/katex.min.css";+export { default } from "rehype-katex";diff --git a/webui/src/lib/thread-display-compat.ts b/webui/src/lib/thread-display-compat.tsindex 0bb69041c..184d16f3c 100644--- a/webui/src/lib/thread-display-compat.ts+++ b/webui/src/lib/thread-display-compat.ts@@ -24,73 +24,74 @@ export function normalizeLegacyLongTaskMessages(messages: UIMessage[]): UIMessag});}-/**- * Replay timestamps an assistant row when its first output is recorded, while- * latency covers the whole turn. Derive the end from the matching user start- * so the displayed time cannot double-count the pre-output interval.- */-function deriveAssistantCompletionTimes(messages: UIMessage[]): UIMessage[] {- const userStartedAtByTurn = new Map<string, number>();- let latestUserStartedAt: number | undefined;-- return messages.map((message) => {- if (message.role === "user") {- if (Number.isFinite(message.createdAt)) {- latestUserStartedAt = message.createdAt;- if (message.turnId) userStartedAtByTurn.set(message.turnId, message.createdAt);- }- return message;- }- if (- message.role !== "assistant"- || message.kind === "trace"- || message.completedAt !== undefined- || message.latencyMs === undefined- || !Number.isFinite(message.latencyMs)- || message.latencyMs < 0- ) {- return message;- }-- const startedAt = message.turnId- ? userStartedAtByTurn.get(message.turnId)- : message.source- ? undefined- : latestUserStartedAt;- if (startedAt === undefined) return message;- return { ...message, completedAt: startedAt + message.latencyMs };- });+interface PreparedMessage {+ message: UIMessage;+ hidden: boolean;+ compact: boolean;}-function identifyCompactReplies(messages: UIMessage[]): UIMessage[] {- const turns = new Set(messages.flatMap((message) => (- message.role === "user" && message.content.trim().toLowerCase() === "/compact" && message.turnId- ? [message.turnId]- : []- )));- return messages.map((message) => {- if (message.role !== "assistant" || message.kind || message.isStreaming- || !message.turnId || !turns.has(message.turnId)) return message;- if (message.content === "Nothing to compact.") return { ...message, compactReply: "empty" };- if (message.content === "Unable to compact context. Check the logs and try again.") {- return { ...message, compactReply: "failed" };- }- return message;- });+const preparedMessages = new WeakMap<UIMessage, PreparedMessage>();+const completionMessages = new WeakMap<UIMessage, { completedAt: number; message: UIMessage }>();++function prepareMessage(original: UIMessage): PreparedMessage {+ const cached = preparedMessages.get(original);+ if (cached) return cached;+ const message = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages([original]))[0];+ const prepared = {+ message,+ hidden: isSystemCommandTurnId(message.turnId)+ || (message.role === "user" && isModelCommandText(message.content))+ || (message.role === "assistant" && isModelCommandResponseText(message.content)),+ compact: message.role === "user" && message.content.trim().toLowerCase() === "/compact",+ };+ preparedMessages.set(original, prepared);+ return prepared;}export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] {- const normalized = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages(messages));- const hiddenTurns = new Set(normalized.flatMap((message) => (- message.role === "user" && isModelCommandText(message.content) && message.turnId- ? [message.turnId]- : []- )));- const visible = normalized.filter((message) => (- !isSystemCommandTurnId(message.turnId)- && (!message.turnId || !hiddenTurns.has(message.turnId))- && !(message.role === "user" && isModelCommandText(message.content))- && !(message.role === "assistant" && isModelCommandResponseText(message.content))- ));- return deriveAssistantCompletionTimes(identifyCompactReplies(visible));+ const hiddenTurns = new Set<string>();+ const compactTurns = new Set<string>();+ for (const original of messages) {+ const { message, hidden, compact } = prepareMessage(original);+ if (message.role !== "user" || !message.turnId) continue;+ if (hidden && isModelCommandText(message.content)) hiddenTurns.add(message.turnId);+ if (compact && !hidden) compactTurns.add(message.turnId);+ }+ const visible: UIMessage[] = [];+ const starts = new Map<string, number>();+ let latestStart: number | undefined;+ for (const original of messages) {+ const prepared = prepareMessage(original);+ let message = prepared.message;+ if (prepared.hidden || (message.turnId && hiddenTurns.has(message.turnId))) continue;+ if (message.role === "user" && Number.isFinite(message.createdAt)) {+ latestStart = message.createdAt;+ if (message.turnId) starts.set(message.turnId, message.createdAt);+ }+ if (message.role === "assistant" && !message.kind && !message.isStreaming+ && message.turnId && compactTurns.has(message.turnId)) {+ if (message.content === "Nothing to compact.") message = { ...message, compactReply: "empty" };+ if (message.content === "Unable to compact context. Check the logs and try again.") {+ message = { ...message, compactReply: "failed" };+ }+ }+ // Replay latency starts at the user prompt, not the first assistant output.+ if (message.role === "assistant" && message.kind !== "trace"+ && message.completedAt === undefined && message.latencyMs !== undefined+ && Number.isFinite(message.latencyMs) && message.latencyMs >= 0) {+ const start = message.turnId ? starts.get(message.turnId) : message.source ? undefined : latestStart;+ if (start !== undefined) {+ const completedAt = start + message.latencyMs;+ const cached = completionMessages.get(message);+ if (cached?.completedAt === completedAt) message = cached.message;+ else {+ const completed = { ...message, completedAt };+ completionMessages.set(message, { completedAt, message: completed });+ message = completed;+ }+ }+ }+ visible.push(message);+ }+ return visible;}diff --git a/webui/src/lib/thread-message-cache.ts b/webui/src/lib/thread-message-cache.tsnew file mode 100644index 000000000..a4fe30ea8--- /dev/null+++ b/webui/src/lib/thread-message-cache.ts@@ -0,0 +1,49 @@+import type { UIMessage } from "./types";++/** Bounded replay cache; temporary chats remain pinned because they have no disk history. */+export class ThreadMessageCache {+ private entries = new Map<string, { messages: UIMessage[]; bytes: number }>();+ private sizes = new WeakMap<object, number>();+ private bytes = 0;++ constructor(+ private isPinned: (key: string) => boolean,+ private maxBytes = 16 * 1024 * 1024,+ private maxEntries = 12,+ ) {}++ get(key: string): UIMessage[] | undefined {+ const entry = this.entries.get(key);+ if (!entry) return undefined;+ this.entries.delete(key);+ this.entries.set(key, entry);+ return entry.messages;+ }++ set(key: string, messages: UIMessage[]): void {+ this.delete(key);+ const bytes = this.estimate(messages);+ this.entries.set(key, { messages, bytes });+ this.bytes += bytes;+ for (const candidate of this.entries.keys()) {+ if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;+ if (!this.isPinned(candidate)) this.delete(candidate);+ }+ }++ delete(key: string): void {+ const entry = this.entries.get(key);+ if (entry) this.bytes -= entry.bytes;+ this.entries.delete(key);+ }++ private estimate(value: unknown): number {+ if (typeof value === "string") return value.length * 2;+ if (!value || typeof value !== "object") return 8;+ const cached = this.sizes.get(value);+ if (cached !== undefined) return cached;+ const size = 32 + Object.values(value).reduce<number>((total, item) => total + this.estimate(item), 0);+ this.sizes.set(value, size);+ return size;+ }+}diff --git a/webui/src/tests/activity-message-model.test.ts b/webui/src/tests/activity-message-model.test.tsindex 061d0f2c4..4485afc73 100644--- a/webui/src/tests/activity-message-model.test.ts+++ b/webui/src/tests/activity-message-model.test.ts@@ -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"),diff --git a/webui/src/tests/agent-activity-cluster.test.tsx b/webui/src/tests/agent-activity-cluster.test.tsxindex 0c16954e6..91dbd28c8 100644--- a/webui/src/tests/agent-activity-cluster.test.tsx+++ b/webui/src/tests/agent-activity-cluster.test.tsx@@ -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);diff --git a/webui/src/tests/code-block.test.tsx b/webui/src/tests/code-block.test.tsxindex 9c6f370ef..fc9109a19 100644--- a/webui/src/tests/code-block.test.tsx+++ b/webui/src/tests/code-block.test.tsx@@ -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">diff --git a/webui/src/tests/fixtures/live-replay-event-projection.json b/webui/src/tests/fixtures/live-replay-event-projection.jsonindex 89866d5c3..49b66f840 100644--- a/webui/src/tests/fixtures/live-replay-event-projection.json+++ b/webui/src/tests/fixtures/live-replay-event-projection.json@@ -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+ }+ ]}]}diff --git a/webui/src/tests/markdown-text-renderer.test.tsx b/webui/src/tests/markdown-text-renderer.test.tsxindex cb2b7c818..142f4921c 100644--- a/webui/src/tests/markdown-text-renderer.test.tsx+++ b/webui/src/tests/markdown-text-renderer.test.tsx@@ -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>);diff --git a/webui/src/tests/session-search-dialog.test.tsx b/webui/src/tests/session-search-dialog.test.tsxindex bad0c8102..e007caceb 100644--- a/webui/src/tests/session-search-dialog.test.tsx+++ b/webui/src/tests/session-search-dialog.test.tsx@@ -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();});diff --git a/webui/src/tests/thinking-reasoning-shell.test.tsx b/webui/src/tests/thinking-reasoning-shell.test.tsxindex 2fe497810..ababf8863 100644--- a/webui/src/tests/thinking-reasoning-shell.test.tsx+++ b/webui/src/tests/thinking-reasoning-shell.test.tsx@@ -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" });diff --git a/webui/src/tests/thread-display-compat.test.ts b/webui/src/tests/thread-display-compat.test.tsindex 086f795a3..28b70f6e2 100644--- a/webui/src/tests/thread-display-compat.test.ts+++ b/webui/src/tests/thread-display-compat.test.ts@@ -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">> = {},diff --git a/webui/src/tests/thread-message-cache.test.ts b/webui/src/tests/thread-message-cache.test.tsnew file mode 100644index 000000000..d4bfd9700--- /dev/null+++ b/webui/src/tests/thread-message-cache.test.ts@@ -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);+});diff --git a/webui/src/tests/thread-messages.test.tsx b/webui/src/tests/thread-messages.test.tsxindex d893e3d32..06a4ed5a0 100644--- a/webui/src/tests/thread-messages.test.tsx+++ b/webui/src/tests/thread-messages.test.tsx@@ -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 () => {diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsxindex 5851b232d..e885d90da 100644--- a/webui/src/tests/useNanobotStream.test.tsx+++ b/webui/src/tests/useNanobotStream.test.tsx@@ -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.",+ ]);});});diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsxindex fa0c61d82..eebfe58d0 100644--- a/webui/src/tests/useSessions.test.tsx+++ b/webui/src/tests/useSessions.test.tsx@@ -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 () => {diff --git a/webui/src/tests/vite-config.test.ts b/webui/src/tests/vite-config.test.tsindex 813d963a3..7825f27fb 100644--- a/webui/src/tests/vite-config.test.ts+++ b/webui/src/tests/vite-config.test.ts@@ -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", () => {diff --git a/webui/vite.config.ts b/webui/vite.config.tsindex 605c0a83b..991791c14 100644--- a/webui/vite.config.ts+++ b/webui/vite.config.ts@@ -59,6 +59,17 @@ export function gzipWebuiAssets(): Plugin {}export function webuiManualChunk(id: string): string | undefined {+ const locale = /\/webui\/locales\/([^/]+)\.json$/.exec(id)?.[1]+ ?? /\/src\/i18n\/locales\/([^/]+)\/common\.json$/.exec(id)?.[1];+ if (locale) return `locale-${locale}`;+ // Clipboard actions are shared with lazy Markdown and must not pull it into the shell.+ if (id.endsWith("/src/lib/clipboard.ts")) return "clipboard";+ if (id.endsWith("/src/lib/markdown-math.ts")+ || id.includes("node_modules/rehype-katex/")+ // The micromark barrel also exports an HTML renderer that imports KaTeX.+ || (id.includes("node_modules/micromark-extension-math/") && id.endsWith("/html.js"))) {+ return "markdown-math";+ }if (id.includes("node_modules/react/")|| id.includes("node_modules/react-dom/")@@ -73,12 +84,8 @@ export function webuiManualChunk(id: string): string | undefined {}// Streamdown lazy-loads diagrams and highlighted code. Keep those modules// outside the core markdown chunk so ordinary replies do not download them.- if (- id.includes("node_modules/streamdown/dist/mermaid-")- || id.includes("node_modules/streamdown/dist/highlighted-body-")- ) {- return;- }+ if (id.includes("node_modules/streamdown/dist/mermaid-")) return "markdown-diagrams";+ if (id.includes("node_modules/streamdown/dist/highlighted-body-")) return "markdown-code";// Refractor reaches this HAST helper through hastscript. Keeping it with// Refractor prevents syntax-highlight <-> markdown-vendor circular chunks.if (