Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
63 changes: 62 additions & 1 deletion packages/web-shell/client/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -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 () => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
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<HTMLButtonElement>('[data-testid="open-split-view"]')
?.click();
await Promise.resolve();
});
await act(async () => {
container
.querySelector<HTMLButtonElement>('[data-testid="split-report-panes"]')
?.click();
await Promise.resolve();
});

// Leave the split (back to the overview)…
await act(async () => {
container
.querySelector<HTMLButtonElement>('[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<HTMLButtonElement>('[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 {
Expand Down
41 changes: 32 additions & 9 deletions packages/web-shell/client/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
// An explicit selection (the overview, or a `?split=` URL) replaces the
Comment thread
wenshao marked this conversation as resolved.
Resolved
// 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;
Comment thread
wenshao marked this conversation as resolved.
Resolved
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.
Expand Down Expand Up @@ -4577,6 +4592,14 @@ export function App({
<CompactModeContext.Provider value={compactMode}>
<SplitView
initialSessionIds={splitSessionIds}
// Mirror live pane add/remove back up so switching away
// and re-entering restores the same panes. Pass the
// setter directly — a fresh arrow each render would loop
// SplitView's reporting effect.
onPanesChange={setSplitSessionIds}
// Refresh the "add pane" picker when the session list
// changes elsewhere, matching the sidebar.
sessionListReloadToken={sessionListReloadToken}
// Back returns to the Session Overview (the hub the split
// is launched from), not the single-session chat.
onExit={handleSplitExit}
Expand Down
108 changes: 107 additions & 1 deletion packages/web-shell/client/components/SplitView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as React from 'react';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nProvider } from '../i18n';
Expand All @@ -15,6 +16,9 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
/* eslint-disable @typescript-eslint/no-explicit-any */
let connectionState: any;
let sessionsState: any[];
// Stable across renders (assigned once per test) so SplitView's reload effects,
// which depend on `reload`'s identity, don't re-fire on every render.
let reloadMock: ReturnType<typeof vi.fn>;

vi.mock('@qwen-code/webui/daemon-react-sdk', () => ({
DaemonSessionProvider: (props: any) => (
Expand All @@ -23,7 +27,18 @@ vi.mock('@qwen-code/webui/daemon-react-sdk', () => ({
</div>
),
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<any[]>(() => sessionsState);
const reload = React.useCallback(async () => {
reloadMock();
setSessions([...sessionsState]);
return sessionsState;
}, []);
return { sessions, reload };
},
}));

vi.mock('./ChatPane', () => ({
Expand Down Expand Up @@ -60,6 +75,7 @@ beforeEach(() => {
{ sessionId: 's3', workspaceCwd: '/w', displayName: 'Three' },
{ sessionId: 's4', workspaceCwd: '/w', displayName: 'Four' },
];
reloadMock = vi.fn();
});

afterEach(() => {
Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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)', () => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
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(
<I18nProvider language="en">
<SplitView
onExit={() => {}}
initialSessionIds={['s1']}
sessionListReloadToken={1}
/>
</I18nProvider>,
),
);
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']);
});
});
55 changes: 54 additions & 1 deletion packages/web-shell/client/components/SplitView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -39,8 +53,10 @@ export interface SplitViewProps {
*/
export function SplitView({
initialSessionIds,
onPanesChange,
onExit,
onError,
sessionListReloadToken,
}: SplitViewProps) {
const { t } = useI18n();
const connection = useConnection();
Expand All @@ -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',
Expand Down Expand Up @@ -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(() => {
Comment thread
wenshao marked this conversation as resolved.
Resolved
if (pickerOpen) void reload();
Comment thread
wenshao marked this conversation as resolved.
Resolved
}, [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.
// Skip while a reload is already in flight: a burst of session changes (bulk
// create/delete) bumps the token repeatedly, and we don't want a redundant
// concurrent round-trip per bump. `useDaemonResource` already discards stale
// responses via its sequence counter; this just avoids the wasted requests.
const reloadInFlightRef = useRef(false);
const prevReloadTokenRef = useRef(sessionListReloadToken);
useEffect(() => {
if (
sessionListReloadToken !== undefined &&
sessionListReloadToken !== prevReloadTokenRef.current &&
!reloadInFlightRef.current
Comment thread
wenshao marked this conversation as resolved.
Resolved
) {
prevReloadTokenRef.current = sessionListReloadToken;
reloadInFlightRef.current = true;
void Promise.resolve(reload()).finally(() => {
reloadInFlightRef.current = false;
});
}
}, [sessionListReloadToken, reload]);

const titleById = useMemo(() => {
const map = new Map<string, string>();
for (const session of sessions) {
Expand Down Expand Up @@ -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));
}, []);
Expand Down
Loading