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
feat(project-setup): local spawn runner + both-shell wiring
enesee7e22410d51
diff --git a/src/core/project-setup-runner-local.test.ts b/src/core/project-setup-runner-local.test.tsnew file mode 100644index 000000000..6495699ca--- /dev/null+++ b/src/core/project-setup-runner-local.test.ts@@ -0,0 +1,179 @@+import fs from 'fs'+import os from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import {+ SETUP_OUTPUT_CAP,+ makeLocalSetupRunner,+ resolveProjectSetupTarget,+ type ProjectSetupTargetInfo+} from './project-setup-runner-local'+import type { WorktreeListResult } from '../shared/worktree'++describe('makeLocalSetupRunner', () => {+ let tmpDir: string++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-setup-runner-'))+ })++ afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true })+ })++ const run = (+ script: string,+ opts: { env?: Record<string, string>; shell?: string; timeoutMs?: number; signal?: AbortSignal } = {}+ ) => {+ const runner = makeLocalSetupRunner({ shell: opts.shell, timeoutMs: opts.timeoutMs })+ const chunks: string[] = []+ const controller = new AbortController()+ const promise = runner({+ script,+ cwd: tmpDir,+ env: opts.env ?? {},+ onChunk: (text) => chunks.push(text),+ signal: opts.signal ?? controller.signal+ })+ return { promise, chunks, controller }+ }++ it('env vars passed to the runner are visible to the script', async () => {+ const { promise, chunks } = run('echo "$NODETERM_ROOT_PATH"', {+ env: { NODETERM_ROOT_PATH: '/some/root/path' }+ })+ const result = await promise+ expect(result.exitCode).toBe(0)+ expect(chunks.join('')).toContain('/some/root/path')+ })++ it('propagates the script exit code', async () => {+ const { promise } = run('exit 7')+ const result = await promise+ expect(result.exitCode).toBe(7)+ })++ it('runs in the given cwd', async () => {+ const { promise, chunks } = run('pwd')+ await promise+ // macOS temp dirs resolve through a /private symlink — compare realpaths.+ expect(chunks.join('').trim()).toBe(fs.realpathSync(tmpDir))+ })++ it('never rejects: a spawn error resolves exitCode 127 with the message as a chunk', async () => {+ const { promise, chunks } = run('echo hi', { shell: '/nonexistent/nope-shell-binary' })+ const result = await promise+ expect(result.exitCode).toBe(127)+ expect(chunks.join('').length).toBeGreaterThan(0)+ })++ it('caps combined output at SETUP_OUTPUT_CAP and appends exactly one truncation note', async () => {+ const { promise, chunks } = run('yes 0123456789abcdef0123456789abcdef 2>&1', { timeoutMs: 500 })+ const result = await promise+ const combined = chunks.join('')+ // A generous margin over the cap: the last chunk that crosses the budget can carry a partial+ // line plus the truncation note, but nothing appended AFTER truncation.+ expect(Buffer.byteLength(combined, 'utf-8')).toBeLessThan(SETUP_OUTPUT_CAP + 200)+ expect(combined.match(/truncated/g)?.length).toBe(1)+ // Killed by the timeout's SIGKILL (yes never exits on its own).+ expect(result.exitCode).not.toBe(0)+ }, 10_000)++ it('an abort signal kills the process promptly', async () => {+ const controller = new AbortController()+ const { promise } = run('sleep 30', { timeoutMs: 60_000, signal: controller.signal })+ const start = Date.now()+ setTimeout(() => controller.abort(), 30)+ const result = await promise+ expect(Date.now() - start).toBeLessThan(3000)+ expect(result.exitCode).not.toBe(0)+ }, 10_000)++ it('coalesces rapid writes into fewer onChunk calls than lines written (debounced)', async () => {+ const { promise, chunks } = run('echo one; echo two; echo three')+ const result = await promise+ expect(result.exitCode).toBe(0)+ expect(chunks.length).toBeLessThan(3)+ const combined = chunks.join('')+ expect(combined).toContain('one')+ expect(combined).toContain('two')+ expect(combined).toContain('three')+ })+})++describe('resolveProjectSetupTarget', () => {+ const okList = (paths: string[]): ((repoPath: string) => Promise<WorktreeListResult>) =>+ async () => ({ ok: true, entries: paths.map((p) => ({ path: p, branch: null, head: null, isBare: false })) })++ it('refuses an unknown project id (null info)', async () => {+ const result = await resolveProjectSetupTarget('missing', undefined, null, okList([]))+ expect(result).toBeNull()+ })++ it('refuses an inline/cwd-less local project (no cwd, no ssh)', async () => {+ const info: ProjectSetupTargetInfo = { name: 'inline' }+ const result = await resolveProjectSetupTarget('p1', undefined, info, okList([]))+ expect(result).toBeNull()+ })++ it('builds a local target with no worktreePath', async () => {+ const info: ProjectSetupTargetInfo = { name: 'proj', cwd: '/repo' }+ const result = await resolveProjectSetupTarget('p1', undefined, info, okList([]))+ expect(result).toEqual({ projectId: 'p1', projectName: 'proj', rootPath: '/repo' })+ })++ it('accepts a worktreePath equal to rootPath', async () => {+ const info: ProjectSetupTargetInfo = { name: 'proj', cwd: '/repo' }+ const result = await resolveProjectSetupTarget('p1', '/repo', info, okList([]))+ expect(result?.worktreePath).toBe(path.resolve('/repo'))+ })++ it('accepts a worktreePath matching a listed git worktree (sibling directory, NOT nested)', async () => {+ const info: ProjectSetupTargetInfo = { name: 'proj', cwd: '/repo' }+ const wt = '/repo.worktrees/my-branch'+ const result = await resolveProjectSetupTarget('p1', wt, info, okList(['/repo', wt]))+ expect(result?.worktreePath).toBe(path.resolve(wt))+ })++ it('refuses a worktreePath that is not a listed worktree', async () => {+ const info: ProjectSetupTargetInfo = { name: 'proj', cwd: '/repo' }+ const result = await resolveProjectSetupTarget('p1', '/etc/passwd', info, okList(['/repo']))+ expect(result).toBeNull()+ })++ it('refuses a relative worktreePath (must be absolute)', async () => {+ const info: ProjectSetupTargetInfo = { name: 'proj', cwd: '/repo' }+ const result = await resolveProjectSetupTarget('p1', 'relative/path', info, okList(['/repo']))+ expect(result).toBeNull()+ })++ it('refuses when the worktree listing itself failed (ok:false)', async () => {+ const info: ProjectSetupTargetInfo = { name: 'proj', cwd: '/repo' }+ const listFails = async (): Promise<WorktreeListResult> => ({ ok: false, entries: [] })+ const result = await resolveProjectSetupTarget('p1', '/repo.worktrees/b', info, listFails)+ expect(result).toBeNull()+ })++ it('refuses when the worktree listing throws', async () => {+ const info: ProjectSetupTargetInfo = { name: 'proj', cwd: '/repo' }+ const listThrows = async (): Promise<WorktreeListResult> => {+ throw new Error('git not found')+ }+ const result = await resolveProjectSetupTarget('p1', '/repo.worktrees/b', info, listThrows)+ expect(result).toBeNull()+ })++ it('builds an ssh target with no worktreePath', async () => {+ const ssh = { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }+ const info: ProjectSetupTargetInfo = { name: 'proj', ssh }+ const result = await resolveProjectSetupTarget('p1', undefined, info, okList([]))+ expect(result).toEqual({ projectId: 'p1', projectName: 'proj', rootPath: '/srv/app', ssh })+ })++ it('refuses an ssh target with a worktreePath — worktrees are local-only', async () => {+ const ssh = { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }+ const info: ProjectSetupTargetInfo = { name: 'proj', ssh }+ const result = await resolveProjectSetupTarget('p1', '/srv/app', info, okList([]))+ expect(result).toBeNull()+ })+})diff --git a/src/core/project-setup-runner-local.ts b/src/core/project-setup-runner-local.tsnew file mode 100644index 000000000..f19d3895c--- /dev/null+++ b/src/core/project-setup-runner-local.ts@@ -0,0 +1,222 @@+import { execFile, spawn } from 'child_process'+import path from 'path'+import { findInPathString, shellPathNow } from './exec-path'+import type { ProjectSetupRunner, ProjectSetupTarget } from './project-setup-service'+import type { WorktreeListResult } from '../shared/worktree'++/** Combined stdout+stderr budget for one run — the SAME cap `ProjectSetupEvent.chunk` documents+ * ("stdout+stderr interleaved, capped"). Deliberately one shared budget rather than one per+ * stream: a script that floods only stderr must not get 1MB total just because stdout stayed+ * quiet. */+export const SETUP_OUTPUT_CAP = 512 * 1024+/** SIGKILL a run that outlives this — a hung `setupScript` must never wedge the single-flight+ * slot forever. Test-injectable via `opts.timeoutMs` so a suite doesn't wait 10 real minutes. */+export const SETUP_TIMEOUT_MS = 10 * 60 * 1000+/** Chunks are batched to `onChunk` at most this often (plus one final flush on exit), matching+ * the debounce the brief calls for — a script that `echo`s in a tight loop must not turn into+ * an event per line. */+const FLUSH_DEBOUNCE_MS = 150++const TRUNCATION_NOTE = '\n[output truncated — exceeded 512KB]\n'++/** Resolve a configured shell to an absolute path via the cached login-shell PATH (exec-path.ts) —+ * a GUI process's inherited PATH misses Homebrew/nvm/etc, the same problem commit-message.ts's+ * `resolveBinary` solves for commit agents. An explicit path (contains a separator) is used as-is;+ * an unresolvable bare name is handed to `spawn` unchanged so ITS own PATH search gets a chance+ * (and a genuine ENOENT still surfaces cleanly through the runner's `error` handling below). */+function resolveShellBin(shell: string): string {+ if (shell.includes('/') || shell.includes('\\')) return shell+ return findInPathString(shell, shellPathNow() ?? process.env.PATH) ?? shell+}++/**+ * The local half of `ProjectSetupRunner` (Task 1's `project-setup-service.ts` injects it as+ * `runLocal`): `spawn(shell, ['-lc', script], …)` with the commit-message.ts spawn discipline —+ * capped+debounced output, a hard timeout, an abort-signal kill, and a Promise that NEVER rejects+ * (a spawn failure resolves `{exitCode: 127}` with the error text as a chunk, exactly like a+ * failed script run — the service layer has one failure shape to handle, not two).+ */+export function makeLocalSetupRunner(opts?: { shell?: string; timeoutMs?: number }): ProjectSetupRunner {+ const shell = opts?.shell?.trim() || 'sh'+ const timeoutMs = opts?.timeoutMs ?? SETUP_TIMEOUT_MS++ return ({ script, cwd, env, onChunk, signal }) =>+ new Promise((resolve) => {+ // Already aborted before we ever spawned (a cancel raced the async gate above this call) —+ // nothing to kill, and starting a process now would leak one nobody is waiting for.+ if (signal.aborted) {+ resolve({ exitCode: 143 })+ return+ }++ let totalBytes = 0+ let truncated = false+ let pending = ''+ let flushTimer: ReturnType<typeof setTimeout> | null = null++ const flush = (): void => {+ if (flushTimer) {+ clearTimeout(flushTimer)+ flushTimer = null+ }+ if (!pending) return+ const text = pending+ pending = ''+ onChunk(text)+ }++ const scheduleFlush = (): void => {+ if (flushTimer) return+ flushTimer = setTimeout(flush, FLUSH_DEBOUNCE_MS)+ flushTimer.unref?.()+ }++ const append = (text: string): void => {+ if (!text || truncated) return+ const remaining = SETUP_OUTPUT_CAP - totalBytes+ if (remaining <= 0) {+ truncated = true+ pending += TRUNCATION_NOTE+ scheduleFlush()+ return+ }+ const asBytes = Buffer.byteLength(text, 'utf-8')+ if (asBytes <= remaining) {+ pending += text+ totalBytes += asBytes+ } else {+ const cut = Buffer.from(text, 'utf-8').subarray(0, remaining).toString('utf-8')+ pending += cut+ totalBytes += Buffer.byteLength(cut, 'utf-8')+ truncated = true+ pending += TRUNCATION_NOTE+ }+ scheduleFlush()+ }++ const isWin = process.platform === 'win32'+ const shellBin = resolveShellBin(shell)+ const child = spawn(shellBin, ['-lc', script], {+ cwd,+ env: { ...process.env, ...env },+ stdio: ['ignore', 'pipe', 'pipe'],+ windowsHide: true,+ // POSIX: a new session/process-group leader (setsid), so `killTree` below can SIGKILL the+ // whole group — not just the shell. A script's own children (`npm install` spawning its own+ // tree, a backgrounded `sleep`, `yes | …`) inherit our stdout/stderr pipes; killing only the+ // immediate shell leaves them running and holding those pipes open, so `close` never fires+ // and cancel/timeout silently do nothing until the orphan exits on its own. Verified: killing+ // only the direct child hangs `close` for the ORPHAN's remaining lifetime, not ours.+ detached: !isWin+ })++ // Kill the shell AND every process it spawned (see the `detached` comment above) — never just+ // the shell itself. POSIX: SIGKILL the whole process group via the negative pid. Windows has no+ // such group-kill; `taskkill /t` walks the same parent-child tree `detached` would have no+ // effect on anyway, so Windows never opts into `detached`.+ const killTree = (): void => {+ if (!child.pid) return+ if (isWin) {+ execFile('taskkill', ['/pid', String(child.pid), '/t', '/f'], () => {+ // Best-effort: ENOENT/'not found' just means it already exited.+ })+ } else {+ try {+ process.kill(-child.pid, 'SIGKILL')+ } catch {+ // The group is already gone (process exited between our check and this call) — nothing+ // left to kill.+ }+ }+ }++ const timeoutTimer = setTimeout(killTree, timeoutMs)+ timeoutTimer.unref?.()+ const onAbort = (): void => killTree()+ signal.addEventListener('abort', onAbort)++ const finish = (exitCode: number): void => {+ clearTimeout(timeoutTimer)+ signal.removeEventListener('abort', onAbort)+ flush() // final flush — whatever the debounce timer hadn't fired yet+ resolve({ exitCode })+ }++ child.stdout?.on('data', (d: Buffer) => append(d.toString('utf-8')))+ child.stderr?.on('data', (d: Buffer) => append(d.toString('utf-8')))+ // Never reject: a spawn failure (bad shell path, EACCES, …) is reported the same way a+ // failing SCRIPT is — a chunk plus a non-zero exit — so the service layer has one shape to+ // handle either way.+ child.on('error', (e) => {+ append(`${(e as Error).message}\n`)+ finish(127)+ })+ child.on('close', (code) => finish(code ?? 1))+ })+}++/** Minimal shape `resolveProjectSetupTarget` needs from the workspace index — see+ * `WorkspaceStore.projectTargetInfo`. */+export interface ProjectSetupTargetInfo {+ cwd?: string+ ssh?: ProjectSetupTarget['ssh']+ name: string+}++/**+ * Turns a renderer's `(projectId, worktreePath?)` into a fully-trusted `ProjectSetupTarget`, or+ * `null` when it cannot — the CARRIED Task 1 review finding: `rootPath`/`projectName`/`ssh` are+ * NEVER taken from the renderer (a hostile/compromised renderer could otherwise name any path on+ * disk, or forge an `ssh` target pointing somewhere it does not own). `info` comes straight from+ * `WorkspaceStore.projectTargetInfo(projectId)` — the machine-local index, not attacker-controlled+ * `project.json` content.+ *+ * `worktreePath`, when given, must be an absolute path that is either the project's own rootPath OR+ * one of ITS ACTUAL git worktrees (`listWorktrees`, e.g. `GitService.worktreeList` bound to the+ * caller's instance) — never a plain "is it a subdirectory of rootPath" check: the default worktree+ * layout (`../${repoName}.worktrees/${branch}`, see shared/worktree.ts) is a SIBLING of the repo,+ * not nested under it, so containment would reject the common case. Worktrees are local-only (the+ * SDD plan's ruling): an ssh target with a worktreePath is refused outright rather than silently+ * dropping the worktree half.+ *+ * Exported (not file-private) so it is unit-testable without Electron/git — callers pass a fake+ * `listWorktrees` in tests, and the real `GitService#worktreeList` in main/server wiring.+ */+export async function resolveProjectSetupTarget(+ projectId: string,+ worktreePath: string | undefined,+ info: ProjectSetupTargetInfo | null,+ listWorktrees: (repoPath: string) => Promise<WorktreeListResult>+): Promise<ProjectSetupTarget | null> {+ if (!info) return null++ if (info.ssh) {+ // Worktrees are local-only (git runs against a local filesystem) — a worktreePath alongside an+ // ssh target is either a stale renderer state or hostile input. Refuse rather than guess which.+ if (worktreePath !== undefined) return null+ return { projectId, projectName: info.name, rootPath: info.ssh.remoteCwd, ssh: info.ssh }+ }++ // No local folder and no ssh target — an inline/cwd-less canvas has nothing to run against.+ if (!info.cwd) return null++ const target: ProjectSetupTarget = { projectId, projectName: info.name, rootPath: info.cwd }+ if (worktreePath === undefined) return target++ if (!path.isAbsolute(worktreePath)) return null+ const resolvedRoot = path.resolve(info.cwd)+ const resolvedWt = path.resolve(worktreePath)+ if (resolvedWt !== resolvedRoot) {+ let listed: WorktreeListResult+ try {+ listed = await listWorktrees(info.cwd)+ } catch {+ return null+ }+ if (!listed.ok) return null+ const known = listed.entries.some((e) => path.resolve(e.path) === resolvedWt)+ if (!known) return null+ }+ target.worktreePath = resolvedWt+ return target+}diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 7b411167a..7e3816dfb 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -1015,6 +1015,16 @@ export class WorkspaceStore {return this.index?.entries.find((e) => e.id === projectId && e.cwd)?.cwd}+ /** Minimal per-project target info for the setup/archive runner (project-setup-runner-local.ts's+ * `resolveProjectSetupTarget`) — cwd/ssh/name straight off the loaded index. Sync, like+ * `localCwdForProject`: this is what closes the Task 1 review finding that a run's rootPath/+ * ssh/projectName must come from THIS machine's own index, never from whatever the renderer+ * happened to send. */+ projectTargetInfo(projectId: string): { cwd?: string; ssh?: Project['ssh']; name: string } | null {+ const e = this.index?.entries.find((x) => x.id === projectId)+ return e ? { cwd: e.cwd, ssh: e.ssh, name: e.name } : null+ }+/** Resolve the shared project together with its machine-local trust identity. The approval id* never enters the shared project object or project.json. */async githubProject(projectId: string): Promise<{diff --git a/src/main/index.ts b/src/main/index.tsindex 7f4aba1f7..0526e4b2d 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -63,6 +63,10 @@ import { registerAgentEnvIpc } from '../core/agent-env-ipc'import { presenceHub } from '../core/presence/hub'import { SshStore } from './ssh-store'import { GitService } from '../core/git-service'+import { ProjectTrustStore } from '../core/project-trust-store'+import { ProjectSetupService } from '../core/project-setup-service'+import { registerProjectSetupHandlers, type ProjectSetupHandlerService } from '../core/project-setup-handlers'+import { makeLocalSetupRunner, resolveProjectSetupTarget } from '../core/project-setup-runner-local'import { registerGitHubIntegration } from '../core/github/integration'import { runGitHubCliCommand } from '../core/github/credentials'import {@@ -340,6 +344,38 @@ workspaceStore.onPersist = () => {}const gitService = new GitService()+// Project setup/archive runner (SDD: 2026-08-19-project-settings-trust). The trust store is keyed+// by LOCATION, never project id (hostile-project-json), so one instance covers every project.+// `readSettings` reuses WorkspaceStore's own resolution instead of re-reading disk.+const projectTrustStore = new ProjectTrustStore()+const projectSetupService = new ProjectSetupService({+ trust: projectTrustStore,+ readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),+ runLocal: makeLocalSetupRunner()+ // runSsh: a later task's manual-run leg. Until wired, an ssh target's run answers+ // `{status:'skipped', reason:'unavailable'}` — same as any other missing runner.+})+// `registerProjectSetupHandlers` (project-setup-handlers.ts) shape-checks its wire `target` but+// otherwise trusts whatever it is given — a deliberate low-level seam (Task 1). The TRUST boundary+// lives here instead: `target.rootPath`/`projectName`/`ssh` are the wire's own placeholders (see+// preload's `projectSetup.run`) and are IGNORED — rootPath/ssh/projectName are re-derived from THIS+// machine's own workspace index by `target.projectId`, and `worktreePath` is independently+// re-validated against the project's actual git worktrees (`resolveProjectSetupTarget`). Nothing+// path-shaped that crosses the wire is trusted as-is (Task 1 review finding, carried to this task).+const projectSetupHandlerService: ProjectSetupHandlerService = {+ run: async (target, kind) => {+ const info = workspaceStore.projectTargetInfo(target.projectId)+ const resolved = await resolveProjectSetupTarget(target.projectId, target.worktreePath, info, (repoPath) =>+ gitService.worktreeList(repoPath)+ )+ if (!resolved) return { status: 'skipped', reason: 'unavailable' }+ return projectSetupService.run(resolved, kind)+ },+ cancel: (runKey) => projectSetupService.cancel(runKey),+ submitConsent: (requestId, answer) => projectSetupService.submitConsent(requestId, answer)+}+registerProjectSetupHandlers(corePlatform, projectSetupHandlerService)+// Markers delimiting the `projects.list` relay blob. The iOS client splits on these exact// strings to recover [workspace.json | newline-joined tmux session names | agent-status.json],// matching the SSH browse pipeline it already uses — keep them in sync with NodetermProjects.swift.diff --git a/src/preload/index.ts b/src/preload/index.tsindex 73cce0a7f..d2f2a7a80 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -18,6 +18,7 @@ import type {WorkspaceMigrationKind} from '../shared/types'import type { ClientId, PeerDiff, PeerIdentity, PeerState } from '../shared/presence'+import type { ProjectSetupConsentRequest, ProjectSetupEvent } from '../shared/project-settings'// Fan a single ipcRenderer listener per channel out to many renderer subscribers. Without// this, every node that subscribes (e.g. Cmd+M markdown toggle on each terminal/editor) adds@@ -54,6 +55,15 @@ const subscribeRelayPeerPending = subscribe<[RelayPeerPending]>(IPC.relayHostPeeconst subscribeRelayHostOpen = subscribe<[{ id: string; email?: string }]>(IPC.relayHostOpen)const subscribeRelayHostClosed = subscribe<[{ id: string }]>(IPC.relayHostClosed)+// Project setup/archive (SDD: 2026-08-19-project-settings-trust): global (not per-project) main →+// renderer prompts, fanned out the same way as the relay events above.+const subscribeProjectSetupConsentRequest = subscribe<[ProjectSetupConsentRequest]>(+ IPC.projectSetupConsentRequest+)+const subscribeProjectSetupConsentDismiss = subscribe<[{ requestId: string }]>(+ IPC.projectSetupConsentDismiss+)+const api: NodeTerminalApi = {pty: {create: (options: PtyCreateOptions) => ipcRenderer.invoke(IPC.ptyCreate, options),@@ -144,6 +154,35 @@ const api: NodeTerminalApi = {updateLocal: (projectId: string, local) =>ipcRenderer.invoke(IPC.projectSettingsUpdateLocal, projectId, local)},+ projectSetup: {+ // The wire's `target` first argument is `project-setup-handlers.ts`'s `sanitizeTarget` shape+ // (Task 1) — `projectName`/`rootPath` here are UNUSED PLACEHOLDERS satisfying that shape only;+ // main re-derives the real rootPath/projectName/ssh from its own workspace index by projectId+ // and never trusts what crosses this wire (Task 1 review finding — see main/index.ts's+ // `projectSetupHandlerService`). Only `projectId`/`worktreePath` cross meaningfully.+ run: (projectId, kind, worktreePath) =>+ ipcRenderer.invoke(+ IPC.projectSetupRun,+ { projectId, projectName: '', rootPath: '.', ...(worktreePath ? { worktreePath } : {}) },+ kind+ ),+ cancel: (runKey: string) => ipcRenderer.invoke(IPC.projectSetupCancel, runKey),+ consent: async (requestId, answer) => {+ ipcRenderer.send(IPC.projectSetupConsentSubmit, requestId, answer)+ },+ onConsentRequest: subscribeProjectSetupConsentRequest,+ onConsentDismiss: subscribeProjectSetupConsentDismiss,+ onEvent: (projectId, cb) => {+ const ch = IPC.projectSetupEvent(projectId)+ const handler = (_e: unknown, ev: ProjectSetupEvent): void => cb(ev)+ ipcRenderer.on(ch, handler)+ ipcRenderer.send(IPC.projectSetupSubscribe, projectId)+ return () => {+ ipcRenderer.removeListener(ch, handler)+ ipcRenderer.send(IPC.projectSetupUnsubscribe, projectId)+ }+ }+ },dialog: {selectFolder: () => ipcRenderer.invoke(IPC.dialogSelectFolder),selectFile: () => ipcRenderer.invoke(IPC.dialogSelectFile)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 367bb1299..5d32345e5 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -303,6 +303,18 @@ export function buildStubApi(): Omit<writeShared: () => Promise.resolve(false),updateLocal: () => Promise.resolve(false)},+ projectSetup: {+ // Same fallback story as `projectSettings` above — real over the bridge+ // (`buildRealApi`'s `projectSetup`); this only matters if some future assembly spreads the+ // stub alone. `run` fails closed with the SAME shape a real "nothing to run" answer uses, so+ // a caller needs no extra branch to handle the stub differently from the real thing.+ run: () => Promise.resolve({ status: 'skipped', reason: 'unavailable' }),+ cancel: () => Promise.resolve(false),+ consent: pnoop,+ onConsentRequest: noopUnsub,+ onConsentDismiss: noopUnsub,+ onEvent: noopUnsub+ },chat: {readTranscript: U('chat.readTranscript')},diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 120fcda95..be5233dcd 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -209,7 +209,10 @@ const AI_NAMING_UNAVAILABLE = {* invoke(→request)/send(→cast) split exactly. */export function buildRealApi(client: RpcClient-): Pick<NodeTerminalApi, 'pty' | 'workspace' | 'projectSettings' | 'settings' | 'agent' | 'userDataDir'> {+): Pick<+ NodeTerminalApi,+ 'pty' | 'workspace' | 'projectSettings' | 'projectSetup' | 'settings' | 'agent' | 'userDataDir'+> {const pty: PtyApi = {create: (options: PtyCreateOptions) =>client.request(IPC.ptyCreate, options) as ReturnType<PtyApi['create']>,@@ -301,6 +304,32 @@ export function buildRealApi(client.request(IPC.projectSettingsUpdateLocal, projectId, local) as Promise<boolean>}+ // REAL: registerProjectSetupHandlers (core) is wired on the same construction-order point as+ // src/main/index.ts — see the "target.rootPath/projectName/ssh are placeholders" comment there.+ // `run`'s wire shape mirrors the preload's exactly, for the same reason.+ const projectSetup: NodeTerminalApi['projectSetup'] = {+ run: (projectId, kind, worktreePath) =>+ client.request(+ IPC.projectSetupRun,+ { projectId, projectName: '', rootPath: '.', ...(worktreePath ? { worktreePath } : {}) },+ kind+ ) as ReturnType<NodeTerminalApi['projectSetup']['run']>,+ cancel: (runKey) => client.request(IPC.projectSetupCancel, runKey) as Promise<boolean>,+ consent: async (requestId, answer) => {+ client.cast(IPC.projectSetupConsentSubmit, requestId, answer)+ },+ onConsentRequest: (cb) => client.subscribe(IPC.projectSetupConsentRequest, cb as Listener),+ onConsentDismiss: (cb) => client.subscribe(IPC.projectSetupConsentDismiss, cb as Listener),+ onEvent: (projectId, cb) => {+ const unsub = client.subscribe(IPC.projectSetupEvent(projectId), cb as Listener)+ client.cast(IPC.projectSetupSubscribe, projectId)+ return () => {+ unsub()+ client.cast(IPC.projectSetupUnsubscribe, projectId)+ }+ }+ }+const settings: SettingsApi = {load: () => client.request(IPC.settingsLoad) as Promise<Settings>,save: (s: Settings) => client.request(IPC.settingsSave, s) as Promise<void>@@ -335,7 +364,7 @@ export function buildRealApi(// `/worktrees/…` at the filesystem root (the server usually runs as root, and git would create it).const userDataDir = (): Promise<string> => client.request(IPC.appUserDataDir) as Promise<string>- return { pty, workspace, projectSettings, settings, agent, userDataDir }+ return { pty, workspace, projectSettings, projectSetup, settings, agent, userDataDir }}export function buildGitHubApi(diff --git a/src/server/index.ts b/src/server/index.tsindex 71c6f1f6b..59e0ea9b4 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -31,6 +31,10 @@ import {} from '../core/model-gateway-credentials'import { DownloadTickets } from '../core/download-tickets'import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'+import { ProjectTrustStore } from '../core/project-trust-store'+import { ProjectSetupService } from '../core/project-setup-service'+import { registerProjectSetupHandlers, type ProjectSetupHandlerService } from '../core/project-setup-handlers'+import { makeLocalSetupRunner, resolveProjectSetupTarget } from '../core/project-setup-runner-local'import { LogBuffer } from '../core/log-buffer'import { installLogSink } from '../core/log-sink'import { registerLogHandlers } from '../core/log-handlers'@@ -266,6 +270,34 @@ export async function startServer(downloadTickets,localProjectCwd: (projectId: string) => workspaceStore.localCwdForProject(projectId)})+ // Project setup/archive runner — same construction + trust boundary as src/main/index.ts. No ssh+ // leg here at all (the Server Edition has no SSH projects, same reason board-log's router below+ // never resolves one): `resolveProjectSetupTarget` degrades an ssh-shaped index entry to+ // `unavailable` on its own since `info.ssh` is never populated on this shell.+ const projectTrustStore = new ProjectTrustStore()+ const projectSetupService = new ProjectSetupService({+ trust: projectTrustStore,+ readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),+ runLocal: makeLocalSetupRunner()+ })+ // See src/main/index.ts's matching comment: `target.rootPath`/`projectName`/`ssh` on the wire are+ // placeholders (preload/ws-bridge never send real ones) and are IGNORED here — rootPath/ssh/+ // projectName are re-derived from this process's own workspace index by `target.projectId`, and+ // `worktreePath` is independently re-validated against the project's actual git worktrees.+ const projectSetupHandlerService: ProjectSetupHandlerService = {+ run: async (target, kind) => {+ const info = workspaceStore.projectTargetInfo(target.projectId)+ const resolved = await resolveProjectSetupTarget(target.projectId, target.worktreePath, info, (repoPath) =>+ gitService.worktreeList(repoPath)+ )+ if (!resolved) return { status: 'skipped', reason: 'unavailable' }+ return projectSetupService.run(resolved, kind)+ },+ cancel: (runKey) => projectSetupService.cancel(runKey),+ submitConsent: (requestId, answer) => projectSetupService.submitConsent(requestId, answer)+ }+ registerProjectSetupHandlers(platform, projectSetupHandlerService)+const github = registerGitHubIntegration({platform,userDataDir: config.dataDir,diff --git a/src/shared/types.ts b/src/shared/types.tsindex dac640707..659f72d14 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -768,6 +768,31 @@ export interface ProjectSettingsApi {): Promise<boolean>}+export interface ProjectSetupApi {+ /** Launch a project's setup/archive script behind the trust gate (`project-setup-service.ts`).+ * `worktreePath`, when given, is the ONLY path-shaped hint this call carries — main derives+ * `rootPath`/`ssh` from its own workspace index by `projectId` and independently validates+ * `worktreePath` against that project's actual git worktrees; nothing path-shaped sent here is+ * trusted as-is (Task 1 review finding). */+ run(+ projectId: string,+ kind: import('./project-settings').ProjectSetupKind,+ worktreePath?: string+ ): Promise<import('./project-settings').ProjectSetupRunResult>+ /** Aborts a live run, or one still waiting at its consent dialog. `false` = nothing by that+ * runKey exists (already finished, or never did). */+ cancel(runKey: string): Promise<boolean>+ /** Renderer's answer to a `onConsentRequest` prompt. A stale/unknown requestId is a silent no-op. */+ consent(requestId: string, answer: import('./project-settings').ProjectSetupConsentAnswer): Promise<void>+ /** main → renderer: raise the trust dialog before a shared-sourced script runs. */+ onConsentRequest(cb: (req: import('./project-settings').ProjectSetupConsentRequest) => void): () => void+ /** main → renderer: close a prompt nobody answered before the renderer did. */+ onConsentDismiss(cb: (p: { requestId: string }) => void): () => void+ /** Per-project run progress (`ProjectSetupEvent`), mirroring `boardLog.onChanged`'s ref-counted+ * subscribe/unsubscribe shape. */+ onEvent(projectId: string, cb: (ev: import('./project-settings').ProjectSetupEvent) => void): () => void+}+export interface DialogApi {/** Opens a native folder picker; returns the chosen path or null if cancelled. */selectFolder(): Promise<string | null>@@ -2478,6 +2503,7 @@ export interface NodeTerminalApi {pty: PtyApiworkspace: WorkspaceApiprojectSettings: ProjectSettingsApi+ projectSetup: ProjectSetupApidialog: DialogApisettings: SettingsApispeech: SpeechApi