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): wire the blink phase into the addon — the cursor actually blinks

enes96bdbb14bda8
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 081e865ab..48a9ca60b 100644
--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
@@ -232,10 +232,13 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
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.
+ **A block cursor blinks as a whole cell and every other shape as a hairline overlay — walk at
+ least one of each** (Settings → Terminal → Cursor style), because the two are drawn by
+ different halves of the renderer and a phase that hid only one would show as a cursor that
+ goes hollow instead of away, or as an inverted cell with no mark on it. A cursor that is
+ **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.
**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
@@ -481,8 +484,9 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
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.)
+ 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.
**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
@@ -530,19 +534,6 @@ 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 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.
- **L5 — FIXED in round 2 (bands at the bottom/right).** Kept here as the record, because it is the
one item on this list whose expected observation INVERTED. It used to read: the plate covers the
grid plus one scalar of host padding (`padPx`, the 6px max of `.term-node__xterm`'s asymmetric
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index 8d2fe9d4f..a83d04d99 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -1220,6 +1220,11 @@ export const CURSOR_BLINK_INTERVAL_MS = 600
* 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.
+ *
+ * THE PRODUCER is `GlyphGridRendererAddonCore` — `setCursorBlinkPhase` for (2) and (3), published
+ * on its own focus edges for (1) through the `blink` seam the attach shell supplies
+ * (`terminal/glyphgrid-attach.ts`). It has to be the addon: it is the only thing that tracks which
+ * terminal has focus and the only thing that holds both halves of a cursor.
*/
export interface CursorBlinkTarget {
/** Show or hide this terminal's cursor for the current phase. */
diff --git a/src/renderer/glyphgrid/addon.test.ts b/src/renderer/glyphgrid/addon.test.ts
index 1813771e0..0a5d23438 100644
--- a/src/renderer/glyphgrid/addon.test.ts
+++ b/src/renderer/glyphgrid/addon.test.ts
@@ -1,10 +1,17 @@
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 { 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'
@@ -164,6 +171,41 @@ function fakeDecorations(
}
}
+/** 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
@@ -181,9 +223,14 @@ interface FakeTermOpts {
/** 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'>>
+type FakeTermState = Required<
+ Omit<FakeTermOpts, 'decorations' | 'cursorStyle' | 'wideCols' | 'blink'>
+>
function fakeTerm(o: FakeTermOpts = {}): TermInternals & { state: FakeTermState } {
const state: FakeTermState = {
@@ -219,6 +266,8 @@ function fakeTerm(o: FakeTermOpts = {}): TermInternals & { state: FakeTermState
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,
@@ -709,6 +758,348 @@ describe('GlyphGridRendererAddonCore cursor shape', () => {
})
})
+/** THE BLINK PHASE — the producer half of the canvas's cursor-blink clock.
+ *
+ * The clock (`canvas/SharedGlyphLayer.tsx`) owns the timing; the addon is the only thing that can
+ * APPLY a phase, because a block cursor is a CELL rewrite and every other shape is an OVERLAY and
+ * only this class holds both. So every test here asserts BOTH halves: a phase that hid one and not
+ * the other would leave an inverted cell under a cleared overlay, or a bar hanging beside a cursor
+ * that is supposed to be gone. */
+describe('GlyphGridRendererAddonCore.setCursorBlinkPhase', () => {
+ const lastCursor = (h: ReturnType<typeof recordingHandle>): GridCursor | null | undefined =>
+ h.cursors.at(-1)
+ /** The cursor flag on the NEWEST pack of a row — the older packs are still in the log, and a
+ * blink is precisely a sequence of packs of the same row. */
+ const cursorFlag = (
+ h: ReturnType<typeof recordingHandle>,
+ row: number,
+ col: number
+ ): number => {
+ const rec = [...h.rows].reverse().find((r) => r.row === row)
+ if (!rec) throw new Error(`row ${row} was never packed`)
+ return readCell(rec.cells, col).flags & FLAG_CURSOR
+ }
+
+ it('hides BOTH halves of a block cursor for the hidden phase, and brings both back', () => {
+ const { core, handle } = make({ rows: 4, cols: 4, cursorY: 1, cursorX: 2 })
+ core.renderRows(0, 3)
+ expect(cursorFlag(handle, 1, 2)).toBe(FLAG_CURSOR)
+ // A block never uses the overlay — the cells carry it, which is why the overlay alone could
+ // never have implemented this.
+ expect(lastCursor(handle)).toBe(null)
+
+ core.setCursorBlinkPhase(false)
+ expect(cursorFlag(handle, 1, 2)).toBe(0)
+ expect(lastCursor(handle)).toBe(null)
+
+ core.setCursorBlinkPhase(true)
+ expect(cursorFlag(handle, 1, 2)).toBe(FLAG_CURSOR)
+ })
+
+ it('hides the OVERLAY half too — a bar cursor blinks on the same phase', () => {
+ const { core, handle } = make({
+ rows: 4,
+ cols: 4,
+ cursorY: 1,
+ cursorX: 2,
+ cursorStyle: { style: 'bar' }
+ })
+ core.renderRows(0, 3)
+ expect(lastCursor(handle)?.shape).toBe('bar')
+
+ core.setCursorBlinkPhase(false)
+ expect(lastCursor(handle)).toBe(null)
+ expect(cursorFlag(handle, 1, 2)).toBe(0)
+
+ core.setCursorBlinkPhase(true)
+ expect(lastCursor(handle)?.shape).toBe('bar')
+ })
+
+ it('repacks the cursor row SYNCHRONOUSLY, and asks for NO redraw', () => {
+ // THE contract. The clock brackets this call to route the damage it produces through the frame
+ // loop's one-shot `pulse()`; a repack handed to `onRequestRedraw` (as an atlas reset or a
+ // decoration change is) would land outside that bracket, take `wake()`, and re-arm the 30-frame
+ // idle streak twice a second.
+ const { core, handle } = make({ rows: 4, cols: 4, cursorY: 2, cursorX: 0 })
+ const redraws: Array<{ start: number; end: number }> = []
+ core.onRequestRedraw((e) => redraws.push(e))
+ handle.rows.length = 0
+
+ core.setCursorBlinkPhase(false)
+
+ expect(handle.rows.map((r) => r.row)).toEqual([2])
+ expect(redraws).toEqual([])
+ })
+
+ it('is change-gated — the same phase twice costs one pack', () => {
+ const { core, handle } = make({ rows: 4, cols: 4, cursorY: 2, cursorX: 0 })
+ handle.rows.length = 0
+ core.setCursorBlinkPhase(false)
+ core.setCursorBlinkPhase(false)
+ expect(handle.rows.map((r) => r.row)).toEqual([2])
+ })
+
+ it('is inert after dispose — a clock tick racing a teardown must not touch the grid', () => {
+ const { core, handle } = make({ rows: 4, cols: 4, cursorY: 2, cursorX: 0 })
+ core.dispose()
+ handle.log.length = 0
+ core.setCursorBlinkPhase(false)
+ expect(handle.log).toEqual([])
+ })
+
+ it('a pack that misses the cursor row during a hidden phase neither repairs nor resurrects it', () => {
+ // A hidden phase is the same "no cursor row in this pass" case DECTCEM already produces, so
+ // `settleCursorCells` takes neither branch: no repair repack, and certainly no block painted
+ // back onto a row the blink just cleared.
+ const { core, handle } = make({ rows: 8, cols: 4, cursorY: 0, cursorX: 1 })
+ core.renderRows(0, 7)
+ core.setCursorBlinkPhase(false)
+ handle.rows.length = 0
+ core.renderRows(4, 5)
+ expect(handle.rows.map((r) => r.row)).toEqual([4, 5])
+ })
+
+ it('the block-ness repair still fires once the phase returns', () => {
+ // Constraint: hiding the cursor must not corrupt `cellCursorBlock`. Flip block-ness WHILE the
+ // cursor is hidden and pack rows that miss it — the bookkeeping the repair reads is stale by
+ // construction — then show the cursor again and the row must come back as an outline: cells
+ // un-inverted, overlay pushed.
+ const style = { style: 'block', inactiveStyle: 'block' }
+ const { core, handle } = make({
+ rows: 8,
+ cols: 4,
+ cursorY: 0,
+ cursorX: 1,
+ focus: false,
+ cursorStyle: style
+ })
+ core.renderRows(0, 7)
+ expect(cursorFlag(handle, 0, 1)).toBe(FLAG_CURSOR)
+
+ core.setCursorBlinkPhase(false)
+ style.inactiveStyle = 'outline'
+ core.renderRows(4, 5)
+ handle.rows.length = 0
+
+ core.setCursorBlinkPhase(true)
+ expect(handle.rows.map((r) => r.row)).toEqual([0])
+ expect(cursorFlag(handle, 0, 1)).toBe(0)
+ expect(lastCursor(handle)?.shape).toBe('outline')
+ })
+
+ it('a cursor the APP has hidden stays hidden through a shown phase', () => {
+ // DECTCEM and the blink are independent reasons not to draw; neither may override the other.
+ const { core, handle } = make({
+ rows: 4,
+ cols: 4,
+ cursorY: 1,
+ cursorX: 1,
+ cursorVisible: false
+ })
+ core.renderRows(0, 3)
+ core.setCursorBlinkPhase(false)
+ core.setCursorBlinkPhase(true)
+ expect(cursorFlag(handle, 1, 1)).toBe(0)
+ expect(lastCursor(handle)).toBe(null)
+ })
+})
+
+/** WHICH terminal blinks — the focus edge the clock's only gate is built on. */
+describe('GlyphGridRendererAddonCore blink target', () => {
+ it('claims the blink at construction when the terminal already has focus', () => {
+ // A mode switch or a remount attaches to a terminal the user is already typing in; a clock
+ // that only learned about focus on the NEXT focus event would leave that cursor static.
+ const blink = fakeBlinkSeam()
+ const { core } = make({ blink: blink.seam, focus: true })
+ expect(blink.target()).not.toBe(null)
+ core.dispose()
+ })
+
+ it('claims nothing while the terminal is blurred', () => {
+ const blink = fakeBlinkSeam()
+ make({ blink: blink.seam, focus: false })
+ expect(blink.claims).toEqual([])
+ expect(blink.target()).toBe(null)
+ })
+
+ it('claims on focus, releases on blur, and hands over the SAME object every time', () => {
+ // Identity is the contract: the clock is change-gated on it (`next !== current`), so a fresh
+ // object per focus event would restart the blink period on every notification.
+ const blink = fakeBlinkSeam()
+ const { core } = make({ blink: blink.seam, focus: false })
+ core.handleFocus()
+ const first = blink.target()
+ expect(first).not.toBe(null)
+ core.handleBlur()
+ expect(blink.target()).toBe(null)
+ core.handleFocus()
+ expect(blink.target()).toBe(first)
+ })
+
+ it('a LATE blur cannot steal the blink from the terminal that just took focus', () => {
+ // Browsers do not promise the blur of the old terminal reaches us before the focus of the new
+ // one. An unconditional clear on blur would stop the cursor of the terminal the user just
+ // clicked into — which is the only terminal that is supposed to be blinking.
+ const blink = fakeBlinkSeam()
+ const a = make({ blink: blink.seam, focus: true })
+ const b = make({ blink: blink.seam, focus: false })
+ b.core.handleFocus()
+ const bTarget = blink.target()
+ a.core.handleBlur()
+ expect(blink.target()).toBe(bTarget)
+ })
+
+ it('releases BEFORE it goes inert, so the clock can hand the cursor back shown', () => {
+ // The clock restores the phase from inside its release path. If dispose had already flipped the
+ // addon inert, that restore would be a silent no-op and the last packed row would keep the
+ // cursor the blink happened to be hiding — an invisible cursor on a node swapped back to the
+ // DOM renderer.
+ const blink = fakeBlinkSeam({ onRelease: (t) => t.setPhase(true) })
+ const { core, handle } = make({ rows: 4, cols: 4, cursorY: 1, cursorX: 2, blink: blink.seam })
+ core.renderRows(0, 3)
+ core.setCursorBlinkPhase(false)
+ handle.rows.length = 0
+
+ core.dispose()
+
+ const rec = [...handle.rows].reverse().find((r) => r.row === 1)
+ expect(rec).toBeDefined()
+ expect(readCell(rec!.cells, 2).flags & FLAG_CURSOR).toBe(FLAG_CURSOR)
+ expect(blink.target()).toBe(null)
+ })
+
+ 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 })
+ core.renderRows(0, 3)
+ core.handleFocus()
+ core.handleBlur()
+ core.dispose()
+ expect(handle.rows.length).toBeGreaterThan(0)
+ })
+})
+
+/**
+ * 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)
+ })
+})
+
/** BLUR AND THE SELECTION — limitation L3.
*
* xterm paints an unfocused terminal's selection in a quieter colour; this engine's theme lanes
diff --git a/src/renderer/glyphgrid/addon.ts b/src/renderer/glyphgrid/addon.ts
index 20a912f46..6b820f5a2 100644
--- a/src/renderer/glyphgrid/addon.ts
+++ b/src/renderer/glyphgrid/addon.ts
@@ -27,6 +27,32 @@ export interface DeviceMetrics {
cellH: number
}
+/** This terminal's end of the canvas cursor-blink clock: the clock hands the focused terminal its
+ * phase through here. Declared structurally rather than imported from the shared layer — this
+ * directory imports nothing — and it is the same shape as the layer's `CursorBlinkTarget`. */
+export interface CursorBlinkPhaseTarget {
+ setPhase(visible: boolean): void
+}
+
+/**
+ * How the addon publishes WHICH terminal the canvas's single blink clock should be driving.
+ *
+ * The addon is the only thing that can answer it: it tracks focus itself (see `focused`), and a
+ * focused block cursor produces no overlay at all, so focus is invisible from the engine side.
+ *
+ * OPTIONAL, like the decorations: a build with no shared layer hands over nothing and the cursor
+ * simply never blinks — Phase 1b's behaviour, not a broken renderer.
+ *
+ * `release(target)` rather than a bare `setTarget(null)`, and it is IDENTITY-GUARDED by the shell:
+ * browsers do not promise that the blurred terminal's blur reaches us before the newly focused
+ * one's focus, and an unconditional clear on a late blur would stop the cursor of the terminal the
+ * user just clicked into — the only one that is supposed to be blinking.
+ */
+export interface CursorBlinkSeam {
+ claim(target: CursorBlinkPhaseTarget): void
+ release(target: CursorBlinkPhaseTarget): void
+}
+
/** What the addon needs from a live terminal. Kept minimal so the addon is testable with fakes and
* survives xterm minor bumps. */
export interface TermInternals {
@@ -60,6 +86,8 @@ export interface TermInternals {
* `focused`), because whether the browser service's flag has flipped by the time xterm calls
* handleBlur is an ordering detail the cursor's correctness must not rest on. */
cursorStyle?(): { style?: string; inactiveStyle?: string }
+ /** The canvas's blink clock, or undefined on a build that has none. See `CursorBlinkSeam`. */
+ blink?: CursorBlinkSeam
/** The terminal's decorations — the cell colours a ⌘F hit paints — or undefined.
*
* ALL THREE DECORATION MEMBERS ARE OPTIONAL, together: an xterm build whose decoration service
@@ -155,6 +183,24 @@ export class GlyphGridRendererAddonCore {
*/
private cellCursorBlock: boolean
+ /**
+ * Whether the canvas's blink clock currently wants this terminal's cursor SHOWN.
+ *
+ * A third reason a cursor may not be drawn this instant, independent of focus and of the app's
+ * own DECTCEM state — see `cursorShown`, which is the single place the three meet. True whenever
+ * no clock is driving this terminal, so every terminal that is not the blink target (and every
+ * terminal at all, on a build with no shared layer) draws exactly as it did before.
+ */
+ private blinkVisible = true
+
+ /** ONE object for the addon's lifetime, handed to the clock on every focus edge. Identity is the
+ * contract, not an optimization: the clock is change-gated on it (`next !== current`, and
+ * `setCursorBlinkTarget` compares by reference), so a fresh object per focus event would restart
+ * the blink period every time a focus notification arrived. */
+ private readonly blinkSelf: CursorBlinkPhaseTarget = {
+ setPhase: (visible: boolean): void => this.setCursorBlinkPhase(visible)
+ }
+
/** Mutable because `readCellBound` closes over it: one closure for the lifetime of the addon
* instead of one per packed row. */
private absRow = 0
@@ -199,6 +245,12 @@ export class GlyphGridRendererAddonCore {
const onRemoved = internals.onDecorationRemoved
if (onRegistered) this.decorationSubs.push(onRegistered(() => this.handleDecorationChange()))
if (onRemoved) this.decorationSubs.push(onRemoved(() => this.handleDecorationChange()))
+ // LAST, and after the subscriptions, for the same reason they go last: this publishes the addon
+ // into a CANVAS-LEVEL singleton, and a construction that threw afterwards would leave it there
+ // with nobody holding an addon to release it. Seeded rather than waited for, because a mode
+ // switch or a remount attaches to a terminal the user is already typing in — a clock that only
+ // learned about focus on the next focus EVENT would leave that cursor static.
+ this.publishBlinkTarget()
}
// ---------------------------------------------------------------- xterm renderer surface
@@ -283,12 +335,38 @@ export class GlyphGridRendererAddonCore {
if (this.disposed) return
this.focused = false
this.repaintFocusDependent()
+ // AFTER the repaint: releasing makes the clock restore this cursor to its shown phase, and it
+ // must restore the blurred SHAPE, which `repaintFocusDependent` has just established.
+ this.publishBlinkTarget()
}
handleFocus(): void {
if (this.disposed) return
this.focused = true
this.repaintFocusDependent()
+ this.publishBlinkTarget()
+ }
+
+ /**
+ * The canvas blink clock's phase for THIS terminal — show or hide its cursor for the half-period.
+ *
+ * SYNCHRONOUS, and that is the contract rather than an implementation detail. The clock brackets
+ * this call so the damage it produces is routed to the frame loop's one-shot `pulse()` instead of
+ * `wake()` (see `CursorBlinkTarget` in `canvas/SharedGlyphLayer.tsx`): a repack deferred to a
+ * redraw request — the way an atlas reset and a decoration change defer theirs — would land
+ * OUTSIDE that bracket, take the wake path, and re-arm the 30-frame idle streak twice a second.
+ * That is Phase 1c's idle park silently undone on every canvas with a focused terminal, i.e. the
+ * exact failure the clock exists to prevent. So the row is packed here, on the caller's stack;
+ * this must never become an `emitRedraw`.
+ *
+ * BOTH halves go together, which is why only the addon can apply a phase: `packRows` re-pushes
+ * the overlay (`syncCursor`) before it packs, and `cursorShown()` gates the cell half in the same
+ * breath — so a block's cell inversion and every other shape's overlay disappear on one phase.
+ */
+ setCursorBlinkPhase(visible: boolean): void {
+ if (this.disposed || this.blinkVisible === visible) return
+ this.blinkVisible = visible
+ this.packCursorRow()
}
/** Not part of xterm's renderer surface — the shell calls it from `_themeService.onChangeColors`.
@@ -314,6 +392,11 @@ export class GlyphGridRendererAddonCore {
* The grid HANDLE is deliberately not disposed — the node that registered it owns its lifetime
* (it outlives a renderer swap back to DOM). */
dispose(): void {
+ // BEFORE `disposed`, deliberately: the clock restores the phase from inside its release path,
+ // and an addon already flipped inert would swallow that `setPhase(true)` — leaving the last
+ // packed row without the cursor the blink happened to be hiding. Identity-guarded in the shell,
+ // so a terminal torn down after another has taken focus cannot stop the new one's blink.
+ this.releaseBlinkTarget()
this.disposed = true
// The overlay cursor is a GRID-level value, so — unlike a packed row — nothing will ever
// overwrite it. A renderer swapped back to xterm's DOM one would otherwise leave a bar or an
@@ -409,6 +492,31 @@ export class GlyphGridRendererAddonCore {
if (sel) this.packRows(sel[0], sel[1])
}
+ /** Tell the canvas's blink clock whether this terminal is the one to blink. Called on every focus
+ * edge and once at construction; `dispose` uses `releaseBlinkTarget` directly, because by then
+ * the answer is "nobody" whatever the focus flag says. */
+ private publishBlinkTarget(): void {
+ if (this.focused) this.internals.blink?.claim(this.blinkSelf)
+ else this.releaseBlinkTarget()
+ }
+
+ private releaseBlinkTarget(): void {
+ this.internals.blink?.release(this.blinkSelf)
+ }
+
+ /**
+ * Is the cursor drawn at all right now?
+ *
+ * Two independent reasons it may not be — the app's own DECTCEM state (a TUI hiding it) and the
+ * blink clock's phase — and every path that draws EITHER half asks this one question, which is
+ * what keeps the cell half and the overlay half from ever disagreeing about a phase. Focus is
+ * deliberately not in here: a blurred terminal still has a cursor, it just wears a different
+ * shape (see `cursorShape`).
+ */
+ private cursorShown(): boolean {
+ return this.blinkVisible && this.internals.cursorVisible()
+ }
+
/** The shape the cursor takes right now, from the shell's options and OUR focus flag. */
private cursorShape(): CursorShape {
const opts = this.internals.cursorStyle?.()
@@ -420,14 +528,15 @@ export class GlyphGridRendererAddonCore {
*
* Null for a BLOCK as well as for `none`: a block is a cell rewrite (only that path can invert the
* glyph under it), and drawing it here too would paint an opaque quad over the inversion the feed
- * just produced. Null for a hidden cursor (DECTCEM inside a TUI) and for one scrolled out of the
- * viewport, both for the same reason: the overlay is a GRID-level value, so nothing else would
- * ever erase a stale one — unlike a packed row, which the next frame rewrites wholesale.
+ * just produced. Null for a cursor that is not shown right now (`cursorShown` — DECTCEM inside a
+ * TUI, or the blink's hidden phase) and for one scrolled out of the viewport, both for the same
+ * reason: the overlay is a GRID-level value, so nothing else would ever erase a stale one —
+ * unlike a packed row, which the next frame rewrites wholesale.
*/
private cursorSpec(): GridCursor | null {
const shape = this.cursorShape()
if (shape === 'block' || shape === 'none') return null
- if (!this.internals.cursorVisible()) return null
+ if (!this.cursorShown()) return null
if (this.cols <= 0 || this.rows <= 0) return null
const row = this.cursorViewportRow()
if (row < 0 || row >= this.rows) return null
@@ -472,10 +581,13 @@ export class GlyphGridRendererAddonCore {
if (end < start || this.cols <= 0) return
const theme = this.internals.theme()
const viewportY = this.internals.viewportY()
- // -1 = no cursor row in this pass (the app hid it — DECTCEM inside a TUI). NOT focus-gated any
- // more: a blurred terminal still has a cursor, it just wears a different shape, and which of the
- // two paths draws it is `cursorShape`'s answer below — not this row's.
- const cursorRow = this.internals.cursorVisible()
+ // -1 = no cursor row in this pass — the app hid it (DECTCEM inside a TUI) or the blink clock is
+ // in its hidden phase. The two share this branch on purpose: `settleCursorCells` already knows
+ // that a cursor row of -1 means "there is no block to keep in step with", so a phase costs no
+ // repair repack and can never paint a block back onto the row it just cleared. NOT focus-gated:
+ // a blurred terminal still has a cursor, it just wears a different shape, and which of the two
+ // paths draws it is `cursorShape`'s answer below — not this row's.
+ const cursorRow = this.cursorShown()
? this.internals.baseY() + this.internals.cursorY() - viewportY
: -1
// Resolved ONCE for the range: only a `block` is a cell rewrite, and the feed ignores
diff --git a/src/renderer/terminal/glyphgrid-attach.ts b/src/renderer/terminal/glyphgrid-attach.ts
index 633e841a6..81a7f5a12 100644
--- a/src/renderer/terminal/glyphgrid-attach.ts
+++ b/src/renderer/terminal/glyphgrid-attach.ts
@@ -12,6 +12,7 @@
* behavior we ship today. */
import type { Terminal } from '@xterm/xterm'
+import { cursorBlinkTarget, setCursorBlinkTarget } from '../canvas/SharedGlyphLayer'
import {
GlyphGridRendererAddonCore,
type DeviceMetrics,
@@ -319,6 +320,22 @@ export function attachGlyphGrid(
style: term.options.cursorStyle,
inactiveStyle: term.options.cursorInactiveStyle
}),
+ // The canvas's cursor-blink clock lives in the shared layer and drives exactly ONE terminal —
+ // the focused one — so the addon publishes its own focus edges through here. It is the addon
+ // 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.
+ blink: {
+ claim: (target) => setCursorBlinkTarget(target),
+ release: (target) => {
+ if (cursorBlinkTarget() === target) setCursorBlinkTarget(null)
+ }
+ },
// Spread, so a terminal with no usable decoration service leaves all three members undefined —
// the addon's "this terminal has no highlights" case.
...(decorationsOf(core) ?? {})