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(kanban): boards sync live, item by item, from the one store funnel

review7520f7098c0d
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.ts
index bfcc3ca12..f84025b09 100644
--- a/src/core/canvas-sync.convergence.test.ts
+++ b/src/core/canvas-sync.convergence.test.ts
@@ -34,8 +34,11 @@ import {
PENDING_TTL_MS
} from '../shared/canvas-order'
import { createCanvasPublisher, publishableScene } from '../shared/canvas-publish'
+import { applyCanvasOp, type CanvasContent } from '../shared/canvas-content'
+import { defaultKanbanFor } from '../shared/kanban-default-board'
+import { applyKanbanOp, diffKanbanOps, isKanbanOp, sanitizeKanbanOp } from '../shared/kanban-ops'
import { IPC } from '../shared/ipc'
-import type { BridgeLink, CanvasMutation, CanvasNodeState } from '../shared/types'
+import type { BridgeLink, CanvasMutation, CanvasNodeState, ProjectKanban } from '../shared/types'
const node = (id: string, x: number, title = 't', color = '#fff'): CanvasNodeState =>
({
@@ -156,12 +159,19 @@ class Client {
ropes: BridgeLink[] = []
/** Ephemeral cards (subagent / loop) this client renders — derived locally, never published. */
ephemeral = new Set<string>()
+ /** The project's board. Absent = the deterministic lazy default, exactly as a project whose file
+ * has no `kanban` block — so it is part of what converges, like the edge lists. */
+ board: ProjectKanban | undefined = undefined
+ /** Every mutation this client CAST, in order (after its own gates) — what a test reads to prove a
+ * rule held on the SENDING side, e.g. that a prune removal never left this client. */
+ readonly cast: CanvasMutation[] = []
/** 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>
+ private readonly src: string
/** Mirrors Canvas's presence subscription: reset the order state only on a GENUINE reconnect. */
private readonly reconnected = createReconnectWatch(null)
@@ -173,33 +183,13 @@ 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.src = 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.
- // Stamp our causal position FIRST, so the guard judges the exact payload that is cast
- // (canvas-order rule 4 — `seen` is what lets a delete beat a concurrent drag frame).
- const stamped = this.order.stamp(m)
- // The re-creation gate, as Canvas has it: a re-creation of a key whose remove of ours is
- // still unacked would carry a `seen` below that remove — held (owed) until the echo lands.
- // The project rides every key the order builds (ruling R4: a board's order ops are
- // per-project singletons) — the same PROJECT the cast goes out on.
- if (!isRemoveOp(stamped) && this.order.hasPendingRemove(mutationKey(stamped, PROJECT))) return false
- if (!isCanvasMutation(stamped)) {
- this.refused++
- return false
- }
- this.order.onLocal(stamped, PROJECT)
- bus.cast(id, PROJECT, stamped)
- return true
- },
- { src }
- )
+ // Mirrors Canvas: the node/edge publisher and the board publisher cast through ONE send
+ // (`castFor`), so both families are stamped, gated and recorded by the same order.
+ this.pub = createCanvasPublisher((m) => this.send(m), { src })
bus.deliver.set(id, (projectId, m) => {
if (projectId !== PROJECT) return
// Mirrors Canvas: our own remove coming back RELEASES a re-creation the gate held — cast it now,
@@ -208,7 +198,12 @@ class Client {
const held = this.order.hasPendingRemove(key)
const apply = this.order.accept(m, projectId)
const released = held && !this.order.hasPendingRemove(key)
- if (apply) {
+ if (apply && isKanbanOp(m)) {
+ // Mirrors Canvas: a board op lands in the projects STORE through the one reducer — never
+ // through the board funnel, whose publish hook would cast it again — and touches no node.
+ this.applied++
+ this.board = applyCanvasOp(this.content(), m, PROJECT).kanban
+ } else if (apply) {
this.applied++
this.states = applyCanvasMutation(this.states, m)
// One id is one edge across both lists — what Canvas and the projects store apply.
@@ -221,6 +216,35 @@ class Client {
})
}
+ /** THE ONE CAST — Canvas's `castFor`, for the one project this harness has: stamp `src` + `seen`,
+ * the re-creation gate, the reflector's own predicate, then record it as pending and cast. */
+ private send(m: CanvasMutation): boolean {
+ // 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.
+ // Stamp our causal position FIRST, so the guard judges the exact payload that is cast
+ // (canvas-order rule 4 — `seen` is what lets a delete beat a concurrent drag frame).
+ const stamped = this.order.stamp({ ...m, src: this.src })
+ // The re-creation gate, as Canvas has it: a re-creation of a key whose remove of ours is
+ // still unacked would carry a `seen` below that remove — held (owed) until the echo lands.
+ // The project rides every key the order builds (ruling R4: a board's order ops are
+ // per-project singletons) — the same PROJECT the cast goes out on.
+ if (!isRemoveOp(stamped) && this.order.hasPendingRemove(mutationKey(stamped, PROJECT))) return false
+ if (!isCanvasMutation(stamped)) {
+ this.refused++
+ return false
+ }
+ this.order.onLocal(stamped, PROJECT)
+ this.cast.push(stamped)
+ this.bus.cast(this.id, PROJECT, stamped)
+ return true
+ }
+
+ private content(): CanvasContent {
+ return { nodes: this.states, bridges: this.bridges, ropes: this.ropes, ...(this.board ? { kanban: this.board } : {}) }
+ }
+
private publishable(): CanvasScene {
return publishableScene(
{ nodes: this.states, bridges: this.bridges, ropes: this.ropes },
@@ -242,6 +266,24 @@ class Client {
this.pub.publish(this.publishable())
}
+ /** A local BOARD edit — what `useProjects.setProjectKanban` + the kanban publisher do
+ * (renderer/canvas/kanban-sync.ts): diff the board item by item against this client's OWN nodes
+ * (a card whose node is not live here is pruned locally and its removal is never cast), cast the
+ * clean form of each op through the same send, and keep that clean form locally when the board
+ * held something else (ruling R2: the reflector repairs what it relays and our own echo is only
+ * an ack, so an unrepaired local value would be ours alone, for good). */
+ editBoard(next: ProjectKanban): void {
+ const prev = this.board
+ this.board = next
+ const live = new Set(this.states.map((n) => n.id))
+ for (const op of diffKanbanOps(prev, next, PROJECT, live)) {
+ const clean = sanitizeKanbanOp(op)
+ if (!clean) continue
+ if (this.send(clean) && stableJson(clean) !== stableJson(op))
+ this.board = applyCanvasOp(this.content(), clean, PROJECT).kanban
+ }
+ }
+
/** 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. */
@@ -280,6 +322,15 @@ class Client {
* node set all agree, so either client's save writes a canvas the other agrees with. Documented as
* such in docs/team-presence.md; use this helper wherever a resurrection can happen.
*/
+/** JSON with sorted keys — "the same op" as the kanban publisher judges it (key order is not a change). */
+function stableJson(v: unknown): string {
+ return JSON.stringify(v, (_k, val: unknown) =>
+ val && typeof val === 'object' && !Array.isArray(val)
+ ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, (val as Record<string, unknown>)[k]]))
+ : val
+ )
+}
+
const canon = (c: Client): CanvasNodeState[] =>
[...c.persisted().nodes].sort((x, y) => x.id.localeCompare(y.id))
@@ -901,3 +952,204 @@ describe('canvas convergence (async bus)', () => {
expect(b.ids()).toEqual(['n2'])
})
})
+
+// ---- boards (kanban) ----
+// The board is canvas content too: `.nodeterm/project.json` carries it beside the nodes, so a peer's
+// next whole-file save writes whatever board THAT peer holds. Item-level ops ride the same bus, the
+// same reflector `seq` and the same order as nodes, under their own `k:` keys (@shared/kanban-ops).
+describe('boards converge like nodes (kanban ops)', () => {
+ const COLS = defaultKanbanFor(PROJECT).columns
+ const TODO = COLS[0].id
+ const DOING = COLS[1].id
+ const DONE = COLS[2].id
+
+ /** `board` with `nodeId` filed into `columnId` — a person's drag, as the board computes it. */
+ const file = (board: ProjectKanban | undefined, nodeId: string, columnId: string): ProjectKanban =>
+ applyKanbanOp(board, { op: 'kb-card', assignment: { nodeId, columnId } }, PROJECT)
+
+ /** What the board UI does to every commit (renderer lib/kanban `pruneAssignments`): drop the cards
+ * and meta of nodes this client does not hold. A LOCAL, lazy cleanup — never an edit. */
+ const prune = (board: ProjectKanban, live: string[]): ProjectKanban => ({
+ ...board,
+ assignments: board.assignments.filter((a) => live.includes(a.nodeId)),
+ ...(board.meta ? { meta: board.meta.filter((m) => live.includes(m.nodeId)) } : {})
+ })
+
+ /** The column a card SHOWS in: its assignment's column when that column exists, else null — the
+ * virtual Ungrouped column, which holds unassigned AND dangling cards alike. */
+ const where = (c: Client, nodeId: string): string | null => {
+ const board = c.board ?? defaultKanbanFor(PROJECT)
+ const a = board.assignments.find((x) => x.nodeId === nodeId)
+ return a && board.columns.some((col) => col.id === a.columnId) ? a.columnId : null
+ }
+
+ /** The board as a person sees it: the columns in order, and each column's cards in order. */
+ const shown = (c: Client) => {
+ const board = c.board ?? defaultKanbanFor(PROJECT)
+ return board.columns.map((col) => ({
+ id: col.id,
+ title: col.title,
+ cards: board.assignments.filter((a) => a.columnId === col.id).map((a) => a.nodeId)
+ }))
+ }
+
+ const kbCast = (c: Client, op: string) => c.cast.filter((m) => m.op === op)
+
+ it('1. A and B each move a DIFFERENT card at the same time → both moves land on both', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ bus.settle()
+ a.editBoard(file(file(undefined, 'n1', TODO), 'n2', TODO))
+ bus.settle()
+ expect(b.board).toEqual(a.board)
+ expect(b.cast).toEqual([]) // B applied A's board ops and cast nothing back (never re-published)
+
+ // Neither hears the other before it commits: both inboxes stalled, both casts in flight.
+ bus.stall(1)
+ bus.stall(2)
+ a.editBoard(file(a.board, 'n1', DOING))
+ b.editBoard(file(b.board, 'n2', DONE))
+ bus.settle()
+ bus.unstall(1)
+ bus.unstall(2)
+ bus.settle()
+
+ for (const c of [a, b]) {
+ expect(where(c, 'n1')).toBe(DOING)
+ expect(where(c, 'n2')).toBe(DONE)
+ }
+ expect(shown(a)).toEqual(shown(b))
+ })
+
+ it('2. A and B move the SAME card concurrently → both end on the higher-seq column', () => {
+ a.edit([node('n1', 0)])
+ bus.settle()
+ a.editBoard(file(undefined, 'n1', TODO))
+ bus.settle()
+
+ a.editBoard(file(a.board, 'n1', DOING)) // cast first → the lower seq
+ b.editBoard(file(b.board, 'n1', DONE)) // cast second → the higher seq, wins everywhere
+ bus.settle()
+ expect(where(a, 'n1')).toBe(DONE)
+ expect(where(b, 'n1')).toBe(DONE)
+ expect(shown(a)).toEqual(shown(b))
+
+ // …and the other way round.
+ b.editBoard(file(b.board, 'n1', TODO))
+ a.editBoard(file(a.board, 'n1', DOING))
+ bus.settle()
+ expect(where(a, 'n1')).toBe(DOING)
+ expect(where(b, 'n1')).toBe(DOING)
+ })
+
+ it('3. a first-ever board edit made by both at once → three columns on both (deterministic ids)', () => {
+ a.edit([node('n1', 0), node('n2', 0)])
+ bus.settle()
+ expect(a.board).toBeUndefined()
+ expect(b.board).toBeUndefined()
+
+ a.editBoard(file(undefined, 'n1', TODO))
+ b.editBoard(file(undefined, 'n2', DOING))
+ bus.settle()
+
+ for (const c of [a, b]) {
+ expect(c.board?.columns.map((col) => col.id)).toEqual(COLS.map((col) => col.id))
+ expect(where(c, 'n1')).toBe(TODO)
+ expect(where(c, 'n2')).toBe(DOING)
+ }
+ // The lazy default is the same board on both, so materializing it casts no column at all — a
+ // random id per client would have cast three columns each and left six on every board.
+ expect([...kbCast(a, 'kb-column'), ...kbCast(b, 'kb-column'), ...kbCast(a, 'kb-column-order'), ...kbCast(b, 'kb-column-order')]).toEqual([])
+ expect(shown(a)).toEqual(shown(b))
+ })
+
+ it('4. B commits a board edit while A’s card for a new node is still in flight → no kb-card-remove, the card placed on both', () => {
+ a.edit([node('m', 0)])
+ bus.settle()
+ a.editBoard(file(undefined, 'm', TODO))
+ bus.settle()
+
+ // A creates n and files its card (the node op leaves first, as the spec's batch order has it);
+ // neither has reached B.
+ bus.stall(2)
+ a.edit([...a.states, node('n', 0)])
+ a.editBoard(file(a.board, 'n', DOING))
+ // B, meanwhile, moves m — and prunes, as every board commit does, against its OWN nodes.
+ b.editBoard(prune(file(b.board, 'm', DONE), b.ids()))
+ expect(kbCast(b, 'kb-card-remove')).toEqual([])
+ bus.settle()
+ bus.unstall(2)
+ bus.settle()
+
+ for (const c of [a, b]) {
+ expect(where(c, 'n')).toBe(DOING)
+ expect(where(c, 'm')).toBe(DONE)
+ }
+ expect(shown(a)).toEqual(shown(b))
+ })
+
+ // The same rule on the arrival order the live canvas produces: a board write is published the
+ // moment the store funnel runs, a new node only after React renders it — so a peer can hold the
+ // CARD of a node it has not received yet. Its commit prunes that card locally (the board UI prunes
+ // every commit), and the removal is never cast: every replica that did not prune keeps the card.
+ // The pruning client's own copy is the local, lazy cleanup spec amendment 6 accepts.
+ it('4b. a card that arrives before its node survives a peer that prunes it (the removal is never cast)', () => {
+ const c = new Client(3, bus)
+ bus.clients = [1, 2, 3]
+ a.edit([node('m', 0)])
+ bus.settle()
+ a.editBoard(file(undefined, 'm', TODO))
+ bus.settle()
+
+ a.editBoard(file(a.board, 'n', DOING)) // the card, before the node op has left A
+ bus.settle()
+ expect(b.board?.assignments.some((x) => x.nodeId === 'n')).toBe(true) // B holds it, without n
+ bus.stall(2)
+ a.edit([...a.states, node('n', 0)]) // the node op, held in B's inbox
+ b.editBoard(prune(file(b.board, 'm', DONE), b.ids()))
+ expect(kbCast(b, 'kb-card-remove')).toEqual([]) // the prune stayed local
+ bus.settle()
+ bus.unstall(2)
+ bus.settle()
+
+ expect(where(a, 'n')).toBe(DOING)
+ expect(where(c, 'n')).toBe(DOING)
+ for (const x of [a, b, c]) expect(where(x, 'm')).toBe(DONE)
+ })
+
+ it('5. A deletes a column while B moves a card into it → the column is gone, the card Ungrouped on both', () => {
+ for (const bFirst of [false, true]) {
+ boot()
+ a.edit([node('n', 0)])
+ bus.settle()
+ a.editBoard(file(undefined, 'n', TODO))
+ bus.settle()
+
+ const drop = (board: ProjectKanban): ProjectKanban => ({
+ ...board,
+ columns: board.columns.filter((col) => col.id !== DONE),
+ assignments: board.assignments.filter((x) => x.columnId !== DONE)
+ })
+ const tag = bFirst ? 'B ordered first' : 'A ordered first'
+ if (bFirst) b.editBoard(file(b.board, 'n', DONE)) // B had not seen the delete
+ a.editBoard(drop(a.board!))
+ if (!bFirst) b.editBoard(file(b.board, 'n', DONE))
+ bus.settle()
+
+ for (const x of [a, b]) {
+ expect(x.board?.columns.map((col) => col.id), tag).toEqual([TODO, DOING])
+ expect(where(x, 'n'), tag).toBeNull()
+ }
+ expect(shown(a), tag).toEqual(shown(b))
+ }
+ })
+
+ // Ruling R2: the reflector relays the REPAIRED op and the sender drops its own echo as an ack, so
+ // the sender must hold the repaired value too — or its board shows a name no peer has.
+ it('6. an over-long label name lands cut on every board, the sender’s included', () => {
+ a.editBoard({ ...defaultKanbanFor(PROJECT), labels: [{ id: 'lab-1', name: 'x'.repeat(90), color: 'red' }] })
+ bus.settle()
+ expect(a.board?.labels).toEqual([{ id: 'lab-1', name: 'x'.repeat(60), color: 'red' }])
+ expect(b.board?.labels).toEqual(a.board?.labels)
+ expect(a.cast.filter((m) => m.op === 'kb-label')).toHaveLength(1) // repaired locally, not re-cast
+ })
+})
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 0ed2bc93f..8aee3e71f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -401,7 +401,7 @@ import {
shouldShowExplorerPinHint,
writeSeenExplorerPinHint
} from '../lib/explorerPinHint'
-import { useProjects } from '../state/projects'
+import { setKanbanPublishHook, useProjects } from '../state/projects'
import { useAgentStatus } from '../state/agentStatus'
import { hostChatSend, hostChatSession, hostChatStatus } from '../lib/hostChatQuery'
import { chatPaneRefusal } from '../lib/chatPaneGate'
@@ -618,6 +618,7 @@ import { snapNodeToGrid } from '../lib/nodeSizing'
import { snapResizeChanges } from '../lib/resizeSnap'
import { canClearDirty, canCommitCanvas, canCreateOnCanvas, liveCanvasHolds } from '../state/persistGuards'
import { rebaseOnLatest, useNodesEpoch } from './nodesEpoch'
+import { createKanbanPublisher } from './kanban-sync'
import { isHidden } from '../lib/ui-visibility'
import { boardLogEvents } from '../lib/boardLogDiff'
import { useBoardLog } from '../state/boardLog'
@@ -644,6 +645,7 @@ import {
isEdgeMutation,
type CanvasScene
} from '@shared/canvas-mutations'
+import { isKanbanOp } from '@shared/kanban-ops'
import { chordHeld, isHoldChord, isModifierEventKey, matchesShortcut } from '@shared/shortcut'
// The dispatch below is the CONSUMER of the confirm-gated set. Before this import the set named
@@ -3117,10 +3119,10 @@ export function Canvas() {
return card ? card.title || 'Untitled' : ''
}
for (const { nodeId, event } of boardLogEvents(prev, next, cardTitle)) {
- useBoardLog.getState().append(api, id, { kind: 'event', nodeId, event })
+ useBoardLog.getState().append(sessionForProject(id).api, id, { kind: 'event', nodeId, event })
}
},
- [markDirty, api]
+ [markDirty]
)
// The board moving a session card by itself because every pull request linked to it merged
@@ -3139,13 +3141,13 @@ export function Canvas() {
markDirty()
const title = (id: string | null): string =>
(id && current.columns.find((column) => column.id === id)?.title) || 'Ungrouped'
- useBoardLog.getState().append(api, projectId, {
+ useBoardLog.getState().append(sessionForProject(projectId).api, projectId, {
kind: 'event',
nodeId: cardId,
event: { type: 'card-moved', from: title(fromColumnId), to: title(toColumnId), title: note }
})
},
- [markDirty, api]
+ [markDirty]
)
// The node states that go on the wire: React Flow's managed nodes minus the ephemeral cards
@@ -3658,6 +3660,25 @@ export function Canvas() {
// the SAS-approval effect above — one feeds the dialog, this one feeds the live/pending seats store.
useTeamAccessEvents()
+ /**
+ * Apply ONE op to a project's STORED copy, through the store reducer (`applyCanvasOp`) — never
+ * through `setProjectKanban`, whose publish hook would cast it again. The path for a peer's op on
+ * a project React Flow does not hold, for EVERY peer board op (the board reads the store, not
+ * React Flow), and for the kanban publisher's local repair (ruling R2). Save only when that copy
+ * actually changed: the store writes nothing for an op that changes nothing (a duplicate cast —
+ * every Server Edition tab re-casts what it receives — or a remove of something already gone), so
+ * the project object's identity is the answer, and a no-op schedules no save.
+ */
+ const applyToStored = useCallback(
+ (projectId: string, mutation: CanvasMutation): void => {
+ const store = useProjects.getState()
+ const before = store.getProject(projectId)
+ if (store.applyCanvasOp(projectId, mutation) && useProjects.getState().getProject(projectId) !== before)
+ markDirty()
+ },
+ [markDirty]
+ )
+
// ---- canvas sync (team) ----
// Emitting side: diff each settled node snapshot against the last one we published and cast the
// mutations on `canvas:mut`. The core reflector (src/core/canvas-sync.ts) fans each one out to
@@ -3717,54 +3738,105 @@ export function Canvas() {
// ~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()
+ /**
+ * The node ids live in `projectId` — what the kanban publisher's prune rule asks (a card whose
+ * node is not live is pruned locally and its removal NEVER cast). One project's set, never a mix:
+ * the project React Flow holds answers from the epoch pair (`nodesRef` is that project's canvas
+ * exactly while `nodesProjectIdRef` names it — useNodesEpoch), every other project from its
+ * stored copy (a project mid-load is still the store's until the load installs it).
+ */
+ const liveNodeIdsFor = (projectId: string): ReadonlySet<string> =>
+ new Set(
+ (nodesProjectIdRef.current === projectId
+ ? nodesRef.current
+ : (useProjects.getState().getProject(projectId)?.nodes ?? [])
+ ).map((n) => n.id)
+ )
+ /**
+ * THE ONE CAST on canvas:mut, for every family this Canvas publishes — nodes and edges (the
+ * canvas publisher, for the active project) and board ops (the kanban publisher, for whichever
+ * project a board write touched: the Omni board and node labels write background projects too).
+ *
+ * Only a project on the core this effect is bound to. `order` hears ONE core's echoes — the
+ * receive effect below subscribes `activeSession.api` and nothing else — so rule 1 (our echo is
+ * our ack) holds only there, and `seen` is a position in THAT core's `seq`. Cast anywhere else, a
+ * pending entry would wait for an echo nobody listens to, and `seen` would be judged against
+ * another core's counter. `sessionForProject(projectId)` is the session the project belongs to
+ * (a relay tab → its host), so on a match the cast target below IS that session's api.
+ */
+ const castFor = (projectId: string, m: CanvasMutation): boolean => {
+ if (sessionForProject(projectId).api !== activeSession.api) return false
+ // Stamp our causal position FIRST (canvas-order rule 4: what we had applied when we cast —
+ // it is what lets a teammate's delete beat this frame instead of being resurrected by it),
+ // so the size guard below judges the EXACT payload that goes on the wire. `stamp` is pure:
+ // a refusal still records no pending entry.
+ const stamped = order.stamp({ ...m, src })
+ // THE RE-CREATION GATE (canvas-order `hasPendingRemove`): our own remove of this key has not
+ // come back yet, so it is not in our `seen` — a re-creation cast now (a link redrawn, a node
+ // ⌘Z'd, within one round trip) would be dropped by every peer as a stale frame while we keep
+ // showing it. Held = owed: the publisher keeps it, and the receive handler's release casts it
+ // the moment the remove's echo lands. Never a remove itself (a remove is never stale).
+ // The key carries the project it is cast into: a board's two order ops are per-project
+ // singletons in the ONE order this Canvas keeps for every loaded project (ruling R4).
+ if (!isRemoveOp(stamped) && order.hasPendingRemove(mutationKey(stamped, projectId))) return false
+ // 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. ONLY for a node upsert, though: an
+ // edge op (or a remove) is refused only for a malformed / over-long id, and "this note is
+ // too large" would name a cause nobody measured.
+ if (!guard(stamped)) {
+ if (stamped.op === 'upsert') 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.'
+ )
+ else console.warn('[canvas-sync] refused an unsendable mutation', stamped.op)
+ return false
+ }
+ order.onLocal(stamped, projectId)
+ // Cast to the project's session's core — a relay tab publishes to the relay HOST, not to its
+ // own local core. Byte-identical on a local tab (`activeSession.api` IS `window.nodeTerminal`).
+ // `canvasSyncTarget` decides the GATE (hasPeers) at bind time; the cast target is just the
+ // session's api, so reach it directly — no per-cast allocation on this ~20 Hz path.
+ activeSession.api.canvas.mutate(projectId, stamped)
+ return true
+ }
+ /**
+ * THE ONE PUBLISH GATE, asked by the node publisher (for the active project) and the kanban
+ * publisher (for the project a board write touched). Someone else must be attached (the solo
+ * gate), the project must be on the core this effect casts to (see `castFor`), and a hosted
+ * Viewer/Commenter publishes nothing: the host refuses canvas:mut for them (R5).
+ */
+ const shouldPublishFor = (projectId: string): boolean =>
+ sessionForProject(projectId).api === activeSession.api &&
+ hasPeersRef.current &&
+ !isHostedReadOnly(activeSession.id)
const pub = createCanvasPublisher(
(m) => {
const projectId = useProjects.getState().activeProjectId
if (!projectId) return false // no active canvas: nothing was cast — retry on the next publish
- // Stamp our causal position FIRST (canvas-order rule 4: what we had applied when we cast —
- // it is what lets a teammate's delete beat this frame instead of being resurrected by it),
- // so the size guard below judges the EXACT payload that goes on the wire. `stamp` is pure:
- // a refusal still records no pending entry.
- const stamped = order.stamp(m)
- // THE RE-CREATION GATE (canvas-order `hasPendingRemove`): our own remove of this key has not
- // come back yet, so it is not in our `seen` — a re-creation cast now (a link redrawn, a node
- // ⌘Z'd, within one round trip) would be dropped by every peer as a stale frame while we keep
- // showing it. Held = owed: the publisher keeps it, and the receive handler's release casts it
- // the moment the remove's echo lands. Never a remove itself (a remove is never stale).
- // The key carries the project it is cast into: a board's two order ops are per-project
- // singletons in the ONE order this Canvas keeps for every loaded project (ruling R4).
- if (!isRemoveOp(stamped) && order.hasPendingRemove(mutationKey(stamped, projectId))) return false
- // 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. ONLY for a node upsert, though: an
- // edge op (or a remove) is refused only for a malformed / over-long id, and "this note is
- // too large" would name a cause nobody measured.
- if (!guard(stamped)) {
- if (stamped.op === 'upsert') 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.'
- )
- else console.warn('[canvas-sync] refused an unsendable mutation', stamped.op)
- return false
- }
- order.onLocal(stamped, projectId)
- // 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` decides the GATE (hasPeers) at bind time;
- // the cast target is just the session's api, so reach it directly — no per-cast allocation
- // on this ~20 Hz path.
- activeSession.api.canvas.mutate(projectId, stamped)
- return true
+ return castFor(projectId, m)
},
- // A hosted Viewer/Commenter publishes nothing: the host refuses canvas:mut for them (R5).
- { src, shouldPublish: () => hasPeersRef.current && !isHostedReadOnly(activeSession.id) }
+ { src, shouldPublish: () => shouldPublishFor(useProjects.getState().activeProjectId) }
)
publisherRef.current = pub
+ // Boards (spec §5, §11.3): every board write goes through `setProjectKanban`, and the store
+ // calls this hook after it — so the board, the card modal, the Omni board, node labels and the
+ // `assign` verb all publish here, through the same cast and the same gate as the nodes. A peer's
+ // board op is applied with the store REDUCER (the receive effect below), which never calls the
+ // hook: nothing received is ever published again.
+ const kanbanPublisher = createKanbanPublisher({
+ send: (projectId, m) => castFor(projectId, m),
+ liveNodeIds: (projectId) => liveNodeIdsFor(projectId),
+ shouldPublish: (projectId) => shouldPublishFor(projectId),
+ applyLocal: (projectId, m) => applyToStored(projectId, m)
+ })
+ setKanbanPublishHook((id, prev, next) => kanbanPublisher.publish(id, prev, next))
return () => {
+ setKanbanPublishHook(null)
unsub()
pub.dispose()
publisherRef.current = null
@@ -3773,7 +3845,8 @@ export function Canvas() {
// 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])
+ // `applyToStored` is stable for the Canvas's lifetime (it depends on `markDirty` alone).
+ }, [activeSession.api, applyToStored])
// 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 /
@@ -3836,16 +3909,6 @@ export function Canvas() {
if (!pub || !pub.hasOwed() || loadingRef.current) return
pub.publish(publishableLater(nodesRef.current))
}
- // A peer op for a project React Flow does not hold lands in its STORED copy. Save only when
- // that copy actually changed: the store writes nothing for an op that changes nothing (a
- // duplicate cast — every Server Edition tab re-casts what it receives — or a remove of something
- // already gone), so the project object's identity is the answer, and a no-op schedules no save.
- const applyToStored = (projectId: string, mutation: CanvasMutation): void => {
- const store = useProjects.getState()
- const before = store.getProject(projectId)
- if (store.applyCanvasOp(projectId, mutation) && useProjects.getState().getProject(projectId) !== before)
- markDirty()
- }
return activeSession.api.canvas.onMutation((projectId, mutation) => {
hasPeersRef.current = true // proof of a peer, whatever the presence table says
const order = orderRef.current
@@ -3856,6 +3919,15 @@ export function Canvas() {
const released = held && !order.hasPendingRemove(key)
if (released) queueMicrotask(releaseHeld)
if (!apply) return
+ // ---- the board (kanban) ----
+ // Into the projects STORE, for the active project and a background one alike: the board, the
+ // column pills and the card modal all read the store live, and React Flow holds no board. The
+ // store reducer, never `setProjectKanban` — its publish hook would re-cast a peer's op as ours
+ // — and no board-log entry: only the client that made the change records it (spec §5).
+ if (isKanbanOp(mutation)) {
+ applyToStored(projectId, mutation)
+ return
+ }
// ---- edges (context links + "spawned by" ropes) ----
// They live outside React Flow's `nodes` array, in their own state, so they take their own
// apply path — but everything around it is the node path's contract, unchanged: the ordering
@@ -3957,7 +4029,7 @@ export function Canvas() {
setNodes(rebaseOnLatest(base, flow, (ns) => applyMutationToFlow(ns as CanvasNode[], mutation)))
markDirty()
})
- }, [activeSession.api, setNodes, setLinkEdges, setControlEdges, markDirty, publishableLater])
+ }, [activeSession.api, setNodes, setLinkEdges, setControlEdges, markDirty, publishableLater, applyToStored])
// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).
useEffect(() => {
@@ -6103,9 +6175,9 @@ export function Canvas() {
) => {
if (!node.issueRef) return
const entry = runEndedEntry(node.issueRef, node, useAgentStatus.getState().byId[node.id])
- if (entry) useBoardLog.getState().append(api, projectId, entry)
+ if (entry) useBoardLog.getState().append(sessionForProject(projectId).api, projectId, entry)
},
- [api]
+ []
)
const deleteNodes = useCallback(
@@ -10502,13 +10574,13 @@ export function Canvas() {
?.label ??
choice.agentId
const title = (node.data.title as string) || kindLabel
- useBoardLog.getState().append(api, targetProjectId, {
+ useBoardLog.getState().append(sessionForProject(targetProjectId).api, targetProjectId, {
kind: 'event',
nodeId: node.id,
event: { type: 'card-created', to: toName, title }
})
},
- [emptyNodePos, setNodes, markDirty, api]
+ [emptyNodePos, setNodes, markDirty]
)
// ---- GitHub issue → agent session ("Start with agent ▸") ----
@@ -10542,7 +10614,7 @@ export function Canvas() {
useSettings.getState().settings.customAgents.find((a) => a.id === agentId)?.label ||
agentId
// The session card's own feed says where it came from, exactly like a "+ New" card…
- useBoardLog.getState().append(api, targetProjectId, {
+ useBoardLog.getState().append(sessionForProject(targetProjectId).api, targetProjectId, {
kind: 'event',
nodeId,
event: { type: 'card-created', to: column?.title ?? 'Ungrouped', title }
@@ -10555,9 +10627,9 @@ export function Canvas() {
agentId,
agentSessionId: node.data.agentSessionId as string | undefined
})
- if (started) useBoardLog.getState().append(api, targetProjectId, started)
+ if (started) useBoardLog.getState().append(sessionForProject(targetProjectId).api, targetProjectId, started)
},
- [markDirty, api]
+ [markDirty]
)
/** The reference + first prompt of an issue start, or a notice saying why nothing started. The
@@ -11286,7 +11358,7 @@ export function Canvas() {
agentId: n.data.agentId as string | undefined,
agentSessionId: n.data.agentSessionId as string | undefined
})
- if (entry) useBoardLog.getState().append(api, projectId, entry)
+ if (entry) useBoardLog.getState().append(sessionForProject(projectId).api, projectId, entry)
}
}
// Resolved ONCE, HERE — before any open path below snapshots the projects store. A `#N` may
@@ -14253,7 +14325,7 @@ export function Canvas() {
return card ? card.title || 'Untitled' : ''
}
for (const { nodeId: nid, event } of boardLogEvents(prev, next, cardTitle)) {
- useBoardLog.getState().append(api, pid, { kind: 'event', nodeId: nid, event })
+ useBoardLog.getState().append(sessionForProject(pid).api, pid, { kind: 'event', nodeId: nid, event })
}
// Handoff pings (lib/handoffPings): an agent filing a card ASSIGNED TO THIS USER into a
// handoff column (a done column, or a started one past the first) tells them — through the
diff --git a/src/renderer/canvas/canvas-sync-ordering.source.test.ts b/src/renderer/canvas/canvas-sync-ordering.source.test.ts
index 6a1744350..e78726057 100644
--- a/src/renderer/canvas/canvas-sync-ordering.source.test.ts
+++ b/src/renderer/canvas/canvas-sync-ordering.source.test.ts
@@ -6,9 +6,12 @@ import { readFileSync } from 'node:fs'
import { describe, it, expect } from 'vitest'
const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
-/** The publisher's send callback, from its creation to the cast. */
+/** The ONE cast both publishers send through (`castFor` — the node/edge publisher for the active
+ * project, the kanban publisher for whichever project a board write touched), from its creation to
+ * the cast. Task 6 moved the body here out of the node publisher's own send callback. */
function sendCallback(): string {
- const start = src.indexOf('const pub = createCanvasPublisher(')
+ const start = src.indexOf('const castFor = (projectId: string, m: CanvasMutation): boolean => {')
+ expect(start).toBeGreaterThan(-1)
return src.slice(start, src.indexOf('activeSession.api.canvas.mutate(projectId, stamped)', start))
}
diff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.ts
index 4ad76f059..2dbc0cef4 100644
--- a/src/renderer/canvas/hosted-team.source.test.ts
+++ b/src/renderer/canvas/hosted-team.source.test.ts
@@ -63,7 +63,15 @@ describe('hosted team glue in Canvas', () => {
})
it('a read-only role never publishes canvas edits, and the rule is false for every non-hosted tab', () => {
- expect(src).toContain('shouldPublish: () => hasPeersRef.current && !isHostedReadOnly(activeSession.id)')
+ // ONE gate for the node publisher and the kanban publisher (Task 6): the read-only refusal lives
+ // in `shouldPublishFor`, and the node publisher asks it for the active project.
+ const start = src.indexOf('const shouldPublishFor = (projectId: string): boolean =>')
+ expect(start).toBeGreaterThan(-1)
+ const gate = src.slice(start, src.indexOf('const pub = createCanvasPublisher(', start))
+ expect(gate).toContain('hasPeersRef.current &&')
+ expect(gate).toContain('!isHostedReadOnly(activeSession.id)')
+ expect(src).toContain('shouldPublish: () => shouldPublishFor(useProjects.getState().activeProjectId)')
+ expect(src).toContain('shouldPublish: (projectId) => shouldPublishFor(projectId)')
})
it('the canvas turns read-only only for a hosted Viewer/Commenter (a spread: nothing new otherwise)', () => {
diff --git a/src/renderer/canvas/kanban-sync-wiring.test.ts b/src/renderer/canvas/kanban-sync-wiring.test.ts
new file mode 100644
index 000000000..14639662f
--- /dev/null
+++ b/src/renderer/canvas/kanban-sync-wiring.test.ts
@@ -0,0 +1,99 @@
+// Source pins for the kanban half of canvas sync (Task 6). Canvas.tsx cannot be rendered in the node
+// test environment, so the load-bearing SHAPES are pinned here; the behaviour behind each lives in
+// kanban-sync.test.ts (the publisher, and the store funnel + reducer together),
+// projects.mutation.test.ts (the hook) and canvas-sync.convergence.test.ts (boards converge).
+import { readFileSync } from 'node:fs'
+import { describe, it, expect } from 'vitest'
+const canvas = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+const store = readFileSync(new URL('../state/projects.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+const omni = readFileSync(new URL('../components/kanban/GlobalKanbanView.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+/** From `start` to the first `end` after it (the whole rest of the file if `end` is missing). */
+function between(src: string, start: string, end: string): string {
+ const i = src.indexOf(start)
+ expect(i, `missing: ${start}`).toBeGreaterThan(-1)
+ const j = src.indexOf(end, i + start.length)
+ return src.slice(i, j === -1 ? undefined : j)
+}
+
+/** The publisher effect: from the order's creation to its teardown. */
+const publisherEffect = (): string => between(canvas, 'const order = createCanvasOrder(src)', 'orderRef.current = null')
+/** The peer-mutation receive handler. */
+const receiveHandler = (): string =>
+ between(canvas, 'return activeSession.api.canvas.onMutation((projectId, mutation) => {', '}, [activeSession.api, setNodes')
+
+describe('kanban sync wiring', () => {
+ it('Canvas registers the kanban publish hook and clears it', () => {
+ const body = publisherEffect()
+ expect(body).toMatch(/setKanbanPublishHook\(\(id, prev, next\) => kanbanPublisher\.publish\(id, prev, next\)\)/)
+ expect(body).toMatch(/setKanbanPublishHook\(null\)/)
+ })
+
+ // The board ops ride the SAME cast as the nodes and edges: one order stamps and records them, one
+ // gate decides whether anything is published at all (Task 9 extends that ONE gate).
+ it('the kanban publisher casts through castFor and asks the node publisher’s gate', () => {
+ const body = publisherEffect()
+ expect(body).toContain('send: (projectId, m) => castFor(projectId, m)')
+ expect(body).toContain('liveNodeIds: (projectId) => liveNodeIdsFor(projectId)')
+ expect(body).toContain('shouldPublish: (projectId) => shouldPublishFor(projectId)')
+ // R2: the repaired form lands through the store reducer, never through setProjectKanban.
+ expect(body).toContain('applyLocal: (projectId, m) => applyToStored(projectId, m)')
+ // …and the node publisher goes through the very same two functions.
+ expect(body).toMatch(/return castFor\(projectId, m\)/)
+ expect(body).toContain('shouldPublish: () => shouldPublishFor(useProjects.getState().activeProjectId)')
+ expect(body).not.toMatch(/setProjectKanban\(/)
+ })
+
+ // Only the core whose echoes THIS order hears may be cast to: our own echo is our ack (rule 1), and
+ // an echo from a core nobody subscribed never comes back to draw the pending entry down.
+ it('castFor refuses a project on another core, and casts through the bound session', () => {
+ const body = between(canvas, 'const castFor = (projectId: string, m: CanvasMutation): boolean => {', 'const pub = createCanvasPublisher(')
+ expect(body).toContain('if (sessionForProject(projectId).api !== activeSession.api) return false')
+ expect(body).toContain('const stamped = order.stamp({ ...m, src })')
+ expect(body).toContain('activeSession.api.canvas.mutate(projectId, stamped)')
+ const gate = between(canvas, 'const shouldPublishFor = (projectId: string): boolean =>', 'const pub = createCanvasPublisher(')
+ expect(gate).toContain('sessionForProject(projectId).api === activeSession.api')
+ expect(gate).toContain('hasPeersRef.current')
+ expect(gate).toContain('!isHostedReadOnly(activeSession.id)')
+ })
+
+ // Never a mix of two projects: the rendered project's ids come from the epoch pair, every other
+ // project's from the store.
+ it('the live node ids are the epoch-correct set for the project asked about', () => {
+ const body = between(canvas, 'const liveNodeIdsFor = (projectId: string): ReadonlySet<string> =>', 'const castFor = ')
+ expect(body).toMatch(/nodesProjectIdRef\.current === projectId\s*\?\s*nodesRef\.current/)
+ expect(body).toMatch(/useProjects\.getState\(\)\.getProject\(projectId\)\?\.nodes/)
+ })
+
+ it('peer kanban ops are applied through the store reducer, never through setProjectKanban', () => {
+ const recv = receiveHandler()
+ expect(recv).toMatch(/if \(isKanbanOp\(mutation\)\) \{\s*applyToStored\(projectId, mutation\)\s*return\s*\}/)
+ // Before the edge and node branches: a board op never touches React Flow, active project or not.
+ expect(recv.indexOf('isKanbanOp(mutation)')).toBeLessThan(recv.indexOf('isEdgeMutation(mutation)'))
+ expect(recv).not.toMatch(/setProjectKanban\(/)
+ const apply = between(canvas, 'const applyToStored = useCallback(', '[markDirty]')
+ expect(apply).toContain('store.applyCanvasOp(projectId, mutation)')
+ })
+
+ // Spec §5: only the originating client records a board-log entry — a client applying a peer's op
+ // records nothing, or every move would be logged once per connected client.
+ it('applying a peer op never appends to the board log', () => {
+ const recv = receiveHandler()
+ expect(recv).not.toMatch(/useBoardLog|boardLogEvents|\.append\(/)
+ })
+
+ // Spec §11.4: a relay tab's board log lives on its host. The board and the Omni board sit OUTSIDE
+ // the per-session provider, so the mount-time `api` is the LOCAL core's.
+ it('board-log appends use the project session', () => {
+ const cb = canvas.slice(canvas.indexOf('boardLogEvents('), canvas.indexOf('boardLogEvents(') + 800)
+ expect(cb).toMatch(/sessionForProject\(/)
+ expect(canvas).not.toMatch(/useBoardLog\.getState\(\)\.append\(api,/)
+ expect(omni).toMatch(/useBoardLog\.getState\(\)\.append\(sessionForProject\(projectId\)\.api, projectId,/)
+ expect(omni).not.toMatch(/useBoardLog\.getState\(\)\.append\(api,/)
+ })
+
+ it('setProjectKanban publishes after writing', () => {
+ const fn = store.slice(store.indexOf('setProjectKanban(id, kanban) {'), store.indexOf('setProjectKanban(id, kanban) {') + 600)
+ expect(fn).toMatch(/const prev = get\(\)\.getProject\(id\)\?\.kanban[\s\S]*set\(\(s\) =>[\s\S]*kanbanPublishHook\?\.\(id, prev, kanban\)/)
+ })
+})
diff --git a/src/renderer/canvas/kanban-sync.test.ts b/src/renderer/canvas/kanban-sync.test.ts
new file mode 100644
index 000000000..e9e19906d
--- /dev/null
+++ b/src/renderer/canvas/kanban-sync.test.ts
@@ -0,0 +1,199 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { createKanbanPublisher, type KanbanPublisherDeps } from './kanban-sync'
+import { applyKanbanOp } from '@shared/kanban-ops'
+import { defaultKanbanFor } from '@shared/kanban-default-board'
+import type { CanvasMutation, KanbanOp, ProjectKanban } from '@shared/types'
+import { setKanbanPublishHook, useProjects } from '../state/projects'
+
+const P = 'project-1'
+const todo = defaultKanbanFor(P).columns[0].id
+const doing = defaultKanbanFor(P).columns[1].id
+
+/** A publisher over recording deps: every cast and every local repair it makes lands in a list. */
+function harness(over: Partial<KanbanPublisherDeps> = {}) {
+ const sent: Array<[string, CanvasMutation]> = []
+ const repaired: Array<[string, CanvasMutation]> = []
+ const pub = createKanbanPublisher({
+ send: (id, m) => { sent.push([id, m]); return true },
+ liveNodeIds: () => new Set(['n1', 'n2']),
+ shouldPublish: () => true,
+ applyLocal: (id, m) => { repaired.push([id, m]) },
+ ...over
+ })
+ return { pub, sent, repaired }
+}
+
+const withCard = (board: ProjectKanban | undefined, nodeId: string, columnId: string): ProjectKanban =>
+ applyKanbanOp(board, { op: 'kb-card', assignment: { nodeId, columnId } }, P)
+
+describe('createKanbanPublisher', () => {
+ it('casts item ops for the project, and nothing when publishing is off', () => {
+ const sent: Array<[string, CanvasMutation]> = []
+ let on = true
+ const pub = createKanbanPublisher({
+ send: (id, m) => { sent.push([id, m]); return true },
+ liveNodeIds: () => new Set(['n1']),
+ shouldPublish: () => on,
+ applyLocal: () => {}
+ })
+ const next = applyKanbanOp(undefined, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }, P)
+ pub.publish(P, undefined, next)
+ expect(sent).toEqual([[P, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }]])
+ on = false
+ pub.publish(P, next, undefined)
+ expect(sent).toHaveLength(1)
+ })
+
+ // The test above closes the gate on a write to `undefined`, which diffs to nothing whatever the
+ // gate says. A REAL change must also stay home while the gate is closed (solo, read-only role).
+ it('a real change is not cast, and nothing is repaired, while the gate is closed', () => {
+ const { pub, sent, repaired } = harness({ shouldPublish: () => false })
+ pub.publish(P, withCard(undefined, 'n1', todo), withCard(undefined, 'n1', doing))
+ pub.publish(P, defaultKanbanFor(P), { ...defaultKanbanFor(P), labels: [{ id: 'l', name: 'y'.repeat(80), color: 'red' }] })
+ expect(sent).toEqual([])
+ expect(repaired).toEqual([])
+ })
+
+ it('never casts a pruned dead card', () => {
+ const sent: CanvasMutation[] = []
+ const pub = createKanbanPublisher({
+ send: (_id, m) => { sent.push(m); return true },
+ liveNodeIds: () => new Set(),
+ shouldPublish: () => true,
+ applyLocal: () => {}
+ })
+ const prev = applyKanbanOp(undefined, { op: 'kb-card', assignment: { nodeId: 'dead', columnId: todo } }, P)
+ pub.publish(P, prev, defaultKanbanFor(P))
+ expect(sent).toEqual([])
+ })
+
+ it('never casts a pruned dead card’s meta either', () => {
+ const { pub, sent } = harness({ liveNodeIds: () => new Set() })
+ const prev = applyKanbanOp(undefined, { op: 'kb-meta', meta: { nodeId: 'dead', priority: 'high' } }, P)
+ pub.publish(P, prev, { ...prev, meta: [] })
+ expect(sent).toEqual([])
+ })
+
+ // The other half of the prune rule: a LIVE card taken off the board is a real edit and is cast.
+ // Without this the two tests above would pass for a publisher that casts no removal at all.
+ it('casts the removal of a live card (a person moving it back to Ungrouped)', () => {
+ const { pub, sent } = harness()
+ const prev = withCard(undefined, 'n1', todo)
+ pub.publish(P, prev, defaultKanbanFor(P))
+ expect(sent).toEqual([[P, { op: 'kb-card-remove', nodeId: 'n1' }]])
+ })
+
+ it('asks the gate with the project it publishes for, and reads that project’s live nodes', () => {
+ const asked: string[] = []
+ const { pub, sent } = harness({
+ shouldPublish: (id) => { asked.push(`gate:${id}`); return true },
+ liveNodeIds: (id) => { asked.push(`live:${id}`); return new Set(['n1']) }
+ })
+ const other = defaultKanbanFor('other')
+ const prev = applyKanbanOp(other, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: other.columns[0].id } }, 'other')
+ pub.publish('other', prev, other)
+ expect(asked).toEqual(['gate:other', 'live:other'])
+ expect(sent).toEqual([['other', { op: 'kb-card-remove', nodeId: 'n1' }]])
+ })
+
+ it('a write that changes nothing the vocabulary carries casts nothing (github config)', () => {
+ const { pub, sent } = harness()
+ const prev = withCard(undefined, 'n1', todo)
+ pub.publish(P, prev, { ...prev, github: { repo: 'o/r' } } as unknown as ProjectKanban)
+ expect(sent).toEqual([])
+ })
+
+ // RULING R2. The reflector repairs a name and the sender drops its own echo, so a board holding
+ // the unrepaired value would show something no peer has, forever. The clean form is what is cast,
+ // and — when it differs from what the board holds — what the board is set to, through the store
+ // reducer (never setProjectKanban: that would publish again).
+ describe('R2: the clean form is cast, and applied locally when it differs', () => {
+ const long = 'x'.repeat(80)
+ const board = (name: string): ProjectKanban => ({
+ ...defaultKanbanFor(P),
+ labels: [{ id: 'lab-1', name, color: 'red' }]
+ })
+
+ it('an over-long label name is cast cut to 60, and the cut form is applied locally', () => {
+ const { pub, sent, repaired } = harness()
+ pub.publish(P, defaultKanbanFor(P), board(long))
+ const clean = { op: 'kb-label', label: { id: 'lab-1', name: 'x'.repeat(60), color: 'red' } }
+ expect(sent).toContainEqual([P, clean])
+ expect(repaired).toEqual([[P, clean]])
+ })
+
+ it('a value that is already clean is not re-applied', () => {
+ const { pub, sent, repaired } = harness()
+ pub.publish(P, defaultKanbanFor(P), board('bug'))
+ expect(sent.length).toBeGreaterThan(0)
+ expect(repaired).toEqual([])
+ })
+
+ it('key order alone is not a difference', () => {
+ const { pub, repaired } = harness()
+ const next: ProjectKanban = {
+ ...defaultKanbanFor(P),
+ columns: defaultKanbanFor(P).columns.map((c) => ({ category: c.category, color: c.color, title: c.title, id: c.id }))
+ }
+ pub.publish(P, withCard(undefined, 'n1', todo), withCard(next, 'n1', doing))
+ expect(repaired).toEqual([])
+ })
+
+ it('nothing is applied locally for an op that was not cast', () => {
+ const { pub, repaired } = harness({ send: () => false })
+ pub.publish(P, defaultKanbanFor(P), board(long))
+ expect(repaired).toEqual([])
+ })
+
+ it('an op the sanitizer refuses is never cast (the reflector would refuse it too)', () => {
+ const { pub, sent } = harness()
+ // An id is an address: never repaired, only refused (here: past the 128-char ref bound).
+ const bad = { ...defaultKanbanFor(P), labels: [{ id: 'l'.repeat(129), name: 'bell', color: 'red' }] } as ProjectKanban
+ pub.publish(P, defaultKanbanFor(P), bad)
+ expect(sent.filter(([, m]) => m.op === 'kb-label')).toEqual([])
+ })
+ })
+})
+
+// The store funnel + the publisher + the store reducer, together: what Canvas wires up.
+describe('the store funnel publishes, and only the funnel', () => {
+ const node = { id: 'n1', kind: 'terminal', title: 'n1', color: '#fff', group: '', position: { x: 0, y: 0 }, size: { width: 10, height: 10 } }
+ let calls: Array<[string, ProjectKanban | undefined, ProjectKanban | undefined]>
+ let sent: CanvasMutation[]
+ let pid: string
+
+ beforeEach(() => {
+ useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: [] })
+ pid = useProjects.getState().addProject('p').id
+ useProjects.getState().commitCanvas(pid, [node as never], { x: 0, y: 0, zoom: 1 })
+ calls = []
+ sent = []
+ const pub = createKanbanPublisher({
+ send: (_id, m) => { sent.push(m); return true },
+ liveNodeIds: (id) => new Set((useProjects.getState().getProject(id)?.nodes ?? []).map((n) => n.id)),
+ shouldPublish: () => true,
+ applyLocal: (id, m) => { useProjects.getState().applyCanvasOp(id, m) }
+ })
+ setKanbanPublishHook((id, prev, next) => {
+ calls.push([id, prev, next])
+ pub.publish(id, prev, next)
+ })
+ })
+ afterEach(() => setKanbanPublishHook(null))
+
+ it('R2 end to end: the board ends on the clean name, and the repair publishes nothing more', () => {
+ const next: ProjectKanban = { ...defaultKanbanFor(pid), labels: [{ id: 'lab-1', name: 'y'.repeat(90), color: 'red' }] }
+ useProjects.getState().setProjectKanban(pid, next)
+ expect(useProjects.getState().getProject(pid)?.kanban?.labels).toEqual([{ id: 'lab-1', name: 'y'.repeat(60), color: 'red' }])
+ expect(calls).toHaveLength(1) // the repair went through the reducer, not the funnel
+ expect(sent.filter((m) => m.op === 'kb-label')).toHaveLength(1)
+ })
+
+ it('a peer op applied through the store reducer never publishes', () => {
+ const op: KanbanOp = { op: 'kb-card', assignment: { nodeId: 'n1', columnId: defaultKanbanFor(pid).columns[0].id } }
+ expect(useProjects.getState().applyCanvasOp(pid, op)).toBe(true)
+ expect(useProjects.getState().getProject(pid)?.kanban?.assignments).toEqual([op.assignment])
+ expect(calls).toEqual([])
+ expect(sent).toEqual([])
+ })
+})
diff --git a/src/renderer/canvas/kanban-sync.ts b/src/renderer/canvas/kanban-sync.ts
new file mode 100644
index 000000000..81e4a02e8
--- /dev/null
+++ b/src/renderer/canvas/kanban-sync.ts
@@ -0,0 +1,61 @@
+// Publishes board changes as item-level ops (spec §5). It hangs off the ONE store funnel,
+// useProjects.setProjectKanban, so every board writer — the board, the card modal, the Omni board,
+// node labels, the GitHub settings section — publishes without a call site of its own. The send is
+// Canvas's canvas:mut send (`castFor`): it stamps src/seen, records the pending entry (canvas-order
+// rules 1-3) and casts through the PROJECT's session (a relay tab's board edits go to its host, not
+// the local core).
+//
+// Two rules live here rather than in Canvas, so they are tested without a canvas:
+// - PRUNE REMOVALS ARE NEVER CAST (spec §11.6). `diffKanbanOps` drops the removal of a card or meta
+// whose node is not live in that project: every board commit prunes dead cards against the LOCAL
+// node list, and a peer whose node op has not arrived yet would otherwise delete a fresh card for
+// everyone. `liveNodeIds` must therefore be that project's nodes and nothing else.
+// - THE CLEAN FORM IS CAST, AND KEPT (ruling R2). The reflector repairs what it relays (a label name
+// cut to its bound, an invalid rank dropped) and the sender drops its own echo as an ack, so a
+// board still holding the unrepaired value would show something no peer has, for good. The
+// publisher casts `sanitizeKanbanOp(op)` and, when that differs from what the board holds, applies
+// the clean form to the local store too — through the store REDUCER (`applyLocal`), never through
+// `setProjectKanban`, whose publish hook would cast it a second time.
+import { diffKanbanOps, sanitizeKanbanOp } from '@shared/kanban-ops'
+import type { CanvasMutation, KanbanOp, ProjectKanban } from '@shared/types'
+
+export interface KanbanPublisherDeps {
+ /** Cast one op for `projectId`. `false` = not cast (the op is dropped, and nothing is repaired). */
+ send(projectId: string, m: CanvasMutation): boolean
+ /** The node ids live in `projectId` — one project's, never a mix (see the prune rule above). */
+ liveNodeIds(projectId: string): ReadonlySet<string>
+ /** The publish gate for `projectId` — the SAME one the node publisher asks. */
+ shouldPublish(projectId: string): boolean
+ /** Apply a repaired op to the local store WITHOUT publishing it (the store reducer). */
+ applyLocal(projectId: string, m: CanvasMutation): void
+}
+
+export function createKanbanPublisher(deps: KanbanPublisherDeps): {
+ publish(projectId: string, prev: ProjectKanban | undefined, next: ProjectKanban | undefined): void
+} {
+ return {
+ publish(projectId, prev, next) {
+ if (!deps.shouldPublish(projectId)) return
+ for (const op of diffKanbanOps(prev, next, projectId, deps.liveNodeIds(projectId))) {
+ const clean = sanitizeKanbanOp(op)
+ // Refused (an unaddressable id): the reflector refuses it too, so casting it would only cost
+ // a pending entry for an echo that never comes. Nothing the UI produces is refused.
+ if (!clean) continue
+ if (deps.send(projectId, clean) && !sameOp(op, clean)) deps.applyLocal(projectId, clean)
+ }
+ }
+ }
+}
+
+/** The same op as JSON sees it: key order does not matter and an `undefined`-valued key is absent. */
+function sameOp(a: KanbanOp, b: KanbanOp): boolean {
+ return stable(a) === stable(b)
+}
+
+function stable(v: unknown): string {
+ return JSON.stringify(v, (_k, val: unknown) =>
+ val && typeof val === 'object' && !Array.isArray(val)
+ ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, (val as Record<string, unknown>)[k]]))
+ : val
+ )
+}
diff --git a/src/renderer/components/kanban/GlobalKanbanView.tsx b/src/renderer/components/kanban/GlobalKanbanView.tsx
index c2fc822ad..4181ed19a 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx
@@ -15,7 +15,7 @@ import { toKanbanSessionState } from '../../canvas/toKanbanSessionState'
import { createAgentNode, createBrowserNode, createStickyNode, createTerminalNode, flowToNodeStates, resolveNewNodeAccount } from '../../state/workspace'
import { markCanvasCovered } from '../../lib/canvasCovered'
import { useViewMode } from '../../state/viewMode'
-import { useSession } from '../../session/session'
+import { sessionForProject } from '../../session/session'
import { activePermissionMode } from '../../state/permissionMode'
import { CardModal } from './CardModal'
import { ContextMenu, type MenuItem } from '../ContextMenu'
@@ -314,7 +314,6 @@ export const GlobalKanbanView = memo(function GlobalKanbanView() {
useEffect(() => markCanvasCovered(document.documentElement), [])
const boardStyle = useBoardWallpaperStyle()
const projects = useProjects(s => s.projects.filter(p => !p.closed))
- const { api } = useSession()
const modalRef = useRef<string | null>(null)
const highlightId = useViewMode(s => s.highlightedSwimlaneId)
const setHighlightId = useViewMode(s => s.setHighlightedSwimlaneId)
@@ -345,9 +344,11 @@ export const GlobalKanbanView = memo(function GlobalKanbanView() {
return s ? s.title || 'Untitled' : ''
}
for (const { nodeId, event } of boardLogEvents(prev, next, cardTitle)) {
- useBoardLog.getState().append(api, projectId, { kind: 'event', nodeId, event })
+ // The project's own session: a relay tab's board log lives on its host (spec §11.4) — this
+ // board sits outside the per-session provider, so a `useSession()` api here is the LOCAL core.
+ useBoardLog.getState().append(sessionForProject(projectId).api, projectId, { kind: 'event', nodeId, event })
}
- }, [api])
+ }, [])
const onCreateNode = useCallback((projectId: string, choice: KanbanCreateChoice, columnId: string | null) => {
// Delegate to Canvas's createNodeInColumn which correctly mounts the TerminalNode
diff --git a/src/renderer/state/projects.mutation.test.ts b/src/renderer/state/projects.mutation.test.ts
index 900af2256..5d32dcea4 100644
--- a/src/renderer/state/projects.mutation.test.ts
+++ b/src/renderer/state/projects.mutation.test.ts
@@ -1,6 +1,6 @@
-import { describe, it, expect, beforeEach } from 'vitest'
-import { useProjects } from './projects'
-import type { CanvasMutation, CanvasNodeState } from '@shared/types'
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { setKanbanPublishHook, useProjects } from './projects'
+import type { CanvasMutation, CanvasNodeState, ProjectKanban } from '@shared/types'
import { defaultKanbanFor } from '@shared/kanban-default-board'
const node = (id: string, x = 0): CanvasNodeState => ({
@@ -216,3 +216,49 @@ describe('applyCanvasOp', () => {
expect(useProjects.getState().getProject(id)?.nodes.find((n) => n.id === 'evil')?.shell).toBeUndefined()
})
})
+
+/**
+ * The kanban publish hook (spec §11.3): every board write goes through `setProjectKanban`, so that is
+ * where a board change is published — once, after the store write, with the board read BEFORE it.
+ * A peer's op arrives through `applyCanvasOp`, which must never reach the hook: publishing it would
+ * re-cast someone else's edit as ours.
+ */
+describe('setKanbanPublishHook', () => {
+ let calls: Array<[string, ProjectKanban | undefined, ProjectKanban | undefined]>
+ beforeEach(() => {
+ calls = []
+ setKanbanPublishHook((id, prev, next) => {
+ // AFTER the write: the store already holds `next` when the hook runs.
+ expect(useProjects.getState().getProject(id)?.kanban).toBe(next)
+ calls.push([id, prev, next])
+ })
+ })
+ afterEach(() => setKanbanPublishHook(null))
+
+ it('setProjectKanban calls it once with (id, prev, next), prev read before the write', () => {
+ const p = useProjects.getState().addProject('p')
+ const first = defaultKanbanFor(p.id)
+ useProjects.getState().setProjectKanban(p.id, first)
+ expect(calls).toEqual([[p.id, undefined, first]])
+ const second: ProjectKanban = { ...first, assignments: [{ nodeId: 'a', columnId: first.columns[0].id }] }
+ useProjects.getState().setProjectKanban(p.id, second)
+ expect(calls).toHaveLength(2)
+ expect(calls[1][1]).toBe(first)
+ expect(calls[1][2]).toBe(second)
+ })
+
+ it('applyCanvasOp with a board op does not call it (a peer op is never re-published)', () => {
+ const p = useProjects.getState().addProject('p')
+ const col = defaultKanbanFor(p.id).columns[0].id
+ expect(useProjects.getState().applyCanvasOp(p.id, { op: 'kb-card', assignment: { nodeId: 'a', columnId: col } })).toBe(true)
+ expect(useProjects.getState().getProject(p.id)?.kanban?.assignments).toEqual([{ nodeId: 'a', columnId: col }])
+ expect(calls).toEqual([])
+ })
+
+ it('a cleared hook is not called', () => {
+ setKanbanPublishHook(null)
+ const p = useProjects.getState().addProject('p')
+ useProjects.getState().setProjectKanban(p.id, defaultKanbanFor(p.id))
+ expect(calls).toEqual([])
+ })
+})
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 0f28b2c70..23c44c0df 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -380,6 +380,28 @@ function mapProjectNodes(
return projects.map((p) => (p.id === projectId ? { ...p, nodes: fn(p.nodes) } : p))
}
+/**
+ * Publishes a board write to the project's peers (spec §11.3). Every board write in the renderer
+ * goes through `setProjectKanban` — the board, the card modal, the Omni board, node labels, the
+ * GitHub settings section, the canvas-control `assign` verb (fenced by board-writers.guard.test.ts)
+ * — so the ONE place a board change is published is here, and no writer needs a call site of its
+ * own. `prev` is the board read BEFORE the write (`undefined` = the project's lazy default), `next`
+ * the board written.
+ *
+ * A peer's board op must NEVER come through here: it is applied with `applyCanvasOp` (the store
+ * reducer), which does not call the hook — publishing it would re-cast someone else's edit as ours.
+ */
+export type KanbanPublishHook = (
+ projectId: string,
+ prev: ProjectKanban | undefined,
+ next: ProjectKanban | undefined
+) => void
+let kanbanPublishHook: KanbanPublishHook | null = null
+/** Canvas registers this once per core binding and clears it (`null`) on teardown. */
+export function setKanbanPublishHook(hook: KanbanPublishHook | null): void {
+ kanbanPublishHook = hook
+}
+
export const useProjects = create<ProjectsState>((set, get) => ({
projects: [],
activeProjectId: '',
@@ -562,9 +584,13 @@ export const useProjects = create<ProjectsState>((set, get) => ({
},
setProjectKanban(id, kanban) {
+ // Read BEFORE the write: the publish hook diffs this against what was written.
+ const prev = get().getProject(id)?.kanban
set((s) => ({
projects: s.projects.map((p) => (p.id === id ? { ...p, kanban } : p))
}))
+ // AFTER the write, so a local repair the publisher applies (ruling R2) lands on `kanban`.
+ kanbanPublishHook?.(id, prev, kanban)
},
setProjectBreadcrumbs(id, breadcrumbs) {