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.

fix(canvas): a late ack repairs the node, and a refused cast is never made

enesb91b827676f5
diff --git a/docs/team-presence.md b/docs/team-presence.md
index 1d547170d..f77f6b017 100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@ -340,12 +340,35 @@ independently on each client from the already-broadcast `agent:status` stream; a
attached client, the sender included (`CorePlatform.clientIds()` + `onWithSender`). `seq` is
server-authoritative (a client-supplied one is overwritten at ingest).
- **Ordering** (`src/shared/canvas-order.ts`) — the client half, and the reason concurrent edits
- converge instead of splitting the canvas in two. Per node, the highest `seq` wins. Two rules: (1)
+ converge instead of splitting the canvas in two. Per node, the highest `seq` wins. Three rules: (1)
our own echo is an **ack**, not an edit — it carries the `seq` our mutation was given, and is never
re-applied (re-applying it would rubber-band a node we are still dragging); (2) while one of our
own mutations for a node is unacked, we ignore peers' mutations for that node — FIFO delivery means
- ours is necessarily *later* in the total order, so it will win on every other client too. A pending
- entry expires after `PENDING_TTL_MS` so a cast the reflector refused cannot deafen a node forever.
+ ours is necessarily *later* in the total order, so it will win on every other client too; (3) rule
+ 1 is only sound **while our optimistic value is still on our canvas**. Rule 2's suppression is
+ bounded by `PENDING_TTL_MS` (an ack can be late — the same socket carries pty output, and Stage 2
+ tolerates an 8 MB backlog on it), and once it lapses a peer's mutation can overwrite the value we
+ are still waiting to have acked. From that moment our echo is the **only** copy of a value that
+ already won on every other client, so it is **applied** (a repair), not dropped. Without rule 3 a
+ late ack left that client permanently on the losing value — and its whole-file `workspace.save`
+ then wrote those losing bytes over everyone else's canvas, which is precisely the property this
+ stage exists to guarantee. The pending entry's `since` is refreshed on every local mutation for
+ that node, so a drag longer than the TTL cannot expire its own suppression mid-drag.
+ `order.reset()` is called whenever our presence clientId changes (i.e. on every (re)connect): if
+ the core restarted, its `seq` restarted at 0 while our `seen` map still held high values, and we
+ would silently drop every new mutation as a straggler. Correctness no longer depends on the
+ ws-bridge's `location.reload()`.
+- **A cast the reflector would refuse is never made** — the publisher validates with the **same**
+ predicate the reflector's ingest uses (`isCanvasMutation`, moved to `src/shared/canvas-mutations.ts`
+ so both ends share one verdict) *before* recording a pending entry and *before* casting. A refusal
+ therefore costs neither a pending entry (which would have deafened that node to its peers for the
+ whole TTL — a peer's `remove` landing in that window was dropped and never recovered, so the next
+ whole-file save resurrected the node they deleted) nor the retry: the refused node keeps its
+ **previous baseline entry**, so the very next publish re-emits it and it syncs the moment it becomes
+ castable. The only thing that can legitimately exceed `MUTATION_MAX_BYTES` is free text — a sticky
+ someone pasted a document into — so Canvas **tells the user** ("This note is too large to share with
+ your teammates (over 250 KB)… they will not see it until you shorten it") instead of leaving them
+ with a note the team silently never receives.
- **Loop guard** — a mutation applied from a peer is `adopt()`ed into the publisher's baseline before
the next diff runs, so it can never be re-published (no A→B→C→A ping-pong).
- **Apply** — the vocabulary is single-sourced in `src/shared/canvas-mutations.ts` and used by both
@@ -567,6 +590,13 @@ persistence depends on: whichever client's whole-file `workspace.save` runs, it
others agree with. Proven end-to-end against an **asynchronous** bus (queued casts + FIFO deliveries,
edits genuinely in flight) in `src/core/canvas-sync.convergence.test.ts`.
+That guarantee does **not** rest on any timeout. The pending TTL is a bound on how long we *suppress*
+peers, never on correctness: an ack that arrives after it **repairs** the node (rule 3 above), and a
+cast the reflector would refuse is never made in the first place (the publisher shares the reflector's
+predicate, records no pending entry, and keeps retrying the node until it is castable). Both cases are
+in the convergence suite — a client whose socket is stalled past the TTL, and an oversized sticky cast
+concurrently with a peer's delete.
+
**Does NOT converge — named, not hidden:**
- **Array order after a resurrection.** If a delete *loses* the order race, the client that issued it
@@ -576,13 +606,18 @@ edits genuinely in flight) in `src/core/canvas-sync.convergence.test.ts`.
- **Intent, on a contended node.** Two people dragging the same node fight: the node lands wherever
the last-ordered frame put it. Two people typing a title get one title. That is last-write-wins,
not a merge — by design (no CRDT).
-- **A delete that loses to a concurrent edit.** If A deletes a node while B is mid-drag, and B's next
- frame is ordered after A's remove, the node **survives on both canvases** — the last write wins,
- and it happened to be an upsert. A's `transport.destroy` already killed the tmux session, so the
- surviving node is a shell: opening it starts a fresh session. The node is *consistent* everywhere
- (no split-brain save, which was the whole point), it is simply not the outcome A wanted. Deleting a
- node someone else is actively dragging is a race between two humans; nodeterm resolves it, it does
- not arbitrate it.
+- **A delete that loses to a concurrent edit — and the node comes back with a DEAD TERMINAL.** If A
+ deletes a node while B is mid-drag, and B's next frame is ordered after A's remove, the node
+ **survives on both canvases** — the last write wins, and it happened to be an upsert. But A's
+ `transport.destroy` had already run `tmux kill-session`, and nothing resurrects a killed session:
+ the node that comes back is a **shell around a dead terminal**. Its scrollback and its running
+ process are gone; the next time it is opened, `pty.create` starts a **fresh** session under the same
+ `nt-<nodeId>` (a cold start: scrollback replay finds nothing, an agent node re-launches its CLI).
+ The canvas is *consistent* everywhere (no split-brain save, which was the whole point) — the node
+ content is not. Deleting a node someone else is actively dragging is a race between two humans;
+ nodeterm resolves the canvas, it cannot un-kill a process. A "delete always wins" tiebreak would
+ trade this for the opposite hazard (a stale drag frame from a disconnected peer erasing a node that
+ was legitimately re-created), so v1 leaves the total order in charge and names the wart here.
- **Anything outside the node vocabulary** — edges, project lifecycle (see item 5 above).
## Non-goals (v1)
@@ -623,7 +658,10 @@ read-only guests, per-user settings.
`src/shared/canvas-mutations.test.ts`
- **Ordering** (delivered): an own echo is an ack and is never re-applied; a peer's edit loses to an
unacked local edit of the same node (per node, counted per in-flight frame); a superseded straggler
- is dropped; an ack that never comes expires. → `src/shared/canvas-order.test.ts` (11 tests)
+ is dropped; an ack that never comes expires; a **late** ack repairs a node a peer overwrote after
+ the TTL lapsed (and one that lost the total order is still just an ack); a fresh local edit re-arms
+ the node; a continuous drag keeps its own suppression alive past the TTL.
+ → `src/shared/canvas-order.test.ts` (15 tests)
- **Canvas convergence** (delivered): two clients running the **real** publisher and **real** ordering
against the **real** reflector, over an **ASYNCHRONOUS** bus (casts and deliveries queued, FIFO per
link — so several edits are genuinely in flight and the test chooses the interleaving). *The
@@ -634,8 +672,11 @@ read-only guests, per-user settings.
editing one node converge; every interleaving × every settle point of a six-edit set converges; a
peer's mutation is applied once and **re-published never** (one cast per local edit, no
counter-cast, even for a bulk delete across three clients); ephemeral cards never go on the wire; a
- late joiner converges; and a peer's delete is not resurrected by the surviving client's next save.
- → `src/core/canvas-sync.convergence.test.ts` (14 tests)
+ late joiner converges; a peer's delete is not resurrected by the surviving client's next save; a
+ client whose **inbox is stalled past the TTL** (a backed-up socket) is repaired by its own late ack
+ instead of being left on the losing value; and an **oversized** node the reflector would refuse
+ neither deafens that node to a peer's concurrent delete nor is silently lost (it is retried, and
+ syncs once trimmed). → `src/core/canvas-sync.convergence.test.ts` (18 tests)
- **Applying a peer's mutation** (delivered): patches the live React Flow array — keeps your
selection, keeps relay-remote nodes, keeps local-only node data, keeps every untouched node's
object identity, drops the stale `measured` size so a peer's resize is not fought back, and keeps
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.ts
index 5fd94db1d..638088a62 100644
--- a/src/core/canvas-sync.convergence.test.ts
+++ b/src/core/canvas-sync.convergence.test.ts
@@ -19,9 +19,9 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'
-import { initCanvasSync } from './canvas-sync'
-import { applyCanvasMutation } from '../shared/canvas-mutations'
-import { createCanvasOrder } from '../shared/canvas-order'
+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 { createCanvasPublisher, publishableStates } from '../shared/canvas-publish'
import { IPC } from '../shared/ipc'
import type { CanvasMutation, CanvasNodeState } from '../shared/types'
@@ -37,6 +37,15 @@ const node = (id: string, x: number, title = 't', color = '#fff'): CanvasNodeSta
size: { width: 10, height: 10 }
}) as CanvasNodeState
+/** A sticky whose body someone pasted a document into: its serialized form is over
+ * MUTATION_MAX_BYTES, so the reflector REFUSES it at ingest — silently, with no negative ack. */
+const fat = (id: string): CanvasNodeState =>
+ ({
+ ...node(id, 0),
+ kind: 'sticky',
+ data: { text: 'x'.repeat(MUTATION_MAX_BYTES) }
+ }) as CanvasNodeState
+
const PROJECT = 'p1'
/**
@@ -54,6 +63,10 @@ class Bus {
clients: number[] = []
/** Total casts made BY clients (publisher → reflector). One per real local edit; never more. */
castCount = 0
+ /** Clients whose INBOX is stalled — their socket is backed up (Stage 2 tolerates an 8 MB pty
+ * backlog on the very same socket), so their acks and their peers' mutations arrive late.
+ * Their casts still reach the reflector: only the return path is blocked. */
+ private readonly stalled = new Set<number>()
platform: CorePlatform = {
userDataDir: '/tmp/nodeterm-convergence',
@@ -88,9 +101,19 @@ class Bus {
return true
}
+ /** Stall / unstall one client's inbox (a backed-up socket). */
+ stall(id: number): void {
+ this.stalled.add(id)
+ }
+
+ unstall(id: number): void {
+ this.stalled.delete(id)
+ }
+
/** Pop one queued delivery into its addressed client (FIFO within that client's inbox). */
private stepDelivery(): boolean {
for (const id of this.clients) {
+ if (this.stalled.has(id)) continue
const q = this.inbox.get(id)
if (!q?.length) continue
const d = q.shift() as { projectId: string; m: CanvasMutation }
@@ -120,6 +143,8 @@ class Client {
ephemeral = new Set<string>()
/** Mutations APPLIED from the wire (an own echo, or one the order supersedes, is not applied). */
applied = 0
+ /** Local mutations the publisher tried to cast and this client refused (oversized / malformed). */
+ refused = 0
private readonly order: ReturnType<typeof createCanvasOrder>
private readonly pub: ReturnType<typeof createCanvasPublisher>
@@ -131,11 +156,22 @@ class Client {
// properties are assigned, so `this.id` would still be undefined and both clients would stamp
// the same `src` — every peer mutation would then look like their own echo.
const src = `src-${id}`
- this.order = createCanvasOrder(src)
+ // A FAKE clock: the pending TTL is the one time-dependent rule in canvas-order, and the tests
+ // below need to cross it deliberately (`clock += ...`) rather than by sleeping.
+ this.order = createCanvasOrder(src, { now: () => clock })
this.pub = createCanvasPublisher(
(m) => {
+ // Mirrors Canvas: ask the SAME predicate the reflector's ingest asks, BEFORE recording a
+ // pending entry or casting. A refusal means nothing was cast — so nothing is pending (the
+ // node stays open to its peers) and the publisher keeps the node in its baseline and
+ // retries it on the next publish. Canvas also surfaces the refusal to the user.
+ if (!isCanvasMutation(m)) {
+ this.refused++
+ return false
+ }
this.order.onLocal(m)
bus.cast(id, PROJECT, m)
+ return true
},
{ src }
)
@@ -195,8 +231,11 @@ const canon = (c: Client): CanvasNodeState[] =>
let bus: Bus
let a: Client
let b: Client
+/** The clients' shared fake clock (ms), read by every canvas-order pending TTL. */
+let clock = 0
function boot(): void {
+ clock = 1_000
bus = new Bus()
initPlatform(bus.platform)
initCanvasSync()
@@ -441,6 +480,73 @@ describe('canvas convergence (async bus)', () => {
expect(a.persisted()).toEqual(c.persisted())
})
+ // A LATE ACK. Rule 1 (never re-apply our own echo) is only sound while our optimistic value is
+ // still on our canvas. Once rule 2's suppression lapses on the TTL and a peer's OLDER mutation
+ // overwrites it, our echo is the only thing that can restore the value that won everywhere else —
+ // and rule 1 used to throw it away. Realistic trigger: our socket is backed up with pty output
+ // (Stage 2 tolerates an 8 MB backlog on that same socket), so our ack takes longer than the TTL.
+ it('a peer edit applied after the TTL is repaired by our own late ack (no permanent split-brain)', () => {
+ a.edit([node('n1', 0)])
+ bus.settle()
+
+ bus.stall(a.id) // A's socket backs up: nothing reaches A, but its casts still leave.
+ b.edit([node('n1', 50)]) // B's edit is cast (and ordered) FIRST…
+ a.edit([node('n1', 100)]) // …A's is ordered AFTER it, so A's value wins on every other client.
+ bus.settle()
+ expect(b.x('n1')).toBe(100) // …and it does: B (and every other client) shows A's 100.
+
+ clock += PENDING_TTL_MS + 1 // A's pending entry expires while its inbox is still stalled.
+ bus.unstall(a.id)
+ bus.settle() // A now receives B's older mutation, then its OWN echo.
+
+ // A must not be left holding the value that lost the total order — its next whole-file
+ // workspace.save would write those losing bytes over everyone else's canvas.
+ expect(a.x('n1')).toBe(100)
+ expect(a.x('n1')).toBe(b.x('n1'))
+ expect(a.persisted()).toEqual(b.persisted())
+ })
+
+ // 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 the
+ // whole TTL. A peer's `remove` landing in that window was dropped and never recovered → the next
+ // save resurrected the node they deleted. Trigger: a sticky whose body a user pasted a document
+ // into (sticky text is unbounded in the UI) is over MUTATION_MAX_BYTES.
+ it('an oversized node the reflector refuses does not deafen it to a peer delete', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ bus.settle()
+
+ a.edit([fat('n1'), node('n2', 0)]) // A pastes a document into n1 → the cast is refused at ingest
+ b.edit(b.states.filter((n) => n.id !== 'n1')) // …and B deletes n1 in the same window
+ bus.settle()
+
+ expect(a.ids()).toEqual(b.ids()) // was: A ['n1','n2'] vs B ['n2'] — forever
+ expect(a.ids()).toEqual(['n2'])
+ expect(a.persisted()).toEqual(b.persisted())
+ })
+
+ it('a refused cast is retried on the next publish (once the node is within the size limit)', () => {
+ a.edit([node('n1', 0)])
+ bus.settle()
+
+ a.edit([fat('n1')]) // refused: never reaches B
+ bus.settle()
+ expect(b.x('n1')).toBe(0) // B still shows the last mutation that WAS reflected
+
+ a.edit([node('n1', 7)]) // the user trims the sticky → the edit is within the limit again
+ bus.settle()
+ expect(b.x('n1')).toBe(7)
+ expect(a.persisted()).toEqual(b.persisted())
+ })
+
+ it('a refused cast does not block the OTHER nodes in the same snapshot', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ bus.settle()
+ a.edit([fat('n1'), node('n2', 42)]) // one refused upsert, one legitimate one
+ bus.settle()
+ expect(b.x('n2')).toBe(42)
+ })
+
it('a peer delete is not resurrected by the surviving client (the save-safety property)', () => {
a.edit([node('n1', 0), node('n2', 0)])
bus.settle()
diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.ts
index 744193b9c..0c07e242e 100644
--- a/src/core/canvas-sync.ts
+++ b/src/core/canvas-sync.ts
@@ -38,16 +38,16 @@
import { platform, type CorePlatform } from './platform'
import { IPC } from '../shared/ipc'
-import { REF_MAX_LEN, type ClientId } from '../shared/presence'
+import { isCanvasMutation, isRefId, MUTATION_MAX_BYTES } from '../shared/canvas-mutations'
+import { type ClientId } from '../shared/presence'
import type { CanvasMutation } from '../shared/types'
-/**
- * Ceiling on one mutation's serialized size. A node carries free text (a sticky's body, an
- * editor's path), and the whole object is reflected verbatim to every peer — so an unbounded one
- * is an N-way amplifier straight into everyone's WS send buffer (the same sink pty output rides).
- * 256 KB is orders of magnitude past any real node and cannot refuse a legitimate edit.
- */
-export const MUTATION_MAX_BYTES = 256_000
+// The ingest guard (`isCanvasMutation`) and its size cap live in `shared`, because the PUBLISHER
+// must reach the same verdict BEFORE it casts: a mutation this reflector refuses is dropped
+// silently, and a publisher that only learned about it by never hearing an ack would advance its
+// baseline (never retrying the edit) and deafen that node to its peers for a whole pending TTL.
+// Re-exported here because this is where the refusal is enforced, and where the tests look for it.
+export { isCanvasMutation, MUTATION_MAX_BYTES }
/**
* Every attached client the mutation goes to — INCLUDING the sender, whose copy is its ack (see the
@@ -71,44 +71,6 @@ export function stampMutation(m: CanvasMutation, seq: number): CanvasMutation {
return stamped
}
-/** An id off the wire: non-empty and bounded by the shared ref cap (node ids and project ids are
- * short and generated — `term-ab12`, `project-1` — so this can never refuse a real one). Ids are
- * REJECTED, never truncated: a truncated id would address the WRONG node on every peer. */
-function isRefId(value: unknown): value is string {
- return typeof value === 'string' && value.length > 0 && value.length <= REF_MAX_LEN
-}
-
-/**
- * Shape + size guard: a client cast is untrusted input, and it is reflected to every peer as-is.
- * A malformed payload would wedge a peer's React Flow (applyCanvasMutation would upsert a node with
- * no id, or a NaN position, which React Flow cannot lay out); an oversized one would flood their
- * sockets. Drop it here — the reflector never throws, and never keys anything by a wire string.
- */
-export function isCanvasMutation(value: unknown): value is CanvasMutation {
- if (!value || typeof value !== 'object') return false
- const m = value as { op?: unknown; id?: unknown; node?: unknown }
- if (m.op === 'remove') return isRefId(m.id)
- if (m.op !== 'upsert') return false
- const node = m.node as { id?: unknown; position?: { x?: unknown; y?: unknown } } | undefined
- if (!node || typeof node !== 'object') return false
- if (!isRefId(node.id)) return false
- const pos = node.position
- if (!pos || typeof pos !== 'object') return false
- if (!Number.isFinite(pos.x) || !Number.isFinite(pos.y)) return false
- return withinSizeLimit(m)
-}
-
-function withinSizeLimit(m: unknown): boolean {
- try {
- // The wire form is JSON on the server and a structured clone on the desktop; either way this
- // is a faithful measure of what would be pushed to every peer. A value that cannot even be
- // stringified (BigInt, a cycle) is not something we should be reflecting.
- return JSON.stringify(m).length <= MUTATION_MAX_BYTES
- } catch {
- return false
- }
-}
-
/** The platform this reflector is already installed on. `on`/`onWithSender` COMPOSE on the same
* channel (ServerPlatform keeps an ordered SET per channel), so a second registration on the same
* platform would reflect every mutation twice. Keyed by platform, not a bare boolean, so a fresh
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 7c6dd11ff..821891336 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -133,6 +133,7 @@ import {
type CanvasPublisher
} from '@shared/canvas-publish'
import { createCanvasOrder, type CanvasOrder } from '@shared/canvas-order'
+import { isCanvasMutation } from '@shared/canvas-mutations'
import {
applyCanvasMutation,
applyMutationToFlow,
@@ -287,6 +288,11 @@ export function Canvas() {
// (the user must pick a side). One-shot v2→v3 migration note (dismissible strip).
const [conflict, setConflict] = useState<Project | null>(null)
const [migrationNote, setMigrationNote] = useState<string | null>(null)
+ // A local edit team-sync cannot carry (a node over MUTATION_MAX_BYTES — in practice a sticky
+ // whose body someone pasted a document into). The reflector refuses it SILENTLY, so the user is
+ // told here rather than being left with a note their teammates never see. Dismissible; re-armed
+ // by the next refused cast (the publisher keeps retrying that node, so it syncs once trimmed).
+ const [syncNote, setSyncNote] = useState<string | null>(null)
const [zoomPct, setZoomPct] = useState(100)
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
const [remotePicker, setRemotePicker] = useState<{ x: number; y: number } | null>(null)
@@ -989,18 +995,47 @@ export function Canvas() {
// Solo gate: publish only once someone else is attached. The presence hub's peer table includes
// US, so >1 means a peer. Subscribed imperatively (no useStore selector) — this must never
// re-render Canvas.
- const readPeers = (): void => {
+ //
+ // 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
+ 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()
+ }
}
- readPeers()
- const unsub = usePresence.subscribe(readPeers)
+ readPresence()
+ const unsub = usePresence.subscribe(readPresence)
const pub = createCanvasPublisher(
(m) => {
const projectId = useProjects.getState().activeProjectId
- if (!projectId) return // no active canvas → the cast would be dropped at ingest, un-acked
+ if (!projectId) return false // no active canvas: nothing was cast — retry on the next publish
+ // The reflector REFUSES an oversized / malformed mutation at ingest, silently: no peer ever
+ // sees it and there is no negative ack. Ask the same predicate FIRST, so a refusal costs us
+ // neither a pending entry (which would deafen this node to its peers for the whole TTL — a
+ // peer's delete landing in that window would be lost, and our next whole-file save would
+ // 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)) {
+ 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.'
+ )
+ return false
+ }
order.onLocal(m)
window.nodeTerminal.canvas.mutate(projectId, m)
+ return true
},
{ src, shouldPublish: () => hasPeersRef.current }
)
@@ -3991,6 +4026,21 @@ export function Canvas() {
</button>
</div>
)}
+ {syncNote && (
+ <div className="announce-banner announce-banner--info">
+ <span className="announce-banner__dot" />
+ <div className="announce-banner__content">
+ <span className="announce-banner__body">{syncNote}</span>
+ </div>
+ <button
+ className="announce-banner__close"
+ title="Dismiss"
+ onClick={() => setSyncNote(null)}
+ >
+ ✕
+ </button>
+ </div>
+ )}
{conflict && (
<ConflictBar
onReload={() => {
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index d37531ecb..1a235bcb3 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -2,8 +2,63 @@
// the relay host (src/main/remote), the renderer (Canvas), and the canvas-sync reflector
// (src/core). Pure: no electron, no sockets, no disk.
+import { REF_MAX_LEN } from './presence'
import type { CanvasMutation, CanvasNodeState } from './types'
+/**
+ * Ceiling on one mutation's serialized size. A node carries free text (a sticky's body, an
+ * editor's path), and the whole object is reflected verbatim to every peer — so an unbounded one
+ * is an N-way amplifier straight into everyone's WS send buffer (the same sink pty output rides).
+ * 256 KB is orders of magnitude past any real node and cannot refuse a legitimate edit.
+ */
+export const MUTATION_MAX_BYTES = 256_000
+
+/** An id off the wire: non-empty and bounded by the shared ref cap (node ids and project ids are
+ * short and generated — `term-ab12`, `project-1` — so this can never refuse a real one). Ids are
+ * REJECTED, never truncated: a truncated id would address the WRONG node on every peer. */
+export function isRefId(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= REF_MAX_LEN
+}
+
+/**
+ * Shape + size guard: a client cast is untrusted input, and it is reflected to every peer as-is.
+ * A malformed payload would wedge a peer's React Flow (applyCanvasMutation would upsert a node with
+ * no id, or a NaN position, which React Flow cannot lay out); an oversized one would flood their
+ * sockets.
+ *
+ * IT LIVES IN `shared`, NOT IN THE REFLECTOR, because BOTH ends need the same verdict. The reflector
+ * drops what it refuses — silently, with no negative ack — so a publisher that cast it anyway would
+ * advance its baseline (never retrying) and record a pending entry (deafening that node to its peers
+ * for the whole pending TTL: a peer's `remove` landing in that window would be dropped, and the next
+ * whole-file save would resurrect the node they deleted). The publisher therefore asks THIS function
+ * first and, on a refusal, casts nothing, records nothing, and keeps the node in its baseline so the
+ * next edit retries it. One predicate, one verdict, both ends.
+ */
+export function isCanvasMutation(value: unknown): value is CanvasMutation {
+ if (!value || typeof value !== 'object') return false
+ const m = value as { op?: unknown; id?: unknown; node?: unknown }
+ if (m.op === 'remove') return isRefId(m.id)
+ if (m.op !== 'upsert') return false
+ const node = m.node as { id?: unknown; position?: { x?: unknown; y?: unknown } } | undefined
+ if (!node || typeof node !== 'object') return false
+ if (!isRefId(node.id)) return false
+ const pos = node.position
+ if (!pos || typeof pos !== 'object') return false
+ if (!Number.isFinite(pos.x) || !Number.isFinite(pos.y)) return false
+ return withinSizeLimit(m)
+}
+
+function withinSizeLimit(m: unknown): boolean {
+ try {
+ // The wire form is JSON on the server and a structured clone on the desktop; either way this
+ // is a faithful measure of what would be pushed to every peer. A value that cannot even be
+ // stringified (BigInt, a cycle) is not something we should be reflecting.
+ return JSON.stringify(m).length <= MUTATION_MAX_BYTES
+ } catch {
+ return false
+ }
+}
+
/**
* 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` filters
diff --git a/src/shared/canvas-order.test.ts b/src/shared/canvas-order.test.ts
index b37f67f52..77879a3d6 100644
--- a/src/shared/canvas-order.test.ts
+++ b/src/shared/canvas-order.test.ts
@@ -99,18 +99,67 @@ describe('createCanvasOrder', () => {
expect(o.accept(up('n1', 1, 'other', 5))).toBe(true) // a NEWER one can (that is undo-of-delete)
})
- // The pending gate assumes the ack always comes back. It usually does — but the reflector drops
- // a mutation it refuses (oversized), and that would otherwise deafen the node to its peers for
- // the rest of the session.
+ // The pending gate assumes the ack always comes back. It usually does — but an ack can be LATE
+ // (our socket carries pty output too), and unbounded suppression would deafen the node to its
+ // peers for the rest of the session.
it('an ack that never arrives expires — a lost cast cannot deafen a node forever', () => {
let t = 1000
const o = createCanvasOrder('me', { now: () => t })
- o.onLocal(up('n1', 1, 'me', 0)) // cast… and the reflector refuses it: no ack, ever
+ o.onLocal(up('n1', 1, 'me', 0)) // cast… and no ack comes back
expect(o.accept(up('n1', 5, 'peer', 2))).toBe(false)
t += PENDING_TTL_MS + 1
expect(o.accept(up('n1', 6, 'peer', 3))).toBe(true)
})
+ // Rule 3. Expiring the suppression let a peer overwrite an optimistic value we are still waiting
+ // to have acked. Our echo is then the only copy of a value that WON on every other client — so it
+ // repairs the node instead of being dropped as an ack. Without this, this client sat on the
+ // losing value forever and wrote it to disk over everyone else's canvas.
+ it('a late ack REPAIRS a node a peer overwrote after the TTL lapsed', () => {
+ let t = 1000
+ const o = createCanvasOrder('me', { now: () => t })
+ o.onLocal(up('n1', 100, 'me', 0)) // cast; the reflector ordered it 7th — it wins everywhere
+ t += PENDING_TTL_MS + 1 // our ack is stuck behind a backed-up socket
+ expect(o.accept(up('n1', 50, 'peer', 6))).toBe(true) // …so the peer's OLDER edit lands on us
+ expect(o.accept(up('n1', 100, 'me', 7))).toBe(true) // …and our late ack puts our value back
+ // Settled: the node listens to peers again, and later echoes are ordinary acks once more.
+ expect(o.accept(up('n1', 20, 'peer', 8))).toBe(true)
+ })
+
+ it('a late ack that LOST the total order is still just an ack (no rubber-band)', () => {
+ let t = 1000
+ const o = createCanvasOrder('me', { now: () => t })
+ o.onLocal(up('n1', 100, 'me', 0)) // ordered 6th — the peer's edit is ordered AFTER it
+ t += PENDING_TTL_MS + 1
+ expect(o.accept(up('n1', 50, 'peer', 7))).toBe(true) // the peer's edit wins everywhere…
+ expect(o.accept(up('n1', 100, 'me', 6))).toBe(false) // …so our echo is superseded: dropped
+ })
+
+ it('a fresh local edit re-arms the node, so an older echo of ours cannot replay over it', () => {
+ let t = 1000
+ const o = createCanvasOrder('me', { now: () => t })
+ o.onLocal(up('n1', 100, 'me', 0))
+ t += PENDING_TTL_MS + 1
+ expect(o.accept(up('n1', 50, 'peer', 6))).toBe(true) // peer overwrote our optimistic value…
+ o.onLocal(up('n1', 300, 'me', 0)) // …but the user drags it again: 300 is on our canvas now
+ expect(o.accept(up('n1', 100, 'me', 7))).toBe(false) // the old echo must not rubber-band it
+ expect(o.accept(up('n1', 300, 'me', 8))).toBe(false) // our new cast's echo is a plain ack
+ })
+
+ // A drag emits a frame every 50 ms. Dating the pending entry from the OLDEST unacked cast expired
+ // it mid-drag, and a peer's older frame then rubber-banded a node the user was still holding.
+ it('a continuous drag keeps its own suppression alive past the TTL', () => {
+ let t = 1000
+ const o = createCanvasOrder('me', { now: () => t })
+ for (let i = 0; i < 200; i++) {
+ o.onLocal(up('n1', i, 'me', 0)) // 200 frames × 50 ms = 10 s of dragging, all acked promptly
+ expect(o.accept(up('n1', i, 'me', i + 1))).toBe(false)
+ t += 50
+ }
+ o.onLocal(up('n1', 999, 'me', 0)) // still dragging, this frame not yet acked
+ expect(o.accept(up('n1', 5, 'peer', 500))).toBe(false) // …a peer's frame still loses to ours
+ })
+
it('an unstamped mutation (no reflector in the path) is never treated as stale', () => {
const o = createCanvasOrder('me')
const unstamped: CanvasMutation = { op: 'upsert', node: node('n1', 1) }
diff --git a/src/shared/canvas-order.ts b/src/shared/canvas-order.ts
index 4d8fb2a36..9360056dd 100644
--- a/src/shared/canvas-order.ts
+++ b/src/shared/canvas-order.ts
@@ -28,6 +28,14 @@
// necessarily LATER in the total order than anything we are hearing now — it will win on every
// other client, and keeping it here is what agrees with them.
//
+// 3. …AND RULE 1 IS ONLY SOUND WHILE OUR OPTIMISTIC VALUE IS STILL ON OUR CANVAS. Rule 2's
+// suppression is bounded by a TTL (an ack can be late — our socket carries pty output too), and
+// once it lapses a peer's mutation can overwrite the value we are still waiting to have acked.
+// From that moment our echo is not "something we already show", it is the ONLY copy of a value
+// that won on every other client — so it is APPLIED, not dropped (`superseded` below). Without
+// this, a late ack left the client permanently on the losing value and its whole-file save
+// wrote those bytes over everyone else's canvas.
+//
// Together those give: every client ends on the mutation with the highest `seq` for that node.
// Convergence, on any interleaving. What it deliberately does NOT give is intent preservation —
// two people dragging one node still fight, and a delete concurrent with an edit is decided by the
@@ -40,12 +48,17 @@ import type { CanvasMutation } from './types'
/**
* How long an unacked local mutation keeps suppressing peers' mutations for that node.
*
- * Rule 2 above assumes the ack ALWAYS comes back. Almost always it does — but the reflector drops
- * a mutation it cannot validate (an oversized sticky body: MUTATION_MAX_BYTES) and a cast made with
- * no project active never reaches it at all. Without a bound, one such drop would silently deafen
- * that node to its peers for the rest of the session. So a pending entry expires: after this long,
- * the node listens again. Generous next to a round trip (sub-millisecond in-process, single-digit
- * ms over a LAN WS) and short next to a human noticing.
+ * Rule 2 above assumes the ack ALWAYS comes back, and normally it does — but an ack can be LATE
+ * (our socket carries pty output too, and Stage 2 tolerates an 8 MB backlog on it before it gives
+ * up), so the suppression cannot be unbounded: one slow ack would deafen that node to its peers for
+ * the rest of the session. Hence the expiry — a TIME bound on a CORRECTNESS rule, which is only
+ * sound because of RULE 3 below: expiring the suppression is reversible, and the late ack repairs
+ * whatever it cost us. Generous next to a round trip (sub-millisecond in-process, single-digit ms
+ * over a LAN WS) and short next to a human noticing.
+ *
+ * A cast the reflector REFUSES (oversized / malformed) is not this case and must never reach here:
+ * the publisher validates with the same predicate the reflector uses (`isCanvasMutation`) BEFORE
+ * calling `onLocal`, so a refused cast records no pending entry at all.
*/
export const PENDING_TTL_MS = 5000
@@ -70,8 +83,16 @@ export interface CanvasOrder {
interface Pending {
count: number
- /** When the OLDEST still-unacked mutation for this node was cast (for PENDING_TTL_MS). */
+ /** When the MOST RECENT still-unacked mutation for this node was cast (for PENDING_TTL_MS).
+ * Refreshed on every local mutation: a continuous drag emits a frame every 50 ms, and dating the
+ * entry from the OLDEST one expired it mid-drag — after 5 s of dragging, a peer's older frame
+ * would land and rubber-band the node out from under the hand holding it. What the TTL is for is
+ * an ack that is not coming back soon; a drag we are still emitting is not that. */
since: number
+ /** The TTL lapsed: this node no longer suppresses its peers (rule 2 is off), but our casts are
+ * still unacked, so the entry stays — `count` still has to be drawn down by the acks, and rule 3
+ * needs to know they are ours. */
+ stale?: boolean
}
/**
@@ -88,14 +109,25 @@ export function createCanvasOrder(
const seen = new Map<string, number>()
/** Our own casts for a node that have not been echoed back yet. */
const pending = new Map<string, Pending>()
+ /**
+ * RULE 3 — nodes where our optimistic value is NO LONGER on our canvas: the TTL lapsed on one of
+ * our unacked casts and a peer's mutation overwrote it. Rule 1 (drop our own echo) is only sound
+ * while our optimistic value is still showing; here it is not, so the echo — when it finally
+ * arrives — is the ONLY thing that can put back a value that already won on every other client
+ * (it has the higher `seq` there). Dropping it left this client permanently on the LOSING value,
+ * and its whole-file workspace.save then wrote those losing bytes over everyone else's canvas —
+ * the exact save-safety property this stage exists to guarantee. So: while a node is in here, a
+ * late ack is APPLIED rather than dropped, if the total order still says it wins.
+ */
+ const superseded = new Set<string>()
- const hasPending = (id: string): boolean => {
+ /** Is rule 2's suppression live for this node? Lapses on the TTL (the entry stays: see Pending). */
+ const suppressing = (id: string): boolean => {
const p = pending.get(id)
if (!p) return false
+ if (p.stale) return false
if (now() - p.since > ttlMs) {
- // The ack never came (the reflector refused the cast, or the project went away). Stop
- // suppressing this node's peers — a lost ack must not cost us the node forever.
- pending.delete(id)
+ p.stale = true
return false
}
return true
@@ -105,35 +137,57 @@ export function createCanvasOrder(
onLocal(m) {
const id = mutationNodeId(m)
const p = pending.get(id)
- if (p) p.count++
- else pending.set(id, { count: 1, since: now() })
+ if (p) {
+ p.count++
+ p.since = now() // a live drag re-arms its own suppression (see Pending.since)
+ p.stale = false
+ } else {
+ pending.set(id, { count: 1, since: now() })
+ }
+ // A fresh local edit IS an optimistic value on our canvas again, so rule 1 is sound for this
+ // node once more and an older echo of ours must not be replayed over it. (This one's own echo
+ // will be dropped as the ack it is; it carries what we already show.)
+ superseded.delete(id)
},
accept(m) {
const id = mutationNodeId(m)
const seq = m.seq ?? 0
const highest = seen.get(id) ?? 0
+ // `seq` 0 means an unstamped mutation (no reflector in the path) — never treat it as stale.
+ const current = seq === 0 || seq > highest
if (seq > highest) seen.set(id, seq)
if (m.src && m.src === src) {
- // Rule 1: our own mutation, echoed back. It is the ack — consume it, apply nothing.
const p = pending.get(id)
- if (p && --p.count <= 0) pending.delete(id)
- return false
+ // Rule 3: our optimistic value was overwritten by a peer while this cast was in flight (the
+ // TTL had lapsed, so rule 2 no longer held it off). If this echo still wins the total order,
+ // it is a REPAIR, not a rubber-band — apply it and land where every other client already is.
+ const repair = superseded.has(id) && current
+ // Rule 1: otherwise our own echo is just an ack — consume it, apply nothing.
+ if (p && --p.count <= 0) {
+ pending.delete(id)
+ superseded.delete(id) // every cast of ours is accounted for; the node is settled
+ }
+ return repair
}
// A straggler: a mutation the total order has already superseded on this client (applied, or
// deliberately dropped). Applying it would move the node BACKWARDS out of the total order.
- // `seq` 0 means an unstamped mutation (no reflector in the path) — never treat it as stale.
- if (seq !== 0 && seq <= highest) return false
+ if (!current) return false
// Rule 2: an edit of ours for this node is still in flight, so it is later in the total order
// than this one and will win everywhere. Keep ours; the peers will land on it.
- if (hasPending(id)) return false
+ if (suppressing(id)) return false
+ // Applying a peer's mutation over an unacked cast of ours (the TTL lapsed — `suppressing`
+ // just said so, but the entry is still there): remember that our value is gone, so the late
+ // ack can repair it (rule 3).
+ if (pending.has(id)) superseded.add(id)
return true
},
reset() {
seen.clear()
pending.clear()
+ superseded.clear()
}
}
}
diff --git a/src/shared/canvas-publish.test.ts b/src/shared/canvas-publish.test.ts
index e9bc05ebb..3638743a2 100644
--- a/src/shared/canvas-publish.test.ts
+++ b/src/shared/canvas-publish.test.ts
@@ -19,7 +19,10 @@ const node = (id: string, x = 0): CanvasNodeState =>
function collect() {
const sent: CanvasMutation[] = []
- return { sent, send: (m: CanvasMutation) => sent.push(m) }
+ return {
+ sent,
+ send: (m: CanvasMutation): void => void sent.push(m) // void: `send` returning false means REFUSED
+ }
}
beforeEach(() => vi.useFakeTimers())
@@ -119,6 +122,82 @@ describe('createCanvasPublisher', () => {
})
})
+// A cast the reflector would REFUSE (an oversized sticky; a cast with no project active) must not
+// be counted as published: it never reaches a peer, and nothing else would ever re-emit it.
+describe('a refused cast (send → false)', () => {
+ /** Refuses every mutation touching `bad`, records everything it was asked to send. */
+ function gate(bad: string) {
+ const tried: CanvasMutation[] = []
+ const sent: CanvasMutation[] = []
+ const send = (m: CanvasMutation): boolean => {
+ tried.push(m)
+ const id = m.op === 'remove' ? m.id : m.node.id
+ if (id === bad) return false
+ sent.push(m)
+ return true
+ }
+ return { tried, sent, send }
+ }
+
+ it('is retried on the next publish (the baseline does not advance over it)', () => {
+ const c = gate('a')
+ const p = createCanvasPublisher(c.send)
+ p.adopt([node('a')])
+ p.publish([node('a', 5)]) // refused: the peers never see it
+ expect(c.sent).toEqual([])
+ p.publish([node('a', 5)]) // the same snapshot again → still owed, so it is re-emitted
+ expect(c.tried).toHaveLength(2)
+ })
+
+ it('syncs the moment the edit becomes castable again (the user trims the sticky)', () => {
+ let bad = 'a'
+ const sent: CanvasMutation[] = []
+ const p = createCanvasPublisher((m) => {
+ const id = m.op === 'remove' ? m.id : m.node.id
+ if (id === bad) return false
+ sent.push(m)
+ return true
+ })
+ p.adopt([node('a')])
+ p.publish([node('a', 5)]) // oversized → refused
+ expect(sent).toEqual([])
+ bad = '' // trimmed: it fits now
+ p.publish([node('a', 6)])
+ expect(sent).toEqual([{ op: 'upsert', node: node('a', 6) }]) // …and it carries the LIVE value
+ })
+
+ it('does not hold up the other nodes in the same snapshot', () => {
+ const c = gate('a')
+ const p = createCanvasPublisher(c.send)
+ p.adopt([node('a'), node('b')])
+ p.publish([node('a', 5), node('b', 5)])
+ expect(c.sent).toEqual([{ op: 'upsert', node: node('b', 5) }])
+ p.publish([node('a', 5), node('b', 5)])
+ expect(c.sent).toEqual([{ op: 'upsert', node: node('b', 5) }]) // b was cast: not re-sent
+ })
+
+ it('re-emits a refused ADD as an add, and a refused REMOVE as a remove', () => {
+ const c = gate('a')
+ const p = createCanvasPublisher(c.send)
+ p.publish([node('a')]) // an ADD, refused → not in the baseline
+ p.publish([node('a')])
+ expect(c.tried).toEqual([
+ { op: 'upsert', node: node('a') },
+ { op: 'upsert', node: node('a') }
+ ])
+
+ const d = gate('z')
+ const q = createCanvasPublisher(d.send)
+ q.adopt([node('z')])
+ q.publish([]) // a REMOVE, refused → the node stays in the baseline
+ q.publish([])
+ expect(d.tried).toEqual([
+ { op: 'remove', id: 'z' },
+ { op: 'remove', id: 'z' }
+ ])
+ })
+})
+
describe('src (the sender tag)', () => {
// The reflector echoes a mutation back to its sender too — that echo is the ack that carries the
// total order. `src` is how the sender recognizes it as its own rather than re-applying it.
diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.ts
index 1ada3e30c..0a05d6672 100644
--- a/src/shared/canvas-publish.ts
+++ b/src/shared/canvas-publish.ts
@@ -22,6 +22,7 @@
// Pure + DOM-free (vitest runs in the node environment): only setTimeout, no React, no window.
import { diffToMutations } from './canvas-mutations'
+import { mutationNodeId } from './canvas-order'
import type { CanvasMutation, CanvasNodeState } from './types'
/** ~20 Hz while dragging — the same budget the presence cursor stream uses. */
@@ -42,7 +43,44 @@ export interface CanvasPublisher {
}
/**
- * @param send casts one mutation (already stamped with `src`).
+ * The baseline after a cast was REFUSED (`send` returned false: an oversized sticky the reflector
+ * would drop at ingest, or no active project to cast into). The refused nodes keep their PREVIOUS
+ * baseline entry — as if the edit had never been published — so the very next diff emits them again
+ * and the edit syncs the moment it becomes castable (the user trims the sticky, a project opens).
+ * Advancing the baseline over them, which is what the publisher used to do, meant the edit was
+ * dropped SILENTLY AND FOREVER: the peers never saw it and nothing ever retried it.
+ *
+ * Per NODE, not per snapshot: everything else in the same snapshot was cast and must not be re-sent.
+ * A refused node that had no previous entry is simply left OUT of the baseline (so it re-diffs as an
+ * add); a refused `remove` keeps its node in the baseline (so the remove is re-emitted).
+ */
+function rebaseRefused(
+ prev: CanvasNodeState[],
+ next: CanvasNodeState[],
+ refused: Set<string>
+): CanvasNodeState[] {
+ const prevById = new Map(prev.map((n) => [n.id, n]))
+ const nextIds = new Set(next.map((n) => n.id))
+ const out: CanvasNodeState[] = []
+ for (const n of next) {
+ if (!refused.has(n.id)) {
+ out.push(n)
+ continue
+ }
+ const before = prevById.get(n.id)
+ if (before) out.push(before)
+ }
+ for (const n of prev) {
+ if (refused.has(n.id) && !nextIds.has(n.id)) out.push(n) // a refused remove: still owed
+ }
+ return out
+}
+
+/**
+ * @param send casts one mutation (already stamped with `src`). Returning `false` means the
+ * cast did NOT happen (refused / no project): the mutation is then owed — its
+ * node keeps its old baseline entry and the next publish retries it. Any other
+ * return value (including `undefined`) means it was cast.
* @param opts.src this client's publisher tag, stamped onto every mutation it sends, so it can
* recognize its own echo coming back (see canvas-order). Omitted in tests that
* only care about the diff.
@@ -55,7 +93,7 @@ export interface CanvasPublisher {
* there is no resync step and no missed mutation. Default: always publish.
*/
export function createCanvasPublisher(
- send: (m: CanvasMutation) => void,
+ send: (m: CanvasMutation) => void | boolean,
opts: { intervalMs?: number; src?: string; shouldPublish?: () => boolean } = {}
): CanvasPublisher {
const intervalMs = opts.intervalMs ?? PUBLISH_INTERVAL_MS
@@ -70,8 +108,11 @@ export function createCanvasPublisher(
return
}
const mutations = diffToMutations(last, next)
- last = next
- for (const m of mutations) send(opts.src ? { ...m, src: opts.src } : m)
+ const refused = new Set<string>()
+ for (const m of mutations) {
+ if (send(opts.src ? { ...m, src: opts.src } : m) === false) refused.add(mutationNodeId(m))
+ }
+ last = refused.size ? rebaseRefused(last, next, refused) : next
}
const onTimer = (): void => {