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(ssh): Share with team re-checks the canvas before it marks the project

review3c0e6b172cc5
diff --git a/CLAUDE.md b/CLAUDE.md
index 997629a3e..28f87b09a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8458,6 +8458,17 @@ invariants:
even when the kill or the join fails, because that would be a second writer. `team resume` re-asks
with the core's exact `sessionVerdict` (the folded `sessionExists` prefix-matches): present ⇒
`already-running`, unknown ⇒ refused, so a re-run never doubles an agent.
+- **What may be handed over is read twice, and only what the user confirmed may change nothing.**
+ Busy is `working`, `blocked` AND `waiting` (a Codex approval prompt and an open AskUserQuestion
+ are `waiting`); an agent only the status store knows (launched by hand) counts as busy
+ (`ShareNode.liveAgentId`) but is never resumed — resume stays on `node.agentId`, so a stale status
+ agent cannot make the server type `claude --resume`. A terminal attached to another host
+ (`otherHost`, `sshConnectionIdForProject`) refuses the share by title: its kill on the project's
+ host would read "gone" and leave it running elsewhere. The orchestrator re-reads the canvas
+ (`ShareDeps.canvas()`, which commits the live canvas first) right before the mark: a busy agent or
+ a changed terminal SET refuses with nothing changed, and the handover then uses that read. The
+ flush check compares EVERY node id of the project (notes, frames) with the host's file, read
+ again at the flush, because the server adopts that file.
- **Single writer: `handedOffTo` (machine-local, index entry only, never in `project.json`).** The
in-progress mark (`{at}`, no `hostId`) is set and SAVED before the mirror flush, not at the close:
a save between the flush and the close would otherwise queue a throttled mirror write that lands
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.md
index 88c0afda1..0a78fbc0a 100644
--- a/docs/hosted-team-relay.md
+++ b/docs/hosted-team-relay.md
@@ -271,10 +271,15 @@ starts on the server while its old session might still run: two processes on one
interleave its transcript. And once the server owns the project's file, this desktop never writes it
again.
-1. **Refusals first, before the host is touched.** An agent node that is working, or waiting on a
- permission prompt (hook state `working` or `blocked`), refuses the share: "Wait for these agents
- to finish (or stop them), then share again.", with the agents listed. More than 200 terminals is
- refused too.
+1. **Refusals first, before the host is touched.** An agent that is working, waiting on a
+ permission prompt, or holding a question or an approval nobody has answered (hook state
+ `working`, `blocked` or `waiting`; a Codex approval prompt and an open AskUserQuestion are
+ `waiting`, a finished turn is `done`) refuses the share: "Wait for these agents to finish (or
+ stop them), then share again.", with the agents listed. An agent launched by hand in a plain
+ terminal counts too (the status store knows it), though only a node created as an agent is ever
+ resumed. A terminal attached to another host than the project's refuses it, naming each one,
+ because the handover would "stop" it on the project's host (where it has no session) and leave it
+ running where it is. More than 200 terminals is refused too.
2. **Probe**, one generated command over the project's ControlMaster: the OS and the login, git and
curl, which unit runs nodeterm-server and with which binary, its version, whether it knows
`team bootstrap`, whether it answers, the real paths of the home directory and the project
@@ -289,13 +294,16 @@ again.
Enter does not stop a long install): no second probe, nothing saved, marked or closed, and the
result says "The install was cancelled, so nothing was shared. The host may keep a partly
installed nodeterm-server; the next install replaces it."
-5. **Save the canvas.**
+5. **Save the canvas, and read it again.** The install can take many minutes. If an agent became
+ busy meanwhile, or a terminal was added or removed, the share stops with nothing changed (the
+ busy refusal above, or "The canvas changed while preparing the share. Nothing was changed; share
+ again."). The rest of the handover works on this read.
6. **Mark the project handed off, in progress** (`handedOffTo` with no host yet), and save, so no
later save on this desktop mirrors the project to the host.
-7. **Flush the pending mirror write and read the host's `project.json` back.** Every terminal of the
- project must be in it, because that file is what the server adopts. If one is missing, the share
- stops: "The canvas on the host is not up to date (N terminals missing). Nothing was changed; try
- again in a moment."
+7. **Flush the pending mirror write and read the host's `project.json` back.** Every node of the
+ project, read again now (terminals, notes, frames), must be in it, because that file is what the
+ server adopts. If one is missing, the share stops: "The canvas on the host is not up to date (N
+ nodes missing). Nothing was changed; try again in a moment."
8. **Close the SSH project**, non-destructively: it moves to "Recently closed", and its tmux sessions
keep running.
9. **`team bootstrap`**, as the login user, with the folder's real path from main's own probe (the
@@ -379,7 +387,9 @@ teammate's, still compares the SAS.
| When | What the desktop says |
|---|---|
| The SSH connection is down | The menu item is disabled: "Connect this project first (its SSH connection is down)." |
-| An agent is working or blocked | "Wait for these agents to finish (or stop them), then share again.", with the agents listed |
+| An agent is working, blocked, or waiting on a question or an approval | "Wait for these agents to finish (or stop them), then share again.", with the agents listed |
+| A terminal runs on another host than the project's | "These terminals run on another host: <titles>. Close them or move them out of this project, then share again." |
+| A terminal was added or removed, or an agent became busy, while the share was being prepared | "The canvas changed while preparing the share. Nothing was changed; share again." (a busy agent gets the busy refusal) |
| More than 200 terminals | "This project has more than 200 terminals; Share with team handles at most that many." |
| The SSH login is root | "This SSH login is root. Share with team runs nodeterm-server as your own user, so log in to the project as a regular user and try again." |
| The host has a root (system) install | "This host runs nodeterm-server as a system service (root). Share with team needs a per-user install; see docs/hosted-team-relay.md." |
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 7fa82f689..223a0b62a 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -379,7 +379,7 @@ import { sessionPauseOffer, type SessionPauseOffer } from '../lib/sessionPause'
import { RemoteAccessDialog } from '../components/RemoteAccessDialog'
import { ShareTeamDialog } from '../components/ShareTeamDialog'
import { runShare, type ShareConfirmSummary, type ShareOutcome, type SharePhase } from '../lib/shareSshTeam'
-import { followSharedProject, shareProjectDeps, shareTerminals } from '../lib/shareTeamCanvas'
+import { followSharedProject, shareCanvas, shareProjectDeps } from '../lib/shareTeamCanvas'
import { handedOffWarning } from '../lib/handedOff'
import { SshProjectDialog } from '../components/SshProjectDialog'
import { SshPassphrasePrompt } from '../components/SshPassphrasePrompt'
@@ -16986,6 +16986,13 @@ export function Canvas() {
return runShare(
{
api: window.nodeTerminal.shareTeam,
+ // Read fresh each time (start, right before the mark, the flush check), committing the
+ // live canvas first so a node added since the last read is in it.
+ canvas: () => {
+ commitActiveToStore()
+ const p = useProjects.getState().getProject(projectId)
+ return shareCanvas(p?.nodes ?? [], useAgentStatus.getState().byId, { id: projectId, server: p?.ssh?.server })
+ },
confirm: ui.confirm,
phase: ui.phase,
...steps,
@@ -16996,7 +17003,6 @@ export function Canvas() {
projectName: project.name,
host: project.ssh.server.host,
user: project.ssh.server.user,
- terminals: shareTerminals(project.nodes, useAgentStatus.getState().byId),
permissionMode: resolvePermissionMode(project, useSettings.getState().settings)
}
)
diff --git a/src/renderer/lib/shareSshTeam.test.ts b/src/renderer/lib/shareSshTeam.test.ts
index 69d463bde..e2b69a7d0 100644
--- a/src/renderer/lib/shareSshTeam.test.ts
+++ b/src/renderer/lib/shareSshTeam.test.ts
@@ -6,16 +6,40 @@ import {
INSTALL_CANCELLED,
INSTALL_REPROBE_ATTEMPTS,
INSTALL_REPROBE_GAP_MS,
+ BUSY_REFUSAL,
+ CANVAS_CHANGED,
+ otherHostRefusal,
+ busyTerminals,
+ type ShareCanvas,
type ShareDeps,
- type ShareInput
+ type ShareInput,
+ type ShareNode
} from './shareSshTeam'
const READY = { ok: true, probe: { adoptCwd: '/home/alice/proj', teamExists: false } as never, plan: { kind: 'ready' }, paneCommands: { 'term-p': 'npm' } } as const
const BOOT = { ok: true, result: { hostId: 'H', projectId: 'project-9', projectName: 'proj', joinCode: 'nodeterm://join/CODE', hosting: 'up', created: { team: true, owner: true, project: true, share: true } } } as const
-function setup(o: Partial<Record<'probe' | 'flush' | 'bootstrap' | 'kill' | 'resume', unknown>> & { confirm?: boolean; install?: boolean } = {}) {
+const TERMS: ShareNode[] = [
+ { nodeId: 'term-a', title: 'Claude', agentId: 'claude', sessionId: 's-1', state: 'done' },
+ { nodeId: 'term-p', title: 'dev server' },
+ { nodeId: 'term-x', title: 'Work account', agentId: 'claude', sessionId: 's-2', accountId: 'acct' }
+]
+const canvasOf = (terminals: ShareNode[], extraNodeIds: string[] = []): ShareCanvas => ({
+ terminals,
+ nodeIds: [...terminals.map((n) => n.nodeId), ...extraNodeIds]
+})
+
+function setup(
+ o: Partial<Record<'probe' | 'flush' | 'bootstrap' | 'kill' | 'resume', unknown>> & {
+ confirm?: boolean
+ install?: boolean
+ terminals?: ShareNode[]
+ } = {}
+) {
const log: string[] = []
+ const terminals = o.terminals ?? TERMS
const deps: ShareDeps = {
+ canvas: () => canvasOf(terminals),
api: {
probe: async () => (log.push('probe'), (o.probe ?? READY) as never),
install: async () => (log.push('install'), { ok: true, exitCode: 0 }),
@@ -37,16 +61,9 @@ function setup(o: Partial<Record<'probe' | 'flush' | 'bootstrap' | 'kill' | 'res
}
return { deps, log }
}
-const INPUT: ShareInput = {
- projectId: 'ssh-1', projectName: 'proj', host: 'box', user: 'alice', permissionMode: 'auto',
- terminals: [
- { nodeId: 'term-a', title: 'Claude', agentId: 'claude', sessionId: 's-1', state: 'done' },
- { nodeId: 'term-p', title: 'dev server' },
- { nodeId: 'term-x', title: 'Work account', agentId: 'claude', sessionId: 's-2', accountId: 'acct' }
- ]
-}
+const INPUT: ShareInput = { projectId: 'ssh-1', projectName: 'proj', host: 'box', user: 'alice', permissionMode: 'auto' }
/** A second resumable agent, for the cases that need more than one node in the resume request. */
-const TERM_B: ShareInput['terminals'][number] = { nodeId: 'term-b', title: 'Codex', agentId: 'codex', sessionId: 's-3', state: 'done' }
+const TERM_B: ShareNode = { nodeId: 'term-b', title: 'Codex', agentId: 'codex', sessionId: 's-3', state: 'done' }
const FLUSH_WITH_B = { ok: true, nodeIds: ['term-a', 'term-p', 'term-x', 'term-b'] }
describe('runShare', () => {
@@ -67,27 +84,76 @@ describe('runShare', () => {
expect(log).not.toContain('restore')
})
it('refuses while an agent is working or blocked, before touching the host', async () => {
- const { deps, log } = setup()
- const out = await runShare(deps, { ...INPUT, terminals: [{ ...INPUT.terminals[0], state: 'working' }] })
+ const { deps, log } = setup({ terminals: [{ ...TERMS[0], state: 'working' }] })
+ const out = await runShare(deps, INPUT)
expect(out).toMatchObject({ kind: 'refused', busy: [{ nodeId: 'term-a' }] })
expect(log).toEqual([])
})
it('refuses a blocked agent too', async () => {
- const { deps, log } = setup()
- const out = await runShare(deps, { ...INPUT, terminals: [{ ...INPUT.terminals[0], state: 'blocked' }, INPUT.terminals[1]] })
+ const { deps, log } = setup({ terminals: [{ ...TERMS[0], state: 'blocked' }, TERMS[1]] })
+ const out = await runShare(deps, INPUT)
expect(out).toEqual({
kind: 'refused',
reason: 'Wait for these agents to finish (or stop them), then share again.',
- busy: [{ ...INPUT.terminals[0], state: 'blocked' }]
+ busy: [{ ...TERMS[0], state: 'blocked' }]
})
expect(log).toEqual([])
})
+ it('refuses an agent waiting on a question or an approval (a Codex prompt, an AskUserQuestion)', async () => {
+ const { deps, log } = setup({ terminals: [{ ...TERMS[0], state: 'waiting' }, TERMS[1]] })
+ expect(await runShare(deps, INPUT)).toEqual({ kind: 'refused', reason: BUSY_REFUSAL, busy: [{ ...TERMS[0], state: 'waiting' }] })
+ expect(log).toEqual([])
+ })
it('refuses more terminals than one share handles, before touching the host', async () => {
- const { deps, log } = setup()
const terminals = Array.from({ length: 201 }, (_, i) => ({ nodeId: `t-${i}`, title: `T${i}` }))
- expect(await runShare(deps, { ...INPUT, terminals })).toMatchObject({ kind: 'refused', reason: expect.stringContaining('more than 200') })
+ const { deps, log } = setup({ terminals })
+ expect(await runShare(deps, INPUT)).toMatchObject({ kind: 'refused', reason: expect.stringContaining('more than 200') })
+ expect(log).toEqual([])
+ })
+ it('refuses a terminal that runs on another host, naming it, before touching the host', async () => {
+ const { deps, log } = setup({ terminals: [...TERMS, { nodeId: 'term-o', title: 'prod logs', otherHost: true }] })
+ expect(await runShare(deps, INPUT)).toEqual({ kind: 'refused', reason: otherHostRefusal(['prod logs']) })
+ expect(otherHostRefusal(['prod logs', 'db'])).toBe(
+ 'These terminals run on another host: prod logs, db. Close them or move them out of this project, then share again.'
+ )
expect(log).toEqual([])
})
+ it('re-reads the canvas right before the mark: a turn that started during the install refuses, nothing changed', async () => {
+ const { deps, log } = setup()
+ let reads = 0
+ deps.canvas = () => (reads++ === 0 ? canvasOf(TERMS) : canvasOf([{ ...TERMS[0], state: 'working' }, TERMS[1], TERMS[2]]))
+ expect(await runShare(deps, INPUT)).toMatchObject({ kind: 'refused', reason: BUSY_REFUSAL, busy: [{ nodeId: 'term-a' }] })
+ expect(log).toContain('prepare')
+ expect(log.some((l) => /^(mark|flush|release|restore|bootstrap|kill)/.test(l))).toBe(false)
+ })
+ it('re-reads the canvas right before the mark: a terminal added (or removed) meanwhile refuses, nothing changed', async () => {
+ for (const later of [[...TERMS, { nodeId: 'term-new', title: 'new' }], TERMS.slice(0, 2)]) {
+ const { deps, log } = setup()
+ let reads = 0
+ deps.canvas = () => (reads++ === 0 ? canvasOf(TERMS) : canvasOf(later))
+ expect(await runShare(deps, INPUT)).toEqual({ kind: 'refused', reason: CANVAS_CHANGED })
+ expect(log.some((l) => /^(mark|flush|release|restore|bootstrap|kill)/.test(l))).toBe(false)
+ }
+ expect(CANVAS_CHANGED).toBe('The canvas changed while preparing the share. Nothing was changed; share again.')
+ })
+ it('resumes with the session id of the read right before the mark (a /clear during the install)', async () => {
+ const { deps, log } = setup()
+ const seen: string[] = []
+ let reads = 0
+ deps.canvas = () => (reads++ === 0 ? canvasOf(TERMS) : canvasOf([{ ...TERMS[0], sessionId: 's-new' }, TERMS[1], TERMS[2]]))
+ deps.api.resume = async (_p, _sid, sessions) => (seen.push(...sessions.map((e) => e.sessionId)), { ok: true, results: sessions.map((e) => ({ nodeId: e.nodeId, status: 'resumed' as const })) })
+ expect(await runShare(deps, INPUT)).toMatchObject({ kind: 'shared' })
+ expect(seen).toEqual(['s-new'])
+ expect(log).toContain('mark')
+ })
+ it('the flush check covers every node of the project, not only terminals', async () => {
+ const { deps, log } = setup()
+ deps.canvas = () => canvasOf(TERMS, ['sticky-1'])
+ const out = await runShare(deps, INPUT)
+ expect(out).toMatchObject({ kind: 'failed', step: 'releasing', error: expect.stringContaining('(1 node missing)') })
+ expect(log).not.toContain('release')
+ expect(log.indexOf('restore')).toBeGreaterThan(log.indexOf('flush'))
+ })
it('a probe failure fails at probing, and a refusing plan is a refusal; neither asks to confirm', async () => {
const failed = setup({ probe: { ok: false, error: 'not connected' } })
expect(await runShare(failed.deps, INPUT)).toEqual({ kind: 'failed', step: 'probing', error: 'not connected', reopened: false })
@@ -103,7 +169,7 @@ describe('runShare', () => {
it('a canvas missing on the host stops BEFORE release and clears the pending mark', async () => {
const { deps, log } = setup({ flush: { ok: true, nodeIds: ['term-a'] } })
const out = await runShare(deps, INPUT)
- expect(out).toMatchObject({ kind: 'failed', step: 'releasing', reopened: false, error: expect.stringContaining('2 terminals missing') })
+ expect(out).toMatchObject({ kind: 'failed', step: 'releasing', reopened: false, error: expect.stringContaining('2 nodes missing') })
expect(log).not.toContain('release')
expect(log).not.toContain('bootstrap')
expect(log.indexOf('restore')).toBeGreaterThan(log.indexOf('mark'))
@@ -176,7 +242,7 @@ describe('runShare', () => {
expect(await runShare(deps, INPUT)).toEqual({
kind: 'failed',
step: 'releasing',
- error: 'The canvas on the host is not up to date (1 terminal missing). Try again in a moment.',
+ error: 'The canvas on the host is not up to date (1 node missing). Try again in a moment.',
reopened: false,
restoreFailed: true
})
@@ -286,8 +352,8 @@ describe('runShare', () => {
expect(await runShare(deps, INPUT)).toMatchObject({ kind: 'shared', resumed: [{ nodeId: 'term-a' }] })
})
it('a failed resume reply puts every sent node in notResumed with that error', async () => {
- const { deps } = setup({ flush: FLUSH_WITH_B, resume: { ok: false, error: 'server busy' } })
- const out = await runShare(deps, { ...INPUT, terminals: [...INPUT.terminals, TERM_B] })
+ const { deps } = setup({ flush: FLUSH_WITH_B, resume: { ok: false, error: 'server busy' }, terminals: [...TERMS, TERM_B] })
+ const out = await runShare(deps, INPUT)
expect(out).toMatchObject({
kind: 'shared',
resumed: [],
@@ -299,8 +365,8 @@ describe('runShare', () => {
})
})
it('a node the resume reply leaves out is reported as unanswered, not resumed', async () => {
- const { deps } = setup({ flush: FLUSH_WITH_B, resume: { ok: true, results: [{ nodeId: 'term-a', status: 'resumed' }] } })
- const out = await runShare(deps, { ...INPUT, terminals: [...INPUT.terminals, TERM_B] })
+ const { deps } = setup({ flush: FLUSH_WITH_B, resume: { ok: true, results: [{ nodeId: 'term-a', status: 'resumed' }] }, terminals: [...TERMS, TERM_B] })
+ const out = await runShare(deps, INPUT)
expect(out).toMatchObject({ kind: 'shared', resumed: [{ nodeId: 'term-a' }] })
expect((out as { notResumed: unknown[] }).notResumed).toContainEqual({
node: expect.objectContaining({ nodeId: 'term-b' }),
@@ -395,6 +461,19 @@ describe('runShare', () => {
})
})
+describe('busyTerminals', () => {
+ it('working, blocked and waiting are busy; done and an unknown state are not', () => {
+ const at = (state: ShareNode['state']): ShareNode => ({ nodeId: 'a', title: 'A', agentId: 'codex', state })
+ expect(busyTerminals([at('working'), at('blocked'), at('waiting')])).toHaveLength(3)
+ expect(busyTerminals([at('done'), at(undefined)])).toEqual([])
+ })
+ it('an agent known only to the status store (launched by hand) counts as busy; a plain terminal never does', () => {
+ const hand: ShareNode = { nodeId: 'h', title: 'H', liveAgentId: 'claude', state: 'working' }
+ expect(busyTerminals([hand])).toEqual([hand])
+ expect(busyTerminals([{ nodeId: 'p', title: 'P', state: 'working' }])).toEqual([])
+ })
+})
+
describe('classifyTerminals', () => {
it('sorts agents into resumable / manual and plain terminals into stopping (only a non-shell command)', () => {
const r = classifyTerminals(
@@ -412,6 +491,15 @@ describe('classifyTerminals', () => {
expect(r.manual.map((m) => m.node.nodeId)).toEqual(['b', 'c', 'd'])
expect(r.stopping).toEqual([{ node: { nodeId: 'e', title: 'E' }, command: 'npm' }])
})
+ it('an agent known only to the status store is never resumed: its pane is a plain terminal that stops', () => {
+ // A stale status agent must never make the server type `claude --resume` into a node created
+ // as a plain terminal.
+ const hand: ShareNode = { nodeId: 'h', title: 'H', liveAgentId: 'claude', sessionId: 's1', state: 'done' }
+ const r = classifyTerminals([hand], { h: 'claude' })
+ expect(r.resumable).toEqual([])
+ expect(r.manual).toEqual([])
+ expect(r.stopping).toEqual([{ node: hand, command: 'claude' }])
+ })
})
it('securityNote is the exact sentence', () => {
diff --git a/src/renderer/lib/shareSshTeam.ts b/src/renderer/lib/shareSshTeam.ts
index e64e0b86f..7cb418757 100644
--- a/src/renderer/lib/shareSshTeam.ts
+++ b/src/renderer/lib/shareSshTeam.ts
@@ -35,17 +35,28 @@ import {
export interface ShareNode {
nodeId: string
title: string
+ /** The agent the node was created to run: the only one the server is asked to resume. */
agentId?: string
+ /** The agent the status store saw in this pane (a hand-launched one included). It decides only
+ * whether the pane is busy, never what is resumed. */
+ liveAgentId?: string
sessionId?: string
accountId?: string
state?: AgentState
+ /** A remote-tmux terminal on a different host than the project's (a host attachment). */
+ otherHost?: boolean
+}
+/** The project as the share reads it at one moment. */
+export interface ShareCanvas {
+ terminals: ShareNode[]
+ /** Every node id of the project (terminals, notes, frames…): what the host's file must hold. */
+ nodeIds: string[]
}
export interface ShareInput {
projectId: string
projectName: string
host: string
user: string
- terminals: ShareNode[]
permissionMode: AgentPermissionMode
}
export type SharePhase =
@@ -95,6 +106,9 @@ export type ShareOutcome =
}
export interface ShareDeps {
api: Pick<ShareTeamApi, 'probe' | 'install' | 'flushMirror' | 'bootstrap' | 'killSessions' | 'resume' | 'seedBookmark'>
+ /** The project as it is right now (read at the start, right before the mark, and at the flush): a
+ * long install leaves plenty of time for a turn to start or a node to be added. */
+ canvas(): ShareCanvas
confirm(summary: ShareConfirmSummary): Promise<boolean>
phase(p: SharePhase): void
/** Commit the live canvas and save, so the latest nodes are on their way to the host. */
@@ -112,12 +126,47 @@ export interface ShareDeps {
wait(ms: number): Promise<void>
}
-const BUSY_STATES = new Set<AgentState>(['working', 'blocked'])
+/** Mid-turn, or holding a question or an approval nobody has answered yet (a Codex approval prompt
+ * and an open AskUserQuestion are `waiting`); a finished turn is `done`. Ending such a session loses
+ * the turn or the answer. */
+const BUSY_STATES = new Set<AgentState>(['working', 'blocked', 'waiting'])
const isAgentResumable = (id: string | undefined): boolean =>
!!id && (RESUMABLE_AGENTS as readonly string[]).includes(id)
const errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e))
+export const BUSY_REFUSAL = 'Wait for these agents to finish (or stop them), then share again.'
+export const CANVAS_CHANGED = 'The canvas changed while preparing the share. Nothing was changed; share again.'
+export const otherHostRefusal = (titles: string[]): string =>
+ `These terminals run on another host: ${titles.join(', ')}. Close them or move them out of this project, then share again.`
+
+/** The agents whose session the handover must not end now. An agent known only to the status store
+ * (launched by hand in a plain terminal) counts too: its pane is as busy as any other. */
+export function busyTerminals(terminals: ShareNode[]): ShareNode[] {
+ return terminals.filter((n) => (n.agentId || n.liveAgentId) && n.state !== undefined && BUSY_STATES.has(n.state))
+}
+
+/** The refusals the canvas alone decides. A terminal on another host would be "killed" on the
+ * project's host (where it has no session, so it reads as gone) and left running where it is. */
+function canvasRefusal(terminals: ShareNode[]): Extract<ShareOutcome, { kind: 'refused' }> | null {
+ const foreign = terminals.filter((n) => n.otherHost)
+ if (foreign.length) return { kind: 'refused', reason: otherHostRefusal(foreign.map((n) => n.title)) }
+ const busy = busyTerminals(terminals)
+ if (busy.length) return { kind: 'refused', reason: BUSY_REFUSAL, busy }
+ if (terminals.length > SHARE_MAX_TERMINALS) {
+ return {
+ kind: 'refused',
+ reason: `This project has more than ${SHARE_MAX_TERMINALS} terminals; Share with team handles at most that many.`
+ }
+ }
+ return null
+}
+
+const sameIds = (a: readonly string[], b: readonly string[]): boolean => {
+ const set = new Set(a)
+ return set.size === new Set(b).size && b.every((id) => set.has(id))
+}
+
/** How often the host is probed after an install that exited 0, and how far apart: the restarted
* service can take a moment before its admin socket answers `team status`. */
export const INSTALL_REPROBE_ATTEMPTS = 3
@@ -171,7 +220,7 @@ const BOOTSTRAP_MAY_HAVE_FINISHED =
export async function runShare(deps: ShareDeps, input: ShareInput): Promise<ShareOutcome> {
const { api } = deps
- const { projectId, terminals, host, user } = input
+ const { projectId, host, user } = input
const failed = (step: SharePhase, error: string, reopened: boolean, restoreFailed = false): ShareOutcome => ({
kind: 'failed',
step,
@@ -190,17 +239,10 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
}
// Refusals that need no host: checked before anything is asked of it.
- const busy = terminals.filter((n) => n.agentId && n.state && BUSY_STATES.has(n.state))
- if (busy.length) {
- return { kind: 'refused', reason: 'Wait for these agents to finish (or stop them), then share again.', busy }
- }
- if (terminals.length > SHARE_MAX_TERMINALS) {
- return {
- kind: 'refused',
- reason: `This project has more than ${SHARE_MAX_TERMINALS} terminals; Share with team handles at most that many.`
- }
- }
- const ids = terminals.map((n) => n.nodeId)
+ const start = deps.canvas()
+ const refusedAtStart = canvasRefusal(start.terminals)
+ if (refusedAtStart) return refusedAtStart
+ const ids = start.terminals.map((n) => n.nodeId)
phase('probing')
const probed = await call(() => api.probe(projectId, ids))
@@ -208,13 +250,13 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
const plan = probed.plan
if (plan.kind === 'refuse') return { kind: 'refused', reason: plan.reason }
- const classified = classifyTerminals(terminals, probed.paneCommands)
+ const confirmed = classifyTerminals(start.terminals, probed.paneCommands)
const agreed = await deps.confirm({
host,
user,
install: plan.kind === 'install' ? plan.reason : null,
restartsService: plan.kind === 'install' && probed.probe.teamExists,
- ...classified,
+ ...confirmed,
security: securityNote(user, host)
})
if (!agreed) return { kind: 'cancelled' }
@@ -251,6 +293,20 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
} catch (e) {
return failed('releasing', errorText(e), false)
}
+ // Read the canvas again right before the mark: an install can take many minutes, in which a turn
+ // can start (a cron, a loop, an armed launch) and a node can be added. Either refuses with nothing
+ // changed. From here on the handover works on THIS read (fresh session ids included).
+ let now: ShareCanvas
+ try {
+ now = deps.canvas()
+ } catch (e) {
+ return failed('releasing', errorText(e), false)
+ }
+ const refusedNow = canvasRefusal(now.terminals)
+ if (refusedNow) return refusedNow
+ if (!sameIds(ids, now.terminals.map((n) => n.nodeId))) return { kind: 'refused', reason: CANVAS_CHANGED }
+ const terminals = now.terminals
+ const classified = classifyTerminals(terminals, probed.paneCommands)
// From the mark until a successful bootstrap, every failure clears the mark (and reopens the
// project if it was closed) before it is reported. The original failure stays the reported error;
// whether restore worked is reported beside it, because a mark left behind stops the project's
@@ -275,10 +331,18 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
}
const flushed = await call(() => api.flushMirror(projectId))
if (!flushed.ok) return failAndUndo('releasing', flushed.error, false)
+ // EVERY node of the project, read now, must be in the host's file the server adopts: a note or a
+ // frame an earlier mirror write dropped would otherwise be adopted stale.
+ let projectNodeIds: string[]
+ try {
+ projectNodeIds = deps.canvas().nodeIds
+ } catch (e) {
+ return failAndUndo('releasing', errorText(e), false)
+ }
const onHost = new Set(flushed.nodeIds)
- const missing = terminals.filter((n) => !onHost.has(n.nodeId))
+ const missing = projectNodeIds.filter((id) => !onHost.has(id))
if (missing.length) {
- const stale = `The canvas on the host is not up to date (${missing.length} terminal${missing.length === 1 ? '' : 's'} missing).`
+ const stale = `The canvas on the host is not up to date (${missing.length} node${missing.length === 1 ? '' : 's'} missing).`
// "Nothing was changed" holds only when the mark was cleared again.
return failAndUndo(
'releasing',
@@ -322,7 +386,7 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
const resumed: ShareNode[] = []
const notResumed: Array<{ node: ShareNode; reason: string }> = []
let stillOnSsh: ShareNode[]
- const killed = await call(() => api.killSessions(projectId, ids))
+ const killed = await call(() => api.killSessions(projectId, terminals.map((n) => n.nodeId)))
if (!killed.ok) {
stillOnSsh = terminals
for (const n of classified.resumable) notResumed.push({ node: n, reason: 'its SSH session could not be stopped' })
diff --git a/src/renderer/lib/shareTeamCanvas.test.ts b/src/renderer/lib/shareTeamCanvas.test.ts
index 23bac305b..11e42f02e 100644
--- a/src/renderer/lib/shareTeamCanvas.test.ts
+++ b/src/renderer/lib/shareTeamCanvas.test.ts
@@ -6,10 +6,13 @@ import {
followSharedProject,
shareFocusStep,
shareProjectDeps,
+ shareCanvas,
shareTerminals,
type ShareCanvasOps
} from './shareTeamCanvas'
+const PROJ = { id: 'ssh-1', server: { host: 'box', user: 'alice' } }
+
const node = (over: Partial<CanvasNodeState> & { id: string }): CanvasNodeState => ({
kind: 'terminal',
position: { x: 0, y: 0 },
@@ -29,7 +32,7 @@ describe('shareTerminals', () => {
node({ id: 's', kind: 'sticky' }),
node({ id: 'g', kind: 'group' })
]
- const out = shareTerminals(nodes, { a: { sessionId: 'hooked', state: 'done' } })
+ const out = shareTerminals(nodes, { a: { sessionId: 'hooked', state: 'done' } }, PROJ)
expect(out).toEqual([
// The hook-fed id wins over the minted one: /clear and --fork-session mint a new one in-CLI.
{ nodeId: 'a', title: 'Claude', agentId: 'claude', sessionId: 'hooked', accountId: 'acc', state: 'done' },
@@ -40,10 +43,43 @@ describe('shareTerminals', () => {
})
it('falls back to the persisted session id when no hook reported one', () => {
- const out = shareTerminals([node({ id: 'a', agentId: 'claude', agentSessionId: 'minted' })], {})
+ const out = shareTerminals([node({ id: 'a', agentId: 'claude', agentSessionId: 'minted' })], {}, PROJ)
expect(out[0].sessionId).toBe('minted')
expect('state' in out[0]).toBe(false)
})
+
+ it('carries the status store agent beside the node own one, and only when the store knows one', () => {
+ const out = shareTerminals(
+ [node({ id: 'hand' }), node({ id: 'made', agentId: 'claude' })],
+ { hand: { agentId: 'codex', state: 'working' }, made: { state: 'done' } },
+ PROJ
+ )
+ expect(out[0]).toEqual({ nodeId: 'hand', title: 'hand', liveAgentId: 'codex', state: 'working' })
+ expect(out[1]).toEqual({ nodeId: 'made', title: 'made', agentId: 'claude', state: 'done' })
+ })
+
+ it('marks a remote-tmux terminal on another host (a host attachment); same host and plain ssh are not', () => {
+ const out = shareTerminals(
+ [
+ node({ id: 'own', ssh: { host: 'box', user: 'alice' }, sshRemoteTmux: true }),
+ // The project's own host under another login is still served by the project's master.
+ node({ id: 'own-other-user', ssh: { host: 'box', user: 'bob' }, sshRemoteTmux: true }),
+ node({ id: 'att', ssh: { host: 'prod', user: 'alice' }, sshRemoteTmux: true }),
+ node({ id: 'plain-ssh', ssh: { host: 'prod', user: 'alice' } })
+ ],
+ {},
+ PROJ
+ )
+ expect(out.filter((n) => n.otherHost).map((n) => n.nodeId)).toEqual(['att'])
+ })
+})
+
+describe('shareCanvas', () => {
+ it('lists every node id of the project (notes and frames too) beside its terminals', () => {
+ const c = shareCanvas([node({ id: 't' }), node({ id: 's', kind: 'sticky' }), node({ id: 'g', kind: 'group' })], {}, PROJ)
+ expect(c.terminals.map((n) => n.nodeId)).toEqual(['t'])
+ expect(c.nodeIds).toEqual(['t', 's', 'g'])
+ })
})
type FakeOps = ShareCanvasOps & { calls: string[]; mark: HandedOffTo | undefined; closed: boolean }
diff --git a/src/renderer/lib/shareTeamCanvas.ts b/src/renderer/lib/shareTeamCanvas.ts
index 7f388146f..fb990452f 100644
--- a/src/renderer/lib/shareTeamCanvas.ts
+++ b/src/renderer/lib/shareTeamCanvas.ts
@@ -3,31 +3,49 @@
// over injected canvas operations, so each rule below is pinned by a test rather than by a reading
// of Canvas.tsx.
import type { AgentState } from '@shared/agents/normalize'
+import { sshConnectionIdForProject, type SshConnection } from '@shared/ssh'
import type { CanvasNodeState, HandedOffTo } from '@shared/types'
-import type { ShareDeps, ShareNode } from './shareSshTeam'
+import type { ShareCanvas, ShareDeps, ShareNode } from './shareSshTeam'
+
+type AgentStatusView = Record<string, { sessionId?: string; state?: AgentState; agentId?: string } | undefined>
+/** The project the nodes belong to: its id and, for an SSH project, the server it is bound to. */
+export interface ShareProjectRef {
+ id: string
+ server?: SshConnection
+}
/** The project's terminal nodes as the share sees them. The hook-fed session id wins over the one
- * persisted at launch: `/clear` and `--fork-session` mint a new one inside the CLI. */
-export function shareTerminals(
- nodes: CanvasNodeState[],
- status: Record<string, { sessionId?: string; state?: AgentState } | undefined>
-): ShareNode[] {
+ * persisted at launch: `/clear` and `--fork-session` mint a new one inside the CLI. The status
+ * store's agent rides beside the node's own (`liveAgentId`), so a hand-launched agent still counts
+ * as busy, while only the node's own agent is ever resumed. A remote-tmux node whose endpoint is
+ * not the project's own (`sshConnectionIdForProject`, the rule every remote consumer uses) is a
+ * host attachment, marked `otherHost`. */
+export function shareTerminals(nodes: CanvasNodeState[], status: AgentStatusView, project: ShareProjectRef): ShareNode[] {
return nodes
.filter((n) => (n.kind ?? 'terminal') === 'terminal')
.map((n) => {
const live = status[n.id]
const sessionId = live?.sessionId ?? n.agentSessionId
+ const otherHost =
+ !!n.ssh && n.sshRemoteTmux === true && sshConnectionIdForProject(project.id, n.ssh, project.server) !== project.id
return {
nodeId: n.id,
title: n.title || n.id,
...(n.agentId ? { agentId: n.agentId } : {}),
+ ...(live?.agentId ? { liveAgentId: live.agentId } : {}),
...(sessionId ? { sessionId } : {}),
...(n.accountId ? { accountId: n.accountId } : {}),
- ...(live?.state ? { state: live.state } : {})
+ ...(live?.state ? { state: live.state } : {}),
+ ...(otherHost ? { otherHost: true } : {})
}
})
}
+/** The project as the share reads it at one moment: its terminals, and every node id. */
+export function shareCanvas(nodes: CanvasNodeState[], status: AgentStatusView, project: ShareProjectRef): ShareCanvas {
+ return { terminals: shareTerminals(nodes, status, project), nodeIds: nodes.map((n) => n.id) }
+}
+
/** What the share needs from the canvas for ONE project. */
export interface ShareCanvasOps {
/** Commit the live canvas into the store. */