Skip to content

Commit 9ed4a72

Browse files
wspwsp1911
authored andcommitted
perf(scene-bar): Reuse tab projections
Narrow scene subscriptions and stabilize derived tab arrays so unrelated updates reuse compiled tab items. Keep surface changes reactive. Add real-hook render benchmarks and cache invalidation coverage. Validation: 101 focused tests and TypeScript checks pass. The web gate is blocked by an existing Dialog typography token violation.
1 parent 5909a00 commit 9ed4a72

4 files changed

Lines changed: 240 additions & 71 deletions

File tree

‎src/web-ui/AGENTS.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,21 @@ scroll-strip coordinate. Preserve reveal across edge-control layout changes, and
200200
release automatic reveal when the user wheels or pages the strip. These fixtures
201201
use supplied geometry; native overflow coverage is in `tests/e2e/AGENTS.md`.
202202

203+
For SceneBar projection caching and render costs:
204+
205+
```bash
206+
SCENE_BAR_BENCH=1 pnpm --dir src/web-ui run test:run src/app/components/SceneBar/SceneBar.performance.test.tsx
207+
```
208+
209+
This fixture uses the real scene manager, session-label hooks and TabGroup with
210+
24 tabs, ten warm-up renders and 100 updates per scenario. It reports React
211+
Profiler render time and item-array identities for parent renders, history-only
212+
updates and selection payloads including `lastUsed`. Timing is diagnostic, not a
213+
CI threshold. To compare the same fixture against an unoptimized checkout, set
214+
`SCENE_BAR_BASELINE=1` to omit optimization-specific assertions. These jsdom
215+
fixtures cover simulated SSH resource badges and Peer surface/title changes;
216+
they do not measure native layout/paint, live transport or end-to-end navigation.
217+
203218
For project creation entry points, work-location/environment selection, and local / SSH / WSL / Docker routing:
204219

