Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(quick-open): index SSH projects over the ControlMaster
enes047dff847c21
diff --git a/src/core/fs-ops.ts b/src/core/fs-ops.tsindex 720f80688..395a1ac88 100644--- a/src/core/fs-ops.ts+++ b/src/core/fs-ops.ts@@ -19,7 +19,8 @@ import {buildGitLsFilesArgs,normalizeQuickOpenRgLine,shouldIncludeQuickOpenPath,- HIDDEN_DIR_BLOCKLIST+ HIDDEN_DIR_BLOCKLIST,+ QUICK_OPEN_FILE_CAP} from '../shared/quick-open-filter'const run = promisify(execFile)@@ -119,7 +120,6 @@ export async function pathExists(p: string): Promise<boolean> {}}-const QUICK_OPEN_FILE_CAP = 50_000const QUICK_OPEN_TIMEOUT_MS = 10_000// Spawn a lister command, stream stdout split on `splitChar`, normalize+filter each path intodiff --git a/src/main/index.ts b/src/main/index.tsindex 5f41257fb..8c15465a0 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -841,6 +841,10 @@ app.whenReady().then(async () => {const ref = sshFsRefFor(projectId)return ref ? sshFs.exists(ref, p) : Promise.resolve(false)})+ ipcMain.handle(IPC.sshFsQuickOpen, (_e, projectId: string, cwd: string) => {+ const ref = sshFsRefFor(projectId)+ return ref ? sshFs.listQuickOpenFiles(ref, cwd) : Promise.resolve([])+ })// Board-log: same CorePlatform registrar as the Server Edition (core/board-log-handlers.ts), with// a desktop router that adds SSH routing on top of the local-cwd/unsupported the server also does.diff --git a/src/main/ssh-fs.test.ts b/src/main/ssh-fs.test.tsindex 9b1d444a7..6312c876f 100644--- a/src/main/ssh-fs.test.ts+++ b/src/main/ssh-fs.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest'-import { sshListArgs, sshReadArgs, sshReadBinaryArgs, sshWriteArgs, sshMkdirArgs, sshExistsArgs, sshCheckIgnoreArgs, sshAppendArgs, sshTailArgs, sshSizeArgs, parseLsEntries, SshFs } from './ssh-fs'+import { sshListArgs, sshReadArgs, sshReadBinaryArgs, sshWriteArgs, sshMkdirArgs, sshExistsArgs, sshCheckIgnoreArgs, sshAppendArgs, sshTailArgs, sshSizeArgs, sshQuickOpenArgs, parseQuickOpenListing, parseLsEntries, SshFs, SSH_QUICK_OPEN_MAX_BYTES } from './ssh-fs'const conn = { host: 'h', user: 'u' }const ref = { conn, controlPath: '/s.sock' }@@ -134,3 +134,64 @@ describe('SshFs (injected runner)', () => {expect(await new SshFs(async () => { throw new Error('spawn') }).readTextChecked(ref, '/x')).toEqual({ status: 'error' })})})++// ⌘K Quick Open over SSH: one remote round-trip that mirrors the local fallback chain+// (rg two passes → git ls-files two passes → find), parsed with the same shared filter.+describe('sshQuickOpenArgs', () => {+ const cmd = (): string => sshQuickOpenArgs(conn, '/s.sock', '/re po').join(' ')+ it('cds into the quoted cwd so every lister emits cwd-relative paths', () => {+ expect(cmd()).toContain(`cd '/re po' && `)+ })+ it('leaves a leading ~/ unquoted so the remote shell tilde-expands the cwd', () => {+ expect(sshQuickOpenArgs(conn, '/s.sock', '~/projects').join(' ')).toContain(`cd ~/'projects' && `)+ })+ it('prefers rg: two passes (ignore-respecting + --no-ignore-vcs), pruning node_modules', () => {+ const c = cmd()+ expect(c).toContain('command -v rg')+ expect(c).toContain(`rg --files --hidden '--glob' '!**/node_modules'`)+ expect(c).toContain('--no-ignore-vcs')+ })+ it('falls back to git ls-files (NUL-delimited, tracked+untracked then ignored pass)', () => {+ const c = cmd()+ expect(c).toContain('git ls-files -z --cached --others --exclude-standard')+ expect(c).toContain('git ls-files -z --others --ignored --exclude-standard')+ })+ it('falls back to a pruned find for non-git roots without rg', () => {+ const c = cmd()+ expect(c).toContain('find .')+ expect(c).toContain(`-name 'node_modules'`)+ expect(c).toContain('-prune')+ })+ it('caps the transfer with head -c so a huge repo cannot flood the master', () => {+ expect(cmd()).toContain(`| head -c ${SSH_QUICK_OPEN_MAX_BYTES}`)+ })+})++describe('parseQuickOpenListing', () => {+ it('splits on newline (rg/find) and NUL (git -z), normalizes ./ prefixes, sorts', () => {+ expect(parseQuickOpenListing('./src/b.ts\nsrc/a.ts\n')).toEqual(['src/a.ts', 'src/b.ts'])+ expect(parseQuickOpenListing('a.ts\0b with space.ts\0')).toEqual(['a.ts', 'b with space.ts'])+ })+ it('dedupes the two rg/git passes', () => {+ expect(parseQuickOpenListing('src/a.ts\nsrc/a.ts\n')).toEqual(['src/a.ts'])+ })+ it('drops blocklisted dirs and root escapes — the remote listing is untrusted', () => {+ expect(parseQuickOpenListing('node_modules/x.js\n../up\n/abs\na/../b\nok.ts\n')).toEqual(['ok.ts'])+ })+ it('drops the (possibly truncated) last entry when output hit the head -c cap', () => {+ const filler = 'y'.repeat(SSH_QUICK_OPEN_MAX_BYTES - 8)+ expect(parseQuickOpenListing(`good.ts\n${filler}`)).toEqual(['good.ts'])+ })+})++describe('SshFs.listQuickOpenFiles', () => {+ it('returns the parsed listing on exit 0', async () => {+ const fs = new SshFs(async () => ({ code: 0, stdout: './src/a.ts\nREADME.md\n' }))+ expect(await fs.listQuickOpenFiles(ref, '~/p')).toEqual(['README.md', 'src/a.ts'])+ })+ it('fail-open: [] on non-zero exit (bad cwd / connection down) and on a runner throw', async () => {+ expect(await new SshFs(async () => ({ code: 1, stdout: '' })).listQuickOpenFiles(ref, '/p')).toEqual([])+ expect(await new SshFs(async () => ({ code: 255, stdout: '' })).listQuickOpenFiles(ref, '/p')).toEqual([])+ expect(await new SshFs(async () => { throw new Error('spawn') }).listQuickOpenFiles(ref, '/p')).toEqual([])+ })+})diff --git a/src/main/ssh-fs.ts b/src/main/ssh-fs.tsindex 15aca647b..0dee65fb3 100644--- a/src/main/ssh-fs.ts+++ b/src/main/ssh-fs.ts@@ -5,6 +5,14 @@// interpolated). check-ignore entry NAMES are bare filenames, so they stay posixQuote'd.import { childArgs } from '../core/remote-ssh/control-master'import { posixQuote, quoteRemotePath, type SshConnection } from '../shared/ssh'+import {+ buildHiddenDirExcludeGlobs,+ isSafeQuickOpenRelPath,+ normalizeQuickOpenRgLine,+ quickOpenPruneNames,+ shouldIncludeQuickOpenPath,+ QUICK_OPEN_FILE_CAP+} from '../shared/quick-open-filter'import type { DirEntry } from '../shared/types'export interface SshFsRef {@@ -60,6 +68,45 @@ export function sshSizeArgs(conn: SshConnection, cp: string, path: string): striexport function sshExistsArgs(conn: SshConnection, cp: string, path: string): string[] {return childArgs(conn, cp, `test -e ${quoteRemotePath(path)}`)}+/** Transfer cap for the quick-open listing (`head -c`): ~50k paths fit comfortably. */+export const SSH_QUICK_OPEN_MAX_BYTES = 4_194_304++export function sshQuickOpenArgs(conn: SshConnection, cp: string, cwd: string): string[] {+ // The remote analog of fs-ops.listQuickOpenFiles' fallback chain, folded into ONE round-trip:+ // rg two passes (tracked + git-ignored build output) → git ls-files two passes → pruned find.+ // Local falls to git when rg yields nothing; remotely that extra round-trip isn't worth it, so+ // the chain branches on `command -v rg` alone. git output is NUL-delimited (-z) so paths never+ // come back C-quoted; the parser splits on both \n and \0.+ const globs = buildHiddenDirExcludeGlobs().map(posixQuote).join(' ')+ const prunes = quickOpenPruneNames().map((n) => `-name ${posixQuote(n)}`).join(' -o ')+ const rg = `rg --files --hidden ${globs} . ; rg --files --hidden --no-ignore-vcs ${globs} .`+ const git = `git ls-files -z --cached --others --exclude-standard ; git ls-files -z --others --ignored --exclude-standard`+ const find = `find . \\( ${prunes} \\) -prune -o -type f -print`+ const chain = `if command -v rg >/dev/null 2>&1; then ${rg}; elif git rev-parse --is-inside-work-tree >/dev/null 2>&1; then ${git}; else ${find}; fi`+ return childArgs(+ conn,+ cp,+ `cd ${quoteRemotePath(cwd)} && { ${chain}; } 2>/dev/null | head -c ${SSH_QUICK_OPEN_MAX_BYTES}`+ )+}++/**+ * Remote lister stdout → sorted, deduped, root-relative quick-open index. The listing is+ * REMOTE-SUPPLIED, so beyond the shared noise filter every entry must also pass the traversal+ * guard. Output that hit the head -c cap drops its (possibly cut mid-path) last entry.+ */+export function parseQuickOpenListing(stdout: string): string[] {+ const lines = stdout.split(/[\n\0]/)+ if (Buffer.byteLength(stdout, 'utf8') >= SSH_QUICK_OPEN_MAX_BYTES) lines.pop()+ const out = new Set<string>()+ for (const line of lines) {+ if (out.size >= QUICK_OPEN_FILE_CAP) break+ const rel = normalizeQuickOpenRgLine(line)+ if (rel && isSafeQuickOpenRelPath(rel) && shouldIncludeQuickOpenPath(rel)) out.add(rel)+ }+ return [...out].sort()+}+export function sshCheckIgnoreArgs(conn: SshConnection, cp: string, dir: string, names: string[]): string[] {// The dir is a remote path (may be tilde-prefixed) → quoteRemotePath; the entry NAMES are bare// filenames with no tilde → posixQuote literally (and inject-safe).@@ -156,6 +203,15 @@ export class SshFs {}}+ async listQuickOpenFiles(ref: SshFsRef, cwd: string): Promise<string[]> {+ try {+ const { code, stdout } = await this.run(sshQuickOpenArgs(ref.conn, ref.controlPath, cwd))+ return code === 0 ? parseQuickOpenListing(stdout) : []+ } catch {+ return []+ }+ }+async exists(ref: SshFsRef, path: string): Promise<boolean> {try {const { code } = await this.run(sshExistsArgs(ref.conn, ref.controlPath, path))diff --git a/src/preload/index.ts b/src/preload/index.tsindex 22fabf38d..039847160 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -232,7 +232,9 @@ const api: NodeTerminalApi = {write: (projectId: string, path: string, content: string) =>ipcRenderer.invoke(IPC.sshFsWrite, projectId, path, content),mkdir: (projectId: string, p: string) => ipcRenderer.invoke(IPC.sshFsMkdir, projectId, p),- exists: (projectId: string, p: string) => ipcRenderer.invoke(IPC.sshFsExists, projectId, p)+ exists: (projectId: string, p: string) => ipcRenderer.invoke(IPC.sshFsExists, projectId, p),+ quickOpen: (projectId: string, cwd: string) =>+ ipcRenderer.invoke(IPC.sshFsQuickOpen, projectId, cwd)},git: {status: (cwd) => ipcRenderer.invoke(IPC.gitStatus, cwd),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 6cd9d82a0..6a472233e 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -152,7 +152,8 @@ export function buildStubApi(): Omit<readBinary: U('sshFs.readBinary'),write: U('sshFs.write'),mkdir: U('sshFs.mkdir'),- exists: U('sshFs.exists')+ exists: U('sshFs.exists'),+ quickOpen: U('sshFs.quickOpen')},clipboard: {// Clipboard API → execCommand → visible error. `navigator.clipboard` only exists in a SECUREdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 353c1ffc1..b6fcce7f7 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -186,6 +186,7 @@ import { planHibernation, HIBERNATE_SWEEP_MS } from '../terminal/hibernation-polimport { buildHibernationCandidates } from '../lib/hibernationCandidates'import { applyLoopDismiss } from '../lib/loopCard'import { prepareQuickOpenFiles, type QuickOpenIndexedFile } from '../lib/quickOpenSearch'+import { isSafeQuickOpenRelPath } from '@shared/quick-open-filter'import { opensInEditor } from '../lib/openTarget'import { newEntryPath, parentDir } from '../lib/explorerCreate'import { useProjects } from '../state/projects'@@ -3100,33 +3101,44 @@ export function Canvas() {}}, [hasProjects, kanbanOpen, placeCanvasImages, screenToFlowPosition, viewCenter, welcomeOpen])- // Load the quick-open file index when the palette opens.+ // Load the quick-open file index when the palette opens. An SSH project indexes its remoteCwd+ // over the ControlMaster (sshFs.quickOpen); the browser client's sshFs is a stub, so the catch+ // fails open to an empty index there instead of surfacing an "unsupported" error.useEffect(() => {if (!paletteOpen) return- const cwd = useProjects.getState().getProject(activeProjectId ?? '')?.cwd- if (!cwd) {+ const project = useProjects.getState().getProject(activeProjectId ?? '')+ const cwd = project?.ssh?.remoteCwd ?? project?.cwd+ if (!project || !cwd) {setFileIndex([])return}let cancelled = false- void window.nodeTerminal.files.quickOpen(cwd).then((files) => {- if (!cancelled) setFileIndex(prepareQuickOpenFiles(files))- })+ const index = project.ssh+ ? window.nodeTerminal.sshFs.quickOpen(project.id, cwd)+ : window.nodeTerminal.files.quickOpen(cwd)+ void index+ .catch(() => [] as string[])+ .then((files) => {+ if (!cancelled) setFileIndex(prepareQuickOpenFiles(files))+ })return () => {cancelled = true}}, [paletteOpen, activeProjectId])/** Open a quick-open file result by root-relative path: editor node for text/images,- * OS default app for binaries (e.g. .dmg). */+ * OS default app for binaries (e.g. .dmg). On an SSH project everything opens as a canvas+ * node routed over `sshFs` (there is no OS to hand a remote path to). */const openProjectFile = useCallback((relPath: string) => {- const cwd = useProjects.getState().getProject(activeProjectId ?? '')?.cwd+ const project = useProjects.getState().getProject(activeProjectId ?? '')+ const cwd = project?.ssh?.remoteCwd ?? project?.cwdif (!cwd) return- // relPath comes from the trusted local file index (always cwd-relative), so the- // `cwd + relPath` join needs no traversal guard in v1; a future remote/untrusted source would.+ // An SSH project's index is remote-supplied, so guard the join against traversal.+ if (!isSafeQuickOpenRelPath(relPath)) returnconst abs = `${cwd.replace(/\/$/, '')}/${relPath}`- if (opensInEditor(relPath)) openFile(abs)+ if (project?.ssh) openFile(abs, undefined, true)+ else if (opensInEditor(relPath)) openFile(abs)else window.nodeTerminal.shell.openPath(abs)},[activeProjectId, openFile]diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 28cad05eb..e2420d912 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -242,6 +242,7 @@ export const IPC = {sshFsWrite: 'sshFs:write',sshFsMkdir: 'sshFs:mkdir',sshFsExists: 'sshFs:exists',+ sshFsQuickOpen: 'sshFs:quick-open',sshProjectStatus: 'ssh-project:status',/** main → renderer: an SSH project's identity file is passphrase-protected and the ssh-agent* does not hold the key (or the last answer was wrong), so show a prompt.diff --git a/src/shared/quick-open-filter.test.ts b/src/shared/quick-open-filter.test.tsindex a2403745d..d2318aa06 100644--- a/src/shared/quick-open-filter.test.ts+++ b/src/shared/quick-open-filter.test.ts@@ -4,7 +4,8 @@ import {buildHiddenDirExcludeGlobs,buildRgArgsForQuickOpen,buildGitLsFilesArgs,- normalizeQuickOpenRgLine+ normalizeQuickOpenRgLine,+ isSafeQuickOpenRelPath} from './quick-open-filter'describe('shouldIncludeQuickOpenPath', () => {@@ -35,6 +36,25 @@ describe('normalizeQuickOpenRgLine', () => {})})+// The quick-open index used to be a trusted LOCAL listing; with SSH projects it is+// remote-supplied, so the `cwd + relPath` join in the renderer needs a traversal guard.+describe('isSafeQuickOpenRelPath', () => {+ it('accepts normal root-relative paths', () => {+ expect(isSafeQuickOpenRelPath('src/main/index.ts')).toBe(true)+ expect(isSafeQuickOpenRelPath('docs/codex-shared-identity.md')).toBe(true)+ expect(isSafeQuickOpenRelPath('a b/dotted..name.ts')).toBe(true)+ })+ it('rejects escapes: absolute, drive-letter, .. segments (either separator), empty', () => {+ expect(isSafeQuickOpenRelPath('')).toBe(false)+ expect(isSafeQuickOpenRelPath('/etc/passwd')).toBe(false)+ expect(isSafeQuickOpenRelPath('C:/Windows/system32')).toBe(false)+ expect(isSafeQuickOpenRelPath('..')).toBe(false)+ expect(isSafeQuickOpenRelPath('../escape')).toBe(false)+ expect(isSafeQuickOpenRelPath('a/../../etc/passwd')).toBe(false)+ expect(isSafeQuickOpenRelPath('a\\..\\b')).toBe(false)+ })+})+describe('arg builders', () => {it('rg primary respects ignore, ignoredPass adds --no-ignore-vcs; both prune node_modules', () => {const { primary, ignoredPass } = buildRgArgsForQuickOpen({ forceSlashSeparator: false })diff --git a/src/shared/quick-open-filter.ts b/src/shared/quick-open-filter.tsindex dd845c77e..fd67ff5b5 100644--- a/src/shared/quick-open-filter.ts+++ b/src/shared/quick-open-filter.ts@@ -1,8 +1,8 @@/*** Pure Quick Open (⌘K file search) listing policy — no IO, no Electron. Provides- * a noise blocklist + rg/git arg builders + line normalization.- * The caller (main process) owns process execution. v1 is single local root (no- * WSL/SSH/exclude-prefix logic).+ * a noise blocklist + rg/git arg builders + line normalization + the traversal guard.+ * Callers own process execution: fs-ops.listQuickOpenFiles runs the listers locally,+ * ssh-fs.sshQuickOpenArgs folds the same chain into one remote command.*/// Tool-generated caches / VCS / editor state that are never hand-edited. Deliberately omits@@ -24,6 +24,24 @@ export const HIDDEN_DIR_BLOCKLIST: ReadonlySet<string> = new Set([// Pruned from every traversal but not a dotdir, so tracked separately.const NON_DOTTED_PRUNE = 'node_modules'+/** Hard cap on index size — local and SSH listers both stop here. */+export const QUICK_OPEN_FILE_CAP = 50_000++/** Every dir name pruned from traversal (find/walk fallbacks build their prune list from this). */+export function quickOpenPruneNames(): string[] {+ return [NON_DOTTED_PRUNE, ...HIDDEN_DIR_BLOCKLIST]+}++/**+ * Guard for joining an index-supplied relPath onto the project root. The local index is trusted,+ * but an SSH project's index comes from the remote host — a compromised host must not be able to+ * point the join outside the root (`../`, absolute, drive-letter).+ */+export function isSafeQuickOpenRelPath(relPath: string): boolean {+ if (!relPath || relPath.startsWith('/') || /^[A-Za-z]:/.test(relPath)) return false+ return relPath.split(/[\\/]/).every((seg) => seg !== '' && seg !== '..')+}+/*** True if `relPath` (`/`-separated, root-relative) does not traverse a blocklisted segment.* Correctness backstop after the rg/git pruning globs. Walks segment-by-segment without@@ -55,7 +73,7 @@ function escapeGlob(segment: string): string {* prunes traversal of huge caches instead of merely dropping already-listed files.*/export function buildHiddenDirExcludeGlobs(): string[] {- const names = [NON_DOTTED_PRUNE, ...HIDDEN_DIR_BLOCKLIST]+ const names = quickOpenPruneNames()const out: string[] = []for (const name of names) out.push('--glob', `!**/${escapeGlob(name)}`)return outdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 1fc74435d..72a2fc165 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1286,6 +1286,8 @@ export interface SshFsApi {write(projectId: string, path: string, content: string): Promise<boolean>mkdir(projectId: string, path: string): Promise<boolean>exists(projectId: string, path: string): Promise<boolean>+ /** ⌘K Quick Open index of the project's remoteCwd: root-relative `/`-paths ([] on failure). */+ quickOpen(projectId: string, cwd: string): Promise<string[]>}export interface GitFileChange {