From 6297d19b04af0a13efe8a8764747087507031b4f Mon Sep 17 00:00:00 2001 From: default-cybe <201046277+default-cybe@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:32:07 -0800 Subject: [PATCH 1/3] Pick a folder like in Codex: search, Recent, Open folder browser, Add as project One FolderMenu (web features/home/FolderPicker.tsx) on the folder chip, Device and folder and the phone place sheet: Search folders (typed paths list matching folders on the device), No folder, Recent (project or folder name over a muted path, deduped, newest first, at most 8), Open folder... and an "On " row. Open folder... is an in-app browser over GET /api/devices/:device/files with breadcrumbs, Up, folders only, Show hidden, Home/Desktop/Documents/roots, New folder (the existing POST /api/devices/:device/folder) and Select. A folder that is no project yet can be added as one (new POST /api/projects, the projects service's add: marker for a plain folder, pinned location). The device folder routes now refuse NUL/line breaks like the projects routes. Tests: menu, keyboard, browser, Recent/search rules, member refusal, mkdir private-path checks in TS and Rust. Committed-by: Conclave (cliproxy/claude-opus-5-5) --- CHANGELOG.md | 6 + packages/core/src/client/index.ts | 2 + packages/core/src/projects/service.ts | 27 + packages/core/test/machine/private.test.ts | 4 + packages/core/test/projects/move.test.ts | 23 +- packages/daemon-rs/src/private.rs | 14 + packages/server/src/route-policy.ts | 2 + packages/server/src/routes-projects.ts | 15 +- packages/server/src/routes.ts | 10 +- packages/server/test/folder-check.test.ts | 27 +- packages/server/test/projects-routes.test.ts | 11 + packages/web/src/features/chat/pickers.tsx | 67 +-- .../web/src/features/home/FolderPicker.tsx | 541 ++++++++++++++++++ .../web/src/features/home/SessionStart.tsx | 54 +- packages/web/src/features/home/Where.tsx | 83 +-- packages/web/test/folder-check.test.tsx | 217 +++++-- 16 files changed, 927 insertions(+), 176 deletions(-) create mode 100644 packages/web/src/features/home/FolderPicker.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index a99b38ddf..c6fc4b3c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ from the section of its version (`scripts/releases/notes.ts`); a release without one fails. At tag time, rename `[Unreleased]` to the version and date, like `## [0.4.16] - 2026-10-24`. +## [Unreleased] + +### Changed + +- Pick a folder like in Codex: search, recent folders, and Open folder… with a folder browser; add a folder as a project in one step + ## [0.4.102] - 2026-11-17 ### Added diff --git a/packages/core/src/client/index.ts b/packages/core/src/client/index.ts index d2593c103..e3a4d6c6f 100644 --- a/packages/core/src/client/index.ts +++ b/packages/core/src/client/index.ts @@ -1962,6 +1962,8 @@ export class ConclaveClient { identifyFolder = (input: { device: string; path: string; sessionId?: string; projectId?: string }) => this.request('POST', '/api/projects/identify', input); projects = () => this.request('GET', '/api/projects'); project = (id: string) => this.request('GET', `/api/projects/${id}`); + /** Add as project: the folder becomes a project named `name` (a plain folder gets a .conclave/project.json marker). */ + addProject = (device: string, path: string, name: string) => this.request('POST', '/api/projects', { device, path, name }); /** Verify a folder is the project and pin it as its location on the device. */ pinLocation = (projectId: string, device: string, path: string) => this.request('PUT', `/api/projects/${projectId}/locations`, { device, path }); unpinLocation = (projectId: string, device: string, path: string) => this.request('DELETE', `/api/projects/${projectId}/locations`, undefined, { device, path }); diff --git a/packages/core/src/projects/service.ts b/packages/core/src/projects/service.ts index c54c6e2af..31562e1f2 100644 --- a/packages/core/src/projects/service.ts +++ b/packages/core/src/projects/service.ts @@ -405,6 +405,33 @@ export class ProjectsService { return this.dto(this.store.get(p.id)!); } + /** + * Add as project (the folder picker): make a folder the account's project + * under the name the owner gave. A git repository or synced folder is + * known by its history; a plain folder gets a marker + * (.conclave/project.json) so it can be told apart later. A folder that is + * already a project of the account answers that project. + */ + async add(device: string, path: string, name: string, accountId: string = OWNER_ID): Promise { + const m = this.machine(device); + if (!m) throw new EngineError(409, `${this.deviceName(device)} is offline`); + const abs = trimSlash(m.resolve(path, (await this.engine.machineHome(m)) ?? '/')); + let probe = await this.probe(device, abs); + if (!probe.exists) throw new EngineError(400, `${abs} does not exist on ${this.deviceName(device)}`); + const root = repoRoot(abs, probe); + const found = this.findProject(probe, device, root, accountId); + if (found) return this.dto(found); + if (!this.identifiable(probe)) { + await m.writeFile(`${root}/.conclave/project.json`, `${JSON.stringify({ id: crypto.randomUUID() }, null, 2)}\n`); + probe = await this.probe(device, abs); + } + const p = this.store.create(name.trim() || probe.name, identityOf(probe), accountId); + this.store.saveLocation(p.id, { device, path: root, via: 'pinned', pinned: true, head: probe.head }); + this.engine.audit(undefined, 'project.add', `${p.name}: ${device} ${root}`); + this.emitProject(p); + return this.dto(p); + } + unpin(projectId: string, device: string, path: string): ProjectDto { const p = this.store.get(projectId); if (!p) throw new EngineError(404, `unknown project ${projectId}`); diff --git a/packages/core/test/machine/private.test.ts b/packages/core/test/machine/private.test.ts index e6647c409..9d2ea96d4 100644 --- a/packages/core/test/machine/private.test.ts +++ b/packages/core/test/machine/private.test.ts @@ -42,6 +42,10 @@ describe('the CLIProxyAPI folder is out of reach of tools', () => { await expect(m.readFile(join(work, 'link', 'auth', 'claude-me.json'))).rejects.toThrow(/Refused/); await expect(m.readdir(join(home, 'cliproxy', 'auth'))).rejects.toThrow(/Refused/); await expect(m.writeFile(join(home, 'cliproxy', 'auth', 'x.json'), '{}')).rejects.toThrow(/Refused/); + // New folder in the folder browser goes through mkdir (POST /api/devices/:device/folder) + await expect(m.mkdir(join(home, 'cliproxy', 'auth', 'new'))).rejects.toThrow(/Refused/); + await expect(m.mkdir(join(work, 'link', 'new'))).rejects.toThrow(/Refused/); + await m.mkdir(join(work, 'project', 'new')); await expect(m.remove(home, { recursive: true })).rejects.toThrow(/Refused/); await expect(m.rename(join(home, 'cliproxy', 'config.yaml'), join(work, 'stolen.yaml'))).rejects.toThrow(/Refused/); expect(await m.readText(join(home, 'notes.txt'))).toContain('word'); diff --git a/packages/core/test/projects/move.test.ts b/packages/core/test/projects/move.test.ts index 02665a908..88deac65e 100644 --- a/packages/core/test/projects/move.test.ts +++ b/packages/core/test/projects/move.test.ts @@ -4,7 +4,7 @@ * from test/engine/harness.ts: no paid calls. */ import { afterEach, describe, expect, test } from 'bun:test'; -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { startTestEngine, toolResults, until, type Step, type TestEngine } from '../engine/harness'; import { projectsOf } from '../../src/projects/registry'; @@ -250,6 +250,27 @@ describe('the banner', () => { }); }); +describe('Add as project (the folder picker)', () => { + test('a plain folder gets a marker and a pinned location; a repository does not; adding again answers the same project', async () => { + const { d, svc } = await setup(); + const plain = join(d.pc.home, 'notes'); + mkdirSync(plain, { recursive: true }); + const p = await svc.add('pc', plain, ' My notes '); + expect(p.name).toBe('My notes'); + expect(JSON.parse(readFileSync(join(plain, '.conclave', 'project.json'), 'utf8')).id).toBeTruthy(); + expect(p.locations).toMatchObject([{ device: 'pc', path: plain, pinned: true }]); + expect((await svc.add('pc', plain, 'Other name')).id).toBe(p.id); + expect(svc.list().map((x) => x.id)).toContain(p.id); + + const repo = join(d.pc.home, 'code', 'site'); + makeRepo(repo); + const r = await svc.add('pc', repo, ''); + expect(r.name).toBe('site'); + expect(existsSync(join(repo, '.conclave'))).toBe(false); + await expect(svc.add('pc', join(d.pc.home, 'nope'), 'x')).rejects.toThrow(/does not exist/); + }); +}); + describe('the resumed context', () => { test('an offline device parks the turn; it continues when the device is back', async () => { const { t, d, svc } = await setup(); diff --git a/packages/daemon-rs/src/private.rs b/packages/daemon-rs/src/private.rs index f5d6f6863..90ed80fea 100644 --- a/packages/daemon-rs/src/private.rs +++ b/packages/daemon-rs/src/private.rs @@ -163,6 +163,20 @@ pub mod tests { done(&home); } + /// New folder in the folder browser: the "mkdir" RPC checks the path, then makes it (server.rs). + #[test] + fn mkdir_keeps_out_of_it() { + let (home, work) = fixture("mkdir"); + let mk = |p: String| check(&p).and_then(|_| crate::fsops::mkdir_p(&p)); + assert_eq!(mk(format!("{home}/cliproxy/auth/new")).unwrap_err().code.as_deref(), Some("EACCES")); + #[cfg(unix)] + assert!(mk(format!("{work}/link/new")).is_err()); + assert!(mk(format!("{work}/project/new")).is_ok()); + assert!(std::path::Path::new(&format!("{work}/project/new")).is_dir()); + assert!(crate::fsops::mkdir_p("").is_err()); + done(&home); + } + #[test] fn a_shell_command_that_names_it() { let (home, _) = fixture("commands"); diff --git a/packages/server/src/route-policy.ts b/packages/server/src/route-policy.ts index 46d5ce319..37ebc504f 100644 --- a/packages/server/src/route-policy.ts +++ b/packages/server/src/route-policy.ts @@ -177,6 +177,8 @@ export const ROUTE_POLICY: Record = { // ----- folders across devices ----- 'POST /api/projects/identify': 'self', 'GET /api/projects': 'self', + // the route checks the device is the caller's own (scope.ts ownDevice) + 'POST /api/projects': 'self', 'GET /api/projects/:id': own({ id: 'project' }), 'PUT /api/projects/:id/locations': own({ id: 'project' }), 'DELETE /api/projects/:id/locations': own({ id: 'project' }), diff --git a/packages/server/src/routes-projects.ts b/packages/server/src/routes-projects.ts index 2fb9b28d6..32b002c84 100644 --- a/packages/server/src/routes-projects.ts +++ b/packages/server/src/routes-projects.ts @@ -20,7 +20,7 @@ import { accountOf, ownDevice } from './scope'; const MAX_PATH = 4096; /** A folder path from a body or query: a string of sane length with no NUL or line break (it goes into a shell on the device). */ -function pathString(v: unknown, name: string): string { +export function pathString(v: unknown, name: string): string { const s = requireString(v, name); if (s.length > MAX_PATH) throw badRequest(`${name} is longer than ${MAX_PATH} characters`); if (/[\u0000\r\n]/.test(s)) throw badRequest(`${name} has a NUL or line break in it`); @@ -134,6 +134,19 @@ export function registerProjectRoutes(app: Hono, ctx: ServerContext, au app.get('/api/projects', (c) => c.json(svc().list(accountOf(c)))); + // Add as project (the folder picker): a folder on a device of the caller's own becomes their project + app.post('/api/projects', async (c) => { + const body = await readJson>(c); + const device = requireString(body.device, 'device'); + known(c, device); + const path = pathString(body.path, 'path'); + const name = optString(body.name, 'name') ?? ''; + if (name.length > 200 || /[\u0000-\u001f]/.test(name)) throw badRequest('name must be one line of at most 200 characters'); + const project = await svc().add(device, path, name, accountOf(c)); + audit(c, 'project.add', `${project.name} ${device} ${path}`, { device }); + return c.json(project); + }); + app.get('/api/projects/:id', (c) => { const p = svc().get(c.req.param('id')); if (!p) throw notFound(`unknown project ${c.req.param('id')}`); diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 48cd97b0c..9eddd0bc3 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -58,7 +58,7 @@ import { registerWatchRoutes } from './routes-watches'; import { registerBrowserRoutes } from './routes-browser'; import { registerPreviewRoutes } from './routes-preview'; import { registerFlowRoutes } from './routes-flows'; -import { patchSession, registerProjectRoutes } from './routes-projects'; +import { pathString, patchSession, registerProjectRoutes } from './routes-projects'; import { registerGithubRoutes } from './routes-github'; import { registerImportRoutes } from './routes-import'; import { registerWorkflowRoutes } from './routes-workflows'; @@ -1167,20 +1167,22 @@ export function registerRoutes(app: Hono, ctx: ServerContext): void { app.get('/api/devices/:device/files', async (c) => { const device = c.req.param('device'); deviceMachine(device); - return c.json(await engine.browse(device, c.req.query('path') ?? '')); + const path = c.req.query('path'); + return c.json(await engine.browse(device, path ? pathString(path, 'path') : '')); }); // the folder pickers ask before Choose or Start (core machine/folder-check.ts); 409 when the device is offline app.get('/api/devices/:device/folder', async (c) => { const device = c.req.param('device'); deviceMachine(device); - return c.json(await engine.folderCheck(device, requireString(c.req.query('path'), 'path'))); + return c.json(await engine.folderCheck(device, pathString(c.req.query('path'), 'path'))); }); app.post('/api/devices/:device/folder', async (c) => { const device = c.req.param('device'); deviceMachine(device); - const path = requireString((await readJson<{ path?: unknown }>(c)).path, 'path'); + // New folder and Create folder: one path, no NUL or line break; the device's own mkdir keeps out of the hub's private folders + const path = pathString((await readJson<{ path?: unknown }>(c)).path, 'path'); const made = await engine.makeFolder(device, path); audit(c, 'device.folder.create', made.path, { device }); return c.json(made); diff --git a/packages/server/test/folder-check.test.ts b/packages/server/test/folder-check.test.ts index c07421da6..d689e8a08 100644 --- a/packages/server/test/folder-check.test.ts +++ b/packages/server/test/folder-check.test.ts @@ -18,10 +18,10 @@ let t: TestEngine; let running: RunningServer; const root = mkdtempSync(join(tmpdir(), 'folder-check-')); -async function call(method: string, path: string, json?: unknown): Promise<{ status: number; body: any }> { +async function call(method: string, path: string, json?: unknown, token = OWNER): Promise<{ status: number; body: any }> { const res = await fetch(`${running.url}${path}`, { method, - headers: { authorization: `Bearer ${OWNER}`, ...(json !== undefined ? { 'content-type': 'application/json' } : {}) }, + headers: { authorization: `Bearer ${token}`, ...(json !== undefined ? { 'content-type': 'application/json' } : {}) }, ...(json !== undefined ? { body: JSON.stringify(json) } : {}), }); const text = await res.text(); @@ -66,6 +66,29 @@ describe('folder check', () => { expect((await call('GET', `/api/devices/local/folder?path=${encodeURIComponent(want)}`)).body.exists).toBe(true); }); + test('a path with a NUL or line break is refused before it reaches the device', async () => { + for (const bad of [`${root}/a\nb`, `${root}/a\u0000b`]) { + expect((await call('POST', '/api/devices/local/folder', { path: bad })).status).toBe(400); + expect((await call('GET', `/api/devices/local/folder?path=${encodeURIComponent(bad)}`)).status).toBe(400); + expect((await call('GET', `/api/devices/local/files?path=${encodeURIComponent(bad)}`)).status).toBe(400); + } + expect(existsSync(join(root, 'a'))).toBe(false); + }); + + test("a member cannot browse, make a folder or add a project on another account's device", async () => { + const made = await call('POST', '/api/people', { name: 'bob', password: 'correct horse battery staple', providers: { mock: { monthlyUsd: 5 } } }); + expect(made.status).toBe(200); + const login = (await fetch(`${running.url}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ account: 'bob', password: 'correct horse battery staple', name: 'bob web', platform: 'web' }) }).then((r) => r.json())) as { token: string }; + const want = join(root, 'bob-made'); + expect((await call('GET', `/api/devices/local/files?path=${encodeURIComponent(root)}`, undefined, login.token)).status).toBe(404); + expect((await call('GET', `/api/devices/local/folder?path=${encodeURIComponent(root)}`, undefined, login.token)).status).toBe(404); + expect((await call('POST', '/api/devices/local/folder', { path: want }, login.token)).status).toBe(404); + expect((await call('POST', '/api/projects', { device: 'local', path: root, name: 'x' }, login.token)).status).toBe(404); + expect(existsSync(want)).toBe(false); + // the owner still lists it, folders and files + expect((await call('GET', `/api/devices/local/files?path=${encodeURIComponent(root)}`)).status).toBe(200); + }); + test('an unknown device answers 404, not a guess', async () => { expect((await call('GET', '/api/devices/nope/folder?path=/tmp')).status).toBe(404); }); diff --git a/packages/server/test/projects-routes.test.ts b/packages/server/test/projects-routes.test.ts index ff19f4fda..b72f8f34c 100644 --- a/packages/server/test/projects-routes.test.ts +++ b/packages/server/test/projects-routes.test.ts @@ -52,6 +52,7 @@ function stub(): void { unpin: (id: string, device: string, path: string) => (calls.push({ method: 'unpin', args: [id, device, path] }), { id, name: 'portfolio', locations: [] }), deviceFolders: async (device: string) => ({ device, locations: [] }), deletePrefix: (id: string) => id === 'pfx_1', + add: async (device: string, path: string, name: string, acct: string) => (calls.push({ method: 'add', args: [device, path, name, acct] }), { id: 'prj_new', name, locations: [] }), }; setProjects(hub.engine, svc as unknown as ProjectsService); } @@ -121,4 +122,14 @@ describe('with the service', () => { expect((await hub.api('/api/devices/mac/folders')).status).toBe(200); expect((await hub.api('/api/projects', { token: null })).status).toBe(401); }); + + test('Add as project checks the device, path and name, then passes them on with the account', async () => { + expect((await hub.api('/api/projects', { method: 'POST', json: { device: 'nope', path: '~/x', name: 'x' } })).status).toBe(404); + expect((await hub.api('/api/projects', { method: 'POST', json: { device: 'mac', path: '~/x\n/y', name: 'x' } })).status).toBe(400); + expect((await hub.api('/api/projects', { method: 'POST', json: { device: 'mac', path: '~/x', name: 'a\nb' } })).status).toBe(400); + const r = await hub.api('/api/projects', { method: 'POST', json: { device: 'mac', path: '~/code/site', name: 'Site' } }); + expect(r.status).toBe(200); + expect(((await r.json()) as { name: string }).name).toBe('Site'); + expect(calls.find((c) => c.method === 'add')?.args).toEqual(['mac', '~/code/site', 'Site', 'owner']); + }); }); diff --git a/packages/web/src/features/chat/pickers.tsx b/packages/web/src/features/chat/pickers.tsx index a7fd104ab..5d3383ba1 100644 --- a/packages/web/src/features/chat/pickers.tsx +++ b/packages/web/src/features/chat/pickers.tsx @@ -16,8 +16,8 @@ import { PickerButton, SelectMenu } from '@/components/ui/Select'; import { ModelList, ModelPicker } from '@/components/pickers/ModelPicker'; import { placeName } from '@/features/home/start'; import { computerList } from '@/features/home/Where'; +import { FolderMenu, useOpenFolder } from '@/features/home/FolderPicker'; import { MODES, MORE_STYLES, PERMISSION_MODES, STYLE_HEADING } from './modes'; -import { FolderCheckNote, useFolderCheck } from './folderCheck'; export { AgentPicker } from '@/components/pickers/Pickers'; @@ -53,11 +53,10 @@ export function DeviceFolderPicker({ const [open, setOpen] = useState(false); const devices = useHub((s) => s.devices); const d = device ? devices[device] : undefined; - const [path, setPath] = useState(cwd ?? ''); // the hub first, by its name ("madx (hub)"), then the computers const list = computerList(devices); - // the folder is asked of the device before Set (folderCheck.tsx) - const check = useFolderCheck(device, open && onCwd ? path : ''); + // the same menu as the folder chip (FolderPicker.tsx); Open folder… opens the browser + const browse = useOpenFolder(device ?? 'local', cwd, (p) => onCwd?.(p)); return ( <> { - setPath(cwd ?? ''); - setOpen((o) => !o); - }} + onClick={() => setOpen((o) => !o)} > {device ? placeName(d, device) : 'hub'} {showCwd && cwd && cwd !== '~' && {cwd.length > 22 ? `…${cwd.slice(-20)}` : cwd}} setOpen(false)} width={340} label="Device and folder" sheetTitle="Device and folder"> -
+ {onCwd && ( + { + onCwd(p); + setOpen(false); + }} + onDevice={(id) => { + onDevice(id); + if (closeOnDevice) setOpen(false); + }} + onClose={() => setOpen(false)} + onOpenFolder={() => { + setOpen(false); + browse.open(); + }} + /> + )} + {!onCwd &&
Device
{list.map((dev) => ( ))} -
- {onCwd && ( -
{ - e.preventDefault(); - if (!check.ready) return; - onCwd(path.trim() || '~'); - setOpen(false); - }} - > - -
- setPath(e.target.value)} placeholder="~/code/project" className="flex-1" /> - -
- - {d?.roots?.length ? ( -
- {d.roots.map((r) => ( - - ))} -
- ) : null} - - )} +
}
+ {onCwd && browse.browser} ); } diff --git a/packages/web/src/features/home/FolderPicker.tsx b/packages/web/src/features/home/FolderPicker.tsx new file mode 100644 index 000000000..c700d3e05 --- /dev/null +++ b/packages/web/src/features/home/FolderPicker.tsx @@ -0,0 +1,541 @@ +/** + * Pick a folder like in Codex: one menu for the composer's folder chip and + * Home's Where picker (Where.tsx) and the phone's place sheet. Top to + * bottom: Search folders…, No folder, Recent (the project's or folder's name + * over its muted path), Open folder…, then "On " to switch the + * device. A typed path lists matching folders on the device and is checked + * as before (folderCheck.tsx). Open folder… opens FolderBrowser over + * GET /api/devices/:device/files: breadcrumbs, Up, folders only, Show hidden, + * Home, Desktop and Documents, New folder (POST /api/devices/:device/folder) + * and Select this folder. A folder that is no project yet can be added as + * one in place (POST /api/projects). + */ +import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'; +import { Check, ChevronLeft, ChevronRight, FolderOpen, Search } from 'lucide-react'; +import type { FileEntryDto, ProjectDto } from '@conclave/core/client'; +import type { Session } from '@conclave/core/types'; +import { api } from '@/lib/api'; +import { attempt, toast, useHub } from '@/store/store'; +import { cn } from '@/lib/text'; +import { Button, IconButton } from '@/components/ui/Button'; +import { Checkbox, Input } from '@/components/ui/Field'; +import { Dialog } from '@/components/ui/Overlay'; +import { StateWord } from '@/components/ui/List'; +import { LoadingRows } from '@/components/ui/EmptyState'; +import { FolderCheckNote, useFolderCheck, useMissingFolders } from '@/features/chat/folderCheck'; +import { tildePath } from '@/features/chat/FolderChooser'; +import { placeName } from './start'; +import { computerList } from './Where'; + +const trim = (p: string) => (p.length > 1 ? p.replace(/[\\/]+$/, '') : p); +const base = (p: string) => trim(p).split(/[\\/]/).pop() || p; +/** ~ and ~/x to the device's home. */ +export const expandHome = (p: string, home?: string) => (home && (p === '~' || p.startsWith('~/')) ? `${trim(home)}${p.slice(1)}` : p); + +export interface FolderRow { + path: string; + name: string; + /** The muted second line: the path, when the name alone is ambiguous or the path says more. */ + detail?: string; + projectId?: string; +} + +/** The account's project a folder on the device is (or is inside), with the part below it. */ +export function projectOf(projects: ProjectDto[], device: string, abs: string): { project: ProjectDto; rel: string } | undefined { + for (const p of projects) + for (const l of p.locations) + if (l.device === device && (abs === trim(l.path) || abs.startsWith(`${trim(l.path)}/`))) return { project: p, rel: abs.slice(trim(l.path).length + 1) }; + return undefined; +} + +/** Give each row its second line: shown when two rows share a name, or when the path is more than ~/. */ +export function withDetails(rows: Omit[], home?: string): FolderRow[] { + const count = new Map(); + for (const r of rows) count.set(r.name.toLowerCase(), (count.get(r.name.toLowerCase()) ?? 0) + 1); + return rows.map((r) => { + const shown = tildePath(r.path, home); + const plain = shown === r.name || shown === `~/${r.name}`; + return (count.get(r.name.toLowerCase()) ?? 0) > 1 || !plain ? { ...r, detail: shown } : r; + }); +} + +/** + * Recent: the folders of recent Code sessions on the device, newest first, + * each once, at most `max`. The home folder and repository worktrees are + * left out. A folder of a project reads by the project's name. + */ +export function recentFolders(sessions: Session[], projects: ProjectDto[], device: string, home?: string, max = 8): FolderRow[] { + const seen = new Set(); + const rows: Omit[] = []; + for (const s of [...sessions].sort((a, b) => b.updatedAt - a.updatedAt)) { + if (rows.length >= max) break; + if (s.device !== device || s.kind === 'chat' || !s.cwd || s.cwd === '~' || (s.meta as { repo?: unknown } | undefined)?.repo) continue; + const abs = trim(expandHome(s.cwd, home)); + if (abs === trim(home ?? '') || seen.has(abs)) continue; + seen.add(abs); + const hit = projectOf(projects, device, abs); + rows.push({ path: s.cwd, name: hit ? (hit.rel ? `${hit.project.name}/${hit.rel}` : hit.project.name) : base(abs), ...(hit ? { projectId: hit.project.id } : {}) }); + } + return withDetails(rows, home); +} + +/** The projects with a folder on the device, as rows (for search). */ +export function projectFolders(projects: ProjectDto[], device: string, home?: string): Omit[] { + return projects.flatMap((p) => p.locations.filter((l) => l.device === device).map((l) => ({ path: tildePath(l.path, home), name: p.name, projectId: p.id }))); +} + +/** Rows whose name or path holds every word of the query, in any case. */ +export function filterFolders(rows: T[], q: string): T[] { + const words = q.toLowerCase().split(/\s+/).filter(Boolean); + if (!words.length) return rows; + return rows.filter((r) => words.every((w) => r.name.toLowerCase().includes(w) || r.path.toLowerCase().includes(w))); +} + +/** "~/code", "/srv", "./x", "C:\\Users" or anything with a slash: a path to look up on the device. */ +export const looksLikePath = (q: string) => /^(~|\/|\.{1,2}[\\/]|[A-Za-z]:[\\/])/.test(q.trim()) || /[\\/]/.test(q.trim()); + +/** Folders on the device that a typed path starts: "~/co" lists ~/code and ~/courses. */ +function usePathMatches(device: string, q: string, home?: string): string[] { + const [hits, setHits] = useState<{ key: string; list: string[] }>(); + const t = q.trim(); + const on = looksLikePath(t); + const cut = Math.max(t.lastIndexOf('/'), t.lastIndexOf('\\')); + const parent = cut < 0 ? '~' : cut === 0 ? '/' : t.slice(0, cut); + const prefix = cut < 0 ? (t === '~' ? '' : t) : t.slice(cut + 1); + const key = `${device}\n${parent}`; + useEffect(() => { + if (!on) return; + let live = true; + const timer = setTimeout(() => { + api() + .browse(device, expandHome(parent, home)) + .then((list) => live && setHits({ key, list: list.filter((e) => e.type === 'dir' || e.type === 'symlink').map((e) => e.name) })) + .catch(() => live && setHits({ key, list: [] })); + }, 200); + return () => { + live = false; + clearTimeout(timer); + }; + }, [on, device, parent, home, key]); + if (!on || hits?.key !== key) return []; + const sep = parent.endsWith('/') ? '' : '/'; + return hits.list + .filter((n) => n.toLowerCase().startsWith(prefix.toLowerCase()) && (prefix.startsWith('.') || !n.startsWith('.'))) + .sort((a, b) => a.localeCompare(b)) + .slice(0, 8) + .map((n) => `${parent}${sep}${n}`); +} + +interface Item { + key: string; + run: () => void; +} + +const ROW = 'flex w-full items-center gap-2 rounded-[var(--r-1)] px-2 text-left text-[13px] phone:text-[15px]'; + +/** + * The folder menu. `cwd` undefined or "~" is No folder. onPick gets a path + * ("~" for No folder); onOpenFolder asks for the browser; onDevice adds the + * "On " row while there is more than one place to run. + */ +export function FolderMenu({ device, cwd, onPick, onOpenFolder, onDevice, onClose }: { device: string; cwd?: string; onPick: (path: string) => void; onOpenFolder: () => void; onDevice?: (id: string) => void; onClose?: () => void }) { + const sessions = useHub((s) => s.sessions); + const projectMap = useHub((s) => s.projects); + const devices = useHub((s) => s.devices); + const d = devices[device]; + const home = d?.info?.home; + const projects = useMemo(() => Object.values(projectMap), [projectMap]); + const [q, setQ] = useState(''); + const [active, setActive] = useState(0); + const [devicesOpen, setDevicesOpen] = useState(false); + const listId = useId(); + const recent = useMemo(() => recentFolders(Object.values(sessions), projects, device, home), [sessions, projects, device, home]); + const searching = q.trim().length > 0; + const typedPath = looksLikePath(q) ? q.trim() : ''; + const matches = usePathMatches(device, typedPath, home); + const found = useMemo(() => { + if (!searching || typedPath) return recent; + const extra = projectFolders(projects, device, home).filter((p) => !recent.some((r) => trim(expandHome(r.path, home)) === trim(expandHome(p.path, home)))); + return withDetails(filterFolders([...recent, ...extra], q), home); + }, [searching, typedPath, recent, projects, device, home, q]); + // a recent folder that is gone is marked, not offered; a typed path is asked of the device (folderCheck.tsx) + const gone = useMissingFolders(device, recent.map((r) => r.path)); + const check = useFolderCheck(device, typedPath); + const list = computerList(devices); + const many = !!onDevice && list.length > 1; + const none = !cwd || cwd === '~'; + const current = cwd ? trim(expandHome(cwd, home)) : ''; + + const items: Item[] = []; + if (typedPath) items.push({ key: `typed:${typedPath}`, run: () => check.ready && onPick(typedPath) }); + for (const m of matches) if (m !== typedPath) items.push({ key: `match:${m}`, run: () => onPick(m) }); + if (!searching) items.push({ key: 'none', run: () => onPick('~') }); + for (const r of found) items.push({ key: `row:${r.path}`, run: () => !gone.has(r.path) && onPick(r.path) }); + items.push({ key: 'open', run: onOpenFolder }); + if (many) { + items.push({ key: 'device', run: () => setDevicesOpen((o) => !o) }); + if (devicesOpen) for (const dev of list) items.push({ key: `dev:${dev.id}`, run: () => (dev.id !== device && onDevice!(dev.id), setDevicesOpen(false)) }); + } + const at = Math.min(active, items.length - 1); + const idx = (key: string) => items.findIndex((i) => i.key === key); + useEffect(() => setActive(0), [q]); + + const onKey = (e: KeyboardEvent) => { + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault(); + setActive((a) => (Math.min(a, items.length - 1) + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length); + } else if (e.key === 'Enter') { + e.preventDefault(); + items[at]?.run(); + } else if (e.key === 'Tab' && !e.shiftKey && items[at]?.key.startsWith('match:')) { + // Tab fills the field with the folder, to go on typing below it + e.preventDefault(); + setQ(`${items[at].key.slice(6)}/`); + } else if (e.key === 'Escape' && onClose) { + e.preventDefault(); + e.stopPropagation(); + onClose(); + } + }; + const rowProps = (key: string) => { + const i = idx(key); + return { id: `${listId}-${i}`, role: 'option' as const, 'aria-selected': i === at, 'data-active': i === at || undefined, onMouseMove: () => i !== at && setActive(i) }; + }; + const hl = (key: string) => idx(key) === at && 'bg-hover'; + + return ( +
+
+ setQ(e.target.value)} + onKeyDown={onKey} + placeholder="Search folders…" + aria-label="Search folders" + role="combobox" + aria-expanded + aria-controls={listId} + aria-activedescendant={`${listId}-${at}`} + autoCapitalize="off" + autoCorrect="off" + spellCheck={false} + prefix={} + /> + {typedPath && } +
+
+ {typedPath && ( + + )} + {matches + .filter((m) => m !== typedPath) + .map((m) => ( + + ))} + {!searching && ( + + )} + {found.length > 0 && ( +
+
+ {searching && !typedPath ? 'Folders' : 'Recent'} +
+ {found.map((r) => { + const missing = gone.has(r.path); + const on = current && trim(expandHome(r.path, home)) === current; + return ( + + ); + })} +
+ )} + {searching && !typedPath && !found.length &&

No folder matches. Type a path, like ~/code.

} +
+
+ +
+ {many && ( +
+ + {devicesOpen && + list.map((dev) => ( + + ))} +
+ )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Open folder…: the folder browser +// --------------------------------------------------------------------------- + +/** The breadcrumb parts of an absolute path: "/" or "C:" first, then each folder with its own path. */ +export function crumbs(path: string): { name: string; path: string }[] { + const win = /^[A-Za-z]:/.test(path); + const parts = path.split(/[\\/]/).filter(Boolean); + const out: { name: string; path: string }[] = win ? [] : [{ name: '/', path: '/' }]; + let at = ''; + for (const [i, p] of parts.entries()) { + at = win && i === 0 ? `${p}/` : at === '' || at.endsWith('/') ? `${at || '/'}${p}` : `${at}/${p}`; + out.push({ name: p, path: at }); + } + return out; +} + +/** The folder above, or undefined at the top. */ +export function parentPath(path: string): string | undefined { + const c = crumbs(path); + return c.length > 1 ? c[c.length - 2].path : undefined; +} + +/** A name New folder takes: one folder, not "." or "..", no slash. */ +export const folderNameOk = (n: string) => !!n.trim() && !/[\\/\u0000]/.test(n) && n.trim() !== '.' && n.trim() !== '..'; + +const joinPath = (dir: string, name: string) => `${trim(dir)}${dir.endsWith('/') ? '' : '/'}${name}`; + +/** + * The folder browser. Desktop: a dialog; phones: a tall sheet. Typing a path + * in the bar and Go still works, checked as before. + */ +export function FolderBrowser({ open, device, start, onSelect, onClose }: { open: boolean; device: string; start?: string; onSelect: (path: string) => void; onClose: () => void }) { + const d = useHub((s) => s.devices[device]); + const home = d?.info?.home; + const startAt = expandHome(start && start !== '~' ? start : (home ?? '/'), home); + const [path, setPath] = useState(startAt); + const [typed, setTyped] = useState(tildePath(startAt, home)); + const [entries, setEntries] = useState(); + const [error, setError] = useState(); + const [hidden, setHidden] = useState(false); + const [made, setMade] = useState(0); + const [newName, setNewName] = useState(); + const [adding, setAdding] = useState(); + const [busy, setBusy] = useState(false); + const there = useFolderCheck(device, path, () => setMade((n) => n + 1)); + const projectMap = useHub((s) => s.projects); + const project = projectOf(Object.values(projectMap), device, trim(path)); + + useEffect(() => { + if (!open) return; + setPath(startAt); + setNewName(undefined); + setAdding(undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open]); + useEffect(() => { + if (!open) return; + let live = true; + setEntries(undefined); + setError(undefined); + setTyped(tildePath(path, home)); + api() + .browse(device, path) + .then((list) => live && setEntries(list.filter((e) => e.type === 'dir' || e.type === 'symlink').sort((a, b) => a.name.localeCompare(b.name)))) + .catch((e) => live && setError(e instanceof Error ? e.message : String(e))); + return () => { + live = false; + }; + }, [open, device, path, home, made]); + + const shown = entries?.filter((e) => hidden || !e.name.startsWith('.')); + const up = parentPath(path); + const jumps = home + ? [ + { name: 'Home', path: home }, + { name: 'Desktop', path: joinPath(home, 'Desktop') }, + { name: 'Documents', path: joinPath(home, 'Documents') }, + ] + : []; + for (const r of d?.roots ?? []) { + const p = expandHome(r, home); + if (!jumps.some((j) => trim(j.path) === trim(p))) jumps.push({ name: tildePath(p, home), path: p }); + } + + const makeFolder = async () => { + if (newName === undefined || !folderNameOk(newName)) return; + const at = joinPath(path, newName.trim()); + const r = await attempt(() => api().makeFolder(device, at)); + if (r?.exists) { + setNewName(undefined); + setPath(r.path); + } + }; + const select = async () => { + if (adding !== undefined) { + setBusy(true); + const p = await attempt(() => api().addProject(device, path, adding.trim())); + setBusy(false); + if (!p) return; + useHub.setState((s) => ({ projects: { ...s.projects, [p.id]: p } })); + toast({ title: `${p.name} is a project now`, level: 'success' }); + } + onSelect(tildePath(path, home)); + }; + + return ( + + {!project && adding === undefined && ( + + )} + {adding !== undefined && ( +
+ setAdding(e.target.value)} className="w-[180px] phone:flex-1" /> + +
+ )} + + + + } + > +
{ + e.preventDefault(); + const t = typed.trim(); + if (t) setPath(expandHome(t, home)); + }} + > + up && setPath(up)}> + + + setTyped(e.target.value)} className="min-w-0 flex-1" autoCapitalize="off" autoCorrect="off" spellCheck={false} /> + +
+ + + {jumps.length > 0 && ( +
+ {jumps.map((j) => ( + + ))} +
+ )} +
+ {there.state === 'missing' ? null : error ? ( +

{error}

+ ) : !shown ? ( + + ) : shown.length ? ( + shown.map((e) => ( + + )) + ) : ( +

No folders in here.

+ )} +
+
+ {newName === undefined ? ( + + ) : ( +
{ + e.preventDefault(); + void makeFolder(); + }} + > + setNewName(e.target.value)} className="min-w-0 flex-1" autoCapitalize="off" autoCorrect="off" spellCheck={false} /> + + +
+ )} + + + +
+ {project &&

In project {project.project.name}.

} +
+ ); +} + +/** The menu's way to the browser: state for the browser, and the browser to render beside the menu. */ +export function useOpenFolder(device: string, cwd: string | undefined, onSelect: (path: string) => void): { open: () => void; browser: ReactNode } { + const [open, setOpen] = useState(false); + const started = useRef(cwd); + if (!open) started.current = cwd; + return { + open: () => setOpen(true), + browser: ( + setOpen(false)} + onSelect={(p) => { + setOpen(false); + onSelect(p); + }} + /> + ), + }; +} diff --git a/packages/web/src/features/home/SessionStart.tsx b/packages/web/src/features/home/SessionStart.tsx index 04efb19c5..0e5dadfbc 100644 --- a/packages/web/src/features/home/SessionStart.tsx +++ b/packages/web/src/features/home/SessionStart.tsx @@ -75,7 +75,8 @@ import { BranchPicker, IssuePicker, RepoList, RepoPicker, type IssuePick, type R import { ASSISTANT_AGENT, CODE_AGENT, CODE_NEEDS_DEVICE, commandOf, customAgent, lastOwnSession, needsOwnDevice, offersIncognito, placeName, readPicks, savePicks, SECURITY_AGENT, sessionSetup, startCommands, startEffort, type Picks, type SessionKind } from './start'; import { startSurface, useThisComputer } from './here'; import { FolderChip, computerList, useComputers } from './Where'; -import { FolderCheckNote, useFolderCheck, useMissingFolders } from '@/features/chat/folderCheck'; +import { FolderCheckNote, useFolderCheck } from '@/features/chat/folderCheck'; +import { FolderMenu, useOpenFolder } from './FolderPicker'; import { StateWord } from '@/components/ui/List'; import { CODE_INCOGNITO_LINE, memoryChat, usePrivacy } from '@/features/conversation/incognito'; @@ -488,7 +489,6 @@ function PlaceSheet({ onStartRepo: (r: RepoPick) => void; }) { const devices = useHub((s) => s.devices); - const sessions = useHub((s) => s.sessions); const [path, setPath] = useState(cwd ?? ''); const [from, setFrom] = useState<'folder' | 'github'>('folder'); const [repo, setRepo] = useState(); @@ -497,16 +497,11 @@ function PlaceSheet({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]); const list = useMemo(() => computerList(devices), [devices]); - const known = useMemo(() => { - const seen = new Set(); - for (const s of Object.values(sessions).sort((a, b) => b.updatedAt - a.updatedAt)) if (s.device === device && s.kind !== 'chat' && s.cwd && s.cwd !== '~') seen.add(s.cwd); - for (const r of devices[device]?.roots ?? []) seen.add(r); - return [...seen].slice(0, 4); - }, [sessions, devices, device]); // the folder is asked of the device; an offline one waits for "Use anyway" (features/chat/folderCheck.tsx) const folder = from === 'folder' && open; const check = useFolderCheck(device, folder ? path : ''); - const gone = useMissingFolders(device, folder ? known : []); + // the same folder menu as the chip (FolderPicker.tsx), with the browser as a tall sheet + const browse = useOpenFolder(device, path, setPath); return (
-
Device
- {list.map((d) => ( - - ))} + {/* a folder's device is the menu's "On " row; a repository still picks it here */} + {from === 'github' && ( + <> +
Device
+ {list.map((d) => ( + + ))} + + )} {!noRepo && )} {from === 'folder' && ( - <> - - setPath(e.target.value)} placeholder="~/code/project" autoCapitalize="off" autoCorrect="off" spellCheck={false} /> - - - )} - {from === 'folder' && known.length > 0 && ( -
- {known.map((k) => ( - - ))} +
+ + {path && path !== '~' && }
)}
+ {browse.browser} ); } diff --git a/packages/web/src/features/home/Where.tsx b/packages/web/src/features/home/Where.tsx index 1ffafce6b..766b2c2dc 100644 --- a/packages/web/src/features/home/Where.tsx +++ b/packages/web/src/features/home/Where.tsx @@ -5,39 +5,25 @@ * the device after a dot: "~/code/conclave · arch-desktop". Its popover * holds both. The hub is always one of the places, by its name: "madx (hub)". */ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useMemo, useRef, useState } from 'react'; import { Folder } from 'lucide-react'; import { useHub } from '@/store/store'; import { cn } from '@/lib/text'; import { shortPath } from '@/lib/format'; -import { Button } from '@/components/ui/Button'; -import { Input } from '@/components/ui/Field'; import { Popover, type MenuItem } from '@/components/ui/Overlay'; import { PickerButton } from '@/components/ui/Select'; -import { StateWord } from '@/components/ui/List'; import { placeName } from './start'; -import { FolderCheckNote, useFolderCheck, useMissingFolders } from '@/features/chat/folderCheck'; +import { FolderMenu, useOpenFolder } from './FolderPicker'; const CHIP = 'h-[24px] text-[12px] phone:text-[13px]'; -/** Folders this device worked in lately, then its roots: the first few to pick from. */ -export function useKnownFolders(device: string): string[] { - const sessions = useHub((s) => s.sessions); - const roots = useHub((s) => s.devices[device]?.roots); - return useMemo(() => { - const seen = new Set(); - for (const s of Object.values(sessions).sort((a, b) => b.updatedAt - a.updatedAt)) if (s.device === device && s.kind !== 'chat' && s.cwd && s.cwd !== '~' && !(s.meta as { repo?: unknown } | undefined)?.repo) seen.add(s.cwd); - for (const r of roots ?? []) seen.add(r); - return [...seen].slice(0, 5); - }, [sessions, roots, device]); -} - /** * The folder and device chip. `cwd` undefined reads "Choose folder"; a pick - * calls onCwd with the path ("~" for the home folder). No `onCwd`: the folder - * is not this chip's to change (a repository), so it is the device only, "on - * MacBook". `onDevice` adds the device while there is more than one place to - * run. Nothing to show: no chip. + * calls onCwd with the path ("~" for No folder). The menu is FolderMenu + * (FolderPicker.tsx), with the device as its "On " row. No `onCwd`: + * the folder is not this chip's to change (a repository), so it is the + * device only, "on MacBook". `onDevice` adds the device while there is more + * than one place to run. Nothing to show: no chip. */ export function FolderChip({ device, cwd, onCwd, onDevice, open: openProp, onOpenChange }: { device: string; cwd?: string; onCwd?: (cwd: string) => void; onDevice?: (id: string) => void; open?: boolean; onOpenChange?: (open: boolean) => void }) { const ref = useRef(null); @@ -48,18 +34,12 @@ export function FolderChip({ device, cwd, onCwd, onDevice, open: openProp, onOpe const d = useHub((s) => s.devices[device]); const list = useComputers(); const devices = !!onDevice && list.length > 1; - const known = useKnownFolders(device); - const [path, setPath] = useState(cwd ?? ''); - useEffect(() => { - if (open) setPath(cwd && cwd !== '~' ? cwd : ''); - }, [open, cwd]); const set = (p: string) => { onCwd?.(p.trim() || '~'); setOpen(false); }; - // a typed path is asked of the device; a recent one that is gone is marked, not offered (features/chat/folderCheck.tsx) - const check = useFolderCheck(device, open ? path : ''); - const gone = useMissingFolders(device, open ? known : []); + // Open folder…: the in-app browser everywhere (the desktop app has no native folder dialog: no tauri-plugin-dialog or rfd) + const browse = useOpenFolder(device, cwd, (p) => onCwd?.(p)); if (!onCwd && !devices) return null; const shown = cwd && cwd !== '~' ? shortPath(cwd, 2) : undefined; const place = placeName(d, device); @@ -85,38 +65,20 @@ export function FolderChip({ device, cwd, onCwd, onDevice, open: openProp, onOpe setOpen(false)} placement="top-start" width={340} label={onCwd ? 'Folder' : 'Device'} sheetTitle={onCwd ? `Folder on ${name}` : 'Device'}> {onCwd && ( -
{ - e.preventDefault(); - if (check.ready) set(path); - }} - > - -
- setPath(e.target.value)} placeholder="~/code/project" autoCapitalize="off" autoCorrect="off" spellCheck={false} className="flex-1" /> - -
- - - )} - {onCwd && known.length > 0 && ( -
- {known.map((k) => ( - - ))} -
+ setOpen(false)} + onOpenFolder={() => { + setOpen(false); + browse.open(); + }} + /> )} - {devices && ( -
- {onCwd &&
Run on
} + {devices && !onCwd && ( +
{list.map((dev) => (