Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(workbench): retain new-session flow across Settings (#2050)

Max2e35d109f0f5
diff --git a/ui/e2e/home-media/README.md b/ui/e2e/home-media/README.md
index 4d4b641b5..f85c8d212 100644
--- a/ui/e2e/home-media/README.md
+++ b/ui/e2e/home-media/README.md
@@ -55,3 +55,37 @@ in dark/light Chinese/English under `e2e/.artifacts/home-media/`.
Production authentication/transcription and the integrated standalone Settings
shell remain for the orchestrator's authorized acceptance pass. The fixture is
interaction evidence, not live backend or cloud acceptance.
+
+## Settings suspension follow-up
+
+The follow-up branch starts from merged master (including PRs #2047/#2045),
+under execution-contract amendments 10:06, 10:13 and 10:54, reference
+`824544d91`. Its production change consumes the existing route activity context;
+C's AppShell must keep the NewSessionSheet owner mounted, preserve logical
+`open={newSessionOpen}` and provide `active={!settingsOpen}`. The lane's shell
+producer is a test fixture, not C's implementation; full B+C acceptance remains
+separate.
+
+The sheet's existing pendingDraft now survives modal-content unmounts. A true
+close invalidates old Composer callbacks; Settings only removes foreground
+presentation. The existing useNewSession checks still stop a create/upload
+completion before the next POST while inactive. A POST already admitted can
+finish: the sheet holds its successful result and uses the current navigator
+once on return, or preserves the retry/error/uncertainty state. No automatic
+resubmission and no replay state are introduced.
+
+DirectoryBrowser retains unconfirmed paths, history, manual-path input and
+new-folder text while withdrawing its modal and global keyboard/focus effects.
+NewProjectDialog retains confirmation state and alone owns deferred project
+completion for all callers. A successful or authorization-fenced null result
+is delivered through the current callback only after foreground returns. A
+cancelled or unmounted dialog cannot reopen an obsolete flow.
+
+`sheet-suspension.spec.ts` drives the actual sheet, project dialog and directory
+picker through the frozen shell producer shape. Alt+S is a fixture-only route
+entry (the real sheet has no Settings button); all other input, selection,
+submit, close, keyboard and return actions use real components. It exercises
+Unicode state, 390/1366px, accepted/rejected/uncertain network completion,
+pre-POST suspension, true close/fresh reopen, project creation success/failure/
+cancel and retained directory inputs. Unexpected requests fail the fixture;
+all external traffic is refused.
diff --git a/ui/e2e/home-media/fixture.tsx b/ui/e2e/home-media/fixture.tsx
index 1fe061beb..3031bbae2 100644
--- a/ui/e2e/home-media/fixture.tsx
+++ b/ui/e2e/home-media/fixture.tsx
@@ -1,4 +1,4 @@
-import { StrictMode, useState } from 'react';
+import { StrictMode, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { createHashRouter, RouterProvider, Route, useLocation, useNavigate, useParams } from 'react-router-dom';
import { ApiProvider } from '../../src/context/ApiContext';
@@ -6,6 +6,7 @@ import { WorkbenchProjectsProvider } from '../../src/context/WorkbenchProjectsPr
import { InstanceAuthorizationContext } from '../../src/context/InstanceAuthorizationContext';
import { ToastProvider } from '../../src/context/ToastProvider';
import { SettingsOverlayRouteSurface } from '../../src/components/settings/SettingsOverlayRouteSurface';
+import { RouteSurfaceActivityBoundary } from '../../src/components/RouteSurfaceActivityBoundary';
import { NewSessionSheet } from '../../src/components/workbench/NewSessionSheet';
import { UnsavedChangesProvider } from '../../src/context/UnsavedChangesProvider';
import { Workbench } from '../../src/components/Workbench';
@@ -17,11 +18,13 @@ import '../../src/index.css';
const params = new URLSearchParams(location.search);
void i18n.changeLanguage(params.get('lang') ?? 'en');
document.documentElement.dataset.theme = params.get('theme') === 'light' ? 'light' : 'dark';
-const projects = [{
+const firstProject = {
id: 'project-中文', scope_id: 'scope-中文', display_name: '中文项目', folder_path: '/fixture/中文项目',
created_at: '2026-09-01T00:00:00Z', last_active_at: null, archived: false,
capabilities: { can_chat: true, has_folder: true },
-}];
+};
+const projects = params.has('empty') ? [] : [firstProject];
+if (params.has('twoProjects')) projects.push({ ...firstProject, id: 'project-second', scope_id: 'scope-second', display_name: '第二个项目', folder_path: '/fixture/第二个项目' });
const agents = ['codex', 'claude'].map((name) => ({ id: `agent-${name}`, name, display_name: name, backend: name, enabled: true, archived: false, model: null }));
type Write = { path: string; body: Record<string, unknown> };
const writes: Write[] = [];
@@ -29,13 +32,26 @@ const sessions: Array<Record<string, unknown>> = [];
const uploads = new Map<string, { sessionId: string; token: string }>();
const control = {
writes,
+ unexpectedRequests: [] as string[],
uploadFailures: 0,
uploadTerminal: false,
messageTerminal: 0,
messageMode: 'success' as 'success' | 'rejected' | 'unknown' | 'network',
holdUpload: false,
releaseUpload: () => {},
+ holdMessage: false,
+ releaseMessage: () => {},
asrFailures: 0,
+ holdCreate: false,
+ releaseCreate: () => {},
+ holdProject: false,
+ projectFailure: false,
+ releaseProject: () => {},
+ messageCompletions: 0,
+ projectCompletions: 0,
+ heldBrowsePaths: [] as string[],
+ pendingBrowses: [] as Array<{ path: string; release: () => void }>,
+ browseCompletions: [] as string[],
};
declare global { interface Window { homeMedia: typeof control } }
window.homeMedia = control;
@@ -55,14 +71,24 @@ window.fetch = async (input, init) => {
if (path === '/api/csrf-token') return reply({ csrf_token: 'fixture' });
if (path === '/api/agents') return reply({ ok: true, agents, default_agent_name: 'codex' });
if (path === '/api/projects' && init?.method === 'POST') {
- const project = { ...projects[0], id: `project-${projects.length}`, scope_id: `scope-${projects.length}`, folder_path: body.folder_path, display_name: body.display_name || body.folder_path.split('/').pop() };
+ if (control.holdProject) await new Promise<void>((resolve) => { control.releaseProject = resolve; });
+ control.projectCompletions++;
+ if (control.projectFailure) return reply({ error: 'fixture project rejected' }, 500);
+ const project = { ...firstProject, id: `project-${projects.length}`, scope_id: `scope-${projects.length}`, folder_path: body.folder_path, display_name: body.display_name || body.folder_path.split('/').pop() };
projects.push(project);
return reply(project);
}
if (path === '/api/projects' || path === '/api/workbench/projects-bootstrap') return reply({ projects, sessions: {} });
- if (path === '/api/browse') return reply({ ok: true, path: body.path || '/fixture', parent: '/fixture', dirs: [{ name: '另一个项目', path: '/fixture/另一个项目' }] });
+ if (path === '/api/browse') {
+ if (control.heldBrowsePaths.includes(body.path)) {
+ await new Promise<void>((resolve) => { control.pendingBrowses.push({ path: body.path, release: resolve }); });
+ }
+ control.browseCompletions.push(body.path);
+ return reply({ ok: true, path: body.path === '~' ? '/fixture' : body.path || '/fixture', parent: '/fixture', dirs: [{ name: '另一个项目', path: '/fixture/另一个项目' }] });
+ }
if (path === '/api/browse/favorites') return reply({ ok: true, favorites: [{ key: 'home', path: '/fixture' }] });
if (path === '/api/sessions' && init?.method === 'POST') {
+ if (control.holdCreate) await new Promise<void>((resolve) => { control.releaseCreate = resolve; });
const session = { ...body, id: `ses-${sessions.length + 1}`, status: 'active', agent_status: 'idle', created_at: '2026-09-01T00:00:00Z', updated_at: '2026-09-01T00:00:00Z', metadata: {} };
sessions.push(session);
return reply(session, 201);
@@ -84,6 +110,8 @@ window.fetch = async (input, init) => {
if (path.endsWith('/messages')) {
const attachments = (body.content?.attachments ?? []) as Array<{ token: string }>;
if (attachments.some((attachment) => uploads.get(attachment.token)?.sessionId !== path.split('/')[3])) return reply({ error: 'scope mismatch' }, 400);
+ if (control.holdMessage) await new Promise<void>((resolve) => { control.releaseMessage = resolve; });
+ control.messageCompletions++;
if (control.messageTerminal) return reply({ error: 'session unavailable' }, control.messageTerminal);
if (control.messageMode === 'network') throw new TypeError('fixture connection lost after admission');
if (control.messageMode === 'unknown') return reply({ state: 'reserved', dispatch_error: 'dispatch_pending' }, 504);
@@ -98,7 +126,8 @@ window.fetch = async (input, init) => {
}
if (path.endsWith('/connection')) return reply({ backend: path.split('/')[3], ready: true });
if (path.endsWith('/models')) return reply({ ok: true, models: [] });
- return reply({});
+ control.unexpectedRequests.push(`${init?.method ?? 'GET'} ${path}`);
+ throw new Error(`Undeclared fixture request: ${path}`);
};
export function SettingsEntry() {
@@ -111,26 +140,51 @@ export function Settings() {
return <div className="h-full bg-background p-6"><h1>Fixture Settings</h1><button onClick={() => navigate(-1)}>Back to app</button></div>;
}
export function Conversation() {
- const { sessionId } = useParams();
+ const { sessionId: routeSessionId } = useParams();
const location = useLocation();
+ const sessionId = routeSessionId ?? location.pathname.split('/').at(-1);
return <div data-testid="conversation">{sessionId}<pre data-testid="handoff">{JSON.stringify(location.state)}</pre></div>;
}
-export function SheetHarness() {
+// Test-owned producer for C's frozen shell contract: sheet state lives outside
+// route content, logical open stays true during Settings, activity alone changes.
+function SheetHarness() {
const [open, setOpen] = useState(false);
- return <><button onClick={() => setOpen(true)}>Open new session</button>
- <NewSessionSheet open={open} onOpen={() => setOpen(true)} onClose={() => setOpen(false)} />
+ const location = useLocation();
+ const navigate = useNavigate();
+ const settings = location.pathname.startsWith('/settings');
+ useEffect(() => {
+ const entry = (event: KeyboardEvent) => {
+ if (event.altKey && event.code === 'KeyS') {
+ event.preventDefault();
+ navigate('/settings/general');
+ }
+ };
+ window.addEventListener('keydown', entry);
+ return () => window.removeEventListener('keydown', entry);
+ }, [navigate]);
+ return <>
+ {settings ? <section data-testid="settings-foreground">
+ <h1>Fixture Settings</h1><input aria-label="Settings value" />
+ <button onClick={() => navigate(-1)}>Back to app</button>
+ <button onClick={() => setOpen(false)}>Discard suspended sheet</button>
+ </section> : location.pathname.startsWith('/chat/') ? <Conversation /> :
+ <button onClick={() => setOpen(true)}>Open new session</button>}
+ <RouteSurfaceActivityBoundary active={!settings}>
+ <NewSessionSheet open={open} onOpen={() => setOpen(true)} onClose={() => setOpen(false)} />
+ </RouteSurfaceActivityBoundary>
+ <output data-testid="sheet-logical-open">{String(open)}</output>
</>;
}
export function Fixture() {
return <InstanceAuthorizationContext.Provider value={{ remote: false, instanceKind: 'personal', instanceRole: 'owner', capabilities: OWNER_INSTANCE_CAPABILITIES }}>
<ToastProvider><ApiProvider><UnsavedChangesProvider><WorkbenchProjectsProvider>
<main className="mx-auto min-h-dvh max-w-6xl bg-background p-4 text-foreground md:p-8">
- <SettingsOverlayRouteSurface fallbackElement={<div>Missing route</div>}>
- <Route path="/" element={params.get('surface') === 'sheet' ? <SheetHarness /> : <><SettingsEntry /><Workbench /></>} />
+ {params.get('surface') === 'sheet' ? <SheetHarness /> : <SettingsOverlayRouteSurface fallbackElement={<div>Missing route</div>}>
+ <Route path="/" element={<><SettingsEntry /><Workbench /></>} />
<Route path="/chat/:sessionId" element={<Conversation />} />
<Route path="/agents" element={<div>Agents destination</div>} />
<Route path="/settings/general" element={<Settings />} />
- </SettingsOverlayRouteSurface>
+ </SettingsOverlayRouteSurface>}
</main>
</WorkbenchProjectsProvider></UnsavedChangesProvider></ApiProvider></ToastProvider>
</InstanceAuthorizationContext.Provider>;
diff --git a/ui/e2e/home-media/sheet-suspension.spec.ts b/ui/e2e/home-media/sheet-suspension.spec.ts
new file mode 100644
index 000000000..eeba891de
--- /dev/null
+++ b/ui/e2e/home-media/sheet-suspension.spec.ts
@@ -0,0 +1,414 @@
+import { expect, test, type Page } from '@playwright/test';
+import en from '../../src/i18n/en.json' with { type: 'json' };
+
+const draft = (page: Page) => page.getByPlaceholder(en.newSession.placeholder);
+const send = (page: Page) => page.getByRole('button', { name: en.chat.compose.send, exact: true });
+const writes = (page: Page, suffix: string) => page.evaluate((suffix) => window.homeMedia.writes.filter((write) => write.path.endsWith(suffix)), suffix);
+async function open(page: Page, query = '') {
+ await page.route('**/*', (route) => new URL(route.request().url()).origin === 'http://127.0.0.1:5217' ? route.continue() : route.abort());
+ await page.goto(`/e2e/home-media/fixture.html?surface=sheet${query}`);
+ await page.getByRole('button', { name: 'Open new session' }).click();
+ await expect(draft(page)).toBeEnabled();
+}
+async function settings(page: Page, history = false) {
+ // A test-owned foreground navigation shortcut models shell/external entry;
+ // B has no Settings button inside the real mobile sheet.
+ if (history) await page.goForward();
+ else await page.keyboard.press('Alt+s');
+ await expect(page.getByTestId('settings-foreground')).toBeVisible();
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ const input = page.getByRole('textbox', { name: 'Settings value' });
+ await input.fill('设置不应被后台抢走');
+ await expect(input).toBeFocused();
+ await page.keyboard.press('Alt+z');
+ await page.keyboard.press('Control+n');
+ await page.keyboard.press('Meta+n');
+ await expect(input).toBeFocused();
+ expect(await page.evaluate(() => document.body.style.pointerEvents)).not.toBe('none');
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('button', { name: 'Back to app' })).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(page.getByRole('button', { name: 'Discard suspended sheet' })).toBeFocused();
+}
+test.afterEach(async ({ page }) => {
+ expect(await page.evaluate(() => window.homeMedia.unexpectedRequests)).toEqual([]);
+});
+const back = (page: Page) => page.getByRole('button', { name: 'Back to app' }).click();
+const picker = (page: Page) => page.getByRole('dialog', { name: en.directoryBrowser.title });
+const manualPath = (page: Page) => page.getByPlaceholder(en.directoryBrowser.editPathPlaceholder);
+const resolvedPath = (page: Page) => picker(page).locator('code');
+async function openProjectPicker(page: Page) {
+ await open(page);
+ await page.getByRole('button', { name: en.newSession.newProject, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText('/fixture');
+ await expect(picker(page).getByRole('button', { name: en.directoryBrowser.select, exact: true })).toBeEnabled();
+}
+const holdBrowse = (page: Page, path: string) => page.evaluate((path) => { window.homeMedia.heldBrowsePaths.push(path); }, path);
+const pendingBrowse = (page: Page, path: string) => expect.poll(() => page.evaluate((path) => window.homeMedia.pendingBrowses.some((request) => request.path === path), path)).toBe(true);
+const releaseBrowse = (page: Page, path: string) => page.evaluate((path) => {
+ const index = window.homeMedia.pendingBrowses.findIndex((request) => request.path === path);
+ if (index < 0) throw new Error(`No held browse for ${path}`);
+ window.homeMedia.pendingBrowses.splice(index, 1)[0].release();
+ window.homeMedia.heldBrowsePaths = window.homeMedia.heldBrowsePaths.filter((held) => held !== path);
+}, path);
+const selection = (page: Page) => manualPath(page).evaluate((input: HTMLInputElement) => ({ start: input.selectionStart, end: input.selectionEnd, direction: input.selectionDirection }));
+
+for (const width of [390, 1366]) for (const suspended of [false, true]) {
+ test(`directory draft ${width}: pending browse preserves text and selection ${suspended ? 'through Settings' : 'in foreground'}`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 768 });
+ await openProjectPicker(page);
+ const destination = '/fixture/另一个项目';
+ await holdBrowse(page, destination);
+ await picker(page).getByRole('button', { name: '另一个项目', exact: true }).click();
+ await pendingBrowse(page, destination);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.editPath, exact: true }).click();
+ const text = '/未确认的路径/草稿🌱';
+ await manualPath(page).fill(text);
+ for (let index = 0; index <= text.length; index++) await page.keyboard.press('ArrowLeft');
+ await page.keyboard.press('ArrowRight');
+ await page.keyboard.press('Shift+ArrowRight');
+ await page.keyboard.press('Shift+ArrowRight');
+ const selected = await selection(page);
+ expect(selected).toMatchObject({ start: 1, end: 3 });
+ const settingsInput = page.getByRole('textbox', { name: 'Settings value' });
+ if (suspended) {
+ await settings(page);
+ await settingsInput.focus();
+ }
+ await releaseBrowse(page, destination);
+ await expect.poll(() => page.evaluate((path) => window.homeMedia.browseCompletions.includes(path), destination)).toBe(true);
+ if (suspended) {
+ await expect(settingsInput).toBeFocused();
+ await expect(picker(page)).toHaveCount(0);
+ await back(page);
+ }
+ await expect(resolvedPath(page)).toHaveText(destination);
+ await expect(manualPath(page)).toHaveValue(text);
+ await expect(manualPath(page)).toBeFocused();
+ expect(await selection(page)).toEqual(selected);
+ // An ordinary key must land at the retained selection, without refocusing
+ // or manually restoring the caret after the browse response.
+ await page.keyboard.press('x');
+ await expect(manualPath(page)).toHaveValue('/x认的路径/草稿🌱');
+
+ await page.keyboard.press('Escape');
+ await picker(page).getByRole('button', { name: en.directoryBrowser.editPath, exact: true }).click();
+ await expect(manualPath(page)).toHaveValue(destination);
+ const target = '/手动选择/最终目录';
+ await manualPath(page).fill(target);
+ await page.keyboard.press('Enter');
+ await expect(manualPath(page)).toHaveCount(0);
+ await expect(resolvedPath(page)).toHaveText(target);
+ expect((await writes(page, '/api/browse')).at(-1)?.body.path).toBe(target);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText(destination);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.forward, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText(target);
+ });
+}
+
+test('directory draft survives history and hidden refresh while an obsolete browse cannot replace a manual target', async ({ page }) => {
+ await openProjectPicker(page);
+ const start = '/fixture';
+ const destination = '/fixture/另一个项目';
+ await picker(page).getByRole('button', { name: '另一个项目', exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText(destination);
+ await holdBrowse(page, start);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
+ await pendingBrowse(page, start);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.editPath, exact: true }).click();
+ await manualPath(page).fill('/历史期间草稿');
+ await releaseBrowse(page, start);
+ await expect(resolvedPath(page)).toHaveText(start);
+ await expect(manualPath(page)).toHaveValue('/历史期间草稿');
+ await holdBrowse(page, destination);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.forward, exact: true }).click();
+ await pendingBrowse(page, destination);
+ await manualPath(page).fill('/隐藏文件刷新草稿');
+ await releaseBrowse(page, destination);
+ await expect(resolvedPath(page)).toHaveText(destination);
+ await expect(manualPath(page)).toHaveValue('/隐藏文件刷新草稿');
+ await holdBrowse(page, destination);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.hiddenFiles, exact: true }).click();
+ await pendingBrowse(page, destination);
+ const target = '/用户明确提交的路径';
+ await manualPath(page).fill(target);
+ await page.keyboard.press('Enter');
+ await expect(manualPath(page)).toHaveCount(0);
+ await expect(resolvedPath(page)).toHaveText(target);
+ await releaseBrowse(page, destination);
+ await expect(resolvedPath(page)).toHaveText(target);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText(destination);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.forward, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText(target);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.select, exact: true }).click();
+ await page.getByRole('button', { name: en.workbench.newProjectDialog.create, exact: true }).click();
+ await expect(draft(page)).toBeVisible();
+ expect((await writes(page, '/api/projects')).at(-1)?.body.folder_path).toBe(target);
+});
+
+for (const width of [390, 1366]) for (const reopen of [false, true]) test(`directory manual submit ${width} retains the ${reopen ? 'reopened' : 'newer'} draft and caret through Settings`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 768 });
+ await openProjectPicker(page);
+ await settings(page);
+ await back(page);
+ const edit = picker(page).getByRole('button', { name: en.directoryBrowser.editPath, exact: true });
+ await edit.click();
+ const submitted = '/已提交的目录';
+ await manualPath(page).fill(submitted);
+ await holdBrowse(page, submitted);
+ await page.keyboard.press('Enter');
+ await pendingBrowse(page, submitted);
+ if (reopen) {
+ await page.keyboard.press('Escape');
+ await expect(manualPath(page)).toHaveCount(0);
+ await edit.click();
+ await expect(manualPath(page)).toHaveValue('/fixture');
+ }
+ await page.keyboard.press('ControlOrMeta+a');
+ await page.keyboard.insertText('/提交后的新草稿🌱');
+ expect(await selection(page)).toMatchObject({ start: 10, end: 10 });
+ // History entry adds no key event to refresh a stale React onSelect record.
+ await settings(page, true);
+ await releaseBrowse(page, submitted);
+ await expect.poll(() => page.evaluate((path) => window.homeMedia.browseCompletions.includes(path), submitted)).toBe(true);
+ await expect(picker(page)).toHaveCount(0);
+ await back(page);
+ await expect(resolvedPath(page)).toHaveText(submitted);
+ await expect(manualPath(page)).toHaveValue('/提交后的新草稿🌱');
+ // Observe after deferred modal cleanup, before a key could repair focus.
+ await page.waitForTimeout(300);
+ await expect(manualPath(page)).toBeFocused();
+ expect(await selection(page)).toMatchObject({ start: 10, end: 10 });
+ await page.keyboard.press('x');
+ await expect(manualPath(page)).toHaveValue('/提交后的新草稿🌱x');
+ await page.keyboard.insertText('续写🌿');
+ await expect(manualPath(page)).toHaveValue('/提交后的新草稿🌱x续写🌿');
+ await page.keyboard.press('Escape');
+ await edit.click();
+ await expect(manualPath(page)).toHaveValue(submitted);
+ expect(await selection(page)).toMatchObject({ start: 0, end: submitted.length });
+ await page.keyboard.press('Escape');
+ await picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText('/fixture');
+ await picker(page).getByRole('button', { name: en.directoryBrowser.forward, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText(submitted);
+});
+
+for (const width of [390, 1366]) test(`directory selection ${width} follows text insertion, deletion and caret-only changes through repeated withdrawal`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 768 });
+ await openProjectPicker(page);
+ await settings(page);
+ await back(page);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.editPath, exact: true }).click();
+ await page.keyboard.press('ControlOrMeta+a');
+ await page.keyboard.insertText('/粘贴式输入🌱');
+ for (const edit of ['insert', 'delete', 'move', 'range'] as const) {
+ if (edit === 'delete') await page.keyboard.press('Backspace');
+ if (edit === 'move' || edit === 'range') await page.keyboard.press('ArrowLeft');
+ if (edit === 'range') await page.keyboard.press('Shift+ArrowLeft');
+ const value = await manualPath(page).inputValue();
+ const before = await selection(page);
+ expect(before.start).not.toBeNull();
+ expect(before.end).not.toBeNull();
+ if (edit === 'range') expect(before.end! - before.start!).toBeGreaterThan(0);
+ else expect(before.start).toBe(before.end);
+ await settings(page, true);
+ await back(page);
+ await page.waitForTimeout(300);
+ await expect(manualPath(page)).toBeFocused();
+ await expect(manualPath(page)).toHaveValue(value);
+ expect(await selection(page)).toEqual(before);
+ await page.keyboard.press('x');
+ const continued = `${value.slice(0, before.start!)}x${value.slice(before.end!)}`;
+ await expect(manualPath(page)).toHaveValue(continued);
+ await page.keyboard.insertText('续');
+ await expect(manualPath(page)).toHaveValue(`${value.slice(0, before.start!)}x续${value.slice(before.end!)}`);
+ }
+});
+
+for (const width of [390, 1366]) test(`sheet ${width} keeps Unicode draft and selected project/Agent while its open picker loses all modal effects`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 768 });
+ await open(page, '&twoProjects');
+ await draft(page).fill('项目乙:请检查发布 ✓');
+ await page.getByRole('button', { name: '第二个项目', exact: true }).click();
+ await page.getByRole('button', { name: /codex/ }).first().click();
+ await page.getByRole('button', { name: /^claude/ }).click();
+ await settings(page);
+ await expect(page.getByTestId('sheet-logical-open')).toHaveText('true');
+ expect(await writes(page, '/messages')).toHaveLength(0);
+ await back(page);
+ await expect(draft(page)).toHaveValue('项目乙:请检查发布 ✓');
+ await expect(page.getByRole('button', { name: /claude/ }).first()).toBeVisible();
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toContainText('ses-1');
+ expect((await writes(page, '/api/sessions'))[0].body).toMatchObject({ project_id: 'project-second', agent_name: 'claude' });
+ expect(await writes(page, '/messages')).toHaveLength(1);
+});
+
+for (const outcome of ['success', 'rejected', 'unknown', 'network'] as const) {
+ test(`admitted POST ${outcome} during Settings preserves its result without hidden navigation or automatic resend`, async ({ page }) => {
+ await open(page);
+ await draft(page).fill('只执行一次,保留结果');
+ await page.evaluate((outcome) => { window.homeMedia.holdMessage = true; window.homeMedia.messageMode = outcome; }, outcome);
+ await send(page).click();
+ await expect.poll(async () => (await writes(page, '/messages')).length).toBe(1);
+ await settings(page);
+ await page.evaluate(() => window.homeMedia.releaseMessage());
+ await expect.poll(() => page.evaluate(() => window.homeMedia.messageCompletions)).toBe(1);
+ await expect(page.getByTestId('settings-foreground')).toBeVisible();
+ await expect(page.getByTestId('sheet-logical-open')).toHaveText('true');
+ expect(await writes(page, '/messages')).toHaveLength(1);
+ await back(page);
+ if (outcome === 'success') {
+ await expect(page.getByTestId('conversation')).toContainText('ses-1');
+ await expect(page.getByTestId('sheet-logical-open')).toHaveText('false');
+ expect(await page.getByTestId('handoff').textContent()).toBe('null');
+ } else {
+ await expect(draft(page)).toHaveValue('只执行一次,保留结果');
+ if (outcome === 'rejected') {
+ await expect(send(page)).toBeEnabled();
+ await page.evaluate(() => { window.homeMedia.holdMessage = false; window.homeMedia.messageMode = 'success'; });
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toContainText('ses-1');
+ expect(await writes(page, '/api/sessions')).toHaveLength(1);
+ expect(await writes(page, '/messages')).toHaveLength(2);
+ } else {
+ await expect(send(page)).toBeDisabled();
+ await expect(page.getByRole('link', { name: en.newSession.inspectSession })).toBeVisible();
+ await settings(page);
+ await back(page);
+ await expect(send(page)).toBeDisabled();
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { name: 'Open new session' }).click();
+ await expect(draft(page)).toHaveValue('');
+ await expect(page.getByRole('link', { name: en.newSession.inspectSession })).toHaveCount(0);
+ await draft(page).fill('明确新会话');
+ await page.evaluate(() => { window.homeMedia.holdMessage = false; window.homeMedia.messageMode = 'success'; });
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toContainText('ses-2');
+ }
+ }
+ });
+}
+
+test('create completing under Settings retains its scope and waits for explicit send before POST', async ({ page }) => {
+ await open(page);
+ await draft(page).fill('创建后暂停');
+ await page.evaluate(() => { window.homeMedia.holdCreate = true; });
+ await send(page).click();
+ await expect.poll(async () => (await writes(page, '/api/sessions')).length).toBe(1);
+ await settings(page);
+ await page.evaluate(() => window.homeMedia.releaseCreate());
+ await back(page);
+ await expect(draft(page)).toHaveValue('创建后暂停');
+ await expect(send(page)).toBeEnabled();
+ expect(await writes(page, '/messages')).toHaveLength(0);
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toContainText('ses-1');
+ expect(await writes(page, '/api/sessions')).toHaveLength(1);
+});
+
+for (const timing of ['pending', 'completed'] as const) test(`actual close discards ${timing} suspended send without letting its old Composer overwrite a new draft`, async ({ page }) => {
+ await open(page);
+ await draft(page).fill('旧的发送');
+ await page.evaluate(() => { window.homeMedia.holdMessage = true; });
+ await send(page).click();
+ await expect.poll(async () => (await writes(page, '/messages')).length).toBe(1);
+ await settings(page);
+ if (timing === 'completed') {
+ await page.evaluate(() => window.homeMedia.releaseMessage());
+ await expect.poll(() => page.evaluate(() => window.homeMedia.messageCompletions)).toBe(1);
+ }
+ await page.getByRole('button', { name: 'Discard suspended sheet' }).click();
+ await back(page);
+ await page.getByRole('button', { name: 'Open new session' }).click();
+ await expect(draft(page)).toHaveValue('');
+ await draft(page).fill('新草稿不能被旧回调覆盖');
+ if (timing === 'pending') {
+ await page.evaluate(() => { window.homeMedia.messageMode = 'unknown'; window.homeMedia.releaseMessage(); });
+ await expect.poll(() => page.evaluate(() => window.homeMedia.messageCompletions)).toBe(1);
+ }
+ await expect(draft(page)).toHaveValue('新草稿不能被旧回调覆盖');
+ await expect(page.getByRole('link', { name: en.newSession.inspectSession })).toHaveCount(0);
+ await expect(send(page)).toBeEnabled();
+});
+
+async function pickFolder(page: Page) {
+ await page.getByRole('button', { name: '另一个项目', exact: true }).click();
+ await page.getByRole('button', { name: en.directoryBrowser.select, exact: true }).click();
+}
+
+test('no-project handoff preserves picker path/history/manual input and confirmation name across Settings', async ({ page }) => {
+ await open(page, '&empty');
+ await draft(page).fill('没有项目时也保留的中文任务');
+ await send(page).click();
+ await expect(page.getByRole('dialog', { name: en.directoryBrowser.title })).toBeVisible();
+ await page.getByRole('button', { name: '另一个项目', exact: true }).click();
+ await page.getByRole('button', { name: en.directoryBrowser.editPath, exact: true }).click();
+ const path = page.getByPlaceholder(en.directoryBrowser.editPathPlaceholder);
+ await path.fill('/未确认的路径/草稿');
+ await settings(page);
+ await back(page);
+ await expect(path).toHaveValue('/未确认的路径/草稿');
+ await expect(path).toBeFocused();
+ await page.keyboard.press('End');
+ await page.keyboard.insertText('/继续编辑');
+ await expect(path).toHaveValue('/未确认的路径/草稿/继续编辑');
+ await expect(page.getByPlaceholder(en.directoryBrowser.newFolderPlaceholder)).toHaveCount(0);
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { name: en.directoryBrowser.newFolder, exact: true }).click();
+ const folderName = page.getByPlaceholder(en.directoryBrowser.newFolderPlaceholder);
+ await folderName.fill('未创建文件夹');
+ await settings(page);
+ await back(page);
+ await expect(folderName).toHaveValue('未创建文件夹');
+ await expect(folderName).toBeFocused();
+ expect(await writes(page, '/api/browse/mkdir')).toHaveLength(0);
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
+ await expect(page.getByRole('button', { name: en.directoryBrowser.forward, exact: true })).toBeEnabled();
+ await page.getByRole('button', { name: en.directoryBrowser.forward, exact: true }).click();
+ await page.getByRole('button', { name: en.directoryBrowser.select, exact: true }).click();
+ const name = page.getByLabel(en.workbench.newProjectDialog.displayName, { exact: true });
+ await name.fill('保留的项目名称');
+ await settings(page);
+ await back(page);
+ await expect(name).toHaveValue('保留的项目名称');
+ await page.getByRole('button', { name: en.workbench.newProjectDialog.create, exact: true }).click();
+ await expect(draft(page)).toHaveValue('没有项目时也保留的中文任务');
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toBeVisible();
+ expect((await writes(page, '/api/projects'))[0].body).toMatchObject({ folder_path: '/fixture/另一个项目', display_name: '保留的项目名称' });
+ expect((await writes(page, '/messages'))[0].body.text).toBe('没有项目时也保留的中文任务');
+});
+
+for (const outcome of ['success', 'failure', 'cancel'] as const) test(`project create ${outcome} under Settings preserves the correct continuation`, async ({ page }) => {
+ await open(page);
+ await draft(page).fill('项目创建期间的草稿');
+ await page.getByRole('button', { name: en.newSession.newProject, exact: true }).click();
+ await pickFolder(page);
+ await page.evaluate((outcome) => { window.homeMedia.holdProject = true; window.homeMedia.projectFailure = outcome === 'failure'; }, outcome);
+ await page.getByRole('button', { name: en.workbench.newProjectDialog.create, exact: true }).click();
+ await expect.poll(async () => (await writes(page, '/api/projects')).length).toBe(1);
+ if (outcome === 'cancel') await page.getByRole('button', { name: en.workbench.newProjectDialog.cancel, exact: true }).first().click();
+ await settings(page);
+ await page.evaluate(() => window.homeMedia.releaseProject());
+ await expect.poll(() => page.evaluate(() => window.homeMedia.projectCompletions)).toBe(1);
+ await expect(page.getByTestId('sheet-logical-open')).toHaveText('false');
+ await back(page);
+ if (outcome === 'success') {
+ await expect(draft(page)).toHaveValue('项目创建期间的草稿');
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toContainText('ses-1');
+ expect((await writes(page, '/api/sessions'))[0].body.project_id).toBe('project-1');
+ } else if (outcome === 'failure') {
+ await expect(page.getByLabel(en.workbench.newProjectDialog.displayName, { exact: true })).toBeVisible();
+ await expect(page.getByRole('button', { name: en.workbench.newProjectDialog.create, exact: true })).toBeEnabled();
+ } else {
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ await expect(page.getByTestId('sheet-logical-open')).toHaveText('false');
+ }
+ expect(await writes(page, '/api/projects')).toHaveLength(1);
+});
diff --git a/ui/src/components/ui/directory-browser.tsx b/ui/src/components/ui/directory-browser.tsx
index 2a9f7d13e..d11dfa85f 100644
--- a/ui/src/components/ui/directory-browser.tsx
+++ b/ui/src/components/ui/directory-browser.tsx
@@ -1,5 +1,5 @@
import type { TranslationKey } from '@/i18n/types';
-import React, { useEffect, useState, useCallback, useRef } from 'react';
+import React, { useEffect, useState, useCallback, useLayoutEffect, useRef } from 'react';
import {
Check,
ChevronLeft,
@@ -26,6 +26,7 @@ import { useApi } from '../../context/ApiContext';
import { Button } from './button';
import { Dialog, DialogContent, DialogTitle } from './dialog';
import { errorMessage } from '@/lib/errorMessage';
+import { useRouteSurfaceActive, useRouteSurfaceWindowEvent } from '@/lib/routeSurfaceActivity';
interface DirectoryBrowserProps {
/** Initial path to show when opening */
@@ -82,6 +83,9 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
}) => {
const { t } = useTranslation();
const api = useApi();
+ const surfaceActive = useRouteSurfaceActive();
+ const foreground = useRef(surfaceActive);
+ useLayoutEffect(() => { foreground.current = surfaceActive; }, [surfaceActive]);
const [currentPath, setCurrentPath] = useState('');
// Resolved user home — captured on the first browse('~') response so the
@@ -111,6 +115,19 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
const [pathInput, setPathInput] = useState('');
const [pathError, setPathError] = useState<string | null>(null);
const pathInputRef = useRef<HTMLInputElement | null>(null);
+ const pathEditRevision = useRef(0);
+ const pathSelection = useRef<{ start: number; end: number; direction: 'forward' | 'backward' | 'none' } | null>(null);
+
+ const capturePathSelection = (input: HTMLInputElement) => {
+ // Text edits can move the caret without React firing onSelect. Capture
+ // both events, retaining the last foreground range through portal teardown.
+ if (!foreground.current || !input.isConnected || input.ownerDocument.activeElement !== input) return;
+ pathSelection.current = {
+ start: input.selectionStart ?? 0,
+ end: input.selectionEnd ?? 0,
+ direction: input.selectionDirection ?? 'none',
+ };
+ };
// OS-appropriate quick-access shortcuts, resolved + existence-checked by the
// backend (macOS Finder entries, Linux /tmp·/data·roots, Windows drives…).
@@ -126,24 +143,17 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
};
}, []);
- // Esc closes the picker, ⌘N opens the new-folder prompt — both familiar
- // shortcuts from Finder.
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'n' && !creating) {
- e.preventDefault();
- setCreating(true);
- }
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [creating, pathEditing, onClose]);
+ useRouteSurfaceWindowEvent('keydown', (event) => {
+ if (!event.defaultPrevented && (event.metaKey || event.ctrlKey)
+ && event.key.toLowerCase() === 'n' && !creating) {
+ event.preventDefault();
+ setCreating(true);
+ }
+ });
useEffect(() => {
- if (creating) {
- newFolderInputRef.current?.focus();
- }
- }, [creating]);
+ if (surfaceActive && creating) newFolderInputRef.current?.focus();
+ }, [creating, surfaceActive]);
const fetchPath = useCallback(
async (path: string, hidden?: boolean) => {
@@ -245,27 +255,48 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
}, [api]);
useEffect(() => {
- if (pathEditing) {
- // Pre-fill with the current path so the user can edit it instead
- // of typing from scratch — that's the common case.
- setPathInput(currentPath);
- setPathError(null);
+ if (pathEditing && foreground.current) {
pathInputRef.current?.focus();
pathInputRef.current?.select();
}
- }, [pathEditing, currentPath]);
+ }, [pathEditing]);
+
+ const togglePathEditing = () => {
+ if (!foreground.current) return;
+ pathEditRevision.current++;
+ if (!pathEditing) {
+ // Snapshot only when an edit begins. Later browse responses update the
+ // directory and history, not the user's unconfirmed text or selection.
+ setPathInput(currentPath);
+ setPathError(null);
+ pathSelection.current = null;
+ }
+ setPathEditing(!pathEditing);
+ };
+
+ const cancelPathEditing = () => {
+ pathEditRevision.current++;
+ setPathEditing(false);
+ };
const submitManualPath = async () => {
+ if (!foreground.current) return;
const target = pathInput.trim();
if (!target) return;
+ const editRevision = pathEditRevision.current;
setPathError(null);
- const resolved = await fetchPath(target);
+ const request = fetchPath(target);
+ const requestId = reqIdRef.current;
+ const resolved = await request;
+ if (!mountedRef.current || reqIdRef.current !== requestId) return;
if (resolved) {
// Mirror `navigate` history bookkeeping so the back arrow works.
setHistory((prev) => [...prev.slice(0, historyIndex + 1), resolved]);
setHistoryIndex((prev) => prev + 1);
- setPathEditing(false);
- } else {
+ // A submitted target may resolve after the user starts another edit.
+ // Keep its navigation result without dismissing that newer draft.
+ if (pathEditRevision.current === editRevision) setPathEditing(false);
+ } else if (pathEditRevision.current === editRevision) {
setPathError(t('directoryBrowser.pathNotFound'));
}
};
@@ -277,6 +308,7 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
};
const submitNewFolder = async () => {
+ if (!foreground.current) return;
const name = newFolderName.trim();
if (!name) return;
setCreateError(null);
@@ -327,9 +359,28 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
const canBack = historyIndex > 0;
const canForward = historyIndex < history.length - 1;
+ // Keep this owner (including unconfirmed inputs/history) mounted, while
+ // withdrawing the complete modal layer and its focus/pointer/scroll effects.
+ if (!surfaceActive) return null;
+
return (
- <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>
+ <Dialog open onOpenChange={(open) => { if (!open && foreground.current) onClose(); }}>
<DialogContent
+ onOpenAutoFocus={(event) => {
+ if (!foreground.current) { event.preventDefault(); return; }
+ // The portal mounts after its retained owner's effects. Resume the
+ // editor here, without reinitializing or selecting its draft text.
+ const editor = creating ? newFolderInputRef.current : pathEditing ? pathInputRef.current : null;
+ if (editor) {
+ event.preventDefault();
+ editor.focus();
+ if (editor === pathInputRef.current && pathSelection.current) {
+ const { start, end, direction } = pathSelection.current;
+ editor.setSelectionRange(start, end, direction);
+ }
+ }
+ }}
+ onCloseAutoFocus={(event) => { if (!foreground.current) event.preventDefault(); }}
aria-describedby={undefined}
closeLabel={t('directoryBrowser.cancel')}
onEscapeKeyDown={(event) => {
@@ -338,7 +389,7 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
setCreating(false);
setNewFolderName('');
setCreateError(null);
- setPathEditing(false);
+ cancelPathEditing();
}
}}
className="flex h-[80dvh] max-h-[720px] min-h-0 w-full max-w-3xl flex-col gap-0 overflow-hidden rounded-2xl border-border-strong bg-surface p-0 max-md:h-[90dvh] max-md:p-0 max-md:pb-0"
@@ -400,7 +451,12 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
ref={pathInputRef}
type="text"
value={pathInput}
- onChange={(e) => setPathInput(e.target.value)}
+ onChange={(event) => {
+ capturePathSelection(event.currentTarget);
+ pathEditRevision.current++;
+ setPathInput(event.currentTarget.value);
+ }}
+ onSelect={(event) => capturePathSelection(event.currentTarget)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
@@ -446,7 +502,7 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
<button
type="button"
- onClick={() => setPathEditing((prev) => !prev)}
+ onClick={togglePathEditing}
aria-label={t('directoryBrowser.editPath')}
title={t('directoryBrowser.editPath')}
className={clsx(
diff --git a/ui/src/components/workbench/NewProjectDialog.test.tsx b/ui/src/components/workbench/NewProjectDialog.test.tsx
index 49d9dece5..7c1cc166b 100644
--- a/ui/src/components/workbench/NewProjectDialog.test.tsx
+++ b/ui/src/components/workbench/NewProjectDialog.test.tsx
@@ -1,12 +1,15 @@
/* @vitest-environment jsdom */
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
-vi.mock('../../context/WorkbenchProjectsContext', () => ({ useWorkbenchProjectsActions: () => ({ createProject: vi.fn() }) }));
+const mocks = vi.hoisted(() => ({ createProject: vi.fn() }));
+vi.mock('../../context/WorkbenchProjectsContext', () => ({ useWorkbenchProjectsActions: () => mocks }));
vi.mock('../ui/directory-browser', () => ({ DirectoryBrowser: ({ initialPath, onSelect }: { initialPath?: string; onSelect: (path: string) => void }) => (
<button data-testid="directory" data-path={initialPath} onClick={() => onSelect('/工作区/选择的项目')}>select-folder</button>
) }));
import { NewProjectDialog } from './NewProjectDialog';
+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
+import type { WorkbenchProject } from '../../context/ApiContext';
afterEach(cleanup);
it.each([undefined, '/工作区/当前项目'])('starts from the caller directory (%s), then reopens the selected directory', (initialPath) => {
render(<NewProjectDialog initialPath={initialPath} onClose={() => {}} onCreated={() => {}} />);
@@ -15,3 +18,32 @@ it.each([undefined, '/工作区/当前项目'])('starts from the caller director
fireEvent.click(screen.getByText('workbench.newProjectDialog.pickFolder'));
expect(screen.getByTestId('directory').getAttribute('data-path')).toBe('/工作区/选择的项目');
});
+
+it.each(['project', 'null', 'unmount'] as const)('a suspended create %s delivers only to the current foreground owner', async (outcome) => {
+ let resolve!: (project: WorkbenchProject | null) => void;
+ mocks.createProject.mockReturnValueOnce(new Promise<WorkbenchProject | null>((done) => { resolve = done; }));
+ const oldCreated = vi.fn();
+ const latestCreated = vi.fn();
+ const closed = vi.fn();
+ const view = (active: boolean, onCreated = oldCreated) => <RouteSurfaceActiveContext.Provider value={active}>
+ <NewProjectDialog onCreated={onCreated} onClose={closed} />
+ </RouteSurfaceActiveContext.Provider>;
+ const { rerender, unmount } = render(view(true));
+ fireEvent.click(screen.getByTestId('directory'));
+ fireEvent.change(screen.getByLabelText('workbench.newProjectDialog.displayName'), { target: { value: '中文项目名称' } });
+ fireEvent.click(screen.getByRole('button', { name: 'workbench.newProjectDialog.create', exact: true }));
+ rerender(view(false));
+ if (outcome === 'unmount') unmount();
+ const project = { id: 'new-project' } as WorkbenchProject;
+ await act(async () => { resolve(outcome === 'null' ? null : project); });
+ expect(oldCreated).not.toHaveBeenCalled();
+ expect(closed).not.toHaveBeenCalled();
+ if (outcome === 'unmount') return;
+ rerender(view(true, latestCreated));
+ await waitFor(() => expect(outcome === 'null' ? closed : latestCreated).toHaveBeenCalledTimes(1));
+ rerender(view(false, latestCreated));
+ rerender(view(true, latestCreated));
+ expect(oldCreated).not.toHaveBeenCalled();
+ expect(latestCreated).toHaveBeenCalledTimes(outcome === 'null' ? 0 : 1);
+ expect(closed).toHaveBeenCalledTimes(outcome === 'null' ? 1 : 0);
+});
diff --git a/ui/src/components/workbench/NewProjectDialog.tsx b/ui/src/components/workbench/NewProjectDialog.tsx
index f354180b3..aa280847a 100644
--- a/ui/src/components/workbench/NewProjectDialog.tsx
+++ b/ui/src/components/workbench/NewProjectDialog.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Folder, FolderOpen, Loader2, X } from 'lucide-react';
@@ -8,6 +8,7 @@ import { DirectoryBrowser } from '../ui/directory-browser';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { errorMessage } from '@/lib/errorMessage';
+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
interface NewProjectDialogProps {
initialPath?: string;
@@ -27,17 +28,40 @@ interface NewProjectDialogProps {
export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onCreated, initialPath }) => {
const { t } = useTranslation();
const { createProject } = useWorkbenchProjectsActions();
+ const surfaceActive = useRouteSurfaceActive();
+ const lifetime = useRef({ mounted: true, cancelled: false, active: surfaceActive, submitting: false });
+ useLayoutEffect(() => { lifetime.current.active = surfaceActive; }, [surfaceActive]);
+ useEffect(() => {
+ const current = lifetime.current;
+ current.mounted = true;
+ return () => { current.mounted = false; };
+ }, []);
const [phase, setPhase] = useState<'pick' | 'confirm'>('pick');
const [folderPath, setFolderPath] = useState<string>('');
const [displayName, setDisplayName] = useState<string>('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [completion, setCompletion] = useState<{ project: WorkbenchProject | null } | null>(null);
+ const delivered = useRef<typeof completion>(null);
+ const close = () => {
+ if (!lifetime.current.active) return;
+ lifetime.current.cancelled = true;
+ onClose();
+ };
+ useEffect(() => {
+ if (!surfaceActive || !completion || delivered.current === completion
+ || lifetime.current.cancelled || !lifetime.current.mounted) return;
+ delivered.current = completion;
+ // A null result is the provider's authorization fence, not a new project.
+ if (completion.project) onCreated(completion.project);
+ else onClose();
+ }, [completion, onClose, onCreated, surfaceActive]);
if (phase === 'pick') {
return (
<DirectoryBrowser
initialPath={folderPath || initialPath}
- onClose={onClose}
+ onClose={close}
onSelect={(path) => {
setFolderPath(path);
setPhase('confirm');
@@ -49,7 +73,8 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onC
const folderBasename = folderPath.split('/').filter(Boolean).pop() || folderPath || '—';
const submit = async () => {
- if (!folderPath || submitting) return;
+ if (!folderPath || lifetime.current.submitting || !lifetime.current.active || lifetime.current.cancelled) return;
+ lifetime.current.submitting = true;
setSubmitting(true);
setError(null);
try {
@@ -57,26 +82,25 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onC
folder_path: folderPath,
display_name: displayName.trim() || undefined,
});
- // null = created, but an authorization change landed while we waited, so
- // this document no longer holds a tree to place it in. Just close.
- if (!project) {
- onClose();
- return;
- }
- onCreated(project);
+ if (!lifetime.current.mounted || lifetime.current.cancelled) return;
+ setCompletion({ project });
} catch (err) {
+ if (!lifetime.current.mounted || lifetime.current.cancelled) return;
+ lifetime.current.submitting = false;
setError(errorMessage(err) ?? String(err));
setSubmitting(false);
}
};
+ if (!surfaceActive || completion) return null;
+
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
role="dialog"
aria-modal="true"
aria-label={t('workbench.newProjectDialog.title')}
- onClick={onClose}
+ onClick={close}
>
<div
className="flex w-full max-w-md flex-col gap-4 rounded-2xl border border-border-strong bg-surface p-5 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.6)]"
@@ -94,7 +118,7 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onC
</div>
<button
type="button"
- onClick={onClose}
+ onClick={close}
aria-label={t('workbench.newProjectDialog.cancel')}
className="text-muted transition hover:text-foreground"
>
@@ -146,7 +170,7 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onC
)}
<div className="flex items-center justify-end gap-2">
- <Button type="button" variant="outline" size="sm" onClick={onClose} disabled={submitting}>
+ <Button type="button" variant="outline" size="sm" onClick={close} disabled={submitting}>
{t('workbench.newProjectDialog.cancel')}
</Button>
<Button
diff --git a/ui/src/components/workbench/NewSessionSheet.tsx b/ui/src/components/workbench/NewSessionSheet.tsx
index 670ae3b8b..ed2006d50 100644
--- a/ui/src/components/workbench/NewSessionSheet.tsx
+++ b/ui/src/components/workbench/NewSessionSheet.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -9,6 +9,8 @@ import { Composer } from './Composer';
import { NewProjectDialog } from './NewProjectDialog';
import { ProjectPicker } from './ProjectPicker';
import { AgentRoutePicker } from './AgentRoutePicker';
+import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';
+import type { UnsavedChangesActionAuthorization } from '../../lib/unsavedChangesRegistry';
interface NewSessionSheetProps {
open: boolean;
@@ -25,6 +27,7 @@ interface NewSessionSheetProps {
export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose, onOpen }) => {
const { t } = useTranslation();
const navigate = useNavigate();
+ const surfaceActive = useRouteSurfaceActive();
const authorizeRouteAction = useUnsavedChangesActionGuard();
// active: open → the hook reloads + resets per-open (the sheet is permanently
// mounted by AppShell, so stale submit/error state must not leak across opens).
@@ -34,59 +37,102 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
createFailedText: t('newSession.createFailed'),
errorText: t,
});
- // Stashed prompt: the no-project path closes the sheet (unmounting the
- // Composer) to create a project, so we hold the typed text and re-seed it
- // when the sheet reopens, instead of losing it.
+ // This existing stash owns text while the modal's Composer is unmounted,
+ // both for Settings suspension and the no-project handoff.
const [pendingDraft, setPendingDraft] = useState('');
const [newProjectOpen, setNewProjectOpen] = useState(false);
+ const [pendingNavigation, setPendingNavigation] = useState<{
+ sessionId: string;
+ authorization: UnsavedChangesActionAuthorization | undefined;
+ } | null>(null);
+ const [lifetime, setLifetime] = useState(0);
+ const [previousOpen, setPreviousOpen] = useState(open);
+ // A parent close invalidates old Composer callbacks too. The project detour
+ // deliberately retains its prompt; Settings does not change logical open.
+ if (previousOpen !== open) {
+ setPreviousOpen(open);
+ setLifetime(lifetime + 1);
+ setPendingNavigation(null);
+ if (!open && !newProjectOpen) setPendingDraft('');
+ }
+ const current = useRef({ open, surfaceActive, lifetime, mounted: true });
+ useLayoutEffect(() => {
+ current.current = { open, surfaceActive, lifetime, mounted: true };
+ return () => { current.current.mounted = false; };
+ }, [open, surfaceActive, lifetime]);
+ const navigationClaim = useRef<typeof pendingNavigation>(null);
const close = () => {
+ if (!current.current.surfaceActive) return;
+ setPendingNavigation(null);
setPendingDraft('');
onClose();
};
+ const updateDraft = (text: string) => {
+ if (current.current.mounted && current.current.lifetime === lifetime) setPendingDraft(text);
+ };
- // Close the sheet first, THEN open the project dialog: the parent Radix Dialog
- // traps focus/pointer to its own content, so a NewProjectDialog rendered while
- // the sheet is open would be unreachable. Sheet closed → no trap → accessible.
- const openNewProject = () => {
- // Don't tear down the sheet for project creation while a session create is
- // in flight — the pending success would still navigate, stranding the
- // project modal over the new chat.
- if (ns.sending) return;
+ // A completed POST is final even if Settings currently owns the foreground.
+ // Retain that result, then consume it once with the latest navigator on
+ // return. Never capture a pre-suspension navigator here.
+ useEffect(() => {
+ if (!open || !surfaceActive || !pendingNavigation || navigationClaim.current === pendingNavigation) return;
+ navigationClaim.current = pendingNavigation;
+ const { sessionId, authorization } = pendingNavigation;
+ const navigateToSession = () => navigate(`/chat/${encodeURIComponent(sessionId)}`);
+ if (authorization) authorization.runNavigation(navigateToSession);
+ else navigateToSession();
onClose();
+ }, [navigate, onClose, open, pendingNavigation, surfaceActive]);
+
+ // Close the sheet before opening a sibling project dialog so the old modal
+ // cannot trap pointer/focus over the new folder picker.
+ const openNewProject = () => {
+ if (!current.current.surfaceActive || ns.sending || pendingNavigation) return;
setNewProjectOpen(true);
+ onClose();
};
const send = async (text: string): Promise<boolean> => {
- // Creating the session is irreversible and its target route does not exist until the API
- // succeeds. Confirm before that mutation, then let its one resulting navigation bypass the
- // router blocker so the user sees exactly one prompt.
+ if (!current.current.open || !current.current.surfaceActive || pendingNavigation) return false;
+ // Composer clears optimistically before calling us. Retain the text in its
+ // owner while the request may outlive that particular Composer instance.
+ setPendingDraft(text);
const canCreate = text.trim() !== '' && ns.loaded && ns.target !== null && !ns.sending;
const authorization = canCreate ? authorizeRouteAction() : undefined;
if (authorization === null) return false;
const result = await ns.send(text);
+ if (!current.current.mounted || current.current.lifetime !== lifetime) return false;
if (result) {
setPendingDraft('');
- const navigateToSession = () =>
- navigate(`/chat/${encodeURIComponent(result.sessionId)}`);
- if (authorization) authorization.runNavigation(navigateToSession);
- else navigateToSession();
- onClose();
+ setPendingNavigation({ sessionId: result.sessionId, authorization });
return true;
}
- // No project to target → stash the prompt and route to the New Project flow.
- const trimmed = text.trim();
- if (trimmed && ns.needsProject) {
- setPendingDraft(trimmed);
- openNewProject();
- }
+ // No project to target → stash the prompt and open the existing handoff.
+ if (text.trim() && ns.needsProject && current.current.surfaceActive) openNewProject();
return false;
};
return (
<>
- <Dialog open={open} onOpenChange={(o) => { if (!o && !ns.sending) close(); }}>
- <DialogContent className="gap-5" onOpenAutoFocus={(e) => e.preventDefault()}>
+ <Dialog
+ open={open && surfaceActive && !pendingNavigation}
+ onOpenChange={(nextOpen) => {
+ // Settings suspension closes only the visible modal content. Keep the
+ // logical sheet open so its hook lifetime, selections and uncertainty
+ // remain intact until the user explicitly closes it.
+ if (!nextOpen && open && !surfaceActive) return;
+ if (!nextOpen && !ns.sending && !pendingNavigation) close();
+ }}
+ >
+ {surfaceActive && !pendingNavigation && <DialogContent
+ className="gap-5"
+ aria-describedby={undefined}
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ onCloseAutoFocus={(event) => {
+ if (!current.current.surfaceActive) event.preventDefault();
+ }}
+ >
<DialogTitle className="text-lg font-bold">{t('newSession.title')}</DialogTitle>
<ProjectPicker
@@ -127,12 +173,13 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
re-seeds a prompt stashed when the no-project flow closed the sheet. */}
<Composer
onSend={send}
+ onDraftChange={updateDraft}
placeholder={t('newSession.placeholder')}
disabled={ns.sending || !ns.loaded}
sendDisabled={Boolean(ns.uncertainSessionId)}
initialDraft={pendingDraft}
/>
- </DialogContent>
+ </DialogContent>}
</Dialog>
{/* Sibling of the sheet's Dialog (and opened only after the sheet closes)
diff --git a/ui/src/lib/useNewSession.lifecycle.test.tsx b/ui/src/lib/useNewSession.lifecycle.test.tsx
index c3bdaae93..3ae8040fd 100644
--- a/ui/src/lib/useNewSession.lifecycle.test.tsx
+++ b/ui/src/lib/useNewSession.lifecycle.test.tsx
@@ -21,6 +21,7 @@ vi.mock('../context/WorkbenchProjectsContext', () => ({ useWorkbenchProjectsTree
vi.mock('./apiFetch', () => ({ apiFetch: mocks.fetch }));
vi.mock('./workbenchUpload', async (original) => ({ ...await original<typeof import('./workbenchUpload')>(), uploadWorkbenchAttachment: mocks.upload }));
import { useNewSession } from './useNewSession';
+import { RouteSurfaceActiveContext } from './routeSurfaceActivity';
const attachment: ComposerAttachment = { localId: 'file-id', file: new File(['内容'], '中文.txt'), token: '', name: '中文.txt', mime: 'text/plain', size: 6, kind: 'file', url: '', status: 'staged' };
const mount = () => renderHook(() => useNewSession({ loadErrorText: 'load failed', createFailedText: 'send failed' }));
beforeEach(() => {
@@ -139,3 +140,59 @@ it('a missing upload session gets a new scope on explicit retry', async () => {
await act(async () => { expect(await result.current.send('', [attachment])).toEqual({ sessionId: 'session-2' }); });
expect(mocks.upload).toHaveBeenNthCalledWith(2, 'session-2', attachment.file, attachment.localId);
});
+
+it.each(['create', 'upload'])('foreground suspension after %s retains scope and stops before POST until explicit retry', async (stage) => {
+ let release!: (value: unknown) => void;
+ const held = new Promise((resolve) => { release = resolve; });
+ if (stage === 'create') mocks.create.mockReturnValueOnce(held);
+ else mocks.upload.mockReturnValueOnce(held);
+ let foreground = true;
+ const { result, rerender } = renderHook(() => useNewSession({ active: true, loadErrorText: 'load failed', createFailedText: 'send failed' }), {
+ wrapper: ({ children }) => <RouteSurfaceActiveContext.Provider value={foreground}>{children}</RouteSurfaceActiveContext.Provider>,
+ });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ let attempt!: ReturnType<typeof result.current.send>;
+ act(() => { attempt = result.current.send('挂起草稿', [attachment]); });
+ await waitFor(() => expect(stage === 'create' ? mocks.create : mocks.upload).toHaveBeenCalledTimes(1));
+ foreground = false;
+ rerender();
+ await act(async () => {
+ release(stage === 'create' ? { id: 'session-1' } : { token: 'uploaded', name: attachment.name });
+ expect(await attempt).toBeNull();
+ });
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ await act(async () => { expect(await result.current.send('后台禁止发送')).toBeNull(); });
+ foreground = true;
+ rerender();
+ await act(async () => { expect(await result.current.send('挂起草稿', [attachment])).toEqual({ sessionId: 'session-1' }); });
+ expect(mocks.create).toHaveBeenCalledTimes(1);
+ expect(mocks.upload).toHaveBeenCalledTimes(1);
+ expect(mocks.fetch).toHaveBeenCalledTimes(1);
+});
+
+it.each(['success', 'uncertain'])('already admitted POST %s survives suspension without resetting the sheet lifetime', async (outcome) => {
+ let release!: (value: Response) => void;
+ mocks.fetch.mockReturnValueOnce(new Promise<Response>((resolve) => { release = resolve; }));
+ let foreground = true;
+ const { result, rerender } = renderHook(() => useNewSession({ active: true, loadErrorText: 'load failed', createFailedText: 'send failed' }), {
+ wrapper: ({ children }) => <RouteSurfaceActiveContext.Provider value={foreground}>{children}</RouteSurfaceActiveContext.Provider>,
+ });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ let attempt!: ReturnType<typeof result.current.send>;
+ act(() => { attempt = result.current.send('发送已受理'); });
+ await waitFor(() => expect(mocks.fetch).toHaveBeenCalledTimes(1));
+ foreground = false;
+ rerender();
+ await act(async () => {
+ release(outcome === 'success' ? new Response('{}', { status: 201 }) : new Response('{"dispatch_error":"dispatch_pending"}', { status: 504 }));
+ expect(await attempt).toEqual(outcome === 'success' ? { sessionId: 'session-1' } : null);
+ });
+ foreground = true;
+ rerender();
+ if (outcome === 'uncertain') {
+ expect(result.current.uncertainSessionId).toBe('session-1');
+ await act(async () => { expect(await result.current.send('不能重复')).toBeNull(); });
+ }
+ expect(mocks.create).toHaveBeenCalledTimes(1);
+ expect(mocks.fetch).toHaveBeenCalledTimes(1);
+});