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(glyphgrid): the real z, the render-time answer, and the gestures the drag flag can't see

enes5f108df0fa21
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
index 58026cfc0..e524dc296 100644
--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
@@ -152,13 +152,36 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
click the partially-covered terminal → it comes to the FRONT, chrome and contents together,
and nothing of the node it now covers is visible through it. Click the other one → they swap,
cleanly, with no intermediate frame in which both are legible in the same rectangle. Drag one
- over the other and back: the same, throughout the gesture and after it settles.
+ over the other and back: the same, throughout the gesture and after it settles. **Watch the
+ DROP specifically** — the frame at which the mouse is released is where the previous build
+ flashed the dropped node transparent over what it had landed on (the set is now computed
+ during Canvas's render, so the node learns it must stay opaque in the very render that ends
+ the drag). Also create a NEW terminal on top of an existing one, and reload a project whose
+ nodes already overlap: neither may flash transparent on arrival.
+- [ ] **3.9e Group drag and node resize (round 5).** Two gestures that are not a plain node drag:
+ (a) drag a GROUP FRAME containing terminals across other nodes — the terminals inside must be
+ opaque for the whole sweep (React Flow never marks a dragged frame's children `dragging`, so
+ this is covered by an ancestor walk, and it was the worst case: a frame sweeping transparent
+ terminals across the canvas); (b) grab a terminal's resize handle and drag it over a
+ neighbour — same expectation, and on release it must settle to the correct answer for its new
+ size. In both, the canvas must not visibly churn (terminals flickering between crisp and soft)
+ during the gesture: the set is frozen for its duration and recomputed once on the settle.
- [ ] **3.9c Node-attached UI that escapes the node box (round 5: the round-4 trade is GONE).** The
💬 comments flyout (`.term-node__comments`) and the kanban column half-pill (`ColumnPill`) are
positioned OUTSIDE their node's rect. With selection elevation restored they are lifted with
their node again, so: open a flyout on a terminal that another terminal overlaps, click the
node — the flyout must come to the front with it and be fully readable and clickable. Same
for a session node's column pill. Anything covered here is a defect now, not a known trade.
+ **The one case that is NOT covered and must not be filed:** the opposite direction — a
+ NEIGHBOUR's flyout or pill overhanging a *glyph* terminal. The rule compares node RECTS, and
+ these two surfaces are deliberately outside their node's rect, so a neighbour's overhang can
+ show through a transparent body. Known, stated in L15, Phase 2.
+- [ ] **3.9d Ephemeral cards over a glyph terminal (NOT a defect — confirm and move on).** With a
+ Claude node running subagents (or a /loop card up), drag the parent terminal so a subagent
+ card lands over ANOTHER terminal's body. The card may be visible through that terminal: the
+ ephemeral cards live outside Canvas's `nodes` array by design, so the opaque rule cannot see
+ them (L15). Note whether it looks broken enough to matter — that judgement is the point of the
+ item, not the artifact itself.
- [ ] **3.9b Overlap, the whole of it (round 5).** With two terminals overlapping, look at the
covered region closely. Expected: the upper node hides the lower one **completely** — no text,
no cursor, no selection band, **and no frame hairline**. Round 4's L15 ghost (the lower node's
@@ -302,14 +325,18 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
- **L6 — Adopting a parked terminal after a font change may keep a stale cell size.** The grid is
registered from the cell xterm reports at adopt time; a font change applied in the same commit
can land after it. Refreshing the node re-registers at the correct size.
-- **L7 — Group-parented z is an approximation.** The paint order is the node array order with
- selected nodes elevated (mirroring React Flow's `elevateNodesOnSelect`); React Flow additionally
- gives a grouped node `parentZ + 1`, which `effectiveStackOrder` does not model. Overlaps that mix
- grouped and ungrouped terminals can therefore order differently from the DOM. Round 5 shrinks the
- blast radius rather than fixing it: a terminal that overlaps anything below it is off the shared
- canvas entirely (L15), so a mis-ordered pair of GRIDS needs both terminals to believe they are in
- the clear — and being wrong about the order there costs a trip to the DOM renderer, never a
- bleed-through, because the two rules read the same `effectiveStackOrder`.
+- **L7 — Group-parented z: MODELLED in round 5, with one transient residual.** This used to read "an
+ approximation": the order was array order plus selection, while React Flow additionally bumps a
+ root frame into a band (`ROOT_PARENT_Z_INCREMENT`, 10 per frame in first-child order) and gives
+ each child `parentZ >= childZ ? parentZ + 1 : childZ`. That is why an unselected GROUPED terminal
+ sits above every ungrouped one wherever it is in the array, and why a selected FRAME carries its
+ children above a selected ungrouped node — both of which the old model got backwards.
+ `nodeStackZ` now reproduces the whole rule (`adoptUserNodes` → `calculateZ` / `calculateChildXYZ`
+ in `@xyflow/system`) and BOTH consumers read it — the grids' z and the opaque set — so they cannot
+ disagree about who is on top. **Residual:** React Flow reuses a node's internal object, and its z,
+ when the user node object is identical (`checkEquality`), so in a commit where only some nodes
+ were rebuilt a live z can lag this model by a pass. It converges on the next full adopt, and the
+ bands themselves are stable across the partial ones. Verify by item **3.10**.
- **L8 — The kanban card modal stays on xterm's DOM renderer, by design in v1.** The modal is a
second, co-attached view of the same tmux session living outside the canvas' coordinate space;
it has no grid, no camera and no z in the shared canvas. Board parity here is a Phase-2 question.
@@ -363,19 +390,32 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
canvas. The moment it could reveal a node beneath it, it hands the grid back and renders on
xterm's own DOM renderer — opaque body, native stacking, total occlusion. The rule is
`opaqueNodeIds` (`canvas/SharedGlyphLayer.tsx`): OPAQUE when the node's rect intersects the rect
- of any node BELOW it in the effective paint order, or while it is being dragged. A terminal that
- is only UNDERNEATH others stays on the canvas — the opaque node above hides it natively.
- Selection elevation is back on everywhere, and the frame ghost is gone with the transparency that
- caused it.
+ of any node BELOW it in the effective paint order, or while it (or a group frame containing it) is
+ in a drag or resize gesture. A terminal that is only UNDERNEATH others stays on the canvas — the
+ opaque node above hides it natively. Selection elevation is back on everywhere, and the frame
+ ghost is gone with the transparency that caused it.
**What remains, and what to watch for on device:** a stacked terminal is on the DOM renderer for
as long as it is stacked, so its text is very slightly softer than its neighbours' at zoom ≠ 1
(checklist 3.9b). The switch itself is the existing teardown/setup machinery that collapse and ⌘M
- already use, so it also costs one renderer swap per transition; the opaque set is frozen while
- anything is dragging so a neighbour cannot be swapped twice a frame. Phase 2's answer if the DOM
+ already use, so it also costs one renderer swap per transition; the opaque set is frozen for the
+ length of a gesture so a neighbour cannot be swapped twice a frame. Phase 2's answer if the DOM
fallback turns out to be frequent enough to matter is a SECOND canvas above the node layer for an
elevated tier — the two-tier design this envelope deliberately defers.
+ **TWO THINGS THE RULE DOES NOT SEE — do not file either as a defect:**
+ 1. **Ephemeral subagent / loop cards.** They are merged into React Flow at the `<ReactFlow>` prop
+ and are not in Canvas's `nodes` array (which is what keeps them out of persistence and undo),
+ so the rule cannot see them. A card sitting over a glyph terminal can therefore be visible
+ through that terminal's body. Display-only, and alive for the length of one turn.
+ 2. **A NEIGHBOUR's node-attached overhang.** The rule compares NODE RECTS, and two surfaces
+ deliberately escape their node's rect: the 💬 comments flyout (`.term-node__comments`) and the
+ kanban `ColumnPill`, both siblings of the overflow:hidden node root. Another node's flyout or
+ pill overhanging a glyph terminal is outside every rect this rule compares, so it can show
+ through. (The node's OWN flyout/pill is fine — selection elevation lifts them with it, which is
+ what 3.9c tests.) Fixing this means feeding real chrome geometry into the rule — Phase 2, and
+ the same question the "chrome on the canvas" answer settles for free.
+
---
## Result
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index f9e9f58af..beb7718aa 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -30,11 +30,14 @@ import {
import { solveFitPadding } from './fit-view'
import {
SharedGlyphLayer,
+ flushOpaqueNodeIds,
+ gestureTerminalIds,
+ hasActiveGesture,
idsFromOrderSig,
nodeOrderSig,
opaqueNodeIds,
+ primeOpaqueNodeIds,
setNodeZOrder,
- setOpaqueNodeIds,
setSharedGlyphCamera,
useSharedGlyphActive
} from './SharedGlyphLayer'
@@ -291,6 +294,10 @@ const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
const GRID = 24
+/** The empty opaque set (glyphgrid), shared so the render-time compute allocates nothing on the
+ * overwhelmingly common "nothing overlaps / layer off" path. */
+const EMPTY_OPAQUE: string[] = []
+
/** Diagonal offset for a copy made without a cursor position (⌘K, agent CLI) — the classic
* "duplicate appears slightly off the original" nudge. */
const DUPLICATE_NUDGE = 28
@@ -4986,23 +4993,45 @@ export function Canvas() {
// now, because their transparent body would otherwise reveal a node stacked beneath them. The
// rule, and why it is the rule, is documented at `opaqueNodeIds`.
//
- // WHEN it runs is this effect's job, and there is exactly one subtlety: it is FROZEN while any
- // node is being dragged. `nodes` is rebuilt every frame of a drag, and recomputing there would
- // flip the dragged node's neighbours between the two renderers at 60 Hz — each flip is a real
- // xterm renderer swap, which is both jank and a chance to land blank. Nothing is lost by
- // waiting: the DRAGGED node needs nothing from this set (TerminalNode reads React Flow's own
- // `dragging` prop and goes DOM for the whole gesture, so it occludes correctly the entire time),
- // and the drag's settle is itself a nodes change, so the set is recomputed exactly once, at rest.
- // Same cadence as the order signature above — this effect adds one `some()` per nodes change and
- // an O(n²) rect sweep per SETTLED change, over a node count that is tens.
- useEffect(() => {
+ // COMPUTED IN RENDER, DELIBERATELY. React renders a parent before its children, so this is the
+ // one moment at which a TerminalNode can read the answer for the same `nodes` array it is itself
+ // rendering with. An effect cannot: effects run CHILD FIRST, so on the commit that ends a drag
+ // the node's participation effect re-attached its glyph against the PREVIOUS set and the parent's
+ // effect then told it to tear the glyph down again — one frame of a transparent node sitting over
+ // the thing it had just been dropped on, plus a wasted attach/detach pair, and the same window on
+ // create-into-overlap and on project-load-with-overlaps. The store write is therefore PRIMED here
+ // and the NOTIFICATION is delivered by the effect below (a listener's setState during another
+ // component's render is what React refuses); `primeOpaqueNodeIds` carries the full argument.
+ //
+ // GESTURE FREEZE: while any node is dragging or resizing the O(n²) rect sweep is skipped —
+ // `nodes` is rebuilt every frame there, and each renderer swap is real work — and the last
+ // SETTLED answer is topped up with `gestureTerminalIds` (the gesture's own terminals AND the
+ // children of a dragged group frame, which React Flow never marks `dragging` themselves). That
+ // union is stable for the whole gesture, so the signature gate makes the per-frame calls free,
+ // and the batch that ENDS the gesture recomputes properly.
+ const glyphSettledOpaqueRef = useRef<string[]>(EMPTY_OPAQUE)
+ const glyphOpaqueSig = useMemo(() => {
if (!glyphLayerActive) {
- setOpaqueNodeIds([])
- return
+ glyphSettledOpaqueRef.current = EMPTY_OPAQUE
+ return primeOpaqueNodeIds(EMPTY_OPAQUE)
}
- if (nodes.some((n) => n.dragging)) return
- setOpaqueNodeIds(opaqueNodeIds(nodes))
+ if (hasActiveGesture(nodes)) {
+ const settled = glyphSettledOpaqueRef.current
+ const gesture = gestureTerminalIds(nodes)
+ return primeOpaqueNodeIds(
+ gesture.length === 0 ? settled : [...new Set([...settled, ...gesture])]
+ )
+ }
+ const next = opaqueNodeIds(nodes)
+ glyphSettledOpaqueRef.current = next
+ return primeOpaqueNodeIds(next)
}, [glyphLayerActive, nodes])
+ // The notification the render above could not send. It reaches the ONE case a render-time read
+ // cannot: a terminal whose own node object did not change (so it never re-rendered) but which
+ // something else slid underneath. Keyed on the signature, so it fires only on a real change.
+ useEffect(() => {
+ flushOpaqueNodeIds()
+ }, [glyphOpaqueSig])
const zoomRafRef = useRef<number | null>(null)
const gestureSettleRef = useRef<ReturnType<typeof setTimeout> | null>(null)
diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.ts
index 7c8fdc0c4..4209fdfb2 100644
--- a/src/renderer/canvas/SharedGlyphLayer.test.ts
+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts
@@ -2,11 +2,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
failSharedGlyph,
getSharedGlyphContext,
+ effectiveStackOrder,
+ flushOpaqueNodeIds,
+ gestureTerminalIds,
+ hasActiveGesture,
idsFromOrderSig,
nodeIsOpaque,
nodeOrderSig,
+ nodeStackZ,
nodeZFor,
opaqueNodeIds,
+ primeOpaqueNodeIds,
setNodeZOrder,
setOpaqueNodeIds,
setSharedGlyphCamera,
@@ -106,6 +112,27 @@ describe('nodeOrderSig', () => {
expect(idsFromOrderSig(sig)).toEqual(['t1', 't2'])
})
+ it('puts a GROUPED terminal above an ungrouped one that follows it in the array', () => {
+ // React Flow gives a child `parentZ + 1`, and a root frame with children is itself bumped into
+ // a band — so a grouped node outranks every ungrouped one regardless of array position. The
+ // first cut of round 5 modelled selection only and got this backwards.
+ const sig = nodeOrderSig([
+ { id: 'g', type: 'group' },
+ { id: 'inside', type: 'terminal', parentId: 'g' },
+ { id: 'outside', type: 'terminal' }
+ ])
+ expect(idsFromOrderSig(sig)).toEqual(['outside', 'inside'])
+ })
+
+ it('a SELECTED frame carries its children above a selected ungrouped terminal', () => {
+ const sig = nodeOrderSig([
+ { id: 'g', type: 'group', selected: true },
+ { id: 'inside', type: 'terminal', parentId: 'g' },
+ { id: 'outside', type: 'terminal', selected: true }
+ ])
+ expect(idsFromOrderSig(sig)).toEqual(['outside', 'inside'])
+ })
+
it('an untyped node is not a terminal (React Flow defaults type to "default")', () => {
expect(nodeOrderSig([{ id: 'a' }])).toBe('')
})
@@ -276,6 +303,73 @@ describe('setNodeZOrder', () => {
})
})
+describe('nodeStackZ (React Flow z, reproduced)', () => {
+ it('is 0 for a plain node and 1000 for a selected one', () => {
+ const z = nodeStackZ([{ id: 'a' }, { id: 'b', selected: true }])
+ expect(z.get('a')).toBe(0)
+ expect(z.get('b')).toBe(1000)
+ })
+
+ it('bumps a root frame into a band and lifts its child one above it', () => {
+ // calculateChildXYZ: parentZ >= childZ ? parentZ + 1 : childZ, with the parent bumped by
+ // ROOT_PARENT_Z_INCREMENT (10) when its first child is processed.
+ const z = nodeStackZ([{ id: 'g' }, { id: 'c', parentId: 'g' }])
+ expect(z.get('g')).toBe(10)
+ expect(z.get('c')).toBe(11)
+ })
+
+ it('gives each root frame its own band, in first-child order', () => {
+ const z = nodeStackZ([
+ { id: 'g1' },
+ { id: 'g2' },
+ { id: 'c1', parentId: 'g1' },
+ { id: 'c2', parentId: 'g2' }
+ ])
+ expect(z.get('g1')).toBe(10)
+ expect(z.get('c1')).toBe(11)
+ expect(z.get('g2')).toBe(20)
+ expect(z.get('c2')).toBe(21)
+ })
+
+ it('a selected frame carries its children above 1000', () => {
+ const z = nodeStackZ([{ id: 'g', selected: true }, { id: 'c', parentId: 'g' }])
+ expect(z.get('g')).toBe(1010)
+ expect(z.get('c')).toBe(1011)
+ })
+
+ it('a selected CHILD of an unselected frame wins on its own z', () => {
+ // childZ 1000 > parentZ 10, so the child keeps 1000 rather than parentZ + 1.
+ const z = nodeStackZ([{ id: 'g' }, { id: 'c', parentId: 'g', selected: true }])
+ expect(z.get('c')).toBe(1000)
+ })
+
+ it('ignores a child whose parent is missing or comes later (React Flow warns and gives up)', () => {
+ const z = nodeStackZ([{ id: 'c', parentId: 'g' }, { id: 'g' }])
+ expect(z.get('c')).toBe(0)
+ })
+
+ it('survives a parentId cycle', () => {
+ expect(() => nodeStackZ([{ id: 'a', parentId: 'b' }, { id: 'b', parentId: 'a' }])).not.toThrow()
+ })
+})
+
+describe('effectiveStackOrder', () => {
+ it('returns the input array itself when every z is 0 (no copy on the common canvas)', () => {
+ const nodes = [{ id: 'a' }, { id: 'b' }]
+ expect(effectiveStackOrder(nodes)).toBe(nodes)
+ })
+
+ it('breaks z ties by array order (a stable sort)', () => {
+ const order = effectiveStackOrder([
+ { id: 'a' },
+ { id: 'b' },
+ { id: 'c', selected: true },
+ { id: 'd' }
+ ])
+ expect(order.map((n) => n.id)).toEqual(['a', 'b', 'd', 'c'])
+ })
+})
+
describe('opaqueNodeIds', () => {
/** A 100×100 node at (x, y). Sizes come through `measured` (a live canvas) unless overridden. */
const at = (
@@ -395,6 +489,72 @@ describe('opaqueNodeIds', () => {
it('reports every stacked terminal on a pile, not just the top one', () => {
expect(opaqueNodeIds([at('a', 0, 0), at('b', 20, 20), at('c', 40, 40)])).toEqual(['b', 'c'])
})
+
+ it('marks the GROUPED terminal, not the ungrouped one that follows it in the array', () => {
+ // The grouped terminal is above by React Flow's z (parentZ + 1) even though it comes FIRST.
+ // Reading array order alone marked the wrong node — the ungrouped one would have gone opaque
+ // while the grouped one stayed transparent ON TOP of it.
+ const group: StackedNode = {
+ id: 'g',
+ type: 'group',
+ position: { x: 0, y: 0 },
+ measured: { width: 400, height: 400 }
+ }
+ const inside = at('inside', 20, 20, { parentId: 'g' })
+ const outside = at('outside', 60, 60)
+ expect(opaqueNodeIds([group, inside, outside])).toEqual(['inside'])
+ })
+})
+
+describe('hasActiveGesture / gestureTerminalIds', () => {
+ const node = (id: string, extra: Partial<StackedNode> = {}): StackedNode => ({
+ id,
+ type: 'terminal',
+ position: { x: 0, y: 0 },
+ measured: { width: 100, height: 100 },
+ ...extra
+ })
+
+ it('sees a drag and a RESIZE alike', () => {
+ expect(hasActiveGesture([node('a')])).toBe(false)
+ expect(hasActiveGesture([node('a', { dragging: true })])).toBe(true)
+ expect(hasActiveGesture([node('a', { resizing: true })])).toBe(true)
+ })
+
+ it('a gesture on a NON-terminal still freezes (it changes who overlaps whom)', () => {
+ expect(hasActiveGesture([node('s', { type: 'sticky', dragging: true })])).toBe(true)
+ expect(gestureTerminalIds([node('s', { type: 'sticky', dragging: true })])).toEqual([])
+ })
+
+ it('names the dragged terminal itself', () => {
+ expect(gestureTerminalIds([node('a', { dragging: true }), node('b')])).toEqual(['a'])
+ })
+
+ it('names the CHILDREN of a dragged group frame', () => {
+ // React Flow's getDragItems excludes children of a dragged parent, so they never carry
+ // `dragging` themselves — without the ancestor walk they stayed transparent all gesture.
+ const nodes: StackedNode[] = [
+ node('g', { type: 'group', dragging: true }),
+ node('c1', { parentId: 'g' }),
+ node('c2', { parentId: 'g' }),
+ node('far')
+ ]
+ expect(gestureTerminalIds(nodes)).toEqual(['c1', 'c2'])
+ })
+
+ it('walks more than one level of frame', () => {
+ const nodes: StackedNode[] = [
+ node('outer', { type: 'group', resizing: true }),
+ node('inner', { type: 'group', parentId: 'outer' }),
+ node('t', { parentId: 'inner' })
+ ]
+ expect(gestureTerminalIds(nodes)).toEqual(['t'])
+ })
+
+ it('survives a parentId cycle', () => {
+ const nodes: StackedNode[] = [node('a', { parentId: 'b' }), node('b', { parentId: 'a' })]
+ expect(() => gestureTerminalIds(nodes)).not.toThrow()
+ })
})
describe('setOpaqueNodeIds', () => {
@@ -451,6 +611,50 @@ describe('setOpaqueNodeIds', () => {
})
})
+describe('primeOpaqueNodeIds / flushOpaqueNodeIds', () => {
+ it('primes the ANSWER immediately and the NOTIFICATION only on flush', () => {
+ // This is the ordering fix: Canvas primes during its own render (a listener's setState there is
+ // what React refuses), so a child reads the current answer while rendering, and the
+ // notification — needed only by nodes that did not re-render — follows from an effect.
+ const seen = vi.fn()
+ const unsub = subscribeOpaqueSet(seen)
+ primeOpaqueNodeIds(['a'])
+ expect(nodeIsOpaque('a')).toBe(true)
+ expect(seen).not.toHaveBeenCalled()
+ flushOpaqueNodeIds()
+ expect(seen).toHaveBeenCalledTimes(1)
+ unsub()
+ })
+
+ it('returns the signature, so the caller can key an effect on it', () => {
+ expect(primeOpaqueNodeIds(['b', 'a'])).toBe(primeOpaqueNodeIds(['a', 'b']))
+ })
+
+ it('a flush with nothing pending is free', () => {
+ primeOpaqueNodeIds(['a'])
+ flushOpaqueNodeIds()
+ const seen = vi.fn()
+ const unsub = subscribeOpaqueSet(seen)
+ flushOpaqueNodeIds()
+ flushOpaqueNodeIds()
+ expect(seen).not.toHaveBeenCalled()
+ unsub()
+ })
+
+ it('coalesces several primes into ONE notification', () => {
+ const seen = vi.fn()
+ const unsub = subscribeOpaqueSet(seen)
+ primeOpaqueNodeIds(['a'])
+ primeOpaqueNodeIds(['a', 'b'])
+ primeOpaqueNodeIds(['c'])
+ flushOpaqueNodeIds()
+ expect(seen).toHaveBeenCalledTimes(1)
+ expect(nodeIsOpaque('c')).toBe(true)
+ expect(nodeIsOpaque('a')).toBe(false)
+ unsub()
+ })
+})
+
describe('graceful degrade without a GPU', () => {
/** A plausible xterm device cell (13px font at dpr 2): fractional width, integer height. */
const CELL = { cellW: 15.66, cellH: 31 }
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index d78233fb0..cd01e133f 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -181,35 +181,98 @@ let zOrder = new Map<string, number>()
let zOrderSig = ''
const zListeners = new Set<() => void>()
+/** React Flow's own stacking constants (`@xyflow/system`, `SELECTED_NODE_Z` /
+ * `ROOT_PARENT_Z_INCREMENT`). Copied rather than imported because they are not exported; pinned
+ * by `nodeStackZ`'s tests, which state the rule they came from. */
+const SELECTED_NODE_Z = 1000
+const ROOT_PARENT_Z_INCREMENT = 10
+
+/** The node fields the stacking model reads. */
+export interface StackOrderNode {
+ id: string
+ parentId?: string
+ selected?: boolean
+}
+
/**
- * The order React Flow actually PAINTS the nodes in: array order, with selected nodes moved to
- * the end (stable within each of the two groups). That is `elevateNodesOnSelect` — on by default,
- * and the only DOM stacking rule this app uses that diverges from array order.
+ * REPRODUCTION of the z React Flow assigns each node, for this app's configuration: no explicit
+ * `zIndex` anywhere, default `zIndexMode` ('auto'), and `elevateNodesOnSelect` at its default
+ * (on). The algorithm is `adoptUserNodes` → `calculateZ` / `updateChildNode` / `calculateChildXYZ`
+ * in `@xyflow/system`, transcribed:
+ *
+ * - Every node starts at `selected ? 1000 : 0`.
+ * - The FIRST time a ROOT parent (a frame with no parent of its own) has a child processed, that
+ * parent's z is bumped by `++counter * 10`. Root frames are therefore separated into bands in
+ * the order their first child appears.
+ * - A child's z is `parentZ >= childZ ? parentZ + 1 : childZ` — so an unselected node inside a
+ * frame outranks EVERY ungrouped unselected node, wherever it sits in the array, and a SELECTED
+ * FRAME carries its children up with it (parentZ 1000+ ⇒ children 1001+, above a selected
+ * ungrouped node at 1000).
+ * - Returning to an already-indexed parent resets the running counter to that parent's index,
+ * which is why the counter is not monotonic. Reproduced, because it decides the bands.
+ *
+ * That last group of rules is the part round 5's first cut got wrong: it modelled selection only,
+ * which said a grouped terminal was BELOW an ungrouped one it is in fact above — and the opaque
+ * rule reads this order to decide who may stay transparent.
+ *
+ * Known residual, and why it is small: React Flow reuses a node's internal object (and its z) when
+ * the user node object is identical (`checkEquality`), so in a transient where only some nodes were
+ * rebuilt a live z can lag this model by a commit. It converges on the next full adopt, and the
+ * bands themselves (which frame is above which) are stable across those partial passes.
+ */
+export function nodeStackZ(nodes: readonly StackOrderNode[]): Map<string, number> {
+ const z = new Map<string, number>()
+ const byId = new Map<string, StackOrderNode>()
+ for (const n of nodes) byId.set(n.id, n)
+ const rootParentIndex = new Map<string, number>()
+ let counter = 0
+ for (const node of nodes) {
+ const ownZ = node.selected ? SELECTED_NODE_Z : 0
+ z.set(node.id, ownZ)
+ if (!node.parentId) continue
+ const parent = byId.get(node.parentId)
+ // React Flow warns and gives up on a child whose parent is missing or comes LATER in the
+ // array; `nodeStatesToFlow` sorts parents first precisely so this cannot happen.
+ if (!parent || !z.has(parent.id)) continue
+ if (!parent.parentId && !rootParentIndex.has(parent.id)) {
+ counter += 1
+ rootParentIndex.set(parent.id, counter)
+ z.set(parent.id, (z.get(parent.id) ?? 0) + counter * ROOT_PARENT_Z_INCREMENT)
+ }
+ const known = rootParentIndex.get(parent.id)
+ if (known !== undefined) counter = known
+ const parentZ = z.get(parent.id) ?? 0
+ z.set(node.id, parentZ >= ownZ ? parentZ + 1 : ownZ)
+ }
+ return z
+}
+
+/**
+ * The order React Flow actually PAINTS the nodes in: ascending `nodeStackZ`, ties broken by array
+ * order (a stable sort). Later in this list = nearer the viewer.
*
* ONE function, because two consumers must never disagree about it: `nodeOrderSig` (the grids' z)
* and `opaqueNodeIds` (which terminals may stay on the shared canvas at all). If the opaque set
* were derived from a different order than the z, a terminal could be told it is in the clear by
- * one rule and painted underneath by the other — the mixed-order soup of round 4, reintroduced
- * one level down.
- *
- * Approximation, deliberately: React Flow also gives a group frame's children a z above the frame
- * itself, and honours an explicit `zIndex`, neither of which we set. `opaqueNodeIds` is written so
- * that being wrong here costs a terminal a trip to the DOM renderer, never a bleed-through.
+ * one rule and painted underneath by the other — the mixed-order soup of round 4, reintroduced one
+ * level down.
*/
-export function effectiveStackOrder<T extends { selected?: boolean }>(
- nodes: readonly T[]
-): readonly T[] {
- let elevated: T[] | null = null
+export function effectiveStackOrder<T extends StackOrderNode>(nodes: readonly T[]): readonly T[] {
+ const z = nodeStackZ(nodes)
+ let ordered = false
for (const n of nodes) {
- if (!n.selected) continue
- if (!elevated) elevated = []
- elevated.push(n)
+ if (z.get(n.id) !== 0) {
+ ordered = true
+ break
+ }
}
- // Nothing selected — the overwhelmingly common case — is the input array itself, no copy.
- if (!elevated) return nodes
- const base: T[] = []
- for (const n of nodes) if (!n.selected) base.push(n)
- return base.concat(elevated)
+ // A flat, unselected canvas — the overwhelmingly common case — is already in paint order; return
+ // the input array itself rather than an identical copy.
+ if (!ordered) return nodes
+ return nodes
+ .map((n, i) => ({ n, i, z: z.get(n.id) ?? 0 }))
+ .sort((a, b) => a.z - b.z || a.i - b.i)
+ .map((e) => e.n)
}
/**
@@ -220,10 +283,9 @@ export function effectiveStackOrder<T extends { selected?: boolean }>(
* Only terminals: they are the only kind that registers a grid, and mixing other kinds in would
* churn the signature on every sticky edit.
*
- * **The rule is `effectiveStackOrder` — array order, with SELECTED nodes last** — because that is
- * what the DOM does: React Flow's `elevateNodesOnSelect` is on by default and lifts a selected
- * node's z-index to 1000 wherever it sits in the array. The canvas z among the glyph grids mirrors
- * the DOM elevation, so both worlds tell the same story about who is on top.
+ * **The rule is `effectiveStackOrder`** — React Flow's own z (selection elevation AND group-frame
+ * banding; see `nodeStackZ`), ties broken by array order. The canvas z among the glyph grids
+ * mirrors the DOM's, so both worlds tell the same story about who is on top.
*
* Round 4 removed the mirroring and turned the PROP off instead. That was the wrong end of the
* problem: it did make the two orders agree, but at the cost of "click/drag brings a node to the
@@ -239,7 +301,7 @@ export function effectiveStackOrder<T extends { selected?: boolean }>(
* which a wrong z is visible, which is why the mirroring is worth its handful of lines.
*/
export function nodeOrderSig(
- nodes: readonly { id: string; type?: string; selected?: boolean }[]
+ nodes: readonly (StackOrderNode & { type?: string })[]
): string {
let sig = ''
for (const n of effectiveStackOrder(nodes)) {
@@ -325,22 +387,32 @@ export function subscribeNodeZOrder(fn: () => void): () => void {
* React Flow has measured a fresh node). They contribute nothing in either direction, and the
* measurement lands as an ordinary nodes change that recomputes the set.
*
- * Known gap, small and stated rather than papered over: the EPHEMERAL subagent/loop cards are
- * merged into React Flow at the `<ReactFlow>` prop and are not in Canvas's `nodes` array, so they
- * are invisible to this rule. They are display-only cards that live for the length of one turn.
+ * TWO KNOWN GAPS, stated rather than papered over — a device tester must not file either as a bug:
+ * - The EPHEMERAL subagent/loop cards are merged into React Flow at the `<ReactFlow>` prop and are
+ * not in Canvas's `nodes` array, so they are invisible to this rule. A card can therefore sit
+ * over a glyph terminal and be visible through its body. They are display-only, they live for
+ * the length of one turn, and putting them in the rule means putting them in the nodes array,
+ * which is precisely what keeps them out of persistence and undo.
+ * - The rule compares NODE RECTS, and two node-attached surfaces deliberately escape their node's
+ * rect: the 💬 comments flyout (`.term-node__comments`) and the kanban `ColumnPill`, both
+ * siblings of the overflow:hidden node root. A NEIGHBOUR's flyout or pill overhanging a glyph
+ * terminal is not seen here, so it can show through that terminal's body. Fixing it means
+ * feeding real chrome geometry into the rule — a Phase-2 question, and the same one L15's other
+ * Phase-2 answer (chrome on the canvas) settles for free.
*/
/** Node shape this derivation reads. Loose on purpose: it must accept a live measured node and a
* freshly deserialized one (`width`/`height`, no `measured`) alike. */
-export interface StackedNode {
- id: string
+export interface StackedNode extends StackOrderNode {
type?: string
- selected?: boolean
position: { x: number; y: number }
- parentId?: string
width?: number | null
height?: number | null
measured?: { width?: number | null; height?: number | null }
+ /** React Flow's own gesture flags: `dragging` during a node drag, `resizing` while a
+ * `NodeResizer` handle is held. */
+ dragging?: boolean
+ resizing?: boolean
data?: { collapsed?: unknown; mdMode?: unknown }
}
@@ -430,25 +502,102 @@ export function opaqueNodeIds(nodes: readonly StackedNode[]): string[] {
return out
}
+/**
+ * Is a node GESTURE (drag or `NodeResizer` resize) in progress anywhere on the canvas? While one
+ * is, the O(n²) rect sweep above is skipped: `nodes` is rebuilt every frame of a gesture, and
+ * recomputing there would flip a terminal's neighbours between the two renderers at 60 Hz — each
+ * flip is a real xterm renderer swap. The frozen set is topped up with `gestureTerminalIds`.
+ */
+export function hasActiveGesture(nodes: readonly StackedNode[]): boolean {
+ for (const n of nodes) if (n.dragging || n.resizing) return true
+ return false
+}
+
+/**
+ * The terminals that must be opaque BECAUSE OF a gesture: their own node is being dragged/resized,
+ * or an ANCESTOR is.
+ *
+ * The ancestor half is not a nicety. React Flow's `getDragItems` excludes the children of a dragged
+ * parent (the frame moves, the children ride along on `positionAbsolute`), so dragging a GROUP
+ * never sets `dragging` on the terminals inside it. Without this walk those terminals stayed
+ * transparent for the whole gesture while the frame swept them across the canvas — the worst case
+ * of the bug this design exists to fix, and the one case the per-node `dragging` prop cannot see.
+ *
+ * The dragged node itself is included even though TerminalNode also reads its own `dragging` prop:
+ * one answer, from one place, for a state two consumers act on.
+ */
+export function gestureTerminalIds(nodes: readonly StackedNode[]): string[] {
+ const byId = new Map<string, StackedNode>()
+ for (const n of nodes) byId.set(n.id, n)
+ const out: string[] = []
+ for (const node of nodes) {
+ if (node.type !== 'terminal') continue
+ let cur: StackedNode | undefined = node
+ const seen = new Set<string>()
+ for (let depth = 0; cur && depth <= MAX_PARENT_DEPTH; depth++) {
+ if (cur.dragging || cur.resizing) {
+ out.push(node.id)
+ break
+ }
+ if (seen.has(cur.id)) break
+ seen.add(cur.id)
+ cur = cur.parentId ? byId.get(cur.parentId) : undefined
+ }
+ }
+ return out
+}
+
let opaqueIds = new Set<string>()
let opaqueSig = ''
+let opaquePending = false
const opaqueListeners = new Set<() => void>()
/**
- * Publish the opaque set. Change-gated on a SORTED signature — this is a set, not a sequence, so
- * the same membership arriving in a different order (a node reorder that changes nothing about who
- * overlaps whom) must not wake every terminal on the canvas.
+ * Store the opaque set WITHOUT notifying, returning the signature. Change-gated on a SORTED
+ * signature — this is a set, not a sequence, so the same membership arriving in a different order
+ * (a node reorder that changes nothing about who overlaps whom) must not wake every terminal.
+ *
+ * **The split from `flushOpaqueNodeIds` is the ordering fix, and it is the point of this seam.**
+ * Canvas computes the set DURING ITS RENDER, because React renders a parent before its children:
+ * that is the only moment at which a TerminalNode can read the answer for the same `nodes` array
+ * it is itself rendering with. Computing it in an effect cannot work — effects run CHILD FIRST, so
+ * on the commit that ends a drag the node's participation effect re-attached a glyph against the
+ * PREVIOUS set, and the parent's effect then told it to tear the glyph down again: one frame of a
+ * transparent node sitting over the thing it had just been dropped on, plus a wasted attach/detach
+ * pair. The same window opened on create-into-overlap and on project-load-with-overlaps.
+ *
+ * Notifying cannot happen there, though: a listener's `setState` during another component's render
+ * is exactly what React refuses. So the write and the notification are separated — the write is
+ * safe during render, and `flushOpaqueNodeIds` (an effect) delivers the notification afterwards,
+ * for the one case a render-time read cannot cover: a node whose own object did not change and
+ * which therefore did not re-render at all (something slid UNDER it).
*/
-export function setOpaqueNodeIds(ids: readonly string[]): void {
+export function primeOpaqueNodeIds(ids: readonly string[]): string {
const sig = [...ids].sort().join(ORDER_SEP)
- if (sig === opaqueSig) return
+ if (sig === opaqueSig) return sig
opaqueSig = sig
opaqueIds = new Set(ids)
+ opaquePending = true
+ return sig
+}
+
+/** Deliver the notification for a primed change. Idempotent — a second call with nothing pending
+ * is free, which is what lets Canvas call it from an effect keyed on the signature. */
+export function flushOpaqueNodeIds(): void {
+ if (!opaquePending) return
+ opaquePending = false
for (const fn of opaqueListeners) fn()
}
+/** Prime + flush in one call. The imperative form, for callers that are NOT inside a render. */
+export function setOpaqueNodeIds(ids: readonly string[]): void {
+ primeOpaqueNodeIds(ids)
+ flushOpaqueNodeIds()
+}
+
/** Must this node paint its own pixels right now? Always false while nothing has been pushed,
- * which is every default-mode session. */
+ * which is every default-mode session. Read at RENDER time by TerminalNode (see above) — never
+ * mirrored into state, which is what would make it stale. */
export function nodeIsOpaque(id: string): boolean {
return opaqueIds.has(id)
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index d6c11ed53..52245c293 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -566,15 +566,35 @@ export function TerminalNode({
// runs after the font options have reached xterm — see the participation effect below.
const [glyphEpoch, setGlyphEpoch] = useState(0)
// Is this node in the shared layer's OPAQUE SET — i.e. does its body currently sit over another
- // node, so that a transparent glyph window would let that node show through? Pushed by Canvas
- // and read back here; see the stacking rule at `opaqueNodeIds`. Always false while the shared
- // layer is off (nothing is ever pushed), so the subscription below costs a default-mode session
- // one Set insert per terminal and no renders at all.
- const [glyphOpaque, setGlyphOpaque] = useState(() => nodeIsOpaque(id))
+ // node, so that a transparent glyph window would let that node show through? See the stacking
+ // rule at `opaqueNodeIds`.
+ //
+ // READ AT RENDER TIME, never mirrored into state, and that is the whole ordering fix. Canvas
+ // computes and stores the set during ITS render, and React renders a parent before its children —
+ // so this read always sees the answer for the same `nodes` array that produced the `dragging`
+ // prop and the position we are rendering with. Held in state instead, it lagged by a commit, and
+ // the lag was visible: on the commit that ended a drag this node re-attached a glyph against the
+ // stale set and tore it down again one pass later, flashing transparent over the node it had just
+ // been dropped on. Same window on create-into-overlap and project-load-with-overlaps.
+ //
+ // The subscription exists for the ONE case a render-time read cannot cover: this node's own
+ // object did not change (so it did not re-render) and something else slid underneath it. It
+ // forces a re-render, and only when OUR membership actually flipped — a set change elsewhere on
+ // the canvas must not re-render every terminal. `glyphOpaqueRef` is the last value we rendered
+ // with, written below on every render so the two paths cannot disagree.
+ const [, bumpGlyphOpaque] = useState(0)
+ const glyphOpaque = nodeIsOpaque(id)
+ const glyphOpaqueRef = useRef(glyphOpaque)
+ glyphOpaqueRef.current = glyphOpaque
useEffect(() => {
- const read = (): void => setGlyphOpaque(nodeIsOpaque(id))
- // Read once on (re-)subscribe: the set can have been pushed between this node's render and
- // this effect, and nothing would notify us about a change we were not yet listening for.
+ const read = (): void => {
+ const now = nodeIsOpaque(id)
+ if (now === glyphOpaqueRef.current) return
+ glyphOpaqueRef.current = now
+ bumpGlyphOpaque((n) => n + 1)
+ }
+ // Once on (re-)subscribe: the set can have been pushed between this node's render and this
+ // effect, and nothing would notify us about a change we were not yet listening for.
read()
return subscribeOpaqueSet(read)
}, [id])
@@ -1267,10 +1287,22 @@ export function TerminalNode({
if (glyphOffRef.current) {
// Held OFF the shared canvas — and which half of `glyphOff` it is decides the budget
// client. Covered up (collapsed / ⌘M): nothing to draw, so no client, exactly as before.
- // Held OPAQUE (stacked over another node, or being dragged): this terminal is fully
- // visible and painting its own pixels, so it is a WebGL client like any default-mode
- // terminal — without this it would end up with NEITHER renderer coordinated and quietly
- // run on xterm's DOM renderer for as long as the overlap lasts.
+ // Held OPAQUE (stacked over another node, or in a gesture): this terminal is fully visible
+ // and painting its own pixels, so it is a WebGL client like any default-mode terminal.
+ //
+ // BE HONEST ABOUT WHAT THIS IS. Today it is BOOKKEEPING, not a behaviour change: in shared
+ // mode `sharedGlyphAvailable()` is true, so the mount path never registered a budget client
+ // for this node in the first place and an opaque terminal simply runs on xterm's DOM
+ // renderer — visibly fine, just unaccelerated. This line makes the accounting say what is
+ // actually true, which is what a future "shared mode with a live per-node WebGL budget"
+ // needs, and it is NOT yet invariant-complete: the paths that can still leave an opaque
+ // terminal without a client are the generation-bump handler (it tears down and defers to
+ // the participation effect, which lands here and now arms the client — covered), and the
+ // expand / ⌘M-exit transitions of a node that is ALSO opaque (collapsed→expanded while
+ // stacked: `glyphHiddenRef` has already flipped by the time we run, so this arms it —
+ // also covered), against the reverse order in a single commit where both flip at once,
+ // which is not. Finishing it means moving the budget decision out of these two gates and
+ // into one derivation; that is Phase 2's job, with the live budget.
if (!glyphHiddenRef.current) ensureWebglClient()
return
}
@@ -2238,10 +2270,16 @@ export function TerminalNode({
// the node root) and removes `glyphgrid-mode` from the xterm element, which is exactly what makes
// the body opaque and the DOM rows visible again. Nothing here is a special case for stacking.
//
- // `dragging` flips synchronously at gesture start, so a drag goes DOM before the node has moved a
- // pixel and stays there until it settles — no mid-gesture flip back, and the drop position's
- // overlap answer arrives with the settle. HYSTERESIS is otherwise Canvas's job: it freezes the
- // opaque set while anything is dragging, so a neighbour cannot be swapped renderer twice a frame.
+ // ORDERING, the second time: `glyphOff` is built from a RENDER-TIME read of the opaque set, which
+ // Canvas stores during its own render — i.e. before this component rendered at all. So on the
+ // commit that ends a drag, `dragging: false` and the post-drop overlap answer arrive TOGETHER,
+ // and this effect makes one decision instead of attaching a glyph and tearing it down again a
+ // pass later. Do not "simplify" that read into state; state is exactly what lagged.
+ //
+ // `dragging` (this node's own prop) is kept alongside because it flips synchronously at gesture
+ // start and needs nobody else. Children of a dragged GROUP frame never get it — React Flow's
+ // `getDragItems` excludes them — which is why the set carries `gestureTerminalIds` too, and why
+ // one gesture answer coming from two places is deliberate rather than redundant.
//
// No-op (one ref null check) unless this node participates in the shared canvas.
useEffect(() => {