diff --git a/packages/web-shell/client/App.test.tsx b/packages/web-shell/client/App.test.tsx index d02b4b6282d..3f95fc2611e 100644 --- a/packages/web-shell/client/App.test.tsx +++ b/packages/web-shell/client/App.test.tsx @@ -352,10 +352,30 @@ mockComponent('./components/SessionOverviewPanel', 'SessionOverviewPanel'); vi.doMock('./components/SplitView', async () => { const React = await import('react'); return { - SplitView: (props: { onExit?: () => void }) => + SplitView: (props: { + onExit?: () => void; + initialSessionIds?: string[]; + onPanesChange?: (ids: string[]) => void; + }) => React.createElement( 'div', { 'data-testid': 'split-view-mock' }, + // Surface the seed so a test can assert the App preserved / restored it. + React.createElement( + 'span', + { 'data-testid': 'split-initial' }, + (props.initialSessionIds ?? []).join(','), + ), + // Simulate the real SplitView reporting its live pane set up to the App. + React.createElement( + 'button', + { + 'data-testid': 'split-report-panes', + type: 'button', + onClick: () => props.onPanesChange?.(['s1', 's2', 's3']), + }, + 'report', + ), React.createElement( 'button', { 'data-testid': 'split-back', type: 'button', onClick: props.onExit }, @@ -1032,6 +1052,47 @@ describe('App session callbacks', () => { expect(panel?.getAttribute('aria-label')).toBe('Session Overview'); }); + it('preserves the pane set when leaving the split view and reopening it', async () => { + const { container } = renderApp(); + await flush(); + + // Open the split, then let SplitView report a live pane set (s1,s2,s3) back + // to the App — the same way real add/remove mirrors up via onPanesChange. + await act(async () => { + container + .querySelector('[data-testid="open-split-view"]') + ?.click(); + await Promise.resolve(); + }); + await act(async () => { + container + .querySelector('[data-testid="split-report-panes"]') + ?.click(); + await Promise.resolve(); + }); + + // Leave the split (back to the overview)… + await act(async () => { + container + .querySelector('[data-testid="split-back"]') + ?.click(); + await Promise.resolve(); + }); + expect(container.querySelector('[data-testid="split-view-page"]')).toBeNull(); + + // …and reopen it from the toolbar. The reported panes must be restored, not + // reset to empty / the current session (the regression this guards). + await act(async () => { + container + .querySelector('[data-testid="open-split-view"]') + ?.click(); + await Promise.resolve(); + }); + expect( + container.querySelector('[data-testid="split-initial"]')?.textContent, + ).toBe('s1,s2,s3'); + }); + it('enters the split view from a ?split= URL and consumes the param', async () => { window.history.pushState({}, '', '/?split=s1,s2'); try { @@ -1047,6 +1108,22 @@ describe('App session callbacks', () => { } }); + it('seeds the split from a ?split= URL, deduping and capping the explicit selection', async () => { + // Duplicates and more than MAX_SPLIT_PANES (6) ids drive the explicit- + // selection branch of openSplitView (dedupe + cap + replace), distinct from + // the no-selection restore branch covered above. + window.history.pushState({}, '', '/?split=s1,s1,s2,s3,s4,s5,s6,s7'); + try { + const { container } = renderApp(); + await flush(); + expect( + container.querySelector('[data-testid="split-initial"]')?.textContent, + ).toBe('s1,s2,s3,s4,s5,s6'); + } finally { + window.history.pushState({}, '', '/'); + } + }); + it('keeps the split view open when an approval becomes pending (unlike the scheduled-tasks page)', async () => { // Each split pane owns its own session's approval, so an approval on the // outer main session must NOT yank the user out of the split. diff --git a/packages/web-shell/client/App.tsx b/packages/web-shell/client/App.tsx index 48fb51a18d4..687db49d3fb 100644 --- a/packages/web-shell/client/App.tsx +++ b/packages/web-shell/client/App.tsx @@ -68,7 +68,7 @@ import { DaemonStatusDialog } from './components/dialogs/DaemonStatusDialog'; import { SessionOverviewPanel } from './components/SessionOverviewPanel'; import { SplitView } from './components/SplitView'; import { useIsLargeScreen } from './hooks/useIsLargeScreen'; -import { parseSplitSessionIds } from './utils/splitUrl'; +import { MAX_SPLIT_PANES, parseSplitSessionIds } from './utils/splitUrl'; import { ScheduledTasksDialog } from './components/dialogs/ScheduledTasksDialog'; import { ExtensionsDialog } from './components/dialogs/ExtensionsDialog'; import { SettingsMessage } from './components/messages/SettingsMessage'; @@ -1237,14 +1237,29 @@ export function App({ setActivePanel(null); setMainView('scheduledTasks'); }, []); - // Open the in-window split view showing 2+ sessions side by side. Seeds with - // the given sessions (e.g. the overview selection); SplitView falls back to - // the current session when the list is empty. - const openSplitView = useCallback((sessionIds?: string[]) => { - setActivePanel(null); - setSplitSessionIds(sessionIds ?? []); - setMainView('split'); - }, []); + // Open the in-window split view showing 2+ sessions side by side. `splitSessionIds` + // is the live pane set — SplitView mirrors add/remove back into it via + // onPanesChange — so it must be preserved across entries, not blindly reset. + const openSplitView = useCallback( + (sessionIds?: string[]) => { + setActivePanel(null); + setSplitSessionIds((prev) => { + // An explicit selection (the overview, or a `?split=` URL) replaces the + // split with exactly those sessions. + const requested = Array.from( + new Set((sessionIds ?? []).filter(Boolean)), + ).slice(0, MAX_SPLIT_PANES); + if (requested.length > 0) return requested; + // No selection (the toolbar "Open Split View" button): restore the split + // the user already had so switching away and back doesn't clear it; fall + // back to the current session when there is nothing to restore. + if (prev.length > 0) return prev; + return connection.sessionId ? [connection.sessionId] : []; + }); + setMainView('split'); + }, + [connection.sessionId], + ); // Stable so SplitView's onExit-dependent effect (auto-exit on last pane // close) doesn't re-fire on every App re-render. Back from the split returns // to the Session Overview — the hub the split is launched from. @@ -4577,6 +4592,14 @@ export function App({ ; vi.mock('@qwen-code/webui/daemon-react-sdk', () => ({ DaemonSessionProvider: (props: any) => ( @@ -23,7 +27,18 @@ vi.mock('@qwen-code/webui/daemon-react-sdk', () => ({ ), useConnection: () => connectionState, - useSessions: () => ({ sessions: sessionsState }), + // Stateful, like the real hook: reload() re-renders with the CURRENT module + // store. This lets a test prove the picker renders sessions that appeared + // only after the reload — not merely that reload() was called. + useSessions: () => { + const [sessions, setSessions] = React.useState(() => sessionsState); + const reload = React.useCallback(async () => { + reloadMock(); + setSessions([...sessionsState]); + return sessionsState; + }, []); + return { sessions, reload }; + }, })); vi.mock('./ChatPane', () => ({ @@ -60,6 +75,7 @@ beforeEach(() => { { sessionId: 's3', workspaceCwd: '/w', displayName: 'Three' }, { sessionId: 's4', workspaceCwd: '/w', displayName: 'Four' }, ]; + reloadMock = vi.fn(); }); afterEach(() => { @@ -90,6 +106,19 @@ function titles(): string[] { (el) => el.textContent ?? '', ); } +function pickerOptions(): string[] { + return Array.from( + container!.querySelectorAll('[role="option"] button'), + ).map((el) => (el.textContent ?? '').trim()); +} +function openPicker(): void { + const addButton = container!.querySelector( + 'button[aria-haspopup="listbox"]', + ) as HTMLButtonElement; + act(() => + addButton.dispatchEvent(new MouseEvent('click', { bubbles: true })), + ); +} describe('SplitView', () => { it('renders one pane per initial session, each under its own provider', () => { @@ -243,4 +272,81 @@ describe('SplitView', () => { expect(panes()).toHaveLength(1); expect(titles()).toEqual(['Two']); }); + + it('reloads the session list when the picker opens (never a stale list)', () => { + render({ initialSessionIds: ['s1'] }); + // `useSessions` only fetches on mount; nothing reloads until the user acts. + expect(reloadMock).not.toHaveBeenCalled(); + const addButton = container!.querySelector( + 'button[aria-haspopup="listbox"]', + ) as HTMLButtonElement; + act(() => + addButton.dispatchEvent(new MouseEvent('click', { bubbles: true })), + ); + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + + it('renders the refreshed session list on reopen — not the entry snapshot', () => { + render({ initialSessionIds: ['s1'] }); + // First open: the picker offers the sessions present at entry. + openPicker(); + expect(pickerOptions()).toEqual(['Two', 'Three', 'Four']); + // A session is created elsewhere after the split was entered… + sessionsState = [ + ...sessionsState, + { sessionId: 's5', workspaceCwd: '/w', displayName: 'Five' }, + ]; + // …reopening the picker reloads and the new session now appears. Without the + // reload-on-open the list would be frozen at the entry snapshot (no 'Five'). + act(() => + document.dispatchEvent( + new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }), + ), + ); + openPicker(); + expect(pickerOptions()).toEqual(['Two', 'Three', 'Four', 'Five']); + }); + + it('reloads the picker list when the parent bumps the reload token', () => { + render({ initialSessionIds: ['s1'], sessionListReloadToken: 0 }); + // The initial token is not a change, so it does not trigger a reload. + expect(reloadMock).not.toHaveBeenCalled(); + act(() => + root!.render( + + {}} + initialSessionIds={['s1']} + sessionListReloadToken={1} + /> + , + ), + ); + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + + it('mirrors the live pane set up to the parent as panes change', () => { + const onPanesChange = vi.fn(); + render({ initialSessionIds: ['s1'], onPanesChange }); + // Reported on mount so the parent's seed reflects the actual panes… + expect(onPanesChange).toHaveBeenLastCalledWith(['s1']); + // …and after every add (so switching away and back restores it). + const addButton = container!.querySelector( + 'button[aria-haspopup="listbox"]', + ) as HTMLButtonElement; + act(() => + addButton.dispatchEvent(new MouseEvent('click', { bubbles: true })), + ); + const options = container!.querySelectorAll('[role="option"] button'); + act(() => + options[0].dispatchEvent(new MouseEvent('click', { bubbles: true })), + ); + expect(onPanesChange).toHaveBeenLastCalledWith(['s1', 's2']); + // …and after every remove. + const close = container!.querySelector('[data-testid="pane-close"]'); + act(() => + close!.dispatchEvent(new MouseEvent('click', { bubbles: true })), + ); + expect(onPanesChange).toHaveBeenLastCalledWith(['s2']); + }); }); diff --git a/packages/web-shell/client/components/SplitView.tsx b/packages/web-shell/client/components/SplitView.tsx index 5379b5658c3..898ad428d5f 100644 --- a/packages/web-shell/client/components/SplitView.tsx +++ b/packages/web-shell/client/components/SplitView.tsx @@ -25,9 +25,23 @@ const MAX_PANES = MAX_SPLIT_PANES; export interface SplitViewProps { /** Sessions to open initially (e.g. the selection from the overview). */ initialSessionIds?: string[]; + /** + * Report the live pane set (after every add / remove) up to the parent so it + * survives this view unmounting. Switching away from the split and back must + * restore exactly the panes the user had, not reseed from a stale selection. + * Must be referentially stable (e.g. a `useState` setter) — a fresh callback + * each render would re-fire the reporting effect and loop. + */ + onPanesChange?: (sessionIds: string[]) => void; /** Leave the split view (back to the single-session chat). */ onExit: () => void; onError?: (error: unknown, fallback: string) => void; + /** + * Bumped by the parent whenever the session list changes elsewhere (create / + * delete / rename). The "add pane" picker reloads on a change so it never + * offers a session that has since been removed or misses one just created. + */ + sessionListReloadToken?: number; } /** @@ -39,8 +53,10 @@ export interface SplitViewProps { */ export function SplitView({ initialSessionIds, + onPanesChange, onExit, onError, + sessionListReloadToken, }: SplitViewProps) { const { t } = useI18n(); const connection = useConnection(); @@ -49,7 +65,7 @@ export function SplitView({ connection.capabilities?.features?.includes( SESSION_ORGANIZATION_FEATURE, ) ?? false; - const { sessions } = useSessions({ + const { sessions, reload } = useSessions({ autoLoad: true, pageSize: SESSION_LIST_PAGE_SIZE, archiveState: 'active', @@ -93,6 +109,36 @@ export function SplitView({ }; }, [pickerOpen]); + // Refresh the list the moment the picker opens — `useSessions` only fetches on + // mount, so without this the picker would offer whatever was current when the + // split was first entered, missing sessions created since. + useEffect(() => { + if (pickerOpen) void reload(); + }, [pickerOpen, reload]); + + // Also refresh when the parent signals the list changed elsewhere (a session + // created / deleted / renamed in the sidebar or another tab), so an open + // picker — or the next open — reflects it without re-entering the split. + // Reload on every distinct token bump. `useDaemonResource` serializes + // responses via its sequence counter (last write wins), so overlapping reloads + // are safe; and the token is bumped only on discrete session-change events + // (App fires an immediate bump plus one delayed follow-up per change), not as a + // high-frequency stream. Deliberately *not* skipping while a reload is in + // flight: doing so would drop a bump that lands mid-reload — the effect has + // already run for that value and clearing an in-flight flag wouldn't re-run it, + // so the picker could stay stale after a burst. An occasional redundant fetch + // is far cheaper than a lost refresh, and the split has no polling fallback. + const prevReloadTokenRef = useRef(sessionListReloadToken); + useEffect(() => { + if ( + sessionListReloadToken !== undefined && + sessionListReloadToken !== prevReloadTokenRef.current + ) { + prevReloadTokenRef.current = sessionListReloadToken; + void reload(); + } + }, [sessionListReloadToken, reload]); + const titleById = useMemo(() => { const map = new Map(); for (const session of sessions) { @@ -125,6 +171,13 @@ export function SplitView({ } }, [paneIds, onExit]); + // Mirror the live pane set up to the parent so it outlives this component + // unmounting when the user switches views. On re-entry the parent reseeds + // `initialSessionIds` from it, restoring the exact panes instead of clearing. + useEffect(() => { + onPanesChange?.(paneIds); + }, [paneIds, onPanesChange]); + const removePane = useCallback((sessionId: string) => { setPaneIds((prev) => prev.filter((id) => id !== sessionId)); }, []);