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): family-generic consent (agents/shell) + trust-changed broadcast

enese8ebf6cd8e50
diff --git a/src/core/project-setup-handlers.ts b/src/core/project-setup-handlers.ts
index 993e6df16..2df9c1548 100644
--- a/src/core/project-setup-handlers.ts
+++ b/src/core/project-setup-handlers.ts
@@ -2,7 +2,7 @@ import { IPC } from '../shared/ipc'
import type { ProjectSetupConsentAnswer, ProjectSetupKind, ProjectSetupRunResult } from '../shared/project-settings'
import type { WorktreeListResult } from '../shared/worktree'
import type { CorePlatform } from './platform'
-import type { ProjectSetupTarget } from './project-setup-service'
+import type { ProjectConsumerFamily, ProjectSetupTarget } from './project-setup-service'
import { resolveProjectSetupTarget, type ProjectSetupTargetInfo } from './project-setup-runner-local'
/**
@@ -27,6 +27,11 @@ export interface ProjectSetupHandlerService {
run(target: ProjectSetupTarget, kind: ProjectSetupKind): Promise<ProjectSetupRunResult>
cancel(runKey: string): boolean
submitConsent(requestId: string, answer: ProjectSetupConsentAnswer): void
+ /** The launch-settings gate (`ProjectSetupService.ensureFamilyTrusted`). OPTIONAL so a service
+ * built against the run-only surface still registers; the channel is registered either way and
+ * simply answers `false` — fail closed, never a missing-handler rejection a caller has to
+ * special-case. */
+ ensureFamilyTrusted?(target: ProjectSetupTarget, family: ProjectConsumerFamily): Promise<boolean>
}
/** What `registerProjectSetupHandlers` needs from its shell to resolve a trusted target — the
@@ -61,6 +66,23 @@ export function registerProjectSetupHandlers(
return service.run(target, kind)
}
)
+ platform.handle(
+ IPC.projectSetupRequestTrust,
+ async (projectId: unknown, family: unknown): Promise<boolean> => {
+ // `setup` is NOT accepted: that family is gated inside `run` itself, and admitting it here
+ // would hand a caller a run-less way to raise (and then answer) the host's setup dialog.
+ if (typeof projectId !== 'string' || !projectId) return false
+ if (family !== 'agents' && family !== 'shell') return false
+ const ask = service.ensureFamilyTrusted?.bind(service)
+ if (!ask) return false
+ // Same derivation as `run`, minus the worktree: trust is keyed to the project ROOT (a
+ // worktree inherits the root's approval), so there is no path-shaped argument at all here.
+ const info = deps.projectTargetInfo(projectId)
+ const target = await resolveProjectSetupTarget(projectId, undefined, info, deps.worktreeList)
+ if (!target) return false
+ return ask(target, family)
+ }
+ )
platform.handle(IPC.projectSetupCancel, (runKey: unknown) =>
typeof runKey === 'string' ? service.cancel(runKey) : false)
platform.on(IPC.projectSetupConsentSubmit, (requestId: unknown, answer: unknown) => {
diff --git a/src/core/project-setup-service.test.ts b/src/core/project-setup-service.test.ts
index fd064b82b..6c42584a2 100644
--- a/src/core/project-setup-service.test.ts
+++ b/src/core/project-setup-service.test.ts
@@ -11,6 +11,7 @@ import {
type ProjectSettingsFileV1,
type ProjectSettingsSnapshot,
type ProjectLocalSettings,
+ type ProjectConsentRequest,
type ProjectSetupConsentRequest,
type ProjectSetupEvent,
type ProjectSetupRunResult
@@ -736,3 +737,229 @@ describe('ProjectSetupService — disposeAll', () => {
expect(calls).toHaveLength(0)
})
})
+
+/**
+ * `ensureFamilyTrusted` — the SAME gate as the setup runner's, aimed at the two families nothing in
+ * this service executes: `agents` (launchCmd + env) and `shell` (the terminal program). A launcher
+ * asks before it consumes a shared-sourced value; the answer is recorded per FAMILY, at the
+ * LOCATION, and every asker's project is told to re-read its verdict.
+ */
+describe('ProjectSetupService — ensureFamilyTrusted', () => {
+ const familyPrompts = (family: 'agents' | 'shell'): ProjectConsentRequest[] =>
+ plat.sent
+ .filter((s) => s.channel === IPC.projectSetupConsentRequest)
+ .map((s) => s.args[0] as ProjectConsentRequest)
+ .filter((r) => r.family === family)
+
+ const trustChanged = (): string[] =>
+ plat.sent
+ .filter((s) => s.channel === IPC.projectTrustChanged)
+ .map((s) => (s.args[0] as { projectId: string }).projectId)
+
+ const agentsDoc: ProjectSettingsDoc = {
+ agents: { launchCmd: 'claude --mcp evil', env: { API_KEY: 'sk-1', PATH: '/evil/bin' } }
+ }
+
+ it('is promptless when the SHARED document has nothing executable in that family', async () => {
+ const trust = new ProjectTrustStore()
+ const svc = new ProjectSetupService({
+ trust,
+ // A LOCAL launchCmd is the user's own instruction and the shared doc sets nothing — there is
+ // no hostile input to gate, so a dialog here would be asking about the user's own typing.
+ readSettings: async () => snapshot(sharedFile({}), { agents: { launchCmd: 'mine' } })
+ })
+ expect(await svc.ensureFamilyTrusted(target(), 'agents')).toBe(true)
+ expect(await svc.ensureFamilyTrusted(target(), 'shell')).toBe(true)
+ expect(familyPrompts('agents')).toEqual([])
+ expect(familyPrompts('shell')).toEqual([])
+ expect(trustChanged()).toEqual([])
+ })
+
+ it('prompts with the whole agents family, and an approve records THE FAMILY hash + broadcasts', async () => {
+ const trust = new ProjectTrustStore()
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(agentsDoc)) })
+ const pending = svc.ensureFamilyTrusted(target(), 'agents')
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ const req = familyPrompts('agents')[0]
+ expect(req).toMatchObject({
+ family: 'agents',
+ projectName: 'App',
+ previouslyApproved: false,
+ launchCmd: 'claude --mcp evil',
+ // env is inside the hash (PATH/LD_PRELOAD hijack), so it is inside the question.
+ env: { API_KEY: 'sk-1', PATH: '/evil/bin' }
+ })
+ expect(req.locationLabel).toContain('/proj/app')
+
+ svc.submitConsent(req.requestId, 'approve')
+ expect(await pending).toBe(true)
+ const hash = hashTrustContent(projectTrustContent('agents', agentsDoc)!)
+ expect(await trust.isTrusted(localTrustKey('/proj/app'), 'agents', hash)).toBe(true)
+ // Per family: approving the launch settings approves NOTHING about the setup scripts.
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'setup')).toBeNull()
+ expect(trustChanged()).toEqual(['p1'])
+
+ // Already trusted → the next ask is promptless.
+ expect(await svc.ensureFamilyTrusted(target(), 'agents')).toBe(true)
+ expect(familyPrompts('agents')).toHaveLength(1)
+ })
+
+ it('a skip records nothing, broadcasts nothing and answers false', async () => {
+ const trust = new ProjectTrustStore()
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(agentsDoc)) })
+ const pending = svc.ensureFamilyTrusted(target(), 'agents')
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ svc.submitConsent(familyPrompts('agents')[0].requestId, 'skip')
+ expect(await pending).toBe(false)
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'agents')).toBeNull()
+ expect(trustChanged()).toEqual([])
+ })
+
+ it('an unanswered prompt expires: false, dismissed, nothing recorded — never a retroactive yes', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ const trust = new ProjectTrustStore()
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(agentsDoc)) })
+ const pending = svc.ensureFamilyTrusted(target(), 'agents')
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ const { requestId } = familyPrompts('agents')[0]
+
+ await vi.advanceTimersByTimeAsync(299_000)
+ expect(dismissed()).toEqual([])
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(await pending).toBe(false)
+ expect(dismissed()).toEqual([requestId])
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'agents')).toBeNull()
+
+ svc.submitConsent(requestId, 'approve')
+ await vi.advanceTimersByTimeAsync(0)
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'agents')).toBeNull()
+ expect(trustChanged()).toEqual([])
+ })
+
+ it('re-prompts with previouslyApproved=true once the approved content changed', async () => {
+ const trust = new ProjectTrustStore()
+ const stale = hashTrustContent(projectTrustContent('agents', { agents: { launchCmd: 'old' } })!)
+ await trust.record(localTrustKey('/proj/app'), 'agents', stale, '2026-08-01T00:00:00.000Z')
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(agentsDoc)) })
+ const pending = svc.ensureFamilyTrusted(target(), 'agents')
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ expect(familyPrompts('agents')[0].previouslyApproved).toBe(true)
+ svc.submitConsent(familyPrompts('agents')[0].requestId, 'skip')
+ expect(await pending).toBe(false)
+ })
+
+ it('the shell variant carries the bare program and records under the shell family', async () => {
+ const doc: ProjectSettingsDoc = { terminal: { shell: '/tmp/evil.sh', theme: 'dark' } }
+ const trust = new ProjectTrustStore()
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(doc)) })
+ const pending = svc.ensureFamilyTrusted(target(), 'shell')
+ await vi.waitFor(() => expect(familyPrompts('shell')).toHaveLength(1))
+ const req = familyPrompts('shell')[0]
+ expect(req).toMatchObject({ family: 'shell', shell: '/tmp/evil.sh', projectName: 'App' })
+ svc.submitConsent(req.requestId, 'approve')
+ expect(await pending).toBe(true)
+ const hash = hashTrustContent(projectTrustContent('shell', doc)!)
+ expect(await trust.isTrusted(localTrustKey('/proj/app'), 'shell', hash)).toBe(true)
+ expect(await trust.getRecord(localTrustKey('/proj/app'), 'agents')).toBeNull()
+ })
+
+ it('single-flights per (location, family): concurrent asks share ONE prompt and ONE answer', async () => {
+ const trust = new ProjectTrustStore()
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(agentsDoc)) })
+ // Two canvas nodes on the SAME folder: different project ids, one location, one question.
+ const a = svc.ensureFamilyTrusted(target({ projectId: 'p1' }), 'agents')
+ const b = svc.ensureFamilyTrusted(target({ projectId: 'p2' }), 'agents')
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(familyPrompts('agents')).toHaveLength(1)
+
+ svc.submitConsent(familyPrompts('agents')[0].requestId, 'approve')
+ expect(await a).toBe(true)
+ expect(await b).toBe(true)
+ // Every asker's project is invalidated, not just whoever happened to raise the prompt.
+ expect(trustChanged().sort()).toEqual(['p1', 'p2'])
+ })
+
+ it('shares the app-wide queue with a setup run — one dialog at a time', async () => {
+ const trust = new ProjectTrustStore()
+ const { runner } = recorder()
+ const svc = new ProjectSetupService({
+ trust,
+ readSettings: async () => snapshot(sharedFile({ ...agentsDoc, setup: { setupScript: 'npm ci' } })),
+ runLocal: runner
+ })
+ const run = svc.run(target(), 'setup')
+ await vi.waitFor(() => expect(consentRequests()).toHaveLength(1))
+ const ask = svc.ensureFamilyTrusted(target(), 'agents')
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(familyPrompts('agents')).toEqual([])
+
+ svc.submitConsent(consentRequests()[0].requestId, 'skip')
+ expect(await run).toEqual({ status: 'skipped', reason: 'declined' })
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ svc.submitConsent(familyPrompts('agents')[0].requestId, 'skip')
+ expect(await ask).toBe(false)
+ })
+
+ it('a trust WRITE failure is not an approval', async () => {
+ const trust = new ProjectTrustStore()
+ trust.record = async () => {
+ throw new Error('EACCES')
+ }
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(agentsDoc)) })
+ const pending = svc.ensureFamilyTrusted(target(), 'agents')
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ svc.submitConsent(familyPrompts('agents')[0].requestId, 'approve')
+ // A grant that exists only in memory is no grant: fail closed, and tell nobody it changed.
+ expect(await pending).toBe(false)
+ expect(trustChanged()).toEqual([])
+ })
+
+ it('gates an ssh target on its ssh location key, never the local one', async () => {
+ const ssh = { server: { host: 'h', user: 'u' }, remoteCwd: '/srv/app' }
+ const trust = new ProjectTrustStore()
+ const svc = new ProjectSetupService({ trust, readSettings: async () => snapshot(sharedFile(agentsDoc)) })
+ const pending = svc.ensureFamilyTrusted(target({ ssh }), 'agents')
+ await vi.waitFor(() => expect(familyPrompts('agents')).toHaveLength(1))
+ expect(familyPrompts('agents')[0].locationLabel).toBe('u@h:/srv/app')
+ svc.submitConsent(familyPrompts('agents')[0].requestId, 'approve')
+ expect(await pending).toBe(true)
+ const hash = hashTrustContent(projectTrustContent('agents', agentsDoc)!)
+ expect(await trust.isTrusted(sshTrustKey(ssh), 'agents', hash)).toBe(true)
+ expect(await trust.isTrusted(localTrustKey('/proj/app'), 'agents', hash)).toBe(false)
+ })
+
+ it('project-setup:request-trust derives the target from the workspace index, never the caller', async () => {
+ const asks: Array<[ProjectSetupTarget, string]> = []
+ registerProjectSetupHandlers(
+ plat,
+ {
+ run: async () => ({ status: 'skipped', reason: 'unavailable' }) as const,
+ cancel: () => false,
+ submitConsent: () => {},
+ ensureFamilyTrusted: async (t, family) => {
+ asks.push([t, family])
+ return true
+ }
+ },
+ {
+ projectTargetInfo: (projectId) => (projectId === 'p1' ? { cwd: '/proj/app', name: 'App' } : null),
+ worktreeList: async () => ({ ok: true, entries: [] })
+ }
+ )
+ const call = plat.handlers[IPC.projectSetupRequestTrust]
+ expect(await call('p1', 'agents')).toBe(true)
+ expect(asks[0]).toEqual([{ projectId: 'p1', projectName: 'App', rootPath: '/proj/app' }, 'agents'])
+
+ // Unknown project; a family this channel does not own (`setup` is the runner's own gate — a
+ // renderer must not be able to raise a setup prompt out of band); a non-string id; a missing
+ // family. All refused without ever reaching the service.
+ expect(await call('missing', 'agents')).toBe(false)
+ expect(await call('p1', 'setup')).toBe(false)
+ expect(await call(42, 'agents')).toBe(false)
+ expect(await call('p1')).toBe(false)
+ expect(asks).toHaveLength(1)
+ })
+})
diff --git a/src/core/project-setup-service.ts b/src/core/project-setup-service.ts
index b041e2ed3..ec06997dd 100644
--- a/src/core/project-setup-service.ts
+++ b/src/core/project-setup-service.ts
@@ -5,13 +5,15 @@ import { IPC } from '../shared/ipc'
import {
projectTrustContent,
resolveProjectSettings,
+ type ProjectConsentRequest,
type ProjectSettingsDoc,
type ProjectSettingsSnapshot,
type ProjectSetupConsentAnswer,
type ProjectSetupConsentRequest,
type ProjectSetupEvent,
type ProjectSetupKind,
- type ProjectSetupRunResult
+ type ProjectSetupRunResult,
+ type ProjectTrustFamily
} from '../shared/project-settings'
import type { SshConnection } from '../shared/ssh'
import { platform } from './platform'
@@ -39,6 +41,12 @@ import { ProjectTrustStore, hashTrustContent, localTrustKey, sshTrustKey } from
*
* 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.
+ *
+ * `ensureFamilyTrusted` is the same gate aimed at the families this service never RUNS — the launch
+ * settings (`agents`) and the terminal program (`shell`) a caller elsewhere is about to consume. It
+ * reuses every invariant above (one queue, one dialog, the trichotomy, location keying, host-only
+ * delivery) through the same `queuePrompt` core, and adds one of its own: an approval broadcasts
+ * `IPC.projectTrustChanged` so a renderer holding a stale "not trusted" verdict re-reads it.
*/
/** How long an unanswered consent prompt is held before it is dismissed and reported as
@@ -116,6 +124,34 @@ function familyScripts(sharedDoc: ProjectSettingsDoc): ProjectSetupConsentReques
return out
}
+/** The families `ensureFamilyTrusted` answers for: everything a launcher consumes but this service
+ * never runs itself. `setup` is excluded on purpose — the runner owns that gate, and admitting it
+ * here would be a second, run-less way to raise a setup prompt. */
+export type ProjectConsumerFamily = Exclude<ProjectTrustFamily, 'setup'>
+
+/** The dialog payload for a consumer family, built from the SHARED document alone — exactly the
+ * fields `projectTrustContent(family, …)` hashes, so what is rendered is what is approved. */
+function familyConsentPayload(
+ family: ProjectConsumerFamily,
+ sharedDoc: ProjectSettingsDoc,
+ base: { requestId: string; previouslyApproved: boolean; projectName: string; locationLabel: string }
+): ProjectConsentRequest {
+ if (family === 'shell') {
+ // Non-null by construction: a null `projectTrustContent('shell', …)` returned before this point.
+ return { family: 'shell', ...base, shell: sharedDoc.terminal?.shell ?? '' }
+ }
+ const agents = sharedDoc.agents
+ const req: ProjectConsentRequest = { family: 'agents', ...base }
+ if (agents?.launchCmd !== undefined) req.launchCmd = agents.launchCmd
+ if (agents?.env) {
+ // Key-sorted, like the hash's own canonical form, so the dialog's order is the approved order.
+ const env: Record<string, string> = {}
+ for (const k of Object.keys(agents.env).sort()) env[k] = agents.env[k]
+ req.env = env
+ }
+ return req
+}
+
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)
@@ -138,11 +174,21 @@ interface ActiveRun {
consentRequestId?: string
}
+interface TrustFlight {
+ promise: Promise<boolean>
+ /** Every project id that asked while this one question was open. All of them are invalidated on
+ * an approval: two canvas nodes on one folder share a trust key but not a project id. */
+ projectIds: Set<string>
+}
+
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. */
+ /** App-wide prompt queue: each ask chains onto the previous one, so only one dialog is live.
+ * SHARED with `ensureFamilyTrusted` — a launch prompt and a setup prompt are the same modal. */
private consentQueue: Promise<unknown> = Promise.resolve()
+ /** Live `ensureFamilyTrusted` asks, keyed by (family, LOCATION) — see `ensureFamilyTrusted`. */
+ private readonly trustFlights = new Map<string, TrustFlight>()
constructor(private readonly deps: ProjectSetupDeps) {}
@@ -218,6 +264,99 @@ export class ProjectSetupService {
}
}
+ /**
+ * The SAME gate as `run`'s, for a family this service never executes: `agents` (launchCmd + env)
+ * and `shell` (the terminal program). A launcher calls this before it consumes a shared-sourced
+ * value; `true` means that family is trusted AT THIS LOCATION right now.
+ *
+ * - Nothing executable in the SHARED document (`projectTrustContent` → null) → `true` with NO
+ * prompt. There is nothing hostile to gate: a value that exists only in this machine's local
+ * overlay is the user's own instruction (the same rule `run` applies to a local script).
+ * - Already trusted (the family's shared-content hash matches the record) → `true`, no prompt.
+ * - Otherwise ONE prompt, on the app-wide queue, and only `approve` records — skip and expiry
+ * are both `false`, and neither leaves anything behind. A record that cannot be persisted is
+ * not an approval either (fail closed rather than grant something only memory knows).
+ *
+ * SINGLE-FLIGHT per (family, LOCATION): concurrent askers share one promise, so five nodes
+ * launching against the same folder raise ONE dialog, not five. The flight is keyed by the trust
+ * key — the same identity the approval itself is keyed by — so joiners are asking the same
+ * question about the same document, and every joiner's projectId is invalidated on approval.
+ */
+ async ensureFamilyTrusted(target: ProjectSetupTarget, family: ProjectConsumerFamily): Promise<boolean> {
+ const trustKey = trustKeyFor(target)
+ const flightKey = `${family}\0${trustKey}`
+ const inflight = this.trustFlights.get(flightKey)
+ if (inflight) {
+ inflight.projectIds.add(target.projectId)
+ return inflight.promise
+ }
+ const flight: TrustFlight = { projectIds: new Set([target.projectId]), promise: Promise.resolve(false) }
+ // Registered BEFORE the first await inside `resolveFamilyTrust` can settle, so a caller that
+ // asks in the same tick joins this flight instead of opening a second dialog.
+ flight.promise = this.resolveFamilyTrust(target, family, trustKey, flight).finally(() => {
+ this.trustFlights.delete(flightKey)
+ })
+ this.trustFlights.set(flightKey, flight)
+ return flight.promise
+ }
+
+ private async resolveFamilyTrust(
+ target: ProjectSetupTarget,
+ family: ProjectConsumerFamily,
+ trustKey: string,
+ flight: TrustFlight
+ ): Promise<boolean> {
+ let snap: ProjectSettingsSnapshot | null
+ try {
+ snap = await this.deps.readSettings(target.projectId)
+ } catch {
+ return false // settings unreadable → no verdict, and a no-verdict is never a yes
+ }
+ const sharedDoc: ProjectSettingsDoc = snap?.shared ?? {}
+ const content = projectTrustContent(family, sharedDoc)
+ if (content === null) return true // nothing shared to gate
+ const hash = hashTrustContent(content)
+ let trusted: boolean
+ try {
+ trusted = await this.deps.trust.isTrusted(trustKey, family, hash)
+ } catch {
+ return false
+ }
+ if (trusted) return true
+
+ const answer = await this.askFamilyConsent(trustKey, family, sharedDoc, target)
+ if (answer !== 'approve') return false
+ try {
+ await this.deps.trust.record(trustKey, family, hash, new Date(this.now()).toISOString())
+ } catch {
+ return false
+ }
+ // The renderer's launch-info cache is keyed by project id, so every asker is told — including
+ // the ones that merely joined this flight.
+ for (const projectId of flight.projectIds) {
+ platform().broadcast(IPC.projectTrustChanged, { projectId })
+ }
+ return true
+ }
+
+ private askFamilyConsent(
+ trustKey: string,
+ family: ProjectConsumerFamily,
+ sharedDoc: ProjectSettingsDoc,
+ target: ProjectSetupTarget
+ ): Promise<ProjectSetupConsentAnswer | undefined> {
+ return this.queuePrompt({
+ trustKey,
+ family,
+ payload: (base) =>
+ familyConsentPayload(family, sharedDoc, {
+ ...base,
+ projectName: target.projectName,
+ locationLabel: locationLabel(target)
+ })
+ })
+ }
+
/** Aborts a run — live OR still waiting at its consent dialog. `false` = nothing by that runKey
* exists (already finished, or never did). */
cancel(runKey: string): boolean {
@@ -238,10 +377,9 @@ export class ProjectSetupService {
/**
* Shell shutdown: abort every run still in flight. A local run is a DETACHED process group
* (setsid, so a cancel can SIGKILL the whole tree) — which is also why quitting without this
- * leaves `npm ci` churning with nothing left to report to, and, on the ssh leg, an orphaned remote
- * command. Goes through `cancel`, so a run parked at its consent dialog is closed and its dialog
- * dismissed too. Idempotent: Electron's `before-quit` runs twice, and the second pass finds
- * nothing left.
+ * leaves `npm ci` churning with nothing left to report to. Goes through `cancel`, so a run parked
+ * at its consent dialog is closed and its dialog dismissed too. Idempotent: Electron's
+ * `before-quit` runs twice, and the second pass finds nothing left.
*/
disposeAll(): void {
for (const runKey of [...this.active.keys()]) this.cancel(runKey)
@@ -269,18 +407,47 @@ export class ProjectSetupService {
trustKey: string,
req: Omit<ProjectSetupConsentRequest, 'requestId' | 'previouslyApproved'>
): Promise<ProjectSetupConsentAnswer | undefined> {
- const step = this.consentQueue.then(async () => {
+ return this.queuePrompt({
+ trustKey,
+ family: 'setup',
// Cancelled while queued behind another dialog — never raise one for a run that is gone.
- if (entry.abort.signal.aborted) return undefined
+ skipIf: () => entry.abort.signal.aborted,
+ // So `cancel` can close the dialog this run is parked at instead of leaving a modal up for a
+ // run that no longer exists.
+ bind: (requestId) => {
+ entry.consentRequestId = requestId
+ },
+ payload: (base) => ({ family: 'setup', ...req, ...base })
+ })
+ }
+
+ /**
+ * THE prompt: one dialog at a time, app-wide, whatever family asked. Shared by the setup runner
+ * (`askConsent`) and the launch-settings gate (`askFamilyConsent`) so there is exactly one place
+ * that mints a requestId, holds the expiry, and delivers through the host-only seam — a second
+ * copy of this is how one caller ends up with a prompt that cannot expire, or that a stale
+ * requestId can answer.
+ */
+ private queuePrompt(opts: {
+ trustKey: string
+ family: ProjectTrustFamily
+ /** Checked at PROMPT time (not enqueue time): true → no dialog, answer `undefined`. */
+ skipIf?: () => boolean
+ /** The live requestId while the dialog is up, then `undefined`. */
+ bind?: (requestId: string | undefined) => void
+ payload: (base: { requestId: string; previouslyApproved: boolean }) => ProjectConsentRequest
+ }): Promise<ProjectSetupConsentAnswer | undefined> {
+ const step = this.consentQueue.then(async () => {
+ if (opts.skipIf?.()) return undefined
// 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'))
+ const previouslyApproved = !!(await this.deps.trust.getRecord(opts.trustKey, opts.family))
return new Promise<ProjectSetupConsentAnswer | undefined>((resolve) => {
const requestId = randomUUID()
const settle = (answer: ProjectSetupConsentAnswer | undefined): void => {
this.pending.delete(requestId)
- entry.consentRequestId = undefined
+ opts.bind?.(undefined)
resolve(answer)
}
const timer = setTimeout(() => {
@@ -292,9 +459,8 @@ export class ProjectSetupService {
clearTimeout(timer)
settle(answer)
})
- entry.consentRequestId = requestId
- const payload: ProjectSetupConsentRequest = { ...req, requestId, previouslyApproved }
- this.sendConsent(IPC.projectSetupConsentRequest, payload)
+ opts.bind?.(requestId)
+ this.sendConsent(IPC.projectSetupConsentRequest, opts.payload({ requestId, previouslyApproved }))
})
})
// A rejected step must not poison the queue for every later prompt.
diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.ts
index c9b4de552..c276f9b99 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -8,6 +8,13 @@ import { E_NO_HANDLER, type RpcErr, type RpcOk, type RpcRequest } from '../share
type Handler = { fn: (...args: any[]) => unknown; withSender: boolean }
type Listener = { fn: (...args: any[]) => void; withSender: boolean }
+/** How often a REFUSED host-control cast may be logged. The refusal itself is unconditional; only
+ * the log line is throttled, because the rate is chosen by the peer: a guest casting in a loop
+ * would otherwise turn the host's log into its own amplifier. One line per window is the whole
+ * diagnostic — that it happened at all. */
+const REFUSAL_LOG_INTERVAL_MS = 60_000
+let lastRefusalLog = 0
+
/**
* The Electron platform, with the two extra members a relay PEER needs (they are deliberately NOT
* on CorePlatform: the core never dispatches, only the shell that owns the socket does — exactly as
@@ -125,7 +132,11 @@ export function electronPlatform(): ElectronPlatform {
// a cast (ws-bridge.ts) — i.e. a guest could not start a run but could still answer the host's
// trust prompt for it. A cast has no reply channel, so a refusal can only be dropped + logged.
if (isHostOnlyChannel(method)) {
- console.warn(`[peer] refused host-control cast ${method} from peer ${clientId}`)
+ const now = Date.now()
+ if (now - lastRefusalLog >= REFUSAL_LOG_INTERVAL_MS) {
+ lastRefusalLog = now
+ console.warn(`[peer] refused host-control cast ${method} from peer ${clientId}`)
+ }
return
}
const set = listeners.get(method)
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 772099971..6eb1c9988 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -18,7 +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'
+import type { ProjectConsentRequest, 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
@@ -57,7 +57,7 @@ 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]>(
+const subscribeProjectSetupConsentRequest = subscribe<[ProjectConsentRequest]>(
IPC.projectSetupConsentRequest
)
const subscribeProjectSetupConsentDismiss = subscribe<[{ requestId: string }]>(
@@ -170,6 +170,8 @@ const api: NodeTerminalApi = {
consent: async (requestId, answer) => {
ipcRenderer.send(IPC.projectSetupConsentSubmit, requestId, answer)
},
+ requestTrust: (projectId, family) =>
+ ipcRenderer.invoke(IPC.projectSetupRequestTrust, projectId, family),
onConsentRequest: subscribeProjectSetupConsentRequest,
onConsentDismiss: subscribeProjectSetupConsentDismiss,
onEvent: (projectId, cb) => {
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 215bb15fe..c56aa59f7 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -313,6 +313,9 @@ export function buildStubApi(): Omit<
run: () => Promise.resolve({ status: 'skipped', reason: 'unavailable' }),
cancel: () => Promise.resolve(false),
consent: pnoop,
+ // Fails closed, like `run`: no bridge means no way to ask a human, and an unasked question
+ // is never an approval.
+ requestTrust: () => Promise.resolve(false),
onConsentRequest: noopUnsub,
onConsentDismiss: noopUnsub,
onEvent: noopUnsub
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 34e7eff8b..7f5b6921e 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -306,8 +306,8 @@ export function buildRealApi(
client.request(IPC.projectSettingsLaunchInfo, projectId) as ReturnType<
NodeTerminalApi['projectSettings']['launchInfo']
>,
- // REAL: nobody broadcasts IPC.projectTrustChanged yet (Task 2 records approvals) — the
- // subscription is wired ahead of the emitter, same posture as the preload leg.
+ // REAL: `ProjectSetupService.ensureFamilyTrusted` broadcasts IPC.projectTrustChanged on every
+ // approval, for each project id that asked.
onTrustChanged: (cb) => client.subscribe(IPC.projectTrustChanged, cb as Listener)
}
@@ -323,6 +323,14 @@ export function buildRealApi(
consent: async (requestId, answer) => {
client.cast(IPC.projectSetupConsentSubmit, requestId, answer)
},
+ // Fails CLOSED on a rejection rather than throwing at the caller: over the relay this method is
+ // host-only, so a guest's call comes back E_FORBIDDEN — and "not trusted" is exactly the right
+ // answer for a client that may not raise the host's dialog.
+ requestTrust: (projectId, family) =>
+ client.request(IPC.projectSetupRequestTrust, projectId, family).then(
+ (v) => v === true,
+ () => false
+ ),
onConsentRequest: (cb) => client.subscribe(IPC.projectSetupConsentRequest, cb as Listener),
onConsentDismiss: (cb) => client.subscribe(IPC.projectSetupConsentDismiss, cb as Listener),
onEvent: (projectId, cb) => {
diff --git a/src/renderer/components/SetupConsentDialog.test.tsx b/src/renderer/components/SetupConsentDialog.test.tsx
index 4809b41ac..dafc0f2a8 100644
--- a/src/renderer/components/SetupConsentDialog.test.tsx
+++ b/src/renderer/components/SetupConsentDialog.test.tsx
@@ -14,7 +14,7 @@
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 type { ProjectConsentRequest, ProjectSetupConsentRequest } from '@shared/project-settings'
import { CONFIRM_ARM_MS } from './confirm-key'
import { SETUP_LABEL_MAX, SetupConsentDialog } from './SetupConsentDialog'
@@ -309,3 +309,145 @@ describe('SetupConsentDialog', () => {
root = createRoot(host)
})
})
+
+/**
+ * The same dialog, the other two trust families. `agents` (launchCmd + env) and `shell` (the
+ * terminal program) are approved by the same one-answer machinery, so everything asserted above
+ * about answering still holds; what is asserted here is that the CONTENT being approved is on
+ * screen, verbatim and bidi-pinned, the way the script bodies are.
+ */
+describe('SetupConsentDialog — agents/shell trust variants', () => {
+ // The file's shared emitter is typed to the setup shape; main sends the tagged union over that
+ // same channel. One cast here rather than a second harness.
+ const emit = (req: ProjectConsentRequest): void =>
+ (emitRequest as unknown as (r: ProjectConsentRequest) => void)(req)
+
+ const agents = (over: Partial<Extract<ProjectConsentRequest, { family: 'agents' }>> = {}): ProjectConsentRequest => ({
+ family: 'agents',
+ requestId: 'req-a',
+ projectName: 'cloned-repo',
+ locationLabel: '~/code/cloned-repo',
+ previouslyApproved: false,
+ launchCmd: 'claude --mcp ./evil.js',
+ env: { API_KEY: 'sk-live-1', PATH: '/evil/bin:/usr/bin' },
+ ...over
+ })
+
+ const shell = (over: Partial<Extract<ProjectConsentRequest, { family: 'shell' }>> = {}): ProjectConsentRequest => ({
+ family: 'shell',
+ requestId: 'req-s',
+ projectName: 'cloned-repo',
+ locationLabel: '~/code/cloned-repo',
+ previouslyApproved: false,
+ shell: '/tmp/evil.sh',
+ ...over
+ })
+
+ const envRows = (): HTMLElement[] => [...document.querySelectorAll<HTMLElement>('.confirm [data-env-key]')]
+ const launchCmd = (): HTMLElement | null => document.querySelector<HTMLElement>('.confirm pre[data-launch-cmd]')
+
+ it('shows the launch command and EVERY env var — that whole set is what one answer covers', () => {
+ mount()
+ act(() => emit(agents()))
+ expect(text()).toContain('cloned-repo')
+ expect(launchCmd()!.textContent).toBe('claude --mcp ./evil.js')
+ expect(envRows().map((r) => r.textContent)).toEqual([
+ 'API_KEY=sk-live-1',
+ 'PATH=/evil/bin:/usr/bin'
+ ])
+ })
+
+ it('pins the approved bytes to byte order — command AND env values (Trojan source)', () => {
+ mount()
+ // Written as \u escapes on purpose (see the label test above): a raw bidi byte in a source
+ // file is invisible to git and ripgrep.
+ const rtl = String.fromCharCode(0x202e) // U+202E RIGHT-TO-LEFT OVERRIDE
+ const cmd = `sh${rtl}# nur`
+ const val = `x${rtl}y`
+ act(() => emit(agents({ launchCmd: cmd, env: { A: val } })))
+ // Verbatim: these are the bytes being approved, so nothing is stripped or truncated.
+ expect(launchCmd()!.textContent).toBe(cmd)
+ expect(launchCmd()!.style.unicodeBidi).toBe('bidi-override')
+ // The whole row is pinned, key included — the dialog must not lean on the sanitizer's key
+ // charset for its display order to match its bytes.
+ const row = envRows()[0]
+ expect(row.querySelector<HTMLElement>('[data-env-value]')!.textContent).toBe(val)
+ expect(row.style.unicodeBidi).toBe('bidi-override')
+ expect(row.style.direction).toBe('ltr')
+ })
+
+ it('omits the halves the family does not set', () => {
+ mount()
+ act(() => emit(agents({ env: undefined })))
+ expect(envRows()).toHaveLength(0)
+ expect(launchCmd()).toBeTruthy()
+ act(() => emitDismiss({ requestId: 'req-a' }))
+ act(() => emit(agents({ requestId: 'req-a2', launchCmd: undefined, env: { ONLY: 'x' } })))
+ expect(launchCmd()).toBeNull()
+ expect(envRows().map((r) => r.textContent)).toEqual(['ONLY=x'])
+ })
+
+ it('answers through the same one-answer path, and Escape still submits NOTHING', () => {
+ mount()
+ act(() => emit(agents()))
+ const approve = button('Approve')
+ act(() => {
+ approve.click()
+ approve.click()
+ })
+ expect(consent).toHaveBeenCalledTimes(1)
+ expect(consent).toHaveBeenCalledWith('req-a', 'approve')
+
+ act(() => emit(shell()))
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
+ })
+ expect(dialog()).toBeNull()
+ expect(consent).toHaveBeenCalledTimes(1)
+ })
+
+ it('the shell variant shows the bare program', () => {
+ mount()
+ act(() => emit(shell()))
+ const pre = document.querySelector<HTMLElement>('.confirm pre[data-shell]')!
+ expect(pre.textContent).toBe('/tmp/evil.sh')
+ expect(pre.style.unicodeBidi).toBe('bidi-override')
+ act(() => button('Skip').click())
+ expect(consent).toHaveBeenCalledWith('req-s', 'skip')
+ })
+
+ it('says the settings CHANGED when a previous approval exists', () => {
+ mount()
+ act(() => emit(agents({ previouslyApproved: true })))
+ expect(text().toLowerCase()).toContain('changed since you approved')
+ })
+
+ it('renders a TAGGED setup request exactly as the untagged one — the tag changed nothing', () => {
+ mount()
+ act(() =>
+ emit({
+ family: 'setup',
+ requestId: 'req-t',
+ kind: 'setup',
+ projectName: 'cloned-repo',
+ locationLabel: '~/code/cloned-repo',
+ scripts: { setup: 'npm install' },
+ previouslyApproved: false
+ })
+ )
+ expect(scripts()).toHaveLength(1)
+ expect(scripts()[0].textContent).toBe('npm install')
+ expect(button('Run once')).toBeTruthy()
+ })
+
+ it('IGNORES a request whose family it does not know — never a dialog over unrendered content', () => {
+ mount()
+ // Fail closed: a variant this build cannot render must not be approvable through a dialog that
+ // shows the user nothing of what it covers.
+ act(() => emit({ family: 'worktree', requestId: 'req-x' } as unknown as ProjectConsentRequest))
+ expect(dialog()).toBeNull()
+ // …and it does not block the queue for a request that IS renderable.
+ act(() => emit(shell()))
+ expect(dialog()).toBeTruthy()
+ })
+})
diff --git a/src/renderer/components/SetupConsentDialog.tsx b/src/renderer/components/SetupConsentDialog.tsx
index 82561afb3..4e734a9af 100644
--- a/src/renderer/components/SetupConsentDialog.tsx
+++ b/src/renderer/components/SetupConsentDialog.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import type {
+ ProjectConsentRequest,
ProjectSetupConsentAnswer,
ProjectSetupConsentRequest,
ProjectSetupKind
@@ -75,6 +76,20 @@ function safeLabel(raw: string): string {
const KIND_LABEL: Record<ProjectSetupKind, string> = { setup: 'Setup', archive: 'Archive' }
+/**
+ * The pin that defeats Trojan-source reordering on APPROVED BYTES (a script body, a launch command,
+ * an env value, a shell path): it forces the DISPLAY order to the byte order, so a U+202E inside
+ * the content cannot make the reader see a different program than the one that will run. It alters
+ * nothing about the bytes themselves — which is the point: these are shown so they can be approved.
+ */
+const BIDI_PIN: React.CSSProperties = { unicodeBidi: 'bidi-override', direction: 'ltr' }
+
+/** The scroll box every approved-bytes block sits in. Carries NO conflicting utility (no border
+ * colour, no whitespace mode): each use adds its own, so two Tailwind classes of the same family
+ * never race — the winner of that race is stylesheet order, not string order. */
+const APPROVED_BOX =
+ 'max-h-40 overflow-auto break-words rounded-md border bg-bg px-2.5 py-2 font-mono text-[12px] leading-relaxed text-text'
+
/** 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']
@@ -83,10 +98,23 @@ function orderedScripts(req: ProjectSetupConsentRequest): { kind: ProjectSetupKi
.filter((s): s is { kind: ProjectSetupKind; body: string } => s.body !== undefined)
}
+/**
+ * Which variant's content this request carries, or `null` for one this build cannot render.
+ *
+ * An untagged payload is the SETUP request — the only variant that predates the tag — so an older
+ * main is still answered correctly. An unknown tag is refused outright rather than rendered as the
+ * nearest variant: the whole point of this dialog is that nothing is approved that was not on
+ * screen, and a payload whose content this build cannot lay out is content it cannot show.
+ */
+function familyOf(req: ProjectConsentRequest): ProjectConsentRequest['family'] | null {
+ const tag = (req as { family?: string }).family ?? 'setup'
+ return tag === 'setup' || tag === 'agents' || tag === 'shell' ? tag : null
+}
+
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[]>([])
+ const [queue, setQueue] = useState<ProjectConsentRequest[]>([])
// 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.
@@ -95,6 +123,9 @@ export function SetupConsentDialog(): React.JSX.Element | null {
useEffect(() => {
const api = window.nodeTerminal.projectSetup
const offRequest = api.onConsentRequest((req) => {
+ // Unrenderable variants never enter the queue at all — they must neither raise a dialog nor
+ // block the ones behind them (see `familyOf`).
+ if (!familyOf(req)) return
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.
@@ -123,6 +154,118 @@ export function SetupConsentDialog(): React.JSX.Element | null {
const name = safeLabel(head.projectName)
const location = safeLabel(head.locationLabel)
+ // Per variant: the question, the grant button's wording, and the content the answer covers. The
+ // `setup` arm is the fallback, so an untagged (older-main) payload renders exactly as before.
+ const view =
+ head.family === 'agents'
+ ? {
+ message: `Use the shared agent launch settings for "${name}"?`,
+ confirmLabel: 'Approve',
+ changed: 'These settings have changed since you approved them for this project.',
+ intro: (
+ <>
+ 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 the launch command and
+ every variable below.
+ </>
+ ),
+ detail: (
+ <>
+ {head.launchCmd !== undefined ? (
+ <div className="space-y-1">
+ <p className="text-[12px] font-semibold text-text">Launch command</p>
+ {/* Text child, never markup — and never truncated: this is what is approved. */}
+ <pre
+ style={BIDI_PIN}
+ data-launch-cmd=""
+ className={`${APPROVED_BOX} whitespace-pre-wrap border-accent`}
+ >
+ {head.launchCmd}
+ </pre>
+ </div>
+ ) : null}
+ {head.env ? (
+ <div className="space-y-1">
+ <p className="text-[12px] font-semibold text-text">Environment</p>
+ {/* Every pair, verbatim: an env var is code's blast radius (PATH/LD_PRELOAD), so
+ it is inside the hash and must be inside the question. The whole ROW is pinned
+ to byte order, key included — a `KEY=value` line that renders in some other
+ order than its bytes is the same Trojan-source problem as a reordered script,
+ and this dialog must not depend on the sanitizer's key charset to be safe. */}
+ <div className={`${APPROVED_BOX} border-accent`}>
+ {Object.entries(head.env).map(([key, value]) => (
+ <div key={key} data-env-key={key} style={BIDI_PIN} className="break-all">
+ <span className="text-muted">{key}=</span>
+ <span data-env-value="">{value}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ </>
+ )
+ }
+ : head.family === 'shell'
+ ? {
+ message: `Use the shared terminal shell for "${name}"?`,
+ confirmLabel: 'Approve',
+ changed: 'This setting has changed since you approved it for this project.',
+ intro: (
+ <>
+ It comes from the project&apos;s shared <code>.nodeterm/settings.json</code>, so anyone
+ who can commit to the repo can change it. Every terminal you open for this project
+ starts this program.
+ </>
+ ),
+ detail: (
+ <div className="space-y-1">
+ <p className="text-[12px] font-semibold text-text">Shell</p>
+ <pre
+ style={BIDI_PIN}
+ data-shell=""
+ className={`${APPROVED_BOX} whitespace-pre-wrap border-accent`}
+ >
+ {head.shell}
+ </pre>
+ </div>
+ )
+ }
+ : {
+ message: `Run the ${KIND_LABEL[head.kind].toLowerCase()} script for "${name}"?`,
+ confirmLabel: 'Run once',
+ changed: 'These scripts have changed since you approved them for this project.',
+ intro: (
+ <>
+ 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.
+ </>
+ ),
+ detail: (
+ <>
+ {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. `BIDI_PIN` pins the DISPLAY order to the byte order, so a U+202E in
+ the script cannot make the reader see a different program than the one that
+ will run (Trojan source). It changes nothing about the bytes themselves. */}
+ <pre
+ style={BIDI_PIN}
+ 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>
+ ))}
+ </>
+ )
+ }
+
return (
<ConfirmDialog
// Keyed per request: the next prompt in the queue must be a FRESH dialog — its own
@@ -133,40 +276,16 @@ export function SetupConsentDialog(): React.JSX.Element | null {
<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>
+ <p className="text-[13px] text-[color:var(--warn)]">{view.changed}</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.
- `bidi-override`/`ltr` pins the DISPLAY order to the byte order, so a U+202E in the
- script cannot make the reader see a different program than the one that will run
- (Trojan source). It changes nothing about the bytes themselves. */}
- <pre
- style={{ unicodeBidi: 'bidi-override', direction: 'ltr' }}
- data-script-kind={s.kind}
- className={`max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-md border px-2.5 py-2 font-mono text-[12px] leading-relaxed text-text ${
- s.kind === head.kind ? 'border-accent bg-bg' : 'border-border bg-bg opacity-80'
- }`}
- >
- {s.body}
- </pre>
- </div>
- ))}
+ <p className="text-[13px] text-muted">{view.intro}</p>
+ {view.detail}
</div>
}
- message={`Run the ${KIND_LABEL[head.kind].toLowerCase()} script for "${name}"?`}
- confirmLabel="Run once"
+ message={view.message}
+ confirmLabel={view.confirmLabel}
cancelLabel="Skip"
- // "Run once" is the grant, so it carries the danger styling; no button takes focus.
+ // The confirm button is the grant, so it carries the danger styling; no button takes focus.
danger
enterConfirms={false}
autoFocusButtons={false}
diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.ts
index dfdedfd44..d3f437287 100644
--- a/src/shared/host-control.test.ts
+++ b/src/shared/host-control.test.ts
@@ -21,6 +21,13 @@ describe('isHostOnlyChannel', () => {
expect(isHostOnlyChannel(IPC.projectSetupCancel)).toBe(true)
})
+ it('covers request-trust too — it RAISES the host’s own consent prompt', () => {
+ // A guest that could cast this one would be able to put a dialog on the host's screen at will
+ // (prompt spam), and — paired with an admitted consent-submit — approve a shared launchCmd/env
+ // for the host's own agent launches. Same self-approval loop as run+consent-submit.
+ expect(isHostOnlyChannel(IPC.projectSetupRequestTrust)).toBe(true)
+ })
+
it('leaves the read-only/lifecycle channels alone — the gate is on ACTION, not on the namespace', () => {
// Subscribing and receiving events costs a guest nothing the canvas does not already show;
// running host code, and answering the host's own trust prompt, are the two acts being gated.
diff --git a/src/shared/host-control.ts b/src/shared/host-control.ts
index 55931a263..bd3800392 100644
--- a/src/shared/host-control.ts
+++ b/src/shared/host-control.ts
@@ -16,6 +16,10 @@ import { IPC } from './ipc'
* dialog. Either one alone is much weaker; the pair is a complete self-approval loop.
* - `project-setup:cancel` — the other side of the same run's control: a guest must not be able to
* kill the host's setup mid-write.
+ * - `project-setup:request-trust` — RAISES the host's own consent dialog for a project's launch
+ * settings. Alone it is prompt spam on someone else's screen; paired with an admitted
+ * consent-submit it is the same self-approval loop as run+consent-submit, ending in a shared
+ * `launchCmd`/`env` (or shell) approved for the host's own agent launches.
*
* DELIBERATELY NOT LISTED: `project-setup:subscribe`/`unsubscribe` and the `project-setup:event:*`
* push. They neither start nor authorize anything, and a peer that can see the canvas can already
@@ -30,7 +34,8 @@ export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = ['githubControl:']
export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([
IPC.projectSetupRun,
IPC.projectSetupCancel,
- IPC.projectSetupConsentSubmit
+ IPC.projectSetupConsentSubmit,
+ IPC.projectSetupRequestTrust
])
/** What a refused peer is told. One wording, so the two shells answer identically. */
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index d7f9756f3..51666322a 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -246,8 +246,9 @@ export const IPC = {
* unknown project id, same as projectSettingsRead. */
projectSettingsLaunchInfo: 'project-settings:launch-info',
/** main→renderer broadcast: `{projectId}` after ANY family approval changes for that project (a
- * consent dialog answered, a trust record revoked). Nobody emits this yet (Task 2 records
- * approvals) — the channel exists so the renderer cache can subscribe ahead of the emitter. */
+ * consent dialog answered, a trust record revoked). Emitted by
+ * `ProjectSetupService.ensureFamilyTrusted` on an approval — for EVERY project that asked, not
+ * just the one that raised the prompt (two canvas nodes can share one location). */
projectTrustChanged: 'project-trust:changed',
/** Run a project's setup/archive script. Args: (projectId, kind, worktreePath?) — NO rootPath/
* projectName/ssh: the handler derives those itself from its own workspace index by projectId,
@@ -256,10 +257,18 @@ export const IPC = {
* projectSetupEvent. */
projectSetupRun: 'project-setup:run',
projectSetupCancel: 'project-setup:cancel',
+ /** Ask for one project's `agents`/`shell` family to be trusted, prompting if it is not. Args:
+ * `(projectId, family)` — nothing path-shaped: the handler derives the location from its own
+ * workspace index, same as projectSetupRun. Answers `true` only when the family is trusted at
+ * that location (nothing shared to gate, an existing grant, or a fresh approval); `false` covers
+ * skip, expiry and every failure. HOST-ONLY (`shared/host-control.ts`): it raises the host's own
+ * dialog. `setup` is deliberately NOT accepted here — that family is gated by the runner. */
+ projectSetupRequestTrust: 'project-setup:request-trust',
/** 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). */
+ /** main→renderer: raise the trust dialog (payload: ProjectConsentRequest — tagged by family, the
+ * `setup` arm being the script-runner's own request). */
projectSetupConsentRequest: 'project-setup:consent-request',
/** main→renderer: close a prompt nobody answered (payload: { requestId }). */
projectSetupConsentDismiss: 'project-setup:consent-dismiss',
diff --git a/src/shared/project-settings.ts b/src/shared/project-settings.ts
index 2ec418314..e6575cd86 100644
--- a/src/shared/project-settings.ts
+++ b/src/shared/project-settings.ts
@@ -373,6 +373,51 @@ export interface ProjectSetupConsentRequest {
previouslyApproved: boolean
}
+/**
+ * main→renderer: the consent prompt for a family nothing in the setup service EXECUTES — the launch
+ * settings a caller is about to consume. Same one-answer machinery, same trichotomy, same host-only
+ * delivery as the setup request; what differs is the content the dialog must put on screen, because
+ * that content is what the one approval covers (`projectTrustContent('agents', …)` hashes launchCmd
+ * AND every env pair, so BOTH are in the payload — showing one half would approve the other unseen).
+ *
+ * Straight from the SHARED document, like `scripts` above: a local override must never be able to
+ * launder a shared value past the dialog by making it look like the user's own typing.
+ */
+export interface ProjectAgentsConsentRequest {
+ family: 'agents'
+ requestId: string
+ projectName: string
+ locationLabel: string
+ previouslyApproved: boolean
+ /** Absent when the shared doc sets no launch command (an env-only family is still gated). */
+ launchCmd?: string
+ /** Absent when the shared doc sets no env. Values are the approved bytes — rendered verbatim. */
+ env?: Record<string, string>
+}
+
+/** main→renderer: the consent prompt for the terminal program a shared document names. The whole
+ * family's executable content is this one string (`projectTrustContent('shell', …)`). */
+export interface ProjectShellConsentRequest {
+ family: 'shell'
+ requestId: string
+ projectName: string
+ locationLabel: string
+ previouslyApproved: boolean
+ shell: string
+}
+
+/**
+ * Everything that can arrive on `IPC.projectSetupConsentRequest`, TAGGED by trust family: one
+ * channel, one queue, one dialog — the tag says which variant's content to render. The `setup` arm
+ * is the original payload with the tag added; a renderer that switches on `family` must treat a tag
+ * it does not know as unrenderable (never as "some other variant"), because approving a prompt
+ * whose content was not on screen is exactly what this dialog exists to prevent.
+ */
+export type ProjectConsentRequest =
+ | ({ family: 'setup' } & ProjectSetupConsentRequest)
+ | ProjectAgentsConsentRequest
+ | ProjectShellConsentRequest
+
export type ProjectSetupConsentAnswer = 'approve' | 'skip'
export type ProjectSetupRunResult =
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 9357b6076..a2dce84a9 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -801,8 +801,19 @@ export interface ProjectSetupApi {
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
+ /**
+ * Ask for this project's `agents`/`shell` family to be trusted, prompting the human if it is not
+ * yet — the call a launcher makes before consuming a shared-sourced `launchCmd`/`env`/`shell`.
+ * `true` only when the family is trusted at that project's location (nothing shared to gate, an
+ * existing grant, or a fresh approval); skip, expiry, an unknown project and a refused (relay
+ * guest) call are all `false`. Concurrent asks for one location share ONE dialog. On approval,
+ * `projectSettings.onTrustChanged` fires for the project, so a cached launch-info verdict is
+ * re-read rather than trusted from before the answer.
+ */
+ requestTrust(projectId: string, family: 'agents' | 'shell'): Promise<boolean>
+ /** main → renderer: raise the trust dialog before a shared-sourced script runs, or before a
+ * shared-sourced launch setting is consumed — tagged by family (`ProjectConsentRequest`). */
+ onConsentRequest(cb: (req: import('./project-settings').ProjectConsentRequest) => 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