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): pure viewport-row feed — colors, selection, cursor, wide/invalid cells
enesdad7cd2491f7
diff --git a/src/renderer/glyphgrid/feed.test.ts b/src/renderer/glyphgrid/feed.test.tsnew file mode 100644index 000000000..c8ce55d03--- /dev/null+++ b/src/renderer/glyphgrid/feed.test.ts@@ -0,0 +1,311 @@+import { describe, expect, it } from 'vitest'+import { CELL_STRIDE, FLAG_BOLD, FLAG_CURSOR, FLAG_ITALIC, FLAG_SELECTED, FLAG_UNDERLINE, FLAG_WIDE, packColor, readCell } from './cells'+import type { GlyphAtlas } from './atlas'+import { packViewportRow, type CellView, type RowFeedOpts, type ThemeLanes } from './feed'++const THEME: ThemeLanes = {+ fg: packColor(0xd0, 0xd1, 0xd2, 0xff),+ bg: packColor(0x10, 0x11, 0x12, 0xff),+ // One distinguishable color per index, so a wrong index is a wrong assertion and not a+ // coincidence: index i is recoverable from any channel.+ 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)+}++/** Records every glyphFor call so "the atlas was NOT called" is assertable, and hands back a+ * distinct non-zero slot per call so a glyph lane can be traced to the call that produced it. */+function fakeAtlas(): Pick<GlyphAtlas, 'glyphFor'> & { calls: Array<[number, boolean, boolean]> } {+ const calls: Array<[number, boolean, boolean]> = []+ return {+ calls,+ glyphFor(code: number, bold: boolean, italic: boolean): number {+ calls.push([code, bold, italic])+ return 900 + calls.length+ }+ }+}++type Attr = 'default' | ['palette', number] | ['rgb', number]++function makeCell(+ o: {+ code?: number+ width?: number+ bold?: boolean+ italic?: boolean+ underline?: boolean+ inverse?: boolean+ dim?: boolean+ fg?: Attr+ bg?: Attr+ } = {}+): CellView {+ const fg: Attr = o.fg ?? 'default'+ const bg: Attr = o.bg ?? 'default'+ const is = (a: Attr, mode: string): boolean => (a === 'default' ? mode === 'default' : a[0] === mode)+ const val = (a: Attr): number => (a === 'default' ? 0 : a[1])+ return {+ getCode: () => o.code ?? 0x41,+ getWidth: () => o.width ?? 1,+ isBold: () => (o.bold ? 1 : 0),+ isItalic: () => (o.italic ? 1 : 0),+ isUnderline: () => (o.underline ? 1 : 0),+ isInverse: () => (o.inverse ? 1 : 0),+ isDim: () => (o.dim ? 1 : 0),+ isFgDefault: () => is(fg, 'default'),+ isFgPalette: () => is(fg, 'palette'),+ isFgRGB: () => is(fg, 'rgb'),+ isBgDefault: () => is(bg, 'default'),+ isBgPalette: () => is(bg, 'palette'),+ isBgRGB: () => is(bg, 'rgb'),+ getFgColor: () => val(fg),+ getBgColor: () => val(bg)+ }+}++function pack(+ cells: readonly (CellView | undefined)[],+ o: Partial<Pick<RowFeedOpts, 'cols' | 'selection' | 'cursorCol' | 'atlas'>> = {}+): { out: Uint32Array; atlas: ReturnType<typeof fakeAtlas> } {+ const atlas = (o.atlas as ReturnType<typeof fakeAtlas>) ?? fakeAtlas()+ const cols = o.cols ?? cells.length+ const out = new Uint32Array(cols * CELL_STRIDE)+ packViewportRow(out, (col) => cells[col], makeCell(), {+ cols,+ atlas,+ theme: THEME,+ selection: o.selection ?? null,+ cursorCol: o.cursorCol ?? -1+ })+ return { out, atlas }+}++const halve = (c: number): number =>+ packColor((c & 0xff) >>> 1, ((c >>> 8) & 0xff) >>> 1, ((c >>> 16) & 0xff) >>> 1, (c >>> 24) & 0xff)++describe('packViewportRow — colors', () => {+ it('default fg/bg resolve to the theme lanes and the glyph comes from the atlas', () => {+ const { out, atlas } = pack([makeCell({ code: 0x41 })])+ expect(readCell(out, 0)).toEqual({ glyph: 901, fg: THEME.fg, bg: THEME.bg, flags: 0 })+ expect(atlas.calls).toEqual([[0x41, false, false]])+ })++ it('palette fg/bg index into theme.ansi', () => {+ const { out } = pack([makeCell({ fg: ['palette', 2], bg: ['palette', 250] })])+ const c = readCell(out, 0)+ expect(c.fg).toBe(THEME.ansi[2])+ expect(c.bg).toBe(THEME.ansi[250])+ })++ it('an out-of-range palette index falls back to the theme default rather than undefined', () => {+ const { out } = pack([makeCell({ fg: ['palette', 999], bg: ['palette', -1] })])+ const c = readCell(out, 0)+ expect(c.fg).toBe(THEME.fg)+ expect(c.bg).toBe(THEME.bg)+ })++ it('RGB colors pack 0xRRGGBB into opaque lanes', () => {+ const { out } = pack([makeCell({ fg: ['rgb', 0xaabbcc], bg: ['rgb', 0x123456] })])+ const c = readCell(out, 0)+ expect(c.fg).toBe(packColor(0xaa, 0xbb, 0xcc, 0xff))+ expect(c.bg).toBe(packColor(0x12, 0x34, 0x56, 0xff))+ })++ it('inverse swaps the RESOLVED pair (palette fg on default bg)', () => {+ const { out } = pack([makeCell({ fg: ['palette', 2], inverse: true })])+ const c = readCell(out, 0)+ expect(c.fg).toBe(THEME.bg)+ expect(c.bg).toBe(THEME.ansi[2])+ })++ it('dim halves the fg RGB channels and keeps alpha', () => {+ const { out } = pack([makeCell({ fg: ['rgb', 0xff0f01], dim: true })])+ expect(readCell(out, 0).fg).toBe(packColor(0x7f, 0x07, 0x00, 0xff))+ })++ it('dim applies AFTER inverse — it halves the swapped foreground, not the original', () => {+ const { out } = pack([makeCell({ fg: ['palette', 2], dim: true, inverse: true })])+ const c = readCell(out, 0)+ expect(c.fg).toBe(halve(THEME.bg)) // the bg that inverse moved into the fg slot+ expect(c.bg).toBe(THEME.ansi[2]) // background is never dimmed+ })+})++describe('packViewportRow — attributes', () => {+ it('bold picks the bold glyph variant and sets FLAG_BOLD (no bright-color promotion in v1)', () => {+ const { out, atlas } = pack([makeCell({ code: 0x42, bold: true, fg: ['palette', 1] })])+ expect(atlas.calls).toEqual([[0x42, true, false]])+ const c = readCell(out, 0)+ expect(c.flags).toBe(FLAG_BOLD)+ expect(c.fg).toBe(THEME.ansi[1]) // NOT promoted to ansi[9]+ })++ it('italic and underline set their flags; italic reaches the atlas key', () => {+ const { out, atlas } = pack([makeCell({ code: 0x43, italic: true, underline: true })])+ expect(atlas.calls).toEqual([[0x43, false, true]])+ expect(readCell(out, 0).flags).toBe(FLAG_ITALIC | FLAG_UNDERLINE)+ })+})++describe('packViewportRow — wide and zero-width cells', () => {+ it('a wide char paints its glyph in the lead cell and a blank, bg-continuous continuation', () => {+ const wide = makeCell({ code: 0x4e2d, width: 2, bg: ['rgb', 0x223344] })+ const cont = makeCell({ code: 0, width: 0, bg: ['rgb', 0x223344] })+ const { out, atlas } = pack([wide, cont])+ const lead = readCell(out, 0)+ const tail = readCell(out, 1)+ expect(lead.glyph).toBe(901)+ expect(lead.flags & FLAG_WIDE).toBe(FLAG_WIDE)+ expect(tail.glyph).toBe(0) // blank slot — the lead's ink covers both columns+ expect(tail.bg).toBe(lead.bg) // unbroken background run under the glyph+ expect(tail.fg).toBe(lead.fg)+ expect(atlas.calls).toEqual([[0x4e2d, false, false]]) // the continuation asks for no glyph+ })++ it('a zero-width cell with no wide lead before it still writes a blank cell (never stale)', () => {+ // The row buffer is reused across frames, so "write nothing" would leave the PREVIOUS+ // frame's lanes at that column. Every column is always written.+ const out = new Uint32Array(1 * CELL_STRIDE)+ out.fill(0xdeadbeef)+ packViewportRow(out, () => makeCell({ code: 0x300, width: 0, bg: ['rgb', 0x010203] }), makeCell(), {+ cols: 1,+ atlas: fakeAtlas(),+ theme: THEME,+ selection: null,+ cursorCol: -1+ })+ const c = readCell(out, 0)+ expect(c.glyph).toBe(0)+ expect(c.bg).toBe(packColor(0x01, 0x02, 0x03, 0xff))+ })++ it('a wide lead in the last column does not write past the row', () => {+ const out = new Uint32Array(1 * CELL_STRIDE)+ packViewportRow(out, () => makeCell({ code: 0x4e2d, width: 2 }), makeCell(), {+ cols: 1,+ atlas: fakeAtlas(),+ theme: THEME,+ selection: null,+ cursorCol: -1+ })+ expect(out.length).toBe(CELL_STRIDE)+ expect(readCell(out, 0).glyph).toBe(901)+ })+})++describe('packViewportRow — code point validation', () => {+ // Guards the rasterizer's String.fromCodePoint: a lone surrogate or an out-of-range code point+ // THROWS there, taking the whole frame down. The atlas must never see one.+ const invalid: Array<[string, number]> = [+ ['NUL', 0],+ ['a control char', 0x1f],+ ['a low surrogate boundary', 0xd800],+ ['a high surrogate boundary', 0xdfff],+ ['past the Unicode range', 0x110000],+ ['a negative code', -1],+ ['a non-integer code', 1.5],+ ['NaN', Number.NaN]+ ]+ for (const [label, code] of invalid) {+ it(`maps ${label} to the blank slot without calling the atlas`, () => {+ const { out, atlas } = pack([makeCell({ code })])+ expect(readCell(out, 0).glyph).toBe(0)+ expect(atlas.calls).toEqual([])+ })+ }++ it('a space is blank without a lookup, and the first printable code is rasterized', () => {+ const { out, atlas } = pack([makeCell({ code: 0x20 }), makeCell({ code: 0x21 })])+ expect(readCell(out, 0).glyph).toBe(0)+ expect(readCell(out, 1).glyph).toBe(901)+ expect(atlas.calls).toEqual([[0x21, false, false]])+ })+})++describe('packViewportRow — cursor and selection', () => {+ it('the cursor cell paints cursorBg/cursorFg and sets FLAG_CURSOR', () => {+ const { out } = pack([makeCell(), makeCell({ fg: ['palette', 3] })], { cursorCol: 1 })+ expect(readCell(out, 0).flags).toBe(0)+ const c = readCell(out, 1)+ expect(c.fg).toBe(THEME.cursorFg)+ expect(c.bg).toBe(THEME.cursorBg)+ expect(c.flags).toBe(FLAG_CURSOR)+ })++ it('a selection span [start, endExcl) repaints only its bg, leaving fg resolved', () => {+ const cells = [0, 1, 2, 3].map(() => makeCell({ fg: ['palette', 4] }))+ const { out } = pack(cells, { selection: [1, 3] })+ expect(readCell(out, 0).bg).toBe(THEME.bg)+ for (const col of [1, 2]) {+ const c = readCell(out, col)+ expect(c.bg).toBe(THEME.selectionBg)+ expect(c.fg).toBe(THEME.ansi[4]) // fg is untouched by selection+ expect(c.flags).toBe(FLAG_SELECTED)+ }+ expect(readCell(out, 3).bg).toBe(THEME.bg) // end is EXCLUSIVE+ expect(readCell(out, 3).flags).toBe(0)+ })++ it('cursor wins over selection on overlap; both state flags stay set', () => {+ const { out } = pack([makeCell(), makeCell(), makeCell()], { selection: [0, 3], cursorCol: 1 })+ const c = readCell(out, 1)+ expect(c.bg).toBe(THEME.cursorBg)+ expect(c.fg).toBe(THEME.cursorFg)+ expect(c.flags).toBe(FLAG_SELECTED | FLAG_CURSOR)+ expect(readCell(out, 0).bg).toBe(THEME.selectionBg)+ })++ it('a null selection and cursorCol -1 paint nothing', () => {+ const { out } = pack([makeCell()], { selection: null, cursorCol: -1 })+ expect(readCell(out, 0).flags).toBe(0)+ })+})++describe('packViewportRow — missing cells and buffer reuse', () => {+ it('a column past the end of the line becomes a blank cell on the theme background', () => {+ const { out } = pack([makeCell(), undefined], { cols: 2 })+ expect(readCell(out, 1)).toEqual({ glyph: 0, fg: THEME.fg, bg: THEME.bg, flags: 0 })+ })++ it('the cursor still paints on a column past the end of the line', () => {+ // The most common cursor position of all: one past the last typed character.+ const { out } = pack([makeCell(), undefined], { cols: 2, cursorCol: 1 })+ const c = readCell(out, 1)+ expect(c.bg).toBe(THEME.cursorBg)+ expect(c.flags).toBe(FLAG_CURSOR)+ })++ it('every column of a reused row buffer is overwritten — no stale lanes survive', () => {+ const out = new Uint32Array(3 * CELL_STRIDE)+ out.fill(0xdeadbeef)+ packViewportRow(out, (col) => (col === 1 ? undefined : makeCell({ code: 0x20 })), makeCell(), {+ cols: 3,+ atlas: fakeAtlas(),+ theme: THEME,+ selection: null,+ cursorCol: -1+ })+ for (let col = 0; col < 3; col++) {+ expect(readCell(out, col)).toEqual({ glyph: 0, fg: THEME.fg, bg: THEME.bg, flags: 0 })+ }+ })++ it('hands the caller-owned work cell to readCell so the shell can fill it in place', () => {+ const work = makeCell({ code: 0x5a })+ const seen: Array<CellView | undefined> = []+ const out = new Uint32Array(2 * CELL_STRIDE)+ packViewportRow(+ out,+ (_col, into) => {+ seen.push(into)+ return into+ },+ work,+ { cols: 2, atlas: fakeAtlas(), theme: THEME, selection: null, cursorCol: -1 }+ )+ expect(seen).toEqual([work, work])+ expect(readCell(out, 0).glyph).toBe(901)+ })+})diff --git a/src/renderer/glyphgrid/feed.ts b/src/renderer/glyphgrid/feed.tsnew file mode 100644index 000000000..28a664606--- /dev/null+++ b/src/renderer/glyphgrid/feed.ts@@ -0,0 +1,222 @@+/** The color/glyph brain of the xterm integration: buffer cells in, engine lanes out.+ *+ * This module imports NOTHING from xterm — everything arrives through `CellView` (a narrow view+ * of `IBufferCell`) and `ThemeLanes` (a snapshot of the theme already packed into the engine's+ * color space). That is what keeps it pure, headless-testable and free of a dependency on+ * xterm's internals, which are the part of that library most likely to move under us. */++import type { GlyphAtlas } from './atlas'+import {+ FLAG_BOLD,+ FLAG_CURSOR,+ FLAG_ITALIC,+ FLAG_SELECTED,+ FLAG_UNDERLINE,+ FLAG_WIDE,+ packColor,+ writeCell+} from './cells'++/** Narrow view of one buffer cell — the subset of xterm's IBufferCell the feed reads. The shell+ * passes real cells; tests pass literals. */+export interface CellView {+ getCode(): number+ getWidth(): number+ isBold(): number+ isItalic(): number+ isUnderline(): number+ isInverse(): number+ isDim(): number+ isFgDefault(): boolean+ isFgPalette(): boolean+ isFgRGB(): boolean+ isBgDefault(): boolean+ isBgPalette(): boolean+ isBgRGB(): boolean+ getFgColor(): number // palette index | 0xRRGGBB when RGB+ getBgColor(): number+}++/** Snapshot of the theme in the engine's packed-color space (packColor lanes). Built once per+ * theme change by the shell from _themeService.colors: rgb = (color.rgba >> 8) & 0xffffff. */+export interface ThemeLanes {+ fg: number // packColor default foreground+ bg: number // packColor default background (opaque)+ ansi: number[] // 256 packed colors (16 base + 240 extended)+ cursorFg: number // glyph color when under the block cursor+ cursorBg: number+ selectionBg: number // opaque selection background+}++export interface RowFeedOpts {+ cols: number+ atlas: Pick<GlyphAtlas, 'glyphFor'>+ theme: ThemeLanes+ /** Selection span on THIS viewport row, in columns [startCol, endColExclusive), or null. */+ selection: readonly [number, number] | null+ /** Block-cursor column on THIS row, or -1. (Bar/underline cursors: Phase 2 — block only.) */+ cursorCol: number+}++const MAX_CODE_POINT = 0x10ffff++/** Whether a code point may reach the atlas — i.e. whether `String.fromCodePoint(code)` in the+ * rasterizer is safe AND worth a slot.+ *+ * This is a CRASH GUARD, not a nicety: `String.fromCodePoint` THROWS a RangeError on a negative,+ * non-integer, or out-of-range argument, and a lone surrogate (0xD800-0xDFFF) rasterizes to+ * garbage. A buffer cell can hold any of those after a malformed UTF-8 run, and the throw would+ * take down the whole frame — the Phase 0 review's Task-4 crash class.+ *+ * Everything at or below 0x20 is excluded too, for a different reason: control codes have no+ * printable form, and space (0x20) is the most common cell on the canvas — answering it here+ * saves a map lookup per blank cell (the atlas would return slot 0 for it anyway). */+function isRenderableCode(code: number): boolean {+ return (+ Number.isInteger(code) &&+ code > 0x20 &&+ code <= MAX_CODE_POINT &&+ !(code >= 0xd800 && code <= 0xdfff)+ )+}++/** 0xRRGGBB (xterm's RGB encoding) → an opaque packed lane. */+function rgbLane(v: number): number {+ return packColor((v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, 0xff)+}++/** A palette index outside the theme's 256 entries falls back to the default rather than writing+ * `undefined` (which a Uint32Array silently stores as 0 = transparent black). */+function paletteLane(theme: ThemeLanes, index: number, fallback: number): number {+ const c = theme.ansi[index]+ return typeof c === 'number' ? c : fallback+}++/** DIM halves the RGB channels and keeps alpha. NOTE: xterm's own renderers dim by drawing the+ * foreground at 50% OPACITY (blending toward the background); halving the channels blends toward+ * black instead. The two agree on a dark background and differ on a light one — matching xterm's+ * blend is Phase 2 work, and needs the resolved bg, so it belongs here when it lands. */+function dimLane(c: number): number {+ return packColor(+ (c & 0xff) >>> 1,+ ((c >>> 8) & 0xff) >>> 1,+ ((c >>> 16) & 0xff) >>> 1,+ (c >>> 24) & 0xff+ )+}++function resolveFg(cell: CellView, theme: ThemeLanes): number {+ if (cell.isFgPalette()) return paletteLane(theme, cell.getFgColor(), theme.fg)+ if (cell.isFgRGB()) return rgbLane(cell.getFgColor())+ return theme.fg // isFgDefault, and anything unclassifiable+}++function resolveBg(cell: CellView, theme: ThemeLanes): number {+ if (cell.isBgPalette()) return paletteLane(theme, cell.getBgColor(), theme.bg)+ if (cell.isBgRGB()) return rgbLane(cell.getBgColor())+ return theme.bg+}++/** Pack one viewport row into engine lanes. PURE. Row buffer is caller-provided and reused.+ *+ * ORDER OF RESOLUTION (each step depends on the previous one — do not reorder):+ * 1. resolve fg and bg independently (default / palette / RGB),+ * 2. INVERSE swaps the RESOLVED pair — so "inverse on a palette fg" moves that palette color+ * into the background, which is what makes inverse composable with any color mode,+ * 3. DIM halves the foreground that step 2 left in place (never the background).+ * This matches xterm's own renderers, which swap during resolution and apply dim to whatever+ * foreground came out of it.+ *+ * BOLD selects the bold glyph variant only — no bright-color promotion, matching modern xterm's+ * default `drawBoldTextInBrightColors: false`. Making that an option is Phase 2 work.+ *+ * WIDE / ZERO-WIDTH cells are one mechanism seen from two sides. A double-width glyph occupies+ * two buffer cells: the lead reports width 2, and the cell right after it reports width 0. The+ * lead carries the glyph (plus FLAG_WIDE); the follower is written as a BLANK cell carrying the+ * LEAD's colors, so the background under a wide glyph — a selection, the cursor, a colored+ * block — is one unbroken run instead of two halves that can disagree. The follower is never+ * skipped: this row buffer is REUSED across frames, so "write nothing" would leave the previous+ * frame's lanes standing at that column. Every column in [0, cols) is always written.+ *+ * CURSOR and SELECTION are applied last, over whatever the cell resolved to. Selection repaints+ * only the background (the foreground must stay readable as itself); the cursor repaints both.+ * On overlap the CURSOR WINS the colors, and BOTH flags stay set — the flags describe the cell's+ * state (this cell is selected AND under the cursor), only the paint has to pick a winner. */+export function packViewportRow(+ out: Uint32Array,+ readCell: (col: number, into: CellView) => CellView | undefined,+ workCell: CellView,+ opts: RowFeedOpts+): void {+ const { cols, atlas, theme, selection, cursorCol } = opts+ const selStart = selection ? selection[0] : -1+ const selEnd = selection ? selection[1] : -1++ // Colors carried from a wide lead into its zero-width follower (see the doc comment).+ let carryPending = false+ let carryFg = 0+ let carryBg = 0++ for (let col = 0; col < cols; col++) {+ const cell = readCell(col, workCell)+ let glyph = 0+ let fg = theme.fg+ let bg = theme.bg+ let flags = 0++ if (cell) {+ fg = resolveFg(cell, theme)+ bg = resolveBg(cell, theme)+ if (cell.isInverse()) {+ const swap = fg+ fg = bg+ bg = swap+ }+ if (cell.isDim()) fg = dimLane(fg)++ const width = cell.getWidth()+ if (width === 0) {+ // Second half of the preceding wide glyph: no glyph of its own, and the lead's colors+ // when we have them (a stray width-0 cell with no lead keeps its own — still never+ // stale). Glyph-styling flags mean nothing on a blank; underline continuity across a+ // wide glyph is Phase 2, since nothing renders underline yet.+ if (carryPending) {+ fg = carryFg+ bg = carryBg+ }+ carryPending = false+ } else {+ const bold = cell.isBold() !== 0+ const italic = cell.isItalic() !== 0+ const code = cell.getCode()+ if (isRenderableCode(code)) glyph = atlas.glyphFor(code, bold, italic)+ if (bold) flags |= FLAG_BOLD+ if (italic) flags |= FLAG_ITALIC+ if (cell.isUnderline() !== 0) flags |= FLAG_UNDERLINE+ if (width === 2) {+ flags |= FLAG_WIDE+ carryPending = true+ carryFg = fg+ carryBg = bg+ } else {+ carryPending = false+ }+ }+ } else {+ // Past the end of a short line (or no line at all): a blank cell on the theme background.+ carryPending = false+ }++ if (col >= selStart && col < selEnd) {+ bg = theme.selectionBg+ flags |= FLAG_SELECTED+ }+ if (col === cursorCol) {+ fg = theme.cursorFg+ bg = theme.cursorBg+ flags |= FLAG_CURSOR+ }++ writeCell(out, col, glyph, fg, bg, flags)+ }+}