Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/web-ui/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
130 changes: 130 additions & 0 deletions src/web-ui/src/app/components/SceneBar/SceneBar.performance.test.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof import('@openbitfun/ui')>();
const React = await import('react');
return { ...actual, TabGroup: React.forwardRef<HTMLDivElement, React.ComponentProps<typeof actual.TabGroup>>((props, ref) => {
captured.items.push(props.items);
return <actual.TabGroup {...props} ref={ref} />;
}) };
});
vi.mock('@/infrastructure/runtime', async importOriginal => ({
...await importOriginal<typeof import('@/infrastructure/runtime')>(), 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(<Profiler id="scene-bar" onRender={(_id, _phase, duration) => durations.push(duration)}><SceneBar /></Profiler>);
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(<SceneBar />));
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(<SceneBar pane="secondary" />));
expect(latest()).toHaveLength(0);
act(() => root.render(<SceneBar pane="primary" />));
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();
}
});
88 changes: 45 additions & 43 deletions src/web-ui/src/app/components/SceneBar/SceneBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -248,51 +248,53 @@ const SceneBar: React.FC<SceneBarProps> = ({
});
};

// Each tab names its device through the label that opens its group.
let groupLabel: string | undefined;
const tabItems = shownTabs.reduce<TabGroupItem[]>((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<TabGroupItem[]>(() => {
let groupLabel: string | undefined;
return shownTabs.reduce<TabGroupItem[]>((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 && <Pin size={12} aria-label={tComponents('tabs.unpin')} />}
{tab.contentId && resources[tab.contentId]?.isDirty && <span aria-label={tComponents('tabs.unsaved')}>•</span>}
{tab.contentId && resources[tab.contentId]?.fileMissing && <CircleAlert size={12} aria-label={tComponents('tabs.fileDeleted')} />}
</> : 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 ? (
<button
type="button"
aria-label={closeLabel}
data-motion="none"
data-scene-bar-part="closeTab"
data-scene-id={tab.id}
onClick={(event) => {
event.stopPropagation();
closeScene(tab.id);
}}
tabIndex={-1}
>
<Icon name="xmark" size="xs" aria-hidden="true" />
</button>
) : 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 && <Pin size={12} aria-label={tComponents('tabs.unpin')} />}
{tab.contentId && resources[tab.contentId]?.isDirty && <span aria-label={tComponents('tabs.unsaved')}>•</span>}
{tab.contentId && resources[tab.contentId]?.fileMissing && <CircleAlert size={12} aria-label={tComponents('tabs.fileDeleted')} />}
</> : 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 ? (
<button
type="button"
aria-label={closeLabel}
data-motion="none"
data-scene-bar-part="closeTab"
data-scene-id={tab.id}
onClick={(event) => {
event.stopPropagation();
closeScene(tab.id);
}}
tabIndex={-1}
>
<Icon name="xmark" size="xs" aria-hidden="true" />
</button>
) : undefined,
});
return items;
}, []);
}, [closeScene, groupLabelId, groupStarts, resources, sessionLabels, shownTabs, t, tComponents, tabDefs]);

return (
<div data-openbitfun-component="scene-bar" data-openbitfun-part="root"
Expand Down
78 changes: 50 additions & 28 deletions src/web-ui/src/app/hooks/useSceneManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* write to the same Zustand store, so state is always in sync.
*/

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

export interface UseSceneManagerReturn {
openTabs: ReturnType<typeof useSceneStore.getState>['openTabs'];
Expand All @@ -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,
Expand Down
Loading