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(project-setup): per-run runId + bidi-safe dialog + ack-attached run lanes
enes55168fc2dad6
diff --git a/src/core/project-setup-service.test.ts b/src/core/project-setup-service.test.tsindex 156aead44..c02fce03f 100644--- a/src/core/project-setup-service.test.ts+++ b/src/core/project-setup-service.test.ts@@ -12,7 +12,8 @@ import {type ProjectSettingsSnapshot,type ProjectLocalSettings,type ProjectSetupConsentRequest,- type ProjectSetupEvent+ type ProjectSetupEvent,+ type ProjectSetupRunResult} from '../shared/project-settings'import { IPC } from '../shared/ipc'import {@@ -100,6 +101,34 @@ describe('setupRunKey', () => {})describe('ProjectSetupService — local-sourced scripts', () => {+ it('mints a FRESH runId per launch, while the runKey (the single-flight key) stays deterministic', async () => {+ const { runner } = recorder()+ const svc = new ProjectSetupService({+ trust: new ProjectTrustStore(),+ readSettings: async () => snapshot(null, { setup: { setupScript: 'echo hi' } }),+ runLocal: runner+ })+ const first = await svc.run(target(), 'setup')+ await vi.waitFor(() => expect(events().some((e) => e.state === 'done')).toBe(true))+ const second = await svc.run(target(), 'setup')+ await vi.waitFor(() => expect(events().filter((e) => e.state === 'done')).toHaveLength(2))++ expect(first.status).toBe('started')+ expect(second.status).toBe('started')+ const a = first as Extract<ProjectSetupRunResult, { status: 'started' }>+ const b = second as Extract<ProjectSetupRunResult, { status: 'started' }>+ // Same script, same location => the SAME single-flight key (that is what makes a concurrent+ // second launch `busy`)...+ expect(b.runKey).toBe(a.runKey)+ // ...and a DIFFERENT run identity, because both runs' `seq` counters start at 1 and a client+ // folding on runKey alone would swallow the second run as the first one's stale tail.+ expect(b.runId).not.toBe(a.runId)+ const ids = new Set(events().map((e) => e.runId))+ expect(ids).toEqual(new Set([a.runId, b.runId]))+ // Each run numbers its own events from 1.+ expect(events().filter((e) => e.runId === b.runId).map((e) => e.seq)).toEqual([1, 2, 3])+ })+it('runs a local-sourced script without any consent prompt', async () => {const { calls, runner } = recorder()const svc = new ProjectSetupService({@@ -108,7 +137,14 @@ describe('ProjectSetupService — local-sourced scripts', () => {runLocal: runner})const res = await svc.run(target(), 'setup')- expect(res).toEqual({ status: 'started', runKey: setupRunKey(target(), 'setup'), waitForSetup: true })+ // `runId` is a fresh uuid per launch (unlike the deterministic runKey), so it is matched by+ // shape: it is what tells this run from the NEXT run of the same script.+ expect(res).toEqual({+ status: 'started',+ runKey: setupRunKey(target(), 'setup'),+ runId: expect.any(String),+ waitForSetup: true+ })expect(consentRequests()).toEqual([])await vi.waitFor(() => expect(events().some((e) => e.state === 'done')).toBe(true))@@ -475,7 +511,7 @@ describe('registerProjectSetupHandlers', () => {const service = {run: async (t: ProjectSetupTarget, kind: 'setup' | 'archive') => {runs.push([t, kind])- return { status: 'started', runKey: 'k', waitForSetup: false } as const+ return { status: 'started', runKey: 'k', runId: 'run-1', waitForSetup: false } as const},cancel: (runKey: string) => {cancels.push(runKey)diff --git a/src/core/project-setup-service.ts b/src/core/project-setup-service.tsindex 727ca0f03..cca769e68 100644--- a/src/core/project-setup-service.ts+++ b/src/core/project-setup-service.ts@@ -110,6 +110,9 @@ function locationLabel(target: ProjectSetupTarget): string {interface ActiveRun {runKey: string+ /** Unique per launch, unlike `runKey` (which is the deterministic single-flight key). Every event+ * carries it so a client can tell this run from the PREVIOUS run of the same script. */+ runId: stringprojectId: stringkind: ProjectSetupKindabort: AbortController@@ -142,7 +145,7 @@ export class ProjectSetupService {// Claimed BEFORE the consent await on purpose: while a dialog for this location is open, a// second launch must be `busy`, not a second dialog asking about the same script.- const entry: ActiveRun = { runKey, projectId: target.projectId, kind, abort: new AbortController(), seq: 0, closed: false }+ const entry: ActiveRun = { runKey, runId: randomUUID(), projectId: target.projectId, kind, abort: new AbortController(), seq: 0, closed: false }this.active.set(runKey, entry)const abandon = (reason: 'declined' | 'unanswered' | 'unavailable' | 'no-script'): ProjectSetupRunResult => {this.active.delete(runKey)@@ -190,7 +193,14 @@ export class ProjectSetupService {if (entry.abort.signal.aborted) return abandon('declined')void this.execute(entry, runner, script, target)- return { status: 'started', runKey, waitForSetup: resolved.setup.waitForSetup?.value === true }+ // `runId` travels back with the ack so the initiator can attach THIS run (not the previous run+ // of the same script, which shares `runKey`) to its own lane.+ return {+ status: 'started',+ runKey,+ runId: entry.runId,+ waitForSetup: resolved.setup.waitForSetup?.value === true+ }}/** Aborts a run — live OR still waiting at its consent dialog. `false` = nothing by that runKey@@ -302,12 +312,18 @@ export class ProjectSetupService {entry.closed = true}- private emit(entry: ActiveRun, ev: Omit<ProjectSetupEvent, 'runKey' | 'kind' | 'seq'>): void {+ private emit(entry: ActiveRun, ev: Omit<ProjectSetupEvent, 'runKey' | 'runId' | 'kind' | 'seq'>): void {// A chunk arriving after the terminal event (a runner that keeps draining) would reopen a run// the UI has already closed out.if (entry.closed) returnentry.seq += 1- const full: ProjectSetupEvent = { runKey: entry.runKey, kind: entry.kind, seq: entry.seq, ...ev }+ const full: ProjectSetupEvent = {+ runKey: entry.runKey,+ runId: entry.runId,+ kind: entry.kind,+ seq: entry.seq,+ ...ev+ }platform().broadcast(IPC.projectSetupEvent(entry.projectId), full)}}diff --git a/src/renderer/components/SetupConsentDialog.test.tsx b/src/renderer/components/SetupConsentDialog.test.tsxindex 1005d01a0..4809b41ac 100644--- a/src/renderer/components/SetupConsentDialog.test.tsx+++ b/src/renderer/components/SetupConsentDialog.test.tsx@@ -257,6 +257,40 @@ describe('SetupConsentDialog', () => {expect(shown).toContain('\u2026')})+ it('I2: strips BIDI OVERRIDES and zero-width marks from the labels — a name must not misrender', () => {+ mount()+ act(() =>+ emitRequest(+ request({+ // The presence-name attack, aimed at a trust dialog instead: U+202E reverses everything+ // after it, so this location DISPLAYS as something other than what it inspects as. Same+ // class, same reasoning as shared/presence.ts's UNSAFE_NAME_CHARS.+ projectName: 'safe-repo\u202eevil',+ locationLabel: '~/code/\u200bap\ufeffp'+ })+ )+ )+ const shown = text()+ expect(shown).not.toContain('\u202e')+ expect(shown).not.toContain('\u200b')+ expect(shown).not.toContain('\ufeff')+ // Every VISIBLE character survives — the strip removes only what has no glyph.+ expect(shown).toContain('safe-repoevil')+ expect(shown).toContain('~/code/app')+ })++ it('I2: pins the script boxes to byte order, so a Trojan-source U+202E cannot reorder what is approved', () => {+ mount()+ // The bytes are NOT altered — this is what will run, and it must be shown verbatim — so the+ // defence is presentational: bidi-override forces the display order to the byte order.+ const body = 'rm -rf /\u202e # elbmaerp'+ act(() => emitRequest(request({ scripts: { setup: body } })))+ const pre = scripts()[0]+ expect(pre.textContent).toBe(body)+ expect(pre.style.unicodeBidi).toBe('bidi-override')+ expect(pre.style.direction).toBe('ltr')+ })+it('renders the script bodies VERBATIM — they are what the approval covers', () => {mount()act(() => emitRequest(request({ scripts: { setup: 'echo "<img src=x>"\nmake install' } })))diff --git a/src/renderer/components/SetupConsentDialog.tsx b/src/renderer/components/SetupConsentDialog.tsxindex 7ff28af87..fd2b271f6 100644--- a/src/renderer/components/SetupConsentDialog.tsx+++ b/src/renderer/components/SetupConsentDialog.tsx@@ -29,11 +29,16 @@ import { ConfirmDialog } from './ConfirmDialog'* that a stranger may have written (a cloned repo, a teammate's commit). The rule here is TEXT* ONLY: they are rendered as React text children (never interpolated into markup, a template that* gets parsed, a `title`/`href`, or anything handed to a terminal) and they are clamped by- * `safeLabel` first — control characters stripped and the length capped — so neither an ANSI- * escape run nor a 50 KB name can rewrite or overflow the dialog that is asking the question. The- * SCRIPT BODIES are deliberately NOT clamped: they are the thing being approved, and truncating- * them would mean the user approves bytes that were never on screen. They are rendered as text in- * a scrollable `<pre>`, which is inert.+ * `safeLabel` first — control characters, bidi overrides and zero-width marks stripped, then the+ * length capped — so neither an ANSI escape run, a U+202E that reverses the location, nor a 50 KB+ * name can rewrite or overflow the dialog that is asking the question.+ *+ * The SCRIPT BODIES are deliberately NOT clamped: they are the thing being approved, and stripping+ * or truncating them would mean the user approves bytes that were never on screen. They are+ * rendered as text in a scrollable `<pre>`, which is inert — and that `<pre>` carries+ * `unicode-bidi: bidi-override; direction: ltr`, which defeats Trojan-source reordering (a U+202E+ * inside a script making a comment read as executable code, or vice versa) by pinning the DISPLAY+ * order to the byte order, WITHOUT altering a single byte of what is approved and run.** KNOWN GAP (documented here, not fixable from this side — final-wave decision): a relay guest can* currently dispatch `project-setup:run` AND `project-setup:consent-submit` on the host@@ -47,10 +52,22 @@ import { ConfirmDialog } from './ConfirmDialog'/** Longest a name/location may be on screen, in characters. */export const SETUP_LABEL_MAX = 200-/** Clamp for a cross-boundary label: control characters out (see `oneLine` — a name is one line of- * text and no control character has a glyph), then capped with an ellipsis. */+/**+ * Characters a cross-boundary LABEL may never contain — the same class, for the same reason, that+ * `capName` strips from a presence display name (`src/shared/presence.ts`, `UNSAFE_NAME_CHARS`,+ * where the rationale is written out): a bidi override (U+202E) reverses everything after it, so+ * "app" + U+202E + "hs.live-nur" DISPLAYS as a different location than the one that inspects out+ * of the file, and the zero-width marks/isolates (U+200B-200F, U+2066-2069, U+FEFF) do the same+ * job invisibly. Replicated rather than imported because that constant is private to the presence+ * module and its cap (`capName`) is a different one; keep the two in step.+ */+const UNSAFE_LABEL_CHARS = /[\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g++/** Clamp for a cross-boundary label: control characters out (see `oneLine` — a label is one line of+ * text and no control character has a glyph), then the bidi/zero-width spoofing set out, then+ * capped with an ellipsis. */function safeLabel(raw: string): string {- const flat = oneLine(raw)+ const flat = oneLine(raw.replace(UNSAFE_LABEL_CHARS, '')).trim()return flat.length > SETUP_LABEL_MAX ? flat.slice(0, SETUP_LABEL_MAX - 1) + '…' : flat}@@ -127,8 +144,12 @@ export function SetupConsentDialog(): React.JSX.Element | null {<p className="text-[12px] font-semibold text-text">{KIND_LABEL[s.kind]} script{s.kind === head.kind ? ' (about to run)' : ''}</p>- {/* Text child, never markup — and never truncated: this is what is being approved. */}+ {/* Text child, never markup — and never truncated: this is what is being approved.+ `bidi-override`/`ltr` pins the DISPLAY order to the byte order, so a U+202E in the+ script cannot make the reader see a different program than the one that will run+ (Trojan source). It changes nothing about the bytes themselves. */}<pre+ style={{ unicodeBidi: 'bidi-override', direction: 'ltr' }}data-script-kind={s.kind}className={`max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-md border px-2.5 py-2 font-mono text-[12px] leading-relaxed text-text ${s.kind === head.kind ? 'border-accent bg-bg' : 'border-border bg-bg opacity-80'diff --git a/src/renderer/components/settings/ProjectSettingsFamilies.tsx b/src/renderer/components/settings/ProjectSettingsFamilies.tsxindex a1abbefc9..67532a9a9 100644--- a/src/renderer/components/settings/ProjectSettingsFamilies.tsx+++ b/src/renderer/components/settings/ProjectSettingsFamilies.tsx@@ -413,13 +413,16 @@ function SetupRunControls({canRun: booleanhasScript: Record<ProjectSetupKind, boolean>}): React.JSX.Element {- const run = useProjectSetup((s) => s.byProject[projectId])+ // Resolved through the ATTACHMENT this component made at ack time, not through "whatever event+ // arrived on the channel we subscribed to": events carry no lane discriminator, so a worktree's+ // run and this panel's run are told apart only by who claimed which runKey.+ const attached = useProjectSetup((s) => s.runForProject(projectId))const [busy, setBusy] = useState<'' | ProjectSetupKind | 'cancel'>('')const [notice, setNotice] = useState('')- /** The runKey main acknowledged, held until the store reports that run reaching a terminal- * state. Without it the buttons flicker back to enabled in the window between the ack and the- * first event — and that window contains the consent dialog, which can be minutes long. */- const [startedKey, setStartedKey] = useState<string | null>(null)+ /** The run main acknowledged, held until the store reports THAT run (by `runId`). `runKey` alone+ * will not do: it is deterministic, so the entry sitting under it may still be the PREVIOUS run+ * of the same script — showing its exit badge over a script that is starting right now. */+ const [started, setStarted] = useState<{ runKey: string; runId: string } | null>(null)const unsubRef = useRef<(() => void) | null>(null)useEffect(() => () => {@@ -429,9 +432,12 @@ function SetupRunControls({[])- const awaitingStarted = startedKey !== null && (!run || run.runKey !== startedKey)+ // The acked run's first event has not landed yet, so what sits in the lane (if anything) is the+ // PREVIOUS run of the same script. It is not ours to show.+ const awaitingStarted = started !== null && attached?.runId !== started.runId+ const run = awaitingStarted ? undefined : attachedconst active = busy !== '' || run?.state === 'running' || awaitingStarted- const liveKey = run?.state === 'running' ? run.runKey : awaitingStarted ? startedKey : null+ const liveKey = run?.state === 'running' ? run.runKey : awaitingStarted ? started.runKey : nullconst start = async (kind: ProjectSetupKind): Promise<void> => {setNotice('')@@ -440,8 +446,14 @@ function SetupRunControls({if (!unsubRef.current) unsubRef.current = useProjectSetup.getState().subscribeProject(projectId)try {const res = await window.nodeTerminal.projectSetup.run(projectId, kind, undefined)- if (res.status === 'skipped') setNotice(SKIP_NOTE[res.reason])- else setStartedKey(res.runKey)+ if (res.status === 'skipped') {+ setNotice(SKIP_NOTE[res.reason])+ return+ }+ // Claim the lane with the runKey main gave us — this is what makes the events ours rather+ // than some other initiator's, and it is why `attachProject` takes the ACKED key.+ useProjectSetup.getState().attachProject(projectId, res.runKey)+ setStarted({ runKey: res.runKey, runId: res.runId })} catch {setNotice('Could not start the script — the project may have become unavailable.')} finally {@@ -458,7 +470,9 @@ function SetupRunControls({the truth about whether it ended. */} finally {setBusy('')- setStartedKey(null)+ // Stop waiting for an acked run we just asked to die: from here the event stream (a+ // `cancelled`, or a terminal event that beat the cancel) owns what the box shows.+ setStarted(null)}}diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsxindex eb2c83a28..919249c68 100644--- a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx@@ -795,8 +795,8 @@ describe('ProjectSettingsSection — setup run controls', () => {beforeEach(() => {host = document.createElement('div')document.body.appendChild(host)- useProjectSetup.setState({ byProject: {}, byGroup: {} })- runSetup = vi.fn(async () => ({ status: 'started', runKey: 'run-1', waitForSetup: false }))+ useProjectSetup.setState({ byRunKey: {}, projectRunKey: {}, groupRunKey: {} })+ runSetup = vi.fn(async () => ({ status: 'started', runKey: 'rk-setup', runId: 'run-a', waitForSetup: false }))cancel = vi.fn(async () => true)off = vi.fn()onEvent = vi.fn((_projectId: string, cb: (ev: ProjectSetupEvent) => void) => {@@ -814,7 +814,7 @@ describe('ProjectSettingsSection — setup run controls', () => {act(() => root.unmount())host.remove()useProjects.setState({ projects: [], activeProjectId: '' })- useProjectSetup.setState({ byProject: {}, byGroup: {} })+ useProjectSetup.setState({ byRunKey: {}, projectRunKey: {}, groupRunKey: {} })})it('runs the setup script for this project, SUBSCRIBING to the event channel first', async () => {@@ -860,7 +860,7 @@ describe('ProjectSettingsSection — setup run controls', () => {await act(async () => {button('Run setup').click()})- act(() => emit({ runKey: 'run-1', kind: 'setup', seq: 1, state: 'running', chunk: 'compiling…\n' }))+ act(() => emit({ runKey: 'rk-setup', runId: 'run-a', kind: 'setup', seq: 1, state: 'running', chunk: 'compiling…\n' }))expect(log()!.textContent).toContain('compiling…')expect(button('Run setup').disabled).toBe(true)expect(button('Run archive').disabled).toBe(true)@@ -872,11 +872,11 @@ describe('ProjectSettingsSection — setup run controls', () => {await act(async () => {button('Run setup').click()})- act(() => emit({ runKey: 'run-1', kind: 'setup', seq: 1, state: 'running', chunk: 'x' }))+ act(() => emit({ runKey: 'rk-setup', runId: 'run-a', kind: 'setup', seq: 1, state: 'running', chunk: 'x' }))await act(async () => {button('Cancel').click()})- expect(cancel).toHaveBeenCalledWith('run-1')+ expect(cancel).toHaveBeenCalledWith('rk-setup')})it('reports the exit code when the run ends, and re-enables the buttons', async () => {@@ -884,8 +884,8 @@ describe('ProjectSettingsSection — setup run controls', () => {await act(async () => {button('Run setup').click()})- act(() => emit({ runKey: 'run-1', kind: 'setup', seq: 1, state: 'running', chunk: 'boom\n' }))- act(() => emit({ runKey: 'run-1', kind: 'setup', seq: 2, state: 'failed', exitCode: 2 }))+ act(() => emit({ runKey: 'rk-setup', runId: 'run-a', kind: 'setup', seq: 1, state: 'running', chunk: 'boom\n' }))+ act(() => emit({ runKey: 'rk-setup', runId: 'run-a', kind: 'setup', seq: 2, state: 'failed', exitCode: 2 }))expect(host.textContent).toContain('2')expect(host.textContent?.toLowerCase()).toContain('failed')expect(button('Run setup').disabled).toBe(false)@@ -902,6 +902,58 @@ describe('ProjectSettingsSection — setup run controls', () => {expect(button('Run setup').disabled).toBe(false)})+ it('C1: a SECOND run of the same script (same runKey, new runId) resets the box and re-disables the buttons', async () => {+ await mountPanel(snapshotWith({ setupScript: 'make' }))+ await act(async () => {+ button('Run setup').click()+ })+ act(() => emit({ runKey: 'rk-setup', runId: 'run-a', kind: 'setup', seq: 1, state: 'running', chunk: 'first run\n' }))+ act(() => emit({ runKey: 'rk-setup', runId: 'run-a', kind: 'setup', seq: 2, state: 'failed', exitCode: 1 }))+ expect(button('Run setup').disabled).toBe(false)+ expect(host.textContent).toContain('Failed (exit 1)')++ // Run it again. `runKey` is DETERMINISTIC (kind + location), so the second run re-uses it and+ // its `seq` restarts at 1 — the exact shape that used to be swallowed as stale, leaving the+ // failed badge standing over a live script.+ runSetup.mockResolvedValue({ status: 'started', runKey: 'rk-setup', runId: 'run-b', waitForSetup: false })+ await act(async () => {+ button('Run setup').click()+ })+ // Between the ack and the first event the lane still holds run A: it must not be shown.+ expect(button('Run setup').disabled).toBe(true)+ expect(host.textContent).not.toContain('Failed (exit 1)')++ act(() => emit({ runKey: 'rk-setup', runId: 'run-b', kind: 'setup', seq: 1, state: 'running', chunk: 'second run\n' }))+ expect(log()!.textContent).toContain('second run')+ expect(log()!.textContent).not.toContain('first run')+ expect(button('Run setup').disabled).toBe(true)+ act(() => emit({ runKey: 'rk-setup', runId: 'run-b', kind: 'setup', seq: 2, state: 'done', exitCode: 0 }))+ expect(host.textContent).toContain('Finished (exit 0)')+ expect(button('Run setup').disabled).toBe(false)+ })++ it('I3: an event stream for a runKey this panel never claimed does not surface here', async () => {+ await mountPanel(snapshotWith({ setupScript: 'make' }))+ await act(async () => {+ button('Run setup').click()+ })+ // A worktree's run for the same project, on the same channel: it carries no lane+ // discriminator, and only the ATTACHMENT (this panel claimed 'rk-setup') keeps it out.+ act(() => emit({ runKey: 'rk-worktree', runId: 'run-w', kind: 'setup', seq: 1, state: 'running', chunk: 'someone else\n' }))+ expect(log()).toBeNull()+ act(() => emit({ runKey: 'rk-setup', runId: 'run-a', kind: 'setup', seq: 1, state: 'running', chunk: 'mine\n' }))+ expect(log()!.textContent).toContain('mine')+ expect(log()!.textContent).not.toContain('someone else')+ })++ it('attaches the ACKED runKey to this project’s lane', async () => {+ await mountPanel(snapshotWith({ setupScript: 'make' }))+ await act(async () => {+ button('Run setup').click()+ })+ expect(useProjectSetup.getState().projectRunKey.p1).toBe('rk-setup')+ })+it('drops the subscription when the pane goes away', async () => {await mountPanel(snapshotWith({ setupScript: 'make' }))await act(async () => {diff --git a/src/renderer/state/projectSetup.test.ts b/src/renderer/state/projectSetup.test.tsindex 7e7268642..6ac9035d7 100644--- a/src/renderer/state/projectSetup.test.ts+++ b/src/renderer/state/projectSetup.test.ts@@ -1,34 +1,48 @@// @vitest-environment jsdom//-// The renderer's view of a setup/archive run. Everything here exists because the event stream is a-// LOSSY, RE-ORDERABLE wire: `ProjectSetupEvent.seq` is monotonic per run precisely so a client can-// tell a duplicate (relay re-delivery) from a fresh chunk, and the output of a script is unbounded-// while the panel's box is not.+// The renderer's view of a setup/archive run. Everything here exists because of two properties of+// the wire:+//+// - it is LOSSY AND RE-ORDERABLE. `ProjectSetupEvent.seq` is monotonic per run precisely so a+// client can tell a duplicate (relay re-delivery) from a fresh chunk.+// - `runKey` IS NOT UNIQUE OVER TIME. It is the deterministic single-flight key (kind + location),+// so two sequential runs of the same script share it and each restart `seq` at 1. `runId` is the+// per-launch identity; folding on it is what keeps run 2 from being swallowed as run 1's stale+// tail.+//+// And because an event carries no lane discriminator, storage is keyed by `runKey` alone: the+// initiator ATTACHES its run to a project (or a worktree group) at ack time, and the selectors+// resolve through those attachments.import { describe, it, expect, beforeEach, vi } from 'vitest'import type { ProjectSetupEvent } from '@shared/project-settings'import { SETUP_TAIL_MAX, useProjectSetup } from './projectSetup'const ev = (over: Partial<ProjectSetupEvent> = {}): ProjectSetupEvent => ({- runKey: 'r1',+ runKey: 'rk',+ runId: 'run-a',kind: 'setup',seq: 1,state: 'running',...over})-const apply = (e: ProjectSetupEvent, groupId?: string): void =>- useProjectSetup.getState().applyEvent('p1', e, groupId)+const apply = (e: ProjectSetupEvent): void => useProjectSetup.getState().applyEvent(e)+const attachProject = (projectId: string, runKey: string): void =>+ useProjectSetup.getState().attachProject(projectId, runKey)+const runForProject = (projectId: string): ReturnType<typeof useProjectSetup.getState>['byRunKey'][string] =>+ useProjectSetup.getState().runForProject(projectId)beforeEach(() => {- useProjectSetup.setState({ byProject: {}, byGroup: {} })+ useProjectSetup.setState({ byRunKey: {}, projectRunKey: {}, groupRunKey: {} })})-describe('useProjectSetup', () => {+describe('useProjectSetup — folding the event stream', () => {it('opens a run entry from the first event and appends chunks in seq order', () => {apply(ev({ seq: 1, chunk: 'installing…\n' }))apply(ev({ seq: 2, chunk: 'done\n' }))- const run = useProjectSetup.getState().byProject.p1!- expect(run.runKey).toBe('r1')+ const run = useProjectSetup.getState().byRunKey.rk!+ expect(run.runKey).toBe('rk')+ expect(run.runId).toBe('run-a')expect(run.kind).toBe('setup')expect(run.state).toBe('running')expect(run.tail).toBe('installing…\ndone\n')@@ -38,7 +52,7 @@ describe('useProjectSetup', () => {apply(ev({ seq: 1, chunk: 'a' }))apply(ev({ seq: 2, chunk: 'b' }))apply(ev({ seq: 2, chunk: 'b' }))- expect(useProjectSetup.getState().byProject.p1!.tail).toBe('ab')+ expect(useProjectSetup.getState().byRunKey.rk!.tail).toBe('ab')})it('drops a STALE seq that arrives after a newer one', () => {@@ -47,7 +61,7 @@ describe('useProjectSetup', () => {// seq 2 lost the race; re-inserting it here would put the output out of order AND would let a// stale `running` overwrite a terminal state.apply(ev({ seq: 2, chunk: 'b', state: 'done', exitCode: 0 }))- const run = useProjectSetup.getState().byProject.p1!+ const run = useProjectSetup.getState().byRunKey.rk!expect(run.tail).toBe('ac')expect(run.state).toBe('running')expect(run.exitCode).toBeUndefined()@@ -56,7 +70,7 @@ describe('useProjectSetup', () => {it('caps the tail at 8 KB, keeping the END (the failure is at the bottom, not the top)', () => {apply(ev({ seq: 1, chunk: 'x'.repeat(SETUP_TAIL_MAX) }))apply(ev({ seq: 2, chunk: 'TAIL' }))- const { tail } = useProjectSetup.getState().byProject.p1!+ const { tail } = useProjectSetup.getState().byRunKey.rk!expect(tail.length).toBe(SETUP_TAIL_MAX)expect(tail.endsWith('TAIL')).toBe(true)expect(tail.startsWith('x')).toBe(true)@@ -64,41 +78,84 @@ describe('useProjectSetup', () => {it('caps a single over-long chunk too', () => {apply(ev({ seq: 1, chunk: 'y'.repeat(SETUP_TAIL_MAX * 3) }))- expect(useProjectSetup.getState().byProject.p1!.tail.length).toBe(SETUP_TAIL_MAX)+ expect(useProjectSetup.getState().byRunKey.rk!.tail.length).toBe(SETUP_TAIL_MAX)})it('records the terminal state and exit code', () => {apply(ev({ seq: 1, chunk: 'boom\n' }))apply(ev({ seq: 2, state: 'failed', exitCode: 2 }))- const run = useProjectSetup.getState().byProject.p1!+ const run = useProjectSetup.getState().byRunKey.rk!expect(run.state).toBe('failed')expect(run.exitCode).toBe(2)expect(run.tail).toBe('boom\n')})- it('a NEW runKey starts a fresh entry — the previous run’s output never bleeds into it', () => {+ it('a NEW runKey is its own entry — one project’s setup and archive never share a slot', () => {+ apply(ev({ seq: 1, chunk: 'setup output\n' }))+ apply(ev({ runKey: 'rk-archive', runId: 'run-b', kind: 'archive', seq: 1, chunk: 'archive output\n' }))+ expect(useProjectSetup.getState().byRunKey.rk!.tail).toBe('setup output\n')+ expect(useProjectSetup.getState().byRunKey['rk-archive']!.tail).toBe('archive output\n')+ })++ it('C1: a SECOND run under the SAME runKey (new runId) starts fresh — seq restarting at 1 is not stale', () => {apply(ev({ seq: 1, chunk: 'first run\n' }))- apply(ev({ seq: 2, state: 'done', exitCode: 0 }))- apply(ev({ runKey: 'r2', kind: 'archive', seq: 1, chunk: 'second\n' }))- const run = useProjectSetup.getState().byProject.p1!- expect(run.runKey).toBe('r2')- expect(run.kind).toBe('archive')+ apply(ev({ seq: 2, state: 'failed', exitCode: 1 }))+ // The user hits Run again. Same script, same location ⇒ the SAME deterministic runKey, and the+ // service's seq counter starts over. Folding on runKey+seq alone would drop every one of these+ // as stale and leave the failed badge standing over a live run.+ apply(ev({ runId: 'run-b', seq: 1, chunk: 'second run\n' }))+ const run = useProjectSetup.getState().byRunKey.rk!+ expect(run.runId).toBe('run-b')expect(run.state).toBe('running')- expect(run.tail).toBe('second\n')+ expect(run.tail).toBe('second run\n')expect(run.exitCode).toBeUndefined()+ expect(run.seq).toBe(1)+ })++ it('and the fresh entry then dedupes on its OWN seq', () => {+ apply(ev({ seq: 1, chunk: 'first\n' }))+ apply(ev({ runId: 'run-b', seq: 1, chunk: 'second\n' }))+ apply(ev({ runId: 'run-b', seq: 1, chunk: 'second\n' }))+ expect(useProjectSetup.getState().byRunKey.rk!.tail).toBe('second\n')+ })+})++describe('useProjectSetup — lane attachment', () => {+ it('records an event for a runKey nobody has attached yet', () => {+ // The ack and the first event race; the attachment may land a tick later, and the head of the+ // output must survive that.+ apply(ev({ seq: 1, chunk: 'early\n' }))+ expect(runForProject('p1')).toBeUndefined()+ attachProject('p1', 'rk')+ expect(runForProject('p1')!.tail).toBe('early\n')+ })++ it('does NOT surface an unattached run in a project’s lane', () => {+ apply(ev({ runKey: 'someone-elses', runId: 'run-z', seq: 1, chunk: 'not mine\n' }))+ attachProject('p1', 'rk')+ expect(runForProject('p1')).toBeUndefined()})- it('routes a worktree run to byGroup, leaving the project entry alone', () => {+ it('routes a worktree run through attachGroup, independently of the project lane', () => {+ attachProject('p1', 'rk')+ useProjectSetup.getState().attachGroup('g1', 'rk-worktree')apply(ev({ seq: 1, chunk: 'project\n' }))- apply(ev({ runKey: 'r9', seq: 1, chunk: 'group\n' }), 'g1')- expect(useProjectSetup.getState().byProject.p1!.tail).toBe('project\n')- expect(useProjectSetup.getState().byGroup.g1!.tail).toBe('group\n')- // …and the two dedupe independently: same seq, different lane.- apply(ev({ runKey: 'r9', seq: 2, chunk: 'more\n' }), 'g1')- expect(useProjectSetup.getState().byGroup.g1!.tail).toBe('group\nmore\n')+ apply(ev({ runKey: 'rk-worktree', runId: 'run-w', seq: 1, chunk: 'worktree\n' }))+ expect(runForProject('p1')!.tail).toBe('project\n')+ expect(useProjectSetup.getState().runForGroup('g1')!.tail).toBe('worktree\n')})- it('subscribeProject wires api.projectSetup.onEvent into applyEvent and returns its unsubscribe', () => {+ it('re-attaching moves a lane to the newer run', () => {+ apply(ev({ seq: 1, chunk: 'old\n' }))+ attachProject('p1', 'rk')+ apply(ev({ runKey: 'rk2', runId: 'run-b', seq: 1, chunk: 'new\n' }))+ attachProject('p1', 'rk2')+ expect(runForProject('p1')!.tail).toBe('new\n')+ })+})++describe('useProjectSetup — subscription', () => {+ it('wires api.projectSetup.onEvent into applyEvent and returns its unsubscribe', () => {let emit: ((e: ProjectSetupEvent) => void) | null = nullconst off = vi.fn()const onEvent = vi.fn((_projectId: string, cb: (e: ProjectSetupEvent) => void) => {@@ -109,7 +166,7 @@ describe('useProjectSetup', () => {const unsubscribe = useProjectSetup.getState().subscribeProject('p1')expect(onEvent).toHaveBeenCalledWith('p1', expect.any(Function))emit!(ev({ seq: 1, chunk: 'from the wire' }))- expect(useProjectSetup.getState().byProject.p1!.tail).toBe('from the wire')+ expect(useProjectSetup.getState().byRunKey.rk!.tail).toBe('from the wire')unsubscribe()expect(off).toHaveBeenCalledTimes(1)})diff --git a/src/renderer/state/projectSetup.ts b/src/renderer/state/projectSetup.tsindex 29646f88f..c00666f11 100644--- a/src/renderer/state/projectSetup.ts+++ b/src/renderer/state/projectSetup.ts@@ -3,18 +3,28 @@ import type { ProjectSetupEvent, ProjectSetupKind } from '@shared/project-settin/*** Renderer view of the setup/archive runs main is streaming (`ProjectSetupEvent` on- * `IPC.projectSetupEvent(projectId)`). One entry per lane:+ * `IPC.projectSetupEvent(projectId)`).*- * - `byProject` — a run the user started from the project's settings pane,- * - `byGroup` — a run bound to a worktree group (Task 5 fills this from the worktree flow;- * the lane exists now so the shape does not change under it).+ * ONE STORAGE LANE, `byRunKey`, fed by the events themselves — because an event carries no+ * discriminator saying which UI raised the run. Routing by "whoever subscribed last" would put a+ * worktree's setup run in the settings panel and a panel run in the worktree card, at random. So+ * the initiator ATTACHES its run instead: whoever got the `started` ack (and therefore knows the+ * `runKey`) calls `attachProject` / `attachGroup`, and `runForProject` / `runForGroup` resolve+ * through those attachments. Events for a runKey nobody has attached are still recorded — the+ * attachment may land a tick later, and the head of the output must survive that.*- * The wire is the reason this store has any logic at all. `seq` is monotonic PER RUN precisely so- * a client can tell a re-delivered event from a fresh one — over the relay a cast can arrive- * twice, and out of order — so every event is measured against the last one applied and a- * duplicate or stale one is DROPPED. Dropping is the safe direction: a lost chunk costs a few- * bytes of visible output, whereas replaying one would duplicate output, and letting a stale- * `running` land after a `done` would show a finished run as still going.+ * `byRunKey` does not grow without bound: `runKey` is DETERMINISTIC (kind + location), so the key+ * space is two entries per project location, and a re-run of the same script re-uses its slot.+ *+ * FOLDING, and why every field of it is load-bearing:+ * - a different `runId` (unique per launch) always starts a FRESH entry, even under the same+ * `runKey`. Two sequential runs of one script share the runKey and each restart `seq` at 1, so+ * without this the second run's events would be dropped as stale and the finished run's exit+ * badge would stand over a live script.+ * - within one `runId`, `seq` is the dedupe watermark: `ev.seq <= prev.seq` is DROPPED. Over the+ * relay a cast can arrive twice, and out of order. Dropping is the safe direction — replaying+ * would double the output, and a stale `running` landing after a `done` would show a finished+ * run as live.*//** How much of a run's output the panel keeps, in characters. A setup script's output is@@ -23,23 +33,34 @@ import type { ProjectSetupEvent, ProjectSetupKind } from '@shared/project-settinexport const SETUP_TAIL_MAX = 8 * 1024export interface SetupRunState {+ /** The deterministic single-flight key — what `cancel` takes. */runKey: string+ /** Unique per launch; what identity-of-run decisions fold on. */+ runId: stringkind: ProjectSetupKindstate: ProjectSetupEvent['state']/** Last `SETUP_TAIL_MAX` characters of the run's output. */tail: stringexitCode?: number- /** Highest `seq` applied for THIS `runKey` — the dedupe watermark. Lives on the entry (rather+ /** Highest `seq` applied for THIS `runId` — the dedupe watermark. Lives on the entry (rather* than a side map) so a new run resets it by construction; nothing to sweep. */seq: number}interface ProjectSetupState {- byProject: Record<string, SetupRunState | undefined>- byGroup: Record<string, SetupRunState | undefined>- /** Fold one event into the lane it belongs to: `groupId` when the run is a worktree's, else the- * project's own lane. */- applyEvent(projectId: string, ev: ProjectSetupEvent, groupId?: string): void+ /** Every run seen on the wire, keyed by its single-flight key. */+ byRunKey: Record<string, SetupRunState | undefined>+ /** projectId -> the runKey its own launch claimed. */+ projectRunKey: Record<string, string | undefined>+ /** groupId -> the runKey that worktree's launch claimed (Task 5). */+ groupRunKey: Record<string, string | undefined>+ /** Fold one event into `byRunKey`. Takes no lane: the lanes come from the attachments. */+ applyEvent(ev: ProjectSetupEvent): void+ /** Called by the initiator with the runKey main acknowledged. */+ attachProject(projectId: string, runKey: string): void+ attachGroup(groupId: string, runKey: string): void+ runForProject(projectId: string): SetupRunState | undefined+ runForGroup(groupId: string): SetupRunState | undefined/** Wire this project's event channel into `applyEvent`; returns the unsubscribe. The preload api* ref-counts subscribe/unsubscribe per project (boardLog.onChanged's shape), so several callers* may hold one at once. */@@ -53,19 +74,15 @@ function appendTail(prev: string, chunk: string | undefined): string {return next.length <= SETUP_TAIL_MAX ? next : next.slice(next.length - SETUP_TAIL_MAX)}-/**- * The fold. Returns the next entry, or `null` when the event must be dropped.- *- * A DIFFERENT `runKey` always starts a fresh entry: the two runs' `seq` counters are unrelated, so- * there is nothing to compare, and main refuses a second concurrent run for the same target- * (`skipped: 'busy'`) — a live run's events cannot interleave with another's on the same lane.- */+/** The fold. Returns the next entry, or `null` when the event must be dropped. */function foldEvent(prev: SetupRunState | undefined, ev: ProjectSetupEvent): SetupRunState | null {- if (prev && prev.runKey === ev.runKey) {+ // Same LAUNCH: apply the watermark.+ if (prev && prev.runId === ev.runId) {// Duplicate (re-delivered) or stale (overtaken): the watermark has already passed it.if (ev.seq <= prev.seq) return nullreturn {runKey: prev.runKey,+ runId: prev.runId,kind: ev.kind,state: ev.state,tail: appendTail(prev.tail, ev.chunk),@@ -78,8 +95,11 @@ function foldEvent(prev: SetupRunState | undefined, ev: ProjectSetupEvent): Setuseq: ev.seq}}+ // A different launch (or the first one): a fresh entry — nothing of the previous run carries+ // over, and its `seq` counter is unrelated to ours.return {runKey: ev.runKey,+ runId: ev.runId,kind: ev.kind,state: ev.state,tail: appendTail('', ev.chunk),@@ -89,23 +109,34 @@ function foldEvent(prev: SetupRunState | undefined, ev: ProjectSetupEvent): Setu}export const useProjectSetup = create<ProjectSetupState>((set, get) => ({- byProject: {},- byGroup: {},+ byRunKey: {},+ projectRunKey: {},+ groupRunKey: {},- applyEvent: (projectId, ev, groupId) => {- if (groupId !== undefined) {- const next = foldEvent(get().byGroup[groupId], ev)- if (!next) return- set((s) => ({ byGroup: { ...s.byGroup, [groupId]: next } }))- return- }- const next = foldEvent(get().byProject[projectId], ev)+ applyEvent: (ev) => {+ const next = foldEvent(get().byRunKey[ev.runKey], ev)if (!next) return- set((s) => ({ byProject: { ...s.byProject, [projectId]: next } }))+ set((s) => ({ byRunKey: { ...s.byRunKey, [ev.runKey]: next } }))+ },++ attachProject: (projectId, runKey) =>+ set((s) => ({ projectRunKey: { ...s.projectRunKey, [projectId]: runKey } })),++ attachGroup: (groupId, runKey) =>+ set((s) => ({ groupRunKey: { ...s.groupRunKey, [groupId]: runKey } })),++ runForProject: (projectId) => {+ const runKey = get().projectRunKey[projectId]+ return runKey === undefined ? undefined : get().byRunKey[runKey]+ },++ runForGroup: (groupId) => {+ const runKey = get().groupRunKey[groupId]+ return runKey === undefined ? undefined : get().byRunKey[runKey]},subscribeProject: (projectId) =>window.nodeTerminal.projectSetup.onEvent(projectId, (ev) => {- get().applyEvent(projectId, ev)+ get().applyEvent(ev)})}))diff --git a/src/shared/project-settings.ts b/src/shared/project-settings.tsindex 28b4d1895..eeaa8dbf1 100644--- a/src/shared/project-settings.ts+++ b/src/shared/project-settings.ts@@ -361,14 +361,23 @@ export interface ProjectSetupConsentRequest {export type ProjectSetupConsentAnswer = 'approve' | 'skip'export type ProjectSetupRunResult =- | { status: 'started'; runKey: string; waitForSetup: boolean }+ | { status: 'started'; runKey: string; runId: string; waitForSetup: boolean }| { status: 'skipped'; reason: 'no-script' | 'declined' | 'unanswered' | 'busy' | 'unavailable' }/** main→renderer per-run progress on `IPC.projectSetupEvent(projectId)`. `seq` is monotonic per* run, so a client that misses one knows it. */export interface ProjectSetupEvent {+ /** The SINGLE-FLIGHT key: deterministic (kind + location), so a second launch of the same script+ * at the same place is refused as `busy`. It is therefore NOT unique over time — two sequential+ * runs of the same script share it. */runKey: string+ /** Unique per RUN (a fresh uuid each launch). This is what a client folds on: two sequential runs+ * share a `runKey`, so without it the second run's events look like a continuation of the first+ * — its `seq` restarts at 1 and would be dropped as stale, leaving the finished run's exit badge+ * standing over a live script. */+ runId: stringkind: ProjectSetupKind+ /** Monotonic within one `runId`, from 1. */seq: numberstate: 'running' | 'done' | 'failed' | 'cancelled'/** Appended output since the last event (stdout+stderr interleaved, capped). */