205220
```bash
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
// @vitest-environment jsdom
2+
import React, { act, Profiler } from 'react';
3+
import { createRoot } from 'react-dom/client';
4+
import { expect, it, vi } from 'vitest';
5+
import type { TabGroupItem } from '@openbitfun/ui';
6+
import SceneBar from './SceneBar';
7+
import { flowChatStore } from '@/flow_chat/store/FlowChatStore';
8+
import type { Session } from '@/flow_chat/types/flow-chat';
9+
import { resetSceneStoreForTest, useSceneStore } from '../../stores/sceneStore';
10+
import { createPaneState } from '../../workbench/scenePaneModel';
11+
import { useContentResourceStore } from '../../workbench/contentResourceStore';
12+
import { activateSurface } from '@/infrastructure/peer-device/deviceSurface';
13+
import { useDeviceDirectory } from '@/infrastructure/account/deviceDirectory';
14+
import type { SceneTab } from './types';
15+
16+
const captured = vi.hoisted(() => ({ items: [] as TabGroupItem[][] }));
17+
vi.mock('@openbitfun/ui', async importOriginal => {
18+
const actual = await importOriginal<typeof import('@openbitfun/ui')>();
19+
const React = await import('react');
20+
return { ...actual, TabGroup: React.forwardRef<HTMLDivElement, React.ComponentProps<typeof actual.TabGroup>>((props, ref) => {
21+
captured.items.push(props.items);
22+
return <actual.TabGroup {...props} ref={ref} />;
23+
}) };
24+
});
25+
vi.mock('@/infrastructure/runtime', async importOriginal => ({
26+
...await importOriginal<typeof import('@/infrastructure/runtime')>(), supportsNativeWindowDragging: () => false,
27+
}));
28+
vi.mock('@/shared/utils/logger', () => ({
29+
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
30+
}));
31+
32+
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
33+
it('reuses compiled tabs across parent renders and ignores history-only updates', async () => {
34+
resetSceneStoreForTest();
35+
const tabs: SceneTab[] = Array.from({ length: 24 }, (_, i) => ({
36+
id: `session:perf-${i}`, lastUsed: i,
37+
session: { surfaceId: 'local', workspaceKey: 'perf', sessionId: `perf-${i}` },
38+
}));
39+
useSceneStore.setState({ ...createPaneState(tabs, tabs[0].id), activeTabId: tabs[0].id });
40+
const container = document.createElement('div');
41+
document.body.appendChild(container);
42+
const root = createRoot(container);
43+
const durations: number[] = [];
44+
const render = () => root.render(<Profiler id="scene-bar" onRender={(_id, _phase, duration) => durations.push(duration)}><SceneBar /></Profiler>);
45+
try {
46+
await act(async () => { render(); });
47+
for (let i = 0; i < 10; i++) act(render);
48+
const measure = (name: string, update: (i: number) => void) => {
49+
captured.items.length = 0;
50+
durations.length = 0;
51+
for (let i = 0; i < 100; i++) act(() => update(i));
52+
const ordered = [...durations].sort((a, b) => a - b);
53+
const result = { scenario: name, renders: captured.items.length, compilations: new Set(captured.items).size,
54+
totalRenderMs: +durations.reduce((a, b) => a + b, 0).toFixed(2),
55+
p50Ms: +(ordered[Math.floor(ordered.length * .5)] ?? 0).toFixed(3),
56+
p95Ms: +(ordered[Math.floor(ordered.length * .95)] ?? 0).toFixed(3) };
57+
if (process.env.SCENE_BAR_BENCH) process.stdout.write(`${JSON.stringify(result)}\n`);
58+
return result;
59+
};
60+
const parents = measure('parent-rerender', render);
61+
if (!process.env.SCENE_BAR_BASELINE) expect(parents.compilations).toBe(1);
62+
const history = measure('history-only', i => useSceneStore.setState({ navCursor: i }));
63+
if (!process.env.SCENE_BAR_BASELINE) expect(history.renders).toBe(0);
64+
// Model committed navigation, including the real lastUsed update.
65+
measure('selection-with-lastUsed', i => {
66+
const id = tabs[i % tabs.length].id;
67+
const openTabs = useSceneStore.getState().openTabs.map(tab => tab.id === id ? { ...tab, lastUsed: 1000 + i } : tab);
68+
useSceneStore.setState({ ...createPaneState(openTabs, id), activeTabId: id, navigationSequence: i });
69+
});
70+
} finally {
71+
act(() => root.unmount());
72+
container.remove();
73+
resetSceneStoreForTest();
74+
}
75+
});
76+
77+
it('invalidates cached file badges, titles, pinning, pane membership and device groups', async () => {
78+
resetSceneStoreForTest();
79+
activateSurface('local');
80+
const resource = useContentResourceStore.getState().open(
81+
{ type: 'code-editor', title: 'before.ts', data: { filePath: '/project/before.ts' } },
82+
{ surfaceId: 'local', remoteConnectionId: 'ssh-fixture', workspaceId: 'project' },
83+
);
84+
const file: SceneTab = { id: `content:${resource}`, contentId: resource, lastUsed: 1 };
85+
const peer: SceneTab = { id: 'session:peer-fixture', lastUsed: 2,
86+
session: { surfaceId: 'peer-fixture', workspaceKey: 'project', sessionId: 'remote' } };
87+
useSceneStore.setState({ ...createPaneState([file, peer], file.id), activeTabId: file.id });
88+
const container = document.createElement('div');
89+
document.body.appendChild(container);
90+
const root = createRoot(container);
91+
const latest = () => captured.items[captured.items.length - 1];
92+
try {
93+
await act(async () => root.render(<SceneBar />));
94+
expect(latest().find(item => item.value === file.id)?.label).toBe('before.ts');
95+
expect(container.querySelectorAll('[data-openbitfun-part="tabDevice"]')).toHaveLength(2);
96+
const initial = latest();
97+
act(() => useContentResourceStore.getState().update(resource, { isDirty: true, fileMissing: true }));
98+
expect(latest()).not.toBe(initial);
99+
expect(latest().find(item => item.value === file.id)?.labelSuffix).toBeTruthy();
100+
act(() => useContentResourceStore.getState().update(resource, { isDirty: false, fileMissing: false,
101+
content: { type: 'code-editor', title: 'after.ts', data: { filePath: '/project/after.ts' } } }));
102+
expect(latest().find(item => item.value === file.id)?.label).toBe('after.ts');
103+
expect(latest().find(item => item.value === file.id)?.labelSuffix).toBeUndefined();
104+
act(() => useSceneStore.getState().togglePinScene(file.id));
105+
expect(latest().find(item => item.value === file.id)?.labelSuffix).toBeTruthy();
106+
act(() => useDeviceDirectory.setState({ devices: [{ device_id: 'peer-fixture', device_name: 'Renamed peer' } as never] }));
107+
expect(container.textContent).toContain('Renamed peer');
108+
act(() => activateSurface('peer-fixture'));
109+
expect(container.querySelectorAll('[data-openbitfun-part="tabDevice"]')).toHaveLength(0);
110+
const session: Session = { sessionId: 'remote', title: 'Remote title', config: {},
111+
dialogTurns: [], status: 'idle', createdAt: 1, lastActiveAt: 1, error: null };
112+
act(() => flowChatStore.setState(state => ({ ...state, sessions: new Map([['remote', session]]) })));
113+
expect(latest().find(item => item.value === peer.id)?.label).toBe('Remote title');
114+
act(() => flowChatStore.setState(state => ({ ...state,
115+
sessions: new Map([['remote', { ...session, title: 'Renamed session' }]]) })));
116+
expect(latest().find(item => item.value === peer.id)?.label).toBe('Renamed session');
117+
act(() => root.render(<SceneBar pane="secondary" />));
118+
expect(latest()).toHaveLength(0);
119+
act(() => root.render(<SceneBar pane="primary" />));
120+
expect(latest()).toHaveLength(2);
121+
} finally {
122+
act(() => root.unmount());
123+
container.remove();
124+
activateSurface('local');
125+
flowChatStore.discardSurfaceState('peer-fixture');
126+
useDeviceDirectory.setState({ devices: [], localId: null });
127+
useContentResourceStore.getState().remove(resource);
128+
resetSceneStoreForTest();
129+
}
130+
});

‎src/web-ui/src/app/components/SceneBar/SceneBar.tsx‎

Lines changed: 45 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -248,51 +248,53 @@ const SceneBar: React.FC<SceneBarProps> = ({
248248
});
249249
};
250250

251-
// Each tab names its device through the label that opens its group.
252-
let groupLabel: string | undefined;
253-
const tabItems = shownTabs.reduce<TabGroupItem[]>((items, tab) => {
254-
const group = groupStarts.get(tab.id);
255-
if (group) groupLabel = `${groupLabelId}-${group.order}`;
256-
const def = tabDefs.find(candidate => candidate.id === tab.id);
257-
if (!def) return items;
251+
// Each tab names its device through the label that opens its group.
252+
const tabItems = useMemo<TabGroupItem[]>(() => {
253+
let groupLabel: string | undefined;
254+
return shownTabs.reduce<TabGroupItem[]>((items, tab) => {
255+
const group = groupStarts.get(tab.id);
256+
if (group) groupLabel = `${groupLabelId}-${group.order}`;
257+
const def = tabDefs.find(candidate => candidate.id === tab.id);
258+
if (!def) return items;
258259

259-
const translatedLabel = def.labelKey ? t(def.labelKey) : def.label;
260-
const sessionLabel = sessionLabels[tab.id];
261-
const displayLabel = sessionLabel?.title || translatedLabel;
262-
const closeLabel = t('sceneBar.closeTab', { label: displayLabel });
263-
const closable = isSceneTabClosable(def);
260+
const translatedLabel = def.labelKey ? t(def.labelKey) : def.label;
261+
const sessionLabel = sessionLabels[tab.id];
262+
const displayLabel = sessionLabel?.title || translatedLabel;
263+
const closeLabel = t('sceneBar.closeTab', { label: displayLabel });
264+
const closable = isSceneTabClosable(def);
264265

265-
items.push({
266-
value: tab.id,
267-
label: displayLabel,
268-
tabProps: groupLabel ? { 'aria-describedby': groupLabel } : undefined,
269-
labelSuffix: tab.pinned || (tab.contentId && (resources[tab.contentId]?.isDirty || resources[tab.contentId]?.fileMissing)) ? <>
270-
{tab.pinned && <Pin size={12} aria-label={tComponents('tabs.unpin')} />}
271-
{tab.contentId && resources[tab.contentId]?.isDirty && <span aria-label={tComponents('tabs.unsaved')}>•</span>}
272-
{tab.contentId && resources[tab.contentId]?.fileMissing && <CircleAlert size={12} aria-label={tComponents('tabs.fileDeleted')} />}
273-
</> : undefined,
274-
labelTransitionKey: tab.session?.sessionId,
275-
// Keep the close hit target stationary between pointer down and up;
276-
// shrinking it can retarget the click at the button edge (issue #2210).
277-
endAction: closable ? (
278-
<button
279-
type="button"
280-
aria-label={closeLabel}
281-
data-motion="none"
282-
data-scene-bar-part="closeTab"
283-
data-scene-id={tab.id}
284-
onClick={(event) => {
285-
event.stopPropagation();
286-
closeScene(tab.id);
287-
}}
288-
tabIndex={-1}
289-
>
290-
<Icon name="xmark" size="xs" aria-hidden="true" />
291-
</button>
292-
) : undefined,
293-
});
294-
return items;
295-
}, []);
266+
items.push({
267+
value: tab.id,
268+
label: displayLabel,
269+
tabProps: groupLabel ? { 'aria-describedby': groupLabel } : undefined,
270+
labelSuffix: tab.pinned || (tab.contentId && (resources[tab.contentId]?.isDirty || resources[tab.contentId]?.fileMissing)) ? <>
271+
{tab.pinned && <Pin size={12} aria-label={tComponents('tabs.unpin')} />}
272+
{tab.contentId && resources[tab.contentId]?.isDirty && <span aria-label={tComponents('tabs.unsaved')}>•</span>}
273+
{tab.contentId && resources[tab.contentId]?.fileMissing && <CircleAlert size={12} aria-label={tComponents('tabs.fileDeleted')} />}
274+
</> : undefined,
275+
labelTransitionKey: tab.session?.sessionId,
276+
// Keep the close hit target stationary between pointer down and up;
277+
// shrinking it can retarget the click at the button edge (issue #2210).
278+
endAction: closable ? (
279+
<button
280+
type="button"
281+
aria-label={closeLabel}
282+
data-motion="none"
283+
data-scene-bar-part="closeTab"
284+
data-scene-id={tab.id}
285+
onClick={(event) => {
286+
event.stopPropagation();
287+
closeScene(tab.id);
288+
}}
289+
tabIndex={-1}
290+
>
291+
<Icon name="xmark" size="xs" aria-hidden="true" />
292+
</button>
293+
) : undefined,
294+
});
295+
return items;
296+
}, []);
297+
}, [closeScene, groupLabelId, groupStarts, resources, sessionLabels, shownTabs, t, tComponents, tabDefs]);
296298

297299
return (
298300
<div data-openbitfun-component="scene-bar" data-openbitfun-part="root"

‎src/web-ui/src/app/hooks/useSceneManager.ts‎

Lines changed: 50 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
* write to the same Zustand store, so state is always in sync.
66
*/
77

8+
import { useMemo, useSyncExternalStore } from 'react';
9+
import { useShallow } from 'zustand/react/shallow';
810
import { SCENE_TAB_REGISTRY, getMiniAppSceneDef, getSceneDef } from '../scenes/registry';
911
import type { SceneTabDef, SceneTabId } from '../components/SceneBar/types';
1012
import { selectedScene, tabPane, type WorkbenchPane } from '../workbench/scenePaneModel';
@@ -15,7 +17,7 @@ import { useI18n } from '@/infrastructure/i18n';
1517
import { useContentResourceStore } from '../workbench/contentResourceStore';
1618
import { useOptionalWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext';
1719
import { parseProjectResourceTarget } from '../scenes/project-resources/projectResourceTarget';
18-
import { getActiveSurfaceId } from '@/infrastructure/peer-device/deviceSurface';
20+
import { getActiveSurfaceId, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface';
1921

2022
export interface UseSceneManagerReturn {
2123
openTabs: ReturnType<typeof useSceneStore.getState>['openTabs'];
@@ -41,46 +43,66 @@ export function useSceneManager(pane?: WorkbenchPane): UseSceneManagerReturn {
4143
activateScene,
4244
openScene,
4345
closeScene,
44-
} = useSceneStore();
46+
} = useSceneStore(useShallow(state => ({
47+
openTabs: state.openTabs,
48+
activeTabId: state.activeTabId,
49+
pendingTabId: state.pendingTabId,
50+
paneSelections: state.paneSelections,
51+
navigationMotion: state.navigationMotion,
52+
navigationSequence: state.navigationSequence,
53+
activateScene: state.activateScene,
54+
openScene: state.openScene,
55+
closeScene: state.closeScene,
56+
})));
4557
const apps = useMiniAppStore((s) => s.apps);
4658
const { currentLanguage } = useI18n();
4759
const resources = useContentResourceStore(state => state.resources);
4860
const workspaceContext = useOptionalWorkspaceContext();
49-
const projectDefs: SceneTabDef[] = openTabs.flatMap(tab => {
50-
const target = parseProjectResourceTarget(tab.id);
51-
const def = target && getSceneDef(tab.id);
52-
if (!target || !def) return [];
53-
const workspace = target.surfaceId === getActiveSurfaceId()
54-
? workspaceContext?.openedWorkspaces.get(target.workspaceId) : undefined;
55-
return [{ ...def, ...(workspace ? { label: workspace.name, labelKey: undefined } : {}) }];
56-
});
57-
const contentDefs: SceneTabDef[] = openTabs.flatMap(tab => {
58-
const resource = tab.contentId ? resources[tab.contentId] : undefined;
59-
return resource ? [{ id: tab.id, label: resource.content.title, pinned: false,
60-
closable: true, singleton: false, defaultOpen: false }] : [];
61-
});
62-
63-
const miniAppDefs: SceneTabDef[] = openTabs
64-
.filter((t) => typeof t.id === 'string' && t.id.startsWith('miniapp:'))
65-
.map((t) => {
66-
const appId = (t.id as string).slice('miniapp:'.length);
67-
const app = apps.find((a) => a.id === appId);
68-
const localizedName = app ? pickLocalizedString(app, currentLanguage, 'name') : undefined;
69-
return getMiniAppSceneDef(appId, localizedName ?? app?.name);
61+
const activeSurfaceId = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceId, getActiveSurfaceId);
62+
const openedWorkspaces = workspaceContext?.openedWorkspaces;
63+
// Preserve projections during selection/parent renders so label snapshots and
64+
// SceneBar item compilation can reuse their inputs. Surface changes still
65+
// invalidate workspace labels even when the tab list itself is retained.
66+
const paneTabs = useMemo(() => pane ? openTabs.filter(tab => tabPane(tab) === pane) : openTabs, [openTabs, pane]);
67+
const tabDefs = useMemo(() => {
68+
const projectDefs: SceneTabDef[] = openTabs.flatMap(tab => {
69+
const target = parseProjectResourceTarget(tab.id);
70+
const def = target && getSceneDef(tab.id);
71+
if (!target || !def) return [];
72+
const workspace = target.surfaceId === activeSurfaceId
73+
? openedWorkspaces?.get(target.workspaceId) : undefined;
74+
return [{ ...def, ...(workspace ? { label: workspace.name, labelKey: undefined } : {}) }];
75+
});
76+
const contentDefs: SceneTabDef[] = openTabs.flatMap(tab => {
77+
const resource = tab.contentId ? resources[tab.contentId] : undefined;
78+
return resource ? [{ id: tab.id, label: resource.content.title, pinned: false,
79+
closable: true, singleton: false, defaultOpen: false }] : [];
7080
});
7181

72-
const sessionDefs: SceneTabDef[] = openTabs
73-
.filter(tab => tab.session)
74-
.map(tab => ({ ...getSceneDef('session')!, id: tab.id }));
82+
const miniAppDefs: SceneTabDef[] = openTabs
83+
.filter((t) => typeof t.id === 'string' && t.id.startsWith('miniapp:'))
84+
.map((t) => {
85+
const appId = (t.id as string).slice('miniapp:'.length);
86+
const app = apps.find((a) => a.id === appId);
87+
const localizedName = app ? pickLocalizedString(app, currentLanguage, 'name') : undefined;
88+
return getMiniAppSceneDef(appId, localizedName ?? app?.name);
89+
});
90+
91+
const sessionDefs: SceneTabDef[] = openTabs
92+
.filter(tab => tab.session)
93+
.map(tab => ({ ...getSceneDef('session')!, id: tab.id }));
94+
95+
return [...SCENE_TAB_REGISTRY, ...sessionDefs, ...miniAppDefs, ...contentDefs, ...projectDefs];
96+
}, [openTabs, apps, currentLanguage, resources, openedWorkspaces, activeSurfaceId]);
7597

7698
return {
77-
openTabs: pane ? openTabs.filter(tab => tabPane(tab) === pane) : openTabs,
99+
openTabs: paneTabs,
78100
activeTabId: pane ? selectedScene(paneSelections[pane]) : activeTabId,
79101
pendingTabId: !pane || openTabs.some(tab => tab.id === pendingTabId && tabPane(tab) === pane) ? pendingTabId : null,
80102
paneSelections,
81103
navigationMotion,
82104
navigationSequence,
83-
tabDefs: [...SCENE_TAB_REGISTRY, ...sessionDefs, ...miniAppDefs, ...contentDefs, ...projectDefs],
105+
tabDefs,
84106
activateScene,
85107
openScene,
86108
closeScene,

0 commit comments

Comments
 (0)