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(relay): team resume — restart handed-over agents on the core's own tmux

review4c226c7adf6a
diff --git a/src/core/pty-join-only.test.ts b/src/core/pty-join-only.test.ts
index 334b5d497..dfc9dfe98 100644
--- a/src/core/pty-join-only.test.ts
+++ b/src/core/pty-join-only.test.ts
@@ -367,3 +367,45 @@ describe('sizeVote: false — a viewer never constrains the shared pty size', ()
expect(spawned[0].resizes.at(-1)).toEqual({ cols: 120, rows: 40 })
})
})
+
+// `team resume` asks this before it starts an agent on a handed-over node: the same strict probe a
+// join-only create uses, exposed as a tri-state. The argv is pinned because the exact target
+// (`=nt-<id>`) is the whole point — a bare target prefix-matches a longer, unrelated session.
+describe('sessionVerdict: the strict, exact-target existence probe', () => {
+ /** A manager whose strict probe answers from `live` (or fails to run), recording every argv. */
+ async function verdictManager(live: string[] | 'error') {
+ const calls: Array<readonly string[]> = []
+ const confirmedProcessRun: ConfirmedProcessRun = async (_file, args) => {
+ calls.push(args)
+ if (live === 'error') throw Object.assign(new Error('spawn EAGAIN'), { code: 'EAGAIN' })
+ if (hasSession(live, args)) return { stdout: '', stderr: '' }
+ throw Object.assign(new Error("can't find session"), { code: 1 })
+ }
+ const m = await manager({ confirmedProcessRun })
+ ;(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'
+ return { m, calls }
+ }
+
+ it('asks tmux for the EXACT session and answers present', async () => {
+ const { m, calls } = await verdictManager(['nt-term-1'])
+ expect(await m.sessionVerdict('term-1')).toBe('present')
+ expect(calls).toEqual([['-L', 'node-terminal', 'has-session', '-t', '=nt-term-1']])
+ })
+
+ it("answers absent on tmux's own exit 1, even while a session whose name extends this one runs", async () => {
+ const { m } = await verdictManager(['nt-term-12'])
+ expect(await m.sessionVerdict('term-1')).toBe('absent')
+ })
+
+ it('answers unknown when the probe could not run (never read as absent)', async () => {
+ const { m } = await verdictManager('error')
+ expect(await m.sessionVerdict('term-1')).toBe('unknown')
+ })
+
+ it('answers absent with no tmux at all, without running anything', async () => {
+ const calls: Array<readonly string[]> = []
+ const m = await manager({ confirmedProcessRun: async (_f, args) => calls.push(args) })
+ expect(await m.sessionVerdict('term-1')).toBe('absent')
+ expect(calls).toEqual([])
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 09c30c72e..22fd6c333 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -3168,6 +3168,16 @@ export class PtyManager {
}
}
+ /**
+ * Is the tmux session for `persistKey` running, by the EXACT target (`=nt-<id>`)? Public for
+ * `team resume`, which must never start a second agent on a conversation whose session exists.
+ * `sessionExists` cannot answer this: its tmux leg prefix-matches, and it folds "could not tell"
+ * into "exists". No tmux at all answers 'absent' (nothing can be running there).
+ */
+ sessionVerdict(persistKey: string): Promise<'present' | 'absent' | 'unknown'> {
+ return this.strictTmuxVerdict(persistKey)
+ }
+
/**
* The strict existence probe a JOIN-ONLY create needs, as a tri-state: `unknown` when tmux could
* not be asked (a spawn error, a timeout), which such a create must refuse rather than read as
diff --git a/src/core/relay/team-admin.test.ts b/src/core/relay/team-admin.test.ts
index a4d037eb7..18cd685dc 100644
--- a/src/core/relay/team-admin.test.ts
+++ b/src/core/relay/team-admin.test.ts
@@ -557,6 +557,57 @@ describe.skipIf(process.platform === 'win32')('team admin socket (unix socket, P
})
})
+ it('resume hands the parsed session list to the resume op and returns its result', async () => {
+ const dataDir = tmp()
+ writeTeam(dataDir)
+ const asked: unknown[] = []
+ const admin = await startTeamAdmin(dataDir, fakeService().svc, {
+ resume: async (req) => {
+ asked.push(req)
+ return { results: [{ nodeId: 'n', status: 'resumed' }] }
+ }
+ })
+ closers.push(() => admin.close())
+ const sessions = [{ nodeId: 'n', agentId: 'claude', sessionId: 's' }]
+ expect(await callTeamAdmin(dataDir, { cmd: 'resume', projectId: 'p', sessions })).toEqual({
+ ok: true,
+ result: { results: [{ nodeId: 'n', status: 'resumed' }] }
+ })
+ expect(asked).toEqual([{ cmd: 'resume', projectId: 'p', sessions }])
+ })
+
+ it('resume refuses a malformed session list with E_BAD_REQUEST', async () => {
+ const dataDir = tmp()
+ writeTeam(dataDir)
+ const admin = await startTeamAdmin(dataDir, fakeService().svc, {
+ resume: async () => ({ results: [] })
+ })
+ closers.push(() => admin.close())
+ expect(JSON.parse(await rawExchange(dataDir, '{"cmd":"resume","projectId":"p","sessions":{}}\n'))).toMatchObject({
+ ok: false,
+ code: 'E_BAD_REQUEST'
+ })
+ })
+
+ it('resume without a team answers NO_TEAM (no code), and without a resume op E_UNSUPPORTED', async () => {
+ const dataDir = tmp()
+ let called = false
+ const admin = await startTeamAdmin(dataDir, fakeService().svc, {
+ resume: async () => {
+ called = true
+ return { results: [] }
+ }
+ })
+ closers.push(() => admin.close())
+ const req = { cmd: 'resume' as const, projectId: 'p', sessions: [] }
+ expect(await callTeamAdmin(dataDir, req)).toEqual({ ok: false, error: expect.stringMatching(/no hosted team/) })
+ expect(called).toBe(false)
+ const other = tmp()
+ writeTeam(other)
+ await boot(other, fakeService().svc)
+ expect(await callTeamAdmin(other, req)).toMatchObject({ ok: false, code: 'E_UNSUPPORTED' })
+ })
+
it('close() removes the socket and does not hang on a connection that never sends a request', async () => {
const dataDir = tmp()
const admin = await startTeamAdmin(dataDir, fakeService().svc)
diff --git a/src/core/relay/team-admin.ts b/src/core/relay/team-admin.ts
index f1f4a90ee..8078797a7 100644
--- a/src/core/relay/team-admin.ts
+++ b/src/core/relay/team-admin.ts
@@ -11,6 +11,8 @@
// With no hosted team on this server, the channel serves `init`, `status`, `info` and `bootstrap`
// only: every other verb would create team state (a team.json, a host key) on a server that never
// asked to host. `bootstrap` is `init` plus an owner, an adopted folder and its share, in one call.
+// `resume` restarts handed-over agent sessions on this core's own tmux; it needs a team (a share
+// hands sessions over only to a server that hosts one).
import net from 'node:net'
import path from 'node:path'
import { chmodSync, lstatSync, rmSync } from 'node:fs'
@@ -20,6 +22,7 @@ import { loadHostKey } from './host-key'
import { publicKeyFromB64, publicKeyToB64 } from './e2ee'
import { ADMIN_ERROR_CODE_RE, adminErrorCode } from './admin-error'
import { runBootstrap } from './team-bootstrap'
+import { parseResumeSessions, type ResumeEntry, type ResumeResult } from '../../shared/share-team'
import type {
HostedInfo,
HostedRotateResult,
@@ -40,6 +43,7 @@ export type AdminRequest =
| { cmd: 'share'; projectId: string; on: boolean }
| { cmd: 'rotate-key' }
| { cmd: 'bootstrap'; ownerKey: string; ownerLabel: string; adoptCwd: string }
+ | { cmd: 'resume'; projectId: string; sessions: ResumeEntry[] }
export type AdminReply = { ok: true; result: unknown } | { ok: false; error: string; code?: string }
/** A request refused with a stable code (`parseAdminRequest`), so a remote caller can branch on it. */
export interface AdminRefusal {
@@ -52,6 +56,8 @@ export interface AdminRefusal {
export interface TeamAdminOps {
/** Adopt a folder into this core's workspace (saved before it returns) — `team bootstrap`. */
adoptFolder?(cwd: string): Promise<AdoptFolderResult>
+ /** Restart handed-over agent sessions on this core's own tmux — `team resume`. */
+ resume?(req: { projectId: string; sessions: ResumeEntry[] }): Promise<ResumeResult>
}
/** `init`'s answer. The address and join code are present only when hosting is running. */
@@ -242,6 +248,14 @@ export function parseAdminRequest(raw: unknown): AdminRequest | string | AdminRe
if (cwdProblem) return { refused: cwdProblem, code: 'E_BAD_CWD' }
return { cmd: 'bootstrap', ownerKey: o.ownerKey, ownerLabel: o.ownerLabel, adoptCwd: o.adoptCwd }
}
+ case 'resume': {
+ if (typeof o.projectId !== 'string') return { refused: 'bad request: resume needs a projectId string', code: 'E_BAD_REQUEST' }
+ const idProblem = projectIdProblem(o.projectId)
+ if (idProblem) return { refused: idProblem, code: 'E_BAD_REQUEST' }
+ const sessions = parseResumeSessions(o.sessions)
+ if (typeof sessions === 'string') return { refused: sessions, code: 'E_BAD_REQUEST' }
+ return { cmd: 'resume', projectId: o.projectId, sessions }
+ }
default:
return `bad request: unknown command ${JSON.stringify(typeof o.cmd === 'string' ? o.cmd.slice(0, 40) : o.cmd)}`
}
@@ -345,6 +359,8 @@ async function handle(
const adopt = ops.adoptFolder
return ok(await runBootstrap({ svc, adoptFolder: (cwd) => adopt(cwd), closing }, req))
}
+ case 'resume':
+ return ops.resume ? ok(await ops.resume(req)) : fail('This server cannot resume sessions.', 'E_UNSUPPORTED')
}
}
diff --git a/src/core/relay/team-resume.test.ts b/src/core/relay/team-resume.test.ts
new file mode 100644
index 000000000..c470e6ab1
--- /dev/null
+++ b/src/core/relay/team-resume.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect } from 'vitest'
+import { runResume, RESUME_CONCURRENCY, type ResumeDeps } from './team-resume'
+import type { CanvasNodeState, Project } from '../../shared/types'
+
+const node = (o: Partial<CanvasNodeState>): CanvasNodeState =>
+ ({ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, title: 'T', color: '#fff', ...o }) as CanvasNodeState
+const PROJECT = {
+ id: 'project-1', name: 'p', color: '#fff', cwd: '/home/u/p', viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [
+ node({ id: 'term-a', agentId: 'claude', cwd: '/home/u/p' }),
+ node({ id: 'term-b', agentId: 'codex' }),
+ node({ id: 'term-c', agentId: 'gemini' }),
+ node({ id: 'term-acct', agentId: 'claude', accountId: 'acct-1' }),
+ node({ id: 'term-plain' }),
+ node({ id: 'sticky-1', kind: 'sticky' })
+ ]
+} as unknown as Project
+
+function deps(o: { verdict?: Record<string, 'present' | 'absent' | 'unknown'>; launch?: 'delivered' | 'failed' } = {}) {
+ const launched: Array<{ nodeId: string; command: string }> = []
+ let inFlight = 0
+ let peak = 0
+ const d: ResumeDeps = {
+ loadProject: async (id) => (id === 'project-1' ? PROJECT : null),
+ sessionVerdict: async (nodeId) => o.verdict?.[nodeId] ?? 'absent',
+ command: async (entry) => `${entry.agentId} --resume ${entry.sessionId}${entry.permissionMode ? ` <${entry.permissionMode}>` : ''}`,
+ launch: async (_p, n, command) => {
+ inFlight++
+ peak = Math.max(peak, inFlight)
+ await new Promise((r) => setTimeout(r, 5))
+ inFlight--
+ launched.push({ nodeId: n.id, command })
+ return o.launch === 'failed' ? { outcome: 'failed', reason: 'no-shell' } : { outcome: 'delivered', fresh: true }
+ }
+ }
+ return { d, launched, peak: () => peak }
+}
+const E = (nodeId: string, agentId = 'claude', sessionId = 'sess-1', permissionMode?: string) => ({ nodeId, agentId, sessionId, ...(permissionMode ? { permissionMode } : {}) })
+
+describe('runResume', () => {
+ it('launches a valid entry with the composed command and reports resumed', async () => {
+ const { d, launched } = deps()
+ expect(await runResume(d, { projectId: 'project-1', sessions: [E('term-a', 'claude', 's1', 'auto')] })).toEqual({
+ results: [{ nodeId: 'term-a', status: 'resumed' }]
+ })
+ expect(launched).toEqual([{ nodeId: 'term-a', command: 'claude --resume s1 <auto>' }])
+ })
+ it('an unknown permission mode is dropped (bare command), never forwarded', async () => {
+ const { d, launched } = deps()
+ await runResume(d, { projectId: 'project-1', sessions: [E('term-a', 'claude', 's1', 'constructor')] })
+ expect(launched[0].command).toBe('claude --resume s1')
+ })
+ it('a live session answers already-running and is not launched again', async () => {
+ const { d, launched } = deps({ verdict: { 'term-a': 'present' } })
+ expect((await runResume(d, { projectId: 'project-1', sessions: [E('term-a')] })).results[0].status).toBe('already-running')
+ expect(launched).toEqual([])
+ })
+ it('an unknown verdict is refused (never a launch on uncertainty)', async () => {
+ const { d, launched } = deps({ verdict: { 'term-a': 'unknown' } })
+ expect((await runResume(d, { projectId: 'project-1', sessions: [E('term-a')] })).results[0]).toMatchObject({ status: 'refused' })
+ expect(launched).toEqual([])
+ })
+ it('refuses, per entry: no such node, a sticky, a non-resumable agent, a mismatched agent, a managed account, an unsafe session id, a duplicate', async () => {
+ const { d, launched } = deps()
+ const r = await runResume(d, {
+ projectId: 'project-1',
+ sessions: [
+ E('term-zzz'), E('sticky-1'), E('term-plain', 'mycustom'), E('term-c', 'claude'),
+ E('term-acct'), E('term-a', 'claude', '../../etc'), E('term-b', 'codex', 's2'), E('term-b', 'codex', 's3')
+ ]
+ })
+ expect(r.results.map((x) => x.status)).toEqual(['refused', 'refused', 'refused', 'refused', 'refused', 'refused', 'resumed', 'refused'])
+ expect(r.results.every((x) => x.status !== 'refused' || typeof x.reason === 'string')).toBe(true)
+ expect(launched.map((l) => l.nodeId)).toEqual(['term-b'])
+ })
+ it('a failed launch is refused with its reason', async () => {
+ const { d } = deps({ launch: 'failed' })
+ expect((await runResume(d, { projectId: 'project-1', sessions: [E('term-a')] })).results[0]).toMatchObject({ status: 'refused', reason: expect.stringMatching(/no-shell/) })
+ })
+ it('an unknown project is a coded refusal of the whole request', async () => {
+ const { d } = deps()
+ await expect(runResume(d, { projectId: 'nope', sessions: [] })).rejects.toMatchObject({ code: 'E_BAD_REQUEST' })
+ })
+ it(`never runs more than ${RESUME_CONCURRENCY} launches at once, and keeps result order`, async () => {
+ const nodes = Array.from({ length: 10 }, (_, i) => node({ id: `t${i}`, agentId: 'claude' }))
+ const { d, peak } = deps()
+ d.loadProject = async () => ({ ...PROJECT, nodes }) as Project
+ const r = await runResume(d, { projectId: 'project-1', sessions: nodes.map((n) => E(n.id)) })
+ expect(peak()).toBeLessThanOrEqual(RESUME_CONCURRENCY)
+ expect(r.results.map((x) => x.nodeId)).toEqual(nodes.map((n) => n.id))
+ })
+})
diff --git a/src/core/relay/team-resume.ts b/src/core/relay/team-resume.ts
new file mode 100644
index 000000000..3e07d3fa2
--- /dev/null
+++ b/src/core/relay/team-resume.ts
@@ -0,0 +1,101 @@
+// `team resume`: restart the agents a desktop handed over, on THIS core's tmux socket, with their
+// conversations resumed (`claude --resume <id>`, …). Called by "Share with team" only after the
+// desktop VERIFIED each node's old `nodeterm-rmt` session is gone — two processes on one
+// conversation would interleave its transcript — and re-checked here per node with the EXACT tmux
+// target (a bare `has-session` prefix-matches, so `nt-x-1` would answer for `nt-x-12`).
+// Idempotent: a session that already exists is `already-running`, so a re-run never doubles.
+import type { CanvasNodeState, Project } from '../../shared/types'
+import type { HeadlessLaunchResult } from '../../shared/headless-launch'
+import { RESUMABLE_AGENTS, isPermissionMode, type AgentPermissionMode } from '../../shared/agents/config'
+import { SAFE_SESSION_ID } from '../../shared/session-id'
+import { isSafeNodeId } from '../../shared/safe-id'
+import type { ResumeEntry, ResumeResult, ResumeResultEntry } from '../../shared/share-team'
+import { codedError } from './admin-error'
+
+/** At most this many agent launches run at once: each one settles a fresh shell and types a line. */
+export const RESUME_CONCURRENCY = 4
+
+/** An entry that passed every per-entry check; `permissionMode` is present only when it is a mode. */
+export interface ValidResumeEntry {
+ nodeId: string
+ agentId: string
+ sessionId: string
+ permissionMode?: AgentPermissionMode
+}
+export interface ResumeDeps {
+ loadProject(projectId: string): Promise<Project | null>
+ sessionVerdict(nodeId: string): Promise<'present' | 'absent' | 'unknown'>
+ /** The command line that resumes this entry on this host (null = cannot be composed). */
+ command(entry: ValidResumeEntry, node: CanvasNodeState, project: Project): Promise<string | null>
+ launch(project: Project, node: CanvasNodeState, command: string): Promise<HeadlessLaunchResult>
+}
+
+const isTerminal = (n: CanvasNodeState): boolean => n.kind === undefined || n.kind === 'terminal'
+
+/**
+ * Resume every listed session that may be resumed here, at most RESUME_CONCURRENCY at a time, and
+ * answer one result per entry in request order. Every refusal is per entry and carries its reason;
+ * only an unknown project refuses the whole request. A node listed twice is refused after its first
+ * occurrence, so one request can never start two agents on one node.
+ */
+export async function runResume(
+ deps: ResumeDeps,
+ req: { projectId: string; sessions: ResumeEntry[] }
+): Promise<ResumeResult> {
+ const project = await deps.loadProject(req.projectId)
+ if (!project) throw codedError('E_BAD_REQUEST', `There is no project ${req.projectId} on this server.`)
+ const seen = new Set<string>()
+ const jobs: Array<() => Promise<ResumeResultEntry>> = req.sessions.map((e) => {
+ const refuse = (reason: string) => async (): Promise<ResumeResultEntry> => ({ nodeId: e.nodeId, status: 'refused', reason })
+ if (seen.has(e.nodeId)) return refuse('listed twice')
+ seen.add(e.nodeId)
+ if (!isSafeNodeId(e.nodeId)) return refuse('not a valid node id')
+ const node = project.nodes.find((n) => n.id === e.nodeId)
+ if (!node || !isTerminal(node)) return refuse('not a terminal node of this project')
+ if (!(RESUMABLE_AGENTS as readonly string[]).includes(e.agentId)) return refuse('this agent cannot be resumed')
+ if (node.agentId !== e.agentId) return refuse('the node runs a different agent')
+ // A managed account's config dir lives on the machine that added it; this core cannot know it.
+ if (node.accountId) return refuse('runs under a managed account; resume it by hand')
+ // The id ends up on a shell command line: re-validated here, never trusted by its type.
+ if (!SAFE_SESSION_ID.test(e.sessionId)) return refuse('not a valid session id')
+ // An unrecognized mode is dropped (the bare command), never forwarded to the command line.
+ const entry: ValidResumeEntry = {
+ nodeId: e.nodeId,
+ agentId: e.agentId,
+ sessionId: e.sessionId,
+ ...(isPermissionMode(e.permissionMode) ? { permissionMode: e.permissionMode } : {})
+ }
+ return async (): Promise<ResumeResultEntry> => {
+ const verdict = await deps.sessionVerdict(e.nodeId)
+ if (verdict === 'present') return { nodeId: e.nodeId, status: 'already-running' }
+ // Never a launch on uncertainty: a session we could not see may still be running the agent.
+ if (verdict === 'unknown') {
+ return { nodeId: e.nodeId, status: 'refused', reason: 'could not check whether its session is running' }
+ }
+ const command = await deps.command(entry, node, project)
+ if (!command) return { nodeId: e.nodeId, status: 'refused', reason: 'no resume command for this agent' }
+ const r = await deps.launch(project, node, command)
+ return r.outcome === 'delivered'
+ ? { nodeId: e.nodeId, status: 'resumed' }
+ : { nodeId: e.nodeId, status: 'refused', reason: `launch failed (${r.reason})` }
+ }
+ })
+ const results: ResumeResultEntry[] = new Array(jobs.length)
+ let next = 0
+ const worker = async (): Promise<void> => {
+ while (next < jobs.length) {
+ const i = next++
+ try {
+ results[i] = await jobs[i]()
+ } catch (err) {
+ results[i] = {
+ nodeId: req.sessions[i].nodeId,
+ status: 'refused',
+ reason: err instanceof Error ? err.message : String(err)
+ }
+ }
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(RESUME_CONCURRENCY, jobs.length) }, worker))
+ return { results }
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index 8eeadf2c4..a6ef541e8 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -97,7 +97,9 @@ import { createMemoryPressureMonitor } from '../core/memory-pressure'
import { createPtyPressureMonitor } from '../core/pty-pressure'
import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
import { codexCliCaps } from '../core/codex-cli'
+import { codexIdentityCaps } from '../core/codex-identity-caps'
import type { CodexCliCaps } from '../shared/types'
+import { UNKNOWN_CODEX_CLI_CAPS } from '../shared/types'
import { claudeConfigDirFor, registerClaudeAccountsSource } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
import { initCanvasSync, publishCanvasMutation, setReflectedListener } from '../core/canvas-sync'
@@ -117,6 +119,11 @@ import { isPremium, getStoredEntitlement } from '../core/license'
import { getDeviceId } from '../core/device-id'
import { createHostedService } from '../core/relay/hosted-service'
import { startTeamAdmin } from '../core/relay/team-admin'
+import { runResume } from '../core/relay/team-resume'
+import { launchHeadless } from '../core/headless-launch'
+import { HEADLESS_COLS, HEADLESS_ROWS, localNodePtyOptions } from '../shared/node-pty-options'
+import { assembleResumeCommand } from '../shared/agents/launch'
+import { gatePermissionMode, type AgentId, type BuiltinAgentId } from '../shared/agents/config'
import {
createWatchLinkService,
registerWatchLinkIpc,
@@ -988,7 +995,51 @@ export async function startServer(
// `team bootstrap`: adopt the folder into THIS core's workspace (saved before it is shared, so
// the canvas authority can read it). The server runs as the SSH login user, so its home is the
// one an SSH project's `~` cwds meant.
- adoptFolder: (cwd) => workspaceStore.adoptFolder(cwd, { home: os.homedir() })
+ adoptFolder: (cwd) => workspaceStore.adoptFolder(cwd, { home: os.homedir() }),
+ // `team resume`: restart a handed-over agent on THIS core (its hook env reports to this core,
+ // so every teammate sees its status). Same launch primitive and the same release rule as the
+ // desktop's headless start: persistent tmux required, the synthetic client released after.
+ resume: (req) =>
+ runResume(
+ {
+ loadProject: async (id) => (await workspaceStore.load({ sideline: false })).projects.find((p) => p.id === id) ?? null,
+ sessionVerdict: (nodeId) => ptyManager.sessionVerdict(nodeId),
+ command: async (entry, node) => {
+ const settings = settingsStore.get()
+ const permissionMode =
+ entry.permissionMode && entry.agentId === 'claude'
+ ? gatePermissionMode(entry.permissionMode, (await claudeCliCaps().catch(() => null))?.autoPermissionMode === true)
+ : entry.permissionMode
+ const codexCaps = entry.agentId === 'codex' ? await codexCliCaps().catch(() => UNKNOWN_CODEX_CLI_CAPS) : UNKNOWN_CODEX_CLI_CAPS
+ const sharedIdentity = entry.agentId === 'codex' ? await codexIdentityCaps().then((c) => c.shared).catch(() => false) : false
+ return assembleResumeCommand(
+ {
+ agentId: entry.agentId as AgentId,
+ sessionId: entry.sessionId,
+ permissionMode,
+ model: node.agentModel,
+ launchCmdOverride: settings.agentLaunchCommands?.[entry.agentId as BuiltinAgentId],
+ sharedIdentity,
+ approvalCaps: { codexApprovalValues: codexCaps.approvalValues, codexNoDaemon: codexCaps.noDaemon ?? null }
+ },
+ process.env
+ ).command
+ },
+ launch: (project, node, command) =>
+ launchHeadless(
+ {
+ persistentSpawnAvailable: () => ptyManager.persistentSpawnAvailable(),
+ createHeadless: (o) => ptyManager.createHeadless(o),
+ paneCommand: (k) => ptyManager.paneCommand(k),
+ writeHeadless: (k, d) => ptyManager.writeHeadless(k, d),
+ onOutput: (k, cb) => ptyManager.onOutput(k, cb),
+ releaseHeadless: (k) => ptyManager.releaseHeadless(k)
+ },
+ { ptyOptions: localNodePtyOptions(project, node, { cols: HEADLESS_COLS, rows: HEADLESS_ROWS }), command, release: true, requirePersistent: true }
+ )
+ },
+ req
+ )
}).catch((err: unknown) => {
if ((err as { code?: unknown } | null)?.code === 'E_ADMIN_SOCKET_BUSY') otherServerHere = true
console.error(`[hosted-team] team admin socket disabled: ${err instanceof Error ? err.message : String(err)}`)
diff --git a/src/server/team-cli.test.ts b/src/server/team-cli.test.ts
index 0deb97a79..c41ef7a1c 100644
--- a/src/server/team-cli.test.ts
+++ b/src/server/team-cli.test.ts
@@ -3,7 +3,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { parseTeamArgv, runTeamCli, describeStatus, teamArgv, TEAM_USAGE } from './team-cli'
-import { startTeamAdmin, adminSocketPath, type AdminStatusResult } from '../core/relay/team-admin'
+import { startTeamAdmin, adminSocketPath, type AdminStatusResult, type TeamAdminOps } from '../core/relay/team-admin'
import { genKeyPair, publicKeyToB64 } from '../core/relay/e2ee'
import type { HostedService, HostedStatus } from '../core/relay/hosted-service'
import { POP_REFUSED_MESSAGE } from '../core/relay/relay-pop'
@@ -77,6 +77,14 @@ describe('team argv', () => {
it('`team --help` lists bootstrap at the row start a remote probe greps for', () => {
expect(TEAM_USAGE).toMatch(/^ {2}bootstrap /m)
})
+
+ it('resume needs --project (checked) and takes its sessions from stdin, not argv', () => {
+ expect(parseTeamArgv(['resume', '--project', 'p1', '--json'])).toEqual({ cmd: 'resume', projectId: 'p1', sessions: [] })
+ expect(parseTeamArgv(['resume'])).toEqual({ error: expect.stringMatching(/needs --project/) })
+ expect(parseTeamArgv(['resume', '--project', 'x'.repeat(129)])).toEqual({ error: expect.stringMatching(/128/) })
+ expect(parseTeamArgv(['resume', '--project', 'p1', 'extra'])).toEqual({ error: expect.stringMatching(/takes no arguments/) })
+ expect(TEAM_USAGE).toMatch(/^ {2}resume --project <id>/m)
+ })
})
describe('teamArgv (main.cjs dispatch)', () => {
@@ -252,22 +260,30 @@ function fake(o: { running?: boolean; rotate?: string } = {}): { svc: HostedServ
return { svc, calls }
}
-async function served(o: Parameters<typeof fake>[0] = {}, withTeam = true): Promise<{ dataDir: string; calls: string[] }> {
+async function served(
+ o: Parameters<typeof fake>[0] = {},
+ withTeam = true,
+ ops: TeamAdminOps = {}
+): Promise<{ dataDir: string; calls: string[] }> {
const dataDir = tmp()
if (withTeam) {
fs.mkdirSync(path.join(dataDir, 'relay'), { recursive: true, mode: 0o700 })
fs.writeFileSync(path.join(dataDir, 'relay', 'team.json'), JSON.stringify({ v: 1, peers: [], sharedProjects: [] }))
}
const f = fake(o)
- const admin = await startTeamAdmin(dataDir, f.svc)
+ const admin = await startTeamAdmin(dataDir, f.svc, ops)
closers.push(() => admin.close())
return { dataDir, calls: f.calls }
}
-async function run(argv: string[], dataDir: string): Promise<{ code: number; out: string; err: string }> {
+async function run(
+ argv: string[],
+ dataDir: string,
+ readStdin?: () => Promise<string>
+): Promise<{ code: number; out: string; err: string }> {
const out: string[] = []
const err: string[] = []
- const code = await runTeamCli(argv, dataDir, (s) => out.push(s), (s) => err.push(s))
+ const code = await runTeamCli(argv, dataDir, (s) => out.push(s), (s) => err.push(s), readStdin)
return { code, out: out.join('\n'), err: err.join('\n') }
}
@@ -446,6 +462,41 @@ describe.skipIf(process.platform === 'win32')('runTeamCli over the admin socket
expect(JSON.parse(r.out)).toEqual({ ok: false, error: expect.stringMatching(/cannot adopt/), code: 'E_UNSUPPORTED' })
})
+ it('resume reads the session list from stdin and prints the result as JSON', async () => {
+ const asked: unknown[] = []
+ const { dataDir } = await served({ running: true }, true, {
+ resume: async (req) => {
+ asked.push(req)
+ return { results: [{ nodeId: 'n', status: 'resumed' }] }
+ }
+ })
+ const sessions = [{ nodeId: 'n', agentId: 'claude', sessionId: 's' }]
+ const r = await run(['resume', '--project', 'p', '--json'], dataDir, async () => JSON.stringify(sessions))
+ expect(r.code).toBe(0)
+ expect(JSON.parse(r.out)).toEqual({ results: [{ nodeId: 'n', status: 'resumed' }] })
+ expect(asked).toEqual([{ cmd: 'resume', projectId: 'p', sessions }])
+ const human = await run(['resume', '--project', 'p'], dataDir, async () => JSON.stringify(sessions))
+ expect(human.code).toBe(0)
+ expect(human.out).toBe(' n resumed')
+ })
+
+ it('resume refuses stdin that is not a JSON list of sessions before reaching the server', async () => {
+ let called = false
+ const { dataDir } = await served({ running: true }, true, {
+ resume: async () => {
+ called = true
+ return { results: [] }
+ }
+ })
+ const notJson = await run(['resume', '--project', 'p', '--json'], dataDir, async () => 'not json')
+ expect(notJson.code).toBe(2)
+ expect(notJson.err).toMatch(/JSON list of sessions/)
+ const notList = await run(['resume', '--project', 'p'], dataDir, async () => '{}')
+ expect(notList.code).toBe(2)
+ expect(notList.err).toMatch(/JSON list of sessions/)
+ expect(called).toBe(false)
+ })
+
it('a refused --json verb prints {"ok":false,…} on stdout and the human line on stderr', async () => {
const dataDir = tmp()
fs.mkdirSync(path.join(dataDir, 'relay'), { recursive: true, mode: 0o700 })
diff --git a/src/server/team-cli.ts b/src/server/team-cli.ts
index e8a5aa931..f798e3bf0 100644
--- a/src/server/team-cli.ts
+++ b/src/server/team-cli.ts
@@ -19,6 +19,7 @@ import {
type AdminStatusResult
} from '../core/relay/team-admin'
import { POP_REFUSED_MESSAGE } from '../core/relay/relay-pop'
+import { parseResumeSessions } from '../shared/share-team'
// One rule for what never reaches the admin's terminal: the same characters a label may not
// contain (C0/C1 controls, DEL, and the text-direction controls). Server-supplied strings can carry
@@ -45,7 +46,8 @@ const USAGE_ROWS: Array<[string, string]> = [
['unshare <projectId>', 'stop showing it'],
['info [--json]', "this host's team address and join code"],
['status [--json]', 'hosting state, members and join requests'],
- ['rotate-key', 'replace the host key (every teammate needs a new join code)']
+ ['rotate-key', 'replace the host key (every teammate needs a new join code)'],
+ ['resume --project <id> [--json] < sessions.json', 'restart handed-over agent sessions (a JSON list on stdin)']
]
const USAGE_WIDTH = Math.max(...USAGE_ROWS.map(([cmd]) => cmd.length))
export const TEAM_USAGE = [
@@ -67,7 +69,8 @@ const COMMANDS: Record<string, CommandSpec> = {
unshare: { positionals: 1, flags: {} },
info: { positionals: 0, flags: { json: 'bool' } },
status: { positionals: 0, flags: { json: 'bool' } },
- 'rotate-key': { positionals: 0, flags: {} }
+ 'rotate-key': { positionals: 0, flags: {} },
+ resume: { positionals: 0, flags: { project: 'value', json: 'bool' } }
}
const usageError = (why: string): { error: string } => ({ error: `${why}\n${TEAM_USAGE}` })
@@ -137,6 +140,14 @@ export function parseTeamArgv(argv: string[]): AdminRequest | { error: string }
const problem = projectIdProblem(positionals[0])
return problem ? { error: problem } : { cmd: 'share', projectId: positionals[0], on: cmd === 'share' }
}
+ case 'resume': {
+ // The session list is not argv: it arrives on stdin (runTeamCli fills `sessions`), so a long
+ // list never meets ARG_MAX and never shows up in `ps`.
+ const projectId = typeof flags.project === 'string' ? flags.project : ''
+ if (!projectId) return usageError('resume needs --project <id>')
+ const problem = projectIdProblem(projectId)
+ return problem ? { error: problem } : { cmd: 'resume', projectId, sessions: [] }
+ }
}
return usageError(`unknown command "${clean(cmd)}"`)
}
@@ -288,7 +299,7 @@ export function describeStatus(result: AdminStatusResult): string[] {
/** Render a successful reply. The exit code is 1 when the command did its part but the outcome it
* exists for did not happen (hosting did not start, there is no address yet). Only `info`,
- * `status` and `bootstrap` take `--json`. */
+ * `status`, `bootstrap` and `resume` take `--json`. */
function render(req: AdminRequest, result: unknown, json: boolean): { lines: string[]; code: number } {
switch (req.cmd) {
case 'init': {
@@ -345,6 +356,16 @@ function render(req: AdminRequest, result: unknown, json: boolean): { lines: str
]
return { lines, code: 0 }
}
+ case 'resume': {
+ if (json) return { lines: [safeJson(result)], code: 0 }
+ const rows = Array.isArray(obj(result).results) ? (obj(result).results as unknown[]).map(obj) : []
+ const lines = rows.map(
+ (r) =>
+ ` ${str(r.nodeId, '?')} ${r.status === 'already-running' ? 'already running' : str(r.status, '?')}` +
+ (typeof r.reason === 'string' ? ` (${str(r.reason)})` : '')
+ )
+ return { lines: lines.length ? lines : ['No sessions to resume.'], code: 0 }
+ }
case 'rotate-key': {
const r = obj(result) as Partial<AdminRotateResult>
if (r.result === 'not-running') {
@@ -370,11 +391,32 @@ function render(req: AdminRequest, result: unknown, json: boolean): { lines: str
}
}
+/** The longest stdin `team resume` reads: the admin socket's request cap, less its envelope. */
+const RESUME_STDIN_MAX = 60 * 1024
+
+function readProcessStdin(): Promise<string> {
+ if (process.stdin.isTTY) return Promise.reject(new Error('pipe the session list on stdin'))
+ return new Promise((resolve, reject) => {
+ let buf = ''
+ process.stdin.setEncoding('utf8')
+ process.stdin.on('data', (d: string) => {
+ buf += d
+ if (buf.length > RESUME_STDIN_MAX) {
+ process.stdin.destroy()
+ reject(new Error(`the session list is larger than ${RESUME_STDIN_MAX} bytes`))
+ }
+ })
+ process.stdin.on('end', () => resolve(buf))
+ process.stdin.on('error', reject)
+ })
+}
+
export async function runTeamCli(
argv: string[],
dataDir: string,
out: (s: string) => void,
- err: (s: string) => void = out
+ err: (s: string) => void = out,
+ readStdin: () => Promise<string> = readProcessStdin
): Promise<number> {
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h' || argv[0] === 'help')) {
out(TEAM_USAGE)
@@ -390,6 +432,21 @@ export async function runTeamCli(
err(req.error)
return 2
}
+ if (req.cmd === 'resume') {
+ let raw: unknown
+ try {
+ raw = JSON.parse(await readStdin())
+ } catch (e) {
+ err(`team resume reads a JSON list of sessions on stdin: ${clean(e instanceof Error ? e.message : String(e))}`)
+ return 2
+ }
+ const sessions = parseResumeSessions(raw)
+ if (typeof sessions === 'string') {
+ err(clean(sessions))
+ return 2
+ }
+ req.sessions = sessions
+ }
const r = await callTeamAdmin(dd.dataDir ?? dataDir, req)
const json = dd.argv.includes('--json')
if (!r.ok) {
diff --git a/src/shared/share-team.test.ts b/src/shared/share-team.test.ts
new file mode 100644
index 000000000..b7775a8ac
--- /dev/null
+++ b/src/shared/share-team.test.ts
@@ -0,0 +1,18 @@
+import { describe, it, expect } from 'vitest'
+import { parseResumeSessions, RESUME_MAX_SESSIONS } from './share-team'
+
+describe('parseResumeSessions', () => {
+ it('accepts a list of entries and keeps only the known string fields', () => {
+ expect(parseResumeSessions([{ nodeId: 'term-1', agentId: 'claude', sessionId: 's-1', permissionMode: 'auto', extra: 1 }])).toEqual([
+ { nodeId: 'term-1', agentId: 'claude', sessionId: 's-1', permissionMode: 'auto' }
+ ])
+ })
+ it('refuses a non-array, a malformed entry, oversize fields and too many entries', () => {
+ expect(parseResumeSessions({})).toMatch(/list/)
+ expect(parseResumeSessions([{ nodeId: 'a' }])).toMatch(/entry 0/)
+ expect(parseResumeSessions([{ nodeId: 'a'.repeat(129), agentId: 'claude', sessionId: 's' }])).toMatch(/entry 0/)
+ expect(parseResumeSessions([{ nodeId: 'a', agentId: 'claude', sessionId: 's', permissionMode: 7 }])).toMatch(/entry 0/)
+ const many = Array.from({ length: RESUME_MAX_SESSIONS + 1 }, (_, i) => ({ nodeId: `n${i}`, agentId: 'claude', sessionId: 's' }))
+ expect(parseResumeSessions(many)).toMatch(/at most/)
+ })
+})
diff --git a/src/shared/share-team.ts b/src/shared/share-team.ts
index ce44bad98..11a19d6ca 100644
--- a/src/shared/share-team.ts
+++ b/src/shared/share-team.ts
@@ -1,5 +1,7 @@
// Wire shapes shared by the desktop's "Share with team" flow and the Server Edition's `team` admin
// verbs. Everything here crosses an ssh exec channel as JSON, so every reader is strict.
+import { NODE_ID_MAX } from './safe-id'
+import { SESSION_ID_MAX } from './session-id'
/** `team bootstrap --json`'s answer: the team's address, the project it adopted and shared, the
* join code, and what this call changed (every `created` flag false on a re-run). */
@@ -12,3 +14,58 @@ export interface BootstrapResult {
hosting: 'up' | 'starting'
created: { team: boolean; owner: boolean; project: boolean; share: boolean }
}
+
+/** One agent session `team resume` restarts: the node it belongs to, the agent it runs, and the
+ * conversation to resume. `permissionMode` is a request only; the server re-validates it. */
+export interface ResumeEntry {
+ nodeId: string
+ agentId: string
+ sessionId: string
+ permissionMode?: string
+}
+/** `already-running` is a success: the node's session exists, so nothing was started twice. */
+export type ResumeStatus = 'resumed' | 'already-running' | 'refused'
+export interface ResumeResultEntry {
+ nodeId: string
+ status: ResumeStatus
+ reason?: string
+}
+/** `team resume --json`'s answer: one result per requested session, in request order. */
+export interface ResumeResult {
+ results: ResumeResultEntry[]
+}
+/** The most sessions one resume request takes (a share handles at most this many terminals). */
+export const RESUME_MAX_SESSIONS = 200
+
+const boundedString = (v: unknown, max: number): v is string =>
+ typeof v === 'string' && v.length > 0 && v.length <= max
+
+/** Shape check for a resume list arriving from the wire or stdin. Returns the list, or why not.
+ * Only the known fields survive; every value is checked again where it is used. */
+export function parseResumeSessions(raw: unknown): ResumeEntry[] | string {
+ if (!Array.isArray(raw)) return 'The resume input must be a JSON list of sessions.'
+ if (raw.length > RESUME_MAX_SESSIONS) return `A resume request takes at most ${RESUME_MAX_SESSIONS} sessions.`
+ const out: ResumeEntry[] = []
+ for (let i = 0; i < raw.length; i++) {
+ const e = raw[i] as Record<string, unknown> | null
+ if (
+ !e ||
+ typeof e !== 'object' ||
+ !boundedString(e.nodeId, NODE_ID_MAX) ||
+ !boundedString(e.agentId, 64) ||
+ !boundedString(e.sessionId, SESSION_ID_MAX)
+ ) {
+ return `Resume entry ${i} needs nodeId, agentId and sessionId strings.`
+ }
+ if (e.permissionMode !== undefined && !boundedString(e.permissionMode, 32)) {
+ return `Resume entry ${i} has a bad permissionMode.`
+ }
+ out.push({
+ nodeId: e.nodeId,
+ agentId: e.agentId,
+ sessionId: e.sessionId,
+ ...(typeof e.permissionMode === 'string' ? { permissionMode: e.permissionMode } : {})
+ })
+ }
+ return out
+}