fix(webui): navigate complete prompt history with bounded pages

This commit is contained in:
Xubin Ren committed 2026-10-18 17:13:18 +08:00
1 parent 5f6e8a6baa
commit bf1eada575
20 files changed
+949 -401

No files matched your search

@@ -1,7 +1,7 @@
import {
PromptNavigationIcon,
} from "@/components/icons/product-icons";
import { useMemo, useState } from "react";
import { useMemo, useRef, useState } from "react";
import { Search } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -22,17 +22,23 @@ import { cn } from "@/lib/utils";
interface PromptNavigatorProps {
messages: UIMessage[];
prompts?: PromptAnchor[];
onJumpToPrompt: (promptId: string) => void;
}
const ROW_HEIGHT = 88;
export function PromptNavigator({
messages,
prompts: suppliedPrompts,
onJumpToPrompt,
}: PromptNavigatorProps) {
const { i18n, t } = useTranslation();
const prompts = useMemo(() => userPromptAnchors(messages), [messages]);
const prompts = useMemo(() => suppliedPrompts ?? userPromptAnchors(messages), [suppliedPrompts, messages]);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const listRef = useRef<HTMLDivElement>(null);
const [listTop, setListTop] = useState(0);
const filteredPrompts = useMemo(() => {
const needle = query.trim().toLocaleLowerCase();
@@ -41,6 +47,8 @@ export function PromptNavigator({
`${prompt.label}\n${prompt.preview}`.toLocaleLowerCase().includes(needle),
);
}, [prompts, query]);
const firstRow = Math.max(0, Math.floor(listTop / ROW_HEIGHT) - 2);
const lastRow = firstRow + Math.ceil(window.innerHeight / ROW_HEIGHT) + 5;
if (prompts.length === 0) return null;
@@ -60,7 +68,7 @@ export function PromptNavigator({
"hover:text-foreground",
)}
aria-label={t("thread.promptNavigator.open")}
onClick={() => setOpen(true)}
onClick={() => { setListTop(0); setOpen(true); }}
>
<PromptNavigationIcon className="h-4 w-4" />
</Button>
@@ -82,7 +90,11 @@ export function PromptNavigator({
/>
<SearchInput
value={query}
onChange={(event) => setQuery(event.target.value)}
onChange={(event) => {
setQuery(event.target.value);
setListTop(0);
if (listRef.current) listRef.current.scrollTop = 0;
}}
aria-label={t("thread.promptNavigator.search")}
placeholder={t("thread.promptNavigator.search")}
className="h-10 rounded-full border-border bg-background pl-9 pr-3 text-sm transition-colors"
@@ -90,12 +102,29 @@ export function PromptNavigator({
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-2 py-2">
<div ref={listRef} className="min-h-0 flex-1 overflow-y-auto px-2 py-2"
onScroll={(event) => setListTop(event.currentTarget.scrollTop)}
onKeyDown={(event) => {
const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-prompt-row]");
if (!button || !listRef.current) return;
const index = Number(button.dataset.promptRow);
let next = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: filteredPrompts.length - 1 }[event.key];
if (event.key === "Tab") {
if (!event.shiftKey && index === lastRow - 1) next = index + 1;
if (event.shiftKey && index === firstRow && firstRow > 0) next = index - 1;
}
if (next === undefined || next < 0 || next >= filteredPrompts.length) return;
event.preventDefault();
listRef.current.scrollTop = next * ROW_HEIGHT;
setListTop(listRef.current.scrollTop);
requestAnimationFrame(() => listRef.current?.querySelector<HTMLButtonElement>(`[data-prompt-row="${next}"]`)?.focus());
}}>
{filteredPrompts.length > 0 ? (
<div className="space-y-1">
{filteredPrompts.map((prompt) => (
<div style={{ paddingTop: firstRow * ROW_HEIGHT, paddingBottom: Math.max(0, filteredPrompts.length - lastRow) * ROW_HEIGHT }}>
{filteredPrompts.slice(firstRow, lastRow).map((prompt, offset) => (
<PromptNavigatorRow
key={prompt.id}
row={firstRow + offset}
locale={i18n.resolvedLanguage || i18n.language}
prompt={prompt}
onJump={jump}
@@ -115,12 +144,14 @@ export function PromptNavigator({
}
interface PromptNavigatorRowProps {
row: number;
locale: string;
onJump: (promptId: string) => void;
prompt: PromptAnchor;
}
function PromptNavigatorRow({
row,
locale,
onJump,
prompt,
@@ -130,14 +161,15 @@ function PromptNavigatorRow({
return (
<button
type="button"
data-prompt-row={row}
className={cn(
"w-full rounded-control px-3 py-3 text-left transition",
"h-[88px] w-full overflow-hidden rounded-control px-3 py-3 text-left transition",
"hover:bg-accent focus-visible:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
)}
aria-label={t("thread.promptNavigator.jumpTo", { label: prompt.label })}
onClick={() => onJump(prompt.id)}
>
<div className="max-h-20 overflow-hidden whitespace-pre-wrap break-words text-sm leading-5 text-foreground">
<div className="line-clamp-2 whitespace-pre-wrap break-words text-sm leading-5 text-foreground">
{prompt.preview}
</div>
{timestamp ? (
+123 -349
View File
@@ -1,377 +1,151 @@
import {
Fragment,
type RefObject,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { type RefObject, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { MarkdownText } from "@/components/MarkdownText";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { cn } from "@/lib/utils";
import type { UIMessage } from "@/lib/types";
import {
type PromptAnchor,
promptTop,
userPromptAnchors,
} from "@/components/thread/promptNavigation";
import { type PromptAnchor, promptTop, userPromptAnchors } from "./promptNavigation";
interface PromptRailProps {
bottomOffset: number;
messages: UIMessage[];
prompts?: PromptAnchor[];
onJumpToPrompt: (promptId: string) => void;
scrollRef: RefObject<HTMLDivElement>;
}
interface MeasuredPrompt extends PromptAnchor {
top: number;
topPercent: number;
}
const GAP = 16;
const EDGE = 20;
const WIDTHS = [28, 22, 16, 11];
interface PromptMarker {
answerPreview: string;
count: number;
ids: string[];
label: string;
preview: string;
topPercent: number;
}
const MIN_PROMPTS_FOR_RAIL = 2;
const RAIL_MIN_SCROLL_RANGE_PX = 80;
const DENSE_PROMPT_THRESHOLD = 30;
const DENSE_BUCKET_HEIGHT_PX = 12;
const DENSE_BUCKET_FALLBACK_COUNT = 32;
const DENSE_BUCKET_MAX_COUNT = 42;
const MARKER_BASE_WIDTH_PX = 9;
const MARKER_STACK_GAP_PX = 16;
const RAIL_FALLBACK_HEIGHT_PX = 300;
const HOVER_MARKER_WIDTHS_PX = [28, 22, 16, 11];
export function PromptRail({
bottomOffset,
messages,
onJumpToPrompt,
scrollRef,
}: PromptRailProps) {
/** Complete logical list; only the visible markers and one preview are mounted. */
export function PromptRail({ bottomOffset, messages, prompts, onJumpToPrompt, scrollRef }: PromptRailProps) {
const { t } = useTranslation();
const anchors = useMemo(() => prompts ?? userPromptAnchors(messages), [prompts, messages]);
const railRef = useRef<HTMLDivElement>(null);
const measuredPromptsRef = useRef<MeasuredPrompt[]>([]);
const promptAnchors = useMemo(() => userPromptAnchors(messages), [messages]);
const [markers, setMarkers] = useState<PromptMarker[]>([]);
const [activePromptId, setActivePromptId] = useState<string | null>(null);
const [focusedMarkerIndex, setFocusedMarkerIndex] = useState<number | null>(null);
const inside = useRef(false);
const [height, setHeight] = useState(300);
const [scrollTop, setScrollTop] = useState(0);
const [activeId, setActiveId] = useState<string | null>(null);
const [focused, setFocused] = useState<number | null>(null);
const contentHeight = Math.max(height, (anchors.length - 1) * GAP + EDGE * 2);
const padding = (contentHeight - (anchors.length - 1) * GAP) / 2;
const first = Math.max(0, Math.floor((scrollTop - padding) / GAP) - 4);
const end = Math.min(anchors.length, Math.ceil((scrollTop + height - padding) / GAP) + 5);
const updateMarkers = useCallback(() => {
const scrollEl = scrollRef.current;
const nextRailHeight = railRef.current?.clientHeight ?? 0;
if (!scrollEl || promptAnchors.length < MIN_PROMPTS_FOR_RAIL) {
measuredPromptsRef.current = [];
setMarkers([]);
setActivePromptId(null);
return;
}
const scrollRange = scrollEl.scrollHeight - scrollEl.clientHeight;
if (scrollRange < RAIL_MIN_SCROLL_RANGE_PX) {
measuredPromptsRef.current = [];
setMarkers([]);
setActivePromptId(null);
return;
}
const measured = measurePrompts(scrollEl, promptAnchors, scrollRange);
measuredPromptsRef.current = measured;
const grouped = groupPromptMarkers(measured, nextRailHeight);
setMarkers(distributeMarkerPositions(grouped, nextRailHeight));
setActivePromptId(activePromptForScroll(measured, scrollEl.scrollTop));
}, [promptAnchors, scrollRef]);
const updateActivePrompt = useCallback(() => {
const scrollEl = scrollRef.current;
if (!scrollEl) return;
const next = activePromptForScroll(measuredPromptsRef.current, scrollEl.scrollTop);
setActivePromptId((current) => current === next ? current : next);
}, [scrollRef]);
const railVisible = markers.length > 0;
useEffect(() => {
const scrollEl = scrollRef.current;
if (!scrollEl) return undefined;
const rail = railRef.current;
if (!rail) return;
const measure = () => setHeight(rail.clientHeight || 300);
measure();
const observer = new ResizeObserver(measure);
observer.observe(rail);
return () => observer.disconnect();
}, [anchors.length >= 2, bottomOffset]);
let scrollFrame = 0;
let resizeFrame = 0;
const scheduleActivePrompt = () => {
window.cancelAnimationFrame(scrollFrame);
scrollFrame = window.requestAnimationFrame(updateActivePrompt);
useEffect(() => {
const scroller = scrollRef.current;
if (!scroller) return;
// Measure only mounted messages, not the complete navigation index.
let positions: { id: string; top: number }[] = [];
let frame = 0;
const update = () => {
const cursor = scroller.scrollTop + 96;
let low = 0;
let high = positions.length - 1;
while (low <= high) {
const middle = (low + high) >>> 1;
if (positions[middle].top <= cursor) low = middle + 1;
else high = middle - 1;
}
setActiveId(positions[Math.max(0, high)]?.id ?? null);
};
const scheduleMeasurement = () => {
if (resizeFrame) return;
resizeFrame = window.requestAnimationFrame(() => {
resizeFrame = 0;
updateMarkers();
});
const measure = () => {
positions = Array.from(scroller.querySelectorAll<HTMLElement>("[data-user-prompt-id]"),
(element) => ({ id: element.dataset.userPromptId!, top: promptTop(scroller, element) - 16 }));
update();
};
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);
const schedule = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(update);
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(scroller);
if (scroller.firstElementChild) observer.observe(scroller.firstElementChild);
scroller.addEventListener("scroll", schedule, { passive: true });
return () => {
window.cancelAnimationFrame(scrollFrame);
window.cancelAnimationFrame(resizeFrame);
observer?.disconnect();
scrollEl.removeEventListener("scroll", scheduleActivePrompt);
window.removeEventListener("resize", scheduleMeasurement);
cancelAnimationFrame(frame);
observer.disconnect();
scroller.removeEventListener("scroll", schedule);
};
}, [bottomOffset, railVisible, scrollRef, updateActivePrompt, updateMarkers]);
}, [messages, scrollRef]);
if (markers.length === 0) return null;
return (
<div
ref={railRef}
aria-label={t("thread.promptNavigator.railAria")}
className={cn(
"thread-prompt-rail group pointer-events-auto absolute top-3 z-20 w-9 opacity-100",
"transition-opacity duration-200",
"motion-safe:animate-in motion-safe:fade-in-0 motion-safe:duration-200",
)}
onPointerLeave={() => setFocusedMarkerIndex(null)}
style={{ bottom: Math.max(80, bottomOffset) }}
>
{markers.map((marker, index) => {
const active = marker.ids.includes(activePromptId ?? "");
const previewVisible = focusedMarkerIndex === index;
const hoverDistance =
focusedMarkerIndex === null ? null : Math.abs(index - focusedMarkerIndex);
return (
<Fragment key={marker.ids.join("|")}>
<button
type="button"
aria-label={t("thread.promptNavigator.jumpTo", { label: marker.label })}
onClick={() => onJumpToPrompt(marker.ids[marker.ids.length - 1])}
onBlur={() => setFocusedMarkerIndex(null)}
onFocus={() => setFocusedMarkerIndex(index)}
onPointerEnter={() => setFocusedMarkerIndex(index)}
onPointerLeave={() => setFocusedMarkerIndex(null)}
className={cn(
"absolute left-0 h-4 w-9 -translate-y-1/2 overflow-visible rounded-sm",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-400/60",
)}
style={{ top: `${marker.topPercent}%` }}
>
<span
aria-hidden
data-testid="prompt-rail-marker"
className={cn(
"absolute left-0 top-1/2 h-0.5 -translate-y-1/2 rounded-full",
"transition-[width,background-color,opacity,height] duration-150",
railMarkerTone(hoverDistance, active),
)}
style={{
height: markerHeight(hoverDistance),
width: markerWidth(hoverDistance),
}}
/>
</button>
<div
ref={makeInert}
aria-hidden
data-testid={previewVisible ? "prompt-rail-preview" : undefined}
className={cn(
"pointer-events-none absolute left-10 z-30 w-[34rem] max-w-[calc(100vw-4rem)] -translate-y-1/2 rounded-panel px-4 py-3 text-left",
floatingSurfaceElevationClassName,
"transition-[opacity,transform] duration-150",
previewVisible
? "translate-x-0 scale-100 opacity-100"
: "-translate-x-2 scale-[0.98] opacity-0",
)}
style={{ top: `${marker.topPercent}%` }}
>
{previewVisible ? (
<>
<div className="line-clamp-2 whitespace-pre-wrap break-words text-[15px] font-semibold leading-6">
{marker.preview}
</div>
{marker.answerPreview ? (
<div className="mt-1.5 max-h-[4.5rem] overflow-hidden break-words text-[14px] leading-6 text-muted-foreground dark:text-white/55">
<MarkdownText
className={cn(
"max-w-none text-[14px] leading-6 text-inherit",
"[--tw-prose-body:currentColor] [--tw-prose-headings:currentColor] [--tw-prose-bold:currentColor]",
"prose-headings:my-0 prose-h1:text-[14px] prose-h2:text-[14px] prose-h3:text-[14px] prose-h4:text-[14px]",
"prose-p:my-0 prose-ul:my-0 prose-ol:my-0 prose-li:my-0",
)}
>
{marker.answerPreview}
</MarkdownText>
</div>
) : null}
</>
) : null}
</div>
</Fragment>
);
})}
</div>
);
}
function makeInert(node: HTMLDivElement | null): void {
if (node) node.inert = true;
}
function measurePrompts(
scrollEl: HTMLElement,
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 = elements.get(anchor.id);
if (!target) return [];
const top = Math.max(0, Math.min(scrollRange, promptTop(scrollEl, target) - 16));
return [{
...anchor,
top,
topPercent: clamp((top / scrollRange) * 100, 2, 98),
}];
});
}
function groupPromptMarkers(
measured: MeasuredPrompt[],
railHeight: number,
): PromptMarker[] {
if (measured.length === 0) return [];
if (measured.length >= DENSE_PROMPT_THRESHOLD) {
return bucketPromptMarkers(measured, railHeight);
}
return measured.map((prompt) => ({
answerPreview: prompt.answerPreview,
count: 1,
ids: [prompt.id],
label: prompt.label,
preview: prompt.preview,
topPercent: prompt.topPercent,
}));
}
function bucketPromptMarkers(
measured: MeasuredPrompt[],
railHeight: number,
): PromptMarker[] {
const bucketCount = railHeight > 0
? clamp(
Math.floor(railHeight / DENSE_BUCKET_HEIGHT_PX),
1,
DENSE_BUCKET_MAX_COUNT,
)
: DENSE_BUCKET_FALLBACK_COUNT;
const buckets = Array.from({ length: bucketCount }, () => [] as MeasuredPrompt[]);
for (const [index, prompt] of measured.entries()) {
const bucketIndex = Math.floor((index / measured.length) * bucketCount);
buckets[bucketIndex].push(prompt);
}
return buckets.flatMap((bucket) => {
if (bucket.length === 0) return [];
const latest = bucket[bucket.length - 1];
const topPercent =
bucket.reduce((sum, prompt) => sum + prompt.topPercent, 0) / bucket.length;
return [{
count: bucket.length,
ids: bucket.map((prompt) => prompt.id),
label: bucket.length === 1
? latest.label
: groupedPromptLabel(bucket.length, latest.label),
answerPreview: latest.answerPreview,
preview: latest.preview,
topPercent,
}];
});
}
function distributeMarkerPositions(markers: PromptMarker[], railHeight: number): PromptMarker[] {
const height = railHeight > 0 ? railHeight : RAIL_FALLBACK_HEIGHT_PX;
if (markers.length <= 1) {
return markers.map((marker) => ({ ...marker, topPercent: 50 }));
}
const availableHeight = Math.max(0, height - MARKER_STACK_GAP_PX);
const stepPx = Math.min(MARKER_STACK_GAP_PX, availableHeight / (markers.length - 1));
const stackHeight = stepPx * (markers.length - 1);
const firstMarkerPx = (height - stackHeight) / 2;
return markers.map((marker, index) => ({
...marker,
topPercent: ((firstMarkerPx + stepPx * index) / height) * 100,
}));
}
function activePromptForScroll(
measured: MeasuredPrompt[],
scrollTop: number,
): string | null {
if (measured.length === 0) return null;
const cursor = scrollTop + 96;
let lower = 0;
let upper = measured.length - 1;
let activeIndex = 0;
while (lower <= upper) {
const middle = Math.floor((lower + upper) / 2);
if (measured[middle].top <= cursor) {
activeIndex = middle;
lower = middle + 1;
} else {
upper = middle - 1;
useEffect(() => {
if (inside.current) return;
const rail = railRef.current;
const index = anchors.findIndex((item) => item.id === activeId);
if (rail && index >= 0) {
rail.scrollTop = Math.max(0, padding + index * GAP - height / 2);
setScrollTop(rail.scrollTop);
}
}
return measured[activeIndex].id;
}
}, [activeId, anchors, height, padding]);
function groupedPromptLabel(count: number, latestLabel: string): string {
return `${count} prompts, latest: ${latestLabel}`;
}
if (anchors.length < 2) return null;
const preview = focused === null ? undefined : anchors[focused];
const moveFocus = (index: number) => {
const rail = railRef.current;
if (!rail) return;
const next = Math.max(0, Math.min(anchors.length - 1, index));
rail.scrollTop = Math.max(0, padding + next * GAP - height / 2);
setScrollTop(rail.scrollTop);
setFocused(next);
requestAnimationFrame(() => rail.querySelector<HTMLButtonElement>('[data-prompt-index="' + next + '"]')?.focus());
};
function markerWidth(hoverDistance: number | null): number {
if (hoverDistance === null) return MARKER_BASE_WIDTH_PX;
return HOVER_MARKER_WIDTHS_PX[hoverDistance] ?? MARKER_BASE_WIDTH_PX;
}
function markerHeight(hoverDistance: number | null): number {
return hoverDistance === 0 ? 3 : 2;
}
function railMarkerTone(hoverDistance: number | null, active: boolean): string {
if (hoverDistance === 0) {
return "bg-[#222222] opacity-100 dark:bg-white";
}
if (hoverDistance !== null && hoverDistance < HOVER_MARKER_WIDTHS_PX.length) {
return "bg-[#d0d0d0] opacity-100 dark:bg-white/35";
}
if (active) {
return "bg-[#6f6f6f] opacity-100 dark:bg-white/55";
}
return "bg-[#d8d8d8] opacity-100 dark:bg-white/25";
}
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
return <div
aria-label={t("thread.promptNavigator.railAria")}
className="thread-prompt-rail pointer-events-auto absolute top-3 z-20 w-9"
style={{ bottom: Math.max(16, bottomOffset) }}
onPointerEnter={() => { inside.current = true; }}
onPointerLeave={() => { inside.current = false; setFocused(null); }}
>
<div ref={railRef} data-testid="prompt-rail-scroll" className="thread-prompt-rail-scroll h-full overflow-y-auto overscroll-contain"
onScroll={(event) => { setScrollTop(event.currentTarget.scrollTop); setFocused(null); }}>
<div className="relative w-9" style={{ height: contentHeight }}>
{anchors.slice(first, end).map((anchor, offset) => {
const index = first + offset;
const distance = focused === null ? null : Math.abs(index - focused);
const active = anchor.id === activeId;
return <button key={anchor.id} type="button" data-prompt-index={index}
aria-label={t("thread.promptNavigator.jumpTo", { label: anchor.label })}
aria-current={active ? "location" : undefined}
onClick={() => onJumpToPrompt(anchor.id)}
onFocus={() => { inside.current = true; setFocused(index); }}
onBlur={() => { inside.current = false; setFocused(null); }}
onPointerEnter={() => setFocused(index)}
onPointerLeave={() => setFocused(null)}
onKeyDown={(event) => {
const next = { ArrowUp: index - 1, ArrowDown: index + 1, Home: 0, End: anchors.length - 1 }[event.key];
if (next !== undefined) { event.preventDefault(); moveFocus(next); }
}}
className="absolute left-0 h-4 w-9 -translate-y-1/2 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
style={{ top: padding + index * GAP }}>
<span aria-hidden data-testid="prompt-rail-marker"
className={cn("absolute left-0 top-1/2 -translate-y-1/2 rounded-full transition-[width,background-color] duration-150 motion-reduce:transition-none",
distance === 0 ? "bg-foreground" : active ? "bg-foreground/60" : "bg-foreground/20")}
style={{ width: distance === null ? 9 : WIDTHS[distance] ?? 9, height: distance === 0 ? 3 : 2 }} />
</button>;
})}
</div>
</div>
{preview && focused !== null ? <div aria-hidden ref={(node) => { if (node) node.inert = true; }} data-testid="prompt-rail-preview"
className={cn("pointer-events-none absolute left-10 z-30 w-[34rem] max-w-[calc(100vw-4rem)] -translate-y-1/2 rounded-panel px-4 py-3 text-left", floatingSurfaceElevationClassName)}
style={{ top: Math.max(60, Math.min(height - 60, padding + focused * GAP - scrollTop)) }}>
<div className="line-clamp-2 whitespace-pre-wrap break-words text-[15px] font-semibold leading-6">{preview.preview || preview.label}</div>
{preview.answerPreview ? <div className="mt-1.5 max-h-[4.5rem] overflow-hidden break-words text-sm leading-6 text-muted-foreground">
<MarkdownText className="max-w-none text-sm leading-6 prose-headings:my-0 prose-headings:text-sm prose-p:my-0">{preview.answerPreview}</MarkdownText>
</div> : null}
</div> : null}
</div>;
}
+11 -4
View File
@@ -13,6 +13,7 @@ import { parseWebLink } from "@/lib/web-preview";
import { createFilePreviewResource } from "@/lib/file-preview-resource";
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { usePromptHistory } from "@/hooks/usePromptHistory";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
@@ -934,6 +935,9 @@ export function ThreadShell({
} = useNanobotStream(
chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds,
);
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);
const updateNavigationMessages = promptNavigation.updateMessages;
const loadTraceDetails = useCallback(async (refs: string[]) => {
const requestKey = historyKey;
@@ -950,13 +954,15 @@ export function ThreadShell({
.then((detail) => {
if (activeHistoryKeyRef.current !== requestKey) return;
const projected = projectThreadEvents(detail.events);
setMessages((current) => current.flatMap((message) => {
const hydrate = (current: UIMessage[]) => current.flatMap((message) => {
if (message.traceDetail?.ref !== ref) return [message];
return projected.map((replacement) => ({
...replacement,
activitySegmentId: message.activitySegmentId ?? replacement.activitySegmentId,
}));
}));
});
setMessages(hydrate);
updateNavigationMessages(hydrate);
})
.catch((error: unknown) => {
if (activeHistoryKeyRef.current !== requestKey) return;
@@ -969,7 +975,7 @@ export function ThreadShell({
requests.push(request);
}
await Promise.all(requests);
}, [getToken, historyKey, setMessages]);
}, [getToken, historyKey, setMessages, updateNavigationMessages]);
useEffect(() => () => {
activeHistoryKeyRef.current = null;
@@ -1033,7 +1039,6 @@ export function ThreadShell({
};
}, []);
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
const hasAppMentions = displayMessages.some((message) => message.cliApps?.length || message.mcpPresets?.length);
useEffect(() => {
if (hasAppMentions) requestMentionCatalogs();
@@ -2008,6 +2013,7 @@ export function ThreadShell({
const promptNavigatorAction = historyKey ? (
<PromptNavigator
messages={displayMessages}
prompts={promptNavigation.prompts}
onJumpToPrompt={(promptId) => viewportRef.current?.jumpToUserPrompt(promptId)}
/>
) : undefined;
@@ -2070,6 +2076,7 @@ export function ThreadShell({
<ThreadViewport
ref={viewportRef}
messages={displayMessages}
navigation={promptNavigation}
temporary={temporary}
isStreaming={turnActive}
runStartedAt={currentRunStartedAt}
+76 -20
View File
@@ -27,6 +27,7 @@ import {
promptTop,
} from "@/components/thread/promptNavigation";
import { cn } from "@/lib/utils";
import type { PromptHistoryNavigation } from "@/hooks/usePromptHistory";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
export interface ThreadViewportHandle {
@@ -36,6 +37,7 @@ export interface ThreadViewportHandle {
interface ThreadViewportProps {
messages: UIMessage[];
navigation?: PromptHistoryNavigation;
temporary?: boolean;
isStreaming: boolean;
/** Optimistic or canonical start time for the active turn, in unix seconds. */
@@ -232,15 +234,16 @@ function readSoftKeyboardInsetBottom(container: HTMLElement | null): number {
}
export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProps>(function ThreadViewport({
messages,
messages: latestMessages,
navigation,
temporary = false,
isStreaming,
isStreaming: liveStreaming,
runStartedAt = null,
retryStatus = null,
composer,
emptyState,
scrollToBottomSignal = 0,
activeTurnId = null,
activeTurnId: liveTurnId = null,
activeTurnStartedHere = false,
conversationKey = null,
conversationReady = true,
@@ -248,12 +251,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
cliApps = [],
mcpPresets = [],
slashCommands = [],
forkBoundaryMessageCount = null,
hasMoreBefore = false,
loadingOlder = false,
olderError = null,
userMessageOffset = 0,
onLoadOlder,
forkBoundaryMessageCount: latestForkBoundary = null,
hasMoreBefore: latestHasMoreBefore = false,
loadingOlder: latestLoadingOlder = false,
olderError: latestOlderError = null,
userMessageOffset: latestUserOffset = 0,
onLoadOlder: loadLatestOlder,
traceDetailScope = null,
onLoadTraceDetails,
onOpenFilePreview,
@@ -261,6 +264,16 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onQuoteSelection,
}, ref) {
const { t } = useTranslation();
const historyWindow = navigation?.window;
const messages = historyWindow?.messages ?? latestMessages;
const isStreaming = !historyWindow && liveStreaming;
const activeTurnId = historyWindow ? null : liveTurnId;
const forkBoundaryMessageCount = historyWindow ? historyWindow.forkBoundaryMessageCount : latestForkBoundary;
const hasMoreBefore = historyWindow?.hasMoreBefore ?? latestHasMoreBefore;
const loadingOlder = historyWindow ? navigation!.loading : latestLoadingOlder;
const olderError = historyWindow ? navigation!.error : latestOlderError;
const userMessageOffset = historyWindow?.userMessageOffset ?? latestUserOffset;
const onLoadOlder = historyWindow ? navigation!.older : loadLatestOlder;
const scrollRef = useRef<HTMLDivElement | null>(null);
const viewportFrameRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
@@ -516,13 +529,34 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const jumpToUserPrompt = useCallback((promptId: string) => {
if (navigateToVisiblePrompt(promptId)) return;
if (navigation?.prompts.some((prompt) => prompt.id === promptId && prompt.cursor)) {
threadMotionRef.current?.takeUserControl();
navigation.jump(promptId);
return;
}
const index = messages.findIndex((message) => message.id === promptId);
if (index < 0) return;
threadMotionRef.current?.takeUserControl();
pendingPromptJumpRef.current = promptId;
setAtBottom(false);
setVisibleMessageCount((count) => Math.max(count, messages.length - index));
}, [messages, navigateToVisiblePrompt]);
}, [messages, navigateToVisiblePrompt, navigation]);
useLayoutEffect(() => {
if (!navigation?.target) return;
historyScrollAnchorRef.current = null;
restoreScrollAfterPrependRef.current = null;
pendingConversationScrollRef.current = false;
pendingPromptJumpRef.current = navigation.target.id;
threadMotionRef.current?.takeUserControl();
setAtBottom(false);
const index = messages.findIndex((message) => message.id === navigation.target!.id);
setVisibleMessageCount(Math.max(INITIAL_HISTORY_WINDOW, messages.length - Math.max(0, index)));
}, [navigation?.target]);
useEffect(() => {
if (activeTurnStartedHere && liveTurnId) navigation?.latest();
}, [activeTurnStartedHere, liveTurnId, navigation?.latest]);
const cancelAutoScroll = useCallback(() => {
threadMotionRef.current?.takeUserControl();
@@ -661,16 +695,19 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
Math.max(0, pending.top + delta),
);
threadMotionRef.current?.jumpTo(nextTop);
}, [reconcileHistoryScrollAnchor, visibleMessages.length, messages.length]);
}, [reconcileHistoryScrollAnchor, visibleMessages.length, messages]);
useLayoutEffect(() => {
const promptId = pendingPromptJumpRef.current;
const scrollEl = scrollRef.current;
if (!promptId || !scrollEl || !findPromptElement(scrollEl, promptId)) return;
pendingPromptJumpRef.current = null;
const frame = window.requestAnimationFrame(() => navigateToVisiblePrompt(promptId));
const frame = window.requestAnimationFrame(() => {
if (pendingPromptJumpRef.current === promptId && navigateToVisiblePrompt(promptId)) {
pendingPromptJumpRef.current = null;
}
});
return () => window.cancelAnimationFrame(frame);
}, [navigateToVisiblePrompt, visibleMessages.length]);
}, [navigateToVisiblePrompt, visibleMessages, navigation?.target]);
useLayoutEffect(() => {
if (!pendingConversationScrollRef.current) return;
@@ -768,13 +805,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
const near = distance < NEAR_BOTTOM_PX;
const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";
const logicallyAtBottom = owner === "automatic" || (owner === "navigation" && near);
const logicallyAtBottom = !historyWindow && (owner === "automatic" || (owner === "navigation" && near));
setAtBottom((current) =>
current === logicallyAtBottom ? current : logicallyAtBottom,
);
if (owner === "user") {
captureHistoryScrollAnchor();
if (allowHistoryLoad) maybeLoadEarlierFromScroll();
if (allowHistoryLoad && distance < HISTORY_PREFETCH_MIN_PX
&& historyWindow?.hasMoreAfter && !navigation?.loading && !navigation?.error) navigation?.newer();
} else if (near) {
historyScrollAnchorRef.current = null;
}
@@ -789,6 +828,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
direction: ThreadScrollDirection | null,
) => {
if (!direction) return;
if (direction === "forward" && historyWindow?.hasMoreAfter
&& el.scrollHeight - el.scrollTop - el.clientHeight < HISTORY_PREFETCH_MIN_PX
&& !navigation?.loading && !navigation?.error) {
captureHistoryScrollAnchor();
navigation?.newer();
}
// At the top (including a page too short to scroll), backward intent
// produces no scroll event. It must still be able to reveal history.
if (direction === "backward" && canLoadAtTop()) {
@@ -930,6 +975,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
maybeLoadEarlierFromScroll,
olderError,
yieldCameraToUser,
historyWindow,
navigation,
]);
return (
@@ -1062,7 +1109,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
/>
) : null}
</div>
{hasMessages && conversationReady && nearHistoryTop && hasMoreBefore ? (
{navigation && (navigation.loading || navigation.error) ? (
<ThreadHistoryStatus loading={navigation.loading} error={navigation.error} onRetry={navigation.retry} />
) : hasMessages && conversationReady && nearHistoryTop && hasMoreBefore ? (
<ThreadHistoryStatus
key={conversationKey}
loading={loadingOlder}
@@ -1076,14 +1125,15 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
{hasMessages ? (
<PromptRail
messages={visibleMessages}
messages={messages}
prompts={navigation?.prompts}
scrollRef={scrollRef}
bottomOffset={scrollButtonBottom}
onJumpToPrompt={navigateToVisiblePrompt}
onJumpToPrompt={jumpToUserPrompt}
/>
) : null}
{showScrollToBottomButton && !atBottom && (
{showScrollToBottomButton && (!atBottom || historyWindow) && (
<div
className="absolute left-1/2 z-20 -translate-x-1/2"
style={{ bottom: scrollButtonBottom }}
@@ -1091,7 +1141,13 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<Button
variant="outline"
size="icon"
onClick={() => scrollToBottom(true, { force: true })}
onClick={() => {
if (historyWindow) {
pendingConversationScrollRef.current = true;
setVisibleMessageCount(INITIAL_HISTORY_WINDOW);
navigation?.latest();
} else scrollToBottom(true, { force: true });
}}
className={cn(
"h-8 w-8 rounded-full",
"bg-background/90 backdrop-blur",
@@ -7,6 +7,7 @@ export interface PromptAnchor {
preview: string;
createdAt: number;
index: number;
cursor?: string;
}
export function userPromptAnchors(messages: UIMessage[]): PromptAnchor[] {