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.

test(pendingLaunch): behavioural tests for the owner/relay trust paths

review05237761b7b1
diff --git a/src/main/platform-electron.test.ts b/src/main/platform-electron.test.ts
index 88d5d81ed..b0c708507 100644
--- a/src/main/platform-electron.test.ts
+++ b/src/main/platform-electron.test.ts
@@ -107,6 +107,41 @@ describe('electronPlatform', () => {
})
})
+/**
+ * Who is the OWNER. The canvas reflector (core/canvas-sync.ts) lets a node's machine-local held
+ * launch (`pendingLaunch`) travel only owner→owner, so the app's own window must be the owner and a
+ * relay peer never may be — whatever else is true of its id.
+ */
+describe('electronPlatform.isOwnerClient', () => {
+ it('is true for the live main window, false for a relay peer and for an unknown id', () => {
+ const p = electronPlatform()
+ h.clientIds = [1]
+ registerPeerSink(PEER, peerSink().sink)
+ expect(p.isOwnerClient?.(1)).toBe(true)
+ expect(p.isOwnerClient?.(PEER)).toBe(false)
+ expect(p.isOwnerClient?.(2)).toBe(false)
+ })
+
+ it('is false while there is no window (macOS: the window closed, the app still running)', () => {
+ const p = electronPlatform()
+ h.clientIds = []
+ expect(p.isOwnerClient?.(1)).toBe(false)
+ })
+
+ it('a registered peer is never the owner, even if its id were also reported as a window', () => {
+ // Peer ids come from allocateRelayClientId() (≥ 1_000_000) precisely so they cannot collide with
+ // a webContents id; this pins the second guard, which holds even if that allocation ever broke.
+ const p = electronPlatform()
+ h.clientIds = [PEER]
+ registerPeerSink(PEER, peerSink().sink)
+ expect(p.isOwnerClient?.(PEER)).toBe(false)
+ })
+
+ it('a minted relay peer id never equals a small webContents id', () => {
+ expect(allocateRelayClientId()).toBeGreaterThanOrEqual(1_000_000)
+ })
+})
+
/**
* The seam that makes a relay peer a FIRST-CLASS client of this desktop's core: a peer has no
* webContents, so before this every sendTo/broadcast aimed at one silently no-op'd (the host saw the
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 111a95a3b..eff76ce4c 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -76,7 +76,7 @@ import {
useSharedGlyphActive
} from './SharedGlyphLayer'
import { SshReconnector } from '../lib/sshReconnect'
-import { projectMayDialSsh, sanitizeRelayMutation } from '../session/relay-ssh'
+import { projectMayDialSsh, receivedCanvasMutation } from '../session/relay-ssh'
import {
hostAttachmentsFor,
planActiveProjectDials,
@@ -657,7 +657,6 @@ 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
@@ -3775,7 +3774,7 @@ export function Canvas() {
// dial-capable SSH connection onto this machine (session/relay-ssh.ts).
const relay = activeSession.source === 'relay'
return activeSession.api.canvas.onMutation((projectId, received) => {
- const mutation = relay ? sanitizeRelayMutation(withoutCoreOrigin(received)) : received
+ const mutation = receivedCanvasMutation(received, relay)
hasPeersRef.current = true // proof of a peer, whatever the presence table says
if (!orderRef.current?.accept(mutation)) return
if (projectId !== useProjects.getState().activeProjectId) {
diff --git a/src/renderer/session/relay-ssh.test.ts b/src/renderer/session/relay-ssh.test.ts
index ebc0151ef..9b3eef7bf 100644
--- a/src/renderer/session/relay-ssh.test.ts
+++ b/src/renderer/session/relay-ssh.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { CanvasNodeState, Project } from '@shared/types'
-import { projectMayDialSsh, sanitizeRelayMutation, sanitizeRelayNode, sanitizeRelayProject } from './relay-ssh'
+import { projectMayDialSsh, receivedCanvasMutation, sanitizeRelayMutation, sanitizeRelayNode, sanitizeRelayProject } from './relay-ssh'
const EVIL = { host: 'evil.example', user: 'me', identityFile: '/home/me/.ssh/id_ed25519', extraArgs: '-A' }
@@ -46,6 +46,16 @@ describe('relay-ssh', () => {
expect(sanitizeRelayMutation(rm)).toBe(rm)
})
+ it('receivedCanvasMutation: a relay session loses the remote origin and the ssh endpoint; a local one is untouched', () => {
+ const m = { op: 'upsert' as const, node: node({ ssh: EVIL, sshRemoteTmux: true }), seq: 3, origin: 'core' as const }
+ const relay = receivedCanvasMutation(m, true)
+ expect(relay.origin).toBeUndefined()
+ expect(relay.op === 'upsert' && relay.node.ssh).toBeFalsy()
+ expect(relay.seq).toBe(3)
+ expect(receivedCanvasMutation(m, false)).toBe(m)
+ // What that means for a held launch is behaviour-tested in state/pending-launch-sync.test.ts.
+ })
+
it('projectMayDialSsh refuses exactly relay projects', () => {
expect(projectMayDialSsh({ remote: true })).toBe(false)
expect(projectMayDialSsh({})).toBe(true)
diff --git a/src/renderer/session/relay-ssh.ts b/src/renderer/session/relay-ssh.ts
index cd84427b9..0eca4c643 100644
--- a/src/renderer/session/relay-ssh.ts
+++ b/src/renderer/session/relay-ssh.ts
@@ -1,4 +1,5 @@
import type { CanvasMutation, CanvasNodeState, Project } from '@shared/types'
+import { withoutCoreOrigin } from '@shared/node-exec'
/**
* A relay tab must never make THIS machine dial SSH.
@@ -72,6 +73,16 @@ export function sanitizeRelayMutation(mutation: CanvasMutation): CanvasMutation
return node === mutation.node ? mutation : { ...mutation, node }
}
+/**
+ * What a canvas-sync mutation received on a session may do here. 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: it is dropped (the node's held launch stays ours — @shared/node-exec) and the
+ * dial-capable SSH connection is stripped. A local session's mutation is returned as received.
+ */
+export function receivedCanvasMutation(received: CanvasMutation, relay: boolean): CanvasMutation {
+ return relay ? sanitizeRelayMutation(withoutCoreOrigin(received)) : received
+}
+
/**
* THE gate every guest-side SSH dial asks: a relay tab's project never dials, whatever it carries.
* `undefined` (unknown project) is not a relay project — the caller's own "nothing to dial" check
diff --git a/src/renderer/session/relay-ssh.wiring.test.ts b/src/renderer/session/relay-ssh.wiring.test.ts
index 856aefa2a..c3c8cb283 100644
--- a/src/renderer/session/relay-ssh.wiring.test.ts
+++ b/src/renderer/session/relay-ssh.wiring.test.ts
@@ -27,7 +27,8 @@ describe('relay tabs never reach a guest-side ssh dial', () => {
})
it('relay canvas-sync mutations are stripped', () => {
- expect(canvas).toContain('const mutation = relay ? sanitizeRelayMutation(withoutCoreOrigin(received)) : received')
+ // The decision itself is behaviour-tested in relay-ssh.test.ts (`receivedCanvasMutation`).
+ expect(canvas).toContain('const mutation = receivedCanvasMutation(received, relay)')
})
it('a relay terminal never resolves a guest-local ControlMaster', () => {
diff --git a/src/renderer/state/pending-launch-sync.test.ts b/src/renderer/state/pending-launch-sync.test.ts
index f8636cf6e..10e199e50 100644
--- a/src/renderer/state/pending-launch-sync.test.ts
+++ b/src/renderer/state/pending-launch-sync.test.ts
@@ -1,15 +1,16 @@
// `pendingLaunch` across the live canvas (applyMutationToFlow), the background-project store
-// (applyNodeMutation / applyOwnNodeMutation), and two Server Edition tabs sharing one core.
+// (applyNodeMutation / applyOwnNodeMutation), and a relay tab's receive path. The two-owner-tabs
+// half (through the real core reflector) is cross-layer and lives in
+// test/acceptance/pending-launch-reflector.test.ts.
//
// 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.
+// is authoritative. The peer/relay half is pinned here.
import { describe, it, expect, beforeEach } from 'vitest'
-import { applyMutationToFlow, nodeStatesToFlow, flowToNodeStates, type CanvasNode } from './workspace'
+import { applyMutationToFlow, nodeStatesToFlow, type CanvasNode } from './workspace'
import { useProjects } from './projects'
-import { sanitizeInboundMutation, stripCastNodeExec } from '@shared/node-exec'
-import { launchesToFire } from '../lib/pendingLaunch'
+import { receivedCanvasMutation } from '../session/relay-ssh'
import type { CanvasMutation, CanvasNodeState, PendingLaunch } from '@shared/types'
const armed: PendingLaunch = { after: [], command: 'claude "brief"', attempted: false }
@@ -45,6 +46,12 @@ describe('applyMutationToFlow (live canvas)', () => {
const cleared = applyMutationToFlow(mine, { op: 'upsert', node: state(), origin: 'core' })
expect(cleared[0].data.pendingLaunch).toBeUndefined()
})
+ it('a core-vouched copy of a node we do NOT have yet is appended WITH its launch', () => {
+ // The append branch: the Server Edition's headless factory publishes a brand-new held node.
+ const other = flow(state({ id: 'n0' }))
+ const out = applyMutationToFlow(other, { op: 'upsert', node: state({ pendingLaunch: armed }), origin: 'core' })
+ expect(out.find((n) => n.id === 'n1')?.data.pendingLaunch).toEqual(armed)
+ })
})
describe('projects store (a project not on screen)', () => {
@@ -71,26 +78,35 @@ describe('projects store (a project not on screen)', () => {
})
})
-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([])
+/**
+ * A relay TAB on this machine shows another machine's project; its mutations come from that
+ * machine's core, which can put `origin: 'core'` on anything. Canvas.tsx passes every received
+ * mutation through `receivedCanvasMutation(received, relay)` before applying it (live canvas, or
+ * the store for a background project) — so a remote vouch can neither plant nor clear a launch here.
+ */
+describe('a relay tab: a remote core\'s origin:\'core\' vouches for nothing', () => {
+ const vouchedClear: CanvasMutation = { op: 'upsert', node: state(), origin: 'core', seq: 1 }
+ const vouchedPlant: CanvasMutation = { op: 'upsert', node: state({ id: 'x', pendingLaunch: { after: [], command: 'evil' } }), origin: 'core', seq: 2 }
+ it('live canvas: cannot clear our launch, cannot plant one', () => {
+ const mine = flow(state({ pendingLaunch: armed }))
+ expect(applyMutationToFlow(mine, receivedCanvasMutation(vouchedClear, true))[0].data.pendingLaunch).toEqual(armed)
+ const planted = applyMutationToFlow(mine, receivedCanvasMutation(vouchedPlant, true))
+ expect(planted.find((n) => n.id === 'x')?.data.pendingLaunch).toBeUndefined()
+ })
+ it('background project (the store): cannot clear our launch, cannot plant one', () => {
+ useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: [] })
+ const p = useProjects.getState().addProject('p', '/tmp/p')
+ useProjects.getState().applyOwnNodeMutation(p.id, { op: 'upsert', node: state({ pendingLaunch: armed }) })
+ useProjects.getState().applyNodeMutation(p.id, receivedCanvasMutation(vouchedClear, true))
+ useProjects.getState().applyNodeMutation(p.id, receivedCanvasMutation(vouchedPlant, true))
+ const nodes = useProjects.getState().getProject(p.id)!.nodes
+ expect(nodes.find((n) => n.id === 'n1')?.pendingLaunch).toEqual(armed)
+ expect(nodes.find((n) => n.id === 'x')?.pendingLaunch).toBeUndefined()
})
- 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'])
+ it('control: the same vouched copy on a LOCAL session is authoritative (sets and clears)', () => {
+ const mine = flow(state({ pendingLaunch: armed }))
+ expect(applyMutationToFlow(mine, receivedCanvasMutation(vouchedClear, false))[0].data.pendingLaunch).toBeUndefined()
+ const planted = applyMutationToFlow(mine, receivedCanvasMutation(vouchedPlant, false))
+ expect(planted.find((n) => n.id === 'x')?.data.pendingLaunch).toEqual({ after: [], command: 'evil' })
})
})
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index a7f18bc44..147bdbf37 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -240,7 +240,9 @@ describe('HeadlessNodeFactory', () => {
stateOf: (id) => states[id],
outcomeOf: (id) => outcomes[id],
launchTiming: { quietMs: 0, capMs: 0 },
- publishNode: (_projectId, node) => published.push(node),
+ // A snapshot, as the real publisher (publishCanvasMutation) takes one at call time: the factory
+ // goes on to update the same node object in place after it publishes.
+ publishNode: (_projectId, node) => published.push(structuredClone(node)),
publishRemoval: (_projectId, nodeId) => removed.push(nodeId),
publishProject: (project) => publishedProjects.push(structuredClone(project))
})
@@ -273,6 +275,11 @@ describe('HeadlessNodeFactory', () => {
expect(pty.sends).toEqual([{ nodeId: id, text: 'printf hello' }])
// The persisted hold is published first, then its acknowledged delivery.
expect(published.map((node) => node.id)).toEqual([id, id])
+ // …and the first publish CARRIES the claimed hold: an owner tab appends this brand-new node
+ // with its launch (test/acceptance/pending-launch-reflector.test.ts), so its next save
+ // cannot drop what this core persisted. The second is the delivery, which clears it.
+ expect(published[0].pendingLaunch).toMatchObject({ command: 'printf hello', attempted: true, manualOnly: true })
+ expect(published[1].pendingLaunch).toBeUndefined()
expect(fs.existsSync(path.join(dataDir, 'workspace.json'))).toBe(true)
const projectFile = path.join(projectDir, '.nodeterm', 'project.json')
diff --git a/src/server/owner-client.test.ts b/src/server/owner-client.test.ts
index 45f5f1c46..1cd668f29 100644
--- a/src/server/owner-client.test.ts
+++ b/src/server/owner-client.test.ts
@@ -21,24 +21,19 @@ describe('ServerPlatform.isOwnerClient', () => {
})
})
+// The other owner decisions are behaviour-tested where they live:
+// - the authenticated browser socket attaches as owner: ws.test.ts (a real WS connection);
+// - Electron's window is the owner, a relay peer never is: main/platform-electron.test.ts;
+// - a relay tab cannot set or clear a local launch with a remote `origin: 'core'`:
+// renderer/state/pending-launch-sync.test.ts (`receivedCanvasMutation`, applied to the live
+// canvas and the store).
+// The hosted-team attach adapter is inline in the server's boot function, so it is still pinned by
+// its source line; ServerPlatform.attach without the flag is the behaviour tested above.
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 ? sanitizeRelayMutation(withoutCoreOrigin(received)) : received')
- })
})
diff --git a/src/server/ws.test.ts b/src/server/ws.test.ts
index 5aec6217b..35f2f2102 100644
--- a/src/server/ws.test.ts
+++ b/src/server/ws.test.ts
@@ -86,6 +86,15 @@ describe('ws endpoint', () => {
).rejects.toThrow()
})
+ it('an authenticated browser socket is attached as the OWNER (the only way a held launch reaches it)', async () => {
+ // core/canvas-sync.ts forwards a node's machine-local held launch only owner→owner. A browser
+ // that got past the cookie check is the server's one user, and must be the owner.
+ await connect({ cookie, origin: `http://127.0.0.1:${port}` })
+ await until(() => platform.clientIds().length === 1, 'the socket attached')
+ const [uiId] = platform.clientIds()
+ expect(platform.isOwnerClient(uiId)).toBe(true)
+ })
+
it('accepts a valid cookie (same-host Origin ok), dispatches req and cast, pushes events', async () => {
platform.handle('echo:x', (v: string) => `got:${v}`)
const casts: unknown[] = []
diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.ts
index 295bd881e..63d6f7837 100644
--- a/src/shared/canvas-mutations.test.ts
+++ b/src/shared/canvas-mutations.test.ts
@@ -34,6 +34,22 @@ describe('applyCanvasMutation', () => {
applyCanvasMutation([n('1'), n('2')], { op: 'remove', id: '1' }).map((x) => x.id)
).toEqual(['2'])
})
+
+ // A held launch (`pendingLaunch`) is machine-local (@shared/node-exec). The APPEND branch is the
+ // one the Server Edition's headless factory depends on: it publishes a brand-new held node, and
+ // an owner tab must receive it WITH its launch, or that tab's next save drops the launch.
+ describe('pendingLaunch on an APPENDED node', () => {
+ const held = { after: [], command: 'claude "brief"', attempted: true, manualOnly: true }
+ it('a core-vouched upsert of a node we do not have keeps its launch', () => {
+ const out = applyCanvasMutation([n('1')], { op: 'upsert', node: { ...n('2'), pendingLaunch: held }, origin: 'core' })
+ expect(out.find((x) => x.id === '2')?.pendingLaunch).toEqual(held)
+ })
+ it('an unvouched (peer) upsert of a node we do not have drops it', () => {
+ const out = applyCanvasMutation([n('1')], { op: 'upsert', node: { ...n('2'), pendingLaunch: held } })
+ expect(out.find((x) => x.id === '2')).toBeDefined()
+ expect(out.find((x) => x.id === '2')?.pendingLaunch).toBeUndefined()
+ })
+ })
})
describe('diffToMutations', () => {
diff --git a/test/acceptance/pending-launch-reflector.test.ts b/test/acceptance/pending-launch-reflector.test.ts
new file mode 100644
index 000000000..d2710a1f3
--- /dev/null
+++ b/test/acceptance/pending-launch-reflector.test.ts
@@ -0,0 +1,143 @@
+// `pendingLaunch` (a machine-local held launch, @shared/node-exec) through the REAL core reflector
+// and into the renderer that applies what it delivered.
+//
+// CROSS-LAYER on purpose, which is why it lives here rather than in `src/`: the per-recipient
+// decision is the core's (core/canvas-sync.ts) and the apply is the renderer's (applyMutationToFlow,
+// the projects store), and production layering forbids the renderer importing core. Testing the
+// renderer half against a hand-built copy of the core's decision would stay green if the two drifted.
+import { describe, it, expect, afterEach } from 'vitest'
+import { applyMutationToFlow, nodeStatesToFlow, flowToNodeStates, type CanvasNode } from '../../src/renderer/state/workspace'
+import { useProjects } from '../../src/renderer/state/projects'
+import { launchesToFire } from '../../src/renderer/lib/pendingLaunch'
+import { stripCastNodeExec } from '../../src/shared/node-exec'
+import { applyCanvasMutation } from '../../src/shared/canvas-mutations'
+import { IPC } from '../../src/shared/ipc'
+import { initCanvasSync, publishCanvasMutation } from '../../src/core/canvas-sync'
+import { initPlatform, resetPlatformForTests, type CorePlatform } from '../../src/core/platform'
+import type { CanvasMutation, CanvasNodeState, PendingLaunch } from '../../src/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])
+
+/**
+ * The REAL reflector (core/canvas-sync.ts: `initCanvasSync` → stampMutation → fanOutMutation), on a
+ * fake platform with three clients: tab A (1) and tab B (2) are owner browser tabs of one Server
+ * Edition core, 3 is a relay-hosted guest. What each client receives is exactly what the core sent
+ * it; the renderer half then applies it. No hand-built copy of the core's per-recipient decision.
+ */
+const TAB_A = 1
+const TAB_B = 2
+const GUEST = 3
+function reflectorPlatform(owners: number[]) {
+ const sent: Array<{ to: number; m: CanvasMutation }> = []
+ let listener: ((senderId: number, ...args: unknown[]) => void) | undefined
+ const p: CorePlatform = {
+ userDataDir: '/nonexistent',
+ appVersion: '0.0.0-test',
+ isPackaged: false,
+ handle: () => {},
+ on: () => {},
+ handleWithSender: () => {},
+ onWithSender: (ch, fn) => {
+ if (ch === IPC.canvasMut) listener = fn
+ },
+ clientIds: () => [TAB_A, TAB_B, GUEST],
+ isOwnerClient: (id) => owners.includes(id),
+ sendTo: (to, channel, _projectId, m) => {
+ if (channel === IPC.canvasMut) sent.push({ to, m: m as CanvasMutation })
+ },
+ broadcast: () => {},
+ openExternal: async () => {}
+ }
+ initPlatform(p)
+ initCanvasSync()
+ return {
+ /** Client `from` casts `m`; returns what the core delivered to each client. */
+ cast(from: number, m: CanvasMutation): Map<number, CanvasMutation> {
+ sent.length = 0
+ listener?.(from, 'p1', m)
+ return new Map(sent.map((s) => [s.to, s.m]))
+ },
+ /** The core publishes `m` itself (the headless factory's path); returns each delivery. */
+ publish(m: CanvasMutation): Map<number, CanvasMutation> {
+ sent.length = 0
+ expect(publishCanvasMutation('p1', m)).toBe(true)
+ return new Map(sent.map((s) => [s.to, s.m]))
+ }
+ }
+}
+afterEach(() => resetPlatformForTests())
+
+const claimedLaunch: PendingLaunch = { ...armed, attempted: true, manualOnly: true }
+/** Tab A's cast of its claim (the write-ahead `attempted:true, manualOnly:true`), as the renderer
+ * publisher builds it. */
+const claimCast = (): CanvasMutation => ({
+ op: 'upsert',
+ node: stripCastNodeExec(flowToNodeStates(flow(state({ pendingLaunch: claimedLaunch }))))[0],
+ src: 'cv-a',
+ seq: 1
+})
+
+describe('two owner tabs on one Server Edition core: a launch is typed exactly once', () => {
+ it('an owner tab B receives A\'s claim through the reflector and does not fire', () => {
+ const got = reflectorPlatform([TAB_A, TAB_B]).cast(TAB_A, claimCast())
+ const b = applyMutationToFlow(flow(state({ pendingLaunch: armed })), got.get(TAB_B)!)
+ expect(b[0].data.pendingLaunch?.manualOnly).toBe(true)
+ expect(launchesToFire(b as never, {}, new Set(['n1']))).toEqual([])
+ })
+ it('A\'s delivery (the claim cleared) clears it on B too', () => {
+ const r = reflectorPlatform([TAB_A, TAB_B])
+ const b = applyMutationToFlow(flow(state({ pendingLaunch: claimedLaunch })), r.cast(TAB_A, { op: 'upsert', node: state(), src: 'cv-a', seq: 2 }).get(TAB_B)!)
+ expect(b[0].data.pendingLaunch).toBeUndefined()
+ })
+ it('the relay guest gets the node WITHOUT the owner\'s launch, and keeps its own', () => {
+ const got = reflectorPlatform([TAB_A, TAB_B]).cast(TAB_A, claimCast())
+ const guest = applyMutationToFlow(flow(state({ pendingLaunch: armed })), got.get(GUEST)!)
+ expect(guest[0].data.pendingLaunch).toEqual(armed)
+ })
+ it('control: if B were not an owner, it would not receive the claim and would fire a second time', () => {
+ const got = reflectorPlatform([TAB_A]).cast(TAB_A, claimCast())
+ const b = applyMutationToFlow(flow(state({ pendingLaunch: armed })), got.get(TAB_B)!)
+ expect(launchesToFire(b as never, {}, new Set(['n1'])).map((l) => l.id)).toEqual(['n1'])
+ })
+ it('a relay guest\'s cast (even stamped origin:\'core\') neither sets nor clears an owner\'s launch', () => {
+ const r = reflectorPlatform([TAB_A, TAB_B])
+ const forged: CanvasMutation = { op: 'upsert', node: state(), src: 'cv-g', seq: 1, origin: 'core' }
+ const b = applyMutationToFlow(flow(state({ pendingLaunch: armed })), r.cast(GUEST, forged).get(TAB_B)!)
+ expect(b[0].data.pendingLaunch).toEqual(armed)
+ const planted: CanvasMutation = { ...forged, node: state({ id: 'x', pendingLaunch: armed }) }
+ const b2 = applyMutationToFlow(flow(state()), r.cast(GUEST, planted).get(TAB_B)!)
+ expect(b2.find((n) => n.id === 'x')?.data.pendingLaunch).toBeUndefined()
+ })
+})
+
+describe('the core publishes a brand-new held node (Server Edition headless factory)', () => {
+ // headless-node-factory.test.ts pins that the factory publishes the held node first; this is what
+ // an owner tab does with that publish — the APPEND branch, on screen and in the store.
+ const held = (): CanvasNodeState => state({ id: 'h1', pendingLaunch: claimedLaunch })
+ it('an owner tab appends it with its launch (live canvas and a background project alike)', () => {
+ const got = reflectorPlatform([TAB_A, TAB_B]).publish({ op: 'upsert', node: held() })
+ const live = applyMutationToFlow(flow(state()), got.get(TAB_B)!)
+ expect(live.find((n) => n.id === 'h1')?.data.pendingLaunch).toEqual(claimedLaunch)
+ expect(applyCanvasMutation([state()], got.get(TAB_B)!).find((n) => n.id === 'h1')?.pendingLaunch).toEqual(claimedLaunch)
+
+ useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: [] })
+ const p = useProjects.getState().addProject('p', '/tmp/p')
+ expect(useProjects.getState().applyNodeMutation(p.id, got.get(TAB_B)!)).toBe(true)
+ expect(useProjects.getState().getProject(p.id)!.nodes.find((n) => n.id === 'h1')?.pendingLaunch).toEqual(claimedLaunch)
+ })
+ it('the relay guest appends it without the launch', () => {
+ const got = reflectorPlatform([TAB_A, TAB_B]).publish({ op: 'upsert', node: held() })
+ expect(applyMutationToFlow([], got.get(GUEST)!)[0].data.pendingLaunch).toBeUndefined()
+ })
+})