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(relay): Canvas canvas-sync publisher + onMutation follow the active session (collab Task 4)

enesdc618997dffc
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 32ea4ec41..939dad3e7 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -83,7 +83,6 @@ import { UsageIndicator } from '../components/UsageIndicator'
import { PresenceLayer } from '../components/PresenceLayer'
import { Facepile } from '../components/Facepile'
import { PresenceNamePrompt } from '../components/PresenceNamePrompt'
-import { usePresence } from '../state/presence'
import { nodeTravel, projectTravel } from '../lib/presenceTravel'
import { RemoteAccessDialog } from '../components/RemoteAccessDialog'
import { SshProjectDialog } from '../components/SshProjectDialog'
@@ -170,6 +169,7 @@ import {
} from '@shared/canvas-publish'
import { createCanvasOrder, createReconnectWatch, type CanvasOrder } from '@shared/canvas-order'
import { createMutationGuard } from '@shared/canvas-mutations'
+import { canvasSyncTarget } from './collab-sync'
import {
applyCanvasMutation,
applyMutationToFlow,
@@ -610,6 +610,19 @@ export function Canvas() {
useReactFlow()
const activeProjectId = useProjects((s) => s.activeProjectId)
+ // The ACTIVE session + its presence — what the canvas-sync publisher and onMutation subscriber
+ // must follow (Task 4). `sessionForProject` / `presenceForProject` are plain, allocation-free
+ // resolves of the memoized (per-core) session/presence — NOT reactive subscriptions to the peer
+ // table — so these are STABLE references per session (a relay tab → the relay core; a local tab →
+ // `window.nodeTerminal` / `defaultPresence`, byte-identical to today) and the sync effects below
+ // re-key on `activeSession.api` (the api OBJECT, stable per core): local→local tab switches keep
+ // the SAME api → the effects do NOT re-run → the per-node `order`/reconnect state survives the
+ // switch (the documented invariant); a local↔relay switch changes the api → they re-bind on the
+ // new core. Deliberately NOT keyed on `activeProjectId` — that would reset `order` on every local
+ // tab switch. Reading presence imperatively via `.store.getState()`/`.subscribe` (never a reactive
+ // `usePresence(sel)` hook) is the PERF CONTRACT: a peer's 20 Hz cursor never re-renders Canvas.
+ const activeSession = sessionForProject(activeProjectId || '')
+ const activePresence = presenceForProject(activeProjectId || '')
// "Has projects" = at least one OPEN (non-closed) tab. With only closed projects left, the
// welcome screen shows (and lists them under "Recently closed" for reopening).
const hasProjects = useProjects((s) => s.projects.some((p) => !p.closed))
@@ -1291,14 +1304,23 @@ export function Canvas() {
// everyone else's canvas. There is nothing to forget at the first hello — an empty `seen` map
// cannot be stale. (Nor on a project switch: this Canvas keeps applying mutations for
// loaded-but-inactive projects, so their order state has to survive a tab switch.)
- const reconnected = createReconnectWatch(usePresence.getState().myId)
+ // Gate + reconnect are read off the ACTIVE session's presence store, imperatively (never a
+ // reactive `usePresence(sel)` hook — the PERF CONTRACT), so a relay tab counts the RELAY core's
+ // peers instead of the always-empty local table (the bug: `hasPeers` was false → nothing cast).
+ // Peer reality is PER SESSION: this effect now re-binds when the active core changes, so the
+ // accumulated gate must start clean on each (re-)bind — otherwise a relay tab's `hasPeers=true`
+ // would LEAK onto a subsequent solo local tab and make it cast to its own local core. `readPresence`
+ // below re-derives it immediately from THIS session's presence. (No-op on a local→local switch:
+ // the api is unchanged, so the effect does not re-run and the gate — like `order` — survives.)
+ hasPeersRef.current = false
+ const reconnected = createReconnectWatch(activePresence.store.getState().myId)
const readPresence = (): void => {
hasPeersRef.current =
- hasPeersRef.current || Object.keys(usePresence.getState().peers).length > 1
- if (reconnected(usePresence.getState().myId)) order.reset()
+ hasPeersRef.current || canvasSyncTarget(activeSession, activePresence.store.getState()).hasPeers
+ if (reconnected(activePresence.store.getState().myId)) order.reset()
}
readPresence()
- const unsub = usePresence.subscribe(readPresence)
+ const unsub = activePresence.store.subscribe(readPresence)
// `isCanvasMutation`, with a refusal remembered per node: a refused node is re-emitted on every
// publish (that is what makes it sync the moment the sticky is trimmed) and a drag publishes at
// ~20 Hz, so the size check re-serialized the one oversized node 20×/s, at a cost proportional to
@@ -1323,7 +1345,10 @@ export function Canvas() {
return false
}
order.onLocal(m)
- api.canvas.mutate(projectId, m)
+ // Cast to the ACTIVE session's core — a relay tab publishes to the relay HOST, not to B's
+ // own local core (the bug this fixes). Byte-identical on a local tab (`activeSession.api`
+ // IS `window.nodeTerminal`).
+ canvasSyncTarget(activeSession, activePresence.store.getState()).api.canvas.mutate(projectId, m)
return true
},
{ src, shouldPublish: () => hasPeersRef.current }
@@ -1335,7 +1360,10 @@ export function Canvas() {
publisherRef.current = null
orderRef.current = null
}
- }, [])
+ // Keyed on the api OBJECT (stable per core): a local↔relay switch re-binds order + subscription
+ // on the new core; a local→local switch keeps the SAME api so the effect does NOT re-run and the
+ // per-node order/reconnect state survives the tab switch (the documented invariant).
+ }, [activeSession.api])
// Publish on every settled node change. While dragging we throttle to ~20 Hz (position frames);
// the drag-stop handlers flush, and every other change (add / remove / color / title / collapse /
@@ -1378,7 +1406,11 @@ export function Canvas() {
// direct setNodes() bypasses handleNodesChange (which is where local edits mark dirty). Two
// clients saving the same converged state is harmless; never saving it is not.
useEffect(() => {
- return api.canvas.onMutation((projectId, mutation) => {
+ // Subscribe the ACTIVE session's core — inbound relay mutations arrive on the relay api, not the
+ // mount-time local one (the bug). Byte-identical on a local tab (`activeSession.api` IS
+ // `window.nodeTerminal`). Re-keyed on the api OBJECT below, in lockstep with the publisher, so a
+ // tab switch tears down + re-binds both together (and a local→local switch does neither).
+ return activeSession.api.canvas.onMutation((projectId, mutation) => {
hasPeersRef.current = true // proof of a peer, whatever the presence table says
if (!orderRef.current?.accept(mutation)) return
if (projectId !== useProjects.getState().activeProjectId) {
@@ -1416,7 +1448,7 @@ export function Canvas() {
setNodes(flow)
markDirty()
})
- }, [setNodes, markDirty, publishableNow])
+ }, [activeSession.api, setNodes, markDirty, publishableNow])
// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).
useEffect(() => {
diff --git a/src/renderer/canvas/collab-sync.test.ts b/src/renderer/canvas/collab-sync.test.ts
new file mode 100644
index 000000000..bc6be9c2e
--- /dev/null
+++ b/src/renderer/canvas/collab-sync.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import type { NodeTerminalApi } from '@shared/types'
+import {
+ createSession,
+ setActiveSession,
+ bindProjectToSession,
+ sessionForProject,
+ resetSessionsForTest,
+} from '../session/session'
+import { canvasSyncTarget } from './collab-sync'
+
+const localApi = { marker: 'local' } as unknown as NodeTerminalApi
+const relayApi = { marker: 'relay' } as unknown as NodeTerminalApi
+
+describe('canvasSyncTarget (Task 4 — publisher/onMutation follow the ACTIVE session)', () => {
+ beforeEach(() => resetSessionsForTest())
+
+ it('relay tab: the mutate/subscribe target is the RELAY api, and the gate arms when the relay presence has a peer', () => {
+ const local = createSession('local', localApi, 'This Mac')
+ setActiveSession(local.id)
+ const relay = createSession('relay', relayApi, "Ayşe's Mac")
+ bindProjectToSession('remote-tab', relay.id)
+
+ // The active tab is the relay one → publisher/onMutation must hit the RELAY core, not local.
+ const active = sessionForProject('remote-tab')
+
+ // A teammate is attached on the relay presence (peers includes me + Ayşe) → publish.
+ const withPeer = canvasSyncTarget(active, { peers: { me: {}, ayse: {} } })
+ expect(withPeer.api).toBe(relayApi)
+ expect(withPeer.api).not.toBe(localApi)
+ expect(withPeer.hasPeers).toBe(true)
+
+ // Solo on the relay (only my own row) → no publish, but the target api is unchanged.
+ const solo = canvasSyncTarget(active, { peers: { me: {} } })
+ expect(solo.api).toBe(relayApi)
+ expect(solo.hasPeers).toBe(false)
+ })
+
+ it('local tab: the target is window.nodeTerminal (the local api) — byte-identical to today', () => {
+ const local = createSession('local', localApi, 'This Mac')
+ setActiveSession(local.id)
+ createSession('relay', relayApi, "Ayşe's Mac") // registered but not the active tab's binding
+
+ const active = sessionForProject('some-local-tab') // unbound → resolves local
+ expect(canvasSyncTarget(active, { peers: { me: {} } }).api).toBe(localApi)
+ expect(canvasSyncTarget(active, { peers: { me: {}, other: {} } }).hasPeers).toBe(true)
+ })
+
+ it('empty peer table → no peers (nothing published on a fresh, still-connecting session)', () => {
+ const local = createSession('local', localApi, 'This Mac')
+ setActiveSession(local.id)
+ expect(canvasSyncTarget(local, { peers: {} }).hasPeers).toBe(false)
+ })
+})
diff --git a/src/renderer/canvas/collab-sync.ts b/src/renderer/canvas/collab-sync.ts
new file mode 100644
index 000000000..fff765002
--- /dev/null
+++ b/src/renderer/canvas/collab-sync.ts
@@ -0,0 +1,21 @@
+import type { NodeTerminalApi } from '@shared/types'
+import type { WorkspaceSession } from '../session/session'
+
+/**
+ * Task 4's whole fix in one pure place: the canvas-sync PUBLISHER + the onMutation SUBSCRIBER must
+ * hit the ACTIVE session's core, and the solo publish gate must count the ACTIVE session's presence
+ * peers — NOT the LOCAL session's. The bug this replaces: on a relay tab the publisher mutated B's
+ * OWN local core (never the relay host) and gated on the empty local presence, so `hasPeers` was
+ * false and a node B opened never reached A.
+ *
+ * The `peers` table includes ourselves, so `> 1` means a teammate is attached (the same predicate
+ * the presence session's own solo gate uses). Kept a pure `(session, presenceState) → target` so it
+ * is unit-testable without rendering Canvas: a relay session yields the relay api + its peer count,
+ * a local session yields `window.nodeTerminal` + the local peer count — byte-identical to today.
+ */
+export function canvasSyncTarget(
+ session: WorkspaceSession,
+ presenceState: { peers: Record<string, unknown> }
+): { api: NodeTerminalApi; hasPeers: boolean } {
+ return { api: session.api, hasPeers: Object.keys(presenceState.peers).length > 1 }
+}