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
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CanvasToolbarHost, CanvasToolbarProvider } from '../CanvasToolbar';
import { useAgentCanvasStore } from '../stores';
import type { EditorGroupId, SplitMode } from '../types';
import type { EditorGroupId, PanelContentType, SplitMode } from '../types';
import { EditorArea } from './EditorArea';

vi.mock('react-i18next', async original => ({
...await original<typeof import('react-i18next')>(),
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock('../../base/FlexiblePanel', () => ({ default: () => null }));
vi.mock('../../base/FlexiblePanel', () => ({
default: ({ content, isActive }: { content: { title: string }; isActive: boolean }) => (
<input data-panel-title={content.title} data-active={isActive} />
),
}));

// Exercise real groups, tab bars and toolbar registration without mounting editors.
describe('split canvas tab placement', () => {
Expand All @@ -34,9 +38,9 @@ describe('split canvas tab placement', () => {
vi.unstubAllGlobals();
});

function addTab(groupId: EditorGroupId, title: string = groupId) {
function addTab(groupId: EditorGroupId, title: string = groupId, type: PanelContentType = 'text-viewer') {
useAgentCanvasStore.getState().addTab({
type: 'text-viewer', title, data: { content: title },
type, title, data: { content: title },
}, 'active', groupId);
return useAgentCanvasStore.getState()[`${groupId}Group`].activeTabId!;
}
Expand Down Expand Up @@ -130,4 +134,42 @@ describe('split canvas tab placement', () => {
expect(group('primary').querySelector('[role="tablist"]')).not.toBeNull();
expect(group('secondary').querySelector('[role="tablist"]')).not.toBeNull();
});

it('keeps hidden editors laid out and inert until selected again', () => {
const editorId = addTab('primary', 'Editor', 'code-editor');
render();
let diffId!: string;
let terminalId!: string;
act(() => { diffId = addTab('primary', 'Diff', 'diff-code-editor'); });
act(() => { terminalId = addTab('primary', 'Terminal', 'terminal'); });

const pane = (title: string) => container.querySelector(`[data-panel-title="${title}"]`)!
.closest<HTMLElement>('[data-openbitfun-part="tabContent"]')!;
const inactive = 'canvas-editor-group__tab-content--inactive-editor';
const editor = pane('Editor');
const diff = pane('Diff');
const terminal = pane('Terminal');
for (const hidden of [editor, diff]) {
expect(hidden.classList.contains(inactive)).toBe(true);
expect(hidden.style.display).toBe('');
expect(hidden.getAttribute('aria-hidden')).toBe('true');
expect(hidden.hasAttribute('inert')).toBe(true);
expect(hidden.querySelector('input')?.getAttribute('data-active')).toBe('false');
}

for (const [id, title, retained] of [[editorId, 'Editor', editor], [diffId, 'Diff', diff]] as const) {
act(() => tab(id).click());
expect(pane(title)).toBe(retained);
expect(retained.classList.contains(inactive)).toBe(false);
expect(retained.hasAttribute('inert')).toBe(false);
expect(retained.hasAttribute('aria-hidden')).toBe(false);
expect(retained.querySelector('input')?.getAttribute('data-active')).toBe('true');
expect(terminal.style.display).toBe('none');
expect(terminal.classList.contains(inactive)).toBe(false);
}

act(() => tab(terminalId).click());
expect(pane('Terminal')).toBe(terminal);
expect(terminal.style.display).toBe('');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
position: absolute;
inset: 0;

// Keep Monaco's observed box stable while the cached editor is inactive.
&--inactive-editor {
visibility: hidden;
opacity: 0;
}

// FlexiblePanel overrides
.openbitfun-flexible-panel {
flex: 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,33 +288,43 @@ export const EditorGroup: React.FC<EditorGroupProps> = ({
<div data-openbitfun-component="canvas-editor-group" data-openbitfun-part="content" className="canvas-editor-group__content">
{/* Render cached tabs (active shown, others hidden) for instant switching */}
{tabsToRender.length > 0 ? (
tabsToRender.map((tab) => (
<div
key={tab.id}
ref={effectiveActiveTabId === tab.id ? activeTabContentRef : undefined}
data-openbitfun-component="canvas-editor-group"
data-openbitfun-part="tabContent"
className="canvas-editor-group__tab-content"
style={{ display: effectiveActiveTabId === tab.id ? 'flex' : 'none' }}
>
<CanvasContentView
documentId={canvasTabDocumentId(tab)}
content={tab.content as any}
isActive={isSceneActive && effectiveActiveTabId === tab.id}
onContentChange={effectiveActiveTabId === tab.id ? handleContentChange : undefined}
onDirtyStateChange={effectiveActiveTabId === tab.id ? handleDirtyStateChange : undefined}
onFileMissingFromDiskChange={
onTabFileDeletedFromDiskChange
? (missing) => onTabFileDeletedFromDiskChange(tab.id, missing)
: undefined
}
onInteraction={onInteraction}
workspacePath={workspacePath}
terminalResizeSuspended={terminalResizeSuspended}
resizeSuspended={resizeSuspended}
/>
</div>
))
tabsToRender.map((tab) => {
const isSelected = effectiveActiveTabId === tab.id;
const keepHiddenLayout = !isSelected && (
tab.content.type === 'code-editor' || tab.content.type === 'diff-code-editor'
);
return (
<div
key={tab.id}
ref={isSelected ? activeTabContentRef : undefined}
data-openbitfun-component="canvas-editor-group"
data-openbitfun-part="tabContent"
className={keepHiddenLayout
? 'canvas-editor-group__tab-content canvas-editor-group__tab-content--inactive-editor'
: 'canvas-editor-group__tab-content'}
style={!isSelected && !keepHiddenLayout ? { display: 'none' } : undefined}
aria-hidden={keepHiddenLayout || undefined}
{...(keepHiddenLayout ? { inert: '' } : {})}
>
<CanvasContentView
documentId={canvasTabDocumentId(tab)}
content={tab.content as any}
isActive={isSceneActive && isSelected}
onContentChange={isSelected ? handleContentChange : undefined}
onDirtyStateChange={isSelected ? handleDirtyStateChange : undefined}
onFileMissingFromDiskChange={
onTabFileDeletedFromDiskChange
? (missing) => onTabFileDeletedFromDiskChange(tab.id, missing)
: undefined
}
onInteraction={onInteraction}
workspacePath={workspacePath}
terminalResizeSuspended={terminalResizeSuspended}
resizeSuspended={resizeSuspended}
/>
</div>
);
})
) : visibleTabs.length === 0 ? (
<div data-openbitfun-component="canvas-editor-group" data-openbitfun-part="empty" className="canvas-editor-group__empty">
<div data-openbitfun-component="canvas-editor-group" data-openbitfun-part="emptyContent" className="canvas-editor-group__empty-content">
Expand Down
76 changes: 67 additions & 9 deletions src/web-ui/src/app/scenes/settings/SettingsNav.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import React, { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { createInstance, type i18n as I18nApi } from 'i18next';
import { I18nextProvider } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

globalThis.IS_REACT_ACT_ENVIRONMENT = true;
Expand All @@ -10,7 +12,10 @@ vi.mock('./settingsRegistry', () => {
const icon = () => null;
const pages = [
{ id: 'application.general', categoryId: 'application', labelKey: 'General' },
{ id: 'application.appearance', categoryId: 'application', labelKey: 'Appearance' },
{
id: 'application.appearance', categoryId: 'application', labelKey: 'Appearance',
searchPhrases: [{ namespace: 'settings/appearance', key: 'themeKeyword' }],
},
{
id: 'application.pet', categoryId: 'application', labelKey: 'Pet & assistant',
descriptionKey: 'Desktop pet and realtime voice calls',
Expand All @@ -34,11 +39,6 @@ vi.mock('./settingsRegistry', () => {
};
});

vi.mock('react-i18next', () => {
const t = (key: string) => key;
const i18n = { language: 'en-US', getFixedT: () => t };
return { useTranslation: () => ({ t, i18n }) };
});
vi.mock('@/infrastructure/i18n/hooks/useI18n', () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
Expand All @@ -57,16 +57,35 @@ import {
describe('SettingsNav shared component composition', () => {
let container: HTMLDivElement;
let root: Root;
let i18n: I18nApi;

beforeEach(() => {
beforeEach(async () => {
i18n = createInstance();
await i18n.init({
lng: 'en-US',
fallbackLng: 'en-US',
ns: ['settings', 'shared'],
resources: {
'en-US': {
settings: {
Application: 'Application', General: 'General', Appearance: 'Appearance',
'Pet & assistant': 'Pet & assistant', Pet: 'Pet', 'Realtime voice calls': 'Realtime voice calls',
'Desktop pet and realtime voice calls': 'Desktop pet and realtime voice calls', Models: 'Models',
},
shared: { features: { settings: 'Settings' } },
},
'zh-CN': { settings: { Appearance: '外观' }, 'settings/appearance': { themeKeyword: '配色' } },
},
});
vi.spyOn(i18n, 'getFixedT');
vi.useFakeTimers();
vi.mocked(preloadSettingsPage).mockReset().mockResolvedValue(undefined);
resetSettingsDraftRegistryForTests();
useSettingsStore.setState(useSettingsStore.getInitialState());
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
act(() => root.render(<SettingsNav />));
act(() => root.render(<I18nextProvider i18n={i18n}><SettingsNav /></I18nextProvider>));
});

afterEach(() => {
Expand Down Expand Up @@ -95,7 +114,7 @@ describe('SettingsNav shared component composition', () => {
const header = nav.querySelector(':scope > [data-openbitfun-part="header"]')!;
const viewport = nav.querySelector('[data-openbitfun-component="scroll-area"]')!;
const content = viewport.querySelector('[data-openbitfun-part="content"]')!;
expect(nav.getAttribute('aria-label')).toBe('shared:features.settings');
expect(nav.getAttribute('aria-label')).toBe('Settings');
expect(header.querySelector('input')).not.toBeNull();
expect(viewport.contains(header)).toBe(false);
expect(content.classList.contains('openbitfun-settings-nav__content')).toBe(true);
Expand Down Expand Up @@ -153,6 +172,45 @@ describe('SettingsNav shared component composition', () => {
expect(container.querySelector('[role="status"]')).toBeNull();
});

it('defers indexing until search and reuses the index after clearing', async () => {
const phraseLookups = () => vi.mocked(i18n.getFixedT).mock.calls
.filter(([, namespace]) => namespace === 'settings/appearance');
const appearance = container.querySelector<HTMLButtonElement>('[data-settings-page="application.appearance"]')!;

await act(async () => appearance.click());
await search(' ');
expect(phraseLookups()).toHaveLength(0);

await act(async () => { i18n.addResourceBundle('en-US', 'settings/appearance', { themeKeyword: 'palette' }); });
expect(phraseLookups()).toHaveLength(0);
const input = await search('palette');
expect(container.querySelector('[role="option"]')?.textContent).toContain('Appearance');
expect(phraseLookups()).toHaveLength(1);

act(() => pressKey(input, 'Escape'));
await search('palette');
expect(phraseLookups()).toHaveLength(1);
});

it('refreshes an active search when indexed translations change', async () => {
await search('palette');
expect(container.querySelector('[role="option"]')).toBeNull();
await act(async () => { i18n.addResourceBundle('en-US', 'settings/appearance', { themeKeyword: 'palette' }); });
expect(container.querySelector('[role="option"]')?.textContent).toContain('Appearance');

const lookupCount = vi.mocked(i18n.getFixedT).mock.calls.length;
act(() => i18n.addResourceBundle('en-US', 'unrelated', { label: 'Palette' }));
expect(i18n.getFixedT).toHaveBeenCalledTimes(lookupCount);

await act(async () => { await i18n.changeLanguage('zh-CN'); });
expect(container.querySelector('[role="option"]')).toBeNull();
await search('配色');
expect(container.querySelector('[role="option"]')?.textContent).toContain('外观');

act(() => i18n.removeResourceBundle('zh-CN', 'settings/appearance'));
expect(container.querySelector('[role="option"]')).toBeNull();
});

it('keeps unsaved markers outside navigation and search-result text', async () => {
act(() => {
registerSettingsDraft({
Expand Down
41 changes: 39 additions & 2 deletions src/web-ui/src/app/scenes/settings/SettingsNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import React, {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
Expand Down Expand Up @@ -108,6 +109,38 @@
});
}

function useSettingsSearchIndex(t: SettingsT, i18n: I18nApi, hasSearched: boolean) {
const [resourcesRevision, setResourcesRevision] = useState(0);
const { store, languages } = i18n;

useLayoutEffect(() => {
if (!hasSearched) return;

const namespaces = new Set(['settings']);
for (const page of SETTINGS_PAGE_MANIFESTS) {
for (const entry of [page, ...(page.sections ?? []), ...(page.views ?? [])]) {
for (const { namespace } of entry.searchPhrases) namespaces.add(namespace);
}
}
const invalidate = (language: string, namespace: string) => {
if (languages.includes(language) && namespaces.has(namespace)) {
setResourcesRevision(revision => revision + 1);
}
};
store.on('added', invalidate);
store.on('removed', invalidate);
return () => {
store.off('added', invalidate);
store.off('removed', invalidate);
};
}, [hasSearched, languages, store]);

return useMemo(
() => hasSearched ? buildSettingsSearchIndex(t, i18n) : [],
[hasSearched, i18n, resourcesRevision, t],

Check failure on line 140 in src/web-ui/src/app/scenes/settings/SettingsNav.tsx

View workflow job for this annotation

GitHub Actions / Frontend Build

React Hook useMemo has an unnecessary dependency: 'resourcesRevision'. Either exclude it or remove the dependency array
);
}

function highlightFirstMatch(text: string, query: string): React.ReactNode {
const needle = query.trim();
if (!needle) return text;
Expand Down Expand Up @@ -139,6 +172,7 @@
const searchQuery = useSettingsStore((state) => state.searchQuery);
const setSearchQuery = useSettingsStore((state) => state.setSearchQuery);
const [draftQuery, setDraftQuery] = useState('');
const [hasSearched, setHasSearched] = useState(false);
const [highlightedIndex, setHighlightedIndex] = useState(-1);
const searchInputRef = useRef<HTMLInputElement>(null);
const resultsRef = useRef<HTMLDivElement>(null);
Expand All @@ -152,11 +186,14 @@
}, []);

useEffect(() => {
const timer = window.setTimeout(() => setSearchQuery(draftQuery), SEARCH_DEBOUNCE_MS);
const timer = window.setTimeout(() => {
if (draftQuery.trim()) setHasSearched(true);
setSearchQuery(draftQuery);
}, SEARCH_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [draftQuery, setSearchQuery]);

const searchIndex = useMemo(() => buildSettingsSearchIndex(t, i18n), [i18n, t]);
const searchIndex = useSettingsSearchIndex(t, i18n, hasSearched);
const results = useMemo(() => {
const query = searchQuery.trim().toLowerCase();
if (!query) return [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ const BtwSessionPanelContent: React.FC<BtwSessionPanelProps & { viewState: BtwPa
? t(resolveSubagentNameKey(childSessionId ?? ''))
: displayTitle?.trim() || resolveSessionTitle(childSession, childTitleFallback);
const headerModelName = childKind === 'subagent' ? childSession?.config?.modelName?.trim() : undefined;
const [projectSession] = useState(createSessionVirtualItemProjector);
const [projectSession] = useState(() => createSessionVirtualItemProjector({ reuseSnapshotsAcrossMounts: true }));
const sessionVirtualItems = useMemo(
() => projectSession(childSession ?? null),
[childSession, projectSession],
Expand Down
Loading
Loading