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(handoff): transfer works on SSH projects; report-only dialogs stop offering "Delete"

enesbc979fc1eda2
diff --git a/src/main/handoff/index.ts b/src/main/handoff/index.ts
index 6ccb550ec..825ea0310 100644
--- a/src/main/handoff/index.ts
+++ b/src/main/handoff/index.ts
@@ -1,6 +1,9 @@
// Cross-agent conversation transfer (main process). Locates the source agent's native
-// transcript by sessionId, renders it to full Markdown, and writes a portable handoff file
-// under <cwd>/.nodeterm/. The PRIMARY file is context-budgeted (budget.ts): a long session
+// transcript, renders it to full Markdown, and writes a portable handoff file under
+// <cwd>/.nodeterm/ — on the REMOTE host when the source node's session runs on an SSH
+// project's host (`HandoffRemote`), so the transferred-to node, which runs there too, can
+// actually read it. Before that the whole flow assumed one machine: the locators searched
+// the desktop's disk and the write went to a local path built from a REMOTE cwd. The PRIMARY file is context-budgeted (budget.ts): a long session
// used to dump megabytes, and a target agent obeying "read the entire file" hit its own
// context ceiling, compacted, and forgot the task (field report — codex greeted with
// "What would you like to work on?"). Over-budget sessions keep the recent conversation
@@ -41,34 +44,81 @@ export function handoffFilename(nodeId: string, ts: string): string {
return `handoff-${safe}-${ts}.md`
}
+/** Tail bytes pulled from a REMOTE transcript. Matches context-link's remote cap: a handoff is
+ * budgeted down anyway (budget.ts), and the tail is the part that survives that budget. A tail
+ * read can start mid-line; every renderer skips unparseable lines, so the partial head is
+ * dropped silently rather than corrupting the render. */
+const REMOTE_TRANSCRIPT_MAX_BYTES = 2 * 1024 * 1024
+
+/**
+ * The host-dependent half of a handoff, injected by `src/main` so the build logic itself is the
+ * same whether the session runs on this machine or on an SSH project's host. Without it (Server
+ * Edition, tests) buildHandoff stays local-only — exactly its previous behavior.
+ */
+export interface HandoffRemote {
+ /** Does this node's session run on an SSH project's remote host? */
+ isRemoteNode: (nodeId: string) => boolean
+ /** The node's hook-fed transcript path, already JAILED where the hook payload arrives
+ * (`isSafeRemoteTranscriptPath`). '' when no hook has reported one yet. */
+ hookedTranscriptPath: (nodeId: string) => string
+ /** Tail-read a file on the node's host. null on any failure. */
+ readRemoteFile: (nodeId: string, filePath: string, maxBytes: number) => Promise<string | null>
+ /** Write a file on the node's host (atomic, parents created). false on any failure. */
+ writeRemoteFile: (nodeId: string, filePath: string, content: string) => Promise<boolean>
+}
+
export async function buildHandoff(opts: {
sessionId: string
agentId: string
sourceNodeId: string
cwd?: string
accountId?: string
+ remote?: HandoffRemote
}): Promise<HandoffResult> {
const { sessionId, agentId, sourceNodeId, cwd, accountId } = opts
if (!sessionId || !SESSION_ID_RE.test(sessionId)) return { error: 'No valid session id to transfer.' }
const render = RENDERERS[agentId]
- const locate = LOCATORS[agentId]
- if (!render || !locate) return { error: `Transfer is not supported from ${agentId}.` }
+ if (!render) return { error: `Transfer is not supported from ${agentId}.` }
+ // Everything below branches on ONE question: does this node's session live on a remote host?
+ const remote = opts.remote?.isRemoteNode(sourceNodeId) ? opts.remote : undefined
- const src = await locate(sessionId, accountId)
- if (!src) return { error: "Couldn't find the source conversation transcript." }
-
- let raw: string
- try {
- raw = await fs.promises.readFile(src, 'utf8')
- } catch {
- return { error: 'Failed to read the source transcript.' }
+ let raw: string | null
+ if (remote) {
+ // The locators search THIS machine's disk. For a remote node they would find nothing (the
+ // failure this fixes) or — worse — some unrelated local session's file. The hook-fed path is
+ // the only trustworthy source, exactly as context-link's resolveLinkTranscript decided.
+ const src = remote.hookedTranscriptPath(sourceNodeId)
+ if (!src) {
+ return {
+ error:
+ "Couldn't locate this remote session's transcript yet — its hooks haven't reported one. " +
+ 'Send a message in that session, then transfer again.'
+ }
+ }
+ raw = await remote.readRemoteFile(sourceNodeId, src, REMOTE_TRANSCRIPT_MAX_BYTES)
+ if (raw === null) return { error: 'Failed to read the source transcript from the remote host.' }
+ } else {
+ const locate = LOCATORS[agentId]
+ if (!locate) return { error: `Transfer is not supported from ${agentId}.` }
+ const src = await locate(sessionId, accountId)
+ if (!src) return { error: "Couldn't find the source conversation transcript." }
+ try {
+ raw = await fs.promises.readFile(src, 'utf8')
+ } catch {
+ return { error: 'Failed to read the source transcript.' }
+ }
}
const full = render(raw)
const ts = new Date().toISOString().replace(/[:.]/g, '-')
- const dir = path.join(cwd && cwd.length ? cwd : os.homedir(), '.nodeterm')
- const filePath = path.join(dir, handoffFilename(sourceNodeId, ts))
+ // The handoff file must land where the TARGET agent can read it: on the remote host for an SSH
+ // project (its new node runs there too), on this disk otherwise. `cwd` is already the right
+ // machine's path either way — only the writer differs. POSIX join for the remote side so a
+ // Windows desktop can't emit backslash paths into a unix host.
+ const join = remote ? path.posix.join : path.join
+ const dir = join(cwd && cwd.length ? cwd : remote ? '~' : os.homedir(), '.nodeterm')
+ const filePath = join(dir, handoffFilename(sourceNodeId, ts))
const fullPath = filePath.replace(/\.md$/, '-full.md')
const { body, truncated } = budgetHandoff(full, undefined, fullPath)
@@ -79,9 +129,18 @@ export async function buildHandoff(opts: {
? `This is the prior conversation, condensed to fit your context (see the note below).\n\n---\n\n`
: `This is the COMPLETE prior conversation, including all tool calls and outputs.\n\n---\n\n`)
+ if (remote) {
+ // The complete render goes first: if it fails, the primary must not promise a full copy.
+ if (truncated && !(await remote.writeRemoteFile(sourceNodeId, fullPath, full))) {
+ return { error: 'Failed to write the handoff file to the remote host.' }
+ }
+ if (!(await remote.writeRemoteFile(sourceNodeId, filePath, header + body))) {
+ return { error: 'Failed to write the handoff file to the remote host.' }
+ }
+ return { filePath }
+ }
try {
await fs.promises.mkdir(dir, { recursive: true })
- // The complete render goes first: if it fails, the primary must not promise a full copy.
if (truncated) await fs.promises.writeFile(fullPath, full, 'utf8')
await fs.promises.writeFile(filePath, header + body, 'utf8')
} catch {
diff --git a/src/main/handoff/remote.test.ts b/src/main/handoff/remote.test.ts
new file mode 100644
index 000000000..75b191ccb
--- /dev/null
+++ b/src/main/handoff/remote.test.ts
@@ -0,0 +1,128 @@
+import { describe, it, expect, vi } from 'vitest'
+import os from 'os'
+import path from 'path'
+import { promises as fs } from 'fs'
+import { buildHandoff, type HandoffRemote } from './index'
+
+const SESSION = '11111111-2222-3333-4444-555555555555'
+const NODE = 'term-remote-1'
+const TRANSCRIPT = '/home/deploy/.claude/projects/-srv-app/' + SESSION + '.jsonl'
+
+/** Two claude transcript lines — enough for the renderer to produce a real body. */
+const RAW = [
+ JSON.stringify({ type: 'user', message: { role: 'user', content: 'ship the parser' } }),
+ JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'on it' }] } })
+].join('\n')
+
+function remoteDeps(over: Partial<HandoffRemote> = {}): {
+ deps: HandoffRemote
+ writes: Array<{ path: string; content: string }>
+} {
+ const writes: Array<{ path: string; content: string }> = []
+ const deps: HandoffRemote = {
+ isRemoteNode: () => true,
+ hookedTranscriptPath: () => TRANSCRIPT,
+ readRemoteFile: async () => RAW,
+ writeRemoteFile: async (_n, p, content) => {
+ writes.push({ path: p, content })
+ return true
+ },
+ ...over
+ }
+ return { deps, writes }
+}
+
+describe('buildHandoff — remote (SSH project) source', () => {
+ it('reads the hook-fed transcript and writes the handoff ON THE HOST, never locally', async () => {
+ const { deps, writes } = remoteDeps()
+ const mkdir = vi.spyOn(fs, 'mkdir')
+ const writeFile = vi.spyOn(fs, 'writeFile')
+ const res = await buildHandoff({
+ sessionId: SESSION,
+ agentId: 'claude',
+ sourceNodeId: NODE,
+ cwd: '/srv/app',
+ remote: deps
+ })
+ expect('filePath' in res).toBe(true)
+ // The returned path is the REMOTE one the transferred-to node will read.
+ expect((res as { filePath: string }).filePath).toMatch(/^\/srv\/app\/\.nodeterm\/handoff-term-remote-1-.*\.md$/)
+ expect(writes).toHaveLength(1)
+ expect(writes[0].content).toContain('ship the parser')
+ expect(writes[0].content).toContain('on it')
+ // Nothing touched this machine's disk.
+ expect(mkdir).not.toHaveBeenCalled()
+ expect(writeFile).not.toHaveBeenCalled()
+ mkdir.mockRestore()
+ writeFile.mockRestore()
+ })
+
+ it('never falls back to the LOCAL locators for a remote node', async () => {
+ // No hook-fed path yet. A local locator could resolve some unrelated same-id file on this
+ // machine; the remote branch must refuse instead of reading a stranger's transcript.
+ const { deps, writes } = remoteDeps({ hookedTranscriptPath: () => '' })
+ const read = vi.fn()
+ const res = await buildHandoff({
+ sessionId: SESSION,
+ agentId: 'claude',
+ sourceNodeId: NODE,
+ cwd: '/srv/app',
+ remote: { ...deps, readRemoteFile: read }
+ })
+ expect(res).toEqual({
+ error: expect.stringContaining("hooks haven't reported one")
+ })
+ expect(read).not.toHaveBeenCalled()
+ expect(writes).toHaveLength(0)
+ })
+
+ it('reports a failed remote read instead of writing an empty handoff', async () => {
+ const { deps, writes } = remoteDeps({ readRemoteFile: async () => null })
+ const res = await buildHandoff({
+ sessionId: SESSION,
+ agentId: 'claude',
+ sourceNodeId: NODE,
+ cwd: '/srv/app',
+ remote: deps
+ })
+ expect(res).toEqual({ error: expect.stringContaining('remote host') })
+ expect(writes).toHaveLength(0)
+ })
+
+ it('reports a failed remote write rather than returning a path that does not exist', async () => {
+ const { deps } = remoteDeps({ writeRemoteFile: async () => false })
+ const res = await buildHandoff({
+ sessionId: SESSION,
+ agentId: 'claude',
+ sourceNodeId: NODE,
+ cwd: '/srv/app',
+ remote: deps
+ })
+ expect(res).toEqual({ error: expect.stringContaining('Failed to write') })
+ })
+
+ it('falls back to the remote home (~), not this machine, when the node has no cwd', async () => {
+ const { deps, writes } = remoteDeps()
+ const res = await buildHandoff({ sessionId: SESSION, agentId: 'claude', sourceNodeId: NODE, remote: deps })
+ expect((res as { filePath: string }).filePath.startsWith('~/.nodeterm/')).toBe(true)
+ expect(writes[0].path.startsWith(os.homedir())).toBe(false)
+ })
+
+ it('a LOCAL node with remote deps present still takes the local path', async () => {
+ // isRemoteNode false ⇒ the deps must be inert (Server Edition / plain local project).
+ const { deps, writes } = remoteDeps({ isRemoteNode: () => false })
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'handoff-local-'))
+ const res = await buildHandoff({
+ sessionId: SESSION,
+ agentId: 'claude',
+ sourceNodeId: NODE,
+ cwd: dir,
+ remote: deps
+ })
+ // No transcript exists locally for this id, so it fails the LOCAL way — the point is that it
+ // never consulted the remote deps.
+ expect(res).toEqual({ error: "Couldn't find the source conversation transcript." })
+ expect(writes).toHaveLength(0)
+ await fs.rm(dir, { recursive: true, force: true })
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 8390cc07c..d9bec6aab 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -81,8 +81,9 @@ import { createRemoteSubagentTail } from './remote-subagent-tail'
import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'
import { childArgs } from '../core/remote-ssh/control-master'
import { posixQuote } from '../shared/ssh'
-import { buildHandoff } from './handoff'
+import { buildHandoff, type HandoffRemote } from './handoff'
import { initContextLink, setNodeTranscript } from '../core/context-link'
+import { transcriptPathOf } from '../core/context-link-core'
import { initCanvasControl, installCanvasSkillInto } from './canvas-control'
import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'
import { initTelemetry } from './telemetry'
@@ -120,7 +121,7 @@ import { decodeOffer } from './remote/pairing'
import { loadOrCreatePeerKeyPair } from './remote/peer-identity'
import { initSshProject } from './remote-ssh/ssh-project'
import { setGitRemoteResolver, type GitRemoteRef } from '../core/remote-ssh/remote-git'
-import { SshFs, sshAppendArgs, sshTailArgs, sshSizeArgs } from './ssh-fs'
+import { SshFs, sshAppendArgs, sshTailArgs, sshSizeArgs, sshWriteArgs } from './ssh-fs'
import { makeRemoteWorkspaceIO } from './remote-workspace-io'
import {
registerMediaScheme,
@@ -1111,6 +1112,35 @@ app.whenReady().then(async () => {
if (!p && cwd) p = await transcriptPathForCwd(cwd)
if (p) contextTail.track(sessionId, p)
})
+ // The remote half of a handoff. Same three-line shape as the context-link deps above and for
+ // the same reason: reading (and here also WRITING) on an SSH project's host is the one thing
+ // the handoff builder cannot answer for itself. Absent deps ⇒ local-only, as before.
+ const handoffRemote: HandoffRemote = {
+ isRemoteNode: (nodeId) => !!ptyManager.sshRemoteForNode(nodeId),
+ hookedTranscriptPath: (nodeId) => transcriptPathOf(nodeId),
+ readRemoteFile: async (nodeId, filePath, maxBytes) => {
+ const rt = ptyManager.sshRemoteForNode(nodeId)
+ if (!rt) return null
+ const text = await remoteFile.readTail(
+ { conn: rt.conn, controlPath: rt.controlPath, path: filePath },
+ maxBytes
+ )
+ return text || null
+ },
+ writeRemoteFile: async (nodeId, filePath, content) => {
+ const rt = ptyManager.sshRemoteForNode(nodeId)
+ if (!rt || !sshProjectManager) return false
+ try {
+ const { code } = await sshProjectManager.sshRun(
+ sshWriteArgs(rt.conn, rt.controlPath, filePath),
+ content
+ )
+ return code === 0
+ } catch {
+ return false
+ }
+ }
+ }
corePlatform.handle(
IPC.handoffBuild,
(
@@ -1119,7 +1149,7 @@ app.whenReady().then(async () => {
sourceNodeId: string,
cwd: string | undefined,
accountId: string | undefined
- ) => buildHandoff({ sessionId, agentId, sourceNodeId, cwd, accountId })
+ ) => buildHandoff({ sessionId, agentId, sourceNodeId, cwd, accountId, remote: handoffRemote })
)
installManagedAgentHooks()
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 958348129..769446634 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -258,6 +258,8 @@ interface ConfirmState {
confirmLabel?: string
cancelLabel?: string
danger?: boolean
+ /** Report-only (an error, a "not ready yet"): one dismiss button, no destructive default. */
+ alert?: boolean
/** Set when an AGENT asked for this dialog: it is answered by an explicit click, never by an
* Enter the user aimed at their terminal (see components/confirm-key). */
requestedBy?: string
@@ -3597,7 +3599,7 @@ export function Canvas() {
const error = res.error ?? 'Branch failed.'
// The error dialog is for humans; agent-CLI calls get the error in the reply instead.
if (opts?.interactive !== false) {
- setConfirm({ message: error, onConfirm: () => setConfirm(null) })
+ setConfirm({ message: error, alert: true, onConfirm: () => setConfirm(null) })
}
return { ok: false, error }
}
@@ -3638,6 +3640,7 @@ export function Canvas() {
if (!sourceAgentId || !sessionId) {
setConfirm({
message: 'Conversation not ready to transfer yet.',
+ alert: true,
onConfirm: () => setConfirm(null)
})
return
@@ -3650,7 +3653,7 @@ export function Canvas() {
source.data.accountId
)
if ('error' in res) {
- setConfirm({ message: res.error, onConfirm: () => setConfirm(null) })
+ setConfirm({ message: res.error, alert: true, onConfirm: () => setConfirm(null) })
return
}
// The file is context-budgeted by buildHandoff (long sessions: digest + verbatim tail,
@@ -3665,13 +3668,19 @@ export function Canvas() {
`Read the file, then continue seamlessly from exactly where the conversation left ` +
`off — as if you had been the assistant all along. If a task is in progress, resume ` +
`it immediately; do not greet, re-introduce yourself, or summarize the file back.`
+ // An SSH project's transfer target must run on the SAME host as the source: the handoff
+ // file was written there (buildHandoff's remote branch), and `cwd` is a remote path. A
+ // local node here would open in a directory that doesn't exist on this machine and could
+ // never read the file it was told to read.
+ const { projects, activeProjectId } = useProjects.getState()
+ const projectSsh = projects.find((p) => p.id === activeProjectId)?.ssh
const node = createAgentNode(
targetAgentId,
nodesRef.current.length,
source.data.cwd,
undefined,
prompt,
- undefined,
+ source.data.sshRemoteTmux ? projectSsh : undefined,
// Inherit the source's Claude account (dropped by the factory unless the target is claude),
// so a claude→claude transfer resumes the transcript from the right account dir.
source.data.accountId,
@@ -6498,6 +6507,7 @@ export function Canvas() {
confirmLabel={confirm.confirmLabel}
cancelLabel={confirm.cancelLabel}
danger={confirm.danger}
+ alert={confirm.alert}
// The user did not open this one — an agent did. It appeared under their hands, so it is
// answered by a click, never by a keystroke aimed somewhere else (components/confirm-key).
enterConfirms={!confirm.requestedBy}
diff --git a/src/renderer/components/ConfirmDialog.tsx b/src/renderer/components/ConfirmDialog.tsx
index e20d6497a..82d67bce2 100644
--- a/src/renderer/components/ConfirmDialog.tsx
+++ b/src/renderer/components/ConfirmDialog.tsx
@@ -11,6 +11,10 @@ interface ConfirmDialogProps {
confirmLabel?: string
cancelLabel?: string
danger?: boolean
+ /** Nothing to decide — the dialog only REPORTS (an error, a "not ready yet"). Renders a single
+ * dismiss button instead of the destructive default pair: an error message offering
+ * "Cancel / Delete" reads as though dismissing it will delete something. */
+ alert?: boolean
/** An explicit opt-in shown above the buttons (e.g. "Delete the worktree directory from disk
* too"). The caller owns the value, so it can also swap the confirm label / danger styling. */
option?: { label: string; checked: boolean; onChange: (checked: boolean) => void }
@@ -34,14 +38,19 @@ interface ConfirmDialogProps {
export function ConfirmDialog({
message,
body,
- confirmLabel = 'Delete',
+ confirmLabel,
cancelLabel = 'Cancel',
- danger = true,
+ danger: dangerProp,
+ alert = false,
option,
enterConfirms = true,
onConfirm,
onCancel
}: ConfirmDialogProps) {
+ // An alert has nothing destructive to warn about and nothing to cancel; anything else keeps the
+ // historical destructive defaults ("Delete", danger styling, focus parked on the safe button).
+ const danger = dangerProp ?? !alert
+ const confirmText = confirmLabel ?? (alert ? 'OK' : 'Delete')
// One id per instance, for the lifetime of the component (mount order == paint order == stack).
const idRef = useRef<string>()
if (!idRef.current) idRef.current = nextDialogId()
@@ -98,15 +107,17 @@ export function ConfirmDialog({
{/* The DESTRUCTIVE button never takes focus: autoFocus on it is what turned a stray Enter
(or Space) into a deletion. On a danger dialog the safe button is the focused one; on a
harmless one the primary action may keep it. */}
- <button className="confirm__btn" autoFocus={danger} onClick={onCancel}>
- {cancelLabel}
- </button>
+ {!alert && (
+ <button className="confirm__btn" autoFocus={danger} onClick={onCancel}>
+ {cancelLabel}
+ </button>
+ )}
<button
className={`confirm__btn${danger ? ' danger' : ' primary'}`}
autoFocus={!danger}
onClick={onConfirm}
>
- {confirmLabel}
+ {confirmText}
</button>
</div>
</div>