From 7cede64f078f4435053f4a33964ea719ce582684 Mon Sep 17 00:00:00 2001 From: chengyongru Date: Fri, 11 Sep 2026 13:10:18 +0800 Subject: [PATCH] perf(webui): bound reasoning previews and pace streaming updates --- .../thread/activity/ActivityStep.tsx | 8 +- .../thread/activity/ReasoningRow.tsx | 9 +- webui/src/hooks/useNanobotStream.ts | 42 +++++++-- webui/src/tests/reasoning-row.test.tsx | 31 +++++++ webui/src/tests/useNanobotStream.test.tsx | 89 +++++++++++++++++++ 5 files changed, 167 insertions(+), 12 deletions(-) diff --git a/webui/src/components/thread/activity/ActivityStep.tsx b/webui/src/components/thread/activity/ActivityStep.tsx index 21f3bd2cf..c1603a5f6 100644 --- a/webui/src/components/thread/activity/ActivityStep.tsx +++ b/webui/src/components/thread/activity/ActivityStep.tsx @@ -12,8 +12,10 @@ export interface ActivityStepProps { marker?: ReactNode; showMarker?: boolean; label: ReactNode; + tooltipContent?: ReactNode; ariaLabel?: string; active?: boolean; + animateLabel?: boolean; tone?: ActivityStepTone; className?: string; contentClassName?: string; @@ -27,8 +29,10 @@ export function ActivityStep({ marker, showMarker = true, label, + tooltipContent, ariaLabel, active = false, + animateLabel = true, tone = active ? "active" : "neutral", className, contentClassName, @@ -43,7 +47,7 @@ export function ActivityStep({ className="flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap" > {line} - {label} + {tooltipContent ?? label} diff --git a/webui/src/components/thread/activity/ReasoningRow.tsx b/webui/src/components/thread/activity/ReasoningRow.tsx index dcca377a0..dd6cddb15 100644 --- a/webui/src/components/thread/activity/ReasoningRow.tsx +++ b/webui/src/components/thread/activity/ReasoningRow.tsx @@ -21,12 +21,19 @@ export function ReasoningRow({ ? t("message.reasoningStreaming", { defaultValue: "Thinking…" }) : t("message.reasoning", { defaultValue: "Thinking" }); 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 ( } active={streaming} + animateLabel={!truncated} tone={streaming ? "active" : "success"} - label={preview} + label={label} + tooltipContent={preview} labelClassName="italic text-muted-foreground/78" contentClassName="overflow-hidden" className={className} diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 88e05e972..37f3bc2d1 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -63,6 +63,8 @@ type PendingStreamEvent = | { kind: "reasoning"; text: string; turn: UIMessageTurnFields }; 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``. @@ -303,6 +305,7 @@ export function useNanobotStream( const pendingStreamEventsRef = useRef([]); const streamFrameRef = useRef(null); const streamTimerRef = useRef(null); + const lastStreamFlushRef = useRef(0); const suppressStreamUntilTurnEndRef = useRef(false); const sideChannelTurnIdsRef = useRef>(new Set()); @@ -328,6 +331,7 @@ export function useNanobotStream( streamTimerRef.current = null; } pendingStreamEventsRef.current = []; + lastStreamFlushRef.current = 0; }, []); const isSideChannelEvent = useCallback((ev: InboundEvent) => { @@ -580,6 +584,7 @@ export function useNanobotStream( turn?: UIMessageTurnFields; source?: UIMessage["source"]; }) => { + lastStreamFlushRef.current = 0; if (streamFrameRef.current !== null) { window.cancelAnimationFrame(streamFrameRef.current); streamFrameRef.current = null; @@ -659,7 +664,7 @@ export function useNanobotStream( }); }, [applyPendingStreamEvents, closeActiveAssistantStream, resolveActiveAssistantIndex]); - const schedulePendingStreamFlush = useCallback(() => { + const schedulePendingStreamFlush = useCallback(function schedule() { if (streamFrameRef.current !== null || streamTimerRef.current !== null) return; if (document.visibilityState === "hidden" || !threadVisibleRef.current) { streamTimerRef.current = window.setTimeout(() => { @@ -671,11 +676,21 @@ export function useNanobotStream( }, BACKGROUND_STREAM_FLUSH_INTERVAL_MS); 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 = null; const events = pendingStreamEventsRef.current; if (events.length === 0) return; pendingStreamEventsRef.current = []; + lastStreamFlushRef.current = performance.now(); setMessages((prev) => applyPendingStreamEvents(prev, events)); }); }, [applyPendingStreamEvents]); @@ -683,22 +698,31 @@ export function useNanobotStream( useEffect(() => { if (threadVisible) { flushPendingStreamEvents(); - } else if (streamFrameRef.current !== null) { - window.cancelAnimationFrame(streamFrameRef.current); + } else if (streamFrameRef.current !== null || streamTimerRef.current !== null) { + if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current); streamFrameRef.current = null; + if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current); + streamTimerRef.current = null; schedulePendingStreamFlush(); } }, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]); useEffect(() => { - const flushOnReturn = () => { - if (document.visibilityState !== "visible" || !threadVisibleRef.current) return; + const onVisibilityChange = () => { 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); - return () => document.removeEventListener("visibilitychange", flushOnReturn); - }, [flushPendingStreamEvents]); + document.addEventListener("visibilitychange", onVisibilityChange); + return () => document.removeEventListener("visibilitychange", onVisibilityChange); + }, [flushPendingStreamEvents, schedulePendingStreamFlush]); useEffect(() => { if (!chatId) return; diff --git a/webui/src/tests/reasoning-row.test.tsx b/webui/src/tests/reasoning-row.test.tsx index ea8d2e52e..614312d2a 100644 --- a/webui/src/tests/reasoning-row.test.tsx +++ b/webui/src/tests/reasoning-row.test.tsx @@ -20,3 +20,34 @@ it("shows the reasoning preview in the shared tooltip on hover and keyboard focu await user.keyboard("{Escape}"); 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(); + 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(); + 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(); + 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(); + expect(screen.getByTestId("activity-line").textContent).toBe("x".repeat(511) + "…"); +}); diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index e885d90da..efc21ed2e 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -296,6 +296,95 @@ describe("useNanobotStream", () => { 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", () => { vi.useFakeTimers(); const visibilityDescriptor = Object.getOwnPropertyDescriptor(document, "visibilityState");