Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(video): play SSH-project videos by caching the host file locally

enesfe5e789abc9a
diff --git a/src/core/remote-ssh/media-cache.test.ts b/src/core/remote-ssh/media-cache.test.ts
new file mode 100644
index 000000000..fe06c2628
--- /dev/null
+++ b/src/core/remote-ssh/media-cache.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest'
+import { MEDIA_CACHE_KEEP, mediaCachePruneList, remoteMediaCacheName } from './media-cache'
+
+describe('remoteMediaCacheName', () => {
+ it('is deterministic for the same host+path', () => {
+ const a = remoteMediaCacheName('root@h1', '/srv/demo.mp4', 'demo.mp4')
+ const b = remoteMediaCacheName('root@h1', '/srv/demo.mp4', 'demo.mp4')
+ expect(a).toBe(b)
+ expect(a.endsWith('-demo.mp4')).toBe(true)
+ })
+
+ it('differs across hosts and across paths sharing a basename', () => {
+ const h1 = remoteMediaCacheName('root@h1', '/srv/demo.mp4', 'demo.mp4')
+ const h2 = remoteMediaCacheName('root@h2', '/srv/demo.mp4', 'demo.mp4')
+ const p2 = remoteMediaCacheName('root@h1', '/tmp/demo.mp4', 'demo.mp4')
+ expect(new Set([h1, h2, p2]).size).toBe(3)
+ })
+})
+
+describe('mediaCachePruneList', () => {
+ const entry = (name: string, mtimeMs: number) => ({ name, mtimeMs })
+
+ it('keeps everything under the cap', () => {
+ const entries = [entry('a', 1), entry('b', 2)]
+ expect(mediaCachePruneList(entries, 'c', 3)).toEqual([])
+ })
+
+ it('drops the oldest beyond the cap, reserving a slot for the incoming entry', () => {
+ // keep=3 with a new entry incoming → 2 existing survive, oldest goes.
+ const entries = [entry('old', 1), entry('mid', 2), entry('new', 3)]
+ expect(mediaCachePruneList(entries, 'incoming', 3)).toEqual(['old'])
+ })
+
+ it('never lists the entry being written, even if it is oldest', () => {
+ const entries = [entry('target', 1), entry('b', 2), entry('c', 3), entry('d', 4)]
+ expect(mediaCachePruneList(entries, 'target', 3)).toEqual(['b'])
+ })
+
+ it('has a sane default cap', () => {
+ expect(MEDIA_CACHE_KEEP).toBeGreaterThan(0)
+ })
+})
diff --git a/src/core/remote-ssh/media-cache.ts b/src/core/remote-ssh/media-cache.ts
new file mode 100644
index 000000000..12f20efd0
--- /dev/null
+++ b/src/core/remote-ssh/media-cache.ts
@@ -0,0 +1,35 @@
+// Pure helpers for the remote-media cache: a VideoNode in an SSH project plays a HOST file, so
+// main pulls it into <userData>/remote-media-cache/ over the ControlMaster and serves the cached
+// copy via nt-media://. These stay pure (no fs) so they are unit-testable; the manager does the IO.
+import { createHash } from 'crypto'
+
+/**
+ * Deterministic cache file name for (host, remote path): re-opening the same remote file lands on
+ * the same cache entry (so an unchanged file is not re-downloaded), while two hosts — or two paths
+ * with the same basename — can never collide. The basename is kept for debuggability and so the
+ * served file keeps its extension (container sniffing).
+ */
+export function remoteMediaCacheName(hostKey: string, remotePath: string, basename: string): string {
+ const h = createHash('sha256').update(`${hostKey}\n${remotePath}`).digest('hex').slice(0, 16)
+ return `${h}-${basename}`
+}
+
+/** Cache entries beyond this many are pruned oldest-first (videos are large; the cache is a
+ * convenience, not a store). */
+export const MEDIA_CACHE_KEEP = 20
+
+/**
+ * Given the cache dir's entries, return the file names to DELETE, keeping the newest `keep`.
+ * Pure: the caller stats and deletes. `except` (the entry being (re)written) is never returned.
+ */
+export function mediaCachePruneList(
+ entries: readonly { name: string; mtimeMs: number }[],
+ except: string,
+ keep: number = MEDIA_CACHE_KEEP
+): string[] {
+ return entries
+ .filter((e) => e.name !== except)
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
+ .slice(Math.max(0, keep - 1))
+ .map((e) => e.name)
+}
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.ts
index 231a1a14e..3769d2499 100644
--- a/src/main/canvas-control-core.ts
+++ b/src/main/canvas-control-core.ts
@@ -306,9 +306,9 @@ Verbs:
- \`show-video <path>\` — open a video file as a player node.
- \`show-web (--url U | --file P.html | --html "<...>")\` — open a web viewer (live URL or local HTML you wrote).
- \`open-browser --url U\` — open a navigable browser (back/forward/address bar) at a URL.
- In an SSH project, nodes you open run on the HOST (same machine as you). The media viewers are
- the exception: they read the DESKTOP's disk, so \`show-image\` works (it reads back over the
- connection) but \`show-video\` and \`show-web --file/--html\` are refused for a host path —
+ In an SSH project, nodes you open run on the HOST (same machine as you). The media viewers
+ render on the DESKTOP: \`show-image\` and \`show-video\` still work with a host path (the
+ file is read/fetched back over the connection), but \`show-web --file/--html\` is refused —
use \`--url\`, or copy the file to the desktop first.
- \`group --nodes <id,id> [--label "Frontend Team"]\` — wrap nodes in a labeled group frame.
- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]\` — tidy layout, no overlap.
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index f2af9848e..52ba25758 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -6,6 +6,8 @@ import { IPC } from '../../shared/ipc'
import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, sshHostKey, type SshConnection } from '../../shared/ssh'
import type { DownloadResult, SshProjectStatusEvent } from '../../shared/types'
import { candidateName, safeDownloadBasename } from '../../core/download-name'
+import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'
+import { allowMediaPath } from '../media-protocol'
import { remoteAccountConfigDir, isSupportedClaudeVersion } from '../../core/claude-accounts-core'
import { supportsAutoPermissionMode, supportsFullscreenTui } from '../../shared/agents/config'
import {
@@ -512,6 +514,75 @@ export class SshProjectManager {
return path.join(destDir, candidateName(name, Date.now()))
}
+ /**
+ * Pull a remote FILE into the local media cache (for nt-media:// playback) and resolve its
+ * cached absolute path. The entry is keyed by (host, remote path) — see remoteMediaCacheName —
+ * so re-opening an unchanged file reuses the cached copy: reuse is gated on the remote size
+ * still matching (`wc -c` is portable where `stat -c/-f` is not). A FAILED size probe is not
+ * evidence of anything (a hiccup ≠ a changed file) — it falls through to a fresh transfer,
+ * whose own failure is the real error. Directories are refused: a player node plays one file.
+ */
+ async cacheMediaFile(
+ projectId: string,
+ remotePath: string,
+ cacheDir: string
+ ): Promise<{ ok: true; localPath: string } | { ok: false; error: string }> {
+ 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 played.' }
+ try {
+ const dirProbe = await this.r.run(
+ childArgs(c.conn, c.controlPath, `test -d ${quoteRemotePath(remotePath)}`)
+ )
+ if (dirProbe.code === 0) return { ok: false, error: 'That path is a directory, not a video file.' }
+ const dest = path.join(cacheDir, remoteMediaCacheName(sshHostKey(c.conn), remotePath, name))
+ const sizeProbe = await this.r.run(
+ childArgs(c.conn, c.controlPath, `wc -c < ${quoteRemotePath(remotePath)}`)
+ )
+ const remoteSize = sizeProbe.code === 0 ? parseInt(sizeProbe.stdout.trim(), 10) : NaN
+ const cachedSize = await fs
+ .stat(dest)
+ .then((s) => s.size)
+ .catch(() => -1)
+ if (Number.isFinite(remoteSize) && remoteSize >= 0 && cachedSize === remoteSize) {
+ return { ok: true, localPath: dest }
+ }
+ await fs.mkdir(cacheDir, { recursive: true })
+ // Same write-then-rename discipline as downloadFile: never leave a half-copied file
+ // under the final name — nt-media would happily serve a truncated video.
+ const partPath = `${dest}.part`
+ await fs.rm(partPath, { force: true }).catch(() => {})
+ const res = await this.r.runScp(scpDownArgs(c.conn, c.controlPath, remotePath, partPath, false))
+ if (res.code !== 0) {
+ await fs.rm(partPath, { force: true }).catch(() => {})
+ return { ok: false, error: 'The transfer failed. Is the file still there, and readable?' }
+ }
+ await fs.rename(partPath, dest)
+ void this.pruneMediaCache(cacheDir, path.basename(dest))
+ return { ok: true, localPath: dest }
+ } catch {
+ return { ok: false, error: 'The file could not be fetched from the host.' }
+ }
+ }
+
+ /** Best-effort, bounded cache: keep the newest MEDIA_CACHE_KEEP entries. An evicted entry that
+ * is still playing in an open node stops being seekable — acceptable for a 20-deep cache of a
+ * convenience copy; the node re-fetches on next open. */
+ private async pruneMediaCache(cacheDir: string, except: string): Promise<void> {
+ try {
+ const names = (await fs.readdir(cacheDir)).filter((n) => !n.endsWith('.part'))
+ const entries = await Promise.all(
+ names.map(async (n) => ({ name: n, mtimeMs: (await fs.stat(path.join(cacheDir, n))).mtimeMs }))
+ )
+ for (const n of mediaCachePruneList(entries, except)) {
+ await fs.rm(path.join(cacheDir, n), { force: true }).catch(() => {})
+ }
+ } catch {
+ // pruning is best-effort — a fat cache is a nuisance, not a fault
+ }
+ }
+
/**
* 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
@@ -970,5 +1041,15 @@ export function initSshProject(
ipcMain.handle(IPC.sshDownloadFile, (_e, projectId: string, remotePath: string, destDir?: string) =>
mgr.downloadFile(projectId, remotePath, destDir || app.getPath('downloads'))
)
+ // A VideoNode in an SSH project plays a HOST file: pull it into the local media cache over the
+ // ControlMaster, allowlist the cached copy, and hand back its nt-media:// URL.
+ ipcMain.handle(IPC.sshMediaAllow, async (_e, projectId: string, remotePath: string) => {
+ const r = await mgr.cacheMediaFile(
+ projectId,
+ remotePath,
+ path.join(app.getPath('userData'), 'remote-media-cache')
+ )
+ return r.ok ? { ok: true, url: allowMediaPath(r.localPath) } : r
+ })
return mgr
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 11ecac710..831461c4e 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -259,6 +259,8 @@ const api: NodeTerminalApi = {
},
media: {
allow: (absPath: string) => ipcRenderer.invoke(IPC.mediaAllow, absPath),
+ allowSsh: (projectId: string, remotePath: string) =>
+ ipcRenderer.invoke(IPC.sshMediaAllow, projectId, remotePath),
writeHtml: (html: string) => ipcRenderer.invoke(IPC.mediaWriteHtml, html)
},
browser: {
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 4afd9115a..a8afa6842 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -174,6 +174,11 @@ export function buildStubApi(): Omit<
},
media: {
allow: U('media.allow'),
+ // Deliberate graceful degrade: the remote-media cache lives on the DESKTOP shell (scp over
+ // the project's ControlMaster). Resolve a typed refusal instead of rejecting so the
+ // VideoNode shows the reason rather than a generic load failure.
+ allowSsh: (): Promise<{ ok: false; error: string }> =>
+ Promise.resolve({ ok: false, error: 'Playing videos from an SSH host is not available in the browser.' }),
writeHtml: U('media.writeHtml')
},
browser: {
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 5fb30723a..e06909ab3 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -330,10 +330,10 @@ interface PendingPeerState {
const WORKTREE_SSH_HINT = 'Not supported in SSH projects yet'
const WORKTREE_SSH_NOTICE = 'Worktrees are not supported in SSH projects yet.'
-// Media nodes render off the LOCAL disk (the video allowlist and the webview's file loader have
-// no remote counterpart), so a host path from a remote agent could only resolve to a same-named
-// local file — or nothing. Refuse and say why, rather than opening a node that quietly shows the
-// wrong thing. `%s` is the verb.
+// The webview's file loader renders off the LOCAL disk and has no remote counterpart, so a host
+// path from a remote agent could only resolve to a same-named local file — or nothing. Refuse and
+// say why, rather than opening a node that quietly shows the wrong thing. `%s` is the verb.
+// (Videos no longer take this path: VideoNode fetches a host file into the local media cache.)
const MEDIA_SSH_NOTICE =
'%s cannot render a file from an SSH project: the viewer reads the local disk, and this path is on the remote host. Use --url, or copy the file to this machine first.'
@@ -2536,7 +2536,7 @@ export function Canvas() {
...ns.map((n) => (n.selected ? { ...n, selected: false } : n)),
{
...(isVideoFile(filePath)
- ? createVideoNode(ns.length, filePath, center ?? viewCenter())
+ ? createVideoNode(ns.length, filePath, center ?? viewCenter(), sshFs)
: createEditorNode(ns.length, filePath, center ?? viewCenter(), sshFs)),
selected: true
}
@@ -5474,16 +5474,14 @@ export function Canvas() {
reply({ ok: false, error: 'show-video requires --path' })
return
}
- // The video node streams through the LOCAL media allowlist, which has no remote
- // counterpart — so on an SSH project a host path could only ever resolve to a local
- // file of the same name, or nothing. Refuse with the reason rather than opening a
- // node that silently shows the wrong thing (same call as worktrees-on-SSH).
- if (ctlSsh) {
- reply({ ok: false, error: MEDIA_SSH_NOTICE.replace('%s', 'show-video') })
- return
- }
- await window.nodeTerminal.media.allow(args.path)
- const id = addAndConnect(createVideoNode(nodesRef.current.length, args.path, placeBelow()))
+ // On an SSH project the agent's path lives on the HOST: stamp the node `sshFs` so
+ // VideoNode pulls the file into the local media cache over the ControlMaster
+ // (media.allowSsh) — playing it locally would either miss or, worse, play a
+ // same-named local file. Local projects allowlist the local path as before.
+ if (!ctlSsh) await window.nodeTerminal.media.allow(args.path)
+ const id = addAndConnect(
+ createVideoNode(nodesRef.current.length, args.path, placeBelow(), !!ctlSsh)
+ )
reply({ ok: true, message: `showing video ${id}`, result: { id } })
return
}
diff --git a/src/renderer/nodes/VideoNode.tsx b/src/renderer/nodes/VideoNode.tsx
index 8a2efb333..3e4077b13 100644
--- a/src/renderer/nodes/VideoNode.tsx
+++ b/src/renderer/nodes/VideoNode.tsx
@@ -1,23 +1,53 @@
import { useEffect, useState } from 'react'
import { Handle, NodeResizer, Position, useReactFlow, type NodeProps } from '@xyflow/react'
import type { CanvasNode } from '../state/workspace'
+import { useProjects } from '../state/projects'
/**
- * A video player node for a local video file. The file is served over the `nt-media://`
- * protocol (allowlisted on mount via `media.allow`) and rendered with native controls so
- * seeking/scrubbing works. The frame/header mirror {@link EditorNode} for consistent
- * drag/resize/close behavior.
+ * A video player node. A local file is served over the `nt-media://` protocol (allowlisted on
+ * mount via `media.allow`) and rendered with native controls so seeking/scrubbing works. A file
+ * in an SSH project (`data.sshFs` — the path lives on the HOST, mirroring EditorNode's flag) is
+ * first pulled into the local media cache over the project's ControlMaster (`media.allowSsh`;
+ * re-fetch is skipped when the cached copy still matches), then played the same way. The
+ * frame/header mirror {@link EditorNode} for consistent drag/resize/close behavior.
*/
export default function VideoNode({ id, data, selected }: NodeProps<CanvasNode>) {
const { deleteElements } = useReactFlow()
const [src, setSrc] = useState('')
const [error, setError] = useState('')
+ const [fetching, setFetching] = useState(false)
const filePath = (data.filePath as string) ?? ''
const fileName = filePath.split('/').pop() || 'video'
+ const remote = !!data.sshFs
useEffect(() => {
if (!filePath) return
let alive = true
+ if (remote) {
+ // Remote fetch can take a while for a large file — say what the wait is.
+ const projectId = useProjects.getState().activeProjectId
+ if (!projectId) {
+ setError('Couldn’t load this video.')
+ return
+ }
+ setFetching(true)
+ window.nodeTerminal.media
+ .allowSsh(projectId, filePath)
+ .then((r) => {
+ if (!alive) return
+ setFetching(false)
+ if (r.ok) setSrc(r.url)
+ else setError(r.error)
+ })
+ .catch(() => {
+ if (!alive) return
+ setFetching(false)
+ setError('Couldn’t load this video.')
+ })
+ return () => {
+ alive = false
+ }
+ }
window.nodeTerminal.media
.allow(filePath)
.then((url) => {
@@ -29,7 +59,10 @@ export default function VideoNode({ id, data, selected }: NodeProps<CanvasNode>)
return () => {
alive = false
}
- }, [filePath])
+ // activeProjectId is read at effect time on purpose: the node lives inside its project's
+ // canvas, so the active project when the node mounts IS its project.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [filePath, remote])
return (
<div
@@ -70,7 +103,9 @@ export default function VideoNode({ id, data, selected }: NodeProps<CanvasNode>)
style={{ width: '100%', height: '100%', objectFit: 'contain' }}
/>
) : (
- <span className="editor-node__loading">{error || 'Loading…'}</span>
+ <span className="editor-node__loading">
+ {error || (fetching ? 'Fetching from the host…' : 'Loading…')}
+ </span>
)}
</div>
</div>
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 8fdb45681..ac2dd7dec 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -476,11 +476,15 @@ export function isVideoFile(path: string): boolean {
return VIDEO_EXTS.includes(ext)
}
-/** Creates a video player node for a local video file (streamed via nt-media://). */
+/** Creates a video player node for a video file (streamed via nt-media://). When `sshFs` is true,
+ * `data.sshFs` is stamped so VideoNode fetches the file from the SSH project's host into the
+ * local media cache (media.allowSsh) instead of allowlisting a local path — mirroring
+ * createEditorNode's remote-fs flag. */
export function createVideoNode(
index: number,
filePath: string,
- center?: { x: number; y: number }
+ center?: { x: number; y: number },
+ sshFs?: boolean
): CanvasNode {
return {
id: nextId('video'),
@@ -493,7 +497,8 @@ export function createVideoNode(
title: filePath.split('/').pop() || 'video',
color: '#bf5af2',
group: null,
- filePath
+ filePath,
+ ...(sshFs ? { sshFs: true } : {})
}
}
}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 4ec8eed3f..c706b9469 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -192,6 +192,9 @@ export const IPC = {
sshMkdir: 'ssh:mkdir',
sshUploadFile: 'ssh:upload-file',
sshDownloadFile: 'ssh:download-file',
+ /** Cache a remote media file locally (scp over the ControlMaster) and allowlist it for
+ * nt-media:// playback — how a VideoNode plays a file that lives on an SSH project's host. */
+ sshMediaAllow: 'ssh:media-allow',
sshFsList: 'sshFs:list',
sshFsRead: 'sshFs:read',
sshFsReadBinary: 'sshFs:read-binary',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 26ae94839..56dbaf90d 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -585,6 +585,13 @@ export interface FilesApi {
export interface MediaApi {
/** Allow an absolute local path to be served, and return its nt-media:// URL. */
allow(absPath: string): Promise<string>
+ /**
+ * Allow a file that lives on an SSH project's HOST: main pulls it into a local cache over the
+ * project's ControlMaster (skipped when the cached copy's size still matches the remote), then
+ * allowlists the cached copy. Resolves the playable nt-media:// URL, or a reason it couldn't
+ * (not connected, transfer failed). Desktop only — the browser bridge rejects it.
+ */
+ allowSsh(projectId: string, remotePath: string): Promise<{ ok: true; url: string } | { ok: false; error: string }>
/** Persist raw HTML to <userData>/agent-web/<id>.html, allowlist it, return its absolute path. */
writeHtml(html: string): Promise<string>
}