Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(explorer): download files off the machine the tree belongs to
enes2253512826db
diff --git a/src/core/download-name.test.ts b/src/core/download-name.test.tsnew file mode 100644index 000000000..067d11cf2--- /dev/null+++ b/src/core/download-name.test.ts@@ -0,0 +1,43 @@+import { describe, it, expect } from 'vitest'+import { candidateName, safeDownloadBasename } from './download-name'++describe('safeDownloadBasename', () => {+ it('takes the basename of a remote path', () => {+ expect(safeDownloadBasename('/srv/app/docs/notes.md')).toBe('notes.md')+ expect(safeDownloadBasename('~/work/report.pdf')).toBe('report.pdf')+ expect(safeDownloadBasename('/srv/app/docs/')).toBe('docs')+ })++ it('refuses paths that name nothing writable', () => {+ for (const p of ['', '/', '.', '..', '~', '/srv/..']) expect(safeDownloadBasename(p)).toBeNull()+ })++ it('neutralizes separators and control characters rather than refusing the download', () => {+ expect(safeDownloadBasename('/srv/a\\b.txt')).toBe('a_b.txt')+ expect(safeDownloadBasename('/srv/we:ird?.txt')).toBe('we_ird_.txt')+ expect(safeDownloadBasename('/srv/nl\nname')).toBe('nl_name')+ })++ it('cannot produce a traversal component', () => {+ // A remote file literally named `..` (or `../x` as one component) must never come back as one.+ expect(safeDownloadBasename('/srv/app/..')).toBeNull()+ expect(safeDownloadBasename('/srv/app/...')).toBe('...')+ })+})++describe('candidateName', () => {+ it('leaves the first attempt alone', () => {+ expect(candidateName('notes.md', 1)).toBe('notes.md')+ expect(candidateName('notes.md', 0)).toBe('notes.md')+ })++ it('numbers before the extension', () => {+ expect(candidateName('notes.md', 2)).toBe('notes (2).md')+ expect(candidateName('archive.tar.gz', 3)).toBe('archive.tar (3).gz')+ })++ it('appends at the end when there is no extension to protect', () => {+ expect(candidateName('README', 2)).toBe('README (2)')+ expect(candidateName('.bashrc', 2)).toBe('.bashrc (2)')+ })+})diff --git a/src/core/download-name.ts b/src/core/download-name.tsnew file mode 100644index 000000000..51b827ee1--- /dev/null+++ b/src/core/download-name.ts@@ -0,0 +1,34 @@+// Naming rules for a file pulled down from a remote host. Pure and shell-free so the SSH manager+// (and any later transport) share one answer, and so the awkward cases are testable.+//+// The remote name is the only attacker-influenced part of a download's LOCAL path: it comes off+// another machine's filesystem, and it ends up as a write target here. So it is basenamed and+// sanitized before it is joined to anything — never trusted as a path component on its own.+import path from 'node:path'++/**+ * The local filename for a remote path, or null when the remote path names nothing writable+ * (`/`, `.`, `..`, empty). Separators and control characters are replaced rather than rejected:+ * a name like `a\b.txt` is perfectly legal on the remote POSIX host but is a PATH on Windows,+ * and silently refusing the download would be worse than renaming it.+ */+export function safeDownloadBasename(remotePath: string): string | null {+ const base = path.posix.basename(remotePath.replace(/\/+$/, ''))+ if (!base || base === '.' || base === '..' || base === '~') return null+ // eslint-disable-next-line no-control-regex+ const safe = base.replace(/[\\/:*?"<>|\x00-\x1f]/g, '_').trim()+ return safe && safe !== '.' && safe !== '..' ? safe : null+}++/**+ * The n-th candidate name for a collision: `notes.md`, `notes (2).md`, `notes (3).md`. The counter+ * goes before the extension (Finder/Explorer convention) so the file still opens in the right app;+ * a dotfile (`.bashrc`) has no extension to speak of and takes the suffix at the end.+ */+export function candidateName(name: string, attempt: number): string {+ if (attempt <= 1) return name+ const dot = name.lastIndexOf('.')+ // `dot <= 0` covers both "no extension" and a leading-dot name like `.bashrc`.+ if (dot <= 0) return `${name} (${attempt})`+ return `${name.slice(0, dot)} (${attempt})${name.slice(dot)}`+}diff --git a/src/core/download-tickets.test.ts b/src/core/download-tickets.test.tsnew file mode 100644index 000000000..721c9e828--- /dev/null+++ b/src/core/download-tickets.test.ts@@ -0,0 +1,44 @@+import { describe, it, expect } from 'vitest'+import { DownloadTickets } from './download-tickets'++describe('DownloadTickets', () => {+ it('redeems a ticket exactly once', () => {+ const t = new DownloadTickets()+ const token = t.issue('/srv/app/notes.md', false)+ expect(t.redeem(token)).toMatchObject({ path: '/srv/app/notes.md', dir: false })+ expect(t.redeem(token)).toBeNull()+ })++ it('refuses an expired ticket (and does not leak it back on a later call)', () => {+ let now = 1_000+ const t = new DownloadTickets({ ttlMs: 100, now: () => now })+ const token = t.issue('/srv/app/big.zip', false)+ now = 1_101+ expect(t.redeem(token)).toBeNull()+ now = 1_050+ expect(t.redeem(token)).toBeNull()+ })++ it('refuses an unknown token', () => {+ expect(new DownloadTickets().redeem('nope')).toBeNull()+ })++ it('mints unguessable, distinct tokens', () => {+ const t = new DownloadTickets()+ const tokens = new Set(Array.from({ length: 50 }, () => t.issue('/x', false)))+ expect(tokens.size).toBe(50)+ for (const token of tokens) expect(token.length).toBeGreaterThanOrEqual(30)+ })++ it('carries the directory flag through', () => {+ const t = new DownloadTickets()+ expect(t.redeem(t.issue('/srv/app/docs', true))).toMatchObject({ dir: true })+ })++ it('evicts under the cap without dropping a freshly minted ticket', () => {+ const t = new DownloadTickets()+ for (let i = 0; i < 300; i++) t.issue(`/x/${i}`, false)+ const fresh = t.issue('/x/fresh', false)+ expect(t.redeem(fresh)).toMatchObject({ path: '/x/fresh' })+ })+})diff --git a/src/core/download-tickets.ts b/src/core/download-tickets.tsnew file mode 100644index 000000000..fd583f0ea--- /dev/null+++ b/src/core/download-tickets.ts@@ -0,0 +1,71 @@+// One-shot, short-lived tickets that let an ALREADY-AUTHENTICATED caller pull a file down over+// plain HTTP instead of through the RPC bridge.+//+// Why tickets at all: the RPC path (`fs.readBinary`) base64s the whole file into one message and+// is capped at FS_READ_BINARY_MAX_BYTES — fine for an image preview, useless as a download+// transport. A plain HTTP GET streams, shows the browser's own progress, and has no cap. But the+// GET arrives as a top-level navigation, so the safest thing it can carry is a token that means+// nothing on its own: the ticket names the path, so the download route never parses a caller-+// supplied path and needs no jail of its own (the same rule board-log follows — the path always+// derives from the server's own state).+//+// Threat model is otherwise unchanged from `fs-handlers.ts`: minting requires a valid session, and+// whoever has one already has a terminal on this machine. The TTL and the one-shot redeem are+// there so a URL that leaks (history, a shared screen, a proxy log) is inert seconds later.+import { randomBytes } from 'node:crypto'++export interface DownloadTicketEntry {+ path: string+ /** True when the path is a directory — the route streams it as a `.tar.gz`. */+ dir: boolean+ expiresAt: number+}++/** Long enough for a click → navigation round trip on a slow tab, short enough to be worthless+ * if the URL is ever seen by someone else. */+export const DOWNLOAD_TICKET_TTL_MS = 30_000+/** Backstop so a caller that mints and never redeems can't grow the map without bound. */+const MAX_TICKETS = 256++export class DownloadTickets {+ private tickets = new Map<string, DownloadTicketEntry>()+ private ttlMs: number+ private now: () => number++ constructor(opts: { ttlMs?: number; now?: () => number } = {}) {+ this.ttlMs = opts.ttlMs ?? DOWNLOAD_TICKET_TTL_MS+ this.now = opts.now ?? Date.now+ }++ /** Mint a token for `path`. The token is the ONLY thing that travels in the URL. */+ issue(path: string, dir: boolean): string {+ this.sweep()+ // Oldest-first eviction under the cap: a flood of un-redeemed tickets expires the stale ones+ // rather than the one the user is about to click.+ while (this.tickets.size >= MAX_TICKETS) {+ const oldest = this.tickets.keys().next()+ if (oldest.done) break+ this.tickets.delete(oldest.value)+ }+ const token = randomBytes(24).toString('base64url')+ this.tickets.set(token, { path, dir, expiresAt: this.now() + this.ttlMs })+ return token+ }++ /**+ * Redeem a token, or null when it is unknown, already used, or expired. One-shot: the entry is+ * dropped whether or not the transfer that follows succeeds. A retry mints a new ticket — which+ * is cheap — and that is what keeps a captured URL from being replayable.+ */+ redeem(token: string): DownloadTicketEntry | null {+ const entry = this.tickets.get(token)+ if (!entry) return null+ this.tickets.delete(token)+ return entry.expiresAt > this.now() ? entry : null+ }++ private sweep(): void {+ const t = this.now()+ for (const [token, entry] of this.tickets) if (entry.expiresAt <= t) this.tickets.delete(token)+ }+}diff --git a/src/core/fs-handlers.ts b/src/core/fs-handlers.tsindex fa1c133fb..0ad899f04 100644--- a/src/core/fs-handlers.ts+++ b/src/core/fs-handlers.ts@@ -1,6 +1,7 @@import type { CorePlatform } from './platform'import * as fsOps from './fs-ops'import { IPC } from '../shared/ipc'+import type { DownloadTicket } from '../shared/types'/** The fs.* + files.quickOpen RPC surface, registered ONCE for every shell (Electron main, the* Server Edition, and — through the Electron platform's handler table — a relay peer). The logic@@ -9,7 +10,19 @@ import { IPC } from '../shared/ipc'* It lives here, and not in either shell, so the two can never drift: the desktop used to register* these on raw `ipcMain`, which made them unreachable for a peer (a peer has no webContents).* Threat model unchanged: whoever can reach these already has a terminal on this machine. */-export function registerFsHandlers(platform: CorePlatform): void {+export function registerFsHandlers(+ platform: CorePlatform,+ deps: {+ /**+ * Mint an HTTP download ticket for `path` — supplied ONLY by a shell that has an HTTP surface+ * to redeem it on (the Server Edition). Absent everywhere else, and the handler then answers+ * `null` rather than going unregistered: the renderer awaits this to decide whether to offer a+ * download at all, and an unregistered channel would reject instead, which reads as an error+ * rather than as "not offered here".+ */+ issueDownloadTicket?: (path: string) => Promise<DownloadTicket | null>+ } = {}+): void {platform.handle(IPC.fsList, (dirPath: string) => fsOps.listDir(dirPath))platform.handle(IPC.fsRead, (filePath: string) => fsOps.readText(filePath))platform.handle(IPC.fsReadBinary, (filePath: string) => fsOps.readBinary(filePath))@@ -19,4 +32,7 @@ export function registerFsHandlers(platform: CorePlatform): void {platform.handle(IPC.fsMkdir, (dirPath: string) => fsOps.makeDir(dirPath))platform.handle(IPC.fsExists, (p: string) => fsOps.pathExists(p))platform.handle(IPC.filesQuickOpen, (cwd: string) => fsOps.listQuickOpenFiles(cwd))+ platform.handle(IPC.filesDownloadTicket, (p: string) =>+ deps.issueDownloadTicket ? deps.issueDownloadTicket(p) : Promise.resolve(null)+ )}diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.tsindex a60406ebd..73a1ac09c 100644--- a/src/core/remote-ssh/control-master.test.ts+++ b/src/core/remote-ssh/control-master.test.ts@@ -17,7 +17,9 @@ import {hookForwardCancelArgs,remoteHookEnvArgs,remoteEndpointFileContents,- scpArgs+ scpArgs,+ scpDownArgs,+ remoteScpPath} from './control-master'const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }@@ -236,6 +238,38 @@ describe('scpArgs', () => {})})+describe('scpDownArgs', () => {+ it('pulls remote → local over the master, with the remote side after host: (never an option)', () => {+ const j = scpDownArgs(conn, '/s.sock', '/srv/app/notes.md', '/Users/e/Downloads/notes.md.part').join(' ')+ expect(j).toContain('-o ControlPath=/s.sock')+ expect(j).toContain('-o BatchMode=yes')+ expect(j).toContain('-P 2222')+ expect(j).toContain('[email protected]:/srv/app/notes.md /Users/e/Downloads/notes.md.part')+ expect(j).not.toContain(' -r ')+ })++ it('adds -r for a directory tree', () => {+ expect(scpDownArgs(conn, '/s.sock', '/srv/app/docs', '/d/docs.part', true)).toContain('-r')+ })++ it('a leading `-` in the remote path cannot become an scp option (it rides behind host:)', () => {+ const args = scpDownArgs(conn, '/s.sock', '-oProxyCommand=touch /tmp/pwned', '/d/x')+ expect(args).not.toContain('-oProxyCommand=touch /tmp/pwned')+ expect(args).toContain('[email protected]:-oProxyCommand=touch /tmp/pwned')+ })++ it('sends a ~-relative path as RELATIVE — SFTP has no shell to expand the tilde', () => {+ // The regression this guards: an SSH project's remoteCwd is home-relative, so the Explorer's+ // paths are `~/…`; a literal `~` made scp look for a directory actually named `~`.+ expect(remoteScpPath('~/work/report.pdf')).toBe('work/report.pdf')+ expect(remoteScpPath('~')).toBe('.')+ expect(remoteScpPath('/srv/app/x')).toBe('/srv/app/x')+ expect(scpDownArgs(conn, '/s.sock', '~/a b.txt', '/d/x').join(' ')).toContain(+ '[email protected]:a b.txt /d/x'+ )+ })+})+describe('listDirArgs', () => {it('lists directory entries of a quoted absolute path', () => {expect(listDirArgs(conn, '/s.sock', '/srv/app')).toEqual([diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.tsindex db02a5fda..dd695f98a 100644--- a/src/core/remote-ssh/control-master.ts+++ b/src/core/remote-ssh/control-master.ts@@ -214,6 +214,40 @@ export function scpArgs(conn: SshConnection, controlPath: string, localPath: strreturn args}+/**+ * The remote side of an scp argument. A `~`-prefixed path (SSH projects default to a home-relative+ * `remoteCwd`, so the Explorer's paths inherit it) must NOT travel as a literal `~`: modern scp+ * speaks SFTP with no remote shell to expand it, and the transfer would fail looking for a+ * directory actually named `~`. A RELATIVE path is the portable answer — SFTP resolves it against+ * the login directory, and legacy (shell-mode) scp lands in the same place.+ */+export function remoteScpPath(p: string): string {+ if (p === '~') return '.'+ return p.startsWith('~/') ? p.slice(2) : p+}++/**+ * scp argv that pulls `remotePath` DOWN to `localPath` over the project's ControlMaster — the+ * mirror of `scpArgs`. `-r` copies a directory tree. Direction is the only real difference: the+ * remote path is still passed raw after `host:` (see scpArgs — quoting it would make the SFTP+ * server look for a literally-quoted name), and it can never be read as an option because it is+ * concatenated behind `user@host:`. `localPath` is built by MAIN (never a renderer string), so+ * the flag-smuggling guard that `uploadFile` needs has no counterpart here.+ */+export function scpDownArgs(+ conn: SshConnection,+ controlPath: string,+ remotePath: string,+ localPath: string,+ recursive = false+): string[] {+ const args = ['-o', 'ControlMaster=no', '-o', `ControlPath=${controlPath}`, '-o', 'BatchMode=yes', '-P', String(conn.port ?? 22)]+ if (conn.identityFile) args.push('-i', conn.identityFile)+ if (recursive) args.push('-r')+ args.push(`${conn.user}@${conn.host}:${remoteScpPath(remotePath)}`, localPath)+ return args+}+/*** Reverse-forward the local hook server's loopback TCP port to a remote unix socket over the* existing master (`ssh -O forward -R <remoteSock>:127.0.0.1:<hookPort>`), so remote hook scriptsdiff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex e94da7224..bcd9c4b8d 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -1,4 +1,6 @@import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'import { afterEach, describe, expect, it, vi } from 'vitest'import { SshProjectManager, lastSshErrorLine } from './ssh-project'import { controlPathFor } from '../../core/remote-ssh/control-master'@@ -359,6 +361,104 @@ describe('SshProjectManager', () => {expect((await unknown.mgr.remoteAccountAdd('p3', 'acc1'))?.versionSupported).toBe(true)})+ // --- downloadFile (remote → this machine) -------------------------------------------------+ // These run against a REAL temp directory: collision resolution, the `.part` staging file and+ // the rename are filesystem behavior, and mocking the fs would only test the mock.+ describe('downloadFile', () => {+ const tmpDirs: string[] = []+ async function destDir(): Promise<string> {+ const d = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-dl-'))+ tmpDirs.push(d)+ return d+ }+ afterEach(async () => {+ for (const d of tmpDirs.splice(0)) await fs.rm(d, { recursive: true, force: true })+ })++ /** `isDir` decides what the remote `test -d` probe answers; scp "succeeds" by creating the+ * local target it was told to write, so the rename step is exercised for real. */+ function makeDlMgr(isDir = false, scpCode = 0) {+ const scpCalls: string[][] = []+ const run = vi.fn(async (args: string[]) => ({+ code: args.join(' ').includes('test -d') ? (isDir ? 0 : 1) : 0,+ stdout: ''+ }))+ const runScp = vi.fn(async (args: string[]) => {+ scpCalls.push(args)+ if (scpCode === 0) {+ const local = args[args.length - 1]+ if (isDir) await fs.mkdir(local, { recursive: true })+ else await fs.writeFile(local, 'payload')+ }+ return { code: scpCode }+ })+ 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()+ })+ return { mgr, scpCalls, runScp }+ }++ it('lands the file under its remote basename and stages through .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'))+ expect(await fs.readdir(dir)).toEqual(['notes.md'])+ })++ it('never overwrites an existing file — it takes the next (n) name', async () => {+ const { mgr } = makeDlMgr()+ await mgr.connect('p1', conn, '/srv/repo')+ const dir = await destDir()+ await fs.writeFile(path.join(dir, 'notes.md'), 'mine')+ 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.readFile(path.join(dir, 'notes.md'), 'utf8')).toBe('mine')+ })++ 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')+ const dir = await destDir()+ const res = await mgr.downloadFile('p1', '/srv/repo/docs', dir)+ expect(res).toMatchObject({ ok: true, dir: true })+ expect(scpCalls[0]).toContain('-r')+ })++ it('a failed transfer leaves nothing behind — no target, no .part', async () => {+ 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([])+ })++ it('refuses a remote path that names nothing downloadable, without invoking scp', async () => {+ const { mgr, runScp } = makeDlMgr()+ await mgr.connect('p1', conn, '/srv/repo')+ const dir = await destDir()+ for (const p of ['/', '/srv/repo/..', '~']) {+ expect((await mgr.downloadFile('p1', p, dir)).ok).toBe(false)+ }+ expect(runScp).not.toHaveBeenCalled()+ })++ it('fails (never throws) when the project is not connected', async () => {+ const { mgr } = makeDlMgr()+ expect(await mgr.downloadFile('nope', '/x/y.txt', await destDir())).toMatchObject({ ok: false })+ })+ })+it('uploadFile fails open (null) when not connected', async () => {const { mgr } = makeMgr()expect(await mgr.uploadFile('nope', '/x', 'x')).toBeNull()diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 144a2cf1b..b2eabf55e 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -4,7 +4,8 @@ import { spawn, execFile, execFileSync } from 'child_process'import { app, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, sshHostKey, type SshConnection } from '../../shared/ssh'-import type { SshProjectStatusEvent } from '../../shared/types'+import type { DownloadResult, SshProjectStatusEvent } from '../../shared/types'+import { candidateName, safeDownloadBasename } from '../../core/download-name'import { remoteAccountConfigDir, isSupportedClaudeVersion } from '../../core/claude-accounts-core'import { supportsAutoPermissionMode, supportsFullscreenTui } from '../../shared/agents/config'import {@@ -17,6 +18,7 @@ import {remoteTmuxKillArgs,childArgs,scpArgs,+ scpDownArgs,RMT_TMUX_SOCKET} from '../../core/remote-ssh/control-master'import { claudeVersionProbeCommand, parseClaudeVersionProbe } from '../../core/remote-ssh/claude-version-probe'@@ -52,6 +54,9 @@ interface Runners {* a CLI doesn't change under a live connection; the next connect re-probes anyway. */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+/** Cap on how much master stderr we retain (a misconfigured host can spew) — enough for the error. */const MASTER_STDERR_CAP = 8 * 1024@@ -451,6 +456,62 @@ export class SshProjectManager {}}+ /**+ * Pull a remote file (or directory tree) down to `destDir` over the project's ControlMaster —+ * the mirror of `uploadFile`, and what the Explorer's Download action runs on an SSH project.+ *+ * Three things carry the safety here:+ * - **The local path is ours.** `destDir` is supplied by main (`app.getPath('downloads')` or a+ * 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.+ */+ 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.' }+ 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" —+ // but `test -d` failing on a live master overwhelmingly means "not a directory", and the+ // worst case of guessing wrong is a plain scp error, so this stays fail-open.+ 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))+ 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 fs.rename(partPath, finalPath)+ return { ok: true, localPath: finalPath, dir: isDir }+ } catch {+ return { ok: false, error: 'The download could not be completed.' }+ }+ }++ /** First `<dir>/<name>` variant that exists neither as the target nor as a leftover `.part`. */+ private async freeDestPath(destDir: string, name: string): Promise<string> {+ 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+ }+ // Every readable variant is taken: fall back to a stamped name rather than overwriting one.+ return path.join(destDir, candidateName(name, Date.now()))+ }+/*** Authoritatively end the given nodes' REMOTE tmux sessions over the project's live master.* Called on project delete BEFORE disconnect, so the remote `nt-<id>` sessions are killed@@ -890,5 +951,11 @@ export function initSshProject(ipcMain.handle(IPC.sshUploadFile, (_e, projectId: string, localPath: string, fileName: string) =>mgr.uploadFile(projectId, localPath, fileName))+ // The DESTINATION is resolved here, in main: the OS Downloads folder unless the renderer passed+ // a directory the user picked in the native folder dialog. The renderer never gets to name an+ // arbitrary local write target for a remote payload.+ ipcMain.handle(IPC.sshDownloadFile, (_e, projectId: string, remotePath: string, destDir?: string) =>+ mgr.downloadFile(projectId, remotePath, destDir || app.getPath('downloads'))+ )return mgr}diff --git a/src/preload/index.ts b/src/preload/index.tsindex fccd18742..b4d1c2a4a 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -170,6 +170,8 @@ const api: NodeTerminalApi = {mkdir: (projectId, dir) => ipcRenderer.invoke(IPC.sshMkdir, projectId, dir),uploadFile: (projectId, localPath, fileName) =>ipcRenderer.invoke(IPC.sshUploadFile, projectId, localPath, fileName),+ downloadFile: (projectId, remotePath, destDir) =>+ ipcRenderer.invoke(IPC.sshDownloadFile, projectId, remotePath, destDir),onStatus: (cb) => {const h = (_e: unknown, e: unknown) => cb(e as never)ipcRenderer.on(IPC.sshProjectStatus, h)@@ -268,7 +270,11 @@ const api: NodeTerminalApi = {}},files: {- quickOpen: (cwd: string) => ipcRenderer.invoke(IPC.filesQuickOpen, cwd)+ quickOpen: (cwd: string) => ipcRenderer.invoke(IPC.filesQuickOpen, cwd),+ // Desktop has no HTTP surface to redeem a ticket on — the core handler answers null here, and+ // the Explorer reads that as "this shell downloads over scp instead" (SSH) or "the file is+ // already on this machine" (local project).+ downloadTicket: (p: string) => ipcRenderer.invoke(IPC.filesDownloadTicket, p)},updates: {onAvailable: (listener) => {diff --git a/src/renderer/bridge/runtime.ts b/src/renderer/bridge/runtime.tsnew file mode 100644index 000000000..dd0c259dc--- /dev/null+++ b/src/renderer/bridge/runtime.ts@@ -0,0 +1,22 @@+// Which shell is this renderer running under?+//+// Almost nothing needs to ask — the whole point of `window.nodeTerminal` is that the two shells+// look alike, and a feature that differs should degrade through a member that answers "not here"+// (the `satisfies NodeTerminalApi` doctrine). But a couple of AFFORDANCES have to be decided+// before any call is made: "Reveal in Finder" is inert in a browser tab, and a download is offered+// by a different route on each shell. Probing by minting a ticket would be worse than asking.+//+// The flag is set by the boot switch in `main.tsx` — the one place that already knows, because it+// is the place that installs the bridge. Kept in its own module (rather than on `window`) so the+// desktop bundle never pulls the bridge in just to read it.+let browserRuntime = false++/** Called by the boot switch when it installs the WS bridge (i.e. there is no Electron preload). */+export function markBrowserRuntime(): void {+ browserRuntime = true+}++/** True in a browser tab (Server Edition), false under Electron. */+export function isBrowserRuntime(): boolean {+ return browserRuntime+}diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 18e503160..4f44c1591 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -138,6 +138,7 @@ export function buildStubApi(): Omit<listDir: U('sshProject.listDir'),mkdir: U('sshProject.mkdir'),uploadFile: U('sshProject.uploadFile'),+ downloadFile: U('sshProject.downloadFile'),onStatus: noopUnsub},sshFs: {diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex c7cd9e246..335f28d0e 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -21,6 +21,7 @@ import {type ClaudeApi,type ClaudeCliCaps,type ContextApi,+ type DownloadTicket,type FilesApi,type FsApi,type GitApi,@@ -381,7 +382,11 @@ export function buildFilesApi(}const files: FilesApi = {- quickOpen: (cwd) => client.request(IPC.filesQuickOpen, cwd) as Promise<string[]>+ quickOpen: (cwd) => client.request(IPC.filesQuickOpen, cwd) as Promise<string[]>,+ // A REAL implementation, not a stub: this is the browser's only way to get a file off the+ // server, and it deliberately does not stream through this socket — it mints a ticket the+ // browser redeems with a plain GET (src/server/download.ts).+ downloadTicket: (p) => client.request(IPC.filesDownloadTicket, p) as Promise<DownloadTicket | null>}const context: ContextApi = {diff --git a/src/renderer/components/ExplorerPanel.tsx b/src/renderer/components/ExplorerPanel.tsxindex 3707155b1..b5ef93597 100644--- a/src/renderer/components/ExplorerPanel.tsx+++ b/src/renderer/components/ExplorerPanel.tsx@@ -7,6 +7,8 @@ import { sshFs } from '../terminal/ssh-fs'import { useSession } from '../session/session'import { promptDialog } from './promptDialog'import { ancestorDirs, createTargetDir, newEntryPath, parentDir } from '../lib/explorerCreate'+import { canRevealLocally, downloadRoute, triggerBrowserDownload } from '../lib/download'+import { isBrowserRuntime } from '../bridge/runtime'interface ExplorerPanelProps {onClose: () => void@@ -21,6 +23,18 @@ interface ExplorerPanelProps {type ContextFn = (x: number, y: number, path: string, isDir: boolean) => voidtype OpenFn = (path: string) => voidtype SelectFn = (path: string) => void+type DownloadFn = (path: string, isDir: boolean) => void++/** One entry in the drawer's download strip. `localPath` is set once a desktop (scp) download has+ * landed, which is what makes it revealable. */+interface DownloadItem {+ id: number+ name: string+ dir: boolean+ status: 'running' | 'done' | 'error'+ detail?: string+ localPath?: string+}// Surface a transient error message (matches the Canvas listener at Canvas.tsx:380).const toast = (message: string): void => {@@ -50,7 +64,8 @@ function TreeEntry({selected,onContext,onOpenFile,- onSelect+ onSelect,+ onDownload}: {entry: DirEntrypath: string@@ -62,6 +77,9 @@ function TreeEntry({onContext: ContextFnonOpenFile: OpenFnonSelect: SelectFn+ /** Omitted where this tree can't be downloaded from (see lib/download.ts) — the row then has+ * no download button at all, rather than one that fails on click. */+ onDownload?: DownloadFn}) {const open = useExplorer((s) => (s.expandedByProject[projectId] ?? []).includes(path))const [children, setChildren] = useState<DirEntry[] | null>(null)@@ -131,6 +149,20 @@ function TreeEntry({<span className={`ex-chevron${entry.dir ? '' : ' hidden'}${open ? ' open' : ''}`}>›</span><EntryIcon dir={entry.dir} /><span className="ex-name">{entry.name}</span>+ {onDownload && (+ <button+ className="ex-dl"+ title={entry.dir ? `Download ${entry.name} folder` : `Download ${entry.name}`}+ aria-label="Download"+ // The row's own onClick opens/expands — a download must not also do that.+ onClick={(e) => {+ e.stopPropagation()+ onDownload(path, entry.dir)+ }}+ >+ ⤓+ </button>+ )}</div>{entry.dir &&open &&@@ -147,6 +179,7 @@ function TreeEntry({onContext={onContext}onOpenFile={onOpenFile}onSelect={onSelect}+ onDownload={onDownload}/>))}</>@@ -184,6 +217,74 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelPropconst [selected, setSelected] = useState<string | null>(null)const [menu, setMenu] = useState<{ x: number; y: number; path: string; dir: boolean } | null>(null)+ // Downloading is only meaningful when the tree is NOT this machine's own filesystem, and the+ // transport differs per shell — the whole decision is the pure `downloadRoute` (lib/download.ts).+ const session = useSession()+ const dlCtx = useMemo(+ () => ({ browser: isBrowserRuntime(), ssh: !!ssh, source: session.source }),+ [ssh, session.source]+ )+ const route = downloadRoute(dlCtx)+ const [downloads, setDownloads] = useState<DownloadItem[]>([])+ const dlSeq = useRef(0)++ const patchDownload = useCallback((id: number, patch: Partial<DownloadItem>): void => {+ setDownloads((list) => list.map((d) => (d.id === id ? { ...d, ...patch } : d)))+ }, [])++ /**+ * Download one entry. `destDir` (desktop only) overrides the OS Downloads folder — it comes from+ * the native folder picker, and main still builds the final path itself.+ *+ * Both routes report through the same strip, but they finish differently on purpose: an scp pull+ * is ours from start to finish, so it ends as a revealable local file; an HTTP download is handed+ * to the BROWSER at the first byte, and its own download shelf owns the progress from there — so+ * the strip's job is just to cover the mint round-trip and then get out of the way.+ */+ const download = useCallback(+ async (path: string, isDir: boolean, destDir?: string): Promise<void> => {+ if (route === 'none') return+ const id = ++dlSeq.current+ const name = path.split('/').filter(Boolean).pop() || path+ setDownloads((list) => [...list, { id, name, dir: isDir, status: 'running' }])+ try {+ if (route === 'scp') {+ const res = await window.nodeTerminal.sshProject.downloadFile(project!.id, path, destDir)+ if (res.ok) patchDownload(id, { status: 'done', localPath: res.localPath })+ else patchDownload(id, { status: 'error', detail: res.error })+ return+ }+ const ticket = await session.api.files.downloadTicket(path)+ if (!ticket) {+ patchDownload(id, { status: 'error', detail: 'Downloading is not available here.' })+ return+ }+ triggerBrowserDownload(ticket.url, ticket.name)+ patchDownload(id, { status: 'done', detail: 'Sent to your browser downloads.' })+ // The browser has it now; the strip row would just be noise from here on.+ setTimeout(() => setDownloads((list) => list.filter((d) => d.id !== id)), 4000)+ } catch {+ patchDownload(id, { status: 'error', detail: 'The download could not be started.' })+ }+ },+ [route, project, session.api, patchDownload]+ )++ const onDownload = useMemo<DownloadFn | undefined>(+ () => (route === 'none' ? undefined : (p, isDir) => void download(p, isDir)),+ [route, download]+ )++ /** "Download to…" — desktop only (the browser has no native folder picker, and its own download+ * location is a browser setting, not ours to ask about). */+ const downloadTo = useCallback(+ async (path: string, isDir: boolean): Promise<void> => {+ const dir = await window.nodeTerminal.dialog.selectFolder()+ if (dir) await download(path, isDir, dir)+ },+ [download]+ )+useEffect(() => {if (cwd) fs.list(cwd).then(setRoots)else setRoots(null)@@ -298,10 +399,40 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProponContext={onContext}onOpenFile={handleOpenFile}onSelect={setSelected}+ onDownload={onDownload}/>))}</div>)}++ {downloads.length > 0 && (+ <div className="ex-dls">+ {downloads.map((d) => (+ <div key={d.id} className={`ex-dls__row ${d.status}`}>+ {d.status === 'running' && <span className="ex-dls__spin" />}+ <span className="ex-dls__name" title={d.detail || d.localPath || d.name}>+ {d.name}+ {d.dir && d.status === 'running' ? ' (folder)' : ''}+ </span>+ {d.status === 'done' && d.localPath && (+ <button+ className="ex-dls__act"+ onClick={() => window.nodeTerminal.shell.reveal(d.localPath!)}+ >+ Reveal+ </button>+ )}+ <button+ className="ex-dls__act"+ aria-label="Dismiss"+ onClick={() => setDownloads((list) => list.filter((x) => x.id !== d.id))}+ >+ ×+ </button>+ </div>+ ))}+ </div>+ )}</aside>{menu &&@@ -329,6 +460,35 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProp>New Folder…</button>+ {route !== 'none' && (+ <>+ <div className="ctx-sep" />+ <button+ className="ctx-item"+ onClick={() => {+ const m = menu+ setMenu(null)+ void download(m.path, m.dir)+ }}+ >+ {/* scp -r brings a folder down AS a folder; the HTTP route has to archive it+ on the fly, and the user should know what will land in Downloads. */}+ {menu.dir ? (route === 'http' ? 'Download Folder (.tar.gz)' : 'Download Folder') : 'Download'}+ </button>+ {route === 'scp' && (+ <button+ className="ctx-item"+ onClick={() => {+ const m = menu+ setMenu(null)+ void downloadTo(m.path, m.dir)+ }}+ >+ Download to…+ </button>+ )}+ </>+ )}<div className="ctx-sep" /><buttonclassName="ctx-item"@@ -348,16 +508,22 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProp>Copy Relative Path</button>- <div className="ctx-sep" />- <button- className="ctx-item"- onClick={() => {- window.nodeTerminal.shell.reveal(menu.path)- setMenu(null)- }}- >- Reveal in Finder- </button>+ {/* Only where it can work: revealing an SSH project's REMOTE path in the local file+ manager did nothing, and in a browser tab the whole member is an inert stub. */}+ {canRevealLocally(dlCtx) && (+ <>+ <div className="ctx-sep" />+ <button+ className="ctx-item"+ onClick={() => {+ window.nodeTerminal.shell.reveal(menu.path)+ setMenu(null)+ }}+ >+ Reveal in Finder+ </button>+ </>+ )}</div></>,document.bodydiff --git a/src/renderer/lib/download.test.ts b/src/renderer/lib/download.test.tsnew file mode 100644index 000000000..fd5fca89b--- /dev/null+++ b/src/renderer/lib/download.test.ts@@ -0,0 +1,37 @@+import { describe, it, expect } from 'vitest'+import { canRevealLocally, downloadRoute } from './download'++describe('downloadRoute', () => {+ it('pulls an SSH project over scp on the desktop', () => {+ expect(downloadRoute({ browser: false, ssh: true, source: 'local' })).toBe('scp')+ })++ it('serves every browser tree over HTTP — including a "local" project, which is on the server', () => {+ expect(downloadRoute({ browser: true, ssh: false, source: 'local' })).toBe('http')+ })++ it('offers nothing for a desktop local project (the file is already here)', () => {+ expect(downloadRoute({ browser: false, ssh: false, source: 'local' })).toBe('none')+ })++ it('offers nothing on a relay tab, whatever the project is', () => {+ expect(downloadRoute({ browser: false, ssh: true, source: 'relay' })).toBe('none')+ expect(downloadRoute({ browser: true, ssh: false, source: 'relay' })).toBe('none')+ })++ it('does not mint a ticket for an SSH tree in the browser (that fs is not the server’s)', () => {+ expect(downloadRoute({ browser: true, ssh: true, source: 'local' })).toBe('none')+ })+})++describe('canRevealLocally', () => {+ it('is true only for a desktop local project', () => {+ expect(canRevealLocally({ browser: false, ssh: false, source: 'local' })).toBe(true)+ })++ it('is false where the path is not on this machine, or nothing can open it', () => {+ expect(canRevealLocally({ browser: false, ssh: true, source: 'local' })).toBe(false)+ expect(canRevealLocally({ browser: true, ssh: false, source: 'local' })).toBe(false)+ expect(canRevealLocally({ browser: false, ssh: false, source: 'relay' })).toBe(false)+ })+})diff --git a/src/renderer/lib/download.ts b/src/renderer/lib/download.tsnew file mode 100644index 000000000..388845b2e--- /dev/null+++ b/src/renderer/lib/download.ts@@ -0,0 +1,69 @@+// Which download route (if any) the Explorer offers for the tree it is currently showing.+//+// "Download" only means something when the file is NOT already on the user's machine, and the two+// cases where it isn't are reached by completely different transports:+//+// - **Desktop + SSH project** — the tree is another host's filesystem, so the file comes down over+// the project's ControlMaster with `scp` and lands in the OS Downloads folder. This is the only+// route that streams straight to disk, which is why big files must take it.+// - **Browser (Server Edition)** — every file in the tree is on the server, including a "local"+// project's. The transfer is a plain HTTP GET against a one-shot ticket, and the browser saves+// it. NOT `fs.readBinary`: that base64s the whole file into one RPC message and is capped.+//+// Everything else answers `none`, and the affordance is hidden rather than shown-and-broken:+// - **Desktop + local project** — the file is already on this machine; Reveal in Finder is the+// honest action, and it is right there in the same menu.+// - **Relay tab** — the files are on the peer's machine and the only path to them is the bridged+// `fs.readBinary`, i.e. the capped base64 one. Offering a Download that silently truncates a+// 25 MB file would be worse than not offering it; a real relay transport is follow-up work.+import type { SessionSource } from '../session/session'++export type DownloadRoute = 'scp' | 'http' | 'none'++export interface DownloadContext {+ /** Renderer shell: a browser tab (Server Edition) vs Electron. */+ browser: boolean+ /** The Explorer's project is an SSH project (its tree is the remote host's fs). */+ ssh: boolean+ /** Which session the active project's tab belongs to. */+ source: SessionSource+}++export function downloadRoute({ browser, ssh, source }: DownloadContext): DownloadRoute {+ if (source === 'relay') return 'none'+ if (ssh) {+ // An SSH project's tree is served by the desktop's ControlMaster; the Server Edition has no+ // SSH projects at all (its sshFs members are unsupported stubs), so a browser + ssh pairing+ // is not a thing we can serve — say so rather than minting a ticket for a path that is not on+ // the server's own disk.+ return browser ? 'none' : 'scp'+ }+ return browser ? 'http' : 'none'+}++/**+ * True when "Reveal in Finder" can actually do something: an Electron shell, showing paths that+ * are on THIS machine. It was previously offered unconditionally — on an SSH project it handed a+ * remote path to the local file manager, and in a browser tab it is an inert stub. Both were+ * silent no-ops, which reads as a broken app rather than as an unavailable feature.+ */+export function canRevealLocally({ browser, ssh, source }: DownloadContext): boolean {+ return !browser && !ssh && source !== 'relay'+}++/**+ * Start a browser download for `url` without navigating the page. An anchor with `download` is+ * used rather than `location.assign` so a response that (for any reason) lacks+ * `Content-Disposition` still saves instead of replacing the app. The `name` is a hint only — the+ * server's header wins, and must, because it knows a folder became `<name>.tar.gz`.+ */+export function triggerBrowserDownload(url: string, name: string): void {+ const a = document.createElement('a')+ a.href = url+ a.download = name+ a.rel = 'noopener'+ a.style.display = 'none'+ document.body.appendChild(a)+ a.click()+ a.remove()+}diff --git a/src/renderer/main.tsx b/src/renderer/main.tsxindex b8f299539..b6f7ecdb4 100644--- a/src/renderer/main.tsx+++ b/src/renderer/main.tsx@@ -3,7 +3,13 @@// desktop. In a browser (Server Edition) we install the WS bridge first, then boot.async function bootstrap(): Promise<void> {if (!window.nodeTerminal) {- const { installWsBridge } = await import('./bridge/ws-bridge')+ // Record the shell BEFORE the bridge installs: affordances that only work under Electron+ // (Reveal in Finder) or only in a browser (HTTP downloads) read this. See bridge/runtime.ts.+ const [{ markBrowserRuntime }, { installWsBridge }] = await Promise.all([+ import('./bridge/runtime'),+ import('./bridge/ws-bridge')+ ])+ markBrowserRuntime()const connected = await installWsBridge()if (!connected) return // overlay is up; startReconnect reloads on the first reopen} else {diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 96245fa78..4cb94532d 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3606,6 +3606,99 @@ body,text-overflow: ellipsis;}+/* Per-row download button. Hidden until the row is hovered/selected (and always reachable by+ keyboard focus) so the tree stays a tree — the context menu carries the same action. */+.ex-dl {+ margin-left: auto;+ flex-shrink: 0;+ padding: 0 4px;+ background: transparent;+ border: none;+ border-radius: 4px;+ color: var(--muted);+ font-size: 14px;+ line-height: 1;+ cursor: pointer;+ opacity: 0;+}++.ex-row:hover .ex-dl,+.ex-row.selected .ex-dl,+.ex-dl:focus-visible {+ opacity: 1;+}++.ex-dl:hover {+ color: var(--text);+ background: color-mix(in srgb, var(--text) 12%, transparent);+}++/* Download strip: pinned under the tree, one row per transfer. */+.ex-dls {+ flex-shrink: 0;+ border-top: 1px solid var(--border);+ padding: 6px 8px;+ display: flex;+ flex-direction: column;+ gap: 4px;+ max-height: 30%;+ overflow-y: auto;+}++.ex-dls__row {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: var(--muted);+}++.ex-dls__row.done {+ color: var(--text);+}++.ex-dls__row.error {+ color: var(--danger, #ff6b6b);+}++.ex-dls__name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.ex-dls__act {+ margin-left: auto;+ background: transparent;+ border: none;+ color: var(--accent);+ font-size: 12px;+ cursor: pointer;+ padding: 0 2px;+}++/* The `+ .ex-dls__act` sibling is the dismiss ×: only the FIRST action pushes right. */+.ex-dls__act + .ex-dls__act {+ margin-left: 0;+ color: var(--muted);+}++.ex-dls__spin {+ flex-shrink: 0;+ width: 10px;+ height: 10px;+ border: 2px solid color-mix(in srgb, var(--accent) 35%, transparent);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: ex-dls-spin 0.8s linear infinite;+}++@keyframes ex-dls-spin {+ to {+ transform: rotate(360deg);+ }+}+/* ---- Confirm dialog ---- */.confirm-overlay {position: fixed;diff --git a/src/server/download.test.ts b/src/server/download.test.tsnew file mode 100644index 000000000..230cb4fc6--- /dev/null+++ b/src/server/download.test.ts@@ -0,0 +1,139 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import http from 'http'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { Auth } from './auth'+import { createHttpHandler, SESSION_COOKIE } from './http'+import { contentDisposition, downloadName } from './download'+import { DownloadTickets } from '../core/download-tickets'++let dir: string, rendererDir: string, server: http.Server, base: string, auth: Auth+let tickets: DownloadTickets++beforeEach(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-dlroute-'))+ rendererDir = path.join(dir, 'renderer')+ fs.mkdirSync(rendererDir)+ fs.writeFileSync(path.join(rendererDir, 'index.html'), '<div id="root"></div>')+ fs.writeFileSync(path.join(dir, 'notes.md'), '# hello\n')+ fs.mkdirSync(path.join(dir, 'docs'))+ fs.writeFileSync(path.join(dir, 'docs', 'a.txt'), 'a')+ auth = new Auth(dir)+ tickets = new DownloadTickets()+ server = http.createServer(createHttpHandler({ auth, rendererDir, downloadTickets: tickets }))+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`+})+afterEach(async () => {+ await new Promise((r) => server.close(r))+ fs.rmSync(dir, { recursive: true, force: true })+})++async function login(): Promise<string> {+ const res = await fetch(`${base}/auth/setup`, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: `token=${auth.setupToken()}&password=hunter22-secret`,+ redirect: 'manual'+ })+ return res.headers.get('set-cookie')!.split(';')[0]+}++describe('contentDisposition', () => {+ it('emits both a sanitized ASCII fallback and the UTF-8 form', () => {+ const h = contentDisposition('belgeler özet.txt')+ expect(h).toContain("filename*=UTF-8''belgeler%20%C3%B6zet.txt")+ expect(h).toContain('filename="belgeler _zet.txt"')+ })++ it('cannot be broken out of by a quote or backslash in the filename', () => {+ const h = contentDisposition('a";x=y\\.txt')+ expect(h).toContain('filename="a_;x=y_.txt"')+ expect(h).not.toContain('"a"')+ })+})++describe('downloadName', () => {+ it('archives a directory', () => {+ expect(downloadName('/srv/app/docs', true)).toBe('docs.tar.gz')+ expect(downloadName('/srv/app/notes.md', false)).toBe('notes.md')+ })+})++describe('GET /download', () => {+ it('requires a session even with a valid ticket', async () => {+ const token = tickets.issue(path.join(dir, 'notes.md'), false)+ const res = await fetch(`${base}/download?t=${token}`, { redirect: 'manual' })+ expect(res.status).toBe(401)+ })++ it('streams the file as an attachment', async () => {+ const cookie = await login()+ const token = tickets.issue(path.join(dir, 'notes.md'), false)+ const res = await fetch(`${base}/download?t=${token}`, { headers: { cookie } })+ expect(res.status).toBe(200)+ expect(res.headers.get('content-disposition')).toContain('filename="notes.md"')+ expect(res.headers.get('content-length')).toBe('8')+ expect(await res.text()).toBe('# hello\n')+ })++ it('spends the ticket: the same URL is 404 the second time', async () => {+ const cookie = await login()+ const token = tickets.issue(path.join(dir, 'notes.md'), false)+ expect((await fetch(`${base}/download?t=${token}`, { headers: { cookie } })).status).toBe(200)+ const again = await fetch(`${base}/download?t=${token}`, { headers: { cookie } })+ expect(again.status).toBe(404)+ })++ it('404s an unknown ticket, and never reveals a path', async () => {+ const cookie = await login()+ const res = await fetch(`${base}/download?t=made-up`, { headers: { cookie } })+ expect(res.status).toBe(404)+ expect(await res.text()).not.toContain(dir)+ })++ it('carries no caller-supplied path — a path in the query is ignored entirely', async () => {+ const cookie = await login()+ const res = await fetch(`${base}/download?path=${encodeURIComponent('/etc/passwd')}`, {+ headers: { cookie }+ })+ expect(res.status).toBe(404)+ })++ it('404s a ticket whose file has since disappeared', async () => {+ const cookie = await login()+ const token = tickets.issue(path.join(dir, 'gone.md'), false)+ expect((await fetch(`${base}/download?t=${token}`, { headers: { cookie } })).status).toBe(404)+ })++ it('streams a directory as a gzipped tarball', async () => {+ const cookie = await login()+ const token = tickets.issue(path.join(dir, 'docs'), true)+ const res = await fetch(`${base}/download?t=${token}`, { headers: { cookie } })+ expect(res.status).toBe(200)+ expect(res.headers.get('content-disposition')).toContain('filename="docs.tar.gz"')+ const body = new Uint8Array(await res.arrayBuffer())+ // gzip magic — the archive is real, not an empty 200.+ expect([body[0], body[1]]).toEqual([0x1f, 0x8b])+ expect(body.length).toBeGreaterThan(20)+ })++ it('rejects a non-GET method', async () => {+ const cookie = await login()+ const token = tickets.issue(path.join(dir, 'notes.md'), false)+ const res = await fetch(`${base}/download?t=${token}`, { method: 'POST', headers: { cookie } })+ expect(res.status).toBe(405)+ })++ it('is absent when the shell wires no ticket store (the route falls through to static)', async () => {+ const plain = http.createServer(createHttpHandler({ auth, rendererDir }))+ await new Promise<void>((r) => plain.listen(0, '127.0.0.1', r))+ const p = `http://127.0.0.1:${(plain.address() as { port: number }).port}`+ const cookie = await login()+ const res = await fetch(`${p}/download?t=x`, { headers: { cookie } })+ expect(res.status).toBe(404) // static serving, not the download route+ expect(res.headers.get('content-disposition')).toBeNull()+ await new Promise((r) => plain.close(r))+ })+})diff --git a/src/server/download.ts b/src/server/download.tsnew file mode 100644index 000000000..6d78d0090--- /dev/null+++ b/src/server/download.ts@@ -0,0 +1,150 @@+// GET /download?t=<ticket> — the Server Edition's file-download route.+//+// The browser cannot reach the machine's filesystem, so "download this file from the Explorer"+// has to become a real HTTP transfer: it streams (no FS_READ_BINARY_MAX_BYTES ceiling, no base64+// inflation), the browser renders its own progress and lands the file in the user's Downloads+// folder, and none of it occupies the WS bridge that terminals are multiplexed over.+//+// The request carries a one-shot ticket, never a path (see core/download-tickets.ts): the ticket+// was minted over the authenticated RPC channel, so this route resolves a path from the server's+// OWN state and has no caller-supplied path to jail. It still sits BEHIND the session gate in+// http.ts — a ticket is a second factor, not a replacement for the session.+import type http from 'http'+import fs from 'fs'+import path from 'path'+import { spawn } from 'child_process'+import type { DownloadTickets } from '../core/download-tickets'++export const DOWNLOAD_PATH = '/download'++/**+ * `Content-Disposition` for an attachment named `name`. Both forms are emitted: `filename*` is+ * what every current browser reads (UTF-8, so "belgeler.txt" survives), and the quoted ASCII+ * `filename` is the fallback. The fallback is stripped of quotes, backslashes and control+ * characters — a filename is attacker-influenced input in the sense that it comes from a+ * filesystem, and an unescaped `"` there would let it forge further header parameters.+ */+export function contentDisposition(name: string): string {+ // eslint-disable-next-line no-control-regex+ const ascii = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_') || 'download'+ return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`+}++/** The name a download lands under: a directory arrives as a gzipped tarball. */+export function downloadName(p: string, dir: boolean): string {+ const base = path.basename(p) || 'download'+ return dir ? `${base}.tar.gz` : base+}++/**+ * Serve one download. Returns false when the request is not a download request at all (so the+ * caller falls through to the next route). Any failure AFTER the response has started can only be+ * a destroyed socket — a truncated file the browser reports as failed, which is the honest+ * outcome; we never end a broken transfer with a clean 200 body.+ */+export async function handleDownload(+ req: http.IncomingMessage,+ res: http.ServerResponse,+ url: URL,+ tickets: DownloadTickets+): Promise<boolean> {+ if (url.pathname !== DOWNLOAD_PATH) return false+ if ((req.method || 'GET') !== 'GET') {+ res.writeHead(405, { Allow: 'GET' })+ res.end()+ return true+ }+ const entry = tickets.redeem(url.searchParams.get('t') || '')+ // Unknown, spent and expired tickets are one 404: which of the three it was is not the+ // caller's business, and a distinct 403 would confirm that a path exists.+ if (!entry) {+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })+ res.end('Download link expired. Try again from the Explorer.')+ return true+ }++ let stat: fs.Stats+ try {+ stat = await fs.promises.stat(entry.path)+ } catch {+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })+ res.end('File not found.')+ return true+ }++ if (stat.isDirectory()) {+ streamTarball(res, entry.path)+ return true+ }++ const name = downloadName(entry.path, false)+ const stream = fs.createReadStream(entry.path)+ let opened = false+ stream.on('error', () => {+ if (!opened && !res.headersSent) {+ res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' })+ res.end('Could not read the file.')+ } else {+ res.destroy()+ }+ })+ stream.on('open', () => {+ opened = true+ res.writeHead(200, {+ 'Content-Type': 'application/octet-stream',+ 'Content-Length': String(stat.size),+ 'Content-Disposition': contentDisposition(name),+ 'Cache-Control': 'no-store'+ })+ stream.pipe(res)+ })+ // A user who cancels mid-download (or closes the tab) leaves us piping into a dead socket.+ res.on('close', () => stream.destroy())+ return true+}++/** Stream a directory as `tar.gz`. No Content-Length — the archive is produced as it is sent. */+function streamTarball(res: http.ServerResponse, dirPath: string): void {+ const parent = path.dirname(dirPath)+ const base = path.basename(dirPath)+ const child = spawn('tar', ['-czf', '-', '-C', parent, base], { stdio: ['ignore', 'pipe', 'ignore'] })+ let started = false+ const fail = (): void => {+ if (started || res.headersSent) res.destroy()+ else {+ res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' })+ res.end('Could not archive the folder.')+ }+ }+ child.on('error', fail)+ // Headers go out on the FIRST byte, not on spawn: a `tar` that is missing or refuses the path+ // fails before producing output, and that has to surface as a 500 rather than as a 200 with an+ // empty (corrupt) archive body.+ child.stdout.on('data', (chunk: Buffer) => {+ if (!started) {+ started = true+ res.writeHead(200, {+ 'Content-Type': 'application/gzip',+ 'Content-Disposition': contentDisposition(downloadName(dirPath, true)),+ 'Cache-Control': 'no-store'+ })+ }+ if (!res.write(chunk)) {+ child.stdout.pause()+ res.once('drain', () => child.stdout.resume())+ }+ })+ child.on('close', (code) => {+ if (code === 0 && started) res.end()+ else if (code === 0) {+ // An empty archive is still a valid one (an empty folder).+ res.writeHead(200, {+ 'Content-Type': 'application/gzip',+ 'Content-Disposition': contentDisposition(downloadName(dirPath, true)),+ 'Cache-Control': 'no-store'+ })+ res.end()+ } else fail()+ })+ res.on('close', () => child.kill())+}diff --git a/src/server/handlers/index.test.ts b/src/server/handlers/index.test.tsindex 54e5b896c..32f8d3b01 100644--- a/src/server/handlers/index.test.ts+++ b/src/server/handlers/index.test.ts@@ -8,6 +8,7 @@ import { registerCoreHandlers } from './index'import { IPC } from '../../shared/ipc'import { DEFAULT_SETTINGS, type GitStatus } from '../../shared/types'import { initPlatform, resetPlatformForTests } from '../../core/platform'+import { DownloadTickets } from '../../core/download-tickets'let repo: string, platform: ServerPlatform, ui: numberbeforeEach(() => {@@ -62,3 +63,57 @@ describe('registerCoreHandlers (git)', () => {expect(await call(IPC.appUserDataDir)).toBe(repo)})})++describe('registerCoreHandlers (download tickets)', () => {+ it('mints a redeemable ticket whose URL carries only the token', async () => {+ const tickets = new DownloadTickets()+ resetPlatformForTests()+ const p2 = new ServerPlatform({ userDataDir: repo, appVersion: '0' })+ initPlatform(p2)+ registerCoreHandlers(p2, { getSettings: () => DEFAULT_SETTINGS, downloadTickets: tickets })+ const ui2 = p2.attach({ sendText: () => {}, sendBinary: () => {} })+ const res = await p2.dispatch(ui2, {+ t: 'req',+ id: 1,+ method: IPC.filesDownloadTicket,+ args: [path.join(repo, 'a.txt')]+ })+ expect(res.ok).toBe(true)+ const ticket = (res as { result: { url: string; name: string } }).result+ expect(ticket.name).toBe('a.txt')+ expect(ticket.url).not.toContain(repo) // the path never travels in the URL+ const token = new URL(ticket.url, 'http://x').searchParams.get('t')!+ expect(tickets.redeem(token)).toMatchObject({ path: path.join(repo, 'a.txt'), dir: false })+ })++ it('names a directory ticket as a tarball', async () => {+ const tickets = new DownloadTickets()+ resetPlatformForTests()+ const p2 = new ServerPlatform({ userDataDir: repo, appVersion: '0' })+ initPlatform(p2)+ registerCoreHandlers(p2, { getSettings: () => DEFAULT_SETTINGS, downloadTickets: tickets })+ const ui2 = p2.attach({ sendText: () => {}, sendBinary: () => {} })+ const res = await p2.dispatch(ui2, { t: 'req', id: 1, method: IPC.filesDownloadTicket, args: [repo] })+ expect((res as { result: { name: string } }).result.name).toBe(`${path.basename(repo)}.tar.gz`)+ })++ it('answers null for a path that is not there (rather than a ticket that 404s later)', async () => {+ const tickets = new DownloadTickets()+ resetPlatformForTests()+ const p2 = new ServerPlatform({ userDataDir: repo, appVersion: '0' })+ initPlatform(p2)+ registerCoreHandlers(p2, { getSettings: () => DEFAULT_SETTINGS, downloadTickets: tickets })+ const ui2 = p2.attach({ sendText: () => {}, sendBinary: () => {} })+ const res = await p2.dispatch(ui2, {+ t: 'req',+ id: 1,+ method: IPC.filesDownloadTicket,+ args: [path.join(repo, 'nope.txt')]+ })+ expect((res as { result: unknown }).result).toBeNull()+ })++ it('answers null where no shell wired a ticket store (desktop, relay)', async () => {+ expect(await call(IPC.filesDownloadTicket, path.join(repo, 'a.txt'))).toBeNull()+ })+})diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.tsindex 986533c5f..4e30b94ba 100644--- a/src/server/handlers/index.ts+++ b/src/server/handlers/index.ts@@ -1,5 +1,8 @@-import type { Settings } from '../../shared/types'+import { stat } from 'node:fs/promises'+import type { DownloadTicket, Settings } from '../../shared/types'import type { ServerPlatform } from '../platform-server'+import type { DownloadTickets } from '../../core/download-tickets'+import { DOWNLOAD_PATH, downloadName } from '../download'import { GitService } from '../../core/git-service'import { generateCommitMessage } from '../../core/commit-message'import { registerFsHandlers } from '../../core/fs-handlers'@@ -17,9 +20,26 @@ import { IPC } from '../../shared/ipc'* routing on desktop, which the server edition does not have (terminals are local). */export function registerCoreHandlers(platform: ServerPlatform,- deps: { getSettings: () => Settings }+ deps: { getSettings: () => Settings; downloadTickets?: DownloadTickets }): { gitService: GitService } {- registerFsHandlers(platform)+ // Explorer downloads: mint a one-shot ticket over this (authenticated) channel; the transfer+ // itself is a plain HTTP GET the browser performs (src/server/download.ts). Statting here keeps+ // the URL honest about the name — a folder arrives as `<name>.tar.gz`.+ const { downloadTickets } = deps+ registerFsHandlers(platform, {+ issueDownloadTicket: downloadTickets+ ? async (p: string): Promise<DownloadTicket | null> => {+ let dir = false+ try {+ dir = (await stat(p)).isDirectory()+ } catch {+ return null+ }+ const token = downloadTickets.issue(p, dir)+ return { url: `${DOWNLOAD_PATH}?t=${encodeURIComponent(token)}`, name: downloadName(p, dir) }+ }+ : undefined+ })const gitService = new GitService()// registers all git:* channels via the global core platform().handlediff --git a/src/server/http.ts b/src/server/http.tsindex a772336dd..d1d9fa3f5 100644--- a/src/server/http.ts+++ b/src/server/http.ts@@ -8,6 +8,8 @@ import fs from 'fs'import path from 'path'import type { Auth } from './auth'import { proxyAuthAllowed, type TrustProxyConfig } from './proxy-trust'+import { handleDownload } from './download'+import type { DownloadTickets } from '../core/download-tickets'export const SESSION_COOKIE = 'nt_session'@@ -38,6 +40,9 @@ export interface HttpHandlerOpts {* through to the normal cookie/login path.*/trustProxy?: TrustProxyConfig+ /** Ticket store backing `GET /download` (Explorer file downloads). Omitted in tests that don't+ * exercise it — the route then simply doesn't exist. */+ downloadTickets?: DownloadTickets}/** Parse the `nt_session=` value out of a Cookie header. Exported for the WS upgrade (Task 5). */@@ -223,7 +228,7 @@ function serveStatic(export function createHttpHandler(opts: HttpHandlerOpts): (req: http.IncomingMessage, res: http.ServerResponse) => void {- const { auth, rendererDir, trustProxy } = opts+ const { auth, rendererDir, trustProxy, downloadTickets } = optsreturn function handler(req: http.IncomingMessage, res: http.ServerResponse): void {void handle(req, res).catch(() => {@@ -341,6 +346,9 @@ export function createHttpHandler(return}+ // Authenticated: an Explorer download redeems its one-shot ticket here (see download.ts).+ if (downloadTickets && (await handleDownload(req, res, url, downloadTickets))) return+// Authenticated: serve static renderer files (index.html fallback for '/').serveStatic(req, res, rendererDir, pathname)}diff --git a/src/server/index.ts b/src/server/index.tsindex 55e41097c..9aa6b1711 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -14,6 +14,7 @@ import { SettingsStore } from '../core/settings-store'import { WorkspaceStore } from '../core/workspace-store'import { PtyManager } from '../core/pty-manager'import { registerCoreHandlers } from './handlers'+import { DownloadTickets } from '../core/download-tickets'import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'import os from 'os'import { hookServer } from '../core/agents/hook-server'@@ -203,8 +204,11 @@ export async function startServer(ptyManager.captureSession(persistKey, full))- // fs + git + commit handlers (shared with desktop core services).- registerCoreHandlers(platform, { getSettings: () => settingsStore.get() })+ // fs + git + commit handlers (shared with desktop core services). The ticket store is shared+ // between the RPC side (which mints) and the HTTP side (which redeems) — one instance, so a+ // ticket minted over the socket is redeemable by the GET that follows it.+ const downloadTickets = new DownloadTickets()+ registerCoreHandlers(platform, { getSettings: () => settingsStore.get(), downloadTickets })// Board-log: same CorePlatform registrar as desktop, but the Server Edition has no SSH projects// (terminals are local), so the router only ever resolves a local folder cwd or unsupported —@@ -378,7 +382,12 @@ export async function startServer(}const server = http.createServer(- createHttpHandler({ auth, rendererDir: config.rendererDir, trustProxy: config.trustProxy })+ createHttpHandler({+ auth,+ rendererDir: config.rendererDir,+ trustProxy: config.trustProxy,+ downloadTickets+ }))// A closed browser tab is the NORMAL way to leave the Server Edition and sends no `pty:kill`,// so the WS close hook is what unsubscribes that client from the sessions it was watching.diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex f7662391e..dcecb8e6c 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -170,6 +170,8 @@ export const IPC = {fsMkdir: 'fs:mkdir',fsExists: 'fs:exists',filesQuickOpen: 'files:quick-open',+ /** Mint a one-shot HTTP download ticket (Server Edition only; every other shell answers null). */+ filesDownloadTicket: 'files:download-ticket',settingsLoad: 'settings:load',settingsSave: 'settings:save',sshList: 'ssh:list',@@ -182,6 +184,7 @@ export const IPC = {sshListDir: 'ssh:list-dir',sshMkdir: 'ssh:mkdir',sshUploadFile: 'ssh:upload-file',+ sshDownloadFile: 'ssh:download-file',sshFsList: 'sshFs:list',sshFsRead: 'sshFs:read',sshFsReadBinary: 'sshFs:read-binary',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 7cc8d54c7..9dbd58376 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -552,6 +552,13 @@ export interface FsApi {export interface FilesApi {/** Fuzzy-open file index for a project root: root-relative `/`-paths ([] on failure). */quickOpen(cwd: string): Promise<string[]>+ /**+ * Mint a one-shot, short-TTL ticket for downloading `path` over HTTP, and resolve the URL to+ * navigate to. Resolves **null** where the shell has no HTTP surface to redeem it on (Electron+ * desktop, relay) — callers treat null as "downloading is not offered here" and hide the+ * affordance rather than erroring.+ */+ downloadTicket(path: string): Promise<DownloadTicket | null>}export interface MediaApi {@@ -895,9 +902,31 @@ export interface SshProjectApi {* success, or null on any failure (not connected, unresolved remote home, mkdir/scp failure).*/uploadFile(projectId: string, localPath: string, fileName: string): Promise<string | null>+ /**+ * Pull a remote file (or, with a directory, the whole tree) down to this machine over the+ * project's ControlMaster, into the OS Downloads folder unless `destDir` names another one.+ * The DESTINATION is built in main (`app.getPath('downloads')` + the remote basename, collision-+ * resolved) — the renderer only ever names the remote side, so no renderer string reaches the+ * local write path. Never throws: a failure resolves `{ ok: false, error }`.+ */+ downloadFile(projectId: string, remotePath: string, destDir?: string): Promise<DownloadResult>onStatus(cb: (e: SshProjectStatusEvent) => void): () => void}+/** Outcome of a file download (SSH pull). `localPath` is the absolute path actually written —+ * collision resolution may have renamed it (`notes.md` → `notes (2).md`). */+export type DownloadResult =+ | { ok: true; localPath: string; dir: boolean }+ | { ok: false; error: string }++/** A one-shot HTTP download ticket (Server Edition). `url` is same-origin and carries the token;+ * the browser does the transfer natively, so nothing streams through the WS bridge. */+export interface DownloadTicket {+ url: string+ /** Filename the download will land under (a directory becomes `<name>.tar.gz`). */+ name: string+}+/*** SSH-project Explorer/Editor filesystem API: the same `FsApi` contract scoped to a project,* proxied over the project's ControlMaster (renderer → `sshFs:*` IPC → main `SshFs`). The renderer