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.

feat(canvas): Download in the file-manager node's right-click menu

reviewed23bd1c419e
diff --git a/src/renderer/components/DownloadStrip.tsx b/src/renderer/components/DownloadStrip.tsx
new file mode 100644
index 000000000..96231db60
--- /dev/null
+++ b/src/renderer/components/DownloadStrip.tsx
@@ -0,0 +1,44 @@
+import type { DownloadItem } from '../lib/useDownloads'
+import { IconClose } from './icons'
+
+/**
+ * The list of transfers under a file surface (the Explorer drawer, a file-manager node): one row
+ * per download, a spinner while it runs, Reveal once an scp pull has landed on this machine.
+ * Renders nothing while there is nothing to report.
+ */
+export function DownloadStrip({
+ downloads,
+ onDismiss,
+ className
+}: {
+ downloads: DownloadItem[]
+ onDismiss: (id: number) => void
+ className?: string
+}) {
+ if (downloads.length === 0) return null
+ return (
+ <div className={className ? `ex-dls ${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 ex-dls__dismiss"
+ aria-label="Dismiss"
+ onClick={() => onDismiss(d.id)}
+ >
+ <IconClose />
+ </button>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/src/renderer/components/ExplorerPanel.tsx b/src/renderer/components/ExplorerPanel.tsx
index 32bb4911f..237f1449b 100644
--- a/src/renderer/components/ExplorerPanel.tsx
+++ b/src/renderer/components/ExplorerPanel.tsx
@@ -8,7 +8,9 @@ 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 { canRevealLocally, downloadRoute, isDownloadablePath } from '../lib/download'
+import { ROW_DOWNLOAD_TITLE, useDownloads, type RowDownloadState } from '../lib/useDownloads'
+import { DownloadStrip } from './DownloadStrip'
import { explorerOverlayClickCloses } from '../lib/explorerPin'
import { isBrowserRuntime } from '../bridge/runtime'
import { IconClose, IconPin, IconReload } from './icons'
@@ -34,31 +36,6 @@ type OpenFn = (path: string) => void
type SelectFn = (path: string) => void
type DownloadFn = (path: string, isDir: boolean) => void
-/** What a tree row's download button is showing right now. */
-type RowDownloadState = 'running' | 'done' | 'error'
-
-/** How long a finished row keeps its ✓ / ! before falling back to a plain ⤓. Long enough to be
- * read after a click, short enough that a tree of them doesn't stay decorated. */
-const ROW_FLASH_MS = 2200
-
-/** Row-button tooltip per state. The failure text points at the strip, which carries the reason. */
-const DL_TITLE: Record<RowDownloadState, string> = {
- running: 'Downloading…',
- done: 'Downloaded',
- error: 'Download failed — see the list below'
-}
-
-/** 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 => {
window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message } }))
@@ -180,7 +157,7 @@ function TreeEntry({
{onDownload && (
<button
className={`ex-dl${dl ? ` ${dl}` : ''}`}
- title={dl ? DL_TITLE[dl] : entry.dir ? `Download ${entry.name} folder` : `Download ${entry.name}`}
+ title={dl ? ROW_DOWNLOAD_TITLE[dl] : entry.dir ? `Download ${entry.name} folder` : `Download ${entry.name}`}
aria-label="Download"
aria-busy={dl === 'running'}
// A second click while the first transfer is still running would start a duplicate
@@ -272,93 +249,17 @@ export function ExplorerPanel({
[ssh, session.source]
)
const route = downloadRoute(dlCtx)
- const [downloads, setDownloads] = useState<DownloadItem[]>([])
- const dlSeq = useRef(0)
- // Per-ROW download state, keyed by path. The strip at the bottom of the drawer reports the same
- // transfers, but the user's eye is on the button they just pressed — and on the HTTP route the
- // whole thing can be over before a glance travels down there. So the row answers for itself.
- const [rowDl, setRowDl] = useState<Record<string, RowDownloadState>>({})
- const setRowState = useCallback((path: string, state: RowDownloadState): void => {
- setRowDl((m) => ({ ...m, [path]: state }))
- }, [])
-
- 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' }])
- setRowState(path, 'running')
- const finish = (state: RowDownloadState): void => {
- setRowState(path, state)
- // Clear the row back to a plain ⤓ after the flash. Keyed by PATH, so a second download of
- // the same entry started meanwhile owns the row and its timer must not wipe that state.
- setTimeout(
- () =>
- setRowDl((m) => {
- if (m[path] !== state) return m
- const next = { ...m }
- delete next[path]
- return next
- }),
- ROW_FLASH_MS
- )
- }
- 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 })
- finish(res.ok ? 'done' : 'error')
- return
- }
- const ticket = await session.api.files.downloadTicket(path)
- if (!ticket) {
- patchDownload(id, { status: 'error', detail: 'Downloading is not available here.' })
- finish('error')
- return
- }
- triggerBrowserDownload(ticket.url, ticket.name)
- patchDownload(id, { status: 'done', detail: 'Sent to your browser downloads.' })
- finish('done')
- // 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.' })
- finish('error')
- }
- },
- [route, project, session.api, patchDownload, setRowState]
- )
+ const { downloads, rowDl, download, downloadTo, dismiss } = useDownloads({
+ route,
+ projectId: project?.id,
+ files: session.api.files
+ })
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)
@@ -529,34 +430,7 @@ export function ExplorerPanel({
</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 ex-dls__dismiss"
- aria-label="Dismiss"
- onClick={() => setDownloads((list) => list.filter((x) => x.id !== d.id))}
- >
- <IconClose />
- </button>
- </div>
- ))}
- </div>
- )}
+ <DownloadStrip downloads={downloads} onDismiss={dismiss} />
</aside>
{menu &&
@@ -600,7 +474,7 @@ export function ExplorerPanel({
>
New Folder…
</button>
- {route !== 'none' && (
+ {route !== 'none' && isDownloadablePath(menu.path) && (
<>
<div className="ctx-sep" />
<button
diff --git a/src/renderer/lib/download.test.ts b/src/renderer/lib/download.test.ts
index efb7192f8..0b2382ac7 100644
--- a/src/renderer/lib/download.test.ts
+++ b/src/renderer/lib/download.test.ts
@@ -1,5 +1,12 @@
-import { describe, it, expect } from 'vitest'
-import { canRevealLocally, canUseLocalShell, downloadRoute } from './download'
+import { describe, it, expect, vi } from 'vitest'
+import {
+ canRevealLocally,
+ canUseLocalShell,
+ downloadRoute,
+ isDownloadablePath,
+ performDownload,
+ type DownloadTransport
+} from './download'
describe('downloadRoute', () => {
it('pulls an SSH project over scp on the desktop', () => {
@@ -62,3 +69,97 @@ describe('canUseLocalShell', () => {
)
})
})
+
+describe('isDownloadablePath', () => {
+ // The same refusal set as core's `safeDownloadBasename`: a path whose basename cannot name a
+ // download. A file manager node can stand on `/`, and the HTTP route would happily tar the
+ // whole server filesystem for it.
+ it('refuses the filesystem root and paths with no nameable basename', () => {
+ for (const p of ['/', '', '//', '~', '/srv/..', '/srv/.', '~/'])
+ expect(isDownloadablePath(p), p).toBe(false)
+ })
+
+ it('accepts an ordinary file or folder, trailing slash or not', () => {
+ for (const p of ['/srv/app/notes.md', '/srv/app/', '~/project', '/.bashrc'])
+ expect(isDownloadablePath(p), p).toBe(true)
+ })
+})
+
+describe('performDownload', () => {
+ const transport = (over: Partial<DownloadTransport> = {}): DownloadTransport & {
+ handed: { url: string; name: string }[]
+ } => {
+ const handed: { url: string; name: string }[] = []
+ return {
+ handed,
+ scp: vi.fn(async () => ({ ok: true as const, localPath: '/Users/me/Downloads/a.txt', dir: false })),
+ ticket: vi.fn(async () => ({ url: '/download?t=abc', name: 'a.txt' })),
+ hand: (url, name) => handed.push({ url, name }),
+ ...over
+ }
+ }
+
+ it('pulls over scp with the project id and the chosen folder, and reports where it landed', async () => {
+ const t = transport()
+ const out = await performDownload('scp', { path: '/srv/a.txt', projectId: 'p1', destDir: '/tmp/x' }, t)
+ expect(t.scp).toHaveBeenCalledWith('p1', '/srv/a.txt', '/tmp/x')
+ expect(out).toEqual({ ok: true, localPath: '/Users/me/Downloads/a.txt' })
+ })
+
+ it('passes an scp failure reason through unchanged', async () => {
+ const t = transport({ scp: async () => ({ ok: false as const, error: 'Not connected.' }) })
+ expect(await performDownload('scp', { path: '/srv/a.txt', projectId: 'p1' }, t)).toEqual({
+ ok: false,
+ error: 'Not connected.'
+ })
+ })
+
+ it('refuses scp without a project instead of sending an undefined id to main', async () => {
+ const t = transport()
+ const out = await performDownload('scp', { path: '/srv/a.txt' }, t)
+ expect(out.ok).toBe(false)
+ expect(t.scp).not.toHaveBeenCalled()
+ })
+
+ it('hands a minted ticket to the browser and never touches scp', async () => {
+ const t = transport()
+ const out = await performDownload('http', { path: '/srv/a.txt', projectId: 'p1' }, t)
+ expect(out).toEqual({ ok: true })
+ expect(t.handed).toEqual([{ url: '/download?t=abc', name: 'a.txt' }])
+ expect(t.scp).not.toHaveBeenCalled()
+ })
+
+ it('reports a null ticket as unavailable rather than handing nothing to the browser', async () => {
+ const t = transport({ ticket: async () => null })
+ const out = await performDownload('http', { path: '/srv/a.txt' }, t)
+ expect(out).toEqual({ ok: false, error: 'Downloading is not available here.' })
+ expect(t.handed).toEqual([])
+ })
+
+ it('turns a rejected transport into a failed outcome, never a throw', async () => {
+ const t = transport({
+ scp: async () => {
+ throw new Error('ipc gone')
+ },
+ ticket: async () => {
+ throw new Error('ws gone')
+ }
+ })
+ expect(await performDownload('scp', { path: '/a', projectId: 'p' }, t)).toEqual({
+ ok: false,
+ error: 'The download could not be started.'
+ })
+ expect(await performDownload('http', { path: '/a' }, t)).toEqual({
+ ok: false,
+ error: 'The download could not be started.'
+ })
+ })
+
+ it('does nothing at all on the none route', async () => {
+ const t = transport()
+ const out = await performDownload('none', { path: '/a', projectId: 'p' }, t)
+ expect(out.ok).toBe(false)
+ expect(t.scp).not.toHaveBeenCalled()
+ expect(t.ticket).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/lib/download.ts b/src/renderer/lib/download.ts
index a59dfe90d..adecc9e7f 100644
--- a/src/renderer/lib/download.ts
+++ b/src/renderer/lib/download.ts
@@ -16,6 +16,7 @@
// - **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 { DownloadResult, DownloadTicket } from '@shared/types'
import type { SessionSource } from '../session/session'
export type DownloadRoute = 'scp' | 'http' | 'none'
@@ -41,6 +42,65 @@ export function downloadRoute({ browser, ssh, source }: DownloadContext): Downlo
return browser ? 'http' : 'none'
}
+/**
+ * True when `path` can name a download at all. The same refusal set as core's
+ * `safeDownloadBasename` (the scp leg), applied BEFORE the affordance is shown: a path whose
+ * basename is empty, `.`, `..` or `~` has nothing to call the result. The one that matters is
+ * `/` — a file manager node can stand on the filesystem root, and the HTTP route has no such
+ * guard, so it would stream the whole server filesystem as one `.tar.gz`.
+ */
+export function isDownloadablePath(path: string): boolean {
+ const base = path.replace(/\/+$/, '').split('/').pop() ?? ''
+ return !!base && base !== '.' && base !== '..' && base !== '~'
+}
+
+/** What one download attempt came to. `localPath` is set only when the file landed on THIS
+ * machine (the scp route) — that is what makes it revealable; an HTTP download belongs to the
+ * browser from its first byte. */
+export type DownloadOutcome = { ok: true; localPath?: string } | { ok: false; error: string }
+
+/** The two transports, injected so the decision below is testable without a preload. */
+export interface DownloadTransport {
+ /** Desktop + SSH: `sshProject.downloadFile` — scp over the project's ControlMaster. */
+ scp: (projectId: string, path: string, destDir?: string) => Promise<DownloadResult>
+ /** Browser: `files.downloadTicket` — a one-shot ticket for `GET /download`. */
+ ticket: (path: string) => Promise<DownloadTicket | null>
+ /** Hand a ticket URL to the browser's own downloader (`triggerBrowserDownload`). */
+ hand: (url: string, name: string) => void
+}
+
+const NOT_AVAILABLE = 'Downloading is not available here.'
+
+/**
+ * Run one download over `route`. ONE implementation for every surface that offers Download (the
+ * Explorer drawer and the file-manager node), so the transport rules — which API, what a null
+ * ticket means, how a rejected IPC reads — cannot drift between them. Never throws.
+ */
+export async function performDownload(
+ route: DownloadRoute,
+ req: { path: string; projectId?: string; destDir?: string },
+ t: DownloadTransport
+): Promise<DownloadOutcome> {
+ try {
+ if (route === 'scp') {
+ // Main resolves the ControlMaster from the project id; an undefined one is a renderer bug,
+ // not something to hand across the IPC boundary.
+ if (!req.projectId) return { ok: false, error: 'Not connected.' }
+ const res = await t.scp(req.projectId, req.path, req.destDir)
+ return res.ok ? { ok: true, localPath: res.localPath } : { ok: false, error: res.error }
+ }
+ if (route === 'http') {
+ const ticket = await t.ticket(req.path)
+ if (!ticket) return { ok: false, error: NOT_AVAILABLE }
+ t.hand(ticket.url, ticket.name)
+ return { ok: true }
+ }
+ return { ok: false, error: NOT_AVAILABLE }
+ } catch {
+ return { ok: false, error: 'The download could not be started.' }
+ }
+}
+
/**
* True when this machine's Electron `shell.*` can actually act on a path the UI is showing:
* an Electron shell (both members are `noop` stubs in a browser tab — see `bridge/stubs.ts`),
diff --git a/src/renderer/lib/filesNode.test.ts b/src/renderer/lib/filesNode.test.ts
index be789bb84..afbe8dcc7 100644
--- a/src/renderer/lib/filesNode.test.ts
+++ b/src/renderer/lib/filesNode.test.ts
@@ -4,6 +4,7 @@ import {
childPath,
classifyEmptyListing,
displacedFilesPatch,
+ downloadMenuEntries,
fileOpenTarget,
filterEntries,
folderTitle,
@@ -200,3 +201,33 @@ describe('displacedFilesPatch', () => {
expect(displacedFilesPatch({ titleAuto: false }, '')).toBeNull()
})
})
+
+describe('downloadMenuEntries', () => {
+ const labels = (...a: Parameters<typeof downloadMenuEntries>) => downloadMenuEntries(...a).map((e) => e.label)
+
+ it('offers nothing where the listing cannot be downloaded from (desktop local, relay)', () => {
+ expect(downloadMenuEntries('none', '/srv/app/a.txt', { dir: false, here: false })).toEqual([])
+ })
+
+ it('offers nothing for the filesystem root — the HTTP route would tar the whole server', () => {
+ expect(downloadMenuEntries('http', '/', { dir: true, here: true })).toEqual([])
+ expect(downloadMenuEntries('scp', '/', { dir: true, here: true })).toEqual([])
+ })
+
+ it('offers Download and Download to… for a file on an SSH host', () => {
+ expect(labels('scp', '/srv/app/a.txt', { dir: false, here: false })).toEqual(['Download', 'Download to…'])
+ expect(downloadMenuEntries('scp', '/srv/app/a.txt', { dir: false, here: false })[1].pickFolder).toBe(true)
+ })
+
+ it('says a folder arrives as a .tar.gz in the browser, and offers no folder picker there', () => {
+ expect(labels('http', '/srv/app/src', { dir: true, here: false })).toEqual(['Download folder (.tar.gz)'])
+ })
+
+ it('names the folder being shown when the menu was opened on empty space', () => {
+ expect(labels('scp', '/srv/app/src', { dir: true, here: true })).toEqual([
+ 'Download this folder',
+ 'Download to…'
+ ])
+ expect(labels('http', '/srv/app/src', { dir: true, here: true })).toEqual(['Download this folder (.tar.gz)'])
+ })
+})
diff --git a/src/renderer/lib/filesNode.ts b/src/renderer/lib/filesNode.ts
index 4a57a5912..462f9948e 100644
--- a/src/renderer/lib/filesNode.ts
+++ b/src/renderer/lib/filesNode.ts
@@ -19,6 +19,7 @@
import { isMediaFile } from '../state/workspace'
import { opensInEditor } from './openTarget'
import { folderTitle } from './explorerCreate'
+import { isDownloadablePath, type DownloadRoute } from './download'
export { folderTitle, parentDir } from './explorerCreate'
@@ -191,3 +192,36 @@ export function fileOpenTarget(path: string, opts: { remote?: boolean } = {}): '
if (isMediaFile(path)) return 'canvas'
return opensInEditor(path) ? 'canvas' : 'os'
}
+
+/** One Download row in a files node's context menu. `pickFolder` = ask for a destination first
+ * ("Download to…"), which only the desktop scp route can honour. */
+export interface DownloadMenuEntry {
+ label: string
+ pickFolder: boolean
+}
+
+/**
+ * The Download rows a files node's context menu offers for `path`. Where the route is `none`
+ * (a desktop local project — the file is already here — or a relay tab) there are none, and so
+ * for a path that cannot name a download: the node can stand on `/`, and a "Download this folder"
+ * there would stream the whole server filesystem.
+ *
+ * `here` = the menu was opened on empty space, so `path` is the folder being shown rather than a
+ * row in it — named as such, because "Download folder" over a blank area does not say which one.
+ * An HTTP folder download arrives as a `.tar.gz` (the server archives it on the fly) and the label
+ * says so; scp brings a folder down AS a folder.
+ */
+export function downloadMenuEntries(
+ route: DownloadRoute,
+ path: string,
+ { dir, here }: { dir: boolean; here: boolean }
+): DownloadMenuEntry[] {
+ if (route === 'none' || !isDownloadablePath(path)) return []
+ const what = dir ? (here ? 'Download this folder' : 'Download folder') : 'Download'
+ const entries: DownloadMenuEntry[] = [
+ { label: dir && route === 'http' ? `${what} (.tar.gz)` : what, pickFolder: false }
+ ]
+ // The browser has no native folder picker, and where its downloads land is a browser setting.
+ if (route === 'scp') entries.push({ label: 'Download to…', pickFolder: true })
+ return entries
+}
diff --git a/src/renderer/lib/useDownloads.ts b/src/renderer/lib/useDownloads.ts
new file mode 100644
index 000000000..593f14658
--- /dev/null
+++ b/src/renderer/lib/useDownloads.ts
@@ -0,0 +1,128 @@
+// The download state a file surface shows: a strip of transfers, and a per-ROW mark on the entry
+// that was clicked. Shared by the Explorer drawer and the file-manager node so both report a
+// download the same way — the transport itself is `performDownload` (lib/download.ts).
+import { useCallback, useRef, useState } from 'react'
+import type { FilesApi } from '@shared/types'
+import { performDownload, triggerBrowserDownload, type DownloadRoute } from './download'
+
+/** What a row's download mark is showing right now. */
+export type RowDownloadState = 'running' | 'done' | 'error'
+
+/** How long a finished row keeps its ✓ / ! before falling back to nothing. Long enough to be
+ * read after a click, short enough that a listing of them doesn't stay decorated. */
+export const ROW_FLASH_MS = 2200
+
+/** Row tooltip per state. The failure text points at the strip, which carries the reason. */
+export const ROW_DOWNLOAD_TITLE: Record<RowDownloadState, string> = {
+ running: 'Downloading…',
+ done: 'Downloaded',
+ error: 'Download failed — see the list below'
+}
+
+/** One entry in a download strip. `localPath` is set once a desktop (scp) download has landed,
+ * which is what makes it revealable. */
+export interface DownloadItem {
+ id: number
+ name: string
+ dir: boolean
+ status: 'running' | 'done' | 'error'
+ detail?: string
+ localPath?: string
+}
+
+export interface Downloads {
+ downloads: DownloadItem[]
+ /** Download state per path — the whole map, so a row anywhere sees its own entry. */
+ rowDl: Record<string, RowDownloadState>
+ /** 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. */
+ download: (path: string, isDir: boolean, destDir?: string) => Promise<void>
+ /** "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). */
+ downloadTo: (path: string, isDir: boolean) => Promise<void>
+ dismiss: (id: number) => void
+}
+
+export function useDownloads({
+ route,
+ projectId,
+ files
+}: {
+ route: DownloadRoute
+ /** The SSH project whose ControlMaster the scp route pulls over. */
+ projectId: string | undefined
+ /** The SESSION's files api — the ticket must be minted by the core the tree belongs to. */
+ files: Pick<FilesApi, 'downloadTicket'>
+}): Downloads {
+ const [downloads, setDownloads] = useState<DownloadItem[]>([])
+ const seq = useRef(0)
+ // Per-ROW state, keyed by path. The strip reports the same transfers, but the user's eye is on
+ // the entry they just acted on — and on the HTTP route the whole thing can be over before a
+ // glance travels down there. So the row answers for itself.
+ const [rowDl, setRowDl] = useState<Record<string, RowDownloadState>>({})
+
+ const patch = useCallback((id: number, p: Partial<DownloadItem>): void => {
+ setDownloads((list) => list.map((d) => (d.id === id ? { ...d, ...p } : d)))
+ }, [])
+
+ /**
+ * 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 = ++seq.current
+ const name = path.split('/').filter(Boolean).pop() || path
+ setDownloads((list) => [...list, { id, name, dir: isDir, status: 'running' }])
+ setRowDl((m) => ({ ...m, [path]: 'running' }))
+ const res = await performDownload(
+ route,
+ { path, projectId, destDir },
+ {
+ scp: (p, remotePath, dest) => window.nodeTerminal.sshProject.downloadFile(p, remotePath, dest),
+ ticket: (p) => files.downloadTicket(p),
+ hand: triggerBrowserDownload
+ }
+ )
+ if (!res.ok) patch(id, { status: 'error', detail: res.error })
+ else if (res.localPath) patch(id, { status: 'done', localPath: res.localPath })
+ else {
+ patch(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)
+ }
+ const state: RowDownloadState = res.ok ? 'done' : 'error'
+ setRowDl((m) => ({ ...m, [path]: state }))
+ // Clear the row after the flash. Keyed by PATH, so a second download of the same entry
+ // started meanwhile owns the row and its timer must not wipe that state.
+ setTimeout(
+ () =>
+ setRowDl((m) => {
+ if (m[path] !== state) return m
+ const next = { ...m }
+ delete next[path]
+ return next
+ }),
+ ROW_FLASH_MS
+ )
+ },
+ [route, projectId, files, patch]
+ )
+
+ 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]
+ )
+
+ const dismiss = useCallback((id: number): void => {
+ setDownloads((list) => list.filter((d) => d.id !== id))
+ }, [])
+
+ return { downloads, rowDl, download, downloadTo, dismiss }
+}
diff --git a/src/renderer/nodes/FilesNode.tsx b/src/renderer/nodes/FilesNode.tsx
index cb420de01..31d1bf422 100644
--- a/src/renderer/nodes/FilesNode.tsx
+++ b/src/renderer/nodes/FilesNode.tsx
@@ -35,6 +35,7 @@ import {
breadcrumbs,
childPath,
classifyEmptyListing,
+ downloadMenuEntries,
fileOpenTarget,
filterEntries,
folderTitle,
@@ -47,7 +48,9 @@ import { useProjects } from '../state/projects'
import { promptDialog } from '../components/promptDialog'
import { ContextMenu, type MenuItem } from '../components/ContextMenu'
import { isBrowserRuntime } from '../bridge/runtime'
-import { canUseLocalShell } from '../lib/download'
+import { canUseLocalShell, downloadRoute } from '../lib/download'
+import { ROW_DOWNLOAD_TITLE, useDownloads, type RowDownloadState } from '../lib/useDownloads'
+import { DownloadStrip } from '../components/DownloadStrip'
/**
* Shown when the parent listing could not be read either. It deliberately names BOTH possible
@@ -75,6 +78,17 @@ function EntryGlyph({ dir }: { dir: boolean }) {
)
}
+/** A row's download feedback, at the row that was right-clicked: the menu is gone by the time the
+ * transfer starts, so this is where "did it start?" gets answered. Nothing when idle. */
+function RowDownloadMark({ state }: { state: RowDownloadState | undefined }) {
+ if (!state) return null
+ return (
+ <span className={`files-node__dl ${state}`} title={ROW_DOWNLOAD_TITLE[state]} aria-live="polite">
+ {state === 'running' ? <span className="ex-dl__spin" /> : state === 'done' ? '✓' : '!'}
+ </span>
+ )
+}
+
export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {
const { updateNodeData, deleteElements, setNodes } = useReactFlow()
const [showColors, setShowColors] = useState(false)
@@ -120,6 +134,16 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {
* THIS machine. Both members are `noop` stubs in a browser tab, so an ungated call is a dead
* click — which is what "Reveal" was written to avoid and what `openPath` still did. */
const localShell = canUseLocalShell({ browser: isBrowserRuntime(), ssh: isSshFs, source })
+ /** Same decision the Explorer drawer makes (lib/download.ts), read off THIS node's filesystem:
+ * an SSH host's files come down over scp, a browser tab's over an HTTP ticket, and a desktop
+ * local listing (already on this machine) or a relay peer's offers no Download at all. */
+ const route = downloadRoute({ browser: isBrowserRuntime(), ssh: isSshFs, source })
+ const { downloads, rowDl, download, downloadTo, dismiss } = useDownloads({
+ route,
+ // The same project `fs` lists through: an sshFs node lives in the active project.
+ projectId: activeProjectId || undefined,
+ files: api.files
+ })
useEffect(() => {
let live = true
@@ -304,6 +328,21 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {
items.push({ type: 'separator' })
items.push({ label: 'New file…', onClick: () => void create(dir, 'file') })
items.push({ label: 'New folder…', onClick: () => void create(dir, 'folder') })
+ const dl = downloadMenuEntries(route, path, { dir: entry ? entry.dir : true, here: !entry })
+ if (dl.length) {
+ items.push({ type: 'separator' })
+ const isDir = entry ? entry.dir : true
+ // A second start while the first is still running would land a duplicate `name (2)`.
+ const busy = rowDl[path] === 'running'
+ for (const d of dl) {
+ items.push({
+ label: d.label,
+ disabled: busy,
+ hint: busy ? 'Already downloading' : undefined,
+ onClick: () => void (d.pickFolder ? downloadTo(path, isDir) : download(path, isDir))
+ })
+ }
+ }
items.push({ type: 'separator' })
items.push({
label: 'Copy path',
@@ -314,7 +353,7 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {
}
setMenu({ x: e.clientX, y: e.clientY, items })
},
- [cwd, open, create, api, localShell, source]
+ [cwd, open, create, api, localShell, source, route, rowDl, download, downloadTo]
)
const toggleCollapse = () =>
@@ -482,10 +521,15 @@ export function FilesNode({ id, data, selected }: NodeProps<CanvasNode>) {
>
<EntryGlyph dir={entry.dir} />
<span className="files-node__name">{entry.name}</span>
+ <RowDownloadMark state={rowDl[childPath(cwd, entry.name)]} />
</div>
))
)}
</div>
+
+ {/* Where a finished scp pull can be revealed, and where a failure says why — the row's
+ own mark only flashes ✓ / !. */}
+ <DownloadStrip downloads={downloads} onDismiss={dismiss} className="files-node__dls nodrag nowheel" />
</>
)}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 73f3c8854..a53c23230 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -14116,6 +14116,25 @@ body.focus-mode .dock:hover {
white-space: nowrap;
}
+/* A row's download mark (spinner → ✓ / !), pushed to the row's end. Same colours as the Explorer's
+ ⤓ states — one fact, read the same way on both surfaces. The spinner is `.ex-dl__spin`. */
+.files-node__dl {
+ margin-left: auto;
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ font-size: 12px;
+ line-height: 1;
+ color: var(--muted);
+}
+.files-node__dl.done {
+ color: var(--success);
+}
+.files-node__dl.error {
+ color: var(--danger);
+ font-weight: 700;
+}
+
.files-node__empty {
padding: 10px 8px;
font-size: 12px;