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:
1 parent
1c451b5b5f
commit
1469d4811c
32 files changed
+1156
-361
No files matched your search
@@ -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 (
|
||||
<pre
|
||||
className={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 (
|
||||
<div
|
||||
|
||||
@@ -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"}
|
||||
parseIncompleteMarkdown
|
||||
remend={REMEND_OPTIONS}
|
||||
|
||||
@@ -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 }}>
|
||||
<button
|
||||
ref={(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));
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 [{
|
||||
|
||||
@@ -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}
|
||||
</>
|
||||
|
||||
@@ -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)));
|
||||
|
||||
Reference in new issue
Block a user