diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b24e5015..24376d177 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ like `## [0.4.16] - 2026-10-24`. - Members: model pickers list models a member cannot use under Not available, so a fallback list no longer fails with "You can't use ... on this hub". The web app no longer calls the owner-only MCP, Preview and hub copy routes for a member. - Pasting a copied picture (from a website, Snipping Tool or a screenshot) works on Windows, in the app and the browser +### 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.103] - 2026-11-19 ### Fixed diff --git a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/CodeOptions.kt b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/CodeOptions.kt index 8a7460067..392f75097 100644 --- a/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/CodeOptions.kt +++ b/packages/android/app/src/main/kotlin/dev/conclave/app/ui/conversation/CodeOptions.kt @@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding @@ -17,7 +18,11 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text @@ -33,6 +38,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import dev.conclave.app.data.CodeDefaults @@ -47,10 +53,12 @@ import dev.conclave.client.folderGit import dev.conclave.client.github import dev.conclave.client.githubBranches import dev.conclave.client.githubRepos +import dev.conclave.client.logic.Locations import dev.conclave.client.logic.Panel import dev.conclave.client.logic.Paths import dev.conclave.client.logic.RepoWords import dev.conclave.client.logic.Start +import dev.conclave.client.model.FileEntry import dev.conclave.client.model.FolderGit import dev.conclave.client.model.GithubBranches import dev.conclave.client.model.GithubRepo @@ -147,7 +155,11 @@ fun CodeWhereSheet( var typed by remember { mutableStateOf("") } var fromGithub by remember { mutableStateOf(github && (startGithub || d.repo != null)) } val device = d.device - val folders = remember(sessions, device) { if (device == null) emptyList() else Panel.recentFolders(sessions, device) } + val home = devices.firstOrNull { it.id == device }?.info?.home?.ifBlank { null } + // Recent as in Codex: the folder's name over its muted path (Panel.recentRows) + val rows = remember(sessions, device, home) { if (device == null) emptyList() else Panel.recentRows(sessions, device, home) } + val folders = rows.map { it.path } + var browsing by remember { mutableStateOf(false) } // the folder picked is asked of its device before Start; the hub refuses a missing one too (core machine/folder-check.ts) val chosen = if (fromGithub) null else d.cwd val online = device == Start.HUB || devices.firstOrNull { it.id == device }?.online == true @@ -200,9 +212,10 @@ fun CodeWhereSheet( HorizontalDivider(thickness = 1.dp, color = c.rule, modifier = Modifier.padding(top = 6.dp)) OptionLabel("Folder") ChoiceRow("Home folder", selected = d.cwd == "~", onClick = { onChange(d.copy(cwd = "~", repo = null, base = null)) }) - folders.forEach { f -> - ChoiceRow(Paths.folderName(f), selected = d.cwd == f, detail = Paths.shortPath(f, 3), onClick = { onChange(d.copy(cwd = f, repo = null, base = null)) }) + rows.forEach { r -> + ChoiceRow(r.name, selected = d.cwd == r.path, detail = r.detail, onClick = { onChange(d.copy(cwd = r.path, repo = null, base = null)) }) } + ChoiceRow("Browse…", selected = false, onClick = { browsing = true }) Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) { OutlinedTextField( value = typed, @@ -240,6 +253,12 @@ fun CodeWhereSheet( if (!anyway) TextButton(onClick = { anyway = true }, modifier = Modifier.padding(horizontal = 12.dp)) { Text("Use anyway") } } } + if (browsing && device != null) { + BrowseFolderSheet(device, deviceName, home, start = d.cwd, onSelect = { + browsing = false + onChange(d.copy(cwd = it, repo = null, base = null)) + }, onDismiss = { browsing = false }) + } Spacer(Modifier.height(8.dp)) Button( onClick = onDone, @@ -251,6 +270,59 @@ fun CodeWhereSheet( } } +/** + * Browse… in CodeWhereSheet: the device's folders over GET + * /api/devices/:device/files (as Choose folder does, FolderPickerSheet.kt). + * Tap a folder to go in, Up to go back, Select to use the folder shown. + */ +@Composable +private fun BrowseFolderSheet(device: String, deviceName: String, home: String?, start: String?, onSelect: (String) -> Unit, onDismiss: () -> Unit) { + val hub = LocalAppContainer.current.hub + val c = Conclave.colors + var path by remember { mutableStateOf(Locations.expandTilde(start?.takeIf { it.isNotBlank() } ?: "~", home).ifBlank { home ?: "/" }) } + var entries by remember { mutableStateOf?>(null) } + var error by remember { mutableStateOf(null) } + LaunchedEffect(path) { + entries = null + error = null + try { + entries = hub.api { it.browse(device, path) }.filter { it.type == "dir" || it.type == "symlink" }.filter { !it.name.startsWith(".") }.sortedBy { it.name.lowercase() } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + error = errorText(e) + } + } + val up = Locations.parentOf(path) + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), containerColor = c.bgRaise) { + Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) { + Text("Open folder on $deviceName", style = ConclaveType.title, color = c.fg, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)) + Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = { up?.let { path = it } }, enabled = up != null) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Up one folder") + } + Text(Locations.tildePath(path, home), style = CodeStyle, color = c.fg2, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + } + HorizontalDivider(thickness = 1.dp, color = c.rule) + Column(Modifier.fillMaxWidth().heightIn(min = 120.dp, max = 420.dp).verticalScroll(rememberScrollState())) { + val list = entries + when { + error != null -> Text(error.orEmpty(), style = ConclaveType.meta, color = c.fault, modifier = Modifier.padding(horizontal = 20.dp, vertical = 10.dp)) + list == null -> Text("Reading the folder", style = ConclaveType.meta, color = c.fg3, modifier = Modifier.padding(horizontal = 20.dp, vertical = 10.dp)) + list.isEmpty() -> Text("No folders in here.", style = ConclaveType.meta, color = c.fg3, modifier = Modifier.padding(horizontal = 20.dp, vertical = 10.dp)) + else -> list.forEach { e -> ChoiceRow(e.name, selected = false, onClick = { path = e.path.ifBlank { path.trimEnd('/') + "/" + e.name } }) } + } + } + Button( + onClick = { onSelect(Locations.tildePath(path, home)) }, + enabled = error == null, + colors = solidButtonColors(), + modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp).height(52.dp), + ) { Text("Select this folder") } + } + } +} + /** The folder picked in CodeWhereSheet: there (or not checkable: OK), being asked, or not on the device. */ private enum class FolderState { OK, CHECKING, MISSING } diff --git a/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Panel.kt b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Panel.kt index a0a1e344f..158b8f582 100644 --- a/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Panel.kt +++ b/packages/android/client/src/main/kotlin/dev/conclave/client/logic/Panel.kt @@ -72,6 +72,25 @@ object Panel { .map { it.cwd.trimEnd('/', '\\') } .distinct() .take(count) + + /** One Recent row as in Codex: the folder's name over its muted path; [detail] is null when ~/ says nothing more. */ + data class FolderRow(val path: String, val name: String, val detail: String?) + + /** + * [recentFolders] as rows (web: FolderPicker.tsx withDetails). The path + * shows under the name when two rows share a name, or when it is more + * than ~/. + */ + fun recentRows(sessions: List, device: String, home: String?, count: Int = 8): List { + val folders = recentFolders(sessions, device, count) + val names = folders.map { Paths.folderName(Locations.tildePath(it, home)).ifEmpty { it } } + return folders.mapIndexed { i, f -> + val shown = Locations.tildePath(f, home) + val name = names[i] + val plain = shown == "~/$name" || shown == name + FolderRow(f, name, if (!plain || names.count { it.equals(name, ignoreCase = true) } > 1) shown else null) + } + } } object Lists { diff --git a/packages/android/client/src/test/kotlin/dev/conclave/client/PanelTest.kt b/packages/android/client/src/test/kotlin/dev/conclave/client/PanelTest.kt index 8a4f480e4..7b49bd488 100644 --- a/packages/android/client/src/test/kotlin/dev/conclave/client/PanelTest.kt +++ b/packages/android/client/src/test/kotlin/dev/conclave/client/PanelTest.kt @@ -112,6 +112,26 @@ class PanelTest { assertEquals(listOf("/srv/app"), Panel.recentFolders(sessions, "local")) } + @Test + fun recentRowsShowTheNameAndThePathOnlyWhenItSaysMore() { + val sessions = listOf( + agent("a", "x", at(20, 9)).copy(cwd = "/Users/sam/site"), + agent("b", "x", at(20, 10)).copy(cwd = "/Users/sam/work/site/"), + agent("c", "x", at(20, 8)).copy(cwd = "/Users/sam/conclave"), + agent("d", "x", at(20, 7)).copy(cwd = "/Users/sam/uni/Project-1"), + agent("e", "x", at(20, 6)).copy(cwd = "/Users/sam/conclave"), + ) + assertEquals( + listOf( + Panel.FolderRow("/Users/sam/work/site", "site", "~/work/site"), + Panel.FolderRow("/Users/sam/site", "site", "~/site"), + Panel.FolderRow("/Users/sam/conclave", "conclave", null), + Panel.FolderRow("/Users/sam/uni/Project-1", "Project-1", "~/uni/Project-1"), + ), + Panel.recentRows(sessions, "mac", "/Users/sam"), + ) + } + @Test fun listsAreChatsOrCodePinnedFirstThenByTime() { val sessions = listOf( 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 054012b8d..1114ef00c 100644 --- a/packages/core/src/projects/service.ts +++ b/packages/core/src/projects/service.ts @@ -405,6 +405,55 @@ 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. + */ + add(device: string, path: string, name: string, accountId: string = OWNER_ID): Promise { + // one add per device and path at a time: a second Select waits and finds the first one's project + const key = `${accountId}\n${device}\n${path}`; + const prev = this.adding.get(key) ?? Promise.resolve(); + const run = prev.catch(() => undefined).then(() => this.addNow(device, path, name, accountId)); + const tail = run.catch(() => undefined).finally(() => this.adding.get(key) === tail && this.adding.delete(key)); + this.adding.set(key, tail); + return run; + } + + private adding = new Map>(); + + private async addNow(device: string, path: string, name: string, accountId: string): Promise { + const m = this.machine(device); + if (!m) throw new EngineError(409, `${this.deviceName(device)} is offline`); + const home = await this.engine.machineHome(m); + const abs = trimSlash(m.resolve(path, home ?? '/')); + // the home folder or the root as a project would make every folder under it that project + if (!abs || abs === '/' || /^[A-Za-z]:[\\/]?$/.test(abs) || (home && abs === trimSlash(home))) throw new EngineError(400, 'Pick a folder inside the home folder, not the home folder or the root'); + 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) { + // the same history known from another place: this folder becomes one of its places too + if (!this.store.locations(found.id).some((l) => l.device === device && trimSlash(l.path) === root)) { + this.store.saveLocation(found.id, { device, path: root, via: 'pinned', pinned: true, head: probe.head }); + this.emitProject(this.store.get(found.id)!); + } + return this.dto(this.store.get(found.id)!); + } + 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..92748e32b 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,40 @@ 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/); + await expect(svc.add('pc', d.pc.home, 'home')).rejects.toThrow(/not the home folder/); + await expect(svc.add('pc', '/', 'root')).rejects.toThrow(/not the home folder/); + // two Selects at once: one project, one marker + const twice = join(d.pc.home, 'twice'); + mkdirSync(twice); + const [a, b] = await Promise.all([svc.add('pc', twice, 'Twice'), svc.add('pc', twice, 'Twice')]); + expect(a.id).toBe(b.id); + // the same history in another clone: that folder becomes another place of the project + const clone = join(d.pc.home, 'site-copy'); + cloneRepo(repo, clone); + const again = await svc.add('pc', clone, 'ignored'); + expect(again.id).toBe(r.id); + expect(again.locations.map((l) => l.path)).toContain(clone); + }); +}); + 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..5e31003fa 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,20 @@ 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') ?? ''; + // control and direction-override characters would spoof the name in lists and the audit log + if (name.length > 200 || /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/.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 f903a7bf9..aa12b6f97 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,12 +53,11 @@ 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 ?? ''); const member = useHub((s) => s.me?.role === 'member'); // the hub first, by its name ("madx (hub)"), then the computers; a member's code never runs on the hub (moveTarget) const list = computerList(devices).filter((x) => !member || x.id !== 'local'); - // 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..ba6115853 --- /dev/null +++ b/packages/web/src/features/home/FolderPicker.tsx @@ -0,0 +1,548 @@ +/** + * 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 { + // the deepest place wins (a project inside another); a place at the root is no prefix of everything + let best: { project: ProjectDto; at: string } | undefined; + for (const p of projects) + for (const l of p.locations) { + const at = trim(l.path); + if (l.device !== device || at === '/' || !at) continue; + if ((abs === at || abs.startsWith(`${at}/`)) && (!best || at.length > best.at.length)) best = { project: p, at }; + } + return best && { project: best.project, rel: abs.slice(best.at.length + 1) }; +} + +/** 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 member = useHub((s) => s.me?.role === 'member'); + // a member's code never runs on the hub (moveTarget), so the hub is not offered to them + const list = computerList(devices).filter((x) => !member || x.id !== 'local'); + 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..973813688 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); @@ -46,20 +32,16 @@ export function FolderChip({ device, cwd, onCwd, onDevice, open: openProp, onOpe const setOpen = (v: boolean) => (onOpenChange ? onOpenChange(v) : setOwn(v)); const name = useHub((s) => s.devices[device]?.name ?? device); const d = useHub((s) => s.devices[device]); - const list = useComputers(); + const member = useHub((s) => s.me?.role === 'member'); + // as Device and folder (pickers.tsx): a member's code never runs on the hub + const list = useComputers().filter((x) => !member || x.id !== 'local'); 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 +67,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) => (