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(canvas): the first presence hello is not a reconnect, and an oversized node is validated once
enes2ff277c2567f
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.tsindex 638088a62..466e3fa96 100644--- a/src/core/canvas-sync.convergence.test.ts+++ b/src/core/canvas-sync.convergence.test.ts@@ -21,7 +21,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'import { initCanvasSync, MUTATION_MAX_BYTES } from './canvas-sync'import { applyCanvasMutation, isCanvasMutation } from '../shared/canvas-mutations'-import { createCanvasOrder, PENDING_TTL_MS } from '../shared/canvas-order'+import { createCanvasOrder, createReconnectWatch, PENDING_TTL_MS } from '../shared/canvas-order'import { createCanvasPublisher, publishableStates } from '../shared/canvas-publish'import { IPC } from '../shared/ipc'import type { CanvasMutation, CanvasNodeState } from '../shared/types'@@ -147,6 +147,8 @@ class Client {refused = 0private readonly order: ReturnType<typeof createCanvasOrder>private readonly pub: ReturnType<typeof createCanvasPublisher>+ /** Mirrors Canvas's presence subscription: reset the order state only on a GENUINE reconnect. */+ private readonly reconnected = createReconnectWatch(null)constructor(readonly id: number,@@ -194,6 +196,13 @@ class Client {this.pub.publish(this.publishable())}+ /** Our presence clientId resolved (or changed). What Canvas's presence subscription does: the+ * ordering state is forgotten ONLY when a NEW clientId replaces an OLD one — a fresh connection+ * to a core whose `seq` may have restarted at 0. The first `null → myId` hello is not that. */+ presence(id: string | null): void {+ if (this.reconnected(id)) this.order.reset()+ }+/** Adopt the freshly loaded canvas as the publisher baseline without publishing it — what Canvas* does while `loadingRef` is set (a project load is not an edit). */pubAdopt(): void {@@ -506,6 +515,48 @@ describe('canvas convergence (async bus)', () => {expect(a.persisted()).toEqual(b.persisted())})+ // THE FIRST HELLO IS NOT A RECONNECT. Canvas resets the ordering state whenever its presence+ // clientId changes — including the very first `null → myId`, which lands a few ms after mount.+ // A peer's mutation can arrive before that (it is proof of a peer, so we publish), which means one+ // of OUR casts can already be in flight when the reset fires. The reset drops `pending` — so the+ // peer's mutation is no longer suppressed, and our own echo is no longer recognizable as the+ // repair of a value that already won everywhere else. It was dropped, and this client stayed on+ // the LOSING value forever (its whole-file save then wrote those bytes over everyone's canvas):+ // the permanent split-brain the ordering state exists to prevent, reopened by a lifecycle event.+ it('our first presence hello does not lose a cast in flight (the late echo still repairs)', () => {+ a.edit([node('n1', 0)])+ bus.settle()++ b.edit([node('n1', 50)]) // B's edit is cast (and ordered) first…+ a.edit([node('n1', 100)]) // …ours is ordered AFTER it, so 100 wins on every other client.+ a.presence('cl-a') // …and NOW our own presence hello resolves, with that cast still unacked.+ bus.settle()++ expect(b.x('n1')).toBe(100) // B lands on the ordered winner…+ expect(a.x('n1')).toBe(100) // …and so must we (was: 50 — our echo was thrown away).+ expect(a.persisted()).toEqual(b.persisted()) // whoever saves writes the same bytes+ })++ // …but a GENUINE reconnect must still reset. The core restarting puts its `seq` counter back at 0+ // while our `seen` map still holds the old (high) values — every mutation that follows would look+ // like a straggler and be silently dropped, and this client would drift away from its peers with+ // no way back. (Here: a new clientId, and a peer mutation stamped with a LOW seq from the restarted+ // reflector.)+ it('a genuine reconnect forgets the stale seq floor (a restarted core starts at seq 1 again)', () => {+ a.presence('cl-a')+ a.edit([node('n1', 0)])+ b.edit([node('n1', 1)])+ b.edit([node('n1', 2)])+ bus.settle()+ expect(a.x('n1')).toBe(2) // a few mutations in: A's `seen` floor for n1 is now high++ a.presence('cl-a2') // the core restarted → new connection, new clientId, `seq` back at 0+ // The restarted reflector stamps from 1 again. Without the reset this is a straggler and is+ // dropped — A would sit on the old value for the rest of the session.+ bus.deliver.get(a.id)?.(PROJECT, { op: 'upsert', node: node('n1', 9), src: 'src-2', seq: 1 })+ expect(a.x('n1')).toBe(9)+ })+// A REFUSED CAST. The reflector drops a malformed / oversized mutation at ingest (silently — there// is no negative ack). If the publisher has already advanced its baseline it never retries, and if// the ordering state has already recorded a pending entry the node goes DEAF to its peers for thediff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 821891336..838d88b9a 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -132,8 +132,8 @@ import {publishableStates,type CanvasPublisher} from '@shared/canvas-publish'-import { createCanvasOrder, type CanvasOrder } from '@shared/canvas-order'-import { isCanvasMutation } from '@shared/canvas-mutations'+import { createCanvasOrder, createReconnectWatch, type CanvasOrder } from '@shared/canvas-order'+import { createMutationGuard } from '@shared/canvas-mutations'import {applyCanvasMutation,applyMutationToFlow,@@ -996,25 +996,34 @@ export function Canvas() {// US, so >1 means a peer. Subscribed imperatively (no useStore selector) — this must never// re-render Canvas.//- // The same subscription watches our own clientId. A NEW one means a NEW connection to the core —- // and if the core RESTARTED, its `seq` counter restarted at 0 while our `seen` map still holds- // the old (high) values, which would make us silently drop every mutation that follows as a- // straggler. Forget the order state on every (re)connect: correctness must not depend on- // ws-bridge happening to `location.reload()` the page. (NOT on a project switch: this Canvas- // keeps applying mutations for loaded-but-inactive projects, so their order state has to- // survive a tab switch.)- let myId = usePresence.getState().myId+ // The same subscription watches our own clientId, because a NEW one means a NEW connection to the+ // core — and if the core RESTARTED, its `seq` counter restarted at 0 while our `seen` map still+ // holds the old (high) values, which would make us silently drop every mutation that follows as a+ // straggler. So a genuine reconnect forgets the order state; correctness must not depend on+ // ws-bridge happening to `location.reload()` the page.+ //+ // ONLY a genuine reconnect (`createReconnectWatch`). `id !== previous` also fired on the FIRST+ // `null → myId`, which resolves asynchronously a few ms after mount — by which time a peer's+ // mutation may already have arrived (that is itself proof of a peer, so we are publishing) and+ // one of our own casts may be in flight. Resetting there threw away the `pending`/`superseded`+ // record of that cast, so our own late echo was no longer recognizable as the REPAIR of a value a+ // peer had overwritten: we stayed on the losing value, and our next whole-file save wrote it over+ // 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)const readPresence = (): void => {hasPeersRef.current =hasPeersRef.current || Object.keys(usePresence.getState().peers).length > 1- const id = usePresence.getState().myId- if (id !== myId) {- myId = id- order.reset()- }+ if (reconnected(usePresence.getState().myId)) order.reset()}readPresence()const unsub = usePresence.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+ // its size. Same verdict, paid again only when the node actually changes (@shared/canvas-mutations).+ const guard = createMutationGuard()const pub = createCanvasPublisher((m) => {const projectId = useProjects.getState().activeProjectId@@ -1026,7 +1035,7 @@ export function Canvas() {// resurrect their node) nor the retry (the publisher keeps the node in its baseline). The// only thing that can legitimately blow the cap is free text, i.e. a sticky's body — so say// so, instead of letting the note silently never sync.- if (!isCanvasMutation(m)) {+ if (!guard(m)) {setSyncNote('This note is too large to share with your teammates (over 250 KB). It stays on your ' +'canvas, but they will not see it until you shorten it.'diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.tsindex 17dc5d4ba..295bd881e 100644--- a/src/shared/canvas-mutations.test.ts+++ b/src/shared/canvas-mutations.test.ts@@ -1,5 +1,11 @@-import { describe, it, expect } from 'vitest'-import { applyCanvasMutation, diffToMutations } from './canvas-mutations'+import { describe, it, expect, vi, afterEach } from 'vitest'+import {+ applyCanvasMutation,+ createMutationGuard,+ diffToMutations,+ isCanvasMutation,+ MUTATION_MAX_BYTES+} from './canvas-mutations'import type { CanvasNodeState } from './types'const n = (id: string, x = 0, title = 't'): CanvasNodeState =>@@ -59,3 +65,87 @@ describe('diffToMutations', () => {])})})++// The publisher's guard: the same verdict as `isCanvasMutation`, but it must not PAY for it twice on+// an unchanged node. The size check serializes the whole node, the publisher re-emits a refused node+// on every publish (that is what makes it sync the moment the user trims it), and a drag publishes at+// 20 Hz — so the one node that is already pathological (a sticky holding a pasted document) was being+// stringified 20×/s, at a cost proportional to its size.+describe('createMutationGuard', () => {+ afterEach(() => vi.restoreAllMocks())++ /** A sticky over the size cap. `text` is the SAME string on every rebuild — exactly what+ * flowToNodeStates does: it rebuilds the node object each publish but passes `data.text` through+ * by reference. */+ const bigText = 'x'.repeat(MUTATION_MAX_BYTES)+ const fat = (x = 0, text = bigText): CanvasNodeState =>+ ({ ...n('sticky-1', x), kind: 'sticky', text }) as CanvasNodeState++ /** Count only the serializations of a NODE (the expensive path) — not vitest's own internals. */+ const countSerializations = (): { calls: () => number } => {+ const spy = vi.spyOn(JSON, 'stringify')+ return {+ calls: () =>+ spy.mock.calls.filter((c) => {+ const v = c[0] as { node?: { id?: unknown } } | undefined+ return !!v && typeof v === 'object' && !!v.node+ }).length+ }+ }++ it('serializes an unchanged oversized node ONCE, however many times it is re-published', () => {+ const guard = createMutationGuard()+ const { calls } = countSerializations()++ // 40 publishes of the SAME (still oversized) sticky — two seconds of a 20 Hz drag.+ for (let i = 0; i < 40; i++) {+ expect(guard({ op: 'upsert', node: fat(), src: 'me' })).toBe(false)+ }+ expect(calls()).toBe(1) // was: 40 — one full serialization of a 256 KB node per publish+ })++ it('re-validates the moment the node actually changes (and the trimmed sticky syncs)', () => {+ const guard = createMutationGuard()+ expect(guard({ op: 'upsert', node: fat() })).toBe(false)++ // Still too big, but MOVED: a changed node is a new verdict, so it is paid for again…+ const { calls } = countSerializations()+ expect(guard({ op: 'upsert', node: fat(7) })).toBe(false)+ expect(calls()).toBe(1)++ // …and the user trims it → it is within the cap → it CASTS. (The refusal must not be sticky:+ // the whole point of retrying a refused node is that it syncs as soon as it fits.)+ expect(guard({ op: 'upsert', node: fat(7, 'short') })).toBe(true)+ // …and stays castable afterwards, without re-consulting a stale refusal.+ expect(guard({ op: 'upsert', node: fat(7, 'short') })).toBe(true)+ })++ it('gives exactly the verdict of isCanvasMutation (shape, ids, geometry, size)', () => {+ const guard = createMutationGuard()+ const cases: unknown[] = [+ { op: 'upsert', node: n('1') },+ { op: 'remove', id: '1' },+ { op: 'remove', id: '' },+ { op: 'upsert', node: { ...n('1'), id: '' } },+ { op: 'upsert', node: { ...n('1'), position: { x: NaN, y: 0 } } },+ { op: 'upsert', node: fat() },+ { op: 'nope' },+ null+ ]+ for (const c of cases) {+ expect(guard(c as never), JSON.stringify(c).slice(0, 40)).toBe(isCanvasMutation(c))+ }+ })++ it('remembers a refusal per node — one fat sticky does not mask another', () => {+ const guard = createMutationGuard()+ const other = (): CanvasNodeState =>+ ({ ...n('sticky-2'), kind: 'sticky', text: bigText }) as CanvasNodeState+ expect(guard({ op: 'upsert', node: fat() })).toBe(false)+ expect(guard({ op: 'upsert', node: other() })).toBe(false)+ const { calls } = countSerializations()+ expect(guard({ op: 'upsert', node: fat() })).toBe(false)+ expect(guard({ op: 'upsert', node: other() })).toBe(false)+ expect(calls()).toBe(0) // both refusals are remembered, neither is re-serialized+ })+})diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.tsindex 1a235bcb3..7f163e339 100644--- a/src/shared/canvas-mutations.ts+++ b/src/shared/canvas-mutations.ts@@ -59,6 +59,82 @@ function withinSizeLimit(m: unknown): boolean {}}+/**+ * Same top-level VALUE? A shallow compare, deliberately: it never reads the CONTENT of a string+ * field, which is the whole point (the free text is what makes an oversized node expensive).+ *+ * Sound because of how the snapshot is built: `flowToNodeStates` rebuilds the node object on every+ * publish but passes each field through BY REFERENCE (`text: n.data.text`, `tags: n.data.tags`, …),+ * so an untouched field is the SAME reference and `Object.is` settles it in O(1). `position` and+ * `size` are freshly built objects of numbers, so they are compared field-wise.+ *+ * Conservative in the only direction that matters: equal references ⇒ equal content, so it can never+ * report "unchanged" for a node that changed (which would strand an edit). The reverse (an equal+ * value rebuilt as a new reference) merely costs one honest re-validation — what happens today.+ */+function sameNodeValue(a: CanvasNodeState, b: CanvasNodeState): boolean {+ if (a === b) return true+ const ka = Object.keys(a)+ if (ka.length !== Object.keys(b).length) return false+ const ra = a as unknown as Record<string, unknown>+ const rb = b as unknown as Record<string, unknown>+ for (const k of ka) {+ const va = ra[k]+ const vb = rb[k]+ if (Object.is(va, vb)) continue+ if (k !== 'position' && k !== 'size') return false+ // The two geometry objects: plain records of numbers, rebuilt on every snapshot.+ const oa = va as Record<string, number> | undefined+ const ob = vb as Record<string, number> | undefined+ if (!oa || !ob) return false+ const gk = Object.keys(oa)+ if (gk.length !== Object.keys(ob).length) return false+ for (const g of gk) if (!Object.is(oa[g], ob[g])) return false+ }+ return true+}++/**+ * The PUBLISHER's guard: `isCanvasMutation`'s verdict, with a refusal REMEMBERED per node.+ *+ * `isCanvasMutation` answers the size question by serializing the whole node, and a refused node is+ * deliberately re-emitted on every publish (that is what makes the sticky sync the instant the user+ * trims it — see `rebaseRefused` in canvas-publish). A drag publishes at ~20 Hz. So the ONE node that+ * is already pathological — a sticky someone pasted a document into — was being stringified 20 times+ * a second, at a cost proportional to its size, for as long as it stayed oversized. The pathological+ * case must not also be the expensive one.+ *+ * The memo holds the refused node itself and re-checks only when that node's value actually changes+ * (`sameNodeValue`: reference-shallow, so it never touches the big string). Behaviour is unchanged:+ * the same verdict for every input, the refusal is re-paid the moment the node is edited, and the+ * trimmed sticky casts immediately (its entry is dropped as soon as it passes). Bounded by the number+ * of oversized nodes on the canvas — in practice zero or one, and their memory is the node the canvas+ * already holds.+ *+ * The REFLECTOR keeps calling the plain `isCanvasMutation`: its input is untrusted, freshly decoded+ * off the wire for every client, so nothing there would ever hit a memo and the map would grow with+ * whatever ids a client cared to invent. One predicate, one verdict, both ends — this only caches the+ * one end that asks the same question about the same node over and over.+ */+export function createMutationGuard(): (m: CanvasMutation) => boolean {+ const refused = new Map<string, CanvasNodeState>()+ return (m) => {+ // A `remove` is a couple of dozen bytes: nothing to amortize, and nothing that can grow.+ if (!m || typeof m !== 'object' || (m as { op?: unknown }).op !== 'upsert')+ return isCanvasMutation(m)+ const node = (m as { node?: CanvasNodeState }).node+ if (!node || typeof node !== 'object' || typeof node.id !== 'string') return isCanvasMutation(m)++ const last = refused.get(node.id)+ if (last && sameNodeValue(last, node)) return false // already refused, and nothing has changed++ const ok = isCanvasMutation(m)+ if (ok) refused.delete(node.id)+ else refused.set(node.id, node)+ return ok+ }+}+/*** Apply a single mutation to a node list, returning a NEW array (the input is never mutated).* `upsert` replaces the node with the matching id, or appends it if absent; `remove` filtersdiff --git a/src/shared/canvas-order.test.ts b/src/shared/canvas-order.test.tsindex 77879a3d6..e16dc2d2b 100644--- a/src/shared/canvas-order.test.ts+++ b/src/shared/canvas-order.test.ts@@ -3,7 +3,12 @@// (two clients, async bus); this pins the rules one at a time.import { describe, it, expect } from 'vitest'-import { createCanvasOrder, mutationNodeId, PENDING_TTL_MS } from './canvas-order'+import {+ createCanvasOrder,+ createReconnectWatch,+ mutationNodeId,+ PENDING_TTL_MS+} from './canvas-order'import type { CanvasMutation, CanvasNodeState } from './types'const node = (id: string, x = 0): CanvasNodeState =>@@ -175,3 +180,46 @@ describe('createCanvasOrder', () => {expect(o.accept(up('n1', 5, 'peer', 1))).toBe(true) // pending gone AND the seq floor gone})})++// WHEN to call reset(). It exists for ONE reason — a core restart puts `seq` back at 0 while our+// `seen` map still holds the old (high) values, and we would then drop every new mutation as a+// straggler — and it is EXPENSIVE to call when that reason does not hold: it drops `pending` and+// `superseded`, i.e. the in-flight casts whose late echo is the only thing that can repair a node a+// peer overwrote. So it must fire on a genuine reconnect and NOWHERE else.+describe('createReconnectWatch', () => {+ it('does not reset on the first hello (null → myId): there is no older connection to forget', () => {+ const w = createReconnectWatch(null)+ expect(w(null)).toBe(false) // still no id (presence has not answered yet)+ expect(w('cl-1')).toBe(false) // our FIRST clientId — nothing was ever seen from an older core+ expect(w('cl-1')).toBe(false) // idle presence updates (a peer's cursor) are not reconnects+ })++ it('resets when a NEW clientId replaces an old one (a genuine reconnect)', () => {+ const w = createReconnectWatch(null)+ expect(w('cl-1')).toBe(false)+ expect(w('cl-2')).toBe(true) // reconnected: the core may have restarted with seq back at 0+ expect(w('cl-2')).toBe(false)+ })++ it('survives the null in the middle of a reconnect (id → null → new id still resets)', () => {+ const w = createReconnectWatch('cl-1')+ expect(w(null)).toBe(false) // the socket dropped: keep the state, wait for the new id+ expect(w('cl-1')).toBe(false) // …the SAME connection came back: nothing to forget+ expect(w(null)).toBe(false)+ expect(w('cl-3')).toBe(true) // a different one: reset+ })++ it('an id already known at mount is not a reconnect', () => {+ const w = createReconnectWatch('cl-1')+ expect(w('cl-1')).toBe(false)+ })++ // The desktop presence hub's clientId is a NUMBER (the Electron sender id) — and 0 is a perfectly+ // real connection, so only `null` may mean "no id yet".+ it('treats a numeric clientId of 0 as a real connection, not as "not resolved yet"', () => {+ const w = createReconnectWatch(null)+ expect(w(0)).toBe(false) // the first hello…+ expect(w(0)).toBe(false)+ expect(w(1)).toBe(true) // …and a genuine reconnect after it+ })+})diff --git a/src/shared/canvas-order.ts b/src/shared/canvas-order.tsindex 9360056dd..9462f3686 100644--- a/src/shared/canvas-order.ts+++ b/src/shared/canvas-order.ts@@ -191,3 +191,52 @@ export function createCanvasOrder(}}}++/**+ * WHEN the ordering state may be reset — the lifecycle half of the contract above.+ *+ * `reset()` exists for exactly ONE reason: if the core RESTARTS, its `seq` counter restarts at 0+ * while a surviving client's `seen` map still holds the old (high) values — that client would then+ * drop every mutation the new core stamps as a straggler and drift away from its peers for the rest+ * of the session, with no way back. A NEW presence clientId is the observable signal of exactly that:+ * a new connection, possibly to a new core.+ *+ * But reset() is far from free: it also drops `pending` and `superseded`, the record of our own casts+ * that are still in flight. Drop those and rule 1 (our own echo is an ack) is left with no way to+ * tell an ack from a REPAIR — so if a peer's edit has overwritten our optimistic value, our late echo+ * is thrown away and we stay on the LOSING value forever, and the next whole-file workspace.save+ * writes those bytes over everyone else's canvas. That is the permanent split-brain rule 3 exists to+ * prevent, and a mistimed reset reopens it.+ *+ * So it must fire on a GENUINE reconnect and nowhere else. The trap: presence resolves our clientId+ * ASYNCHRONOUSLY, so a naive `id !== previous` also fires on the very first `null → myId` at mount —+ * and by then we may already be publishing (a peer's mutation is itself proof of a peer), i.e. our+ * own casts can already be in flight. There is nothing to forget at the first hello: an empty `seen`+ * map cannot be stale. This watch therefore reports a reconnect only when a NEW non-null id REPLACES+ * a previously seen one, and ignores the `null`s in between (a dropped socket must not throw away+ * state the reconnect to the SAME core would still need).+ *+ * Returns a predicate to be fed every presence update: `true` ⇒ call `order.reset()`.+ *+ * The id is whatever the presence hub calls a connection (a numeric clientId on the desktop, a string+ * elsewhere) — it is only ever compared, never parsed.+ */+export type ConnectionId = string | number++export function createReconnectWatch(+ initialId: ConnectionId | null = null+): (id: ConnectionId | null) => boolean {+ let known = initialId+ return (id) => {+ // `null` (and nothing else — a clientId of 0 is a real connection): not resolved yet, or the+ // socket dropped. Keep the state: reconnecting to the SAME core still needs it.+ if (id === null || id === undefined) return false+ if (known === null) {+ known = id // the FIRST hello — there is no older connection whose `seq` could be stale+ return false+ }+ if (id === known) return false+ known = id+ return true // a new connection replaced the old one: the core may have restarted at seq 0+ }+}