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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(mirror): seed only stateless entries, age the seed, share one session-id rule
review4c541d3837d0
diff --git a/src/core/agent-launch.ts b/src/core/agent-launch.tsindex 16d99abf8..b0157539e 100644--- a/src/core/agent-launch.ts+++ b/src/core/agent-launch.ts@@ -13,6 +13,7 @@ import {type PromptInjectionMode,} from "../shared/agents/config";import { approvalFlags } from "../shared/agents/approval-mode";+import { SAFE_SESSION_ID } from "../shared/session-id";/** The parser that owns a live local Windows-profile terminal. */export type AgentLaunchDialect =@@ -109,7 +110,6 @@ interface ResolvedAgentConfig {builtin: boolean;}-const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;const SAFE_NEW_SESSION_UUID_V4 =/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;// PowerShell and POSIX parsers also treat Unicode line/paragraph separators as command boundariesdiff --git a/src/core/agent-status-mirror.seed.test.ts b/src/core/agent-status-mirror.seed.test.tsindex 522dc44e5..890c64b15 100644--- a/src/core/agent-status-mirror.seed.test.ts+++ b/src/core/agent-status-mirror.seed.test.ts@@ -19,6 +19,9 @@ import {initAgentStatusMirror,filterMirrorForNodes,mirrorEntry,+ sessionNameSweepEntries,+ EXPIRE_MS,+ IDENTITY_EXPIRE_MS,_resetForTest,_snapshot,type MirrorFile@@ -75,6 +78,16 @@ describe('seedNodeIdentities', () => {expect(mirrorEntry('n1')!.sessionId).toBeUndefined()})+ it('never fills an entry that holds a live STATE this run, even with no session id', () => {+ // A seeded id is last-known and possibly stale; next to a live state it would read as the id+ // of the session that state belongs to (the phone's permission-dialog guard reads it so).+ recordAgentEvent({ nodeId: 'n1', agentId: 'claude', kind: 'state', state: 'blocked' })+ expect(mirrorEntry('n1')!.sessionId).toBeUndefined()+ expect(seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 'stale' }])).toBe(0)+ expect(mirrorEntry('n1')!.sessionId).toBeUndefined()+ expect(mirrorEntry('n1')!.state).toBe('blocked')+ })+it('fills the identity of a hibernated-only entry without touching the flag', () => {// The renderer's boot replay reports hibernated nodes BEFORE the seed; those are exactly the// long-idle nodes the phone could not open.@@ -132,6 +145,27 @@ describe('seedNodeIdentities', () => {expect(Object.keys(_snapshot())).toHaveLength(IDENTITY_SEED_MAX)})+ it('a seeded entry reads as OLD: past EXPIRE_MS, inside the identity TTL, out of the name sweep', () => {+ const before = Date.now()+ seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 's' }])+ const at = mirrorEntry('n1')!.updatedAt+ expect(before - at).toBeGreaterThan(EXPIRE_MS)+ expect(Date.now() - at).toBeLessThan(IDENTITY_EXPIRE_MS)+ expect(sessionNameSweepEntries()).toEqual([])+ })++ it('stays identity-only across a restart (the marker itself is not persisted)', async () => {+ const file = path.join(dir, 'agent-status.json')+ seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 's' }])+ await flush()+ _resetForTest()+ initAgentStatusMirror(file)+ const e = mirrorEntry('n1')!+ expect(e.sessionId).toBe('s')+ expect(e.stateExpired).toBe(true)+ expect(sessionNameSweepEntries()).toEqual([])+ })+it('a later hook event supersedes the seed normally', () => {seedNodeIdentities([{ nodeId: 'n1', agentId: 'claude', sessionId: 'old' }])recordAgentEvent({ nodeId: 'n1', agentId: 'claude', kind: 'state', state: 'working', sessionId: 'new' })diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex 7fa2ae83e..363b89cbf 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -2104,10 +2104,18 @@ export function setNodeHibernated(nodeId: string, on: boolean): void {* and the renderer's own filter;* - an entry that already carries a `sessionId` is NEVER touched — a hook-fed id is fresher than* anything localStorage remembers — and neither is one whose `agentId` disagrees;- * - an entry with no identity at all (the boot replay's hibernated-only entry) gets its identity- * filled, nothing else;- * - a new entry is the IDENTITY-ONLY shape (`stateExpired`, no state, no proof): it says nothing- * about what the node is doing, so every state-gated reader sees "no current observation".+ * - an entry holding a STATE is never filled either, even with no session id: a seeded id is+ * last-known and possibly stale, and beside a live state it would read as the id of the session+ * that state belongs to (the phone's permission-dialog guard reads it exactly so);+ * - a STATELESS entry with no session id (the boot replay's hibernated-only entry, a restored+ * stateless one) gets its identity filled, nothing else;+ * - a new entry is the IDENTITY-ONLY shape (`stateExpired`, no state, no proof) with `updatedAt`+ * set just past EXPIRE_MS, so it reads as OLD to every freshness check. That matters because+ * `stateExpired` is not persisted: restored after a restart it is re-derived from the age, so a+ * fresh `updatedAt` would come back as a plain stateless entry and join the session-name sweep+ * (a transcript read per pass, over ssh for a remote node). The identity TTL then runs from the+ * seed — but the renderer re-seeds whenever the entry has been pruned, so in practice the+ * identity lives as long as the node and its localStorage entry do.* Returns how many entries changed. Schedules a write (and so an SSH slice push) only then.*/export function seedNodeIdentities(input: unknown): number {@@ -2120,7 +2128,7 @@ export function seedNodeIdentities(input: unknown): number {if (liveIds && !liveIds.has(s.nodeId)) continueconst e = state.get(s.nodeId)if (e) {- if (e.sessionId) continue+ if (e.sessionId || e.state) continueif (e.agentId && e.agentId !== s.agentId) continuestate.set(s.nodeId, {...e,@@ -2133,7 +2141,7 @@ export function seedNodeIdentities(input: unknown): number {agentId: s.agentId,sessionId: s.sessionId,...(s.account ? { account: s.account } : {}),- updatedAt: now,+ updatedAt: now - EXPIRE_MS - 1,stateExpired: true})}diff --git a/src/shared/agent-identity-seed.ts b/src/shared/agent-identity-seed.tsindex 76f4376a0..d8f8031e1 100644--- a/src/shared/agent-identity-seed.ts+++ b/src/shared/agent-identity-seed.ts@@ -15,6 +15,7 @@* `nt-<nodeId>` tmux names). Anything that does not match is dropped whole — never repaired.*/import { isSafeNodeId } from './safe-id'+import { SAFE_SESSION_ID } from './session-id'import { BUILTIN_AGENT_IDS } from './agents/config'import type { ObservedClaudeAccount } from './types'@@ -30,8 +31,6 @@ export interface IdentitySeedEntry {account?: ObservedClaudeAccount}-/** The same session-id alphabet `resumeCommand` / `agent-launch.ts` accept, bounded. */-const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$//** `custom:<uuid>` — the node-id alphabet after the prefix. */const CUSTOM_AGENT_ID = /^custom:[A-Za-z0-9._-]{1,128}$/const CONFIG_DIR_MAX = 4096diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 5e15b49c2..af1b2928a 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -2,6 +2,8 @@// Design: an open AgentId string, a declarative config record, and// capabilities expressed as const membership lists (not a capability object).+import { SAFE_SESSION_ID_UNBOUNDED } from '../session-id'+export type BuiltinAgentId = 'claude' | 'codex' | 'gemini' | 'opencode' | 'grok' | 'copilot'// Open type — custom agents are any string ('custom:<uuid>'). Never restrict the set.export type AgentId = BuiltinAgentId | (string & {})@@ -502,8 +504,10 @@ export function createdAgentId(// Session ids are interpolated into a shell command line (written into the live shell on a// cold restart), so accept only the safe charset agents actually use (UUIDs etc.) — never a-// flag-like or metacharacter-bearing value.-const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/+// flag-like or metacharacter-bearing value. The shared alphabet in its UNBOUNDED form: these+// helpers never capped the length, and capping them now would stop resuming an id that works today+// (see `@shared/session-id`).+const SAFE_SESSION_ID = SAFE_SESSION_ID_UNBOUNDED/*** Appends the minted-session-id flag to a FIRST-LAUNCH command, for agents indiff --git a/src/shared/session-id.test.ts b/src/shared/session-id.test.tsnew file mode 100644index 000000000..535a5a309--- /dev/null+++ b/src/shared/session-id.test.ts@@ -0,0 +1,35 @@+// ONE definition of the safe session-id alphabet. It used to be re-typed at three sites (config.ts,+// agent-launch.ts, agent-identity-seed.ts) with two different bounds; a guard keeps a fourth copy+// from appearing.+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { SAFE_SESSION_ID, SAFE_SESSION_ID_UNBOUNDED, SESSION_ID_MAX } from './session-id'++describe('shared session-id alphabet', () => {+ it('accepts uuid-like ids and refuses flags, metacharacters and empties', () => {+ for (const re of [SAFE_SESSION_ID, SAFE_SESSION_ID_UNBOUNDED]) {+ expect(re.test('0f3e-aa.b_c')).toBe(true)+ expect(re.test('-flag')).toBe(false)+ expect(re.test('.x')).toBe(false)+ expect(re.test('a b')).toBe(false)+ expect(re.test('$(x)')).toBe(false)+ expect(re.test('')).toBe(false)+ }+ })++ it('the bounded form stops at SESSION_ID_MAX; the unbounded one does not', () => {+ expect(SESSION_ID_MAX).toBe(256)+ expect(SAFE_SESSION_ID.test('a'.repeat(256))).toBe(true)+ expect(SAFE_SESSION_ID.test('a'.repeat(257))).toBe(false)+ expect(SAFE_SESSION_ID_UNBOUNDED.test('a'.repeat(257))).toBe(true)+ })++ it('no site re-types its own copy', () => {+ for (const f of ['shared/agents/config.ts', 'core/agent-launch.ts', 'shared/agent-identity-seed.ts']) {+ const src = readFileSync(resolve(__dirname, '..', f), 'utf8')+ expect(src, f).not.toMatch(/SAFE_SESSION_ID\s*=\s*\//)+ expect(src, f).toMatch(/from ['"][./]*(shared\/)?session-id['"]/)+ }+ })+})diff --git a/src/shared/session-id.ts b/src/shared/session-id.tsnew file mode 100644index 000000000..c7cc81653--- /dev/null+++ b/src/shared/session-id.ts@@ -0,0 +1,18 @@+/**+ * THE safe agent session-id alphabet: a leading alphanumeric, then `[A-Za-z0-9._-]` — covers every+ * id the agent CLIs mint (UUIDs, codex/grok thread ids) and refuses a flag-like (`-x`), dot-led or+ * metacharacter-bearing value. Session ids are interpolated into shell command lines+ * (`--resume <id>`), so every site re-validates against this, never by type. No imports: usable+ * from core, main, renderer and the server shell alike.+ *+ * Two forms, because the three sites that used to re-type it disagreed on the bound and unifying+ * would change behaviour:+ * - `SAFE_SESSION_ID` — bounded to SESSION_ID_MAX. Input-boundary checks (the launch intent in+ * `core/agent-launch.ts`, the renderer's identity seed) use it.+ * - `SAFE_SESSION_ID_UNBOUNDED` — no length cap. `shared/agents/config.ts`'s resume / minted-id+ * helpers have always used it; bounding them would silently stop resuming a (hypothetical) id+ * longer than 256 characters that works today, so their semantics are kept explicit instead.+ */+export const SESSION_ID_MAX = 256+export const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/+export const SAFE_SESSION_ID_UNBOUNDED = /^[A-Za-z0-9][A-Za-z0-9._-]*$/