From a645978b3aa89babec08e400bab537190eb2a80d Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 16 Nov 2026 12:35:08 +0800 Subject: [PATCH 1/3] perf(web-ui): eliminate WebKit scrollbar/layout thrashing and streaming overhead Eliminate major desktop WebView (especially macOS WKWebView) frame drops and synchronous layout/style bottlenecks across session switching, turn navigation, focus modality transitions, and long streaming conversations without altering visual streaming cadence or session behavior: 1. Scoped scrollbar & reset CSS for WebKit/Blink: - Gate legacy universal `*::-webkit-scrollbar*` rules behind `@supports not (scrollbar-color: transparent transparent)` so modern engines supporting CSS Scrollbars Level 1 skip matching 7 universal pseudo-element rules on every descendant DOM node (~39% faster transcript layout/remount in WKWebView). - Rewrite fine-pointer scrollbar reveal rules via De Morgan equivalence so toggling `:root[data-openbitfun-focus-visible]` only invalidates `:focus-within` ancestors instead of `:root[...] *` across the whole DOM (19.46 ms -> 1.71 ms per modality flip). - Remove duplicate `AppLayout.scss` import in `AppLayout.tsx` and redundant unlayered `!important` universal `*::before/*::after` box-sizing reset. 2. Eliminate sequential forced synchronous layouts in FlowChat & SceneBar: - Run `centerFlowChatExtent` (`extent.style.left` write) after `useFlowChatVirtualizer` layout reads, reuse `ResizeObserverEntry` `borderBoxSize` in `publishOriginInset`, and set `tabIndex={-1}` in JSX. - Skip `getBoundingClientRect()` DOM scans in `revealPendingTab` when the SceneBar tab strip has no horizontal overflow. - Split `measureRenderedItems` into an attribute-write pass followed by a measurement-read pass, guard key-set diffing by `itemKeyRevision`, and skip `getBoundingClientRect()` in `useTimelineInteraction` while following. 3. Incremental Markdown streaming & zero-allocation budget/hash walks: - Strip closed inline code spans and ignore plain `<` comparisons in `markdownSections` so technical replies (`Vec`, `a < b`) keep 3k-char section freezing instead of falling back to whole-document re-parsing. - Run `rehype-raw` (`parse5`) only when `remark-rehype` emits `raw` HAST nodes, strip code before math detection, enable `remarkCachedParse` for settled math blocks, and reject skipped subtrees at the element level in `useStreamingTextReveal`. - Replace recursive `Object.entries` tuple allocations in `estimateRetainedBytes` and `JSON.stringify` in `calculateTurnHash` with zero-allocation traversals. --- .../packages/ui/src/styles/scrollbars.css | 106 ++++++++++-------- .../packages/ui/tests/scroll-area.test.mjs | 5 + .../src/app/components/SceneBar/SceneBar.tsx | 3 +- .../SceneBar/useSceneTabNavigation.ts | 18 ++- src/web-ui/src/app/layout/AppLayout.scss | 10 +- src/web-ui/src/app/layout/AppLayout.tsx | 1 - .../components/modern/VirtualMessageList.tsx | 10 +- .../modern/useFlowChatVirtualizer.ts | 48 +++++--- .../PersistenceModule.test.ts | 21 ++++ .../flow-chat-manager/PersistenceModule.ts | 102 +++++++++++++---- .../timeline/useTimelineInteraction.ts | 13 ++- .../markdown/MarkdownMathRenderer.tsx | 7 +- .../markdown/MarkdownRenderer.tsx | 33 +++++- .../markdown/markdownSections.test.ts | 9 ++ .../markdown/markdownSections.ts | 16 ++- .../markdown/rehypeRawIfNeeded.ts | 31 +++++ .../markdown/useStreamingTextReveal.ts | 23 +++- src/web-ui/src/shared/utils/resourceBudget.ts | 25 ++++- 18 files changed, 368 insertions(+), 113 deletions(-) create mode 100644 src/web-ui/src/infrastructure/markdown/rehypeRawIfNeeded.ts diff --git a/design-system/packages/ui/src/styles/scrollbars.css b/design-system/packages/ui/src/styles/scrollbars.css index 17d9cd5d10..fc3b9f4049 100644 --- a/design-system/packages/ui/src/styles/scrollbars.css +++ b/design-system/packages/ui/src/styles/scrollbars.css @@ -9,29 +9,56 @@ * tracks for edge-to-edge content. */ @layer openbitfun.base { - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar { - width: var(--openbitfun-scrollbar-width); - height: var(--openbitfun-scrollbar-width); - background: transparent; - } + /* + * Legacy WebKit fallback only when standard `scrollbar-color` is unavailable + * (e.g. Safari <= 18.1). Where `scrollbar-color` is supported, CSS Scrollbars + * Level 1 supersedes `::-webkit-scrollbar*` anyway, while universal + * `*::-webkit-scrollbar*` selectors still force WebKit style/layout work on + * every descendant node. + */ + @supports not (scrollbar-color: transparent transparent) { + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar { + width: var(--openbitfun-scrollbar-width); + height: var(--openbitfun-scrollbar-width); + background: transparent; + } - /* OS settings can expose the root, track pieces, buttons, and corner. */ - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-track, - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-track-piece, - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-corner, - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-button, - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-resizer { - background: transparent; - } + /* OS settings can expose the root, track pieces, buttons, and corner. */ + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-track, + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-track-piece, + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-corner, + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-button, + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-resizer { + background: transparent; + } - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb { - background: var(--openbitfun-color-scrollbar-thumb); - border-radius: var(--openbitfun-scrollbar-radius); - } + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb { + background: var(--openbitfun-color-scrollbar-thumb); + border-radius: var(--openbitfun-scrollbar-radius); + } + + @media (hover: hover) and (pointer: fine) and (forced-colors: none) { + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb { + background: transparent; + } + + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"], :root:not([data-openbitfun-focus-visible="false"]) :focus-within, :root:not([data-openbitfun-focus-visible="false"]):focus-within)::-webkit-scrollbar-thumb { + background: var(--openbitfun-color-scrollbar-thumb); + } + } + + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:hover, + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:active { + background: var(--openbitfun-color-scrollbar-thumb-hover); + } - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:hover, - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:active { - background: var(--openbitfun-color-scrollbar-thumb-hover); + @media (forced-colors: active) { + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb, + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:hover, + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:active { + background: CanvasText; + } + } } /* @@ -43,36 +70,33 @@ scrollbar-width: thin; scrollbar-color: var(--openbitfun-color-scrollbar-thumb) transparent; } - } - /* - * Hide only for a primary mouse/trackpad. Touch keeps a discoverable native - * thumb, and forced colors keeps the operating system's accessibility cues. - * Keyboard focus reveals its viewport without latching ordinary mouse focus. - * A document focus flag avoids a relational selector on every descendant. - * CSS-only consumers conservatively keep focused viewports discoverable. - * Scroll events (including streaming output) do not reveal an idle viewport. - */ - @media (hover: hover) and (pointer: fine) and (forced-colors: none) { - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:not(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"])):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *)::-webkit-scrollbar-thumb { - background: transparent; - } - - @supports (scrollbar-color: transparent transparent) { - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:not(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"])):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *) { + /* + * Hide only for a primary mouse/trackpad. Touch keeps a discoverable native + * thumb, and forced colors keeps the operating system's accessibility cues. + * Keyboard focus reveals its viewport without latching ordinary mouse focus. + * Expressing reveal positively avoids `:root[data-openbitfun-focus-visible="false"] *`, + * which otherwise invalidates every DOM element whenever focus modality flips. + */ + @media (hover: hover) and (pointer: fine) and (forced-colors: none) { + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]) { scrollbar-color: transparent transparent; } + + :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]):where(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"], :root:not([data-openbitfun-focus-visible="false"]) :focus-within, :root:not([data-openbitfun-focus-visible="false"]):focus-within) { + scrollbar-color: var(--openbitfun-color-scrollbar-thumb) transparent; + } } } /* Opt-in hover viewports release idle tracks instead of only hiding paint. Native overflow still owns whether a track is needed when revealed. */ @media (hover: hover) and (pointer: fine) and (forced-colors: none) { - [data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *) { + [data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"][data-openbitfun-scrollbar-visibility="hover"], :root[data-openbitfun-focus-visible="false"] [data-openbitfun-scrollbar-visibility="hover"]) { scrollbar-width: none; } - [data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *)::-webkit-scrollbar { + [data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible):where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"][data-openbitfun-scrollbar-visibility="hover"], :root[data-openbitfun-focus-visible="false"] [data-openbitfun-scrollbar-visibility="hover"])::-webkit-scrollbar { display: none; } } @@ -90,11 +114,5 @@ :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility]) { scrollbar-color: auto; } - - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb, - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:hover, - :where([data-openbitfun-design-system-root], [data-openbitfun-design-system-root] *, [data-openbitfun-scrollbar-visibility])::-webkit-scrollbar-thumb:active { - background: CanvasText; - } } } diff --git a/design-system/packages/ui/tests/scroll-area.test.mjs b/design-system/packages/ui/tests/scroll-area.test.mjs index e634a03821..0350ff0bcb 100644 --- a/design-system/packages/ui/tests/scroll-area.test.mjs +++ b/design-system/packages/ui/tests/scroll-area.test.mjs @@ -66,5 +66,10 @@ test("ScrollArea styling uses public scrollbar tokens and preserves native scrol assert.match(publishedStyles, /--openbitfun-color-scrollbar-thumb-hover/); assert.match(publishedStyles, /\[data-openbitfun-scrollbar-visibility\]/); assert.match(publishedStyles, /scrollbar-width:\s*none/); + // Universal legacy WebKit scrollbar rules must stay gated behind + // `@supports not (scrollbar-color: transparent transparent)` and avoid + // `:root[data-openbitfun-focus-visible="false"] *` full-tree invalidation. + assert.match(publishedStyles, /@supports not\s*\(scrollbar-color:\s*transparent transparent\)/); + assert.doesNotMatch(publishedStyles, /\[data-openbitfun-focus-visible="false"\]\s*\*/); assert.doesNotMatch(styles, /#[0-9a-f]{3,8}/i); }); diff --git a/src/web-ui/src/app/components/SceneBar/SceneBar.tsx b/src/web-ui/src/app/components/SceneBar/SceneBar.tsx index 9b895015a7..f959f845b6 100644 --- a/src/web-ui/src/app/components/SceneBar/SceneBar.tsx +++ b/src/web-ui/src/app/components/SceneBar/SceneBar.tsx @@ -136,6 +136,7 @@ const SceneBar: React.FC = ({ const canAcceptTab = canAcceptCanvasTab || offeredSceneTab; const activeCanvasDrop = canAcceptTab ? canvasDrop : null; const sceneBarClassName = `openbitfun-scene-bar ${className}`.trim(); + const openTabIds = useMemo(() => shownTabs.map(tab => tab.id), [shownTabs]); const { tabRegionRef, tabsRef, @@ -146,7 +147,7 @@ const SceneBar: React.FC = ({ } = useSceneTabNavigation({ activeTabId: selectedTabId, navigationMotion, - openTabIds: shownTabs.map(tab => tab.id), + openTabIds, }); /** diff --git a/src/web-ui/src/app/components/SceneBar/useSceneTabNavigation.ts b/src/web-ui/src/app/components/SceneBar/useSceneTabNavigation.ts index ed947140a0..4e5fb6f8c0 100644 --- a/src/web-ui/src/app/components/SceneBar/useSceneTabNavigation.ts +++ b/src/web-ui/src/app/components/SceneBar/useSceneTabNavigation.ts @@ -102,11 +102,23 @@ export function useSceneTabNavigation({ const pending = pendingRevealRef.current; if (!pending) return; const tabs = tabsRef.current; + if (!tabs) { pendingRevealRef.current = null; return; } + + const visibleStart = tabs.scrollLeft; + const maxScrollLeft = Math.max(0, tabs.scrollWidth - tabs.clientWidth); + // Fast path: when the tab strip fits completely within its viewport and is + // already at origin, any clamped scroll target is 0. Avoid querying tab DOM + // nodes and calling `getBoundingClientRect()`, which otherwise forces an + // extra synchronous layout pass during session switches. + if (maxScrollLeft <= SCROLL_EDGE_EPSILON && visibleStart <= SCROLL_EDGE_EPSILON) { + pendingRevealRef.current = null; + return; + } + const activeTab = getTabElements().find(tab => tab.dataset.openbitfunValue === pending.id); const activeItem = activeTab?.closest('[data-openbitfun-part="item"]') ?? activeTab; - if (!tabs || !activeItem) { pendingRevealRef.current = null; return; } + if (!activeItem) { pendingRevealRef.current = null; return; } - const visibleStart = tabs.scrollLeft; const visibleEnd = visibleStart + tabs.clientWidth; // TabGroup's item is nested in a positioned, draggable SceneBar wrapper. // Its offsetLeft belongs to that wrapper, not this scroll viewport. @@ -121,7 +133,7 @@ export function useSceneTabNavigation({ nextLeft = tabEnd - tabs.clientWidth; } - const target = Math.max(0, Math.min(nextLeft, tabs.scrollWidth - tabs.clientWidth)); + const target = Math.max(0, Math.min(nextLeft, maxScrollLeft)); if (Math.abs(target - visibleStart) <= SCROLL_EDGE_EPSILON) { pendingRevealRef.current = null; return; diff --git a/src/web-ui/src/app/layout/AppLayout.scss b/src/web-ui/src/app/layout/AppLayout.scss index 358a8155ed..66ca3c49b2 100644 --- a/src/web-ui/src/app/layout/AppLayout.scss +++ b/src/web-ui/src/app/layout/AppLayout.scss @@ -6,12 +6,10 @@ */ @use '@/shared/styles/surface-recipes' as surfaces; -// ==================== CSS reset ==================== -// Note: keep box-sizing !important for global consistency. -*, *::before, *::after { - box-sizing: border-box !important; -} - +// ==================== Shell root ==================== +// `box-sizing: border-box` is owned by `@layer openbitfun.reset` in index.html +// and `@openbitfun/ui/styles.css`; avoid unlayered universal `*::before/*::after` +// `!important` rules that force WebKit pseudo-element style resolution on every node. html, body { margin: 0; padding: 0; diff --git a/src/web-ui/src/app/layout/AppLayout.tsx b/src/web-ui/src/app/layout/AppLayout.tsx index c9f3f5105c..108eafee35 100644 --- a/src/web-ui/src/app/layout/AppLayout.tsx +++ b/src/web-ui/src/app/layout/AppLayout.tsx @@ -46,7 +46,6 @@ import { AcpSessionNotifications } from './AcpSessionNotifications'; import { api } from '@/infrastructure/api/service-api/ApiClient'; import { AppearanceBackgroundMediaLayer, appearanceRuntime, useAppearance } from '@/infrastructure/appearance'; import { PeerConnectionStatus } from '@/infrastructure/peer-device/PeerConnectionStatus'; -import './AppLayout.scss'; type TransitionDirection = 'entering' | 'returning' | null; diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx index b98e6bca3c..156262dc0e 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx @@ -490,9 +490,6 @@ const VirtualMessageListSession = forwardRef { - if (scrollerElement && extentElementRef.current) centerFlowChatExtent(scrollerElement, extentElementRef.current); - }, [scrollerElement, viewportWidthPx, endOrigin]); /** Native minimization withdraws the scroller without unmounting the session. */ const isViewportSuspendedRef = useRef(false); const [, commitResumedViewport] = useReducer(revision => revision + 1, 0); @@ -673,6 +670,12 @@ const VirtualMessageListSession = forwardRef { + if (scrollerElement && extentElementRef.current) centerFlowChatExtent(scrollerElement, extentElementRef.current); + }, [scrollerElement, viewportWidthPx, endOrigin]); const measuredWidthRef = useRef(availableWidthPx); measuredWidthRef.current = availableWidthPx; const retainedViewportRectRef = useRef(initialViewportRect); @@ -2745,6 +2748,7 @@ const VirtualMessageListSession = forwardRef
({ const originInsetObserverRef = useRef<{ element: HTMLElement; observer: ResizeObserver } | null>(null); // Initial binding and delayed observer deliveries publish through the same // ownership check, so a retired node cannot replace the current inset. - const publishOriginInset = useCallback((element: HTMLElement | null) => { + const publishOriginInset = useCallback((element: HTMLElement | null, borderBoxBlockSize?: number) => { if (element) { if (originInsetObserverRef.current?.element !== element || !element.isConnected) return; - setContentStartPx(element.offsetHeight); + setContentStartPx( + borderBoxBlockSize !== undefined && Number.isFinite(borderBoxBlockSize) + ? Math.round(borderBoxBlockSize) + : element.offsetHeight, + ); } else if (originInsetObserverRef.current === null) { setContentStartPx(0); } @@ -618,7 +622,9 @@ export function useFlowChatVirtualizer({ previous?.observer.disconnect(); originInsetObserverRef.current = null; if (!originInset) { publishOriginInset(null); return; } - const observer = new ResizeObserver(() => publishOriginInset(originInset)); + const observer = new ResizeObserver((entries) => { + publishOriginInset(originInset, entries[0]?.borderBoxSize?.[0]?.blockSize); + }); originInsetObserverRef.current = { element: originInset, observer }; observer.observe(originInset, { box: 'border-box' }); publishOriginInset(originInset); @@ -1043,14 +1049,24 @@ export function useFlowChatVirtualizer({ const scroller = scrollerRef.current; if (!scroller || isViewportSuspendedRef.current()) return; const elements = scroller.querySelectorAll('[data-virtual-index]'); - const measurements: Array<[number, number]> = []; + const targets: Array<[number, HTMLElement]> = []; + // Pass 1: commit any changed index attributes before reading layout so + // interleaved DOM attribute writes + getBoundingClientRect() calls do not + // force N separate style/layout recalculations across rendered rows. for (const element of elements) { if (element.closest('[data-flowchat-virtual-viewport]') !== scroller) continue; const index = toVirtualIndex(Number(element.getAttribute('data-virtual-index'))); if (!Number.isInteger(index)) continue; - element.setAttribute('data-flowchat-measure-index', String(index)); - measurements.push([index, virtualizer.options.measureElement(element, undefined, virtualizer)]); + const indexAttr = String(index); + if (element.getAttribute('data-flowchat-measure-index') !== indexAttr) { + element.setAttribute('data-flowchat-measure-index', indexAttr); + } + targets.push([index, element]); } + const measurements: Array<[number, number]> = targets.map(([index, element]) => [ + index, + virtualizer.options.measureElement(element, undefined, virtualizer), + ]); // measure() clears keyed sizes but leaves the previous derived positions. // Rebuild those before resizeItem compares heights: otherwise unchanged // compact rows look like zero deltas, never repopulate the empty size cache, @@ -1069,20 +1085,24 @@ export function useFlowChatVirtualizer({ }, []); const layoutSignature = `${estimateContext?.availableWidthPx ?? ''}:${fontRevision}`; const measuredLayoutRef = useRef(layoutSignature); + const previousKeyRevisionRef = useRef(null); const previousKeysRef = useRef(new Set()); const retiredMeasurementsRef = useRef(0); /** A pass owed to a layout that a pane drag had not finished moving. */ const pendingLayoutMeasureRef = useRef(false); useLayoutEffect(() => { - const keys = new Set(itemKeysRef.current); - for (const key of previousKeysRef.current) if (!keys.has(key)) { - retiredMeasurementsRef.current++; - reservedEstimatesRef.current.delete(key); - measuredKeysRef.current.delete(key); - // A key that returns later starts from an estimate, not its retained size. - restoredItemKeys.delete(key); + if (previousKeyRevisionRef.current !== itemKeyRevision) { + previousKeyRevisionRef.current = itemKeyRevision; + const keys = new Set(itemKeysRef.current); + for (const key of previousKeysRef.current) if (!keys.has(key)) { + retiredMeasurementsRef.current++; + reservedEstimatesRef.current.delete(key); + measuredKeysRef.current.delete(key); + // A key that returns later starts from an estimate, not its retained size. + restoredItemKeys.delete(key); + } + previousKeysRef.current = keys; } - previousKeysRef.current = keys; if (measuredLayoutRef.current === layoutSignature && retiredMeasurementsRef.current < 2048 && !pendingLayoutMeasureRef.current) return; /* diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts index 8e441b237d..c139dcc0be 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { activateSurface, getActiveSurfaceId } from '@/infrastructure/peer-device/deviceSurface'; import type { DialogTurn, ModelRound } from '../../types/flow-chat'; import { + calculateTurnHash, convertDialogTurnToBackendFormat, debouncedSaveDialogTurn, immediateSaveDialogTurn, @@ -544,4 +545,24 @@ describe('PersistenceModule', () => { 'workspace-local', ); }); + + it('computes deterministic structural turn hashes without JSON.stringify', () => { + const stringifySpy = vi.spyOn(JSON, 'stringify'); + const base = createDialogTurn('processing'); + base.modelRounds[0].items = [ + { id: 't1', type: 'text', content: 'hello world', isStreaming: true, timestamp: 1001 } as any, + ]; + const clone = structuredClone(base); + expect(calculateTurnHash(base)).toBe(calculateTurnHash(clone)); + expect(stringifySpy).not.toHaveBeenCalled(); + + const changedText = structuredClone(base); + (changedText.modelRounds[0].items[0] as any).content = 'hello world!'; + expect(calculateTurnHash(changedText)).not.toBe(calculateTurnHash(base)); + + const completed = structuredClone(base); + completed.status = 'completed'; + expect(calculateTurnHash(completed)).not.toBe(calculateTurnHash(base)); + stringifySpy.mockRestore(); + }); }); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts index 61e2dd5143..c35d901ca7 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PersistenceModule.ts @@ -96,31 +96,89 @@ async function runSerialDialogTurnSave( await task; } +function mixHashByte(state: { h1: number; h2: number }, code: number): void { + state.h1 = Math.imul(state.h1 ^ code, 16777619) >>> 0; + state.h2 = (Math.imul(state.h2, 33) + code) >>> 0; +} + +function mixHashString(state: { h1: number; h2: number }, value: string): void { + mixHashByte(state, value.length); + for (let i = 0; i < value.length; i += 1) { + mixHashByte(state, value.charCodeAt(i)); + } +} + +function mixHashValue(state: { h1: number; h2: number }, value: unknown, seen: Set): void { + if (value === null) { + mixHashByte(state, 1); + return; + } + if (value === undefined) { + mixHashByte(state, 2); + return; + } + const kind = typeof value; + if (kind === 'string') { + mixHashByte(state, 3); + mixHashString(state, value as string); + return; + } + if (kind === 'number') { + mixHashByte(state, 4); + mixHashString(state, Number.isFinite(value as number) ? String(value) : 'null'); + return; + } + if (kind === 'boolean') { + mixHashByte(state, (value as boolean) ? 5 : 6); + return; + } + if (kind !== 'object') { + return; + } + const obj = value as object; + if (seen.has(obj)) { + mixHashByte(state, 7); + return; + } + seen.add(obj); + if (Array.isArray(obj)) { + mixHashByte(state, 8); + mixHashByte(state, obj.length); + for (let i = 0; i < obj.length; i += 1) { + mixHashValue(state, obj[i], seen); + } + seen.delete(obj); + return; + } + mixHashByte(state, 9); + const record = obj as Record; + for (const key in record) { + if (Object.prototype.hasOwnProperty.call(record, key)) { + const child = record[key]; + if (child !== undefined && typeof child !== 'function') { + mixHashString(state, key); + mixHashValue(state, child, seen); + } + } + } + seen.delete(obj); +} + /** - * Calculate content hash for dialog turn (for deduplication) + * Calculate content hash for dialog turn (for deduplication) without allocating + * a multi-hundred-KB `JSON.stringify` buffer over tool results and round items. */ export function calculateTurnHash(dialogTurn: DialogTurn): string { - const keyData = JSON.stringify({ - status: dialogTurn.status, - roundsCount: dialogTurn.modelRounds.length, - lastRoundData: dialogTurn.modelRounds[dialogTurn.modelRounds.length - 1] - ? { - ...dialogTurn.modelRounds[dialogTurn.modelRounds.length - 1], - items: dialogTurn.modelRounds[dialogTurn.modelRounds.length - 1].items, - } - : null, - error: dialogTurn.error, - endTime: dialogTurn.endTime, - tokenUsage: dialogTurn.tokenUsage, - }); - - let hash = 0; - for (let i = 0; i < keyData.length; i++) { - const char = keyData.charCodeAt(i); - hash = ((hash << 5) - hash) + char; - hash = hash & hash; - } - return hash.toString(36); + const state = { h1: 2166136261, h2: 5381 }; + const seen = new Set(); + const lastRound = dialogTurn.modelRounds[dialogTurn.modelRounds.length - 1] ?? null; + mixHashValue(state, dialogTurn.status, seen); + mixHashByte(state, dialogTurn.modelRounds.length); + mixHashValue(state, lastRound, seen); + mixHashValue(state, dialogTurn.error, seen); + mixHashValue(state, dialogTurn.endTime, seen); + mixHashValue(state, dialogTurn.tokenUsage, seen); + return `${state.h1.toString(36)}_${state.h2.toString(36)}`; } /** diff --git a/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts b/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts index 61cc4bc548..33b0ebcecc 100644 --- a/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts +++ b/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts @@ -74,11 +74,18 @@ export function useTimelineInteraction( setPinnedKeys(previous => previous.size === pinned.size && [...pinned].every(key => previous.has(key)) ? previous : pinned); reader.setPinnedRows(pinned); const groups = new Set(); - const bounds = scroller.getBoundingClientRect(); + const following = followingRef.current(); + const bounds = following ? null : scroller.getBoundingClientRect(); scroller.querySelectorAll('.virtual-item-wrapper[data-timeline-kind="group-members"]').forEach(row => { - const rect = row.getBoundingClientRect(); - if (pinned.has(row.dataset.virtualItemKey!) || (!followingRef.current() && rect.bottom > bounds.top && rect.top < bounds.bottom)) { + if (pinned.has(row.dataset.virtualItemKey!)) { groups.add(row.dataset.timelineGroupId!); + return; + } + if (bounds) { + const rect = row.getBoundingClientRect(); + if (rect.bottom > bounds.top && rect.top < bounds.bottom) { + groups.add(row.dataset.timelineGroupId!); + } } }); for (const [group, release] of holds) if (!groups.has(group)) { release(); holds.delete(group); } diff --git a/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx b/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx index a4a121a56b..f2853e712f 100644 --- a/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx +++ b/src/web-ui/src/infrastructure/markdown/MarkdownMathRenderer.tsx @@ -7,7 +7,8 @@ import { remarkAutolinkBoundaries } from './remarkAutolinkBoundaries'; import { remarkStreamingTableLinks } from './remarkStreamingTableLinks'; import remarkMath from 'remark-math'; import rehypeKatex from 'rehype-katex'; -import rehypeRaw from 'rehype-raw'; +import { remarkCachedParse } from './markdownParseCache'; +import { rehypeRawIfNeeded } from './rehypeRawIfNeeded'; import rehypeSanitize from 'rehype-sanitize'; import type { Options as RehypeSanitizeOptions } from 'rehype-sanitize'; import type { Pluggable } from 'unified'; @@ -41,8 +42,8 @@ export const MarkdownMathRenderer: React.FC = ({ }) => { const content = ( diff --git a/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx b/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx index 72dbaa15db..a7d3cc74c7 100644 --- a/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx +++ b/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx @@ -15,7 +15,7 @@ import { remarkCachedParse } from './markdownParseCache'; import { remarkAutolinkBoundaries } from './remarkAutolinkBoundaries'; import { remarkStreamingTableLinks } from './remarkStreamingTableLinks'; import { rehypeImageThumbnails } from './rehypeImageThumbnails'; -import rehypeRaw from 'rehype-raw'; +import { rehypeRawIfNeeded } from './rehypeRawIfNeeded'; import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'; import { visit } from 'unist-util-visit'; import { i18nService } from '@/infrastructure/i18n'; @@ -175,16 +175,39 @@ function mayNeedWorkspacePathForMarkdownLinks(content: string): boolean { /]*href=["']\s*(?!https?:|mailto:|visualization:|tab:|#)[^"']+["']/i.test(content); } +function stripMarkdownCodeForMathCheck(content: string): string { + let stripped = content; + if (stripped.includes('```') || stripped.includes('~~~')) { + stripped = stripped.replace( + /(^[ \t]{0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^[ \t]{0,3}\2[ \t]*$|$))/gm, + '\n', + ); + } + if (stripped.includes('`')) { + stripped = stripped.replace(/(`+)[^\n]*?\1/g, ' '); + } + return stripped; +} + function mayContainMarkdownMath(content: string): boolean { if (!content) { return false; } - if (content.includes('$$') || content.includes('\\(') || content.includes('\\[')) { + if ( + !content.includes('$') && + !content.includes('\\(') && + !content.includes('\\[') + ) { + return false; + } + + const prose = stripMarkdownCodeForMathCheck(content); + if (prose.includes('$$') || prose.includes('\\(') || prose.includes('\\[')) { return true; } - return /(^|[^\\$])\$[^$\n]{1,240}\$(?!\d)/.test(content); + return /(^|[^\\$])\$[^$\n]{1,240}\$(?!\d)/.test(prose); } /** Catches render errors from react-markdown/remark-gfm (e.g. RegExp in transformGfmAutolinkLiterals) and shows plain text fallback. */ @@ -1765,7 +1788,7 @@ const MarkdownSurface = React.memo{fragment} @@ -1787,7 +1810,7 @@ const MarkdownSurface = React.memo diff --git a/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts b/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts index bc17b48f1d..5797b8d0c5 100644 --- a/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts +++ b/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts @@ -61,4 +61,13 @@ describe('Markdown presentation sections', () => { const source = prefix + dependent + '\n\n' + prefix; expect(markdownSections(source)).toEqual([{ start: 0, end: source.length }]); }); + + it('splits technical documents with inline code generics, indexing, and < comparisons', () => { + const technical = ( + 'Use `Vec`, `Result`, and `matrix[i][j]` whenever latency < 16 ms and a <= b.\n\n' + ).repeat(120); + const sections = markdownSections(technical, { streaming: true }); + expect(sections.length).toBeGreaterThan(2); + expect(sections.map(section => technical.slice(section.start, section.end)).join('')).toBe(technical); + }); }); diff --git a/src/web-ui/src/infrastructure/markdown/markdownSections.ts b/src/web-ui/src/infrastructure/markdown/markdownSections.ts index bccdfc58ae..9d583a963d 100644 --- a/src/web-ui/src/infrastructure/markdown/markdownSections.ts +++ b/src/web-ui/src/infrastructure/markdown/markdownSections.ts @@ -24,6 +24,20 @@ interface SettledPrefixRecord { let lastRecord: SettledPrefixRecord | undefined; +function stripInlineCodeSpans(content: string): string { + if (!content.includes('`')) return content; + return content.replace(/(`+)[\s\S]*?\1/g, ' '); +} + +function hasCrossBlockInlineSyntax(content: string): boolean { + if (!content.includes('<') && !content.includes('[')) return false; + const outsideCode = stripInlineCodeSpans(content); + // Match actual HTML/comment/declaration/autolink starts (or an unfinished + // trailing `<` while streaming) plus reference/footnote brackets, while keeping + // inline code (`Vec`, `arr[0][1]`) and prose comparisons (`a < b`) splittable. + return /<(?:[A-Za-z!?/]|$)|\]\s*\[|\[\^/.test(outsideCode); +} + function computeRawBoundaries(source: string): { boundaries: number[]; extendable: boolean } { const normalized = source.replace(/\r\n?|\0/g, match => match === '\0' ? '\uFFFD' : '\n'); const tokens: Parameters[3] = []; @@ -32,7 +46,7 @@ function computeRawBoundaries(source: string): { boundaries: number[]; extendabl if (environment.references || environment.footnotes || tokens.some(token => token.type.startsWith('html') || token.type.startsWith('footnote') // Inline HTML/reference definitions may bind beyond a top-level block. - || (token.type === 'inline' && /<|\]\s*\[|\[\^/.test(token.content)))) { + || (token.type === 'inline' && hasCrossBlockInlineSyntax(token.content)))) { return { boundaries: [0], extendable: false }; } const offsets = [0]; diff --git a/src/web-ui/src/infrastructure/markdown/rehypeRawIfNeeded.ts b/src/web-ui/src/infrastructure/markdown/rehypeRawIfNeeded.ts new file mode 100644 index 0000000000..26b9c09829 --- /dev/null +++ b/src/web-ui/src/infrastructure/markdown/rehypeRawIfNeeded.ts @@ -0,0 +1,31 @@ +import rehypeRaw from 'rehype-raw'; + +function hastContainsRawNode(node: unknown): boolean { + if (!node || typeof node !== 'object') { + return false; + } + const record = node as { type?: string; children?: unknown[] }; + if (record.type === 'raw') { + return true; + } + const children = record.children; + if (Array.isArray(children)) { + for (let i = 0; i < children.length; i += 1) { + if (hastContainsRawNode(children[i])) { + return true; + } + } + } + return false; +} + +/** + * Runs `rehype-raw` (`hast-util-raw` + `parse5` HTML5 fragment parser) only when + * `remark-rehype` actually emitted at least one `raw` HTML node. Pure Markdown + * trees already consist of standard HAST elements and avoid a full `parse5` + * re-parse on every streaming frame. + */ +export function rehypeRawIfNeeded() { + const rawTransform = rehypeRaw(); + return (tree: any, file: any) => (hastContainsRawNode(tree) ? rawTransform(tree, file) : tree); +} diff --git a/src/web-ui/src/infrastructure/markdown/useStreamingTextReveal.ts b/src/web-ui/src/infrastructure/markdown/useStreamingTextReveal.ts index c31408e502..1844a40c20 100644 --- a/src/web-ui/src/infrastructure/markdown/useStreamingTextReveal.ts +++ b/src/web-ui/src/infrastructure/markdown/useStreamingTextReveal.ts @@ -26,11 +26,26 @@ function pruneEmptyBuckets(entries: OwnedRange[]): void { } } +const SKIPPED_SUBTREE_SELECTOR = 'button, [aria-hidden="true"], .katex-mathml'; + function readRuns(root: HTMLElement): { runs: TextRun[]; text: string } { - const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT, { - acceptNode: node => node.parentElement?.closest('button, [aria-hidden="true"], .katex-mathml') - ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT, - }); + // Rejecting excluded elements at the element level skips their entire subtree + // in O(1) instead of walking `parentElement.closest(...)` up to document root + // for every text node in syntax-highlighted code blocks and tables. + const walker = root.ownerDocument.createTreeWalker( + root, + NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, + { + acceptNode: node => { + if (node.nodeType === Node.ELEMENT_NODE) { + return (node as Element).matches(SKIPPED_SUBTREE_SELECTOR) + ? NodeFilter.FILTER_REJECT + : NodeFilter.FILTER_SKIP; + } + return NodeFilter.FILTER_ACCEPT; + }, + }, + ); const runs: TextRun[] = []; let text = ''; for (let node = walker.nextNode(); node; node = walker.nextNode()) { diff --git a/src/web-ui/src/shared/utils/resourceBudget.ts b/src/web-ui/src/shared/utils/resourceBudget.ts index 77d508e0d6..6952ed664f 100644 --- a/src/web-ui/src/shared/utils/resourceBudget.ts +++ b/src/web-ui/src/shared/utils/resourceBudget.ts @@ -88,15 +88,34 @@ if (import.meta.env.DEV || globalThis.__OPENBITFUN_PERF_TRACE_ENABLED__ === true globalThis.__OPENBITFUN_RESOURCE_BUDGET__ = { snapshot: () => resourceBudget.snapshot() }; } -/** No stringify-sized temporary copy. Shared references are counted once per working set. */ +function decimalDigitCount(index: number): number { + if (index < 10) return 1; + if (index < 100) return 2; + if (index < 1000) return 3; + if (index < 10000) return 4; + return String(index).length; +} + +/** No stringify-sized temporary copy or Object.entries tuple allocations. Shared references are counted once per working set. */ export function estimateRetainedBytes(value: unknown, seen = new Set()): number { if (typeof value === 'string') return value.length * 2; if (!value || typeof value !== 'object') return 8; if (seen.has(value)) return 0; seen.add(value); let bytes = 32; - for (const [key, child] of Object.entries(value)) { - bytes += key.length * 2 + 8 + estimateRetainedBytes(child, seen); + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + if (i in value) { + bytes += decimalDigitCount(i) * 2 + 8 + estimateRetainedBytes(value[i], seen); + } + } + return bytes; + } + const record = value as Record; + for (const key in record) { + if (Object.prototype.hasOwnProperty.call(record, key)) { + bytes += key.length * 2 + 8 + estimateRetainedBytes(record[key], seen); + } } return bytes; } From 43e2e9eb71bf99b7d2f7f23c327e926901136dcf Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 16 Nov 2026 13:04:34 +0800 Subject: [PATCH 2/3] test(web-ui): align scrollbar contract test with @supports WebKit gating --- src/web-ui/src/app/styles/scrollbar.test.ts | 52 +++++++++++++-------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/src/web-ui/src/app/styles/scrollbar.test.ts b/src/web-ui/src/app/styles/scrollbar.test.ts index 19e49d73a5..b2b2adbd15 100644 --- a/src/web-ui/src/app/styles/scrollbar.test.ts +++ b/src/web-ui/src/app/styles/scrollbar.test.ts @@ -26,41 +26,55 @@ describe('shared native scrollbar presentation', () => { }); it('preserves automatic track geometry and only releases explicitly opted-in hover tracks', () => { - const interactionRules = stylesheet.slice( - stylesheet.indexOf('@media (hover: hover)'), - stylesheet.indexOf('/* Opt-in hover viewports'), - ); - const hoverRules = stylesheet.slice( - stylesheet.indexOf('/* Opt-in hover viewports'), - stylesheet.indexOf('/* Explicit hidden viewports'), + const hoverStart = stylesheet.indexOf('/* Opt-in hover viewports'); + const hiddenStart = stylesheet.indexOf('/* Explicit hidden viewports'); + const interactionBlocks = Array.from( + stylesheet + .slice(0, hoverStart) + .matchAll(/@media \(hover: hover\) and \(pointer: fine\) and \(forced-colors: none\)\s*\{([\s\S]*?)\n \}/g), + match => match[1], ); + const hoverRules = stylesheet.slice(hoverStart, hiddenStart); + const positiveRevealSelector = + ':where(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"], :root:not([data-openbitfun-focus-visible="false"]) :focus-within, :root:not([data-openbitfun-focus-visible="false"]):focus-within)'; + + expect(interactionBlocks).toHaveLength(2); + expect(interactionBlocks[0]).toContain('background: transparent;'); + expect(interactionBlocks[0]).toContain(positiveRevealSelector); + expect(interactionBlocks[0]).toContain('background: var(--openbitfun-color-scrollbar-thumb);'); + expect(interactionBlocks[1]).toContain('scrollbar-color: transparent transparent;'); + expect(interactionBlocks[1]).toContain(positiveRevealSelector); + expect(interactionBlocks[1]).toContain('scrollbar-color: var(--openbitfun-color-scrollbar-thumb) transparent;'); + for (const block of interactionBlocks) { + expect(block).not.toMatch(/(?:overflow|width|height|display|scrollbar-gutter)\s*:/); + } - expect(interactionRules).toContain('(pointer: fine) and (forced-colors: none)'); - expect(interactionRules).toContain( - ':not(:hover, :focus-visible, [data-openbitfun-scrollbar-visibility="always"])', - ); - expect(interactionRules).toContain(':where(:not(:focus-within), :root[data-openbitfun-focus-visible="false"], :root[data-openbitfun-focus-visible="false"] *)'); - expect(interactionRules).toContain('background: transparent;'); - expect(interactionRules).toContain('scrollbar-color: transparent transparent;'); - expect(interactionRules).not.toMatch(/(?:overflow|width|height|display|scrollbar-gutter)\s*:/); expect(hoverRules).toContain('@media (hover: hover) and (pointer: fine) and (forced-colors: none)'); expect(hoverRules).toMatch( - /\[data-openbitfun-scrollbar-visibility="hover"\]:not\(:hover, :focus-visible\):where\(:not\(:focus-within\), :root\[data-openbitfun-focus-visible="false"\], :root\[data-openbitfun-focus-visible="false"\] \*\)\s*\{\s*scrollbar-width:\s*none;/, + /\[data-openbitfun-scrollbar-visibility="hover"\]:not\(:hover, :focus-visible\):where\(:not\(:focus-within\), :root\[data-openbitfun-focus-visible="false"\]\[data-openbitfun-scrollbar-visibility="hover"\], :root\[data-openbitfun-focus-visible="false"\] \[data-openbitfun-scrollbar-visibility="hover"\]\)\s*\{\s*scrollbar-width:\s*none;/, ); expect(hoverRules).toMatch( - /\[data-openbitfun-scrollbar-visibility="hover"\]:not\(:hover, :focus-visible\):where\(:not\(:focus-within\), :root\[data-openbitfun-focus-visible="false"\], :root\[data-openbitfun-focus-visible="false"\] \*\)::-webkit-scrollbar\s*\{\s*display:\s*none;/, + /\[data-openbitfun-scrollbar-visibility="hover"\]:not\(:hover, :focus-visible\):where\(:not\(:focus-within\), :root\[data-openbitfun-focus-visible="false"\]\[data-openbitfun-scrollbar-visibility="hover"\], :root\[data-openbitfun-focus-visible="false"\] \[data-openbitfun-scrollbar-visibility="hover"\]\)::-webkit-scrollbar\s*\{\s*display:\s*none;/, ); + const rulesOnly = stylesheet.replace(/\/\*[\s\S]*?\*\//g, ''); expect(hoverRules).not.toMatch(/(?:overflow(?:-[xy])?|scrollbar-gutter)\s*:/); - expect(stylesheet).not.toMatch(/\.is-scrolling|:has\(|!important/); + expect(rulesOnly).not.toMatch(/\[data-openbitfun-focus-visible="false"\]\s*\*/); + expect(rulesOnly).not.toMatch(/\.is-scrolling|:has\(|!important/); }); it('guards standard width and color together so Safari 18 keeps the WebKit path', () => { + expect(stylesheet).toMatch( + /@supports not \(scrollbar-color: transparent transparent\)\s*\{[\s\S]*::-webkit-scrollbar\s*\{/, + ); expect(stylesheet).toMatch( /@supports \(scrollbar-color: transparent transparent\)\s*\{[^{}]+\{\s*scrollbar-width:\s*thin;\s*scrollbar-color:\s*var\(--openbitfun-color-scrollbar-thumb\) transparent;/, ); expect(stylesheet.match(/scrollbar-width:\s*thin/g)).toHaveLength(1); expect(stylesheet).toMatch( - /@media \(forced-colors: active\)[\s\S]*scrollbar-color:\s*auto;[\s\S]*background:\s*CanvasText;/, + /@media \(forced-colors: active\)\s*\{[\s\S]*?background:\s*CanvasText;/, + ); + expect(stylesheet).toMatch( + /@media \(forced-colors: active\)\s*\{[^{}]+\{\s*scrollbar-color:\s*auto;/, ); }); From 06150ddb988a3a752bab5c40b2135588c6c3e231 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 16 Nov 2026 13:04:34 +0800 Subject: [PATCH 3/3] refactor(flow-chat): unify session switch loading with compact brand spinner --- .../device-switch/DeviceSwitchCurtain.tsx | 4 +- .../modern/FLOWCHAT_HISTORY_PAGING.md | 12 +- .../modern/HistorySessionLoadingBoundary.scss | 106 ++---------------- .../HistorySessionLoadingBoundary.test.tsx | 34 +++++- .../modern/HistorySessionLoadingBoundary.tsx | 32 ++---- 5 files changed, 52 insertions(+), 136 deletions(-) diff --git a/src/web-ui/src/app/scenes/device-switch/DeviceSwitchCurtain.tsx b/src/web-ui/src/app/scenes/device-switch/DeviceSwitchCurtain.tsx index b77d070df3..3c23f25df6 100644 --- a/src/web-ui/src/app/scenes/device-switch/DeviceSwitchCurtain.tsx +++ b/src/web-ui/src/app/scenes/device-switch/DeviceSwitchCurtain.tsx @@ -8,8 +8,8 @@ * the action settled and the target scene had a frame to paint. * * Opening an existing session needs no curtain: its tab is held in front and - * the session view shows its own loading skeleton, in its own layout, so the - * loading presentation never changes size or position mid-open. + * the session view shows its own centered loading spinner, in its own layout, + * so the loading presentation never changes size or position mid-open. */ import React, { useEffect, useRef, useState } from 'react'; diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md index b3bd5b0f37..7cfa7734ad 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md @@ -3,10 +3,10 @@ ## History loading presentation `HistorySessionLoadingBoundary` covers open intents, cold hydration and bookmark -restoration with seven 24px lines and a rounded user bubble. Session loading -indicators appear after 200 ms, including reduced-motion mode and new-session -creation. The boundary retains the loading surface until the complete Turn and -`data-open-viewport-settled` are ready. It then +restoration with a centered muted `md` brand `Spinner`, matching the new-session +and device-switch curtains. Session loading indicators appear after 200 ms, +including reduced-motion mode and new-session creation. The boundary retains the +loading surface until the complete Turn and `data-open-viewport-settled` are ready. It then publishes the transcript immediately in the same React commit. Warm session switches also pass through the viewport gate and display settled content immediately. @@ -23,8 +23,8 @@ Session and surface-activation changes disconnect old readiness observers. Failures, inactive scenes and hidden documents release the loading surface. Streaming updates and virtual-window remounts retain the settled presentation. The old `historyOpenIntentSpinner` appearance part remains a hidden compatibility -slot so installed appearance packages still validate. The skeleton is exposed -through `historySkeleton`. +slot so installed appearance packages still validate. The loading indicator +container continues to be exposed through `historySkeleton`. ## Last-Turn opening diff --git a/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.scss b/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.scss index b5a68050dc..f387314d0c 100644 --- a/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.scss +++ b/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.scss @@ -1,5 +1,3 @@ -@use '../../transcript-layout' as transcriptLayout; - .history-session-loading { position: relative; height: 100%; @@ -15,116 +13,28 @@ background: var(--openbitfun-color-surface-scene); touch-action: none; } - } +// The indicator appears only once a load has lasted long enough to notice; a +// fast open goes straight to its settled transcript without any loading flash. .history-session-skeleton { position: absolute; inset: 0; + display: flex; + align-items: center; + justify-content: center; color: var(--openbitfun-color-content-primary); + opacity: 0; pointer-events: none; - - &__column { - @include transcriptLayout.reading-column; - @include transcriptLayout.content-column; - position: relative; - height: 100%; - } - - &__user { - position: absolute; - top: var(--openbitfun-space-6); - right: var(--openbitfun-control-flow-chat-content-padding-inline); - width: min(288px, 54%); - padding: var(--openbitfun-space-5); - display: flex; - flex-direction: column; - gap: var(--openbitfun-space-3); - border-radius: var(--openbitfun-radius-xl); - background: var(--openbitfun-color-action-quiet-hover); - - span { - display: block; - height: var(--openbitfun-space-4); - width: 82%; - border-radius: var(--openbitfun-radius-pill); - background: color-mix(in srgb, var(--openbitfun-color-content-primary) 18%, transparent); - } - - span:last-child { width: 56%; opacity: 0.7; } - } - - &__group { - position: absolute; - left: var(--openbitfun-control-flow-chat-content-padding-inline); - right: var(--openbitfun-control-flow-chat-content-padding-inline); - display: flex; - flex-direction: column; - gap: var(--openbitfun-space-3); - } - - &__bar { - display: block; - height: var(--openbitfun-space-6); - flex-shrink: 0; - border-radius: var(--openbitfun-radius-pill); - background: color-mix(in srgb, var(--openbitfun-color-content-primary) 18%, transparent); - transform-origin: left center; - } - - &__group--first { - top: max(148px, 29%); - .history-session-skeleton__bar:nth-child(1) { width: 66%; opacity: 0.72; } - .history-session-skeleton__bar:nth-child(2) { width: 83%; opacity: 0.64; } - .history-session-skeleton__bar:nth-child(3) { width: 34%; opacity: 0.56; } - } - - &__group--second { - top: max(280px, 54%); - .history-session-skeleton__bar:nth-child(1) { width: 74%; opacity: 0.56; } - .history-session-skeleton__bar:nth-child(2) { width: 44%; opacity: 0.48; } - } - - &__group--third { - top: max(380px, 79%); - .history-session-skeleton__bar:nth-child(1) { width: 59%; opacity: 0.4; } - .history-session-skeleton__bar:nth-child(2) { width: 28%; opacity: 0.32; } - } - - @media (max-width: 768px) { - &__user { right: var(--openbitfun-control-flow-chat-content-padding-inline-mobile); } - &__group { - left: var(--openbitfun-control-flow-chat-content-padding-inline-mobile); - right: var(--openbitfun-control-flow-chat-content-padding-inline-mobile); - } - } -} - -// One moving alpha field illuminates the complete composition. -@media (prefers-reduced-motion: no-preference) and (forced-colors: none) { - .history-session-skeleton { - mask-image: linear-gradient(105deg, currentColor 28%, color-mix(in srgb, currentColor 40%, transparent) 48%, currentColor 68%); - mask-size: 230% 100%; - mask-repeat: no-repeat; - animation: history-session-skeleton-light calc(var(--openbitfun-motion-duration-loop) * 5.5) ease-in-out infinite; - } - -} - -@keyframes history-session-skeleton-light { - 0%, 12% { mask-position: 100% 0; } - 85%, 100% { mask-position: 0 0; } } -// The skeleton appears only once a load has lasted long enough to notice; a -// fast open goes straight to its transcript. .history-session-loading__overlay .history-session-skeleton { - animation: history-session-skeleton-reveal 180ms ease-out both; + animation: history-session-skeleton-reveal 200ms var(--openbitfun-motion-easing-standard) both; } @keyframes history-session-skeleton-reveal { from { opacity: 0; } - to { opacity: 1; } + to { opacity: var(--openbitfun-opacity-muted); } } @media (prefers-reduced-motion: reduce) { diff --git a/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.test.tsx b/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.test.tsx index fcdbda89a2..7100cc5ed1 100644 --- a/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.test.tsx @@ -15,6 +15,8 @@ describe('history loading presentation handoff', () => { let media: MediaQueryList; let hidden: boolean; const action = vi.fn(); + const presentationAnimate = vi.fn(() => { throw new Error('Presentation must be immediate'); }); + const spinnerAnimate = vi.fn(() => ({ cancel: vi.fn(), play: vi.fn(), pause: vi.fn(), effect: null }) as unknown as Animation); const originalAnimate = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'animate'); const transcript = (settled = true, content: React.ReactNode = 'Restored conversation') => (
@@ -38,6 +40,8 @@ describe('history loading presentation handoff', () => { root = createRoot(host); hidden = false; action.mockReset(); + presentationAnimate.mockClear(); + spinnerAnimate.mockClear(); media = Object.assign(new EventTarget(), { media: '(prefers-reduced-motion: reduce)', matches: false, }) as MediaQueryList; @@ -50,7 +54,12 @@ describe('history loading presentation handoff', () => { }); Object.defineProperty(HTMLElement.prototype, 'animate', { configurable: true, - value: vi.fn(() => { throw new Error('Presentation must be immediate'); }), + value: function (this: HTMLElement, ...args: Parameters) { + if (this.closest('[data-openbitfun-component="spinner"]')) { + return spinnerAnimate.apply(this, args); + } + return presentationAnimate.apply(this, args); + }, }); }); @@ -70,7 +79,7 @@ describe('history loading presentation handoff', () => { expect(HTMLElement.prototype.getBoundingClientRect).not.toHaveBeenCalled(); await act(async () => { element('.virtual-message-list').dataset.openViewportSettled = 'true'; }); expect(phase()).toBe('idle'); - expect(HTMLElement.prototype.animate).not.toHaveBeenCalled(); + expect(presentationAnimate).not.toHaveBeenCalled(); expect(HTMLElement.prototype.getBoundingClientRect).not.toHaveBeenCalled(); }); @@ -131,7 +140,7 @@ describe('history loading presentation handoff', () => { clock.mockReturnValue(5_000 + elapsed); render({ loading: false }); expect(phase()).toBe('idle'); - expect(HTMLElement.prototype.animate).not.toHaveBeenCalled(); + expect(presentationAnimate).not.toHaveBeenCalled(); expect(element('.history-session-loading__content').style.opacity).toBe(''); element('button').click(); expect(action).toHaveBeenCalledOnce(); @@ -186,7 +195,7 @@ describe('history loading presentation handoff', () => { expect(element('.virtual-item-wrapper')).toBe(row); expect(row.style.cssText).toBe(''); expect(element('.virtual-message-list').scrollTop).toBe(0); - expect(HTMLElement.prototype.animate).not.toHaveBeenCalled(); + expect(presentationAnimate).not.toHaveBeenCalled(); }); it('guards invisible transcript actions until viewport readiness', async () => { @@ -255,13 +264,26 @@ describe('history loading presentation handoff', () => { expect(phase()).toBe('idle'); }); + it('renders the compact brand spinner instead of full-pane skeleton bars', () => { + render(); + const indicator = element('.history-session-skeleton'); + const spinner = indicator.querySelector('[data-openbitfun-component="spinner"]'); + expect(spinner?.getAttribute('data-size')).toBe('md'); + expect(spinner?.getAttribute('data-variant')).toBe('logo'); + expect(indicator.querySelector('[data-history-loading-line]')).toBeNull(); + expect(indicator.querySelector('.history-session-skeleton__user')).toBeNull(); + expect(spinnerAnimate).toHaveBeenCalled(); + expect(presentationAnimate).not.toHaveBeenCalled(); + }); + it('uses the same delayed indicator and immediate settled presentation with reduced motion', () => { Object.defineProperty(media, 'matches', { value: true }); render(); expect(element('.history-session-skeleton').style.animationDelay).toBe('200ms'); + expect(spinnerAnimate).not.toHaveBeenCalled(); render({ loading: false }); expect(phase()).toBe('idle'); - expect(HTMLElement.prototype.animate).not.toHaveBeenCalled(); + expect(presentationAnimate).not.toHaveBeenCalled(); }); it('releases a hidden document without replaying when it becomes visible', async () => { @@ -279,6 +301,6 @@ describe('history loading presentation handoff', () => { render({ loading: false }); render({ loading: false, children: transcript(true,
New virtual window
) }); expect(phase()).toBe('idle'); - expect(HTMLElement.prototype.animate).not.toHaveBeenCalled(); + expect(presentationAnimate).not.toHaveBeenCalled(); }); }); diff --git a/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.tsx b/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.tsx index 7bf50470fa..143d3f2b46 100644 --- a/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.tsx +++ b/src/web-ui/src/flow_chat/components/modern/HistorySessionLoadingBoundary.tsx @@ -1,4 +1,5 @@ import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'; +import { Spinner } from '@openbitfun/ui'; import { FlowChatOpeningBoundary } from './FlowChatOpeningBoundary'; import { SESSION_LOADING_DELAY_MS } from '../../services/sessionOpenIntent'; import './HistorySessionLoadingBoundary.scss'; @@ -25,9 +26,6 @@ export function HistorySessionLoadingBoundary({ const [state, setState] = useState<{ identity: string; phase: Phase }>({ identity, phase: initialPhase, }); - if (state.identity !== identity) { - setState({ identity, phase: initialPhase }); - } const phase = state.identity === identity ? state.phase : initialPhase; const covering = !disabled && (loading || phase !== 'idle'); @@ -37,14 +35,15 @@ export function HistorySessionLoadingBoundary({ useLayoutEffect(() => { const setPhase = (next: Phase) => setState(previous => ( - previous.identity === identity && previous.phase !== next - ? { identity, phase: next } - : previous + previous.identity === identity && previous.phase === next + ? previous + : { identity, phase: next } )); // Inactive scenes expose their placeholder and recheck the viewport on resume. if (disabled) { setPhase(hasTranscript ? 'loading' : 'idle'); return; } if (loading) { setPhase('loading'); return; } - if (phase === 'idle') return; + if (phase === 'idle') { setPhase('idle'); return; } + setPhase('loading'); const root = rootRef.current; const content = root?.querySelector('.history-session-loading__content'); @@ -119,27 +118,12 @@ export function HistorySessionLoadingBoundary({ ); } -/** The history loading skeleton, shared with presentations that precede a session (a device switch). */ +/** Centered session loading indicator, aligned with new-session and device-switch curtains. */ export function HistorySessionSkeleton() { return ( ); }