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(mobile): give phone-started Claude nodes a persisted session id

review2b46e091c601
diff --git a/CLAUDE.md b/CLAUDE.md
index a2bfbe969..7de096445 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3548,7 +3548,19 @@ its agent status" under Hosted team relay.
`settings` block (`claudePermissionMode`/`autoSupported`/`claudeAccounts`) so the phone can
launch agents with the desktop's permission mode + managed accounts, and SSH slices get their
**per-host** settings (remote CLI caps + host-matched accounts) injected via
- `remote-status-push`'s `settingsFor` dep. `settings.customAgents` (`[{id, label, baseAgent?,
+ `remote-status-push`'s `settingsFor` dep. **`settings.claudeSessionIdFlag`** (present only as
+ `true`) is how a phone-started node gets the persisted conversation id every canvas-minted node
+ has: the phone launches `claude --session-id <uuid>` only when the HOST's own `claude --help`
+ advertised the flag (an unknown option makes claude exit), then hands that id over with the node
+ it registers — `RemoteNodeInput.agentSessionId` on `projects.registerNode`, the same key in the
+ node it writes over direct SSH — and `appendProjectNode` persists it as `data.agentSessionId`.
+ Before this a phone node had ONE route to its session (a hook event reaching this desktop), so
+ whenever none had arrived its ⌘M fell back to the markdown view, its title never adopted the
+ session name and a cold restore relaunched blank. Three writers publish the block and each must
+ answer with the probe for the machine its file describes — local claude caps in both shells, the
+ host's own probe (`core/remote-ssh/claude-session-id-probe.ts`) for an SSH slice; all three go
+ through `mirrorClaudeSessionIdFlag` and are pinned in `mirror-session-id-flag.test.ts`.
+ `settings.customAgents` (`[{id, label, baseAgent?,
binaries}]`) lets the phone chat with a custom agent: built ONLY by `core/mirror-custom-agents.ts`
(one definition for all three providers — local file, which relay `projects.list` also serves,
SSH slices, Server Edition), `binaries` = `binariesFor` from the pane-owner predicate, published
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c4c8861c9..9ab37071a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1037,6 +1037,14 @@ Put the rule in one predicate under `src/shared` and have every mint site ask it
things that follow from it (a node's color, say) from that same call rather than re-deriving the
condition per caller.
+**A node field the canvas sets must be asked about on the phone leg too.** The same two mint sites
+again: `createAgentNode` gave every Claude node a persisted session id (`data.agentSessionId`,
+launched with `--session-id`), and nothing asked what a phone-registered node should carry — so it
+carried none, and depended on a hook event reaching the desktop for its chat view, its title and
+its cold restore. When you add a field to the node a factory builds, decide in the same change what
+`appendProjectNode` / `RemoteNodeInput` does for it, and whether the phone needs a host fact to
+produce it (`MirrorSettings` is where those travel — see `claudeSessionIdFlag`).
+
**A feature that creates links owes an ownership rule, and it must be a property of the plan.**
"Share `~/.claude/skills` with this account" (issue #643) links each system skill into a managed
account's own `skills/` and removes those links again when switched off — one wrong removal deletes
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 1d63ed134..3b49f770a 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -239,6 +239,22 @@ export interface MirrorSettings {
* Absent = unknown = emit nothing: clap exits on an unknown option.
*/
codexNoDaemon?: true
+ /**
+ * THIS host's `claude` advertises `--session-id` in its own `--help` — present only as `true`.
+ * A reader that starts a Claude session on this host should then launch it as
+ * `claude --session-id <fresh uuid>` and hand that id over with the node it registers
+ * (`agentSessionId` — `RemoteNodeInput` on the relay verb, the same key in the project.json node
+ * it writes over direct SSH). That is what gives a phone-started node the persisted conversation
+ * id every canvas-minted node has; without it the node knows its session only once a hook event
+ * has reached the desktop, and until then has no chat view, no session-name title and nothing
+ * to cold-restore with.
+ *
+ * Absent = unknown = launch the bare command: claude EXITS on an option it does not know. A
+ * per-agent, per-host fact like its neighbours — it answers for *claude* on *this* host. FIRST
+ * launch only: `--session-id` with an id that already exists is a launch error, so a relaunch
+ * of the same node must resume instead.
+ */
+ claudeSessionIdFlag?: true
/**
* The user's custom agents (Settings → Agents), reduced to what a phone needs to chat with one:
* which builtin harness it inherits (the chat capability follows `baseAgent`) and which binary
@@ -257,6 +273,16 @@ export interface MirrorSettings {
hostPlatform?: string
}
+/**
+ * The `claudeSessionIdFlag` slot of a settings block, from a probe answer. ONE spelling of "only a
+ * seen `true`, otherwise absent" for the three writers of that block (desktop mirror, Server
+ * Edition mirror, the SSH slice) — each passes the probe that answers for the machine its file
+ * describes. Pinned per site in `mirror-session-id-flag.test.ts`.
+ */
+export const mirrorClaudeSessionIdFlag = (
+ supported: boolean | undefined
+): Pick<MirrorSettings, 'claudeSessionIdFlag'> => (supported === true ? { claudeSessionIdFlag: true } : {})
+
/** One custom agent as the mirror advertises it (see MirrorSettings.customAgents). */
export interface MirrorCustomAgent {
/** `custom:<uuid>` — the node's `agentId`. */
diff --git a/src/core/claude-cli.ts b/src/core/claude-cli.ts
index d4be78bab..8a5de3853 100644
--- a/src/core/claude-cli.ts
+++ b/src/core/claude-cli.ts
@@ -8,6 +8,7 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { supportsAutoPermissionMode, supportsFullscreenTui } from '../shared/agents/config'
+import { claudeHelpHasSessionIdFlag } from '../shared/agents/claude-session-id-flag'
import { IPC } from '../shared/ipc'
import { UNKNOWN_CLAUDE_CLI_CAPS, type ClaudeCliCaps } from '../shared/types'
import { directExecutableInvocation } from './exec-path'
@@ -37,9 +38,9 @@ export function claudeCliCapsFrom(
version,
autoPermissionMode: supportsAutoPermissionMode(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 ?? '')
+ // The rule (and its anchoring) lives beside its shell twin, which the REMOTE probe runs on an
+ // SSH host — see shared/agents/claude-session-id-flag.ts.
+ sessionIdFlag: claudeHelpHasSessionIdFlag(helpOutput)
}
}
diff --git a/src/core/mirror-session-id-flag.test.ts b/src/core/mirror-session-id-flag.test.ts
new file mode 100644
index 000000000..0c2b3ed64
--- /dev/null
+++ b/src/core/mirror-session-id-flag.test.ts
@@ -0,0 +1,44 @@
+// `MirrorSettings.claudeSessionIdFlag` — what lets a PHONE launch `claude --session-id <uuid>`.
+//
+// The phone starts the session itself and cannot probe the host's CLI, so it adds the flag only
+// when the status file it reads says the host's claude takes it. Three writers publish that file
+// (the desktop's local mirror, the Server Edition's, and the per-project slice the desktop pushes
+// onto an SSH host), each from an inline closure in a shell's boot code. A writer that forgets the
+// field costs nothing visible — the phone just keeps launching bare, and its nodes go on having no
+// persisted session id on that surface only. So the three sites are pinned at source level, the
+// same guard `hook-verified-parity.test.ts` uses for the two raw listeners.
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { mirrorClaudeSessionIdFlag } from './agent-status-mirror'
+
+describe('mirrorClaudeSessionIdFlag', () => {
+ it('publishes the field only for a SEEN true', () => {
+ expect(mirrorClaudeSessionIdFlag(true)).toEqual({ claudeSessionIdFlag: true })
+ })
+
+ it('publishes nothing when the CLI lacks the flag or was not probed', () => {
+ // Absent, never `false`: a reader must treat "old host file" and "CLI without the flag" the
+ // same way (no flag), and an explicit false invites one that does not.
+ expect(mirrorClaudeSessionIdFlag(false)).toEqual({})
+ expect(mirrorClaudeSessionIdFlag(undefined)).toEqual({})
+ })
+})
+
+describe('every status-file writer publishes it from the right CLI', () => {
+ const src = (rel: string): string => readFileSync(resolve(__dirname, '..', rel), 'utf-8')
+
+ it('desktop: the local mirror answers with the LOCAL claude probe', () => {
+ expect(src('main/index.ts')).toContain('...mirrorClaudeSessionIdFlag(localClaudeCaps?.sessionIdFlag)')
+ })
+
+ it('Server Edition: same field from its own local probe', () => {
+ expect(src('server/index.ts')).toContain('...mirrorClaudeSessionIdFlag(localClaudeCaps?.sessionIdFlag)')
+ })
+
+ it('SSH slice: the HOST\'s own probe, never this machine\'s', () => {
+ expect(src('main/index.ts')).toContain(
+ '...mirrorClaudeSessionIdFlag(sshProjectManager?.remoteClaudeSessionIdFlagFor(projectId))'
+ )
+ })
+})
diff --git a/src/core/project-node-append.test.ts b/src/core/project-node-append.test.ts
index 66c28d997..bf31c5cfd 100644
--- a/src/core/project-node-append.test.ts
+++ b/src/core/project-node-append.test.ts
@@ -296,3 +296,50 @@ describe('removeProjectNode', () => {
expect(removeProjectNode(baseFile(two), '', NOW)).toBeNull()
})
})
+
+// The phone launches `claude --session-id <uuid>` and hands the id over with the registration, so a
+// phone-started node has the same two routes to its conversation a canvas-minted one has: the
+// hook-fed id AND a persisted one. Without the persisted leg the node depended on a hook event
+// reaching this desktop — and showed the markdown-of-output view instead of the chat view (and
+// cold-restored as a blank conversation) whenever none had.
+describe('appendProjectNode — agentSessionId', () => {
+ const SID = '6f1d2c3b-4a59-4e68-9f70-8192a3b4c5d6'
+
+ it('persists the session id the phone minted for an agent that launches with one', () => {
+ const f = JSON.parse(
+ appendProjectNode(baseFile([]), { id: 'term-c-1', agentId: 'claude', agentSessionId: SID }, NOW)!
+ )
+ expect(f.nodes[0].agentSessionId).toBe(SID)
+ })
+
+ it('writes no session id when the phone sent none (a pre-minting phone registers as before)', () => {
+ const f = JSON.parse(appendProjectNode(baseFile([]), { id: 'term-c-1', agentId: 'claude' }, NOW)!)
+ expect('agentSessionId' in f.nodes[0]).toBe(false)
+ })
+
+ it('drops the id for an agent that never launches with a caller-chosen one', () => {
+ // A codex/gemini/plain node carrying an id would be cold-restored with `resume <that id>` —
+ // an id no such CLI ever created.
+ for (const agentId of ['codex', 'gemini', undefined]) {
+ const f = JSON.parse(
+ appendProjectNode(baseFile([]), { id: 'term-c-1', agentId, agentSessionId: SID }, NOW)!
+ )
+ expect('agentSessionId' in f.nodes[0]).toBe(false)
+ }
+ })
+
+ it('drops an unsafe or non-string id but still registers the node', () => {
+ // The id ends up on a `claude --resume <id>` line typed into a pane. Dropping it degrades to
+ // the hook-only node this field exists to improve on; refusing the registration would orphan a
+ // session that is already running.
+ for (const bad of ['a; rm -rf ~', '--help', '', 'x'.repeat(300), 42, null, { id: SID }]) {
+ const out = appendProjectNode(
+ baseFile([]),
+ { id: 'term-c-1', agentId: 'claude', agentSessionId: bad as unknown as string },
+ NOW
+ )
+ expect(out).not.toBeNull()
+ expect('agentSessionId' in JSON.parse(out!).nodes[0]).toBe(false)
+ }
+ })
+})
diff --git a/src/core/project-node-append.ts b/src/core/project-node-append.ts
index 700567ff4..5d8d441c3 100644
--- a/src/core/project-node-append.ts
+++ b/src/core/project-node-append.ts
@@ -8,7 +8,8 @@
// parse must never be invented or overwritten), a duplicate id (a retry must not churn rev), or
// an unsafe id (it becomes a tmux session name).
-import { agentConfig } from '../shared/agents/config'
+import { agentConfig, mintsSessionId } from '../shared/agents/config'
+import { SAFE_SESSION_ID } from '../shared/session-id'
import { boundAccountId } from '../shared/agents/account-binding'
import { isSafeAccountId } from './claude-accounts-core'
@@ -26,6 +27,22 @@ export interface RemoteNodeInput {
* root, and a cold restore resumed the conversation under the wrong identity.
*/
accountId?: string
+ /**
+ * The provider session id the phone LAUNCHED the agent with (`claude --session-id <uuid>`), i.e.
+ * the phone's twin of the id the canvas mints in `createAgentNode` and persists as
+ * `data.agentSessionId`. Not host-derivable either: the host never saw the launch line.
+ *
+ * Without it a phone-started node had ONE route to its conversation — a hook event reaching this
+ * desktop — where a canvas-minted node has two. Whenever that event had not arrived (the desktop
+ * was asleep or closed while the phone ran the turns, a dead hook tunnel, a host with no
+ * endpoint file) the node had no session id at all: ⌘M fell back to the markdown-of-output view
+ * instead of the chat view, the title never adopted the session's name, and a cold restore
+ * relaunched a BLANK conversation while the transcript sat intact on disk.
+ *
+ * Only a phone that knows the host's CLI accepts the flag sends it (`MirrorSettings
+ * .claudeSessionIdFlag`), so an absent field is the normal case, not an error.
+ */
+ agentSessionId?: string
}
/** The desktop id shape (`term-<base36 ms>-<token>`). Anything else is refused — the id is
@@ -144,6 +161,21 @@ export function appendProjectNode(
}
if (agentId !== undefined) node.agentId = agentId
if (bound) node.accountId = bound
+ // Stamped only for an agent that really launches with a caller-chosen id (SESSION_ID_CAPABLE):
+ // on any other node the cold restore would `resume` an id that CLI never created. And only a
+ // value safe to interpolate — it ends up on a `claude --resume <id>` line typed into a pane, the
+ // same re-validate-at-the-boundary rule every other reader of this field applies. A bad id is
+ // DROPPED rather than refusing the append (unlike `accountId` above): the node without it is
+ // exactly the hook-only node every phone registered before this field existed, whereas a
+ // refusal would orphan a session that is already running.
+ if (
+ agentId !== undefined &&
+ mintsSessionId(agentId) &&
+ typeof input.agentSessionId === 'string' &&
+ SAFE_SESSION_ID.test(input.agentSessionId)
+ ) {
+ node.agentSessionId = input.agentSessionId
+ }
// Desktop remote nodes carry the connection spec PER NODE — a sibling terminal in the same
// project has the right values; copy verbatim. No genuine donor → a plain local node.
//
diff --git a/src/core/remote-ssh/claude-session-id-probe.test.ts b/src/core/remote-ssh/claude-session-id-probe.test.ts
new file mode 100644
index 000000000..7af7de98b
--- /dev/null
+++ b/src/core/remote-ssh/claude-session-id-probe.test.ts
@@ -0,0 +1,117 @@
+// The remote "does this host's claude take --session-id?" probe, run for real under /bin/sh against
+// a fake host: the command is generated shell that no compiler checks.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFile } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { testTmpDir } from '../test-tmp'
+import { claudeHelpHasSessionIdFlag } from '../../shared/agents/claude-session-id-flag'
+import {
+ CLAUDE_SESSION_ID_END,
+ CLAUDE_SESSION_ID_START,
+ claudeSessionIdProbeCommand,
+ parseClaudeSessionIdProbe
+} from './claude-session-id-probe'
+
+const run = promisify(execFile)
+
+// Lines lifted from a real `claude --help` (2.1.x). The `--resume` entry is the decoy that matters:
+// it SAYS "session-id" without the flag existing.
+const HELP_WITH = [
+ 'Usage: claude [options] [command] [prompt]',
+ ' -r, --resume [value] Resume a conversation by session ID, or with',
+ ' --resume <session-id>, continues that',
+ ' --session-id <uuid> Use a specific session ID for the',
+ ' conversation (must be a valid UUID)',
+ ''
+].join('\n')
+const HELP_WITHOUT = [
+ 'Usage: claude [options] [command] [prompt]',
+ ' -r, --resume [value] Resume a conversation by session ID, or with',
+ ' --resume <session-id>, continues that',
+ ' --session-id-file <path> (a different option that merely starts the same)',
+ ''
+].join('\n')
+
+let root = ''
+beforeAll(() => {
+ root = testTmpDir('nt-claude-sid-probe-')
+})
+afterAll(() => fs.rmSync(root, { recursive: true, force: true }))
+
+/** A host whose `claude --help` prints `help`, installed under `where`, with a noisy login profile. */
+function host(help: string | null, where: 'bin' | '.local/bin' = 'bin'): Record<string, string> {
+ const home = fs.mkdtempSync(path.join(root, 'h-'))
+ const bin = path.join(home, 'bin')
+ fs.mkdirSync(bin)
+ if (help !== null) {
+ const dir = path.join(home, where)
+ fs.mkdirSync(dir, { recursive: true })
+ const helpFile = path.join(home, 'help.txt')
+ fs.writeFileSync(helpFile, help)
+ fs.writeFileSync(path.join(dir, 'claude'), `#!/bin/sh\n[ "$1" = --help ] && cat '${helpFile}'\n`, {
+ mode: 0o755
+ })
+ }
+ // A login-profile banner that must never read as an answer.
+ fs.writeFileSync(path.join(home, '.profile'), 'echo "Welcome — --session-id yes"\n')
+ // Only the tools the probe needs — never the system bin dirs, where a REAL claude may live.
+ const tools = path.join(home, 'tools')
+ fs.mkdirSync(tools)
+ for (const t of ['grep', 'cat']) {
+ const real = ['/usr/bin', '/bin'].map((d) => path.join(d, t)).find((f) => fs.existsSync(f))
+ if (real) fs.symlinkSync(real, path.join(tools, t))
+ }
+ fs.symlinkSync('/bin/sh', path.join(tools, 'sh'))
+ const login = path.join(tools, 'login-sh')
+ fs.writeFileSync(login, '#!/bin/sh\n[ "$1" = -lc ] && shift\n. "$HOME/.profile"\nexec /bin/sh -c "$1"\n', {
+ mode: 0o755
+ })
+ return { HOME: home, SHELL: login, PATH: `${bin}:${tools}` }
+}
+
+async function probe(env: Record<string, string>): Promise<boolean | null> {
+ const { stdout } = await run('/bin/sh', ['-c', claudeSessionIdProbeCommand()], { env }).catch(
+ (e: { stdout?: string }) => ({ stdout: e.stdout ?? '' })
+ )
+ return parseClaudeSessionIdProbe(stdout)
+}
+
+describe('claudeSessionIdProbeCommand under a real /bin/sh', () => {
+ it('answers true for a host whose claude advertises --session-id', async () => {
+ expect(await probe(host(HELP_WITH))).toBe(true)
+ })
+
+ it('answers false when the help only mentions session ids in prose or in another option', async () => {
+ expect(await probe(host(HELP_WITHOUT))).toBe(false)
+ })
+
+ it('answers unknown when the host has no claude at all', async () => {
+ expect(await probe(host(null))).toBeNull()
+ })
+
+ it('finds a claude the official installer put in ~/.local/bin, off the login PATH', async () => {
+ // The same miss the version probe had: a stock root .profile never adds ~/.local/bin.
+ expect(await probe(host(HELP_WITH, '.local/bin'))).toBe(true)
+ })
+
+ it('agrees with the local probe on the same help text', () => {
+ // Two spellings of one rule (a JS regex locally, a grep ERE on the host): if they ever
+ // disagree, the phone mints on hosts the desktop would not, or the reverse.
+ expect(claudeHelpHasSessionIdFlag(HELP_WITH)).toBe(true)
+ expect(claudeHelpHasSessionIdFlag(HELP_WITHOUT)).toBe(false)
+ })
+})
+
+describe('parseClaudeSessionIdProbe', () => {
+ it('reads only what sits between the markers', () => {
+ const wrap = (v: string): string => `banner yes\n${CLAUDE_SESSION_ID_START}${v}${CLAUDE_SESSION_ID_END}\nno`
+ expect(parseClaudeSessionIdProbe(wrap('yes'))).toBe(true)
+ expect(parseClaudeSessionIdProbe(wrap('no'))).toBe(false)
+ expect(parseClaudeSessionIdProbe(wrap('maybe'))).toBeNull()
+ expect(parseClaudeSessionIdProbe('yes')).toBeNull()
+ expect(parseClaudeSessionIdProbe(`${CLAUDE_SESSION_ID_START}yes`)).toBeNull()
+ expect(parseClaudeSessionIdProbe(null)).toBeNull()
+ })
+})
diff --git a/src/core/remote-ssh/claude-session-id-probe.ts b/src/core/remote-ssh/claude-session-id-probe.ts
new file mode 100644
index 000000000..81a64db71
--- /dev/null
+++ b/src/core/remote-ssh/claude-session-id-probe.ts
@@ -0,0 +1,46 @@
+// Pure shell command + parser for the REMOTE "does this host's `claude` take `--session-id`?" probe.
+//
+// Who needs the answer: the PHONE. A session it starts on this host is launched by the phone
+// itself, and it can only add `--session-id <uuid>` — the flag that gives the node a persisted
+// conversation id (`agentSessionId`, see core/project-node-append.ts) — when it knows the host's
+// CLI accepts it: claude EXITS on an option it does not know, taking the launch with it. The
+// answer travels in the agent-status slice pushed onto the host (`MirrorSettings
+// .claudeSessionIdFlag`), and this machine's own probe says nothing about another machine's binary.
+//
+// Same discipline as `claude-version-probe.ts` and `codex-no-daemon-probe.ts`: through the LOGIN
+// shell (an exec channel's shell usually never sees an nvm/npm-global PATH), with claude's own
+// install locations prepended (the official installer targets `~/.local/bin`, which a stock root
+// `.profile` never adds), and the answer DELIMITED so a profile banner can never be read as one.
+// No marker ⇒ unknown ⇒ the phone launches the bare command, exactly as it always has.
+import { posixQuote } from '../../shared/ssh'
+import { CLAUDE_SESSION_ID_HELP_ERE } from '../../shared/agents/claude-session-id-flag'
+
+export const CLAUDE_SESSION_ID_START = '__NT_CLAUDE_SID__'
+export const CLAUDE_SESSION_ID_END = '__NT_CLAUDE_SID_END__'
+
+/**
+ * Prints `yes` / `no` between the markers when a `claude` resolves, nothing otherwise. A
+ * `claude --help` that fails answers `no` — the conservative reading (no flag).
+ */
+export function claudeSessionIdProbeCommand(): string {
+ const emit =
+ `PATH="$HOME/.local/bin:$HOME/.claude/local:$PATH"; ` +
+ `command -v claude >/dev/null 2>&1 && { ` +
+ `if claude --help 2>/dev/null | grep -q -E '${CLAUDE_SESSION_ID_HELP_ERE}'; ` +
+ `then a=yes; else a=no; fi; ` +
+ `printf '${CLAUDE_SESSION_ID_START}%s${CLAUDE_SESSION_ID_END}' "$a"; }`
+ const q = posixQuote(emit)
+ return `$SHELL -lc ${q} 2>/dev/null || sh -c ${q} 2>/dev/null`
+}
+
+/** `true` / `false` from the markers, `null` when they are absent (no claude, a failed probe). */
+export function parseClaudeSessionIdProbe(stdout: string | null | undefined): boolean | null {
+ if (!stdout) return null
+ const start = stdout.indexOf(CLAUDE_SESSION_ID_START)
+ if (start < 0) return null
+ const from = start + CLAUDE_SESSION_ID_START.length
+ const end = stdout.indexOf(CLAUDE_SESSION_ID_END, from)
+ if (end < 0) return null
+ const v = stdout.slice(from, end).trim()
+ return v === 'yes' ? true : v === 'no' ? false : null
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 7af9e3295..19c50ff12 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -119,6 +119,7 @@ import { boardLogRemotePath } from '../core/board-log'
import { PtyManager } from '../core/pty-manager'
import { desktopHeadlessRequest, launchHeadless } from '../core/headless-launch'
import { WorkspaceStore } from '../core/workspace-store'
+import type { RemoteNodeInput } from '../core/project-node-append'
import type { CardLabelEdit } from '../core/project-kanban-write'
import { WorkspaceWatcher } from '../core/workspace-watcher'
import { SettingsStore } from '../core/settings-store'
@@ -240,6 +241,7 @@ import {
recordRawToolEvent,
recordContextUsage,
setMirrorSettingsProvider,
+ mirrorClaudeSessionIdFlag,
setMirrorLiveNodesProvider,
setMirrorUsageProvider,
buildMirrorUsage,
@@ -2692,6 +2694,9 @@ app.whenReady().then(async () => {
return {
claudePermissionMode: s.claudePermissionMode,
autoSupported: localClaudeCaps?.autoPermissionMode === true,
+ // A phone starting a Claude session here may then mint `--session-id` and register the node
+ // with it (MirrorSettings.claudeSessionIdFlag). Unprobed / older CLI ⇒ absent ⇒ bare command.
+ ...mirrorClaudeSessionIdFlag(localClaudeCaps?.sessionIdFlag),
...(localCodexCaps?.approvalValues
? { codexApprovalValues: localCodexCaps.approvalValues }
: {}), // unprobed ⇒ absent ⇒ the reader uses the baseline vocabulary
@@ -2936,6 +2941,8 @@ app.whenReady().then(async () => {
claudePermissionMode: s.claudePermissionMode,
// The phone launches claude on the REMOTE host — its CLI is the gate, never the local one.
autoSupported: sshProjectManager?.remoteAutoPermFor(projectId) === true,
+ // Same rule for `--session-id`: the HOST's own `claude --help` answered, or nothing rides.
+ ...mirrorClaudeSessionIdFlag(sshProjectManager?.remoteClaudeSessionIdFlagFor(projectId)),
// `codexApprovalValues` is deliberately ABSENT from an SSH slice: the session runs the HOST's
// codex, the only remote codex probe asks about `--no-daemon` (not the approval vocabulary),
// and publishing this machine's vocabulary for another machine's binary is the cross-host
@@ -4942,11 +4949,10 @@ app.whenReady().then(async () => {
const hostBridge = {
git: gitService,
// `accountId` = the managed Claude account the phone launched the session under. It has to be
- // declared here too, or the wire's honest shape stops at this boundary (see RemoteNodeInput).
- registerNode: (
- projectId: string,
- node: { id: string; title?: string; agentId?: string; accountId?: string }
- ) =>
+ // declared here too, or the wire's honest shape stops at this boundary — which is why this takes
+ // the registrar's own `RemoteNodeInput` instead of re-listing its fields: a hand-copied shape is
+ // where `agentSessionId` (the id the phone launched the agent with) would have stopped next.
+ registerNode: (projectId: string, node: RemoteNodeInput) =>
workspaceStore.appendRemoteNode(
projectId,
node,
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 0bf65358c..8f192d6dd 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -3321,3 +3321,51 @@ describe('SshProjectManager — remote codex --no-daemon probe', () => {
expect(answered(events)).toBeUndefined()
})
})
+
+// The phone launches Claude on this host itself and may add `--session-id` only when the HOST's CLI
+// takes it (an unknown option makes claude exit). The answer rides the pushed agent-status slice;
+// this is where it is learned.
+describe('SshProjectManager — remote claude --session-id probe', () => {
+ function mgrWithClaudeHelp(answer: string) {
+ const run = vi.fn(async (args: string[]) => {
+ const cmd = args.join(' ')
+ if (cmd.includes('__NT_CLAUDE_SID__')) return { code: 0, stdout: `Welcome yes\n${answer}` }
+ if (cmd.includes('printf %s')) return { code: 0, stdout: '/home/u' }
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: () => {}
+ })
+ return { mgr, run }
+ }
+ const probed = (run: { mock: { calls: unknown[][] } }): boolean =>
+ run.mock.calls.some((c) => (c[0] as string[]).join(' ').includes('__NT_CLAUDE_SID__'))
+
+ it('answers true once the host\'s own claude advertised the flag', async () => {
+ const { mgr } = mgrWithClaudeHelp('__NT_CLAUDE_SID__yes__NT_CLAUDE_SID_END__')
+ expect(mgr.remoteClaudeSessionIdFlagFor('p1')).toBe(false) // not connected ⇒ unknown ⇒ no flag
+ await mgr.connect('p1', conn)
+ await vi.waitFor(() => expect(mgr.remoteClaudeSessionIdFlagFor('p1')).toBe(true))
+ })
+
+ it('an older host claude answers false', async () => {
+ const { mgr, run } = mgrWithClaudeHelp('__NT_CLAUDE_SID__no__NT_CLAUDE_SID_END__')
+ await mgr.connect('p1', conn)
+ await vi.waitFor(() => expect(probed(run)).toBe(true))
+ await new Promise((r) => setTimeout(r, 20))
+ expect(mgr.remoteClaudeSessionIdFlagFor('p1')).toBe(false)
+ })
+
+ it('no markers (no claude on the host, a failed probe) stays unknown — the phone keeps its bare command', async () => {
+ const { mgr, run } = mgrWithClaudeHelp('')
+ await mgr.connect('p1', conn)
+ await vi.waitFor(() => expect(probed(run)).toBe(true))
+ await new Promise((r) => setTimeout(r, 20))
+ expect(mgr.remoteClaudeSessionIdFlagFor('p1')).toBe(false)
+ })
+})
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 7673ca5a6..133c11805 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -57,6 +57,10 @@ import {
import { SshChildGate } from '../../core/remote-ssh/ssh-child-gate'
import { claudeVersionProbeCommand, parseClaudeVersionProbe } from '../../core/remote-ssh/claude-version-probe'
import { codexNoDaemonProbeCommand, parseCodexNoDaemonProbe } from '../../core/remote-ssh/codex-no-daemon-probe'
+import {
+ claudeSessionIdProbeCommand,
+ parseClaudeSessionIdProbe
+} from '../../core/remote-ssh/claude-session-id-probe'
import { codexProbeHostKey } from '../../shared/agents/codex-daemon'
import { NO_REMOTE_INTEGRATION, RemoteHooks, type RemoteIntegrationPlan } from './remote-hooks'
import type { AgentToolsTrigger } from './agent-tools-freshness'
@@ -427,6 +431,10 @@ interface Conn {
remoteClaudeVersion?: string | null
/** This host's `codex` takes `--no-daemon` (probed after connect); undefined = not probed. */
remoteCodexNoDaemon?: RemoteCodexNoDaemon
+ /** This host's `claude` advertises `--session-id` in its own `--help` (probed after connect);
+ * undefined = not probed / no claude found. Consumed only by the agent-status slice the phone
+ * reads (`remoteClaudeSessionIdFlagFor`) — no renderer contract hangs off it. */
+ remoteClaudeSessionIdFlag?: boolean
}
/**
@@ -1170,6 +1178,11 @@ export class SshProjectManager {
// as the first one — shared/agents/codex-daemon.ts.) Unawaited and swallowed for the same
// reasons; until it lands, remote Codex lines stay exactly as they were.
if (entry) void this.probeRemoteCodexNoDaemon(projectId, entry).catch(() => {})
+ // And for the host's claude: does it take `--session-id`? Only the PHONE needs this (it
+ // launches Claude on this host itself and reads the answer off the pushed status slice),
+ // so it changes nothing about how this app's own nodes launch. Unawaited and swallowed
+ // like its two neighbours.
+ if (entry) void this.probeRemoteClaudeSessionIdFlag(projectId, entry).catch(() => {})
return {
controlPath,
hookEndpointPath,
@@ -1903,6 +1916,11 @@ export class SshProjectManager {
return this.conns.get(projectId)?.remoteCodexNoDaemon?.supported === true
}
+ /** This connection's host claude takes `--session-id` — `true` only when its own probe said so. */
+ remoteClaudeSessionIdFlagFor(projectId: string): boolean {
+ return this.conns.get(projectId)?.remoteClaudeSessionIdFlag === true
+ }
+
remoteAutoPermFor(projectId: string): boolean | undefined {
return this.conns.get(projectId)?.claudeAutoPermissionMode
}
@@ -2616,6 +2634,27 @@ export class SshProjectManager {
this.emitStatus({ projectId, status: 'connected', remoteCodexNoDaemon: answer })
}
+ /**
+ * One remote `claude --help` (login shell, marker-delimited — `claude-session-id-probe.ts`),
+ * cached on the connection. No retries and no status event: an unknown answer only means a
+ * phone-started Claude session on this host launches the bare command it always has, the next
+ * connect asks again, and the slice's 60 s heartbeat is what carries a landed answer to the phone.
+ */
+ private async probeRemoteClaudeSessionIdFlag(projectId: string, entry: Conn): Promise<void> {
+ let supported: boolean | null = null
+ try {
+ const { stdout } = await this.r.run(
+ childArgs(entry.conn, entry.controlPath, claudeSessionIdProbeCommand())
+ )
+ supported = parseClaudeSessionIdProbe(stdout)
+ } catch {
+ supported = null
+ }
+ // A probe that outlived its connection belongs to a dead Conn — never write it onto a new one.
+ if (supported === null || this.conns.get(projectId) !== entry) return
+ entry.remoteClaudeSessionIdFlag = supported
+ }
+
/**
* Probe the remote CLI's `--permission-mode auto` support AFTER the connect resolves, then push
* the answer into the live conn + the renderer (a `connected` status event carrying it).
diff --git a/src/main/remote/host-git-bridge.test.ts b/src/main/remote/host-git-bridge.test.ts
index 2b209e615..cc19350fb 100644
--- a/src/main/remote/host-git-bridge.test.ts
+++ b/src/main/remote/host-git-bridge.test.ts
@@ -159,6 +159,37 @@ describe('projects.registerNode', () => {
})
})
+ it('forwards the session id the phone launched the agent with (agentSessionId)', async () => {
+ // The direct-SSH leg writes it into project.json itself; without it on the wire a session
+ // started off-LAN would be the one kind of phone node with no persisted conversation id.
+ const f = makeFakes()
+ mk(f).onRpc({
+ id: '1',
+ method: 'projects.registerNode',
+ params: {
+ projectId: 'p1',
+ node: { id: 'term-abc-1', agentId: 'claude', agentSessionId: '6f1d2c3b-4a59-4e68-9f70-8192a3b4c5d6' }
+ }
+ })
+ await flush()
+ expect(f.registerNode).toHaveBeenCalledWith('p1', {
+ id: 'term-abc-1',
+ agentId: 'claude',
+ agentSessionId: '6f1d2c3b-4a59-4e68-9f70-8192a3b4c5d6'
+ })
+ })
+
+ it('drops a non-string agentSessionId instead of passing it on', async () => {
+ const f = makeFakes()
+ mk(f).onRpc({
+ id: '1',
+ method: 'projects.registerNode',
+ params: { projectId: 'p1', node: { id: 'term-abc-1', agentSessionId: 42 } }
+ })
+ await flush()
+ expect(f.registerNode).toHaveBeenCalledWith('p1', { id: 'term-abc-1' })
+ })
+
it('drops a non-string accountId instead of passing it on', async () => {
const f = makeFakes()
mk(f).onRpc({
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 82dbcbebc..2035e210a 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -833,6 +833,12 @@ export function createHostHandlers(
// (appendProjectNode), which refuses the whole append rather than register a wrong identity.
const accountId = str(node.accountId)
if (accountId !== undefined) input.accountId = accountId
+ // The session id the phone launched the agent with (`claude --session-id <uuid>`). Same story
+ // as accountId one field over: the direct-SSH leg writes it into project.json itself, so
+ // dropping it here would make "was the phone on the LAN?" decide whether the node can open its
+ // chat view and cold-restore its conversation. Shape and agent are judged in the registrar.
+ const agentSessionId = str(node.agentSessionId)
+ if (agentSessionId !== undefined) input.agentSessionId = agentSessionId
void registerNode(projectId, input)
.then((registered) => socket.respond(req.id, true, { registered }))
.catch(() => socket.respond(req.id, true, { registered: false }))
@@ -1731,7 +1737,7 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {
* phone node registration). One bag so the init signatures stop growing positionally. */
export interface HostBridgeDeps {
git?: HostGitOps
- registerNode?: (projectId: string, node: { id: string; title?: string; agentId?: string }) => Promise<boolean>
+ registerNode?: (projectId: string, node: RemoteNodeInput) => Promise<boolean>
/** The phone's "End session" (`pty.destroy`): destroy the tmux session on every socket it could
* live on + take the node off its project's canvas — the desktop ×'s two steps. */
destroyNode?: (nodeId: string) => Promise<void>
diff --git a/src/server/index.ts b/src/server/index.ts
index 8a15cd5f9..b9a2ac37b 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -82,6 +82,7 @@ import {
recordAgentEvent,
ackDone,
setMirrorSettingsProvider,
+ mirrorClaudeSessionIdFlag,
setMirrorLiveNodesProvider,
setMirrorServerProvider,
onInboxActionable,
@@ -530,6 +531,9 @@ export async function startServer(
return {
claudePermissionMode: s.claudePermissionMode,
autoSupported: localClaudeCaps?.autoPermissionMode === true,
+ // A phone starting a Claude session here may then mint `--session-id` and register the node
+ // with it (MirrorSettings.claudeSessionIdFlag). Unprobed / older CLI ⇒ absent ⇒ bare command.
+ ...mirrorClaudeSessionIdFlag(localClaudeCaps?.sessionIdFlag),
...(localCodexCaps?.approvalValues
? { codexApprovalValues: localCodexCaps.approvalValues }
: {}), // unprobed ⇒ absent ⇒ the reader uses the baseline vocabulary
diff --git a/src/shared/agents/claude-session-id-flag.ts b/src/shared/agents/claude-session-id-flag.ts
new file mode 100644
index 000000000..b1eaddee0
--- /dev/null
+++ b/src/shared/agents/claude-session-id-flag.ts
@@ -0,0 +1,18 @@
+// "Does this `claude --help` advertise `--session-id`?" — ONE rule in two spellings.
+//
+// The flag is FEATURE-detected from the help text rather than gated on a version (see
+// `claudeCliCapsFrom` for why a guessed floor is uniquely dangerous here: an unrecognised flag makes
+// the CLI exit, taking the launch with it). The local probe reads the text with the regex; the
+// remote probe (`core/remote-ssh/claude-session-id-probe.ts`) cannot ship help text back through a
+// login shell's banner noise, so it asks the HOST's grep with the ERE and returns only yes/no. Two
+// readers of one fact drift unless they are declared side by side, and a test runs both against
+// the same help text.
+//
+// Anchored on whitespace so `--session-id-file`, or prose that merely says "session-id" inside
+// another option's description (`--resume <session-id>,` in the real help), cannot answer yes.
+export const CLAUDE_SESSION_ID_HELP_RE = /(^|\s)--session-id(\s|=|$)/m
+export const CLAUDE_SESSION_ID_HELP_ERE = '(^|[[:space:]])--session-id([[:space:]]|=|$)'
+
+/** Absent help output ⇒ false ⇒ no flag ⇒ the command line every older build emitted. */
+export const claudeHelpHasSessionIdFlag = (helpOutput: string | null | undefined): boolean =>
+ CLAUDE_SESSION_ID_HELP_RE.test(helpOutput ?? '')