Skip to content

Commit ed456a2

Browse files
committed
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.
1 parent 05f2b55 commit ed456a2

21 files changed

Lines changed: 403 additions & 38 deletions

‎design-system/packages/ui/README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,12 @@ or contains visible keyboard focus. Leaving the viewport hides it; scrolling
259259
from streaming output does not reveal an unattended panel. Touch surfaces retain
260260
visible native thumbs, and forced colors retains system accessibility colors.
261261
Tracks stay transparent. Only color changes, so hover never changes viewport
262-
width, overflow, or scrollbar gutters.
262+
width, overflow, or scrollbar gutters. `DesignSystemProvider`, `ThemeRoot`, and
263+
standalone `ScrollArea` share one document focus subscription. It reads native
264+
`:focus-visible` after input/focus changes; streaming and scrolling do not write
265+
focus state. This avoids applying `:has()` to every descendant of the theme root.
266+
CSS-only consumers without these React owners keep `:focus-within` viewports
267+
visible as a conservative keyboard-accessibility fallback.
263268

264269
`ScrollArea` keeps `scrollbarVisibility="auto"` as the default. `always` keeps
265270
the thumb visible and reserves a scrolling track; `hidden` deliberately hides

‎design-system/packages/ui/src/components/ScrollArea/ScrollArea.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { forwardRef, useCallback, useEffect, useRef, type HTMLAttributes } from "react";
22
import { classNames } from "../../internal/classNames";
3+
import { retainScrollbarFocus } from "../../internal/scrollbarFocus";
34
import styles from "./ScrollArea.module.css";
45

