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

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

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

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

* perf(webui): restore conditional replay buffer initialization

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

No files matched your search

@@ -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
+21 -29
View File
@@ -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<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 [{
+28 -11
View File
@@ -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" ? (
<AgentActivityCluster
messages={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}
</>
+4 -1
View File
@@ -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). */
@@ -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 (
<div
className="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 ? (
@@ -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)));