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-authority): keep a governed project's node order parent-first

reviewe7a735f3aed3
diff --git a/CLAUDE.md b/CLAUDE.md
index a7a5af965..9064cc8bc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1484,7 +1484,11 @@ session.
a frame among its siblings, carrying its subtree. `nodeStatesToFlow`/`groupsFirst` emit frames
**depth-first from the root** — a flat "groups first" sort is not enough once two groups compare
equal — and that persisted order is also the downgrade contract (a pre-nesting build's stable
- sort leaves it alone, so a nested tree still hydrates parent-first and renders there).
+ sort leaves it alone, so a nested tree still hydrates parent-first and renders there). The order
+ has ONE definition (`groupsFirstBy`, `src/shared/node-order.ts`), and the shared op reducer
+ (`applyCanvasMutation`) re-sorts with it on an append or a `parentId` change — the same two points
+ the live React Flow apply does — because a governed Server Edition project's file is written from
+ the canvas authority's array, not from React Flow's.
**A frame that gains a child bigger than itself is re-fitted, ancestors included**
(`fitGroupToChildren` up the chain): a wrapper created at `(minX-28, minY-62)` relative to its
parent is routinely negative, and `extent:'parent'` would make React Flow clamp it into an
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.md
index 8cfb4ee3b..a7627d5f3 100644
--- a/docs/hosted-team-relay.md
+++ b/docs/hosted-team-relay.md
@@ -438,6 +438,12 @@ it is a new way to use it.
- **Node order is not synced.** The sessions sidebar's order is the node list's order, and no op
carries an order change, so on a governed project a reorder stays on the screen that made it: the
file keeps the authority's order (the order it read, with nodes it hears about later appended).
+ What IS guaranteed is parent-first: the reducer re-sorts with the shared `groupsFirst`
+ (`src/shared/node-order.ts`) whenever an op appends a node or changes its `parentId`, so every
+ frame the authority writes precedes its descendants, as a normal save's does. That is the
+ downgrade contract (a build that predates nested frames still hydrates the file parent-first). A
+ file that was already out of that order when the authority read it keeps it until one of those
+ ops touches it.
- **Load-time repairs are not cast.** What a client derives while it loads a project (a missing
`--after` dependency rope it heals, a legacy node migrated to its current shape) becomes that
client's baseline and is never cast, so on a governed project it never reaches disk: every load
diff --git a/src/core/canvas-authority.test.ts b/src/core/canvas-authority.test.ts
index fba9500e7..1e645505e 100644
--- a/src/core/canvas-authority.test.ts
+++ b/src/core/canvas-authority.test.ts
@@ -626,3 +626,58 @@ describe('canvas authority — flushing and lifecycle', () => {
expect(h.writes.every((w) => w.at === 0)).toBe(true)
})
})
+
+// The downgrade contract (CLAUDE.md, the group-frame bullet): a frame precedes its descendants in
+// the persisted array, so a pre-nesting build's flat, STABLE groups-first sort still hydrates a
+// nested tree parent-first. A governed project's file is written from the authority's array, not
+// from React Flow's, so its reducer has to keep that order itself.
+describe('canvas authority — the written node order is parent-first', () => {
+ const group = (id: string, over: Partial<CanvasNodeState> = {}): CanvasNodeState => node(id, { kind: 'group', ...over })
+ const under = (parentId: string) => ({ parentId })
+ /** Every node's parent (when it has one in the list) appears before it. */
+ const parentFirst = (nodes: CanvasNodeState[]): boolean =>
+ nodes.every((n, i) => !n.parentId || !nodes.some((p) => p.id === n.parentId) || nodes.findIndex((p) => p.id === n.parentId) < i)
+ /** What a build that predates nesting does on load: a flat, stable "groups first" sort. */
+ const preNestingSort = (nodes: CanvasNodeState[]): CanvasNodeState[] =>
+ [...nodes].sort((a, b) => (a.kind === 'group' ? 0 : 1) - (b.kind === 'group' ? 0 : 1))
+
+ it('grouping two nodes (the new frame is an append) writes the frame first', async () => {
+ const h = harness({ disk: { P: content([node('a'), node('b')]) } })
+ // The ops a client's publisher sends for groupSelectedNodes: next-array order, frame first.
+ h.cast({ op: 'upsert', node: group('G') })
+ h.cast({ op: 'upsert', node: node('a', under('G')) })
+ h.cast({ op: 'upsert', node: node('b', under('G')) })
+ await h.clock.advance(1000)
+ expect(h.writes).toHaveLength(1)
+ expect(ids(h.writes[0].content.nodes)).toEqual(['G', 'a', 'b'])
+ })
+
+ it('wrapping a frame into a new outer frame writes outer, inner, then the leaf', async () => {
+ const h = harness({ disk: { P: content([group('I'), node('x', under('I'))]) } })
+ h.cast({ op: 'upsert', node: group('O') })
+ h.cast({ op: 'upsert', node: group('I', under('O')) })
+ await h.clock.advance(1000)
+ const written = h.writes[0].content.nodes
+ expect(ids(written)).toEqual(['O', 'I', 'x'])
+ // …and that is exactly what the downgrade contract needs: the flat sort leaves it parent-first.
+ expect(parentFirst(preNestingSort(written))).toBe(true)
+ })
+
+ it('the same holds when the reparent reaches it before the new frame does', async () => {
+ const h = harness({ disk: { P: content([group('I'), node('x', under('I'))]) } })
+ h.cast({ op: 'upsert', node: group('I', under('O')) })
+ h.cast({ op: 'upsert', node: group('O') })
+ await h.clock.advance(1000)
+ expect(ids(h.writes[0].content.nodes)).toEqual(['O', 'I', 'x'])
+ })
+
+ it('an upsert that neither appends nor reparents keeps the order it found, even a legacy one', async () => {
+ // A file written before this order was enforced: the leaf ahead of its frame.
+ const h = harness({ disk: { P: content([node('a', under('G')), group('G'), node('b')]) } })
+ h.cast({ op: 'upsert', node: at('a', 42, under('G')) })
+ h.cast({ op: 'upsert', node: group('G', { title: 'renamed' }) })
+ await h.clock.advance(1000)
+ expect(ids(h.writes[0].content.nodes)).toEqual(['a', 'G', 'b'])
+ expect(byId(h.writes[0].content.nodes, 'a')?.position.x).toBe(42)
+ })
+})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 89c4d77b8..41eeedbe3 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -44,6 +44,7 @@ export { applyCanvasMutation, applyOwnCanvasMutation } from '@shared/canvas-muta
export { accountNodeColor, agentAccountColor } from '@shared/agents/account-color'
import { mutationTrustsLaunch, sanitizeInboundNode } from '@shared/node-exec'
import { SYSTEM_NODE_COLORS } from '@shared/node-colors'
+import { groupsFirstBy } from '@shared/node-order'
// Preserve the renderer's long-standing import surface; validation and the palette now live in
// shared so Server Edition and canvas-control accept exactly what these pickers display.
@@ -1355,34 +1356,12 @@ export function alignNodes(nodes: CanvasNode[], ids: string[], edge: AlignEdge):
}
/**
- * Group (parent) nodes must precede their descendants in the array (React Flow requirement).
- * With nesting the old "all groups, then everything else" split is not enough — a child frame
- * could still be emitted before its parent — so groups are emitted depth-first from the root.
- *
- * This order is also the DOWNGRADE contract: `flowToNodeStates` preserves array order, and an
- * older build's flat `kind === 'group'` sort returns 0 for two groups, which a stable sort
- * (ES2019+) leaves alone. So a nested tree written by this build still hydrates parent-first,
- * and therefore still RENDERS, on a build that predates nesting.
+ * Parent-first order for the live React Flow array — the ONE definition is `groupsFirstBy`
+ * (@shared/node-order), which also documents the downgrade contract this order keeps. Only the
+ * group test differs here: a React Flow node says `type`, a persisted state says `kind`.
*/
function groupsFirst(nodes: CanvasNode[]): CanvasNode[] {
- const byId = new Map(nodes.map((node) => [node.id, node]))
- const emitted = new Set<string>()
- const visiting = new Set<string>()
- const groups: CanvasNode[] = []
- const emitGroup = (node: CanvasNode): void => {
- if (emitted.has(node.id) || node.type !== 'group') return
- if (visiting.has(node.id)) return // cyclic parentId: emit once, don't recurse forever
- visiting.add(node.id)
- const parent = node.parentId ? byId.get(node.parentId) : undefined
- if (parent?.type === 'group') emitGroup(parent)
- visiting.delete(node.id)
- if (!emitted.has(node.id)) {
- emitted.add(node.id)
- groups.push(node)
- }
- }
- nodes.forEach(emitGroup)
- return [...groups, ...nodes.filter((node) => node.type !== 'group')]
+ return groupsFirstBy(nodes, (node) => node.type === 'group')
}
/** A node's position in ROOT space: its own position plus every ancestor frame's origin. */
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index b5ba5458c..aa97973b6 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -5,6 +5,7 @@ import path from 'node:path'
import { publishCanvasMutation } from '../core/canvas-sync'
import { contentOf, diffContent, type CanvasContent } from '../shared/canvas-content'
+import { groupsFirst } from '../shared/node-order'
import { launchHeadless } from '../core/headless-launch'
import { gateProjectTarget, GRANT_CAP } from '../core/project-grants'
import {
@@ -470,28 +471,6 @@ function isDescendant(
return false
}
-/** Persist frames before their descendants, matching React Flow's hydration requirement. */
-function groupsFirst(nodes: CanvasNodeState[]): CanvasNodeState[] {
- const byId = new Map(nodes.map((node) => [node.id, node]))
- const emitted = new Set<string>()
- const visiting = new Set<string>()
- const groups: CanvasNodeState[] = []
- const emit = (node: CanvasNodeState): void => {
- if (emitted.has(node.id) || node.kind !== 'group') return
- if (visiting.has(node.id)) return
- visiting.add(node.id)
- const parent = node.parentId ? byId.get(node.parentId) : undefined
- if (parent?.kind === 'group') emit(parent)
- visiting.delete(node.id)
- if (!emitted.has(node.id)) {
- emitted.add(node.id)
- groups.push(node)
- }
- }
- nodes.forEach(emit)
- return [...groups, ...nodes.filter((node) => node.kind !== 'group')]
-}
-
/** Re-fit one persisted group around its direct children without moving them in parent space. */
function fitGroupToChildren(
nodes: CanvasNodeState[],
diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.ts
index bbebe2f5c..76b17a0ca 100644
--- a/src/shared/canvas-mutations.test.ts
+++ b/src/shared/canvas-mutations.test.ts
@@ -501,3 +501,33 @@ describe('applyCanvasMutation with a kanban op', () => {
expect(applyCanvasMutation(a, { op: 'kb-card-remove', nodeId: '1' })).toBe(a)
})
})
+
+describe('applyCanvasMutation — parent-first order (the downgrade contract)', () => {
+ const g = (id: string, parentId?: string): CanvasNodeState =>
+ ({ ...n(id), kind: 'group', ...(parentId ? { parentId } : {}) }) as CanvasNodeState
+ const child = (id: string, parentId: string, x = 0): CanvasNodeState => ({ ...n(id, x), parentId })
+ const ids = (nodes: CanvasNodeState[]): string[] => nodes.map((x) => x.id)
+
+ it('re-sorts when an upsert appends a frame', () => {
+ const out = applyCanvasMutation([n('a'), n('b')], { op: 'upsert', node: g('G') })
+ expect(ids(out)).toEqual(['G', 'a', 'b'])
+ })
+
+ it('re-sorts when an upsert changes a node\'s parentId', () => {
+ // O arrived before this re-sort rule existed, after its future child.
+ const out = applyCanvasMutation([g('I'), child('x', 'I'), g('O')], { op: 'upsert', node: g('I', 'O') })
+ expect(ids(out)).toEqual(['O', 'I', 'x'])
+ })
+
+ it('keeps the order, and every untouched entry, when an upsert neither appends nor reparents', () => {
+ const before = [child('a', 'G'), g('G'), n('b')]
+ const out = applyCanvasMutation(before, { op: 'upsert', node: child('a', 'G', 9) })
+ expect(ids(out)).toEqual(['a', 'G', 'b'])
+ expect(out[1]).toBe(before[1])
+ expect(out[2]).toBe(before[2])
+ })
+
+ it('an appended leaf with no frame in the list keeps plain append order', () => {
+ expect(ids(applyCanvasMutation([n('b'), n('a')], { op: 'upsert', node: n('c') }))).toEqual(['b', 'a', 'c'])
+ })
+})
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index 9c5dc29ed..9bc0764d7 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -4,6 +4,7 @@
import { isKanbanOp, sanitizeKanbanOp } from './kanban-ops'
import { carryLocalNodeExec, mutationTrustsLaunch, sanitizeInboundMutation, sanitizeInboundNode } from './node-exec'
+import { groupsFirst } from './node-order'
import { REF_MAX_LEN } from './presence'
import type { BridgeLink, CanvasEdgeKind, CanvasMutation, CanvasNodeState, SceneMutation } from './types'
@@ -254,7 +255,9 @@ export function createMutationGuard(): (m: CanvasMutation) => boolean {
/**
* 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
- * out the node with the given id.
+ * out the node with the given id. An upsert that appends, or that changes the node's `parentId`,
+ * re-sorts the list parent-first (`groupsFirst`, @shared/node-order); any other upsert keeps the
+ * order it found.
*
* Every caller of this is applying a mutation that came from SOMEONE ELSE (a canvas-sync peer, a
* relay client), so the node goes through `sanitizeInboundNode` first: the exec-enabling fields
@@ -279,12 +282,17 @@ export function applyCanvasMutation(
const trust = mutationTrustsLaunch(m)
const node = sanitizeInboundNode(m.node, trust)
const idx = states.findIndex((n) => n.id === node.id)
- if (idx === -1) return [...states, node]
+ // Append, then re-sort parent-first (@shared/node-order) — exactly where the live React Flow
+ // apply (`applyMutationToFlow`) re-sorts: on an append and on a `parentId` change, and nowhere
+ // else, so an upsert that does neither keeps the order it found. This is the array the Server
+ // Edition canvas authority WRITES for a governed project, so without it grouping would persist
+ // a frame after its children and break the downgrade contract a normal save keeps.
+ if (idx === -1) return groupsFirst([...states, node])
const next = states.slice()
// …and OUR exec fields stay on the node the upsert replaces: they are per-machine, so a peer
// dragging our ssh terminal must not hand it back stripped of the jump host we configured.
next[idx] = carryLocalNodeExec(states[idx], node, trust)
- return next
+ return states[idx].parentId === next[idx].parentId ? next : groupsFirst(next)
}
/**
diff --git a/src/shared/node-order.test.ts b/src/shared/node-order.test.ts
new file mode 100644
index 000000000..dbc89a5f7
--- /dev/null
+++ b/src/shared/node-order.test.ts
@@ -0,0 +1,29 @@
+import { describe, it, expect } from 'vitest'
+import { groupsFirst, groupsFirstBy } from './node-order'
+import type { CanvasNodeState } from './types'
+
+const s = (id: string, kind: CanvasNodeState['kind'], parentId?: string): CanvasNodeState =>
+ ({
+ id, kind, title: id, color: '#fff', position: { x: 0, y: 0 }, size: { width: 1, height: 1 },
+ ...(parentId ? { parentId } : {})
+ }) as CanvasNodeState
+const ids = (nodes: Array<{ id: string }>): string[] => nodes.map((n) => n.id)
+
+describe('groupsFirst — one parent-first order for every node shape', () => {
+ it('emits frames depth-first from the root, then every other node in its own order', () => {
+ const out = groupsFirst([s('x', 'terminal', 'I'), s('I', 'group', 'O'), s('y', 'sticky'), s('O', 'group')])
+ expect(ids(out)).toEqual(['O', 'I', 'x', 'y'])
+ })
+
+ it('a cyclic parentId chain is emitted once; a missing parent is not followed', () => {
+ expect(ids(groupsFirst([s('A', 'group', 'B'), s('B', 'group', 'A'), s('C', 'group', 'gone')]))).toEqual(['B', 'A', 'C'])
+ })
+
+ it('reads the group test it is given (a React Flow node says `type`)', () => {
+ const rf = [
+ { id: 'a', type: 'terminal', parentId: 'G' },
+ { id: 'G', type: 'group' }
+ ]
+ expect(ids(groupsFirstBy(rf, (n) => n.type === 'group'))).toEqual(['G', 'a'])
+ })
+})
diff --git a/src/shared/node-order.ts b/src/shared/node-order.ts
new file mode 100644
index 000000000..7316e3e91
--- /dev/null
+++ b/src/shared/node-order.ts
@@ -0,0 +1,56 @@
+// The parent-first node order — ONE definition, used by the renderer's live React Flow array
+// (`renderer/state/workspace.ts`), the server's headless canvas control, and the shared reducer
+// every canvas op goes through (`applyCanvasMutation`, which is also the Server Edition canvas
+// authority's reducer). Pure: no DOM, no fs.
+
+import type { CanvasNodeState } from './types'
+
+/** The two fields the order reads: every node shape in the app (a persisted `CanvasNodeState`,
+ * a React Flow `Node`) carries both. */
+interface OrderedNode {
+ id: string
+ parentId?: string
+}
+
+/**
+ * Group (parent) nodes must precede their descendants in the array (React Flow requirement).
+ * With nesting the old "all groups, then everything else" split is not enough — a child frame
+ * could still be emitted before its parent — so groups are emitted depth-first from the root.
+ * Non-group nodes keep their relative order, after every group.
+ *
+ * This order is also the DOWNGRADE contract: `flowToNodeStates` preserves array order, and an
+ * older build's flat `kind === 'group'` sort returns 0 for two groups, which a stable sort
+ * (ES2019+) leaves alone. So a nested tree written by this build still hydrates parent-first,
+ * and therefore still RENDERS, on a build that predates nesting. That holds for a governed
+ * project too: the Server Edition canvas authority writes the array its reducer built, and the
+ * reducer re-sorts with this whenever an op appends a node or changes its `parentId`.
+ *
+ * `isGroup` is the only thing that differs between the two node shapes (`kind` on a persisted
+ * state, `type` on a React Flow node). A cyclic `parentId` chain is emitted once, never recursed
+ * forever; a `parentId` naming a node that is absent (or not a group) is simply not followed.
+ */
+export function groupsFirstBy<T extends OrderedNode>(nodes: readonly T[], isGroup: (node: T) => boolean): T[] {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const emitted = new Set<string>()
+ const visiting = new Set<string>()
+ const groups: T[] = []
+ const emitGroup = (node: T): void => {
+ if (emitted.has(node.id) || !isGroup(node)) return
+ if (visiting.has(node.id)) return // cyclic parentId: emit once, don't recurse forever
+ visiting.add(node.id)
+ const parent = node.parentId ? byId.get(node.parentId) : undefined
+ if (parent && isGroup(parent)) emitGroup(parent)
+ visiting.delete(node.id)
+ if (!emitted.has(node.id)) {
+ emitted.add(node.id)
+ groups.push(node)
+ }
+ }
+ nodes.forEach(emitGroup)
+ return [...groups, ...nodes.filter((node) => !isGroup(node))]
+}
+
+/** `groupsFirstBy` for persisted node states (`kind === 'group'`). */
+export function groupsFirst(nodes: readonly CanvasNodeState[]): CanvasNodeState[] {
+ return groupsFirstBy(nodes, (node) => node.kind === 'group')
+}