perf(webui): bound reasoning previews and pace streaming updates
This commit is contained in:
1 parent
9e71087a2a
commit
7cede64f07
5 files changed
+167
-12
No files matched your search
@@ -12,8 +12,10 @@ export interface ActivityStepProps {
|
|||||||
marker?: ReactNode;
|
marker?: ReactNode;
|
||||||
showMarker?: boolean;
|
showMarker?: boolean;
|
||||||
label: ReactNode;
|
label: ReactNode;
|
||||||
|
tooltipContent?: ReactNode;
|
||||||
ariaLabel?: string;
|
ariaLabel?: string;
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
|
animateLabel?: boolean;
|
||||||
tone?: ActivityStepTone;
|
tone?: ActivityStepTone;
|
||||||
className?: string;
|
className?: string;
|
||||||
contentClassName?: string;
|
contentClassName?: string;
|
||||||
@@ -27,8 +29,10 @@ export function ActivityStep({
|
|||||||
marker,
|
marker,
|
||||||
showMarker = true,
|
showMarker = true,
|
||||||
label,
|
label,
|
||||||
|
tooltipContent,
|
||||||
ariaLabel,
|
ariaLabel,
|
||||||
active = false,
|
active = false,
|
||||||
|
animateLabel = true,
|
||||||
tone = active ? "active" : "neutral",
|
tone = active ? "active" : "neutral",
|
||||||
className,
|
className,
|
||||||
contentClassName,
|
contentClassName,
|
||||||
@@ -43,7 +47,7 @@ export function ActivityStep({
|
|||||||
className="flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap"
|
className="flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap"
|
||||||
>
|
>
|
||||||
<StreamingLabelSheen
|
<StreamingLabelSheen
|
||||||
active={active}
|
active={active && animateLabel}
|
||||||
className={cn(
|
className={cn(
|
||||||
"min-w-0 flex-1 truncate font-medium",
|
"min-w-0 flex-1 truncate font-medium",
|
||||||
tone === "error" ? "text-destructive/78" : "text-muted-foreground/85",
|
tone === "error" ? "text-destructive/78" : "text-muted-foreground/85",
|
||||||
@@ -95,7 +99,7 @@ export function ActivityStep({
|
|||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>{line}</TooltipTrigger>
|
<TooltipTrigger asChild>{line}</TooltipTrigger>
|
||||||
<TooltipContent side="top" className="max-w-[min(32rem,calc(100vw-2rem))] whitespace-pre-wrap break-words">
|
<TooltipContent side="top" className="max-w-[min(32rem,calc(100vw-2rem))] whitespace-pre-wrap break-words">
|
||||||
{label}
|
{tooltipContent ?? label}
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
|
|||||||
@@ -21,12 +21,19 @@ export function ReasoningRow({
|
|||||||
? t("message.reasoningStreaming", { defaultValue: "Thinking…" })
|
? t("message.reasoningStreaming", { defaultValue: "Thinking…" })
|
||||||
: t("message.reasoning", { defaultValue: "Thinking" });
|
: t("message.reasoning", { defaultValue: "Thinking" });
|
||||||
const preview = compactReasoningPreview(text) || fallback;
|
const preview = compactReasoningPreview(text) || fallback;
|
||||||
|
// CSS ellipsis still lays out the full string, including the animated copy.
|
||||||
|
const truncated = preview.length > 512;
|
||||||
|
const label = truncated
|
||||||
|
? preview.slice(0, 512).replace(/[\uD800-\uDBFF]$/, "") + "…"
|
||||||
|
: preview;
|
||||||
return (
|
return (
|
||||||
<ActivityStep
|
<ActivityStep
|
||||||
marker={<ReasoningMarker streaming={streaming} />}
|
marker={<ReasoningMarker streaming={streaming} />}
|
||||||
active={streaming}
|
active={streaming}
|
||||||
|
animateLabel={!truncated}
|
||||||
tone={streaming ? "active" : "success"}
|
tone={streaming ? "active" : "success"}
|
||||||
label={preview}
|
label={label}
|
||||||
|
tooltipContent={preview}
|
||||||
labelClassName="italic text-muted-foreground/78"
|
labelClassName="italic text-muted-foreground/78"
|
||||||
contentClassName="overflow-hidden"
|
contentClassName="overflow-hidden"
|
||||||
className={className}
|
className={className}
|
||||||
|
|||||||
@@ -63,6 +63,8 @@ type PendingStreamEvent =
|
|||||||
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields };
|
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields };
|
||||||
|
|
||||||
const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
|
const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
|
||||||
|
// Markdown and layout work must leave room for input between visible updates.
|
||||||
|
const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Append a reasoning chunk to the last open reasoning stream in ``prev``.
|
* Append a reasoning chunk to the last open reasoning stream in ``prev``.
|
||||||
@@ -303,6 +305,7 @@ export function useNanobotStream(
|
|||||||
const pendingStreamEventsRef = useRef<PendingStreamEvent[]>([]);
|
const pendingStreamEventsRef = useRef<PendingStreamEvent[]>([]);
|
||||||
const streamFrameRef = useRef<number | null>(null);
|
const streamFrameRef = useRef<number | null>(null);
|
||||||
const streamTimerRef = useRef<number | null>(null);
|
const streamTimerRef = useRef<number | null>(null);
|
||||||
|
const lastStreamFlushRef = useRef(0);
|
||||||
const suppressStreamUntilTurnEndRef = useRef(false);
|
const suppressStreamUntilTurnEndRef = useRef(false);
|
||||||
const sideChannelTurnIdsRef = useRef<Set<string>>(new Set());
|
const sideChannelTurnIdsRef = useRef<Set<string>>(new Set());
|
||||||
|
|
||||||
@@ -328,6 +331,7 @@ export function useNanobotStream(
|
|||||||
streamTimerRef.current = null;
|
streamTimerRef.current = null;
|
||||||
}
|
}
|
||||||
pendingStreamEventsRef.current = [];
|
pendingStreamEventsRef.current = [];
|
||||||
|
lastStreamFlushRef.current = 0;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const isSideChannelEvent = useCallback((ev: InboundEvent) => {
|
const isSideChannelEvent = useCallback((ev: InboundEvent) => {
|
||||||
@@ -580,6 +584,7 @@ export function useNanobotStream(
|
|||||||
turn?: UIMessageTurnFields;
|
turn?: UIMessageTurnFields;
|
||||||
source?: UIMessage["source"];
|
source?: UIMessage["source"];
|
||||||
}) => {
|
}) => {
|
||||||
|
lastStreamFlushRef.current = 0;
|
||||||
if (streamFrameRef.current !== null) {
|
if (streamFrameRef.current !== null) {
|
||||||
window.cancelAnimationFrame(streamFrameRef.current);
|
window.cancelAnimationFrame(streamFrameRef.current);
|
||||||
streamFrameRef.current = null;
|
streamFrameRef.current = null;
|
||||||
@@ -659,7 +664,7 @@ export function useNanobotStream(
|
|||||||
});
|
});
|
||||||
}, [applyPendingStreamEvents, closeActiveAssistantStream, resolveActiveAssistantIndex]);
|
}, [applyPendingStreamEvents, closeActiveAssistantStream, resolveActiveAssistantIndex]);
|
||||||
|
|
||||||
const schedulePendingStreamFlush = useCallback(() => {
|
const schedulePendingStreamFlush = useCallback(function schedule() {
|
||||||
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
||||||
if (document.visibilityState === "hidden" || !threadVisibleRef.current) {
|
if (document.visibilityState === "hidden" || !threadVisibleRef.current) {
|
||||||
streamTimerRef.current = window.setTimeout(() => {
|
streamTimerRef.current = window.setTimeout(() => {
|
||||||
@@ -671,11 +676,21 @@ export function useNanobotStream(
|
|||||||
}, BACKGROUND_STREAM_FLUSH_INTERVAL_MS);
|
}, BACKGROUND_STREAM_FLUSH_INTERVAL_MS);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const delay = VISIBLE_STREAM_FLUSH_INTERVAL_MS
|
||||||
|
- (performance.now() - lastStreamFlushRef.current);
|
||||||
|
if (delay > 0) {
|
||||||
|
streamTimerRef.current = window.setTimeout(() => {
|
||||||
|
streamTimerRef.current = null;
|
||||||
|
schedule();
|
||||||
|
}, delay);
|
||||||
|
return;
|
||||||
|
}
|
||||||
streamFrameRef.current = window.requestAnimationFrame(() => {
|
streamFrameRef.current = window.requestAnimationFrame(() => {
|
||||||
streamFrameRef.current = null;
|
streamFrameRef.current = null;
|
||||||
const events = pendingStreamEventsRef.current;
|
const events = pendingStreamEventsRef.current;
|
||||||
if (events.length === 0) return;
|
if (events.length === 0) return;
|
||||||
pendingStreamEventsRef.current = [];
|
pendingStreamEventsRef.current = [];
|
||||||
|
lastStreamFlushRef.current = performance.now();
|
||||||
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
||||||
});
|
});
|
||||||
}, [applyPendingStreamEvents]);
|
}, [applyPendingStreamEvents]);
|
||||||
@@ -683,22 +698,31 @@ export function useNanobotStream(
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (threadVisible) {
|
if (threadVisible) {
|
||||||
flushPendingStreamEvents();
|
flushPendingStreamEvents();
|
||||||
} else if (streamFrameRef.current !== null) {
|
} else if (streamFrameRef.current !== null || streamTimerRef.current !== null) {
|
||||||
window.cancelAnimationFrame(streamFrameRef.current);
|
if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current);
|
||||||
streamFrameRef.current = null;
|
streamFrameRef.current = null;
|
||||||
|
if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current);
|
||||||
|
streamTimerRef.current = null;
|
||||||
schedulePendingStreamFlush();
|
schedulePendingStreamFlush();
|
||||||
}
|
}
|
||||||
}, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]);
|
}, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const flushOnReturn = () => {
|
const onVisibilityChange = () => {
|
||||||
if (document.visibilityState !== "visible" || !threadVisibleRef.current) return;
|
|
||||||
if (pendingStreamEventsRef.current.length === 0) return;
|
if (pendingStreamEventsRef.current.length === 0) return;
|
||||||
flushPendingStreamEvents();
|
if (document.visibilityState === "visible" && threadVisibleRef.current) {
|
||||||
|
flushPendingStreamEvents();
|
||||||
|
} else {
|
||||||
|
if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current);
|
||||||
|
streamFrameRef.current = null;
|
||||||
|
if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current);
|
||||||
|
streamTimerRef.current = null;
|
||||||
|
schedulePendingStreamFlush();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
document.addEventListener("visibilitychange", flushOnReturn);
|
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||||
return () => document.removeEventListener("visibilitychange", flushOnReturn);
|
return () => document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||||
}, [flushPendingStreamEvents]);
|
}, [flushPendingStreamEvents, schedulePendingStreamFlush]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!chatId) return;
|
if (!chatId) return;
|
||||||
|
|||||||
@@ -20,3 +20,34 @@ it("shows the reasoning preview in the shared tooltip on hover and keyboard focu
|
|||||||
await user.keyboard("{Escape}");
|
await user.keyboard("{Escape}");
|
||||||
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
|
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("bounds reasoning text without repainting a truncated label and keeps the complete tooltip current", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const text = "A long reasoning paragraph. ".repeat(2_000) + "original tail";
|
||||||
|
const { container, rerender } = render(<ReasoningRow text={text} streaming />);
|
||||||
|
const line = screen.getByTestId("activity-line");
|
||||||
|
|
||||||
|
expect(line.textContent).toBe(text.slice(0, 512) + "…");
|
||||||
|
expect(container.querySelector("[data-sheen-text]")).toBeNull();
|
||||||
|
expect(screen.getByTestId("activity-reasoning-marker")).toHaveAttribute("data-state", "thinking");
|
||||||
|
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await user.tab();
|
||||||
|
expect(line).toHaveFocus();
|
||||||
|
expect(await screen.findByRole("tooltip")).toHaveTextContent(text);
|
||||||
|
rerender(<ReasoningRow text={text + " latest tail"} streaming />);
|
||||||
|
expect(screen.getByRole("tooltip")).toHaveTextContent(text + " latest tail");
|
||||||
|
await user.keyboard("{Escape}");
|
||||||
|
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
|
||||||
|
expect(line.textContent).toBe(text.slice(0, 512) + "…");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the existing text animation for short active reasoning", () => {
|
||||||
|
const { container } = render(<ReasoningRow text="Short active reasoning" streaming />);
|
||||||
|
expect(container.querySelector("[data-sheen-text]")).toHaveAttribute("data-sheen-text", "Short active reasoning");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not split a surrogate pair at the reasoning preview boundary", () => {
|
||||||
|
render(<ReasoningRow text={"x".repeat(511) + "🚀 tail"} streaming />);
|
||||||
|
expect(screen.getByTestId("activity-line").textContent).toBe("x".repeat(511) + "…");
|
||||||
|
});
|
||||||
@@ -296,6 +296,95 @@ describe("useNanobotStream", () => {
|
|||||||
requestFrame.mockRestore();
|
requestFrame.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("paces visible updates and immediately flushes the final ordered text", () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const now = vi.spyOn(performance, "now").mockReturnValue(1_000);
|
||||||
|
const frames: FrameRequestCallback[] = [];
|
||||||
|
const requestFrame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
|
||||||
|
frames.push(callback);
|
||||||
|
return frames.length;
|
||||||
|
});
|
||||||
|
const fake = fakeClient();
|
||||||
|
const { result, unmount } = renderHook(() => useNanobotStream("paced", EMPTY_MESSAGES), {
|
||||||
|
wrapper: wrap(fake.client),
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
act(() => fake.emit("paced", { event: "delta", chat_id: "paced", text: "first" }));
|
||||||
|
expect(frames).toHaveLength(1);
|
||||||
|
act(() => frames.shift()!(1_000));
|
||||||
|
expect(result.current.messages[0].content).toBe("first");
|
||||||
|
act(() => {
|
||||||
|
fake.emit("paced", { event: "delta", chat_id: "paced", text: " 中文" });
|
||||||
|
fake.emit("paced", { event: "delta", chat_id: "paced", text: "🚀" });
|
||||||
|
vi.advanceTimersByTime(49);
|
||||||
|
});
|
||||||
|
expect(frames).toHaveLength(0);
|
||||||
|
expect(result.current.messages[0].content).toBe("first");
|
||||||
|
now.mockReturnValue(1_050);
|
||||||
|
act(() => vi.advanceTimersByTime(1));
|
||||||
|
expect(frames).toHaveLength(1);
|
||||||
|
act(() => frames.shift()!(1_050));
|
||||||
|
expect(result.current.messages[0].content).toBe("first 中文🚀");
|
||||||
|
act(() => {
|
||||||
|
fake.emit("paced", { event: "delta", chat_id: "paced", text: " tail" });
|
||||||
|
fake.emit("paced", { event: "stream_end", chat_id: "paced" });
|
||||||
|
});
|
||||||
|
expect(result.current.messages[0].content).toBe("first 中文🚀 tail");
|
||||||
|
act(() => fake.emit("paced", { event: "turn_end", chat_id: "paced" }));
|
||||||
|
expect(result.current.messages[0].isStreaming).toBe(false);
|
||||||
|
expect(vi.getTimerCount()).toBe(0);
|
||||||
|
} finally {
|
||||||
|
unmount();
|
||||||
|
requestFrame.mockRestore();
|
||||||
|
now.mockRestore();
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["frame", "timer"] as const)("moves a pending visible %s to background cadence and flushes on return", (pending) => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const descriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
||||||
|
const now = vi.spyOn(performance, "now").mockReturnValue(1_000);
|
||||||
|
const frames: FrameRequestCallback[] = [];
|
||||||
|
const requestFrame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
|
||||||
|
frames.push(callback);
|
||||||
|
return frames.length;
|
||||||
|
});
|
||||||
|
const fake = fakeClient();
|
||||||
|
const { result, unmount } = renderHook(() => useNanobotStream("visibility", EMPTY_MESSAGES), {
|
||||||
|
wrapper: wrap(fake.client),
|
||||||
|
});
|
||||||
|
const visibility = (value: string) => {
|
||||||
|
Object.defineProperty(document, "visibilityState", { configurable: true, value });
|
||||||
|
document.dispatchEvent(new Event("visibilitychange"));
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
act(() => fake.emit("visibility", { event: "delta", chat_id: "visibility", text: "first" }));
|
||||||
|
if (pending === "timer") act(() => frames.shift()!(1_000));
|
||||||
|
act(() => {
|
||||||
|
fake.emit("visibility", { event: "delta", chat_id: "visibility", text: " hidden" });
|
||||||
|
visibility("hidden");
|
||||||
|
vi.advanceTimersByTime(999);
|
||||||
|
});
|
||||||
|
expect(result.current.messages[0]?.content).toBe(pending === "timer" ? "first" : undefined);
|
||||||
|
act(() => vi.advanceTimersByTime(1));
|
||||||
|
expect(result.current.messages[0].content).toBe("first hidden");
|
||||||
|
act(() => {
|
||||||
|
fake.emit("visibility", { event: "delta", chat_id: "visibility", text: " returned" });
|
||||||
|
visibility("visible");
|
||||||
|
});
|
||||||
|
expect(result.current.messages[0].content).toBe("first hidden returned");
|
||||||
|
expect(vi.getTimerCount()).toBe(0);
|
||||||
|
} finally {
|
||||||
|
unmount();
|
||||||
|
requestFrame.mockRestore();
|
||||||
|
now.mockRestore();
|
||||||
|
if (descriptor) Object.defineProperty(document, "visibilityState", descriptor);
|
||||||
|
else delete (document as Document & { visibilityState?: string }).visibilityState;
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("coalesces hidden-tab deltas without scheduling paint frames", () => {
|
it("coalesces hidden-tab deltas without scheduling paint frames", () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");
|
||||||
|
|||||||
Reference in new issue
Block a user