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(phone registration): deaf watcher, wrong-machine nodes, lost account

enes4c589d30e712
diff --git a/src/core/claude-accounts-core.ts b/src/core/claude-accounts-core.ts
index 71760c9fd..445c7fc42 100644
--- a/src/core/claude-accounts-core.ts
+++ b/src/core/claude-accounts-core.ts
@@ -6,8 +6,15 @@ import path from 'path'
/** Shape of a valid account id (uuid / opaque token). Shared by every path builder so a bad id
* can never traverse out of the accounts root — locally OR on a remote host over ssh. */
const ACCOUNT_ID_RE = /^[A-Za-z0-9_-]+$/
+/** The same rule as a predicate, for callers that must REFUSE a bad id rather than throw on it —
+ * `project-node-append` validates the account id a phone sends over the relay before writing it
+ * into a project file. One definition: a second copy of this alphabet would drift out of step
+ * with the path builders it exists to protect. */
+export function isSafeAccountId(accountId: string): boolean {
+ return ACCOUNT_ID_RE.test(accountId)
+}
function assertAccountId(accountId: string): void {
- if (!ACCOUNT_ID_RE.test(accountId)) {
+ if (!isSafeAccountId(accountId)) {
throw new Error(`invalid account id: ${JSON.stringify(accountId)}`)
}
}
diff --git a/src/core/project-node-append.test.ts b/src/core/project-node-append.test.ts
index 684e589b5..4db3e744f 100644
--- a/src/core/project-node-append.test.ts
+++ b/src/core/project-node-append.test.ts
@@ -98,6 +98,57 @@ describe('appendProjectNode', () => {
expect(f.futureField).toEqual({ deep: true })
})
+ it('inherits ssh ONLY from a real remote-tmux sibling — never from an `ssh <host>` terminal', () => {
+ // A local project can hold a terminal that merely RUNS ssh (or a host attachment): it carries
+ // `data.ssh` and runs on the local pty. The phone's session runs on THIS machine, so copying
+ // that spec (and force-setting sshRemoteTmux) sent the desktop off to the other host, where
+ // `tmux new-session -A` created a fresh empty session instead of finding the phone's.
+ const sshTerminal = { ...sibling, id: 'term-aaa-9', sshRemoteTmux: undefined }
+ const local = JSON.parse(appendProjectNode(baseFile([sshTerminal]), { id: 'term-c-1' }, NOW)!)
+ expect(local.nodes[1].ssh).toBeUndefined()
+ expect(local.nodes[1].sshRemoteTmux).toBeUndefined()
+
+ // Explicitly false is the same answer, and so is a donor whose spec cannot be dialled.
+ const off = JSON.parse(
+ appendProjectNode(baseFile([{ ...sibling, sshRemoteTmux: false }]), { id: 'term-c-2' }, NOW)!
+ )
+ expect(off.nodes[1].ssh).toBeUndefined()
+ const halfSpec = JSON.parse(
+ appendProjectNode(baseFile([{ ...sibling, ssh: { host: 'h' } }]), { id: 'term-c-3' }, NOW)!
+ )
+ expect(halfSpec.nodes[1].ssh).toBeUndefined()
+ expect(halfSpec.nodes[1].sshRemoteTmux).toBeUndefined()
+
+ // A genuine remote-tmux sibling still donates, and is preferred over the local ssh terminal.
+ const remote = JSON.parse(
+ appendProjectNode(baseFile([sshTerminal, sibling]), { id: 'term-c-4' }, NOW)!
+ )
+ expect(remote.nodes[2].ssh).toEqual({ host: 'h', user: 'u' })
+ expect(remote.nodes[2].sshRemoteTmux).toBe(true)
+ })
+
+ it('carries accountId so the session keeps the identity the phone launched it under', () => {
+ const f = JSON.parse(
+ appendProjectNode(
+ baseFile([]),
+ { id: 'term-c-1', agentId: 'claude', accountId: '9f1c2b3d-4e5f-6071-8293-a4b5c6d7e8f9' },
+ NOW
+ )!
+ )
+ expect(f.nodes[0].accountId).toBe('9f1c2b3d-4e5f-6071-8293-a4b5c6d7e8f9')
+ // Absent = the system account (~/.claude), exactly as before.
+ const plain = JSON.parse(appendProjectNode(baseFile([]), { id: 'term-c-2' }, NOW)!)
+ expect(plain.nodes[0].accountId).toBeUndefined()
+ })
+
+ it('refuses an unsafe accountId — it becomes a config-dir path segment', () => {
+ // Refused whole, not written without the field: a node registered under the SYSTEM account is
+ // the very wrong-identity bug accountId exists to prevent, and it would look like a success.
+ for (const bad of ['../../etc', 'a/b', 'a b', '', 'a.b', 123 as never, {} as never]) {
+ expect(appendProjectNode(baseFile([]), { id: 'term-c-1', accountId: bad }, NOW)).toBeNull()
+ }
+ })
+
it('refuses: bad JSON / wrong shape / wrong version — never invents a file', () => {
expect(appendProjectNode('{ not json', { id: 'term-c-1' }, NOW)).toBeNull()
expect(appendProjectNode('{"version":99,"rev":1,"nodes":[]}', { id: 'term-c-1' }, NOW)).toBeNull()
diff --git a/src/core/project-node-append.ts b/src/core/project-node-append.ts
index eb40e9c6d..9299ee673 100644
--- a/src/core/project-node-append.ts
+++ b/src/core/project-node-append.ts
@@ -9,12 +9,22 @@
// an unsafe id (it becomes a tmux session name).
import { agentConfig } from '../shared/agents/config'
+import { isSafeAccountId } from './claude-accounts-core'
/** What the phone is allowed to choose; everything else is host-derived. */
export interface RemoteNodeInput {
id: string
title?: string
agentId?: string
+ /**
+ * Managed Claude account the phone actually launched the session under (its `CLAUDE_CONFIG_DIR`).
+ * Not host-derivable: the desktop cannot tell from the outside which identity a session runs as,
+ * and the DIRECT-SSH registration path has always written it. Dropping it off the relay leg meant
+ * an off-LAN session started under account X registered as the SYSTEM account — after which every
+ * reader scoped by account (transcript, context meter, find-bar index) resolved against the wrong
+ * root, and a cold restore resumed the conversation under the wrong identity.
+ */
+ accountId?: string
}
/** The desktop id shape (`term-<base36 ms>-<token>`). Anything else is refused — the id is
@@ -29,8 +39,30 @@ const SAFE_NODE_ID = /^term-[a-z0-9]+-[a-z0-9]{1,16}$/
const TITLE_MAX = 120
+/**
+ * A `data.ssh` block usable as a donor: the two fields the pty manager needs to dial the host.
+ * Half a spec is worse than none — it would produce a node that claims to be remote and cannot
+ * connect.
+ */
+function isSshSpec(value: unknown): boolean {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
+ const c = value as { host?: unknown; user?: unknown }
+ return typeof c.host === 'string' && c.host !== '' && typeof c.user === 'string' && c.user !== ''
+}
+
export function appendProjectNode(raw: string, input: RemoteNodeInput, now: Date): string | null {
if (!SAFE_NODE_ID.test(input.id)) return null
+ // Refused, not silently dropped: an account id becomes a config-DIR path segment
+ // (`claude-accounts/<id>`, `~/.nodeterm/claude-accounts/<id>` on a host), so a bad one must never
+ // reach the file — and quietly writing the node WITHOUT it would resurrect exactly the
+ // wrong-identity bug this field exists to fix. Same alphabet the path builders enforce.
+ // (`typeof` first: RegExp.test coerces, so a numeric id would sail through isSafeAccountId.)
+ if (
+ input.accountId !== undefined &&
+ (typeof input.accountId !== 'string' || !isSafeAccountId(input.accountId))
+ ) {
+ return null
+ }
let root: Record<string, unknown>
try {
const parsed: unknown = JSON.parse(raw)
@@ -86,9 +118,19 @@ export function appendProjectNode(raw: string, input: RemoteNodeInput, now: Date
cwd: typeof sibling?.cwd === 'string' ? sibling.cwd : '.'
}
if (typeof input.agentId === 'string') node.agentId = input.agentId
+ if (typeof input.accountId === 'string') node.accountId = input.accountId
// Desktop remote nodes carry the connection spec PER NODE — a sibling terminal in the same
- // project has the right values; copy verbatim. No sibling with ssh → a plain local node.
- const sshDonor = nodes.find((n) => isTerminal(n) && n.ssh !== undefined)
+ // project has the right values; copy verbatim. No genuine donor → a plain local node.
+ //
+ // "Genuine" is load-bearing, and the rule used to be `n.ssh !== undefined` — which does not even
+ // ask about `sshRemoteTmux`, yet force-set it to true on the new node. But `data.ssh` alone means
+ // something else entirely: a plain `ssh <host>` terminal (or a host attachment) that runs on the
+ // LOCAL pty. So on a LOCAL project holding one such node, the phone's session — which really runs
+ // on this desktop's own machine — was written as a remote tmux node on that host; the desktop then
+ // dialled the host and `tmux new-session -A` obligingly created a brand-new EMPTY session there,
+ // while the phone's real session sat unreachable on this machine. Only a node that is ITSELF a
+ // remote tmux session, with a spec complete enough to dial, describes the same context.
+ const sshDonor = nodes.find((n) => isTerminal(n) && n.sshRemoteTmux === true && isSshSpec(n.ssh))
if (sshDonor) {
node.ssh = sshDonor.ssh
node.sshRemoteTmux = true
diff --git a/src/core/workspace-watcher.test.ts b/src/core/workspace-watcher.test.ts
index 2fcbbe195..6d4be2ad9 100644
--- a/src/core/workspace-watcher.test.ts
+++ b/src/core/workspace-watcher.test.ts
@@ -36,6 +36,58 @@ describe('WorkspaceWatcher', () => {
w.dispose()
})
+ // The two below use a REAL atomic replace (`mv -f tmp project.json`), not writeFile: writeFile
+ // truncates in place and keeps the inode, so it fires forever on its own and proves nothing.
+ // A file-bound fs.watch follows the inode, so only the rebind keeps these alive.
+ const replace = async (content: string): Promise<void> => {
+ const tmp = path.join(dir, `t-${Math.random().toString(36).slice(2)}`)
+ await fs.writeFile(tmp, content)
+ await fs.rename(tmp, file)
+ }
+
+ it('keeps firing across repeated atomic replacements (the inode changes every time)', async () => {
+ const events: string[] = []
+ const w = new WorkspaceWatcher({
+ paths: () => [file],
+ isSelfWrite: () => false,
+ onExternalChange: (p) => events.push(p),
+ debounceMs: 30
+ })
+ w.sync()
+ for (let i = 0; i < 3; i++) {
+ await replace(`{"v":${i}}`)
+ await wait(150)
+ }
+ expect(events).toEqual([file, file, file])
+ w.dispose()
+ })
+
+ it('survives an unreadable moment: the corrupt-file sideline must not leave the path deaf', async () => {
+ const events: string[] = []
+ const w = new WorkspaceWatcher({
+ paths: () => [file],
+ isSelfWrite: () => false,
+ onExternalChange: (p) => events.push(p),
+ debounceMs: 30
+ })
+ w.sync()
+ // What the store does with a project.json it cannot parse: rename it out of the way. The
+ // watcher wakes, finds nothing to read, and must still re-arm on the NAME.
+ await fs.rename(file, `${file}.corrupt-1`)
+ await wait(150)
+ expect(events).toEqual([])
+ // A fresh file lands at the same path (the store rewrites it, or a `git checkout` restores it).
+ await replace('{"v":"fresh"}')
+ await wait(300)
+ // …and an outside edit after that is still seen. Before the fix this was silence for the rest
+ // of the run: the dead watcher stayed in the map, so sync() skipped the path forever.
+ events.length = 0
+ await replace('{"v":"outside"}')
+ await wait(200)
+ expect(events).toEqual([file])
+ w.dispose()
+ })
+
it('drops watchers for paths that disappear from paths()', async () => {
const events: string[] = []
let paths = [file]
diff --git a/src/core/workspace-watcher.ts b/src/core/workspace-watcher.ts
index f4aebd0ee..f70a08c68 100644
--- a/src/core/workspace-watcher.ts
+++ b/src/core/workspace-watcher.ts
@@ -8,6 +8,12 @@ interface Opts {
debounceMs?: number
}
+/** Retry cadence for a rebind that could not attach because the name was momentarily absent.
+ * Bounded: a path that is simply gone (an unavailable ref) falls back to "next sync() retries",
+ * which is the behaviour this class always had for a path that never existed. */
+const REARM_RETRY_MS = 120
+const REARM_MAX_TRIES = 25
+
/**
* Watches each local ref's project.json for outside edits (git pull, file sync,
* a teammate's commit). Self-writes are recognized by exact content match against
@@ -17,6 +23,8 @@ interface Opts {
export class WorkspaceWatcher {
private watchers = new Map<string, FSWatcher>()
private timers = new Map<string, ReturnType<typeof setTimeout>>()
+ private rearms = new Map<string, ReturnType<typeof setTimeout>>()
+ private rearmTries = new Map<string, number>()
constructor(private opts: Opts) {}
@@ -50,24 +58,55 @@ export class WorkspaceWatcher {
}
private async check(p: string): Promise<void> {
+ // Re-arm FIRST, and unconditionally — before anything that can fail or return early.
+ // Measured on Linux/inotify: a FILE-bound fs.watch follows the INODE, so it reports the first
+ // `mv -f tmp project.json` and then nothing, ever again. The rebind after each event is what
+ // keeps this watcher alive at all.
+ //
+ // It used to live at the bottom, duplicated into the self-write and outside-edit branches, so
+ // a failed read returned before reaching either — and it did NOT even drop the dead watcher,
+ // which left the map holding an entry that is deaf (its inode is gone) yet indistinguishable
+ // from a live one, so every later sync() skipped the path. One unreadable moment (the
+ // corrupt-file sideline rename project.json → project.json.corrupt-<ts>, a transient EACCES)
+ // therefore made that project permanently blind to outside edits for the rest of the run —
+ // including every session the phone registers over direct SSH.
+ this.rearm(p)
let content: string
try {
content = await fs.readFile(p, 'utf-8')
} catch {
- return // transient (atomic rename in flight)
- }
- if (this.opts.isSelfWrite(p, content)) {
- // Atomic saves replace the inode — rewatch so future outside edits still fire.
- this.watchers.get(p)?.close()
- this.watchers.delete(p)
- this.sync()
- return
+ return // transient (atomic rename in flight) — the watch is already re-armed
}
- // Atomic saves replace the inode — rewatch so future edits still fire.
+ if (this.opts.isSelfWrite(p, content)) return
+ this.opts.onExternalChange(p)
+ }
+
+ /** Close and re-open the watch on `p` (see `check`). When the name is momentarily absent — an
+ * atomic replace in flight, or the corrupt-file sideline before the fresh file lands — `watch`
+ * throws and nothing else would re-add the path (`sync()` only runs when the workspace itself
+ * changes), so a bounded retry finishes the job. */
+ private rearm(p: string): void {
this.watchers.get(p)?.close()
this.watchers.delete(p)
this.sync()
- this.opts.onExternalChange(p)
+ if (this.watchers.has(p) || !this.opts.paths().includes(p)) {
+ this.rearmTries.delete(p)
+ return
+ }
+ const tries = (this.rearmTries.get(p) ?? 0) + 1
+ if (tries > REARM_MAX_TRIES) {
+ this.rearmTries.delete(p)
+ return
+ }
+ this.rearmTries.set(p, tries)
+ clearTimeout(this.rearms.get(p))
+ this.rearms.set(
+ p,
+ setTimeout(() => {
+ this.rearms.delete(p)
+ this.rearm(p)
+ }, REARM_RETRY_MS)
+ )
}
dispose(): void {
@@ -75,5 +114,8 @@ export class WorkspaceWatcher {
this.watchers.clear()
for (const t of this.timers.values()) clearTimeout(t)
this.timers.clear()
+ for (const t of this.rearms.values()) clearTimeout(t)
+ this.rearms.clear()
+ this.rearmTries.clear()
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 6c62f43d8..1b8150cb9 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -2122,8 +2122,12 @@ app.whenReady().then(async () => {
// the canvas adopts the node live).
const hostBridge = {
git: gitService,
- registerNode: (projectId: string, node: { id: string; title?: string; agentId?: string }) =>
- workspaceStore.appendRemoteNode(projectId, node),
+ // `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 }
+ ) => workspaceStore.appendRemoteNode(projectId, node),
// Jail roots beyond the active canvas: the phone browses EVERY project (projects.list), so
// its fs/git access spans every local project root — not just the tab the desktop happens
// to have focused (that gap read as "cwd is outside the shared project roots" on the phone).
diff --git a/src/main/remote/host-git-bridge.test.ts b/src/main/remote/host-git-bridge.test.ts
index 65edbb7f6..2b209e615 100644
--- a/src/main/remote/host-git-bridge.test.ts
+++ b/src/main/remote/host-git-bridge.test.ts
@@ -138,6 +138,38 @@ describe('projects.registerNode', () => {
expect(f.responses).toEqual([{ id: '1', ok: true, body: { registered: true } }])
})
+ it('forwards the managed account the phone launched under (accountId)', async () => {
+ // Without this the off-LAN leg registered every managed-Claude session as the SYSTEM account
+ // while the direct-SSH leg got it right — the same session registered as a different identity
+ // depending only on whether the phone happened to be on the LAN.
+ const f = makeFakes()
+ mk(f).onRpc({
+ id: '1',
+ method: 'projects.registerNode',
+ params: {
+ projectId: 'p1',
+ node: { id: 'term-abc-1', agentId: 'claude', accountId: 'acc-1', note: 'ignored' }
+ }
+ })
+ await flush()
+ expect(f.registerNode).toHaveBeenCalledWith('p1', {
+ id: 'term-abc-1',
+ agentId: 'claude',
+ accountId: 'acc-1'
+ })
+ })
+
+ it('drops a non-string accountId 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', accountId: 42 } }
+ })
+ await flush()
+ expect(f.registerNode).toHaveBeenCalledWith('p1', { id: 'term-abc-1' })
+ })
+
it('a refused registration (bad shape / unknown project) reports registered:false', async () => {
const f = makeFakes()
f.registerNode.mockResolvedValueOnce(false as never)
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 4d19856b3..21a529998 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -28,6 +28,7 @@ import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '..
import type { AgentId } from '../../shared/agents/config'
import { PtyManager, type DetachedSinks } from '../../core/pty-manager'
import * as fsOps from '../../core/fs-ops'
+import type { RemoteNodeInput } from '../../core/project-node-append'
import { getStoredEntitlement, isPremium } from '../../core/license'
import { publicKeyToB64, type KeyPair } from './e2ee'
import { loadOrCreateHostKeyPair, HostKeyLockedError } from './host-identity'
@@ -190,7 +191,7 @@ export function createHostHandlers(
git?: HostGitOps,
// Registers a phone-started session as a project node (WorkspaceStore.appendRemoteNode).
// Absent ⇒ `projects.registerNode` is not served.
- registerNode?: (projectId: string, node: { id: string; title?: string; agentId?: string }) => Promise<boolean>
+ registerNode?: (projectId: string, node: RemoteNodeInput) => Promise<boolean>
): HostHandlers {
// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no
// reverse (sessionId -> streamId) index is needed.
@@ -442,11 +443,19 @@ export function createHostHandlers(
socket.respond(req.id, false, { message: 'projects.registerNode requires projectId and node.id.' })
return
}
- const input: { id: string; title?: string; agentId?: string } = { id }
+ const input: RemoteNodeInput = { id }
const title = str(node.title)
if (title !== undefined) input.title = title
const agentId = str(node.agentId)
if (agentId !== undefined) input.agentId = agentId
+ // The managed Claude account the phone launched this session under (its CLAUDE_CONFIG_DIR).
+ // The direct-SSH registration path has always persisted it; this leg used to drop it on the
+ // floor, so an off-LAN session under account X came back as the system account and every
+ // account-scoped reader (transcript, context meter, find bar) then resolved against the wrong
+ // root — and a cold restore resumed it as the wrong identity. Validated in the registrar
+ // (appendProjectNode), which refuses the whole append rather than register a wrong identity.
+ const accountId = str(node.accountId)
+ if (accountId !== undefined) input.accountId = accountId
void registerNode(projectId, input)
.then((registered) => socket.respond(req.id, true, { registered }))
.catch(() => socket.respond(req.id, true, { registered: false }))
@@ -719,7 +728,7 @@ export interface HostSessionOptions {
/** Typed, jailed `git.*` bridge (see HostGitOps). Optional: absent ⇒ the verbs are not served. */
git?: HostGitOps
/** Registers a phone-started session as a project node (`projects.registerNode`). Optional. */
- registerNode?: (projectId: string, node: { id: string; title?: string; agentId?: string }) => Promise<boolean>
+ registerNode?: (projectId: string, node: RemoteNodeInput) => Promise<boolean>
/** Extra fs/git jail roots beyond the shared canvas's node cwds — production passes the
* workspace's local project cwds: the phone browses EVERY project over `projects.list`, so a
* canvas-only jail denied whichever project the desktop didn't happen to have focused. */