Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
perf(webui): bound reasoning previews and pace streaming updates
chengyongru7cede64f078f
diff --git a/webui/src/components/thread/activity/ActivityStep.tsx b/webui/src/components/thread/activity/ActivityStep.tsxindex 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"><StreamingLabelSheen- active={active}+ active={active && animateLabel}className={cn("min-w-0 flex-1 truncate font-medium",tone === "error" ? "text-destructive/78" : "text-muted-foreground/85",@@ -95,7 +99,7 @@ export function ActivityStep({<Tooltip><TooltipTrigger asChild>{line}</TooltipTrigger><TooltipContent side="top" className="max-w-[min(32rem,calc(100vw-2rem))] whitespace-pre-wrap break-words">- {label}+ {tooltipContent ?? label}</TooltipContent></Tooltip></TooltipProvider>diff --git a/webui/src/components/thread/activity/ReasoningRow.tsx b/webui/src/components/thread/activity/ReasoningRow.tsxindex 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 (<ActivityStepmarker={<ReasoningMarker streaming={streaming} />}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.tsindex 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<PendingStreamEvent[]>([]);const streamFrameRef = useRef<number | null>(null);const streamTimerRef = useRef<number | null>(null);+ const lastStreamFlushRef = useRef(0);const suppressStreamUntilTurnEndRef = useRef(false);const sideChannelTurnIdsRef = useRef<Set<string>>(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.tsxindex 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 focuawait 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(<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) + "…");+});diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsxindex 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");