diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py
index 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 = None
buffer_parts: list[str] = []
+ merge_reasoning_message_id: str | None = None
suppress_until_turn_end = False
active_activity_segment_id: str | None = None
active_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 None
if 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 = None
buffer_parts = []
+ merge_reasoning_message_id = buffer_message_id if merge_next else None
continue
if ev == "reasoning_delta":
diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py
index a331b3a7e..ac87b7759 100644
--- a/tests/utils/test_webui_transcript.py
+++ b/tests/utils/test_webui_transcript.py
@@ -4,6 +4,8 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
import nanobot.webui.transcript as transcript_module
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from 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"
+@pytest.mark.parametrize("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.tsx
index 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 (
-
{t("settings.status.loading")}
+
{label ?? t("settings.status.loading")}
@@ -2617,133 +2620,137 @@ function Shell({
view !== "chat" && "hidden",
)}
>
-
{
- 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 (
-
- );
- }
+
+ }>
+ {
+ 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 (
+
+ );
+ }
- 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 (
- 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}
- />
- );
- }}
- />
+ 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 (
+ 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}
+ />
+ );
+ }}
+ />
+
+
{view !== "chat" && (
diff --git a/webui/src/components/CodeBlock.tsx b/webui/src/components/CodeBlock.tsx
index 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 (
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 (
= [
remarkCjkStrongBoundaries,
remarkSafeHtmlSubset,
];
-const rehypePlugins: NonNullable
= [rehypeKatex];
+type MathPlugin = typeof import("@/lib/markdown-math").default;
+let loadedMathPlugin: MathPlugin | undefined;
+let mathPluginPromise: Promise | undefined;
+
+function loadMathPlugin(): Promise {
+ 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 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>(
+ () => needsMath && mathPlugin ? [mathPlugin] : [],
+ [needsMath, mathPlugin],
+ );
const components = useMemo(
() => ({
code({ className: cls, children: kids, node: _node, ...props }) {
@@ -798,6 +822,7 @@ export default function MarkdownTextRenderer({
return (
void;
}
+const EMPTY_TITLE_OVERRIDES: Record = {};
+
export function SessionSearchDialog({
open,
sessions,
activeKey,
loading,
- titleOverrides = {},
+ titleOverrides = EMPTY_TITLE_OVERRIDES,
onOpenChange,
onSelect,
}: SessionSearchDialogProps) {
const { t } = useTranslation();
const inputRef = useRef(null);
+ const scrollRef = useRef(null);
+ const [scrollTop, setScrollTop] = useState(0);
const itemRefs = useRef>([]);
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({
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}
) : (
-
- {sessionResults.map((session, index) => {
+
+
+ {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 (
- -
+
-
);
})}
+
)}
@@ -217,20 +243,3 @@ export function SessionSearchDialog({
);
}
-
-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.tsx
index 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 activity
diff --git a/webui/src/components/thread/PromptRail.tsx b/webui/src/components/thread/PromptRail.tsx
index 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-surf
import { 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();
+ for (const element of scrollEl.querySelectorAll("[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.tsx
index 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(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 (
<>
setInteracted(true)}
+ onFocusCapture={() => setInteracted(true)}
data-thread-display-unit={unitKey}
data-user-prompt-id={userPromptId}
>
- {unit.type === "activity" ? (
+ {retainContent ? unit.type === "activity" ? (
- )}
+ ) : null}
{showForkBoundary ? : null}
>
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 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;
@@ -789,8 +790,10 @@ export function ThreadShell({
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState(null);
const viewportRef = useRef(null);
const activeViewportTurnByChatIdRef = useRef