Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(server): restore saved project grants after restart
freshjuiceze9cb50ba8d26
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 9205e0978..5bfb78781 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -314,6 +314,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {' confirm (your first open of an already-registered project asks once too) and may be denied —',' a denial is final, do not retry it. Local only (refused from an SSH project), and it never',' focuses the new project\'s tab. The returned id is what `--project` accepts.',+ ' Server Edition is narrower: it can only re-open an exact local project already saved in its',+ ' workspace (pass `--cwd` only); it never creates, adds, renames, recolors, or focuses one.','- `show-image <path>` / `show-video <path>` — open a media file as a node.','- `show-web (--url U | --file P.html | --html "<...>")` — open a web viewer.','- `open-browser --url U` — open a navigable browser node.',@@ -665,6 +667,9 @@ Verbs:already-registered project asks once too) and may be denied — a denial is final, do not retryit. Local only (refused from an SSH project), and it never focuses the new project's tab: usethe returned id with \`--project\` to open sessions there.+ On Server Edition this is a restart-recovery operation only: pass \`--cwd\` for an exact local+ project already saved in that Server workspace. It never creates, adds, renames, recolors, or+ focuses a project; register a missing project in the UI first.- \`show-image <path>\` — open an image file as a node.- \`show-video <path>\` — open a video file as a player node.- \`show-web (--url U | --file P.html | --html "<...>")\` — open a web viewer (live URL or local HTML you wrote).diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex 79218cef4..5aa218c61 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -170,6 +170,8 @@ export async function initServerCanvasControl(messaging.queue = queueconst actions: ServerEditionControlActions = {+ openProject: (sourceNodeId, args, verified) =>+ factory.openProject(sourceNodeId, args, verified),openTerminal: (sourceNodeId, args, verified) =>factory.openTerminal(sourceNodeId, args, verified),openAgent: (sourceNodeId, args, verified) => factory.openAgent(sourceNodeId, args, verified),diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.tsindex 4882b7217..e7d438982 100644--- a/src/server/control-unsupported.test.ts+++ b/src/server/control-unsupported.test.ts@@ -100,10 +100,10 @@ describe('the Server Edition refuses canvas control by name', () => {expect(text).toContain('do not retry')})- it('`open-project` is unreachable on this edition — the P8 pin for issue #338', async () => {- // No server code changed for #338 and none may need to: the SE registers this handler for- // ALL verbs, so open-project (and any --project-carrying open) answers the same permanent- // named refusal. Pinned by name so the contract cannot drift silently.+ it('`open-project` stays unreachable when Server canvas control is disabled', async () => {+ // The feature-off rollback handler refuses every verb. The enabled handler below exposes the+ // narrow existing-local-project recovery form, but a disabled deployment must still answer a+ // permanent named refusal rather than pretending the operation succeeded.expect(await serverEditionControlHandler({ verb: 'open-project' })).toEqual({ok: false,error: CONTROL_UNSUPPORTED_ERROR,@@ -173,6 +173,7 @@ describe('the Server Edition wires it at boot', () => {describe('the enabled Server Edition handler parses and dispatches the v1 surface', () => {const actions = () => ({+ openProject: vi.fn(async () => ({ ok: true as const, result: { projectId: 'project-loop' } })),openTerminal: vi.fn(async () => ({ ok: true as const, result: { id: 'term-new' } })),openAgent: vi.fn(async () => ({ ok: true as const, result: { id: 'agent-new' } })),close: vi.fn(async () => ({ ok: true as const, result: { id: 'closed' } })),@@ -206,6 +207,20 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac).resolves.toEqual({ ok: false, error: 'open-agent requires --agent <id>' })expect(a.openAgent).not.toHaveBeenCalled()+ await expect(+ handler({+ verb: 'open-project',+ nodeId: 'term-source',+ args: { cwd: '/srv/loop' },+ verified: true+ })+ ).resolves.toMatchObject({ ok: true })+ expect(a.openProject).toHaveBeenCalledWith(+ 'term-source',+ { cwd: '/srv/loop' },+ true+ )+await expect(handler({verb: 'close',@@ -308,7 +323,7 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfacit('keeps every deferred or unknown verb a clean permanent edition refusal', async () => {const handler = createServerEditionControlHandler(actions())- for (const verb of ['list', 'browser', 'open-project', 'write', 'not-a-verb']) {+ for (const verb of ['list', 'browser', 'write', 'not-a-verb']) {const reply = await handler({ verb, nodeId: 'term-source', args: {}, verified: true })expect(reply, verb).toMatchObject({ ok: false, error: CONTROL_UNSUPPORTED_ERROR })expect(reply.message, verb).toContain('do not retry')diff --git a/src/server/control-unsupported.ts b/src/server/control-unsupported.tsindex e914371d1..561e5a752 100644--- a/src/server/control-unsupported.ts+++ b/src/server/control-unsupported.ts@@ -64,6 +64,11 @@ export async function serverEditionControlHandler({ verb }: { verb: string }): P}export interface ServerEditionControlActions {+ openProject(+ sourceNodeId: string,+ args: Record<string, string>,+ verified: boolean+ ): Promise<ServerControlReply>openTerminal(sourceNodeId: string,args: Record<string, string>,@@ -97,6 +102,7 @@ export interface ServerEditionControlActions {}const SERVER_V1_VERBS: ReadonlySet<string> = new Set([+ 'open-project','open-terminal','open-agent','close',@@ -143,6 +149,8 @@ export function createServerEditionControlHandler(actions: ServerEditionControlAif ('error' in command) return { ok: false, error: command.error }switch (command.verb) {+ case 'open-project':+ return actions.openProject(nodeId, command.args, verified)case 'open-terminal':return actions.openTerminal(nodeId, command.args, verified)case 'open-agent':diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.tsindex 3ac7c1f1c..a244f5ac4 100644--- a/src/server/headless-node-factory.test.ts+++ b/src/server/headless-node-factory.test.ts@@ -182,6 +182,96 @@ describe('HeadlessNodeFactory', () => {})})+ it('re-grants an exact saved local project after a Server restart before cross-project open', async () => {+ const targetDir = path.join(dataDir, 'loop-project')+ fs.mkdirSync(targetDir, { recursive: true })+ const workspace = await store.load({ sideline: false })+ workspace.projects.push({+ id: 'project-loop',+ name: 'Loop',+ color: '#6ac4dc',+ cwd: targetDir,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [],+ bridges: [],+ ropes: []+ })+ await store.save(workspace)++ await expect(+ factory.openAgent(+ 'term-source',+ { agent: 'claude', project: 'project-loop', prompt: 'resume loop' },+ true+ )+ ).resolves.toMatchObject({+ ok: false,+ error: expect.stringContaining('project-target-refused')+ })++ await expect(+ factory.openProject('term-source', { cwd: targetDir }, true)+ ).resolves.toMatchObject({+ ok: true,+ result: {+ projectId: 'project-loop',+ cwd: targetDir,+ created: false,+ serverExistingOnly: true+ }+ })++ // A grant belongs to the exact verified caller. Another agent in the same source project may+ // not consume it merely because it learned the returned project id.+ await expect(+ factory.openAgent(+ 'term-upstream',+ { agent: 'claude', project: 'project-loop', prompt: 'steal grant' },+ true+ )+ ).resolves.toMatchObject({+ ok: false,+ error: expect.stringContaining('project-target-refused')+ })++ const opened = await factory.openAgent(+ 'term-source',+ { agent: 'claude', project: 'project-loop', prompt: 'resume loop' },+ true+ )+ expect(opened.ok).toBe(true)+ const id = (opened.result as { id: string }).id+ expect(pty.creates.at(-1)).toMatchObject({+ persistKey: id,+ ownerProjectId: 'project-loop',+ cwd: targetDir+ })+ expect((await store.load({ sideline: false })).projects+ .find((project) => project.id === 'project-loop')?.nodes+ .some((node) => node.id === id)).toBe(true)+ })++ it('never creates or enumerates a project through Server open-project', async () => {+ const missing = path.join(dataDir, 'not-registered')+ fs.mkdirSync(missing, { recursive: true })++ await expect(+ factory.openProject('term-source', { cwd: missing }, true)+ ).resolves.toMatchObject({+ ok: false,+ error: expect.stringContaining('server-existing-only')+ })+ await expect(+ factory.openProject('term-source', { cwd: projectDir }, false)+ ).resolves.toMatchObject({+ ok: false,+ error: expect.stringContaining('identity-refused')+ })++ const reloaded = await store.load({ sideline: false })+ expect(reloaded.projects).toHaveLength(1)+ })+it('lets a verified caller close its own spawn, killing the pane before persisted edge removal and fanout', async () => {const opened = await factory.openAgent('term-source',diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex 7292c4c19..49985b8c3 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -1,7 +1,8 @@import { randomBytes, randomUUID } from 'node:crypto'+import path from 'node:path'import { publishCanvasMutation } from '../core/canvas-sync'-import { gateProjectTarget } from '../core/project-grants'+import { gateProjectTarget, GRANT_CAP } from '../core/project-grants'import { planBridges, type LinkEndpoint } from '../shared/canvas-link'import {invalidNodeColorMessage,@@ -452,6 +453,13 @@ export class HeadlessNodeFactory {private spawnedBy = new Map<string, { sourceNodeId: string; projectId: string }>()/** Fresh server-spawned agents that have not emitted their first real working turn yet. */private awaitingFirstWorking = new Set<string>()+ /**+ * Server-local `open-project` grants. The browser shell's grant ledger is process-local too,+ * but Server Edition has its own process and handler. A service restart deliberately clears+ * this map; `openProject()` can re-establish a grant only for an exact, already-saved local+ * project path, so a surviving agent session is never stranded after that restart.+ */+ private projectGrants = new Map<string, Set<string>>()private retryCount = new Map<string, number>()private retryTimers = new Map<string, ReturnType<typeof setTimeout>>()private stopped = false@@ -487,6 +495,18 @@ export class HeadlessNodeFactory {this.publishChangeSet(project, nodes, [])}+ private projectGranted(sourceNodeId: string, projectId: string): boolean {+ return this.projectGrants.get(sourceNodeId)?.has(projectId) ?? false+ }++ private grantProject(sourceNodeId: string, projectId: string): boolean {+ const grants = this.projectGrants.get(sourceNodeId) ?? new Set<string>()+ if (!grants.has(projectId) && grants.size >= GRANT_CAP) return false+ grants.add(projectId)+ this.projectGrants.set(sourceNodeId, grants)+ return true+ }+private async attach(project: Project, node: CanvasNodeState): Promise<PtyCreateResult> {if (this.attached.has(node.id)) {return { sessionId: node.id, fresh: false }@@ -511,8 +531,7 @@ export class HeadlessNodeFactory {targetProjectId: args.project || undefined,callerProjectId: source.project.id,targetIsSsh: target ? !!target.ssh : undefined,- // `open-project` is not part of Server Edition v1, so this runtime never mints a grant.- granted: false+ granted: this.projectGranted(source.node.id, targetId)})if (gate !== 'allow') return { ok: false, error: gate.refuse }if (!target) return { ok: false, error: 'project-target-refused: target project is unavailable' }@@ -554,6 +573,81 @@ export class HeadlessNodeFactory {return this.open(sourceNodeId, 'open-terminal', args, verified)}+ /**+ * Re-open one exact local project that is already present in the Server workspace and mint a+ * process-local targeting grant for this verified caller. Server Edition still cannot create,+ * add, rename, recolor, or focus projects: those operations require the browser UI's explicit+ * confirmation. This narrow existing-only form is the restart recovery path for long-lived+ * agent nodes whose tmux sessions survive the Server process.+ */+ openProject(+ sourceNodeId: string,+ args: Record<string, string>,+ verified: boolean+ ): Promise<ServerControlReply> {+ return this.runExclusive(async () => {+ const flagError = unsupportedFlags(args, new Set(['cwd']))+ if (flagError) return { ok: false, error: `open-project: ${flagError}` }+ if (!verified) {+ return {+ ok: false,+ error: 'open-project-identity-refused: Server Edition open-project requires verified node identity'+ }+ }++ const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const source = sourceProject(workspace, sourceNodeId)+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {+ return { ok: false, error: 'source node is not a control-capable agent' }+ }+ if (source.project.ssh) {+ return {+ ok: false,+ error: 'open-project-local-only: open-project is not available from an SSH project — do not retry'+ }+ }++ const rawCwd = args.cwd ?? ''+ if (!path.isAbsolute(rawCwd)) {+ return {+ ok: false,+ error: 'open-project-cwd-invalid: --cwd must be an absolute path to an existing saved local project'+ }+ }+ const cwd = path.resolve(rawCwd)+ const target = workspace.projects.find(+ (project) => !project.ssh && !!project.cwd && path.resolve(project.cwd) === cwd+ )+ if (!target) {+ return {+ ok: false,+ error:+ 'open-project-server-existing-only: Server Edition can only re-open an exact saved ' ++ 'local project path; add the project in the UI first — do not retry this path'+ }+ }+ if (!this.grantProject(sourceNodeId, target.id)) {+ return {+ ok: false,+ error: 'open-project-grant-cap: this session already holds the maximum number of project grants'+ }+ }++ return {+ ok: true,+ message: `re-opened saved local project ${target.id}; cross-project grant restored`,+ result: {+ projectId: target.id,+ name: target.name,+ cwd,+ created: false,+ serverExistingOnly: true+ }+ }+ })+ }+async openAgent(sourceNodeId: string,args: Record<string, string>,@@ -1218,5 +1312,6 @@ export class HeadlessNodeFactory {for (const timer of this.retryTimers.values()) (this.deps.clearSchedule ?? clearTimeout)(timer)this.retryTimers.clear()this.spawnedBy.clear()+ this.projectGrants.clear()}}