56
export type ScrollAreaOrientation = "vertical" | "horizontal" | "both";
@@ -31,6 +32,9 @@ export const ScrollArea = forwardRef<HTMLDivElement, ScrollAreaProps>(
3132
...props
3233
}, ref) {
3334
const viewportRef = useRef<HTMLDivElement | null>(null);
35+
useEffect(() => {
36+
if (viewportRef.current) return retainScrollbarFocus(viewportRef.current.ownerDocument);
37+
}, []);
3438
const setViewportRef = useCallback((viewport: HTMLDivElement | null) => {
3539
viewportRef.current = viewport;
3640
if (typeof ref === "function") ref(viewport);
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const ATTRIBUTE = "data-openbitfun-focus-visible";
2+
const documents = new WeakMap<Document, { count: number; dispose: () => void }>();
3+
4+
/** Share the browser's focus-visible state without a :has() on every DOM node. */
5+
export function retainScrollbarFocus(ownerDocument: Document): () => void {
6+
let state = documents.get(ownerDocument);
7+
if (!state) {
8+
const root = ownerDocument.documentElement;
9+
const view = ownerDocument.defaultView;
10+
const previous = root.getAttribute(ATTRIBUTE);
11+
let frame: number | undefined;
12+
const update = () => {
13+
frame = undefined;
14+
let active = ownerDocument.activeElement;
15+
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
16+
const value = String(!!active?.matches(":focus-visible"));
17+
if (root.getAttribute(ATTRIBUTE) !== value) root.setAttribute(ATTRIBUTE, value);
18+
};
19+
const schedule = () => {
20+
if (frame === undefined && view) frame = view.requestAnimationFrame(update);
21+
};
22+
// Focus can change without input; keyboard/pointer modality can change
23+
// without moving focus. Read after the browser updates its pseudo-state.
24+
const events = ["focusin", "focusout", "keydown", "keyup", "pointerdown", "pointerup"];
25+
for (const event of events) ownerDocument.addEventListener(event, schedule, true);
26+
view?.addEventListener("focus", schedule);
27+
view?.addEventListener("blur", schedule);
28+
update();
29+
state = { count: 0, dispose: () => {
30+
if (frame !== undefined) view?.cancelAnimationFrame(frame);
31+
for (const event of events) ownerDocument.removeEventListener(event, schedule, true);
32+
view?.removeEventListener("focus", schedule);
33+
view?.removeEventListener("blur", schedule);
34+
if (previous === null) root.removeAttribute(ATTRIBUTE);
35+
else root.setAttribute(ATTRIBUTE, previous);
36+
} };
37+
documents.set(ownerDocument, state);
38+
}
39+
state.count++;
40+
let released = false;
41+
return () => {
42+
if (released) return;
43+
released = true;
44+
if (--state.count === 0) {
45+
state.dispose();
46+
documents.delete(ownerDocument);
47+
}
48+
};
49+
}

‎design-system/packages/ui/src/primitives/ThemeRoot/ThemeRoot.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
1+
import { useEffect, useRef, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";
22
import { classNames } from "../../internal/classNames";
3+
import { retainScrollbarFocus } from "../../internal/scrollbarFocus";
34
import styles from "./ThemeRoot.module.css";
45

56
export type ColorScheme = "light" | "dark";
@@ -28,6 +29,10 @@ export function ThemeRoot({
2829
tokenOverrides,
2930
...props
3031
}: ThemeRootProps) {
32+
const rootRef = useRef<HTMLDivElement>(null);
33+
useEffect(() => {
34+
if (rootRef.current) return retainScrollbarFocus(rootRef.current.ownerDocument);
35+
}, []);
3136
const mergedStyle = {
3237
...style,
3338
...tokenOverrides,
@@ -36,6 +41,7 @@ export function ThemeRoot({
3641
return (
3742
<div
3843
{...props}
44+
ref={rootRef}
3945
className={classNames(styles.root, className)}
4046
data-openbitfun-design-system-root=""
4147
data-color-scheme={colorScheme}

‎design-system/packages/ui/src/providers/DesignSystemProvider.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { useContext, useMemo, type ReactNode } from "react";
1+
import { useContext, useEffect, useMemo, type ReactNode } from "react";
2+
import { retainScrollbarFocus } from "../internal/scrollbarFocus";
23
import { ApplicationTitleTooltips, ApplicationTitleTooltipsContext } from "./ApplicationTitleTooltips";
34
import type {
45
ColorScheme,
@@ -42,6 +43,7 @@ export function DesignSystemProvider({
4243
nativeTooltipPolicy = "native",
4344
}: DesignSystemProviderProps) {
4445
const ownerDocument = resolvePortalTarget(portalHost)?.ownerDocument;
46+
useEffect(() => ownerDocument && retainScrollbarFocus(ownerDocument), [ownerDocument]);
4547
const layerStack = getOverlayLayerStack(ownerDocument);
4648
const inheritedTitlePolicy = useContext(ApplicationTitleTooltipsContext);
4749
const applicationTitles = inheritedTitlePolicy || nativeTooltipPolicy === "application";

‎design-system/packages/ui/src/styles/scrollbars.css‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,17 @@
4949
* Hide only for a primary mouse/trackpad. Touch keeps a discoverable native
5050
* thumb, and forced colors keeps the operating system's accessibility cues.
5151
* Keyboard focus reveals its viewport without latching ordinary mouse focus.
52+
* A document focus flag avoids a relational selector on every descendant.
53+
* CSS-only consumers conservatively keep focused viewports discoverable.
5254
* Scroll events (including streaming output) do not reveal an idle viewport.
5355
*/
5456
@media (hover: hover) and (pointer: fine) and (forced-colors: none) {
55-
: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 {
57+
: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 {
5658
background: transparent;
5759
}
5860

5961
@supports (scrollbar-color: transparent transparent) {
60-
: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"])) {
62+
: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"] *) {
6163
scrollbar-color: transparent transparent;
6264
}
6365
}
@@ -66,11 +68,11 @@
6668
/* Opt-in hover viewports release idle tracks instead of only hiding paint.
6769
Native overflow still owns whether a track is needed when revealed. */
6870
@media (hover: hover) and (pointer: fine) and (forced-colors: none) {
69-
[data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible, :has(:focus-visible)) {
71+
[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"] *) {
7072
scrollbar-width: none;
7173
}
7274

73-
[data-openbitfun-scrollbar-visibility="hover"]:not(:hover, :focus-visible, :has(:focus-visible))::-webkit-scrollbar {
75+
[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 {
7476
display: none;
7577
}
7678
}

‎src/web-ui/index.html‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -181,21 +181,21 @@
181181

182182
/* Keep the mounting shell from showing through or doubling the tint.
183183
Preserve layout so startup readiness and measurements still complete. */
184-
#root:has(+ #openbitfun-startup-overlay:not(.openbitfun-startup-overlay--exiting)) {
184+
#root[data-startup-stage="loading"] {
185185
visibility: hidden;
186186
}
187187

188188
/* The startup mark owns the visible pixels until the handoff completes. */
189-
#root:has(+ #openbitfun-startup-overlay) [data-startup-logo-target],
190-
#root:has(+ #openbitfun-startup-overlay) [data-startup-reveal] {
189+
#root[data-startup-stage] [data-startup-logo-target],
190+
#root[data-startup-stage] [data-startup-reveal] {
191191
opacity: 0;
192192
}
193193

194-
#root:has(+ .openbitfun-startup-overlay--exiting) [data-startup-reveal] {
194+
#root:is([data-startup-stage="exiting"], [data-startup-stage="handoff"]) [data-startup-reveal] {
195195
animation: openbitfun-startup-content-enter 0.2s ease-out both;
196196
}
197197

198-
#root:has(+ .openbitfun-startup-overlay--handoff) [data-startup-reveal] {
198+
#root[data-startup-stage="handoff"] [data-startup-reveal] {
199199
animation-duration: 0.24s;
200200
animation-delay: 0.18s;
201201
}
@@ -371,7 +371,7 @@
371371

372372
@media (prefers-reduced-motion: reduce) {
373373
#openbitfun-startup-overlay.openbitfun-startup-overlay--exiting,
374-
#root:has(+ .openbitfun-startup-overlay--exiting) [data-startup-reveal] {
374+
#root:is([data-startup-stage="exiting"], [data-startup-stage="handoff"]) [data-startup-reveal] {
375375
animation-duration: 0.12s;
376376
animation-delay: 0s;
377377
}
@@ -435,7 +435,7 @@
435435

436436
<body>
437437
<script type="module" src="/src/main.tsx"></script>
438-
<div id="root"></div>
438+
<div id="root" data-startup-stage="loading"></div>
439439
<div id="openbitfun-startup-overlay">
440440
<div class="splash-screen">
441441
<div
@@ -476,11 +476,13 @@
476476
var messages = window.__OPENBITFUN_RESOLVE_BOOTSTRAP_MESSAGES__();
477477
var locale = window.__OPENBITFUN_RESOLVE_BOOTSTRAP_LOCALE__();
478478
var startupOverlay = document.getElementById('openbitfun-startup-overlay');
479+
var startupRoot = document.getElementById('root');
479480
document.documentElement.setAttribute('lang', locale);
480481

481482
if (isPetWindow) {
482483
document.body.classList.add('openbitfun-pet-preload-body');
483484
if (startupOverlay) startupOverlay.remove();
485+
if (startupRoot) startupRoot.removeAttribute('data-startup-stage');
484486
var root = document.getElementById('root');
485487
if (root) {
486488
root.innerHTML = '<div class="openbitfun-pet-preload"><div class="openbitfun-pet-preload__sprite" aria-hidden="true"></div><span class="openbitfun-sr-only"></span></div>';
@@ -493,6 +495,7 @@
493495
if (isDesktopCardWindow) {
494496
document.body.classList.add('openbitfun-desktop-card-preload-body');
495497
if (startupOverlay) startupOverlay.remove();
498+
if (startupRoot) startupRoot.removeAttribute('data-startup-stage');
496499
return;
497500
}
498501

‎src/web-ui/src/app/startup/startupOverlay.test.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,20 +19,28 @@ afterEach(() => {
1919
});
2020

2121
describe('startupOverlay', () => {
22+
it('releases startup state when the overlay has already been removed', async () => {
23+
document.body.innerHTML = '<div id="root" data-startup-stage="loading"></div>';
24+
await hideStartupOverlay();
25+
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
26+
});
27+
2228
it('removes the existing startup overlay when its exit animation completes', async () => {
2329
vi.useFakeTimers();
24-
document.body.innerHTML = '<div id="openbitfun-startup-overlay"></div>';
30+
document.body.innerHTML = '<div id="root" data-startup-stage="loading"></div><div id="openbitfun-startup-overlay"></div>';
2531

2632
const hidden = hideStartupOverlay();
2733

2834
const overlay = document.getElementById('openbitfun-startup-overlay');
2935
expect(overlay?.classList.contains('openbitfun-startup-overlay--exiting')).toBe(true);
3036
expect(overlay?.getAttribute('aria-hidden')).toBe('true');
37+
expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('exiting');
3138

3239
overlay?.dispatchEvent(new Event('animationend'));
3340
await hidden;
3441

3542
expect(isStartupOverlayPresent()).toBe(false);
43+
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
3644
});
3745

3846
it('releases startup-control focus before hiding the exiting overlay', async () => {
@@ -61,7 +69,7 @@ describe('startupOverlay', () => {
6169

6270
it('falls back to a timer when the exit animation event is not delivered', async () => {
6371
vi.useFakeTimers();
64-
document.body.innerHTML = '<div id="openbitfun-startup-overlay"></div>';
72+
document.body.innerHTML = '<div id="root" data-startup-stage="loading"></div><div id="openbitfun-startup-overlay"></div>';
6573

6674
const hidden = hideStartupOverlay();
6775

@@ -72,6 +80,7 @@ describe('startupOverlay', () => {
7280
await hidden;
7381

7482
expect(isStartupOverlayPresent()).toBe(false);
83+
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
7584
});
7685

7786
it('tracks elapsed time from the static overlay first paint', () => {
@@ -87,7 +96,7 @@ describe('startupOverlay', () => {
8796
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(callback, 16));
8897
vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id));
8998
document.body.innerHTML = `
90-
<div id="root"><section>
99+
<div id="root" data-startup-stage="loading"><section>
91100
<span data-startup-logo-target aria-hidden="true"></span>
92101
<span data-startup-reveal>OpenBitFun</span>
93102
</section></div>
@@ -120,6 +129,7 @@ describe('startupOverlay', () => {
120129
expect(mark.style.width).toBe('119px');
121130
expect(target.isConnected).toBe(true);
122131
expect(overlay.classList.contains('openbitfun-startup-overlay--handoff')).toBe(true);
132+
expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('handoff');
123133
expect(animate).toHaveBeenCalledWith([
124134
expect.objectContaining({ transform: 'translate(0px, 0px) scale(1, 1)' }),
125135
expect.objectContaining({ transform: `translate(-160px, -40px) scale(${size / 119}, ${size / 119})` }),
@@ -147,6 +157,7 @@ describe('startupOverlay', () => {
147157
await vi.runAllTimersAsync();
148158
await hidden;
149159
expect(isStartupOverlayPresent()).toBe(false);
160+
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
150161
});
151162

152163
it('restores the static mark if the WebView cannot create the animation', async () => {
@@ -167,11 +178,13 @@ describe('startupOverlay', () => {
167178
if (reason === 'cancel') reject();
168179
await vi.advanceTimersByTimeAsync(16);
169180
expect(overlay.classList.contains('openbitfun-startup-overlay--handoff')).toBe(true);
181+
expect(document.getElementById('root')?.getAttribute('data-startup-stage')).toBe('handoff');
170182
expect(overlay.classList.contains('openbitfun-startup-overlay--interrupted')).toBe(true);
171183
expect(animation.cancel).toHaveBeenCalledOnce();
172184
overlay.dispatchEvent(new Event('animationend'));
173185
await hidden;
174186
expect(isStartupOverlayPresent()).toBe(false);
187+
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
175188
expect(vi.getTimerCount()).toBe(0);
176189
});
177190

@@ -181,6 +194,7 @@ describe('startupOverlay', () => {
181194
await vi.advanceTimersByTimeAsync(520);
182195
await hidden;
183196
expect(isStartupOverlayPresent()).toBe(false);
197+
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
184198
expect(vi.getTimerCount()).toBe(0);
185199
});
186200

@@ -191,6 +205,7 @@ describe('startupOverlay', () => {
191205
document.dispatchEvent(new Event('visibilitychange'));
192206
await hidden;
193207
expect(isStartupOverlayPresent()).toBe(false);
208+
expect(document.getElementById('root')?.hasAttribute('data-startup-stage')).toBe(false);
194209
expect(animation.cancel).toHaveBeenCalledOnce();
195210
expect(vi.getTimerCount()).toBe(0);
196211
});

‎src/web-ui/src/app/startup/startupOverlay.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ function waitForOverlayExitAnimation(overlay: HTMLElement, handoff: LogoHandoff
110110
if (frame !== undefined) window.cancelAnimationFrame(frame);
111111
// Remove first so cancelling a filled animation cannot flash its origin.
112112
overlay.remove();
113+
document.getElementById('root')?.removeAttribute('data-startup-stage');
113114
activeHandoff?.animation.cancel();
114115
resolve();
115116
}
@@ -170,6 +171,7 @@ function waitForOverlayExitAnimation(overlay: HTMLElement, handoff: LogoHandoff
170171
export function hideStartupOverlay(): Promise<void> {
171172
const overlay = getOverlay();
172173
if (!overlay) {
174+
document.getElementById('root')?.removeAttribute('data-startup-stage');
173175
return Promise.resolve();
174176
}
175177

@@ -183,6 +185,9 @@ export function hideStartupOverlay(): Promise<void> {
183185
});
184186
pendingExits.set(overlay, exited);
185187
overlay.classList.add(EXIT_CLASS);
188+
// Startup owns this state directly; a root :has() would invalidate unrelated
189+
// transcript descendants whenever virtualized or streaming DOM changes.
190+
document.getElementById('root')?.setAttribute('data-startup-stage', handoff ? 'handoff' : 'exiting');
186191
// Static startup window controls can still own focus when the React shell
187192
// becomes ready. Release that focus before hiding the overlay from the
188193
// accessibility tree, then make the exiting surface non-interactive so it

‎src/web-ui/src/app/startup/startupPerformanceContract.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ function readSource(relativePath: string): string {
99
return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8').replace(/\r\n?/g, '\n');
1010
}
1111

12+
it('does not make the app root a relational selector subject after startup', () => {
13+
const html = readSource('../../../index.html');
14+
expect(html).not.toContain('#root:has(');
15+
expect(html).toContain('id="root" data-startup-stage="loading"');
16+
});
17+
1218
function dynamicImportSpecifiers(source: string): string[] {
1319
return Array.from(
1420
source.matchAll(/import\(\s*(['"])(.*?)\1\s*\)/g),

0 commit comments

Comments
 (0)