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(ssh): uploadFile — scp a dropped file to the remote over the master

enes0296e25a8ad6
diff --git a/src/main/remote-ssh/control-master.test.ts b/src/main/remote-ssh/control-master.test.ts
index 1f8a2323b..846553cf9 100644
--- a/src/main/remote-ssh/control-master.test.ts
+++ b/src/main/remote-ssh/control-master.test.ts
@@ -13,7 +13,8 @@ import {
hookForwardArgs,
hookForwardCancelArgs,
remoteHookEnvArgs,
- remoteEndpointFileContents
+ remoteEndpointFileContents,
+ scpArgs
} from './control-master'
const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
@@ -141,6 +142,17 @@ describe('hook forwarding', () => {
})
})
+describe('scpArgs', () => {
+ it('reuses the master socket, uses scp -P for the port, and quotes the absolute remote path', () => {
+ const j = scpArgs(conn, '/s.sock', '/local/i m.png', '/home/u/.nodeterm/uploads/t/i m.png').join(' ')
+ expect(j).toContain('-o ControlPath=/s.sock')
+ expect(j).toContain('-P 2222') // scp uses uppercase -P
+ expect(j).toContain('-i /k/id') // identityFile
+ // local path raw; remote spec is user@host:<posixQuote(remotePath)>
+ expect(j).toContain(`/local/i m.png [email protected]:'/home/u/.nodeterm/uploads/t/i m.png'`)
+ })
+})
+
describe('listDirArgs', () => {
it('lists directory entries of a quoted absolute path', () => {
expect(listDirArgs(conn, '/s.sock', '/srv/app')).toEqual([
diff --git a/src/main/remote-ssh/control-master.ts b/src/main/remote-ssh/control-master.ts
index e99d64a67..f1aed8e9d 100644
--- a/src/main/remote-ssh/control-master.ts
+++ b/src/main/remote-ssh/control-master.ts
@@ -3,7 +3,7 @@
import os from 'os'
import path from 'path'
import { createHash } from 'crypto'
-import { quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'
+import { posixQuote, quoteRemotePath, remoteTmuxCommand, type SshConnection } from '../../shared/ssh'
/** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */
export const RMT_TMUX_SOCKET = 'nodeterm-rmt'
@@ -88,6 +88,15 @@ export function mkDirArgs(conn: SshConnection, controlPath: string, path: string
return childArgs(conn, controlPath, `mkdir -p ${quoteRemotePath(path)}`)
}
+/** scp argv that reuses the project's ControlMaster. `localPath` is a raw local arg; the absolute
+ * `remotePath` is posixQuote'd (the remote shell interprets it). scp uses `-P` for the port. */
+export function scpArgs(conn: SshConnection, controlPath: string, localPath: string, remotePath: string): string[] {
+ const args = ['-o', 'ControlMaster=no', '-o', `ControlPath=${controlPath}`, '-P', String(conn.port ?? 22)]
+ if (conn.identityFile) args.push('-i', conn.identityFile)
+ args.push(localPath, `${conn.user}@${conn.host}:${posixQuote(remotePath)}`)
+ 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 scripts
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 56e9543d3..e4eea12bc 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -9,10 +9,12 @@ function makeMgr() {
// spawnMaster: returns a fake child that "stays up"; run: resolves stdout for one-shot ssh.
const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
const run = vi.fn(async (_args: string[], _stdin?: string) => ({ code: 0, stdout: 'src/\nbin/\n' }))
+ const runScp = vi.fn(async (_args: string[]) => ({ code: 0 }))
const mgr = new SshProjectManager({
userDataDir: '/ud',
spawnMaster,
run,
+ runScp,
getHook: () => ({ port: 51234, token: 'tok', version: '1' }),
onStatus: (e) => statuses.push(e.status)
})
@@ -55,4 +57,33 @@ describe('SshProjectManager', () => {
expect(mgr.refForRemoteCwd('/srv/repo')).toEqual({ conn, controlPath: controlPathFor('p1') })
expect(mgr.refForRemoteCwd('/nope')).toBeUndefined()
})
+
+ it('uploadFile uploads via scp under <remoteHome>/.nodeterm/uploads/<token> and returns the abs path', async () => {
+ const scpCalls: string[][] = []
+ const run = vi.fn(async (args: string[]) =>
+ args.join(' ').includes('printf %s') ? { code: 0, stdout: '/home/u' } : { code: 0, stdout: '' }
+ )
+ const runScp = vi.fn(async (args: string[]) => {
+ scpCalls.push(args)
+ return { code: 0 }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp,
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', conn, '/srv/repo')
+ const out = await mgr.uploadFile('p1', '/local/img.png', 'img.png')
+ expect(out).toMatch(/^\/home\/u\/\.nodeterm\/uploads\/[a-z0-9]+\/img\.png$/)
+ // scp targeted that exact absolute remote path (conn is { host: 'h', user: 'u' }).
+ expect(scpCalls[0].join(' ')).toContain(`u@h:'${out}'`)
+ })
+
+ 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.ts
index 088986c1c..350527b74 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -3,7 +3,7 @@ import path from 'path'
import { spawn, execFile, execFileSync } from 'child_process'
import { app, ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
-import { parseLsDirs, type SshConnection } from '../../shared/ssh'
+import { parseLsDirs, posixQuote, type SshConnection } from '../../shared/ssh'
import type { SshProjectStatus } from '../../shared/types'
import {
controlPathFor,
@@ -13,7 +13,8 @@ import {
exitMasterArgs,
checkMasterArgs,
remoteTmuxKillArgs,
- childArgs
+ childArgs,
+ scpArgs
} from './control-master'
import { RemoteHooks } from './remote-hooks'
import { hookServer } from '../agents/hook-server'
@@ -25,6 +26,8 @@ interface Runners {
spawnMaster: (args: string[]) => { kill: () => void; on: (ev: string, cb: (...a: unknown[]) => void) => void }
/** Run a one-shot ssh, resolving its stdout + exit code; optional stdin written to the child. */
run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>
+ /** Run a one-shot scp (file upload over the master); resolves its exit code. */
+ runScp: (args: string[]) => Promise<{ code: number }>
/** Live loopback hook-server coordinates (injected so the manager stays testable). */
getHook: () => { port: number; token: string; version: string }
onStatus: (e: { projectId: string; status: SshProjectStatus; error?: string }) => void
@@ -73,9 +76,37 @@ function sshBin(): string {
return cachedSsh ?? 'ssh'
}
+/** Resolve an absolute `scp` path the same way `sshBin()` resolves `ssh` (GUI apps lack shell PATH). */
+let cachedScp: string | null | undefined
+function scpBin(): string {
+ if (cachedScp !== undefined) return cachedScp ?? 'scp'
+ try {
+ const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', 'command -v scp'], {
+ encoding: 'utf-8'
+ }).trim()
+ cachedScp = out || null
+ } catch {
+ cachedScp = null
+ }
+ if (!cachedScp) {
+ for (const p of ['/usr/bin/scp', '/usr/local/bin/scp', '/opt/homebrew/bin/scp']) {
+ try {
+ execFileSync(p, ['-V'], { stdio: 'ignore' })
+ cachedScp = p
+ break
+ } catch {
+ // keep trying
+ }
+ }
+ }
+ return cachedScp ?? 'scp'
+}
+
export class SshProjectManager {
private conns = new Map<string, Conn>()
private remoteHooks: RemoteHooks
+ /** Per-manager counter mixed into each upload token so concurrent drops never collide. */
+ private uploadSeq = 0
constructor(private r: Runners) {
this.remoteHooks = new RemoteHooks({ run: r.run })
}
@@ -160,6 +191,29 @@ export class SshProjectManager {
return code === 0
}
+ /** Upload a local file to the remote over the master; returns the ABSOLUTE remote path, or null. */
+ async uploadFile(projectId: string, localPath: string, fileName: string): Promise<string | null> {
+ const c = this.conns.get(projectId)
+ if (!c) return null
+ try {
+ let home = c.remoteHome
+ if (!home) {
+ const r = await this.r.run(childArgs(c.conn, c.controlPath, 'printf %s "$HOME"'))
+ if (r.code === 0 && r.stdout.trim()) home = r.stdout.trim()
+ }
+ if (!home) return null
+ const token = `${Date.now().toString(36)}${(this.uploadSeq++).toString(36)}`
+ const dir = `${home}/.nodeterm/uploads/${token}`
+ const mk = await this.r.run(childArgs(c.conn, c.controlPath, `mkdir -p ${posixQuote(dir)}`))
+ if (mk.code !== 0) return null
+ const remotePath = `${dir}/${fileName}`
+ const up = await this.r.runScp(scpArgs(c.conn, c.controlPath, localPath, remotePath))
+ return up.code === 0 ? remotePath : null
+ } catch {
+ return null
+ }
+ }
+
/**
* 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
@@ -260,6 +314,7 @@ export class SshProjectManager {
export function initSshProject(win: BrowserWindow): SshProjectManager {
const ssh = sshBin()
+ const scp = scpBin()
const mgr = new SshProjectManager({
userDataDir: app.getPath('userData'),
spawnMaster: (args) => spawn(ssh, args, { stdio: 'ignore' }),
@@ -277,6 +332,10 @@ export function initSshProject(win: BrowserWindow): SshProjectManager {
child.stdin?.end(stdin)
}
}),
+ runScp: (args) =>
+ new Promise((resolve) => {
+ execFile(scp, args, { maxBuffer: 1024 * 1024 }, (err) => resolve({ code: err ? 1 : 0 }))
+ }),
getHook: () => ({ port: hookServer.getPort(), token: hookServer.getToken(), version: hookServer.getVersion() }),
onStatus: (e) => {
if (!win.isDestroyed()) win.webContents.send(IPC.sshProjectStatus, e)
@@ -291,5 +350,8 @@ export function initSshProject(win: BrowserWindow): SshProjectManager {
)
ipcMain.handle(IPC.sshListDir, (_e, projectId: string, dir: string) => mgr.listDir(projectId, dir))
ipcMain.handle(IPC.sshMkdir, (_e, projectId: string, dir: string) => mgr.makeDir(projectId, dir))
+ ipcMain.handle(IPC.sshUploadFile, (_e, projectId: string, localPath: string, fileName: string) =>
+ mgr.uploadFile(projectId, localPath, fileName)
+ )
return mgr
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index ebc1d0310..aba778025 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -92,6 +92,8 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.sshKillSessions, projectId, nodeIds),
listDir: (projectId, dir) => ipcRenderer.invoke(IPC.sshListDir, projectId, dir),
mkdir: (projectId, dir) => ipcRenderer.invoke(IPC.sshMkdir, projectId, dir),
+ uploadFile: (projectId, localPath, fileName) =>
+ ipcRenderer.invoke(IPC.sshUploadFile, projectId, localPath, fileName),
onStatus: (cb) => {
const h = (_e: unknown, e: unknown) => cb(e as never)
ipcRenderer.on(IPC.sshProjectStatus, h)
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 702ba2522..c0655a4f3 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -69,6 +69,7 @@ export const IPC = {
sshKillSessions: 'ssh:kill-sessions',
sshListDir: 'ssh:list-dir',
sshMkdir: 'ssh:mkdir',
+ sshUploadFile: 'ssh:upload-file',
sshFsList: 'sshFs:list',
sshFsRead: 'sshFs:read',
sshFsReadBinary: 'sshFs:read-binary',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 4159def06..205c7d309 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -341,6 +341,12 @@ export interface SshProjectApi {
listDir(projectId: string, path: string): Promise<{ path: string; dirs: string[] }>
/** Create a remote directory (mkdir -p). Resolves false when not connected or the mkdir fails. */
mkdir(projectId: string, path: string): Promise<boolean>
+ /**
+ * Upload a local file to the remote over the project's ControlMaster, into
+ * `<remoteHome>/.nodeterm/uploads/<token>/<fileName>`. Resolves the ABSOLUTE remote path on
+ * success, or null on any failure (not connected, unresolved remote home, mkdir/scp failure).
+ */
+ uploadFile(projectId: string, localPath: string, fileName: string): Promise<string | null>
onStatus(cb: (e: { projectId: string; status: SshProjectStatus; error?: string }) => void): () => void
}