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
fix(windows): rename Windows-illegal child names in recursive SSH downloads
review701d8fa2a5e5
diff --git a/src/core/download-name.test.ts b/src/core/download-name.test.tsindex 067d11cf2..107fba60e 100644--- a/src/core/download-name.test.ts+++ b/src/core/download-name.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { candidateName, safeDownloadBasename } from './download-name'+import { candidateName, localChildName, safeDownloadBasename, uniqueChildName } from './download-name'describe('safeDownloadBasename', () => {it('takes the basename of a remote path', () => {@@ -41,3 +41,53 @@ describe('candidateName', () => {expect(candidateName('.bashrc', 2)).toBe('.bashrc (2)')})})++describe('localChildName', () => {+ it.each([+ ['a:b', 'a_b'],+ ['x?.txt', 'x_.txt'],+ ['q"<>|*', 'q_____'],+ ['a\\b', 'a_b'],+ ['CON', '_CON'],+ ['com1.txt', '_com1.txt'],+ ['Lpt9', '_Lpt9'],+ ['console.log', 'console.log'],+ ['name. ', 'name'],+ ['nul. ', '_nul'],+ ['...', 'download'],+ ['tab\there', 'tab_here']+ ])('win32: %j → %j', (name, want) => {+ expect(localChildName(name, 'win32')).toBe(want)+ })++ it('POSIX hosts keep every name a POSIX filesystem can hold', () => {+ for (const platform of ['linux', 'darwin'] as const) {+ for (const n of ['a:b', 'x?.txt', 'CON', 'com1.txt', 'name. ', 'a\\b']) expect(localChildName(n, platform)).toBe(n)+ // A separator is never a path, anywhere.+ expect(localChildName('a/b', platform)).toBe('a_b')+ }+ })++ it('names nothing for the directory entries', () => {+ for (const platform of ['win32', 'linux'] as const) {+ expect(localChildName('.', platform)).toBeNull()+ expect(localChildName('..', platform)).toBeNull()+ expect(localChildName('', platform)).toBeNull()+ }+ })+})++describe('uniqueChildName', () => {+ it('win32: case-insensitive, so Foo and foo do not overwrite each other', () => {+ const taken = new Set<string>()+ expect(uniqueChildName('Foo.txt', taken, 'win32')).toBe('Foo.txt')+ expect(uniqueChildName('foo.txt', taken, 'win32')).toBe('foo (2).txt')+ expect(uniqueChildName('FOO.TXT', taken, 'win32')).toBe('FOO (3).TXT')+ })+ it('POSIX: case-sensitive, as the filesystem is', () => {+ const taken = new Set<string>()+ expect(uniqueChildName('Foo', taken, 'linux')).toBe('Foo')+ expect(uniqueChildName('foo', taken, 'linux')).toBe('foo')+ expect(uniqueChildName('foo', taken, 'linux')).toBe('foo (2)')+ })+})diff --git a/src/core/download-name.ts b/src/core/download-name.tsindex 51b827ee1..0fb8029a5 100644--- a/src/core/download-name.ts+++ b/src/core/download-name.ts@@ -32,3 +32,37 @@ export function candidateName(name: string, attempt: number): string {if (dot <= 0) return `${name} (${attempt})`return `${name.slice(0, dot)} (${attempt})${name.slice(dot)}`}++/** Windows device names, which name the DEVICE in every directory and with any extension. */+const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i++/**+ * The local name for one entry INSIDE a downloaded directory tree, or null for one that names+ * nothing (`.`, `..`, empty). The remote host is POSIX, so a child may legally be called `a:b`,+ * `x?.txt` or `CON` — all of which Windows cannot create, and one such child used to fail the whole+ * download. On win32: the characters Windows refuses become `_`, trailing dots/spaces (which Windows+ * silently strips, so two names would alias one file) are dropped, and a device stem is prefixed+ * with `_`. Elsewhere only a separator is neutralized — a name off another machine is never a path.+ */+export function localChildName(name: string, platform: NodeJS.Platform = process.platform): string | null {+ if (!name || name === '.' || name === '..') return null+ if (platform !== 'win32') return name.replace(/[/\x00]/g, '_')+ // eslint-disable-next-line no-control-regex+ let safe = name.replace(/[\\/:*?"<>|\x00-\x1f]/g, '_').replace(/[. ]+$/, '')+ if (!safe) safe = 'download'+ return WINDOWS_RESERVED.test(safe) ? `_${safe}` : safe+}++/**+ * `name`, or the first `candidateName` not already in `taken` (one directory's names so far), and+ * records it. Compared case-insensitively on win32, where `Foo` and `foo` — or `a:b` and `a_b` once+ * sanitized — are the same file and the second would silently overwrite the first.+ */+export function uniqueChildName(name: string, taken: Set<string>, platform: NodeJS.Platform = process.platform): string {+ const key = (n: string): string => (platform === 'win32' ? n.toLowerCase() : n)+ let attempt = 1+ let candidate = name+ while (taken.has(key(candidate))) candidate = candidateName(name, ++attempt)+ taken.add(key(candidate))+ return candidate+}diff --git a/src/core/remote-ssh/native/native-invoke.test.ts b/src/core/remote-ssh/native/native-invoke.test.tsindex 698be0266..b4b80bee5 100644--- a/src/core/remote-ssh/native/native-invoke.test.ts+++ b/src/core/remote-ssh/native/native-invoke.test.ts@@ -5,7 +5,7 @@ import net, { type AddressInfo } from 'net'import path from 'path'import { Server, type Connection } from 'ssh2'import { NativeMux } from './native-mux'-import { runSshArgv, spawnSshArgvStream, startNativeMaster, useNativeSsh } from './native-invoke'+import { download, runSshArgv, spawnSshArgvStream, startNativeMaster, useNativeSsh } from './native-invoke'import {checkMasterArgs,childArgs,@@ -310,3 +310,77 @@ describe('native-invoke', () => {expect(r.stderr.toString()).toMatch(/unsupported ssh argument -L/)})})++describe('download() — a remote tree onto a Windows filesystem', () => {+ // A fake SFTP over an in-memory POSIX tree: names Windows cannot hold, and two that collide.+ const tree: Record<string, string[] | string> = {+ '/r': ['.', '..', 'a:b', 'a_b', 'CON', 'notes. ', 'sub'],+ '/r/a:b': 'colon',+ '/r/a_b': 'underscore',+ '/r/CON': 'device',+ '/r/notes. ': 'dots',+ '/r/sub': ['Foo', 'foo', 'ok.txt'],+ '/r/sub/Foo': 'upper',+ '/r/sub/foo': 'lower',+ '/r/sub/ok.txt': 'fine'+ }+ type Cb<T> = (err: Error | undefined, v: T) => void+ const sftp = {+ stat: (p: string, cb: Cb<{ isDirectory(): boolean }>) =>+ p in tree ? cb(undefined, { isDirectory: () => Array.isArray(tree[p]) }) : cb(new Error(`no ${p}`), undefined as never),+ readdir: (p: string, cb: Cb<{ filename: string }[]>) => cb(undefined, (tree[p] as string[]).map((filename) => ({ filename }))),+ fastGet: (r: string, l: string, cb: (err?: Error) => void) => {+ fs.writeFileSync(l, tree[r] as string)+ cb()+ }+ } as unknown as Parameters<typeof download>[0]++ const files = (root: string): Record<string, string> => {+ const out: Record<string, string> = {}+ const walk = (d: string, rel: string): void => {+ for (const n of fs.readdirSync(d)) {+ const full = path.join(d, n)+ if (fs.statSync(full).isDirectory()) walk(full, `${rel}${n}/`)+ else out[`${rel}${n}`] = fs.readFileSync(full, 'utf8')+ }+ }+ walk(root, '')+ return out+ }++ it('win32: every child gets a legal, unique name, and the renames are counted', async () => {+ const local = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-dl-'))+ try {+ const renamed = { count: 0 }+ await download(sftp, '/r', path.join(local, 'r'), true, 'win32', renamed)+ expect(files(path.join(local, 'r'))).toEqual({+ a_b: 'colon',+ 'a_b (2)': 'underscore',+ _CON: 'device',+ notes: 'dots',+ 'sub/Foo': 'upper',+ 'sub/foo (2)': 'lower',+ 'sub/ok.txt': 'fine'+ })+ // a:b, a_b (displaced), CON, `notes. `, foo.+ expect(renamed.count).toBe(5)+ } finally {+ fs.rmSync(local, { recursive: true, force: true })+ }+ })++ it.skipIf(process.platform === 'win32')('POSIX: the tree lands byte-for-byte as named', async () => {+ // Not runnable on Windows: the point is names that Windows cannot create.+ const local = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-dl-'))+ try {+ const renamed = { count: 0 }+ await download(sftp, '/r', path.join(local, 'r'), true, 'linux', renamed)+ expect(Object.keys(files(path.join(local, 'r'))).sort()).toEqual(+ ['CON', 'a:b', 'a_b', 'notes. ', 'sub/Foo', 'sub/foo', 'sub/ok.txt'].sort()+ )+ expect(renamed.count).toBe(0)+ } finally {+ fs.rmSync(local, { recursive: true, force: true })+ }+ })+})diff --git a/src/core/remote-ssh/native/native-invoke.ts b/src/core/remote-ssh/native/native-invoke.tsindex 281b15dc1..a60729377 100644--- a/src/core/remote-ssh/native/native-invoke.ts+++ b/src/core/remote-ssh/native/native-invoke.ts@@ -15,6 +15,7 @@ import path from 'path'import type { SFTPWrapper } from 'ssh2'import { NativeMux, channelExit, noMasterMessage, type ExecResult } from './native-mux'import { parseScpArgv, parseSshArgv, type ParsedSsh } from './ssh-argv'+import { localChildName, uniqueChildName } from '../../download-name'export function useNativeSsh(platform: NodeJS.Platform = process.platform,@@ -122,7 +123,11 @@ export function startNativeMaster(mux: NativeMux, argv: string[]): NativeMasterH* The scp argv scpArgs / scpDownArgs build, over SFTP on the shared connection. Files and (for a* download) directory trees; a recursive UPLOAD is not something any builder produces.*/-export async function runScpArgv(mux: NativeMux, argv: string[]): Promise<{ code: number; stderr: string }> {+export async function runScpArgv(+ mux: NativeMux,+ argv: string[],+ platform: NodeJS.Platform = process.platform+): Promise<{ code: number; stderr: string; renamed?: number }> {let p: ReturnType<typeof parseScpArgv>try {p = parseScpArgv(argv)@@ -134,13 +139,14 @@ export async function runScpArgv(mux: NativeMux, argv: string[]): Promise<{ codeconst sftp = await mux.sftp(cp, p.target, p.options)try {const remote = await realRemotePath(sftp, p.remotePath)+ const renamed = { count: 0 }if (p.direction === 'up') {if (p.recursive) throw new Error('scp: recursive upload is not supported')await promisify<void>((cb) => sftp.fastPut(p.localPath, remote, cb))} else {- await download(sftp, remote, p.localPath, p.recursive)+ await download(sftp, remote, p.localPath, p.recursive, platform, renamed)}- return { code: 0, stderr: '' }+ return renamed.count ? { code: 0, stderr: '', renamed: renamed.count } : { code: 0, stderr: '' }} finally {sftp.end()}@@ -156,7 +162,19 @@ async function realRemotePath(sftp: SFTPWrapper, p: string): Promise<string> {return p === '' || p === '.' ? home : `${home.replace(/\/$/, '')}/${p}`}-async function download(sftp: SFTPWrapper, remote: string, local: string, recursive: boolean): Promise<void> {+/**+ * One remote file, or a directory tree. Each CHILD name is made valid for this machine and unique+ * within its directory (download-name.ts) — the top-level name is the caller's — and every name+ * that had to change is counted in `renamed`.+ */+export async function download(+ sftp: Pick<SFTPWrapper, 'stat' | 'readdir' | 'fastGet'>,+ remote: string,+ local: string,+ recursive: boolean,+ platform: NodeJS.Platform = process.platform,+ renamed: { count: number } = { count: 0 }+): Promise<void> {const st = await promisify<{ isDirectory(): boolean }>((cb) => sftp.stat(remote, cb))if (!st.isDirectory()) {await promisify<void>((cb) => sftp.fastGet(remote, local, cb))@@ -165,9 +183,13 @@ async function download(sftp: SFTPWrapper, remote: string, local: string, recursif (!recursive) throw new Error(`scp: ${remote}: not a regular file`)fs.mkdirSync(local, { recursive: true })const entries = await promisify<{ filename: string }[]>((cb) => sftp.readdir(remote, cb))+ const taken = new Set<string>()for (const e of entries) {- if (e.filename === '.' || e.filename === '..') continue- await download(sftp, `${remote}/${e.filename}`, path.join(local, e.filename), true)+ const safe = localChildName(e.filename, platform)+ if (safe === null) continue+ const name = uniqueChildName(safe, taken, platform)+ if (name !== e.filename) renamed.count+++ await download(sftp, `${remote}/${e.filename}`, path.join(local, name), true, platform, renamed)}}diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 97a4bd566..7673ca5a6 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -1,4 +1,4 @@-import { nativeMux, setNativePassphrasePrompt, useNativeSsh } from '../../core/remote-ssh/native/native-runtime'+import { findSshBinary, nativeMux, setNativePassphrasePrompt, useNativeSsh } from '../../core/remote-ssh/native/native-runtime'import { runScpArgv, runSshArgv, startNativeMaster } from '../../core/remote-ssh/native/native-invoke'import { promises as fs } from 'fs'import path from 'path'@@ -28,7 +28,7 @@ import {remoteClaudeConfigDir,remoteSessionCopyCommand} from '../../core/remote-claude-session-copy'-import { candidateName, safeDownloadBasename } from '../../core/download-name'+import { candidateName, localChildName, safeDownloadBasename } from '../../core/download-name'import { removeAtomic, renameAtomic } from '../../core/fs-atomic'import { findExecutableSync, shellPathNow } from '../../core/exec-path'import { isSafeRemoteHome } from '../../core/remote-safety'@@ -233,10 +233,11 @@ async function removeScpPart(partPath: string): Promise<void> {.catch(() => {})}-/** Windows aliases terminal dots/spaces, so do not let two remote names bypass one reservation. */+/** Windows aliases terminal dots/spaces (and reserves device names), so do not let two remote+ * names bypass one reservation. The ONE rule, shared with a tree's children (download-name.ts). */function localDownloadName(name: string): string {if (process.platform !== 'win32') return name- return name.replace(/[. ]+$/, '') || 'download'+ return localChildName(name, 'win32') ?? 'download'}/** Cap on how much master stderr we retain (a misconfigured host can spew), enough for the error. */@@ -435,16 +436,8 @@ interface Conn {* the common locations. A MISS is only memoized once the async PATH probe has settled.* (Do NOT use the brief's always-returns-first stub.)*/-let cachedSsh: string | null | undefinedfunction sshBin(): string {- if (cachedSsh !== undefined) return cachedSsh ?? 'ssh'- const found = findExecutableSync('ssh', [- '/usr/bin/ssh',- '/usr/local/bin/ssh',- '/opt/homebrew/bin/ssh'- ])- if (found || shellPathNow() !== undefined) cachedSsh = found- return found ?? 'ssh'+ return findSshBinary() ?? 'ssh'}/** Resolve an absolute `scp` path the same way `sshBin()` resolves `ssh` (GUI apps lack shell PATH). */@@ -3025,7 +3018,10 @@ export function initSshProject(}),runScp: (args) =>native- ? runScpArgv(nativeMux(), args).then((r) => ({ code: r.code }))+ ? runScpArgv(nativeMux(), args).then((r) => {+ if (r.renamed) console.warn(`[ssh] download: ${r.renamed} file name(s) were changed to be valid on this computer`)+ return { code: r.code }+ }): new Promise((resolve) => {// Same reason as `run`: scp re-authenticates when the master socket is gone.execFile(scp, args, { maxBuffer: 1024 * 1024, env: { ...process.env, ...appSshAgent.env() } }, (err) =>