Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(agents): messagingEnabled is the capability GRANT, read per call off the store
Claude Code042aa409450f
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 63633ab86..8f7971156 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -12,6 +12,8 @@ import {serializeProjectFile, splitWorkspace, validKanban,type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3} from './workspace-files'+import { readProjectCapabilities, type ProjectCapability } from '../shared/project-capabilities'+import type { CapabilityAckMap } from './project-capability-consent'import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'import { collisionSeed, derivedProjectId, freshProjectId } from '../shared/project-id'import { appendProjectNode, type RemoteNodeInput } from './project-node-append'@@ -782,6 +784,47 @@ export class WorkspaceStore {return out}+ /**+ * The capability view of one project, for `projectCapabilityGrantedFor`: the STRICT capability+ * flags from the shared file (`readProjectCapabilities` — literal `true`, known keys only) plus+ * this machine's recorded answers from the INDEX ENTRY. Same three-entry-kind scan and same id+ * semantics as `persistedCanvases`, because the projectId a delivery resolved there must look up+ * the same project here.+ *+ * The ack deliberately never comes from the parsed file: a repo hand-carrying `capabilityAck`+ * is a forgery attempt (workspace-files.ts says the same at the fileToProject boundary), and+ * `agent-messaging-switch.test.ts` drives that exact file through a real store. An inline entry+ * stores the Project verbatim (ack included — splitWorkspace gives it no localState), so there+ * the project object IS the entry-local record.+ */+ capabilityProjectFor(+ projectId: string+ ): (Partial<Record<ProjectCapability, true>> & { capabilityAck?: CapabilityAckMap }) | undefined {+ for (const e of this.index?.entries ?? []) {+ if (e.project) {+ if (e.project.id !== projectId) continue+ return {+ ...readProjectCapabilities(e.project),+ ...(e.project.capabilityAck ? { capabilityAck: e.project.capabilityAck } : {})+ }+ }+ if (e.id !== projectId) continue+ const ack = e.capabilityAck ? { capabilityAck: e.capabilityAck } : {}+ if (e.cache) return { ...readProjectCapabilities(e.cache), ...ack }+ if (e.cwd) {+ const raw = this.lastWritten.get(projectFilePath(e.cwd))+ if (!raw) return { ...ack } // file never read this run: no flag known, so nothing grants+ try {+ return { ...readProjectCapabilities(JSON.parse(raw)), ...ack }+ } catch {+ return { ...ack } // corrupt file: fail closed, like every other reader of this cache+ }+ }+ return undefined+ }+ return undefined+ }+getNodeTitle(nodeId: string): string | undefined {for (const e of this.index?.entries ?? []) {let nodes: CanvasNodeState[] | undefineddiff --git a/src/main/agent-messaging-switch.test.ts b/src/main/agent-messaging-switch.test.tsnew file mode 100644index 000000000..906c0296d--- /dev/null+++ b/src/main/agent-messaging-switch.test.ts@@ -0,0 +1,245 @@+/**+ * PR 6's real work: `messagingEnabled` stops being the fail-closed `() => false` placeholder and+ * becomes the per-project capability GRANT — `projectCapabilityGrantedFor(project,+ * 'agentMessaging')`, which requires BOTH the strict `=== true` flag in the git-shared+ * .nodeterm/project.json AND this machine's recorded 'kept' answer to the clone notice.+ *+ * Every test here drives the REAL control path (`deliverFromControl`) with `messagingEnabled`+ * wired exactly as production wires it (`messagingEnabledVia`); the second half additionally runs+ * a REAL WorkspaceStore over real files, so the store's `capabilityProjectFor` — the one reader+ * the desktop wiring consults — is what decides.+ *+ * THE TRAP THIS FILE EXISTS TO CATCH (PR #213 review, I2): wiring the raw file bit+ * (`projectCapabilityFlagInFile`) instead of the grant. The pending-notice and declined tests+ * below go red on exactly that swap — the flag answers `true` in both, and delivery must refuse.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import {+ deliverFromControl,+ messagingEnabledVia,+ type AgentMessagingDeps+} from './agent-messaging'+import type { CapabilityAckMap } from '../core/project-capability-consent'+import { resetMessageFlow } from '../core/agents/agent-message-flow'+import { resetAgentMessageTraceForTests } from '../core/agents/agent-message-trace'+import { MANAGED_SCRIPT_REVISION } from '../core/agents/hooks/managed-script'+import type { MirrorEntry } from '../core/agent-status-mirror'+import { initPlatform, resetPlatformForTests } from '../core/platform'+import { fakePlatform } from '../core/platform-fake'+import { WorkspaceStore } from '../core/workspace-store'+import type { Project, Workspace } from '../shared/types'++const idle: MirrorEntry = {+ state: 'done',+ updatedAt: 1,+ stateVerified: true,+ clientRevision: MANAGED_SCRIPT_REVISION+}++/** The happy-path service deps from agent-messaging.test.ts, minus `messagingEnabled` and+ * `projects` — each test supplies those two, because they are what this file is about. */+function baseDeps(+ over: Partial<AgentMessagingDeps>+): AgentMessagingDeps & { sent: { nodeId: string; payload: string }[] } {+ const sent: { nodeId: string; payload: string }[] = []+ return {+ sent,+ paneOwner: async () => ({+ tty: '/dev/pts/9',+ panePid: 100,+ paneId: '%1',+ command: 'claude',+ argv: ['claude'],+ pids: [200]+ }),+ sendFramedPayload: async (nodeId, payload) => {+ sent.push({ nodeId, payload })+ return true+ },+ hasLiveSession: () => true,+ mirrorEntry: () => idle,+ projects: () => [+ {+ id: 'p1',+ nodes: [+ { id: 'a1', title: 'Alpha', agentId: 'claude' },+ { id: 'b1', title: 'Beta', agentId: 'claude' }+ ]+ }+ ],+ isRemoteNode: () => false,+ messagingEnabled: () => {+ throw new Error('each test wires messagingEnabled itself')+ },+ customAgents: () => undefined,+ appendBoardLog: async () => false,+ subscribeReceipts: (cb) => {+ const t = setTimeout(() => cb({ nodeId: 'b1', newTurn: true, verified: true }), 5)+ return () => clearTimeout(t)+ },+ now: () => 1_000_000,+ ...over+ }+}++const req = { verb: 'send', sourceNodeId: 'a1', targetNodeId: 'b1', body: 'hello' } as never++beforeEach(() => {+ resetMessageFlow()+ resetAgentMessageTraceForTests()+})++describe('messagingEnabledVia — the grant, never the raw file bit', () => {+ const run = (project: (Partial<Record<'agentMessaging', unknown>> & { capabilityAck?: CapabilityAckMap }) | undefined) =>+ deliverFromControl(+ req,+ baseDeps({ messagingEnabled: messagingEnabledVia(() => project) })+ )++ it('flag true but the clone notice UNANSWERED: refused as switch-off, no pane touched', async () => {+ const deps = baseDeps({ messagingEnabled: messagingEnabledVia(() => ({ agentMessaging: true })) })+ const { outcome, reply } = await deliverFromControl(req, deps)+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ expect(reply.ok).toBe(false)+ expect(deps.sent).toEqual([])+ })++ it('flag true but DECLINED on this machine: still refused — a re-arriving hostile true is not a grant', async () => {+ const { outcome } = await run({ agentMessaging: true, capabilityAck: { agentMessaging: 'declined' } })+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ })++ it('flag true + KEPT: the delivery proceeds all the way to the pane write', async () => {+ const deps = baseDeps({+ messagingEnabled: messagingEnabledVia(() => ({+ agentMessaging: true,+ capabilityAck: { agentMessaging: 'kept' as const }+ }))+ })+ const { outcome, reply } = await deliverFromControl(req, deps)+ expect(outcome.kind).toBe('delivered')+ expect(reply.ok).toBe(true)+ expect(deps.sent).toHaveLength(1)+ expect(deps.sent[0].payload).toContain('hello')+ })++ it('a KEPT ack without the file flag grants nothing — consent alone cannot switch it on', async () => {+ const { outcome } = await run({ capabilityAck: { agentMessaging: 'kept' } })+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ })++ it('an unknown project grants nothing', async () => {+ const { outcome } = await run(undefined)+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ })+})++describe('end to end through a REAL WorkspaceStore — the desktop wiring, minus Electron', () => {+ let userData: string+ let projRoot: string++ const project = (over: Partial<Project> = {}): Project => ({+ id: 'p1',+ name: 'msg',+ color: '#7aa2f7',+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [+ { id: 'a1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 'Alpha', color: '#fff', group: null, agentId: 'claude' },+ { id: 'b1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 'Beta', color: '#fff', group: null, agentId: 'claude' }+ ] as Project['nodes'],+ ...over+ })+ const ws = (p: Project): Workspace => ({ version: 2, activeProjectId: p.id, projects: [p] })++ beforeEach(async () => {+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-msgsw-'))+ projRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-msgsw-proj-'))+ initPlatform(fakePlatform({ userDataDir: userData }))+ })+ afterEach(async () => {+ resetPlatformForTests()+ await fs.rm(userData, { recursive: true, force: true })+ await fs.rm(projRoot, { recursive: true, force: true })+ })++ /** Exactly the desktop's two lines: `projects` off the store, the switch off the store. */+ const storeDeps = (store: WorkspaceStore) =>+ baseDeps({+ projects: () => store.persistedCanvases(),+ messagingEnabled: messagingEnabledVia((id) => store.capabilityProjectFor(id))+ })++ it('flag committed in project.json + KEPT on this machine: delivered', async () => {+ const store = new WorkspaceStore()+ await store.save(+ ws(project({ cwd: projRoot, agentMessaging: true, capabilityAck: { agentMessaging: 'kept' } }))+ )+ // The flag travelled to the git-shared file; the ack did not.+ const raw = await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')+ expect(raw).toContain('"agentMessaging": true')+ expect(raw).not.toContain('capabilityAck')+ const deps = storeDeps(store)+ const { outcome } = await deliverFromControl(req, deps)+ expect(outcome.kind).toBe('delivered')+ expect(deps.sent).toHaveLength(1)+ })++ it('flag committed but the notice never answered: refused as switch-off', async () => {+ const store = new WorkspaceStore()+ await store.save(ws(project({ cwd: projRoot, agentMessaging: true })))+ const deps = storeDeps(store)+ const { outcome } = await deliverFromControl(req, deps)+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ expect(deps.sent).toEqual([])+ })++ it('flag committed but DECLINED on this machine: refused as switch-off', async () => {+ const store = new WorkspaceStore()+ await store.save(+ ws(project({ cwd: projRoot, agentMessaging: true, capabilityAck: { agentMessaging: 'declined' } }))+ )+ const { outcome } = await deliverFromControl(req, storeDeps(store))+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ })++ it('a FORGED file-borne capabilityAck is never read: the repo cannot carry this machine\'s consent', async () => {+ // Save without an ack, then let a hostile repo hand-edit the shared file to claim consent.+ const store = new WorkspaceStore()+ await store.save(ws(project({ cwd: projRoot, agentMessaging: true })))+ const filePath = path.join(projRoot, '.nodeterm/project.json')+ const forged = JSON.parse(await fs.readFile(filePath, 'utf-8'))+ forged.capabilityAck = { agentMessaging: 'kept' }+ await fs.writeFile(filePath, JSON.stringify(forged))+ // A fresh app run loads the forged file; the machine-local entry still holds no answer.+ const fresh = new WorkspaceStore()+ await fresh.load()+ const { outcome } = await deliverFromControl(req, storeDeps(fresh))+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ })++ it('a hand-edited "true" (string) in the file never enables — the strict read holds through the store', async () => {+ const store = new WorkspaceStore()+ await store.save(ws(project({ cwd: projRoot, capabilityAck: { agentMessaging: 'kept' } })))+ const filePath = path.join(projRoot, '.nodeterm/project.json')+ const edited = JSON.parse(await fs.readFile(filePath, 'utf-8'))+ edited.agentMessaging = 'true'+ await fs.writeFile(filePath, JSON.stringify(edited))+ const fresh = new WorkspaceStore()+ await fresh.load()+ const { outcome } = await deliverFromControl(req, storeDeps(fresh))+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })+ })++ it('an INLINE (cwd-less) project grants through its entry too', async () => {+ const store = new WorkspaceStore()+ await store.save(+ ws(project({ agentMessaging: true, capabilityAck: { agentMessaging: 'kept' } }))+ )+ const deps = storeDeps(store)+ const { outcome } = await deliverFromControl(req, deps)+ expect(outcome.kind).toBe('delivered')+ })+})diff --git a/src/main/agent-messaging.ts b/src/main/agent-messaging.tsindex dccde560c..d959cb521 100644--- a/src/main/agent-messaging.ts+++ b/src/main/agent-messaging.ts@@ -41,6 +41,11 @@ import { recordDelivery } from '../core/agents/agent-message-trace'import { resolveDeliveryScope, scopeRefusal } from '../core/agents/agent-message-scope'import { nodeTokenFilePresent } from '../core/agents/node-token-files'import { mirrorEntry as coreMirrorEntry, type MirrorEntry } from '../core/agent-status-mirror'+import {+ projectCapabilityGrantedFor,+ type CapabilityAckMap+} from '../core/project-capability-consent'+import type { ProjectCapability } from '../shared/project-capabilities'/** The little the service needs to know about a stored node. */export interface MessagingStoredNode {@@ -63,9 +68,10 @@ export interface AgentMessagingDeps {isRemoteNode(nodeId: string): boolean/*** The per-project switch (Global Constraint 11): messaging is OFF unless the project opted in.- * PR 6 gives `Project`/`ProjectFileV1` the `agentMessaging` field (validated `=== true` — the- * file is hostile input) and wires this to it; until then the desktop wires `() => false`, so- * the verbs ship fail-closed and every delivery answers `notPermitted (switch-off)`.+ * The desktop wires this through `messagingEnabledVia` below — the capability GRANT+ * (`projectCapabilityGrantedFor`: the strict `=== true` flag in the hostile git-shared+ * project.json AND this machine's recorded 'kept' answer to the clone notice), never the raw+ * file bit. Read per call, so an off-toggle or a decline takes effect on the next delivery.*/messagingEnabled(projectId: string): booleancustomAgents(): readonly { id: string; launchCmd: string }[] | undefined@@ -75,6 +81,29 @@ export interface AgentMessagingDeps {now?(): number}+/**+ * The production `messagingEnabled`: the per-project capability GRANT, one call, nothing else.+ *+ * `projectCapabilityGrantedFor` — NEVER `projectCapabilityFlagInFile` (PR #213 review, I2): the+ * raw file bit answers `true` during the pending-notice window and after a recorded decline,+ * which are exactly the states where a hostile cloned project.json must not buy delivery. The+ * grant requires the strict `=== true` flag AND this machine's 'kept' ack, both derived inside+ * the one predicate. `agent-messaging-switch.test.ts` goes red on the flag-for-grant swap.+ *+ * `getProject` is main's ONE store reader for this purpose (`WorkspaceStore.capabilityProjectFor`+ * on the desktop — the same index scan `persistedCanvases` resolves the delivery scope from);+ * factored as a dep so the suite can drive the identical wiring over a real store.+ */+export function messagingEnabledVia(+ getProject: (+ projectId: string+ ) =>+ | (Partial<Record<ProjectCapability, unknown>> & { capabilityAck?: CapabilityAckMap })+ | undefined+): (projectId: string) => boolean {+ return (projectId) => projectCapabilityGrantedFor(getProject(projectId), 'agentMessaging')+}+// ── The receipt bus ───────────────────────────────────────────────────────────────────────────// One tap on the normalized hook-event stream, fanned to per-delivery receipt watches. Fed by// main/index.ts's `emitAgentStatus` — the same single stream the canvas store and the mobilediff --git a/src/main/index.ts b/src/main/index.tsindex 5dcaa858a..8d49b4b5c 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -15,7 +15,12 @@ import {type BrowserSurfaceKind} from './browser-guest-registry'import { appendBoardLogVia, registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'-import { deliverFromControl, isDeliverRequest, onMessagingAgentEvent } from './agent-messaging'+import {+ deliverFromControl,+ isDeliverRequest,+ messagingEnabledVia,+ onMessagingAgentEvent+} from './agent-messaging'import type { RemoteLogExec } from '../core/board-log'import { boardLogRemotePath } from '../core/board-log'import { PtyManager } from '../core/pty-manager'@@ -925,11 +930,11 @@ app.whenReady().then(async () => {projects: () => workspaceStore.persistedCanvases(),isRemoteNode: (id) => !!ptyManager.sshRemoteForNode(id),// GLOBAL CONSTRAINT 11: every delivery path is gated behind the per-project switch, OFF by- // default. The switch itself (Project/ProjectFileV1 `agentMessaging`, validated `=== true`- // against a hostile project.json, plus the Settings row) is PR 6 — until it lands, nothing- // can turn messaging on, and every delivery answers `notPermitted (switch-off)`. PR 6- // replaces this closure with the validated read; it must not weaken the `=== true` rule.- messagingEnabled: () => false,+ // default. The switch is the `agentMessaging` capability GRANT: the strict `=== true` flag+ // in the hostile git-shared project.json AND this machine's recorded 'kept' answer to the+ // clone notice (projectCapabilityGrantedFor — never the raw file bit). Read per call off+ // the store's index, so a decline or an off-toggle refuses the very next delivery.+ messagingEnabled: messagingEnabledVia((id) => workspaceStore.capabilityProjectFor(id)),customAgents: () => settingsStore.get().customAgents,appendBoardLog: (projectId, entry) => appendBoardLogVia(boardLogRouter, projectId, entry)})