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(claude): mint a node's session id instead of only learning it

enesa401a2d94979
diff --git a/src/core/claude-cli.test.ts b/src/core/claude-cli.test.ts
index 1a13b91da..81ec3dbf0 100644
--- a/src/core/claude-cli.test.ts
+++ b/src/core/claude-cli.test.ts
@@ -6,7 +6,8 @@ describe('claudeCliCapsFrom', () => {
expect(claudeCliCapsFrom('2.1.207 (Claude Code)\n')).toEqual({
version: '2.1.207 (Claude Code)',
autoPermissionMode: true,
- fullscreenTui: true
+ fullscreenTui: true,
+ sessionIdFlag: false
})
})
@@ -14,7 +15,8 @@ describe('claudeCliCapsFrom', () => {
expect(claudeCliCapsFrom('2.1.50 (Claude Code)')).toEqual({
version: '2.1.50 (Claude Code)',
autoPermissionMode: false,
- fullscreenTui: false
+ fullscreenTui: false,
+ sessionIdFlag: false
})
})
@@ -39,3 +41,50 @@ describe('claudeCliCapsFrom', () => {
expect(claudeCliCapsFrom('some unrelated banner').autoPermissionMode).toBe(false)
})
})
+
+describe('claudeCliCapsFrom — --session-id is feature-detected, not version-gated', () => {
+ // Verbatim shape of the real help line (claude 2.1.226), including the two-space column gap
+ // the CLI actually emits.
+ const HELP = `Usage: claude [options] [command] [prompt]
+
+Options:
+ --model <model> Model for the current session.
+ --session-id <uuid> Use a specific session ID for the
+ conversation (must be a valid UUID)
+ --setting-sources <sources> Comma-separated list of setting sources
+`
+
+ it('says yes when the CLI advertises the flag', () => {
+ expect(claudeCliCapsFrom('2.1.226 (Claude Code)', HELP).sessionIdFlag).toBe(true)
+ })
+
+ it('says no for help text without it — an old CLI would exit on an unknown flag', () => {
+ const old = 'Options:\n --model <model> Model for the current session.\n'
+ expect(claudeCliCapsFrom('2.1.50 (Claude Code)', old).sessionIdFlag).toBe(false)
+ })
+
+ it('says no when the help probe produced nothing (it degrades on its own)', () => {
+ expect(claudeCliCapsFrom('2.1.226 (Claude Code)', null).sessionIdFlag).toBe(false)
+ expect(claudeCliCapsFrom('2.1.226 (Claude Code)').sessionIdFlag).toBe(false)
+ })
+
+ // Matching a bare substring would let a DIFFERENT option, or prose describing one, answer yes
+ // for a flag the CLI does not accept — and being wrong here kills every launch.
+ it('does not mistake a longer flag or prose for the real one', () => {
+ expect(claudeCliCapsFrom('2.1.226', ' --session-id-file <path>\n').sessionIdFlag).toBe(false)
+ expect(claudeCliCapsFrom('2.1.226', ' --resume overrides--session-id\n').sessionIdFlag).toBe(
+ false
+ )
+ })
+
+ it('accepts the `--session-id=<uuid>` spelling too', () => {
+ expect(claudeCliCapsFrom('2.1.226', ' --session-id=<uuid> use it\n').sessionIdFlag).toBe(true)
+ })
+
+ // The two capabilities are independent: this flag says nothing about `auto`, and vice versa.
+ it('is orthogonal to the version-gated caps', () => {
+ const c = claudeCliCapsFrom('2.1.50 (Claude Code)', HELP)
+ expect(c.sessionIdFlag).toBe(true)
+ expect(c.autoPermissionMode).toBe(false)
+ })
+})
diff --git a/src/core/claude-cli.ts b/src/core/claude-cli.ts
index 3f02609b4..a5ba82193 100644
--- a/src/core/claude-cli.ts
+++ b/src/core/claude-cli.ts
@@ -18,13 +18,27 @@ const PROBE_TIMEOUT_MS = 5000
export { UNKNOWN_CLAUDE_CLI_CAPS, type ClaudeCliCaps }
-/** Pure: `claude --version` output → caps. The impure probe below is just plumbing around it. */
-export function claudeCliCapsFrom(versionOutput: string | null | undefined): ClaudeCliCaps {
+/**
+ * Pure: probe output → caps. The impure probe below is just plumbing around it.
+ *
+ * `--session-id` is FEATURE-detected from `--help` rather than gated on a version, because the
+ * release it first appeared in is not documented anywhere this repo can verify. Guessing a floor
+ * is uniquely dangerous for this flag: an unrecognised flag makes the CLI exit, so a floor set too
+ * low would kill every claude launch on the machines below it. Reading the help text asks the CLI
+ * in front of us what it actually accepts. Absent help output ⇒ false ⇒ no flag ⇒ today's command.
+ */
+export function claudeCliCapsFrom(
+ versionOutput: string | null | undefined,
+ helpOutput?: string | null
+): ClaudeCliCaps {
const version = versionOutput?.trim() || null
return {
version,
autoPermissionMode: supportsAutoPermissionMode(version),
- fullscreenTui: supportsFullscreenTui(version)
+ fullscreenTui: supportsFullscreenTui(version),
+ // Anchored on a word boundary so `--session-id-file` or prose mentioning the flag inside
+ // another option's description cannot answer yes for it.
+ sessionIdFlag: /(^|\s)--session-id(\s|=|$)/m.test(helpOutput ?? '')
}
}
@@ -37,7 +51,13 @@ async function probe(): Promise<ClaudeCliCaps> {
const bin = await findInLoginPath('claude')
if (!bin) return UNKNOWN_CLAUDE_CLI_CAPS
const { stdout } = await execFileP(bin, ['--version'], { timeout: PROBE_TIMEOUT_MS })
- return claudeCliCapsFrom(stdout)
+ // `--help` is a second spawn, paid once per process (this whole probe is memoized). Its
+ // failure must not cost us the version answer, so it degrades on its own: no help text just
+ // means no minted session ids.
+ const help = await execFileP(bin, ['--help'], { timeout: PROBE_TIMEOUT_MS })
+ .then((r) => r.stdout)
+ .catch(() => null)
+ return claudeCliCapsFrom(stdout, help)
} catch {
// Missing CLI, timeout, non-zero exit — all mean "unknown", which means "omit the flag".
return UNKNOWN_CLAUDE_CLI_CAPS
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index fcf0a3b76..906489386 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -2265,9 +2265,19 @@ export function TerminalNode({
updateNodeData(id, { initialCommand: undefined })
} else if (fresh && agentId && canResume(agentId)) {
// Cold restart of an agent node: the live agent is gone, so re-launch it. Resume the
- // prior conversation by its session id (known from hooks) when we have one; otherwise
- // start the agent fresh. Plain terminals get nothing here — just the restored shell.
- const priorId = useAgentStatus.getState().byId[id]?.sessionId
+ // prior conversation by its session id when we have one; otherwise start the agent
+ // fresh. Plain terminals get nothing here — just the restored shell.
+ //
+ // Two sources, in this order, and the order is the whole point:
+ // 1. the LIVE id from hooks, which tracks `/clear` and `--fork-session` minting a new
+ // one mid-conversation, so it is the only one that can be current;
+ // 2. the id nodeterm MINTED at node creation and persisted (`data.agentSessionId`).
+ // Falling back to (2) is what stops a cold start from opening a blank conversation when
+ // no hook ever landed. That is not hypothetical: hook POSTs from an SSH node ride the
+ // reverse tunnel, and after one host reboot 18 of 40 agent nodes had no id at all and
+ // relaunched empty while their transcripts sat on disk, unreachable.
+ const st = useAgentStatus.getState().byId[id]
+ const priorId = st?.sessionId || data.agentSessionId
const base = (priorId && resumeCommand(agentId, priorId)) || agentConfig(agentId)?.launchCmd
// Re-resolve the mode at relaunch: it's a property of how a session is launched, not
// a persisted property of the node, so the current setting wins after a reboot. `base`
diff --git a/src/renderer/state/permissionMode.test.ts b/src/renderer/state/permissionMode.test.ts
index c4abea48f..bdaeaf224 100644
--- a/src/renderer/state/permissionMode.test.ts
+++ b/src/renderer/state/permissionMode.test.ts
@@ -20,8 +20,20 @@ function mockCliCaps(caps: ClaudeCliCaps | Error): ReturnType<typeof vi.fn> {
return fn
}
-const MODERN: ClaudeCliCaps = { version: '2.1.207 (Claude Code)', autoPermissionMode: true, fullscreenTui: true }
-const OLD: ClaudeCliCaps = { version: '2.1.50 (Claude Code)', autoPermissionMode: false, fullscreenTui: false }
+// `sessionIdFlag` is unrelated to what these fixtures exercise (the `auto` version gate); it is
+// spelled out only because ClaudeCliCaps requires it.
+const MODERN: ClaudeCliCaps = {
+ version: '2.1.207 (Claude Code)',
+ autoPermissionMode: true,
+ fullscreenTui: true,
+ sessionIdFlag: true
+}
+const OLD: ClaudeCliCaps = {
+ version: '2.1.50 (Claude Code)',
+ autoPermissionMode: false,
+ fullscreenTui: false,
+ sessionIdFlag: false
+}
const SSH_SERVER = { id: 's1', label: 'box', host: 'box', user: 'me' } as unknown as SshConnection
diff --git a/src/renderer/state/permissionMode.ts b/src/renderer/state/permissionMode.ts
index 63da7941d..70fb937f7 100644
--- a/src/renderer/state/permissionMode.ts
+++ b/src/renderer/state/permissionMode.ts
@@ -52,6 +52,16 @@ export function ensureClaudeCliCaps(): Promise<ClaudeCliCaps> {
return capsPromise
}
+/**
+ * The last-known caps, synchronously. For callers that cannot await — node creation is a sync
+ * factory — and whose correct answer when nothing has been probed yet is simply "assume nothing"
+ * (UNKNOWN, i.e. the pre-feature command line). `ensureClaudeCliCaps` runs at boot, so by the time
+ * a user creates a node this is the real answer.
+ */
+export function claudeCliCapsNow(): ClaudeCliCaps {
+ return caps
+}
+
/** Test seam: drop the memo (and optionally preload a known answer). */
export function resetClaudeCliCapsForTests(next?: ClaudeCliCaps): void {
caps = next ?? UNKNOWN_CLAUDE_CLI_CAPS
diff --git a/src/renderer/state/workspace.session-id.test.ts b/src/renderer/state/workspace.session-id.test.ts
new file mode 100644
index 000000000..6b501b7cf
--- /dev/null
+++ b/src/renderer/state/workspace.session-id.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { createAgentNode, flowToNodeStates, nodeStatesToFlow } from './workspace'
+import { resetClaudeCliCapsForTests } from './permissionMode'
+import { UNKNOWN_CLAUDE_CLI_CAPS } from '@shared/types'
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+/** A CLI that advertises `--session-id` in its help text. */
+const capable = (): void =>
+ resetClaudeCliCapsForTests({ ...UNKNOWN_CLAUDE_CLI_CAPS, version: '2.1.226', sessionIdFlag: true })
+
+afterEach(() => resetClaudeCliCapsForTests())
+
+describe('createAgentNode mints a session id when the CLI accepts one', () => {
+ beforeEach(capable)
+
+ it('stamps claude nodes with a uuid and launches with it', () => {
+ const n = createAgentNode('claude', 0)
+ expect(n.data.agentSessionId).toMatch(UUID_RE)
+ expect(n.data.initialCommand).toContain(`--session-id ${n.data.agentSessionId}`)
+ })
+
+ it('gives every node its own id (two nodes never share a conversation)', () => {
+ const a = createAgentNode('claude', 0)
+ const b = createAgentNode('claude', 1)
+ expect(a.data.agentSessionId).not.toBe(b.data.agentSessionId)
+ })
+
+ // Only claude accepts a caller-chosen id. For every other agent the command line must stay
+ // exactly what it was, or an unknown flag kills the launch.
+ it('leaves non-capable agents unstamped and their command unchanged', () => {
+ for (const id of ['codex', 'gemini', 'grok', 'opencode'] as const) {
+ const n = createAgentNode(id, 0)
+ expect(n.data.agentSessionId).toBeUndefined()
+ expect(n.data.initialCommand).not.toContain('--session-id')
+ }
+ })
+
+ it('still carries the prompt alongside the flag', () => {
+ const n = createAgentNode('claude', 0, undefined, undefined, 'fix the bug')
+ expect(n.data.initialCommand).toContain('fix the bug')
+ expect(n.data.initialCommand).toContain('--session-id')
+ })
+})
+
+describe('the CLI capability gates the mint', () => {
+ // An unrecognised flag does not degrade — claude exits and the node never starts. So anything
+ // short of the CLI saying it accepts `--session-id` must produce the pre-feature command.
+ it('an unprobed or older CLI gets the bare command, byte-identical', () => {
+ resetClaudeCliCapsForTests()
+ const n = createAgentNode('claude', 0)
+ expect(n.data.initialCommand).toBe('claude')
+ expect(n.data.agentSessionId).toBeUndefined()
+ })
+
+ it('a CLI probed as not supporting the flag also stays bare', () => {
+ resetClaudeCliCapsForTests({ ...UNKNOWN_CLAUDE_CLI_CAPS, version: '2.0.0', sessionIdFlag: false })
+ expect(createAgentNode('claude', 0).data.initialCommand).toBe('claude')
+ })
+})
+
+describe('agentSessionId survives persistence', () => {
+ beforeEach(capable)
+
+ // flowToNodeStates lists fields explicitly rather than spreading, and nodeStatesToFlow rebuilds
+ // `data` the same way — a new field missing from EITHER side is dropped silently, and the loss
+ // only surfaces after a reboot fails to resume. Both directions are asserted for that reason.
+ it('round-trips through save and load', () => {
+ const n = createAgentNode('claude', 0)
+ const minted = n.data.agentSessionId
+ const saved = flowToNodeStates([n])
+ expect(saved[0].agentSessionId).toBe(minted)
+ expect(nodeStatesToFlow(saved)[0].data.agentSessionId).toBe(minted)
+ })
+
+ it('a node saved before this field existed loads without one', () => {
+ const [loaded] = nodeStatesToFlow([
+ {
+ id: 'term-legacy',
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 480, height: 320 },
+ title: 'old claude node',
+ color: '#fff',
+ group: null,
+ tags: [],
+ agentId: 'claude'
+ }
+ ])
+ expect(loaded.data.agentSessionId).toBeUndefined()
+ })
+})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 10eb9c622..f84f96e57 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -1,8 +1,10 @@
import type { Node } from '@xyflow/react'
import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, PendingLaunch, Project } from '@shared/types'
import type { AgentId, AgentPermissionMode } from '@shared/agents/config'
-import { agentConfig } from '@shared/agents/config'
+import { agentConfig, mintsSessionId, withSessionId } from '@shared/agents/config'
import { withPermissionMode } from '@shared/agents/approval-mode'
+import { uuid } from '@renderer/lib/uuid'
+import { claudeCliCapsNow } from './permissionMode'
import { sshHostKey } from '@shared/ssh'
import { useSettings } from './settings'
@@ -95,6 +97,14 @@ export interface NodeData {
* Persisted so cold-restore resume reads the transcript from the right account dir.
*/
accountId?: string
+ /**
+ * Agents in `SESSION_ID_CAPABLE` (claude): the session id nodeterm MINTED for this node and
+ * launched the CLI with. Persisted so a resume is possible even when no hook ever delivered an
+ * id — the case that turned 18 of 40 nodes into blank conversations after one host reboot.
+ * The live id from hooks still wins when present: `/clear` and `--fork-session` mint a new one
+ * inside the CLI, and this field only remembers the id we chose at first launch.
+ */
+ agentSessionId?: string
/** group-only: the git worktree this group is bound to (single source of truth). */
worktree?: import('@shared/worktree').GroupWorktree
/**
@@ -354,9 +364,24 @@ export function createAgentNode(
? `${baseCmd} --prompt ${promptArg}`
: `${baseCmd} ${promptArg}`
: baseCmd
+ // The session id is DECIDED here rather than learned from a hook later, so this node always has
+ // something to resume with — see SESSION_ID_CAPABLE for the failure this closes. `uuid()` (not
+ // crypto.randomUUID) because the Server Edition serves plain HTTP on a LAN, where randomUUID is
+ // absent: that exact call already broke "Add agent" once.
+ //
+ // Gated on the CLI actually advertising `--session-id`, because an unknown flag does not degrade
+ // — it makes claude exit, taking the launch with it. Unprobed or older CLI ⇒ no mint ⇒ the
+ // command line stays byte-identical to what it has always been, and the node falls back to
+ // learning its id from hooks exactly as before.
+ const mintedSessionId =
+ mintsSessionId(agentId) && claudeCliCapsNow().sessionIdFlag ? uuid() : undefined
// No mode passed (e.g. a legacy/test call site) = bare command, exactly as before this setting.
- const flagged = (cmd: string): string =>
- permissionMode ? withPermissionMode(cmd, agentId, permissionMode) : cmd
+ // Both flags ride the same helper so they land on the same side of an argv separator: for grok
+ // that is BEFORE `--` (end-of-options), and getting it wrong makes a flag part of the prompt.
+ const flagged = (cmd: string): string => {
+ const withMode = permissionMode ? withPermissionMode(cmd, agentId, permissionMode) : cmd
+ return mintedSessionId ? withSessionId(withMode, agentId, mintedSessionId) : withMode
+ }
// WHERE the mode flag goes is decided by the agent's prompt convention, and the two conventions
// are opposites:
// - No separator (claude): the prompt is a positional that must stay adjacent to the binary, so
@@ -388,6 +413,9 @@ export function createAgentNode(
agentId,
// Accounts are inherently Claude-only — never stamp one onto another agent's node.
...(accountId && agentId === 'claude' ? { accountId } : {}),
+ // Persisted alongside the node (unlike initialCommand, which is consumed on first open), so
+ // a cold restore months later still knows which conversation this node owns.
+ ...(mintedSessionId ? { agentSessionId: mintedSessionId } : {}),
cwd: ssh ? ssh.remoteCwd : cwd,
initialCommand,
...(ssh ? { ssh: ssh.server, sshRemoteTmux: true } : {})
@@ -1045,6 +1073,7 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
highScore: n.highScore,
agentId,
accountId: n.accountId,
+ agentSessionId: n.agentSessionId,
pendingLaunch: n.pendingLaunch,
ssh: n.ssh,
sshRemoteTmux: n.sshRemoteTmux,
@@ -1108,6 +1137,7 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {
highScore: n.data.highScore,
agentId: n.data.agentId,
accountId: n.data.accountId,
+ agentSessionId: n.data.agentSessionId,
pendingLaunch: n.data.pendingLaunch,
ssh: n.data.ssh,
sshRemoteTmux: n.data.sshRemoteTmux,
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index 40ed80577..155f9991b 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -89,6 +89,23 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {
// automatically gets only spawn + terminal-title + process status.
export const AGENT_HOOK_TARGETS = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const
export const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const
+// Agents whose session id we MINT at launch (`--session-id <uuid>`) instead of learning it from
+// hook events. Claude only: it is the one CLI here that accepts a caller-chosen id.
+//
+// Why it matters: everything that resumes a conversation — cold restore after a reboot, the
+// session reaper's recovery path, the ⌘M transcript view — needs the id, and the id used to
+// arrive ONLY over the hook channel (agent fires a hook → POST → renderer stores it in
+// localStorage). For an SSH node that POST rides the reverse tunnel, so a node whose tunnel was
+// down, or that simply never ran a tool, never had an id at all. Measured on one host after a
+// reboot: 18 of 40 agent nodes relaunched as BLANK conversations because there was nothing to
+// resume with, while their transcripts sat intact on disk.
+//
+// Minting fixes the floor, not the whole problem: `/clear`, `--fork-session` and compaction all
+// mint a NEW id inside the CLI (claude's SessionStart hook reports these as source
+// clear/fork/compact), so hooks remain the only way to TRACK an id after launch. What minting
+// guarantees is that a node always has SOME resumable id, so the worst case degrades from "the
+// conversation is gone" to "continuity since the last /clear is gone".
+export const SESSION_ID_CAPABLE = ['claude'] as const
export const SUBAGENT_CAPABLE = ['claude'] as const
export const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cron
export const BRANCH_CAPABLE = ['claude'] as const
@@ -178,6 +195,7 @@ const includes = (list: readonly string[], id: AgentId): boolean => list.include
export const hasHooks = (id: AgentId): boolean => includes(AGENT_HOOK_TARGETS, id)
export const canResume = (id: AgentId): boolean => includes(RESUMABLE_AGENTS, id)
+export const mintsSessionId = (id: AgentId): boolean => includes(SESSION_ID_CAPABLE, id)
export const canSubagent = (id: AgentId): boolean => includes(SUBAGENT_CAPABLE, id)
export const canRecur = (id: AgentId): boolean => includes(RECURRING_CAPABLE, id)
export const canBranch = (id: AgentId): boolean => includes(BRANCH_CAPABLE, id)
@@ -224,6 +242,27 @@ export function createdAgentId(
// flag-like or metacharacter-bearing value.
const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
+/**
+ * Appends the minted-session-id flag to a FIRST-LAUNCH command, for agents in
+ * `SESSION_ID_CAPABLE`. Anything else — another agent, an empty or unsafe id — returns `cmd`
+ * unchanged, so a command line that had no business carrying the flag stays byte-identical.
+ *
+ * First launch ONLY. `claude --session-id <uuid>` refuses an id that already exists ("Session ID
+ * … is already in use.", measured against claude 2.1.226), so a relaunch of the same node must
+ * resume instead — that is `resumeCommand`'s job, and the two shapes can never be collapsed into
+ * one idempotent command.
+ *
+ * Re-validated against SAFE_SESSION_ID at this interpolation site for the same reason
+ * `resumeCommand` is: the value ends up on a tmux `send-keys` line, and the caller's type is a
+ * compile-time promise, not a runtime one.
+ */
+export function withSessionId(cmd: string, id: AgentId, sessionId: string): string {
+ if (!mintsSessionId(id)) return cmd
+ const sid = sessionId.trim()
+ if (!sid || !SAFE_SESSION_ID.test(sid)) return cmd
+ return `${cmd} --session-id ${sid}`
+}
+
/**
* The command that resumes a resumable agent's prior conversation by its provider session id.
* Used on a cold restart (machine reboot) where the tmux session — and the live agent — are
diff --git a/src/shared/agents/resume.test.ts b/src/shared/agents/resume.test.ts
index bbaf381a5..dabcc7bb2 100644
--- a/src/shared/agents/resume.test.ts
+++ b/src/shared/agents/resume.test.ts
@@ -1,5 +1,30 @@
import { describe, it, expect } from 'vitest'
-import { resumeCommand } from './config'
+import { resumeCommand, withSessionId } from './config'
+
+describe('withSessionId', () => {
+ it('appends the minted id for claude', () => {
+ expect(withSessionId('claude', 'claude', 'abc-123')).toBe('claude --session-id abc-123')
+ })
+
+ it('leaves a non-capable agent byte-identical', () => {
+ for (const id of ['codex', 'gemini', 'grok', 'opencode'] as const) {
+ expect(withSessionId(id, id, 'abc-123')).toBe(id)
+ }
+ })
+
+ // The value reaches a tmux send-keys line, so the type is not the guard — the same reason
+ // resumeCommand re-validates. A rejected id must yield the bare command, never a broken one.
+ it('refuses an unsafe or empty id and returns the command unchanged', () => {
+ for (const bad of ['', ' ', '-rf', 'a; rm -rf /', '$(id)', 'a b']) {
+ expect(withSessionId('claude', 'claude', bad)).toBe('claude')
+ }
+ })
+
+ it('accepts the uuid shape it will actually be given', () => {
+ const u = '32f2b123-6b25-4ef0-9e05-afc8705ae1f9'
+ expect(withSessionId('claude', 'claude', u)).toBe(`claude --session-id ${u}`)
+ })
+})
describe('resumeCommand', () => {
it('builds claude resume', () => {
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 45de0f1f8..ee0124e44 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -216,6 +216,14 @@ export interface CanvasNodeState {
* and immutable for the node's lifetime. Undefined = system default (~/.claude).
*/
accountId?: string
+ /**
+ * Agents in `SESSION_ID_CAPABLE` (claude): the session id nodeterm minted and launched this
+ * node's CLI with (`--session-id`). Persisted so a cold restore can resume even when no hook
+ * ever delivered an id — the SSH reverse tunnel is the only path that carries one, and a node
+ * whose tunnel was down came back as a blank conversation with its transcript intact on disk.
+ * The hook-fed id still wins when known: `/clear` and `--fork-session` mint a new one in-CLI.
+ */
+ agentSessionId?: string
/** When set, the terminal runs `ssh` to this host on the local PTY; persisted (auto-reconnects). */
ssh?: import('./ssh').SshConnection
/** When true (SSH-project terminals), the node runs in REMOTE tmux on `ssh` rather than `ssh`-on-local-PTY. */
@@ -1660,6 +1668,14 @@ export interface ClaudeCliCaps {
/** `"tui": "fullscreen"` in settings.json is only understood by Claude Code >= 2.1.89. Gates
* whether nodeterm writes that key (write-if-absent) so sessions render fullscreen in tmux. */
fullscreenTui: boolean
+ /**
+ * Whether this CLI accepts `--session-id <uuid>`, which lets nodeterm MINT a node's session id
+ * instead of waiting to learn it from a hook. Detected by reading `claude --help`, not by
+ * comparing versions: the version this flag first shipped in is not documented anywhere we can
+ * check, and a guessed floor is the one mistake that would be fatal here — an unknown flag makes
+ * the CLI exit, so a wrong guess kills every claude launch rather than degrading.
+ */
+ sessionIdFlag: boolean
}
/** The answer whenever the CLI version can't be determined: no `auto` flag → bare command, and no
@@ -1667,7 +1683,8 @@ export interface ClaudeCliCaps {
export const UNKNOWN_CLAUDE_CLI_CAPS: ClaudeCliCaps = {
version: null,
autoPermissionMode: false,
- fullscreenTui: false
+ fullscreenTui: false,
+ sessionIdFlag: false
}
export interface ClaudeApi {