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(board-log): relay guests read and write the host board with their own identity
enescc8e963cca01
diff --git a/src/main/remote/relay-host-service.test.ts b/src/main/remote/relay-host-service.test.tsindex 85f2e15cc..947df8df0 100644--- a/src/main/remote/relay-host-service.test.ts+++ b/src/main/remote/relay-host-service.test.ts@@ -7,6 +7,9 @@// the same fake relay-host.test.ts drives) are faked. The token mint + keypair + Pro gate are// injected via `deps` so the test never touches the network or the OS keyring.import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'const h: {handlers: Record<string, (...a: any[]) => unknown>@@ -61,6 +64,7 @@ import { peerRegistry, unregisterPeerSink, wirePeerRegistry } from '../peer-regiimport { presenceHub } from '../../core/presence/hub'import { initCanvasSync } from '../../core/canvas-sync'import { initPlatform, resetPlatformForTests } from '../../core/platform'+import { registerBoardLogHandlers, type BoardLogRoute } from '../../core/board-log-handlers'import { IPC } from '../../shared/ipc'const decoder = new TextDecoder()@@ -90,6 +94,10 @@ function wireHost(): {peerConfirms: () => void/** The relay drops the socket under the host. */dropSocket: () => void+ /** The peer sends a raw tunnel frame (an RPC req/cast) to the host. */+ peerSendsTunnelText: (json: string) => void+ /** Non-trust tunnel frames the host pushed back to the peer (RPC res + ev). */+ peerFrames: Array<Record<string, unknown>>} {const hostKeys = genKeyPair()const peerKeys = genKeyPair()@@ -135,9 +143,11 @@ function wireHost(): {let peerGate: TrustGate | null = nulllet peerStore: ApprovedDevices = emptyApprovedDevices()+ let peerSocket: ReturnType<typeof connectRelay> | null = null+ const peerFrames: Array<Record<string, unknown>> = []const connectPeer = (): void => {- const peerSocket = connectRelay({+ const sock = connectRelay({url: 'wss://relay.example',token: 'tok-123',role: 'client',@@ -151,14 +161,20 @@ function wireHost(): {onTunnel: (kind, payload) => {if (kind !== 'text') returnconst json = decoder.decode(payload)- peerGate?.onTunnelText(json)+ if (peerGate?.onTunnelText(json)) return // the host's own trust confirm+ try {+ peerFrames.push(JSON.parse(json))+ } catch {+ /* not JSON — ignore */+ }}})+ peerSocket = sockpeerGate = createTrustGate({- peerKeyB64: peerSocket.peerPublicKeyB64()!,+ peerKeyB64: sock.peerPublicKeyB64()!,sessionId: 'peer-side',- sas: () => peerSocket.sas(),- sendConfirm: (json) => peerSocket.sendTunnelText(json),+ sas: () => sock.sas(),+ sendConfirm: (json) => sock.sendTunnelText(json),onOpen: () => {},load: async () => peerStore,save: async (s) => {@@ -173,13 +189,24 @@ function wireHost(): {peerKeyB64: publicKeyToB64(peerKeys.publicKey),connectPeer,peerConfirms: () => peerGate?.confirmHere(),- dropSocket: () => hostOnClose?.()+ dropSocket: () => hostOnClose?.(),+ peerSendsTunnelText: (json) => peerSocket?.sendTunnelText(json),+ peerFrames}}-/** Run `relay:host:start` and return its offer. */-async function start(): Promise<{ offer: string }> {- return (await h.handlers[IPC.relayHostStart]({})) as { offer: string }+/** Run `relay:host:start` (optionally scoped to a project) and return its offer. */+async function start(projectId?: string): Promise<{ offer: string }> {+ return (await h.handlers[IPC.relayHostStart]({}, projectId)) as { offer: string }+}++/** Drive a peer to a fully-open (mutually approved) platform client. */+async function openPeer(host: ReturnType<typeof wireHost>): Promise<void> {+ host.connectPeer()+ const id = pendingSent()!.id+ h.handlers[IPC.relayHostConfirm]({}, { id })+ host.peerConfirms()+ await vi.waitFor(() => expect(peerRegistry().ids().length).toBe(1))}function pendingSent(): { id: string; sas: string | null; peerKeyB64: string } | undefined {@@ -644,3 +671,160 @@ describe('initRelayHost — Team Access start() aliases invite (additive)', () =expect(captured[0].session.close).not.toHaveBeenCalled()})})++// ── Board-log bridged to the host over the relay tunnel ──────────────────────────────────────────+// A relay guest reads and writes the HOST project's board-log through the SAME registry-jailed core+// handlers the host's own renderer uses (registerBoardLogHandlers). The board-log-specific relay+// guards (scope jail + leak-free onChanged refcount) live in connectRelayHost, exercised for REAL+// here — only the electron shell + the relay wire are faked, as everywhere in this file.+describe('initRelayHost — board-log bridged to the host', () => {+ let tmp: string+ let routed: string[]++ const req = (+ host: ReturnType<typeof wireHost>,+ id: number,+ method: string,+ ...args: unknown[]+ ): void => host.peerSendsTunnelText(JSON.stringify({ t: 'req', id, method, args }))+ const cast = (host: ReturnType<typeof wireHost>, method: string, ...args: unknown[]): void =>+ host.peerSendsTunnelText(JSON.stringify({ t: 'cast', method, args }))+ const resFor = (host: ReturnType<typeof wireHost>, id: number): Record<string, unknown> | undefined =>+ host.peerFrames.find((f) => f.t === 'res' && f.id === id)++ beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-boardlog-'))+ // A real project's .nodeterm dir exists on disk (project.json lives there); the store watches it.+ fs.mkdirSync(path.join(tmp, '.nodeterm'), { recursive: true })+ routed = []+ // The host's registry-jailed router: only 'shared' resolves to a real cwd, anything else is+ // unsupported. Records every projectId it is asked to route, to prove an out-of-scope id NEVER+ // reaches dispatch (the relay scope guard short-circuits before the router — and any path — runs).+ registerBoardLogHandlers(platform, {+ route: (projectId: string): BoardLogRoute => {+ routed.push(projectId)+ return projectId === 'shared' ? { kind: 'local', cwd: tmp } : { kind: 'unsupported' }+ }+ })+ })++ afterEach(() => {+ fs.rmSync(tmp, { recursive: true, force: true })+ })++ it('routes append to the shared project’s log, preserving the guest’s own author', async () => {+ const host = wireHost()+ await start('shared')+ await openPeer(host)++ const entry = {+ id: 'e1',+ ts: 1,+ author: { name: 'Ayşe', color: '#ff00ff' }, // the GUEST's presence identity — the feature+ kind: 'comment',+ text: 'hi from the guest'+ }+ req(host, 1, IPC.boardLogAppend, 'shared', entry)+ await vi.waitFor(() => expect(resFor(host, 1)).toMatchObject({ ok: true, result: true }))++ const written = JSON.parse(+ fs.readFileSync(path.join(tmp, '.nodeterm', 'board-log.jsonl'), 'utf-8').trim()+ )+ expect(written.author).toEqual({ name: 'Ayşe', color: '#ff00ff' })+ expect(written.text).toBe('hi from the guest')+ })++ it('read returns the shared project’s entries newest-first', async () => {+ const host = wireHost()+ await start('shared')+ await openPeer(host)++ const mk = (id: string, ts: number): unknown => ({+ id,+ ts,+ author: { name: 'guest', color: '#111111' },+ kind: 'comment',+ text: id+ })+ req(host, 1, IPC.boardLogAppend, 'shared', mk('a', 1))+ await vi.waitFor(() => expect(resFor(host, 1)).toBeTruthy())+ req(host, 2, IPC.boardLogAppend, 'shared', mk('b', 2))+ await vi.waitFor(() => expect(resFor(host, 2)).toBeTruthy())++ req(host, 3, IPC.boardLogRead, 'shared')+ await vi.waitFor(() => expect(resFor(host, 3)).toBeTruthy())+ const result = resFor(host, 3)!.result as { entries: Array<{ id: string }> }+ expect(result.entries.map((e) => e.id)).toEqual(['b', 'a']) // newest-first (disk is oldest-first)+ })++ it('refuses an out-of-scope projectId (read unsupported, append false) without resolving a path', async () => {+ const host = wireHost()+ await start('shared')+ await openPeer(host)+ routed.length = 0 // ignore the open-time routing; focus on the out-of-scope calls below++ req(host, 1, IPC.boardLogRead, 'other-project')+ await vi.waitFor(() => expect(resFor(host, 1)).toBeTruthy())+ expect(resFor(host, 1)!.result).toEqual({ entries: [], unsupported: true })++ req(host, 2, IPC.boardLogAppend, 'other-project', {+ id: 'x',+ ts: 1,+ author: { name: 'guest', color: '#111111' },+ kind: 'comment',+ text: 'nope'+ })+ await vi.waitFor(() => expect(resFor(host, 2)).toBeTruthy())+ expect(resFor(host, 2)!.result).toBe(false)++ // The scope guard short-circuits BEFORE dispatch, so the host router is never even asked about an+ // out-of-scope project — no filesystem path is ever resolved from a client-supplied id.+ expect(routed).not.toContain('other-project')+ })++ it('a host-side change pushes boardLogChanged to the subscribed peer, and a socket drop releases the watch', async () => {+ // A spy alongside the real board-log handler on the unsubscribe channel: proves the balancing+ // unsubscribe is replayed on drop (the shared per-project watch refcount is released — no leak).+ const unsubSpy = vi.fn()+ platform.on(IPC.boardLogUnsubscribe, unsubSpy)++ const host = wireHost()+ await start('shared')+ await openPeer(host)++ cast(host, IPC.boardLogSubscribe, 'shared')+ await new Promise((r) => setTimeout(r, 50)) // let the subscribe cast arm the fs.watch++ // A real append changes the file; the store's watch (debounced 250ms) broadcasts the change,+ // which fans out to the peer sink over the tunnel as a boardLogChanged event.+ fs.appendFileSync(+ path.join(tmp, '.nodeterm', 'board-log.jsonl'),+ JSON.stringify({ id: 'z', ts: 9, author: { name: 'guest', color: '#111111' }, kind: 'comment', text: 'ping' }) ++ '\n'+ )+ await vi.waitFor(+ () =>+ expect(+ host.peerFrames.some((f) => f.t === 'ev' && f.channel === IPC.boardLogChanged('shared'))+ ).toBe(true),+ { timeout: 3000 }+ )++ // The socket drops with no client-sent unsubscribe (a closed guest tab). The host must replay the+ // balancing unsubscribe so the per-project watch is not leaked.+ host.dropSocket()+ expect(unsubSpy).toHaveBeenCalledWith('shared')+ })++ it('an out-of-scope subscribe never reaches the core watch', async () => {+ const subSpy = vi.fn()+ platform.on(IPC.boardLogSubscribe, subSpy)+ const host = wireHost()+ await start('shared')+ await openPeer(host)++ cast(host, IPC.boardLogSubscribe, 'other-project')+ await new Promise((r) => setTimeout(r, 20))+ expect(subSpy).not.toHaveBeenCalled() // scope-jailed before it could arm a watch+ })+})diff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.tsindex 8be718853..9c8b868b8 100644--- a/src/main/remote/relay-host.ts+++ b/src/main/remote/relay-host.ts@@ -91,11 +91,25 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio// True once we have detected a key swap and cut the session, so we don't do it twice.let keySwapped = false+ // Board-log onChanged over the relay rides the core's per-project watch refcount+ // (registerBoardLogHandlers): the guest casts board-log:subscribe / :unsubscribe, which start/stop+ // the host watch. But a guest whose tab closes or whose socket drops sends no balancing unsubscribe,+ // so we track THIS connection's net per-project subscribe count and replay the unsubscribes on+ // teardown (see detach) — the host watch is released, and the shared local refcount is never touched+ // below this connection's own contribution (an unbalanced guest unsubscribe is ignored).+ const boardLogSubs = new Map<string, number>()+/** The ONE teardown, mirroring src/server/ws.ts's close path exactly: `unregisterPeerSink` IS the* three steps (presenceHub.leave → onPeerGone → PtyManager.dropClient → registry prune). Do NOT* re-implement them here, and do NOT call `wirePeerRegistry` — it is wired once at boot. */const detach = (): void => {if (clientId === null) return+ // Release any board-log watches this connection still holds — a dropped guest tab never sends the+ // balancing unsubscribe, so replay one per outstanding count before the client id is gone.+ for (const [projectId, count] of boardLogSubs) {+ for (let i = 0; i < count; i++) opts.platform.cast(clientId, IPC.boardLogUnsubscribe, [projectId])+ }+ boardLogSubs.clear()unregisterPeerSink(clientId)clientId = null}@@ -167,6 +181,21 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessioreturn { ...res, result: scopeWorkspaceToProject(res.result as Workspace, opts.sharedProjectId) }}+ /** SCOPE jail for the board log (beyond the host registry's own projectId jail): a session bound to+ * one project must never let the guest reach ANOTHER project's board log. A board-log method naming+ * a different projectId is out of scope. Unscoped sessions pass through — the registry is the only+ * gate then, exactly as for the host's own renderer. The guest can never supply a filesystem path;+ * only a projectId the host resolves through its own router. */+ const boardLogOutOfScope = (projectId: unknown): boolean =>+ !!opts.sharedProjectId && projectId !== opts.sharedProjectId++ /** The degraded response for an out-of-scope board-log request — the SAME shape the router gives an+ * unknown project, produced WITHOUT dispatching (never resolving a path). Never throws. */+ const boardLogRefusal = (method: string, id: number): RpcOk =>+ method === IPC.boardLogRead+ ? { t: 'res', id, ok: true, result: { entries: [], unsupported: true } }+ : { t: 'res', id, ok: true, result: false }+const socket = connectRelay({url: opts.url,token: opts.token,@@ -220,11 +249,34 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessioreturn}if (m.t === 'req') {+ // Board-log read/append naming a project outside this session's scope: refuse WITHOUT+ // dispatching (the host router never resolves it), degrading exactly as an unknown project.+ if (+ (m.method === IPC.boardLogAppend || m.method === IPC.boardLogRead) &&+ boardLogOutOfScope(m.args[0])+ ) {+ socket.sendTunnelText(JSON.stringify(boardLogRefusal(m.method, m.id)))+ return+ }const id = clientIdvoid opts.platform.dispatch(id, m).then((res) => socket.sendTunnelText(JSON.stringify(scopeResponse(m.method, res))))} else if (m.t === 'cast') {+ // Board-log subscribe/unsubscribe: scope-jail out-of-scope projects, and track this+ // connection's net per-project count so a dropped guest's watch is released in detach().+ if (m.method === IPC.boardLogSubscribe || m.method === IPC.boardLogUnsubscribe) {+ const projectId = m.args[0]+ if (typeof projectId !== 'string' || boardLogOutOfScope(projectId)) return+ if (m.method === IPC.boardLogSubscribe) {+ boardLogSubs.set(projectId, (boardLogSubs.get(projectId) ?? 0) + 1)+ } else {+ const cur = boardLogSubs.get(projectId) ?? 0+ if (cur <= 0) return // this connection holds no such watch — never decrement the shared count+ if (cur === 1) boardLogSubs.delete(projectId)+ else boardLogSubs.set(projectId, cur - 1)+ }+ }opts.platform.cast(clientId, m.method, m.args)}// res/ev from a peer are ignored (mirrors src/server/ws.ts).diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex e97e2cbf0..188329668 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -100,6 +100,19 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):onData: (sessionId, listener) => local.pty.onData(sessionId, listener)},+ // boardLog is CORE-BOUND: a relay guest reads and writes the HOST project's board comments/activity+ // (with its OWN presence identity in each entry), routed to the host's registry-jailed board-log+ // handlers (and scope-jailed to the shared project host-side in connectRelayHost). Version-skew+ // degrade: an OLDER host with no board-log rpc answers E_NO_HANDLER, which we map to today's+ // behavior — read → `{ entries: [], unsupported: true }`, append → `false` — instead of a rejection.+ // `onChanged` casts subscribe/unsubscribe (fire-and-forget, no reject) and rides the host push.+ boardLog: {+ append: (projectId, entry) => files.boardLog.append(projectId, entry).catch(() => false),+ read: (projectId, opts) =>+ files.boardLog.read(projectId, opts).catch(() => ({ entries: [], unsupported: true })),+ onChanged: (projectId, cb) => files.boardLog.onChanged(projectId, cb)+ },+// `settings` stays LOCAL (font/cursor/theme render in YOUR window). It came in via `...local`;// `real.settings` is deliberately left unused so a remote tab never adopts the host's prefs.@@ -124,8 +137,9 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):// silent no-op): ──// The SDK chat node has no relay chat builder yet (the Server Edition defers it too). Routing to// the local chat driver would run it on the WRONG machine (a host cwd that does not exist- // locally), so refuse with E_UNSUPPORTED instead. contextLink / transcripts / handoff / boardLog- // stay LOCAL by way of `...local` (a v1 degrade: they read/write on this machine, not the host).+ // locally), so refuse with E_UNSUPPORTED instead. contextLink / transcripts / handoff stay LOCAL+ // by way of `...local` (a v1 degrade: they read/write on this machine, not the host). boardLog is+ // now bridged to the host (see above) — it no longer rides `...local`.chat: stub.chat,// Agent canvas-control (`agent:control`) is not wired over the relay (matches the Server// Edition); inert no-ops rather than a local subscription that never carries the host's events.