diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index 1e5175a8b7..e719a95103 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -200,6 +200,21 @@ scroll-strip coordinate. Preserve reveal across edge-control layout changes, and release automatic reveal when the user wheels or pages the strip. These fixtures use supplied geometry; native overflow coverage is in `tests/e2e/AGENTS.md`. +For SceneBar projection caching and render costs: + +```bash +SCENE_BAR_BENCH=1 pnpm --dir src/web-ui run test:run src/app/components/SceneBar/SceneBar.performance.test.tsx +``` + +This fixture uses the real scene manager, session-label hooks and TabGroup with +24 tabs, ten warm-up renders and 100 updates per scenario. It reports React +Profiler render time and item-array identities for parent renders, history-only +updates and selection payloads including `lastUsed`. Timing is diagnostic, not a +CI threshold. To compare the same fixture against an unoptimized checkout, set +`SCENE_BAR_BASELINE=1` to omit optimization-specific assertions. These jsdom +fixtures cover simulated SSH resource badges and Peer surface/title changes; +they do not measure native layout/paint, live transport or end-to-end navigation. + For project creation entry points, work-location/environment selection, and local / SSH / WSL / Docker routing: ```bash diff --git a/src/web-ui/src/app/components/SceneBar/SceneBar.performance.test.tsx b/src/web-ui/src/app/components/SceneBar/SceneBar.performance.test.tsx new file mode 100644 index 0000000000..505ea68e5e --- /dev/null +++ b/src/web-ui/src/app/components/SceneBar/SceneBar.performance.test.tsx @@ -0,0 +1,130 @@ +// @vitest-environment jsdom +import React, { act, Profiler } from 'react'; +import { createRoot } from 'react-dom/client'; +import { expect, it, vi } from 'vitest'; +import type { TabGroupItem } from '@openbitfun/ui'; +import SceneBar from './SceneBar'; +import { flowChatStore } from '@/flow_chat/store/FlowChatStore'; +import type { Session } from '@/flow_chat/types/flow-chat'; +import { resetSceneStoreForTest, useSceneStore } from '../../stores/sceneStore'; +import { createPaneState } from '../../workbench/scenePaneModel'; +import { useContentResourceStore } from '../../workbench/contentResourceStore'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { useDeviceDirectory } from '@/infrastructure/account/deviceDirectory'; +import type { SceneTab } from './types'; + +const captured = vi.hoisted(() => ({ items: [] as TabGroupItem[][] })); +vi.mock('@openbitfun/ui', async importOriginal => { + const actual = await importOriginal(); + const React = await import('react'); + return { ...actual, TabGroup: React.forwardRef>((props, ref) => { + captured.items.push(props.items); + return ; + }) }; +}); +vi.mock('@/infrastructure/runtime', async importOriginal => ({ + ...await importOriginal(), supportsNativeWindowDragging: () => false, +})); +vi.mock('@/shared/utils/logger', () => ({ + createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }), +})); + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; +it('reuses compiled tabs across parent renders and ignores history-only updates', async () => { + resetSceneStoreForTest(); + const tabs: SceneTab[] = Array.from({ length: 24 }, (_, i) => ({ + id: `session:perf-${i}`, lastUsed: i, + session: { surfaceId: 'local', workspaceKey: 'perf', sessionId: `perf-${i}` }, + })); + useSceneStore.setState({ ...createPaneState(tabs, tabs[0].id), activeTabId: tabs[0].id }); + const container = document.createElement('div'); + document.body.appendChild(container); + const root = createRoot(container); + const durations: number[] = []; + const render = () => root.render( durations.push(duration)}>); + try { + await act(async () => { render(); }); + for (let i = 0; i < 10; i++) act(render); + const measure = (name: string, update: (i: number) => void) => { + captured.items.length = 0; + durations.length = 0; + for (let i = 0; i < 100; i++) act(() => update(i)); + const ordered = [...durations].sort((a, b) => a - b); + const result = { scenario: name, renders: captured.items.length, compilations: new Set(captured.items).size, + totalRenderMs: +durations.reduce((a, b) => a + b, 0).toFixed(2), + p50Ms: +(ordered[Math.floor(ordered.length * .5)] ?? 0).toFixed(3), + p95Ms: +(ordered[Math.floor(ordered.length * .95)] ?? 0).toFixed(3) }; + if (process.env.SCENE_BAR_BENCH) process.stdout.write(`${JSON.stringify(result)}\n`); + return result; + }; + const parents = measure('parent-rerender', render); + if (!process.env.SCENE_BAR_BASELINE) expect(parents.compilations).toBe(1); + const history = measure('history-only', i => useSceneStore.setState({ navCursor: i })); + if (!process.env.SCENE_BAR_BASELINE) expect(history.renders).toBe(0); + // Model committed navigation, including the real lastUsed update. + measure('selection-with-lastUsed', i => { + const id = tabs[i % tabs.length].id; + const openTabs = useSceneStore.getState().openTabs.map(tab => tab.id === id ? { ...tab, lastUsed: 1000 + i } : tab); + useSceneStore.setState({ ...createPaneState(openTabs, id), activeTabId: id, navigationSequence: i }); + }); + } finally { + act(() => root.unmount()); + container.remove(); + resetSceneStoreForTest(); + } +}); + +it('invalidates cached file badges, titles, pinning, pane membership and device groups', async () => { + resetSceneStoreForTest(); + activateSurface('local'); + const resource = useContentResourceStore.getState().open( + { type: 'code-editor', title: 'before.ts', data: { filePath: '/project/before.ts' } }, + { surfaceId: 'local', remoteConnectionId: 'ssh-fixture', workspaceId: 'project' }, + ); + const file: SceneTab = { id: `content:${resource}`, contentId: resource, lastUsed: 1 }; + const peer: SceneTab = { id: 'session:peer-fixture', lastUsed: 2, + session: { surfaceId: 'peer-fixture', workspaceKey: 'project', sessionId: 'remote' } }; + useSceneStore.setState({ ...createPaneState([file, peer], file.id), activeTabId: file.id }); + const container = document.createElement('div'); + document.body.appendChild(container); + const root = createRoot(container); + const latest = () => captured.items[captured.items.length - 1]; + try { + await act(async () => root.render()); + expect(latest().find(item => item.value === file.id)?.label).toBe('before.ts'); + expect(container.querySelectorAll('[data-openbitfun-part="tabDevice"]')).toHaveLength(2); + const initial = latest(); + act(() => useContentResourceStore.getState().update(resource, { isDirty: true, fileMissing: true })); + expect(latest()).not.toBe(initial); + expect(latest().find(item => item.value === file.id)?.labelSuffix).toBeTruthy(); + act(() => useContentResourceStore.getState().update(resource, { isDirty: false, fileMissing: false, + content: { type: 'code-editor', title: 'after.ts', data: { filePath: '/project/after.ts' } } })); + expect(latest().find(item => item.value === file.id)?.label).toBe('after.ts'); + expect(latest().find(item => item.value === file.id)?.labelSuffix).toBeUndefined(); + act(() => useSceneStore.getState().togglePinScene(file.id)); + expect(latest().find(item => item.value === file.id)?.labelSuffix).toBeTruthy(); + act(() => useDeviceDirectory.setState({ devices: [{ device_id: 'peer-fixture', device_name: 'Renamed peer' } as never] })); + expect(container.textContent).toContain('Renamed peer'); + act(() => activateSurface('peer-fixture')); + expect(container.querySelectorAll('[data-openbitfun-part="tabDevice"]')).toHaveLength(0); + const session: Session = { sessionId: 'remote', title: 'Remote title', config: {}, + dialogTurns: [], status: 'idle', createdAt: 1, lastActiveAt: 1, error: null }; + act(() => flowChatStore.setState(state => ({ ...state, sessions: new Map([['remote', session]]) }))); + expect(latest().find(item => item.value === peer.id)?.label).toBe('Remote title'); + act(() => flowChatStore.setState(state => ({ ...state, + sessions: new Map([['remote', { ...session, title: 'Renamed session' }]]) }))); + expect(latest().find(item => item.value === peer.id)?.label).toBe('Renamed session'); + act(() => root.render()); + expect(latest()).toHaveLength(0); + act(() => root.render()); + expect(latest()).toHaveLength(2); + } finally { + act(() => root.unmount()); + container.remove(); + activateSurface('local'); + flowChatStore.discardSurfaceState('peer-fixture'); + useDeviceDirectory.setState({ devices: [], localId: null }); + useContentResourceStore.getState().remove(resource); + resetSceneStoreForTest(); + } +}); diff --git a/src/web-ui/src/app/components/SceneBar/SceneBar.tsx b/src/web-ui/src/app/components/SceneBar/SceneBar.tsx index f75257d49a..209053f607 100644 --- a/src/web-ui/src/app/components/SceneBar/SceneBar.tsx +++ b/src/web-ui/src/app/components/SceneBar/SceneBar.tsx @@ -248,51 +248,53 @@ const SceneBar: React.FC = ({ }); }; - // Each tab names its device through the label that opens its group. - let groupLabel: string | undefined; - const tabItems = shownTabs.reduce((items, tab) => { - const group = groupStarts.get(tab.id); - if (group) groupLabel = `${groupLabelId}-${group.order}`; - const def = tabDefs.find(candidate => candidate.id === tab.id); - if (!def) return items; + // Each tab names its device through the label that opens its group. + const tabItems = useMemo(() => { + let groupLabel: string | undefined; + return shownTabs.reduce((items, tab) => { + const group = groupStarts.get(tab.id); + if (group) groupLabel = `${groupLabelId}-${group.order}`; + const def = tabDefs.find(candidate => candidate.id === tab.id); + if (!def) return items; - const translatedLabel = def.labelKey ? t(def.labelKey) : def.label; - const sessionLabel = sessionLabels[tab.id]; - const displayLabel = sessionLabel?.title || translatedLabel; - const closeLabel = t('sceneBar.closeTab', { label: displayLabel }); - const closable = isSceneTabClosable(def); + const translatedLabel = def.labelKey ? t(def.labelKey) : def.label; + const sessionLabel = sessionLabels[tab.id]; + const displayLabel = sessionLabel?.title || translatedLabel; + const closeLabel = t('sceneBar.closeTab', { label: displayLabel }); + const closable = isSceneTabClosable(def); - items.push({ - value: tab.id, - label: displayLabel, - tabProps: groupLabel ? { 'aria-describedby': groupLabel } : undefined, - labelSuffix: tab.pinned || (tab.contentId && (resources[tab.contentId]?.isDirty || resources[tab.contentId]?.fileMissing)) ? <> - {tab.pinned && } - {tab.contentId && resources[tab.contentId]?.isDirty && •} - {tab.contentId && resources[tab.contentId]?.fileMissing && } - : undefined, - labelTransitionKey: tab.session?.sessionId, - // Keep the close hit target stationary between pointer down and up; - // shrinking it can retarget the click at the button edge (issue #2210). - endAction: closable ? ( - - ) : undefined, - }); - return items; - }, []); + items.push({ + value: tab.id, + label: displayLabel, + tabProps: groupLabel ? { 'aria-describedby': groupLabel } : undefined, + labelSuffix: tab.pinned || (tab.contentId && (resources[tab.contentId]?.isDirty || resources[tab.contentId]?.fileMissing)) ? <> + {tab.pinned && } + {tab.contentId && resources[tab.contentId]?.isDirty && •} + {tab.contentId && resources[tab.contentId]?.fileMissing && } + : undefined, + labelTransitionKey: tab.session?.sessionId, + // Keep the close hit target stationary between pointer down and up; + // shrinking it can retarget the click at the button edge (issue #2210). + endAction: closable ? ( + + ) : undefined, + }); + return items; + }, []); + }, [closeScene, groupLabelId, groupStarts, resources, sessionLabels, shownTabs, t, tComponents, tabDefs]); return (
['openTabs']; @@ -41,46 +43,66 @@ export function useSceneManager(pane?: WorkbenchPane): UseSceneManagerReturn { activateScene, openScene, closeScene, - } = useSceneStore(); + } = useSceneStore(useShallow(state => ({ + openTabs: state.openTabs, + activeTabId: state.activeTabId, + pendingTabId: state.pendingTabId, + paneSelections: state.paneSelections, + navigationMotion: state.navigationMotion, + navigationSequence: state.navigationSequence, + activateScene: state.activateScene, + openScene: state.openScene, + closeScene: state.closeScene, + }))); const apps = useMiniAppStore((s) => s.apps); const { currentLanguage } = useI18n(); const resources = useContentResourceStore(state => state.resources); const workspaceContext = useOptionalWorkspaceContext(); - const projectDefs: SceneTabDef[] = openTabs.flatMap(tab => { - const target = parseProjectResourceTarget(tab.id); - const def = target && getSceneDef(tab.id); - if (!target || !def) return []; - const workspace = target.surfaceId === getActiveSurfaceId() - ? workspaceContext?.openedWorkspaces.get(target.workspaceId) : undefined; - return [{ ...def, ...(workspace ? { label: workspace.name, labelKey: undefined } : {}) }]; - }); - const contentDefs: SceneTabDef[] = openTabs.flatMap(tab => { - const resource = tab.contentId ? resources[tab.contentId] : undefined; - return resource ? [{ id: tab.id, label: resource.content.title, pinned: false, - closable: true, singleton: false, defaultOpen: false }] : []; - }); - - const miniAppDefs: SceneTabDef[] = openTabs - .filter((t) => typeof t.id === 'string' && t.id.startsWith('miniapp:')) - .map((t) => { - const appId = (t.id as string).slice('miniapp:'.length); - const app = apps.find((a) => a.id === appId); - const localizedName = app ? pickLocalizedString(app, currentLanguage, 'name') : undefined; - return getMiniAppSceneDef(appId, localizedName ?? app?.name); + const activeSurfaceId = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceId, getActiveSurfaceId); + const openedWorkspaces = workspaceContext?.openedWorkspaces; + // Preserve projections during selection/parent renders so label snapshots and + // SceneBar item compilation can reuse their inputs. Surface changes still + // invalidate workspace labels even when the tab list itself is retained. + const paneTabs = useMemo(() => pane ? openTabs.filter(tab => tabPane(tab) === pane) : openTabs, [openTabs, pane]); + const tabDefs = useMemo(() => { + const projectDefs: SceneTabDef[] = openTabs.flatMap(tab => { + const target = parseProjectResourceTarget(tab.id); + const def = target && getSceneDef(tab.id); + if (!target || !def) return []; + const workspace = target.surfaceId === activeSurfaceId + ? openedWorkspaces?.get(target.workspaceId) : undefined; + return [{ ...def, ...(workspace ? { label: workspace.name, labelKey: undefined } : {}) }]; + }); + const contentDefs: SceneTabDef[] = openTabs.flatMap(tab => { + const resource = tab.contentId ? resources[tab.contentId] : undefined; + return resource ? [{ id: tab.id, label: resource.content.title, pinned: false, + closable: true, singleton: false, defaultOpen: false }] : []; }); - const sessionDefs: SceneTabDef[] = openTabs - .filter(tab => tab.session) - .map(tab => ({ ...getSceneDef('session')!, id: tab.id })); + const miniAppDefs: SceneTabDef[] = openTabs + .filter((t) => typeof t.id === 'string' && t.id.startsWith('miniapp:')) + .map((t) => { + const appId = (t.id as string).slice('miniapp:'.length); + const app = apps.find((a) => a.id === appId); + const localizedName = app ? pickLocalizedString(app, currentLanguage, 'name') : undefined; + return getMiniAppSceneDef(appId, localizedName ?? app?.name); + }); + + const sessionDefs: SceneTabDef[] = openTabs + .filter(tab => tab.session) + .map(tab => ({ ...getSceneDef('session')!, id: tab.id })); + + return [...SCENE_TAB_REGISTRY, ...sessionDefs, ...miniAppDefs, ...contentDefs, ...projectDefs]; + }, [openTabs, apps, currentLanguage, resources, openedWorkspaces, activeSurfaceId]); return { - openTabs: pane ? openTabs.filter(tab => tabPane(tab) === pane) : openTabs, + openTabs: paneTabs, activeTabId: pane ? selectedScene(paneSelections[pane]) : activeTabId, pendingTabId: !pane || openTabs.some(tab => tab.id === pendingTabId && tabPane(tab) === pane) ? pendingTabId : null, paneSelections, navigationMotion, navigationSequence, - tabDefs: [...SCENE_TAB_REGISTRY, ...sessionDefs, ...miniAppDefs, ...contentDefs, ...projectDefs], + tabDefs, activateScene, openScene, closeScene,