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.

feat(project-setup): consent dialog, run-state store, panel run buttons

enes8486e484c98c
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ff685bdb9..f4949d71c 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -156,6 +156,7 @@ import { PtyPressureBanner } from '../components/PtyPressureBanner'
import { ConflictBar } from '../components/ConflictBar'
import { ConfirmDialog } from '../components/ConfirmDialog'
import { CapabilityNotice } from '../components/CapabilityNotice'
+import { SetupConsentDialog } from '../components/SetupConsentDialog'
import { ConsentNotice } from '../remote/ConsentNotice'
import { peerApprovalView } from '@shared/remote/approval'
import { promptDialog } from '../components/promptDialog'
@@ -9805,6 +9806,12 @@ export function Canvas() {
answer machine-locally — see components/CapabilityNotice.tsx and its test. */}
<CapabilityNotice />
+ {/* The trust gate for a git-shared setup/archive script, mounted ONCE for the whole app on
+ the same layer as the clone notice: main raises it (a manual run, or a worktree's setup)
+ and it must be answerable wherever the user is, not only while a settings pane happens to
+ be open — see components/SetupConsentDialog.tsx. */}
+ <SetupConsentDialog />
+
{confirm && (
<ConfirmDialog
message={confirm.message}
diff --git a/src/renderer/components/SetupConsentDialog.test.tsx b/src/renderer/components/SetupConsentDialog.test.tsx
new file mode 100644
index 000000000..1005d01a0
--- /dev/null
+++ b/src/renderer/components/SetupConsentDialog.test.tsx
@@ -0,0 +1,277 @@
+// @vitest-environment jsdom
+//
+// THE trust gate for a git-shared setup/archive script: a cloned repo's `.nodeterm/settings.json`
+// can carry `setupScript: "curl … | sh"`, and this dialog is the only thing between it and a
+// spawn. Everything asserted here is security-shaped:
+//
+// - it must show EVERYTHING the one approval covers (both family scripts), because main hashes
+// the family together — approving after reading only half is approving code unseen,
+// - only the two buttons are answers: Escape / an overlay misclick submit NOTHING (main's expiry
+// owns the `undefined`), mirroring the capability clone notice's dismiss handling,
+// - exactly ONE `consent` call per request, however many times the button is hit,
+// - `projectName` / `locationLabel` cross the IPC boundary from a file the user did not write:
+// they are rendered as TEXT ONLY and clamped (no control characters, length capped).
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import type { ProjectSetupConsentRequest } from '@shared/project-settings'
+import { CONFIRM_ARM_MS } from './confirm-key'
+import { SETUP_LABEL_MAX, SetupConsentDialog } from './SetupConsentDialog'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const request = (over: Partial<ProjectSetupConsentRequest> = {}): ProjectSetupConsentRequest => ({
+ requestId: 'req-1',
+ kind: 'setup',
+ projectName: 'cloned-repo',
+ locationLabel: '~/code/cloned-repo',
+ scripts: { setup: 'npm install', archive: 'rm -rf node_modules' },
+ previouslyApproved: false,
+ ...over
+})
+
+let root: Root
+let host: HTMLElement
+let consent: ReturnType<typeof vi.fn>
+let emitRequest: (req: ProjectSetupConsentRequest) => void
+let emitDismiss: (p: { requestId: string }) => void
+let offRequest: ReturnType<typeof vi.fn>
+let offDismiss: ReturnType<typeof vi.fn>
+
+function mount(): void {
+ root = createRoot(host)
+ act(() => root.render(<SetupConsentDialog />))
+}
+
+function dialog(): HTMLElement | null {
+ return document.querySelector('.confirm')
+}
+
+function text(): string {
+ return dialog()?.textContent ?? ''
+}
+
+function scripts(): HTMLElement[] {
+ return [...document.querySelectorAll<HTMLElement>('.confirm pre[data-script-kind]')]
+}
+
+function button(label: string): HTMLButtonElement {
+ const el = [...document.querySelectorAll<HTMLButtonElement>('.confirm button')].find(
+ (b) => b.textContent === label
+ )
+ expect(el, `button "${label}"`).toBeTruthy()
+ return el!
+}
+
+beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ consent = vi.fn(async () => {})
+ offRequest = vi.fn()
+ offDismiss = vi.fn()
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ projectSetup: {
+ consent,
+ onConsentRequest: (cb: (r: ProjectSetupConsentRequest) => void) => {
+ emitRequest = cb
+ return offRequest
+ },
+ onConsentDismiss: (cb: (p: { requestId: string }) => void) => {
+ emitDismiss = cb
+ return offDismiss
+ }
+ }
+ }
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+describe('SetupConsentDialog', () => {
+ it('renders nothing until a request arrives', () => {
+ mount()
+ expect(dialog()).toBeNull()
+ })
+
+ it('names the project and its location, and shows BOTH family scripts with the running one first', () => {
+ mount()
+ act(() => emitRequest(request({ kind: 'archive' })))
+ expect(text()).toContain('cloned-repo')
+ expect(text()).toContain('~/code/cloned-repo')
+ const boxes = scripts()
+ expect(boxes).toHaveLength(2)
+ // One approval covers the whole family, so the dialog shows the whole family — the script
+ // about to run leads, but the other is right there and is equally approved.
+ expect(boxes[0].dataset.scriptKind).toBe('archive')
+ expect(boxes[0].textContent).toBe('rm -rf node_modules')
+ expect(boxes[1].dataset.scriptKind).toBe('setup')
+ expect(boxes[1].textContent).toBe('npm install')
+ })
+
+ it('omits a script the family does not set', () => {
+ mount()
+ act(() => emitRequest(request({ scripts: { setup: 'make bootstrap' } })))
+ const boxes = scripts()
+ expect(boxes).toHaveLength(1)
+ expect(boxes[0].dataset.scriptKind).toBe('setup')
+ })
+
+ it('says the scripts CHANGED when a previous approval exists', () => {
+ mount()
+ act(() => emitRequest(request({ previouslyApproved: true })))
+ expect(text().toLowerCase()).toContain('changed since you approved')
+ })
+
+ it('does not say that for a first-time approval', () => {
+ mount()
+ act(() => emitRequest(request()))
+ expect(text().toLowerCase()).not.toContain('changed since you approved')
+ })
+
+ it('"Run once" submits approve exactly once, however many clicks land', () => {
+ mount()
+ act(() => emitRequest(request()))
+ const btn = button('Run once')
+ act(() => {
+ btn.click()
+ btn.click()
+ })
+ expect(consent).toHaveBeenCalledTimes(1)
+ expect(consent).toHaveBeenCalledWith('req-1', 'approve')
+ expect(dialog()).toBeNull()
+ })
+
+ it('"Skip" submits skip', () => {
+ mount()
+ act(() => emitRequest(request()))
+ act(() => button('Skip').click())
+ expect(consent).toHaveBeenCalledWith('req-1', 'skip')
+ expect(dialog()).toBeNull()
+ })
+
+ it('Escape submits NOTHING — it closes the dialog and leaves the answer to main’s expiry', () => {
+ mount()
+ act(() => emitRequest(request()))
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
+ })
+ expect(dialog()).toBeNull()
+ expect(consent).not.toHaveBeenCalled()
+ })
+
+ it('an overlay misclick submits NOTHING either', () => {
+ mount()
+ act(() => emitRequest(request()))
+ act(() => {
+ document.querySelector<HTMLElement>('.confirm-overlay')!.click()
+ })
+ expect(dialog()).toBeNull()
+ expect(consent).not.toHaveBeenCalled()
+ })
+
+ it('is CLICK-ONLY: Enter aimed into the dialog approves nothing', async () => {
+ mount()
+ act(() => emitRequest(request()))
+ // Outwait the arm window first: a fresh dialog ignores Enter for CONFIRM_ARM_MS regardless of
+ // `enterConfirms`, so an immediate dispatch would pass even with the prop dropped.
+ await new Promise((r) => setTimeout(r, CONFIRM_ARM_MS + 150))
+ act(() => {
+ dialog()!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }))
+ })
+ expect(dialog()).toBeTruthy()
+ expect(consent).not.toHaveBeenCalled()
+ })
+
+ it('holds focus on NO button, so a native Enter/Space mid-typing cannot approve it', () => {
+ const typing = document.createElement('input')
+ document.body.appendChild(typing)
+ typing.focus()
+ mount()
+ act(() => emitRequest(request()))
+ expect(document.activeElement).toBe(typing)
+ for (const b of document.querySelectorAll('.confirm button')) {
+ expect(document.activeElement).not.toBe(b)
+ }
+ typing.remove()
+ })
+
+ it('the dismiss broadcast drops the local prompt without answering it', () => {
+ mount()
+ act(() => emitRequest(request()))
+ act(() => emitDismiss({ requestId: 'req-1' }))
+ expect(dialog()).toBeNull()
+ expect(consent).not.toHaveBeenCalled()
+ })
+
+ it('a dismiss for some OTHER request leaves this one standing', () => {
+ mount()
+ act(() => emitRequest(request()))
+ act(() => emitDismiss({ requestId: 'req-elsewhere' }))
+ expect(dialog()).toBeTruthy()
+ })
+
+ it('queues a second request and shows it once the first is answered', () => {
+ mount()
+ act(() => emitRequest(request()))
+ act(() => emitRequest(request({ requestId: 'req-2', projectName: 'other-repo' })))
+ expect(text()).toContain('cloned-repo')
+ act(() => button('Skip').click())
+ expect(dialog()).toBeTruthy()
+ expect(text()).toContain('other-repo')
+ act(() => button('Run once').click())
+ expect(consent).toHaveBeenNthCalledWith(1, 'req-1', 'skip')
+ expect(consent).toHaveBeenNthCalledWith(2, 'req-2', 'approve')
+ })
+
+ it('a repeated request id does not stack two prompts for the same question', () => {
+ mount()
+ act(() => emitRequest(request()))
+ act(() => emitRequest(request()))
+ act(() => button('Skip').click())
+ expect(dialog()).toBeNull()
+ })
+
+ it('CLAMPS the project name and location: control characters stripped, length capped', () => {
+ mount()
+ act(() =>
+ emitRequest(
+ request({
+ // Cross-boundary strings out of a file a stranger may have written. The escapes are
+ // written as \u sequences on purpose: a raw control byte in a source file is invisible
+ // to git and ripgrep, which has already cost this repo a day.
+ projectName: 'evil\u001b[31mred\r\nSecond line',
+ locationLabel: '/srv/' + 'a'.repeat(400)
+ })
+ )
+ )
+ const shown = text()
+ // eslint-disable-next-line no-control-regex
+ expect(/[\u0000-\u001f\u007f-\u009f]/.test(shown)).toBe(false)
+ expect(shown).toContain('evil')
+ expect(shown).toContain('Second line')
+ // Capped with an ellipsis rather than allowed to run the dialog off the screen.
+ expect(shown).not.toContain('a'.repeat(SETUP_LABEL_MAX + 1))
+ expect(shown).toContain('\u2026')
+ })
+
+ it('renders the script bodies VERBATIM — they are what the approval covers', () => {
+ mount()
+ act(() => emitRequest(request({ scripts: { setup: 'echo "<img src=x>"\nmake install' } })))
+ // Text, never markup: a `<pre>` child is escaped by React, and the user must see every byte
+ // they are approving — clamping a script would mean approving what is not on screen.
+ expect(scripts()[0].textContent).toBe('echo "<img src=x>"\nmake install')
+ expect(scripts()[0].querySelector('img')).toBeNull()
+ })
+
+ it('unsubscribes both channels on unmount', () => {
+ mount()
+ act(() => root.unmount())
+ expect(offRequest).toHaveBeenCalledTimes(1)
+ expect(offDismiss).toHaveBeenCalledTimes(1)
+ // The afterEach unmount must stay harmless.
+ root = createRoot(host)
+ })
+})
diff --git a/src/renderer/components/SetupConsentDialog.tsx b/src/renderer/components/SetupConsentDialog.tsx
new file mode 100644
index 000000000..7ff28af87
--- /dev/null
+++ b/src/renderer/components/SetupConsentDialog.tsx
@@ -0,0 +1,159 @@
+import { useEffect, useRef, useState } from 'react'
+import type {
+ ProjectSetupConsentAnswer,
+ ProjectSetupConsentRequest,
+ ProjectSetupKind
+} from '@shared/project-settings'
+import { oneLine } from '@shared/one-line'
+import { ConfirmDialog } from './ConfirmDialog'
+
+/**
+ * THE TRUST GATE for a git-shared setup/archive script — the last thing between a cloned repo's
+ * `.nodeterm/settings.json` and a spawn on this machine. Its properties are security-shaped, in
+ * the same family as `CapabilityNotice` (the clone-arrived capability switch):
+ *
+ * - IT SHOWS EVERYTHING THE ANSWER COVERS. One approval pins the whole `setup` family's hash
+ * (`projectTrustContent`), so the payload carries BOTH scripts and both are rendered. Showing
+ * only the one about to run would be approving the other unseen — the next archive would then
+ * execute code the user never read, under an approval they gave for something else.
+ * - ONLY THE TWO BUTTONS ARE ANSWERS. `enterConfirms={false}` shuts the window-keydown path and
+ * `autoFocusButtons={false}` means no button holds focus for a native Enter/Space — this dialog
+ * appears under the user's hands (a worktree they just created starts a setup run), and a
+ * keystroke aimed at a terminal must never approve a script. Escape and an overlay misclick
+ * submit NOTHING: they hide the prompt locally and leave the decision to main's expiry, which
+ * resolves an unanswered request as `undefined` (= not approved, nothing runs).
+ * - EXACTLY ONE SUBMISSION PER REQUEST, guarded by `answeredRef` — a double click must not send a
+ * second answer that a re-used requestId could apply to a different question.
+ *
+ * SECURITY — CROSS-BOUNDARY STRINGS: `projectName` and `locationLabel` come from a project file
+ * 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.
+ *
+ * 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
+ * (`src/main/platform-electron.ts` — `dispatch` forbids only `githubControl:` methods), so a guest
+ * could trigger a prompt and then answer it themselves without the host's user touching anything.
+ * That is a main-side ADMISSION question — which methods a non-host peer may call — and no dialog
+ * property can close it: this component cannot tell whose IPC message reached main. It is recorded
+ * for the final wave's admission decision.
+ */
+
+/** 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. */
+function safeLabel(raw: string): string {
+ const flat = oneLine(raw)
+ return flat.length > SETUP_LABEL_MAX ? flat.slice(0, SETUP_LABEL_MAX - 1) + '…' : flat
+}
+
+const KIND_LABEL: Record<ProjectSetupKind, string> = { setup: 'Setup', archive: 'Archive' }
+
+/** The family's scripts, the one about to run FIRST, skipping the ones the family does not set. */
+function orderedScripts(req: ProjectSetupConsentRequest): { kind: ProjectSetupKind; body: string }[] {
+ const order: ProjectSetupKind[] = req.kind === 'archive' ? ['archive', 'setup'] : ['setup', 'archive']
+ return order
+ .map((kind) => ({ kind, body: req.scripts[kind] }))
+ .filter((s): s is { kind: ProjectSetupKind; body: string } => s.body !== undefined)
+}
+
+export function SetupConsentDialog(): React.JSX.Element | null {
+ // A QUEUE, not a single request: two projects (or a run and a worktree archive) can ask at once,
+ // and answering one must not lose the other. The head is the one on screen.
+ const [queue, setQueue] = useState<ProjectSetupConsentRequest[]>([])
+ // Request ids already answered from here. Belt-and-braces against a double click landing before
+ // the re-render drops the head — main treats an unknown/stale id as a no-op, but a second answer
+ // must never leave this component in the first place.
+ const answeredRef = useRef<Set<string>>(new Set())
+
+ useEffect(() => {
+ const api = window.nodeTerminal.projectSetup
+ const offRequest = api.onConsentRequest((req) => {
+ setQueue((q) => (q.some((r) => r.requestId === req.requestId) ? q : [...q, req]))
+ })
+ // main answered (or expired) this one itself — drop it, silently and without submitting.
+ const offDismiss = api.onConsentDismiss(({ requestId }) => {
+ setQueue((q) => q.filter((r) => r.requestId !== requestId))
+ })
+ return () => {
+ offRequest()
+ offDismiss()
+ }
+ }, [])
+
+ const head = queue[0]
+ if (!head) return null
+
+ const drop = (requestId: string): void =>
+ setQueue((q) => q.filter((r) => r.requestId !== requestId))
+
+ const answer = (a: ProjectSetupConsentAnswer): void => {
+ if (answeredRef.current.has(head.requestId)) return
+ answeredRef.current.add(head.requestId)
+ void window.nodeTerminal.projectSetup.consent(head.requestId, a)
+ drop(head.requestId)
+ }
+
+ const name = safeLabel(head.projectName)
+ const location = safeLabel(head.locationLabel)
+
+ return (
+ <ConfirmDialog
+ // Keyed per request: the next prompt in the queue must be a FRESH dialog — its own
+ // arm-window (CONFIRM_ARM_MS) and its own stack id, never one that inherited the timer of
+ // the prompt the user just answered.
+ key={head.requestId}
+ body={
+ <div className="confirm__msg space-y-2">
+ <p className="text-[13px] text-muted">{location}</p>
+ {head.previouslyApproved ? (
+ <p className="text-[13px] text-[color:var(--warn)]">
+ These scripts have changed since you approved them for this project.
+ </p>
+ ) : null}
+ <p className="text-[13px] text-muted">
+ They come from the project&apos;s shared <code>.nodeterm/settings.json</code>, so anyone
+ who can commit to the repo can change them. One answer covers both.
+ </p>
+ {orderedScripts(head).map((s) => (
+ <div key={s.kind} className="space-y-1">
+ <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. */}
+ <pre
+ 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'
+ }`}
+ >
+ {s.body}
+ </pre>
+ </div>
+ ))}
+ </div>
+ }
+ message={`Run the ${KIND_LABEL[head.kind].toLowerCase()} script for "${name}"?`}
+ confirmLabel="Run once"
+ cancelLabel="Skip"
+ // "Run once" is the grant, so it carries the danger styling; no button takes focus.
+ danger
+ enterConfirms={false}
+ autoFocusButtons={false}
+ onConfirm={() => answer('approve')}
+ onCancel={() => answer('skip')}
+ onDismiss={() => {
+ // NOT an answer. Nothing is submitted: main's pending request expires on its own and
+ // resolves as unanswered, which runs nothing. Only the local prompt goes away.
+ drop(head.requestId)
+ }}
+ />
+ )
+}
diff --git a/src/renderer/components/settings/ProjectSettingsFamilies.tsx b/src/renderer/components/settings/ProjectSettingsFamilies.tsx
index 8f46458ff..a1abbefc9 100644
--- a/src/renderer/components/settings/ProjectSettingsFamilies.tsx
+++ b/src/renderer/components/settings/ProjectSettingsFamilies.tsx
@@ -1,13 +1,17 @@
-import { useEffect, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
import type {
ProjectLocalSettings,
ProjectSettingsDoc,
ProjectSettingsFamily,
ProjectSettingsSnapshot,
+ ProjectSetupKind,
+ ProjectSetupRunResult,
ResolvedProjectSettings
} from '@shared/project-settings'
+import { Button } from '@renderer/ui/Button'
import { Input } from '@renderer/ui/Input'
import { Switch } from '@renderer/ui/Switch'
+import { useProjectSetup } from '../../state/projectSetup'
import { useSettingsSearch } from './context'
import { FieldRow } from './FieldRow'
import { formatEnvLines, formatListLines, parseEnvLines, parseListLines } from './project-settings-env'
@@ -362,6 +366,146 @@ const SAVE_FAILED_NOTE: Record<'shared' | 'local', string> = {
local: 'Could not save this override on this machine; reload the project settings.'
}
+/** Why a run the service refused never happened. A refusal must read as a refusal: the button was
+ * pressed and nothing appeared, which is otherwise indistinguishable from a broken button. */
+const SKIP_NOTE: Record<Extract<ProjectSetupRunResult, { status: 'skipped' }>['reason'], string> = {
+ 'no-script': 'Skipped: no script is set for this project.',
+ declined: 'Skipped: the trust prompt was answered "Skip", so nothing ran.',
+ unanswered: 'Skipped: the trust prompt went unanswered, so nothing ran.',
+ busy: 'Skipped: a run for this project is already in progress.',
+ unavailable: 'Skipped: this project has nowhere to run — no folder and no server connection.'
+}
+
+const RUN_LABEL: Record<ProjectSetupKind, string> = { setup: 'Run setup', archive: 'Run archive' }
+
+/** How a finished run reads in the badge. */
+function exitNote(state: 'done' | 'failed' | 'cancelled', exitCode: number | undefined): string {
+ if (state === 'cancelled') return 'Cancelled'
+ if (state === 'done') return `Finished (exit ${exitCode ?? 0})`
+ return `Failed (exit ${exitCode ?? 'unknown'})`
+}
+
+/**
+ * Manual "Run setup" / "Run archive" for this project, with the live output of whatever is running.
+ *
+ * The service — not this component — decides whether a script may run: a shared-sourced script goes
+ * through the consent dialog (`SetupConsentDialog`), and every refusal comes back as a `skipped`
+ * reason that is shown verbatim-ish below. So the properties that matter here are:
+ *
+ * - SUBSCRIBE BEFORE RUN. Main can emit the first chunks before the `run` invoke resolves, so a
+ * subscription opened on the ack would silently lose the head of the output (Task 1 review, T1).
+ * The subscription is opened on the first click and held until the pane unmounts — a late
+ * `cancelled`/`failed` event after a terminal-looking one must still land.
+ * - HONEST DISABLED STATE. Disabled while a run is live (main would answer `busy` anyway), while
+ * the family sets no EFFECTIVE script for that kind (local-over-shared — a machine-local script
+ * is a real script), and for a project with nowhere to run (no folder, no server): the service
+ * refuses that with `unavailable`, and offering a button that can only fail is a lie.
+ * - The run is PROJECT-scoped: `worktreePath` is deliberately `undefined` here. Worktree-bound
+ * runs come from the worktree flow (Task 5), which owns the path main then validates.
+ */
+function SetupRunControls({
+ projectId,
+ canRun,
+ hasScript
+}: {
+ projectId: string
+ /** False when the project has neither a folder nor an SSH endpoint. */
+ canRun: boolean
+ hasScript: Record<ProjectSetupKind, boolean>
+}): React.JSX.Element {
+ const run = useProjectSetup((s) => s.byProject[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)
+ const unsubRef = useRef<(() => void) | null>(null)
+ useEffect(
+ () => () => {
+ unsubRef.current?.()
+ unsubRef.current = null
+ },
+ []
+ )
+
+ const awaitingStarted = startedKey !== null && (!run || run.runKey !== startedKey)
+ const active = busy !== '' || run?.state === 'running' || awaitingStarted
+ const liveKey = run?.state === 'running' ? run.runKey : awaitingStarted ? startedKey : null
+
+ const start = async (kind: ProjectSetupKind): Promise<void> => {
+ setNotice('')
+ setBusy(kind)
+ // Before the call, never after — see the T1 note above.
+ 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)
+ } catch {
+ setNotice('Could not start the script — the project may have become unavailable.')
+ } finally {
+ setBusy('')
+ }
+ }
+
+ const stop = async (runKey: string): Promise<void> => {
+ setBusy('cancel')
+ try {
+ await window.nodeTerminal.projectSetup.cancel(runKey)
+ } catch {
+ /* A cancel that cannot be delivered leaves the run where it was; the event stream still owns
+ the truth about whether it ended. */
+ } finally {
+ setBusy('')
+ setStartedKey(null)
+ }
+ }
+
+ return (
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ {(['setup', 'archive'] as ProjectSetupKind[]).map((kind) => (
+ <Button
+ key={kind}
+ disabled={!canRun || !hasScript[kind] || active}
+ onClick={() => void start(kind)}
+ >
+ {RUN_LABEL[kind]}
+ </Button>
+ ))}
+ {liveKey ? (
+ <Button variant="ghost" disabled={busy === 'cancel'} onClick={() => void stop(liveKey)}>
+ Cancel
+ </Button>
+ ) : null}
+ {run && run.state !== 'running' ? (
+ <span className="text-[12px] text-muted">{exitNote(run.state, run.exitCode)}</span>
+ ) : null}
+ </div>
+ {!canRun ? (
+ <p className="text-[12px] leading-relaxed text-muted">
+ This project has nowhere to run a script — set a folder or a server connection first.
+ </p>
+ ) : null}
+ {notice ? (
+ <p role="status" className="text-[12px] leading-relaxed text-[color:var(--warn)]">
+ {notice}
+ </p>
+ ) : null}
+ {run ? (
+ <pre
+ role="log"
+ aria-label="Setup script output"
+ className="max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-md border border-border bg-bg px-2.5 py-2 font-mono text-[12px] leading-relaxed text-text"
+ >
+ {run.tail}
+ </pre>
+ ) : null}
+ </div>
+ )
+}
+
function FamilySection({
projectId,
family,
@@ -372,6 +516,7 @@ function FamilySection({
conflict,
ready,
sharedEditable,
+ canRun,
saveShared,
saveLocal,
reload
@@ -391,6 +536,12 @@ function FamilySection({
ready: boolean
/** False when this project has no file to share (see `ProjectFamilyEditors`). */
sharedEditable: boolean
+ /** False when the project has nowhere to run a script. Deliberately NOT `sharedEditable`, even
+ * though today both come out of `project.cwd || project.ssh`: one is about where a FILE can be
+ * written, the other about where a PROCESS can be spawned, and the run buttons live outside the
+ * shared-editing gate entirely (a machine-local script on a folderless project still cannot
+ * run). */
+ canRun: boolean
saveShared: (doc: ProjectSettingsDoc) => Promise<boolean>
saveLocal: (
update: (current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined
@@ -550,6 +701,19 @@ function FamilySection({
return (
<div className="space-y-3 border-t border-border pt-4">
<h3 className="text-[13px] font-semibold text-text">{config.title}</h3>
+ {family === 'setup' ? (
+ <SetupRunControls
+ projectId={projectId}
+ canRun={canRun}
+ // EFFECTIVE values (local-over-shared), not the shared row's text: a machine-local
+ // script is a real script, and a family whose shared half is ignored on this machine
+ // has none even when the file sets one.
+ hasScript={{
+ setup: resolvedFamily.setupScript !== undefined,
+ archive: resolvedFamily.archiveScript !== undefined
+ }}
+ />
+ ) : null}
{saveFailed ? (
<p role="status" className="text-[12px] leading-relaxed text-[color:var(--warn)]">
{SAVE_FAILED_NOTE[saveFailed]}
@@ -585,6 +749,7 @@ export function ProjectFamilyEditors({
resolved,
conflict,
sharedEditable,
+ canRun,
saveShared,
saveLocal,
reload
@@ -603,6 +768,9 @@ export function ProjectFamilyEditors({
* not in the project folder, so `updateLocal` genuinely succeeds for a folderless project.
*/
sharedEditable: boolean
+ /** See `FamilySection`'s `canRun`: where a PROCESS may be spawned, which is a different question
+ * from where the shared file may be written. */
+ canRun: boolean
saveShared: (doc: ProjectSettingsDoc) => Promise<boolean>
saveLocal: (
update: (current: ProjectLocalSettings | undefined) => ProjectLocalSettings | undefined
@@ -635,6 +803,7 @@ export function ProjectFamilyEditors({
conflict={conflict}
ready={ready}
sharedEditable={sharedEditable}
+ canRun={canRun}
saveShared={saveShared}
saveLocal={saveLocal}
reload={reload}
diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx
index 210e3ec61..eb2c83a28 100644
--- a/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx
+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.test.tsx
@@ -10,6 +10,8 @@ import { registerWorkspaceDirty } from '../../../state/workspaceDirty'
import { SettingsSearchContext } from '../context'
import { ProjectSettingsSection } from './ProjectSettingsSection'
import { mergeSharedDoc, useProjectSettings, type ProjectSettingsHook } from '../useProjectSettings'
+import type { ProjectSetupEvent } from '@shared/project-settings'
+import { useProjectSetup } from '../../../state/projectSetup'
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
@@ -740,3 +742,173 @@ describe('mergeSharedDoc', () => {
})
})
})
+
+/**
+ * The setup family's RUN controls (Task 4). These buttons are the manual half of the trust gate:
+ * the service still decides whether the script may run (and raises the consent dialog), so what is
+ * pinned here is the renderer's side — the right call, the right ORDER (subscribe before run, or
+ * the first chunks are lost), an honest disabled state, and the live output.
+ */
+describe('ProjectSettingsSection — setup run controls', () => {
+ let root: Root
+ let host: HTMLElement
+ let runSetup: ReturnType<typeof vi.fn>
+ let cancel: ReturnType<typeof vi.fn>
+ let onEvent: ReturnType<typeof vi.fn>
+ let emit: (ev: ProjectSetupEvent) => void
+ let off: ReturnType<typeof vi.fn>
+
+ const snapshotWith = (setup: Record<string, unknown>): ProjectSettingsSnapshot => ({
+ shared: { version: 1, rev: 1, savedAt: '2026-08-19T00:00:00.000Z', setup },
+ local: undefined
+ })
+
+ const mountPanel = async (
+ snapshot: ProjectSettingsSnapshot,
+ p: Project = project()
+ ): Promise<void> => {
+ ;(window as unknown as { nodeTerminal: any }).nodeTerminal.projectSettings.read = vi.fn(
+ async () => snapshot
+ )
+ useProjects.setState({ projects: [p], activeProjectId: p.id })
+ root = createRoot(host)
+ await act(async () => {
+ root.render(
+ <SettingsSearchContext.Provider value="">
+ <ProjectSettingsSection projectId={p.id} isActive />
+ </SettingsSearchContext.Provider>
+ )
+ })
+ }
+
+ const button = (label: string): HTMLButtonElement => {
+ const el = [...host.querySelectorAll('button')].find((b) => b.textContent === label)
+ expect(el, `button "${label}"`).toBeTruthy()
+ return el as HTMLButtonElement
+ }
+
+ const hasButton = (label: string): boolean =>
+ [...host.querySelectorAll('button')].some((b) => b.textContent === label)
+
+ const log = (): HTMLElement | null => host.querySelector('[role="log"]')
+
+ beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ useProjectSetup.setState({ byProject: {}, byGroup: {} })
+ runSetup = vi.fn(async () => ({ status: 'started', runKey: 'run-1', waitForSetup: false }))
+ cancel = vi.fn(async () => true)
+ off = vi.fn()
+ onEvent = vi.fn((_projectId: string, cb: (ev: ProjectSetupEvent) => void) => {
+ emit = cb
+ return off
+ })
+ ;(window as unknown as { nodeTerminal: any }).nodeTerminal = {
+ projectSettings: { read: vi.fn(async () => EMPTY_SNAPSHOT), writeShared: vi.fn(async () => true), updateLocal: vi.fn(async () => true) },
+ projectSetup: { run: runSetup, cancel, onEvent, consent: vi.fn(), onConsentRequest: vi.fn(), onConsentDismiss: vi.fn() },
+ workspace: { save: vi.fn() }
+ }
+ })
+
+ afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ useProjects.setState({ projects: [], activeProjectId: '' })
+ useProjectSetup.setState({ byProject: {}, byGroup: {} })
+ })
+
+ it('runs the setup script for this project, SUBSCRIBING to the event channel first', async () => {
+ await mountPanel(snapshotWith({ setupScript: 'make bootstrap' }))
+ await act(async () => {
+ button('Run setup').click()
+ })
+ expect(runSetup).toHaveBeenCalledWith('p1', 'setup', undefined)
+ expect(onEvent).toHaveBeenCalledWith('p1', expect.any(Function))
+ // T1: main can emit the first chunks before the `run` invoke resolves, so a subscription
+ // opened after the ack would miss the head of the output.
+ expect(onEvent.mock.invocationCallOrder[0]).toBeLessThan(runSetup.mock.invocationCallOrder[0])
+ })
+
+ it('runs the archive script from its own button', async () => {
+ await mountPanel(snapshotWith({ archiveScript: 'rm -rf node_modules' }))
+ await act(async () => {
+ button('Run archive').click()
+ })
+ expect(runSetup).toHaveBeenCalledWith('p1', 'archive', undefined)
+ })
+
+ it('disables the button whose script is not set', async () => {
+ await mountPanel(snapshotWith({ setupScript: 'make' }))
+ expect(button('Run setup').disabled).toBe(false)
+ expect(button('Run archive').disabled).toBe(true)
+ })
+
+ it('uses the EFFECTIVE value: a machine-local script enables the button with none shared', async () => {
+ await mountPanel({ shared: null, local: { setup: { setupScript: 'local-only.sh' } } })
+ expect(button('Run setup').disabled).toBe(false)
+ })
+
+ it('disables both for a project with nowhere to run — no folder and no server', async () => {
+ await mountPanel(snapshotWith({ setupScript: 'make', archiveScript: 'clean' }), project({ cwd: undefined }))
+ expect(button('Run setup').disabled).toBe(true)
+ expect(button('Run archive').disabled).toBe(true)
+ })
+
+ it('shows the live output in a log box and disables the buttons while the run is going', async () => {
+ await mountPanel(snapshotWith({ setupScript: 'make', archiveScript: 'clean' }))
+ expect(log()).toBeNull()
+ await act(async () => {
+ button('Run setup').click()
+ })
+ act(() => emit({ runKey: 'run-1', 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)
+ expect(hasButton('Cancel')).toBe(true)
+ })
+
+ it('cancels the live run by its runKey', async () => {
+ await mountPanel(snapshotWith({ setupScript: 'make' }))
+ await act(async () => {
+ button('Run setup').click()
+ })
+ act(() => emit({ runKey: 'run-1', kind: 'setup', seq: 1, state: 'running', chunk: 'x' }))
+ await act(async () => {
+ button('Cancel').click()
+ })
+ expect(cancel).toHaveBeenCalledWith('run-1')
+ })
+
+ it('reports the exit code when the run ends, and re-enables the buttons', async () => {
+ await mountPanel(snapshotWith({ setupScript: 'make' }))
+ 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 }))
+ expect(host.textContent).toContain('2')
+ expect(host.textContent?.toLowerCase()).toContain('failed')
+ expect(button('Run setup').disabled).toBe(false)
+ expect(hasButton('Cancel')).toBe(false)
+ })
+
+ it('explains a REFUSED run instead of looking like nothing happened', async () => {
+ runSetup.mockResolvedValue({ status: 'skipped', reason: 'declined' })
+ await mountPanel(snapshotWith({ setupScript: 'make' }))
+ await act(async () => {
+ button('Run setup').click()
+ })
+ expect(host.textContent?.toLowerCase()).toContain('skipped')
+ expect(button('Run setup').disabled).toBe(false)
+ })
+
+ it('drops the subscription when the pane goes away', async () => {
+ await mountPanel(snapshotWith({ setupScript: 'make' }))
+ await act(async () => {
+ button('Run setup').click()
+ })
+ act(() => root.unmount())
+ expect(off).toHaveBeenCalledTimes(1)
+ root = createRoot(host)
+ })
+})
diff --git a/src/renderer/components/settings/sections/ProjectSettingsSection.tsx b/src/renderer/components/settings/sections/ProjectSettingsSection.tsx
index c5f924eb9..51f5adb51 100644
--- a/src/renderer/components/settings/sections/ProjectSettingsSection.tsx
+++ b/src/renderer/components/settings/sections/ProjectSettingsSection.tsx
@@ -342,6 +342,9 @@ function EditableProjectSection({
// Only the shell knows WHERE this project lives; a folderless inline canvas tab has no
// shared settings file and never can have one — see `sharedEditable`.
sharedEditable={Boolean(project.cwd || project.ssh)}
+ // Same predicate today, deliberately a separate prop: this one gates SPAWNING a setup
+ // script, not writing the shared file — see `FamilySection`'s `canRun`.
+ canRun={Boolean(project.cwd || project.ssh)}
saveShared={settings.saveShared}
saveLocal={settings.saveLocal}
reload={settings.reload}
diff --git a/src/renderer/state/projectSetup.test.ts b/src/renderer/state/projectSetup.test.ts
new file mode 100644
index 000000000..7e7268642
--- /dev/null
+++ b/src/renderer/state/projectSetup.test.ts
@@ -0,0 +1,116 @@
+// @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.
+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',
+ kind: 'setup',
+ seq: 1,
+ state: 'running',
+ ...over
+})
+
+const apply = (e: ProjectSetupEvent, groupId?: string): void =>
+ useProjectSetup.getState().applyEvent('p1', e, groupId)
+
+beforeEach(() => {
+ useProjectSetup.setState({ byProject: {}, byGroup: {} })
+})
+
+describe('useProjectSetup', () => {
+ 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')
+ expect(run.kind).toBe('setup')
+ expect(run.state).toBe('running')
+ expect(run.tail).toBe('installing…\ndone\n')
+ })
+
+ it('drops a DUPLICATE seq — a re-delivered event must not double the output', () => {
+ 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')
+ })
+
+ it('drops a STALE seq that arrives after a newer one', () => {
+ apply(ev({ seq: 1, chunk: 'a' }))
+ apply(ev({ seq: 3, chunk: 'c' }))
+ // 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!
+ expect(run.tail).toBe('ac')
+ expect(run.state).toBe('running')
+ expect(run.exitCode).toBeUndefined()
+ })
+
+ 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!
+ expect(tail.length).toBe(SETUP_TAIL_MAX)
+ expect(tail.endsWith('TAIL')).toBe(true)
+ expect(tail.startsWith('x')).toBe(true)
+ })
+
+ 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)
+ })
+
+ 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!
+ 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', () => {
+ 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')
+ expect(run.state).toBe('running')
+ expect(run.tail).toBe('second\n')
+ expect(run.exitCode).toBeUndefined()
+ })
+
+ it('routes a worktree run to byGroup, leaving the project entry alone', () => {
+ 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')
+ })
+
+ it('subscribeProject wires api.projectSetup.onEvent into applyEvent and returns its unsubscribe', () => {
+ let emit: ((e: ProjectSetupEvent) => void) | null = null
+ const off = vi.fn()
+ const onEvent = vi.fn((_projectId: string, cb: (e: ProjectSetupEvent) => void) => {
+ emit = cb
+ return off
+ })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { projectSetup: { onEvent } }
+ 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')
+ unsubscribe()
+ expect(off).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/renderer/state/projectSetup.ts b/src/renderer/state/projectSetup.ts
new file mode 100644
index 000000000..29646f88f
--- /dev/null
+++ b/src/renderer/state/projectSetup.ts
@@ -0,0 +1,111 @@
+import { create } from 'zustand'
+import type { ProjectSetupEvent, ProjectSetupKind } from '@shared/project-settings'
+
+/**
+ * Renderer view of the setup/archive runs main is streaming (`ProjectSetupEvent` on
+ * `IPC.projectSetupEvent(projectId)`). One entry per lane:
+ *
+ * - `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).
+ *
+ * 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.
+ */
+
+/** How much of a run's output the panel keeps, in characters. A setup script's output is
+ * unbounded (an `npm install` alone is tens of KB) and this is a status box, not a terminal: the
+ * END is what matters, because that is where the failure is. */
+export const SETUP_TAIL_MAX = 8 * 1024
+
+export interface SetupRunState {
+ runKey: string
+ kind: ProjectSetupKind
+ state: ProjectSetupEvent['state']
+ /** Last `SETUP_TAIL_MAX` characters of the run's output. */
+ tail: string
+ exitCode?: number
+ /** Highest `seq` applied for THIS `runKey` — 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
+ /** 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. */
+ subscribeProject(projectId: string): () => void
+}
+
+/** Appends `chunk` and keeps only the last `SETUP_TAIL_MAX` characters. */
+function appendTail(prev: string, chunk: string | undefined): string {
+ if (!chunk) return prev
+ const next = prev + chunk
+ 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.
+ */
+function foldEvent(prev: SetupRunState | undefined, ev: ProjectSetupEvent): SetupRunState | null {
+ if (prev && prev.runKey === ev.runKey) {
+ // Duplicate (re-delivered) or stale (overtaken): the watermark has already passed it.
+ if (ev.seq <= prev.seq) return null
+ return {
+ runKey: prev.runKey,
+ kind: ev.kind,
+ state: ev.state,
+ tail: appendTail(prev.tail, ev.chunk),
+ // A terminal event carries the code; a later event never un-sets one already reported.
+ ...(ev.exitCode !== undefined
+ ? { exitCode: ev.exitCode }
+ : prev.exitCode !== undefined
+ ? { exitCode: prev.exitCode }
+ : {}),
+ seq: ev.seq
+ }
+ }
+ return {
+ runKey: ev.runKey,
+ kind: ev.kind,
+ state: ev.state,
+ tail: appendTail('', ev.chunk),
+ ...(ev.exitCode !== undefined ? { exitCode: ev.exitCode } : {}),
+ seq: ev.seq
+ }
+}
+
+export const useProjectSetup = create<ProjectSetupState>((set, get) => ({
+ byProject: {},
+ byGroup: {},
+
+ 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)
+ if (!next) return
+ set((s) => ({ byProject: { ...s.byProject, [projectId]: next } }))
+ },
+
+ subscribeProject: (projectId) =>
+ window.nodeTerminal.projectSetup.onEvent(projectId, (ev) => {
+ get().applyEvent(projectId, ev)
+ })
+}))