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(ui): unify folder browser with Files app

Call White9c01e8e483c1
diff --git a/docs/plans/folder-picker-delivery-diagnosis.md b/docs/plans/folder-picker-delivery-diagnosis.md
new file mode 100644
index 000000000..70d316b37
--- /dev/null
+++ b/docs/plans/folder-picker-delivery-diagnosis.md
@@ -0,0 +1,143 @@
+# Folder picker delivery diagnosis
+
+## Circuit-breaker decision — 2026-09-23
+
+At the navigation-owner decision, PR #2115 had 12 findings-bearing reviewed
+heads and no clean review. GitHub's complete inventory contained 30 finding
+threads, 27 resolved and three open. Reviewed heads are bound through the
+review's commit, not the mutable inline-comment diff location.
+
+| Reviewed head | Root causes in its findings |
+| --- | --- |
+| fe992a7aa6 | Modal keyboard ownership; listing vs operation validity; initial fallback readiness; pending search presentation; truncation |
+| 001682fd51 | Failed favorites fallback; overlay containment; search vs creation lifetime |
+| 6b3d1934f9 | Configured path compatibility; hidden-file refresh; search preservation |
+| d3e26afef2 | Initial resolver lifetime; listing/search refresh consistency |
+| 76742047da | StrictMode lifetime |
+| 7399333512 | Stale initial completion; pending destination refresh; overlay containment; retained creation draft; project fallback failure |
+| 69cc604168 | Upload drop-region ownership; arbitrary path entry; configured symlink compatibility |
+| 6803e37ac0 | Stale manual submission |
+| b902cfec5b | Retained path editor focus |
+| ad888b312d | Stale initial error |
+| abf628c72f | Repeated refresh/search race; favorite and fallback symlink compatibility |
+| 09e7a3c1ea | Stale creation completion; lost navigation history; stale consuming fixture |
+| 2fb7dd9676 | Omitted creation shortcut; lost localized system-favorite labels |
+
+The repeated async-ownership class and the post-extraction head count both
+trip the breaker. Further isolated callback patches are paused. Inspection of
+the diff and the consuming `home-media/sheet-suspension.spec.ts` shows two causes:
+
+1. Initial resolution, favorite resolution, manual submission and listing use
+ independently invalidated identities. Starting a favorite does not invalidate
+ an older listing; editing text can invalidate a favorite without releasing
+ its busy state. Folder creation has no completion fence.
+2. The shared UI extraction did not preserve the full picker interaction
+ contract. History and caret retention disappeared, and the consuming browser
+ fixture still mocks the removed listing transport. Passing focused unit tests
+ did not exercise this contract.
+
+## Scope decision
+
+Keep the shared FileBrowser surface and Files API. No backend, installer,
+permission model, global router or unrelated Files operation changes are needed.
+Consolidate the picker's navigation into one latest-request owner covering
+resolution, listing, errors, busy state and history commit. Reuse the previous
+picker's retained-editor selection behavior. Keep creation identity separate
+from navigation, but invalidate it on navigation, cancellation or a newer draft.
+This is local, reversible and preserves the selection contract.
+
+- Canonicalize external paths (initial, fallback, favorites and manual input);
+ list already-canonical rows, breadcrumbs and history directly.
+- Only the latest navigation can publish a listing, error or history entry.
+ Refresh retains a pending destination, its history intent and the search.
+ Successful navigation alone commits history; failed/stale requests do not.
+ Search results/errors are scoped to directory, query, hidden setting and
+ refresh revision. A local deferred-response test reproduced source-folder
+ hits/errors surviving a destination commit; changing the search context must
+ immediately withdraw those results while the destination search is pending.
+- Unsubmitted text and caret are editor state, not navigation intent. Typing
+ another draft does not cancel admitted navigation or let completion close the
+ newer draft. Opening an editor does not cancel a pending favorite.
+- Escape explicitly cancels an outstanding **manual** navigation, including its
+ resolution/listing phases. Another navigation or submission also supersedes
+ it. This reconciles review 4072117989 with the older consuming test: the
+ Escape/reopen scenario must assert cancellation, while the newer-draft scenario
+ must still assert successful navigation plus preserved draft/caret.
+ If hidden-file settings changed during an abandoned/failed navigation, reload
+ the retained source with those settings. A supplementary read-only review
+ reproduced that mismatch; both cancellation and failure are covered.
+- Route suspension retains state and requests, but withdraws modal effects;
+ real unmount discards completions.
+- A mkdir may finish on the server after cancellation/navigation. Its stale
+ completion must not navigate, clear a newer editor or publish an error.
+- Add optional history controls to the shared surface; do not rebuild a second
+ toolbar. Restore the consuming fixture's actual Files list/search/mkdir
+ contracts without permitting undeclared requests.
+
+## Verification and delivery
+
+Add adversarial deferred success/failure tests for the shared request owner and
+creation, history/failure/refresh tests, and browser checks for retained Unicode
+draft/caret and the actual Files transport. Run the home-media typecheck and full
+Playwright suite, focused component tests, UI lint and build before pushing.
+Do not delete failing race tests to obtain a green result.
+
+The existing Windows smoke failure was an HTTP 500 downloading the released Show
+Runtime after installation, outside this UI scope. Its single failed-job rerun
+passed; no installer or workflow changes were needed.
+
+Local verification passed: 47 picker tests, all 5,318 UI tests across 348 files,
+all 57 home-media browser cases, the fixture typecheck, UI lint and production
+build. Desktop/mobile picker screenshots were inspected. A supplementary
+read-only review found the two search/source-option boundaries noted above;
+after their fixes its six focused probes passed with no further findings.
+The orchestrator also inspected the final production diff and consuming tests.
+No failing race tests were removed.
+
+## Compatibility inventory follow-up
+
+Before further edits, the orchestrator re-read all review heads and threads:
+13 findings-bearing heads, 32 threads, 30 resolved and two open. This is the
+first findings-bearing head after the navigation-owner rewrite. The recurring
+lost-picker-capability class (manual input, retained editors, history, now a
+shortcut and labels) still triggers the root-cause breaker.
+
+Inspection of the removed DirectoryBrowser, the current shared view, the
+route-scoped event helper and the consuming suspension tests supports a narrow
+compatibility completion, not another state-model rewrite. Restore Ctrl/Cmd+N
+through `useRouteSurfaceWindowEvent`, using the same creation entry point and
+readiness guard as the button. It must not act while the picker is suspended,
+reset an existing creation draft or bypass an unavailable directory. Restore
+the existing stable-key translation map in the shared FileBrowser so both the
+Files app and picker, on desktop and mobile, use the same labels. Unknown
+system favorites retain their actual paths.
+
+The old picker capability inventory now covers modal dismissal/focus, arbitrary
+paths, parent/breadcrumb/history navigation, canonical external paths, hidden
+entries, creation by button/shortcut, localized system favorites, selection and
+retained route state. Existing tests cover navigation/lifecycle/selection; add
+shortcut readiness/suspension and English/Chinese favorite-label cases. Preserve
+the existing request-owner tests and run the consuming browser suite before
+pushing. No backend, shared shell shortcut or dependency changes are authorized
+or needed.
+
+### Follow-up verification
+
+The orchestrator inspected the production diff and the consuming shortcut
+test, including suspension into Settings and the retained creation draft on
+return. Both mobile and desktop screenshots show the localized Home label.
+The 53 focused tests, 59 consuming browser cases, fixture typecheck, UI lint
+and production build passed. The complete UI suite passed all 5,324 tests in
+349 files with one worker.
+
+An initial four-worker run exposed an unrelated test-fixture race:
+`lintBaseline.test.mjs` removes its temporary `update-integrity-probe.ts` while
+`glowScale.test.mjs` scans the source tree. The serial rerun passed without
+changing either test or weakening an assertion. No temporary probe remains.
+The preceding committed head's GitHub CI also completed successfully. The new
+commit still requires its own automatic Codex review and CI.
+
+Keep the existing durable PR/Actions Watch. Repository automation owns Codex
+review pickup; do not manually trigger it. Close-out requires a current-version
+review pass, green CI and no open actionable threads. Merge still requires owner
+authorization. Targeted thread replies only; no round-summary PR comments.
diff --git a/ui/e2e/home-media/README.md b/ui/e2e/home-media/README.md
index f85c8d212..cf8abf59a 100644
--- a/ui/e2e/home-media/README.md
+++ b/ui/e2e/home-media/README.md
@@ -38,7 +38,7 @@ 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
+FolderBrowser, 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.
@@ -74,7 +74,7 @@ finish: the sheet holds its successful result and uses the current navigator
once on return, or preserves the retry/error/uncertainty state. No automatic
resubmission and no replay state are introduced.
-DirectoryBrowser retains unconfirmed paths, history, manual-path input and
+FolderBrowser retains unconfirmed paths, history, manual-path input and
new-folder text while withdrawing its modal and global keyboard/focus effects.
NewProjectDialog retains confirmation state and alone owns deferred project
completion for all callers. A successful or authorization-fenced null result
@@ -89,3 +89,11 @@ Unicode state, 390/1366px, accepted/rejected/uncertain network completion,
pre-POST suspension, true close/fresh reopen, project creation success/failure/
cancel and retained directory inputs. Unexpected requests fail the fixture;
all external traffic is refused.
+
+The picker fixture models `/api/browse` for canonicalization and the Files
+list/search/mkdir endpoints for actual browsing. Held browse requests block
+the Files listing, not the compatibility resolver. Successful navigations
+commit history; refreshes and stale/failed completions do not. A newer
+unsubmitted path draft survives an admitted navigation, including its caret.
+Escape explicitly cancels a pending manual submission, so reopening the editor
+cannot revive that submission or add it to history.
diff --git a/ui/e2e/home-media/fixture.tsx b/ui/e2e/home-media/fixture.tsx
index 3031bbae2..3f3af6200 100644
--- a/ui/e2e/home-media/fixture.tsx
+++ b/ui/e2e/home-media/fixture.tsx
@@ -13,6 +13,7 @@ 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 type { FsEntry } from '../../src/lib/filesApi';
import '../../src/index.css';
const params = new URLSearchParams(location.search);
@@ -30,6 +31,12 @@ 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 createdFolders = new Map<string, FsEntry[]>();
+const directoryEntries = (path: string): FsEntry[] => [
+ { name: '另一个项目', kind: 'dir', size: null, mtime: null, ext: '' },
+ { name: '.hidden', kind: 'dir', size: null, mtime: null, ext: '' },
+ ...(createdFolders.get(path) ?? []),
+];
const control = {
writes,
unexpectedRequests: [] as string[],
@@ -52,6 +59,7 @@ const control = {
heldBrowsePaths: [] as string[],
pendingBrowses: [] as Array<{ path: string; release: () => void }>,
browseCompletions: [] as string[],
+ listRequests: [] as Array<{ path: string; showHidden: boolean }>,
};
declare global { interface Window { homeMedia: typeof control } }
window.homeMedia = control;
@@ -80,13 +88,46 @@ window.fetch = async (input, init) => {
}
if (path === '/api/projects' || path === '/api/workbench/projects-bootstrap') return reply({ projects, sessions: {} });
if (path === '/api/browse') {
- if (control.heldBrowsePaths.includes(body.path)) {
- await new Promise<void>((resolve) => { control.pendingBrowses.push({ path: body.path, release: resolve }); });
- }
- control.browseCompletions.push(body.path);
+ // Compatibility resolution is separate from the Files listing. Held
+ // navigation requests below intentionally block the listing phase only.
return reply({ ok: true, path: body.path === '~' ? '/fixture' : body.path || '/fixture', parent: '/fixture', dirs: [{ name: '另一个项目', path: '/fixture/另一个项目' }] });
}
if (path === '/api/browse/favorites') return reply({ ok: true, favorites: [{ key: 'home', path: '/fixture' }] });
+ if (path === '/api/files/list') {
+ const directory = url.searchParams.get('path')!;
+ const showHidden = url.searchParams.get('show_hidden') === '1';
+ control.listRequests.push({ path: directory, showHidden });
+ if (control.heldBrowsePaths.includes(directory)) {
+ await new Promise<void>((resolve) => { control.pendingBrowses.push({ path: directory, release: resolve }); });
+ }
+ control.browseCompletions.push(directory);
+ return reply({
+ ok: true, path: directory, parent: directory.slice(0, directory.lastIndexOf('/')) || '/',
+ entries: directoryEntries(directory).filter((entry) => showHidden || !entry.name.startsWith('.')),
+ truncated: false, limit: 2000,
+ });
+ }
+ if (path === '/api/files/search_names') {
+ const root = url.searchParams.get('root')!;
+ const query = url.searchParams.get('query')!;
+ const showHidden = url.searchParams.get('show_hidden') === '1';
+ return reply({
+ ok: true, root, query, truncated: false, limit: 1000,
+ results: directoryEntries(root)
+ .filter((entry) => (showHidden || !entry.name.startsWith('.')) && entry.name.includes(query))
+ .map((entry) => ({ ...entry, path: `${root}/${entry.name}`, rel: entry.name })),
+ });
+ }
+ if (path === '/api/files/mkdir' && init?.method === 'POST') {
+ const target = String(body.path);
+ const parent = target.slice(0, target.lastIndexOf('/'));
+ const name = target.slice(target.lastIndexOf('/') + 1);
+ if (directoryEntries(parent).some((entry) => entry.name === name)) {
+ return reply({ ok: false, error: { code: 'exists', message: 'Entry already exists' } }, 409);
+ }
+ createdFolders.set(parent, [...(createdFolders.get(parent) ?? []), { name, kind: 'dir', size: null, mtime: null, ext: '' }]);
+ return reply({ ok: true });
+ }
if (path === '/api/sessions' && init?.method === 'POST') {
if (control.holdCreate) await new Promise<void>((resolve) => { control.releaseCreate = resolve; });
const session = { ...body, id: `ses-${sessions.length + 1}`, status: 'active', agent_status: 'idle', created_at: '2026-09-01T00:00:00Z', updated_at: '2026-09-01T00:00:00Z', metadata: {} };
diff --git a/ui/e2e/home-media/media.spec.ts b/ui/e2e/home-media/media.spec.ts
index 3fa8210aa..33b073aff 100644
--- a/ui/e2e/home-media/media.spec.ts
+++ b/ui/e2e/home-media/media.spec.ts
@@ -33,10 +33,10 @@ test('draft files follow final project and Agent selection through picker cancel
await page.keyboard.press('Escape');
await expect(input(page)).toHaveValue('请阅读这份中文文件');
await openProject().click();
- await page.getByRole('button', { name: '另一个项目', exact: true }).click();
+ await page.getByRole('button', { name: /^另一个项目(?: |$)/ }).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/另一个项目');
+ 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(projectChip('另一个项目')).toHaveClass(/bg-mint-soft/);
diff --git a/ui/e2e/home-media/sheet-suspension.spec.ts b/ui/e2e/home-media/sheet-suspension.spec.ts
index eeba891de..53d6a2a10 100644
--- a/ui/e2e/home-media/sheet-suspension.spec.ts
+++ b/ui/e2e/home-media/sheet-suspension.spec.ts
@@ -37,10 +37,11 @@ const back = (page: Page) => page.getByRole('button', { name: 'Back to app' }).c
const picker = (page: Page) => page.getByRole('dialog', { name: en.directoryBrowser.title });
const manualPath = (page: Page) => page.getByPlaceholder(en.directoryBrowser.editPathPlaceholder);
const resolvedPath = (page: Page) => picker(page).locator('code');
+const initialDirectory = '/fixture/中文项目';
async function openProjectPicker(page: Page) {
await open(page);
await page.getByRole('button', { name: en.newSession.newProject, exact: true }).click();
- await expect(resolvedPath(page)).toHaveText('/fixture');
+ await expect(resolvedPath(page)).toHaveText(initialDirectory);
await expect(picker(page).getByRole('button', { name: en.directoryBrowser.select, exact: true })).toBeEnabled();
}
const holdBrowse = (page: Page, path: string) => page.evaluate((path) => { window.homeMedia.heldBrowsePaths.push(path); }, path);
@@ -53,13 +54,54 @@ const releaseBrowse = (page: Page, path: string) => page.evaluate((path) => {
}, path);
const selection = (page: Page) => manualPath(page).evaluate((input: HTMLInputElement) => ({ start: input.selectionStart, end: input.selectionEnd, direction: input.selectionDirection }));
+for (const width of [390, 1366]) test(`Files picker ${width} searches, refreshes hidden entries and creates a folder through the real API client`, async ({ page }, testInfo) => {
+ await page.setViewportSize({ width, height: 768 });
+ await openProjectPicker(page);
+ const search = picker(page).getByPlaceholder(en.apps.fileBrowser.searchPlaceholder);
+ await search.fill('另一个');
+ await expect(picker(page).getByRole('button', { name: /^另一个项目(?: |$)/ })).toBeVisible();
+ await picker(page).getByRole('checkbox', { name: en.apps.fileBrowser.showHidden, exact: true }).check();
+ await picker(page).getByRole('button', { name: en.apps.fileBrowser.refresh, exact: true }).click();
+ await expect(search).toHaveValue('另一个');
+ await search.fill('');
+ await expect(picker(page).getByRole('button', { name: /^\.hidden(?: |$)/ })).toBeVisible();
+ expect((await page.evaluate(() => window.homeMedia.listRequests)).at(-1)).toEqual({ path: initialDirectory, showHidden: true });
+ await picker(page).getByRole('button', { name: en.apps.fileBrowser.newFolder, exact: true }).click();
+ const name = picker(page).getByPlaceholder(en.apps.fileBrowser.newFolderPlaceholder);
+ await name.fill('新建文件夹🌱');
+ await name.press('Enter');
+ await expect(picker(page).getByRole('button', { name: /^新建文件夹🌱(?: |$)/ })).toBeVisible();
+ expect((await writes(page, '/api/files/mkdir')).at(-1)?.body.path).toBe(`${initialDirectory}/新建文件夹🌱`);
+ await expect(picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true })).toBeDisabled();
+ await picker(page).screenshot({ path: testInfo.outputPath('files-picker.png') });
+});
+
+for (const width of [390, 1366]) test(`folder creation shortcut ${width} follows route activity and preserves the draft`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 768 });
+ await openProjectPicker(page);
+ await expect(picker(page).getByRole('button', { name: en.directoryBrowser.favoritesHome, exact: true })).toBeVisible();
+ await page.keyboard.press('Control+n');
+ const folderName = page.getByPlaceholder(en.apps.fileBrowser.newFolderPlaceholder);
+ await expect(folderName).toBeFocused();
+ await folderName.fill('快捷键文件夹');
+ await page.keyboard.press('Meta+n');
+ await expect(folderName).toHaveValue('快捷键文件夹');
+ await settings(page);
+ await back(page);
+ await expect(folderName).toHaveValue('快捷键文件夹');
+ await expect(folderName).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect(picker(page).getByRole('button', { name: /^快捷键文件夹(?: |$)/ })).toBeVisible();
+ expect((await writes(page, '/api/files/mkdir')).at(-1)?.body.path).toBe(`${initialDirectory}/快捷键文件夹`);
+});
+
for (const width of [390, 1366]) for (const suspended of [false, true]) {
test(`directory draft ${width}: pending browse preserves text and selection ${suspended ? 'through Settings' : 'in foreground'}`, async ({ page }) => {
await page.setViewportSize({ width, height: 768 });
await openProjectPicker(page);
- const destination = '/fixture/另一个项目';
+ const destination = `${initialDirectory}/另一个项目`;
await holdBrowse(page, destination);
- await picker(page).getByRole('button', { name: '另一个项目', exact: true }).click();
+ await picker(page).getByRole('button', { name: /^另一个项目(?: |$)/ }).click();
await pendingBrowse(page, destination);
await picker(page).getByRole('button', { name: en.directoryBrowser.editPath, exact: true }).click();
const text = '/未确认的路径/草稿🌱';
@@ -109,9 +151,9 @@ for (const width of [390, 1366]) for (const suspended of [false, true]) {
test('directory draft survives history and hidden refresh while an obsolete browse cannot replace a manual target', async ({ page }) => {
await openProjectPicker(page);
- const start = '/fixture';
- const destination = '/fixture/另一个项目';
- await picker(page).getByRole('button', { name: '另一个项目', exact: true }).click();
+ const start = initialDirectory;
+ const destination = `${initialDirectory}/另一个项目`;
+ await picker(page).getByRole('button', { name: /^另一个项目(?: |$)/ }).click();
await expect(resolvedPath(page)).toHaveText(destination);
await holdBrowse(page, start);
await picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
@@ -129,7 +171,7 @@ test('directory draft survives history and hidden refresh while an obsolete brow
await expect(resolvedPath(page)).toHaveText(destination);
await expect(manualPath(page)).toHaveValue('/隐藏文件刷新草稿');
await holdBrowse(page, destination);
- await picker(page).getByRole('button', { name: en.directoryBrowser.hiddenFiles, exact: true }).click();
+ await picker(page).getByRole('checkbox', { name: en.apps.fileBrowser.showHidden, exact: true }).click();
await pendingBrowse(page, destination);
const target = '/用户明确提交的路径';
await manualPath(page).fill(target);
@@ -164,7 +206,7 @@ for (const width of [390, 1366]) for (const reopen of [false, true]) test(`direc
await page.keyboard.press('Escape');
await expect(manualPath(page)).toHaveCount(0);
await edit.click();
- await expect(manualPath(page)).toHaveValue('/fixture');
+ await expect(manualPath(page)).toHaveValue(initialDirectory);
}
await page.keyboard.press('ControlOrMeta+a');
await page.keyboard.insertText('/提交后的新草稿🌱');
@@ -175,7 +217,10 @@ for (const width of [390, 1366]) for (const reopen of [false, true]) test(`direc
await expect.poll(() => page.evaluate((path) => window.homeMedia.browseCompletions.includes(path), submitted)).toBe(true);
await expect(picker(page)).toHaveCount(0);
await back(page);
- await expect(resolvedPath(page)).toHaveText(submitted);
+ // Escape is an explicit cancellation; typing an unsubmitted newer draft is
+ // not. Both cases retain the new draft/caret through route withdrawal.
+ const committed = reopen ? initialDirectory : submitted;
+ await expect(resolvedPath(page)).toHaveText(committed);
await expect(manualPath(page)).toHaveValue('/提交后的新草稿🌱');
// Observe after deferred modal cleanup, before a key could repair focus.
await page.waitForTimeout(300);
@@ -187,13 +232,18 @@ for (const width of [390, 1366]) for (const reopen of [false, true]) test(`direc
await expect(manualPath(page)).toHaveValue('/提交后的新草稿🌱x续写🌿');
await page.keyboard.press('Escape');
await edit.click();
- await expect(manualPath(page)).toHaveValue(submitted);
- expect(await selection(page)).toMatchObject({ start: 0, end: submitted.length });
+ await expect(manualPath(page)).toHaveValue(committed);
+ expect(await selection(page)).toMatchObject({ start: 0, end: committed.length });
await page.keyboard.press('Escape');
- await picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
- await expect(resolvedPath(page)).toHaveText('/fixture');
- await picker(page).getByRole('button', { name: en.directoryBrowser.forward, exact: true }).click();
- await expect(resolvedPath(page)).toHaveText(submitted);
+ const backButton = picker(page).getByRole('button', { name: en.directoryBrowser.back, exact: true });
+ if (reopen) {
+ await expect(backButton).toBeDisabled();
+ } else {
+ await backButton.click();
+ await expect(resolvedPath(page)).toHaveText(initialDirectory);
+ await picker(page).getByRole('button', { name: en.directoryBrowser.forward, exact: true }).click();
+ await expect(resolvedPath(page)).toHaveText(submitted);
+ }
});
for (const width of [390, 1366]) test(`directory selection ${width} follows text insertion, deletion and caret-only changes through repeated withdrawal`, async ({ page }) => {
@@ -336,7 +386,7 @@ for (const timing of ['pending', 'completed'] as const) test(`actual close disca
});
async function pickFolder(page: Page) {
- await page.getByRole('button', { name: '另一个项目', exact: true }).click();
+ await page.getByRole('button', { name: /^另一个项目(?: |$)/ }).click();
await page.getByRole('button', { name: en.directoryBrowser.select, exact: true }).click();
}
@@ -345,7 +395,7 @@ test('no-project handoff preserves picker path/history/manual input and confirma
await draft(page).fill('没有项目时也保留的中文任务');
await send(page).click();
await expect(page.getByRole('dialog', { name: en.directoryBrowser.title })).toBeVisible();
- await page.getByRole('button', { name: '另一个项目', exact: true }).click();
+ await page.getByRole('button', { name: /^另一个项目(?: |$)/ }).click();
await page.getByRole('button', { name: en.directoryBrowser.editPath, exact: true }).click();
const path = page.getByPlaceholder(en.directoryBrowser.editPathPlaceholder);
await path.fill('/未确认的路径/草稿');
@@ -356,16 +406,16 @@ test('no-project handoff preserves picker path/history/manual input and confirma
await page.keyboard.press('End');
await page.keyboard.insertText('/继续编辑');
await expect(path).toHaveValue('/未确认的路径/草稿/继续编辑');
- await expect(page.getByPlaceholder(en.directoryBrowser.newFolderPlaceholder)).toHaveCount(0);
+ await expect(page.getByPlaceholder(en.apps.fileBrowser.newFolderPlaceholder)).toHaveCount(0);
await page.keyboard.press('Escape');
- await page.getByRole('button', { name: en.directoryBrowser.newFolder, exact: true }).click();
- const folderName = page.getByPlaceholder(en.directoryBrowser.newFolderPlaceholder);
+ await page.getByRole('button', { name: en.apps.fileBrowser.newFolder, exact: true }).click();
+ const folderName = page.getByPlaceholder(en.apps.fileBrowser.newFolderPlaceholder);
await folderName.fill('未创建文件夹');
await settings(page);
await back(page);
await expect(folderName).toHaveValue('未创建文件夹');
await expect(folderName).toBeFocused();
- expect(await writes(page, '/api/browse/mkdir')).toHaveLength(0);
+ expect(await writes(page, '/api/files/mkdir')).toHaveLength(0);
await page.keyboard.press('Escape');
await page.getByRole('button', { name: en.directoryBrowser.back, exact: true }).click();
await expect(page.getByRole('button', { name: en.directoryBrowser.forward, exact: true })).toBeEnabled();
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 6da278c51..227ecbc6e 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -166,9 +166,6 @@
"src/components/steps/SlackConfig.tsx": {
"react-hooks/exhaustive-deps": 3
},
- "src/components/ui/directory-browser.tsx": {
- "react-hooks/exhaustive-deps": 1
- },
"src/components/ui/editor-dialog.tsx": {
"react-hooks/exhaustive-deps": 1
},
diff --git a/ui/src/components/Workbench.test.tsx b/ui/src/components/Workbench.test.tsx
index 91278786d..fb1866903 100644
--- a/ui/src/components/Workbench.test.tsx
+++ b/ui/src/components/Workbench.test.tsx
@@ -49,7 +49,7 @@ vi.mock('../lib/sessionInfo', () => ({
// only need to see that the chip reaches it and that closing it changes nothing.
vi.mock('./workbench/NewProjectDialog', () => ({
NewProjectDialog: ({ onClose, initialPath }: { onClose: () => void; initialPath?: string }) => (
- <div role="dialog" aria-label="directory-browser" data-path={initialPath}>
+ <div role="dialog" aria-label="folder-browser" data-path={initialPath}>
<button type="button" onClick={onClose}>cancel-folder</button>
</div>
),
@@ -219,10 +219,10 @@ describe('Workbench first-task home', () => {
// No menu in between: the row reaches the folder picker itself.
await user.click(screen.getByRole('button', { name: en.newSession.newProject }));
- expect(screen.getByRole('dialog', { name: 'directory-browser' })).toBeTruthy();
+ expect(screen.getByRole('dialog', { name: 'folder-browser' })).toBeTruthy();
await user.click(screen.getByText('cancel-folder'));
- expect(screen.queryByRole('dialog', { name: 'directory-browser' })).toBeNull();
+ expect(screen.queryByRole('dialog', { name: 'folder-browser' })).toBeNull();
expect(input().value).toBe('帮我看看这个仓库');
expect(newSession.setSelected).not.toHaveBeenCalled();
expect(newSession.upsertSelectProject).not.toHaveBeenCalled();
@@ -254,7 +254,7 @@ describe('Workbench first-task home', () => {
await user.type(input(), '开始一个新项目');
await user.click(screen.getByRole('button', { name: en.chat.compose.send }));
- expect(await screen.findByRole('dialog', { name: 'directory-browser' })).toBeTruthy();
+ expect(await screen.findByRole('dialog', { name: 'folder-browser' })).toBeTruthy();
// The prompt survives the detour — the user retries it, not retypes it.
expect(input().value).toBe('开始一个新项目');
});
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index f2e4e11db..a4b4a611e 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -19,7 +19,7 @@ import {
import { useTranslation } from 'react-i18next';
import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
-import { DirectoryBrowser } from '../ui/directory-browser';
+import { FolderBrowser } from '../ui/folder-browser';
import { useNavigate } from 'react-router-dom';
import clsx from 'clsx';
import { getEnabledPlatforms, platformSupportsChannels, platformSupportsToolcallDelivery } from '../../lib/platforms';
@@ -1657,7 +1657,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
? threadConfigs[browseChannelId]?.[browseTopicId]
: platformConfigs[browseChannelId];
return (
- <DirectoryBrowser
+ <FolderBrowser
initialPath={selectedConfig?.custom_cwd || config.runtime?.default_cwd || '~/work'}
onSelect={(path) => {
if (browseTopicId && selectedConfig) {
@@ -2041,7 +2041,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{/* Directory browser modal */}
{browsingCwdFor && (
- <DirectoryBrowser
+ <FolderBrowser
initialPath={configs[browsingCwdFor]?.custom_cwd || config.runtime?.default_cwd || '~/work'}
onSelect={(path) => {
updateConfig(browsingCwdFor, { custom_cwd: path });
diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsx
index c60acf8b4..fbc7ebb22 100644
--- a/ui/src/components/steps/UserList.tsx
+++ b/ui/src/components/steps/UserList.tsx
@@ -20,7 +20,7 @@ import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { getEnabledPlatforms, platformSupportsToolcallDelivery } from '../../lib/platforms';
-import { DirectoryBrowser } from '../ui/directory-browser';
+import { FolderBrowser } from '../ui/folder-browser';
import { copyTextToClipboard } from '../../lib/utils';
import { PlatformIcon } from '../visual';
import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';
@@ -862,7 +862,7 @@ export const UserList: React.FC = () => {
const found = aggregated.find((u) => u.key === browsingCwdFor);
if (!found) return null;
return (
- <DirectoryBrowser
+ <FolderBrowser
initialPath={found.config.custom_cwd || config.runtime?.default_cwd || '~/work'}
onSelect={(path) => {
updateUser(found.platform, found.userId, { custom_cwd: path });
diff --git a/ui/src/components/ui/directory-browser.tsx b/ui/src/components/ui/directory-browser.tsx
deleted file mode 100644
index d11dfa85f..000000000
--- a/ui/src/components/ui/directory-browser.tsx
+++ /dev/null
@@ -1,692 +0,0 @@
-import type { TranslationKey } from '@/i18n/types';
-import React, { useEffect, useState, useCallback, useLayoutEffect, useRef } from 'react';
-import {
- Check,
- ChevronLeft,
- ChevronRight,
- Database,
- Download,
- Eye,
- EyeOff,
- FileText,
- Folder,
- FolderOpen,
- FolderPlus,
- HardDrive,
- Home,
- Keyboard,
- LayoutGrid,
- Monitor,
- RefreshCw,
-} 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';
-import { useRouteSurfaceActive, useRouteSurfaceWindowEvent } from '@/lib/routeSurfaceActivity';
-
-interface DirectoryBrowserProps {
- /** Initial path to show when opening */
- initialPath?: string;
- /** Called when user confirms selection */
- onSelect: (path: string) => void;
- /** Called when user cancels / closes */
- onClose: () => void;
-}
-
-// Per-OS quick-access shortcuts come from the backend (it knows the platform
-// and verifies each path exists). Well-known shortcuts get a localized label;
-// OS roots like /tmp, /data or a Windows drive are shown by their path. Both
-// label and icon are keyed off the backend's stable ``key``.
-const FAVORITE_I18N: Record<string, TranslationKey> = {
- home: 'directoryBrowser.favoritesHome',
- desktop: 'directoryBrowser.favoritesDesktop',
- documents: 'directoryBrowser.favoritesDocuments',
- downloads: 'directoryBrowser.favoritesDownloads',
- applications: 'directoryBrowser.favoritesApplications',
-};
-
-const favoriteIcon = (key: string): React.ReactNode => {
- const cls = 'size-3.5';
- switch (key) {
- case 'home':
- return <Home className={cls} />;
- case 'desktop':
- return <Monitor className={cls} />;
- case 'documents':
- return <FileText className={cls} />;
- case 'downloads':
- return <Download className={cls} />;
- case 'applications':
- return <LayoutGrid className={cls} />;
- case 'data':
- return <Database className={cls} />;
- default:
- // root / mnt / media / drive_* → a volume; anything else a plain folder.
- if (key === 'root' || key === 'mnt' || key === 'media' || key.startsWith('drive_')) {
- return <HardDrive className={cls} />;
- }
- return <Folder className={cls} />;
- }
-};
-
-// Mirrors design.pen y5cQ5 — macOS Finder-style folder picker: traffic
-// lights + toolbar (history nav + breadcrumb + show-hidden + new-folder)
-// + favorites sidebar + folder list + footer (path + cancel + select).
-export const DirectoryBrowser: React.FC<DirectoryBrowserProps> = ({
- initialPath,
- onSelect,
- onClose,
-}) => {
- const { t } = useTranslation();
- const api = useApi();
- const surfaceActive = useRouteSurfaceActive();
- const foreground = useRef(surfaceActive);
- useLayoutEffect(() => { foreground.current = surfaceActive; }, [surfaceActive]);
-
- const [currentPath, setCurrentPath] = useState('');
- // Resolved user home — captured on the first browse('~') response so the
- // breadcrumb collapse to ⌂ has a real prefix to match against. Falls back
- // to '' (no collapse) if the user opened the picker with an absolute path.
- const [homePath, setHomePath] = useState<string>('');
- const [parent, setParent] = useState<string | null>(null);
- const [dirs, setDirs] = useState<{ name: string; path: string }[]>([]);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [showHidden, setShowHidden] = useState(false);
- // Linear history so the < / > arrows behave like a real file browser
- // instead of just walking the directory tree.
- const [history, setHistory] = useState<string[]>([]);
- const [historyIndex, setHistoryIndex] = useState(-1);
- // Inline "create new folder" prompt — shown at the end of the list so
- // it feels like a continuation of the directory rather than a modal.
- const [creating, setCreating] = useState(false);
- const [newFolderName, setNewFolderName] = useState('');
- const [createError, setCreateError] = useState<string | null>(null);
- const newFolderInputRef = useRef<HTMLInputElement | null>(null);
-
- // Manual-path mode — flips the breadcrumb into an editable text input
- // (mirrors Finder's Cmd+Shift+G behavior) so users can paste an
- // arbitrary path and navigate to it directly.
- const [pathEditing, setPathEditing] = useState(false);
- const [pathInput, setPathInput] = useState('');
- const [pathError, setPathError] = useState<string | null>(null);
- const pathInputRef = useRef<HTMLInputElement | null>(null);
- const pathEditRevision = useRef(0);
- const pathSelection = useRef<{ start: number; end: number; direction: 'forward' | 'backward' | 'none' } | null>(null);
-
- const capturePathSelection = (input: HTMLInputElement) => {
- // Text edits can move the caret without React firing onSelect. Capture
- // both events, retaining the last foreground range through portal teardown.
- if (!foreground.current || !input.isConnected || input.ownerDocument.activeElement !== input) return;
- pathSelection.current = {
- start: input.selectionStart ?? 0,
- end: input.selectionEnd ?? 0,
- direction: input.selectionDirection ?? 'none',
- };
- };
-
- // OS-appropriate quick-access shortcuts, resolved + existence-checked by the
- // backend (macOS Finder entries, Linux /tmp·/data·roots, Windows drives…).
- const [favorites, setFavorites] = useState<{ key: string; path: string }[]>([]);
-
- const mountedRef = useRef(true);
- const reqIdRef = useRef(0);
-
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- };
- }, []);
-
- useRouteSurfaceWindowEvent('keydown', (event) => {
- if (!event.defaultPrevented && (event.metaKey || event.ctrlKey)
- && event.key.toLowerCase() === 'n' && !creating) {
- event.preventDefault();
- setCreating(true);
- }
- });
-
- useEffect(() => {
- if (surfaceActive && creating) newFolderInputRef.current?.focus();
- }, [creating, surfaceActive]);
-
- const fetchPath = useCallback(
- async (path: string, hidden?: boolean) => {
- const id = ++reqIdRef.current;
- setLoading(true);
- setError(null);
- const useHidden = hidden ?? showHidden;
- try {
- const result = await api.browseDirectory(path, useHidden);
- if (!mountedRef.current || reqIdRef.current !== id) {
- return null;
- }
- if (result.ok) {
- const resolvedPath = result.path ?? path;
- setCurrentPath(resolvedPath);
- setParent(result.parent ?? null);
- setDirs(result.dirs ?? []);
- // Snapshot the resolved user home the first time the backend
- // expands a tilde-prefixed path. Backend behavior: passing "~"
- // returns the home directory in result.path; passing "~/x"
- // returns "<home>/x". We derive home by trimming the requested
- // suffix off the resolved path.
- if (!homePath && path.startsWith('~')) {
- const suffix = path === '~' ? '' : path.slice(1);
- const derived = suffix && resolvedPath.endsWith(suffix)
- ? resolvedPath.slice(0, resolvedPath.length - suffix.length)
- : resolvedPath;
- const cleaned = derived.replace(/\/+$/, '');
- if (cleaned) setHomePath(cleaned);
- }
- return resolvedPath;
- }
- setError(result.error ?? 'Unknown error');
- return null;
- } catch (e) {
- if (!mountedRef.current || reqIdRef.current !== id) return null;
- setError(errorMessage(e) ?? String(e));
- return null;
- } finally {
- if (mountedRef.current && reqIdRef.current === id) {
- setLoading(false);
- }
- }
- },
- [api, showHidden, homePath],
- );
-
- const navigate = useCallback(
- async (path: string, hidden?: boolean) => {
- // Reset the inline new-folder state whenever the user moves around —
- // a half-typed name shouldn't survive navigating away.
- setCreating(false);
- setNewFolderName('');
- setCreateError(null);
- const resolved = await fetchPath(path, hidden);
- if (resolved) {
- setHistory((prev) => [...prev.slice(0, historyIndex + 1), resolved]);
- setHistoryIndex((prev) => prev + 1);
- }
- },
- [fetchPath, historyIndex],
- );
-
- const goBack = useCallback(() => {
- if (historyIndex <= 0) return;
- const next = historyIndex - 1;
- setHistoryIndex(next);
- fetchPath(history[next]);
- }, [history, historyIndex, fetchPath]);
-
- const goForward = useCallback(() => {
- if (historyIndex >= history.length - 1) return;
- const next = historyIndex + 1;
- setHistoryIndex(next);
- fetchPath(history[next]);
- }, [history, historyIndex, fetchPath]);
-
- useEffect(() => {
- navigate(initialPath || '~');
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Load OS-appropriate shortcuts once on open. The backend knows the platform
- // and verifies each path, so we render exactly what it returns (no dead rows,
- // no client-side OS guesswork).
- useEffect(() => {
- let cancelled = false;
- api
- .browseFavorites()
- .then((res) => {
- if (!cancelled && res.ok && res.favorites) setFavorites(res.favorites);
- })
- .catch(() => {
- /* leave favorites empty on failure — the folder list still works */
- });
- return () => {
- cancelled = true;
- };
- }, [api]);
-
- useEffect(() => {
- if (pathEditing && foreground.current) {
- pathInputRef.current?.focus();
- pathInputRef.current?.select();
- }
- }, [pathEditing]);
-
- const togglePathEditing = () => {
- if (!foreground.current) return;
- pathEditRevision.current++;
- if (!pathEditing) {
- // Snapshot only when an edit begins. Later browse responses update the
- // directory and history, not the user's unconfirmed text or selection.
- setPathInput(currentPath);
- setPathError(null);
- pathSelection.current = null;
- }
- setPathEditing(!pathEditing);
- };
-
- const cancelPathEditing = () => {
- pathEditRevision.current++;
- setPathEditing(false);
- };
-
- const submitManualPath = async () => {
- if (!foreground.current) return;
- const target = pathInput.trim();
- if (!target) return;
- const editRevision = pathEditRevision.current;
- setPathError(null);
- const request = fetchPath(target);
- const requestId = reqIdRef.current;
- const resolved = await request;
- if (!mountedRef.current || reqIdRef.current !== requestId) return;
- if (resolved) {
- // Mirror `navigate` history bookkeeping so the back arrow works.
- setHistory((prev) => [...prev.slice(0, historyIndex + 1), resolved]);
- setHistoryIndex((prev) => prev + 1);
- // A submitted target may resolve after the user starts another edit.
- // Keep its navigation result without dismissing that newer draft.
- if (pathEditRevision.current === editRevision) setPathEditing(false);
- } else if (pathEditRevision.current === editRevision) {
- setPathError(t('directoryBrowser.pathNotFound'));
- }
- };
-
- const toggleHidden = () => {
- const next = !showHidden;
- setShowHidden(next);
- fetchPath(currentPath, next);
- };
-
- const submitNewFolder = async () => {
- if (!foreground.current) return;
- const name = newFolderName.trim();
- if (!name) return;
- setCreateError(null);
- try {
- const target = currentPath ? `${currentPath.replace(/\/$/, '')}/${name}` : name;
- await api.browseMkdir(target);
- setCreating(false);
- setNewFolderName('');
- await fetchPath(currentPath);
- } catch (err) {
- const message: string = errorMessage(err) ?? String(err);
- if (/exists/i.test(message)) {
- setCreateError(t('directoryBrowser.newFolderExists'));
- } else {
- setCreateError(message);
- }
- }
- };
-
- // Breadcrumb: collapse the home prefix to ⌂ so deeply-nested paths still fit
- // in the toolbar without scrolling. ``homePath`` is captured on the first
- // tilde-expanded browse response (see fetchPath).
- const breadcrumbs = (() => {
- if (!currentPath) return [] as { label: string; path: string; isHome?: boolean }[];
- const startsAtHome = !!homePath && currentPath.startsWith(homePath);
- const segments = (startsAtHome ? currentPath.slice(homePath.length) : currentPath)
- .split('/')
- .filter(Boolean);
- const out: { label: string; path: string; isHome?: boolean }[] = [];
- if (startsAtHome) {
- // At home itself, show the full path — a bare ⌂ is cryptic. Collapse to
- // ⌂ only once you're deeper in, where it keeps long paths readable (the
- // full path still lives in the footer and the home crumb's tooltip).
- out.push({ label: segments.length === 0 ? homePath : '⌂', path: homePath, isHome: true });
- } else {
- out.push({ label: '/', path: '/' });
- }
- let acc = startsAtHome ? homePath : '';
- for (const seg of segments) {
- acc = acc === '/' || acc === '' ? `${acc}${seg}` : `${acc}/${seg}`;
- if (!acc.startsWith('/')) acc = `/${acc}`;
- out.push({ label: seg, path: acc });
- }
- return out;
- })();
-
- const canConfirm = !!currentPath && !loading && !error;
- const canBack = historyIndex > 0;
- const canForward = historyIndex < history.length - 1;
-
- // Keep this owner (including unconfirmed inputs/history) mounted, while
- // withdrawing the complete modal layer and its focus/pointer/scroll effects.
- if (!surfaceActive) return null;
-
- return (
- <Dialog open onOpenChange={(open) => { if (!open && foreground.current) onClose(); }}>
- <DialogContent
- onOpenAutoFocus={(event) => {
- if (!foreground.current) { event.preventDefault(); return; }
- // The portal mounts after its retained owner's effects. Resume the
- // editor here, without reinitializing or selecting its draft text.
- const editor = creating ? newFolderInputRef.current : pathEditing ? pathInputRef.current : null;
- if (editor) {
- event.preventDefault();
- editor.focus();
- if (editor === pathInputRef.current && pathSelection.current) {
- const { start, end, direction } = pathSelection.current;
- editor.setSelectionRange(start, end, direction);
- }
- }
- }}
- onCloseAutoFocus={(event) => { if (!foreground.current) event.preventDefault(); }}
- aria-describedby={undefined}
- closeLabel={t('directoryBrowser.cancel')}
- onEscapeKeyDown={(event) => {
- if (creating || pathEditing) {
- event.preventDefault();
- setCreating(false);
- setNewFolderName('');
- setCreateError(null);
- cancelPathEditing();
- }
- }}
- className="flex h-[80dvh] max-h-[720px] min-h-0 w-full max-w-3xl flex-col gap-0 overflow-hidden rounded-2xl border-border-strong bg-surface p-0 max-md:h-[90dvh] max-md:p-0 max-md:pb-0"
- >
- {/* 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={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>
- <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')}
- </DialogTitle>
-
- </div>
-
- {/* Toolbar — history arrows + breadcrumb + show-hidden + new-folder */}
- <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-2.5">
- <button
- type="button"
- onClick={goBack}
- disabled={!canBack}
- aria-label={t('directoryBrowser.back')}
- className={clsx(
- 'flex size-7 items-center justify-center rounded-md border border-border-strong transition',
- canBack ? 'text-foreground hover:bg-foreground/[0.06]' : 'cursor-not-allowed text-muted opacity-50',
- )}
- >
- <ChevronLeft className="size-3.5" />
- </button>
- <button
- type="button"
- onClick={goForward}
- disabled={!canForward}
- aria-label={t('directoryBrowser.forward')}
- className={clsx(
- 'flex size-7 items-center justify-center rounded-md border border-border-strong transition',
- canForward ? 'text-foreground hover:bg-foreground/[0.06]' : 'cursor-not-allowed text-muted opacity-50',
- )}
- >
- <ChevronRight className="size-3.5" />
- </button>
-
- {pathEditing ? (
- // Manual path input — replaces the breadcrumb for free-form
- // entry (paste a long path, use an absolute target outside
- // the usual breadcrumb chain, etc.). Esc reverts to the
- // breadcrumb without navigating.
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <div className="flex items-center gap-1.5 rounded-md border border-cyan/40 bg-cyan/[0.06] px-2 py-1">
- <input
- ref={pathInputRef}
- type="text"
- value={pathInput}
- onChange={(event) => {
- capturePathSelection(event.currentTarget);
- pathEditRevision.current++;
- setPathInput(event.currentTarget.value);
- }}
- onSelect={(event) => capturePathSelection(event.currentTarget)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- submitManualPath();
- }
- // Escape is handled by the window-level listener, which
- // reverts path editing before it would close the picker.
- }}
- placeholder={t('directoryBrowser.editPathPlaceholder')}
- className="flex-1 bg-transparent font-mono text-[11px] text-foreground outline-none placeholder:text-muted"
- />
- <button
- type="button"
- onClick={submitManualPath}
- className="rounded px-2 py-0.5 text-[10px] font-semibold text-cyan-ink hover:bg-foreground/[0.04]"
- >
- {t('directoryBrowser.editPathDone')}
- </button>
- </div>
- {pathError && <div className="px-1 text-[10.5px] text-destructive-ink">{pathError}</div>}
- </div>
- ) : (
- <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" />}
- <button
- type="button"
- onClick={() => navigate(crumb.path)}
- title={crumb.isHome ? homePath : undefined}
- className={clsx(
- 'shrink-0 rounded px-1 py-0.5 transition hover:bg-foreground/[0.04]',
- i === breadcrumbs.length - 1 ? 'font-semibold text-cyan-ink' : 'text-muted',
- )}
- >
- {crumb.label}
- </button>
- </React.Fragment>
- ))}
- {loading && <RefreshCw className="ml-auto size-3 shrink-0 animate-spin text-muted" />}
- </div>
- )}
-
- <button
- type="button"
- onClick={togglePathEditing}
- aria-label={t('directoryBrowser.editPath')}
- title={t('directoryBrowser.editPath')}
- className={clsx(
- 'flex size-7 items-center justify-center rounded-md border transition',
- pathEditing
- ? 'border-cyan/40 bg-cyan/[0.08] text-cyan-ink'
- : 'border-border-strong text-muted hover:text-foreground',
- )}
- >
- <Keyboard className="size-3.5" />
- </button>
-
- <button
- type="button"
- onClick={toggleHidden}
- aria-pressed={showHidden}
- title={t('directoryBrowser.hiddenFiles')}
- className={clsx(
- 'flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-[11px] font-semibold transition',
- showHidden
- ? 'border-cyan/40 bg-cyan/[0.08] text-cyan-ink'
- : 'border-border-strong text-muted hover:text-foreground',
- )}
- >
- {/* Stable label — on/off is conveyed by the Eye/EyeOff icon and the
- cyan (on) vs muted (off) treatment, not by changing the words. */}
- {showHidden ? <Eye className="size-3" /> : <EyeOff className="size-3" />}
- {t('directoryBrowser.hiddenFiles')}
- </button>
-
- <button
- type="button"
- onClick={() => {
- setCreating(true);
- setNewFolderName('');
- setCreateError(null);
- }}
- className="flex items-center gap-1.5 rounded-md border border-border-strong px-2.5 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-foreground/[0.04]"
- >
- <FolderPlus className="size-3" />
- {t('directoryBrowser.newFolder')}
- </button>
- </div>
-
- {/* Body — favorites sidebar + folder list */}
- <div className="flex min-h-0 flex-1">
- {/* Favorites sidebar */}
- <aside className="hidden w-[180px] shrink-0 flex-col gap-1 border-r border-border bg-surface-2 px-2 py-3 sm:flex">
- <div className="px-2 pb-1 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">
- {t('directoryBrowser.favorites')}
- </div>
- {favorites.map((fav) => {
- // Localized label for well-known shortcuts; the raw path for OS
- // roots (/tmp, /data, drives) so they read clearly.
- const label = FAVORITE_I18N[fav.key] ? t(FAVORITE_I18N[fav.key]) : fav.path;
- return (
- <button
- key={fav.path}
- type="button"
- onClick={() => navigate(fav.path)}
- title={fav.path}
- className="flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
- >
- <span className="shrink-0 text-muted">{favoriteIcon(fav.key)}</span>
- <span className="truncate">{label}</span>
- </button>
- );
- })}
- </aside>
-
- {/* Folder list */}
- <div className="flex min-w-0 flex-1 flex-col overflow-y-auto px-2 py-2">
- {error && (
- <div className="mx-2 mb-2 rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-sm text-destructive-ink">
- {error}
- </div>
- )}
-
- {parent && (
- <button
- onClick={() => navigate(parent)}
- className="flex items-center gap-2.5 rounded-md px-3 py-2 text-[13px] text-muted transition hover:bg-foreground/[0.04]"
- >
- <ChevronLeft className="size-3.5" />
- <span className="font-mono">..</span>
- </button>
- )}
-
- {dirs.map((dir) => (
- <button
- key={dir.path}
- onClick={() => navigate(dir.path)}
- className="group flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-[13px] text-foreground transition hover:bg-foreground/[0.04]"
- >
- <Folder className="size-4 shrink-0 text-gold-ink group-hover:hidden" />
- <FolderOpen className="hidden size-4 shrink-0 text-gold-ink group-hover:block" />
- <span className="truncate">{dir.name}</span>
- </button>
- ))}
-
- {!loading && !error && dirs.length === 0 && !creating && (
- <div className="px-3 py-6 text-center text-[12px] italic text-muted">
- {t('directoryBrowser.empty')}
- </div>
- )}
-
- {/* Inline new-folder prompt — sits at the bottom of the list so
- the user keeps context of which directory they're creating in */}
- {creating ? (
- <div className="mt-2 flex flex-col gap-1.5 rounded-md border border-dashed border-border-strong bg-foreground/[0.03] px-3 py-2.5">
- <div className="flex items-center gap-2">
- <FolderPlus className="size-4 shrink-0 text-mint-ink" />
- <input
- ref={newFolderInputRef}
- value={newFolderName}
- onChange={(e) => setNewFolderName(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') submitNewFolder();
- }}
- placeholder={t('directoryBrowser.newFolderPlaceholder')}
- className="flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted"
- />
- <button
- type="button"
- onClick={() => {
- setCreating(false);
- setNewFolderName('');
- setCreateError(null);
- }}
- className="rounded-md px-2 py-0.5 text-[11px] text-muted transition hover:text-foreground"
- >
- {t('directoryBrowser.cancel')}
- </button>
- <Button
- type="button"
- variant="default"
- size={null}
- onClick={submitNewFolder}
- disabled={!newFolderName.trim()}
- className="rounded-md px-2.5 py-0.5 text-[11px] font-semibold"
- >
- {t('directoryBrowser.newFolder')}
- </Button>
- </div>
- {createError && <div className="pl-6 text-[11px] text-destructive-ink">{createError}</div>}
- </div>
- ) : (
- <button
- type="button"
- onClick={() => setCreating(true)}
- className="mt-2 flex items-center gap-2.5 rounded-md border border-dashed border-border-strong bg-foreground/[0.02] px-3 py-2 text-[12px] italic text-muted transition hover:bg-foreground/[0.04]"
- >
- <FolderPlus className="size-4 shrink-0" />
- {t('directoryBrowser.createHere')}
- </button>
- )}
- </div>
- </div>
-
- {/* Footer — current path + cancel + select */}
- <div className="flex items-center gap-3 border-t border-border bg-surface-2 px-4 py-3">
- <code className="flex-1 truncate rounded-md border border-border-strong bg-surface-3 px-2.5 py-1.5 font-mono text-[11px] text-foreground">
- {currentPath || '—'}
- </code>
- <button
- type="button"
- onClick={onClose}
- className="rounded-md border border-border-strong px-4 py-1.5 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]"
- >
- {t('directoryBrowser.cancel')}
- </button>
- <Button
- type="button"
- variant="brand"
- size={null}
- onClick={() => canConfirm && onSelect(currentPath)}
- disabled={!canConfirm}
- className="gap-1.5 rounded-md px-4 py-1.5 text-[12px] font-semibold"
- >
- <Check className="size-3.5" />
- {t('directoryBrowser.select')}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- );
-};
diff --git a/ui/src/components/ui/file-browser.test.tsx b/ui/src/components/ui/file-browser.test.tsx
new file mode 100644
index 000000000..cd6c7e576
--- /dev/null
+++ b/ui/src/components/ui/file-browser.test.tsx
@@ -0,0 +1,54 @@
+/* @vitest-environment jsdom */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { createInstance } from 'i18next';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import { FileBrowser } from './file-browser';
+
+afterEach(cleanup);
+
+it.each(['en', 'zh'] as const)('localizes known favorites in both shared layouts in %s while retaining path targets', async (language) => {
+ const i18n = createInstance();
+ await i18n.init({ lng: language, resources: { en: { translation: en }, zh: { translation: zh } } });
+ const text = (language === 'en' ? en : zh).directoryBrowser;
+ const favorites = [
+ { key: 'home', path: '/Users/alice', label: text.favoritesHome },
+ { key: 'desktop', path: '/Users/alice/Desktop', label: text.favoritesDesktop },
+ { key: 'documents', path: '/Users/alice/Documents', label: text.favoritesDocuments },
+ { key: 'downloads', path: '/Users/alice/Downloads', label: text.favoritesDownloads },
+ { key: 'applications', path: '/Applications', label: text.favoritesApplications },
+ { key: 'drive_z', path: 'Z:\\', label: 'Z:\\' },
+ { key: 'custom', path: '/mnt/backup/daily', label: '/mnt/backup/daily' },
+ ];
+ const navigate = vi.fn();
+ render(
+ <I18nextProvider i18n={i18n}>
+ <FileBrowser
+ cwd="/Users/alice"
+ crumbs={[]}
+ sysFavs={favorites}
+ projectFavs={[{ label: 'Project name', path: '/project' }]}
+ onNavigate={navigate}
+ showHidden={false}
+ onShowHiddenChange={() => {}}
+ listContent={null}
+ />
+ </I18nextProvider>,
+ );
+
+ // jsdom renders both responsive surfaces: the mobile chips and desktop rail.
+ for (const favorite of favorites) {
+ const buttons = screen.getAllByRole('button', { name: favorite.label, exact: true });
+ expect(buttons).toHaveLength(2);
+ for (const button of buttons) {
+ expect(button.getAttribute('title')).toBe(favorite.path);
+ fireEvent.click(button);
+ expect(navigate).toHaveBeenLastCalledWith(favorite.path);
+ }
+ }
+ expect(screen.getAllByRole('button', { name: 'Project name', exact: true })).toHaveLength(2);
+});
diff --git a/ui/src/components/ui/file-browser.tsx b/ui/src/components/ui/file-browser.tsx
new file mode 100644
index 000000000..3788f327e
--- /dev/null
+++ b/ui/src/components/ui/file-browser.tsx
@@ -0,0 +1,412 @@
+import type { HTMLAttributes, ReactNode } from 'react';
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ ChevronLeft,
+ ChevronRight,
+ Download,
+ FileSearch,
+ FileText,
+ Folder,
+ HardDrive,
+ Home,
+ Monitor,
+ RefreshCw,
+ Search,
+ X,
+ type LucideIcon,
+} from 'lucide-react';
+import clsx from 'clsx';
+
+import type { TranslationKey } from '../../i18n/types';
+import type { Favorite, FsEntry } from '../../lib/filesApi';
+import { Button } from './button';
+import { MobileAppHeader } from '../apps/MobileAppHeader';
+
+export type FileBrowserRow = {
+ entry: FsEntry;
+ full: string;
+ dir: string;
+ rel?: string;
+ matchCount?: number;
+};
+
+export type FileBrowserProject = {
+ label: string;
+ path: string;
+};
+
+export type FileBrowserDropProps = {
+ onDragOver: (event: React.DragEvent) => void;
+ onDragLeave: () => void;
+ onDrop: (event: React.DragEvent) => void;
+};
+
+export interface FileBrowserProps {
+ fullBleed?: boolean;
+ mobileRoute?: boolean;
+ mobileTitle?: string;
+ title?: ReactNode;
+ tagline?: ReactNode;
+ cwd: string;
+ crumbs: { label: string; path: string }[];
+ sysFavs: Favorite[];
+ projectFavs: FileBrowserProject[];
+ loading?: boolean;
+ searchBusy?: boolean;
+ query?: string;
+ onQueryChange?: (value: string) => void;
+ searchMode?: 'name' | 'content';
+ onSearchModeChange?: (mode: 'name' | 'content') => void;
+ onRefresh?: () => void;
+ onNavigate: (path: string) => void;
+ onFavoriteNavigate?: (path: string) => void;
+ history?: { onBack?: () => void; onForward?: () => void };
+ onClearQuery?: () => void;
+ navigationControl?: ReactNode;
+ showHidden: boolean;
+ onShowHiddenChange: (showHidden: boolean) => void;
+ error?: string | null;
+ toolbarActions?: ReactNode;
+ listHeader?: ReactNode;
+ listContent: ReactNode;
+ paneProps?: HTMLAttributes<HTMLDivElement>;
+ listProps?: HTMLAttributes<HTMLDivElement>;
+ dropOverlay?: ReactNode;
+ footerContent?: ReactNode;
+ statusContent?: ReactNode;
+ dropTarget?: string | null;
+ getDropProps?: (path: string) => FileBrowserDropProps;
+ className?: string;
+}
+
+const FAV_ICON: Record<string, LucideIcon> = {
+ home: Home,
+ desktop: Monitor,
+ downloads: Download,
+ documents: FileText,
+ root: HardDrive,
+};
+
+const FAV_LABEL: Partial<Record<string, TranslationKey>> = {
+ home: 'directoryBrowser.favoritesHome',
+ desktop: 'directoryBrowser.favoritesDesktop',
+ documents: 'directoryBrowser.favoritesDocuments',
+ downloads: 'directoryBrowser.favoritesDownloads',
+ applications: 'directoryBrowser.favoritesApplications',
+};
+
+export const FileBrowser: React.FC<FileBrowserProps> = ({
+ fullBleed = false,
+ mobileRoute = false,
+ mobileTitle,
+ title,
+ tagline,
+ cwd,
+ crumbs,
+ sysFavs,
+ projectFavs,
+ loading = false,
+ searchBusy = false,
+ query,
+ onQueryChange,
+ searchMode = 'name',
+ onSearchModeChange,
+ onRefresh,
+ onNavigate,
+ onFavoriteNavigate,
+ history,
+ onClearQuery,
+ navigationControl,
+ showHidden,
+ onShowHiddenChange,
+ error,
+ toolbarActions,
+ listHeader,
+ listContent,
+ paneProps,
+ listProps,
+ dropOverlay,
+ footerContent,
+ statusContent,
+ dropTarget,
+ getDropProps,
+ className,
+}) => {
+ const { t } = useTranslation();
+ const favoriteLabel = (favorite: Favorite) => {
+ const key = FAV_LABEL[favorite.key];
+ return key ? t(key) : favorite.path;
+ };
+ const hasSearch = query !== undefined && onQueryChange;
+ const navigateTo = (path: string) => {
+ onClearQuery?.();
+ onNavigate(path);
+ };
+ const navigateFavoriteTo = (path: string) => {
+ onClearQuery?.();
+ (onFavoriteNavigate || onNavigate)(path);
+ };
+ const railDropProps = (path: string) => getDropProps?.(path);
+
+ return (
+ <div
+ className={clsx(
+ fullBleed
+ ? 'relative flex h-full w-full flex-col bg-surface pb-[env(safe-area-inset-bottom)]'
+ : 'relative flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]',
+ className,
+ )}
+ >
+ {mobileRoute && mobileTitle && <MobileAppHeader title={mobileTitle} icon={Folder} />}
+ {!fullBleed && (
+ <div>
+ {title && <h1 className="text-[18px] font-semibold text-foreground">{title}</h1>}
+ {tagline && <p className="text-[12px] text-muted">{tagline}</p>}
+ </div>
+ )}
+
+ <div className={clsx('flex min-h-0 flex-1 flex-col overflow-hidden', !fullBleed && 'rounded-xl border border-border')}>
+ <div
+ className={clsx(
+ 'flex items-center gap-2 border-b border-border bg-surface-2/60',
+ mobileRoute ? 'flex-wrap px-2 py-2' : 'px-3 py-2',
+ )}
+ >
+ <div className={clsx('flex min-w-0 items-center gap-0.5 overflow-x-auto', mobileRoute ? 'order-1 w-full' : 'flex-1')}>
+ {history && (
+ <>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-muted"
+ aria-label={t('directoryBrowser.back')}
+ disabled={!history.onBack || loading}
+ onClick={history.onBack}
+ >
+ <ChevronLeft className="size-3.5" />
+ </Button>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-muted"
+ aria-label={t('directoryBrowser.forward')}
+ disabled={!history.onForward || loading}
+ onClick={history.onForward}
+ >
+ <ChevronRight className="size-3.5" />
+ </Button>
+ </>
+ )}
+ {onRefresh && (
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-muted"
+ aria-label={t('apps.fileBrowser.refresh')}
+ onClick={onRefresh}
+ >
+ <RefreshCw className={clsx('size-3.5', (loading || searchBusy) && 'animate-spin')} />
+ </Button>
+ )}
+ {crumbs.map((crumb, index) => (
+ <span key={crumb.path} className="flex shrink-0 items-center">
+ {index > 0 && <ChevronRight className="size-3 shrink-0 text-muted" />}
+ <button
+ type="button"
+ onClick={() => navigateTo(crumb.path)}
+ {...railDropProps(crumb.path)}
+ className={clsx(
+ 'max-w-[140px] truncate rounded px-1.5 py-0.5 text-[12.5px] text-muted transition hover:bg-foreground/[0.06] hover:text-foreground',
+ dropTarget === crumb.path && 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan',
+ )}
+ >
+ {crumb.label}
+ </button>
+ </span>
+ ))}
+ </div>
+
+ {navigationControl && (mobileRoute ? <div className="order-2 w-full">{navigationControl}</div> : navigationControl)}
+
+ {hasSearch && (
+ <label
+ className={clsx(
+ 'flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2 py-1',
+ mobileRoute ? 'order-2 w-full' : 'shrink-0',
+ )}
+ >
+ {searchBusy ? <RefreshCw className="size-3.5 shrink-0 animate-spin text-muted" /> : <Search className="size-3.5 shrink-0 text-muted" />}
+ <input
+ value={query}
+ onChange={(event) => onQueryChange(event.target.value)}
+ placeholder={t(searchMode === 'content' ? 'apps.fileBrowser.searchContentPlaceholder' : 'apps.fileBrowser.searchPlaceholder')}
+ className={clsx(
+ 'min-w-0 flex-1 bg-transparent text-[12px] text-foreground placeholder:text-muted focus:outline-none',
+ !mobileRoute && 'w-28 flex-none',
+ )}
+ />
+ {onSearchModeChange && (
+ <button
+ type="button"
+ aria-pressed={searchMode === 'content'}
+ aria-label={t('apps.fileBrowser.searchContents')}
+ title={t('apps.fileBrowser.searchContents')}
+ onClick={() => onSearchModeChange(searchMode === 'content' ? 'name' : 'content')}
+ className={clsx(
+ 'grid size-5 shrink-0 place-items-center rounded transition',
+ searchMode === 'content' ? 'bg-cyan-soft text-cyan-ink' : 'text-muted hover:bg-foreground/10 hover:text-foreground',
+ )}
+ >
+ <FileSearch className="size-3.5" />
+ </button>
+ )}
+ {query && (
+ <button type="button" onClick={() => onQueryChange('')} className="shrink-0 text-muted transition hover:text-foreground" aria-label={t('common.close')}>
+ <X className="size-3" strokeWidth={2.5} />
+ </button>
+ )}
+ </label>
+ )}
+
+ {toolbarActions && (
+ <div className={clsx('flex shrink-0 items-center gap-1 overflow-x-auto', mobileRoute ? 'order-3 w-full justify-end' : 'ml-auto')}>
+ {toolbarActions}
+ </div>
+ )}
+ </div>
+
+ {(sysFavs.length > 0 || projectFavs.length > 0) && (
+ <div className="flex shrink-0 items-center gap-2 overflow-x-auto border-b border-border bg-surface-2/60 px-3 py-2 md:hidden">
+ {sysFavs.map((favorite) => {
+ const Icon = FAV_ICON[favorite.key] ?? Folder;
+ const active = cwd === favorite.path;
+ return (
+ <button
+ key={favorite.path}
+ type="button"
+ aria-current={active ? 'true' : undefined}
+ title={favorite.path}
+ onClick={() => navigateFavoriteTo(favorite.path)}
+ className={clsx(
+ 'flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-[12.5px] font-medium transition',
+ active ? 'border-cyan/40 bg-cyan-soft text-foreground' : 'border-border-strong text-muted',
+ )}
+ >
+ <Icon className="size-3.5 shrink-0" />
+ <span className="max-w-[140px] truncate">{favoriteLabel(favorite)}</span>
+ </button>
+ );
+ })}
+ {projectFavs.map((project) => {
+ const active = cwd === project.path;
+ return (
+ <button
+ key={project.path}
+ type="button"
+ aria-current={active ? 'true' : undefined}
+ onClick={() => navigateFavoriteTo(project.path)}
+ className={clsx(
+ 'flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-[12.5px] font-medium transition',
+ active ? 'border-cyan/40 bg-cyan-soft text-foreground' : 'border-border-strong text-muted',
+ )}
+ >
+ <Folder className={clsx('size-3.5 shrink-0', active ? 'text-cyan-ink' : 'text-cyan-ink/70')} />
+ <span className="max-w-[140px] truncate">{project.label}</span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ {error && <div className="border-b border-destructive/40 bg-destructive/[0.06] px-3 py-1.5 text-[11.5px] text-destructive-ink">{error}</div>}
+
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <aside className="hidden w-[196px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-border bg-surface-2/40 p-2 md:flex">
+ {sysFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.favorites')}</RailTitle>}
+ {sysFavs.map((favorite) => {
+ const Icon = FAV_ICON[favorite.key] ?? Folder;
+ return (
+ <RailRow
+ key={favorite.path}
+ icon={<Icon className="size-3.5 text-muted" />}
+ label={favoriteLabel(favorite)}
+ title={favorite.path}
+ active={cwd === favorite.path}
+ dropActive={dropTarget === favorite.path}
+ dropProps={railDropProps(favorite.path)}
+ onClick={() => navigateFavoriteTo(favorite.path)}
+ />
+ );
+ })}
+ {projectFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.projects')}</RailTitle>}
+ {projectFavs.map((project) => (
+ <RailRow
+ key={project.path}
+ icon={<Folder className="size-3.5 text-cyan-ink" />}
+ label={project.label}
+ active={cwd === project.path}
+ dropActive={dropTarget === project.path}
+ dropProps={railDropProps(project.path)}
+ onClick={() => navigateFavoriteTo(project.path)}
+ />
+ ))}
+ </aside>
+
+ <div {...paneProps} className={clsx('relative flex min-w-0 flex-1 flex-col', paneProps?.className)}>
+ {listHeader}
+ <div className="min-h-0 flex-1 overflow-y-auto py-1" {...listProps}>
+ {listContent}
+ </div>
+ {dropOverlay}
+ </div>
+ </div>
+
+ {footerContent}
+
+ <div className="flex items-center gap-3 border-t border-border bg-surface-2/60 px-3 py-1.5 text-[11px] text-muted">
+ <label className="flex items-center gap-1.5">
+ <input type="checkbox" checked={showHidden} onChange={(event) => onShowHiddenChange(event.target.checked)} className="size-3" />
+ {t('apps.fileBrowser.showHidden')}
+ </label>
+ {statusContent}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+const RailTitle: React.FC<{ children: ReactNode }> = ({ children }) => (
+ <div className="px-1 pb-0.5 pt-1.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">{children}</div>
+);
+
+const RailRow: React.FC<{
+ icon: ReactNode;
+ label: string;
+ title?: string;
+ active: boolean;
+ onClick: () => void;
+ dropActive?: boolean;
+ dropProps?: FileBrowserDropProps;
+}> = ({ icon, label, title, active, onClick, dropActive, dropProps }) => (
+ <button
+ type="button"
+ title={title}
+ onClick={onClick}
+ {...dropProps}
+ className={clsx(
+ 'flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',
+ dropActive
+ ? 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan'
+ : active
+ ? 'bg-cyan-soft text-foreground'
+ : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
+ )}
+ >
+ <span className="shrink-0">{icon}</span>
+ <span className="truncate">{label}</span>
+ </button>
+);
diff --git a/ui/src/components/ui/folder-browser.test.tsx b/ui/src/components/ui/folder-browser.test.tsx
new file mode 100644
index 000000000..782e5edc1
--- /dev/null
+++ b/ui/src/components/ui/folder-browser.test.tsx
@@ -0,0 +1,822 @@
+/* @vitest-environment jsdom */
+
+import { StrictMode } from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
+import type { FsListing } from '../../lib/filesApi';
+
+const projects = vi.hoisted(() => ({ value: [] as unknown[] | null, error: null as string | null }));
+const listDir = vi.hoisted(() =>
+ vi.fn(async (path: string): Promise<FsListing> => ({
+ ok: true as const,
+ path,
+ parent: path === '/workspace' ? '/' : '/workspace',
+ entries: path === '/workspace'
+ ? [
+ { name: 'src', kind: 'dir' as const, size: null, mtime: 2, ext: '' },
+ { name: 'README.md', kind: 'file' as const, size: 12, mtime: 1, ext: 'md' },
+ ]
+ : [],
+ })),
+);
+const makeDir = vi.hoisted(() => vi.fn());
+const searchNames = vi.hoisted(() => vi.fn());
+const systemFavorites = vi.hoisted(() => vi.fn().mockResolvedValue([{ key: 'home', path: '/workspace' }]));
+const resolveDirectoryPath = vi.hoisted(() => vi.fn());
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('../../context/WorkbenchProjectsContext', () => ({
+ useWorkbenchProjectsTree: () => ({ projects: projects.value, projectsError: projects.error }),
+}));
+vi.mock('../../lib/useIsDesktop', () => ({ useIsDesktop: () => true }));
+vi.mock('../../lib/filesApi', () => ({
+ fileBrowserErrorMessage: (_error: unknown, _t: unknown, fallback: string) => fallback,
+ isPlainEntryName: (value: string) => value.trim() !== '',
+ joinPath: (base: string, name: string) => `${base}/${name}`,
+ listDir,
+ makeDir,
+ pathCrumbs: (path: string) => [{ label: '/', path: '/' }, { label: path.slice(1), path }],
+ resolveDirectoryPath,
+ searchNames,
+ systemFavorites,
+}));
+
+import { FolderBrowser } from './folder-browser';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (cause: Error) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+beforeEach(() => {
+ projects.value = [];
+ projects.error = null;
+ makeDir.mockReset().mockResolvedValue({ ok: true });
+ searchNames.mockReset().mockResolvedValue({ results: [], truncated: false });
+ systemFavorites.mockReset().mockResolvedValue([{ key: 'home', path: '/workspace' }]);
+ resolveDirectoryPath.mockReset().mockImplementation(async (path: string) => path);
+ listDir.mockReset().mockImplementation(async (path: string) => ({
+ ok: true as const,
+ path,
+ parent: path === '/workspace' ? '/' : '/workspace',
+ entries: path === '/workspace'
+ ? [
+ { name: 'src', kind: 'dir' as const, size: null, mtime: 2, ext: '' },
+ { name: 'README.md', kind: 'file' as const, size: 12, mtime: 1, ext: 'md' },
+ ]
+ : [],
+ }));
+});
+
+it('reuses the Files surface while keeping folder selection actions focused', async () => {
+ const onSelect = vi.fn();
+ render(<FolderBrowser initialPath="/workspace" onSelect={onSelect} onClose={() => {}} />);
+
+ expect(await screen.findByText('src')).toBeTruthy();
+ expect(screen.getByText('apps.fileBrowser.newFolder')).toBeTruthy();
+ expect(screen.queryByText('apps.fileBrowser.newFile')).toBeNull();
+ expect(screen.queryByText('apps.fileBrowser.upload')).toBeNull();
+
+ fireEvent.click(screen.getByText('src'));
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith('/workspace/src', false));
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.select' }));
+ expect(onSelect).toHaveBeenCalledWith('/workspace/src');
+});
+
+it('uses the shared dialog close behavior', async () => {
+ const onClose = vi.fn();
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={onClose} />);
+
+ await screen.findByText('src');
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
+
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('completes initial navigation after a StrictMode effect replay', async () => {
+ render(
+ <StrictMode>
+ <FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />
+ </StrictMode>,
+ );
+
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/workspace', false));
+});
+
+it('waits for the project tree before selecting the initial project', async () => {
+ projects.value = null;
+ const view = render(<FolderBrowser onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(listDir).not.toHaveBeenCalled());
+
+ projects.value = [
+ {
+ id: 'project-1',
+ display_name: 'Project',
+ folder_path: '/project',
+ created_at: '2026-09-22T00:00:00Z',
+ last_active_at: '2026-09-22T00:00:00Z',
+ },
+ ];
+ view.rerender(<FolderBrowser onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/project', false));
+});
+
+it('falls back to home when system favorites fail during initial navigation', async () => {
+ systemFavorites.mockRejectedValueOnce(new Error('offline'));
+ render(<FolderBrowser onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('~', false));
+});
+
+it.each(['home', 'project'] as const)('canonicalizes the symlinked %s fallback', async (source) => {
+ const canonicalPath = '/real/项目';
+ if (source === 'home') {
+ systemFavorites.mockResolvedValue([{ key: 'home', path: '/folder-link' }]);
+ } else {
+ projects.value = [{ id: 'project', display_name: 'Project', folder_path: '/folder-link' }];
+ }
+ resolveDirectoryPath.mockResolvedValue(canonicalPath);
+ const onSelect = vi.fn();
+ render(<FolderBrowser onSelect={onSelect} onClose={() => {}} />);
+
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith(canonicalPath, false));
+ expect(listDir).not.toHaveBeenCalledWith('/folder-link', expect.anything());
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.select' }));
+ expect(onSelect).toHaveBeenCalledWith(canonicalPath);
+});
+
+it.each(['favorite', 'project'] as const)('canonicalizes a selected %s before listing', async (source) => {
+ const canonicalPath = '/real/项目';
+ if (source === 'favorite') {
+ systemFavorites.mockResolvedValue([{ key: 'home', path: '/folder-link' }]);
+ } else {
+ projects.value = [{ id: 'project', display_name: 'folder-link', folder_path: '/folder-link' }];
+ }
+ resolveDirectoryPath.mockImplementation(async (path: string) => path === '/folder-link' ? canonicalPath : path);
+ const onSelect = vi.fn();
+ render(<FolderBrowser initialPath="/workspace" onSelect={onSelect} onClose={() => {}} />);
+ await screen.findByText('src');
+
+ fireEvent.click(screen.getAllByRole('button', { name: source === 'favorite' ? 'directoryBrowser.favoritesHome' : 'folder-link' })[0]);
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith(canonicalPath, false));
+ expect(listDir).not.toHaveBeenCalledWith('/folder-link', expect.anything());
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.select' }));
+ expect(onSelect).toHaveBeenCalledWith(canonicalPath);
+});
+
+it('waits for favorite canonicalization before refreshing with the new hidden-file state', async () => {
+ const resolved = deferred<string>();
+ systemFavorites.mockResolvedValue([{ key: 'home', path: '/folder-link' }]);
+ resolveDirectoryPath.mockImplementation((path: string) => path === '/folder-link' ? resolved.promise : Promise.resolve(path));
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'directoryBrowser.favoritesHome' })[0]);
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('/folder-link'));
+ fireEvent.click(screen.getByRole('checkbox'));
+ expect(listDir).not.toHaveBeenCalledWith('/folder-link', true);
+
+ await act(async () => resolved.resolve('/real/项目'));
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith('/real/项目', true));
+});
+
+it('resolves relative configured paths before using the Files API', async () => {
+ let resolvePath!: (path: string) => void;
+ resolveDirectoryPath.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolvePath = resolve;
+ }),
+ );
+ render(<FolderBrowser initialPath='./workspace' onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('./workspace'));
+ resolvePath('/resolved/workspace');
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/resolved/workspace', false));
+});
+
+it('resolves absolute configured paths before using the Files API', async () => {
+ resolveDirectoryPath.mockResolvedValueOnce('/real/workspace');
+ render(<FolderBrowser initialPath="/workspace-link" onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('/workspace-link'));
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/real/workspace', false));
+});
+
+it('navigates to an arbitrary path entered in the picker', async () => {
+ resolveDirectoryPath.mockImplementation(async (path: string) => (path === '\\\\server\\share' ? '/server/share' : path));
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const input = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(input, { target: { value: '\\\\server\\share' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('\\\\server\\share'));
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith('/server/share', false));
+});
+
+it('discards a manual path submission after explicit navigation', async () => {
+ let resolvePath!: (path: string) => void;
+ resolveDirectoryPath.mockImplementation((path: string) => {
+ if (path === '/stale') {
+ return new Promise((resolve) => {
+ resolvePath = resolve;
+ });
+ }
+ return Promise.resolve(path);
+ });
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const input = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(input, { target: { value: '/stale' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('/stale'));
+
+ fireEvent.click((await screen.findAllByRole('button', { name: 'directoryBrowser.favoritesHome' }))[0]);
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith('/workspace', false));
+ resolvePath('/stale');
+
+ await waitFor(() => expect(listDir).not.toHaveBeenCalledWith('/stale', false));
+});
+
+it('keeps only the newest manual path submission', async () => {
+ let resolveFirst!: (path: string) => void;
+ let resolveSecond!: (path: string) => void;
+ resolveDirectoryPath.mockImplementation((path: string) => {
+ if (path === '/first') {
+ return new Promise((resolve) => {
+ resolveFirst = resolve;
+ });
+ }
+ if (path === '/second') {
+ return new Promise((resolve) => {
+ resolveSecond = resolve;
+ });
+ }
+ return Promise.resolve(path);
+ });
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const input = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(input, { target: { value: '/first' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('/first'));
+
+ fireEvent.change(input, { target: { value: '/second' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('/second'));
+
+ resolveFirst('/first');
+ await waitFor(() => expect(listDir).not.toHaveBeenCalledWith('/first', false));
+ resolveSecond('/second');
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith('/second', false));
+});
+
+it('does not override explicit navigation when initial path resolution finishes later', async () => {
+ let resolvePath!: (path: string) => void;
+ resolveDirectoryPath.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolvePath = resolve;
+ }),
+ );
+ render(<FolderBrowser initialPath="./workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('./workspace'));
+ fireEvent.click((await screen.findAllByRole('button', { name: 'directoryBrowser.favoritesHome' }))[0]);
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/workspace', false));
+
+ resolvePath('/resolved/workspace');
+ await waitFor(() => expect(listDir).not.toHaveBeenCalledWith('/resolved/workspace', false));
+});
+
+it('ignores an initial path resolution error after explicit navigation', async () => {
+ let rejectPath!: (cause: Error) => void;
+ resolveDirectoryPath.mockReturnValueOnce(
+ new Promise((_resolve, reject) => {
+ rejectPath = reject;
+ }),
+ );
+ const onSelect = vi.fn();
+ render(<FolderBrowser initialPath="./workspace" onSelect={onSelect} onClose={() => {}} />);
+
+ await waitFor(() => expect(resolveDirectoryPath).toHaveBeenCalledWith('./workspace'));
+ fireEvent.click((await screen.findAllByRole('button', { name: 'directoryBrowser.favoritesHome' }))[0]);
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/workspace', false));
+
+ await act(async () => {
+ rejectPath(new Error('stale initial path'));
+ await Promise.resolve();
+ });
+
+ expect(screen.queryByText('apps.fileBrowser.errors.listFailed')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.select' }));
+ expect(onSelect).toHaveBeenCalledWith('/workspace');
+});
+
+it('refreshes a pending destination when hidden files change', async () => {
+ const requests: Array<{
+ path: string;
+ showHidden: boolean;
+ resolve: (result: {
+ ok: true;
+ path: string;
+ parent: string;
+ entries: Array<{ name: string; kind: 'dir'; size: null; mtime: number; ext: string }>;
+ }) => void;
+ }> = [];
+ listDir.mockImplementation((path: string, showHidden: boolean) => new Promise((resolve) => {
+ requests.push({ path, showHidden, resolve });
+ }));
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(requests).toHaveLength(1));
+ requests[0].resolve({ ok: true, path: '/workspace', parent: '/', entries: [{ name: 'src', kind: 'dir', size: null, mtime: 1, ext: '' }] });
+ await screen.findByText('src');
+
+ fireEvent.click(screen.getByText('src'));
+ await waitFor(() => expect(requests.some(({ path, showHidden }) => path === '/workspace/src' && !showHidden)).toBe(true));
+ fireEvent.click(screen.getByRole('checkbox'));
+ await waitFor(() => expect(requests.some(({ path, showHidden }) => path === '/workspace/src' && showHidden)).toBe(true));
+});
+
+it('falls back when the project tree fails to load', async () => {
+ projects.value = null;
+ projects.error = 'project tree unavailable';
+ render(<FolderBrowser onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/workspace', false));
+});
+
+it('keeps a new-folder draft while the route surface is suspended', async () => {
+ const props = { initialPath: '/workspace', onSelect: () => {}, onClose: () => {} };
+ const view = render(
+ <RouteSurfaceActiveContext.Provider value>
+ <FolderBrowser {...props} />
+ </RouteSurfaceActiveContext.Provider>,
+ );
+
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.newFolder' }));
+ const input = screen.getByPlaceholderText('apps.fileBrowser.newFolderPlaceholder') as HTMLInputElement;
+ fireEvent.change(input, { target: { value: 'draft-folder' } });
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value={false}>
+ <FolderBrowser {...props} />
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect(screen.queryByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeNull();
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value>
+ <FolderBrowser {...props} />
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect((await screen.findByPlaceholderText('apps.fileBrowser.newFolderPlaceholder') as HTMLInputElement).value).toBe('draft-folder');
+});
+
+it('restores path editor focus after the route surface resumes', async () => {
+ const props = { initialPath: '/workspace', onSelect: () => {}, onClose: () => {} };
+ const view = render(
+ <RouteSurfaceActiveContext.Provider value>
+ <FolderBrowser {...props} />
+ </RouteSurfaceActiveContext.Provider>,
+ );
+
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const input = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(input, { target: { value: '/draft' } });
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value={false}>
+ <FolderBrowser {...props} />
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect(screen.queryByRole('textbox', { name: 'directoryBrowser.editPath' })).toBeNull();
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value>
+ <FolderBrowser {...props} />
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ const resumedInput = await screen.findByRole('textbox', { name: 'directoryBrowser.editPath' });
+ expect((resumedInput as HTMLInputElement).value).toBe('/draft');
+ await waitFor(() => expect(document.activeElement).toBe(resumedInput));
+});
+
+it('re-fetches the initial listing when hidden files are toggled while loading', async () => {
+ let resolveInitial!: (result: { ok: true; path: string; parent: string; entries: never[] }) => void;
+ listDir.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveInitial = resolve;
+ }),
+ );
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await waitFor(() => expect(listDir).toHaveBeenCalledWith('/workspace', false));
+ fireEvent.click(screen.getByRole('checkbox'));
+ resolveInitial({ ok: true, path: '/workspace', parent: '/', entries: [] });
+
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith('/workspace', true));
+});
+
+it('preserves the active search when refreshing', async () => {
+ searchNames.mockResolvedValue({ results: [], truncated: false });
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ const search = screen.getByRole('textbox');
+ fireEvent.change(search, { target: { value: 'src' } });
+ await waitFor(() => expect(searchNames).toHaveBeenCalledWith('/workspace', 'src', false, expect.any(AbortSignal)));
+
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.refresh' }));
+ expect((search as HTMLInputElement).value).toBe('src');
+ await waitFor(() => expect(searchNames).toHaveBeenCalledTimes(2));
+});
+
+it('refreshes the directory listing when hidden files change during search', async () => {
+ searchNames.mockResolvedValue({ results: [], truncated: false });
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ const search = screen.getByRole('textbox');
+ fireEvent.change(search, { target: { value: 'src' } });
+ await waitFor(() => expect(searchNames).toHaveBeenCalledWith('/workspace', 'src', false, expect.any(AbortSignal)));
+
+ fireEvent.click(screen.getByRole('checkbox'));
+ expect((search as HTMLInputElement).value).toBe('src');
+ await waitFor(() => expect(listDir).toHaveBeenLastCalledWith('/workspace', true));
+});
+
+it.each(['hidden-files toggle', 'refresh'] as const)('preserves search across repeated %s with listings pending', async (action) => {
+ searchNames.mockResolvedValue({ results: [], truncated: false });
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ const search = screen.getByPlaceholderText('apps.fileBrowser.searchPlaceholder') as HTMLInputElement;
+ fireEvent.change(search, { target: { value: 'src' } });
+ await waitFor(() => expect(searchNames).toHaveBeenCalledTimes(1));
+ const first = deferred<FsListing>();
+ const second = deferred<FsListing>();
+ listDir.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ const trigger = action === 'refresh'
+ ? screen.getByRole('button', { name: 'apps.fileBrowser.refresh' })
+ : screen.getByRole('checkbox');
+ fireEvent.click(trigger);
+ await waitFor(() => expect(listDir).toHaveBeenCalledTimes(2));
+ fireEvent.click(trigger);
+ await waitFor(() => expect(listDir).toHaveBeenCalledTimes(3));
+
+ expect(search.value).toBe('src');
+ await waitFor(() => expect(searchNames).toHaveBeenLastCalledWith('/workspace', 'src', false, expect.any(AbortSignal)));
+ await act(async () => second.resolve({
+ ok: true, path: '/workspace', parent: '/',
+ entries: [{ name: 'fresh-dir', kind: 'dir', size: null, mtime: 1, ext: '' }],
+ }));
+ await act(async () => first.reject(new Error('stale listing failed')));
+ expect(search.value).toBe('src');
+ expect(screen.queryByText('apps.fileBrowser.errors.listFailed')).toBeNull();
+ fireEvent.change(search, { target: { value: '' } });
+ expect(await screen.findByText('fresh-dir')).toBeTruthy();
+});
+
+it('does not show a false empty state while search is pending', async () => {
+ let resolveSearch!: (result: { results: []; truncated: boolean }) => void;
+ searchNames.mockReturnValueOnce(
+ new Promise<{ results: []; truncated: boolean }>((resolve) => {
+ resolveSearch = resolve;
+ }),
+ );
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'src' } });
+ await waitFor(() => expect(searchNames).toHaveBeenCalledWith('/workspace', 'src', false, expect.any(AbortSignal)));
+
+ expect(screen.queryByText('apps.fileBrowser.noMatches')).toBeNull();
+ resolveSearch({ results: [], truncated: false });
+ expect(await screen.findByText('apps.fileBrowser.noMatches')).toBeTruthy();
+});
+
+it('cancels folder creation when search starts', async () => {
+ const onClose = vi.fn();
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={onClose} />);
+
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.newFolder' }));
+ expect(screen.getByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeTruthy();
+
+ fireEvent.change(screen.getByPlaceholderText('apps.fileBrowser.searchPlaceholder'), { target: { value: 'src' } });
+ expect(screen.queryByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeNull();
+
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
+ expect(onClose).toHaveBeenCalledOnce();
+});
+
+it('keeps selection enabled after a new-folder operation fails', async () => {
+ makeDir.mockRejectedValueOnce(new Error('already exists'));
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ const select = screen.getByRole('button', { name: 'directoryBrowser.select' });
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.newFolder' }));
+ const input = screen.getByPlaceholderText('apps.fileBrowser.newFolderPlaceholder');
+ fireEvent.change(input, { target: { value: 'existing' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ await screen.findByText('apps.fileBrowser.errors.createFolderFailed');
+ expect((select as HTMLButtonElement).disabled).toBe(false);
+
+ fireEvent.keyDown(input, { key: 'Escape' });
+ expect(screen.queryByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeNull();
+});
+
+it('reports truncated directory listings', async () => {
+ listDir.mockResolvedValueOnce({
+ ok: true as const,
+ path: '/workspace',
+ parent: '/',
+ entries: [{ name: 'src', kind: 'dir' as const, size: null, mtime: 2, ext: '' }],
+ truncated: true,
+ limit: 1,
+ });
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+
+ await screen.findByText('src');
+ expect(screen.getByText(/apps\.fileBrowser\.listTruncated/)).toBeTruthy();
+});
+
+const currentDirectory = () => screen.getByRole('dialog').querySelector('code')?.textContent;
+const selectButton = () => screen.getByRole('button', { name: 'directoryBrowser.select' }) as HTMLButtonElement;
+const emptyListing = (path: string): FsListing => ({ ok: true, path, parent: '/', entries: [] });
+
+it.each(['success', 'failure'] as const)('ignores an older listing %s while a favorite resolves, without canceling it when a draft opens', async (outcome) => {
+ const stale = deferred<FsListing>();
+ const favorite = deferred<string>();
+ systemFavorites.mockResolvedValue([{ key: 'home', path: '/favorite' }]);
+ resolveDirectoryPath.mockImplementation((path: string) => path === '/favorite' ? favorite.promise : Promise.resolve(path));
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ listDir.mockReturnValueOnce(stale.promise);
+ fireEvent.click(screen.getByText('src'));
+ fireEvent.click(screen.getAllByRole('button', { name: 'directoryBrowser.favoritesHome' })[0]);
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const editor = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(editor, { target: { value: '/new-draft' } });
+
+ await act(async () => {
+ if (outcome === 'success') stale.resolve(emptyListing('/workspace/src'));
+ else stale.reject(new Error('stale listing'));
+ });
+ expect(currentDirectory()).toBe('/workspace');
+ expect(selectButton().disabled).toBe(true);
+ expect(screen.queryByText('apps.fileBrowser.errors.listFailed')).toBeNull();
+
+ await act(async () => favorite.resolve('/canonical-favorite'));
+ expect(currentDirectory()).toBe('/canonical-favorite');
+ expect(selectButton().disabled).toBe(false);
+ expect((editor as HTMLInputElement).value).toBe('/new-draft');
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.back' }));
+ await waitFor(() => expect(currentDirectory()).toBe('/workspace'));
+});
+
+it.each(['success', 'failure'] as const)('ignores a favorite resolver %s after a manual submission supersedes it', async (outcome) => {
+ const favorite = deferred<string>();
+ systemFavorites.mockResolvedValue([{ key: 'home', path: '/favorite' }]);
+ resolveDirectoryPath.mockImplementation((path: string) => path === '/favorite' ? favorite.promise : Promise.resolve(path));
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ fireEvent.click(screen.getAllByRole('button', { name: 'directoryBrowser.favoritesHome' })[0]);
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const editor = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(editor, { target: { value: '/manual' } });
+ fireEvent.keyDown(editor, { key: 'Enter' });
+ await waitFor(() => expect(currentDirectory()).toBe('/manual'));
+ await act(async () => {
+ if (outcome === 'success') favorite.resolve('/favorite');
+ else favorite.reject(new Error('stale favorite'));
+ });
+ expect(currentDirectory()).toBe('/manual');
+ expect(selectButton().disabled).toBe(false);
+ expect(screen.queryByText('apps.fileBrowser.errors.listFailed')).toBeNull();
+ expect(listDir).not.toHaveBeenCalledWith('/favorite', expect.anything());
+});
+
+it.each([
+ ['resolve', 'success'], ['resolve', 'failure'], ['list', 'success'], ['list', 'failure'],
+] as const)('cancels a manual submission in the %s phase before its %s', async (phase, outcome) => {
+ const resolution = deferred<string>();
+ const listing = deferred<FsListing>();
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ if (phase === 'resolve') resolveDirectoryPath.mockReturnValueOnce(resolution.promise);
+ else listDir.mockReturnValueOnce(listing.promise);
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const editor = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(editor, { target: { value: '/cancelled' } });
+ fireEvent.keyDown(editor, { key: 'Enter' });
+ await waitFor(() => expect(phase === 'resolve' ? resolveDirectoryPath : listDir).toHaveBeenCalledWith(
+ ...phase === 'resolve' ? ['/cancelled'] : ['/cancelled', false],
+ ));
+ fireEvent.keyDown(editor, { key: 'Escape' });
+ expect(selectButton().disabled).toBe(false);
+ await act(async () => {
+ if (outcome === 'failure') (phase === 'resolve' ? resolution : listing).reject(new Error('cancelled request'));
+ else if (phase === 'resolve') resolution.resolve('/cancelled');
+ else listing.resolve(emptyListing('/cancelled'));
+ });
+ expect(currentDirectory()).toBe('/workspace');
+ expect(selectButton().disabled).toBe(false);
+ expect(screen.queryByText('directoryBrowser.pathNotFound')).toBeNull();
+ expect((screen.getByRole('button', { name: 'directoryBrowser.back' }) as HTMLButtonElement).disabled).toBe(true);
+});
+
+it.each(['success', 'failure'] as const)('discards stale mkdir %s without overriding a pending destination', async (outcome) => {
+ const creation = deferred<{ ok: true }>();
+ const destination = deferred<FsListing>();
+ makeDir.mockReturnValueOnce(creation.promise);
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.newFolder' }));
+ const editor = screen.getByPlaceholderText('apps.fileBrowser.newFolderPlaceholder');
+ fireEvent.change(editor, { target: { value: 'new-folder' } });
+ fireEvent.keyDown(editor, { key: 'Enter' });
+ expect(makeDir).toHaveBeenCalledWith('/workspace/new-folder');
+ listDir.mockReturnValueOnce(destination.promise);
+ fireEvent.click(screen.getByText('src'));
+ await act(async () => {
+ if (outcome === 'success') creation.resolve({ ok: true });
+ else creation.reject(new Error('old creation'));
+ });
+ expect(listDir).toHaveBeenCalledTimes(2);
+ expect(selectButton().disabled).toBe(true);
+ expect(screen.queryByText('apps.fileBrowser.errors.createFolderFailed')).toBeNull();
+ await act(async () => destination.resolve(emptyListing('/workspace/src')));
+ expect(currentDirectory()).toBe('/workspace/src');
+ expect(selectButton().disabled).toBe(false);
+});
+
+it.each(['success', 'failure'] as const)('keeps a newer creation draft after an older mkdir %s', async (outcome) => {
+ const creation = deferred<{ ok: true }>();
+ makeDir.mockReturnValueOnce(creation.promise);
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.newFolder' }));
+ const editor = screen.getByPlaceholderText('apps.fileBrowser.newFolderPlaceholder') as HTMLInputElement;
+ fireEvent.change(editor, { target: { value: 'old' } });
+ fireEvent.keyDown(editor, { key: 'Enter' });
+ fireEvent.change(editor, { target: { value: 'new draft' } });
+ await act(async () => {
+ if (outcome === 'success') creation.resolve({ ok: true });
+ else creation.reject(new Error('old creation'));
+ });
+ expect(editor.isConnected).toBe(true);
+ expect(editor.value).toBe('new draft');
+ expect(listDir).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText('apps.fileBrowser.errors.createFolderFailed')).toBeNull();
+});
+
+it('records successful navigation only and preserves history intent across hidden-file refresh', async () => {
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ fireEvent.click(screen.getByText('src'));
+ await waitFor(() => expect(currentDirectory()).toBe('/workspace/src'));
+ const back = screen.getByRole('button', { name: 'directoryBrowser.back' }) as HTMLButtonElement;
+ const forward = screen.getByRole('button', { name: 'directoryBrowser.forward' }) as HTMLButtonElement;
+ const stale = deferred<FsListing>();
+ listDir.mockReturnValueOnce(stale.promise);
+ fireEvent.click(back);
+ fireEvent.click(screen.getByRole('checkbox'));
+ await waitFor(() => expect(currentDirectory()).toBe('/workspace'));
+ await act(async () => stale.reject(new Error('superseded back listing')));
+ expect(back.disabled).toBe(true);
+ expect(forward.disabled).toBe(false);
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.refresh' }));
+ await waitFor(() => expect(selectButton().disabled).toBe(false));
+ expect(back.disabled).toBe(true);
+ expect(forward.disabled).toBe(false);
+ listDir.mockRejectedValueOnce(new Error('forward failed'));
+ fireEvent.click(forward);
+ await screen.findByText('apps.fileBrowser.errors.listFailed');
+ expect(currentDirectory()).toBe('/workspace');
+ expect(back.disabled).toBe(true);
+ expect(forward.disabled).toBe(false);
+ fireEvent.click(forward);
+ await waitFor(() => expect(currentDirectory()).toBe('/workspace/src'));
+ expect(back.disabled).toBe(false);
+ expect(forward.disabled).toBe(true);
+});
+
+it.each(['results', 'error'] as const)('does not carry search %s from the source into a pending destination', async (outcome) => {
+ const destination = deferred<FsListing>();
+ const targetSearch = deferred<{ results: []; truncated: boolean }>();
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ listDir.mockReturnValueOnce(destination.promise);
+ fireEvent.click(screen.getByText('src'));
+ if (outcome === 'error') searchNames.mockRejectedValueOnce(new Error('source search'));
+ else searchNames.mockResolvedValueOnce({
+ results: [{ name: 'source-hit', kind: 'dir', path: '/workspace/source-hit', rel: 'source-hit', size: null, mtime: null, ext: '' }],
+ truncated: false,
+ });
+ searchNames.mockReturnValueOnce(targetSearch.promise);
+ fireEvent.change(screen.getByPlaceholderText('apps.fileBrowser.searchPlaceholder'), { target: { value: 'hit' } });
+ await screen.findByText(outcome === 'error' ? 'apps.fileBrowser.errors.searchFailed' : 'source-hit');
+ await act(async () => destination.resolve(emptyListing('/workspace/src')));
+ expect(currentDirectory()).toBe('/workspace/src');
+ expect(screen.queryByText('source-hit')).toBeNull();
+ expect(screen.queryByText('apps.fileBrowser.errors.searchFailed')).toBeNull();
+ expect(screen.queryByText('apps.fileBrowser.noMatches')).toBeNull();
+ await waitFor(() => expect(searchNames).toHaveBeenLastCalledWith('/workspace/src', 'hit', false, expect.any(AbortSignal)));
+ await act(async () => targetSearch.resolve({ results: [], truncated: false }));
+ expect(await screen.findByText('apps.fileBrowser.noMatches')).toBeTruthy();
+});
+
+it.each(['cancel', 'failure'] as const)('reconciles hidden entries in the source after manual navigation %s', async (outcome) => {
+ const resolution = deferred<string>();
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ resolveDirectoryPath.mockReturnValueOnce(resolution.promise);
+ listDir.mockResolvedValueOnce({
+ ...emptyListing('/workspace'),
+ entries: [{ name: '.hidden', kind: 'dir', size: null, mtime: null, ext: '' }],
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ const editor = screen.getByRole('textbox', { name: 'directoryBrowser.editPath' });
+ fireEvent.change(editor, { target: { value: '/pending' } });
+ fireEvent.keyDown(editor, { key: 'Enter' });
+ fireEvent.click(screen.getByRole('checkbox'));
+ if (outcome === 'cancel') {
+ fireEvent.keyDown(editor, { key: 'Escape' });
+ await act(async () => resolution.resolve('/pending'));
+ } else {
+ await act(async () => resolution.reject(new Error('manual path failed')));
+ expect(screen.getByText('directoryBrowser.pathNotFound')).toBeTruthy();
+ }
+ await screen.findByText('.hidden');
+ expect(listDir).toHaveBeenLastCalledWith('/workspace', true);
+ expect(currentDirectory()).toBe('/workspace');
+ expect(selectButton().disabled).toBe(false);
+});
+
+it.each(['ctrlKey', 'metaKey'] as const)('opens folder creation with %s+N without resetting an existing draft', async (modifier) => {
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await screen.findByText('src');
+ fireEvent.click(screen.getByRole('button', { name: 'directoryBrowser.editPath' }));
+ expect(fireEvent.keyDown(window, { key: 'n', [modifier]: true })).toBe(false);
+ const editor = screen.getByPlaceholderText('apps.fileBrowser.newFolderPlaceholder') as HTMLInputElement;
+ expect(screen.queryByRole('textbox', { name: 'directoryBrowser.editPath' })).toBeNull();
+ fireEvent.change(editor, { target: { value: 'retained draft' } });
+ expect(fireEvent.keyDown(window, { key: 'n', [modifier]: true })).toBe(false);
+ expect(editor.value).toBe('retained draft');
+ fireEvent.keyDown(editor, { key: 'Enter' });
+ await waitFor(() => expect(makeDir).toHaveBeenCalledWith('/workspace/retained draft'));
+});
+
+it('does not bypass new-folder readiness with the shortcut', async () => {
+ const pending = deferred<FsListing>();
+ listDir.mockReturnValueOnce(pending.promise);
+ render(<FolderBrowser initialPath="/workspace" onSelect={() => {}} onClose={() => {}} />);
+ await waitFor(() => expect(listDir).toHaveBeenCalled());
+ fireEvent.keyDown(window, { key: 'n', ctrlKey: true });
+ expect(screen.queryByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeNull();
+ await act(async () => pending.resolve(emptyListing('/workspace')));
+ listDir.mockRejectedValueOnce(new Error('listing unavailable'));
+ fireEvent.click(screen.getByRole('button', { name: 'apps.fileBrowser.refresh' }));
+ await screen.findByText('apps.fileBrowser.errors.listFailed');
+ fireEvent.keyDown(window, { key: 'n', metaKey: true });
+ expect(screen.queryByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeNull();
+});
+
+it('withdraws the creation shortcut while suspended and restores it on return', async () => {
+ const props = { initialPath: '/workspace', onSelect: () => {}, onClose: () => {} };
+ const view = render(<RouteSurfaceActiveContext.Provider value><FolderBrowser {...props} /></RouteSurfaceActiveContext.Provider>);
+ await screen.findByText('src');
+ view.rerender(<RouteSurfaceActiveContext.Provider value={false}><FolderBrowser {...props} /></RouteSurfaceActiveContext.Provider>);
+ expect(fireEvent.keyDown(window, { key: 'n', ctrlKey: true })).toBe(true);
+ view.rerender(<RouteSurfaceActiveContext.Provider value><FolderBrowser {...props} /></RouteSurfaceActiveContext.Provider>);
+ expect(screen.queryByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeNull();
+ expect(fireEvent.keyDown(window, { key: 'n', metaKey: true })).toBe(false);
+ expect(screen.getByPlaceholderText('apps.fileBrowser.newFolderPlaceholder')).toBeTruthy();
+ view.unmount();
+ expect(fireEvent.keyDown(window, { key: 'n', metaKey: true })).toBe(true);
+});
diff --git a/ui/src/components/ui/folder-browser.tsx b/ui/src/components/ui/folder-browser.tsx
new file mode 100644
index 000000000..f2e022ac2
--- /dev/null
+++ b/ui/src/components/ui/folder-browser.tsx
@@ -0,0 +1,624 @@
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Folder, FolderPlus, File as FileIcon, FolderOpen, Keyboard, Loader2 } from 'lucide-react';
+import clsx from 'clsx';
+
+import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { sortProjectsByRecent } from '../../lib/projectOrder';
+import { useRouteSurfaceActive, useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';
+import { useIsDesktop } from '../../lib/useIsDesktop';
+import {
+ fileBrowserErrorMessage,
+ isPlainEntryName,
+ joinPath,
+ listDir,
+ makeDir,
+ pathCrumbs,
+ resolveDirectoryPath,
+ searchNames,
+ systemFavorites,
+ type Favorite,
+ type FsEntry,
+ type FsListing,
+ type NameHit,
+} from '../../lib/filesApi';
+import { Button } from './button';
+import { Dialog, DialogContent, DialogTitle } from './dialog';
+import { FileBrowser, type FileBrowserRow } from './file-browser';
+import { InlineNameInput } from './inline-name-input';
+
+interface FolderBrowserProps {
+ initialPath?: string;
+ onSelect: (path: string) => void;
+ onClose: () => void;
+}
+
+type NavigationRequest = {
+ path: string;
+ resolve?: boolean;
+ history: 'push' | 'refresh' | number;
+ // Only a manual submission can dismiss its own, unchanged editor.
+ editRevision?: number;
+};
+
+type SearchResult = { key: string; rows: FileBrowserRow[]; truncated: boolean; error?: string };
+
+function sortEntries(entries: FsEntry[]): FsEntry[] {
+ return [...entries].sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1));
+}
+
+function searchRow(hit: NameHit): FileBrowserRow {
+ return { entry: hit, full: hit.path, dir: hit.path.slice(0, hit.path.length - hit.name.length).replace(/[\\/]$/, ''), rel: hit.rel };
+}
+
+function relativeFolder(rel: string | undefined): string {
+ if (!rel || !rel.includes('/')) return '';
+ return rel.slice(0, rel.lastIndexOf('/'));
+}
+
+function formatSize(size: number | null): string {
+ if (size == null) return '—';
+ if (size < 1024) return `${size} B`;
+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
+ return `${(size / 1024 / 1024).toFixed(1)} MB`;
+}
+
+function formatMtime(seconds: number | null): string {
+ if (seconds == null) return '—';
+ const date = new Date(seconds * 1000);
+ const sameYear = date.getFullYear() === new Date().getFullYear();
+ return `${date.toLocaleDateString(undefined, sameYear ? { month: 'short', day: 'numeric' } : { year: 'numeric', month: 'short', day: 'numeric' })} ${date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}`;
+}
+
+export const FolderBrowser: React.FC<FolderBrowserProps> = ({ initialPath, onSelect, onClose }) => {
+ const { t } = useTranslation();
+ const { projects, projectsError } = useWorkbenchProjectsTree();
+ const surfaceActive = useRouteSurfaceActive();
+ const isDesktop = useIsDesktop();
+ const [cwd, setCwd] = useState('');
+ const [listing, setListing] = useState<FsListing | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [listingError, setListingError] = useState<string | null>(null);
+ const [showHidden, setShowHidden] = useState(false);
+ const [sysFavs, setSysFavs] = useState<Favorite[]>([]);
+ const [sysFavsLoaded, setSysFavsLoaded] = useState(false);
+ const [query, setQuery] = useState('');
+ const [searchResult, setSearchResult] = useState<SearchResult | null>(null);
+ const [searchRevision, setSearchRevision] = useState(0);
+ const [creatingFolder, setCreatingFolder] = useState(false);
+ const [newFolderName, setNewFolderName] = useState('');
+ const [pathEditing, setPathEditing] = useState(false);
+ const [pathInput, setPathInput] = useState('');
+ const [pathError, setPathError] = useState<string | null>(null);
+ const [history, setHistory] = useState<{ paths: string[]; index: number }>({ paths: [], index: -1 });
+ const navSeq = useRef(0);
+ const pendingNavigation = useRef<NavigationRequest | null>(null);
+ const lastNavigation = useRef<NavigationRequest | null>(null);
+ const loadedDirectory = useRef<{ path: string; hidden: boolean } | null>(null);
+ const searchAbort = useRef<AbortController | null>(null);
+ const initialPathHandled = useRef(false);
+ const pathInputRef = useRef<HTMLInputElement | null>(null);
+ const pathEditRevision = useRef(0);
+ const pathSelection = useRef<{ start: number; end: number; direction: 'forward' | 'backward' | 'none' } | null>(null);
+ const createSeq = useRef(0);
+ const mounted = useRef(true);
+ const showHiddenRef = useRef(showHidden);
+ const foreground = useRef(surfaceActive);
+ // A search result/error is valid only for the directory, query and options
+ // that produced it. Navigation can finish while the user is still searching.
+ const searchKey = JSON.stringify([cwd, query.trim(), showHidden, searchRevision]);
+ const currentSearch = searchResult?.key === searchKey ? searchResult : null;
+ const searchRows = currentSearch?.rows ?? null;
+ const searchTruncated = currentSearch?.truncated ?? false;
+ const searchBusy = !!query.trim() && !currentSearch;
+
+ useLayoutEffect(() => { foreground.current = surfaceActive; }, [surfaceActive]);
+
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+
+ const cancelCreateFolder = useCallback(() => {
+ createSeq.current += 1;
+ setCreatingFolder(false);
+ setNewFolderName('');
+ setError(null);
+ }, []);
+
+ const changeQuery = useCallback((value: string) => {
+ searchAbort.current?.abort();
+ setQuery(value);
+ if (value.trim()) cancelCreateFolder();
+ setSearchResult(null);
+ setError(null);
+ }, [cancelCreateFolder]);
+
+ const capturePathSelection = (input: HTMLInputElement) => {
+ if (!foreground.current || !input.isConnected || input.ownerDocument.activeElement !== input) return;
+ pathSelection.current = {
+ start: input.selectionStart ?? 0,
+ end: input.selectionEnd ?? 0,
+ direction: input.selectionDirection ?? 'none',
+ };
+ };
+
+ const focusPathInput = useCallback(() => {
+ const input = pathInputRef.current;
+ if (!input || !foreground.current) return;
+ input.focus();
+ if (pathSelection.current) {
+ const { start, end, direction } = pathSelection.current;
+ input.setSelectionRange(start, end, direction);
+ } else {
+ input.select();
+ }
+ }, []);
+
+ useEffect(() => {
+ if (pathEditing && surfaceActive) focusPathInput();
+ }, [focusPathInput, pathEditing, surfaceActive]);
+
+ const publishListing = useCallback((result: FsListing, hidden: boolean) => {
+ loadedDirectory.current = { path: result.path, hidden };
+ setCwd(result.path);
+ setListing(result);
+ }, []);
+
+ const runNavigation = useCallback(
+ async (request: NavigationRequest) => {
+ // Resolution and listing belong to the same intent. Every completion
+ // (including errors/finally) checks this one owner before publishing.
+ const seq = ++navSeq.current;
+ const current = () => mounted.current && seq === navSeq.current;
+ pendingNavigation.current = request;
+ lastNavigation.current = request;
+ initialPathHandled.current = true;
+ setPathError(null);
+ cancelCreateFolder();
+ setListingError(null);
+ setLoading(true);
+ try {
+ if (request.resolve) {
+ const resolved = await resolveDirectoryPath(request.path);
+ if (!current()) return;
+ // Refreshes reuse this canonical destination and the history intent.
+ request = { ...request, path: resolved, resolve: false };
+ pendingNavigation.current = request;
+ lastNavigation.current = request;
+ }
+ const hidden = showHiddenRef.current;
+ const result = await listDir(request.path, hidden);
+ if (!current()) return;
+ publishListing(result, hidden);
+ setHistory((previous) => {
+ if (request.history === 'refresh') return previous;
+ if (typeof request.history === 'number') {
+ const paths = [...previous.paths];
+ paths[request.history] = result.path;
+ return { paths, index: request.history };
+ }
+ if (previous.paths[previous.index] === result.path) return previous;
+ const paths = [...previous.paths.slice(0, previous.index + 1), result.path];
+ return { paths, index: paths.length - 1 };
+ });
+ if (request.editRevision !== undefined && request.editRevision === pathEditRevision.current) {
+ setPathEditing(false);
+ }
+ } catch (cause: unknown) {
+ if (!current()) return;
+ if (request.editRevision !== undefined) {
+ if (request.editRevision === pathEditRevision.current) {
+ setPathError(fileBrowserErrorMessage(cause, t, t('directoryBrowser.pathNotFound')));
+ }
+ } else {
+ setListingError(fileBrowserErrorMessage(cause, t, t('apps.fileBrowser.errors.listFailed')));
+ }
+ // The failed destination did not change cwd, but a hidden-file toggle
+ // may have invalidated its retained source listing. Reconcile that
+ // source once, under this same owner, without hiding the path error.
+ const source = loadedDirectory.current;
+ if (source && source.hidden !== showHiddenRef.current) {
+ const hidden = showHiddenRef.current;
+ pendingNavigation.current = { path: source.path, history: 'refresh' };
+ try {
+ const result = await listDir(source.path, hidden);
+ if (current()) publishListing(result, hidden);
+ } catch (refreshCause: unknown) {
+ if (current()) setListingError(fileBrowserErrorMessage(refreshCause, t, t('apps.fileBrowser.errors.listFailed')));
+ }
+ }
+ } finally {
+ if (current()) {
+ pendingNavigation.current = null;
+ setLoading(false);
+ }
+ }
+ },
+ [cancelCreateFolder, publishListing, t],
+ );
+
+ const navigate = useCallback((path: string, resolve = false) => {
+ changeQuery('');
+ void runNavigation({ path, resolve, history: 'push' });
+ }, [changeQuery, runNavigation]);
+
+ const submitPath = useCallback(() => {
+ const target = pathInput.trim();
+ if (!target) return;
+ changeQuery('');
+ void runNavigation({ path: target, resolve: true, history: 'push', editRevision: pathEditRevision.current });
+ }, [changeQuery, pathInput, runNavigation]);
+
+ useEffect(() => {
+ let cancelled = false;
+ systemFavorites()
+ .then((favorites) => { if (!cancelled) setSysFavs(favorites); })
+ .catch(() => {})
+ .finally(() => { if (!cancelled) setSysFavsLoaded(true); });
+ return () => { cancelled = true; };
+ }, []);
+
+ useEffect(() => {
+ if (initialPathHandled.current) return;
+ if (!initialPath && projects === null && !projectsError) return;
+ const recentProject = sortProjectsByRecent(projects || [])[0]?.folder_path;
+ const home = sysFavs.find((favorite) => favorite.key === 'home')?.path;
+ const start = initialPath || recentProject || (sysFavsLoaded ? home || '~' : undefined);
+ if (!start) return;
+ let cancelled = false;
+ Promise.resolve().then(() => {
+ if (!cancelled && !initialPathHandled.current) navigate(start, true);
+ });
+ return () => { cancelled = true; };
+ }, [initialPath, navigate, projects, projectsError, sysFavs, sysFavsLoaded]);
+
+ const refreshSearch = useCallback(() => {
+ searchAbort.current?.abort();
+ setSearchResult(null);
+ setError(null);
+ setSearchRevision((revision) => revision + 1);
+ }, []);
+
+ const refreshCurrent = useCallback(() => {
+ // A resolver will read the latest hidden setting before starting its list.
+ // Never reissue an unresolved external path directly to the Files API.
+ if (pendingNavigation.current?.resolve) return;
+ const request = pendingNavigation.current || (cwd ? { path: cwd, history: 'refresh' as const } : lastNavigation.current);
+ if (request) void runNavigation(request);
+ if (query.trim()) refreshSearch();
+ }, [cwd, query, refreshSearch, runNavigation]);
+
+ const cancelPathEdit = useCallback(() => {
+ pathEditRevision.current += 1;
+ // Editing is independent of navigation, but Escape cancels an admitted
+ // manual submission in either its resolver or listing phase.
+ if (pendingNavigation.current?.editRevision !== undefined) {
+ navSeq.current += 1;
+ pendingNavigation.current = null;
+ lastNavigation.current = null;
+ setLoading(false);
+ const source = loadedDirectory.current;
+ if (source && source.hidden !== showHiddenRef.current) {
+ void runNavigation({ path: source.path, history: 'refresh' });
+ }
+ }
+ setPathEditing(false);
+ setPathError(null);
+ }, [runNavigation]);
+
+ const goToHistory = (index: number) => {
+ changeQuery('');
+ void runNavigation({ path: history.paths[index], history: index });
+ };
+
+ useEffect(() => {
+ const trimmed = query.trim();
+ if (!trimmed || !cwd) {
+ return;
+ }
+ const controller = new AbortController();
+ searchAbort.current = controller;
+ const timeout = window.setTimeout(() => {
+ searchNames(cwd, trimmed, showHidden, controller.signal)
+ .then((result) => {
+ if (controller.signal.aborted) return;
+ setSearchResult({ key: searchKey, rows: result.results.map(searchRow), truncated: result.truncated });
+ })
+ .catch((cause: unknown) => {
+ if (controller.signal.aborted) return;
+ setSearchResult({
+ key: searchKey, rows: [], truncated: false,
+ error: fileBrowserErrorMessage(cause, t, t('apps.fileBrowser.errors.searchFailed')),
+ });
+ });
+ }, 220);
+ return () => {
+ window.clearTimeout(timeout);
+ controller.abort();
+ };
+ }, [cwd, query, searchKey, showHidden, t]);
+
+ const projectFavs = useMemo(
+ () => (projects || []).filter((project) => !!project.folder_path).map((project) => ({ label: project.display_name, path: project.folder_path as string })),
+ [projects],
+ );
+ const crumbs = cwd ? pathCrumbs(cwd) : [];
+ const inSearch = query.trim().length > 0;
+ const rows = useMemo<FileBrowserRow[]>(
+ () =>
+ inSearch
+ ? searchRows || []
+ : sortEntries(listing?.entries || []).map((entry) => ({ entry, full: joinPath(cwd, entry.name), dir: cwd })),
+ [cwd, inSearch, listing, searchRows],
+ );
+ const showSpinner = loading && !listing;
+ const showEmpty =
+ !loading &&
+ !listingError &&
+ !currentSearch?.error &&
+ !creatingFolder &&
+ (inSearch ? !searchBusy && searchRows !== null && searchRows.length === 0 : listing !== null && listing.entries.length === 0);
+
+ const createFolder = async (name: string) => {
+ const trimmed = name.trim();
+ if (!trimmed) {
+ cancelCreateFolder();
+ return;
+ }
+ if (!isPlainEntryName(trimmed)) {
+ setError(t('apps.fileBrowser.errors.invalid_name'));
+ return;
+ }
+ const seq = ++createSeq.current;
+ try {
+ await makeDir(joinPath(cwd, trimmed));
+ if (!mounted.current || seq !== createSeq.current) return;
+ cancelCreateFolder();
+ refreshCurrent();
+ } catch (cause: unknown) {
+ if (mounted.current && seq === createSeq.current) {
+ setError(fileBrowserErrorMessage(cause, t, t('apps.fileBrowser.errors.createFolderFailed')));
+ }
+ }
+ };
+
+ const canCreateFolder = !!cwd && !loading && !listingError && !creatingFolder;
+ const startCreateFolder = () => {
+ if (!canCreateFolder) return;
+ cancelPathEdit();
+ changeQuery('');
+ setNewFolderName('');
+ setCreatingFolder(true);
+ };
+
+ useRouteSurfaceWindowEvent('keydown', (event) => {
+ if (event.defaultPrevented || !(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== 'n') return;
+ event.preventDefault();
+ startCreateFolder();
+ });
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent
+ aria-describedby={undefined}
+ closeLabel={t('common.close')}
+ mobileSheetHeight="tall"
+ className="flex h-[min(84dvh,760px)] max-w-5xl flex-col gap-0 overflow-hidden border-border-strong bg-surface p-0 max-md:p-0 max-md:pb-0"
+ onOpenAutoFocus={(event) => {
+ if (pathEditing) {
+ event.preventDefault();
+ focusPathInput();
+ }
+ }}
+ onEscapeKeyDown={(event) => {
+ if (creatingFolder) {
+ event.preventDefault();
+ cancelCreateFolder();
+ } else if (pathEditing) {
+ event.preventDefault();
+ cancelPathEdit();
+ }
+ }}
+ >
+ <div className="flex shrink-0 items-center gap-3 border-b border-border bg-surface-2 py-4 pl-4 pr-12">
+ <FolderOpen className="size-4 shrink-0 text-mint-ink" />
+ <DialogTitle className="truncate text-[13px] font-semibold text-foreground">{t('directoryBrowser.title')}</DialogTitle>
+ </div>
+
+ <FileBrowser
+ fullBleed
+ className="min-h-0 flex-1"
+ mobileRoute={!isDesktop}
+ cwd={cwd}
+ crumbs={crumbs}
+ sysFavs={sysFavs}
+ projectFavs={projectFavs}
+ loading={loading}
+ searchBusy={searchBusy}
+ query={query}
+ onQueryChange={changeQuery}
+ onRefresh={refreshCurrent}
+ onNavigate={navigate}
+ history={{
+ onBack: history.index > 0 ? () => goToHistory(history.index - 1) : undefined,
+ onForward: history.index < history.paths.length - 1 ? () => goToHistory(history.index + 1) : undefined,
+ }}
+ navigationControl={
+ pathEditing ? (
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-1.5 rounded-lg border border-cyan/40 bg-cyan/[0.06] px-2 py-1">
+ <input
+ ref={pathInputRef}
+ type="text"
+ value={pathInput}
+ aria-label={t('directoryBrowser.editPath')}
+ onChange={(event) => {
+ capturePathSelection(event.currentTarget);
+ pathEditRevision.current += 1;
+ setPathInput(event.target.value);
+ setPathError(null);
+ }}
+ onSelect={(event) => capturePathSelection(event.currentTarget)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void submitPath();
+ }
+ }}
+ placeholder={t('directoryBrowser.editPathPlaceholder')}
+ className="min-w-0 flex-1 bg-transparent font-mono text-[11px] text-foreground outline-none placeholder:text-muted"
+ />
+ <button
+ type="button"
+ onClick={() => void submitPath()}
+ className="shrink-0 rounded px-2 py-0.5 text-[10px] font-semibold text-cyan-ink hover:bg-foreground/[0.04]"
+ >
+ {t('directoryBrowser.editPathDone')}
+ </button>
+ </div>
+ {pathError && <div className="px-1 text-[10.5px] text-destructive-ink">{pathError}</div>}
+ </div>
+ ) : (
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-muted"
+ aria-label={t('directoryBrowser.editPath')}
+ title={t('directoryBrowser.editPath')}
+ onClick={() => {
+ pathEditRevision.current += 1;
+ pathSelection.current = null;
+ setPathInput(cwd);
+ setPathError(null);
+ setPathEditing(true);
+ }}
+ >
+ <Keyboard className="size-3.5" />
+ </Button>
+ )
+ }
+ showHidden={showHidden}
+ onShowHiddenChange={(hidden) => {
+ showHiddenRef.current = hidden;
+ setShowHidden(hidden);
+ refreshCurrent();
+ }}
+ onFavoriteNavigate={(path) => navigate(path, true)}
+ error={listingError || error || currentSearch?.error}
+ toolbarActions={
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7 shrink-0 gap-1.5 px-2.5 text-[12px]"
+ disabled={!canCreateFolder}
+ onClick={startCreateFolder}
+ >
+ <FolderPlus className="size-3.5" />
+ {t('apps.fileBrowser.newFolder')}
+ </Button>
+ }
+ listHeader={
+ <div className="flex items-center border-b border-border px-3 py-1.5 text-[10.5px] font-semibold uppercase tracking-wider text-muted">
+ <span className="min-w-0 flex-1">{t('apps.fileBrowser.colName')}</span>
+ <span className="hidden w-20 shrink-0 text-right sm:block">{t('apps.fileBrowser.colSize')}</span>
+ <span className="hidden w-36 shrink-0 pl-4 sm:block">{t('apps.fileBrowser.colModified')}</span>
+ </div>
+ }
+ listContent={
+ <>
+ {showSpinner && <div className="grid place-items-center py-8"><Loader2 className="size-4 animate-spin text-muted" /></div>}
+ {!inSearch && creatingFolder && (
+ <div className="flex items-center px-3 py-1.5" onContextMenu={(event) => event.stopPropagation()}>
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ <Folder className="size-4 shrink-0 text-cyan-ink" />
+ <InlineNameInput
+ initial=""
+ value={newFolderName}
+ onChange={(value) => {
+ createSeq.current += 1;
+ setNewFolderName(value);
+ setError(null);
+ }}
+ placeholder={t('apps.fileBrowser.newFolderPlaceholder')}
+ onCommit={(value) => void createFolder(value)}
+ onCancel={cancelCreateFolder}
+ className="min-w-0 flex-1 rounded border border-cyan bg-surface px-1.5 py-0.5 text-[12.5px] text-foreground placeholder:text-muted focus:outline-none"
+ />
+ </span>
+ </div>
+ )}
+ {showEmpty && (
+ <div className="px-3 py-8 text-center text-[12px] text-muted">
+ {inSearch ? t('apps.fileBrowser.noMatches') : t('apps.fileBrowser.empty')}
+ </div>
+ )}
+ {rows.map((row) => {
+ const isDir = row.entry.kind === 'dir';
+ const folder = relativeFolder(row.rel);
+ return (
+ <button
+ key={row.full}
+ type="button"
+ disabled={!isDir}
+ onClick={() => isDir && navigate(row.full)}
+ className={clsx(
+ 'flex w-full items-center px-3 py-1.5 text-left text-[12.5px] transition',
+ isDir ? 'text-foreground hover:bg-foreground/[0.04]' : 'cursor-default text-muted/70',
+ )}
+ >
+ {isDir ? <Folder className="size-4 shrink-0 text-cyan-ink" /> : <FileIcon className="size-4 shrink-0 text-muted" />}
+ <span className="ml-2 flex min-w-0 flex-1 items-center gap-2">
+ <span className="truncate">{row.entry.name}</span>
+ {folder && <span className="min-w-0 shrink truncate text-[11px] text-muted">{folder}</span>}
+ </span>
+ <span className="hidden w-20 shrink-0 text-right font-mono text-[11px] text-muted sm:block">
+ {isDir ? '—' : formatSize(row.entry.size)}
+ </span>
+ <span className="hidden w-36 shrink-0 pl-4 font-mono text-[11px] text-muted sm:block">{formatMtime(row.entry.mtime)}</span>
+ </button>
+ );
+ })}
+ </>
+ }
+ footerContent={
+ <div className="flex items-center gap-3 border-t border-border bg-surface-2/80 px-3 py-2">
+ <code className="min-w-0 flex-1 truncate rounded-md border border-border-strong bg-surface-3 px-2.5 py-1.5 font-mono text-[11px] text-foreground">
+ {cwd || '—'}
+ </code>
+ <Button type="button" size="sm" variant="ghost" className="h-8 px-3 text-[12px]" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="brand"
+ className="h-8 gap-1.5 px-3.5 text-[12px]"
+ disabled={!cwd || loading || !!listingError}
+ onClick={() => cwd && onSelect(cwd)}
+ >
+ <FolderOpen className="size-3.5" />
+ {t('directoryBrowser.select')}
+ </Button>
+ </div>
+ }
+ statusContent={
+ <span className="ml-auto flex min-w-0 items-center gap-2 font-mono">
+ <span className="truncate">{cwd || '—'}</span>
+ <span className="shrink-0">
+ {inSearch ? t('apps.fileBrowser.searchCount', { count: rows.length }) : t('apps.fileBrowser.itemCount', { count: rows.length })}
+ </span>
+ {!inSearch && listing?.truncated && <span className="shrink-0">· {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? rows.length })}</span>}
+ {inSearch && searchTruncated && <span className="shrink-0">· {t('apps.fileBrowser.searchTruncated')}</span>}
+ </span>
+ }
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/ui/src/components/ui/inline-name-input.tsx b/ui/src/components/ui/inline-name-input.tsx
index 8af80246e..115cc6813 100644
--- a/ui/src/components/ui/inline-name-input.tsx
+++ b/ui/src/components/ui/inline-name-input.tsx
@@ -6,12 +6,15 @@ import { useRef, useState } from 'react';
// (which also blurs) doesn't double-fire.
export const InlineNameInput: React.FC<{
initial: string;
+ value?: string;
+ onChange?: (value: string) => void;
placeholder?: string;
onCommit: (value: string) => void;
onCancel: () => void;
className?: string;
-}> = ({ initial, placeholder, onCommit, onCancel, className }) => {
- const [value, setValue] = useState(initial);
+}> = ({ initial, value: controlledValue, onChange, placeholder, onCommit, onCancel, className }) => {
+ const [uncontrolledValue, setUncontrolledValue] = useState(initial);
+ const value = controlledValue ?? uncontrolledValue;
const committed = useRef(false);
return (
<input
@@ -19,7 +22,10 @@ export const InlineNameInput: React.FC<{
value={value}
placeholder={placeholder}
onFocus={(e) => e.currentTarget.select()}
- onChange={(e) => setValue(e.target.value)}
+ onChange={(e) => {
+ setUncontrolledValue(e.target.value);
+ onChange?.(e.target.value);
+ }}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index ca5d5eeb8..09adb106d 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -4,29 +4,22 @@ import { useTranslation } from 'react-i18next';
import {
Braces,
ChevronDown,
- ChevronRight,
ChevronUp,
ClipboardPaste,
Copy,
Download,
Eye,
FileCode2,
- FileSearch,
FileText,
File as FileIcon,
Folder,
FolderInput,
FolderPlus,
FilePlus,
- HardDrive,
Hash,
- Home,
Image as ImageIcon,
Loader2,
- Monitor,
Pencil,
- RefreshCw,
- Search,
SquareTerminal,
Trash2,
Undo2,
@@ -78,9 +71,9 @@ import { Checkbox } from '../ui/checkbox';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { ContextMenu, ContextMenuItem } from '../ui/context-menu';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../ui/dialog';
+import { FileBrowser } from '../ui/file-browser';
import { FilePreview } from '../ui/file-preview';
import { InlineNameInput } from '../ui/inline-name-input';
-import { MobileAppHeader } from '../apps/MobileAppHeader';
import { FilePicker } from './FilePicker';
// A code-file extension → its accent + glyph (mirrors design nknn2's colored type icons).
@@ -105,16 +98,6 @@ function entryIcon(e: FsEntry): { Icon: LucideIcon; color: string } {
return EXT_ICON[e.ext?.toLowerCase()] ?? { Icon: FileIcon, color: 'var(--muted)' };
}
-// A favorite's key → a distinct icon (mirrors the Finder rail in design nknn2:
-// Home / Desktop / Downloads / Documents / drive). Unknown keys fall back to a folder.
-const FAV_ICON: Record<string, LucideIcon> = {
- home: Home,
- desktop: Monitor,
- downloads: Download,
- documents: FileText,
- root: HardDrive,
-};
-
// One row in the listing OR the recursive-search results. `full` is the absolute path; `dir` is its
// parent (where rename/delete/move resolve); `rel` (search hits only) is the path relative to the
// search root, so a nested hit can show the folder it lives in; `matchCount` (content-search hits
@@ -1322,87 +1305,35 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
: 0;
return (
- <div className={fullBleed ? 'relative flex h-full w-full flex-col bg-surface pb-[env(safe-area-inset-bottom)]' : 'relative flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]'}>
- {mobileRoute && <MobileAppHeader title={t('apps.fileBrowser.label')} icon={Folder} />}
- {!fullBleed && (
- <div>
- <h1 className="text-[18px] font-semibold text-foreground">{t('apps.fileBrowser.label')}</h1>
- <p className="text-[12px] text-muted">{t('apps.fileBrowser.tagline')}</p>
- </div>
- )}
-
- <div className={clsx('flex min-h-0 flex-1 flex-col overflow-hidden', !fullBleed && 'rounded-xl border border-border')}>
- {/* Toolbar: breadcrumb (left) + search + New File / New Folder (right) */}
- <div className={clsx(
- 'flex items-center gap-2 border-b border-border bg-surface-2/60',
- mobileRoute ? 'flex-wrap px-2 py-2' : 'px-3 py-2',
- )}>
- <div className={clsx(
- 'flex min-w-0 items-center gap-0.5 overflow-x-auto',
- mobileRoute ? 'order-1 w-full' : 'flex-1',
- )}>
- <Button type="button" size="icon" variant="ghost" className="size-7 shrink-0 text-muted" aria-label={t('apps.fileBrowser.refresh')} onClick={() => cwd && refreshAll()}>
- <RefreshCw className={clsx('size-3.5', (loading || searchBusy) && 'animate-spin')} />
- </Button>
- {crumbs.map((c, i) => (
- <span key={c.path} className="flex shrink-0 items-center">
- {i > 0 && <ChevronRight className="size-3 shrink-0 text-muted" />}
- <button
- type="button"
- onClick={() => {
- setQuery('');
- navigate(c.path);
- }}
- {...dropProps(c.path)}
- className={clsx(
- 'max-w-[140px] truncate rounded px-1.5 py-0.5 text-[12.5px] text-muted transition hover:bg-foreground/[0.06] hover:text-foreground',
- dropTarget === c.path && 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan',
- )}
- >
- {c.label}
- </button>
- </span>
- ))}
- </div>
- <label className={clsx(
- 'flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2 py-1',
- mobileRoute ? 'order-2 w-full' : 'shrink-0',
- )}>
- {searchBusy ? <Loader2 className="size-3.5 shrink-0 animate-spin text-muted" /> : <Search className="size-3.5 shrink-0 text-muted" />}
- <input
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={t(searchMode === 'content' ? 'apps.fileBrowser.searchContentPlaceholder' : 'apps.fileBrowser.searchPlaceholder')}
- className={clsx(
- 'min-w-0 flex-1 bg-transparent text-[12px] text-foreground placeholder:text-muted focus:outline-none',
- !mobileRoute && 'w-28 flex-none',
- )}
- />
- {/* Mode toggle: file/folder NAME search (default) ⇄ file CONTENT search; pressed = content. */}
- <button
- type="button"
- aria-pressed={searchMode === 'content'}
- aria-label={t('apps.fileBrowser.searchContents')}
- title={t('apps.fileBrowser.searchContents')}
- onClick={() => setSearchMode((m) => (m === 'content' ? 'name' : 'content'))}
- className={clsx(
- 'grid size-5 shrink-0 place-items-center rounded transition',
- searchMode === 'content' ? 'bg-cyan-soft text-cyan-ink' : 'text-muted hover:bg-foreground/10 hover:text-foreground',
- )}
- >
- <FileSearch className="size-3.5" />
- </button>
- {query && (
- <button type="button" onClick={() => setQuery('')} className="shrink-0 text-muted transition hover:text-foreground" aria-label={t('common.close')}>
- <X className="size-3" strokeWidth={2.5} />
- </button>
- )}
- </label>
- <input ref={uploadInputRef} type="file" multiple className="hidden" onChange={onUploadPick} />
- <div className={clsx(
- 'flex shrink-0 items-center gap-1 overflow-x-auto',
- mobileRoute ? 'order-3 w-full justify-end' : 'ml-auto',
- )}>
+ <>
+ <div className={clsx('relative', fullBleed && 'h-full w-full')}>
+ <FileBrowser
+ fullBleed={fullBleed}
+ mobileRoute={mobileRoute}
+ mobileTitle={t('apps.fileBrowser.label')}
+ title={t('apps.fileBrowser.label')}
+ tagline={t('apps.fileBrowser.tagline')}
+ cwd={cwd}
+ crumbs={crumbs}
+ sysFavs={sysFavs}
+ projectFavs={projectFavs}
+ loading={loading}
+ searchBusy={searchBusy}
+ query={query}
+ onQueryChange={setQuery}
+ searchMode={searchMode}
+ onSearchModeChange={setSearchMode}
+ onRefresh={() => cwd && refreshAll()}
+ onNavigate={navigate}
+ onClearQuery={() => setQuery('')}
+ showHidden={showHidden}
+ onShowHiddenChange={setShowHidden}
+ error={error}
+ dropTarget={dropTarget}
+ getDropProps={dropProps}
+ toolbarActions={
+ <>
+ <input ref={uploadInputRef} type="file" multiple className="hidden" onChange={onUploadPick} />
{selectedItems.length > 1 || touchSelectionMode ? (
<>
<Button type="button" size="sm" variant="ghost" title={t('apps.fileBrowser.copy')} className="h-7 gap-1.5 px-2 text-[12px]" onClick={() => copyRowsToClipboard(selectedItems)} disabled={selectedItems.length === 0}>
@@ -1452,110 +1383,12 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</Button>
</>
)}
- </div>
- </div>
-
- {/* Mobile favorites/projects strip: the rail (below) is hidden under md, so surface the same
- destinations — system favorites then project folders — as a horizontal chip row pinned
- under the toolbar. Tap navigates; the current folder's chip is highlighted. */}
- {(sysFavs.length > 0 || projectFavs.length > 0) && (
- <div className="flex shrink-0 items-center gap-2 overflow-x-auto border-b border-border bg-surface-2/60 px-3 py-2 md:hidden">
- {sysFavs.map((f) => {
- const Icon = FAV_ICON[f.key] ?? Folder;
- const active = cwd === f.path;
- return (
- <button
- key={f.path}
- type="button"
- aria-current={active ? 'true' : undefined}
- onClick={() => {
- setQuery('');
- navigate(f.path);
- }}
- className={clsx(
- 'flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-[12.5px] font-medium transition',
- active ? 'border-cyan/40 bg-cyan-soft text-foreground' : 'border-border-strong text-muted',
- )}
- >
- <Icon className="size-3.5 shrink-0" />
- <span className="max-w-[140px] truncate">{f.path.split('/').filter(Boolean).pop() || f.path}</span>
- </button>
- );
- })}
- {projectFavs.map((f) => {
- const active = cwd === f.path;
- return (
- <button
- key={f.path}
- type="button"
- aria-current={active ? 'true' : undefined}
- onClick={() => {
- setQuery('');
- navigate(f.path);
- }}
- className={clsx(
- 'flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-[12.5px] font-medium transition',
- active ? 'border-cyan/40 bg-cyan-soft text-foreground' : 'border-border-strong text-muted',
- )}
- >
- <Folder className={clsx('size-3.5 shrink-0', active ? 'text-cyan-ink' : 'text-cyan-ink/70')} />
- <span className="max-w-[140px] truncate">{f.label}</span>
- </button>
- );
- })}
- </div>
- )}
+ </>
+ }
- {error && <div className="border-b border-destructive/40 bg-destructive/[0.06] px-3 py-1.5 text-[11.5px] text-destructive-ink">{error}</div>}
-
- <div className="flex min-h-0 flex-1 overflow-hidden">
- {/* Rail: Favorites THEN Projects (design nknn2 order). Folders here are drop targets too. */}
- <aside className="hidden w-[196px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-border bg-surface-2/40 p-2 md:flex">
- {sysFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.favorites')}</RailTitle>}
- {sysFavs.map((f) => {
- const Icon = FAV_ICON[f.key] ?? Folder;
- return (
- <RailRow
- key={f.path}
- icon={<Icon className="size-3.5 text-muted" />}
- label={f.path.split('/').filter(Boolean).pop() || f.path}
- active={cwd === f.path}
- dropActive={dropTarget === f.path}
- dropProps={dropProps(f.path)}
- onClick={() => {
- setQuery('');
- navigate(f.path);
- }}
- />
- );
- })}
- {projectFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.projects')}</RailTitle>}
- {projectFavs.map((f) => (
- <RailRow
- key={f.path}
- icon={<Folder className="size-3.5 text-cyan-ink" />}
- label={f.label}
- active={cwd === f.path}
- dropActive={dropTarget === f.path}
- dropProps={dropProps(f.path)}
- onClick={() => {
- setQuery('');
- navigate(f.path);
- }}
- />
- ))}
- </aside>
-
- {/* Listing: Name / Size / Modified. An OS file drag drops here to upload into the current
- folder; the internal row-move drag (dragRef) is filtered out by isExternalFileDrag. */}
- <div
- className="relative flex min-w-0 flex-1 flex-col"
- onDragOver={onListingDragOver}
- onDragLeave={onListingDragLeave}
- onDrop={onListingDrop}
- >
- <div className="flex items-center border-b border-border px-3 py-1.5 text-[10.5px] font-semibold uppercase tracking-wider text-muted">
- {touchSelectionMode && <span className="mr-2 size-[18px] shrink-0" aria-hidden />}
+ listHeader={
+ <div className="flex items-center border-b border-border px-3 py-1.5 text-[10.5px] font-semibold uppercase tracking-wider text-muted">
+ {touchSelectionMode && <span className="mr-2 size-[18px] shrink-0" aria-hidden />}
<button type="button" onClick={() => cycleSort('name')} className={clsx('flex min-w-0 flex-1 items-center gap-1 text-left transition hover:text-foreground', sort?.col === 'name' && 'text-foreground')}>
<span className="truncate">{t('apps.fileBrowser.colName')}</span>
{sort?.col === 'name' && (sort.dir === 'asc' ? <ChevronUp className="size-3 shrink-0" /> : <ChevronDown className="size-3 shrink-0" />)}
@@ -1568,9 +1401,16 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
{t('apps.fileBrowser.colModified')}
{sort?.col === 'modified' && (sort.dir === 'asc' ? <ChevronUp className="size-3 shrink-0" /> : <ChevronDown className="size-3 shrink-0" />)}
</button>
- </div>
- {/* Right-clicking blank space offers New File / New Folder in the current folder. */}
- <div className="min-h-0 flex-1 overflow-y-auto py-1" onContextMenu={(e) => openMenu(e, null)}>
+ </div>
+ }
+ paneProps={{
+ onDragOver: onListingDragOver,
+ onDragLeave: onListingDragLeave,
+ onDrop: onListingDrop,
+ }}
+ listProps={{ onContextMenu: (event) => openMenu(event, null) }}
+ listContent={
+ <>
{showInitialSpinner && (
<div className="grid place-items-center py-8"><Loader2 className="size-4 animate-spin text-muted" /></div>
)}
@@ -1709,20 +1549,17 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</button>
);
})}
- </div>
- {fileDragOver && (
- <div className="pointer-events-none absolute inset-1.5 z-20 flex items-center justify-center rounded-lg border-2 border-dashed border-cyan bg-cyan-soft/70">
- <span className="rounded-md bg-surface px-3 py-1.5 text-[12.5px] font-medium text-foreground shadow-sm">
- {t('apps.fileBrowser.dropHint')}
- </span>
- </div>
- )}
+ </>
+ }
+ dropOverlay={fileDragOver && (
+ <div className="pointer-events-none absolute inset-1.5 z-20 flex items-center justify-center rounded-lg border-2 border-dashed border-cyan bg-cyan-soft/70">
+ <span className="rounded-md bg-surface px-3 py-1.5 text-[12.5px] font-medium text-foreground shadow-sm">
+ {t('apps.fileBrowser.dropHint')}
+ </span>
</div>
- </div>
+ )}
- {/* Undo bar: one recent revertible action (delete via backend token / move via reverse
- move). Auto-dismisses; doesn't steal focus from the listing. */}
- {undoEntry && (
+ footerContent={undoEntry && (
<div className="flex items-center gap-2 border-t border-border bg-surface-2/80 px-3 py-1.5 text-[12px]">
<span className="min-w-0 flex-1 truncate text-muted">
{undoEntry.count > 1
@@ -1750,39 +1587,35 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</button>
</div>
)}
-
- {/* Status bar: item count + selection, with the hidden-files toggle. */}
- <div className="flex items-center gap-3 border-t border-border bg-surface-2/60 px-3 py-1.5 text-[11px] text-muted">
- <label className="flex items-center gap-1.5">
- <input type="checkbox" checked={showHidden} onChange={(e) => setShowHidden(e.target.checked)} className="size-3" />
- {t('apps.fileBrowser.showHidden')}
- </label>
- {uploadProgress && (
- <span className="flex items-center gap-1.5 text-cyan-ink">
- <Loader2 className="size-3 animate-spin" />
- {t('apps.fileBrowser.uploading', { done: uploadProgress.done, total: uploadProgress.total })}
- </span>
- )}
- <span className="ml-auto flex min-w-0 items-center gap-2 font-mono">
- {selectedItems.length > 1 && (
- <span className="truncate text-foreground/80">
- {t('apps.fileBrowser.selectedStatus', { count: selectedItems.length, size: formatSize(selectedSize) })}
+ statusContent={
+ <>
+ {uploadProgress && (
+ <span className="flex items-center gap-1.5 text-cyan-ink">
+ <Loader2 className="size-3 animate-spin" />
+ {t('apps.fileBrowser.uploading', { done: uploadProgress.done, total: uploadProgress.total })}
</span>
)}
- {selectedEntry && (
- <span className="truncate text-foreground/80">
- {selectedEntry.name}
- {selectedEntry.kind !== 'dir' && selectedEntry.size != null ? ` · ${formatSize(selectedEntry.size)}` : ''}
+ <span className="ml-auto flex min-w-0 items-center gap-2 font-mono">
+ {selectedItems.length > 1 && (
+ <span className="truncate text-foreground/80">
+ {t('apps.fileBrowser.selectedStatus', { count: selectedItems.length, size: formatSize(selectedSize) })}
+ </span>
+ )}
+ {selectedEntry && (
+ <span className="truncate text-foreground/80">
+ {selectedEntry.name}
+ {selectedEntry.kind !== 'dir' && selectedEntry.size != null ? ` · ${formatSize(selectedEntry.size)}` : ''}
+ </span>
+ )}
+ <span className="shrink-0">
+ {inSearch ? t('apps.fileBrowser.searchCount', { count: rows.length }) : t('apps.fileBrowser.itemCount', { count: rows.length })}
</span>
- )}
- <span className="shrink-0">
- {inSearch ? t('apps.fileBrowser.searchCount', { count: rows.length }) : t('apps.fileBrowser.itemCount', { count: rows.length })}
+ {!inSearch && listing?.truncated && <span className="shrink-0">· {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? rows.length })}</span>}
+ {inSearch && searchTruncated && <span className="shrink-0">· {t('apps.fileBrowser.searchTruncated')}</span>}
</span>
- {!inSearch && listing?.truncated && <span className="shrink-0">· {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? rows.length })}</span>}
- {inSearch && searchTruncated && <span className="shrink-0">· {t('apps.fileBrowser.searchTruncated')}</span>}
- </span>
- </div>
- </div>
+ </>
+ }
+ />
{/* MOBILE-ONLY quick-look overlay: on mobile there's no window layer, so a previewable file
opens here in-page instead of the standalone Preview window (desktop uses the window). */}
@@ -1830,18 +1663,18 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</div>
</div>
)}
-
- {movePickerItems && (
- <FilePicker
- mode="open-directory"
- initialPath={cwd}
- onCancel={() => setMovePickerItems(null)}
- onConfirm={async ({ path }) => {
- await moveItemsInto(movePickerItems, path);
- setMovePickerItems(null);
- }}
- />
- )}
+ {movePickerItems && (
+ <FilePicker
+ mode="open-directory"
+ initialPath={cwd}
+ onCancel={() => setMovePickerItems(null)}
+ onConfirm={async ({ path }) => {
+ await moveItemsInto(movePickerItems, path);
+ setMovePickerItems(null);
+ }}
+ />
+ )}
+ </div>
{/* Destructive delete confirmation (product dialog; replaces window.confirm). The wording
stays neutral about undoability — whether the backend could stage the entry is only known
@@ -2042,40 +1875,6 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
)}
</ContextMenu>
)}
- </div>
+ </>
);
};
-
-const RailTitle: React.FC<{ children: React.ReactNode }> = ({ children }) => (
- <div className="px-1 pb-0.5 pt-1.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">{children}</div>
-);
-
-const RailRow: React.FC<{
- icon: React.ReactNode;
- label: string;
- active: boolean;
- onClick: () => void;
- dropActive?: boolean;
- dropProps?: {
- onDragOver: (e: React.DragEvent) => void;
- onDragLeave: () => void;
- onDrop: (e: React.DragEvent) => void;
- };
-}> = ({ icon, label, active, onClick, dropActive, dropProps }) => (
- <button
- type="button"
- onClick={onClick}
- {...dropProps}
- className={clsx(
- 'flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',
- dropActive
- ? 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan'
- : active
- ? 'bg-cyan-soft text-foreground'
- : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
- )}
- >
- <span className="shrink-0">{icon}</span>
- <span className="truncate">{label}</span>
- </button>
-);
diff --git a/ui/src/components/workbench/NewProjectDialog.test.tsx b/ui/src/components/workbench/NewProjectDialog.test.tsx
index 7c1cc166b..8e410df50 100644
--- a/ui/src/components/workbench/NewProjectDialog.test.tsx
+++ b/ui/src/components/workbench/NewProjectDialog.test.tsx
@@ -4,7 +4,7 @@ import { afterEach, expect, it, vi } from 'vitest';
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
const mocks = vi.hoisted(() => ({ createProject: vi.fn() }));
vi.mock('../../context/WorkbenchProjectsContext', () => ({ useWorkbenchProjectsActions: () => mocks }));
-vi.mock('../ui/directory-browser', () => ({ DirectoryBrowser: ({ initialPath, onSelect }: { initialPath?: string; onSelect: (path: string) => void }) => (
+vi.mock('../ui/folder-browser', () => ({ FolderBrowser: ({ initialPath, onSelect }: { initialPath?: string; onSelect: (path: string) => void }) => (
<button data-testid="directory" data-path={initialPath} onClick={() => onSelect('/工作区/选择的项目')}>select-folder</button>
) }));
import { NewProjectDialog } from './NewProjectDialog';
diff --git a/ui/src/components/workbench/NewProjectDialog.tsx b/ui/src/components/workbench/NewProjectDialog.tsx
index aa280847a..b43237f09 100644
--- a/ui/src/components/workbench/NewProjectDialog.tsx
+++ b/ui/src/components/workbench/NewProjectDialog.tsx
@@ -4,7 +4,7 @@ import { Folder, FolderOpen, Loader2, X } from 'lucide-react';
import type { WorkbenchProject } from '../../context/ApiContext';
import { useWorkbenchProjectsActions } from '../../context/WorkbenchProjectsContext';
-import { DirectoryBrowser } from '../ui/directory-browser';
+import { FolderBrowser } from '../ui/folder-browser';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { errorMessage } from '@/lib/errorMessage';
@@ -21,7 +21,7 @@ interface NewProjectDialogProps {
onCreated: (project: WorkbenchProject) => void;
}
-// Two-phase modal: first the macOS-style DirectoryBrowser picks a folder,
+// Two-phase modal: first the shared Files-style FolderBrowser picks a folder,
// 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.
@@ -59,7 +59,7 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onC
if (phase === 'pick') {
return (
- <DirectoryBrowser
+ <FolderBrowser
initialPath={folderPath || initialPath}
onClose={close}
onSelect={(path) => {
diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.ts
index 12f2a30b0..209364e33 100644
--- a/ui/src/lib/filesApi.ts
+++ b/ui/src/lib/filesApi.ts
@@ -410,3 +410,27 @@ export async function systemFavorites(): Promise<Favorite[]> {
const data = await parse<{ ok: true; favorites: Favorite[] }>(await apiFetch('/api/browse/favorites'));
return data.favorites || [];
}
+
+// Persisted runtime and scope cwd settings historically accepted relative paths. Resolve those
+// legacy values through the compatibility browse endpoint before handing them to the stricter
+// Files API, whose paths are intentionally absolute.
+export async function resolveDirectoryPath(path: string): Promise<string> {
+ const res = await apiFetch('/api/browse', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path }),
+ });
+ const raw = await res.text();
+ let data: { ok?: boolean; path?: string; error?: string } | undefined;
+ if (raw) {
+ try {
+ data = JSON.parse(raw) as typeof data;
+ } catch {
+ data = undefined;
+ }
+ }
+ if (!res.ok || !data?.ok || !data.path) {
+ throw new FilesApiError('invalid_path', data?.error || 'The configured directory could not be resolved.');
+ }
+ return data.path;
+}