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(hosted-team): a node id held by several projects is shared only if all are (M4)
reviewb3208682656b
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.mdindex 7fdb20b91..fbeef32fb 100644--- a/docs/hosted-team-relay.md+++ b/docs/hosted-team-relay.md@@ -210,6 +210,10 @@ session key** in the team store.| `agent:subagent-snapshot` | The response is trimmed to shared nodes. || `board-log:read/subscribe/unsubscribe` (+ `append` for Commenters) | Shared projects only. A Commenter's `append` must be a comment (`kind: 'comment'`): an activity entry ("moved a card to Done") is Editor-only. |+**Which project a node is in** is read from the saved canvases (`WorkspaceStore.projectIdsForNode`).+Node ids travel in git-shared project files, so one id can sit in several projects; it counts as+shared only when **every** project holding it is shared, never by whichever comes first.+**Outbound is deny-by-default too.** The core broadcasts to every attached client, so a non-editorreceives only the events `VIEW_EVENTS` lists: `canvas:mut`, `workspace:external-change` /`server-change` and `project-trust:changed` for shared projects; `agent:status` anddiff --git a/src/core/relay/access-policy.test.ts b/src/core/relay/access-policy.test.tsindex 1cd664c47..9fde761e5 100644--- a/src/core/relay/access-policy.test.ts+++ b/src/core/relay/access-policy.test.ts@@ -16,7 +16,7 @@ import type { UiSink } from '../ui-sink-registry'const ctx = (role: AccessContext['role']): AccessContext => ({role,sharedProjects: new Set(['P']),- projectOfNode: (id) => (id === 'n1' ? 'P' : id === 'n2' ? 'Q' : undefined),+ projectsOfNode: (id) => (id === 'n1' ? ['P'] : id === 'n2' ? ['Q'] : []),// Terminal sessions: 's' / 's1' run node n1 (project P, shared), 's2' runs n2 (project Q, not).nodeOfSession: (sid) => (sid === 's' || sid === 's1' ? 'n1' : sid === 's2' ? 'n2' : undefined),projectCwds: () => ['/srv/app'],@@ -113,7 +113,7 @@ describe('access policy: the fs jail', () => {const c: AccessContext = {role: 'viewer',sharedProjects: new Set(['P']),- projectOfNode: () => undefined,+ projectsOfNode: () => [],nodeOfSession: () => undefined,projectCwds: () => [path.join(root, 'link')],realpath: (p) => {@@ -506,7 +506,7 @@ describe('access policy: git needs a shared root that is its own repository (C1)const onDisk = (root: string): AccessContext => ({role: 'viewer',sharedProjects: new Set(['P']),- projectOfNode: () => undefined,+ projectsOfNode: () => [],nodeOfSession: () => undefined,projectCwds: () => [root],realpath: (p) => {@@ -606,3 +606,44 @@ describe('access policy: a terminal stops streaming to a non-editor once its pro}})})++// M4. Node ids travel in git-shared project files, so one id can sit in a shared project AND an+// unshared one. Resolving it to "the first project that has it" made the verdict depend on index+// order. It is shared only when EVERY project holding it is shared.+describe('access policy: a node id held by more than one project (M4)', () => {+ const holders = (map: Record<string, string[]>) => (id: string) => map[id] ?? []+ const dup = (role: AccessContext['role'], shared: string[]): AccessContext => ({+ ...ctx(role),+ sharedProjects: new Set(shared),+ projectsOfNode: holders({ both: ['P', 'Q'], twoShared: ['P', 'P2'], solo: ['P'] }),+ nodeOfSession: (sid) => (sid === 'sBoth' ? 'both' : undefined)+ })+ const status = (nodeId: string) => JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId }] })++ it('an id in a shared and an unshared project is NOT shared, whichever comes first', () => {+ for (const order of [['P', 'Q'], ['Q', 'P']]) {+ const c: AccessContext = { ...dup('viewer', ['P']), projectsOfNode: (id) => (id === 'both' ? order : []) }+ expect(decideAccess('req', IPC.ptyCreate, [{ persistKey: 'both' }], c).allow, order.join()).toBe(false)+ expect(decideAccess('req', IPC.ptyCapture, ['both'], c).allow, order.join()).toBe(false)+ expect(filterOutboundEvent(status('both'), c), order.join()).toBe(false)+ }+ })++ it('an id every one of whose projects is shared is shared; an unknown id is not', () => {+ const c = dup('viewer', ['P', 'P2'])+ expect(decideAccess('req', IPC.ptyCapture, ['twoShared'], c).allow).toBe(true)+ expect(decideAccess('req', IPC.ptyCapture, ['solo'], c).allow).toBe(true)+ expect(decideAccess('req', IPC.ptyCapture, ['nobody'], c).allow).toBe(false)+ })++ it('a terminal session of an ambiguous node does not stream to a viewer', () => {+ const bin: Uint8Array[] = []+ const w = wrapSinkForRole({ sendText: () => {}, sendBinary: (b) => bin.push(b), bufferedAmount: () => 0 }, () => dup('viewer', ['P']))+ w.sendBinary(encodePtyData('sBoth', 'x'))+ expect(bin).toEqual([])+ })++ it('editors are unaffected', () => {+ expect(decideAccess('req', IPC.ptyCapture, ['both'], dup('editor', ['P'])).allow).toBe(true)+ })+})diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsindex bfbea6b16..a01fdef41 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -26,8 +26,9 @@ import type { UiSink } from '../ui-sink-registry'export interface AccessContext {role: TeamRolesharedProjects: ReadonlySet<string>- /** The project a node belongs to, from the persisted canvases. */- projectOfNode(nodeId: string): string | undefined+ /** EVERY project that holds this node id, from the persisted canvases ([] = none). Node ids travel+ * in git-shared project files, so one id can sit in several projects; see `sharedNode`. */+ projectsOfNode(nodeId: string): readonly string[]/** The node (canvas node id) a live terminal session runs, from the pty manager; undefined when* the session is unknown (never existed, or already ended). */nodeOfSession(sessionId: string): string | undefined@@ -47,10 +48,13 @@ const isEditor = (role: unknown): boolean => role === 'owner' || role === 'editoconst sharedProject = (id: unknown, ctx: AccessContext): boolean =>typeof id === 'string' && ctx.sharedProjects.has(id)+/** A node is shared only when EVERY project holding its id is shared (M4). Answering from the first+ * project that has it would make the verdict depend on index order: an id copied into an unshared+ * project (a git-shared file, a clone) would be readable whenever the shared copy came first. */const sharedNode = (id: unknown, ctx: AccessContext): boolean => {if (typeof id !== 'string') return false- const project = ctx.projectOfNode(id)- return project !== undefined && ctx.sharedProjects.has(project)+ const projects = ctx.projectsOfNode(id)+ return projects.length > 0 && projects.every((p) => ctx.sharedProjects.has(p))}/** One property of an object payload (our own fixed key names only), else undefined. */@@ -439,7 +443,7 @@ export const VIEW_EVENTS: Readonly<Record<string, EventCheck>> = Object.freeze({})/**- * Is this terminal session's node (still) in a shared project? `undefined` = the session is not+ * Is this terminal session's node (still) shared (`sharedNode`)? `undefined` = the session is not* known to the pty manager (never existed, or already ended). A viewer subscribes to a session only* through the jailed pty:create above, but `team unshare` does not end that subscription (R45), so* every frame of it is judged again here.diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.tsindex 045346764..f55e4753f 100644--- a/src/core/relay/hosted-service.test.ts+++ b/src/core/relay/hosted-service.test.ts@@ -58,7 +58,7 @@ afterEach(() => {}})-type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectOfNode' | 'nodeOfSession' | 'killPeer'>> & {+type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectsOfNode' | 'nodeOfSession' | 'killPeer'>> & {recordTimers?: booleandataDir?: string}@@ -96,7 +96,7 @@ function world(opts: WorldOpts = {}) {const svc = createHostedService({dataDir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'host-dev', hostLabel: 'box',attach,- projectOfNode: opts.projectOfNode ?? ((id) => (id === 'n-other' ? 'Q' : 'P')),+ projectsOfNode: opts.projectsOfNode ?? ((id) => (id === 'n-other' ? ['Q'] : ['P'])),// Terminal sessions: 'sess-shared' runs n-shared (project P), 'sess-other' runs n-other (Q).nodeOfSession: opts.nodeOfSession ?? ((sid) => (sid === 'sess-shared' ? 'n-shared' : sid === 'sess-other' ? 'n-other' : undefined)),projectCwd: () => '/srv/app',@@ -783,7 +783,7 @@ describe('hosted service — removal', () => {const again = createHostedService({dataDir: w.dataDir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'd', hostLabel: 'x',attach: { attach: () => 1, detach: () => {}, dispatch: async (_i, r) => ({ t: 'res', id: r.id, ok: true, result: null }), cast: () => {} },- projectOfNode: () => undefined, nodeOfSession: () => undefined, projectCwd: () => undefined+ projectsOfNode: () => [], nodeOfSession: () => undefined, projectCwd: () => undefined})expect(await again.remove(pub(keys), false)).toBe('removed')})diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.tsindex e58c4e351..182bb9037 100644--- a/src/core/relay/hosted-service.ts+++ b/src/core/relay/hosted-service.ts@@ -76,7 +76,8 @@ export interface HostedServiceDeps {deviceId: stringhostLabel: stringattach: PeerAttach- projectOfNode(nodeId: string): string | undefined+ /** Every project holding this node id (`WorkspaceStore.projectIdsForNode`); [] = none. */+ projectsOfNode(nodeId: string): readonly string[]/** The node a live terminal session runs (`PtyManager.nodeOfSession`). A viewer's terminal frames* are judged by it, so `team unshare` stops a stream the viewer already joined (R45). */nodeOfSession(sessionId: string): string | undefined@@ -220,7 +221,7 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {return {role,sharedProjects: shared,- projectOfNode: (nodeId) => deps.projectOfNode(nodeId),+ projectsOfNode: (nodeId) => deps.projectsOfNode(nodeId),nodeOfSession: (sessionId) => deps.nodeOfSession(sessionId),projectCwds: () =>[...shared].map((p) => deps.projectCwd(p)).filter((cwd): cwd is string => typeof cwd === 'string' && cwd.length > 0),diff --git a/src/core/workspace-store.node-project.test.ts b/src/core/workspace-store.node-project.test.tsindex f968246b8..d22cdb7c2 100644--- a/src/core/workspace-store.node-project.test.ts+++ b/src/core/workspace-store.node-project.test.ts@@ -1,4 +1,4 @@-// `projectIdForNode` is asked once per access decision for every hosted-team viewer (every+// `projectIdsForNode` is asked once per access decision for every hosted-team viewer (every// agent:status event, every subagent-activity chunk, every unread-clear, every snapshot element).// `persistedCanvases()` re-parses every local project's cached project.json on each call, so the// answer is memoized — and the memo must never serve a stale answer after ANY writer changed a@@ -53,15 +53,15 @@ function parses(fn: () => void): number {}}-describe('WorkspaceStore.projectIdForNode', () => {+describe('WorkspaceStore.projectIdsForNode', () => {it('answers exactly what a persistedCanvases scan answers', async () => {const [a, b] = [await newRoot(), await newRoot()]const store = new WorkspaceStore()await store.save(ws([project('pa', a, ['n1', 'n2']), project('pb', b, ['n3']), project('inline', undefined, ['n4'])]))- const scan = (id: string): string | undefined => store.persistedCanvases().find((c) => c.nodes.some((n) => n.id === id))?.id- for (const id of ['n1', 'n2', 'n3', 'n4', 'nope']) expect(store.projectIdForNode(id)).toBe(scan(id))- expect(store.projectIdForNode('n3')).toBe('pb')- expect(store.projectIdForNode('nope')).toBeUndefined()+ const scan = (id: string): string[] => store.persistedCanvases().filter((c) => c.nodes.some((n) => n.id === id)).map((c) => c.id)+ for (const id of ['n1', 'n2', 'n3', 'n4', 'nope']) expect(store.projectIdsForNode(id)).toEqual(scan(id))+ expect(store.projectIdsForNode('n3')).toEqual(['pb'])+ expect(store.projectIdsForNode('nope')).toEqual([])})it('parses each project file at most once for any number of lookups', async () => {@@ -69,42 +69,42 @@ describe('WorkspaceStore.projectIdForNode', () => {const store = new WorkspaceStore()await store.save(ws(dirs.map((d, i) => project(`p${i}`, d, Array.from({ length: 50 }, (_, j) => `p${i}-n${j}`)))))const n = parses(() => {- for (let k = 0; k < 1000; k++) store.projectIdForNode(`p${k % 5}-n${k % 50}`)+ for (let k = 0; k < 1000; k++) store.projectIdsForNode(`p${k % 5}-n${k % 50}`)})// One rebuild after the save (one parse per local project), then pure map lookups.expect(n).toBeLessThanOrEqual(5)// And a further burst with nothing changed parses nothing at all.- expect(parses(() => { for (let k = 0; k < 1000; k++) store.projectIdForNode('p1-n1') })).toBe(0)+ expect(parses(() => { for (let k = 0; k < 1000; k++) store.projectIdsForNode('p1-n1') })).toBe(0)})it('a save that adds a node or moves one to another project is seen at once', async () => {const [a, b] = [await newRoot(), await newRoot()]const store = new WorkspaceStore()await store.save(ws([project('pa', a, ['n1']), project('pb', b, ['n2'])]))- expect(store.projectIdForNode('n1')).toBe('pa')- expect(store.projectIdForNode('n9')).toBeUndefined()+ expect(store.projectIdsForNode('n1')).toEqual(['pa'])+ expect(store.projectIdsForNode('n9')).toEqual([])await store.save(ws([project('pa', a, ['n9']), project('pb', b, ['n2', 'n1'])]))- expect(store.projectIdForNode('n9')).toBe('pa')- expect(store.projectIdForNode('n1')).toBe('pb')+ expect(store.projectIdsForNode('n9')).toEqual(['pa'])+ expect(store.projectIdsForNode('n1')).toEqual(['pb'])// Into and out of an inline (cwd-less) project, whose nodes live in the index entry itself.await store.save(ws([project('pa', a, ['n9']), project('pb', b, ['n2']), project('inline', undefined, ['n1'])]))- expect(store.projectIdForNode('n1')).toBe('inline')+ expect(store.projectIdsForNode('n1')).toEqual(['inline'])})it('a write that bypasses save() (a phone-registered node) is seen at once', async () => {const a = await newRoot()const store = new WorkspaceStore()await store.save(ws([project('pa', a, ['n1'])]))- expect(store.projectIdForNode('term-abc123-phone1')).toBeUndefined()+ expect(store.projectIdsForNode('term-abc123-phone1')).toEqual([])expect(await store.appendRemoteNode('pa', { id: 'term-abc123-phone1', title: 'from the phone' })).toBe(true)- expect(store.projectIdForNode('term-abc123-phone1')).toBe('pa')+ expect(store.projectIdsForNode('term-abc123-phone1')).toEqual(['pa'])})it('an outside edit picked up by load() (git pull, hand edit) is seen at once', async () => {const [a, b] = [await newRoot(), await newRoot()]const store = new WorkspaceStore()await store.save(ws([project('pa', a, ['n1']), project('pb', b, ['n2'])]))- expect(store.projectIdForNode('n1')).toBe('pa')+ expect(store.projectIdsForNode('n1')).toEqual(['pa'])// Move n1 from pa's file to pb's file behind the store's back, then reload.const fa = path.join(a, '.nodeterm', 'project.json')const fb = path.join(b, '.nodeterm', 'project.json')@@ -117,6 +117,17 @@ describe('WorkspaceStore.projectIdForNode', () => {await fs.writeFile(fa, JSON.stringify(ja, null, 2))await fs.writeFile(fb, JSON.stringify(jb, null, 2))await store.load()- expect(store.projectIdForNode('n1')).toBe('pb')+ expect(store.projectIdsForNode('n1')).toEqual(['pb'])+ })+})++describe('WorkspaceStore.projectIdsForNode — an id in more than one project (M4)', () => {+ it('answers EVERY project holding the id, in index order, never just the first', async () => {+ // Node ids travel in git-shared project files, so the same id can sit in two projects.+ const [a, b] = [await newRoot(), await newRoot()]+ const store = new WorkspaceStore()+ await store.save(ws([project('pa', a, ['dup', 'n1']), project('pb', b, ['dup']), project('inline', undefined, ['dup'])]))+ expect(store.projectIdsForNode('dup')).toEqual(['pa', 'pb', 'inline'])+ expect(store.projectIdsForNode('n1')).toEqual(['pa'])})})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 167064e9b..ab2736dc3 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -64,6 +64,9 @@ const inlineFilePath = (projectId: string): string =>* small enough that a server-side revert to genuinely old content still reads as external. */const RECENT_MIRROR_CAP = 8+/** `projectIdsForNode`'s answer for an id no project holds (shared, frozen: callers only read it). */+const NO_PROJECTS: readonly string[] = Object.freeze([])+const contentHash = (content: string): string => createHash('sha256').update(content).digest('hex')/** Alias of the shared `ProjectSettingsSnapshot` (moved to `shared/project-settings.ts` so the@@ -134,8 +137,8 @@ export class WorkspaceStore {* its last write on EVERY autosave; re-parsing each file each time was pure waste. Keyed by the* raw string, so any `lastWritten.set` elsewhere invalidates it by construction. */private lastWrittenParsed = new Map<string, { raw: string; parsed: ProjectFileV1 }>()- /** `projectIdForNode`'s node → project map, and the `canvasInputs` snapshot it was built from. */- private nodeProjectMemo: { inputs: unknown[]; map: Map<string, string> } | null = null+ /** `projectIdsForNode`'s node → projects map, and the `canvasInputs` snapshot it was built from. */+ private nodeProjectMemo: { inputs: unknown[]; map: Map<string, readonly string[]> } | null = null/** The index bytes we last wrote and the file's size/mtime/inode right after, so an unchanged* index is not rewritten on every autosave — but one another writer changed on disk still is.* The inode is what catches a same-size rewrite on a coarse-mtime filesystem: every writer@@ -1508,9 +1511,12 @@ export class WorkspaceStore {}/**- * The project a node belongs to — the first project that has it, exactly as a `persistedCanvases`- * scan answers. Memoized, because a hosted-team relay asks it once per access decision for every- * viewer (each agent:status event, subagent-activity chunk, unread-clear, snapshot element) and a+ * EVERY project that holds this node id, in index order ([] = none) — exactly what a+ * `persistedCanvases` scan answers. All of them, never the first: node ids travel in git-shared+ * project files, so one id can sit in two projects, and the hosted team's access policy treats a+ * node as shared only when every project holding it is shared. Memoized, because a hosted-team+ * relay asks it once per access decision for every viewer (each agent:status event,+ * subagent-activity chunk, unread-clear, snapshot element, terminal frame) and a* `persistedCanvases()` call re-parses every local project's cached file.** The memo is validated against the IDENTITY of every input `persistedCanvases` reads@@ -1521,18 +1527,23 @@ export class WorkspaceStore {* including writers added later. It rests on one rule this file already keeps: a project's node* array is replaced, never mutated in place.*/- projectIdForNode(nodeId: string): string | undefined {+ projectIdsForNode(nodeId: string): readonly string[] {const inputs = this.canvasInputs()const memo = this.nodeProjectMemoconst fresh =memo !== null && memo.inputs.length === inputs.length && memo.inputs.every((v, i) => v === inputs[i])- if (fresh) return memo.map.get(nodeId)- const map = new Map<string, string>()+ if (fresh) return memo.map.get(nodeId) ?? NO_PROJECTS+ const map = new Map<string, string[]>()for (const c of this.persistedCanvases()) {- for (const n of c.nodes) if (!map.has(n.id)) map.set(n.id, c.id)+ for (const n of c.nodes) {+ const held = map.get(n.id)+ if (!held) map.set(n.id, [c.id])+ else if (!held.includes(c.id)) held.push(c.id)+ }}+ for (const held of map.values()) Object.freeze(held)this.nodeProjectMemo = { inputs, map }- return map.get(nodeId)+ return map.get(nodeId) ?? NO_PROJECTS}/** Every input `persistedCanvases` reads, by identity: the index object, and per entry the entry,diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsindex 549d7feed..91b5ae835 100644--- a/src/main/remote/hosted-join.test.ts+++ b/src/main/remote/hosted-join.test.ts@@ -671,7 +671,7 @@ function hostedWorld() {}const svc = createHostedService({dataDir: dir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'host-dev', hostLabel: 'box',- attach, projectOfNode: () => 'P', nodeOfSession: () => undefined, projectCwd: () => '/srv/app',+ attach, projectsOfNode: () => ['P'], nodeOfSession: () => undefined, projectCwd: () => '/srv/app',fetch: (async () => new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 })) as typeof fetch,transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT }})diff --git a/src/server/hosted-boot.test.ts b/src/server/hosted-boot.test.tsindex 25556f2bd..6f28816e2 100644--- a/src/server/hosted-boot.test.ts+++ b/src/server/hosted-boot.test.ts@@ -43,8 +43,8 @@ describe('hosted team boot wiring (source)', () => {expect(main).not.toMatch(/argv\[0\] === 'team'/)})- it('projectOfNode uses the store\'s memoized lookup, not a persistedCanvases scan per call', () => {- expect(src).toMatch(/projectOfNode: \(nodeId\) => workspaceStore\.projectIdForNode\(nodeId\)/)+ it('projectsOfNode uses the store\'s memoized lookup, not a persistedCanvases scan per call', () => {+ expect(src).toMatch(/projectsOfNode: \(nodeId\) => workspaceStore\.projectIdsForNode\(nodeId\)/)})it('boots after the workspace index is loaded (the access policy reads it)', () => {diff --git a/src/server/index.ts b/src/server/index.tsindex 2675f761b..d9567d353 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -882,7 +882,7 @@ export async function startServer(// Memoized in the store: asked once per access decision for every viewer, and a// persistedCanvases() scan re-parses every local project's file (measured 4.5 ms per call at// 20 projects x 100 nodes).- projectOfNode: (nodeId) => workspaceStore.projectIdForNode(nodeId),+ projectsOfNode: (nodeId) => workspaceStore.projectIdsForNode(nodeId),// A viewer's terminal frames are judged by the session's node, per frame (`team unshare` must// stop a stream the viewer already joined). One map lookup.nodeOfSession: (sessionId) => ptyManager.nodeOfSession(sessionId),