From f8f89f08ab01e04bc534eb227ada119d5d99809d Mon Sep 17 00:00:00 2001 From: wsp Date: Sat, 14 Nov 2026 17:41:24 +0800 Subject: [PATCH] perf(web-ui): reduce style invalidation during concurrent BTW streaming Replace root-level startup relational selectors with explicit startup state and share native focus-visible state across scrollbar consumers. This preserves startup handoff and keyboard accessibility while avoiding broad style recalculation as virtualized transcript content changes. Add a BTW scrolling E2E suite using the 200-turn, 100-tool-call template. Check concurrent streams, bidirectional scrolling, reading anchors, bounded DOM windows, return-to-latest, and completed responses. Across two repetitions per direction on local Windows Desktop, pooled RAF FPS improves from 39.9 to 55.3 in primary live content, 18.4 to 40.7 in history, and 41.6 to 55.0 in BTW content. Both versions use the same native binary and benchmark protocol without CDP instrumentation. Validation: 24 E2E measurement segments, 104 focused tests, 8 benchmark contract tests, 4 ScrollArea tests, native focus/geometry checks, TypeScript, production build, and color/motion audits pass. check:web remains blocked by the existing Dialog.module.css:77 typography violation. Remote scenarios were not exercised. --- design-system/packages/ui/README.md | 7 +- .../src/components/ScrollArea/ScrollArea.tsx | 4 + .../ui/src/internal/scrollbarFocus.ts | 49 ++++++++ .../ui/src/primitives/ThemeRoot/ThemeRoot.tsx | 8 +- .../ui/src/providers/DesignSystemProvider.tsx | 4 +- .../packages/ui/src/styles/scrollbars.css | 10 +- src/web-ui/index.html | 17 +-- .../src/app/startup/startupOverlay.test.ts | 21 +++- src/web-ui/src/app/startup/startupOverlay.ts | 5 + .../startupPerformanceContract.test.ts | 6 + .../src/app/startup/startupPreload.test.ts | 2 + src/web-ui/src/app/styles/scrollbar.test.ts | 9 +- .../src/app/styles/scrollbarFocus.test.ts | 73 ++++++++++++ tests/e2e/AGENTS-CN.md | 8 ++ tests/e2e/AGENTS.md | 10 ++ tests/e2e/README.md | 17 +++ tests/e2e/README.zh-CN.md | 10 ++ .../LongSessionPerformancePage.ts | 53 ++++++++- tests/e2e/scripts/long-session-metrics.mjs | 2 +- .../scripts/run-long-session-performance.mjs | 15 ++- .../long-session-performance.spec.ts | 111 ++++++++++++++++-- 21 files changed, 403 insertions(+), 38 deletions(-) create mode 100644 design-system/packages/ui/src/internal/scrollbarFocus.ts create mode 100644 src/web-ui/src/app/styles/scrollbarFocus.test.ts diff --git a/design-system/packages/ui/README.md b/design-system/packages/ui/README.md index 75f08342d3..cd3d29fc72 100644 --- a/design-system/packages/ui/README.md +++ b/design-system/packages/ui/README.md @@ -259,7 +259,12 @@ or contains visible keyboard focus. Leaving the viewport hides it; scrolling from streaming output does not reveal an unattended panel. Touch surfaces retain visible native thumbs, and forced colors retains system accessibility colors. Tracks stay transparent. Only color changes, so hover never changes viewport -width, overflow, or scrollbar gutters. +width, overflow, or scrollbar gutters. `DesignSystemProvider`, `ThemeRoot`, and +standalone `ScrollArea` share one document focus subscription. It reads native +`:focus-visible` after input/focus changes; streaming and scrolling do not write +focus state. This avoids applying `:has()` to every descendant of the theme root. +CSS-only consumers without these React owners keep `:focus-within` viewports +visible as a conservative keyboard-accessibility fallback. `ScrollArea` keeps `scrollbarVisibility="auto"` as the default. `always` keeps the thumb visible and reserves a scrolling track; `hidden` deliberately hides diff --git a/design-system/packages/ui/src/components/ScrollArea/ScrollArea.tsx b/design-system/packages/ui/src/components/ScrollArea/ScrollArea.tsx index f0c2db3925..d8a84d4fbd 100644 --- a/design-system/packages/ui/src/components/ScrollArea/ScrollArea.tsx +++ b/design-system/packages/ui/src/components/ScrollArea/ScrollArea.tsx @@ -1,5 +1,6 @@ import { forwardRef, useCallback, useEffect, useRef, type HTMLAttributes } from "react"; import { classNames } from "../../internal/classNames"; +import { retainScrollbarFocus } from "../../internal/scrollbarFocus"; import styles from "./ScrollArea.module.css"; export type ScrollAreaOrientation = "vertical" | "horizontal" | "both"; @@ -31,6 +32,9 @@ export const ScrollArea = forwardRef( ...props }, ref) { const viewportRef = useRef(null); + useEffect(() => { + if (viewportRef.current) return retainScrollbarFocus(viewportRef.current.ownerDocument); + }, []); const setViewportRef = useCallback((viewport: HTMLDivElement | null) => { viewportRef.current = viewport; if (typeof ref === "function") ref(viewport); diff --git a/design-system/packages/ui/src/internal/scrollbarFocus.ts b/design-system/packages/ui/src/internal/scrollbarFocus.ts new file mode 100644 index 0000000000..5832c9fbb2 --- /dev/null +++ b/design-system/packages/ui/src/internal/scrollbarFocus.ts @@ -0,0 +1,49 @@ +const ATTRIBUTE = "data-openbitfun-focus-visible"; +const documents = new WeakMap void }>(); + +/** Share the browser's focus-visible state without a :has() on every DOM node. */ +export function retainScrollbarFocus(ownerDocument: Document): () => void { + let state = documents.get(ownerDocument); + if (!state) { + const root = ownerDocument.documentElement; + const view = ownerDocument.defaultView; + const previous = root.getAttribute(ATTRIBUTE); + let frame: number | undefined; + const update = () => { + frame = undefined; + let active = ownerDocument.activeElement; + while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; + const value = String(!!active?.matches(":focus-visible")); + if (root.getAttribute(ATTRIBUTE) !== value) root.setAttribute(ATTRIBUTE, value); + }; + const schedule = () => { + if (frame === undefined && view) frame = view.requestAnimationFrame(update); + }; + // Focus can change without input; keyboard/pointer modality can change + // without moving focus. Read after the browser updates its pseudo-state. + const events = ["focusin", "focusout", "keydown", "keyup", "pointerdown", "pointerup"]; + for (const event of events) ownerDocument.addEventListener(event, schedule, true); + view?.addEventListener("focus", schedule); + view?.addEventListener("blur", schedule); + update(); + state = { count: 0, dispose: () => { + if (frame !== undefined) view?.cancelAnimationFrame(frame); + for (const event of events) ownerDocument.removeEventListener(event, schedule, true); + view?.removeEventListener("focus", schedule); + view?.removeEventListener("blur", schedule); + if (previous === null) root.removeAttribute(ATTRIBUTE); + else root.setAttribute(ATTRIBUTE, previous); + } }; + documents.set(ownerDocument, state); + } + state.count++; + let released = false; + return () => { + if (released) return; + released = true; + if (--state.count === 0) { + state.dispose(); + documents.delete(ownerDocument); + } + }; +} diff --git a/design-system/packages/ui/src/primitives/ThemeRoot/ThemeRoot.tsx b/design-system/packages/ui/src/primitives/ThemeRoot/ThemeRoot.tsx index 0d6b7297fd..0991777401 100644 --- a/design-system/packages/ui/src/primitives/ThemeRoot/ThemeRoot.tsx +++ b/design-system/packages/ui/src/primitives/ThemeRoot/ThemeRoot.tsx @@ -1,5 +1,6 @@ -import type { CSSProperties, HTMLAttributes, ReactNode } from "react"; +import { useEffect, useRef, type CSSProperties, type HTMLAttributes, type ReactNode } from "react"; import { classNames } from "../../internal/classNames"; +import { retainScrollbarFocus } from "../../internal/scrollbarFocus"; import styles from "./ThemeRoot.module.css"; export type ColorScheme = "light" | "dark"; @@ -28,6 +29,10 @@ export function ThemeRoot({ tokenOverrides, ...props }: ThemeRootProps) { + const rootRef = useRef(null); + useEffect(() => { + if (rootRef.current) return retainScrollbarFocus(rootRef.current.ownerDocument); + }, []); const mergedStyle = { ...style, ...tokenOverrides, @@ -36,6 +41,7 @@ export function ThemeRoot({ return (
ownerDocument && retainScrollbarFocus(ownerDocument), [ownerDocument]); const layerStack = getOverlayLayerStack(ownerDocument); const inheritedTitlePolicy = useContext(ApplicationTitleTooltipsContext); const applicationTitles = inheritedTitlePolicy || nativeTooltipPolicy === "application"; diff --git a/design-system/packages/ui/src/styles/scrollbars.css b/design-system/packages/ui/src/styles/scrollbars.css index deab6f9b8a..17d9cd5d10 100644 --- a/design-system/packages/ui/src/styles/scrollbars.css +++ b/design-system/packages/ui/src/styles/scrollbars.css @@ -49,15 +49,17 @@ * 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, :has(:focus-visible), [data-openbitfun-scrollbar-visibility="always"]))::-webkit-scrollbar-thumb { + :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, :has(:focus-visible), [data-openbitfun-scrollbar-visibility="always"])) { + :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"] *) { scrollbar-color: transparent transparent; } } @@ -66,11 +68,11 @@ /* 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, :has(:focus-visible)) { + [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"] *) { scrollbar-width: none; } - [data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible, :has(:focus-visible))::-webkit-scrollbar { + [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 { display: none; } } diff --git a/src/web-ui/index.html b/src/web-ui/index.html index ac8865cc9c..1430d655f7 100644 --- a/src/web-ui/index.html +++ b/src/web-ui/index.html @@ -181,21 +181,21 @@ /* Keep the mounting shell from showing through or doubling the tint. Preserve layout so startup readiness and measurements still complete. */ - #root:has(+ #openbitfun-startup-overlay:not(.openbitfun-startup-overlay--exiting)) { + #root[data-startup-stage="loading"] { visibility: hidden; } /* The startup mark owns the visible pixels until the handoff completes. */ - #root:has(+ #openbitfun-startup-overlay) [data-startup-logo-target], - #root:has(+ #openbitfun-startup-overlay) [data-startup-reveal] { + #root[data-startup-stage] [data-startup-logo-target], + #root[data-startup-stage] [data-startup-reveal] { opacity: 0; } - #root:has(+ .openbitfun-startup-overlay--exiting) [data-startup-reveal] { + #root:is([data-startup-stage="exiting"], [data-startup-stage="handoff"]) [data-startup-reveal] { animation: openbitfun-startup-content-enter 0.2s ease-out both; } - #root:has(+ .openbitfun-startup-overlay--handoff) [data-startup-reveal] { + #root[data-startup-stage="handoff"] [data-startup-reveal] { animation-duration: 0.24s; animation-delay: 0.18s; } @@ -371,7 +371,7 @@ @media (prefers-reduced-motion: reduce) { #openbitfun-startup-overlay.openbitfun-startup-overlay--exiting, - #root:has(+ .openbitfun-startup-overlay--exiting) [data-startup-reveal] { + #root:is([data-startup-stage="exiting"], [data-startup-stage="handoff"]) [data-startup-reveal] { animation-duration: 0.12s; animation-delay: 0s; } @@ -435,7 +435,7 @@ -
+
{ }); describe('startupOverlay', () => { + it('releases startup state when the overlay has already been removed', async () => { + document.body.innerHTML = '
'; + await hideStartupOverlay(); + expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); + }); + it('removes the existing startup overlay when its exit animation completes', async () => { vi.useFakeTimers(); - document.body.innerHTML = '
'; + document.body.innerHTML = '
'; const hidden = hideStartupOverlay(); const overlay = document.getElementById('openbitfun-startup-overlay'); expect(overlay?.classList.contains('openbitfun-startup-overlay--exiting')).toBe(true); expect(overlay?.getAttribute('aria-hidden')).toBe('true'); + expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('exiting'); overlay?.dispatchEvent(new Event('animationend')); await hidden; expect(isStartupOverlayPresent()).toBe(false); + expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); }); it('releases startup-control focus before hiding the exiting overlay', async () => { @@ -61,7 +69,7 @@ describe('startupOverlay', () => { it('falls back to a timer when the exit animation event is not delivered', async () => { vi.useFakeTimers(); - document.body.innerHTML = '
'; + document.body.innerHTML = '
'; const hidden = hideStartupOverlay(); @@ -72,6 +80,7 @@ describe('startupOverlay', () => { await hidden; expect(isStartupOverlayPresent()).toBe(false); + expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); }); it('tracks elapsed time from the static overlay first paint', () => { @@ -87,7 +96,7 @@ describe('startupOverlay', () => { vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(callback, 16)); vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id)); document.body.innerHTML = ` -
+
OpenBitFun
@@ -120,6 +129,7 @@ describe('startupOverlay', () => { expect(mark.style.width).toBe('119px'); expect(target.isConnected).toBe(true); expect(overlay.classList.contains('openbitfun-startup-overlay--handoff')).toBe(true); + expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('handoff'); expect(animate).toHaveBeenCalledWith([ expect.objectContaining({ transform: 'translate(0px, 0px) scale(1, 1)' }), expect.objectContaining({ transform: `translate(-160px, -40px) scale(${size / 119}, ${size / 119})` }), @@ -147,6 +157,7 @@ describe('startupOverlay', () => { await vi.runAllTimersAsync(); await hidden; expect(isStartupOverlayPresent()).toBe(false); + expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); }); it('restores the static mark if the WebView cannot create the animation', async () => { @@ -167,11 +178,13 @@ describe('startupOverlay', () => { if (reason === 'cancel') reject(); await vi.advanceTimersByTimeAsync(16); expect(overlay.classList.contains('openbitfun-startup-overlay--handoff')).toBe(true); + expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('handoff'); expect(overlay.classList.contains('openbitfun-startup-overlay--interrupted')).toBe(true); expect(animation.cancel).toHaveBeenCalledOnce(); overlay.dispatchEvent(new Event('animationend')); await hidden; expect(isStartupOverlayPresent()).toBe(false); + expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); expect(vi.getTimerCount()).toBe(0); }); @@ -181,6 +194,7 @@ describe('startupOverlay', () => { await vi.advanceTimersByTimeAsync(520); await hidden; expect(isStartupOverlayPresent()).toBe(false); + expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); expect(vi.getTimerCount()).toBe(0); }); @@ -191,6 +205,7 @@ describe('startupOverlay', () => { document.dispatchEvent(new Event('visibilitychange')); await hidden; expect(isStartupOverlayPresent()).toBe(false); + expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); expect(animation.cancel).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0); }); diff --git a/src/web-ui/src/app/startup/startupOverlay.ts b/src/web-ui/src/app/startup/startupOverlay.ts index a4088e5105..3f0c745437 100644 --- a/src/web-ui/src/app/startup/startupOverlay.ts +++ b/src/web-ui/src/app/startup/startupOverlay.ts @@ -110,6 +110,7 @@ function waitForOverlayExitAnimation(overlay: HTMLElement, handoff: LogoHandoff if (frame !== undefined) window.cancelAnimationFrame(frame); // Remove first so cancelling a filled animation cannot flash its origin. overlay.remove(); + document.getElementById('root')?.removeAttribute('data-startup-stage'); activeHandoff?.animation.cancel(); resolve(); } @@ -170,6 +171,7 @@ function waitForOverlayExitAnimation(overlay: HTMLElement, handoff: LogoHandoff export function hideStartupOverlay(): Promise { const overlay = getOverlay(); if (!overlay) { + document.getElementById('root')?.removeAttribute('data-startup-stage'); return Promise.resolve(); } @@ -183,6 +185,9 @@ export function hideStartupOverlay(): Promise { }); pendingExits.set(overlay, exited); overlay.classList.add(EXIT_CLASS); + // Startup owns this state directly; a root :has() would invalidate unrelated + // transcript descendants whenever virtualized or streaming DOM changes. + document.getElementById('root')?.setAttribute('data-startup-stage', handoff ? 'handoff' : 'exiting'); // Static startup window controls can still own focus when the React shell // becomes ready. Release that focus before hiding the overlay from the // accessibility tree, then make the exiting surface non-interactive so it diff --git a/src/web-ui/src/app/startup/startupPerformanceContract.test.ts b/src/web-ui/src/app/startup/startupPerformanceContract.test.ts index 518ae74dfa..09e0d744c9 100644 --- a/src/web-ui/src/app/startup/startupPerformanceContract.test.ts +++ b/src/web-ui/src/app/startup/startupPerformanceContract.test.ts @@ -9,6 +9,12 @@ function readSource(relativePath: string): string { return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8').replace(/\r\n?/g, '\n'); } +it('does not make the app root a relational selector subject after startup', () => { + const html = readSource('../../../index.html'); + expect(html).not.toContain('#root:has('); + expect(html).toContain('id="root" data-startup-stage="loading"'); +}); + function dynamicImportSpecifiers(source: string): string[] { return Array.from( source.matchAll(/import\(\s*(['"])(.*?)\1\s*\)/g), diff --git a/src/web-ui/src/app/startup/startupPreload.test.ts b/src/web-ui/src/app/startup/startupPreload.test.ts index b1d09ef281..908fae294d 100644 --- a/src/web-ui/src/app/startup/startupPreload.test.ts +++ b/src/web-ui/src/app/startup/startupPreload.test.ts @@ -235,6 +235,7 @@ describe('startup preload shell', () => { expect(dom.window.document.body.classList.contains('openbitfun-pet-preload-body')).toBe(true); expect(dom.window.document.getElementById('openbitfun-startup-overlay')).toBeNull(); + expect(dom.window.document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); expect(dom.window.document.querySelector('.openbitfun-pet-preload__sprite')).not.toBeNull(); expect(dom.window.document.querySelector('.splash-screen__logo')).toBeNull(); expect(dom.window.document.querySelector('.openbitfun-sr-only')?.textContent).toBe('Loading companion...'); @@ -259,6 +260,7 @@ describe('startup preload shell', () => { expect(dom.window.document.body.classList.contains('openbitfun-desktop-card-preload-body')).toBe(true); expect(dom.window.document.getElementById('openbitfun-startup-overlay')).toBeNull(); + expect(dom.window.document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false); expect(dom.window.document.querySelector('.openbitfun-pet-preload')).toBeNull(); dom.window.close(); }); diff --git a/src/web-ui/src/app/styles/scrollbar.test.ts b/src/web-ui/src/app/styles/scrollbar.test.ts index 4d326bf00b..19e49d73a5 100644 --- a/src/web-ui/src/app/styles/scrollbar.test.ts +++ b/src/web-ui/src/app/styles/scrollbar.test.ts @@ -37,20 +37,21 @@ describe('shared native scrollbar presentation', () => { expect(interactionRules).toContain('(pointer: fine) and (forced-colors: none)'); expect(interactionRules).toContain( - ':not(:hover, :focus-visible, :has(:focus-visible), [data-openbitfun-scrollbar-visibility="always"])', + ':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, :has\(:focus-visible\)\)\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"\], :root\[data-openbitfun-focus-visible="false"\] \*\)\s*\{\s*scrollbar-width:\s*none;/, ); expect(hoverRules).toMatch( - /\[data-openbitfun-scrollbar-visibility="hover"\]:not\(:hover, :focus-visible, :has\(:focus-visible\)\)::-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"\], :root\[data-openbitfun-focus-visible="false"\] \*\)::-webkit-scrollbar\s*\{\s*display:\s*none;/, ); expect(hoverRules).not.toMatch(/(?:overflow(?:-[xy])?|scrollbar-gutter)\s*:/); - expect(stylesheet).not.toMatch(/\.is-scrolling|:focus-within|!important/); + expect(stylesheet).not.toMatch(/\.is-scrolling|:has\(|!important/); }); it('guards standard width and color together so Safari 18 keeps the WebKit path', () => { diff --git a/src/web-ui/src/app/styles/scrollbarFocus.test.ts b/src/web-ui/src/app/styles/scrollbarFocus.test.ts new file mode 100644 index 0000000000..6ef60371d4 --- /dev/null +++ b/src/web-ui/src/app/styles/scrollbarFocus.test.ts @@ -0,0 +1,73 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { retainScrollbarFocus } from '../../../../../design-system/packages/ui/src/internal/scrollbarFocus'; + +const attribute = 'data-openbitfun-focus-visible'; +const releases: Array<() => void> = []; +beforeEach(() => { + vi.useFakeTimers(); + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => window.setTimeout(() => callback(0), 16)); + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => window.clearTimeout(id)); +}); +afterEach(() => { + releases.splice(0).forEach(release => release()); + document.body.innerHTML = ''; + document.documentElement.removeAttribute(attribute); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +it('tracks native focus visibility without moving focus or reacting to streamed DOM', () => { + const button = document.createElement('button'); + document.body.append(button); + button.focus(); + let visible = false; + vi.spyOn(button, 'matches').mockImplementation(selector => selector === ':focus-visible' && visible); + releases.push(retainScrollbarFocus(document)); + const writes = vi.spyOn(document.documentElement, 'setAttribute'); + expect(document.documentElement.getAttribute(attribute)).toBe('false'); + visible = true; + button.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', bubbles: true })); + vi.advanceTimersByTime(16); + expect(document.documentElement.getAttribute(attribute)).toBe('true'); + expect(document.activeElement).toBe(button); + expect(writes).toHaveBeenCalledTimes(1); + + document.body.append(document.createTextNode('New streamed text')); + document.dispatchEvent(new Event('scroll')); + button.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true })); + vi.advanceTimersByTime(16); + expect(writes).toHaveBeenCalledTimes(1); + visible = false; + button.dispatchEvent(new Event('pointerdown', { bubbles: true })); + vi.advanceTimersByTime(16); + expect(document.documentElement.getAttribute(attribute)).toBe('false'); +}); + +it('shares listeners across owners and cancels pending work on final release', () => { + const added = vi.spyOn(document, 'addEventListener'); + const removed = vi.spyOn(document, 'removeEventListener'); + document.documentElement.setAttribute(attribute, 'previous'); + const first = retainScrollbarFocus(document), second = retainScrollbarFocus(document); + releases.push(first, second); + expect(added.mock.calls.filter(([name]) => name === 'focusin')).toHaveLength(1); + first(); first(); + expect(removed).not.toHaveBeenCalled(); + document.dispatchEvent(new Event('focusin')); + expect(vi.getTimerCount()).toBe(1); + second(); + expect(vi.getTimerCount()).toBe(0); + expect(removed.mock.calls.filter(([name]) => name === 'focusin')).toHaveLength(1); + expect(document.documentElement.getAttribute(attribute)).toBe('previous'); +}); + +it('reads the focused descendant of an open shadow root', () => { + const host = document.createElement('div'); + const shadow = host.attachShadow({ mode: 'open' }); + const input = document.createElement('input'); + shadow.append(input); document.body.append(host); input.focus(); + vi.spyOn(input, 'matches').mockReturnValue(true); + releases.push(retainScrollbarFocus(document)); + expect(document.activeElement).toBe(host); + expect(document.documentElement.getAttribute(attribute)).toBe('true'); +}); diff --git a/tests/e2e/AGENTS-CN.md b/tests/e2e/AGENTS-CN.md index bc40d14640..8a258670db 100644 --- a/tests/e2e/AGENTS-CN.md +++ b/tests/e2e/AGENTS-CN.md @@ -48,6 +48,14 @@ Read、Edit、Write、ExecCommand 各 25 次;上述契约测试同时验证生 保留失败证据,仅比较负载与桌面构建类型相同的结果,测量时不要并行构建。 RAF 不等于合成帧率;此测试只覆盖本地桌面,不覆盖四种远程场景。 +验证主会话与 BTW 同时流式、分别滚动时,运行 +`node tests/e2e/scripts/run-long-session-performance.mjs --suite btw-scroll --scenario multi-tool --repeats 2`。 +用例从 200 轮、每轮 100 次工具调用的主会话通过真实 `/btw` 创建临时侧会话, +两路响应均预填 512 段文本,再测试主会话流式区、历史区和 BTW 流式区的双向滚动。 +侧会话是新建临时会话,并非另一份持久化的 200 轮历史。每个阶段要求两路输出均推进, +后续输出保持阅读锚点,两栏 DOM 窗口有界,返回最新能够看到最后一段文本。 +普通验收运行与 CDP 诊断运行分开比较。 + 验证内置 WebDriver 的滚动、聚焦与外层布局时,先构建 Desktop 和当前前端资源,再运行: ```bash diff --git a/tests/e2e/AGENTS.md b/tests/e2e/AGENTS.md index 2467de7c7f..da57fbfa5d 100644 --- a/tests/e2e/AGENTS.md +++ b/tests/e2e/AGENTS.md @@ -52,6 +52,16 @@ Keep failed evidence; compare matching workloads/native profiles and avoid concurrent builds. RAF is not compositor FPS. This is local desktop coverage; none of the four remote scenarios is exercised. +For concurrent primary/BTW streaming and scrolling, use +`node tests/e2e/scripts/run-long-session-performance.mjs --suite btw-scroll --scenario multi-tool --repeats 2`. +It opens a real `/btw` child from a 200-turn, 100-tool-calls-per-turn parent, +seeds both live responses with 512 paragraphs, then measures both directions +in primary live/history content and the BTW live transcript. The child is a new +transient conversation, not a second persisted 200-turn fixture. Both streams +must advance during each phase; subsequent output must preserve a reading +anchor, both DOM windows stay bounded, and return-to-latest must reach the +final paragraph. Keep ordinary acceptance runs separate from CDP diagnostics. + For historical FlowChat scroll continuity, build Desktop and current frontend assets, then run: diff --git a/tests/e2e/README.md b/tests/e2e/README.md index a4b56500f5..1dff7bdca7 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -34,6 +34,23 @@ pnpm --dir tests/e2e test ## Long-session performance +The concurrent BTW workload is available with +`node tests/e2e/scripts/run-long-session-performance.mjs --suite btw-scroll --scenario multi-tool --repeats 2`. +The parent retains the complete 200-turn / 100-tools-per-turn template. A real +`/btw` submission creates a transient child, and both real runtime streams use +the private SSE model. Each starts with 512 Markdown paragraphs; every measured +phase delivers 192 more to each stream at 90 ms intervals. The six phases scroll +up/down through the primary live output, primary tool-heavy history, and child +live output. Wheel steps, batch size, viewport, frontend/native hashes and raw +RAF intervals are retained with the result. Sidebar activation includes the +pointerdown sequence required by the production sidebar. This is embedded +WebDriver wheel delivery, not OS trackpad inertia or compositor FPS. The child +has no historical tool-call fixture. Runs assert fresh concurrent streams, +reading stability during subsequent output, bounded DOM residency in both panes, +and visibility of the final paragraph after returning to latest. Use the same +protocol and native binary for baseline/candidate comparisons; profiling changes +timing and must remain separate. No remote scenario is exercised. + Build the desktop host and production frontend, then run from the repository root: ```powershell diff --git a/tests/e2e/README.zh-CN.md b/tests/e2e/README.zh-CN.md index 0e0612428e..f4ac0c7a88 100644 --- a/tests/e2e/README.zh-CN.md +++ b/tests/e2e/README.zh-CN.md @@ -4,6 +4,16 @@ ## 桌面长会话性能 +双会话流式滚动用例: +`node tests/e2e/scripts/run-long-session-performance.mjs --suite btw-scroll --scenario multi-tool --repeats 2`。 +主会话使用完整的 200 轮、每轮 100 次工具调用模板,通过真实 `/btw` 输入创建临时侧会话。 +两路真实 Agent 运行时连接本地 SSE 模型,各预填 512 段 Markdown;每个计时阶段再各发送 +192 段,默认间隔 90ms。分别测主会话流式区、历史工具区和 BTW 流式区的上下滚动。 +侧会话没有另一份历史工具调用模板。测试断言两路输出持续推进、后续输出不抢占阅读位置、 +两栏 DOM 窗口有界,并验证返回最新后能看到最后一段。每次运行保留原始 RAF 时间、流式计数、 +前端和二进制哈希。比较时保持协议、窗口和二进制一致;带 CDP 采样的运行只用于诊断。 +这是本地桌面的内置 WebDriver 滚轮输入,不是 OS 触控板惯性或合成器 FPS,也不覆盖远程场景。 + 在仓库根目录构建桌面端和生产前端后运行: ```powershell diff --git a/tests/e2e/page-objects/LongSessionPerformancePage.ts b/tests/e2e/page-objects/LongSessionPerformancePage.ts index 1e44f1ba6a..98d263baa4 100644 --- a/tests/e2e/page-objects/LongSessionPerformancePage.ts +++ b/tests/e2e/page-objects/LongSessionPerformancePage.ts @@ -15,7 +15,7 @@ export interface LongSessionProbe { longTasks: Array<{ startTime: number; durationMs: number }> }; scrollPositions?: Array<{ time: number; top: number }>; } -interface ProbeOptions { sessionId: string; turnId?: string; selector?: string; wheelCount?: number; collectRows?: boolean; collectMilestones?: boolean; +interface ProbeOptions { sessionId: string; scrollerSelector?: string; turnId?: string; selector?: string; wheelCount?: number; collectRows?: boolean; collectMilestones?: boolean; postReadyMs?: number; checkAnchor?: boolean; } type ProbeHost = Window & { __longSessionProbe?: { result: Partial; done: boolean; dispose: () => void; @@ -23,6 +23,48 @@ type ProbeHost = Window & { __longSessionProbe?: { /** Measures the production transcript; no Vite imports or product store mutations. */ export class LongSessionPerformancePage extends FlowChatScrollPage { + async activateSession(id: string) { + await $(this.sessionSelector(id)).scrollIntoView(); + // The embedded click endpoint emits MouseEvent only; sidebar activation starts at pointerdown. + await browser.execute((selector: string) => { + const node = document.querySelector(selector)!; + const rect = node.getBoundingClientRect(); + const init = { bubbles: true, cancelable: true, clientX: rect.left + rect.width / 2, + clientY: rect.top + rect.height / 2, button: 0 }; + node.dispatchEvent(new PointerEvent('pointerdown', { ...init, pointerId: 1, pointerType: 'mouse', isPrimary: true, buttons: 1 })); + node.dispatchEvent(new MouseEvent('mousedown', { ...init, buttons: 1 })); + node.dispatchEvent(new PointerEvent('pointerup', { ...init, pointerId: 1, pointerType: 'mouse', isPrimary: true })); + node.dispatchEvent(new MouseEvent('mouseup', init)); node.click(); + }, this.sessionSelector(id)); + await browser.waitUntil(() => browser.execute((id: string) => { + const root = document.querySelector(`[data-testid="flowchat-container"][data-session-id="${id}"]`); + return !!root?.querySelector('[data-open-viewport-settled="true"]') + && !root.querySelector('.history-session-loading:not([data-history-loading-phase="idle"])'); + }, id), { timeout: 30_000, interval: 100 }); + } + + async wheelPane(selector: string, delta: number, count: number) { + const position = await browser.execute((selector: string) => { + const rect = document.querySelector(selector)!.getBoundingClientRect(); + return { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 3) }; + }, selector); + await browser.performActions([{ type: 'wheel', id: 'btw-wheel', actions: Array.from({ length: count }, () => ({ + type: 'scroll', origin: 'viewport', ...position, deltaX: 0, deltaY: delta, duration: 24, + })) }]); + await browser.releaseActions(); + } + + async paneAnchor(selector: string) { + return browser.execute((selector: string) => { + const scroll = document.querySelector(selector)!; + const top = scroll.getBoundingClientRect().top; + const row = [...scroll.querySelectorAll('.virtual-item-wrapper')].find(row => { + const rect = row.getBoundingClientRect(); return rect.bottom > top && rect.top < top + scroll.clientHeight && rect.height > 0; + }); + return { key: row?.dataset.virtualItemKey, offset: row ? row.getBoundingClientRect().top - top : 0 }; + }, selector); + } + async returnToLatest(sessionId: string, paragraph: number) { const selector = '[data-openbitfun-product-component="scroll-to-latest-bar"][data-openbitfun-product-part="root"][data-visible="true"]'; if (await $(selector).isExisting()) await $(selector).click(); @@ -77,7 +119,7 @@ export class LongSessionPerformancePage extends FlowChatScrollPage { }; const taskObserver = result.longTasksSupported ? new PerformanceObserver(list => recordTasks(list.getEntries())) : undefined; taskObserver?.observe({ type: 'longtask' }); - const scroller = () => document.querySelector(`[data-testid="flowchat-container"][data-session-id="${options.sessionId}"] [data-flowchat-scroller]`); + const scroller = () => document.querySelector(options.scrollerSelector ?? `[data-testid="flowchat-container"][data-session-id="${options.sessionId}"] [data-flowchat-scroller]`); let rowObserver: MutationObserver | undefined; if (options.collectRows) { result.rowChurn = { added: {}, removed: {} }; result.rowBatches = []; result.scrollPositions = []; @@ -104,7 +146,7 @@ export class LongSessionPerformancePage extends FlowChatScrollPage { const changed = () => { result.visibilityChanged ||= document.visibilityState !== result.visibility; result.focusChanged ||= document.hasFocus() !== result.focus; }; const input = (event: Event) => { if (!(event.target instanceof Element)) return; - const match = options.wheelCount ? event.type === 'wheel' && event.target.closest('[data-flowchat-scroller]') + const match = options.wheelCount ? event.type === 'wheel' && scroller()?.contains(event.target) : options.selector && event.target.closest(options.selector); if (!match) return; if (result.actionAt === undefined) { result.actionAt = performance.now(); result.inputType = event.type; result.beforeTop = scroller()?.scrollTop ?? 0; } @@ -211,8 +253,9 @@ export class LongSessionPerformancePage extends FlowChatScrollPage { async snapshot(id: string) { return browser.execute((id: string) => { - const root = document.querySelector(`[data-testid="flowchat-container"][data-session-id="${id}"]`); - const scroll = root?.querySelector('[data-flowchat-scroller]'); + const root = document.querySelector(`[data-testid="flowchat-container"][data-session-id="${id}"]`) + ?? document.querySelector(`[data-flowchat-selection-root="${id}"].btw-session-panel__body`); + const scroll = root?.matches('.btw-session-panel__body') ? root as HTMLElement : root?.querySelector('[data-flowchat-scroller]'); return { sessionId: id, exists: !!root, scrollTop: scroll?.scrollTop, scrollHeight: scroll?.scrollHeight, clientHeight: scroll?.clientHeight, rows: root?.querySelectorAll('.virtual-item-wrapper').length, clientWidth: scroll?.clientWidth, domNodes: root?.querySelectorAll('*').length, documentNodes: document.querySelectorAll('*').length, diff --git a/tests/e2e/scripts/long-session-metrics.mjs b/tests/e2e/scripts/long-session-metrics.mjs index cecf729341..b8285f83db 100644 --- a/tests/e2e/scripts/long-session-metrics.mjs +++ b/tests/e2e/scripts/long-session-metrics.mjs @@ -67,7 +67,7 @@ export function renderReport(report) { const html = `Long session performance

Desktop long session performance

Functional: ${escape(report.functionalPassed)} · Budgets: ${escape(report.performanceBudgetsPassed)} · Instrumented: ${escape(report.instrumented ?? false)} · ${escape(report.environment.platform)} · ${escape(report.nativeProfile)}

-First-open means first UI entry in this process, not a cold disk or OS-cache measurement. Streaming sessions are restored in the runtime before first UI entry. RAF FPS measures presentation opportunities, not compositor completion. Scroll latency is first wheel to first observed movement; other latency is input to target readiness plus two RAF opportunities. Short action frame distributions have few samples; inspect raw data. ${report.protocol.suite === 'streaming-switch' ? 'Streaming-switch uses equal controlled output batches; readiness waits between batches are outside timed windows.' : 'Static runs precede streaming runs.'} +First-open means first UI entry in this process, not a cold disk or OS-cache measurement. Streaming sessions are restored in the runtime before first UI entry. RAF FPS measures presentation opportunities, not compositor completion. Scroll latency is first wheel to first observed movement; other latency is input to target readiness plus two RAF opportunities. Short action frame distributions have few samples; inspect raw data. ${report.protocol.suite === 'btw-scroll' ? 'Primary and BTW panes stream concurrently in equal controlled output batches; preparation and reader checks are outside timed windows.' : report.protocol.suite === 'streaming-switch' ? 'Streaming-switch uses equal controlled output batches; readiness waits between batches are outside timed windows.' : 'Static runs precede streaming runs.'} ${columns.map(column => ``).join('')}${rows.map(row => `${row.map(cell => ``).join('')}`).join('')}
${escape(column)}
${format(cell)}

Failures

${escape(JSON.stringify(report.failures, null, 2))}

Protocol

${escape(JSON.stringify(report.protocol, null, 2))}
See result.json for raw frame timestamps, stream counters, environment and hashes. Remote workspace, remote control, Peer Device Mode and Detached Dispatch were not exercised.`; return { csv, html }; diff --git a/tests/e2e/scripts/run-long-session-performance.mjs b/tests/e2e/scripts/run-long-session-performance.mjs index ca401a7e64..05b4f21440 100644 --- a/tests/e2e/scripts/run-long-session-performance.mjs +++ b/tests/e2e/scripts/run-long-session-performance.mjs @@ -42,7 +42,7 @@ for (const [key, value] of Object.entries(options)) { if (!(budget ? Number.isFinite(value) : Number.isInteger(value)) || value < (key === 'toolItems' ? 0 : budget ? Number.MIN_VALUE : 1)) throw new Error(`Invalid ${key}`); } if (options.turns < 8 || options.paragraphChars < 32) throw new Error('Need at least 8 turns and 32 paragraph characters'); -if (!['matrix', 'first-open', 'streaming-switch', 'streaming-scroll', 'streaming-jump'].includes(options.suite)) throw new Error('Unknown performance suite'); +if (!['matrix', 'first-open', 'streaming-switch', 'streaming-scroll', 'streaming-jump', 'btw-scroll'].includes(options.suite)) throw new Error('Unknown performance suite'); if (!['all', 'live', 'history'].includes(options.scrollArea)) throw new Error('Unknown scroll area'); const nativeProfile = process.env.OPENBITFUN_E2E_NATIVE_PROFILE || 'debug'; if (!['debug', 'release-fast'].includes(nativeProfile)) throw new Error('Use a debug or release-fast devtools build'); @@ -92,6 +92,15 @@ if (options.suite === 'streaming-jump') Object.assign(report.protocol, { readiness: 'visible requested-turn content; user-message landing is recorded separately', landingValidation: 'user-message visible at readiness and stable after continued output', }); +if (options.suite === 'btw-scroll') Object.assign(report.protocol, { + version: 2, states: ['streaming'], staticBeforeStreaming: false, + scenarios: ['continuous-scroll-main-live-up', 'continuous-scroll-main-live-down', + 'continuous-scroll-main-history-up', 'continuous-scroll-main-history-down', + 'continuous-scroll-btw-live-up', 'continuous-scroll-btw-live-down'], + initialParagraphs: 512, seedIntervalMs: 2, paragraphsPerScroll: 192, controlledStreams: true, + childHistory: 'New transient session opened through /btw; seeded with 512 live paragraphs', + postMeasurementReaderChecks: true, completionChecks: 'Both panes render the model completion marker', +}); if (options.scenario === MULTI_TOOL_TEMPLATE.id) report.protocol.template = MULTI_TOOL_TEMPLATE; const save = async (data = report) => { const rendered = renderReport(data); @@ -124,9 +133,9 @@ try { report.sourceCommit = (await exec('git', ['rev-parse', 'HEAD'], { cwd: repo, windowsHide: true })).stdout.trim(); report.sourceDirty = Boolean((await exec('git', ['status', '--porcelain'], { cwd: repo, windowsHide: true })).stdout.trim()); const fixtures = []; - for (const prefix of ['perf-static', 'perf-live', 'perf-parking']) { + for (const prefix of options.suite === 'btw-scroll' ? ['perf-live', 'perf-parking'] : ['perf-static', 'perf-live', 'perf-parking']) { const isParking = prefix === 'perf-parking'; - const count = isParking ? 1 : options.suite === 'first-open' ? options.repeats : 2; + const count = isParking || options.suite === 'btw-scroll' ? 1 : options.suite === 'first-open' ? options.repeats : 2; const turns = isParking ? 1 : options.turns; const parking = isParking && options.scenario === MULTI_TOOL_TEMPLATE.id; const result = await exec(process.execPath, [path.join(repo, 'tests/e2e/scripts/generate-long-session-fixture.mjs'), diff --git a/tests/e2e/specs/performance/long-session-performance.spec.ts b/tests/e2e/specs/performance/long-session-performance.spec.ts index 802f22098c..70c4c7379c 100644 --- a/tests/e2e/specs/performance/long-session-performance.spec.ts +++ b/tests/e2e/specs/performance/long-session-performance.spec.ts @@ -15,7 +15,8 @@ const switchOnly = protocol.suite === 'streaming-switch'; const scrollOnly = protocol.suite === 'streaming-scroll'; const jumpOnly = protocol.suite === 'streaming-jump'; const openOnly = protocol.suite === 'first-open'; -const controlled = switchOnly || scrollOnly || jumpOnly || openOnly; +const btwOnly = protocol.suite === 'btw-scroll'; +const controlled = switchOnly || scrollOnly || jumpOnly || openOnly || btwOnly; const page = new LongSessionPerformancePage(); let model: Awaited>; let workspaceId: string; @@ -29,14 +30,14 @@ const save = () => { writeFileSync(join(evidence, 'summary.csv'), csv); writeFileSync(join(evidence, 'report.html'), html); }; -async function sample(state: string, scenario: string, sessionId: string, action: () => Promise) { +async function sample(state: string, scenario: string, sessionId: string, action: () => Promise, streamMarker = sessionId) { const row: Record = { state, scenario, sessionId, index: report.samples.length, valid: false }; report.samples.push(row); save(); try { // Restoring a large runtime history can outlast startup notifications or user focus changes. // Establish the required starting condition outside the timed window; changes during it still fail. await page.focusMainWindow(); - row.streamBefore = state === 'streaming' ? model.snapshot(sessionId) : null; + row.streamBefore = state === 'streaming' ? model.snapshot(streamMarker) : null; row.before = await page.snapshot(sessionId); await action(); const probe = row.probe = await page.collect(); @@ -49,7 +50,7 @@ async function sample(state: string, scenario: string, sessionId: string, action } row.frames = frameMetrics(probe.times, probe.actionAt, probe.endAt); row.after = await page.snapshot(sessionId); - row.streamAfter = state === 'streaming' ? model.snapshot(sessionId) : null; + row.streamAfter = state === 'streaming' ? model.snapshot(streamMarker) : null; assert.equal(probe.timedOut, false, 'Target never became usable'); assert.equal(probe.visibility, 'visible', 'Hidden WebView cannot establish visible-window performance'); assert.equal(probe.visibilityChanged, false, 'Visibility changed during measurement'); @@ -96,7 +97,7 @@ async function openMeasured(state: string, scenario: string, id: string) { async function startSwitchProfile() { const port = process.env.OPENBITFUN_LONG_SESSION_CDP_PORT; if (!port) return async () => {}; - const profileName = openOnly ? `open-${report.samples.length}` : scrollOnly ? `scroll-${report.samples.length}` : jumpOnly ? `jump-${report.samples.length}` : 'switch'; + const profileName = openOnly ? `open-${report.samples.length}` : scrollOnly || btwOnly ? `scroll-${report.samples.length}` : jumpOnly ? `jump-${report.samples.length}` : 'switch'; const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json() as Array<{ type: string; url: string; webSocketDebuggerUrl: string }>; const target = targets.find(value => value.type === 'page' && value.url.includes('index.html') && !value.url.includes('openbitfunWindow=')); assert.ok(target, 'Main WebView CDP target missing'); @@ -179,9 +180,11 @@ describe('Desktop long-session performance matrix', () => { save(); }); - afterEach(function () { + afterEach(async function () { if (this.currentTest?.state === 'failed') { report.failures.push(this.currentTest.err?.stack || this.currentTest.title); save(); + await browser.saveScreenshot(join(evidence, 'failure.png')).catch(() => undefined); + writeFileSync(join(evidence, 'failure-dom.txt'), await browser.execute(() => document.body.innerText).catch(String)); } }); @@ -190,7 +193,7 @@ describe('Desktop long-session performance matrix', () => { await page.cancelMeasurement(); report.modelErrors = model?.errors ?? []; if (report.modelErrors.length) report.failures.push(...report.modelErrors); - report.contentReadyChecksPassed = report.failures.length === 0 && report.samples.length === (openOnly ? 2 * protocol.sessionsPerState : scrollOnly ? 2 * protocol.scrollAreas.length * protocol.repeats : switchOnly || jumpOnly ? protocol.repeats : 2 * (2 + protocol.repeats + 2 + protocol.repeats)) + report.contentReadyChecksPassed = report.failures.length === 0 && report.samples.length === (btwOnly ? 6 * protocol.repeats : openOnly ? 2 * protocol.sessionsPerState : scrollOnly ? 2 * protocol.scrollAreas.length * protocol.repeats : switchOnly || jumpOnly ? protocol.repeats : 2 * (2 + protocol.repeats + 2 + protocol.repeats)) && report.samples.every((row: { valid: boolean }) => row.valid); report.functionalPassed = report.contentReadyChecksPassed && (!jumpOnly || report.jumpLandingChecksPassed === true); const budgets = report.samples.filter((row: { valid: boolean }) => row.valid).map((row: any) => ({ index: row.index, @@ -204,7 +207,99 @@ describe('Desktop long-session performance matrix', () => { } finally { await model?.close(); } }); - for (const state of controlled && !openOnly ? ['streaming'] : ['static', 'streaming']) { + if (btwOnly) it('scrolls both panes while the parent and a real BTW session stream', async () => { + const mainId = 'perf-live-000', childMarker = 'perf-btw'; + await page.invoke('restore_session_with_turns', { sessionId: mainId, workspaceId, workspacePath: workspace }); + await page.prepareSession(mainId); + await page.activateSession(mainId); + await page.enterDraft(`/btw LONG_SESSION_STREAM:${childMarker}`); + assert.ok((await page.draftText()).includes(`LONG_SESSION_STREAM:${childMarker}`), 'BTW draft was not entered'); + await $('[data-testid="chat-input-send-btn"]').click(); + await $('.btw-session-panel__body').waitForDisplayed({ timeout: 30_000 }); + const childId = await $('.btw-session-panel__body').getAttribute('data-flowchat-selection-root'); + assert.ok(childId); + await browser.waitUntil(() => !!model.snapshot(childMarker)?.connected, { timeout: 60_000, interval: 100 }); + await page.invoke('start_dialog_turn', { sessionId: mainId, workspaceId, workspacePath: workspace, + agentType: 'agentic', turnId: tail('streaming', mainId), userInput: `LONG_SESSION_STREAM:${mainId}` }); + const markers = [mainId, childMarker]; + await browser.waitUntil(() => !!model.snapshot(mainId)?.connected, { timeout: 60_000, interval: 100 }); + for (const id of markers) model.release(id, protocol.initialParagraphs, protocol.seedIntervalMs); + await browser.waitUntil(() => markers.every(id => model.snapshot(id)?.emitted === protocol.initialParagraphs), { timeout: 30_000, interval: 100 }); + const main = `[data-testid="flowchat-container"][data-session-id="${mainId}"] [data-flowchat-scroller]`; + const child = `.btw-session-panel__body[data-flowchat-selection-root="${childId}"]`; + report.btw = { mainId, childId, childMarker }; + const latest = async (selector: string, id: string, marker: string, count: number) => { + const button = selector === main + ? '[data-openbitfun-product-component="scroll-to-latest-bar"][data-openbitfun-product-part="root"][data-visible="true"]' + : '.btw-session-panel__scroll-to-bottom[data-visible="true"]'; + if (await $(button).isDisplayed().catch(() => false)) await $(button).click(); + await browser.waitUntil(() => browser.execute((selector: string, text: string) => { + const scroll = document.querySelector(selector)!; + const bounds = scroll.getBoundingClientRect(); + return [...scroll.querySelectorAll('.virtual-item-wrapper')].some(row => { + const rect = row.getBoundingClientRect(); + return rect.bottom > bounds.top && rect.top < bounds.bottom && row.textContent?.includes(text); + }); + }, selector, `Live ${marker} paragraph ${count - 1}:`), { timeout: 30_000, interval: 100, timeoutMsg: `Latest paragraph missing in ${id}` }); + await page.settle(); + }; + for (let cycle = 0; cycle < protocol.repeats; cycle++) { + for (const area of ['main-live', 'main-history', 'btw-live']) for (const direction of [-1, 1]) { + const expected = protocol.initialParagraphs + report.samples.length * protocol.paragraphsPerScroll; + for (const marker of markers) assert.equal(model.snapshot(marker)?.emitted, expected); + await latest(main, mainId, mainId, expected); await latest(child, childId, childMarker, expected); + const selector = area === 'btw-live' ? child : main; + if (area === 'main-history') await jump('streaming', mainId, protocol.turns, tail('streaming', mainId), false); + if (direction > 0) await page.wheelPane(selector, -protocol.wheelDelta, protocol.scrollSteps); + await page.settle(); + const beforeStreams = markers.map(id => model.snapshot(id)); + const stopProfile = await startSwitchProfile(); + try { + const sessionId = area === 'btw-live' ? childId : mainId; + await sample('streaming', `continuous-scroll-${area}-${direction < 0 ? 'up' : 'down'}`, sessionId, async () => { + await page.arm({ sessionId, scrollerSelector: selector, wheelCount: protocol.scrollSteps }); + for (const marker of markers) model.release(marker, protocol.paragraphsPerScroll); + await page.wheelPane(selector, direction * protocol.wheelDelta, protocol.scrollSteps); + }, area === 'btw-live' ? childMarker : mainId); + } finally { await stopProfile(); } + const afterStreams = markers.map(id => model.snapshot(id)); + afterStreams.forEach((stream, index) => { + assert.ok(stream?.connected && !stream.finished && stream.emitted > beforeStreams[index]!.emitted, 'Both streams must advance during scrolling'); + assert.ok(Date.now() - stream.lastEmittedAt < 500, 'Both streams must remain fresh throughout scrolling'); + }); + await page.settle(); + const reading = await page.paneAnchor(selector); + const distanceFromTail = await browser.execute((selector: string) => { + const scroller = document.querySelector(selector)!; + return scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight; + }, selector); + const heldStreams = markers.map(id => model.snapshot(id)); + heldStreams.forEach(stream => assert.ok(stream!.emitted < expected + protocol.paragraphsPerScroll, + 'Reading-position validation requires further output in both panes')); + await browser.waitUntil(() => markers.every(id => model.snapshot(id)?.emitted === expected + protocol.paragraphsPerScroll), { timeout: 30_000, interval: 100 }); + await page.settle(); + const still = await page.paneAnchor(selector); + assert.ok(reading.key); + if (distanceFromTail > 120) { + assert.equal(still.key, reading.key, 'Streaming changed the reading row'); + assert.ok(Math.abs(still.offset - reading.offset) < 8, 'Streaming displaced the reading position'); + } + const panes = await Promise.all([page.snapshot(mainId), page.snapshot(childId)]); + panes.forEach(pane => assert.ok(pane.exists && pane.rows! > 0 && pane.rows! < 90, 'Both panes must retain bounded transcript DOM')); + Object.assign(report.samples.at(-1), { beforeStreams, afterStreams, heldStreams, distanceFromTail, panes, reading, still }); save(); + } + } + const finalCount = protocol.initialParagraphs + report.samples.length * protocol.paragraphsPerScroll; + await latest(main, mainId, mainId, finalCount); await latest(child, childId, childMarker, finalCount); + await browser.saveScreenshot(join(evidence, 'btw-panes.png')); + for (const marker of markers) model.finish(marker); + await browser.waitUntil(() => browser.execute((selectors: string[], markers: string[]) => selectors.every((selector, index) => + document.querySelector(selector)?.textContent?.includes(`LONG_SESSION_COMPLETE:${markers[index]}`)), [main, child], markers), + { timeout: 30_000, interval: 100, timeoutMsg: 'Both panes must render their completed response' }); + report.btw.completedResponsesVisible = true; + }); + + for (const state of btwOnly ? [] : controlled && !openOnly ? ['streaming'] : ['static', 'streaming']) { it(`measures first entry, switching, continuous scroll and turn jumps while ${state}`, async () => { const sessions = scrollOnly || jumpOnly ? ids(state).slice(0, 1) : ids(state); if (state === 'streaming') {