diff --git a/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorArea.test.tsx b/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorArea.test.tsx index dd9482336d..589a956eb4 100644 --- a/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorArea.test.tsx +++ b/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorArea.test.tsx @@ -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(), useTranslation: () => ({ t: (key: string) => key }), })); -vi.mock('../../base/FlexiblePanel', () => ({ default: () => null })); +vi.mock('../../base/FlexiblePanel', () => ({ + default: ({ content, isActive }: { content: { title: string }; isActive: boolean }) => ( + + ), +})); // Exercise real groups, tab bars and toolbar registration without mounting editors. describe('split canvas tab placement', () => { @@ -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!; } @@ -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('[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(''); + }); }); diff --git a/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.scss b/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.scss index 671728ca53..7595d913d2 100644 --- a/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.scss +++ b/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.scss @@ -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; diff --git a/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.tsx b/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.tsx index 8b9a692052..cd0f8845df 100644 --- a/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.tsx +++ b/src/web-ui/src/app/components/panels/content-canvas/editor-area/EditorGroup.tsx @@ -288,33 +288,43 @@ export const EditorGroup: React.FC = ({
{/* Render cached tabs (active shown, others hidden) for instant switching */} {tabsToRender.length > 0 ? ( - tabsToRender.map((tab) => ( -
- onTabFileDeletedFromDiskChange(tab.id, missing) - : undefined - } - onInteraction={onInteraction} - workspacePath={workspacePath} - terminalResizeSuspended={terminalResizeSuspended} - resizeSuspended={resizeSuspended} - /> -
- )) + tabsToRender.map((tab) => { + const isSelected = effectiveActiveTabId === tab.id; + const keepHiddenLayout = !isSelected && ( + tab.content.type === 'code-editor' || tab.content.type === 'diff-code-editor' + ); + return ( +
+ onTabFileDeletedFromDiskChange(tab.id, missing) + : undefined + } + onInteraction={onInteraction} + workspacePath={workspacePath} + terminalResizeSuspended={terminalResizeSuspended} + resizeSuspended={resizeSuspended} + /> +
+ ); + }) ) : visibleTabs.length === 0 ? (
diff --git a/src/web-ui/src/app/scenes/settings/SettingsNav.test.tsx b/src/web-ui/src/app/scenes/settings/SettingsNav.test.tsx index 94e91b73a4..5daf9fb8ef 100644 --- a/src/web-ui/src/app/scenes/settings/SettingsNav.test.tsx +++ b/src/web-ui/src/app/scenes/settings/SettingsNav.test.tsx @@ -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; @@ -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', @@ -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 }), })); @@ -57,8 +57,27 @@ 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(); @@ -66,7 +85,7 @@ describe('SettingsNav shared component composition', () => { container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container); - act(() => root.render()); + act(() => root.render()); }); afterEach(() => { @@ -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); @@ -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('[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({ diff --git a/src/web-ui/src/app/scenes/settings/SettingsNav.tsx b/src/web-ui/src/app/scenes/settings/SettingsNav.tsx index 01c65d44a9..0a7af86ead 100644 --- a/src/web-ui/src/app/scenes/settings/SettingsNav.tsx +++ b/src/web-ui/src/app/scenes/settings/SettingsNav.tsx @@ -18,6 +18,7 @@ import type { i18n as I18nApi } from 'i18next'; import React, { useCallback, useEffect, + useLayoutEffect, useMemo, useRef, useState, @@ -108,6 +109,38 @@ function buildSettingsSearchIndex(t: SettingsT, i18n: I18nApi): SettingsSearchRo }); } +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], + ); +} + function highlightFirstMatch(text: string, query: string): React.ReactNode { const needle = query.trim(); if (!needle) return text; @@ -139,6 +172,7 @@ const SettingsNav: React.FC = () => { 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(null); const resultsRef = useRef(null); @@ -152,11 +186,14 @@ const SettingsNav: React.FC = () => { }, []); 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 []; diff --git a/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx b/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx index 0e630a6cf2..4885961150 100644 --- a/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx +++ b/src/web-ui/src/flow_chat/components/btw/BtwSessionPanel.tsx @@ -229,7 +229,7 @@ const BtwSessionPanelContent: React.FC createSessionVirtualItemProjector({ reuseSnapshotsAcrossMounts: true })); const sessionVirtualItems = useMemo( () => projectSession(childSession ?? null), [childSession, projectSession], diff --git a/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts index db44b8f41e..a7fc153412 100644 --- a/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/modernFlowChatStore.test.ts @@ -220,6 +220,40 @@ describe('incremental projection cache contracts', () => { expect(projectSession(peer)).toBe(peerItems); }); + it('reuses the same snapshot across BTW remounts and rebuilds after history is trimmed', () => { + const completed = makeSession().dialogTurns[0]; + const session = processingSession([makeRound()]); + const streaming = { ...session.dialogTurns[0], id: 'streaming' }; + session.dialogTurns = [completed, streaming]; + + const mountProjector = () => createSessionVirtualItemProjector({ reuseSnapshotsAcrossMounts: true }); + const before = mountProjector()(session); + const reopened = mountProjector(); + expect(reopened({ ...session, title: 'Renamed while hidden' })).toBe(before); + + const trimmed = { ...session, dialogTurns: [streaming], isPartial: true, totalTurnCount: 2 }; + const after = reopened(trimmed); + expect(after).not.toBe(before); + expect(after.every(item => item.turnId === streaming.id)).toBe(true); + expect(after[0]).toMatchObject({ absoluteTurnIndex: 2 }); + expect(mountProjector()(trimmed)).toBe(after); + + const expanded = mountProjector()({ ...trimmed, totalTurnCount: 3 }); + expect(expanded[0]).toMatchObject({ absoluteTurnIndex: 3 }); + }); + + it('does not reuse another surface snapshot with an equal session id', () => { + const local = makeSession(); + const peer = makeSession(); + peer.dialogTurns[0].userMessage.content = 'Peer prompt'; + const mountProjector = () => createSessionVirtualItemProjector({ reuseSnapshotsAcrossMounts: true }); + const localItems = mountProjector()(local); + const peerItems = mountProjector()(peer); + expect(peerItems[0]).toMatchObject({ data: { content: 'Peer prompt' } }); + expect(mountProjector()(local)).toBe(localItems); + expect(mountProjector()(peer)).toBe(peerItems); + }); + it('invalidates cached warm sessions when the presentation store is cleared', () => { const session = makeSession(); const store = createModernFlowChatStore(session); diff --git a/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts b/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts index 0f9f170516..d2ecf406ca 100644 --- a/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/modernFlowChatStore.ts @@ -146,6 +146,7 @@ function isStableTurnProjection(turn: DialogTurn): boolean { } interface SessionProjectionCache { + sessionId: Session['sessionId']; turnCatalogRef: Session['turnCatalog'] | undefined; isPartial: boolean | undefined; totalTurnCount: number | undefined; @@ -153,6 +154,9 @@ interface SessionProjectionCache { virtualItems: VirtualItem[]; } +// A retained projection stays reachable only while its source turn array does. +const retainedSessionProjections = new WeakMap(); + // Settled source Turns can be shared by live, history and side views without // making any one view the owner of another view's streaming state or body. type StableTurnPresentation = 'background' | 'normal'; @@ -417,11 +421,15 @@ function projectTurnItemsWithPrefixCache( return reconciled; } -/** Each mounted projection owns its mutable streaming prefix and warm snapshots. */ -export function createSessionVirtualItemProjector(): (session: Session | null) => VirtualItem[] { +/** Each mounted projection owns its mutable streaming prefix. */ +export function createSessionVirtualItemProjector( + { reuseSnapshotsAcrossMounts = false }: { reuseSnapshotsAcrossMounts?: boolean } = {}, +): (session: Session | null) => VirtualItem[] { let sessionId: string | null = null; let previousProjection: SessionProjectionCache | undefined; - let warmProjections = new WeakMap(); + let warmProjections = reuseSnapshotsAcrossMounts + ? retainedSessionProjections + : new WeakMap(); const cachedTurnPrefixById = new Map(); const emptyItems: VirtualItem[] = []; @@ -429,7 +437,7 @@ export function createSessionVirtualItemProjector(): (session: Session | null) = if (!session) { sessionId = null; previousProjection = undefined; - warmProjections = new WeakMap(); + if (!reuseSnapshotsAcrossMounts) warmProjections = new WeakMap(); cachedTurnPrefixById.clear(); return emptyItems; } @@ -437,6 +445,7 @@ export function createSessionVirtualItemProjector(): (session: Session | null) = sessionId = session.sessionId; const restored = warmProjections.get(session.dialogTurns); if (restored + && restored.sessionId === session.sessionId && restored.turnCatalogRef === session.turnCatalog && restored.isPartial === session.isPartial && restored.totalTurnCount === session.totalTurnCount @@ -455,6 +464,7 @@ export function createSessionVirtualItemProjector(): (session: Session | null) = const items = projectSessionItems(session, cachedTurnPrefixById); const projection = { + sessionId: session.sessionId, turnCatalogRef: session.turnCatalog, isPartial: session.isPartial, totalTurnCount: session.totalTurnCount,