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): materialize-shared IPC wired before worktree setup

enesa95ee5ab3397
diff --git a/src/core/worktree-shared-paths-handlers.test.ts b/src/core/worktree-shared-paths-handlers.test.ts
new file mode 100644
index 000000000..78c01c3e0
--- /dev/null
+++ b/src/core/worktree-shared-paths-handlers.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import {
+ registerWorktreeSharedPathsHandlers,
+ type WorktreeSharedPathsDeps
+} from './worktree-shared-paths-handlers'
+import { IPC } from '../shared/ipc'
+import type { SharedPathResult } from './worktree-shared-paths'
+import type { ProjectSettingsSnapshot } from '../shared/project-settings'
+import type { WorktreeListResult } from '../shared/worktree'
+
+const materialize = (f: FakePlatform, projectId: unknown, worktreePath: unknown) =>
+ f.handlers[IPC.worktreeMaterializeShared](projectId, worktreePath) as Promise<SharedPathResult[]>
+
+// A snapshot whose SHARED doc lists the given sharedPaths — the list the handler must read ITSELF
+// by projectId (never a value the renderer passed in).
+const snapshotWithSharedPaths = (sharedPaths: string[]): ProjectSettingsSnapshot => ({
+ shared: { version: 1, rev: 1, savedAt: '', worktree: { sharedPaths } },
+ local: undefined
+})
+
+describe('registerWorktreeSharedPathsHandlers', () => {
+ let base: string
+ let repoRoot: string
+ let worktreeRoot: string
+ beforeEach(() => {
+ base = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-wt-shared-'))
+ repoRoot = path.join(base, 'repo')
+ worktreeRoot = path.join(base, 'repo.worktrees', 'feature')
+ fs.mkdirSync(repoRoot, { recursive: true })
+ fs.mkdirSync(worktreeRoot, { recursive: true })
+ // A git-ignored dir that the worktree does NOT have yet — the thing sharedPaths links back.
+ fs.mkdirSync(path.join(repoRoot, 'node_modules'), { recursive: true })
+ fs.writeFileSync(path.join(repoRoot, 'node_modules', 'marker.txt'), 'x')
+ })
+ afterEach(() => {
+ fs.rmSync(base, { recursive: true, force: true })
+ })
+
+ const depsFor = (over: Partial<WorktreeSharedPathsDeps> = {}): WorktreeSharedPathsDeps => ({
+ readSettings: async () => snapshotWithSharedPaths(['node_modules']),
+ targetInfo: () => ({ cwd: repoRoot, name: 'demo' }),
+ worktreeList: async (): Promise<WorktreeListResult> => ({
+ ok: true,
+ entries: [
+ { path: repoRoot, branch: 'main', head: null, isBare: false },
+ { path: worktreeRoot, branch: 'feature', head: null, isBare: false }
+ ]
+ }),
+ ...over
+ })
+
+ it('materializes the sharedPaths list it reads by projectId — the renderer never passes one', async () => {
+ const f = fakePlatform()
+ // The wire passes ONLY (projectId, worktreePath); the list comes from readSettings.
+ registerWorktreeSharedPathsHandlers(f, depsFor())
+ const res = await materialize(f, 'p1', worktreeRoot)
+ expect(res).toEqual([{ path: 'node_modules', status: 'linked' }])
+ // The symlink actually points back at the repo copy.
+ const linked = path.join(worktreeRoot, 'node_modules', 'marker.txt')
+ expect(fs.readFileSync(linked, 'utf-8')).toBe('x')
+ })
+
+ it('refuses a worktreePath that is not one of the project’s worktrees → []', async () => {
+ const f = fakePlatform()
+ registerWorktreeSharedPathsHandlers(f, depsFor())
+ const strayer = path.join(os.tmpdir(), 'nt-not-a-worktree')
+ fs.mkdirSync(strayer, { recursive: true })
+ const res = await materialize(f, 'p1', strayer)
+ expect(res).toEqual([])
+ // And nothing was linked into the stray dir.
+ expect(fs.existsSync(path.join(strayer, 'node_modules'))).toBe(false)
+ fs.rmSync(strayer, { recursive: true, force: true })
+ })
+
+ it('an SSH project → [] (materialization is local-only this PR)', async () => {
+ const f = fakePlatform()
+ registerWorktreeSharedPathsHandlers(
+ f,
+ depsFor({
+ targetInfo: () => ({
+ ssh: { host: 'h', user: 'u', remoteCwd: '/srv/app' } as never,
+ name: 'demo'
+ })
+ })
+ )
+ const res = await materialize(f, 'p1', worktreeRoot)
+ expect(res).toEqual([])
+ })
+
+ it('an unknown project (no target info) → []', async () => {
+ const f = fakePlatform()
+ registerWorktreeSharedPathsHandlers(f, depsFor({ targetInfo: () => null }))
+ const res = await materialize(f, 'p1', worktreeRoot)
+ expect(res).toEqual([])
+ })
+
+ it('a non-string projectId or worktreePath → []', async () => {
+ const f = fakePlatform()
+ registerWorktreeSharedPathsHandlers(f, depsFor())
+ expect(await materialize(f, 42, worktreeRoot)).toEqual([])
+ expect(await materialize(f, 'p1', undefined)).toEqual([])
+ })
+
+ it('no sharedPaths configured → [] (nothing to link)', async () => {
+ const f = fakePlatform()
+ registerWorktreeSharedPathsHandlers(
+ f,
+ depsFor({ readSettings: async () => snapshotWithSharedPaths([]) })
+ )
+ const res = await materialize(f, 'p1', worktreeRoot)
+ expect(res).toEqual([])
+ })
+})
diff --git a/src/core/worktree-shared-paths-handlers.ts b/src/core/worktree-shared-paths-handlers.ts
new file mode 100644
index 000000000..1327cbbb7
--- /dev/null
+++ b/src/core/worktree-shared-paths-handlers.ts
@@ -0,0 +1,66 @@
+import { IPC } from '../shared/ipc'
+import { resolveProjectSettings, type ProjectSettingsSnapshot } from '../shared/project-settings'
+import type { WorktreeListResult } from '../shared/worktree'
+import type { CorePlatform } from './platform'
+import { resolveProjectSetupTarget, type ProjectSetupTargetInfo } from './project-setup-runner-local'
+import { materializeSharedPaths, type SharedPathResult } from './worktree-shared-paths'
+
+/**
+ * RPC surface for `worktree:materialize-shared`, registered once per shell (Electron main + Server
+ * Edition) through CorePlatform — the `project-setup-handlers.ts` / `project-launch-info-handlers.ts`
+ * sibling-registrar shape.
+ *
+ * The wire carries ONLY `(projectId, worktreePath)`. It NEVER carries the `sharedPaths` list: a
+ * renderer-supplied list of relative paths is untrusted input (it could name anything, and would
+ * also let a compromised renderer materialize links a project never opted into). The handler reads
+ * the list ITSELF, by projectId, out of the project's resolved settings
+ * (`readSettings` → `resolveProjectSettings` → `worktree.sharedPaths`).
+ *
+ * The trust boundary is the SAME one the setup runner uses (`resolveProjectSetupTarget`): rootPath
+ * (= the project's `cwd`) is derived from THIS process's own workspace index by projectId, never the
+ * caller, and `worktreePath` is independently validated to be either that rootPath or one of the
+ * project's ACTUAL git worktrees — else the call is refused with `[]`. An SSH project is refused the
+ * same way (materialization is local-only this PR; `resolveProjectSetupTarget` already rejects an
+ * ssh target that carries a worktreePath, and we re-check `target.ssh` here as defense in depth).
+ * Every refusal — unknown project, bad worktreePath, ssh, non-string args, no configured
+ * sharedPaths — answers `[]`, the same shape a real "nothing was linked" answer uses, so a caller
+ * needs no extra branch.
+ */
+export interface WorktreeSharedPathsDeps {
+ /** This shell's own settings resolution (e.g. `WorkspaceStore.readProjectSettings`). */
+ readSettings(projectId: string): Promise<ProjectSettingsSnapshot | null>
+ /** This shell's own workspace index lookup (e.g. `WorkspaceStore.projectTargetInfo`). */
+ targetInfo(projectId: string): ProjectSetupTargetInfo | null
+ /** `git worktree list` for a repo root (e.g. `GitService#worktreeList` bound to the caller). */
+ worktreeList(repoPath: string): Promise<WorktreeListResult>
+}
+
+export function registerWorktreeSharedPathsHandlers(
+ platform: CorePlatform,
+ deps: WorktreeSharedPathsDeps
+): void {
+ platform.handle(
+ IPC.worktreeMaterializeShared,
+ async (projectId: unknown, worktreePath: unknown): Promise<SharedPathResult[]> => {
+ if (typeof projectId !== 'string' || !projectId) return []
+ if (typeof worktreePath !== 'string' || !worktreePath) return []
+
+ // Same derivation + validation the setup runner performs: rootPath/ssh come from THIS
+ // process's index by projectId, and `worktreePath` must be the project's rootPath or one of
+ // its actual worktrees. A null target = unknown project / no local folder / refused ssh path.
+ const info = deps.targetInfo(projectId)
+ const target = await resolveProjectSetupTarget(projectId, worktreePath, info, deps.worktreeList)
+ if (!target || target.ssh || !target.worktreePath) return []
+
+ // Read the sharedPaths list ITSELF by projectId — never a value off the wire.
+ const snap = await deps.readSettings(projectId)
+ const resolved = resolveProjectSettings(snap?.local, snap?.shared ?? undefined)
+ const sharedPaths = resolved.worktree.sharedPaths?.value ?? []
+ if (sharedPaths.length === 0) return []
+
+ // repoRoot = the project's own cwd (target.rootPath); target.worktreePath is the validated,
+ // absolute worktree directory. materializeSharedPaths never throws.
+ return materializeSharedPaths(target.rootPath, target.worktreePath, sharedPaths)
+ }
+ )
+}
diff --git a/src/core/worktree-shared-paths.ts b/src/core/worktree-shared-paths.ts
index 414646a99..8c097ffc7 100644
--- a/src/core/worktree-shared-paths.ts
+++ b/src/core/worktree-shared-paths.ts
@@ -20,20 +20,12 @@
import { promises as fs } from 'fs'
import path from 'path'
-import { isInsideDir } from '../shared/worktree'
+import { isInsideDir, type SharedPathResult } from '../shared/worktree'
-export interface SharedPathResult {
- path: string
- status:
- | 'linked'
- | 'skipped-missing-source'
- | 'skipped-exists'
- | 'skipped-reserved'
- | 'skipped-unsafe'
- | 'error'
- /** Present only for `error` (or a noteworthy skip): a short human-readable reason. */
- note?: string
-}
+// The type lives in `shared/worktree.ts` so the renderer's `WorktreeApi` can name it without a
+// wrong-direction import into core; re-exported here so this module's own callers/tests keep
+// importing it from where it originated.
+export type { SharedPathResult }
// Mirror of the sanitizer's relative-safety checks in src/shared/project-settings.ts
// (`hasTraversalSegment` + the absolute / Windows-drive rejection). Values are already sanitized at
diff --git a/src/main/index.ts b/src/main/index.ts
index 0c07238d6..80f20aef3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -71,6 +71,7 @@ import {
type ProjectSetupHandlerDeps
} from '../core/project-setup-handlers'
import { registerProjectLaunchInfoHandlers } from '../core/project-launch-info-handlers'
+import { registerWorktreeSharedPathsHandlers } from '../core/worktree-shared-paths-handlers'
import { makeProjectSpawnOverrides } from '../core/project-spawn-overrides'
import { makeLocalSetupRunner } from '../core/project-setup-runner-local'
import { makeSshSetupRunner } from './remote-ssh/ssh-setup-runner'
@@ -385,6 +386,16 @@ const projectSetupDeps: ProjectSetupHandlerDeps = {
worktreeList: (repoPath) => gitService.worktreeList(repoPath)
}
registerProjectSetupHandlers(corePlatform, projectSetupService, projectSetupDeps)
+// `worktree:materialize-shared` — same sibling-registrar shape and the SAME trust boundary as the
+// setup runner (rootPath/ssh derived from THIS process's index by projectId, `worktreePath`
+// re-validated against the project's actual git worktrees); the sharedPaths LIST is read here by
+// projectId, never taken off the wire. Reuses the very `projectTargetInfo`/`worktreeList` the setup
+// deps already carry, plus the store's own settings resolution.
+registerWorktreeSharedPathsHandlers(corePlatform, {
+ readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),
+ targetInfo: projectSetupDeps.projectTargetInfo,
+ worktreeList: projectSetupDeps.worktreeList
+})
// `project-settings:launch-info` — a sibling registrar (not a widening of
// WorkspaceStore.registerIpc()) sharing the trust store constructed above.
registerProjectLaunchInfoHandlers(corePlatform, workspaceStore, projectTrustStore)
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 6eb1c9988..590cbc8c9 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -185,6 +185,13 @@ const api: NodeTerminalApi = {
}
}
},
+ worktree: {
+ // Wire carries exactly `(projectId, worktreePath)` — never the sharedPaths list: main reads it
+ // itself by projectId and validates the path against the project's own git worktrees
+ // (worktree-shared-paths-handlers.ts).
+ materializeShared: (projectId: string, worktreePath: string) =>
+ ipcRenderer.invoke(IPC.worktreeMaterializeShared, projectId, worktreePath)
+ },
dialog: {
selectFolder: () => ipcRenderer.invoke(IPC.dialogSelectFolder),
selectFile: () => ipcRenderer.invoke(IPC.dialogSelectFile)
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index c56aa59f7..f97d996ad 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -320,6 +320,12 @@ export function buildStubApi(): Omit<
onConsentDismiss: noopUnsub,
onEvent: noopUnsub
},
+ worktree: {
+ // Real over the bridge (`buildRealApi`'s `worktree`); this fallback only matters if some
+ // future assembly spreads the stub alone. Fails closed with the SAME empty-result shape a
+ // real "nothing was linked" answer uses, so a caller needs no extra branch.
+ materializeShared: () => Promise.resolve([])
+ },
chat: {
readTranscript: U('chat.readTranscript')
},
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 7f5b6921e..200a30c5c 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -211,7 +211,14 @@ export function buildRealApi(
client: RpcClient
): Pick<
NodeTerminalApi,
- 'pty' | 'workspace' | 'projectSettings' | 'projectSetup' | 'settings' | 'agent' | 'userDataDir'
+ | 'pty'
+ | 'workspace'
+ | 'projectSettings'
+ | 'projectSetup'
+ | 'worktree'
+ | 'settings'
+ | 'agent'
+ | 'userDataDir'
> {
const pty: PtyApi = {
create: (options: PtyCreateOptions) =>
@@ -343,6 +350,15 @@ export function buildRealApi(
}
}
+ // REAL: registerWorktreeSharedPathsHandlers (core), same construction point as main/server. Wire
+ // carries exactly `(projectId, worktreePath)`; the server reads the sharedPaths list itself.
+ const worktree: NodeTerminalApi['worktree'] = {
+ materializeShared: (projectId, worktreePath) =>
+ client.request(IPC.worktreeMaterializeShared, projectId, worktreePath) as ReturnType<
+ NodeTerminalApi['worktree']['materializeShared']
+ >
+ }
+
const settings: SettingsApi = {
load: () => client.request(IPC.settingsLoad) as Promise<Settings>,
save: (s: Settings) => client.request(IPC.settingsSave, s) as Promise<void>
@@ -377,7 +393,7 @@ export function buildRealApi(
// `/worktrees/…` at the filesystem root (the server usually runs as root, and git would create it).
const userDataDir = (): Promise<string> => client.request(IPC.appUserDataDir) as Promise<string>
- return { pty, workspace, projectSettings, projectSetup, settings, agent, userDataDir }
+ return { pty, workspace, projectSettings, projectSetup, worktree, settings, agent, userDataDir }
}
export function buildGitHubApi(
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index b4f0e573c..59c00a0cc 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -4432,7 +4432,18 @@ export function Canvas() {
// A fresh checkout is the moment the project's `setup` script exists for: this is the single
// shared post-create point (the dialog AND agent-control's open-worktree land here), so the
// trigger lives here rather than being repeated — and never diverging — at each caller.
- startWorktreeSetup(groupId, wt.path)
+ //
+ // Materialize the project's `sharedPaths` (symlink node_modules/etc back to the repo root)
+ // BEFORE the setup script runs, so a setup `npm install` sees those links. Fire-and-forget re
+ // the bind (it never blocks the frame), but ORDERED before `startWorktreeSetup` — main reads
+ // the sharedPaths list itself by projectId and validates `wt.path`, so a `[]`/reject is safe.
+ void (async () => {
+ const projectId = useProjects.getState().activeProjectId
+ if (projectId) {
+ await window.nodeTerminal.worktree.materializeShared(projectId, wt.path).catch(() => {})
+ }
+ startWorktreeSetup(groupId, wt.path)
+ })()
// The bound group's id (fresh one when created here) — nodesRef lags setNodes, so
// callers that need the id (agent-control's open-worktree reply) take it from here.
return groupId
diff --git a/src/server/index.ts b/src/server/index.ts
index 1eaa1cf77..0f63dc15f 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -39,6 +39,7 @@ import {
type ProjectSetupHandlerDeps
} from '../core/project-setup-handlers'
import { registerProjectLaunchInfoHandlers } from '../core/project-launch-info-handlers'
+import { registerWorktreeSharedPathsHandlers } from '../core/worktree-shared-paths-handlers'
import { makeProjectSpawnOverrides } from '../core/project-spawn-overrides'
import { makeLocalSetupRunner } from '../core/project-setup-runner-local'
import { LogBuffer } from '../core/log-buffer'
@@ -294,6 +295,14 @@ export async function startServer(
worktreeList: (repoPath) => gitService.worktreeList(repoPath)
}
registerProjectSetupHandlers(platform, projectSetupService, projectSetupDeps)
+ // `worktree:materialize-shared` — same sibling registrar and trust boundary as main/index.ts,
+ // over this process's own stores. The Server Edition has no SSH projects, so an ssh-shaped target
+ // never arises; the path validation and by-projectId list read are identical.
+ registerWorktreeSharedPathsHandlers(platform, {
+ readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),
+ targetInfo: projectSetupDeps.projectTargetInfo,
+ worktreeList: projectSetupDeps.worktreeList
+ })
// `project-settings:launch-info` — same sibling registrar as main/index.ts, sharing this
// process's own trust store.
registerProjectLaunchInfoHandlers(platform, workspaceStore, projectTrustStore)
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 51666322a..695255edd 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -276,6 +276,13 @@ export const IPC = {
projectSetupEvent: (projectId: string) => `project-setup:event:${projectId}`,
projectSetupSubscribe: 'project-setup:subscribe',
projectSetupUnsubscribe: 'project-setup:unsubscribe',
+ /** Renderer → core: symlink a project's `sharedPaths` from its repo root into a freshly-created
+ * git worktree. Args carry ONLY `(projectId, worktreePath)` — NEVER the path list, which the
+ * handler reads itself by projectId (the list is untrusted from a renderer). The handler
+ * validates `worktreePath` is that project's rootPath or one of its actual git worktrees, and
+ * refuses an SSH project (local-only this PR); an unknown/invalid input answers `[]`. Resolves
+ * `SharedPathResult[]`. See core/worktree-shared-paths-handlers.ts. */
+ worktreeMaterializeShared: 'worktree:materialize-shared',
// main → renderer events
workspaceMigrated: 'workspace:migrated',
/** Payload: the `workspace.json.corrupt-<ts>` filename the unreadable index was preserved as. */
diff --git a/src/shared/types.ts b/src/shared/types.ts
index a2dce84a9..0fd4b4881 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -821,6 +821,23 @@ export interface ProjectSetupApi {
onEvent(projectId: string, cb: (ev: import('./project-settings').ProjectSetupEvent) => void): () => void
}
+export interface WorktreeApi {
+ /**
+ * Symlink a project's configured `sharedPaths` (git-ignored dirs like `node_modules`) from its
+ * repo root into a freshly-created git worktree, so a setup `npm install` there sees the links.
+ *
+ * The renderer passes ONLY `(projectId, worktreePath)` — never the path list: main reads the list
+ * itself out of the project's settings by `projectId`, derives the repo root from its own
+ * workspace index, and validates `worktreePath` is that project's rootPath or one of its actual
+ * git worktrees. An unknown project, an unvalidated path, or an SSH project (local-only this PR)
+ * all resolve `[]`. Never rejects — a per-entry `SharedPathResult[]` reports what happened.
+ */
+ materializeShared(
+ projectId: string,
+ worktreePath: string
+ ): Promise<import('./worktree').SharedPathResult[]>
+}
+
export interface DialogApi {
/** Opens a native folder picker; returns the chosen path or null if cancelled. */
selectFolder(): Promise<string | null>
@@ -2532,6 +2549,7 @@ export interface NodeTerminalApi {
workspace: WorkspaceApi
projectSettings: ProjectSettingsApi
projectSetup: ProjectSetupApi
+ worktree: WorktreeApi
dialog: DialogApi
settings: SettingsApi
speech: SpeechApi
diff --git a/src/shared/worktree.ts b/src/shared/worktree.ts
index 522dfe499..0594d884b 100644
--- a/src/shared/worktree.ts
+++ b/src/shared/worktree.ts
@@ -11,6 +11,22 @@ export interface GroupWorktree {
createdByApp: boolean
}
+/** One entry's outcome from materializing a project's `sharedPaths` into a worktree
+ * (core/worktree-shared-paths.ts). Lives here in `shared` so the renderer's `WorktreeApi` type can
+ * name it without importing core; core's module re-exports it for its own callers/tests. */
+export interface SharedPathResult {
+ path: string
+ status:
+ | 'linked'
+ | 'skipped-missing-source'
+ | 'skipped-exists'
+ | 'skipped-reserved'
+ | 'skipped-unsafe'
+ | 'error'
+ /** Present only for `error` (or a noteworthy skip): a short human-readable reason. */
+ note?: string
+}
+
export interface WorktreeEntry {
path: string
branch: string | null