Skip to content

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.

fix(windows): port the path-semantics safeguards from PR #276

enesfbc65ad8d40b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8545a3c3c..881dacb5d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -55,4 +55,4 @@ jobs:
run: npm run typecheck
- name: Windows-relevant tests
- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts
+ run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts
diff --git a/CLAUDE.md b/CLAUDE.md
index 92d74eaca..a3d6f894f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -595,8 +595,14 @@ session.
all terminals — harmless in a plain shell). **Cmd (mac) / Ctrl+click** opens links in the
output: URLs → default browser (`@xterm/addon-web-links`), file paths → editor node and
directories → Explorer reveal (`terminal/file-links.ts`, existence-verified against the project
- fs via cached parent-dir listings, with `path:line[:col]` compiler-output suffixes; relay-remote
- nodes have no client fs so they are URL-only).
+ fs via cached parent-dir listings, with `path:line[:col]` compiler-output suffixes). The path
+ dialect follows the FILESYSTEM-OWNING CORE, not the viewer: desktop-local may use its own
+ platform, Server Edition and relay tabs use the core's reported `process.platform`, and SSH
+ projects are POSIX. A failed host-platform read disables file links for that connection — it
+ never guesses from the browser. Standalone `ssh` terminal nodes remain URL-only because they
+ have no remote fs API with which to verify a token; relay tabs do have a core-bound, jailed fs
+ API and therefore support file links. Windows existence matching is case-insensitive and accepts
+ both separators; UNC tokens are refused whole before they can be reinterpreted as cwd-relative.
- **Agent** (`createAgentNode(agentId, …)`) — a terminal preset that runs an agent CLI as its
`initialCommand` (runs once on open via `transport.write`, then cleared), with `data.agentId`
set. Builtins (`claude`/`codex`/`gemini`) come from `AGENT_CONFIG` (clay color etc.).
@@ -1927,6 +1933,42 @@ builds (unless `NODETERM_API_BASE` targets a local server). Schema example:
ping to `api.nodeterm.dev/v1/ping` (version/OS on launch + daily), gated on
`settings.telemetryEnabled` + the same build/DNT guards; toggle in Settings → Privacy.
+## Atomic writes (never a bare `fs.rename`)
+
+Every store persists temp-file-then-rename. That is correct on POSIX and **silently lossy on
+Windows**: `MoveFileEx` fails with `EPERM` whenever the destination is open by anyone at that
+instant, and what opens a file you just wrote is Defender's real-time scanner, the search indexer,
+OneDrive over a synced profile, or two of our own concurrent writers racing one destination. The
+save throws and the data is gone — intermittently, unreproducibly, and **more often on the machines
+that are best protected**.
+
+`renameAtomic` / `writeFileAtomic` (`src/core/fs-atomic.ts`) retry briefly. Each attempt is still
+one indivisible rename, so a retry cannot tear a write. They deliberately do NOT retry forever
+(several callers report a failed save as `persisted:false`, and that contract outranks a save that
+eventually lands), do not retry `ENOENT`/`ENOSPC`, do not branch on platform (or the behaviour under
+test on a Mac is not the behaviour shipped to Windows), and never swallow the final error.
+
+**Nothing in the toolchain catches the bare version.** 28 files had it, across three spellings — the user's canvas, their
+settings, their sealed credentials, their pinned devices — and every one of them reads as a correct
+atomic write, because on the platform most of this was written on it is one. The only signal in a
+6,000-test suite was one store's overlapping-saves test, red on Windows for that store's whole life.
+So it is enforced by scan: `src/core/fs-atomic.guard.test.ts` fails on any bare `fs.rename` outside
+the helper. Full write-up, including the separate shared-temp-name bug at the same sites:
+**`docs/atomic-writes.md`**.
+
+SSH/scp staging follows the same ownership rule outside direct `fs` calls. Atomic remote stdin
+writes use `src/main/remote-atomic-write.ts`: a bounded `.nodeterm-<uuid>.tmp` leaf is placed beside
+the target BEFORE both complete paths are quoted, then the shell preserves the write/move status
+while cleaning that exact temp. The temp leaf must stay independent of the target leaf — appending
+`.uuid.tmp` to a valid `NAME_MAX` target makes the write impossible. It currently protects
+filesystem API writes, tmux.conf, the private hook endpoint, node
+tokens, agent status and pending answers; generated hook scripts/config merges still use their
+existing direct writes and must not be described as atomic. Upload directories use UUIDs across app
+processes. Downloads and media-cache copies use hidden UUID `.part` names; user-visible downloads
+also hold an exclusive candidate lock until the rename and cleanup finish. Never simplify any of
+those back to `<target>.tmp` / `<target>.part` or a read-only "does the destination exist?" check —
+the overlap tests exercise the resulting race.
+
## Conventions
- **Two docs, two audiences — keep both.** This file holds the deep invariants with their
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5b68db0e0..d6ae8d3a0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -66,6 +66,26 @@ need it too, and wire it in the same change.
## House rules
+- **Anything path-shaped: Windows is a delivery target.** Most of this was written on
+ macOS/Linux, so the recurring defect is code that is genuinely correct on POSIX —
+ `split('/')`, `startsWith('/')` as an is-absolute test, a bare `fs.rename`. Use
+ `path.basename`/`join`/`sep`, publish files with `renameAtomic`, and write at least one test with
+ a real `C:\`-shaped input. Guards enforce some of this and will fail your PR. In the Server
+ Edition and relay tabs, the browser's OS is NOT the filesystem's OS: obtain the dialect from the
+ core that owns the files, and keep an unobserved host unknown rather than guessing. Conversely,
+ on POSIX a backslash is legal filename text — do not treat both separators as interchangeable
+ unless the owning filesystem is known to be Windows.
+
+- **Never publish a file with a bare `fs.rename`.** Use `renameAtomic` or `writeFileAtomic` from
+ `src/core/fs-atomic.ts`. On Windows a rename fails with `EPERM` whenever anything has the
+ destination open — Defender scanning the file you just wrote, the search indexer, OneDrive — so
+ the plain version loses saves intermittently and only on other people's machines. A test scans
+ for this and will fail your PR; `docs/atomic-writes.md` explains why the retry is safe. Every
+ temp/part staging name must also be unique per call across processes and cleaned by its owner —
+ including paths embedded in generated SSH commands or handed to scp, which the `fs` scan cannot
+ see. Keep a remote temp's own leaf bounded: extending an already-valid maximum-length target leaf
+ with a UUID suffix turns an atomic write into a guaranteed `ENAMETOOLONG` failure.
+
These are the ones that come up in review most often. Each exists because its absence caused a real
bug.
diff --git a/docs/atomic-writes.md b/docs/atomic-writes.md
index ca1c0b267..e8aa49219 100644
--- a/docs/atomic-writes.md
+++ b/docs/atomic-writes.md
@@ -84,7 +84,26 @@ because they make ownership cleanup and diagnostics possible, but they are not g
two containers can both be PID 1, worker isolates share a PID with independent module counters,
and an OS can reuse a PID while crash litter remains. `Date.now()` does **not** make a name unique
either — two bridge calls, shutdown flushes, or WS clients can enter a save inside one millisecond.
-The guard deliberately rejects pid-plus-clock and pid-plus-counter names.
+The guard deliberately rejects pid-plus-clock and pid-plus-counter names. Remote-shell writes use
+the equivalent property with a locally minted random UUID; the remote host never has to
+interpolate a nonce.
+
+The same rule applies to SSH and scp staging even though those writes do not call `fs.writeFile`.
+`remoteAtomicWrite` mints a bounded `.nodeterm-<uuid>.tmp` sibling before quoting both complete
+remote paths, so spaces, apostrophes, literal POSIX backslashes and `~/` expansion keep their
+meanings. The bounded leaf is independent of the target: appending `.uuid.tmp` to a valid
+`NAME_MAX` filename would exceed the directory's component limit. It preserves the `cat`/`mv`
+status while removing exactly that invocation's temp. Uploads likewise use UUID directories rather
+than a timestamp plus a per-manager counter, and failed uploads remove only their own directory.
+Downloads and media-cache fetches stage through hidden UUID `.part` paths beside the target; the
+bounded name avoids lengthening an already maximum-length filename. Ordinary downloads also
+reserve the final candidate with an exclusive lock, so two app processes cannot both observe
+`report.pdf` as absent and overwrite each other after transferring. Candidate checks use `lstat`:
+a dangling symlink is an occupied directory entry, not evidence that the name is free. Atomic
+remote stdin sites use
+the same helper for filesystem writes, tmux.conf, the credential-bearing hook endpoint and node
+tokens, agent status, and pending answers. Generated hook scripts/config merges still have direct
+writes and are not covered by this atomicity claim.
"Only one instance exists" and "the write queue serializes this" are true within one process and
silent about a second — and a second is not hypothetical: the Server Edition takes a `--data-dir`,
@@ -131,5 +150,5 @@ reports clean, which is the same class of silent failure as the bug.
| Surface | Status |
|---|---|
| **Desktop** (Electron) | Covered. Windows is the platform this exists for; on macOS/Linux the retry is inert and behaviour is unchanged. |
-| **Server Edition** | Covered for core stores — the helper is in `src/core`, so both shells get it. Its usual host is Linux, where the retry is inert, but a Windows-hosted server gets the same protection. |
-| **Mobile companion** | No client change; it holds no local stores of its own. |
+| **Server Edition** | Covered for core stores — the helper is in `src/core`, so both shells get it. Its usual host is Linux, where the retry is inert, but a Windows-hosted server gets the same protection. The ControlMaster/scp manager is desktop-only. |
+| **Mobile companion** | No client change. It holds no local stores of its own, but the agent-status mirror it reads from an SSH host now arrives through the unique remote temp path. The transport shape is unchanged. |
diff --git a/src/main/media-protocol.test.ts b/src/main/media-protocol.test.ts
index d51b4dc36..9f4a0729d 100644
--- a/src/main/media-protocol.test.ts
+++ b/src/main/media-protocol.test.ts
@@ -1,16 +1,26 @@
import { describe, it, expect } from 'vitest'
-import { resolveMediaPath, mediaUrlFor } from './media-protocol'
+import { normalize } from 'path'
+import { resolveMediaPath, mediaUrlFor, stripDriveSlash } from './media-protocol'
+
+// resolveMediaPath() runs every decoded pathname through node's platform `normalize()` before
+// comparing it against the allowlist — on win32 that turns `/a/b` into `\a\b`. The real
+// allowlist (allowMediaPath in media-protocol.ts) normalizes on the way in too, so the two
+// sides agree in production; here the fixtures build `allow` by hand, so they have to apply
+// the same normalization or a Windows run compares `\a\b` against a Set holding `/a/b` and
+// every "allowed" case fails as if it were rejected. POSIX is unaffected: normalize() is a
+// no-op on these forward-slash-only fixtures there.
+const n = (p: string): string => normalize(p)
describe('resolveMediaPath (path jail)', () => {
- const allow = new Set(['/projects/app/clip.mp4', '/projects/app/out.html'])
+ const allow = new Set([n('/projects/app/clip.mp4'), n('/projects/app/out.html')])
it('returns the absolute path for an allowed file', () => {
- const url = mediaUrlFor('/projects/app/clip.mp4')
- expect(resolveMediaPath(new URL(url).pathname, allow)).toBe('/projects/app/clip.mp4')
+ const url = mediaUrlFor('/projects/app/clip.mp4', '/')
+ expect(resolveMediaPath(new URL(url).pathname, allow)).toBe(n('/projects/app/clip.mp4'))
})
it('rejects a path not on the allowlist', () => {
- const url = mediaUrlFor('/etc/passwd')
+ const url = mediaUrlFor('/etc/passwd', '/')
expect(resolveMediaPath(new URL(url).pathname, allow)).toBeNull()
})
@@ -19,15 +29,72 @@ describe('resolveMediaPath (path jail)', () => {
})
it('round-trips paths with spaces/unicode via mediaUrlFor', () => {
- const allow2 = new Set(['/a b/çlip.mp4'])
- const url = mediaUrlFor('/a b/çlip.mp4')
- expect(resolveMediaPath(new URL(url).pathname, allow2)).toBe('/a b/çlip.mp4')
+ const allow2 = new Set([n('/a b/çlip.mp4')])
+ const url = mediaUrlFor('/a b/çlip.mp4', '/')
+ expect(resolveMediaPath(new URL(url).pathname, allow2)).toBe(n('/a b/çlip.mp4'))
})
it('round-trips a path containing ? through mediaUrlFor', () => {
const original = '/projects/app/q?x&y#z.mp4'
- const allow3 = new Set([original])
- const url = mediaUrlFor(original)
- expect(resolveMediaPath(new URL(url).pathname, allow3)).toBe(original)
+ const allow3 = new Set([n(original)])
+ const url = mediaUrlFor(original, '/')
+ expect(resolveMediaPath(new URL(url).pathname, allow3)).toBe(n(original))
+ })
+
+ it('preserves a POSIX filename containing a literal backslash', () => {
+ const original = String.raw`/projects/app/name\part.png`
+ const url = mediaUrlFor(original, '/')
+ expect(decodeURIComponent(new URL(url).pathname)).toBe(original)
+ })
+})
+
+describe('a Windows absolute path round-trips through the URL', () => {
+ // The existing cases above all use POSIX paths, which is why this was never caught: on BOTH
+ // platforms `normalize()` runs on each side, so `/projects/app/clip.mp4` matches itself. A real
+ // `C:\Users\...` path was never put through it. Splitting the pathname on '/' alone left one
+ // segment, encoded the backslashes to %5C, and emitted no leading slash — so the drive letter
+ // was swallowed into the URL's authority and every image or video opened from a Windows path
+ // 404'd out of the jail, looking exactly like a path that had never been allowlisted.
+ const WIN = String.raw`C:\Users\me\pics\a.png`
+
+ it('the URL has a real pathname, not a mangled authority', () => {
+ const url = new URL(mediaUrlFor(WIN, '\\'))
+ expect(url.pathname, 'a drive letter must not end up in the authority').toMatch(/^\/C(:|%3A)\//i)
+ expect(url.host).toBe('media')
+ })
+
+ it.runIf(process.platform === 'win32')('resolves back to the allowlisted path', () => {
+ const allow = new Set([n(WIN)])
+ const url = mediaUrlFor(n(WIN), '\\')
+ expect(resolveMediaPath(new URL(url).pathname, allow)).toBe(n(WIN))
+ })
+
+ it('the leading slash added for a drive letter is stripped back off', () => {
+ // Exercises the REAL function. The first version of this test held its own copy of the
+ // regex, the copy's escaping was wrong (`[\/]`, forward slash only), and it asserted on
+ // '/C:Usersmea.png' — a string that can never occur, since '\U' '\m' '\a' are not JS
+ // escapes and the backslashes had silently vanished from the input too. A duplicated
+ // pattern proves nothing about the original, and this one was wrong in two ways at once.
+ expect(stripDriveSlash('/C:/Users/me/a.png')).toBe('C:/Users/me/a.png')
+ expect(stripDriveSlash(String.raw`/C:\Users\me\a.png`)).toBe(String.raw`C:\Users\me\a.png`)
+ // A POSIX path must be untouched — stripping its leading slash would make it relative.
+ expect(stripDriveSlash('/home/me/a.png')).toBe('/home/me/a.png')
+ // Not a drive letter, so not stripped.
+ expect(stripDriveSlash('/CC:/x')).toBe('/CC:/x')
+ expect(stripDriveSlash('/1:/x')).toBe('/1:/x')
+ // No separator after the colon: not a drive root, leave it alone.
+ expect(stripDriveSlash('/C:x')).toBe('/C:x')
+ })
+
+ it('still refuses a path that is not on the allowlist', () => {
+ // The strip must not widen the jail: normalize + the allowlist check still decide.
+ const allow = new Set([n(WIN)])
+ const evil = mediaUrlFor(String.raw`C:\Users\me\..\..\Windows\System32\config\SAM`, '\\')
+ expect(resolveMediaPath(new URL(evil).pathname, allow)).toBeNull()
+ })
+
+ it('a segment with URL-reserved characters still round-trips', () => {
+ const url = new URL(mediaUrlFor(String.raw`C:\Users\me\a#b?c&d.png`, '\\'))
+ expect(decodeURIComponent(url.pathname)).toContain('a#b?c&d.png')
})
})
diff --git a/src/main/media-protocol.ts b/src/main/media-protocol.ts
index 33a0aa958..f31214a70 100644
--- a/src/main/media-protocol.ts
+++ b/src/main/media-protocol.ts
@@ -2,7 +2,7 @@
// Files are served ONLY if they are on the per-session allowlist (path jail), so the
// renderer/agent can never read an arbitrary local file. Supports HTTP Range so <video> seeks.
import { createReadStream, mkdirSync, writeFileSync, promises as fsp } from 'fs'
-import { normalize } from 'path'
+import { join, normalize, sep } from 'path'
import { app, protocol } from 'electron'
export const MEDIA_SCHEME = 'nt-media'
@@ -10,18 +10,48 @@ export const MEDIA_SCHEME = 'nt-media'
// Absolute paths the app has explicitly opened this session. Cleared only on quit.
const allowed = new Set<string>()
-/** Build the nt-media:// URL for an absolute path (path encoded as the URL pathname). */
-export function mediaUrlFor(absPath: string): string {
+/** Build the nt-media:// URL for an absolute path (path encoded as the URL pathname).
+ * `nativeSeparator` is injectable only so both host dialects are behavior-tested on one machine. */
+export function mediaUrlFor(absPath: string, nativeSeparator: '/' | '\\' = sep as '/' | '\\'): string {
// Encode each path segment individually so reserved chars (?, #, &) round-trip through
// the URL pathname (encodeURI leaves them, which would break the pathname match). The
// decode side (resolveMediaPath → decodeURIComponent) stays symmetric.
- const pathname = absPath
- .split('/')
- .map((seg) => encodeURIComponent(seg))
- .join('/')
+ //
+ // Split on the HOST'S separator. `allowMediaPath` hands us `normalize()`d output, which on win32
+ // is backslash-separated — so splitting on '/' alone produced ONE segment, encoded the
+ // backslashes to %5C, and emitted `nt-media://mediaC%3A%5CUsers%5C...`: no leading slash, so
+ // the drive letter was swallowed into the URL's authority and the pathname came out empty.
+ // Every image and video opened from a Windows path failed to load, with a 404 from the jail
+ // that looked exactly like a path that was never allowlisted.
+ //
+ // Do NOT split on both. On POSIX, `\` is legal filename text: `/tmp/a\b.png` names ONE file,
+ // not `/tmp/a/b.png`. Treating it as a separator made the URL point at a different path and the
+ // allowlist correctly rejected the app's own file.
+ const segments = absPath.split(nativeSeparator).map((seg) => encodeURIComponent(seg))
+ // A POSIX absolute path starts with '/', so its first segment is empty and the join already
+ // yields a leading slash. A Windows one starts with the drive letter, so it needs one added
+ // or `new URL()` reads it as the authority. resolveMediaPath strips it back off.
+ const joined = segments.join('/')
+ const pathname = joined.startsWith('/') ? joined : `/${joined}`
return `${MEDIA_SCHEME}://media${pathname}`
}
+/**
+ * Undo the leading slash `mediaUrlFor` puts in front of a Windows drive letter.
+ *
+ * `normalize('/C:/Users/...')` yields `\C:\Users\...` on win32 — not the string that was
+ * allowlisted, so the jail would reject the app's own file. Only a drive-letter prefix is
+ * stripped, and `normalize` plus the allowlist check still run on the result, so this cannot
+ * widen what is reachable: a traversal still has to normalize to a path that is in `allow`.
+ *
+ * Exported so its test exercises THIS function rather than a copy of the regex. The first
+ * version of that test held its own copy, the copy's escaping was wrong, and it asserted on a
+ * string that could never occur — a duplicated pattern proves nothing about the original.
+ */
+export function stripDriveSlash(p: string): string {
+ return /^\/[A-Za-z]:[\\/]/.test(p) ? p.slice(1) : p
+}
+
/**
* Pure jail check: decode the request pathname, normalize it, and return it only if the
* normalized absolute path is on `allow`. Returns null otherwise (unknown path or traversal
@@ -34,7 +64,7 @@ export function resolveMediaPath(requestPath: string, allow: ReadonlySet<string>
} catch {
return null
}
- const norm = normalize(p)
+ const norm = normalize(stripDriveSlash(p))
return allow.has(norm) ? norm : null
}
@@ -52,7 +82,11 @@ export function allowMediaPath(absPath: string): string {
/** The per-session directory holding agent-authored HTML (served under a restrictive CSP). */
function agentWebDir(): string {
- return `${app.getPath('userData')}/agent-web`
+ // path.join (not a manual `/` template) — on win32 this must come out backslash-normalized,
+ // the same as `abs` below (resolveMediaPath's `normalize()` output), or the isAgentHtml
+ // startsWith check never matches on Windows and every agent-authored HTML file is served
+ // WITHOUT the restrictive CSP that keeps it from exfiltrating or reading sibling files.
+ return join(app.getPath('userData'), 'agent-web')
}
// Restrictive CSP for agent-authored HTML: render + inline scripts/styles/media, but NO
@@ -70,7 +104,7 @@ const agentHtmlPaths: string[] = []
export function writeAgentHtml(html: string): string {
const d = agentWebDir()
mkdirSync(d, { recursive: true })
- const p = `${d}/${Date.now().toString(36)}-${++htmlSeq}.html`
+ const p = join(d, `${Date.now().toString(36)}-${++htmlSeq}.html`)
writeFileSync(p, html, { encoding: 'utf8', mode: 0o600 })
allowMediaPath(p)
agentHtmlPaths.push(p)
@@ -88,7 +122,7 @@ async function pruneStaleAgentHtml(): Promise<void> {
const d = agentWebDir()
try {
for (const f of await fsp.readdir(d)) {
- if (f.endsWith('.html')) await fsp.rm(`${d}/${f}`, { force: true })
+ if (f.endsWith('.html')) await fsp.rm(join(d, f), { force: true })
}
} catch {
// dir may not exist yet
@@ -128,7 +162,7 @@ export function initMediaProtocol(): void {
return new Response('Not found', { status: 404 })
}
// Agent-authored HTML gets a restrictive CSP; video/image files get none (unchanged).
- const isAgentHtml = abs.startsWith(agentWebDir() + '/')
+ const isAgentHtml = abs.startsWith(agentWebDir() + sep)
const range = req.headers.get('range')
const m = range && /bytes=(\d*)-(\d*)/.exec(range)
if (m) {
diff --git a/src/main/remote-atomic-write.test.ts b/src/main/remote-atomic-write.test.ts
new file mode 100644
index 000000000..6890cb997
--- /dev/null
+++ b/src/main/remote-atomic-write.test.ts
@@ -0,0 +1,200 @@
+import { execFileSync, spawn, spawnSync, type ChildProcessWithoutNullStreams } from 'child_process'
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'fs'
+import os from 'os'
+import path from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { quoteRemotePath } from '../shared/ssh'
+import { remoteAtomicWrite } from './remote-atomic-write'
+
+const SHELL =
+ process.platform === 'win32'
+ ? ['C:\\Program Files\\Git\\bin\\sh.exe', 'C:\\Program Files\\Git\\usr\\bin\\sh.exe'].find(existsSync)
+ : existsSync('/bin/sh')
+ ? '/bin/sh'
+ : undefined
+
+const roots: string[] = []
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
+})
+
+function shellPath(nativePath: string): string {
+ if (process.platform !== 'win32') return nativePath
+ return execFileSync(SHELL!, ['-c', 'cygpath -u "$1"', 'nodeterm-test', nativePath], {
+ encoding: 'utf8'
+ }).trim()
+}
+
+function finish(child: ChildProcessWithoutNullStreams): Promise<{ code: number | null; stderr: string }> {
+ let stderr = ''
+ child.stderr.setEncoding('utf8')
+ child.stderr.on('data', (chunk: string) => { stderr += chunk })
+ return new Promise((resolve, reject) => {
+ child.once('error', reject)
+ child.once('close', (code) => resolve({ code, stderr }))
+ })
+}
+
+async function waitForTemp(directory: string): Promise<void> {
+ const until = Date.now() + 5_000
+ while (Date.now() < until) {
+ if (readdirSync(directory).some((name) => name.endsWith('.tmp'))) return
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+ throw new Error('writer never opened its temporary file')
+}
+
+describe('remoteAtomicWrite', () => {
+ it('mints a shell-safe, per-call UUID temp and cleans only that temp after publishing', () => {
+ const first = remoteAtomicWrite("~/a b/quo'te\\name.json", {
+ restrictPermissions: true,
+ chmod600: true
+ })
+ const second = remoteAtomicWrite("~/a b/quo'te\\name.json", {
+ restrictPermissions: true,
+ chmod600: true
+ })
+
+ expect(first.temporaryPath).toMatch(/^~\/a b\/\.nodeterm-[0-9a-f-]{36}\.tmp$/)
+ expect(second.temporaryPath).not.toBe(first.temporaryPath)
+ expect(first.command).toContain('umask 077; mkdir -p -- ~/' + "'a b'")
+ expect(first.command).toContain(`cat > ${quoteRemotePath(first.temporaryPath)}`)
+ expect(first.command).toContain(`chmod 600 -- ${quoteRemotePath(first.temporaryPath)}`)
+ expect(first.command).toContain(`mv -f -- ${quoteRemotePath(first.temporaryPath)} ${quoteRemotePath("~/a b/quo'te\\name.json")}`)
+ expect(first.command).toContain(`rm -f -- ${quoteRemotePath(first.temporaryPath)}`)
+ expect(first.command).toContain('exit "$nt_status"')
+ })
+
+ it.skipIf(!SHELL)('quotes spaces and apostrophes correctly when executed by a real POSIX shell', () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-atomic-'))
+ roots.push(root)
+ const nativeTarget = path.join(root, "space and 'quote.txt")
+ const target = `${shellPath(root)}/space and 'quote.txt`
+ const write = remoteAtomicWrite(target, { restrictPermissions: true })
+
+ execFileSync(SHELL!, ['-c', write.command], { input: 'payload', stdio: ['pipe', 'pipe', 'pipe'] })
+
+ expect(readFileSync(nativeTarget, 'utf8')).toBe('payload')
+ expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])
+ })
+
+ it.skipIf(!SHELL)('keeps the sibling temp bounded for a valid long target leaf', () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-ra-'))
+ roots.push(root)
+ // 220 bytes is valid under the usual NAME_MAX=255, while the old `<leaf>.<uuid>.tmp` shape was
+ // 261 bytes and failed before cat could write anything.
+ const leaf = `${'x'.repeat(215)}.json`
+ const nativeTarget = path.join(root, leaf)
+ const target = `${shellPath(root)}/${leaf}`
+ const write = remoteAtomicWrite(target)
+
+ execFileSync(SHELL!, ['-c', write.command], {
+ input: 'long-name',
+ stdio: ['pipe', 'pipe', 'pipe']
+ })
+
+ expect(readFileSync(nativeTarget, 'utf8')).toBe('long-name')
+ expect(path.basename(write.temporaryPath)).toMatch(/^\.nodeterm-[0-9a-f-]{36}\.tmp$/)
+ expect(readdirSync(root)).toEqual([leaf])
+ })
+
+ it.skipIf(!SHELL || process.platform === 'win32')(
+ 'keeps a POSIX backslash as filename text when executed by a real shell',
+ () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-backslash-'))
+ roots.push(root)
+ const leaf = "space and 'quote\\name.txt"
+ const write = remoteAtomicWrite(`${root}/${leaf}`)
+
+ execFileSync(SHELL!, ['-c', write.command], { input: 'literal', stdio: ['pipe', 'pipe', 'pipe'] })
+
+ expect(readFileSync(path.join(root, leaf), 'utf8')).toBe('literal')
+ expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])
+ }
+ )
+
+ it.skipIf(!SHELL || process.platform === 'win32')(
+ 'publishes a credential temp as mode 0600 under a real shell',
+ () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-private-'))
+ roots.push(root)
+ const target = path.join(root, 'token')
+ const write = remoteAtomicWrite(target, {
+ restrictPermissions: true,
+ chmod600: true
+ })
+
+ execFileSync(SHELL!, ['-c', write.command], {
+ input: 'credential',
+ stdio: ['pipe', 'pipe', 'pipe']
+ })
+
+ expect(statSync(target).mode & 0o777).toBe(0o600)
+ }
+ )
+
+ it.skipIf(!SHELL)('removes its own temp and preserves the failing publish status', () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-failure-'))
+ roots.push(root)
+ const target = `${shellPath(root)}/state.json`
+ const write = remoteAtomicWrite(target, {
+ restrictPermissions: true,
+ chmod600: true
+ })
+ const nativeTarget = path.join(root, 'state.json')
+ execFileSync(SHELL!, ['-c', `printf %s old > ${quoteRemotePath(target)}`])
+ const result = spawnSync(SHELL!, ['-c', `mv() { return 23; }\n${write.command}`], {
+ input: 'not-published',
+ encoding: 'utf8'
+ })
+
+ expect(result.status).toBe(23)
+ expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])
+ expect(readFileSync(nativeTarget, 'utf8')).toBe('old')
+ })
+
+ it.skipIf(!SHELL)('uses option terminators for a relative path beginning with a dash', () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-option-'))
+ roots.push(root)
+ const write = remoteAtomicWrite('--target-directory=elsewhere', {
+ restrictPermissions: true,
+ chmod600: true
+ })
+
+ execFileSync(SHELL!, ['-c', write.command], {
+ cwd: root,
+ input: 'literal-name',
+ stdio: ['pipe', 'pipe', 'pipe']
+ })
+
+ expect(readFileSync(path.join(root, '--target-directory=elsewhere'), 'utf8')).toBe(
+ 'literal-name'
+ )
+ expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])
+ })
+
+ it.skipIf(!SHELL)('keeps overlapping real-shell writers on separate temps', async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-overlap-'))
+ roots.push(root)
+ const nativeTarget = path.join(root, 'state.json')
+ const target = `${shellPath(root)}/state.json`
+
+ const privateWrite = () =>
+ remoteAtomicWrite(target, { restrictPermissions: true, chmod600: true }).command
+ const first = spawn(SHELL!, ['-c', privateWrite()], { stdio: 'pipe' })
+ const firstDone = finish(first)
+ first.stdin.write('first-')
+ await waitForTemp(root)
+
+ const second = spawn(SHELL!, ['-c', privateWrite()], { stdio: 'pipe' })
+ const secondDone = finish(second)
+ second.stdin.end('second')
+ expect(await secondDone).toEqual({ code: 0, stderr: '' })
+
+ first.stdin.end('wins')
+ expect(await firstDone).toEqual({ code: 0, stderr: '' })
+ expect(readFileSync(nativeTarget, 'utf8')).toBe('first-wins')
+ expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])
+ })
+})
diff --git a/src/main/remote-atomic-write.ts b/src/main/remote-atomic-write.ts
new file mode 100644
index 000000000..3ac52016c
--- /dev/null
+++ b/src/main/remote-atomic-write.ts
@@ -0,0 +1,64 @@
+import { randomUUID } from 'crypto'
+import { quoteRemotePath } from '../shared/ssh'
+
+export interface RemoteAtomicWrite {
+ command: string
+ temporaryPath: string
+}
+
+export interface RemoteAtomicWriteOptions {
+ /** Apply umask 077 before creating either the parent or the temp. */
+ restrictPermissions?: boolean
+ /** Belt-and-braces for credential files: enforce 0600 on the temp before it is published. */
+ chmod600?: boolean
+ /** False when the caller already created and permissioned the parent directory. */
+ makeParent?: boolean
+}
+
+function remoteDirname(path: string): string {
+ const end = path.replace(/\/+$/, '')
+ const slash = end.lastIndexOf('/')
+ if (slash < 0) return '.'
+ if (slash === 0) return '/'
+ return end.slice(0, slash)
+}
+
+/**
+ * Build the remote-shell half of a stdin → sibling-temp → rename write.
+ *
+ * The UUID is minted locally for every call. A fixed `<target>.tmp` lets overlapping SSH clients
+ * share one inode: one rename can publish the other writer's partial bytes, then the loser cannot
+ * find the temp it still intends to rename. The nonce contains only shell-inert ASCII, while the
+ * complete paths still go through quoteRemotePath so spaces, apostrophes, literal backslashes and
+ * a leading `~/` keep their existing meanings.
+ *
+ * The cleanup preserves the write/move status. Unique temps do not self-heal on the next write,
+ * so a normal cat/mv failure must remove the exact temp this invocation owns.
+ */
+export function remoteAtomicWrite(
+ path: string,
+ options: RemoteAtomicWriteOptions = {}
+): RemoteAtomicWrite {
+ const parentPath = remoteDirname(path)
+ const temporaryLeaf = `.nodeterm-${randomUUID()}.tmp`
+ // Keep the temp beside the target so mv remains one-filesystem atomic, but do not extend the
+ // target leaf: a valid NAME_MAX-length filename plus `.UUID.tmp` cannot be created at all.
+ const temporaryPath =
+ parentPath === '/'
+ ? `/${temporaryLeaf}`
+ : parentPath === '.'
+ ? temporaryLeaf
+ : `${parentPath}/${temporaryLeaf}`
+ const target = quoteRemotePath(path)
+ const temporary = quoteRemotePath(temporaryPath)
+ const prefix = options.restrictPermissions ? 'umask 077; ' : ''
+ const parent = options.makeParent === false
+ ? ''
+ : `mkdir -p -- ${quoteRemotePath(parentPath)} && `
+ const protect = options.chmod600 ? ` && chmod 600 -- ${temporary}` : ''
+ const command =
+ `${prefix}${parent}{ cat > ${temporary}${protect} && mv -f -- ${temporary} ${target}; ` +
+ `nt_status=$?; ` +
+ `rm -f -- ${temporary}; exit "$nt_status"; }`
+ return { command, temporaryPath }
+}
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 81cd5a8a7..31fee9b13 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -15,6 +15,8 @@ function harness(
responses?: Record<string, string>
/** Command substring whose run REJECTS — the fail-open proof for one remote step. */
failOn?: string
+ /** Command substring whose runner result is non-zero (the runner itself still resolves). */
+ failCodeOn?: string
} = {}
) {
// One record per ssh child command. `args` is what the runner was handed; `cmd` is the joined
@@ -26,6 +28,7 @@ function harness(
const joined = args.join(' ')
calls.push({ args, stdin, cmd: joined })
if (opts.failOn && joined.includes(opts.failOn)) throw new Error(`fake ssh failed: ${opts.failOn}`)
+ if (opts.failCodeOn && joined.includes(opts.failCodeOn)) return { code: 1, stdout: '' }
for (const [needle, stdout] of Object.entries(opts.responses ?? {})) {
if (joined.includes(needle)) return { code: 0, stdout }
}
@@ -51,8 +54,17 @@ describe('RemoteHooks.setup', () => {
const joined = calls.map((c) => c.args.join(' '))
// reverse forward binds the ABSOLUTE remote socket (no unexpanded ~).
expect(joined.some((j) => j.includes('-O forward') && j.includes('/home/u/.nodeterm/hook-p1.sock:127.0.0.1:51234'))).toBe(true)
- // endpoint file written to the absolute PER-PROJECT path, with the absolute sock + token.
- expect(joined.some((j) => j.includes(`cat > '/home/u/.nodeterm/hook-endpoint-p1.env'`))).toBe(true)
+ // Endpoint bearer goes to a private, invocation-owned temp and is then published atomically.
+ const endpointWrite = calls.find((c) => (c.stdin ?? '').includes('NODETERM_HOOK_TOKEN=tok'))
+ const endpointTemp = endpointWrite?.cmd.match(
+ /cat > ('\/home\/u\/\.nodeterm\/\.nodeterm-[0-9a-f-]{36}\.tmp')/
+ )?.[1]
+ expect(endpointTemp).toBeTruthy()
+ expect(endpointWrite?.cmd).toContain(`chmod 600 -- ${endpointTemp}`)
+ expect(endpointWrite?.cmd).toContain(
+ `mv -f -- ${endpointTemp} '/home/u/.nodeterm/hook-endpoint-p1.env'`
+ )
+ expect(endpointWrite?.cmd).toContain(`rm -f -- ${endpointTemp}`)
expect(
calls.some(
(c) =>
@@ -163,6 +175,18 @@ describe('RemoteHooks.setup', () => {
expect(calls.map((c) => c.args.join(' ')).some((j) => j.includes('hook-endpoint-p1.env'))).toBe(false)
})
+ it('does not advertise an endpoint whose atomic credential publish returns non-zero', async () => {
+ const { rh, calls } = harness({ failCodeOn: 'hook-endpoint-p1.env' })
+ const res = await rh.setup('p1', conn, '/s.sock', {
+ port: 51234,
+ token: 'tok',
+ version: '1'
+ })
+ expect(res).toBeNull()
+ // A resolved failure is still failure; hook configs must not point sessions at stale bytes.
+ expect(calls.some((c) => c.cmd.includes('/agent-hooks/'))).toBe(false)
+ })
+
it('a failed -O forward bind is retried, never trusted', async () => {
const calls: { args: string[] }[] = []
let forwards = 0
@@ -189,7 +213,11 @@ describe('RemoteHooks.setup', () => {
expect(b?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-ssh-browse-xyz.env')
// the browse writes ITS OWN endpoint file, never the real project's.
const joined = calls.map((c) => c.args.join(' '))
- expect(joined.some((j) => j.includes(`cat > '/home/u/.nodeterm/hook-endpoint-ssh-browse-xyz.env'`))).toBe(true)
+ expect(
+ joined.some(
+ (j) => j.includes('cat > ') && j.includes("hook-endpoint-ssh-browse-xyz.env'")
+ )
+ ).toBe(true)
expect(joined.some((j) => j.includes('hook-endpoint-proj.env'))).toBe(false)
})
})
@@ -220,7 +248,11 @@ describe('RemoteHooks.setup — a hostile remote $HOME', () => {
expect(res?.endpointPath).toBe('/Users/Enes K/.nodeterm/hook-endpoint-p1.env')
const joined = runs.map((r) => r.cmd)
expect(joined.some((j) => j.includes(`mkdir -p '/Users/Enes K/.nodeterm'`))).toBe(true)
- expect(joined.some((j) => j.includes(`cat > '/Users/Enes K/.nodeterm/hook-endpoint-p1.env'`))).toBe(true)
+ expect(
+ joined.some(
+ (j) => j.includes('cat > ') && j.includes("/Users/Enes K/.nodeterm/hook-endpoint-p1.env'")
+ )
+ ).toBe(true)
expect(joined.some((j) => j.includes(`cat > '/Users/Enes K/.claude/settings.json'`))).toBe(true)
// No path derived from $HOME survives UNQUOTED in any remote SHELL LINE (the last argv element
// of an ssh child is the command the remote shell parses; the `-R` forward spec is an ssh
@@ -677,10 +709,18 @@ describe('RemoteHooks.writeNodeTokens', () => {
}
const writes = calls.filter((c) => c.cmd.includes('cat >'))
expect(writes).toHaveLength(2)
- // tmp + rename, the local writer's shape: `cat >` truncates, so writing straight at the file
- // leaves an EMPTY token behind when the host is out of quota or disk.
- expect(writes[0].cmd).toContain("cat > '/home/u/.nodeterm/node-tokens/.node-1.tmp'")
- expect(writes[0].cmd).toContain("mv -f '/home/u/.nodeterm/node-tokens/.node-1.tmp' '/home/u/.nodeterm/node-tokens/node-1'")
+ // Unique tmp + rename: `cat >` truncates, so writing straight at the file leaves an EMPTY
+ // credential behind when the host is out of quota or disk. The same owned temp is chmodded,
+ // published and cleaned without ever carrying the token in argv.
+ const temp = writes[0].cmd.match(
+ /cat > ('\/home\/u\/\.nodeterm\/node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp')/
+ )?.[1]
+ expect(temp).toBeTruthy()
+ expect(writes[0].cmd).toContain(`chmod 600 -- ${temp}`)
+ expect(writes[0].cmd).toContain(
+ `mv -f -- ${temp} '/home/u/.nodeterm/node-tokens/node-1'`
+ )
+ expect(writes[0].cmd).toContain(`rm -f -- ${temp}`)
// ...and the token is on stdin, newline-terminated (the client reads it with `head -n 1`).
expect(writes[0].stdin).toBe(`${mint('node-1')}\n`)
expect(writes.at(-1)?.stdin).toBe(`${mint('node-2')}\n`)
@@ -695,6 +735,24 @@ describe('RemoteHooks.writeNodeTokens', () => {
for (const w of calls.filter((c) => c.cmd.includes('cat >'))) expect(w.cmd).toContain('umask 077')
})
+ it('gives concurrent writers of the same credential separate owned temps', async () => {
+ const { rh, calls } = tokenHarness()
+ await Promise.all([
+ rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint),
+ rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)
+ ])
+ const temps = calls
+ .filter((call) => call.cmd.includes('cat >'))
+ .map((call) =>
+ call.cmd.match(
+ /cat > ('\/home\/u\/\.nodeterm\/node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp')/
+ )?.[1]
+ )
+ expect(temps).toHaveLength(2)
+ expect(temps.every(Boolean)).toBe(true)
+ expect(temps[0]).not.toBe(temps[1])
+ })
+
it('fails open when the host refuses (exit 1) — the connect is never at risk', async () => {
const { rh, calls } = tokenHarness({ code: 1 })
await expect(
@@ -800,8 +858,8 @@ describe('RemoteHooks.writeNodeTokens', () => {
const refusing = (id: string): string => (id === 'Node-1' ? '' : mint(id))
await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['Node-1', 'node-2'], refusing)
expect(calls.some((c) => c.cmd.includes("rm -f '/home/u/.nodeterm/node-tokens/Node-1'"))).toBe(true)
- expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/.Node-1.tmp'"))).toBe(false)
- expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/.node-2.tmp'"))).toBe(true)
+ expect(calls.some((c) => /cat > .*node-tokens\/Node-1\./.test(c.cmd))).toBe(false)
+ expect(calls.some((c) => /cat > .*node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp/.test(c.cmd))).toBe(true)
})
})
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index 6792dd4d5..80d58d34f 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -10,6 +10,7 @@ import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, GROK_HOOK_EVENTS } from '@share
import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'
import { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'
import { hookServer } from '../../core/agents/hook-server'
+import { remoteAtomicWrite } from '../remote-atomic-write'
import { curlHeaderConfigLine } from '../../core/agents/hook-curl-config-sh'
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
import {
@@ -180,12 +181,20 @@ export class RemoteHooks {
return null
}
this.specs.set(projectId, { sock, port: hook.port })
- // 2. remote endpoint file (0600 via umask) — written only after the tunnel proved live,
- // so sessions are never pointed at a socket that answers nothing.
- await this.r.run(
- childArgs(conn, controlPath, `umask 077; cat > ${posixQuote(endpoint)}`),
+ // 2. Remote endpoint file — written only after the tunnel proved live, so sessions are
+ // never pointed at a socket that answers nothing. The file carries the hook bearer. A
+ // direct `cat > endpoint` both exposed partial bytes and preserved an old permissive mode;
+ // publish a new 0600 inode through an invocation-owned temp instead.
+ const endpointWrite = remoteAtomicWrite(endpoint, {
+ restrictPermissions: true,
+ chmod600: true,
+ makeParent: false
+ })
+ const endpointResult = await this.r.run(
+ childArgs(conn, controlPath, endpointWrite.command),
remoteEndpointFileContents(sock, hook.token, hook.version, `${remoteDir}/node-tokens`)
)
+ if (endpointResult.code !== 0) return null
// 3. install the managed hook for each JSON agent (script + merged config).
for (const t of AGENT_TARGETS) {
const script = `${remoteDir}/agent-hooks/${t.agentId}.sh`
@@ -303,24 +312,24 @@ export class RemoteHooks {
)
if (mk.code !== 0) return // no dir ⇒ no files; the nodes stay `legacy`
for (const { id, token } of writes) {
- const file = posixQuote(`${dir}/${id}`)
+ const filePath = `${dir}/${id}`
// TMP + RENAME, the same shape the local writer uses, and for a reason that is not
// cosmetic: `cat > <file>` TRUNCATES before the write can fail, so a host that is out of
// quota or disk left the node holding an EMPTY token file. An empty header reads as
// `legacy`, and a node still latched at the desktop then takes a hard 403 on every
// canvas-control call for the rest of the session. Writing beside the file and renaming
// means a failure costs the node nothing it already had.
- const tmp = posixQuote(`${dir}/.${id}.tmp`)
let wrote = false
try {
// chmod on the TMP, so the mode is right before the name exists; `mv` within one dir is
// a rename, which carries the tmp's 0600 over whatever the destination's mode was.
+ const write = remoteAtomicWrite(filePath, {
+ restrictPermissions: true,
+ chmod600: true,
+ makeParent: false
+ })
const w = await this.r.run(
- childArgs(
- conn,
- controlPath,
- `umask 077; cat > ${tmp} && chmod 600 ${tmp} && mv -f ${tmp} ${file} || { rm -f ${tmp}; exit 1; }`
- ),
+ childArgs(conn, controlPath, write.command),
`${token}\n` // newline-terminated: the client reads it with `head -n 1`
)
// The runner RESOLVES on a non-zero exit — a failed write is a `code`, not a throw, and
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 5c5fbe32b..16a863f9b 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -69,17 +69,47 @@ describe('SshProjectManager', () => {
it('writePendingAnswer writes the answer file over the master (atomic tmp+mv, decision on stdin)', async () => {
const { mgr, run } = makeMgr()
await mgr.connect('p1', conn)
- const ok = await mgr.writePendingAnswer('p1', 'node-1-2', 'allow')
- expect(ok).toBe(true)
- const call = run.mock.calls.find((c) => (c[0] as string[]).join(' ').includes('.answer'))
- expect(call).toBeTruthy()
- const cmd = (call![0] as string[]).join(' ')
- expect(cmd).toContain('umask 077')
- expect(cmd).toContain('.nodeterm/pending')
- // atomic tmp+mv: write to <id>.answer.tmp then rename onto <id>.answer.
- expect(cmd).toMatch(/cat > [\s\S]*\.answer\.tmp/)
- expect(cmd).toMatch(/mv -f [\s\S]*\.answer\.tmp[\s\S]*\.answer/)
- expect(call![1]).toBe('allow') // decision written on stdin
+ const before = run.mock.calls.length
+ expect(await Promise.all([
+ mgr.writePendingAnswer('p1', 'node-1-2', 'allow'),
+ mgr.writePendingAnswer('p1', 'node-1-2', 'deny')
+ ])).toEqual([true, true])
+ const calls = run.mock.calls.slice(before).filter((c) => (c[0] as string[]).join(' ').includes('.answer'))
+ expect(calls).toHaveLength(2)
+ const commands = calls.map((call) => (call[0] as string[]).join(' '))
+ const temps = commands.map((cmd) => cmd.match(/cat > (\S*\.nodeterm-[0-9a-f-]{36}\.tmp')/)?.[1])
+ expect(temps[0]).toBeTruthy()
+ expect(temps[1]).toBeTruthy()
+ expect(temps[0]).not.toBe(temps[1])
+ for (let i = 0; i < commands.length; i++) {
+ expect(commands[i]).toContain('umask 077')
+ expect(commands[i]).toContain('.nodeterm/pending')
+ expect(commands[i]).toContain(`mv -f -- ${temps[i]} ~/'${'/.nodeterm/pending/node-1-2.answer'.slice(1)}'`)
+ expect(commands[i]).toContain(`rm -f -- ${temps[i]}`)
+ }
+ expect(calls.map((call) => call[1])).toEqual(['allow', 'deny']) // decisions stay on stdin
+ })
+
+ it('pushAgentStatus gives overlapping pushes separate temps and preserves private permissions', async () => {
+ const { mgr, run } = makeMgr()
+ await mgr.connect('p1', conn)
+ const before = run.mock.calls.length
+ await Promise.all([
+ mgr.pushAgentStatus('p1', '{"writer":1}'),
+ mgr.pushAgentStatus('p1', '{"writer":2}')
+ ])
+ const writes = run.mock.calls.slice(before).filter((call) => call[1]?.toString().includes('writer'))
+ expect(writes).toHaveLength(2)
+ const commands = writes.map((call) => (call[0] as string[]).at(-1)!)
+ const temps = commands.map((command) => command.match(/cat > (\S*\.nodeterm-[0-9a-f-]{36}\.tmp')/)?.[1])
+ expect(temps[0]).toBeTruthy()
+ expect(temps[1]).toBeTruthy()
+ expect(temps[0]).not.toBe(temps[1])
+ for (let i = 0; i < commands.length; i++) {
+ expect(commands[i]).toContain('umask 077')
+ expect(commands[i]).toContain(`mv -f -- ${temps[i]} ~/'${'/.nodeterm/agent-status-p1.json'.slice(1)}'`)
+ expect(commands[i]).toContain(`rm -f -- ${temps[i]}`)
+ }
})
it('writePendingAnswer refuses an invalid pendingId and a disconnected project (no run)', async () => {
@@ -113,9 +143,10 @@ describe('SshProjectManager', () => {
})
await mgr.connect('p1', conn, '/srv/repo')
const out = await mgr.uploadFile('p1', '/local/img.png', 'img.png')
- expect(out).toMatch(/^\/home\/u\/\.nodeterm\/uploads\/[a-z0-9]+\/img\.png$/)
+ expect(out).toMatch(/^\/home\/u\/\.nodeterm\/uploads\/[0-9a-f-]{36}\/img\.png$/)
// scp targeted that exact absolute remote path (conn is { host: 'h', user: 'u' }).
expect(scpCalls[0].join(' ')).toContain(`u@h:${out}`)
+ expect(run.mock.calls.some((call) => (call[0] as string[]).at(-1)?.startsWith('rm -rf -- '))).toBe(false)
})
it('uploadFile basenames a traversal fileName so it cannot escape the token dir', async () => {
@@ -138,11 +169,108 @@ describe('SshProjectManager', () => {
await mgr.connect('p1', conn, '/srv/repo')
// basename('../../evil') === 'evil' → sanitized to <dir>/evil; never escapes the token dir.
const out = await mgr.uploadFile('p1', '/local/evil', '../../evil')
- expect(out).toMatch(/^\/home\/u\/\.nodeterm\/uploads\/[a-z0-9]+\/evil$/)
+ expect(out).toMatch(/^\/home\/u\/\.nodeterm\/uploads\/[0-9a-f-]{36}\/evil$/)
expect(out).not.toContain('..')
expect(scpCalls[0].join(' ')).toContain(`u@h:${out}`)
})
+ it('uploadFile gives separate manager processes distinct remote staging directories', async () => {
+ const scpCalls: string[][] = []
+ const run = vi.fn(async (args: string[]) =>
+ args.join(' ').includes('printf %s')
+ ? { code: 0, stdout: '/home/u' }
+ : { code: 0, stdout: '' }
+ )
+ const runners = () => ({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async (args: string[]) => {
+ scpCalls.push(args)
+ return { code: 0 }
+ }),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const first = new SshProjectManager(runners())
+ const second = new SshProjectManager(runners())
+ await Promise.all([first.connect('p1', conn), second.connect('p1', conn)])
+
+ const now = vi.spyOn(Date, 'now').mockReturnValue(123456789)
+ try {
+ const outputs = await Promise.all([
+ first.uploadFile('p1', '/local/a.png', 'same.png'),
+ second.uploadFile('p1', '/local/b.png', 'same.png')
+ ])
+ expect(outputs[0]).toMatch(/\/uploads\/[0-9a-f-]{36}\/same\.png$/)
+ expect(outputs[1]).toMatch(/\/uploads\/[0-9a-f-]{36}\/same\.png$/)
+ expect(outputs[0]).not.toBe(outputs[1])
+ expect(new Set(scpCalls.map((args) => args.at(-1))).size).toBe(2)
+ } finally {
+ now.mockRestore()
+ }
+ })
+
+ it('uploadFile cleans only its quoted staging directory when scp fails', async () => {
+ const commands: string[] = []
+ const run = vi.fn(async (args: string[]) => {
+ const command = args.at(-1) ?? ''
+ commands.push(command)
+ return command.includes('printf %s')
+ ? { code: 0, stdout: "/Users/O'Brien Home" }
+ : { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 1 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn)
+
+ expect(await mgr.uploadFile('p1', '/local/a.png', 'same.png')).toBeNull()
+ const cleanup = commands.find((command) => command.startsWith('rm -rf -- '))
+ expect(cleanup).toMatch(
+ /^rm -rf -- '\/Users\/O'\\''Brien Home\/\.nodeterm\/uploads\/[0-9a-f-]{36}'$/
+ )
+ })
+
+ it('uploadFile attempts owned-stage cleanup when mkdir itself returns non-zero', async () => {
+ const commands: string[] = []
+ const run = vi.fn(async (args: string[]) => {
+ const command = args.at(-1) ?? ''
+ commands.push(command)
+ if (command.includes('printf %s')) return { code: 0, stdout: '/home/u' }
+ if (command.includes('/.nodeterm/uploads/') && command.startsWith('mkdir -p')) {
+ return { code: 1, stdout: '' }
+ }
+ return { code: 0, stdout: '' }
+ })
+ const runScp = vi.fn(async () => ({ code: 0 }))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn)
+
+ expect(await mgr.uploadFile('p1', '/local/a.png', 'same.png')).toBeNull()
+ expect(runScp).not.toHaveBeenCalled()
+ const mkdir = commands.find(
+ (command) => command.startsWith('mkdir -p') && command.includes('/.nodeterm/uploads/')
+ )
+ const cleanup = commands.find(
+ (command) => command.startsWith('rm -rf -- ') && command.includes('/.nodeterm/uploads/')
+ )
+ expect(mkdir).toBeTruthy()
+ expect(cleanup?.slice('rm -rf -- '.length)).toBe(mkdir?.slice('mkdir -p '.length))
+ })
+
it('connect writes + source-files the remote tmux.conf and returns its absolute path', async () => {
const calls: { args: string[]; stdin?: string }[] = []
const run = vi.fn(async (args: string[], stdin?: string) => {
@@ -161,10 +289,17 @@ describe('SshProjectManager', () => {
})
const { tmuxConfPath } = await mgr.connect('p1', conn)
expect(tmuxConfPath).toBe('/home/u/.nodeterm/tmux.conf')
- // The conf was written via `cat >` (with the conf body as stdin) and then source-file'd.
- const write = calls.find((c) => c.args.join(' ').includes(`cat > '/home/u/.nodeterm/tmux.conf'`))
+ // The conf was staged via a unique temp (body on stdin), atomically published, then sourced.
+ const write = calls.find((c) => c.args.join(' ').includes("/.nodeterm/tmux.conf'") && c.stdin)
expect(write).toBeDefined()
expect(write?.stdin).toContain('set -g mouse on')
+ const command = write?.args.at(-1) ?? ''
+ const temp = command.match(
+ /cat > ('\/home\/u\/\.nodeterm\/\.nodeterm-[0-9a-f-]{36}\.tmp')/
+ )?.[1]
+ expect(temp).toBeTruthy()
+ expect(command).toContain(`mv -f -- ${temp} '/home/u/.nodeterm/tmux.conf'`)
+ expect(command).toContain(`rm -f -- ${temp}`)
expect(calls.some((c) => c.args.join(' ').includes(`source-file '/home/u/.nodeterm/tmux.conf'`))).toBe(true)
})
@@ -456,18 +591,37 @@ describe('SshProjectManager', () => {
return { mgr, scpCalls, runScp }
}
- it('lands the file under its remote basename and stages through .part', async () => {
+ it('lands the file under its remote basename and stages through a per-call .part', async () => {
const { mgr, scpCalls } = makeDlMgr()
await mgr.connect('p1', conn, '/srv/repo')
const dir = await destDir()
const res = await mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
expect(res).toEqual({ ok: true, localPath: path.join(dir, 'notes.md'), dir: false })
expect(await fs.readFile(path.join(dir, 'notes.md'), 'utf8')).toBe('payload')
- // scp wrote to `<target>.part`, never straight to the final name.
- expect(scpCalls[0][scpCalls[0].length - 1]).toBe(path.join(dir, 'notes.md.part'))
+ // scp wrote to a cross-process UUID part, never straight to the final name.
+ expect(path.basename(scpCalls[0].at(-1)!)).toMatch(
+ /^\.nodeterm-scp-[0-9a-f-]{36}\.part$/
+ )
expect(await fs.readdir(dir)).toEqual(['notes.md'])
})
+ it('uses a fresh UUID stage when the same final name becomes free again', async () => {
+ const { mgr, scpCalls } = makeDlMgr()
+ await mgr.connect('p1', conn, '/srv/repo')
+ const dir = await destDir()
+ const first = await mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
+ expect(first.ok).toBe(true)
+ if (first.ok) await fs.rm(first.localPath)
+ const second = await mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
+ expect(second.ok).toBe(true)
+ expect(scpCalls).toHaveLength(2)
+ expect(scpCalls[0].at(-1)).not.toBe(scpCalls[1].at(-1))
+ expect(scpCalls.map((args) => path.basename(args.at(-1)!))).toEqual([
+ expect.stringMatching(/^\.nodeterm-scp-[0-9a-f-]{36}\.part$/),
+ expect.stringMatching(/^\.nodeterm-scp-[0-9a-f-]{36}\.part$/)
+ ])
+ })
+
it('never overwrites an existing file, it takes the next (n) name', async () => {
const { mgr } = makeDlMgr()
await mgr.connect('p1', conn, '/srv/repo')
@@ -478,6 +632,40 @@ describe('SshProjectManager', () => {
expect(await fs.readFile(path.join(dir, 'notes.md'), 'utf8')).toBe('mine')
})
+ it('treats a dangling symlink directory entry as occupied', async () => {
+ const { mgr } = makeDlMgr()
+ await mgr.connect('p1', conn, '/srv/repo')
+ const dir = await destDir()
+ const dangling = path.join(dir, 'notes.md')
+ if (process.platform === 'win32') {
+ // A junction needs no Developer Mode privilege. Create it while its target exists, then
+ // remove the target to leave the same dangling directory entry lstat must preserve.
+ const vanished = path.join(dir, 'vanished')
+ await fs.mkdir(vanished)
+ await fs.symlink(vanished, dangling, 'junction')
+ await fs.rm(vanished, { recursive: true })
+ } else {
+ await fs.symlink('vanished', dangling)
+ }
+
+ // Node on Windows may report a dangling junction as accessible even though POSIX access(2)
+ // follows the link and returns ENOENT. Force that production-host behavior so an lstat →
+ // access regression is discriminated on the Windows test host too.
+ const windowsAccess = process.platform === 'win32'
+ ? vi.spyOn(fs, 'access').mockRejectedValue(
+ Object.assign(new Error('dangling target'), { code: 'ENOENT' })
+ )
+ : undefined
+ try {
+ const res = await mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
+ expect(res).toMatchObject({ ok: true, localPath: path.join(dir, 'notes (2).md') })
+ expect((await fs.lstat(dangling)).isSymbolicLink()).toBe(true)
+ expect(await fs.readFile(path.join(dir, 'notes (2).md'), 'utf8')).toBe('payload')
+ } finally {
+ windowsAccess?.mockRestore()
+ }
+ })
+
it('passes -r for a remote directory (probed on the host, not taken from the renderer)', async () => {
const { mgr, scpCalls } = makeDlMgr(true)
await mgr.connect('p1', conn, '/srv/repo')
@@ -491,11 +679,277 @@ describe('SshProjectManager', () => {
const { mgr } = makeDlMgr(false, 1)
await mgr.connect('p1', conn, '/srv/repo')
const dir = await destDir()
- const res = await mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
- expect(res.ok).toBe(false)
- expect(await fs.readdir(dir)).toEqual([])
+ const rm = vi.spyOn(fs, 'rm')
+ try {
+ const res = await mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
+ expect(res.ok).toBe(false)
+ expect(await fs.readdir(dir)).toEqual([])
+ const partCleanup = rm.mock.calls.find(([target]) => String(target).endsWith('.part'))
+ expect(partCleanup?.[1]).toMatchObject({
+ recursive: true,
+ force: true,
+ maxRetries: 4,
+ retryDelay: 50
+ })
+ } finally {
+ rm.mockRestore()
+ }
+ })
+
+ it('treats an unreadable destination check as failure, never as permission to overwrite', async () => {
+ const { mgr, runScp } = makeDlMgr()
+ await mgr.connect('p1', conn, '/srv/repo')
+ const dir = await destDir()
+ const denied = vi
+ .spyOn(fs, 'lstat')
+ .mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }))
+ try {
+ const res = await mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
+ expect(res.ok).toBe(false)
+ expect(runScp).not.toHaveBeenCalled()
+ expect(await fs.readdir(dir)).toEqual([])
+ } finally {
+ denied.mockRestore()
+ }
})
+ it('overlapping downloads reserve distinct final names and publish whole files', async () => {
+ const dir = await destDir()
+ const scpTargets: string[] = []
+ let arrived = 0
+ let release!: () => void
+ const bothArrived = new Promise<void>((resolve) => { release = resolve })
+ const run = vi.fn(async (args: string[]) => ({
+ code: args.join(' ').includes('test -d') ? 1 : 0,
+ stdout: ''
+ }))
+ const runScp = vi.fn(async (args: string[]) => {
+ const target = args.at(-1)!
+ const body = ++arrived === 1 ? 'first' : 'second'
+ scpTargets.push(target)
+ if (arrived === 2) release()
+ await bothArrived
+ await fs.writeFile(target, body)
+ return { code: 0 }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+
+ const results = await Promise.all([
+ mgr.downloadFile('p1', '/srv/repo/notes.md', dir),
+ mgr.downloadFile('p1', '/srv/repo/notes.md', dir)
+ ])
+ expect(results.every((result) => result.ok)).toBe(true)
+ const localPaths = results.map((result) => result.ok ? result.localPath : '')
+ expect(new Set(localPaths).size).toBe(2)
+ expect(localPaths.map((file) => path.basename(file)).sort()).toEqual([
+ 'notes (2).md',
+ 'notes.md'
+ ])
+ expect(new Set(scpTargets).size).toBe(2)
+ expect((await Promise.all(localPaths.map((file) => fs.readFile(file, 'utf8')))).sort()).toEqual([
+ 'first',
+ 'second'
+ ])
+ expect((await fs.readdir(dir)).sort()).toEqual(['notes (2).md', 'notes.md'])
+ })
+
+ it('coordinates two spellings of the same destination directory', async () => {
+ const holder = await destDir()
+ const realDir = path.join(holder, 'real')
+ const aliasDir = path.join(holder, 'alias')
+ await fs.mkdir(realDir)
+ await fs.symlink(realDir, aliasDir, process.platform === 'win32' ? 'junction' : 'dir')
+ let arrived = 0
+ let release!: () => void
+ const bothArrived = new Promise<void>((resolve) => { release = resolve })
+ const runScp = vi.fn(async (args: string[]) => {
+ if (++arrived === 2) release()
+ await bothArrived
+ await fs.writeFile(args.at(-1)!, String(arrived))
+ return { code: 0 }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run: vi.fn(async (args: string[]) => ({
+ code: args.join(' ').includes('test -d') ? 1 : 0,
+ stdout: ''
+ })),
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+
+ const results = await Promise.all([
+ mgr.downloadFile('p1', '/srv/repo/notes.md', realDir),
+ mgr.downloadFile('p1', '/srv/repo/notes.md', aliasDir)
+ ])
+ expect(results.every((result) => result.ok)).toBe(true)
+ expect(
+ results.map((result) => result.ok ? path.basename(result.localPath) : '').sort()
+ ).toEqual(['notes (2).md', 'notes.md'])
+ expect((await fs.readdir(realDir)).sort()).toEqual(['notes (2).md', 'notes.md'])
+ })
+
+ it('overlapping media fetches use separate parts and publish one whole cached file', async () => {
+ const dir = await destDir()
+ const scpTargets: string[] = []
+ let arrived = 0
+ let release!: () => void
+ const bothArrived = new Promise<void>((resolve) => { release = resolve })
+ const run = vi.fn(async (args: string[]) => {
+ const command = args.at(-1) ?? ''
+ if (command.includes('printf %s')) return { code: 0, stdout: '/home/u' }
+ if (command.includes('test -d') || command.includes('wc -c')) {
+ return { code: 1, stdout: '' }
+ }
+ return { code: 0, stdout: '' }
+ })
+ const runScp = vi.fn(async (args: string[]) => {
+ const target = args.at(-1)!
+ const body = ++arrived === 1 ? 'AAAAA' : 'B'
+ scpTargets.push(target)
+ if (arrived === 2) release()
+ await bothArrived
+ await fs.writeFile(target, body)
+ return { code: 0 }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+
+ const results = await Promise.all([
+ mgr.cacheMediaFile('p1', '/srv/repo/demo.mp4', dir),
+ mgr.cacheMediaFile('p1', '/srv/repo/demo.mp4', dir)
+ ])
+ expect(results.every((result) => result.ok)).toBe(true)
+ expect(new Set(scpTargets).size).toBe(2)
+ expect(
+ scpTargets.every((target) =>
+ /^\.nodeterm-scp-[0-9a-f-]{36}\.part$/.test(path.basename(target))
+ )
+ ).toBe(true)
+ const localPath = results[0].ok ? results[0].localPath : ''
+ expect(results[1].ok && results[1].localPath).toBe(localPath)
+ expect(['AAAAA', 'B']).toContain(await fs.readFile(localPath, 'utf8'))
+ expect((await fs.readdir(dir)).filter((file) => file.endsWith('.part'))).toEqual([])
+ })
+
+ it('does not replace a cache entry when checking it fails for a reason other than absence', async () => {
+ const dir = await destDir()
+ const runScp = vi.fn(async () => ({ code: 0 }))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run: vi.fn(async (args: string[]) => {
+ const command = args.at(-1) ?? ''
+ if (command.includes('printf %s')) return { code: 0, stdout: '/home/u' }
+ if (command.includes('wc -c')) return { code: 0, stdout: '7' }
+ return { code: command.includes('test -d') ? 1 : 0, stdout: '' }
+ }),
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+ const denied = vi
+ .spyOn(fs, 'stat')
+ .mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }))
+ try {
+ expect(await mgr.cacheMediaFile('p1', '/srv/repo/demo.mp4', dir)).toMatchObject({
+ ok: false
+ })
+ expect(runScp).not.toHaveBeenCalled()
+ } finally {
+ denied.mockRestore()
+ }
+ })
+
+ it.skipIf(process.platform !== 'win32')(
+ 'coordinates Windows names that alias through a terminal dot',
+ async () => {
+ const dir = await destDir()
+ let arrived = 0
+ let release!: () => void
+ const bothArrived = new Promise<void>((resolve) => { release = resolve })
+ const runScp = vi.fn(async (args: string[]) => {
+ if (++arrived === 2) release()
+ await bothArrived
+ await fs.writeFile(args.at(-1)!, String(arrived))
+ return { code: 0 }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run: vi.fn(async (args: string[]) => ({
+ code: args.join(' ').includes('test -d') ? 1 : 0,
+ stdout: ''
+ })),
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+
+ const results = await Promise.all([
+ mgr.downloadFile('p1', '/srv/repo/foo', dir),
+ mgr.downloadFile('p1', '/srv/repo/foo.', dir)
+ ])
+ const names = results.map((result) => result.ok ? path.basename(result.localPath) : '')
+ expect(names.sort()).toEqual(['foo', 'foo (2)'])
+ }
+ )
+
+ it.skipIf(process.platform !== 'darwin')(
+ 'coordinates case aliases on the default macOS filesystem',
+ async () => {
+ const dir = await destDir()
+ let arrived = 0
+ let release!: () => void
+ const bothArrived = new Promise<void>((resolve) => { release = resolve })
+ const runScp = vi.fn(async (args: string[]) => {
+ if (++arrived === 2) release()
+ await bothArrived
+ await fs.writeFile(args.at(-1)!, String(arrived))
+ return { code: 0 }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run: vi.fn(async (args: string[]) => ({
+ code: args.join(' ').includes('test -d') ? 1 : 0,
+ stdout: ''
+ })),
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+
+ const results = await Promise.all([
+ mgr.downloadFile('p1', '/srv/repo/Foo', dir),
+ mgr.downloadFile('p1', '/srv/repo/foo', dir)
+ ])
+ const names = results.map((result) => result.ok ? path.basename(result.localPath) : '')
+ expect(new Set(names.map((name) => name.toLowerCase())).size).toBe(2)
+ }
+ )
+
it('refuses a remote path that names nothing downloadable, without invoking scp', async () => {
const { mgr, runScp } = makeDlMgr()
await mgr.connect('p1', conn, '/srv/repo')
@@ -534,6 +988,42 @@ describe('SshProjectManager', () => {
expect(scpCalls).toHaveLength(0) // scp never invoked for an unsafe localPath
})
+ it.skipIf(process.platform !== 'win32')(
+ 'uploadFile accepts absolute drive and UNC paths from the Windows host',
+ async () => {
+ const scpCalls: string[][] = []
+ const run = vi.fn(async (args: string[]) =>
+ args.join(' ').includes('printf %s')
+ ? { code: 0, stdout: '/home/u' }
+ : { code: 0, stdout: '' }
+ )
+ const runScp = vi.fn(async (args: string[]) => {
+ scpCalls.push(args)
+ return { code: 0 }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+
+ await expect(mgr.uploadFile('p1', 'C:\\drop\\drive.png', 'drive.png')).resolves.toMatch(
+ /\/drive\.png$/
+ )
+ await expect(
+ mgr.uploadFile('p1', '\\\\server\\share\\unc.png', 'unc.png')
+ ).resolves.toMatch(/\/unc\.png$/)
+ expect(scpCalls.map((args) => args.at(-2))).toEqual([
+ 'C:\\drop\\drive.png',
+ '\\\\server\\share\\unc.png'
+ ])
+ }
+ )
+
// --- leftover ControlMaster socket handling -----------------------------------------------
//
// A master socket FILE can outlive its process (app crash, `kill -9`, host sleep). ssh's
@@ -2059,8 +2549,8 @@ describe('SshProjectManager — per-node tokens on the host', () => {
const cmds = run.mock.calls.map(([a]) => (a as string[]).join(' '))
// tmp + rename (`cat >` truncates, so writing straight at the file leaves an EMPTY token
// behind when the host is out of quota or disk — see RemoteHooks.writeNodeTokens).
- expect(cmds.some((c) => c.includes("mv -f '/home/u/.nodeterm/node-tokens/.node-1.tmp' '/home/u/.nodeterm/node-tokens/node-1'"))).toBe(true)
- expect(cmds.some((c) => c.includes("mv -f '/home/u/.nodeterm/node-tokens/.node-2.tmp' '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
+ expect(cmds.some((c) => /mv -f -- .*node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp' '\/home\/u\/\.nodeterm\/node-tokens\/node-1'/.test(c))).toBe(true)
+ expect(cmds.some((c) => /mv -f -- .*node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp' '\/home\/u\/\.nodeterm\/node-tokens\/node-2'/.test(c))).toBe(true)
// never on a command line — the host's process table is readable by its other users.
expect(cmds.some((c) => c.includes('mac-of-node-1'))).toBe(false)
const write = run.mock.calls.find(([a]) =>
@@ -2103,7 +2593,7 @@ describe('SshProjectManager — per-node tokens on the host', () => {
run.mockClear()
await mgr.writeNodeTokenForNode(controlPath, 'node-9')
const cmds = run.mock.calls.map(([a]) => (a as string[]).join(' '))
- expect(cmds.some((c) => c.includes("mv -f '/home/u/.nodeterm/node-tokens/.node-9.tmp' '/home/u/.nodeterm/node-tokens/node-9'"))).toBe(true)
+ expect(cmds.some((c) => /mv -f -- .*node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp' '\/home\/u\/\.nodeterm\/node-tokens\/node-9'/.test(c))).toBe(true)
// an unknown control path is a no-op, not a throw
run.mockClear()
await expect(mgr.writeNodeTokenForNode('/nope.sock', 'node-9')).resolves.toBeUndefined()
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 3bf7065eb..4b06f0c96 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -1,5 +1,6 @@
import { promises as fs } from 'fs'
import path from 'path'
+import { createHash, randomUUID } from 'crypto'
import { spawn, execFile, execFileSync } from 'child_process'
import { app, ipcMain } from 'electron'
import { IPC } from '../../shared/ipc'
@@ -7,7 +8,7 @@ import { getMainWindow, sendToMain } from '../main-window'
import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, sshHostKey, type SshConnection } from '../../shared/ssh'
import type { DownloadResult, SshPassphraseRequest, SshProjectStatusEvent } from '../../shared/types'
import { candidateName, safeDownloadBasename } from '../../core/download-name'
-import { renameAtomic } from '../../core/fs-atomic'
+import { removeAtomic, renameAtomic } from '../../core/fs-atomic'
import { findExecutableSync, shellPathNow } from '../../core/exec-path'
import { isSafeRemoteHome } from '../../core/remote-safety'
import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'
@@ -42,6 +43,7 @@ import { setRemoteSessionEnvWriter } from '../../core/remote-ssh/session-env'
import { askpassServer } from './ssh-askpass'
import { appSshAgent } from './ssh-agent'
import { sessionName } from '../../core/tmux-naming'
+import { remoteAtomicWrite } from '../remote-atomic-write'
interface Runners {
userDataDir: string
@@ -132,6 +134,29 @@ const PROBE_RETRY_DELAYS_MS = [5_000, 15_000, 30_000]
/** How many `name (n)` variants a download tries before falling back to a stamped name. */
const DOWNLOAD_NAME_ATTEMPTS = 50
+/** A hidden, bounded scp stage beside the final path, unique beyond process/PID namespaces. */
+function scpPartPath(finalPath: string): string {
+ return path.join(path.dirname(finalPath), `.nodeterm-scp-${randomUUID()}.part`)
+}
+
+/** Remove file-or-directory scp litter with Node's bounded Windows EPERM/EBUSY retry. */
+async function removeScpPart(partPath: string): Promise<void> {
+ await fs
+ .rm(partPath, {
+ recursive: true,
+ force: true,
+ maxRetries: 4,
+ retryDelay: 50
+ })
+ .catch(() => {})
+}
+
+/** Windows aliases terminal dots/spaces, so do not let two remote names bypass one reservation. */
+function localDownloadName(name: string): string {
+ if (process.platform !== 'win32') return name
+ return name.replace(/[. ]+$/, '') || 'download'
+}
+
/** Cap on how much master stderr we retain (a misconfigured host can spew), enough for the error. */
const MASTER_STDERR_CAP = 8 * 1024
@@ -265,8 +290,6 @@ function scpBin(): string {
export class SshProjectManager {
private conns = new Map<string, Conn>()
private remoteHooks: RemoteHooks
- /** Per-manager counter mixed into each upload token so concurrent drops never collide. */
- private uploadSeq = 0
/** Projects whose agent-status mirror was actually pushed, gates the disconnect cleanup so a
* transient folder-picker browse (never pushed) doesn't pay an extra rm round-trip. */
private statusPushed = new Set<string>()
@@ -566,13 +589,14 @@ export class SshProjectManager {
if (remoteHome) {
const confPath = `${remoteHome}/.nodeterm/tmux.conf`
try {
- const dir = `${remoteHome}/.nodeterm`
// The runner RESOLVES (doesn't throw) on a non-zero remote exit, so the catch below
// only guards a thrown error. Gate `tmuxConfPath` on the WRITE's exit code: a failed
// write (mkdir perms, disk full, …) must leave it undefined so `remoteTmuxCommand`
// never passes `-f <missing-conf>` (which makes tmux refuse to start → terminal dies).
+ // The invocation-owned temp also keeps an older valid config intact if ssh drops.
+ const confWrite = remoteAtomicWrite(confPath)
const w = await this.r.run(
- childArgs(conn, controlPath, `mkdir -p ${posixQuote(dir)} && cat > ${posixQuote(confPath)}`),
+ childArgs(conn, controlPath, confWrite.command),
remoteTmuxConf(50000)
)
if (w.code === 0) {
@@ -738,9 +762,11 @@ export class SshProjectManager {
if (!c) return null
// `localPath` is a renderer string passed straight to scp as a positional arg. A value starting
// with `-` (e.g. `-oProxyCommand=…`) would be parsed by scp as an OPTION (argv flag smuggling →
- // RCE), not a file. A real OS file drop is always an absolute path, so require one here, this
- // rejects `-`-prefixed, relative, and empty paths and fully closes the flag-smuggling vector.
- if (!localPath.startsWith('/')) return null
+ // RCE), not a file. A real OS file drop is always absolute, but `/` is not a cross-platform
+ // absolute-path test: drive-letter and UNC drops are valid on Windows. Ask the local host's path
+ // implementation, while retaining the explicit option guard as defence in depth.
+ if (localPath.startsWith('-') || !path.isAbsolute(localPath)) return null
+ let stagedDir: string | undefined
try {
let home = c.remoteHome
if (!home) {
@@ -748,8 +774,14 @@ export class SshProjectManager {
if (r.code === 0 && isSafeRemoteHome(r.stdout.trim())) home = r.stdout.trim()
}
if (!home) return null
- const token = `${Date.now().toString(36)}${(this.uploadSeq++).toString(36)}`
+ // The upload directory is the staging boundary, so it must be unique across PROCESSES, not
+ // merely calls on this manager. Two app instances can upload the same basename to one host;
+ // the former timestamp + per-instance counter could let both scp processes write one inode.
+ const token = randomUUID()
const dir = `${home}/.nodeterm/uploads/${token}`
+ // mkdir can partially create parents before returning non-zero; once this invocation has a
+ // unique directory name, its finally block owns the cleanup attempt on every failure path.
+ stagedDir = dir
const mk = await this.r.run(childArgs(c.conn, c.controlPath, `mkdir -p ${posixQuote(dir)}`))
if (mk.code !== 0) return null
// `fileName` is a renderer string: posixQuote blocks shell injection but NOT filesystem
@@ -759,9 +791,23 @@ export class SshProjectManager {
if (!safe || safe === '.' || safe === '..') return null
const remotePath = `${dir}/${safe}`
const up = await this.r.runScp(scpArgs(c.conn, c.controlPath, localPath, remotePath))
- return up.code === 0 ? remotePath : null
+ if (up.code !== 0) return null
+ // Successful uploads intentionally stay in the managed uploads directory. Only a failed
+ // call owes cleanup of the unique directory it minted.
+ stagedDir = undefined
+ return remotePath
} catch {
return null
+ } finally {
+ if (stagedDir) {
+ try {
+ await this.r.run(
+ childArgs(c.conn, c.controlPath, `rm -rf -- ${posixQuote(stagedDir)}`)
+ )
+ } catch {
+ // Best-effort: the failed transfer is already reported as null; cleanup cannot replace it.
+ }
+ }
}
}
@@ -774,16 +820,23 @@ export class SshProjectManager {
* folder the user picked in a native dialog); the renderer only names the REMOTE side, and
* that name is basenamed + sanitized (`safeDownloadBasename`) before it is joined. So no
* renderer string can steer the write, and `..` can never appear as a component.
- * - **Nothing existing is overwritten.** A collision takes the next `name (n)` candidate.
- * - **A failed transfer leaves no half-file under the real name.** scp writes to `<name>.part`
- * (a `.part` DIRECTORY for `-r`) and it is renamed into place only on exit 0, the same
- * write-then-rename discipline `sshWriteArgs` uses remotely. A failure unlinks the remains.
+ * - **Nothing existing is overwritten.** A collision takes the next `name (n)` candidate. A
+ * short exclusive lock coordinates that choice across app processes; it is removed in the
+ * same finally block that releases the unique staging path.
+ * - **A failed transfer leaves no half-file under the real name.** scp writes to a hidden,
+ * UUID-owned `.part` (a `.part` DIRECTORY for `-r`) and it is renamed into place only on exit
+ * 0, the same write-then-rename discipline `sshWriteArgs` uses remotely. A failure unlinks
+ * exactly its own remains. This local rename retries a transient Windows sharing-violation
+ * error — see src/core/fs-atomic.ts.
*/
async downloadFile(projectId: string, remotePath: string, destDir: string): Promise<DownloadResult> {
const c = this.conns.get(projectId)
if (!c) return { ok: false, error: 'Not connected.' }
- const name = safeDownloadBasename(remotePath)
- if (!name) return { ok: false, error: 'That path cannot be downloaded.' }
+ const remoteName = safeDownloadBasename(remotePath)
+ if (!remoteName) return { ok: false, error: 'That path cannot be downloaded.' }
+ const name = localDownloadName(remoteName)
+ let reservation: { finalPath: string; lockPath: string } | undefined
+ let partPath: string | undefined
try {
// Ask the REMOTE whether this is a directory rather than trusting the renderer's tree state:
// it decides `-r`, and the tree can be stale. A failed probe is not evidence of "file" ,
@@ -792,33 +845,100 @@ export class SshProjectManager {
const probe = await this.r.run(childArgs(c.conn, c.controlPath, `test -d ${quoteRemotePath(remotePath)}`))
const isDir = probe.code === 0
await fs.mkdir(destDir, { recursive: true })
- const finalPath = await this.freeDestPath(destDir, name)
- const partPath = `${finalPath}.part`
- await fs.rm(partPath, { recursive: true, force: true }).catch(() => {})
- const res = await this.r.runScp(scpDownArgs(c.conn, c.controlPath, remotePath, partPath, isDir))
+ reservation = await this.reserveDestPath(destDir, name)
+ partPath = scpPartPath(reservation.finalPath)
+ const res = await this.r.runScp(
+ scpDownArgs(c.conn, c.controlPath, remotePath, partPath, isDir)
+ )
if (res.code !== 0) {
- await fs.rm(partPath, { recursive: true, force: true }).catch(() => {})
return { ok: false, error: 'The transfer failed. Is the file still there, and readable?' }
}
- await renameAtomic(partPath, finalPath)
- return { ok: true, localPath: finalPath, dir: isDir }
+ await renameAtomic(partPath, reservation.finalPath)
+ return { ok: true, localPath: reservation.finalPath, dir: isDir }
} catch {
return { ok: false, error: 'The download could not be completed.' }
+ } finally {
+ if (partPath) await removeScpPart(partPath)
+ if (reservation) await removeAtomic(reservation.lockPath)
}
}
- /** First `<dir>/<name>` variant that exists neither as the target nor as a leftover `.part`. */
- private async freeDestPath(destDir: string, name: string): Promise<string> {
+ /**
+ * Reserve the first free `<dir>/<name>` variant across app processes.
+ *
+ * A read-only `lstat(candidate)` is not a reservation: two downloads can both observe absence,
+ * choose one final path, and then atomically overwrite each other. The deterministic lock name
+ * is opened with `wx`, so exactly one cooperating process owns each candidate. A crash can leave
+ * a tiny lock behind; that safely advances the next download to `name (n)` instead of risking an
+ * overwrite. The hash keeps the lock filename bounded even for a maximum-length remote basename.
+ */
+ private async reserveDestPath(
+ destDir: string,
+ name: string
+ ): Promise<{ finalPath: string; lockPath: string }> {
+ const tryCandidate = async (
+ finalPath: string
+ ): Promise<{ finalPath: string; lockPath: string } | null> => {
+ // The lock itself lives inside destDir, so its key only needs the candidate basename. Using
+ // the full spelling lets two aliases of the same physical directory (junction/symlink/drive
+ // alias) create different locks beside the same target and race. Basename makes them
+ // converge without a realpath check that can itself go stale.
+ const candidate = path.basename(finalPath).normalize('NFC')
+ const caseInsensitive = process.platform === 'win32' || process.platform === 'darwin'
+ const normalized = caseInsensitive ? candidate.toLowerCase() : candidate
+ const key = createHash('sha256').update(normalized).digest('hex').slice(0, 20)
+ const lockPath = path.join(destDir, `.nodeterm-download-${key}.lock`)
+ let ownsLock = false
+ try {
+ const handle = await fs.open(lockPath, 'wx', 0o600)
+ ownsLock = true
+ await handle.close()
+ let taken = true
+ try {
+ // lstat asks whether the DIRECTORY ENTRY exists. access follows a symlink, so a dangling
+ // link reports ENOENT and was incorrectly treated as a free name, then replaced.
+ await fs.lstat(finalPath)
+ } catch (error) {
+ const code =
+ typeof error === 'object' && error && 'code' in error
+ ? String((error as { code: unknown }).code)
+ : ''
+ // A failed read is not evidence of absence. Only lstat's ENOENT proves the directory
+ // entry is free; EACCES/EIO and unknown failures must refuse instead of authorizing an
+ // overwrite. In particular, lstat succeeds for a dangling symlink while access did not.
+ if (code === 'ENOENT') taken = false
+ else throw error
+ }
+ if (taken) {
+ await removeAtomic(lockPath)
+ return null
+ }
+ return { finalPath, lockPath }
+ } catch (error) {
+ if (ownsLock) await removeAtomic(lockPath)
+ const code =
+ typeof error === 'object' && error && 'code' in error
+ ? String((error as { code: unknown }).code)
+ : ''
+ if (!ownsLock && code === 'EEXIST') return null
+ throw error
+ }
+ }
+
for (let attempt = 1; attempt <= DOWNLOAD_NAME_ATTEMPTS; attempt++) {
- const candidate = path.join(destDir, candidateName(name, attempt))
- const taken = await fs
- .access(candidate)
- .then(() => true)
- .catch(() => false)
- if (!taken) return candidate
+ const reservation = await tryCandidate(path.join(destDir, candidateName(name, attempt)))
+ if (reservation) return reservation
+ }
+ // Every readable variant is taken: try stamped names rather than overwriting one. Still
+ // bounded, so a broken/unwritable directory fails honestly rather than looping forever.
+ const stamp = Date.now()
+ for (let offset = 0; offset < DOWNLOAD_NAME_ATTEMPTS; offset++) {
+ const reservation = await tryCandidate(
+ path.join(destDir, candidateName(name, stamp + offset))
+ )
+ if (reservation) return reservation
}
- // Every readable variant is taken: fall back to a stamped name rather than overwriting one.
- return path.join(destDir, candidateName(name, Date.now()))
+ throw new Error('Could not reserve a download destination.')
}
/**
@@ -848,24 +968,37 @@ export class SshProjectManager {
childArgs(c.conn, c.controlPath, `wc -c < ${quoteRemotePath(remotePath)}`)
)
const remoteSize = sizeProbe.code === 0 ? parseInt(sizeProbe.stdout.trim(), 10) : NaN
- const cachedSize = await fs
- .stat(dest)
- .then((s) => s.size)
- .catch(() => -1)
+ let cachedSize = -1
+ try {
+ cachedSize = (await fs.stat(dest)).size
+ } catch (error) {
+ const code =
+ typeof error === 'object' && error && 'code' in error
+ ? String((error as { code: unknown }).code)
+ : ''
+ // Only ENOENT means there is no cached file. An unreadable cache entry must not be
+ // treated as permission to replace it with a fresh transfer.
+ if (code !== 'ENOENT') throw error
+ }
if (Number.isFinite(remoteSize) && remoteSize >= 0 && cachedSize === remoteSize) {
return { ok: true, localPath: dest }
}
await fs.mkdir(cacheDir, { recursive: true })
// Same write-then-rename discipline as downloadFile: never leave a half-copied file
- // under the final name, nt-media would happily serve a truncated video.
- const partPath = `${dest}.part`
- await fs.rm(partPath, { force: true }).catch(() => {})
- const res = await this.r.runScp(scpDownArgs(c.conn, c.controlPath, remotePath, partPath, false))
- if (res.code !== 0) {
- await fs.rm(partPath, { force: true }).catch(() => {})
- return { ok: false, error: 'The transfer failed. Is the file still there, and readable?' }
+ // under the final name, nt-media would happily serve a truncated video. This local
+ // rename retries a transient Windows sharing-violation error — see src/core/fs-atomic.ts.
+ const partPath = scpPartPath(dest)
+ try {
+ const res = await this.r.runScp(
+ scpDownArgs(c.conn, c.controlPath, remotePath, partPath, false)
+ )
+ if (res.code !== 0) {
+ return { ok: false, error: 'The transfer failed. Is the file still there, and readable?' }
+ }
+ await renameAtomic(partPath, dest)
+ } finally {
+ await removeScpPart(partPath)
}
- await renameAtomic(partPath, dest)
void this.pruneMediaCache(cacheDir, path.basename(dest))
return { ok: true, localPath: dest }
} catch {
@@ -1141,15 +1274,13 @@ export class SshProjectManager {
const c = this.conns.get(projectId)
if (!c) return
const file = this.statusFilePath(projectId, c)
- const q = quoteRemotePath(file)
- const qTmp = quoteRemotePath(`${file}.tmp`)
this.statusPushed.add(projectId)
await this.r
.run(
childArgs(
c.conn,
c.controlPath,
- `umask 077; mkdir -p ${quoteRemotePath(file.slice(0, file.lastIndexOf('/')))} && cat > ${qTmp} && mv -f ${qTmp} ${q}`
+ remoteAtomicWrite(file, { restrictPermissions: true }).command
),
json
)
@@ -1246,15 +1377,12 @@ export class SshProjectManager {
if (decision !== 'allow' && decision !== 'deny') return false
const dir = c.remoteHome ? `${c.remoteHome}/.nodeterm/pending` : '~/.nodeterm/pending'
const file = `${dir}/${pendingId}.answer`
- const q = quoteRemotePath(file)
- const qTmp = quoteRemotePath(`${file}.tmp`)
- const qDir = quoteRemotePath(dir)
const { code } = await this.r
.run(
childArgs(
c.conn,
c.controlPath,
- `umask 077; mkdir -p ${qDir} && cat > ${qTmp} && mv -f ${qTmp} ${q}`
+ remoteAtomicWrite(file, { restrictPermissions: true }).command
),
decision
)
diff --git a/src/main/ssh-fs.test.ts b/src/main/ssh-fs.test.ts
index 6312c876f..227cd8da4 100644
--- a/src/main/ssh-fs.test.ts
+++ b/src/main/ssh-fs.test.ts
@@ -16,23 +16,31 @@ describe('ssh-fs arg builders', () => {
})
// ATOMIC: `cat > file` truncates the target the moment it opens, so a connection dropped (or the
// ControlMaster killed at quit) mid-write left a HALF/EMPTY file behind — for .nodeterm/project.json
- // that read as "my project reset itself". Write a sibling .tmp, then mv into place.
- it('write mkdir -p the dirname, cat > a sibling .tmp, then mv into place (content via stdin)', () => {
- const j = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt').join(' ')
- expect(j).toContain(`mkdir -p '/d/e'`)
- expect(j).toContain(`cat > '/d/e/f.txt.tmp'`)
- expect(j).toContain(`mv -f '/d/e/f.txt.tmp' '/d/e/f.txt'`)
+ // that read as "my project reset itself". Write a unique sibling temp, then mv into place.
+ it('write mkdirs, cats to one per-call temp, then moves and cleans that temp (content via stdin)', () => {
+ const first = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt').join(' ')
+ const second = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt').join(' ')
+ const temp = first.match(/cat > '([^']+\.tmp)'/)?.[1]
+ expect(temp).toMatch(/^\/d\/e\/\.nodeterm-[0-9a-f-]{36}\.tmp$/)
+ expect(second).not.toContain(`cat > '${temp}'`)
+ const j = first
+ expect(j).toContain(`mkdir -p -- '/d/e'`)
+ expect(j).toContain(`cat > '${temp}'`)
+ expect(j).toContain(`mv -f -- '${temp}' '/d/e/f.txt'`)
+ expect(j).toContain(`rm -f -- '${temp}'`)
})
// CRITICAL: SSH projects default to a home-relative remoteCwd (`~`). quoteRemotePath must leave a
// leading `~/` UNQUOTED so the remote shell tilde-expands it; the remainder stays single-quoted.
it('list leaves a leading ~/ unquoted so the remote shell tilde-expands the path', () => {
expect(sshListArgs(conn, '/s', '~/projects').join(' ')).toContain(`ls -Ap1 ~/'projects'`)
})
- it('write keeps ~/ unquoted for the mkdir dirname, the .tmp target and the mv', () => {
+ it('write keeps ~/ unquoted for the mkdir dirname, the unique temp and the mv', () => {
const j = sshWriteArgs(conn, '/s', '~/projects/file.txt').join(' ')
- expect(j).toContain(`mkdir -p ~/'projects'`)
- expect(j).toContain(`cat > ~/'projects/file.txt.tmp'`)
- expect(j).toContain(`mv -f ~/'projects/file.txt.tmp' ~/'projects/file.txt'`)
+ expect(j).toContain(`mkdir -p -- ~/'projects'`)
+ const temp = j.match(/cat > ~\/'([^']+\.tmp)'/)?.[1]
+ expect(temp).toMatch(/^projects\/\.nodeterm-[0-9a-f-]{36}\.tmp$/)
+ expect(j).toContain(`mv -f -- ~/'${temp}' ~/'projects/file.txt'`)
+ expect(j).toContain(`rm -f -- ~/'${temp}'`)
})
it('mkdir runs mkdir -p on the quoted path', () => {
expect(sshMkdirArgs(conn, '/s.sock', '/a b/c').join(' ')).toContain(`mkdir -p '/a b/c'`)
diff --git a/src/main/ssh-fs.ts b/src/main/ssh-fs.ts
index 0dee65fb3..df504e863 100644
--- a/src/main/ssh-fs.ts
+++ b/src/main/ssh-fs.ts
@@ -14,6 +14,7 @@ import {
QUICK_OPEN_FILE_CAP
} from '../shared/quick-open-filter'
import type { DirEntry } from '../shared/types'
+import { remoteAtomicWrite } from './remote-atomic-write'
export interface SshFsRef {
conn: SshConnection
@@ -38,10 +39,9 @@ export function sshReadBinaryArgs(conn: SshConnection, cp: string, path: string)
export function sshWriteArgs(conn: SshConnection, cp: string, path: string): string[] {
// Atomic: `cat > file` truncates on open, so a connection dropped (or the ControlMaster killed
// at app quit) mid-write leaves a half/empty file — fatal for .nodeterm/project.json. Stream to
- // a sibling .tmp and mv into place; a write that dies leaves the target untouched.
- const target = quoteRemotePath(path)
- const tmp = quoteRemotePath(`${path}.tmp`)
- return childArgs(conn, cp, `mkdir -p ${quoteRemotePath(dirname(path))} && cat > ${tmp} && mv -f ${tmp} ${target}`)
+ // a unique sibling temp and mv into place; a write that dies leaves the target untouched.
+ // Per-call uniqueness is load-bearing: two app instances can write this remote path at once.
+ return childArgs(conn, cp, remoteAtomicWrite(path).command)
}
export function sshMkdirArgs(conn: SshConnection, cp: string, path: string): string[] {
return childArgs(conn, cp, `mkdir -p ${quoteRemotePath(path)}`)
diff --git a/src/renderer/bridge/ws-bridge.namespaces.test.ts b/src/renderer/bridge/ws-bridge.namespaces.test.ts
index e8e80cfb0..dbc7960c7 100644
--- a/src/renderer/bridge/ws-bridge.namespaces.test.ts
+++ b/src/renderer/bridge/ws-bridge.namespaces.test.ts
@@ -80,6 +80,24 @@ describe('buildRealApi: workspace', () => {
})
})
+describe('buildRealApi: host platform', () => {
+ it('keeps a failed host read unknown instead of inventing Linux from the browser bridge', async () => {
+ const c = fakeClient()
+ c.request = (method: string, ...args: unknown[]) => {
+ c.calls.push({ kind: 'request', method, args })
+ return Promise.reject(new Error('server unavailable'))
+ }
+ const api = buildRealApi(c as never)
+
+ await expect(api.pty.tmuxStatus()).resolves.toEqual({
+ available: true,
+ installCommand: null,
+ installLabel: null,
+ platform: null
+ })
+ })
+})
+
describe('buildRealApi: sessionMemory', () => {
// A real WS namespace, not a stub: the same core service (`startSessionMemoryService`) registers
// both channels in the server shell, so the browser gets a genuine per-session breakdown of the
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 1762f6079..e5b61a19c 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -234,7 +234,7 @@ export function buildRealApi(
tmuxStatus: () =>
client
.request(IPC.ptyTmuxStatus)
- .catch(() => ({ available: true, installCommand: null, installLabel: null, platform: 'linux' })) as Promise<TmuxStatus>,
+ .catch(() => ({ available: true, installCommand: null, installLabel: null, platform: null })) as Promise<TmuxStatus>,
// Unknown on failure (null), never a rejection: the restart poller reads null as "not a
// shell yet" and gives up on its own deadline.
paneCommand: (persistKey) =>
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index c1059e0c3..4ac9193a8 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -30,6 +30,8 @@ import {
installLinkClickFallback,
makeDirListingLookup
} from '../terminal/file-links'
+import { fileLinkDialect } from '../terminal/file-link-dialect'
+import { hostPlatformFor } from '../terminal/host-platform'
import { sshFs } from '../terminal/ssh-fs'
import type { FsApi, PendingLaunch } from '@shared/types'
import {
@@ -144,6 +146,7 @@ import { useSshConn } from '../state/sshConn'
import { useWorktrees } from '../state/worktrees'
import { isRemoteSessionNode } from '@shared/worktree'
import { useSession, useActiveSessionPresence } from '../session/session'
+import { isBrowserRuntime } from '../bridge/runtime'
import { accountChipLabel, agentLaunchOverride, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'
import {
hasHooks,
@@ -166,7 +169,7 @@ import { agentEnvSnapshot } from '@renderer/lib/agentEnv'
import { normalizedAgentModel } from '@shared/agents/model-gateway'
import { ensureActivePermissionMode } from '../state/permissionMode'
import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'
-import { hintLabel } from '@shared/platform-utils'
+import { hintLabel, isWindowsPlatform } from '@shared/platform-utils'
import { ColumnPill } from '../components/kanban/ColumnPill'
import { BoardLogPanel } from '../components/kanban/BoardLogPanel'
import { AgentMascot } from './AgentMascot'
@@ -908,6 +911,23 @@ export function TerminalNode({
// namespaces (pty, fs) go through it; app-global ones (clipboard, shell) stay on the global.
const session = useSession()
const { api } = session
+ // The path dialect belongs to the core that owns this tab's filesystem, not necessarily this
+ // browser/window. Server Edition and relay tabs can be viewed from a different OS, so their
+ // core reports `process.platform` through the already-core-bound tmux status call. Keep it in a
+ // ref: resolving this fact must not tear down and respawn the terminal lifecycle effect.
+ const corePlatformRef = useRef<string | null>(null)
+ useEffect(() => {
+ let live = true
+ corePlatformRef.current = null
+ void hostPlatformFor(api).then((platform) => {
+ // A failed read is not evidence of Linux. fileLinkDialect fails closed for server/relay;
+ // only the local desktop may use its viewer as the host because they are the same process.
+ if (live) corePlatformRef.current = platform
+ })
+ return () => {
+ live = false
+ }
+ }, [api])
// The ACTIVE session's presence — where our focus/blur casts go. This node renders under Canvas's
// active-session provider, so a relay tab reports focus over the relay core and a local tab hits
// `defaultPresence` (byte-identical to before). Stable for the node's lifetime (a tab switch
@@ -2320,13 +2340,26 @@ export function TerminalNode({
const project = st.projects.find((p) => p.id === st.activeProjectId)
return project?.ssh ? { fs: sshFs(project.id), ssh: true } : { fs: api.fs, ssh: false }
}
- // Relay-remote nodes have no client fs, so file-path links are skipped (URL-only) — mirrors
- // the CLAUDE.md note. A relay project carries the runtime-only `remote` flag.
- const isRelayProject = (): boolean => {
+ const pathConvention = (): { windows?: boolean } | null => {
const st = useProjects.getState()
- return !!st.projects.find((p) => p.id === st.activeProjectId)?.remote
+ const project = st.projects.find((p) => p.id === st.activeProjectId)
+ const dialect = fileLinkDialect({
+ source: session.source,
+ browserRuntime: isBrowserRuntime(),
+ viewerWindows: isWindowsPlatform(),
+ corePlatform: corePlatformRef.current,
+ sshProject: !!project?.ssh,
+ // A standalone ssh terminal's output lives on the remote host, but its project's fs API
+ // is local. Disable file links rather than existence-checking a same-looking local path.
+ standaloneSsh: !project?.ssh && isRemoteSessionNode(data)
+ })
+ return dialect ? { windows: dialect === 'windows' } : null
}
- const lookup = makeDirListingLookup(async (dir) => projectFs().fs.list(dir))
+ const lookup = makeDirListingLookup(
+ async (dir) => projectFs().fs.list(dir),
+ 3000,
+ pathConvention
+ )
const getCwd = (): string | undefined => (data.cwd as string | undefined) || undefined
const openFile = (abs: string, isDir: boolean): void => {
if (isDir) window.dispatchEvent(new CustomEvent('nodeterm:reveal-file', { detail: { path: abs } }))
@@ -2335,7 +2368,14 @@ export function TerminalNode({
new CustomEvent('nodeterm:open-file', { detail: { path: abs, ssh: projectFs().ssh } })
)
}
- term.registerLinkProvider(createFileLinkProvider(term, { getCwd, lookup, activate: openFile }))
+ term.registerLinkProvider(
+ createFileLinkProvider(term, {
+ getCwd,
+ lookup,
+ activate: openFile,
+ convention: pathConvention
+ })
+ )
// Both providers above rely on xterm's own click handling, which
// tmux/agent mouse-reporting swallows. This capture-phase mouse-up fallback restores
// Cmd/Ctrl+click for both URLs and file paths in that mode. Attached to `term.element` so
@@ -2346,7 +2386,8 @@ export function TerminalNode({
lookup,
activateFile: openFile,
openUrl: (uri) => window.nodeTerminal.shell.openExternal(uri),
- fileEnabled: () => !isRelayProject()
+ fileEnabled: () => pathConvention() !== null,
+ convention: pathConvention
})
}
}
diff --git a/src/renderer/terminal/file-link-dialect.test.ts b/src/renderer/terminal/file-link-dialect.test.ts
new file mode 100644
index 000000000..0e9a8cd8b
--- /dev/null
+++ b/src/renderer/terminal/file-link-dialect.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest'
+import { fileLinkDialect, type FileLinkDialectFacts } from './file-link-dialect'
+
+const facts = (overrides: Partial<FileLinkDialectFacts> = {}): FileLinkDialectFacts => ({
+ source: 'local',
+ browserRuntime: false,
+ viewerWindows: false,
+ corePlatform: null,
+ sshProject: false,
+ standaloneSsh: false,
+ ...overrides
+})
+
+describe('fileLinkDialect', () => {
+ it('uses the local desktop viewer only where viewer and filesystem host are the same machine', () => {
+ expect(fileLinkDialect(facts({ viewerWindows: true }))).toBe('windows')
+ expect(fileLinkDialect(facts({ viewerWindows: false }))).toBe('posix')
+ })
+
+ it('uses the Server Edition host rather than the browser OS', () => {
+ expect(
+ fileLinkDialect(
+ facts({ source: 'local', browserRuntime: true, viewerWindows: true, corePlatform: 'linux' })
+ )
+ ).toBe('posix')
+ expect(
+ fileLinkDialect(
+ facts({ source: 'local', browserRuntime: true, viewerWindows: false, corePlatform: 'win32' })
+ )
+ ).toBe('windows')
+ })
+
+ it('uses the relay host rather than the relay guest OS', () => {
+ expect(
+ fileLinkDialect(facts({ source: 'relay', viewerWindows: true, corePlatform: 'darwin' }))
+ ).toBe('posix')
+ expect(
+ fileLinkDialect(facts({ source: 'relay', viewerWindows: false, corePlatform: 'win32' }))
+ ).toBe('windows')
+ })
+
+ it('treats an SSH project as POSIX even when its desktop core is Windows', () => {
+ expect(
+ fileLinkDialect(facts({ viewerWindows: true, corePlatform: 'win32', sshProject: true }))
+ ).toBe('posix')
+ })
+
+ it('refuses a standalone ssh terminal because no remote fs API can verify its paths', () => {
+ expect(fileLinkDialect(facts({ standaloneSsh: true, corePlatform: 'win32' }))).toBeNull()
+ })
+
+ it('does not guess from a browser when the server or relay host platform read failed', () => {
+ expect(
+ fileLinkDialect(facts({ source: 'local', browserRuntime: true, viewerWindows: true }))
+ ).toBeNull()
+ expect(fileLinkDialect(facts({ source: 'server', viewerWindows: true }))).toBeNull()
+ expect(fileLinkDialect(facts({ source: 'relay', viewerWindows: false }))).toBeNull()
+ })
+})
diff --git a/src/renderer/terminal/file-link-dialect.ts b/src/renderer/terminal/file-link-dialect.ts
new file mode 100644
index 000000000..bceaaf6e7
--- /dev/null
+++ b/src/renderer/terminal/file-link-dialect.ts
@@ -0,0 +1,41 @@
+import type { SessionSource } from '../session/session'
+
+export type FileLinkDialect = 'posix' | 'windows'
+
+export interface FileLinkDialectFacts {
+ /** Which core owns the active tab's filesystem. */
+ source: SessionSource
+ /** True for the Server Edition's websocket-backed browser tab (currently source `local`). */
+ browserRuntime: boolean
+ /** The browser/window's OS. It is authoritative only for the local desktop core. */
+ viewerWindows: boolean
+ /** `process.platform` reported by the filesystem-owning core; null means it was not observed. */
+ corePlatform: string | null
+ /** An SSH project's fs API runs on its SSH host, whose supported dialect is POSIX. */
+ sshProject: boolean
+ /** A standalone ssh terminal has remote output but no remote filesystem API to verify links. */
+ standaloneSsh: boolean
+}
+
+/**
+ * Choose the dialect used by terminal output AND by the filesystem existence check behind it.
+ *
+ * A browser's OS is not evidence about a Server Edition or relay host. Guessing there makes a
+ * Windows browser parse a Linux server's output as drive paths, and the inverse on a Windows host.
+ * When the owning core could not report its platform, refuse file links until it can: an absent
+ * link is recoverable; opening a same-looking path on the wrong machine is not.
+ */
+export function fileLinkDialect(facts: FileLinkDialectFacts): FileLinkDialect | null {
+ if (facts.sshProject) return 'posix'
+ if (facts.standaloneSsh) return null
+
+ const platform =
+ facts.corePlatform ??
+ (facts.source === 'local' && !facts.browserRuntime
+ ? facts.viewerWindows
+ ? 'win32'
+ : 'posix'
+ : null)
+ if (!platform) return null
+ return platform === 'win32' ? 'windows' : 'posix'
+}
diff --git a/src/renderer/terminal/file-links.test.ts b/src/renderer/terminal/file-links.test.ts
index dda924e8d..b49145d7a 100644
--- a/src/renderer/terminal/file-links.test.ts
+++ b/src/renderer/terminal/file-links.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
+ makeDirListingLookup,
matchFileTokens,
matchUrlTokens,
paragraphContaining,
@@ -59,6 +60,26 @@ describe('resolveFileToken', () => {
})
})
+describe('POSIX existence lookup', () => {
+ it('keeps a backslash inside the filename and matches case-sensitively', async () => {
+ const listed: string[] = []
+ const lookup = makeDirListingLookup(async (dir) => {
+ listed.push(dir)
+ return [
+ { name: String.raw`name\part.ts`, dir: false },
+ { name: 'CASE.ts', dir: false }
+ ]
+ })
+
+ await expect(lookup(String.raw`/repo/name\part.ts`)).resolves.toEqual({
+ exists: true,
+ dir: false
+ })
+ await expect(lookup('/repo/case.ts')).resolves.toEqual({ exists: false, dir: false })
+ expect(listed).toEqual(['/repo'])
+ })
+})
+
/** Fake buffer: each entry is a row's content; `w:` prefix marks it soft-wrapped. Rows are
* stored untrimmed exactly as given (pad to `cols` yourself to simulate a full row). */
function view(cols: number, rows: string[]): BufferView {
diff --git a/src/renderer/terminal/file-links.ts b/src/renderer/terminal/file-links.ts
index 5a4af4759..e375f6cee 100644
--- a/src/renderer/terminal/file-links.ts
+++ b/src/renderer/terminal/file-links.ts
@@ -37,11 +37,43 @@ export interface FileToken {
// trailing :line[:col]. Trailing punctuation is cleaned afterwards, not in the regex.
const TOKEN_RE =
/(?:(?:\.{1,2}\/|\/)?[\w.@+-]+(?:\/[\w.@+~-]+)+|(?:\.{1,2}\/|\/)[\w.@+-]+)(?::\d+(?::\d+)?)?/g
+
+/**
+ * The same shape with Windows separators, plus drive and UNC prefixes. Used ONLY when the
+ * filesystem-owning core reports Windows — never just because the viewing browser is on Windows,
+ * and never for an SSH project, whose paths are POSIX however the viewer is spelled.
+ *
+ * A SEPARATE regex rather than widening TOKEN_RE's separator class, deliberately: the POSIX path
+ * is what every existing user runs, and it stays byte-identical. Widening it would also start
+ * matching Windows-shaped text inside a POSIX session, where it can only ever be wrong.
+ *
+ * Four alternatives, in order: a UNC path (consumed whole so it can be refused), a drive-absolute
+ * path, a dot-prefixed relative, or a plain multi-segment relative. Both separators are accepted,
+ * because Windows tools emit both. A bare single word is deliberately not a token — `readme` in a
+ * sentence is not a path, and TOKEN_RE takes the same position for POSIX.
+ *
+ * SPACES ARE NOT PART OF A SEGMENT, even though `C:\Program Files\…` is everywhere on Windows.
+ * An unquoted path in terminal output gives no way to tell where it ends, so allowing spaces made
+ * `C:\Users\me\src\a.ts for detail` match as one token — it swallowed the rest of the sentence.
+ * The existence check would have rejected that, which means a path with a space would simply never
+ * have linked while quietly breaking the ones around it. The POSIX matcher takes the same
+ * position, so this is parity rather than a Windows-specific shortfall.
+ */
+const WIN_TOKEN_RE =
+ /(?:(?:\\\\|\/\/)[\w.@+~-]+[\\/][\w.@+~-]+(?:[\\/][\w.@+~-]+)*|[A-Za-z]:[\\/][\w.@+~-]*(?:[\\/][\w.@+~-]+)*|\.{1,2}[\\/][\w.@+~-]+(?:[\\/][\w.@+~-]+)*|[\w.@+-]+(?:[\\/][\w.@+~-]+)+)(?::\d+(?::\d+)?)?/g
const SUFFIX_RE = /^(.*?):(\d+)(?::\d+)?$/
const TRAILING_PUNCT = /[.,;:!?'")\]}>]+$/
+/** `C:\…`, `C:/…`, or a UNC `\\host\share` / `//host/share`. */
+const WIN_ABSOLUTE_RE = /^(?:[A-Za-z]:[\\/]|\\\\|\/\/)/
+
+export interface PathConventionOpts {
+ /** Match and resolve Windows-shaped paths. Off by default, so POSIX behaviour is unchanged. */
+ windows?: boolean
+}
-export function matchFileTokens(lineText: string): FileToken[] {
+export function matchFileTokens(lineText: string, opts: PathConventionOpts = {}): FileToken[] {
const out: FileToken[] = []
+ if (opts.windows) return matchWindowsFileTokens(lineText)
for (const m of lineText.matchAll(TOKEN_RE)) {
let text = m[0]
// URLs (and protocol-ish tokens) belong to the web-links addon. A token preceded by
@@ -67,6 +99,46 @@ export function matchFileTokens(lineText: string): FileToken[] {
return out
}
+/**
+ * The Windows half of `matchFileTokens`. Kept separate so the POSIX path above is untouched.
+ *
+ * The existence check downstream (`makeDirListingLookup`) is what makes a slightly generous
+ * matcher safe: a token that is not a real file simply never becomes a link. So this errs toward
+ * matching, and lets the filesystem decide — the opposite trade from the traversal guards
+ * elsewhere in this codebase, where guessing wrong has a cost.
+ */
+function matchWindowsFileTokens(lineText: string): FileToken[] {
+ const out: FileToken[] = []
+ for (const m of lineText.matchAll(WIN_TOKEN_RE)) {
+ let text = m[0]
+ const before = lineText.slice(Math.max(0, m.index - 8), m.index)
+ // A URL's token can begin at the second slash of `://` — same guard as the POSIX branch.
+ if (/\w+:\/{1,2}$/.test(before) || text.includes('//')) continue
+ text = text.replace(TRAILING_PUNCT, '')
+ if (text.length < 3) continue
+ let path = text
+ // Refuse the WHOLE UNC token here. Without the explicit UNC alternative in WIN_TOKEN_RE the
+ // matcher started two characters in (`server\share\a.ts`), turning the network path into a
+ // relative path under cwd and bypassing resolveWindowsFileToken's UNC refusal.
+ if (/^(?:\\\\|\/\/)/.test(path)) continue
+ let line: number | undefined
+ const suffix = SUFFIX_RE.exec(text)
+ // `C:\src\a.ts:12` splits correctly because SUFFIX_RE anchors the digits at the END — the
+ // drive's own colon is not followed by digits-then-end. `C:12` would split into path `C`,
+ // which the separator requirement below then rejects.
+ if (suffix) {
+ path = suffix[1]
+ line = parseInt(suffix[2], 10)
+ }
+ if (!path) continue
+ // Must look like a path, not a bare word: either drive/UNC-qualified, or containing a
+ // separator. Without this a `:line` suffix on any word would produce a token.
+ if (!WIN_ABSOLUTE_RE.test(path) && !/[\\/]/.test(path)) continue
+ out.push({ text, startIndex: m.index, path, line })
+ }
+ return out
+}
+
// http(s) URLs. Shared by createUrlLinkProvider (hover underline + click outside tmux) and
// the mouse-up click fallback (below), which hit-tests URLs and file paths in one pass —
// under tmux/agent mouse-reporting a provider's own click never fires (see
@@ -100,7 +172,12 @@ export function matchUrlTokens(lineText: string): UrlToken[] {
* A home-relative cwd (`~` or `~/proj`, the SSH-project default) keeps its leading `~` as
* the first segment — the downstream sshFs stack tilde-expands it via quoteRemotePath, so
* `/`-prefixing it (→ `/~/proj`) would break the remote listing. `..` may not pop the `~`. */
-export function resolveFileToken(path: string, cwd: string | undefined): string | null {
+export function resolveFileToken(
+ path: string,
+ cwd: string | undefined,
+ opts: PathConventionOpts = {}
+): string | null {
+ if (opts.windows) return resolveWindowsFileToken(path, cwd)
const raw = path.startsWith('/') ? path : cwd ? `${cwd.replace(/\/+$/, '')}/${path}` : null
if (!raw) return null
const segs = raw.split('/').filter((s) => s && s !== '.')
@@ -116,8 +193,48 @@ export function resolveFileToken(path: string, cwd: string | undefined): string
return tilde ? out.join('/') : '/' + out.join('/')
}
+/**
+ * Windows counterpart. Returns a `/`-separated path that KEEPS its drive prefix
+ * (`C:/Users/me/src/a.ts`).
+ *
+ * Forward slashes on purpose, even though the input is backslashed: Windows accepts either for
+ * filesystem calls, and `makeDirListingLookup` finds the parent directory with
+ * `lastIndexOf('/')`. Returning a native path would make that split fail and the link would never
+ * resolve — silently, since a failed lookup just means no link.
+ *
+ * A UNC path is refused rather than half-handled: `\\host\share\x` has no drive to anchor on, its
+ * first two segments are a host and a share rather than directories, and getting that wrong would
+ * send a directory listing at a network host. Nobody has asked for it, and refusing costs a link
+ * that would not have worked anyway.
+ */
+function resolveWindowsFileToken(path: string, cwd: string | undefined): string | null {
+ const slash = (p: string): string => p.replace(/\\/g, '/')
+ if (/^(?:\\\\|\/\/)/.test(path)) return null // UNC — see above
+ const abs = /^[A-Za-z]:[\\/]/.test(path)
+ const raw = abs ? slash(path) : cwd ? `${slash(cwd).replace(/\/+$/, '')}/${slash(path)}` : null
+ if (!raw) return null
+ // Split off the drive so `..` can never pop past it, the same way the POSIX branch protects `~`.
+ const drive = /^([A-Za-z]:)\//.exec(raw)?.[1]
+ const rest = drive ? raw.slice(drive.length + 1) : raw
+ const segs = rest.split('/').filter((s) => s && s !== '.')
+ const out: string[] = []
+ for (const seg of segs) {
+ if (seg === '..') {
+ if (out.length === 0) return null
+ out.pop()
+ } else out.push(seg)
+ }
+ if (!drive) return null // relative with no drive-qualified cwd — nothing to anchor on
+ return `${drive}/${out.join('/')}`
+}
+
export interface FileLinkDeps {
getCwd(): string | undefined
+ /** Static compatibility option for direct unit consumers. Live terminals use `convention`. */
+ windows?: boolean
+ /** Dynamic host decision. `null` means the owning core's dialect was not observed, so file
+ * links fail closed instead of borrowing the browser's OS. Takes precedence over `windows`. */
+ convention?: () => PathConventionOpts | null
lookup(abs: string): Promise<{ exists: boolean; dir: boolean }>
activate(abs: string, dir: boolean): void
}
@@ -202,7 +319,7 @@ function tokenRange(
}
}
-/** xterm link provider for file paths. Register once per (non-relay) terminal. */
+/** xterm link provider for file paths. Register once per terminal with a reachable filesystem. */
export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILinkProvider {
return {
provideLinks(bufferLineNumber: number, callback: (links: ILink[] | undefined) => void): void {
@@ -213,7 +330,12 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILin
callback(undefined)
return
}
- const tokens = matchFileTokens(logical.text)
+ const convention = deps.convention ? deps.convention() : { windows: deps.windows }
+ if (!convention) {
+ callback(undefined)
+ return
+ }
+ const tokens = matchFileTokens(logical.text, convention)
if (!tokens.length) {
callback(undefined)
return
@@ -221,7 +343,7 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILin
const cols = term.cols
void Promise.all(
tokens.map(async (t): Promise<ILink | null> => {
- const abs = resolveFileToken(t.path, deps.getCwd())
+ const abs = resolveFileToken(t.path, deps.getCwd(), convention)
if (!abs) return null
const found = await deps.lookup(abs)
if (!found.exists) return null
@@ -273,18 +395,38 @@ export function createUrlLinkProvider(term: Terminal, openUrl: (url: string) =>
/** Existence+dir-ness via cached parent-dir listings (one list covers all siblings). */
export function makeDirListingLookup(
list: (dir: string) => Promise<Array<{ name: string; dir: boolean }>>,
- ttlMs = 3000
+ ttlMs = 3000,
+ convention: () => PathConventionOpts | null = () => ({})
): (abs: string) => Promise<{ exists: boolean; dir: boolean }> {
const cache = new Map<string, { at: number; entries: Array<{ name: string; dir: boolean }> }>()
return async (abs) => {
- const i = abs.lastIndexOf('/')
- const dir = i <= 0 ? '/' : abs.slice(0, i)
+ const opts = convention()
+ if (!opts) return { exists: false, dir: false }
+ // On POSIX a backslash is legal filename text, not a separator. Only the Windows dialect may
+ // split on it; resolved Windows tokens normally use `/`, but accepting a native path here keeps
+ // this boundary honest if another caller supplies one later.
+ const i = opts.windows
+ ? Math.max(abs.lastIndexOf('/'), abs.lastIndexOf('\\'))
+ : abs.lastIndexOf('/')
+ // `C:/a.ts` splits to a dir of `C:`, which on Windows means "the current directory on drive
+ // C" rather than its root — a listing of somewhere else entirely. Keep the separator.
+ const separator = i >= 0 ? abs[i] : '/'
+ const dir =
+ i <= 0
+ ? '/'
+ : /^[A-Za-z]:$/.test(abs.slice(0, i))
+ ? abs.slice(0, i) + separator
+ : abs.slice(0, i)
const name = abs.slice(i + 1)
- const hit = cache.get(dir)
+ const cacheKey = opts.windows ? dir.toLowerCase() : dir
+ const hit = cache.get(cacheKey)
const entries =
hit && Date.now() - hit.at < ttlMs ? hit.entries : await list(dir).catch(() => [])
- if (!hit || Date.now() - (hit?.at ?? 0) >= ttlMs) cache.set(dir, { at: Date.now(), entries })
- const e = entries.find((x) => x.name === name)
+ if (!hit || Date.now() - (hit?.at ?? 0) >= ttlMs)
+ cache.set(cacheKey, { at: Date.now(), entries })
+ const e = entries.find((x) =>
+ opts.windows ? x.name.toLowerCase() === name.toLowerCase() : x.name === name
+ )
return { exists: !!e, dir: !!e?.dir }
}
}
@@ -310,10 +452,14 @@ function bufferPosFromEvent(term: Terminal, ev: MouseEvent): { col: number; row:
export interface LinkClickDeps {
getCwd(): string | undefined
+ /** See FileLinkDeps.windows. */
+ windows?: boolean
+ /** See FileLinkDeps.convention. */
+ convention?: () => PathConventionOpts | null
lookup(abs: string): Promise<{ exists: boolean; dir: boolean }>
activateFile(abs: string, dir: boolean): void
openUrl(url: string): void
- /** false for relay-remote nodes (no client fs) — they stay URL-only. */
+ /** False while no correctly-routed filesystem/dialect is available. */
fileEnabled(): boolean
}
@@ -357,9 +503,11 @@ export function installLinkClickFallback(
}
}
if (!deps.fileEnabled()) return
- for (const t of matchFileTokens(logical.text)) {
+ const convention = deps.convention ? deps.convention() : { windows: deps.windows }
+ if (!convention) return
+ for (const t of matchFileTokens(logical.text, convention)) {
if (inRange(t.startIndex, t.text.length)) {
- const abs = resolveFileToken(t.path, deps.getCwd())
+ const abs = resolveFileToken(t.path, deps.getCwd(), convention)
if (!abs) return
// Swallow the click NOW so tmux never gets the mouse report; existence is async and a
// Cmd/Ctrl+click on a path-shaped token is a deliberate open regardless of the outcome.
diff --git a/src/renderer/terminal/file-links.windows.test.ts b/src/renderer/terminal/file-links.windows.test.ts
new file mode 100644
index 000000000..bd1410487
--- /dev/null
+++ b/src/renderer/terminal/file-links.windows.test.ts
@@ -0,0 +1,184 @@
+// Ctrl+click file links for a LOCAL Windows session.
+//
+// Its own file: the POSIX cases in file-links.test.ts are the ones every existing user runs, and
+// they must stay byte-identical. The two matchers are separate functions for the same reason —
+// widening the POSIX regex's separator class would start matching Windows-shaped text inside a
+// POSIX session, where it can only ever be wrong.
+//
+// The gating fact is per-SESSION, not per-platform: an SSH project's paths are POSIX however the
+// desktop is spelled, so a remote session on a Windows machine keeps the POSIX matcher. Getting
+// that backwards would break the SSH links that already work in order to fix the local ones that
+// never did. `TerminalNode` computes it as `isWindowsPlatform() && !remoteSession`.
+
+import { describe, expect, it } from 'vitest'
+import { makeDirListingLookup, matchFileTokens, resolveFileToken } from './file-links'
+
+const WIN = { windows: true } as const
+const CWD = String.raw`C:\Users\me\proj`
+
+/** The paths of every token matched in a line. */
+const paths = (line: string, opts = WIN): string[] =>
+ matchFileTokens(line, opts).map((t) => t.path)
+
+describe('matching Windows paths', () => {
+ it('matches a drive-absolute path', () => {
+ expect(paths(String.raw`see C:\Users\me\src\a.ts for detail`)).toEqual([
+ String.raw`C:\Users\me\src\a.ts`
+ ])
+ })
+
+ it('matches a multi-segment relative path', () => {
+ expect(paths(String.raw`edited src\renderer\a.ts`)).toEqual([String.raw`src\renderer\a.ts`])
+ })
+
+ it('matches a forward-slash relative path emitted by Windows tools', () => {
+ expect(paths('edited src/renderer/a.ts')).toEqual(['src/renderer/a.ts'])
+ })
+
+ it('matches a dot-relative path', () => {
+ expect(paths(String.raw`at .\src\a.ts`)).toEqual([String.raw`.\src\a.ts`])
+ expect(paths(String.raw`at ..\sibling\a.ts`)).toEqual([String.raw`..\sibling\a.ts`])
+ })
+
+ it('carries the :line suffix, with the drive colon left alone', () => {
+ // The trap: a drive letter's colon looks exactly like the start of a `:line` suffix. It is
+ // not, because SUFFIX_RE anchors the digits at the END of the token.
+ const [t] = matchFileTokens(String.raw`C:\src\a.ts:12: error`, WIN)
+ expect(t.path).toBe(String.raw`C:\src\a.ts`)
+ expect(t.line).toBe(12)
+ })
+
+ it('handles :line:col', () => {
+ const [t] = matchFileTokens(String.raw`C:\src\a.ts:12:5`, WIN)
+ expect(t.path).toBe(String.raw`C:\src\a.ts`)
+ expect(t.line).toBe(12)
+ })
+
+ it('does not turn a bare word with a colon-number into a path', () => {
+ // `C:12` would otherwise split into path `C`, line 12.
+ expect(paths('C:12')).toEqual([])
+ expect(paths('warning:42 somewhere')).toEqual([])
+ })
+
+ it('leaves URLs to the web-links addon', () => {
+ expect(paths('open https://example.com/a/b')).toEqual([])
+ })
+
+ it('refuses a whole UNC token instead of relabelling its host as a cwd-relative directory', () => {
+ expect(paths(String.raw`opened \\server\share\a.ts`)).toEqual([])
+ expect(paths('opened //server/share/a.ts')).toEqual([])
+ })
+
+ it('strips trailing punctuation', () => {
+ expect(paths(String.raw`in C:\src\a.ts.`)).toEqual([String.raw`C:\src\a.ts`])
+ expect(paths(String.raw`(see src\a.ts)`)).toEqual([String.raw`src\a.ts`])
+ })
+})
+
+describe('the POSIX matcher is untouched by any of this', () => {
+ it('still matches POSIX paths when the flag is off', () => {
+ expect(paths('edited src/renderer/a.ts:12', {} as never)).toEqual(['src/renderer/a.ts'])
+ })
+
+ it('does not match Windows paths when the flag is off', () => {
+ // An SSH session on a Windows desktop must behave exactly as it does today.
+ expect(paths(String.raw`C:\Users\me\a.ts`, {} as never)).toEqual([])
+ })
+
+ it('defaults to POSIX with no options at all', () => {
+ expect(matchFileTokens(String.raw`C:\Users\me\a.ts`)).toEqual([])
+ expect(matchFileTokens('src/a.ts').map((t) => t.path)).toEqual(['src/a.ts'])
+ })
+})
+
+describe('resolving Windows tokens', () => {
+ it('returns a /-separated path that keeps its drive', () => {
+ // Forward slashes on purpose: makeDirListingLookup finds the parent with lastIndexOf('/'),
+ // and Windows accepts either separator for filesystem calls. A native path would make that
+ // split fail and the link would silently never resolve.
+ expect(resolveFileToken(String.raw`C:\Users\me\src\a.ts`, CWD, WIN)).toBe(
+ 'C:/Users/me/src/a.ts'
+ )
+ })
+
+ it('resolves a relative token against cwd', () => {
+ expect(resolveFileToken(String.raw`src\a.ts`, CWD, WIN)).toBe('C:/Users/me/proj/src/a.ts')
+ })
+
+ it('normalizes . and ..', () => {
+ expect(resolveFileToken(String.raw`.\src\.\a.ts`, CWD, WIN)).toBe('C:/Users/me/proj/src/a.ts')
+ expect(resolveFileToken(String.raw`..\other\a.ts`, CWD, WIN)).toBe('C:/Users/me/other/a.ts')
+ })
+
+ it('refuses .. that would climb past the drive root', () => {
+ expect(resolveFileToken(String.raw`..\..\..\..\..\evil`, CWD, WIN)).toBeNull()
+ })
+
+ it('accepts a forward-slash absolute path, which Windows tools also emit', () => {
+ expect(resolveFileToken('C:/Users/me/a.ts', CWD, WIN)).toBe('C:/Users/me/a.ts')
+ })
+
+ it('refuses a UNC path rather than half-handling it', () => {
+ // No drive to anchor on, and its first two segments are a host and a share rather than
+ // directories — resolving it would aim a directory listing at a network host.
+ expect(resolveFileToken(String.raw`\\server\share\a.ts`, CWD, WIN)).toBeNull()
+ })
+
+ it('refuses a relative token when cwd is not drive-qualified', () => {
+ expect(resolveFileToken(String.raw`src\a.ts`, undefined, WIN)).toBeNull()
+ expect(resolveFileToken(String.raw`src\a.ts`, '/home/me/proj', WIN)).toBeNull()
+ })
+
+ it('the POSIX resolver keeps its exact contract', () => {
+ expect(resolveFileToken('src/a.ts', '/home/me/proj')).toBe('/home/me/proj/src/a.ts')
+ expect(resolveFileToken('/etc/hosts', '/home/me/proj')).toBe('/etc/hosts')
+ expect(resolveFileToken('../../../../etc/passwd', '/home/me')).toBeNull()
+ })
+})
+
+describe('a path containing a space, which is not supported', () => {
+ it('matches only up to the space, rather than swallowing the sentence', () => {
+ // `C:\Program Files\...` is everywhere on Windows, but an unquoted path in terminal output
+ // gives no way to tell where it ends. Allowing spaces made the matcher take the rest of the
+ // line; the existence check would then reject it, so a spaced path would never have linked
+ // while quietly breaking the tokens around it. Documented parity with the POSIX matcher.
+ const got = matchFileTokens(String.raw`C:\Program Files\app\a.exe crashed`, WIN)
+ expect(got.map((t) => t.path)).toEqual([String.raw`C:\Program`, String.raw`Files\app\a.exe`])
+ })
+})
+
+describe('Windows existence lookup', () => {
+ it('uses Windows separators and case-insensitive entry names', async () => {
+ const listed: string[] = []
+ const lookup = makeDirListingLookup(
+ async (dir) => {
+ listed.push(dir)
+ return [{ name: 'App.TSX', dir: false }]
+ },
+ 3000,
+ () => WIN
+ )
+
+ await expect(lookup(String.raw`C:\Users\ME\src\app.tsx`)).resolves.toEqual({
+ exists: true,
+ dir: false
+ })
+ expect(listed).toEqual([String.raw`C:\Users\ME\src`])
+ })
+
+ it('shares a cached directory listing across Windows path casing', async () => {
+ let calls = 0
+ const lookup = makeDirListingLookup(
+ async () => {
+ calls++
+ return [{ name: 'a.ts', dir: false }]
+ },
+ 3000,
+ () => WIN
+ )
+
+ await lookup('C:/Users/ME/src/a.ts')
+ await lookup('c:/users/me/SRC/A.TS')
+ expect(calls).toBe(1)
+ })
+})
diff --git a/src/renderer/terminal/host-platform.test.ts b/src/renderer/terminal/host-platform.test.ts
new file mode 100644
index 000000000..f647fcbff
--- /dev/null
+++ b/src/renderer/terminal/host-platform.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { NodeTerminalApi } from '@shared/types'
+import { hostPlatformFor } from './host-platform'
+
+const apiWith = (tmuxStatus: () => Promise<unknown>): NodeTerminalApi =>
+ ({ pty: { tmuxStatus } } as unknown as NodeTerminalApi)
+
+describe('hostPlatformFor', () => {
+ it('coalesces every terminal on one core onto one immutable platform read', async () => {
+ const tmuxStatus = vi.fn(async () => ({ platform: 'win32' }))
+ const api = apiWith(tmuxStatus)
+
+ await expect(Promise.all([hostPlatformFor(api), hostPlatformFor(api)])).resolves.toEqual([
+ 'win32',
+ 'win32'
+ ])
+ expect(tmuxStatus).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps a failed read unknown', async () => {
+ const api = apiWith(vi.fn(async () => Promise.reject(new Error('offline'))))
+ await expect(hostPlatformFor(api)).resolves.toBeNull()
+ })
+
+ it('does not share a platform fact between different cores', async () => {
+ const linux = apiWith(vi.fn(async () => ({ platform: 'linux' })))
+ const windows = apiWith(vi.fn(async () => ({ platform: 'win32' })))
+ await expect(Promise.all([hostPlatformFor(linux), hostPlatformFor(windows)])).resolves.toEqual([
+ 'linux',
+ 'win32'
+ ])
+ })
+})
diff --git a/src/renderer/terminal/host-platform.ts b/src/renderer/terminal/host-platform.ts
new file mode 100644
index 000000000..70d66a97c
--- /dev/null
+++ b/src/renderer/terminal/host-platform.ts
@@ -0,0 +1,18 @@
+import type { NodeTerminalApi } from '@shared/types'
+
+// A canvas can mount hundreds of terminals at once. The host platform is immutable for the life of
+// one core API, while tmuxStatus() may re-run command discovery when tmux is absent, so coalesce the
+// read per API identity instead of turning node mount into hundreds of process probes.
+const byApi = new WeakMap<NodeTerminalApi, Promise<string | null>>()
+
+/** `process.platform` of the core that owns `api`, or null when it could not be observed. */
+export function hostPlatformFor(api: NodeTerminalApi): Promise<string | null> {
+ const cached = byApi.get(api)
+ if (cached) return cached
+ const read = api.pty.tmuxStatus().then(
+ (status) => status.platform,
+ () => null
+ )
+ byApi.set(api, read)
+ return read
+}
diff --git a/src/shared/platform-utils.ts b/src/shared/platform-utils.ts
index b0e3662ca..f068df552 100644
--- a/src/shared/platform-utils.ts
+++ b/src/shared/platform-utils.ts
@@ -14,6 +14,13 @@ export function isMacPlatform(): boolean {
return /Mac/i.test(navigator.platform || navigator.userAgent)
}
+/** True on Windows (Electron renderer or browser — same `navigator`-based detection as
+ * `isMacPlatform`, so it is correct in both the desktop app and a Server Edition browser tab). */
+export function isWindowsPlatform(): boolean {
+ if (typeof navigator === 'undefined') return false
+ return /Win/i.test(navigator.platform || navigator.userAgent)
+}
+
/** Rewrite mac chord notation in a hint string for the current platform. */
export function hintLabel(text: string, isMac: boolean = isMacPlatform()): string {
if (isMac) return text
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 6e0059745..51e81e220 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -603,7 +603,9 @@ export interface TmuxStatus {
installCommand: string | null
/** Button caption for installCommand (e.g. "Install Homebrew + tmux" when brew must come first). */
installLabel: string | null
- platform: string
+ /** `process.platform` of the core that owns the sessions/filesystem. `null` means the read
+ * failed; callers must not substitute the browser's platform for a server or relay core. */
+ platform: string | null
}
/**