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.

feat(workbench): enable home media before the first message (#2047)

Max27b0d6644500
diff --git a/ui/e2e/home-media/README.md b/ui/e2e/home-media/README.md
new file mode 100644
index 000000000..4d4b641b5
--- /dev/null
+++ b/ui/e2e/home-media/README.md
@@ -0,0 +1,57 @@
+# Home draft and first-send contract
+
+Lane B of the approved desktop alignment: external committed contract
+`9ff92b7f02ad950723d0ccf73218052ad2f7c7d3`,
+`docs/plans/desktop-alignment-20260919/execution-contract.md`, plus the
+orchestrator's September 19 07:16 amendment granting the optional
+`NewProjectDialog.initialPath` boundary.
+
+The home retains local Files, text, Agent/project selection and voice state.
+Only explicit Send creates the eventual session, uploads into that scope and
+submits the first message. Navigation carries no replayable first-message state.
+A definite rejection keeps the draft and successful upload progress for explicit
+retry. Switching the selection preserves the original Files and gives a later
+submission its own upload scope. Closing a picker or opening Settings does not
+replace the draft. The shared new-session sheet uses the same first-message
+submission owner; existing chat media upload and queued attachment presentation
+remain unchanged.
+
+There is no generic caller-provided idempotency key on ordinary message POST.
+A lost response or unresolved dispatch therefore retains the draft, blocks
+resubmission and offers the created conversation in another tab for inspection.
+A fresh global new-session sheet open clears the prior submission lifetime and
+starts with an empty draft; an older request cannot alter the new sheet. Terminal
+session errors discard the invalid upload scope before explicit retry, while
+ordinary dispatch/upload failures keep partial progress.
+
+This is an intentional limit: the frontend never guesses whether an uncertain
+turn ran. Abandoned drafts are component-local, not reload-persistent. A failed
+attempt may leave an empty session, using the existing service lifecycle.
+
+## Verification
+
+Run from `ui/`:
+
+```sh
+npx tsc -p e2e/home-media/tsconfig.json --noEmit
+npx playwright test --config playwright.home-media.config.ts
+```
+
+The fixture mounts the real Workbench, Composer, AgentRoutePicker,
+DirectoryBrowser, NewProjectDialog, API/project providers and retained Settings
+route boundary under StrictMode. It intercepts all fetches in memory; external
+network traffic is refused. Audio capture uses Chromium's fake microphone with
+the real MediaRecorder/recording pipeline and HTTP transcription boundary.
+No Avibe service, credentials, user browser profile or real project is accessed.
+The conversation destination records router state: the lane intentionally does
+not replace ChatPage or modify its queued attachment behavior.
+
+Assertions cover final project/Agent scope, Unicode file names/content, same
+scope retry, attachment-only submission, ambiguous acknowledgment, Settings
+during upload, voice cancel/finalize before session creation, and localized
+responsive geometry. Screenshots are generated at 320, 375, 390, 1366 and 1600px
+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.
diff --git a/ui/e2e/home-media/fixture.html b/ui/e2e/home-media/fixture.html
new file mode 100644
index 000000000..3f80f647f
--- /dev/null
+++ b/ui/e2e/home-media/fixture.html
@@ -0,0 +1 @@
+<!doctype html><html><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/></head><body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body></html>
diff --git a/ui/e2e/home-media/fixture.tsx b/ui/e2e/home-media/fixture.tsx
new file mode 100644
index 000000000..1fe061beb
--- /dev/null
+++ b/ui/e2e/home-media/fixture.tsx
@@ -0,0 +1,138 @@
+import { StrictMode, 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';
+import { WorkbenchProjectsProvider } from '../../src/context/WorkbenchProjectsProvider';
+import { InstanceAuthorizationContext } from '../../src/context/InstanceAuthorizationContext';
+import { ToastProvider } from '../../src/context/ToastProvider';
+import { SettingsOverlayRouteSurface } from '../../src/components/settings/SettingsOverlayRouteSurface';
+import { NewSessionSheet } from '../../src/components/workbench/NewSessionSheet';
+import { UnsavedChangesProvider } from '../../src/context/UnsavedChangesProvider';
+import { Workbench } from '../../src/components/Workbench';
+import { settingsOverlayNavigationState } from '../../src/lib/settingsOverlay';
+import { OWNER_INSTANCE_CAPABILITIES } from '../../src/lib/sessionInfo';
+import i18n from '../../src/i18n';
+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 = [{
+ 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 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[] = [];
+const sessions: Array<Record<string, unknown>> = [];
+const uploads = new Map<string, { sessionId: string; token: string }>();
+const control = {
+ writes,
+ uploadFailures: 0,
+ uploadTerminal: false,
+ messageTerminal: 0,
+ messageMode: 'success' as 'success' | 'rejected' | 'unknown' | 'network',
+ holdUpload: false,
+ releaseUpload: () => {},
+ asrFailures: 0,
+};
+declare global { interface Window { homeMedia: typeof control } }
+window.homeMedia = control;
+class FixtureEvents extends EventTarget {
+ readyState = 1;
+ close() { this.readyState = 2; }
+}
+Object.defineProperty(window, 'EventSource', { value: FixtureEvents });
+// All transport terminates here, including CSRF, upload bytes and ASR. No
+// backend proxy, cloud account, native keychain or real browser profile is used.
+window.fetch = async (input, init) => {
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, location.origin);
+ const path = url.pathname;
+ const reply = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+ const body = typeof init?.body === 'string' ? JSON.parse(init.body) : {};
+ if (init?.method === 'POST') writes.push({ path, body });
+ 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() };
+ 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/favorites') return reply({ ok: true, favorites: [{ key: 'home', path: '/fixture' }] });
+ if (path === '/api/sessions' && init?.method === 'POST') {
+ 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);
+ }
+ if (path === '/api/sessions') return reply({ sessions, next_before_id: null });
+ if (path.endsWith('/attachments')) {
+ const form = init?.body as FormData;
+ const file = form.get('file') as File;
+ const uploadId = String(form.get('upload_id'));
+ const sessionId = path.split('/')[3];
+ writes.at(-1)!.body = { name: file.name, uploadId, sessionId, size: file.size };
+ if (control.holdUpload) await new Promise<void>((resolve) => { control.releaseUpload = resolve; });
+ if (control.uploadTerminal) return reply({ error: { code: 'session_not_found' } }, 404);
+ if (control.uploadFailures-- > 0) return reply({ error: { code: 'upload_failed' } }, 503);
+ const token = `${sessionId}-${uploadId}`;
+ uploads.set(token, { sessionId, token });
+ return reply({ token, name: file.name, mime: file.type, size: file.size, kind: 'file', url: `/api/media/${token}` });
+ }
+ 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.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);
+ if (control.messageMode === 'rejected') return reply({ state: 'retired', dispatch_error: 'dispatch_failed' }, 502);
+ return reply({ id: 'message-1', type: 'user', ...body }, 201);
+ }
+ if (path === '/api/asr/status') return reply({ available: true, max_file_bytes: 25_000_000 });
+ if (path === '/api/cloud/token') return reply({ error: 'fixture local ASR only' }, 503);
+ if (path === '/api/asr/transcribe') {
+ if (control.asrFailures-- > 0) return reply({ error: 'fixture failure' }, 503);
+ return reply({ text: '请整理中文发布说明。', cleanup: 'success' });
+ }
+ if (path.endsWith('/connection')) return reply({ backend: path.split('/')[3], ready: true });
+ if (path.endsWith('/models')) return reply({ ok: true, models: [] });
+ return reply({});
+};
+
+export function SettingsEntry() {
+ const location = useLocation();
+ const navigate = useNavigate();
+ return <button data-testid="settings-entry" onClick={() => navigate('/settings/general', { state: settingsOverlayNavigationState({ destinationPathname: '/settings/general', desktop: true, source: location, targetState: undefined }) })}>Settings</button>;
+}
+export function Settings() {
+ const navigate = useNavigate();
+ 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 location = useLocation();
+ return <div data-testid="conversation">{sessionId}<pre data-testid="handoff">{JSON.stringify(location.state)}</pre></div>;
+}
+export 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)} />
+ </>;
+}
+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 /></>} />
+ <Route path="/chat/:sessionId" element={<Conversation />} />
+ <Route path="/agents" element={<div>Agents destination</div>} />
+ <Route path="/settings/general" element={<Settings />} />
+ </SettingsOverlayRouteSurface>
+ </main>
+ </WorkbenchProjectsProvider></UnsavedChangesProvider></ApiProvider></ToastProvider>
+ </InstanceAuthorizationContext.Provider>;
+}
+createRoot(document.getElementById('root')!).render(<StrictMode><RouterProvider router={createHashRouter([{ path: '*', element: <Fixture /> }])} /></StrictMode>);
diff --git a/ui/e2e/home-media/media.spec.ts b/ui/e2e/home-media/media.spec.ts
new file mode 100644
index 000000000..175df3691
--- /dev/null
+++ b/ui/e2e/home-media/media.spec.ts
@@ -0,0 +1,226 @@
+import { expect, test, type Page } from '@playwright/test';
+import en from '../../src/i18n/en.json' with { type: 'json' };
+import zh from '../../src/i18n/zh.json' with { type: 'json' };
+
+const file = { name: '发布说明 中文.txt', mimeType: 'text/plain', buffer: Buffer.from('版本内容 ✓') };
+const input = (page: Page) => page.getByPlaceholder(en.workbench.home.inputPlaceholder);
+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);
+const attach = async (page: Page) => page.locator('input[type=file]').setInputFiles(file);
+async function open(page: Page, query = '') {
+ await page.route('**/*', (route) => {
+ const url = new URL(route.request().url());
+ if (url.origin !== 'http://127.0.0.1:5217') return route.abort();
+ return route.continue();
+ });
+ await page.goto(`/e2e/home-media/fixture.html${query}`);
+ await expect(page.getByRole('button', { name: en.chat.compose.attach })).toBeEnabled();
+}
+
+test('draft files follow final project and Agent selection through picker cancellation and Settings', async ({ page }) => {
+ await open(page);
+ await input(page).fill('请阅读这份中文文件');
+ await attach(page);
+ await expect(page.getByText(file.name, { exact: true })).toBeVisible();
+ expect(await writes(page, '/api/sessions')).toEqual([]);
+ expect(await writes(page, '/attachments')).toEqual([]);
+ const workspace = () => page.getByRole('button', { name: /^Workspace:/ });
+ await workspace().click();
+ expect((await writes(page, '/api/browse')).at(-1)?.body.path).toBe('/fixture/中文项目');
+ await page.keyboard.press('Escape');
+ await expect(input(page)).toHaveValue('请阅读这份中文文件');
+ await workspace().click();
+ await page.getByRole('button', { name: '另一个项目', exact: true }).click();
+ await page.getByRole('button', { name: en.directoryBrowser.select, exact: true }).click();
+ await page.getByRole('button', { name: en.workbench.newProjectDialog.pickFolder, exact: false }).click();
+ expect((await writes(page, '/api/browse')).at(-1)?.body.path).toBe('/fixture/另一个项目');
+ await page.getByRole('button', { name: en.directoryBrowser.select, exact: true }).click();
+ await page.getByRole('dialog').getByRole('button', { name: en.workbench.newProjectDialog.create, exact: true }).click();
+ await expect(workspace()).toContainText('另一个项目');
+ await page.getByRole('button', { name: /codex/ }).first().click();
+ await page.getByRole('button', { name: /^claude/ }).click();
+ await page.keyboard.press('Escape');
+ await page.getByTestId('settings-entry').click();
+ await expect(page.getByText('Fixture Settings')).toBeVisible();
+ await expect(input(page)).toHaveValue('请阅读这份中文文件');
+ expect(await input(page).evaluate((node) => Boolean(node.closest('[inert]')))).toBe(true);
+ await page.getByRole('button', { name: 'Back to app' }).click();
+ await expect(page.getByText(file.name, { exact: true })).toBeVisible();
+ await send(page).dblclick();
+ await expect(page.getByTestId('conversation')).toContainText('ses-1');
+ expect(await writes(page, '/api/sessions')).toHaveLength(1);
+ expect((await writes(page, '/api/sessions'))[0].body).toMatchObject({ project_id: 'project-1', agent_name: 'claude' });
+ expect(await writes(page, '/messages')).toHaveLength(1);
+ expect(await page.getByTestId('handoff').textContent()).toBe('null');
+});
+
+test('attachment-only send retries definite failures using the same scoped upload and keeps partial progress', async ({ page }) => {
+ await open(page);
+ await attach(page);
+ await page.evaluate(() => { window.homeMedia.uploadFailures = 1; });
+ await send(page).click();
+ await expect(page.getByText(file.name, { exact: true })).toBeVisible();
+ await expect(send(page)).toBeEnabled();
+ expect(await writes(page, '/messages')).toEqual([]);
+ await page.evaluate(() => { window.homeMedia.messageMode = 'rejected'; });
+ await send(page).click();
+ await expect(send(page)).toBeEnabled();
+ await expect(page.getByText(file.name, { exact: true })).toBeVisible();
+ await page.evaluate(() => { window.homeMedia.messageMode = 'success'; });
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toBeVisible();
+ expect(await writes(page, '/api/sessions')).toHaveLength(1);
+ expect(await writes(page, '/attachments')).toHaveLength(2);
+ const submissions = await writes(page, '/messages');
+ expect(submissions).toHaveLength(2);
+ expect(submissions[1].body.text).toBe('');
+ expect(submissions[1].body.content).toMatchObject({ attachments: [{ name: file.name, size: file.buffer.length }] });
+});
+
+for (const mode of ['unknown', 'network'] as const) test(`ambiguous ${mode} result retains input and blocks a duplicate first turn`, async ({ page }) => {
+ await open(page);
+ await input(page).fill('只发送一次');
+ await attach(page);
+ await page.evaluate((mode) => { window.homeMedia.messageMode = mode; }, mode);
+ await send(page).click();
+ await expect(input(page)).toHaveValue('只发送一次');
+ await expect(page.getByText(file.name, { exact: true })).toBeVisible();
+ await expect(page.getByRole('link', { name: en.newSession.inspectSession })).toHaveAttribute('href', '#/chat/ses-1');
+ await expect(send(page)).toBeDisabled();
+ expect(await writes(page, '/messages')).toHaveLength(1);
+});
+
+test('real microphone capture before any session supports cancel, final transcription, Settings and Send', async ({ page }) => {
+ await open(page);
+ await input(page).fill('原始草稿');
+ await page.getByRole('button', { name: en.chat.compose.voice, exact: true }).click();
+ await expect(page.getByRole('button', { name: en.chat.compose.stopRecording, exact: true })).toBeVisible();
+ await page.getByRole('button', { name: en.chat.compose.cancelRecording, exact: true }).click();
+ await expect(input(page)).toHaveValue('原始草稿');
+ await page.getByRole('button', { name: en.chat.compose.voice, exact: true }).click();
+ await expect(page.getByRole('button', { name: en.chat.compose.stopRecording, exact: true })).toBeVisible();
+ await expect.poll(async () => page.locator('span').filter({ hasText: /^0:01$/ }).count()).toBeGreaterThan(0);
+ await page.getByTestId('settings-entry').click();
+ await page.getByRole('button', { name: 'Back to app' }).click();
+ await page.getByRole('button', { name: en.chat.compose.stopRecording, exact: true }).click();
+ await expect(input(page)).toHaveValue(/请整理中文发布说明。/);
+ expect(await writes(page, '/api/sessions')).toEqual([]);
+ expect(await writes(page, '/messages')).toEqual([]);
+ expect(await writes(page, '/api/asr/transcribe')).not.toEqual([]);
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toBeVisible();
+ expect(await writes(page, '/messages')).toHaveLength(1);
+});
+
+test('Settings opened during upload suspends submission and preserves the draft for explicit retry', async ({ page }) => {
+ await open(page);
+ await input(page).fill('保留到返回');
+ await attach(page);
+ await page.evaluate(() => { window.homeMedia.holdUpload = true; });
+ await send(page).click();
+ await expect.poll(async () => (await writes(page, '/attachments')).length).toBe(1);
+ await page.getByTestId('settings-entry').click();
+ await page.evaluate(() => window.homeMedia.releaseUpload());
+ await expect(input(page)).toHaveValue('保留到返回');
+ expect(await writes(page, '/messages')).toEqual([]);
+ await page.getByRole('button', { name: 'Back to app' }).click();
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toBeVisible();
+ expect(await writes(page, '/attachments')).toHaveLength(1);
+ expect(await writes(page, '/messages')).toHaveLength(1);
+});
+
+for (const width of [320, 375, 390, 1366, 1600]) {
+ for (const [lang, theme] of [['zh', 'dark'], ['en', 'dark'], ['zh', 'light'], ['en', 'light']]) {
+ test(`home layout ${width} ${lang} ${theme}`, async ({ page }, testInfo) => {
+ await page.setViewportSize({ width, height: width < 500 ? 700 : 768 });
+ 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?lang=${lang}&theme=${theme}`);
+ const copy = lang === 'zh' ? zh : en;
+ await expect(page.getByRole('heading', { name: copy.workbench.home.heroTitle })).toBeVisible();
+ await expect(page.getByRole('button', { name: copy.chat.compose.voice, exact: true })).toBeVisible();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth)).toBe(false);
+ const attachBox = await page.getByRole('button', { name: copy.chat.compose.attach }).boundingBox();
+ expect(attachBox?.width).toBe(28);
+ expect(attachBox?.height).toBe(28);
+ await page.getByRole('button', { name: copy.chat.compose.attach }).focus();
+ await expect(page.getByRole('button', { name: copy.chat.compose.attach })).toBeFocused();
+ await page.screenshot({ path: testInfo.outputPath('home.png'), fullPage: true });
+ });
+ }
+}
+
+test('voice failure retains the recording for explicit retry while preserving the surrounding draft', async ({ page }) => {
+ await open(page);
+ await input(page).fill('上下文:');
+ await page.evaluate(() => { window.homeMedia.asrFailures = 1; });
+ await input(page).focus();
+ await page.keyboard.press('Alt+z');
+ await expect(page.getByRole('button', { name: en.chat.compose.stopRecording, exact: true })).toBeVisible();
+ await expect.poll(async () => page.locator('span').filter({ hasText: /^0:01$/ }).count()).toBeGreaterThan(0);
+ await page.keyboard.press('Alt+z');
+ await expect(page.getByRole('button', { name: en.chat.compose.voiceRetry, exact: true })).toBeVisible();
+ await expect(input(page)).toHaveValue('上下文:');
+ expect(await writes(page, '/api/sessions')).toEqual([]);
+ await page.getByRole('button', { name: en.chat.compose.voiceRetry, exact: true }).click();
+ await expect(input(page)).toHaveValue(/上下文:.*请整理中文发布说明。/);
+ await expect(send(page)).toBeEnabled();
+});
+
+test('directory picker remains keyboard-contained and its footer reachable on a short narrow viewport', async ({ page }) => {
+ await page.setViewportSize({ width: 320, height: 440 });
+ await open(page);
+ await page.getByRole('button', { name: /^Workspace:/ }).click();
+ const dialog = page.getByRole('dialog');
+ const select = dialog.getByRole('button', { name: en.directoryBrowser.select, exact: true });
+ await expect(select).toBeInViewport();
+ await select.focus();
+ for (let i = 0; i < 18; i++) await page.keyboard.press('Tab');
+ expect(await dialog.evaluate((node) => node.contains(document.activeElement))).toBe(true);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth)).toBe(false);
+ await page.keyboard.press('Escape');
+ await expect(dialog).toHaveCount(0);
+ await expect(input(page)).toBeVisible();
+});
+
+test('global new-session sheet can be reopened after uncertain admission without carrying a send lock or old draft', async ({ page }) => {
+ 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');
+ await page.getByRole('button', { name: 'Open new session' }).click();
+ const draft = page.getByPlaceholder(en.newSession.placeholder);
+ await draft.fill('结果未知的第一条');
+ await page.evaluate(() => { window.homeMedia.messageMode = 'unknown'; });
+ await send(page).click();
+ await expect(draft).toHaveValue('结果未知的第一条');
+ await expect(send(page)).toBeDisabled();
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { name: 'Open new session' }).click();
+ await expect(draft).toHaveValue('');
+ await expect(page.getByRole('link', { name: en.newSession.inspectSession })).toHaveCount(0);
+ await draft.fill('独立的新对话');
+ await page.evaluate(() => { window.homeMedia.messageMode = 'success'; });
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toContainText('ses-2');
+ expect(await writes(page, '/api/sessions')).toHaveLength(2);
+ expect((await writes(page, '/messages')).map((write) => write.body.text)).toEqual(['结果未知的第一条', '独立的新对话']);
+});
+
+for (const failure of ['upload', 'message'] as const) test(`terminal ${failure} scope is replaced on explicit retry, with the same original file`, async ({ page }) => {
+ await open(page);
+ await attach(page);
+ await page.evaluate((failure) => {
+ window.homeMedia.uploadTerminal = failure === 'upload';
+ window.homeMedia.messageTerminal = failure === 'message' ? 409 : 0;
+ }, failure);
+ await send(page).click();
+ await expect(page.getByText(file.name, { exact: true })).toBeVisible();
+ await expect(send(page)).toBeEnabled();
+ await page.evaluate(() => { window.homeMedia.uploadTerminal = false; window.homeMedia.messageTerminal = 0; });
+ await send(page).click();
+ await expect(page.getByTestId('conversation')).toContainText('ses-2');
+ expect(await writes(page, '/api/sessions')).toHaveLength(2);
+ expect((await writes(page, '/attachments')).map((write) => write.body)).toEqual([
+ expect.objectContaining({ name: file.name, sessionId: 'ses-1', size: file.buffer.length }),
+ expect.objectContaining({ name: file.name, sessionId: 'ses-2', size: file.buffer.length }),
+ ]);
+});
diff --git a/ui/e2e/home-media/tsconfig.json b/ui/e2e/home-media/tsconfig.json
new file mode 100644
index 000000000..ae725a9b1
--- /dev/null
+++ b/ui/e2e/home-media/tsconfig.json
@@ -0,0 +1 @@
+{"extends":"../../tsconfig.app.json","compilerOptions":{"noEmit":true,"rootDir":"../.."},"include":["./**/*.ts","./**/*.tsx"],"exclude":[]}
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index f995b5bec..6da278c51 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -125,9 +125,6 @@
"src/lib/useMessageSearch.ts": {
"react-hooks/set-state-in-effect": 1
},
- "src/lib/useNewSession.ts": {
- "react-hooks/set-state-in-effect": 1
- },
"src/lib/usePendingVaultRequests.ts": {
"react-hooks/preserve-manual-memoization": 1
}
diff --git a/ui/playwright.home-media.config.ts b/ui/playwright.home-media.config.ts
new file mode 100644
index 000000000..b709208bb
--- /dev/null
+++ b/ui/playwright.home-media.config.ts
@@ -0,0 +1,20 @@
+import { defineConfig, devices } from '@playwright/test';
+
+export default defineConfig({
+ testDir: './e2e/home-media',
+ outputDir: './e2e/.artifacts/home-media',
+ workers: 1,
+ retries: 0,
+ use: {
+ baseURL: 'http://127.0.0.1:5217',
+ trace: 'retain-on-failure',
+ permissions: ['microphone'],
+ launchOptions: { args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] },
+ },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 5217 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5217/e2e/home-media/fixture.html',
+ },
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+});
diff --git a/ui/src/components/Workbench.test.tsx b/ui/src/components/Workbench.test.tsx
index 5c7874402..8b7da3d0e 100644
--- a/ui/src/components/Workbench.test.tsx
+++ b/ui/src/components/Workbench.test.tsx
@@ -12,6 +12,8 @@ const newSession = vi.hoisted(() => ({
target: undefined as { id: string; display_name: string; folder_path: string } | undefined,
setSelected: vi.fn(),
sending: false,
+ loaded: true,
+ uncertainSessionId: null,
agents: [{ name: 'codex', backend: 'codex' }],
agentRoute: { agent_name: 'codex', agent_backend: 'codex' } as Record<string, unknown>,
setAgentRoute: vi.fn(),
@@ -26,6 +28,7 @@ const authorization = vi.hoisted(() => ({
can_chat: true,
can_manage_projects: true,
can_manage_instance: true,
+ can_manage_agents: true,
},
}));
vi.hoisted(() => {
@@ -45,12 +48,13 @@ vi.mock('../lib/sessionInfo', () => ({
// The real dialog opens the directory browser as its own first phase; here we
// only need to see that the chip reaches it and that closing it changes nothing.
vi.mock('./workbench/NewProjectDialog', () => ({
- NewProjectDialog: ({ onClose }: { onClose: () => void }) => (
- <div role="dialog" aria-label="directory-browser">
+ NewProjectDialog: ({ onClose, initialPath }: { onClose: () => void; initialPath?: string }) => (
+ <div role="dialog" aria-label="directory-browser" data-path={initialPath}>
<button type="button" onClick={onClose}>cancel-folder</button>
</div>
),
}));
+vi.mock('./workbench/CreateViaChatDialog', () => ({ CreateViaChatDialog: ({ onClose }: { onClose: () => void }) => <div role="dialog" aria-label="create-task"><button onClick={onClose}>cancel-task</button></div> }));
vi.mock('./workbench/AgentRoutePicker', () => ({
AgentRoutePicker: ({ onChange }: { onChange: (patch: Record<string, unknown>) => void }) => (
<button type="button" onClick={() => onChange({ agent_name: 'claude', agent_backend: 'claude' })}>
@@ -58,7 +62,7 @@ vi.mock('./workbench/AgentRoutePicker', () => ({
</button>
),
}));
-vi.mock('../lib/apiFetch', () => ({ apiFetch: vi.fn() }));
+vi.mock('../lib/apiFetch', () => ({ apiFetch: vi.fn().mockResolvedValue({ ok: true, json: async () => ({ available: false }) }) }));
// Only the producer seam is stubbed; the predicate and the banner stay real, so
// these tests exercise the lifecycle the home actually runs.
const readiness = vi.hoisted(() => ({
@@ -138,6 +142,7 @@ const homeTree = (state?: unknown) => (
component that knows which route is being shown. */}
<SettingsOverlayRouteSurface fallbackElement={<div>no-such-route</div>}>
<Route path="/" element={<><Workbench /><LocationState /></>} />
+ <Route path="/agents" element={<div>agents-page</div>} />
<Route path="/projects" element={<div>projects-page</div>} />
<Route path="/chat/:sessionId" element={<div>chat-page</div>} />
<Route path="/settings/general" element={<div>settings-page</div>} />
@@ -178,42 +183,31 @@ afterEach(() => {
});
describe('Workbench first-task home', () => {
- it('seeds a starting task into the draft and focuses it, without sending', async () => {
+ it('opens real starting actions without sending or overwriting a draft', async () => {
const user = userEvent.setup();
renderHome();
-
- await user.click(screen.getByText(en.workbench.home.suggestions.researchTitle));
-
- await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.researchDraft));
- expect(document.activeElement).toBe(input());
- expect(input().selectionStart).toBe(en.workbench.home.suggestions.researchDraft.length);
+ await user.type(input(), '保留草稿');
+ await user.click(screen.getByText(en.workbench.home.openProject));
+ expect(screen.getByRole('dialog').getAttribute('data-path')).toBe(项目.folder_path);
+ await user.click(screen.getByText('cancel-folder'));
+ await user.click(screen.getByText(en.workbench.home.createTask));
+ expect(screen.getByRole('dialog', { name: 'create-task' })).toBeTruthy();
+ await user.click(screen.getByText('cancel-task'));
+ expect(input().value).toBe('保留草稿');
expect(newSession.send).not.toHaveBeenCalled();
+ await user.click(screen.getByText(en.workbench.home.manageAgents));
+ expect(await screen.findByText('agents-page')).toBeTruthy();
});
- it('lets the seeded task be edited before it is sent', async () => {
+ it('navigates only after submission, without passing a replayable initial message', async () => {
const user = userEvent.setup();
renderHome();
-
- await user.click(screen.getByText(en.workbench.home.suggestions.planTitle));
- await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.planDraft));
- await user.type(input(), ':先做中文文档');
+ await user.type(input(), '先做中文文档');
await user.click(screen.getByRole('button', { name: en.chat.compose.send }));
-
- expect(newSession.send).toHaveBeenCalledWith(`${en.workbench.home.suggestions.planDraft}:先做中文文档`);
+ expect(newSession.send).toHaveBeenCalledWith('先做中文文档', []);
expect(await screen.findByText('chat-page')).toBeTruthy();
});
- it('replaces the draft when a second starting point is picked', async () => {
- const user = userEvent.setup();
- renderHome();
-
- await user.click(screen.getByText(en.workbench.home.suggestions.exploreTitle));
- await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.exploreDraft));
- await user.click(screen.getByText(en.workbench.home.suggestions.planTitle));
- await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.planDraft));
- expect(newSession.send).not.toHaveBeenCalled();
- });
-
it('opens the folder picker straight from the workspace chip and keeps the draft when it is cancelled', async () => {
const user = userEvent.setup();
renderHome();
@@ -479,6 +473,6 @@ describe('Workbench continuation row', () => {
await user.type(input(), '继续用聊天');
await user.click(screen.getByRole('button', { name: en.chat.compose.send }));
- expect(newSession.send).toHaveBeenCalledWith('继续用聊天');
+ expect(newSession.send).toHaveBeenCalledWith('继续用聊天', []);
});
});
diff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsx
index ee5b05e92..f9363fa97 100644
--- a/ui/src/components/Workbench.tsx
+++ b/ui/src/components/Workbench.tsx
@@ -1,12 +1,12 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Link, Navigate, useLocation, useNavigate } from 'react-router-dom';
-import { ChevronDown, FolderOpen, ListChecks, Search, Smartphone } from 'lucide-react';
-import type { LucideIcon } from 'lucide-react';
+import { Bot, ChevronDown, Clock, FolderOpen, Smartphone } from 'lucide-react';
+import { useRouteSurfaceActive } from '../lib/routeSurfaceActivity';
import { useNewSession } from '../lib/useNewSession';
import { NewProjectDialog } from './workbench/NewProjectDialog';
-import { Composer, type ComposerHandle } from './workbench/Composer';
+import { Composer, type ComposerAttachment } from './workbench/Composer';
import { ProjectPicker } from './workbench/ProjectPicker';
import { AgentRoutePicker } from './workbench/AgentRoutePicker';
import { ReadyBanner } from './workbench/ReadyBanner';
@@ -15,51 +15,19 @@ import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
import { canCreateLocalProject } from '../lib/sessionInfo';
import logoImg from '../assets/logo.png';
-import type { TranslationKey } from '../i18n/types';
+import { CreateViaChatDialog } from './workbench/CreateViaChatDialog';
+import { Button } from './ui/button';
-// The three starting points the home offers (design LDlvV). Each one seeds the
-// draft and focuses the input — it never sends, so the user edits a concrete
-// sentence instead of staring at an empty box.
-const SUGGESTIONS: {
- key: string;
- icon: LucideIcon;
- titleKey: TranslationKey;
- bodyKey: TranslationKey;
- draftKey: TranslationKey;
-}[] = [
- {
- key: 'explore',
- icon: FolderOpen,
- titleKey: 'workbench.home.suggestions.exploreTitle',
- bodyKey: 'workbench.home.suggestions.exploreBody',
- draftKey: 'workbench.home.suggestions.exploreDraft',
- },
- {
- key: 'research',
- icon: Search,
- titleKey: 'workbench.home.suggestions.researchTitle',
- bodyKey: 'workbench.home.suggestions.researchBody',
- draftKey: 'workbench.home.suggestions.researchDraft',
- },
- {
- key: 'plan',
- icon: ListChecks,
- titleKey: 'workbench.home.suggestions.planTitle',
- bodyKey: 'workbench.home.suggestions.planBody',
- draftKey: 'workbench.home.suggestions.planDraft',
- },
-];
-
-// The first-task home (design SfdNo + TfqkD + CRERw): one question, three
-// starting points, and the shared chat Composer carrying the Agent and workspace
-// pickers on its own action row. Sending creates a session under the selected
-// workspace with the selected Agent and routes to /chat/<id> with the typed
-// message pre-seeded; no workspace surfaces the project dialog so the user gets
-// unstuck in place. The create flow lives in the shared useNewSession hook — one
-// source of truth with the mobile NewSessionSheet.
+// The home owns one unsent draft. Files and voice stay in its Composer until
+// explicit Send binds the selected project/Agent and commits the first message.
export const Workbench: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
+ const surfaceActive = useRouteSurfaceActive();
+ const [sentSessionId, setSentSessionId] = useState<string | null>(null);
+ useEffect(() => {
+ if (surfaceActive && sentSessionId) navigate(`/chat/${encodeURIComponent(sentSessionId)}`);
+ }, [navigate, sentSessionId, surfaceActive]);
const location = useLocation();
const { capabilities } = useInstanceAuthorization();
const canCreateProject = canCreateLocalProject(capabilities);
@@ -67,10 +35,11 @@ export const Workbench: React.FC = () => {
active: capabilities.can_chat,
loadErrorText: t('newSession.loadError'),
createFailedText: t('newSession.createFailed'),
+ errorText: t,
});
const [newProjectOpen, setNewProjectOpen] = useState(false);
const [workspaceMenuOpen, setWorkspaceMenuOpen] = useState(false);
- const composerRef = useRef<ComposerHandle>(null);
+ const [newTaskOpen, setNewTaskOpen] = useState(false);
// The wizard hands `{ onboardingCompleted: true }` to this route. That is an
// event, not a property of the location — history state survives a reload, so
@@ -109,25 +78,22 @@ export const Workbench: React.FC = () => {
dismissed: bannerDismissed,
});
- // Returns whether the send actually started, so the Composer only clears the
- // box on a real start — a no-project nudge or a transient create error keeps
- // the typed prompt for retry. Navigation stays here (the hook is router-free).
- const send = async (text: string): Promise<boolean> => {
- const result = await ns.send(text);
+ const send = async (text: string, attachments: ComposerAttachment[] = []): Promise<boolean> => {
+ const result = await ns.send(text, attachments);
if (result) {
- // Hand the typed message to ChatPage as router state; it replays it
- // through the fire-and-forget compose path so the agent turn starts.
- navigate(`/chat/${encodeURIComponent(result.sessionId)}`, { state: { initialMessage: result.initialMessage } });
+ // The first POST has completed. Navigation only opens its transcript;
+ // handing initialMessage to ChatPage here would start a duplicate turn.
+ setSentSessionId(result.sessionId);
return true;
}
- if (text.trim() && ns.needsProject) setNewProjectOpen(true);
+ if ((text.trim() || attachments.length) && ns.needsProject && canCreateProject) setNewProjectOpen(true);
return false;
};
if (!capabilities.can_chat) return <Navigate to="/projects" replace />;
const workspaceLabel = ns.target?.display_name ?? t('workbench.home.chooseWorkspace');
- const workspaceChipClass = 'flex h-7 min-w-0 max-w-[220px] items-center gap-1.5 rounded-md px-2 text-[12px] text-muted transition-colors hover:bg-foreground/[0.06] hover:text-foreground disabled:pointer-events-none disabled:opacity-50';
+ const workspaceChipClass = 'flex h-7 min-w-0 max-w-full sm:max-w-[220px] items-center gap-1.5 rounded-md px-2 text-[12px] text-muted transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50';
const workspaceChipBody = (
<>
<span className="min-w-0 truncate">{workspaceLabel}</span>
@@ -200,37 +166,23 @@ export const Workbench: React.FC = () => {
<p className="max-w-[520px] text-[14px] leading-[1.5] text-muted">{t('workbench.home.heroBody')}</p>
</div>
- {/* Three starting points (design LDlvV): equal columns on desktop, stacked
- on a phone where 277-wide cards would be unreadable. */}
- <div className="grid w-full grid-cols-1 gap-3 sm:grid-cols-3">
- {SUGGESTIONS.map(({ key, icon: Icon, titleKey, bodyKey, draftKey }) => (
- <button
- key={key}
- type="button"
- onClick={() => composerRef.current?.setDraft(t(draftKey))}
- className="flex flex-col items-start gap-3 rounded-xl border border-border bg-surface-2 p-[18px] text-left transition-colors hover:border-border-strong hover:bg-foreground/[0.03]"
- >
- <Icon className="size-[19px] shrink-0 text-mint-ink" />
- <span className="flex flex-col gap-1">
- <span className="text-[13px] font-semibold text-foreground">{t(titleKey)}</span>
- <span className="text-[12px] leading-[1.5] text-muted">{t(bodyKey)}</span>
- </span>
- </button>
- ))}
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ <Button variant="outline" size="sm" disabled={ns.sending}
+ onClick={() => canCreateProject ? setNewProjectOpen(true) : setWorkspaceMenuOpen(true)}>
+ <FolderOpen className="size-4" />{t('workbench.home.openProject')}
+ </Button>
+ {capabilities.can_manage_agents && (
+ <Button variant="outline" size="sm" asChild>
+ <Link to="/agents"><Bot className="size-4" />{t('workbench.home.manageAgents')}</Link>
+ </Button>
+ )}
+ <Button variant="outline" size="sm" disabled={ns.sending} onClick={() => setNewTaskOpen(true)}>
+ <Clock className="size-4" />{t('workbench.home.createTask')}
+ </Button>
</div>
</div>
- {/* On a phone the page is taller than the screen (hero + three stacked
- cards + this block), so at rest its last ~80px sit under the fixed tab
- bar — and that is exactly where the composer's Agent, workspace and
- Send controls are: measured at 390x844, Send's centre hit-tests to the
- nav, so the button is dead until the user happens to scroll. Pinning
- this block to the bottom of the scroll area, one nav clearance above
- the bar, keeps the primary control reachable at any viewport height
- instead of trimming the rhythm above it to fit one phone. It stays a
- sticky child of the scrolling column rather than a fixed bar, so iOS
- keyboard panning still moves it with the page. Desktop is untouched:
- the column already fills the viewport and nothing overlaps it. */}
+ {/* Keep the action row above the mobile tab bar while the content scrolls. */}
<div className="flex flex-col gap-4 pb-2 max-md:sticky max-md:bottom-[var(--mobile-nav-clearance)] max-md:z-10 max-md:bg-background max-md:pt-3">
{/* A card that scrolls behind an opaque block reads as cut in half. The
short fade above it says "passing behind", which is what happens. */}
@@ -239,10 +191,11 @@ export const Workbench: React.FC = () => {
className="pointer-events-none absolute inset-x-0 -top-4 h-4 bg-gradient-to-t from-background to-transparent md:hidden"
/>
<Composer
- ref={composerRef}
+ stageMedia
onSend={send}
placeholder={t('workbench.home.inputPlaceholder')}
- disabled={ns.sending}
+ disabled={ns.sending || !ns.loaded}
+ sendDisabled={Boolean(ns.uncertainSessionId)}
actions={
<>
<AgentRoutePicker
@@ -254,7 +207,7 @@ export const Workbench: React.FC = () => {
: t('newSession.defaultAgent')}
disabled={ns.sending}
align="start"
- triggerClassName="h-7 max-w-[240px] rounded-md px-2 py-0"
+ triggerClassName="h-7 min-w-0 max-w-full sm:max-w-[240px] rounded-md border-transparent bg-transparent px-2 py-0 hover:bg-foreground/[0.06]"
/>
{workspaceChip}
</>
@@ -266,6 +219,12 @@ export const Workbench: React.FC = () => {
{ns.error && (
<div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive-ink">
{ns.error}
+ {ns.uncertainSessionId && (
+ <Link className="ml-2 underline underline-offset-2" target="_blank" rel="noopener noreferrer"
+ to={`/chat/${encodeURIComponent(ns.uncertainSessionId)}`}>
+ {t('newSession.inspectSession')}
+ </Link>
+ )}
</div>
)}
@@ -296,8 +255,10 @@ export const Workbench: React.FC = () => {
)}
</div>
+ {newTaskOpen && <CreateViaChatDialog kind="task" onClose={() => setNewTaskOpen(false)} />}
{newProjectOpen && canCreateProject && (
<NewProjectDialog
+ initialPath={ns.target?.folder_path}
onClose={() => setNewProjectOpen(false)}
onCreated={(project) => {
setNewProjectOpen(false);
diff --git a/ui/src/components/ui/directory-browser.tsx b/ui/src/components/ui/directory-browser.tsx
index ed207c150..2a9f7d13e 100644
--- a/ui/src/components/ui/directory-browser.tsx
+++ b/ui/src/components/ui/directory-browser.tsx
@@ -18,13 +18,13 @@ import {
LayoutGrid,
Monitor,
RefreshCw,
- X,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import { Button } from './button';
+import { Dialog, DialogContent, DialogTitle } from './dialog';
import { errorMessage } from '@/lib/errorMessage';
interface DirectoryBrowserProps {
@@ -120,6 +120,7 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
const reqIdRef = useRef(0);
useEffect(() => {
+ mountedRef.current = true;
return () => {
mountedRef.current = false;
};
@@ -129,21 +130,7 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
// shortcuts from Finder.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- // Escape precedence: cancel an in-progress folder create, else revert
- // manual path editing to the breadcrumb, else close the picker. Path
- // editing must be handled here (not just in the input) because this
- // window listener would otherwise close the whole picker on Esc.
- if (creating) {
- setCreating(false);
- setNewFolderName('');
- setCreateError(null);
- } else if (pathEditing) {
- setPathEditing(false);
- } else {
- onClose();
- }
- } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'n' && !creating) {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'n' && !creating) {
e.preventDefault();
setCreating(true);
}
@@ -341,45 +328,42 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
const canForward = historyIndex < history.length - 1;
return (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
- role="dialog"
- aria-modal="true"
- aria-label={t('directoryBrowser.title')}
- onClick={onClose}
- >
- <div
- className="flex h-[80vh] max-h-[720px] min-h-[560px] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-border-strong bg-surface shadow-[0_24px_64px_-12px_rgba(0,0,0,0.6)]"
- onClick={(e) => e.stopPropagation()}
+ <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>
+ <DialogContent
+ aria-describedby={undefined}
+ closeLabel={t('directoryBrowser.cancel')}
+ onEscapeKeyDown={(event) => {
+ if (creating || pathEditing) {
+ event.preventDefault();
+ setCreating(false);
+ setNewFolderName('');
+ setCreateError(null);
+ setPathEditing(false);
+ }
+ }}
+ 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"
>
{/* Traffic-light header */}
<div className="flex items-center gap-3 border-b border-border bg-surface-2 px-4 py-3">
<div className="flex items-center gap-2">
<button
type="button"
- aria-label="Close"
+ aria-label={t('directoryBrowser.cancel')}
onClick={onClose}
className="size-3 rounded-full bg-[#FF5F57] transition hover:brightness-110"
/>
<span className="size-3 rounded-full bg-[#FFBD2E]" />
<span className="size-3 rounded-full bg-[#28C840]" />
</div>
- <div className="flex flex-1 items-center justify-center gap-2 text-[13px] font-semibold text-foreground">
+ <DialogTitle className="flex flex-1 items-center justify-center gap-2 pr-8 text-[13px] font-semibold text-foreground">
<FolderOpen className="size-3.5 text-mint-ink" />
{t('directoryBrowser.title')}
- </div>
- <button
- type="button"
- onClick={onClose}
- aria-label={t('directoryBrowser.cancel')}
- className="text-muted transition hover:text-foreground"
- >
- <X className="size-4" />
- </button>
+ </DialogTitle>
+
</div>
{/* Toolbar — history arrows + breadcrumb + show-hidden + new-folder */}
- <div className="flex items-center gap-2 border-b border-border px-4 py-2.5">
+ <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-2.5">
<button
type="button"
onClick={goBack}
@@ -439,7 +423,7 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
{pathError && <div className="px-1 text-[10.5px] text-destructive-ink">{pathError}</div>}
</div>
) : (
- <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto rounded-md border border-border-strong bg-surface-2 px-2 py-1 font-mono text-[11px]">
+ <div className="flex min-w-[100px] flex-1 items-center gap-1 overflow-x-auto rounded-md border border-border-strong bg-surface-2 px-2 py-1 font-mono text-[11px]">
{breadcrumbs.map((crumb, i) => (
<React.Fragment key={`${crumb.path}-${i}`}>
{i > 0 && <ChevronRight className="size-3 shrink-0 text-muted" />}
@@ -646,7 +630,7 @@ export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
{t('directoryBrowser.select')}
</Button>
</div>
- </div>
- </div>
+ </DialogContent>
+ </Dialog>
);
};
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 7b6aac2e1..64861f540 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -55,6 +55,7 @@ import {
type VoiceRealtimeFinal,
} from '../../lib/voiceRealtime';
import {
+ MAX_WORKBENCH_ATTACHMENT_BYTES,
isWorkbenchUploadRetryable,
uploadWorkbenchAttachment,
workbenchUploadErrorTranslationKey,
@@ -83,7 +84,9 @@ export type ComposerAttachment = {
// reserves the image box and loading never shifts the transcript.
width?: number;
height?: number;
- status: 'uploading' | 'ready' | 'error';
+ status: 'staged' | 'uploading' | 'ready' | 'error';
+ /** Original file for a home draft; uploaded only after explicit Send. */
+ file?: File;
retryable?: boolean;
};
@@ -344,6 +347,8 @@ export interface ComposerProps {
/** Disable sending (e.g. while the caller creates a session + navigates).
* Also suppresses every live-turn control — see ``busyControls``. */
disabled?: boolean;
+ /** Keep a retained draft editable while an uncertain send is inspected. */
+ sendDisabled?: boolean;
/** Override the row container — e.g. a narrower max-width on the home canvas. */
className?: string;
/** Caller-owned controls (Agent + workspace pickers on the home). Supplying
@@ -351,9 +356,10 @@ export interface ComposerProps {
* carrying these on the left and Send on the right. Callers that pass nothing
* keep the single-row box the chat has always used. */
actions?: React.ReactNode;
- /** When set, enables file upload + voice input scoped to this session. The
- * Workbench home leaves it unset → a plain text-only composer. */
+ /** Upload + retained voice scope for an existing chat session. */
sessionId?: string;
+ /** Home drafts stage local files and transcribe voice without a server session. */
+ stageMedia?: boolean;
/** Focus the textarea on mount (desktop only — skipped on touch devices so it
* never pops the on-screen keyboard). The chat composer remounts per session,
* so this also covers opening / switching sessions. */
@@ -399,9 +405,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onDraftChange,
placeholder,
disabled = false,
+ sendDisabled = false,
className,
actions,
sessionId,
+ stageMedia = false,
autoFocus = false,
onSearchAgents,
onSearchSessions,
@@ -412,6 +420,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const voiceShortcutHint = t('chat.compose.voiceShortcutHint', { shortcut: voiceShortcutLabel });
const { showToast } = useToast();
const [value, setValue] = useState('');
+ const [homeVoiceKey] = useState(() => `draft:${newLocalId()}`);
+ const voiceKey = sessionId ?? (stageMedia ? homeVoiceKey : undefined);
+ const stagedUrlsRef = useRef(new Set<string>());
// The mention editor (Lexical) OWNS its text, so we don't mirror every
// keystroke into ``value`` there — a fast third-party IME (e.g. a voice
// keyboard like Typeless) inserts text in bursts, and re-rendering on each
@@ -439,7 +450,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const [recordingStarting, setRecordingStarting] = useState(false);
const [recording, setRecording] = useState(false);
const [restoringRecording, setRestoringRecording] = useState(() => (
- sessionId != null && voiceSessionLocksDraft(voiceSessionsById.get(sessionId))
+ voiceKey != null && voiceSessionLocksDraft(voiceSessionsById.get(voiceKey))
));
const [recordingSeconds, setRecordingSeconds] = useState(0);
const [realtimeAnnouncement, setRealtimeAnnouncement] = useState('');
@@ -458,9 +469,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const unmountedRef = useRef(false);
const disabledRef = useRef(disabled);
- // Upload + voice are scoped to a session (the upload endpoint needs one); the
- // home composer leaves them off.
- const mediaEnabled = Boolean(sessionId);
+ const mediaEnabled = Boolean(sessionId) || stageMedia;
const voiceDraftReadOnly = recordingStarting || recording || restoringRecording || transcribing;
useLayoutEffect(() => {
@@ -580,11 +589,21 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
setRealtimeAnnouncement('');
setVoiceRetainedSession(null);
setRestoringRecording(
- sessionId != null && voiceSessionLocksDraft(voiceSessionsById.get(sessionId)),
+ voiceKey != null && voiceSessionLocksDraft(voiceSessionsById.get(voiceKey)),
);
- }, [sessionId]);
+ }, [sessionId, voiceKey]);
+
+ useEffect(() => () => {
+ for (const url of stagedUrlsRef.current) URL.revokeObjectURL(url);
+ // A home draft has no durable chat to restore into after a real departure.
+ const voice = voiceSessionsById.get(homeVoiceKey);
+ voice?.abortController.abort();
+ voiceSessionsById.delete(homeVoiceKey);
+ }, [homeVoiceKey]);
const removeAttachment = (localId: string) => {
+ const url = attachments.find((attachment) => attachment.localId === localId)?.url;
+ if (url && stagedUrlsRef.current.delete(url)) URL.revokeObjectURL(url);
attachmentFilesRef.current.delete(localId);
setAttachments((cur) => cur.filter((a) => a.localId !== localId));
};
@@ -640,6 +659,23 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// update so the user sees the full batch at once, then upload with bounded
// concurrency so a big drop of large files doesn't flood memory / the endpoint.
const uploadFiles = async (files: File[]) => {
+ if (!mediaEnabled || disabledRef.current || pendingRef.current || voiceDraftLocked()) return;
+ if (stageMedia && !sessionId) {
+ const staged: ComposerAttachment[] = [];
+ for (const file of files) {
+ if (!file.size || file.size > MAX_WORKBENCH_ATTACHMENT_BYTES) {
+ showToast(t(file.size ? 'chat.compose.attachmentTooLarge' : 'chat.compose.attachmentEmpty'), 'error');
+ continue;
+ }
+ const url = file.type.startsWith('image/') ? URL.createObjectURL(file) : '';
+ if (url) stagedUrlsRef.current.add(url);
+ staged.push({ localId: newLocalId(), file, token: '', name: file.name,
+ mime: file.type || 'application/octet-stream', size: file.size,
+ kind: file.type.startsWith('image/') ? 'image' : 'file', url, status: 'staged' });
+ }
+ setAttachments((cur) => [...cur, ...staged]);
+ return;
+ }
if (!sessionId) return;
const sid = sessionId;
const staged = files.map((file) => ({ file, localId: newLocalId() }));
@@ -676,8 +712,8 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
|| recordingSessionRef.current !== null
|| transcribingRef.current
|| (
- sessionId != null
- && voiceSessionLocksDraft(voiceSessionsById.get(sessionId))
+ voiceKey != null
+ && voiceSessionLocksDraft(voiceSessionsById.get(voiceKey))
)
);
const captureVoiceInsertion = useCallback((): VoiceInsertionSnapshot => {
@@ -806,7 +842,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const presentVoiceSession = useCallback((session: VoiceRecordingSession) => {
const activeHere = (
!unmountedRef.current
- && sessionId === session.sessionId
+ && voiceKey === session.sessionId
&& voiceSessionsById.get(session.sessionId) === session
);
if (session.status === 'ready' && session.transcript) {
@@ -835,10 +871,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
retainSettledVoiceSession(session);
showToast(t(voiceErrorTranslationKey(session.error)), 'error');
}
- }, [insertVoiceTranscript, retainSettledVoiceSession, sessionId, showToast, t]);
+ }, [insertVoiceTranscript, retainSettledVoiceSession, voiceKey, showToast, t]);
const finishVoiceSession = async (session: VoiceRecordingSession) => {
- const activeHere = !unmountedRef.current && sessionId === session.sessionId;
+ const activeHere = !unmountedRef.current && voiceKey === session.sessionId;
if (activeHere) {
transcribingRef.current = true;
setTranscribing(true);
@@ -857,7 +893,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
};
const finishRealtimeVoiceSession = async (session: VoiceRecordingSession) => {
- const activeHere = !unmountedRef.current && sessionId === session.sessionId;
+ const activeHere = !unmountedRef.current && voiceKey === session.sessionId;
if (activeHere) {
transcribingRef.current = true;
setTranscribing(true);
@@ -930,12 +966,12 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}, [showToast, t]);
useEffect(() => {
- if (!sessionId) return;
+ if (!voiceKey) return;
let alive = true;
let timer: ReturnType<typeof setTimeout> | null = null;
const restore = () => {
if (!alive) return;
- const session = voiceSessionsById.get(sessionId);
+ const session = voiceSessionsById.get(voiceKey);
if (!session) {
setRestoringRecording(false);
return;
@@ -965,13 +1001,13 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
alive = false;
if (timer != null) clearTimeout(timer);
};
- }, [presentVoiceSession, sessionId]);
+ }, [presentVoiceSession, voiceKey]);
const startRecording = async (capturedInsertion?: VoiceInsertionSnapshot) => {
if (
- !sessionId
+ !voiceKey
|| recordingStartRef.current
- || voiceSessionsById.has(sessionId)
+ || voiceSessionsById.has(voiceKey)
) {
return;
}
@@ -1001,7 +1037,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const abortController = new AbortController();
const dictationId = newVoiceDictationId();
const session: VoiceRecordingSession = {
- sessionId,
+ sessionId: voiceKey,
dictationId,
abortController,
segments: [],
@@ -1093,7 +1129,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
session.realtime?.abort();
restoreRealtimePreview(session);
reportVoiceFinalization(session, 'empty');
- if (!unmountedRef.current && sessionId === session.sessionId) {
+ if (!unmountedRef.current && voiceKey === session.sessionId) {
showToast(t('chat.compose.voiceEmpty'), 'error');
}
deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);
@@ -1131,14 +1167,14 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const startedAt = Date.now();
session.startedAt = startedAt;
- const previous = voiceSessionsById.get(sessionId);
+ const previous = voiceSessionsById.get(voiceKey);
if (previous) {
// A retained batch may have settled while microphone setup was pending.
// Preserve it until the user explicitly retries or discards it.
pipeline.abort();
return;
}
- voiceSessionsById.set(sessionId, session);
+ voiceSessionsById.set(voiceKey, session);
setVoiceRetainedSession(null);
setRecordingSeconds(0);
recordingTickerRef.current = setInterval(() => {
@@ -1198,7 +1234,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}, recording);
const trimmed = value.trim();
- const readyAttachments = attachments.filter((a) => a.status === 'ready');
+ const readyAttachments = attachments.filter((a) => a.status === 'ready' || a.status === 'staged');
const uploading = attachments.some((a) => a.status === 'uploading');
// The mention path doesn't mirror its text into ``value`` (see onChange), so
// its "is there text?" signal comes from ``hasText``; the textarea path reads
@@ -1210,6 +1246,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const canSubmit =
(hasComposerText || readyAttachments.length > 0)
&& !uploading
+ && !sendDisabled
&& !disabled
&& !voiceDraftReadOnly;
// ``busy && disabled`` is an incoherent pair for ANY caller: ``disabled`` means
@@ -1321,6 +1358,12 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
voiceShortcutAvailable,
]);
+ // Home has no ChatPage shortcut owner. Scope its chord to the retained route
+ // so Settings and foreground picker dialogs keep their own keyboard input.
+ useRouteSurfaceWindowEvent('keydown', (event) => {
+ handleVoiceShortcut(event, true);
+ }, stageMedia);
+
// ChatPage owns the window listener because the shortcut applies across that
// page, while the composer remains the sole owner of voice state and actions.
// No deps array keeps every exposed operation on the latest render state.
@@ -1399,7 +1442,13 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
try {
// If the caller reports the send couldn't start (home no-project nudge),
// restore the prompt + attachments for retry — unless the user typed anew.
- const started = await onSend(submitted, sent, useMentions ? sentRefs : undefined);
+ let started: boolean | void;
+ try {
+ started = await onSend(submitted, sent, useMentions ? sentRefs : undefined);
+ } catch {
+ showToast(t('chat.compose.sendFailed'), 'error');
+ started = false;
+ }
if (started === false) {
if (!unmountedRef.current) {
setAttachments((cur) => (cur.length ? cur : sent));
@@ -1423,6 +1472,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}
onDraftChange?.(submitted);
}
+ } else {
+ for (const attachment of sent) {
+ if (stagedUrlsRef.current.delete(attachment.url)) URL.revokeObjectURL(attachment.url);
+ }
}
} finally {
pendingRef.current = false;
@@ -1459,7 +1512,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onClick={() => fileInputRef.current?.click()}
disabled={disabled}
aria-label={t('chat.compose.attach')}
- className="h-9 w-7 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'h-9 w-7 shrink-0'}
>
<Plus className="size-4" />
</Button>
@@ -1490,7 +1543,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
)}
aria-label={t('chat.compose.voice')}
title={voiceShortcutAvailable ? voiceShortcutHint : t('chat.compose.voice')}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<Mic className="size-4" />
</Button>
@@ -1516,7 +1569,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
size="icon"
disabled
aria-label={t('chat.compose.voiceProcessing')}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<Loader2 className="size-4 animate-spin" />
</Button>
@@ -1529,7 +1582,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onClick={() => void retryVoiceSession(voiceRetainedSession)}
aria-label={t('chat.compose.voiceRetry')}
title={t('chat.compose.voiceRetry')}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<RotateCcw className="size-4" />
</Button>
@@ -1542,7 +1595,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onClick={() => void copyReadyVoiceTranscript(voiceRetainedSession)}
aria-label={t('chat.compose.voiceCopyTranscript')}
title={t('chat.compose.voiceCopyTranscript')}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<Copy className="size-4" />
</Button>
@@ -1605,6 +1658,19 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
ref={textareaRef}
value={value}
onChange={(e) => update(e.target.value)}
+ onPaste={(event) => {
+ const files = Array.from(event.clipboardData.files);
+ if (mediaEnabled && files.length && !disabled && !voiceDraftReadOnly) {
+ event.preventDefault();
+ void uploadFiles(files);
+ }
+ }}
+ onDragOver={(event) => { if (mediaEnabled && event.dataTransfer.types.includes('Files')) event.preventDefault(); }}
+ onDrop={(event) => {
+ if (!mediaEnabled || !event.dataTransfer.files.length) return;
+ event.preventDefault();
+ void uploadFiles(Array.from(event.dataTransfer.files));
+ }}
onKeyDown={(e) => {
// Enter sends, Shift+Enter newline — EXCEPT while the on-screen
// keyboard is open (mobile), where Enter inserts a newline and Send is
@@ -1622,7 +1688,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
disabled={disabled}
readOnly={voiceDraftReadOnly}
placeholder={busyControls ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
- className="max-h-40 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"
+ className="max-h-40 min-h-9 min-w-0 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"
/>
)}
</>
@@ -1650,7 +1716,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onClick={submit}
aria-label={t('chat.compose.queueSend')}
title={t('chat.compose.queueSend')}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<span className="relative inline-flex">
<Send className="size-4" />
@@ -1668,7 +1734,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onClick={onStop}
disabled={!stopArmed}
aria-label={t('chat.compose.stop')}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<Square className="size-4" />
</Button>
@@ -1681,7 +1747,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onClick={submit}
disabled={!canSubmit}
aria-label={t('chat.compose.send')}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<Send className="size-4" />
</Button>
@@ -1704,7 +1770,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
? 'chat.compose.cancelRecording'
: 'chat.compose.voiceDiscard',
)}
- className="size-9 shrink-0"
+ className={actions ? 'size-7 shrink-0' : 'size-9 shrink-0'}
>
<Trash2 className="size-4" />
</Button>
@@ -1774,12 +1840,12 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
/* Two-row box (design TfqkD): the input on top, then an action row
carrying the caller's pickers on the left and Send on the right. */
<div className="flex w-full flex-col gap-[22px] rounded-2xl border border-border-strong bg-surface-2 p-[18px] shadow-[0_-4px_24px_-12px_rgba(0,0,0,0.5)]">
- <div className="flex w-full items-end gap-1.5">
- {mediaControls}
- {inputControl}
- </div>
- <div className="flex w-full items-center justify-between gap-4">
- <div className="flex min-w-0 items-center gap-4">{actions}</div>
+ <div className="flex w-full items-end gap-1.5">{inputControl}</div>
+ <div className="flex w-full items-end justify-between gap-2">
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1">
+ {mediaControls}
+ {actions}
+ </div>
<div className="flex shrink-0 items-center gap-1.5">{sendControls}</div>
</div>
</div>
diff --git a/ui/src/components/workbench/NewProjectDialog.test.tsx b/ui/src/components/workbench/NewProjectDialog.test.tsx
new file mode 100644
index 000000000..49d9dece5
--- /dev/null
+++ b/ui/src/components/workbench/NewProjectDialog.test.tsx
@@ -0,0 +1,17 @@
+/* @vitest-environment jsdom */
+import { cleanup, fireEvent, render, screen } 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() }) }));
+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';
+afterEach(cleanup);
+it.each([undefined, '/工作区/当前项目'])('starts from the caller directory (%s), then reopens the selected directory', (initialPath) => {
+ render(<NewProjectDialog initialPath={initialPath} onClose={() => {}} onCreated={() => {}} />);
+ expect(screen.getByTestId('directory').getAttribute('data-path')).toBe(initialPath ?? null);
+ fireEvent.click(screen.getByTestId('directory'));
+ fireEvent.click(screen.getByText('workbench.newProjectDialog.pickFolder'));
+ expect(screen.getByTestId('directory').getAttribute('data-path')).toBe('/工作区/选择的项目');
+});
diff --git a/ui/src/components/workbench/NewProjectDialog.tsx b/ui/src/components/workbench/NewProjectDialog.tsx
index d435bb507..f354180b3 100644
--- a/ui/src/components/workbench/NewProjectDialog.tsx
+++ b/ui/src/components/workbench/NewProjectDialog.tsx
@@ -10,6 +10,7 @@ import { Input } from '../ui/input';
import { errorMessage } from '@/lib/errorMessage';
interface NewProjectDialogProps {
+ initialPath?: string;
onClose: () => void;
/** The project is already in the shared tree by the time this fires — the
* provider owns that commit so it can fence it against an authorization
@@ -23,7 +24,7 @@ interface NewProjectDialogProps {
// then a compact confirm card lets the user override the display name and
// fire the create call. The backend defaults display_name to the folder
// basename — keep the input empty to accept that default.
-export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onCreated }) => {
+export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onCreated, initialPath }) => {
const { t } = useTranslation();
const { createProject } = useWorkbenchProjectsActions();
const [phase, setPhase] = useState<'pick' | 'confirm'>('pick');
@@ -35,6 +36,7 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onC
if (phase === 'pick') {
return (
<DirectoryBrowser
+ initialPath={folderPath || initialPath}
onClose={onClose}
onSelect={(path) => {
setFolderPath(path);
diff --git a/ui/src/components/workbench/NewSessionSheet.tsx b/ui/src/components/workbench/NewSessionSheet.tsx
index 10ce41663..670ae3b8b 100644
--- a/ui/src/components/workbench/NewSessionSheet.tsx
+++ b/ui/src/components/workbench/NewSessionSheet.tsx
@@ -1,5 +1,5 @@
import { useState } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useNewSession } from '../../lib/useNewSession';
@@ -18,7 +18,7 @@ interface NewSessionSheetProps {
// The workbench center + opens this instead of jumping to the home canvas.
// Pick a project (chips, most-recent first), describe the task, and it creates
-// the session + routes to /chat with the message pre-seeded — the same flow as
+// the session + submits the message before routing to /chat — the same flow as
// the desktop Workbench home, surfaced as a mobile bottom sheet (design.pen KSXXB).
// The create flow itself lives in the shared useNewSession hook (one source of
// truth with the home); the sheet only owns its open/close + draft lifecycle.
@@ -32,12 +32,17 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
active: open,
loadErrorText: t('newSession.loadError'),
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.
const [pendingDraft, setPendingDraft] = useState('');
const [newProjectOpen, setNewProjectOpen] = useState(false);
+ const close = () => {
+ setPendingDraft('');
+ onClose();
+ };
// 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
@@ -63,9 +68,7 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
if (result) {
setPendingDraft('');
const navigateToSession = () =>
- navigate(`/chat/${encodeURIComponent(result.sessionId)}`, {
- state: { initialMessage: result.initialMessage },
- });
+ navigate(`/chat/${encodeURIComponent(result.sessionId)}`);
if (authorization) authorization.runNavigation(navigateToSession);
else navigateToSession();
onClose();
@@ -82,7 +85,7 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
return (
<>
- <Dialog open={open} onOpenChange={(o) => { if (!o && !ns.sending) onClose(); }}>
+ <Dialog open={open} onOpenChange={(o) => { if (!o && !ns.sending) close(); }}>
<DialogContent className="gap-5" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogTitle className="text-lg font-bold">{t('newSession.title')}</DialogTitle>
@@ -104,13 +107,18 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
align="start"
triggerClassName="w-full max-w-full"
modal
- onNavigateAway={onClose}
+ onNavigateAway={close}
/>
</div>
{ns.error && (
<div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive-ink">
{ns.error}
+ {ns.uncertainSessionId && (
+ <Link className="ml-2 underline" to={`/chat/${encodeURIComponent(ns.uncertainSessionId)}`} target="_blank" rel="noopener noreferrer">
+ {t('newSession.inspectSession')}
+ </Link>
+ )}
</div>
)}
@@ -121,6 +129,7 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
onSend={send}
placeholder={t('newSession.placeholder')}
disabled={ns.sending || !ns.loaded}
+ sendDisabled={Boolean(ns.uncertainSessionId)}
initialDraft={pendingDraft}
/>
</DialogContent>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7938fcfd2..81b90cd23 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -170,6 +170,8 @@
"loadFailed": "Couldn't load — tap to retry"
},
"newSession": {
+ "sendUncertain": "The send result is unknown. Your draft is kept here. Open the conversation to check before sending again.",
+ "inspectSession": "Open conversation",
"title": "New session",
"project": "Project",
"newProject": "New",
@@ -2518,7 +2520,7 @@
"placeholderTitle": "Your AI workbench is coming together",
"placeholderBody": "Agents, Skills, Harness, and Vaults will live here. For now, jump into the control panel to configure platforms and backends.",
"home": {
- "heroTitle": "What would you like to do?",
+ "heroTitle": "What would you like to build today?",
"heroBody": "Pick a starting point, or describe your own task",
"suggestions": {
"exploreTitle": "Explore a project",
@@ -2532,6 +2534,9 @@
"planDraft": "Help me turn this goal into a concrete step-by-step plan"
},
"inputPlaceholder": "Describe a task or ask a question...",
+ "openProject": "Open project",
+ "manageAgents": "Manage Agents",
+ "createTask": "Create background task",
"chooseWorkspace": "Choose a workspace",
"workspaceAria": "Workspace: {{path}}",
"noProjectForChat": "No projects yet — add one before starting a chat",
@@ -4226,6 +4231,7 @@
}
},
"compose": {
+ "sendFailed": "Could not send. Your draft has been kept for retry.",
"placeholder": "Type a message…",
"placeholderBusy": "Type to queue while the agent works…",
"placeholderArchived": "This session is archived — read-only",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 2faeda57c..e354fb648 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -170,6 +170,8 @@
"loadFailed": "加载失败,点击重试"
},
"newSession": {
+ "sendUncertain": "发送结果暂时无法确认,草稿已保留。请先打开会话查看,避免重复发送。",
+ "inspectSession": "查看会话",
"title": "新建会话",
"project": "选择项目",
"newProject": "新项目",
@@ -2518,7 +2520,7 @@
"placeholderTitle": "你的 AI 工作台正在搭建",
"placeholderBody": "Agents、Skills、Harness、Vaults 将会汇聚到这里。现在先进控制面板配置平台和 backend。",
"home": {
- "heroTitle": "你想做什么?",
+ "heroTitle": "今天想搭点什么?",
"heroBody": "从一个真实任务开始,助手可以规划、研究和构建",
"suggestions": {
"exploreTitle": "探索项目",
@@ -2532,6 +2534,9 @@
"planDraft": "帮我把这个目标拆成具体、可执行的步骤"
},
"inputPlaceholder": "给你的助手安排任务…",
+ "openProject": "打开项目",
+ "manageAgents": "管理 Agents",
+ "createTask": "建后台任务",
"chooseWorkspace": "选择工作区",
"workspaceAria": "工作区:{{path}}",
"noProjectForChat": "还没有项目 — 先添加一个,再开始对话",
@@ -4226,6 +4231,7 @@
}
},
"compose": {
+ "sendFailed": "发送失败,草稿已保留,可重试。",
"placeholder": "输入消息…",
"placeholderBusy": "Agent 处理中,输入将排队…",
"placeholderArchived": "会话已归档,仅可查看",
diff --git a/ui/src/lib/useNewSession.lifecycle.test.tsx b/ui/src/lib/useNewSession.lifecycle.test.tsx
new file mode 100644
index 000000000..c3bdaae93
--- /dev/null
+++ b/ui/src/lib/useNewSession.lifecycle.test.tsx
@@ -0,0 +1,141 @@
+/* @vitest-environment jsdom */
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { ComposerAttachment } from '../components/workbench/Composer';
+const mocks = vi.hoisted(() => ({
+ create: vi.fn(), upload: vi.fn(), fetch: vi.fn(), events: undefined as undefined | (() => void),
+ projects: [
+ { id: '中文项目', capabilities: { can_chat: true }, created_at: '2026-09-19T00:00:00Z' },
+ { id: '其他项目', capabilities: { can_chat: true }, created_at: '2026-09-18T00:00:00Z' },
+ ],
+}));
+const api = {
+ listVibeAgents: async () => ({ agents: [{ id: 'a', name: 'codex', backend: 'codex', enabled: true }], default_agent_name: 'codex' }),
+ connectWorkbenchEvents: ({ onAuthorizationChanged }: { onAuthorizationChanged: () => void }) => {
+ mocks.events = onAuthorizationChanged;
+ return () => {};
+ },
+};
+vi.mock('../context/ApiContext', () => ({ useApi: () => api }));
+vi.mock('../context/WorkbenchProjectsContext', () => ({ useWorkbenchProjectsTree: () => ({ projects: mocks.projects, projectsError: null, createSessionForProject: mocks.create }) }));
+vi.mock('./apiFetch', () => ({ apiFetch: mocks.fetch }));
+vi.mock('./workbenchUpload', async (original) => ({ ...await original<typeof import('./workbenchUpload')>(), uploadWorkbenchAttachment: mocks.upload }));
+import { useNewSession } from './useNewSession';
+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(() => {
+ mocks.create.mockReset().mockImplementation(async () => ({ id: `session-${mocks.create.mock.calls.length}` }));
+ mocks.upload.mockReset().mockResolvedValue({ token: 'token', name: '中文.txt', mime: 'text/plain', size: 6, kind: 'file', url: '/api/media/token' });
+ mocks.fetch.mockReset().mockResolvedValue(new Response('{}', { status: 201 }));
+});
+afterEach(cleanup);
+it('creates and submits once from a same-tick double send, only after explicit input', async () => {
+ const { result } = mount();
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ expect(mocks.create).not.toHaveBeenCalled();
+ await act(async () => { await Promise.all([result.current.send('', [attachment]), result.current.send('', [attachment])]); });
+ expect(mocks.create).toHaveBeenCalledTimes(1);
+ expect(mocks.fetch).toHaveBeenCalledTimes(1);
+ expect(mocks.upload).toHaveBeenCalledWith('session-1', attachment.file, attachment.localId);
+});
+it('preserves successful uploads for retry but creates a fresh media scope when the selection changes', async () => {
+ const { result } = mount();
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ mocks.fetch.mockResolvedValueOnce(new Response('{"state":"retired"}', { status: 502 }));
+ await act(async () => { expect(await result.current.send('初稿', [attachment])).toBeNull(); });
+ act(() => result.current.setSelected('其他项目'));
+ await act(async () => { await result.current.send('初稿', [attachment]); });
+ expect(mocks.create).toHaveBeenNthCalledWith(2, '其他项目', {});
+ expect(mocks.upload).toHaveBeenNthCalledWith(2, 'session-2', attachment.file, attachment.localId);
+});
+it('captures the project and Agent at Send rather than reading later live selections', async () => {
+ let release!: (session: { id: string }) => void;
+ mocks.create.mockReturnValue(new Promise((resolve) => { release = resolve; }));
+ const { result } = mount();
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ let submission!: ReturnType<typeof result.current.send>;
+ act(() => { submission = result.current.send('中文', [attachment]); });
+ act(() => result.current.setSelected('其他项目'));
+ await act(async () => { release({ id: 'captured-session' }); await submission; });
+ expect(mocks.create).toHaveBeenCalledWith('中文项目', {});
+ expect(mocks.upload).toHaveBeenCalledWith('captured-session', attachment.file, attachment.localId);
+ expect(mocks.fetch.mock.calls[0][0]).toBe('/api/sessions/captured-session/messages');
+});
+it('authorization changes terminate a pending submission before upload or dispatch', async () => {
+ let release!: (session: { id: string }) => void;
+ mocks.create.mockReturnValue(new Promise((resolve) => { release = resolve; }));
+ const { result } = mount();
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ let submission!: ReturnType<typeof result.current.send>;
+ act(() => { submission = result.current.send('中文', [attachment]); });
+ await act(async () => { mocks.events?.(); });
+ await act(async () => { release({ id: 'captured-session' }); expect(await submission).toBeNull(); });
+ expect(mocks.upload).not.toHaveBeenCalled();
+ expect(mocks.fetch).not.toHaveBeenCalled();
+});
+it.each(['network', 'pending'])('uncertain %s admission cannot be resubmitted', async (kind) => {
+ const { result } = mount();
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ if (kind === 'network') mocks.fetch.mockRejectedValue(new Error('lost acknowledgment'));
+ else mocks.fetch.mockResolvedValue(new Response('{"dispatch_error":"dispatch_pending"}', { status: 504 }));
+ await act(async () => { expect(await result.current.send('中文', [attachment])).toBeNull(); });
+ expect(result.current.uncertainSessionId).toBe('session-1');
+ await act(async () => { expect(await result.current.send('中文', [attachment])).toBeNull(); });
+ expect(mocks.fetch).toHaveBeenCalledTimes(1);
+});
+
+it('a fresh sheet open starts a new submission lifetime after an uncertain send', async () => {
+ const { result, rerender } = renderHook(({ active }) => useNewSession({ active, loadErrorText: 'load failed', createFailedText: 'send failed' }), { initialProps: { active: true } });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ mocks.fetch.mockRejectedValueOnce(new Error('lost acknowledgment'));
+ await act(async () => { await result.current.send('第一条'); });
+ expect(result.current.uncertainSessionId).toBe('session-1');
+ rerender({ active: false });
+ rerender({ active: true });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ expect(result.current.uncertainSessionId).toBeNull();
+ await act(async () => { expect(await result.current.send('新的对话')).toEqual({ sessionId: 'session-2' }); });
+ expect(mocks.create).toHaveBeenCalledTimes(2);
+});
+
+it.each(['create', 'message'])('a response from the closed sheet %s cannot alter a new sheet lifetime', async (stage) => {
+ let release!: (value: unknown) => void;
+ const held = new Promise((resolve) => { release = resolve; });
+ if (stage === 'create') mocks.create.mockReturnValueOnce(held);
+ else mocks.fetch.mockReturnValueOnce(held);
+ const { result, rerender } = renderHook(({ active }) => useNewSession({ active, loadErrorText: 'load failed', createFailedText: 'send failed' }), { initialProps: { active: true } });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ let prior!: ReturnType<typeof result.current.send>;
+ act(() => { prior = result.current.send('旧对话'); });
+ await waitFor(() => expect(stage === 'create' ? mocks.create : mocks.fetch).toHaveBeenCalledTimes(1));
+ rerender({ active: false });
+ rerender({ active: true });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ await act(async () => {
+ release(stage === 'create' ? { id: 'old-session' } : new Response('{"dispatch_error":"dispatch_pending"}', { status: 504 }));
+ expect(await prior).toBeNull();
+ });
+ expect(result.current.uncertainSessionId).toBeNull();
+ await act(async () => { expect(await result.current.send('新对话')).not.toBeNull(); });
+ expect(mocks.create).toHaveBeenCalledTimes(2);
+});
+
+it.each([403, 404, 409])('terminal message HTTP %s discards only the invalid scope, preserving the original file for retry', async (status) => {
+ const { result } = mount();
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ mocks.fetch.mockResolvedValueOnce(new Response('{"error":"session unavailable"}', { status }));
+ await act(async () => { expect(await result.current.send('重试', [attachment])).toBeNull(); });
+ 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('a missing upload session gets a new scope on explicit retry', async () => {
+ const { WorkbenchUploadError } = await import('./workbenchUpload');
+ mocks.upload.mockRejectedValueOnce(new WorkbenchUploadError('session_not_found', 'missing', 404));
+ const { result } = mount();
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ await act(async () => { expect(await result.current.send('', [attachment])).toBeNull(); });
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ await act(async () => { expect(await result.current.send('', [attachment])).toEqual({ sessionId: 'session-2' }); });
+ expect(mocks.upload).toHaveBeenNthCalledWith(2, 'session-2', attachment.file, attachment.localId);
+});
diff --git a/ui/src/lib/useNewSession.ts b/ui/src/lib/useNewSession.ts
index 8164dd2d8..9400d8e8d 100644
--- a/ui/src/lib/useNewSession.ts
+++ b/ui/src/lib/useNewSession.ts
@@ -1,9 +1,14 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useApi } from '../context/ApiContext';
import { useWorkbenchProjectsTree } from '../context/WorkbenchProjectsContext';
import type { ApiContextType, VibeAgentBrief, WorkbenchProject, WorkbenchSessionCreate } from '../context/ApiContext';
import { sortProjectsByRecent } from './projectOrder';
+import { apiFetch } from './apiFetch';
+import { uploadWorkbenchAttachment, workbenchUploadErrorTranslationKey, WorkbenchUploadError, type WorkbenchUploadResult } from './workbenchUpload';
+import type { ComposerAttachment } from '../components/workbench/Composer';
+import { useRouteSurfaceActive } from './routeSurfaceActivity';
+import type { TranslationKey } from '../i18n/types';
interface UseNewSessionOptions {
/** Re-run the per-open reset on the rising edge — sheets pass their `open`. Default true. */
@@ -11,6 +16,8 @@ interface UseNewSessionOptions {
/** Pre-translated copy: the hook stays i18n-free, callers pass t(...) strings. */
loadErrorText: string;
createFailedText: string;
+ /** Media/send errors use the same localized policy as the chat composer. */
+ errorText?: (key: TranslationKey) => string;
}
// The agent/model/effort selection (agent route). Empty = the server default
@@ -31,6 +38,7 @@ export interface NewSessionState {
loaded: boolean;
error: string | null;
sending: boolean;
+ uncertainSessionId: string | null;
selectedId: string | null;
setSelected: (id: string) => void;
target: WorkbenchProject | null;
@@ -43,9 +51,9 @@ export interface NewSessionState {
effectiveDefaultAgentName: string | null;
agentRoute: AgentRouteSelection;
setAgentRoute: (patch: AgentRouteSelection) => void;
- /** Creates a session under `target` (with the picked agent route, if any) and returns the
- * nav target; null if it couldn't start. The hook never navigates — the caller does. */
- send: (text: string) => Promise<{ sessionId: string; initialMessage: string } | null>;
+ /** Creates the selected session, uploads staged files, submits once, then
+ * returns the navigation target. Failures leave the caller's draft intact. */
+ send: (text: string, attachments?: ComposerAttachment[]) => Promise<{ sessionId: string } | null>;
upsertSelectProject: (project: WorkbenchProject) => void;
}
@@ -122,8 +130,9 @@ export function createLatestAgentProjectionLoader(
// selections (project + agent route), the transient sending/error state, and
// target resolution. Navigation + draft + the sheet's open/close lifecycle stay
// in the consumer.
-export function useNewSession({ active = true, loadErrorText, createFailedText }: UseNewSessionOptions): NewSessionState {
+export function useNewSession({ active = true, loadErrorText, createFailedText, errorText }: UseNewSessionOptions): NewSessionState {
const api = useApi();
+ const surfaceActive = useRouteSurfaceActive();
// `active` already gates the agent projection below; pass it to the tree too.
// NewSessionSheet is mounted shell-wide, so an unconditional read would make
// the tree bootstrap on every route again — exactly what activation prevents.
@@ -135,6 +144,24 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
const [selectedId, setSelectedId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [sending, setSending] = useState(false);
+ const sendingRef = useRef(false);
+ const [uncertainSessionId, setUncertainSessionId] = useState<string | null>(null);
+ const uncertainRef = useRef<string | null>(null);
+ const lifetime = useRef({ mounted: true, active, authorization: 0, generation: 0 });
+ lifetime.current.active = active && surfaceActive;
+ useEffect(() => {
+ const current = lifetime.current;
+ current.mounted = true;
+ return () => { current.mounted = false; };
+ }, []);
+ // Only failed submissions keep a session. A retry under the same selection
+ // reuses its upload scope; a different selection gets a new scope and uploads
+ // the original files again. No session exists before the first explicit Send.
+ const pendingSessionRef = useRef<{
+ selection: string;
+ id: string;
+ uploads: Map<string, WorkbenchUploadResult>;
+ } | null>(null);
const [agents, setAgents] = useState<VibeAgentBrief[]>([]);
const [defaultAgentName, setDefaultAgentName] = useState<string | null>(null);
const [agentProjectionLoaded, setAgentProjectionLoaded] = useState(false);
@@ -178,6 +205,7 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
void loader.load();
const disconnect = api.connectWorkbenchEvents({
onAuthorizationChanged: () => {
+ lifetime.current.authorization += 1;
void loader.load();
},
});
@@ -187,11 +215,16 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
};
}, [active, api]);
- // Clear transient state when the sheet (re)opens so a prior submit / error
- // doesn't leak into the next open. The home passes active=true (runs once).
+ // A sheet open owns one submission lifetime. Closing discards that lifetime;
+ // late responses cannot lock or navigate a later fresh sheet. Settings only
+ // changes surfaceActive, so its retained home draft keeps the same lifetime.
useEffect(() => {
- if (!active) return;
+ lifetime.current.generation += 1;
+ sendingRef.current = false;
+ pendingSessionRef.current = null;
+ uncertainRef.current = null;
setSending(false);
+ setUncertainSessionId(null);
setError(null);
}, [active]);
@@ -279,10 +312,18 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
: defaultAgentName;
const send = useCallback(
- async (text: string): Promise<{ sessionId: string; initialMessage: string } | null> => {
+ async (text: string, attachments: ComposerAttachment[] = []): Promise<{ sessionId: string } | null> => {
const trimmed = text.trim();
// Never create from a stale/empty/in-flight state; no target → caller opens New Project.
- if (!trimmed || sending || !loaded || !target) return null;
+ if (uncertainRef.current) return null;
+ const authorization = lifetime.current.authorization;
+ const generation = lifetime.current.generation;
+ const currentAttempt = () => lifetime.current.mounted && lifetime.current.generation === generation;
+ const stillAuthorized = () => currentAttempt() && lifetime.current.active
+ && lifetime.current.authorization === authorization;
+ const files = attachments;
+ if (!stillAuthorized() || (!trimmed && files.length === 0) || sendingRef.current || !loaded || !target) return null;
+ sendingRef.current = true;
setSending(true);
setError(null);
// routeForCreate pins a user pick or a project default; the bare global
@@ -301,15 +342,86 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
}
if (routeForCreate.model) overrides.model = routeForCreate.model;
if (routeForCreate.reasoning_effort) overrides.reasoning_effort = routeForCreate.reasoning_effort;
- const session = await createSessionForProject(target.id, overrides);
- setSending(false);
- if (!session) {
- setError(createFailedText);
+ const selection = JSON.stringify([target.id, overrides]);
+ try {
+ let pending = pendingSessionRef.current;
+ if (!pending || pending.selection !== selection) {
+ const session = await createSessionForProject(target.id, overrides);
+ if (!currentAttempt()) return null;
+ if (!session) throw new Error(createFailedText);
+ pending = { selection, id: session.id, uploads: new Map() };
+ pendingSessionRef.current = pending;
+ }
+ if (!stillAuthorized()) return null;
+ const uploaded: WorkbenchUploadResult[] = [];
+ for (const attachment of files) {
+ if (!stillAuthorized()) return null;
+ // A home attachment always carries its original file, never a token
+ // from some other session. Upload IDs make same-scope retries safe.
+ if (!attachment.file) throw new Error(createFailedText);
+ let result = pending.uploads.get(attachment.localId);
+ if (!result) {
+ result = await uploadWorkbenchAttachment(pending.id, attachment.file, attachment.localId);
+ pending.uploads.set(attachment.localId, result);
+ }
+ uploaded.push(result);
+ }
+ if (!stillAuthorized()) return null;
+ // Ordinary message POST has no caller-supplied idempotency key. A
+ // lost response or dispatch_pending can already have started a turn;
+ // keep the draft and require inspection instead of offering resend.
+ const uncertain = () => {
+ if (!currentAttempt()) return;
+ uncertainRef.current = pending.id;
+ setUncertainSessionId(pending.id);
+ setError(errorText?.('newSession.sendUncertain') ?? createFailedText);
+ };
+ let response: Response;
+ try {
+ response = await apiFetch(`/api/sessions/${encodeURIComponent(pending.id)}/messages`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ text: trimmed, ...(uploaded.length ? { content: { text: trimmed, attachments: uploaded } } : {}) }),
+ });
+ } catch {
+ uncertain();
+ return null;
+ }
+ if (!currentAttempt()) return null;
+ if (!response.ok) {
+ const body = await response.json().catch(() => null);
+ if (!currentAttempt()) return null;
+ const rejected = body?.state === 'retired'
+ || ([400, 403, 404, 409, 422].includes(response.status) && body?.dispatch_error !== 'dispatch_pending');
+ if (!rejected) {
+ uncertain();
+ return null;
+ }
+ if ([403, 404, 409].includes(response.status)) pendingSessionRef.current = null;
+ throw new Error(createFailedText);
+ }
+ const sessionId = pending.id;
+ pendingSessionRef.current = null;
+ return { sessionId };
+ } catch (error) {
+ if (!currentAttempt()) return null;
+ // Retryable failures retain successful upload progress. A terminal
+ // session boundary requires a new scope while the caller keeps Files.
+ if (error instanceof WorkbenchUploadError && (
+ error.code === 'session_not_found' || [403, 404, 409].includes(error.status ?? 0)
+ )) pendingSessionRef.current = null;
+ setError(error instanceof WorkbenchUploadError && errorText
+ ? errorText(workbenchUploadErrorTranslationKey(error))
+ : createFailedText);
return null;
+ } finally {
+ if (currentAttempt()) {
+ sendingRef.current = false;
+ setSending(false);
+ }
}
- return { sessionId: session.id, initialMessage: trimmed };
},
- [sending, loaded, target, routeForCreate, agents, createSessionForProject, createFailedText],
+ [loaded, target, routeForCreate, agents, createSessionForProject, createFailedText, errorText],
);
// The dialog already committed the row through the provider (fenced against a
@@ -327,6 +439,7 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
loaded,
error: visibleError,
sending,
+ uncertainSessionId,
selectedId,
setSelected: setSelectedId,
target,