Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(glyphgrid): the cursor blinks, and the idle park survives it
enes1e7a7525a118
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.mdindex 7061a49b0..3aecbed18 100644--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md@@ -225,8 +225,17 @@ Auto after you switched builds, that is why: re-select Shared and carry on.- [ ] **2.8 Selection visual.** Drag-select inside a terminal: the selection band covers exactlythe selected cells, with correct fg/bg inversion, and matches what the DOM renderer draws.- [ ] **2.9 Cursor.** A focused terminal shows a cursor at the right cell (a solid block, with the- default setting). It is **static** — it does not blink even with "Cursor blink" on (known- limitation L1).+ default setting).+ **Blink.** With Settings → Terminal → "Cursor blink" ON, the cursor of the FOCUSED terminal+ flashes at xterm's own rate (600 ms shown, 600 ms hidden) while every other terminal on the+ canvas holds a steady shape; with the setting OFF it is rock steady. Then check the three ways+ it can STOP, each of which must leave the cursor **shown** rather than stuck invisible: turn+ the setting off while it happens to be in its hidden phase, click from one terminal into+ another, and open the kanban board (⌘⇧B) and come back.+ **Report a static cursor as the state of the wiring, not as a bug, until the hook named in L1+ lands** — the canvas-level clock ships here (one clock, focused terminal only, drawn through+ the frame loop's one-shot `pulse()`; see 4.19), but the per-terminal repaint it calls is still+ owed.**The cursor honours Settings → Terminal → Cursor style.** Walk all three: `block` INVERTS theglyph under it (the letter goes dark on a bright cell — a block is drawn as a CELL, and that isthe only path that can invert), `bar` is a hairline down the LEFT edge with the glyph still@@ -454,6 +463,14 @@ Auto after you switched builds, that is why: re-select Shared and carry on.- pan and zoom the canvas → everything keeps repainting smoothly throughout;- switch to another application for a minute and come back → the canvas is live again(focus/visibilitychange wake).+ **The one expected exception to "quiet" is a blinking cursor** (2.9): with a terminal FOCUSED+ and "Cursor blink" on, the canvas ticks about TWICE A SECOND — one frame per phase flip,+ drawn through the loop's one-shot `pulse()` — and that is not a missed park. The FAILURE+ there is the opposite reading: an FPS meter at the display's refresh rate with nothing but a+ blinking cursor happening means the blink took the `wake()` path and is re-arming the 30-frame+ idle streak twice a second. Click into a terminal, leave everything else idle, and confirm the+ meter reads ~2 rather than 60. (Until the phase hook in L1 lands nothing blinks, so this case+ reads as fully quiet.)**BLOCKING symptom to name explicitly: if ANY terminal ever stops repainting until you dragit, click it, or resize something, that is a MISSED WAKE** — the failure this design fears,and far worse than the idle CPU it saves. Report it with what the terminal was doing when it@@ -501,9 +518,19 @@ Auto after you switched builds, that is why: re-select Shared and carry on.## Known limitations (accepted for Phase 1b — verify they are what you see, not that they are absent)-- **L1 — The cursor does not blink.** The shared renderer paints a static block cursor regardless- of the "Cursor blink" setting. Decide on device whether this ships as-is or the setting should be- gated in shared mode.+- **L1 — The cursor does not blink YET: the clock ships, the per-terminal phase hook is owed.**+ Phase 2's blink task built the half that is hard to get right — one canvas-level clock+ (`createCursorBlinkClock` in `SharedGlyphLayer.tsx`), gated on the setting, on a terminal holding+ focus and on the board, whose repaint goes through the frame loop's one-shot `pulse()` so an idle+ canvas ticks twice a second instead of returning to the display's refresh rate (4.19). What is+ missing is the PRODUCER: nothing calls `setCursorBlinkTarget` yet, because the phase has to be+ applied by the addon — a block cursor is a CELL rewrite and every other shape is an overlay, so+ only `GlyphGridRendererAddonCore` can suppress whichever half a terminal is drawing. It needs a+ `setCursorBlinkPhase(visible)` entry point (repacking the cursor row SYNCHRONOUSLY — a deferred+ repack escapes the clock's damage bracket and takes the `wake()` path, which is the failure the+ clock exists to prevent) plus a focus-driven `setCursorBlinkTarget(…)` call from the attach shell.+ Both files were out of scope for the task that built the clock. Until then the shared renderer+ paints a static cursor regardless of the setting, exactly as it did in Phase 1b.- **L4 — Square plate corners.** The grid's plate is a rectangle; the node has `border-radius: 10px`and cannot clip the canvas (it is not a DOM child), so the body's corners read square in sharedmode. Phase 2: rounded/stencilled plate.diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.tsindex 5aebc8445..9d0def382 100644--- a/src/renderer/canvas/SharedGlyphLayer.test.ts+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts@@ -3,6 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { createFrameLoop, type FrameLoop, type FrameLoopHost } from '../glyphgrid/frame-driver'import {createBoardFrameGate,+ createCursorBlinkClock,+ cursorBlinkTarget,+ setCursorBlinkTarget,+ subscribeCursorBlinkTarget,+ CURSOR_BLINK_INTERVAL_MS,failSharedGlyph,getSharedGlyphContext,effectiveStackOrder,@@ -28,6 +33,8 @@ import {syncAtlasPixelRatio,useSharedGlyph,type AtlasResetSource,+ type CursorBlinkClock,+ type CursorBlinkTarget,type StackedNode,type StackOrderNode} from './SharedGlyphLayer'@@ -1225,6 +1232,251 @@ describe('createBoardFrameGate', () => {})})+describe('createCursorBlinkClock', () => {+ /**+ * Everything the clock touches is injected, so the whole policy — the three gates, the phase, the+ * teardown and the damage routing — is exercisable without a DOM, a timer or a GPU.+ *+ * The fake TARGET damages the engine when it repaints, exactly as the addon's cursor-row repack+ * does (`updateRow`/`setCursor` → `markDirty` → the layer's damage subscription). That is the+ * whole point of the harness: the trap this task exists to avoid is not visible unless the+ * repaint's own damage is modelled.+ */+ function blinkHarness(opts: { enabled?: boolean; covered?: boolean } = {}): {+ clock: CursorBlinkClock+ phases: boolean[]+ loop: { wake: ReturnType<typeof vi.fn>; pulse: ReturnType<typeof vi.fn> }+ intervalsStarted(): number+ intervalsCleared(): number+ running(): boolean+ tick(): void+ focus(name?: string): CursorBlinkTarget+ blur(): void+ setEnabled(on: boolean): void+ setCovered(on: boolean): void+ phasesOf(target: CursorBlinkTarget): boolean[]+ } {+ const phases: boolean[] = []+ const perTarget = new Map<CursorBlinkTarget, boolean[]>()+ const loop = { wake: vi.fn(), pulse: vi.fn() }+ const state = {+ enabled: opts.enabled ?? true,+ covered: opts.covered ?? false,+ target: null as CursorBlinkTarget | null+ }+ let started = 0+ let cleared = 0+ let fire: (() => void) | null = null++ const clock = createCursorBlinkClock({+ enabled: () => state.enabled,+ covered: () => state.covered,+ target: () => state.target,+ loop: () => loop,+ setInterval: (cb) => {+ started+++ fire = cb+ return started+ },+ clearInterval: () => {+ cleared+++ fire = null+ }+ })++ const focus = (): CursorBlinkTarget => {+ const target: CursorBlinkTarget = {+ setPhase(visible: boolean): void {+ phases.push(visible)+ const own = perTarget.get(target) ?? []+ own.push(visible)+ perTarget.set(target, own)+ // The repack dirties the engine, synchronously, from inside `setPhase`.+ clock.routeDamage()+ }+ }+ state.target = target+ clock.sync()+ return target+ }++ return {+ clock,+ phases,+ loop,+ intervalsStarted: () => started,+ intervalsCleared: () => cleared,+ running: () => fire !== null,+ tick: () => fire?.(),+ focus,+ blur: () => {+ state.target = null+ clock.sync()+ },+ setEnabled: (on) => {+ state.enabled = on+ clock.sync()+ },+ setCovered: (on) => {+ state.covered = on+ clock.sync()+ },+ phasesOf: (target) => perTarget.get(target) ?? []+ }+ }++ it('has no clock at all while no terminal has focus', () => {+ // The canvas everybody actually leaves open: terminals on screen, focus in the editor or in+ // another app. A clock here would be a repaint twice a second for a cursor nobody is on.+ const h = blinkHarness()+ h.clock.sync()+ expect(h.running()).toBe(false)+ expect(h.intervalsStarted()).toBe(0)+ })++ it('has no clock while the blink setting is off', () => {+ const h = blinkHarness({ enabled: false })+ h.focus()+ expect(h.running()).toBe(false)+ })++ it('has no clock while the kanban board covers the canvas', () => {+ // The board gate has STOPPED the loop, so a phase flip would repack a row nobody draws, every+ // 600 ms, for as long as the board is up.+ const h = blinkHarness({ covered: true })+ h.focus()+ expect(h.running()).toBe(false)+ })++ it('starts one clock when a focused terminal and the setting agree', () => {+ const h = blinkHarness()+ h.focus()+ expect(h.running()).toBe(true)+ expect(h.intervalsStarted()).toBe(1)+ })++ it('alternates the phase, starting from SHOWN', () => {+ const h = blinkHarness()+ h.focus()+ expect(h.phases).toEqual([]) // a freshly focused terminal gets a full period before it hides+ h.tick()+ h.tick()+ h.tick()+ expect(h.phases).toEqual([false, true, false])+ })++ it('repaints through pulse(), NEVER through wake — the park must survive the blink', () => {+ // THE test of this task. `wake()` would draw the frame and then hold rAF alive for another+ // IDLE_FRAMES_BEFORE_PARK frames, twice a second, forever.+ const h = blinkHarness()+ h.focus()+ h.tick()+ h.tick()+ expect(h.loop.pulse).toHaveBeenCalledTimes(2)+ expect(h.loop.wake).not.toHaveBeenCalled()+ })++ it('leaves ORDINARY damage on the wake path — only the blink is a one-shot', () => {+ // Damage from a terminal writing rows is likely to be followed by more, which is exactly what+ // `wake()` is for. Routing everything through `pulse()` would cost a scheduling hop per frame+ // of a streaming terminal.+ const h = blinkHarness()+ h.focus()+ h.clock.routeDamage()+ expect(h.loop.wake).toHaveBeenCalledTimes(1)+ expect(h.loop.pulse).not.toHaveBeenCalled()+ })++ it('a sync that changes nothing does not restart the interval', () => {+ const h = blinkHarness()+ h.focus()+ h.clock.sync()+ h.clock.sync()+ expect(h.intervalsStarted()).toBe(1)+ expect(h.intervalsCleared()).toBe(0)+ })++ it('turning the setting off stops the clock and hands the cursor back SHOWN', () => {+ // A cursor left in its hidden phase is an invisible cursor for the rest of the session — the+ // one way this feature can be worse than not having it.+ const h = blinkHarness()+ h.focus()+ h.tick() // hidden+ h.setEnabled(false)+ expect(h.running()).toBe(false)+ expect(h.phases).toEqual([false, true])+ })++ it('the board covering the canvas stops the clock the same way', () => {+ const h = blinkHarness()+ h.focus()+ h.tick()+ h.setCovered(true)+ expect(h.running()).toBe(false)+ expect(h.phases).toEqual([false, true])+ })++ it('losing focus stops the clock, restoring the terminal that had it', () => {+ const h = blinkHarness()+ const first = h.focus()+ h.tick()+ h.blur()+ expect(h.running()).toBe(false)+ expect(h.phasesOf(first)).toEqual([false, true])+ })++ it('a focus HANDOVER restores the old terminal and starts the new one shown', () => {+ // The old target is restored BEFORE it is forgotten — afterwards there is no handle to fix it+ // with, and its cursor would stay hidden until something unrelated repacked its row.+ const h = blinkHarness()+ const first = h.focus()+ h.tick() // first is hidden+ const second = h.focus()+ expect(h.phasesOf(first)).toEqual([false, true])+ expect(h.phasesOf(second)).toEqual([])+ expect(h.running()).toBe(true)+ h.tick()+ expect(h.phasesOf(second)).toEqual([false])+ })++ it('stop() clears the interval, restores the cursor, and a later sync cannot restart it', () => {+ // Teardown ordering is not guaranteed to beat a store notification already in flight — the+ // same discipline `createBoardFrameGate.stop()` keeps.+ const h = blinkHarness()+ const first = h.focus()+ h.tick()+ h.clock.stop()+ expect(h.running()).toBe(false)+ expect(h.phasesOf(first)).toEqual([false, true])+ h.clock.sync()+ expect(h.running()).toBe(false)+ })++ it('matches xterm’s own blink period, so a DOM-rendered terminal beside a shared one agrees', () => {+ expect(CURSOR_BLINK_INTERVAL_MS).toBe(600)+ })+})++describe('the cursor blink target seam', () => {+ afterEach(() => setCursorBlinkTarget(null))++ it('notifies on a change and not on a repeat', () => {+ const seen = vi.fn()+ const off = subscribeCursorBlinkTarget(seen)+ const target: CursorBlinkTarget = { setPhase: () => {} }+ setCursorBlinkTarget(target)+ setCursorBlinkTarget(target)+ expect(seen).toHaveBeenCalledTimes(1)+ expect(cursorBlinkTarget()).toBe(target)+ setCursorBlinkTarget(null)+ expect(seen).toHaveBeenCalledTimes(2)+ expect(cursorBlinkTarget()).toBeNull()+ off()+ setCursorBlinkTarget(target)+ expect(seen).toHaveBeenCalledTimes(2)+ })+})+describe('installAtlasResetLog', () => {/** The atlas surface the log reads, with a manual trigger. */function fakeAtlas(): {diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsxindex c812f100c..8d2fe9d4f 100644--- a/src/renderer/canvas/SharedGlyphLayer.tsx+++ b/src/renderer/canvas/SharedGlyphLayer.tsx@@ -1188,6 +1188,193 @@ export function createBoardFrameGate(}}+// ---------------------------------------------------------------------------------------------+// The blink clock — ONE for the whole canvas+// ---------------------------------------------------------------------------------------------++/**+ * xterm's own blink half-period (`CursorBlinkStateManager`'s `BLINK_INTERVAL`): 600 ms shown,+ * 600 ms hidden.+ *+ * Matched deliberately rather than picked. A stacked terminal leaves the shared canvas and paints+ * itself on xterm's DOM renderer (see the opaque set above), so two terminals on ONE canvas can be+ * blinking under two different mechanisms at the same moment — ours and xterm's CSS animation. Any+ * other period would make them visibly drift apart.+ */+export const CURSOR_BLINK_INTERVAL_MS = 600++/**+ * The terminal whose cursor is blinking right now — at most ONE, because at most one terminal has+ * focus, which is also why the clock is a canvas-level singleton rather than a timer per node.+ *+ * THE PRODUCER'S CONTRACT, in three parts, because the clock cannot enforce any of them:+ * 1. **Set on focus, cleared on blur.** The clock's "is anything focused" gate IS this value; a+ * target left behind by a blurred terminal is a repaint twice a second for a cursor nobody is+ * on.+ * 2. **`setPhase` must repaint SYNCHRONOUSLY.** The clock brackets the call to route the damage it+ * produces through `pulse()` instead of `wake()` (see `routeDamage`); a phase applied through a+ * deferred/debounced redraw would land outside that bracket, take the wake path, and put the+ * idle canvas back at the display's refresh rate — the exact failure this whole design avoids.+ * 3. **Both halves of the cursor.** A block cursor is a CELL rewrite and every other shape is an+ * overlay (see `glyphgrid/cursor.ts`), so hiding it for a phase means suppressing whichever of+ * the two this terminal is currently drawing — not just the overlay.+ * A terminal that stops being the target must leave its own cursor SHOWN; the clock restores the+ * target it still holds, but it cannot reach one that has already been dropped.+ */+export interface CursorBlinkTarget {+ /** Show or hide this terminal's cursor for the current phase. */+ setPhase(visible: boolean): void+}++let blinkTarget: CursorBlinkTarget | null = null+const blinkTargetListeners = new Set<() => void>()++/** Publish the focused terminal (or null on blur). Change-gated: the producer is a focus handler+ * that may fire more than once for one focus change. */+export function setCursorBlinkTarget(target: CursorBlinkTarget | null): void {+ if (blinkTarget === target) return+ blinkTarget = target+ for (const fn of blinkTargetListeners) fn()+}++export function cursorBlinkTarget(): CursorBlinkTarget | null {+ return blinkTarget+}++export function subscribeCursorBlinkTarget(fn: () => void): () => void {+ blinkTargetListeners.add(fn)+ return () => {+ blinkTargetListeners.delete(fn)+ }+}++/** Everything the clock touches, injected — so the policy is testable without a timer, a DOM or a+ * GPU, exactly as `createBoardFrameGate`'s is. */+export interface CursorBlinkClockDeps {+ /** `settings.cursorBlink`. */+ enabled(): boolean+ /** Is the kanban board covering the canvas? */+ covered(): boolean+ /** The focused terminal, or null. */+ target(): CursorBlinkTarget | null+ /** The loop in charge RIGHT NOW — always through the board gate, never captured: leaving the+ * board builds a fresh loop and a captured one is a corpse for the rest of the session. */+ loop(): Pick<FrameLoop, 'wake' | 'pulse'>+ setInterval(cb: () => void, ms: number): number+ clearInterval(handle: number): void+}++export interface CursorBlinkClock {+ /** Re-read the three gates and act on a change. Change-gated and idempotent, so every store+ * notification that could move any of them can call it unconditionally. */+ sync(): void+ /** Route ONE damage notification from the engine to the loop. The clock owns this because it is+ * the only thing that knows whether the damage is its own. */+ routeDamage(): void+ /** Teardown. Restores the cursor, kills the timer, and makes any later `sync` inert. */+ stop(): void+}++/**+ * The canvas's single cursor-blink clock.+ *+ * **The trap it exists to avoid.** A blink is a TIMED repaint twice a second, and the repaint+ * dirties the engine like any other write — so the ordinary path (`onDamage` → `wake()`) would+ * resume the rAF chain, which then costs `IDLE_FRAMES_BEFORE_PARK` frames before parking again.+ * Thirty frames every 600 ms is a loop that never parks: Phase 1c's idle park silently undone, on+ * every canvas that has a focused terminal, which is most of them. `pulse()` (frame-driver) draws+ * exactly one frame and stays parked — and `routeDamage` is what makes sure the blink's own damage+ * reaches it instead of `wake()`. **Neither half works alone**: `pulse()` without the routing is+ * dead code, since the damage listener would have already woken the loop.+ *+ * **Gated three ways, and torn down when any of them stops holding**: the blink SETTING, a terminal+ * holding FOCUS, and the board not covering the canvas (its gate has stopped the loop, so a phase+ * flip there repacks a row nobody draws). A canvas with no focused terminal has no clock at all —+ * not a clock that ticks and finds nothing to do.+ *+ * **The cursor is always handed back SHOWN.** Every stopping path restores the phase first: a+ * cursor left hidden is an invisible cursor until something unrelated repacks its row, which is the+ * one way this feature can be worse than not having it.+ */+export function createCursorBlinkClock(deps: CursorBlinkClockDeps): CursorBlinkClock {+ let handle = 0+ /** The target we are actually blinking — held rather than re-read, because a stopping path has to+ * restore the cursor of the terminal that HAD the clock, not of whoever has focus now. */+ let current: CursorBlinkTarget | null = null+ /** Is the cursor currently shown? Starts true: nothing has hidden it yet. */+ let visible = true+ /** True only for the duration of a `setPhase` call — see `routeDamage`. */+ let applying = false+ let torn = false++ const clearTimer = (): void => {+ if (!handle) return+ deps.clearInterval(handle)+ handle = 0+ }++ const apply = (next: boolean): void => {+ visible = next+ const target = current+ if (!target) return+ // The bracket is the whole mechanism: `setPhase` repacks the cursor row synchronously, that+ // repack calls `markDirty`, and the damage lands back in `routeDamage` while this flag is up.+ // `finally`, because a throwing addon must not leave every subsequent damage on the pulse path+ // — that would starve a streaming terminal down to one frame per write.+ applying = true+ try {+ target.setPhase(next)+ } finally {+ applying = false+ }+ }++ /** Every path that stops blinking goes through here. */+ const stopClock = (): void => {+ clearTimer()+ if (!visible) apply(true)+ }++ return {+ sync(): void {+ if (torn) return+ const next = deps.target()+ if (next !== current) {+ // Restore BEFORE the handover: afterwards there is no handle to fix the old cursor with,+ // and it would sit hidden until something unrelated repacked its row.+ stopClock()+ current = next+ }+ if (!deps.enabled() || deps.covered() || !current) {+ stopClock()+ return+ }+ // Already ticking and every gate still holds — restarting the interval here would re-arm the+ // period on every unrelated settings write, so a canvas whose settings churn would never+ // reach a hide at all.+ if (handle) return+ // A terminal that has just taken focus starts SHOWN and gets a full period before its first+ // hide — xterm's own `_restartInterval` does exactly this, and it is what keeps the cursor+ // solid at the moment the user clicks into a terminal.+ if (!visible) apply(true)+ handle = deps.setInterval(() => apply(!visible), CURSOR_BLINK_INTERVAL_MS)+ },+ routeDamage(): void {+ const loop = deps.loop()+ // Ours: one frame, still parked. Anyone else's: `wake()`, because ordinary damage (a terminal+ // writing rows) is likely to be followed by more, and a pulse per write would put a+ // scheduling hop in front of every character.+ if (applying) loop.pulse()+ else loop.wake()+ },+ stop(): void {+ torn = true+ stopClock()+ current = null+ }+ }+}+// ---------------------------------------------------------------------------------------------// The component// ---------------------------------------------------------------------------------------------@@ -1274,11 +1461,34 @@ export function SharedGlyphLayer(): JSX.Element {clearTimer: (h) => window.clearTimeout(h)}))+ // ONE blink clock for the whole canvas — not one per terminal — because at most one terminal+ // has focus. It reaches the loop through `gate.loop()` for the same reason the damage+ // subscription does, and its own repaints take `pulse()` rather than `wake()`; see+ // `createCursorBlinkClock` for why that distinction is the whole task.+ const clock = createCursorBlinkClock({+ enabled: () => useSettings.getState().settings.cursorBlink,+ covered: boardCoversCanvas,+ target: cursorBlinkTarget,+ loop: () => gate.loop(),+ setInterval: (cb, ms) => window.setInterval(cb, ms),+ clearInterval: (h) => window.clearInterval(h)+ })+ // Mounted with a terminal already focused (a remount, a project switch back) must start the+ // clock, exactly as the gate reads the board flag at construction rather than assuming.+ clock.sync()// THE wake mechanism: the engine funnels every damage write through `markDirty`, which calls// out on the clean→dirty edge. A parked loop resumes on the very next damaging write. Reached// through `gate.loop()` and never captured — leaving the board builds a fresh loop, and a// subscription pinned to the stopped one would freeze the canvas for the rest of the session.- const damage = ctx.engine.onDamage(() => gate.loop().wake())+ //+ // Routed through the clock, which is the only thing that can tell the blink's own repaint from+ // everybody else's damage: its repaint is isolated in time and takes `pulse()` (one frame, still+ // parked), while ordinary damage keeps the `wake()` it has always had.+ const damage = ctx.engine.onDamage(() => clock.routeDamage())+ // The two gates that can move without the board moving: the blink SETTING and which terminal+ // holds focus. Both are change-gated inside `sync`.+ const unsubBlinkTarget = subscribeCursorBlinkTarget(() => clock.sync())+ const unsubBlinkSetting = useSettings.subscribe(() => clock.sync())// Belt and braces for the background-throttling case (Task 9): a park entered while the window// was occluded must not outlive the return, and a throttled/coalesced rAF can leave the loop// parked with damage pending. Both are cheap — `wake()` only schedules a frame that draws@@ -1292,7 +1502,13 @@ export function SharedGlyphLayer(): JSX.Element {// Both stores, because either can move the board over this canvas: the view toggle, and a// switch to a project that is already on it. `sync` is change-gated, so the projects store's// chattier notifications (it is rewritten on every node serialization) cost a comparison.- const syncBoard = (): void => gate.sync()+ // The board is the blink clock's third gate as well (a stopped loop cannot draw the phase), so+ // the two are synced together — and the gate goes FIRST, so the clock reads the board through+ // an already-updated loop.+ const syncBoard = (): void => {+ gate.sync()+ clock.sync()+ }const unsubView = useViewMode.subscribe(syncBoard)const unsubProjects = useProjects.subscribe(syncBoard)@@ -1310,6 +1526,13 @@ export function SharedGlyphLayer(): JSX.Element {// surviving board subscription would BUILD a loop against a disposed context. `gate.stop()`// is idempotent and also makes a `sync` still in flight inert, so the `ctx.disposed` and// `failSharedGlyph` paths (which stop the loop themselves) land here safely too.+ // The clock goes FIRST, and before `gate.stop()`: it hands the cursor back SHOWN, and that+ // restoring repaint still wants a live loop to draw it. Nothing may outlive the context —+ // this is also the teardown for the `ctx.disposed` and `failSharedGlyph` paths, both of which+ // re-run this effect.+ clock.stop()+ unsubBlinkTarget()+ unsubBlinkSetting()gate.stop()unsubView()unsubProjects()diff --git a/src/renderer/glyphgrid/frame-driver.test.ts b/src/renderer/glyphgrid/frame-driver.test.tsindex a255e29f2..0ad19cb72 100644--- a/src/renderer/glyphgrid/frame-driver.test.ts+++ b/src/renderer/glyphgrid/frame-driver.test.ts@@ -185,6 +185,105 @@ describe('createFrameLoop', () => {expect(h.timer()).toBeNull() // and the heartbeat stood down})+ it('pulse draws ONE frame and parks again, without arming the idle streak', () => {+ // The blink clock's whole reason for existing. Going through `wake()` would draw the frame and+ // then hold rAF alive for another IDLE_FRAMES_BEFORE_PARK frames — thirty frames every 600 ms+ // is a continuously running loop, i.e. the idle park silently undone.+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK) // idle → parked+ const parkedAt = h.frame.mock.calls.length+ h.loop.pulse()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK) // stops as soon as nothing is scheduled+ expect(h.frame).toHaveBeenCalledTimes(parkedAt + 1) // exactly one, not thirty+ expect(h.scheduled()).toBe(false)+ })++ it('a pulse that DRAWS still parks — the blink frame must not restart the loop', () => {+ // The frame a blink schedules always draws (the phase flip dirtied the engine), so "it drew"+ // must NOT be read as "the canvas is busy again" the way `tick` reads it.+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.setDraws([true])+ h.loop.pulse()+ h.runFrame()+ expect(h.scheduled()).toBe(false)+ })++ it('a pulse leaves the parked heartbeat armed — the safety net survives the blink', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.loop.pulse()+ h.runFrame()+ expect(h.timer()?.ms).toBe(HEARTBEAT_MS)+ })++ it('a pulse while the loop is RUNNING schedules nothing extra', () => {+ // The running loop draws the phase on its next frame anyway; a second schedule would be two+ // rAF callbacks for one frame.+ const h = harness()+ const req = vi.spyOn(h.host, 'requestFrame')+ h.loop.start()+ expect(req).toHaveBeenCalledTimes(1)+ h.loop.pulse()+ h.loop.pulse()+ expect(req).toHaveBeenCalledTimes(1)+ })++ it('a wake that lands on a pending pulse keeps the loop RUNNING — the swallowed-wake trap', () => {+ // The one-shot is a flag on the shared tick, not a separate callback, precisely so this case+ // works: damage arriving between `pulse()` and its frame must resume the loop rather than be+ // consumed by a callback that parks again — which would leave a canvas with pending damage+ // parked and its heartbeat already cancelled.+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.loop.pulse()+ h.loop.wake()+ h.setDraws([true])+ h.runFrame()+ expect(h.scheduled()).toBe(true)+ })++ it('pulse() after stop() is inert', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.loop.stop()+ const after = h.frame.mock.calls.length+ h.loop.pulse()+ expect(h.scheduled()).toBe(false)+ expect(h.frame).toHaveBeenCalledTimes(after)+ })++ it('a dead host stops the loop from a pulse too — no timer outlives the context', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.kill()+ h.loop.pulse()+ h.runFrame()+ expect(h.scheduled()).toBe(false)+ expect(h.timer()).toBeNull()+ })++ it('a throwing pulse frame reports and tears down as well', () => {+ const boom = new Error('context lost')+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.host.frame = () => {+ throw boom+ }+ h.loop.pulse()+ h.runFrame()+ expect(h.errors).toEqual([boom])+ expect(h.scheduled()).toBe(false)+ expect(h.timer()).toBeNull()+ })+it('stop() clears the rAF and the heartbeat, and wake() afterwards is inert', () => {const h = harness()h.loop.start()diff --git a/src/renderer/glyphgrid/frame-driver.ts b/src/renderer/glyphgrid/frame-driver.tsindex 16296a2b4..65274e8ea 100644--- a/src/renderer/glyphgrid/frame-driver.ts+++ b/src/renderer/glyphgrid/frame-driver.ts@@ -60,6 +60,20 @@ export interface FrameLoop {/** "There is damage" — resume immediately if parked, otherwise just reset the idle streak.* Never draws inline: it runs inside the mutator that caused the damage. Inert after `stop`. */wake(): void+ /**+ * Draw at most ONE frame and park again immediately, whatever the idle streak was. For repaints+ * that are known to be ISOLATED IN TIME — the blink clock, which repaints twice a second forever+ * — where `wake()` is for damage that is likely to be followed by more.+ *+ * The difference is the whole reason this member exists. `wake()` resumes the rAF chain, which+ * then costs `IDLE_FRAMES_BEFORE_PARK` frames before it parks again: thirty frames every 600 ms+ * is a loop that never parks at all, i.e. the idle canvas back at the display's refresh rate.+ * A pulse costs exactly one frame.+ *+ * A no-op while the loop is already running (that frame draws the repaint anyway) and inert+ * after `stop`.+ */+ pulse(): void/** Cancel everything: the pending frame, the heartbeat, and any future wake. Idempotent. */stop(): void}@@ -69,6 +83,13 @@ export function createFrameLoop(host: FrameLoopHost): FrameLoop {let heartbeat = 0let idleFrames = 0let stopped = false+ /** Is the frame currently scheduled a ONE-SHOT (see `pulse`)? A flag on the shared `tick` rather+ * than a separate callback, because the two must be convertible: damage that lands between a+ * `pulse()` and its frame has to RESUME the loop, and a dedicated one-shot callback would draw+ * that damage and then park anyway — swallowing the wake, with the heartbeat already cancelled+ * by it. `runLoop` therefore clears this, which is all a wake needs to do to adopt the pending+ * frame as its own. */+ let oneShot = falseconst stop = (): void => {stopped = true@@ -76,6 +97,7 @@ export function createFrameLoop(host: FrameLoopHost): FrameLoop {if (heartbeat) host.clearTimer(heartbeat)raf = 0heartbeat = 0+ oneShot = false}/** Everything that runs a frame shares this: liveness first, error policy second. Returns@@ -108,13 +130,24 @@ export function createFrameLoop(host: FrameLoopHost): FrameLoop {heartbeat = 0}idleFrames = 0+ // A frame already scheduled by a `pulse()` is ADOPTED rather than left as a one-shot: see+ // `oneShot`. Doing it here (and not in `wake`) covers the heartbeat's resume path too.+ oneShot = falseif (!raf) raf = host.requestFrame(tick)}const tick = (): void => {raf = 0+ const shot = oneShot+ oneShot = falseconst { alive, drew } = drawOnce()if (!alive) return+ // A pulse is one frame and then parked again — deliberately regardless of `drew`, which is+ // ALWAYS true for a blink frame (the phase flip dirtied the engine). Reading that as "the+ // canvas is busy again" is exactly the loop this path exists to avoid. The idle streak and the+ // heartbeat armed at the park are both left untouched, so the loop is in the same state it was+ // in before the pulse.+ if (shot) returnidleFrames = drew ? 0 : idleFrames + 1if (shouldPark(idleFrames)) park()else raf = host.requestFrame(tick)@@ -147,6 +180,17 @@ export function createFrameLoop(host: FrameLoopHost): FrameLoop {if (stopped) returnrunLoop()},+ pulse(): void {+ // Inert after teardown, like `wake` — a blink tick racing the cleanup must not schedule a+ // frame against a context that is gone.+ if (stopped) return+ // Already running (or a pulse is already pending): that frame draws this repaint too. The+ // early return is also what keeps `oneShot` off a RUNNING loop's pending frame — setting it+ // there would turn the next ordinary tick into a park.+ if (raf) return+ oneShot = true+ raf = host.requestFrame(tick)+ },stop}}