Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(glyphgrid): the blink restarts on input, like xterm's own cursor

enes6cb5032a7dcf
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 48a9ca60b..1c55dc95d 100644
--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
@@ -239,6 +239,12 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
**static** with the setting on is a BUG now (the wiring is complete); report it with which
shape was selected and whether the terminal had focus. See 4.19 for the frame cost this must
not have.
+ **Typing holds the cursor SOLID**, the way xterm's own does: type a slow sentence into a
+ shared terminal and the cursor must not flash under your keystrokes — each one restarts the
+ period. The point of this check is the comparison, so do it beside a **stacked** terminal (one
+ node overlapping another, which leaves the shared canvas for xterm's DOM renderer — L15): the
+ two cursors must behave the same, both while typing and while idle. A shared cursor that keeps
+ flashing while you type is the drift the matched 600 ms period exists to prevent.
**The cursor honours Settings → Terminal → Cursor style.** Walk all three: `block` INVERTS the
glyph under it (the letter goes dark on a bright cell — a block is drawn as a CELL, and that is
the only path that can invert), `bar` is a hairline down the LEFT edge with the glyph still
@@ -486,7 +492,14 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
idle streak twice a second. Click into a terminal, leave everything else idle, and confirm the
meter reads ~2 rather than 60. Then click AWAY (focus another app): the last phase leaves the
cursor shown and the meter drops to quiet — a canvas with no focused terminal has no clock at
- all.
+ all. **Typing is the other expected exception**, and it is the same mechanism: a cursor move
+ holds the cursor solid and restarts the period, so the meter follows your keystrokes rather
+ than flashing under them.
+ **One innocent way to read 60 that is NOT a routing bug**, worth distinguishing before filing
+ one: if the shared ATLAS resets during a blink repack, the addon asks xterm for a full redraw,
+ and xterm's debounced render pass then packs rows from OUTSIDE the clock's bracket — which
+ takes `wake()`, correctly. The atlas logs its resets (`resetCount`), so check the console
+ before concluding the blink is on the wrong path.
**BLOCKING symptom to name explicitly: if ANY terminal ever stops repainting until you drag
it, 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
diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.ts
index 9d0def382..5daaa246c 100644
--- a/src/renderer/canvas/SharedGlyphLayer.test.ts
+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts
@@ -1,11 +1,22 @@
import { adoptUserNodes } from '@xyflow/system'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ GlyphGridRendererAddonCore,
+ type CursorBlinkPhaseTarget,
+ type CursorBlinkSeam
+} from '../glyphgrid/addon'
+// The addon's fakes, shared with `glyphgrid/addon.test.ts`. A plain module, not a `.test.ts`:
+// importing a test file makes vitest collect its whole suite a second time under this one.
+import { fakeTerm, recordingAtlas, recordingHandle } from '../glyphgrid/addon-fakes'
+import { FLAG_CURSOR, readCell } from '../glyphgrid/cells'
+import type { GridHandle } from '../glyphgrid/engine'
import { createFrameLoop, type FrameLoop, type FrameLoopHost } from '../glyphgrid/frame-driver'
import {
createBoardFrameGate,
createCursorBlinkClock,
cursorBlinkTarget,
setCursorBlinkTarget,
+ subscribeCursorBlinkRestart,
subscribeCursorBlinkTarget,
CURSOR_BLINK_INTERVAL_MS,
failSharedGlyph,
@@ -23,6 +34,8 @@ import {
opaqueNodeIds,
pixelRatioChanged,
primeOpaqueNodeIds,
+ releaseCursorBlinkTarget,
+ restartCursorBlink,
setNodeZOrder,
setOpaqueNodeIds,
setSharedGlyphCamera,
@@ -1455,6 +1468,56 @@ describe('createCursorBlinkClock', () => {
it('matches xterm’s own blink period, so a DOM-rendered terminal beside a shared one agrees', () => {
expect(CURSOR_BLINK_INTERVAL_MS).toBe(600)
})
+
+ it('a cursor move during a hidden phase shows the cursor again — through pulse, not wake', () => {
+ // The restart is a BLINK repaint like any other, so it has to stay inside the bracket. A
+ // restart routed to `wake()` would be worse than the phase flips this design was built around:
+ // it happens on every keystroke, not twice a second.
+ const h = blinkHarness()
+ h.focus()
+ h.tick()
+ expect(h.phases).toEqual([false])
+ h.loop.pulse.mockClear()
+ h.loop.wake.mockClear()
+
+ h.clock.restart()
+
+ expect(h.phases).toEqual([false, true])
+ expect(h.loop.pulse).toHaveBeenCalledTimes(1)
+ expect(h.loop.wake).not.toHaveBeenCalled()
+ })
+
+ it('a restart re-arms the period, so the cursor stays solid while you type', () => {
+ // Showing it again without restarting the interval would leave the cursor solid only until the
+ // next tick of the OLD period — up to 600 ms, but as little as a millisecond.
+ const h = blinkHarness()
+ h.focus()
+ expect(h.intervalsStarted()).toBe(1)
+ h.clock.restart()
+ expect(h.intervalsCleared()).toBe(1)
+ expect(h.intervalsStarted()).toBe(2)
+ expect(h.running()).toBe(true)
+ })
+
+ it('a restart starts nothing while a gate is holding the clock stopped', () => {
+ // `sync` owns the gates. A restart that started an interval here would blink a cursor the
+ // setting (or the board) has already stopped.
+ const h = blinkHarness({ enabled: false })
+ h.focus()
+ h.clock.restart()
+ expect(h.running()).toBe(false)
+ expect(h.intervalsStarted()).toBe(0)
+ })
+
+ it('a restart with nothing focused, and one after stop(), are both inert', () => {
+ const h = blinkHarness()
+ h.clock.restart()
+ expect(h.running()).toBe(false)
+ h.focus()
+ h.clock.stop()
+ h.clock.restart()
+ expect(h.running()).toBe(false)
+ })
})
describe('the cursor blink target seam', () => {
@@ -1475,6 +1538,193 @@ describe('the cursor blink target seam', () => {
setCursorBlinkTarget(target)
expect(seen).toHaveBeenCalledTimes(2)
})
+
+ it('release only clears the blink for the target that still HOLDS it', () => {
+ // THE late-blur bug, and the reason the comparison lives in this function rather than in the
+ // attach shell (which has no unit tests by design): the browser does not promise that the old
+ // terminal's blur reaches us before the new one's focus, and an unconditional clear would stop
+ // the cursor of the terminal the user just clicked into.
+ const a: CursorBlinkTarget = { setPhase: () => {} }
+ const b: CursorBlinkTarget = { setPhase: () => {} }
+ setCursorBlinkTarget(a)
+ setCursorBlinkTarget(b)
+ releaseCursorBlinkTarget(a)
+ expect(cursorBlinkTarget()).toBe(b)
+ releaseCursorBlinkTarget(b)
+ expect(cursorBlinkTarget()).toBeNull()
+ })
+
+ it('restart notifies only for the target that holds the blink', () => {
+ // A background terminal streaming output moves its cursor constantly; any of them re-arming the
+ // focused terminal's period would hold the blink permanently solid.
+ const seen = vi.fn()
+ const off = subscribeCursorBlinkRestart(seen)
+ const a: CursorBlinkTarget = { setPhase: () => {} }
+ const b: CursorBlinkTarget = { setPhase: () => {} }
+ setCursorBlinkTarget(a)
+ restartCursorBlink(b)
+ expect(seen).not.toHaveBeenCalled()
+ restartCursorBlink(a)
+ expect(seen).toHaveBeenCalledTimes(1)
+ off()
+ restartCursorBlink(a)
+ expect(seen).toHaveBeenCalledTimes(1)
+ })
+})
+
+/**
+ * THE PARK, END TO END — the one constraint the whole blink design exists to satisfy.
+ *
+ * The addon's own tests prove it repacks on the caller's stack; the clock's tests above prove it
+ * routes bracketed damage to `pulse()`. Neither alone proves the FEATURE parks, because the trap
+ * lives exactly in the seam between them: an addon that repacked one tick later would satisfy both
+ * and still put an idle canvas back at the display's refresh rate, thirty frames every 600 ms.
+ *
+ * So this wires the REAL addon to the REAL clock through a handle that reports damage the way the
+ * engine does — edge-triggered on the clean→dirty transition, cleared by the frame the loop draws.
+ * It lives on THIS side of the boundary because the dependency direction is canvas → glyphgrid; the
+ * fakes come from `glyphgrid/addon-fakes.ts`, which is a plain module rather than a `.test.ts` so
+ * importing it does not collect the addon's suite a second time.
+ */
+describe('the blink phase through the real clock', () => {
+ function wired(): {
+ core: GlyphGridRendererAddonCore
+ loop: { wake: number; pulse: number }
+ intervalsStarted(): number
+ running(): boolean
+ tick(): void
+ frame(): void
+ /** Does the NEWEST pack of the cursor row carry the block cursor? */
+ cursorPainted(): boolean
+ } {
+ const handle = recordingHandle()
+ let clock: CursorBlinkClock | null = null
+ const loop = { wake: 0, pulse: 0 }
+ // The engine's `markDirty` notifies on the clean→dirty EDGE only, and the FRAME clears the flag
+ // — neither `wake()` nor `pulse()` draws inline, they schedule. Modelling that (rather than one
+ // notification per write) is what makes the counts below mean "frames scheduled", which is the
+ // number the park is about.
+ let dirty = false
+ const damage = (): void => {
+ if (dirty) return
+ dirty = true
+ clock?.routeDamage()
+ }
+ const damaging: GridHandle = {
+ ...handle,
+ updateRow(row, cells) {
+ handle.updateRow(row, cells)
+ damage()
+ },
+ setCursor(cursor) {
+ handle.setCursor(cursor)
+ damage()
+ }
+ }
+
+ let current: CursorBlinkPhaseTarget | null = null
+ // The attach shell's seam, verbatim in behaviour: claim publishes, release and restart are
+ // identity-guarded, and a target change re-syncs the clock (the real one does it through the
+ // layer's subscription).
+ const seam: CursorBlinkSeam = {
+ claim(t) {
+ current = t
+ clock?.sync()
+ },
+ release(t) {
+ if (current !== t) return
+ current = null
+ clock?.sync()
+ },
+ restart(t) {
+ if (current !== t) return
+ clock?.restart()
+ }
+ }
+
+ let fire: (() => void) | null = null
+ let started = 0
+ clock = createCursorBlinkClock({
+ enabled: () => true,
+ covered: () => false,
+ target: () => current,
+ loop: () => ({
+ wake: () => {
+ loop.wake++
+ },
+ pulse: () => {
+ loop.pulse++
+ }
+ }),
+ setInterval: (cb) => {
+ started++
+ fire = cb
+ return started
+ },
+ clearInterval: () => {
+ fire = null
+ }
+ })
+
+ const term = fakeTerm({ rows: 4, cols: 4, cursorY: 1, cursorX: 2, focus: true, blink: seam })
+ const core = new GlyphGridRendererAddonCore(term, damaging, recordingAtlas())
+ return {
+ core,
+ loop,
+ intervalsStarted: () => started,
+ running: () => fire !== null,
+ tick: () => fire?.(),
+ frame: () => {
+ dirty = false
+ },
+ cursorPainted: () => {
+ const rec = [...handle.rows].reverse().find((r) => r.row === 1)
+ if (!rec) throw new Error('the cursor row was never packed')
+ return (readCell(rec.cells, 2).flags & FLAG_CURSOR) !== 0
+ }
+ }
+ }
+
+ it('a phase flip costs ONE pulse and never a wake — the idle park survives the blink', () => {
+ const h = wired()
+ // The addon claimed the blink at construction, so the clock is already ticking.
+ expect(h.running()).toBe(true)
+ for (let i = 0; i < 3; i++) {
+ h.tick()
+ // The frame the pulse scheduled draws and clears the engine's dirty flag, 600 ms before the
+ // next phase — which is what lets the next flip notify at all.
+ h.frame()
+ }
+ expect(h.loop.pulse).toBe(3)
+ expect(h.loop.wake).toBe(0)
+ })
+
+ it('ordinary damage from the SAME addon still takes wake()', () => {
+ // The other half of the routing: only the clock's own bracketed repaint is a pulse. 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.
+ const h = wired()
+ h.core.renderRows(0, 3)
+ expect(h.loop.wake).toBe(1)
+ expect(h.loop.pulse).toBe(0)
+ })
+
+ it('a cursor move during a hidden phase shows the cursor, restarts the period, and pulses', () => {
+ // xterm holds its own cursor solid while you type; without this the shared renderer kept
+ // flashing, so a stacked (DOM-rendered) terminal beside a shared one behaved differently in the
+ // most attention-heavy moment there is — the drift the matched period exists to prevent.
+ const h = wired()
+ h.tick()
+ h.frame()
+ expect(h.cursorPainted()).toBe(false)
+
+ h.core.handleCursorMove()
+
+ expect(h.cursorPainted()).toBe(true)
+ expect(h.intervalsStarted()).toBe(2)
+ expect(h.loop.pulse).toBe(2)
+ expect(h.loop.wake).toBe(0)
+ })
})
describe('installAtlasResetLog', () => {
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index a83d04d99..9f604100e 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -1233,6 +1233,7 @@ export interface CursorBlinkTarget {
let blinkTarget: CursorBlinkTarget | null = null
const blinkTargetListeners = new Set<() => void>()
+const blinkRestartListeners = 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. */
@@ -1242,6 +1243,41 @@ export function setCursorBlinkTarget(target: CursorBlinkTarget | null): void {
for (const fn of blinkTargetListeners) fn()
}
+/**
+ * Give the blink up — but ONLY if this target still holds it.
+ *
+ * THE GUARD LIVES HERE, and nowhere else. The browser does not promise that the blurred terminal's
+ * blur reaches us before the newly focused one's focus, so an unconditional
+ * `setCursorBlinkTarget(null)` on a late blur (or on the teardown of a terminal another node has
+ * already taken focus from) would stop the cursor of the terminal the user just clicked into — the
+ * only one that is supposed to be blinking. Its natural home would be the attach shell, which is
+ * the file with no unit tests by design; keeping the comparison in this function is what puts it
+ * under test.
+ */
+export function releaseCursorBlinkTarget(target: CursorBlinkTarget): void {
+ if (blinkTarget !== target) return
+ setCursorBlinkTarget(null)
+}
+
+/**
+ * The cursor MOVED — hold it solid and start the period over.
+ *
+ * xterm's own `CursorBlinkStateManager.restartBlinkAnimation` does exactly this, and matching it is
+ * the same argument that fixed `CURSOR_BLINK_INTERVAL_MS` at 600 ms: a STACKED terminal has left
+ * the shared canvas for xterm's DOM renderer, so two terminals on one canvas blink under two
+ * mechanisms at once. Without this the stacked one holds its cursor solid while you type and the
+ * shared one keeps flashing — the drift the period match exists to prevent, in the most
+ * attention-heavy moment there is.
+ *
+ * Identity-guarded like `releaseCursorBlinkTarget`, for a second reason on top of that one: a
+ * background terminal streaming output moves its cursor constantly, and any of them re-arming the
+ * focused terminal's period would keep the blink permanently solid.
+ */
+export function restartCursorBlink(target: CursorBlinkTarget): void {
+ if (blinkTarget !== target) return
+ for (const fn of blinkRestartListeners) fn()
+}
+
export function cursorBlinkTarget(): CursorBlinkTarget | null {
return blinkTarget
}
@@ -1253,6 +1289,15 @@ export function subscribeCursorBlinkTarget(fn: () => void): () => void {
}
}
+/** A restart is not a target CHANGE, so it needs its own channel — `sync` deliberately does
+ * nothing while the interval is already running. */
+export function subscribeCursorBlinkRestart(fn: () => void): () => void {
+ blinkRestartListeners.add(fn)
+ return () => {
+ blinkRestartListeners.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 {
@@ -1273,6 +1318,9 @@ 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
+ /** The target's cursor moved: show it and start the period over — xterm's
+ * `restartBlinkAnimation`. Inert when nothing is blinking. */
+ restart(): 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
@@ -1299,7 +1347,10 @@ export interface CursorBlinkClock {
*
* **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.
+ * one way this feature can be worse than not having it. Precisely: the restore is PACKED at the
+ * moment the clock stops — on the board path that means it is drawn when the board closes and the
+ * loop starts again, since the board gate has stopped the loop; on every other path a frame follows
+ * immediately.
*/
export function createCursorBlinkClock(deps: CursorBlinkClockDeps): CursorBlinkClock {
let handle = 0
@@ -1308,8 +1359,13 @@ export function createCursorBlinkClock(deps: CursorBlinkClockDeps): CursorBlinkC
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
+ /** How many `setPhase` calls are on the stack right now — see `routeDamage`.
+ *
+ * A DEPTH, not a boolean. Nothing re-enters `apply` today, but a boolean would clear the bracket
+ * at the end of the INNER call and drop the outer one's remaining damage onto `wake()` — and the
+ * bracket is the single invariant this whole design rests on, so it costs nothing to make it
+ * re-entrant rather than to rely on it never being re-entered. */
+ let applying = 0
let torn = false
const clearTimer = (): void => {
@@ -1323,21 +1379,32 @@ export function createCursorBlinkClock(deps: CursorBlinkClockDeps): CursorBlinkC
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
+ // repack calls `markDirty`, and the damage lands back in `routeDamage` while this counter 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++
try {
target.setPhase(next)
} finally {
- applying = false
+ applying--
}
}
/** Every path that stops blinking goes through here. */
const stopClock = (): void => {
clearTimer()
- if (!visible) apply(true)
+ if (visible) return
+ // GUARDED, because `stop()` is the FIRST statement of the layer effect's cleanup. `setPhase`
+ // packs a row into the engine, and the engine rejects a row of the wrong length by throwing —
+ // a throw here would skip every unsubscribe after it and leave a dead loop reachable from the
+ // engine and a damage subscription outliving its context, which is the exact invariant that
+ // cleanup exists to hold. A cursor stuck in its hidden phase is cosmetic and self-heals on the
+ // next repack of its row; a surviving subscription is a frozen canvas for the session.
+ try {
+ apply(true)
+ } catch (err) {
+ console.warn('[glyphgrid] cursor blink restore failed', err)
+ }
}
return {
@@ -1364,12 +1431,26 @@ export function createCursorBlinkClock(deps: CursorBlinkClockDeps): CursorBlinkC
if (!visible) apply(true)
handle = deps.setInterval(() => apply(!visible), CURSOR_BLINK_INTERVAL_MS)
},
+ restart(): void {
+ if (torn || !current) return
+ // Show it FIRST, and through `apply` — so the re-shown cursor's repaint goes through the same
+ // bracket every other phase does and takes `pulse()`. A restart that repainted outside it
+ // would hand the wake path a repaint that happens on EVERY keystroke, which is worse than the
+ // twice-a-second one this design was built to keep off it.
+ if (!visible) apply(true)
+ // Nothing is ticking (the setting is off, or the board is up): there is no period to re-arm,
+ // and starting one here would blink a cursor the gates have already stopped. `sync` owns the
+ // gates; this only ever restarts a clock that is already running.
+ if (!handle) return
+ clearTimer()
+ 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()
+ if (applying > 0) loop.pulse()
else loop.wake()
},
stop(): void {
@@ -1494,6 +1575,10 @@ export function SharedGlyphLayer(): JSX.Element {
// holds focus. Both are change-gated inside `sync`.
const unsubBlinkTarget = subscribeCursorBlinkTarget(() => clock.sync())
const unsubBlinkSetting = useSettings.subscribe(() => clock.sync())
+ // ...and the cursor MOVING, which is not a gate at all: it holds the cursor solid and starts
+ // the period over, exactly as xterm does while you type. Its own channel, because `sync` is
+ // deliberately a no-op while the interval is already running.
+ const unsubBlinkRestart = subscribeCursorBlinkRestart(() => clock.restart())
// 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
@@ -1531,12 +1616,17 @@ 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.
+ // The clock goes FIRST, and before the unsubscribes: it hands the cursor back SHOWN, and it
+ // can only do that while it still HOLDS the target — `stop()` drops it. What that buys is the
+ // packed row, not a drawn frame: the `pulse()` it schedules is cancelled moments later by
+ // `gate.stop()`, and the point is that the grid's buffers no longer hold a hidden cursor, so
+ // whatever draws them next (a remount, the board closing) draws a cursor. Its restore is
+ // guarded inside `stopClock`, so a throwing repack cannot skip the teardown below 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()
+ unsubBlinkRestart()
unsubBlinkSetting()
gate.stop()
unsubView()
diff --git a/src/renderer/glyphgrid/addon-fakes.ts b/src/renderer/glyphgrid/addon-fakes.ts
new file mode 100644
index 000000000..92dfc6be9
--- /dev/null
+++ b/src/renderer/glyphgrid/addon-fakes.ts
@@ -0,0 +1,288 @@
+/**
+ * The addon's test fakes: a recording `GridHandle`, a recording atlas, a fake decoration service, a
+ * fake blink seam, and the `TermInternals` a terminal would supply.
+ *
+ * NOT a `.test.ts`, deliberately. Two test files need these — `addon.test.ts` and the shared
+ * layer's, which drives the real addon through the real blink clock — and importing one test file
+ * from another makes vitest COLLECT the imported file's whole suite a second time under the
+ * importer. A plain module is the only way to share a harness. It is also dead code in a production
+ * build: nothing outside the two test files imports it.
+ *
+ * It lives on the glyphgrid side because the dependency direction is canvas → glyphgrid. The layer
+ * test may reach in here; this directory must never reach out.
+ */
+
+import type { GlyphAtlas } from './atlas'
+import { CELL_STRIDE, packColor } from './cells'
+import type { GridCursor } from './cursor'
+import type { GridHandle } from './engine'
+import type { CursorBlinkPhaseTarget, CursorBlinkSeam, TermInternals } from './addon'
+import type { DecorationReader } from './decorations'
+import type { CellView, ThemeLanes } from './feed'
+
+export const THEME: ThemeLanes = {
+ fg: packColor(0xd0, 0xd1, 0xd2, 0xff),
+ bg: packColor(0x10, 0x11, 0x12, 0xff),
+ ansi: Array.from({ length: 256 }, (_, i) => packColor(i, 0x80, 0xff - i, 0xff)),
+ cursorFg: packColor(0x01, 0x02, 0x03, 0xff),
+ cursorBg: packColor(0xfa, 0xfb, 0xfc, 0xff),
+ selectionBg: packColor(0x30, 0x50, 0x80, 0xff)
+}
+
+/** A cell whose code point encodes the ABSOLUTE buffer row it came from, so a packed row can be
+ * traced back to the buffer row that produced it — which is the whole point of the mapping
+ * tests (a viewportY off-by-one is otherwise invisible). */
+export function rowCodedCell(absRow: number, col: number): CellView {
+ const code = 0x100 + absRow * 16 + col
+ return {
+ getChars: () => String.fromCodePoint(code),
+ getCode: () => code,
+ getWidth: () => 1,
+ isBold: () => 0,
+ isItalic: () => 0,
+ isUnderline: () => 0,
+ isInverse: () => 0,
+ isDim: () => 0,
+ isFgDefault: () => true,
+ isFgPalette: () => false,
+ isFgRGB: () => false,
+ isBgDefault: () => true,
+ isBgPalette: () => false,
+ isBgRGB: () => false,
+ getFgColor: () => 0,
+ getBgColor: () => 0
+ }
+}
+
+export interface RecordedRow {
+ row: number
+ /** Copy — the core reuses ONE row buffer, so keeping the live reference would record the last
+ * frame N times. */
+ cells: Uint32Array
+ /** The buffer INSTANCE handed to updateRow, kept only to assert the reuse contract. */
+ buf: Uint32Array
+}
+
+export function recordingHandle(): GridHandle & {
+ rows: RecordedRow[]
+ log: string[]
+ resizes: Array<[number, number]>
+ /** Every cursor spec pushed to the grid, newest last — `at(-1)` is what a frame would draw. */
+ cursors: Array<GridCursor | null>
+} {
+ const rows: RecordedRow[] = []
+ const log: string[] = []
+ const resizes: Array<[number, number]> = []
+ const cursors: Array<GridCursor | null> = []
+ return {
+ rows,
+ log,
+ resizes,
+ cursors,
+ updateRow(row, cells) {
+ log.push(`updateRow:${row}`)
+ rows.push({ row, cells: cells.slice(), buf: cells })
+ },
+ setOrigin() {},
+ // The addon owns CELLS, never geometry — the plate is the node's business. A stub, present
+ // only to satisfy the handle contract.
+ setPlateRect() {},
+ setCursor(cursor) {
+ cursors.push(cursor)
+ },
+ setZ() {},
+ resize(cols, r) {
+ log.push(`resize:${cols}x${r}`)
+ resizes.push([cols, r])
+ },
+ dispose() {
+ log.push('dispose')
+ }
+ }
+}
+
+/** The atlas surface the addon holds: a slot source AND a reset broadcaster.
+ *
+ * `fireReset()` is the test's hand on the real atlas's most awkward behaviour — a reset fires
+ * SYNCHRONOUSLY inside a `glyphFor` call, i.e. in the middle of someone's row pack — so
+ * `onGlyphFor` exists to fire it from exactly there. */
+export function recordingAtlas(o: { onGlyphFor?: (fire: () => void) => void } = {}): Pick<
+ GlyphAtlas,
+ 'glyphFor' | 'onReset'
+> & { fireReset(): void; subCount(): number } {
+ const subs = new Set<() => void>()
+ const fireReset = (): void => {
+ for (const cb of [...subs]) cb()
+ }
+ return {
+ // Identity-ish: the slot IS derived from the code point, so a packed glyph lane names the cell
+ // it came from without a second bookkeeping structure.
+ glyphFor: (code) => {
+ o.onGlyphFor?.(fireReset)
+ return code
+ },
+ onReset: (cb) => {
+ subs.add(cb)
+ return {
+ dispose: (): void => {
+ subs.delete(cb)
+ }
+ }
+ },
+ fireReset,
+ subCount: () => subs.size
+ }
+}
+
+/** The decoration surface the shell hands over: a reader plus the two "something changed" events.
+ * `fire*` is the test's hand on xterm's decoration service — the search addon registering a hit. */
+export function fakeDecorations(
+ entries: Array<{ col: number; row: number; layer?: string; bg?: number; fg?: number }> = []
+): {
+ reader: DecorationReader
+ onDecorationRegistered(cb: () => void): { dispose(): void }
+ onDecorationRemoved(cb: () => void): { dispose(): void }
+ fireRegistered(): void
+ fireRemoved(): void
+ subCount(): number
+} {
+ const registered = new Set<() => void>()
+ const removed = new Set<() => void>()
+ const sub = (set: Set<() => void>, cb: () => void): { dispose(): void } => {
+ set.add(cb)
+ return {
+ dispose: (): void => {
+ set.delete(cb)
+ }
+ }
+ }
+ return {
+ reader: {
+ empty: () => entries.length === 0,
+ atCell: (col, row, cb) => entries.filter((e) => e.col === col && e.row === row).forEach(cb)
+ },
+ onDecorationRegistered: (cb) => sub(registered, cb),
+ onDecorationRemoved: (cb) => sub(removed, cb),
+ fireRegistered: () => {
+ for (const cb of [...registered]) cb()
+ },
+ fireRemoved: () => {
+ for (const cb of [...removed]) cb()
+ },
+ subCount: () => registered.size + removed.size
+ }
+}
+
+/** The canvas blink clock's end of the seam, as the attach shell implements it: `release` is
+ * IDENTITY-GUARDED, because browsers do not promise that the blurred terminal's blur reaches us
+ * before the newly focused one's focus. Modelling that here is what makes the handover assertion
+ * mean anything — an unguarded fake would pass against an unguarded shell.
+ *
+ * `onRelease` stands in for the clock's own restoring `setPhase(true)`, which is the behaviour
+ * `dispose` has to leave room for. */
+export function fakeBlinkSeam(o: { onRelease?: (t: CursorBlinkPhaseTarget) => void } = {}): {
+ seam: CursorBlinkSeam
+ target(): CursorBlinkPhaseTarget | null
+ claims: CursorBlinkPhaseTarget[]
+ releases: CursorBlinkPhaseTarget[]
+ restarts: CursorBlinkPhaseTarget[]
+} {
+ let current: CursorBlinkPhaseTarget | null = null
+ const claims: CursorBlinkPhaseTarget[] = []
+ const releases: CursorBlinkPhaseTarget[] = []
+ const restarts: CursorBlinkPhaseTarget[] = []
+ return {
+ seam: {
+ claim(t) {
+ claims.push(t)
+ current = t
+ },
+ release(t) {
+ releases.push(t)
+ if (current !== t) return
+ current = null
+ o.onRelease?.(t)
+ },
+ // Recorded UNGUARDED, unlike `release`: the identity guard for a restart is the real seam's
+ // (`restartCursorBlink`, tested where it lives), so what an addon test learns from this list
+ // is whether the ADDON asked at all — which is its own focus rule.
+ restart(t) {
+ restarts.push(t)
+ }
+ },
+ target: () => current,
+ claims,
+ releases,
+ restarts
+ }
+}
+
+export interface FakeTermOpts {
+ cols?: number
+ rows?: number
+ viewportY?: number
+ baseY?: number
+ cursorX?: number
+ cursorY?: number
+ cursorVisible?: boolean
+ focus?: boolean
+ decorations?: ReturnType<typeof fakeDecorations>
+ /** xterm's two cursor options, verbatim. ABSENT on purpose in every test that does not name them:
+ * an xterm build that stopped reporting them must degrade to xterm's own defaults (a focused
+ * block, a blurred outline), never to no cursor at all. */
+ cursorStyle?: { style?: string; inactiveStyle?: string }
+ /** Columns whose cell reports width 2 — a wide glyph's LEAD. The column after one reports width
+ * 0, exactly as xterm's buffer stores a double-width character. */
+ wideCols?: readonly number[]
+ /** The blink seam. ABSENT in every test that does not name it — a build with no shared layer
+ * hands the addon exactly this, and the cursor simply never blinks. */
+ blink?: CursorBlinkSeam
+}
+
+export type FakeTermState = Required<
+ Omit<FakeTermOpts, 'decorations' | 'cursorStyle' | 'wideCols' | 'blink'>
+>
+
+export function fakeTerm(o: FakeTermOpts = {}): TermInternals & { state: FakeTermState } {
+ const state: FakeTermState = {
+ cols: o.cols ?? 4,
+ rows: o.rows ?? 6,
+ viewportY: o.viewportY ?? 0,
+ baseY: o.baseY ?? 0,
+ cursorX: o.cursorX ?? 0,
+ cursorY: o.cursorY ?? 0,
+ cursorVisible: o.cursorVisible ?? true,
+ focus: o.focus ?? true
+ }
+ const workCell = rowCodedCell(-1, -1)
+ return {
+ state,
+ cols: () => state.cols,
+ rows: () => state.rows,
+ viewportY: () => state.viewportY,
+ baseY: () => state.baseY,
+ cursorX: () => state.cursorX,
+ cursorY: () => state.cursorY,
+ cursorVisible: () => state.cursorVisible,
+ readCell: (absRow, col) => {
+ const wide = o.wideCols ?? []
+ if (wide.includes(col)) return { ...rowCodedCell(absRow, col), getWidth: () => 2 }
+ if (wide.includes(col - 1)) return { ...rowCodedCell(absRow, col), getWidth: () => 0 }
+ return rowCodedCell(absRow, col)
+ },
+ makeWorkCell: () => workCell,
+ deviceMetrics: () => ({ charW: 16, charH: 34, cellW: 16, cellH: 34 }),
+ dpr: () => 2,
+ theme: () => THEME,
+ hasFocus: () => state.focus,
+ // Absent unless a test names them — see FakeTermOpts.cursorStyle.
+ cursorStyle: o.cursorStyle ? () => o.cursorStyle as { style?: string } : undefined,
+ // Absent unless a test asks for it, like the decorations below.
+ blink: o.blink,
+ // Absent unless a test asks for them — an xterm build with no decoration service hands the
+ // addon exactly this, and every other test in this file is that case.
+ decorations: o.decorations?.reader,
+ onDecorationRegistered: o.decorations?.onDecorationRegistered,
+ onDecorationRemoved: o.decorations?.onDecorationRemoved
+ }
+}
diff --git a/src/renderer/glyphgrid/addon.test.ts b/src/renderer/glyphgrid/addon.test.ts
index 0a5d23438..bdd7a0231 100644
--- a/src/renderer/glyphgrid/addon.test.ts
+++ b/src/renderer/glyphgrid/addon.test.ts
@@ -1,280 +1,16 @@
import { describe, expect, it } from 'vitest'
-// TEST-ONLY cross-layer import, and the only one in this directory: the blink is a CONTRACT between
-// the clock (which owns the timing and the damage routing) and this addon (which owns applying a
-// phase), and the trap it exists to avoid lives exactly in the seam between them — see the last
-// describe. `src/renderer/glyphgrid/` itself still imports nothing.
-import { createCursorBlinkClock, type CursorBlinkClock } from '../canvas/SharedGlyphLayer'
-import type { GlyphAtlas } from './atlas'
+import {
+ THEME,
+ fakeBlinkSeam,
+ fakeDecorations,
+ fakeTerm,
+ recordingAtlas,
+ recordingHandle,
+ type FakeTermOpts
+} from './addon-fakes'
import { CELL_STRIDE, FLAG_CURSOR, FLAG_SELECTED, packColor, readCell } from './cells'
import type { GridCursor } from './cursor'
-import type { GridHandle } from './engine'
-import {
- GlyphGridRendererAddonCore,
- type CursorBlinkPhaseTarget,
- type CursorBlinkSeam,
- type DeviceMetrics,
- type TermInternals
-} from './addon'
-import type { DecorationReader } from './decorations'
-import type { CellView, ThemeLanes } from './feed'
-
-const THEME: ThemeLanes = {
- fg: packColor(0xd0, 0xd1, 0xd2, 0xff),
- bg: packColor(0x10, 0x11, 0x12, 0xff),
- ansi: Array.from({ length: 256 }, (_, i) => packColor(i, 0x80, 0xff - i, 0xff)),
- cursorFg: packColor(0x01, 0x02, 0x03, 0xff),
- cursorBg: packColor(0xfa, 0xfb, 0xfc, 0xff),
- selectionBg: packColor(0x30, 0x50, 0x80, 0xff)
-}
-
-/** A cell whose code point encodes the ABSOLUTE buffer row it came from, so a packed row can be
- * traced back to the buffer row that produced it — which is the whole point of the mapping
- * tests (a viewportY off-by-one is otherwise invisible). */
-function rowCodedCell(absRow: number, col: number): CellView {
- const code = 0x100 + absRow * 16 + col
- return {
- getChars: () => String.fromCodePoint(code),
- getCode: () => code,
- getWidth: () => 1,
- isBold: () => 0,
- isItalic: () => 0,
- isUnderline: () => 0,
- isInverse: () => 0,
- isDim: () => 0,
- isFgDefault: () => true,
- isFgPalette: () => false,
- isFgRGB: () => false,
- isBgDefault: () => true,
- isBgPalette: () => false,
- isBgRGB: () => false,
- getFgColor: () => 0,
- getBgColor: () => 0
- }
-}
-
-interface RecordedRow {
- row: number
- /** Copy — the core reuses ONE row buffer, so keeping the live reference would record the last
- * frame N times. */
- cells: Uint32Array
- /** The buffer INSTANCE handed to updateRow, kept only to assert the reuse contract. */
- buf: Uint32Array
-}
-
-function recordingHandle(): GridHandle & {
- rows: RecordedRow[]
- log: string[]
- resizes: Array<[number, number]>
- /** Every cursor spec pushed to the grid, newest last — `at(-1)` is what a frame would draw. */
- cursors: Array<GridCursor | null>
-} {
- const rows: RecordedRow[] = []
- const log: string[] = []
- const resizes: Array<[number, number]> = []
- const cursors: Array<GridCursor | null> = []
- return {
- rows,
- log,
- resizes,
- cursors,
- updateRow(row, cells) {
- log.push(`updateRow:${row}`)
- rows.push({ row, cells: cells.slice(), buf: cells })
- },
- setOrigin() {},
- // The addon owns CELLS, never geometry — the plate is the node's business. A stub, present
- // only to satisfy the handle contract.
- setPlateRect() {},
- setCursor(cursor) {
- cursors.push(cursor)
- },
- setZ() {},
- resize(cols, r) {
- log.push(`resize:${cols}x${r}`)
- resizes.push([cols, r])
- },
- dispose() {
- log.push('dispose')
- }
- }
-}
-
-/** The atlas surface the addon holds: a slot source AND a reset broadcaster.
- *
- * `fireReset()` is the test's hand on the real atlas's most awkward behaviour — a reset fires
- * SYNCHRONOUSLY inside a `glyphFor` call, i.e. in the middle of someone's row pack — so
- * `onGlyphFor` exists to fire it from exactly there. */
-function recordingAtlas(o: { onGlyphFor?: (fire: () => void) => void } = {}): Pick<
- GlyphAtlas,
- 'glyphFor' | 'onReset'
-> & { fireReset(): void; subCount(): number } {
- const subs = new Set<() => void>()
- const fireReset = (): void => {
- for (const cb of [...subs]) cb()
- }
- return {
- // Identity-ish: the slot IS derived from the code point, so a packed glyph lane names the cell
- // it came from without a second bookkeeping structure.
- glyphFor: (code) => {
- o.onGlyphFor?.(fireReset)
- return code
- },
- onReset: (cb) => {
- subs.add(cb)
- return {
- dispose: (): void => {
- subs.delete(cb)
- }
- }
- },
- fireReset,
- subCount: () => subs.size
- }
-}
-
-/** The decoration surface the shell hands over: a reader plus the two "something changed" events.
- * `fire*` is the test's hand on xterm's decoration service — the search addon registering a hit. */
-function fakeDecorations(
- entries: Array<{ col: number; row: number; layer?: string; bg?: number; fg?: number }> = []
-): {
- reader: DecorationReader
- onDecorationRegistered(cb: () => void): { dispose(): void }
- onDecorationRemoved(cb: () => void): { dispose(): void }
- fireRegistered(): void
- fireRemoved(): void
- subCount(): number
-} {
- const registered = new Set<() => void>()
- const removed = new Set<() => void>()
- const sub = (set: Set<() => void>, cb: () => void): { dispose(): void } => {
- set.add(cb)
- return {
- dispose: (): void => {
- set.delete(cb)
- }
- }
- }
- return {
- reader: {
- empty: () => entries.length === 0,
- atCell: (col, row, cb) => entries.filter((e) => e.col === col && e.row === row).forEach(cb)
- },
- onDecorationRegistered: (cb) => sub(registered, cb),
- onDecorationRemoved: (cb) => sub(removed, cb),
- fireRegistered: () => {
- for (const cb of [...registered]) cb()
- },
- fireRemoved: () => {
- for (const cb of [...removed]) cb()
- },
- subCount: () => registered.size + removed.size
- }
-}
-
-/** The canvas blink clock's end of the seam, as the attach shell implements it: `release` is
- * IDENTITY-GUARDED, because browsers do not promise that the blurred terminal's blur reaches us
- * before the newly focused one's focus. Modelling that here is what makes the handover assertion
- * mean anything — an unguarded fake would pass against an unguarded shell.
- *
- * `onRelease` stands in for the clock's own restoring `setPhase(true)`, which is the behaviour
- * `dispose` has to leave room for. */
-function fakeBlinkSeam(o: { onRelease?: (t: CursorBlinkPhaseTarget) => void } = {}): {
- seam: CursorBlinkSeam
- target(): CursorBlinkPhaseTarget | null
- claims: CursorBlinkPhaseTarget[]
- releases: CursorBlinkPhaseTarget[]
-} {
- let current: CursorBlinkPhaseTarget | null = null
- const claims: CursorBlinkPhaseTarget[] = []
- const releases: CursorBlinkPhaseTarget[] = []
- return {
- seam: {
- claim(t) {
- claims.push(t)
- current = t
- },
- release(t) {
- releases.push(t)
- if (current !== t) return
- current = null
- o.onRelease?.(t)
- }
- },
- target: () => current,
- claims,
- releases
- }
-}
-
-interface FakeTermOpts {
- cols?: number
- rows?: number
- viewportY?: number
- baseY?: number
- cursorX?: number
- cursorY?: number
- cursorVisible?: boolean
- focus?: boolean
- decorations?: ReturnType<typeof fakeDecorations>
- /** xterm's two cursor options, verbatim. ABSENT on purpose in every test that does not name them:
- * an xterm build that stopped reporting them must degrade to xterm's own defaults (a focused
- * block, a blurred outline), never to no cursor at all. */
- cursorStyle?: { style?: string; inactiveStyle?: string }
- /** Columns whose cell reports width 2 — a wide glyph's LEAD. The column after one reports width
- * 0, exactly as xterm's buffer stores a double-width character. */
- wideCols?: readonly number[]
- /** The blink seam. ABSENT in every test that does not name it — a build with no shared layer
- * hands the addon exactly this, and the cursor simply never blinks. */
- blink?: CursorBlinkSeam
-}
-
-type FakeTermState = Required<
- Omit<FakeTermOpts, 'decorations' | 'cursorStyle' | 'wideCols' | 'blink'>
->
-
-function fakeTerm(o: FakeTermOpts = {}): TermInternals & { state: FakeTermState } {
- const state: FakeTermState = {
- cols: o.cols ?? 4,
- rows: o.rows ?? 6,
- viewportY: o.viewportY ?? 0,
- baseY: o.baseY ?? 0,
- cursorX: o.cursorX ?? 0,
- cursorY: o.cursorY ?? 0,
- cursorVisible: o.cursorVisible ?? true,
- focus: o.focus ?? true
- }
- const workCell = rowCodedCell(-1, -1)
- return {
- state,
- cols: () => state.cols,
- rows: () => state.rows,
- viewportY: () => state.viewportY,
- baseY: () => state.baseY,
- cursorX: () => state.cursorX,
- cursorY: () => state.cursorY,
- cursorVisible: () => state.cursorVisible,
- readCell: (absRow, col) => {
- const wide = o.wideCols ?? []
- if (wide.includes(col)) return { ...rowCodedCell(absRow, col), getWidth: () => 2 }
- if (wide.includes(col - 1)) return { ...rowCodedCell(absRow, col), getWidth: () => 0 }
- return rowCodedCell(absRow, col)
- },
- makeWorkCell: () => workCell,
- deviceMetrics: () => ({ charW: 16, charH: 34, cellW: 16, cellH: 34 }),
- dpr: () => 2,
- theme: () => THEME,
- hasFocus: () => state.focus,
- // Absent unless a test names them — see FakeTermOpts.cursorStyle.
- cursorStyle: o.cursorStyle ? () => o.cursorStyle as { style?: string } : undefined,
- // Absent unless a test asks for it, like the decorations below.
- blink: o.blink,
- // Absent unless a test asks for them — an xterm build with no decoration service hands the
- // addon exactly this, and every other test in this file is that case.
- decorations: o.decorations?.reader,
- onDecorationRegistered: o.decorations?.onDecorationRegistered,
- onDecorationRemoved: o.decorations?.onDecorationRemoved
- }
-}
+import { GlyphGridRendererAddonCore, type DeviceMetrics } from './addon'
function make(
o: FakeTermOpts & { atlas?: ReturnType<typeof recordingAtlas> } = {}
@@ -968,6 +704,33 @@ describe('GlyphGridRendererAddonCore blink target', () => {
expect(blink.target()).toBe(null)
})
+ it('restarts the blink on a cursor move — but only while it has focus', () => {
+ // xterm's own `restartBlinkAnimation` holds the cursor solid while you type. The FOCUS check is
+ // the addon's own: a background terminal streaming output moves its cursor constantly, and the
+ // fake below deliberately does NOT guard by identity (the module-level `restartCursorBlink`
+ // does that) so this asserts the addon's guard rather than the seam's.
+ const blink = fakeBlinkSeam()
+ const { core } = make({ rows: 8, cols: 4, cursorY: 1, cursorX: 1, blink: blink.seam })
+ core.handleCursorMove()
+ expect(blink.restarts.length).toBe(1)
+
+ core.handleBlur()
+ core.handleCursorMove()
+ expect(blink.restarts.length).toBe(1)
+
+ core.handleFocus()
+ core.handleCursorMove()
+ expect(blink.restarts.length).toBe(2)
+ })
+
+ it('asks for no restart once disposed', () => {
+ const blink = fakeBlinkSeam()
+ const { core } = make({ rows: 8, cols: 4, cursorY: 1, blink: blink.seam })
+ core.dispose()
+ core.handleCursorMove()
+ expect(blink.restarts).toEqual([])
+ })
+
it('constructs and packs normally when the shell offers no blink seam at all', () => {
// The degrade: no shared layer, no clock, no blink — Phase 1b's behaviour, not a broken addon.
const { core, handle } = make({ rows: 4, cols: 4, cursorY: 1, cursorX: 2 })
@@ -979,126 +742,11 @@ describe('GlyphGridRendererAddonCore blink target', () => {
})
})
-/**
- * THE PARK, END TO END — the one constraint this whole design exists to satisfy.
- *
- * The unit tests above prove the addon repacks on the caller's stack; the clock's own tests prove it
- * routes its bracketed damage to `pulse()`. Neither alone proves the FEATURE parks, because the trap
- * lives exactly in the seam between them: an addon that repacked one tick later would satisfy both
- * and still put an idle canvas back at the display's refresh rate, thirty frames every 600 ms.
- *
- * So this wires the REAL addon to the REAL clock through a handle that reports damage the way the
- * engine does — edge-triggered on the clean→dirty transition, cleared by the frame the loop draws.
- */
-describe('the blink phase through the real clock', () => {
- function wired(): {
- core: GlyphGridRendererAddonCore
- handle: ReturnType<typeof recordingHandle>
- loop: { wake: number; pulse: number }
- running(): boolean
- tick(): void
- frame(): void
- } {
- const handle = recordingHandle()
- let clock: CursorBlinkClock | null = null
- const loop = { wake: 0, pulse: 0 }
- // The engine's `markDirty` notifies on the clean→dirty EDGE only, and the FRAME clears the flag
- // — neither `wake()` nor `pulse()` draws inline, they schedule. Modelling that (rather than one
- // notification per write) is what makes the counts below mean "frames scheduled", which is the
- // number the park is about.
- let dirty = false
- const damage = (): void => {
- if (dirty) return
- dirty = true
- clock?.routeDamage()
- }
- const damaging: GridHandle = {
- ...handle,
- updateRow(row, cells) {
- handle.updateRow(row, cells)
- damage()
- },
- setCursor(cursor) {
- handle.setCursor(cursor)
- damage()
- }
- }
-
- let current: CursorBlinkPhaseTarget | null = null
- // The attach shell's seam, verbatim in behaviour: claim publishes, release is identity-guarded,
- // and either change re-syncs the clock (the real one does it through the layer's subscription).
- const seam: CursorBlinkSeam = {
- claim(t) {
- current = t
- clock?.sync()
- },
- release(t) {
- if (current !== t) return
- current = null
- clock?.sync()
- }
- }
-
- let fire: (() => void) | null = null
- clock = createCursorBlinkClock({
- enabled: () => true,
- covered: () => false,
- target: () => current,
- loop: () => ({
- wake: () => {
- loop.wake++
- },
- pulse: () => {
- loop.pulse++
- }
- }),
- setInterval: (cb) => {
- fire = cb
- return 1
- },
- clearInterval: () => {
- fire = null
- }
- })
-
- const term = fakeTerm({ rows: 4, cols: 4, cursorY: 1, cursorX: 2, focus: true, blink: seam })
- const core = new GlyphGridRendererAddonCore(term, damaging, recordingAtlas())
- return {
- core,
- handle,
- loop,
- running: () => fire !== null,
- tick: () => fire?.(),
- frame: () => {
- dirty = false
- }
- }
- }
-
- it('a phase flip costs ONE pulse and never a wake — the idle park survives the blink', () => {
- const h = wired()
- // The addon claimed the blink at construction, so the clock is already ticking.
- expect(h.running()).toBe(true)
- for (let i = 0; i < 3; i++) {
- h.tick()
- // The frame the pulse scheduled draws and clears the engine's dirty flag, 600 ms before the
- // next phase — which is what lets the next flip notify at all.
- h.frame()
- }
- expect(h.loop.pulse).toBe(3)
- expect(h.loop.wake).toBe(0)
- })
-
- it('ordinary damage from the SAME addon still takes wake()', () => {
- // The other half of the routing: only the clock's own bracketed repaint is a pulse. 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.
- const h = wired()
- h.core.renderRows(0, 3)
- expect(h.loop.wake).toBe(1)
- expect(h.loop.pulse).toBe(0)
- })
-})
+// The blink's END-TO-END test — the real addon driven by the real clock — lives in
+// `canvas/SharedGlyphLayer.test.ts`, not here: it needs the clock, and the dependency direction is
+// canvas → glyphgrid. Importing the layer from a glyphgrid unit test would drag React, zustand and
+// three stores into this file's module graph. The fakes the two files share live in
+// `addon-fakes.ts` (a plain module, because importing a `.test.ts` collects its suite twice).
/** BLUR AND THE SELECTION — limitation L3.
*
diff --git a/src/renderer/glyphgrid/addon.ts b/src/renderer/glyphgrid/addon.ts
index 6b820f5a2..0851ceaf8 100644
--- a/src/renderer/glyphgrid/addon.ts
+++ b/src/renderer/glyphgrid/addon.ts
@@ -51,6 +51,12 @@ export interface CursorBlinkPhaseTarget {
export interface CursorBlinkSeam {
claim(target: CursorBlinkPhaseTarget): void
release(target: CursorBlinkPhaseTarget): void
+ /** The cursor MOVED: hold it solid and start the period over, exactly as xterm's own
+ * `CursorBlinkStateManager.restartBlinkAnimation` does. Identity-guarded in the shell like
+ * `release`, and for a second reason on top of that one — a background terminal streaming output
+ * moves its cursor constantly, and any of them re-arming the focused terminal's period would
+ * hold the blink permanently solid. */
+ restart(target: CursorBlinkPhaseTarget): void
}
/** What the addon needs from a live terminal. Kept minimal so the addon is testable with fakes and
@@ -324,6 +330,19 @@ export class GlyphGridRendererAddonCore {
handleCursorMove(): void {
if (this.disposed) return
+ // FIRST, before the packs, and only for the terminal that HAS focus. xterm's own cursor holds
+ // solid while you type (`CursorBlinkStateManager.restartBlinkAnimation`), and a STACKED terminal
+ // beside this one is drawing exactly that on xterm's DOM renderer — a shared cursor that kept
+ // flashing through a keystroke is the drift `CURSOR_BLINK_INTERVAL_MS` was matched to prevent.
+ //
+ // Its position in this method is what keeps the restart's repaint inside the clock's bracket:
+ // the clock shows the cursor synchronously from here, so that repaint takes `pulse()`. The two
+ // packs below are ordinary damage — but the engine notifies only on the clean→dirty EDGE, so
+ // whichever write lands first is the one that routes, and a keystroke therefore costs a pulse
+ // rather than a wake. That is fine and deliberate: either route reaches a FRAME, which is the
+ // invariant, and the bracket exists to keep the blink's TIMED repaints off the wake path — not
+ // to make sure typing takes it.
+ if (this.focused) this.internals.blink?.restart(this.blinkSelf)
const next = this.cursorViewportRow()
const prev = this.lastCursorRow
this.lastCursorRow = next
diff --git a/src/renderer/glyphgrid/frame-driver.test.ts b/src/renderer/glyphgrid/frame-driver.test.ts
index 0ad19cb72..b98d7aa6f 100644
--- a/src/renderer/glyphgrid/frame-driver.test.ts
+++ b/src/renderer/glyphgrid/frame-driver.test.ts
@@ -247,6 +247,24 @@ describe('createFrameLoop', () => {
expect(h.scheduled()).toBe(true)
})
+ it('pulse() before start() draws its frame and leaves the loop with NO heartbeat', () => {
+ // Documenting the state rather than defending it. A one-shot on a loop that was never started
+ // parks it without arming the heartbeat, because the heartbeat is armed by the park that
+ // FOLLOWS a running frame — so the loop is left with neither an rAF nor a timer, and only a
+ // later `wake()`/`start()` brings it back. Unreachable through the layer (the board gate starts
+ // the loop before the clock can reach it) and harmless there; asserted so a future change to
+ // `start()`'s or `park()`'s bookkeeping cannot alter it silently.
+ const h = harness()
+ h.loop.pulse()
+ expect(h.scheduled()).toBe(true)
+ h.runFrame()
+ expect(h.frame).toHaveBeenCalledTimes(1)
+ expect(h.scheduled()).toBe(false)
+ expect(h.timer()).toBeNull()
+ h.loop.wake()
+ expect(h.scheduled()).toBe(true)
+ })
+
it('pulse() after stop() is inert', () => {
const h = harness()
h.loop.start()
diff --git a/src/renderer/terminal/glyphgrid-attach.ts b/src/renderer/terminal/glyphgrid-attach.ts
index 81a7f5a12..e22b10ab9 100644
--- a/src/renderer/terminal/glyphgrid-attach.ts
+++ b/src/renderer/terminal/glyphgrid-attach.ts
@@ -12,7 +12,11 @@
* behavior we ship today. */
import type { Terminal } from '@xterm/xterm'
-import { cursorBlinkTarget, setCursorBlinkTarget } from '../canvas/SharedGlyphLayer'
+import {
+ releaseCursorBlinkTarget,
+ restartCursorBlink,
+ setCursorBlinkTarget
+} from '../canvas/SharedGlyphLayer'
import {
GlyphGridRendererAddonCore,
type DeviceMetrics,
@@ -325,16 +329,14 @@ export function attachGlyphGrid(
// that knows: it tracks focus itself (xterm's handleFocus/handleBlur, see `TermInternals`), and
// it is also the only thing that can suppress BOTH halves of a cursor for a phase.
//
- // Not read from xterm at all, so this widens no private surface: the two calls below are ours.
- // `release` is IDENTITY-GUARDED because the browser does not promise the blurred terminal's
- // blur reaches us before the newly focused one's focus — an unconditional
- // `setCursorBlinkTarget(null)` on a late blur would stop the cursor of the terminal the user
- // just clicked into.
+ // Not read from xterm at all, so this widens no private surface: the three calls below are ours.
+ // The identity guards `release` and `restart` need live INSIDE those two functions rather than
+ // here — this file has no unit tests by design, and a guard written out here would be the copy
+ // the suite never exercises.
blink: {
claim: (target) => setCursorBlinkTarget(target),
- release: (target) => {
- if (cursorBlinkTarget() === target) setCursorBlinkTarget(null)
- }
+ release: (target) => releaseCursorBlinkTarget(target),
+ restart: (target) => restartCursorBlink(target)
},
// Spread, so a terminal with no usable decoration service leaves all three members undefined —
// the addon's "this terminal has no highlights" case.