Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(launch): claim held launches in the core so two viewers never type one twice (#1224)
eneskircadeb77c68434f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0d4c5ab98..7ee045310 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4753,8 +4753,18 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile(`carryLocalNodeExec`); the reflector forwards one only between OWNER clients(`CorePlatform.isOwnerClient`: the app window, a cookie-authenticated Server Edition tab — never arelay 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+ owner→owner leg is load-bearing: it is how two Server Edition tabs converge on a launch's+ attempted/cleared state, and how a headless delivery's clear reaches the browser. **It is NOT the+ exactly-once guarantee** — it lands only after a publish → reflector → apply hop, and two tabs on+ one project both claimed a fresh node's launch inside that window and both typed it (#1173). The+ claim therefore asks the CORE first: `commitLaunchAttempt`'s `claim` → `workspace.claimLaunch`+ (`workspace:claim-launch`, `core/launch-claim-ledger.ts`, registered by `WorkspaceStore` in both+ shells, host-only). Keyed (node id, command) → the claiming CLIENT: the first claimant owns it, a+ later AUTOMATIC claim from another client answers `elsewhere` and types nothing and marks+ nothing (the writer's outcome `elsewhere` is not a failure; the canvas loop keeps it in flight),+ the owner asking again is still the owner, and a manual Run now is never refused. In memory and+ bounded (4096): a process restart forgets it, and the persisted `attempted` mark is the barrier+ then. Desktop has one renderer, so its single claimer always wins. Our OWN writesinto a background project go through `applyOwnNodeMutation` (unstripped — a cold open keeps itslaunch, a patch to `undefined` clears it); `applyNodeMutation` is the peer path (the one reducer,`applyCanvasOp`). On a Server Edition that governs a shared project, the canvas authority hearsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aeee66dd9..0ccb26e1e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -85,6 +85,12 @@ through the launch writer (`createLaunchWriter`) so a Windows-native pane can ex`data.launchIntent` instead (`pty:execute-launch`). If you add a launch input the core planner doesnot model, exclude it in `heldLaunchIntentFor`, or the Windows pane launches without it.+**Held launches are claimed by the core, not by a tab.** Every viewer of a project runs the+canvas launch loop against its own copy of the nodes, so a per-tab check cannot stop two Server+Edition tabs from typing the same launch (#1173). A launch path must claim through+`commitLaunchAttempt` with its `claim` (`workspace.claimLaunch`) and treat the `elsewhere`+outcome as "another viewer is typing it": no input, no state change, no failure.+Claude usage identity is scoped to the same config directory as its credentials. Read organizationmetadata even when credentials already include an email, and degrade to the email-only row whenmetadata cannot be read. Managed usage must never fall back to an unscoped system Keychain token:diff --git a/src/core/launch-claim-ledger.test.ts b/src/core/launch-claim-ledger.test.tsnew file mode 100644index 000000000..a10053ea1--- /dev/null+++ b/src/core/launch-claim-ledger.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest'+import { createLaunchClaimLedger } from './launch-claim-ledger'++describe('launch claim ledger (#1173)', () => {+ it('the first automatic claim of a launch wins; every later one is told another viewer owns it', () => {+ const ledger = createLaunchClaimLedger()+ expect(ledger.claim('n1', 'claude --session-id a', false, 1)).toBe('claimed')+ expect(ledger.claim('n1', 'claude --session-id a', false, 2)).toBe('elsewhere')+ expect(ledger.claim('n1', 'claude --session-id a', false, 3)).toBe('elsewhere')+ })++ it('the owner asking again is still the owner (a deferred viewer must not strand its own launch)', () => {+ const ledger = createLaunchClaimLedger()+ expect(ledger.claim('n1', 'a', false, 1)).toBe('claimed')+ expect(ledger.claim('n1', 'a', false, 1)).toBe('claimed')+ expect(ledger.claim('n1', 'a', false, 2)).toBe('elsewhere')+ })++ it('a different node or a different command is a different launch', () => {+ const ledger = createLaunchClaimLedger()+ expect(ledger.claim('n1', 'a', false, 1)).toBe('claimed')+ expect(ledger.claim('n2', 'a', false, 1)).toBe('claimed')+ expect(ledger.claim('n1', 'b', false, 1)).toBe('claimed')+ })++ it('an explicit Run now is never refused, and it records the launch for automatic claimers', () => {+ const ledger = createLaunchClaimLedger()+ expect(ledger.claim('n1', 'a', false, 1)).toBe('claimed')+ expect(ledger.claim('n1', 'a', true, 2)).toBe('claimed')+ expect(ledger.claim('n1', 'a', false, 1)).toBe('elsewhere')+ const fresh = createLaunchClaimLedger()+ expect(fresh.claim('n1', 'a', true, 1)).toBe('claimed')+ expect(fresh.claim('n1', 'a', false, 2)).toBe('elsewhere')+ })++ it('is bounded: the oldest entry is forgotten past the cap', () => {+ const ledger = createLaunchClaimLedger(2)+ ledger.claim('n1', 'a', false, 1)+ ledger.claim('n2', 'a', false, 1)+ ledger.claim('n3', 'a', false, 1)+ expect(ledger.claim('n1', 'a', false, 2)).toBe('claimed')+ expect(ledger.claim('n3', 'a', false, 2)).toBe('elsewhere')+ })++ it('malformed input is never recorded and never refused (the local barrier still applies)', () => {+ const ledger = createLaunchClaimLedger()+ expect(ledger.claim(5 as unknown as string, 'a', false, 1)).toBe('claimed')+ expect(ledger.claim('', 'a', false, 1)).toBe('claimed')+ expect(ledger.claim('n', 'x'.repeat(300_000), false, 1)).toBe('claimed')+ expect(ledger.claim('n', 'x'.repeat(300_000), false, 2)).toBe('claimed')+ })+})diff --git a/src/core/launch-claim-ledger.ts b/src/core/launch-claim-ledger.tsnew file mode 100644index 000000000..a05121096--- /dev/null+++ b/src/core/launch-claim-ledger.ts@@ -0,0 +1,64 @@+/**+ * Exactly-once claim of a renderer-delivered held launch (`pendingLaunch`), owned by the core+ * (issue #1173).+ *+ * Every owner client that shows a project runs the canvas's launch loop against its OWN copy of+ * the nodes, and the write-ahead claim (`commitLaunchAttempt`) used to be decided by that copy+ * alone, followed by a save that compares nothing. On the Server Edition two browser tabs on one+ * project therefore both claimed a fresh node's launch within milliseconds of each other and both+ * typed it — the second copy landing, unsubmitted, in the agent's input box. The owner-to-owner+ * `canvas:mut` leg that forwards `attempted: true` converges the tabs eventually; a launch needs+ * exactly once, and only the process that owns the shell can decide that atomically.+ *+ * So the claim asks HERE first. A launch is identified by (node id, command): node ids are+ * globally unique and never reused (a reopened node is a new id), and an agent launch line carries+ * a freshly minted session id. Rules:+ * - the first claim of a launch wins (`claimed`), every later AUTOMATIC claim of the same launch+ * by ANOTHER client is told another viewer owns it (`elsewhere`) and must type nothing. The+ * owner asking again is answered `claimed`: a viewer may defer after its claim (a project+ * switch inside the round trip) and must not strand its own launch — its local `attempted`+ * mark and its writer's in-flight guard already keep it from typing twice;+ * - an explicit Run now (`manual`) is a person's decision and is never refused here (the+ * renderer's own barrier still kills any half-typed line first) — it is recorded, so an+ * automatic claimer that arrives afterwards stands down;+ * - malformed input is neither recorded nor refused: refusing would only strand a launch, and the+ * local durable barrier still runs;+ * - in memory, bounded, oldest first out. A process restart forgets it, which is the right scope:+ * after a restart every viewer reconnects and the persisted `attempted` mark is the barrier.+ *+ * Desktop: one renderer, so its single claimer always wins — behaviour is unchanged. Relay tabs+ * never reach it (`commitOwnedLaunchAttempt` refuses a non-local core, and the channel is+ * host-only).+ */++export type LaunchClaimVerdict = 'claimed' | 'elsewhere'++export interface LaunchClaimLedger {+ claim(nodeId: string, command: string, manual: boolean, claimant: number): LaunchClaimVerdict+}++const MAX_NODE_ID = 256+const MAX_COMMAND = 256 * 1024+export const LAUNCH_CLAIM_LEDGER_MAX = 4096++export function createLaunchClaimLedger(max = LAUNCH_CLAIM_LEDGER_MAX): LaunchClaimLedger {+ const claimed = new Map<string, number>()+ return {+ claim(nodeId, command, manual, claimant) {+ if (typeof nodeId !== 'string' || !nodeId || nodeId.length > MAX_NODE_ID) return 'claimed'+ if (typeof command !== 'string' || !command || command.length > MAX_COMMAND) return 'claimed'+ const key = `${nodeId}\0${command}`+ const owner = claimed.get(key)+ if (owner !== undefined) {+ if (manual !== true && owner !== claimant) return 'elsewhere'+ claimed.delete(key) // re-insert as newest, owned by whoever is about to type it+ }+ claimed.set(key, claimant)+ while (claimed.size > max) {+ const oldest = claimed.keys().next().value as string+ claimed.delete(oldest)+ }+ return 'claimed'+ }+ }+}diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsindex 42b58c086..652f63fa6 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -303,6 +303,9 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([IPC.ptyExecuteLaunch,// Workspace, project settings and setup: writes, probes of arbitrary folders, trust, scripts.IPC.workspaceSave,+ // Host-only for every peer (shared/host-control.ts): a peer's claim would make every viewer of+ // the host stand down from a launch (#1173). A relay tab never sends it.+ IPC.workspaceClaimLaunch,IPC.workspaceProbeFolder,IPC.workspaceProjectFileState,IPC.projectSettingsRead,diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex 349901a00..ccb563bde 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -434,6 +434,9 @@ export const SCOPED: Readonly<Record<string, Check>> = Object.freeze({export const SCOPED_REFUSED: ReadonlySet<string> = new Set<string>([// A whole-workspace write from a peer would replace the host's other projects.IPC.workspaceSave,+ // Host-only (shared/host-control.ts): a peer's launch claim would make the host's own viewers+ // stand down from a launch (#1173). A relay tab never sends it.+ IPC.workspaceClaimLaunch,// Host-only for every peer (shared/host-control.ts): it would type a launch on the host and read// a host-local prompt file into it. A relay tab never sends it.IPC.ptyExecuteLaunch,diff --git a/src/core/workspace-store.launch-claim.test.ts b/src/core/workspace-store.launch-claim.test.tsnew file mode 100644index 000000000..cccab168b--- /dev/null+++ b/src/core/workspace-store.launch-claim.test.ts@@ -0,0 +1,20 @@+import { afterEach, expect, it } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { WorkspaceStore } from './workspace-store'+import { IPC } from '../shared/ipc'++// #1173 through the REAL store's IPC: two clients of one core (two Server Edition tabs) asking to+// claim the same held launch — the second is told another viewer owns it.+afterEach(() => resetPlatformForTests())++it('the workspace:claim-launch handler answers per client', async () => {+ const fake = fakePlatform()+ initPlatform(fake)+ new WorkspaceStore().registerIpc()+ const claim = fake.handlers[IPC.workspaceClaimLaunch]+ expect(await claim(11, 'node-1', 'claude --session-id s', false)).toBe('claimed')+ expect(await claim(12, 'node-1', 'claude --session-id s', false)).toBe('elsewhere')+ expect(await claim(11, 'node-1', 'claude --session-id s', false)).toBe('claimed')+ expect(await claim(12, 'node-1', 'claude --session-id s', true)).toBe('claimed')+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 3bc4261ec..9f3b9f334 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -43,6 +43,7 @@ import { localizeAdoptedNode } from '../shared/adopt-cwd'import { clampProjectName, folderName } from '../shared/project-name'import { SYSTEM_NODE_COLORS } from '../shared/node-colors'import { codedError } from './relay/admin-error'+import { createLaunchClaimLedger } from './launch-claim-ledger'/** What `WorkspaceStore.adoptFolder` did: the project now holding the folder, and whether this call* added it (`created: false` = an existing project already held the same real directory). */@@ -389,6 +390,8 @@ export class WorkspaceStore {* hands it out (a client that cannot save cannot be the one whose save would drop it).*/private pendingAdoptions = new Set<string>()+ /** Exactly-once claim of renderer-delivered held launches across viewers (#1173). */+ private readonly launchClaims = createLaunchClaimLedger()/** The content authority, when this process runs one (Server Edition hosting a team). */private contentAuthority: ContentAuthorityHooks | null = null@@ -421,6 +424,9 @@ export class WorkspaceStore {})platform().handle(IPC.workspaceSave, (workspace: Workspace, opts?: WorkspaceSaveOptions) =>this.saveFromRenderer(workspace, opts?.localOnly === true))+ platform().handleWithSender(IPC.workspaceClaimLaunch,+ (senderId: number, nodeId: unknown, command: unknown, manual: unknown) =>+ this.launchClaims.claim(nodeId as string, command as string, manual === true, senderId))platform().handle(IPC.workspaceProbeFolder, (folder: string) => this.probeFolder(folder))platform().handle(IPC.workspaceProjectFileState, (cwd: unknown) =>typeof cwd === 'string' && cwd ? this.projectFileState(cwd) : 'unreadable')diff --git a/src/preload/index.ts b/src/preload/index.tsindex ada8b43c6..c9296b3cb 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -163,6 +163,8 @@ const api: NodeTerminalApi = {workspace: {load: () => ipcRenderer.invoke(IPC.workspaceLoad),save: (workspace: Workspace, opts?: WorkspaceSaveOptions) => ipcRenderer.invoke(IPC.workspaceSave, workspace, opts),+ claimLaunch: (nodeId: string, command: string, manual: boolean) =>+ ipcRenderer.invoke(IPC.workspaceClaimLaunch, nodeId, command, manual),probeFolder: (folder: string) => ipcRenderer.invoke(IPC.workspaceProbeFolder, folder),projectFileState: (folder: string) => ipcRenderer.invoke(IPC.workspaceProjectFileState, folder),onMigrated: (cb: (kind: WorkspaceMigrationKind) => void) => {diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 58981073f..b2108442a 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -356,6 +356,10 @@ export function buildRealApi(const workspace: WorkspaceApi = {load: () => client.request(IPC.workspaceLoad) as Promise<Workspace>,save: (ws: Workspace, opts?: WorkspaceSaveOptions) => client.request(IPC.workspaceSave, ws, opts) as Promise<void>,+ // REAL: core's WorkspaceStore registers it, and it is the whole point on this surface — two+ // browser tabs on one project must not both type a launch (#1173).+ claimLaunch: (nodeId: string, command: string, manual: boolean) =>+ client.request(IPC.workspaceClaimLaunch, nodeId, command, manual) as Promise<'claimed' | 'elsewhere'>,// REAL: WorkspaceStore (core) registers IPC.workspaceProbeFolder, so the server serves it.// Stubbing it to `null` meant "Open folder…" on a repo that already carries a committed// .nodeterm/project.json concluded there was no project there, created an EMPTY one, and thediff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 21ad95571..abf97490f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -2649,6 +2649,13 @@ export function Canvas() {launchInFlight.current.delete(f.id)return}+ if (outcome === 'elsewhere') {+ // Another viewer of this project (a second Server Edition tab) claimed this launch and is+ // typing it (#1173). Not a failure, and nothing to retry: keep it in flight here so the+ // loop does not ask again, and let that viewer's attempted/cleared state arrive by sync.+ clearStallTimer(f.id)+ return+ }// The verified writer already exhausted its bounded echo repair. A failed launch// needs an explicit retry; unrelated hooks and remounts must never inject it later.setNodes((ns) => ns.map((n) => n.id === f.id && n.data.pendingLaunch@@ -3653,6 +3660,15 @@ export function Canvas() {pending: node.data.pendingLaunch,command,manual,+ // Exactly once across every viewer of this project (#1173): every owner tab runs this loop+ // against its OWN copy of the node, so the decision belongs to the core that owns the shell.+ claim: api.workspace.claimLaunch+ ? () => api.workspace.claimLaunch!(nodeId, command, manual)+ : undefined,+ // The claim is a round trip: decide against the node as it stands when it answers.+ current: () => canCommitCanvas(nodesProjectIdRef.current, projectId)+ ? nodesRef.current.find((n) => n.id === nodeId)?.data.pendingLaunch+ : undefined,update: (pendingLaunch) => {const next = nodesRef.current.map((n) => n.id === nodeId? { ...n, data: { ...n.data, pendingLaunch } } : n)diff --git a/src/renderer/terminal/launch-attempt.test.ts b/src/renderer/terminal/launch-attempt.test.tsindex b7895675f..d2bfe0ece 100644--- a/src/renderer/terminal/launch-attempt.test.ts+++ b/src/renderer/terminal/launch-attempt.test.ts@@ -104,3 +104,61 @@ it('acknowledges an owning local workspace only after its durable claim save', aexpect(update).toHaveBeenCalledWith({ after: [], command: 'cmd', attempted: true, manualOnly: true })expect(save).toHaveBeenCalledTimes(1)})++it('an unreachable claim falls back to the per-viewer barrier (older core, disconnect)', async () => {+ const update = vi.fn(), save = vi.fn(async () => {})+ expect(await commitLaunchAttempt({ pending: { after: [], command: 'cmd', attempted: false }, command: 'cmd', manual: false,+ update, save, claim: async () => { throw new Error('E_DISCONNECTED') } })).toBe(true)+ expect(save).toHaveBeenCalledTimes(1)+})++it('a launch that changed while the core was asked is not written over', async () => {+ let pending: PendingLaunch | undefined = { after: [], command: 'cmd', attempted: false }+ const update = vi.fn(), save = vi.fn(async () => {})+ const result = commitLaunchAttempt({ pending, current: () => pending, command: 'cmd', manual: false, update, save,+ claim: async () => { pending = { after: [], command: 'cmd', attempted: true, manualOnly: true }; return 'claimed' } })+ expect(await result).toBe(false)+ expect(update).not.toHaveBeenCalled()+})++// #1173: two viewers of one project (two Server Edition tabs) each hold their OWN copy of a fresh+// node's never-attempted launch. The per-viewer barrier alone let both claim and both type.+it('two viewers with their own copies of one launch: exactly one types it, the other stands down', async () => {+ // The core ledger's contract (src/core/launch-claim-ledger.ts, tested there): first claimant+ // owns the launch. The real ledger cannot be imported across the web/node project boundary.+ const owners = new Map<string, number>()+ const ledger = { claim: (node: string, command: string, _manual: boolean, client: number) => {+ const owner = owners.get(`${node}\0${command}`)+ if (owner !== undefined && owner !== client) return 'elsewhere' as const+ owners.set(`${node}\0${command}`, client)+ return 'claimed' as const+ } }+ const typed: string[] = []+ const viewer = (client: number) => {+ let pending: PendingLaunch | undefined = { after: [], command: 'claude --session-id s', attempted: false }+ const update = vi.fn((next: PendingLaunch) => { pending = next })+ let echo: ((d: string) => void) | undefined+ const writer = createLaunchWriter({+ shellReady: async () => true, killLine: '\x15', cleanup: () => {},+ io: { write: (d) => { typed.push(`${client}:${d}`); if (d.endsWith('\r')) return; echo?.(d) },+ onData: (cb) => { echo = cb; return () => {} } },+ claimAttempt: (manual, command) => commitLaunchAttempt({+ pending, current: () => pending, command, manual, update, save: async () => {},+ claim: async () => ledger.claim('node', command, manual, client)+ })+ })+ return { writer, update, pending: () => pending }+ }+ const a = viewer(1), b = viewer(2)+ const [ra, rb] = await Promise.all([a.writer('claude --session-id s', false), b.writer('claude --session-id s', false)])+ expect([ra, rb].filter((o) => o === 'elsewhere')).toHaveLength(1)+ expect(typed.filter((t) => t.startsWith('2:'))).toEqual([])+ expect(typed.some((t) => t.startsWith('1:claude'))).toBe(true)+ // The viewer that stood down leaves its copy untouched (no ⚠ manualOnly over someone else's launch).+ expect(b.update).not.toHaveBeenCalled()+ expect(b.pending()).toMatchObject({ attempted: false })+ expect(b.pending()?.manualOnly).toBeUndefined()+ // And it keeps standing down: an automatic retry is not a failure, and types nothing.+ expect(await b.writer('claude --session-id s', false)).toBe('elsewhere')+ expect(typed.filter((t) => t.startsWith('2:'))).toEqual([])+})diff --git a/src/renderer/terminal/launch-attempt.ts b/src/renderer/terminal/launch-attempt.tsindex 077765d38..24a575769 100644--- a/src/renderer/terminal/launch-attempt.ts+++ b/src/renderer/terminal/launch-attempt.ts@@ -1,6 +1,8 @@import type { PendingLaunch } from '@shared/types'-export type LaunchClaim = boolean | 'deferred'+/** `'elsewhere'`: the core says another viewer of this project already claimed this launch+ * (issue #1173) — type nothing, change nothing, and do not report a failure. */+export type LaunchClaim = boolean | 'deferred' | 'elsewhere'type Commit = (id: string, command: string, manual: boolean) => Promise<LaunchClaim>const commits = new WeakMap<object, Commit>()export function registerLaunchCommit(scope: object, commit: Commit): () => void {@@ -18,10 +20,29 @@ export async function commitLaunchAttempt(opts: {manual: booleanupdate(pending: PendingLaunch): voidsave(): Promise<void>-}): Promise<boolean> {- if (!opts.pending || opts.pending.command !== opts.command) return false- if (!opts.manual && opts.pending.attempted !== false) return false- opts.update({ ...opts.pending, attempted: true, manualOnly: true })+ /**+ * The core's exactly-once claim across every viewer of the project (#1173,+ * `WorkspaceApi.claimLaunch`). Asked after the local check passes and before anything is+ * marked: a viewer told `'elsewhere'` leaves its copy exactly as it was — the owner's+ * `attempted`/cleared state reaches it over the canvas sync. A claim that cannot be asked (an+ * older core, a dropped socket) falls back to the per-viewer barrier, which is the old behaviour.+ */+ claim?(): Promise<'claimed' | 'elsewhere'>+ /** The launch as it stands NOW, re-read after the claim's round trip. Defaults to `pending`. */+ current?(): PendingLaunch | undefined+}): Promise<boolean | 'elsewhere'> {+ const fits = (p: PendingLaunch | undefined): p is PendingLaunch =>+ !!p && p.command === opts.command && (opts.manual || p.attempted === false)+ if (!fits(opts.pending)) return false+ let pending: PendingLaunch | undefined = opts.pending+ if (opts.claim) {+ let verdict: 'claimed' | 'elsewhere' = 'claimed'+ try { verdict = await opts.claim() } catch { /* fail open to the local barrier */ }+ if (verdict === 'elsewhere') return 'elsewhere'+ pending = opts.current ? opts.current() : opts.pending+ if (!fits(pending)) return false+ }+ opts.update({ ...pending, attempted: true, manualOnly: true })try {await opts.save()return true@@ -35,6 +56,6 @@ export async function commitLaunchAttempt(opts: {* Canvas mutation broadcasts have no durable acknowledgment. Refuse until a scoped durable* operation exists; this applies to explicit retry as well as automatic launch. */export function commitOwnedLaunchAttempt(owner: object, local: object,- opts: Parameters<typeof commitLaunchAttempt>[0]): Promise<boolean> {+ opts: Parameters<typeof commitLaunchAttempt>[0]): Promise<boolean | 'elsewhere'> {return owner === local ? commitLaunchAttempt(opts) : Promise.resolve(false)}diff --git a/src/renderer/terminal/launch-claim-wiring.test.ts b/src/renderer/terminal/launch-claim-wiring.test.tsnew file mode 100644index 000000000..957a071a2--- /dev/null+++ b/src/renderer/terminal/launch-claim-wiring.test.ts@@ -0,0 +1,27 @@+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { expect, it } from 'vitest'++// #1173: the cross-viewer launch claim is optional at every hop (an older core, a test double), so+// a dropped hop compiles and ships the fix inert. Pin each hop at source level.+const read = (p: string) => readFileSync(join(__dirname, '../../..', p), 'utf8').replace(/\r\n/g, '\n')++it('core registers the claim channel, keyed by the asking client', () => {+ expect(read('src/core/workspace-store.ts')).toMatch(+ /handleWithSender\(IPC\.workspaceClaimLaunch,[\s\S]{0,200}this\.launchClaims\.claim\([^)]*senderId\)/)+})++it('both shells reach it: desktop preload and the Server Edition bridge', () => {+ expect(read('src/preload/index.ts')).toMatch(/claimLaunch:[\s\S]{0,120}IPC\.workspaceClaimLaunch/)+ expect(read('src/renderer/bridge/ws-bridge.ts')).toMatch(/claimLaunch:[\s\S]{0,120}IPC\.workspaceClaimLaunch/)+})++it('the canvas launch claim asks the core before it marks anything', () => {+ const canvas = read('src/renderer/canvas/Canvas.tsx')+ expect(canvas).toMatch(/claim: api\.workspace\.claimLaunch[\s\S]{0,80}api\.workspace\.claimLaunch!\(nodeId, command, manual\)/)+ expect(canvas).toMatch(/if \(outcome === 'elsewhere'\)/)+})++it('a relay peer can never claim (or block) a host launch', () => {+ expect(read('src/shared/host-control.ts')).toMatch(/IPC\.workspaceClaimLaunch/)+})diff --git a/src/renderer/terminal/launch-command.ts b/src/renderer/terminal/launch-command.tsindex 70bfb8314..7b09aded1 100644--- a/src/renderer/terminal/launch-command.ts+++ b/src/renderer/terminal/launch-command.ts@@ -5,7 +5,9 @@ import { deliverCommand, type DeliveryIo, type DeliveryOutcome } from '@shared/c// A writer belongs to the PTY lifetime (including a parked view), not a Canvas render.// A durable write-ahead claim distinguishes a never-attempted warm launch from an uncertain// earlier submission whose clearing autosave may have been lost.-type LaunchOutcome = DeliveryOutcome | 'deferred'+// `'elsewhere'`: another viewer of the project claimed this launch (#1173); nothing was typed and+// nothing failed.+type LaunchOutcome = DeliveryOutcome | 'deferred' | 'elsewhere'type Writer = (command: string, manual: boolean) => Promise<LaunchOutcome>const defaultScope = {}const scopedWriters = new WeakMap<object, Map<string, Writer>>()@@ -44,6 +46,7 @@ export function createLaunchWriter(opts: {execute?(command: string, manual: boolean): Promise<DeliveryOutcome | 'fallback'>}): Writer {let attempted = false+ let elsewhere = falselet submitted = falselet inFlight: Promise<LaunchOutcome> | undefinedlet disposed = false@@ -51,11 +54,18 @@ export function createLaunchWriter(opts: {return (command, manual) => {if (submitted) return Promise.resolve('submitted') // stale UI/save; never paste twiceif (inFlight) return inFlight+ // Another viewer owns this launch: an automatic retry stands down again rather than reading+ // as a failure. Run now (manual) still goes through, as everywhere else.+ if (!manual && elsewhere && !disposed) return Promise.resolve('elsewhere')if (disposed || (!manual && attempted)) return Promise.resolve('cancelled')inFlight = (async () => {if (!(await opts.shellReady(manual)) || disposed) return 'cancelled' as constconst claim = await opts.claimAttempt(manual, command)if (claim === 'deferred' && !disposed) return 'deferred' as const+ if (claim === 'elsewhere' && !disposed) {+ elsewhere = true+ return 'elsewhere' as const+ }if (!claim || disposed) return 'cancelled' as constattempted = true// Saving can take a remote round trip. Recheck after the barrier, before any input.@@ -106,6 +116,12 @@ export function deliverInitialLaunch(command: string, opts: {opts.whenReady(() => {void opts.write(command, false).then((outcome) => {if (outcome === 'deferred') return // no input/claim; retain never-attempted intent+ if (outcome === 'elsewhere') {+ // Another viewer of this project claimed and is typing it (#1173). Drop only the live+ // alias; the durable record converges from that viewer over the canvas sync.+ opts.update({ initialCommand: undefined })+ return+ }opts.update({ initialCommand: undefined,pendingLaunch: outcome === 'submitted' ? undefined : { ...pendingLaunch, attempted: true, manualOnly: true } })if (outcome !== 'submitted') opts.onFailure(outcome)diff --git a/src/renderer/terminal/relay-initial-launch.ts b/src/renderer/terminal/relay-initial-launch.tsindex 3a814c99d..104cc758d 100644--- a/src/renderer/terminal/relay-initial-launch.ts+++ b/src/renderer/terminal/relay-initial-launch.ts@@ -30,7 +30,8 @@ export function deliverRelayInitialLaunch(opts: {if (fired) returnfired = truevoid write(opts.command, false).then((outcome) => {- if (outcome !== 'submitted' && outcome !== 'deferred') opts.onFailure(outcome)+ // Its claim always answers true, so `elsewhere` cannot come back here.+ if (outcome !== 'submitted' && outcome !== 'deferred' && outcome !== 'elsewhere') opts.onFailure(outcome)})})}diff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex 73745e8ba..1948ddaa6 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -81,6 +81,9 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([IPC.projectSetupConsentSubmit,IPC.projectSetupRequestTrust,IPC.ptyLaunchHeadless,+ // A relay peer never delivers a held launch (commitOwnedLaunchAttempt), and a peer that could+ // claim one would make every viewer of the host stand down from it (#1173).+ IPC.workspaceClaimLaunch,// Executes an agent launch on the host and reads a host-local `--prompt-file` into it. A relay// tab never sends it (its pty bridge omits the member); this holds the refusal host-side too.IPC.ptyExecuteLaunch,diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex b1a03725c..ddac4b0ca 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -459,6 +459,9 @@ export const IPC = {ptyResync: (sessionId: string) => `pty:resync:${sessionId}`,workspaceLoad: 'workspace:load',workspaceSave: 'workspace:save',+ /** Exactly-once claim of a renderer-delivered held launch across every viewer of a project+ * (core/launch-claim-ledger.ts, issue #1173). Host-only. */+ workspaceClaimLaunch: 'workspace:claim-launch',workspaceProbeFolder: 'workspace:probe-folder',/** Is a folder's .nodeterm/project.json present / absent / unreadable — the distinction* `probeFolder`'s null collapses. Recovery of an `unavailable` project needs it (issue #385). */diff --git a/src/shared/types.ts b/src/shared/types.tsindex ae783de0f..28a9b2612 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1441,6 +1441,13 @@ export interface WorkspaceApi {* round trips (the mirror is owed and rides the next ordinary save). For a write-ahead barrier* that must be durable here but must not wait on a remote host — see WorkspaceStore.save. */save(workspace: Workspace, opts?: WorkspaceSaveOptions): Promise<void>+ /**+ * Ask the core to claim one held launch (node id + command) before any viewer types it+ * (issue #1173): `claimed` = this viewer delivers it, `elsewhere` = another viewer of the same+ * project already claimed it, type nothing. A manual Run now is never refused. Optional: a+ * client without it (an older core, a test double) keeps the per-viewer barrier alone.+ */+ claimLaunch?(nodeId: string, command: string, manual: boolean): Promise<'claimed' | 'elsewhere'>/** Reads <folder>/.nodeterm/project.json and returns the assembled Project (cwd resolved), or null. */probeFolder(folder: string): Promise<Project | null>/** Whether <folder>/.nodeterm/project.json is `present`, definitely `absent`, or `unreadable`