From 4231e6455467862a1badea4990997501195a6457 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 21:49:09 -0500 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20img=20element=20=E2=80=94=20public?= =?UTF-8?q?=20surface,=20validation,=20and=20test=20suite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit img() packs the void OP_IMG directive; term.setImage()/removeImage() manage the pixel-surface registry; validate() accepts img ops; the Graphics Specification's suite lands in test/graphics.test.ts. - removeImage() returns void like update(): the next render emits the data-freeing deletion first, once, and only when data was sent. - kitty-graphics capability changes reach the renderer from update(); denial and resize cleanup is asserted on the next render's output. - bg takes the full color value space; symbolic words travel with an IMG_BG_SYMBOLIC flag and resolve against the inherited color. - New coverage: queued deletions inside the BSU/ESU pair (including a deletions-only frame), color-tier redraws re-placing without re-transmission, img replay re-resolving its tier, CSS color bg. - The suite's helper opts into truecolor so art colors assert exactly; the 256-color baseline downmaps them per the color-encoding tier. --- .changeset/img-element.md | 15 ++ ops.ts | 92 ++++++- term.ts | 108 +++++++- test/graphics.test.ts | 529 ++++++++++++++++++++++++++++++++++++++ validate.ts | 31 ++- 5 files changed, 766 insertions(+), 9 deletions(-) create mode 100644 .changeset/img-element.md create mode 100644 test/graphics.test.ts diff --git a/.changeset/img-element.md b/.changeset/img-element.md new file mode 100644 index 00000000..039a1225 --- /dev/null +++ b/.changeset/img-element.md @@ -0,0 +1,15 @@ +--- +"@bomb.sh/tty": minor +--- + +Adds the `img()` directive — declarative images rendered through a fidelity ladder: kitty graphics protocol pixels, shape-aware ASCII character art, or alt text, resolved from capability evidence (`RuntimeCapabilities.kittyGraphics`). + +Surfaces are caller-owned decoded RGBA buffers managed by the Term: + +```ts +term.setImage(1, { width: 128, height: 64, pixels: rgba8 }); +term.render([img("cover", { image: 1, alt: "cover art" })]); +term.removeImage(1); // the next render deletes it from the terminal +``` + +`createTerm` takes an `imagePoolBytes` option (default 4 MiB) sizing the fixed pixel pool. Transmission is lazy; re-transmission only on data change; steady-state renders are byte-silent. Like `update()`, `removeImage()` returns nothing: cleanup after removal, capability denial, or resize is emitted at the start of the next render. `bg` accepts any color value `open({ bg })` does. Line mode caps the ladder at ascii. Errors surface as `IMAGE_NOT_FOUND`, `IMAGE_PLACEMENTS_EXCEEDED`, and `IMAGE_PLACEMENT_COLLISION`. diff --git a/ops.ts b/ops.ts index fd80deaf..2970bf2e 100644 --- a/ops.ts +++ b/ops.ts @@ -31,6 +31,12 @@ const OP_OPEN_ELEMENT = 0x02; const OP_TEXT = 0x03; const OP_CLOSE_ELEMENT = 0x04; const OP_REPLAY = 0x05; +/* the void image directive (Graphics Specification §7.1) */ +const OP_IMG = 0x06; + +/* OP_IMG config word flags, above the variant byte */ +const IMG_BG = 0x100; +const IMG_BG_SYMBOLIC = 0x200; /* Property group masks for OPEN_ELEMENT */ const PROP_LAYOUT = 0x01; @@ -346,6 +352,38 @@ export function pack( break; } + case OP_IMG: { + view.setUint32(o, OP_IMG, true); + o += 4; + + o = packString(view, bytes, op.id, o, end, "element id"); + + // image registry id; 0 = omitted (alt-only element) + view.setUint32(o, op.image ?? 0, true); + o += 4; + + let bg = op.bg === undefined ? undefined : colorWord(op.bg); + view.setUint32( + o, + IMG_VARIANT_CODE[op.variant ?? "auto"] | + (bg !== undefined ? IMG_BG : 0) | + (bg?.symbolic ? IMG_BG_SYMBOLIC : 0), + true, + ); + o += 4; + + o = packAxis(view, o, op.width ?? fit()); + o = packAxis(view, o, op.height ?? fit()); + + o = packString(view, bytes, op.alt, o, end, "alt text"); + + if (bg !== undefined) { + view.setUint32(o, bg.word, true); + o += 4; + } + break; + } + case OP_REPLAY: { view.setUint32(o, OP_REPLAY, true); view.setUint32(o + 4, op.offset, true); @@ -610,7 +648,43 @@ interface Replay { length: number; } -export type Op = OpenElement | Text | CloseElement | Replay; +export type ImgVariant = "auto" | "kitty" | "ascii" | "alt"; + +export interface ImgProps { + /** Registry id of the image to render. Omit for an alt-only element. */ + image?: number; + /** Required. Text fallback and description. "" = decorative. */ + alt: string; + width?: SizingAxis; + height?: SizingAxis; + /** Tier override; evidence-gated — falls through the auto ladder when the + * tier's evidence is missing (Graphics Specification §9.1). */ + variant?: ImgVariant; + /** Element background: a color value as for open({ bg }). */ + bg?: Color; +} + +/** The void image element: one self-closing directive, no children, not + * paired with close() (Graphics Specification §7.1). */ +export interface Img { + directive: typeof OP_IMG; + id: string; + image?: number; + alt: string; + width?: SizingAxis; + height?: SizingAxis; + variant?: ImgVariant; + bg?: Color; +} + +const IMG_VARIANT_CODE: Record = { + auto: 0, + kitty: 1, + ascii: 2, + alt: 3, +}; + +export type Op = OpenElement | Text | CloseElement | Replay | Img; /* * Compile-time color checking (§8.5). A string literal assigned to a color @@ -710,6 +784,22 @@ export function text< return { directive: OP_TEXT, content, ...props }; } +export function img

( + id: string, + props: P & NoInfer>, +): Img { + return { + directive: OP_IMG, + id, + image: props.image, + alt: props.alt, + width: props.width ?? fit(), + height: props.height ?? fit(), + variant: props.variant ?? "auto", + bg: props.bg, + }; +} + export function close(): CloseElement { return { directive: OP_CLOSE_ELEMENT }; } diff --git a/term.ts b/term.ts index 9d7cd89e..91463b26 100644 --- a/term.ts +++ b/term.ts @@ -20,6 +20,21 @@ export interface TermOptions { * baseline. */ terminfo?: TerminalInfo; + /** + * Sizes the Term's carved image pixel pool (Graphics Specification §5.3). + * Default 4 MiB. The registry never grows at runtime (INV-I8). + */ + imagePoolBytes?: number; +} + +/** + * Decoded raster pixels for the image registry (Graphics Specification + * §7.2): straight (non-premultiplied) RGBA8, top-to-bottom rows. + */ +export interface ImageData { + width: number; // positive integer + height: number; // positive integer + pixels: Uint8Array; // exactly width * height * 4 bytes } /** @@ -131,6 +146,9 @@ const ERROR_TYPES = [ "UNBALANCED_OPEN_CLOSE", "CLIP_DEPTH_EXCEEDED", "COMBINING_MARKS_EXCEEDED", + "IMAGE_NOT_FOUND", + "IMAGE_PLACEMENTS_EXCEEDED", + "IMAGE_PLACEMENT_COLLISION", ] as const; export interface ClayError { @@ -165,12 +183,40 @@ export interface Term { */ update(events: readonly InputEvent[]): void; + /** + * Put a decoded image into the Term's pixel-surface registry (Graphics + * Specification §7.2). Emits nothing: transmission is lazy, on the first + * render that places the image. Throws RangeError on validation failure or + * pool/registry exhaustion. Re-setting a live id replaces the image. + */ + setImage(id: number, data: ImageData): void; + + /** + * Remove a registry image. Emits nothing: the next render deletes its + * terminal-side data and repaints the cells it covered (§5.7). Idempotent. + */ + removeImage(id: number): void; + /** Frozen snapshot of the current merged capability state. */ readonly capabilities: RuntimeCapabilities; } +const IMAGE_ERROR_MESSAGES: Record = { + [-1]: "registry id outside [1, 4294967295]", + [-2]: "width and height must be positive integers", + [-4]: "image registry table full", + [-5]: "image pixel pool exhausted (raise the imagePoolBytes option)", + [-6]: "unknown registry id", +}; + +function imageRangeError(n: number): RangeError { + return new RangeError( + `setImage failed: ${IMAGE_ERROR_MESSAGES[n] ?? `native error ${n}`}`, + ); +} + export async function createTerm(options: TermOptions): Promise { - let { width, height, terminfo } = options; + let { width, height, terminfo, imagePoolBytes } = options; let currentCaps: RuntimeCapabilities = runtimeFromStatic( terminfo?.capabilities ?? { @@ -186,12 +232,17 @@ export async function createTerm(options: TermOptions): Promise { }, ); - let native = await createTermNative(width, height, { - syncOutput: currentCaps.syncOutput, - pointerShape: currentCaps.pointerShape, - colors: currentCaps.colors, - trueColor: currentCaps.trueColor, - }); + let native = await createTermNative( + width, + height, + { + syncOutput: currentCaps.syncOutput, + pointerShape: currentCaps.pointerShape, + colors: currentCaps.colors, + trueColor: currentCaps.trueColor, + }, + imagePoolBytes, + ); let { memory } = native; let prev = new Set(); @@ -308,6 +359,43 @@ export async function createTerm(options: TermOptions): Promise { return { output, events, info, errors, animating }; }, + setImage(id: number, data: ImageData): void { + if (!Number.isInteger(id) || id < 1 || id > 4294967295) { + throw new RangeError(`invalid image registry id ${id}`); + } + if ( + !Number.isInteger(data.width) || data.width < 1 || + !Number.isInteger(data.height) || data.height < 1 + ) { + throw new RangeError( + `invalid image dimensions ${data.width}x${data.height}`, + ); + } + if (data.pixels.length !== data.width * data.height * 4) { + throw new RangeError( + `image pixels length ${data.pixels.length} !== ${data.width} * ${data.height} * 4`, + ); + } + let addr = native.imageBegin( + native.statePtr, + id, + data.width, + data.height, + ); + if (addr < 0) { + throw imageRangeError(addr); + } + new Uint8Array(memory.buffer).set(data.pixels, addr); + let committed = native.imageCommit(native.statePtr, id); + if (committed < 0) { + throw imageRangeError(committed); + } + }, + + removeImage(id: number): void { + native.imageRemove(native.statePtr, id); + }, + update(events: readonly InputEvent[]): void { for (let c of events) { let next = applyUpdate(currentCaps, c); @@ -347,6 +435,12 @@ export async function createTerm(options: TermOptions): Promise { trueColor: next.trueColor, }); } + if (next.kittyGraphics !== currentCaps.kittyGraphics) { + native.graphicsCapability( + native.statePtr, + next.kittyGraphics ? 1 : 0, + ); + } if ( next.theme.foreground !== currentCaps.theme.foreground || next.theme.background !== currentCaps.theme.background diff --git a/test/graphics.test.ts b/test/graphics.test.ts new file mode 100644 index 00000000..68e510e4 --- /dev/null +++ b/test/graphics.test.ts @@ -0,0 +1,529 @@ +/* test/graphics.test.ts — the Graphics Specification's test suite (§14). + * One spec, one test file. */ + +import { createInput } from "../input.ts"; +import { close, img, type Op, open, type SizingAxis } from "../ops.ts"; +import { createTerm } from "../term.ts"; +import { describe, it } from "./suite.ts"; +import { print } from "./print.ts"; + +const KITTY_GRANT = { + type: "capability", + key: "kitty-graphics", + value: true, +} as const; +const KITTY_DENY = { + type: "capability", + key: "kitty-graphics", + value: false, +} as const; + +/** Solid-color W×H RGBA image. */ +function solid(w: number, h: number, rgb: [number, number, number]): { + width: number; + height: number; + pixels: Uint8Array; +} { + let pixels = new Uint8Array(w * h * 4); + for (let i = 0; i < pixels.length; i += 4) { + pixels[i] = rgb[0]; + pixels[i + 1] = rgb[1]; + pixels[i + 2] = rgb[2]; + pixels[i + 3] = 255; + } + return { width: w, height: h, pixels }; +} + +const TRUECOLOR = { + type: "capability", + key: "colordepth", + value: "truecolor", +} as const; + +/** A truecolor Term, so art colors assert as exact 24-bit SGR. */ +async function term(w = 40, h = 12) { + let t = await createTerm({ width: w, height: h }); + t.update([TRUECOLOR]); + return t; +} + +/** Render a frame and return the output as a string. */ +function frame(t: Awaited>, ops: Op[]): string { + return new TextDecoder().decode(t.render(ops).output); +} + +function grid(t: Awaited>, ops: Op[]): string[] { + let text = print(frame(t, ops), 40, 12); + return text.split("\n"); +} + +describe("graphics: tier resolution", () => { + it("renders ascii art without evidence (auto ladder)", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (out.includes("\x1b_G")) throw new Error("kitty bytes without evidence"); + if (!out.includes("\x1b[38;2;255;0;0m")) throw new Error("no art color"); + }); + + it("kitty tier after the capability grant", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (!out.includes("\x1b_Ga=t,t=d,f=32,i=1,s=8,v=8,")) { + throw new Error("no transmission block"); + } + if (!out.includes("\x1b_Ga=p,i=1,p=")) throw new Error("no placement"); + if (!out.includes("q=2")) throw new Error("not quiet"); + }); + + it("variant override: alt force, kitty fall-through, ascii direct", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + let alt = frame(t, [img("a", { image: 1, alt: "hart", variant: "alt" })]); + if (alt.includes("\x1b_G") || !alt.includes("hart")) { + throw new Error("variant alt not honored"); + } + let kitty = frame(t, [ + img("a", { image: 1, alt: "x", variant: "kitty" }), + ]); + if (kitty.includes("\x1b_G")) { + throw new Error("variant kitty ignored missing evidence"); + } + // fresh color: the identical art frame would diff to silence + t.setImage(2, solid(8, 8, [0, 255, 0])); + let ascii = frame(t, [ + img("a", { image: 2, alt: "x", variant: "ascii" }), + ]); + if (ascii.includes("\x1b_G") || !ascii.includes("\x1b[38;2;0;255;0m")) { + throw new Error("variant ascii not honored"); + } + }); + + it("image omitted renders alt-only without error", async () => { + let t = await term(); + let out = frame(t, [img("a", { alt: "chart: revenue" })]); + if (!out.includes("chart: revenue")) throw new Error("alt not rendered"); + let errs = t.render([img("a", { alt: "chart: revenue" })]).errors; + if (errs.length !== 0) throw new Error("unexpected error"); + }); + + it("missing registry id renders alt tier + IMAGE_NOT_FOUND", async () => { + let t = await term(); + let r = t.render([img("a", { image: 99, alt: "fallback" })]); + if (!new TextDecoder().decode(r.output).includes("fallback")) { + throw new Error("no alt fallback"); + } + let found = r.errors.some((e) => e.type === "IMAGE_NOT_FOUND"); + if (!found) throw new Error("IMAGE_NOT_FOUND not surfaced"); + }); + + it("line mode caps the ladder at ascii", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + let out = new TextDecoder().decode( + t.render([img("a", { image: 1, alt: "x" })], { mode: "line" }).output, + ); + if (out.includes("\x1b_G")) throw new Error("APC bytes in line mode"); + }); +}); + +describe("graphics: kitty conformance", () => { + it("steady state is byte-silent", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (out.includes("\x1b_G")) throw new Error("re-emitted graphics bytes"); + }); + + it("chunks large payloads m=1/m=0 at 4096 base64 chars", async () => { + let t = await term(); + t.setImage(1, solid(40, 40, [0, 255, 0])); // 6400 bytes → 3 chunks + t.update([KITTY_GRANT]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + let blocks = out.split("\x1b_G").length - 1; + if (blocks !== 4) { + throw new Error(`expected tx 3 chunks + 1 placement, got ${blocks}`); + } + let m1 = out.match(/m=1/g)?.length ?? 0; + let m0 = out.match(/m=0/g)?.length ?? 0; + if (m1 !== 2 || m0 !== 1) throw new Error(`m flags ${m1}/${m0}`); + let first = out.indexOf("a=t,t=d,f=32,i=1,s=40,v=40"); + if (first < 0) throw new Error("tx header missing"); + }); + + it("replace re-transmits with delete-before-transmit, re-places", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + t.setImage(1, solid(8, 8, [0, 0, 255])); // version bump + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + let dIdx = out.indexOf("\x1b_Ga=d,d=I,i=1"); + let txIdx = out.indexOf("\x1b_Ga=t,t=d,f=32,i=1"); + let pIdx = out.indexOf("\x1b_Ga=p,i=1,p="); + if (dIdx < 0 || txIdx < 0 || pIdx < 0) { + throw new Error("replace cycle incomplete"); + } + if (!(dIdx < txIdx && txIdx < pIdx)) { + throw new Error("ordering: delete, transmit, place"); + } + }); + + it("move re-places with the same placement id, no delete/re-transmit", async () => { + let t = await term(40, 12); + t.setImage(1, solid(4, 4, [255, 0, 0])); + t.update([KITTY_GRANT]); + let one = frame(t, [img("a", { image: 1, alt: "x" })]); + let pid = one.match(/a=p,i=1,p=(\d+)/)?.[1]; + if (!pid) throw new Error("no pid"); + frame(t, [img("a", { image: 1, alt: "x" })]); // steady: silent + // move: the same directive inside a padded container shifts the + // element's box (Clay's root is the window, so an img-as-root cannot + // move: its footprint is window-derived) + let three = frame(t, [ + open("wrap", { layout: { padding: { left: 2, top: 2 } } }), + img("a", { image: 1, alt: "x" }), + close(), + ]); + if (!three.includes(`a=p,i=1,p=${pid},c=`)) { + throw new Error("move lost the placement id"); + } + if (three.includes("a=d,")) throw new Error("move emitted a deletion"); + if (three.includes("a=t,")) throw new Error("move re-transmitted"); + }); + + it("unmount deletes the scoped placement and repaints", async () => { + let t = await term(40, 12); + t.setImage(1, solid(4, 4, [255, 0, 0])); + t.update([KITTY_GRANT]); + let one = frame(t, [img("a", { image: 1, alt: "x" })]); + let pid = one.match(/a=p,i=1,p=(\d+)/)?.[1]; + let out = frame(t, []); // element gone + if (!out.includes(`a=d,d=i,i=1,p=${pid}`)) { + throw new Error("no scoped deletion on unmount"); + } + let g = print(out, 40, 12).split("\n"); + // the old footprint repaints as blank content (space), not graphics + if (g[0].slice(0, 4) !== " ") throw new Error("footprint not repainted"); + }); + + it("removeImage emits nothing; the next render deletes once", async () => { + let t = await term(); + t.setImage(1, solid(4, 4, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + t.removeImage(1); + t.removeImage(1); + let out = frame(t, []); + let deletes = out.split("\x1b_Ga=d,d=I,i=1,q=2\x1b\\").length - 1; + if (deletes !== 1) throw new Error(`${deletes} d=I blocks, expected 1`); + if (!out.startsWith("\x1b_Ga=d,d=I,i=1")) { + throw new Error("queued deletion is not first"); + } + if (frame(t, []).includes("\x1b_G")) throw new Error("queue not drained"); + }); + + it("removeImage of never-transmitted data enqueues nothing", async () => { + let t = await term(); + t.setImage(1, solid(4, 4, [255, 0, 0])); + frame(t, [img("a", { image: 1, alt: "x" })]); // ascii: no transmission + t.removeImage(1); + if (frame(t, []).includes("\x1b_G")) { + throw new Error("deleted data that was never sent"); + } + }); + + it("removal after denial deletes exactly once", async () => { + let t = await term(); + t.setImage(1, solid(4, 4, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + t.update([KITTY_DENY]); // denial queues the data-freeing deletion + t.removeImage(1); + let out = frame(t, []); + let deletes = out.split("a=d,d=I,i=1").length - 1; + if (deletes !== 1) throw new Error(`${deletes} d=I blocks, expected 1`); + }); +}); + +describe("graphics: capability invalidation", () => { + it("denial emits its deletions at the head of the next render", async () => { + let t = await term(); + t.setImage(1, solid(4, 4, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + t.update([KITTY_DENY]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (!out.startsWith("\x1b_Ga=d,d=I,i=1,q=2\x1b\\")) { + throw new Error("denial deletion is not first"); + } + if (out.includes("\x1b_Ga=p") || out.includes("\x1b_Ga=t")) { + throw new Error("kitty bytes after denial"); + } + }); + + it("grant then render emits kitty; denial render falls back to ascii", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + let kitty = frame(t, [img("a", { image: 1, alt: "x" })]); + if (!kitty.includes("\x1b_Ga=p")) throw new Error("grant not honored"); + t.update([KITTY_DENY]); + let ascii = frame(t, [img("a", { image: 1, alt: "x" })]); + if (!ascii.includes("\x1b[38;2;255;0;0m")) throw new Error("no ascii art"); + }); + + it("re-arming re-transmits (stored data is never trusted)", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + t.update([KITTY_DENY]); + t.update([KITTY_GRANT]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (!out.includes("\x1b_Ga=t,")) { + throw new Error("re-arm skipped re-transmission"); + } + }); + + it("a color-tier change re-places without re-transmitting", async () => { + let t = await createTerm({ width: 40, height: 12 }); // 256-color tier + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + t.update([TRUECOLOR]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (out.includes("\x1b_Ga=t,")) throw new Error("re-transmitted"); + if (!out.includes("\x1b_Ga=p,i=1,p=")) throw new Error("not re-placed"); + }); +}); + +describe("graphics: resize", () => { + it("next render deletes, redraws, re-transmits, and re-places", async () => { + let t = await term(40, 12); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + t.update([{ type: "resize", width: 30, height: 10 }]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (!out.startsWith("\x1b_Ga=d,d=I,i=1,q=2\x1b\\")) { + throw new Error("resize deletion is not first"); + } + if (!out.includes("\x1b_Ga=t,")) throw new Error("no re-transmission"); + if (!out.includes("\x1b_Ga=p,i=1,p=")) throw new Error("no re-place"); + }); +}); + +describe("graphics: synchronized output", () => { + let syncCaps = { + colors: 256, + trueColor: true, + bce: true, + autoMargin: true, + xenl: true, + altScreen: true, + styledUnderline: false, + syncOutput: true, + pointerShape: false, + }; + + it("graphics bytes sit inside the BSU/ESU pair", async () => { + let t = await createTerm({ + width: 40, + height: 12, + terminfo: { capabilities: syncCaps } as never, + }); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + if (!out.startsWith("\x1b[?2026h\x1b_G")) throw new Error("not wrapped"); + if (!out.endsWith("\x1b[?2026l")) throw new Error("no ESU"); + }); + + it("a frame of only queued deletions is wrapped, not a no-op", async () => { + let t = await createTerm({ + width: 40, + height: 12, + terminfo: { capabilities: syncCaps } as never, + }); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + frame(t, [img("a", { image: 1, alt: "x" })]); + // denial reconciles the covered cells to blank, so an empty frame has no + // cell changes and its only content is the queued deletion + t.update([KITTY_DENY]); + let out = frame(t, []); + if (out !== "\x1b[?2026h\x1b_Ga=d,d=I,i=1,q=2\x1b\\\x1b[?2026l") { + throw new Error(`unexpected frame ${JSON.stringify(out)}`); + } + }); +}); + +describe("graphics: replay", () => { + it("an img replay renders like the direct directive and re-resolves", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + let direct = [open("root", {}), img("a", { image: 1, alt: "x" }), close()]; + let first = t.render(direct); + let replay = first.info.get("a")!.replay; + + let fresh = await term(); + fresh.setImage(1, solid(8, 8, [255, 0, 0])); + fresh.render(direct); + t.update([KITTY_GRANT]); + fresh.update([KITTY_GRANT]); + let viaReplay = new TextDecoder().decode( + t.render([open("root", {}), replay, close()]).output, + ); + let viaDirect = frame(fresh, direct); + if (!viaReplay.includes("\x1b_Ga=p,i=1,p=")) { + throw new Error("replay reused the ascii resolution"); + } + if (viaReplay !== viaDirect) throw new Error("replay differs from direct"); + }); +}); + +describe("graphics: ascii art", () => { + it("solid red square paints uniform density glyphs in red", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + let g = grid(t, [img("a", { image: 1, alt: "x" })]); + for (let y = 0; y < 4; y++) { + if (g[y].slice(0, 8) !== "::::::::") { + throw new Error(`row ${y}: ${JSON.stringify(g[y].slice(0, 8))}`); + } + } + // intrinsic size under the half-row convention: 8 cols × ceil(8/2)=4 rows + for (let y = 4; y < 12; y++) { + if (g[y].slice(0, 8) !== " ") { + throw new Error(`row ${y} painted outside the footprint`); + } + } + }); + + it("luminance ordering: dark square paints lower-density glyphs", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [40, 40, 40])); + let dark = grid(t, [img("a", { image: 1, alt: "x" })])[0].slice(0, 8); + t.setImage(2, solid(8, 8, [220, 220, 220])); + let light = grid(t, [img("b", { image: 2, alt: "x" })])[0].slice(0, 8); + if (dark === light) throw new Error("luminance did not change density"); + }); + + it("determinism: identical inputs, identical art bytes", async () => { + let a = await term(); + let b = await term(); + a.setImage(1, solid(8, 8, [90, 140, 200])); + b.setImage(1, solid(8, 8, [90, 140, 200])); + if ( + frame(a, [img("a", { image: 1, alt: "x" })]) !== + frame(b, [img("a", { image: 1, alt: "x" })]) + ) { + throw new Error("nondeterministic art"); + } + }); + + it("alpha below the threshold is transparent and keeps the background", async () => { + let t = await term(); + // element bg declared; image fully transparent + let px = new Uint8Array(8 * 8 * 4); // alpha 0 everywhere + t.setImage(1, { width: 8, height: 8, pixels: px }); + let bg = 0xff102030; // rgba(): alpha 255 = opaque declared bg + let out = frame(t, [img("a", { image: 1, alt: "x", bg })]); + let g = print(out, 40, 12).split("\n"); + if (g[0].slice(0, 8) !== " ") throw new Error("not blank"); + // the bg is element-declared; the blank cell carries it — asserted via + // the raw output's bg SGR + if (!out.includes("\x1b[48;2;16;32;48m")) { + throw new Error("element bg missing under transparent art"); + } + }); +}); + +describe("graphics: background", () => { + it("bg takes a CSS color string like open({ bg })", async () => { + let t = await term(); + t.setImage(1, { width: 8, height: 8, pixels: new Uint8Array(8 * 8 * 4) }); + let out = frame(t, [img("a", { image: 1, alt: "x", bg: "#102030" })]); + if (!out.includes("\x1b[48;2;16;32;48m")) throw new Error("bg missing"); + }); +}); + +describe("graphics: alt tier", () => { + it("empty alt renders an empty box (decorative)", async () => { + let t = await term(); + let g = print(frame(t, [img("a", { alt: "" })]), 40, 12).split("\n"); + for (let y = 0; y < 12; y++) { + if (g[y].trim() !== "") throw new Error("decorative img painted"); + } + }); +}); + +describe("graphics: registry API", () => { + it("setImage validation throws RangeError", async () => { + let t = await term(); + let bad = [-1, 0, 4294967296, 1.5] as number[]; + for (let id of bad) { + let threw = false; + try { + t.setImage(id, solid(2, 2, [0, 0, 0])); + } catch (e) { + threw = e instanceof RangeError; + } + if (!threw) throw new Error(`id ${id} accepted`); + } + let threw = false; + try { + t.setImage(1, { width: 2, height: 2, pixels: new Uint8Array(3) }); + } catch (e) { + threw = e instanceof RangeError; + } + if (!threw) throw new Error("length mismatch accepted"); + }); + + it("input.scan() sees zero events from the APC frames alone", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + t.update([KITTY_GRANT]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + // INV-I5's claim is about the graphics frames themselves: fed to the + // input parser, an APC frame generates no responses of any kind + // deno-lint-ignore no-control-regex + let apc = out.match(/\x1b_G[^\x1b]*\x1b\\/g) ?? []; + if (apc.length === 0) throw new Error("no APC frames to test"); + let input = await createInput(); + let { events } = input.scan(new TextEncoder().encode(apc.join(""))); + if (events.length !== 0) { + throw new Error(`input parser saw ${events.length} events`); + } + }); +}); + +describe("graphics: validation", () => { + it("img ops pass validate()", async () => { + let { validate } = await import("../validate.ts"); + let sizing: SizingAxis = { type: "fixed", value: 8 }; + if ( + !validate([ + img("a", { image: 1, alt: "x" }), + img("b", { alt: "", width: sizing, height: sizing, variant: "ascii" }), + ]) + ) { + throw new Error("valid img ops rejected"); + } + if (validate([img("c", { image: 0, alt: "x" })])) { + throw new Error("registry id 0 accepted"); + } + if (validate([img("d", { image: 1, alt: undefined as never })])) { + throw new Error("missing alt accepted"); + } + if (validate([img("e", { alt: "x", variant: "sixel" as never })])) { + throw new Error("bad variant accepted"); + } + }); +}); diff --git a/validate.ts b/validate.ts index 8a2c97d0..f9443267 100644 --- a/validate.ts +++ b/validate.ts @@ -224,7 +224,30 @@ const Replay = Type.Object({ length: Type.Integer({ minimum: 4, maximum: 0xFFFFFFFF, multipleOf: 4 }), }); -const Ops = Type.Array(Type.Union([OpenElement, TextOp, CloseElement, Replay])); +/* The void image directive (Graphics Specification §7.1, §7.3): no + * children, not part of open/close balance. `image` is a pixel-surface + * registry id in the kitty protocol's positive-id range. */ +const ImgOp = Type.Object({ + directive: Type.Literal(0x06), + id: Type.String(), + image: Type.Optional(Type.Integer({ minimum: 1, maximum: 4294967295 })), + alt: Type.String(), + width: Type.Optional(SizingAxis), + height: Type.Optional(SizingAxis), + variant: Type.Optional( + Type.Union([ + Type.Literal("auto"), + Type.Literal("kitty"), + Type.Literal("ascii"), + Type.Literal("alt"), + ]), + ), + bg: Type.Optional(color), +}); + +const Ops = Type.Array( + Type.Union([OpenElement, TextOp, CloseElement, Replay, ImgOp]), +); /* ── Compiled validator ───────────────────────────────────────────── */ @@ -311,5 +334,11 @@ export function validated(term: Term): Term { update(events) { term.update(events); }, + setImage(id, data) { + term.setImage(id, data); + }, + removeImage(id) { + term.removeImage(id); + }, }; } From d5b3ddc4189b6be4a228276e89288820b5e14c42 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 22:09:02 -0500 Subject: [PATCH 2/4] test: large transmissions arrive whole within the output buffer --- test/graphics.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/test/graphics.test.ts b/test/graphics.test.ts index 68e510e4..a64c6360 100644 --- a/test/graphics.test.ts +++ b/test/graphics.test.ts @@ -303,6 +303,24 @@ describe("graphics: capability invalidation", () => { }); }); +describe("graphics: output capacity", () => { + it("a transmission larger than the text budget arrives whole", async () => { + let t = await term(40, 12); + let pixels = new Uint8Array(200 * 200 * 4).fill(255); + t.setImage(1, { width: 200, height: 200, pixels }); + t.update([KITTY_GRANT]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + // deno-lint-ignore no-control-regex + let chunks = [...out.matchAll(/\x1b_G[^;\x1b]*;([^\x1b]*)\x1b\\/g)]; + let b64 = chunks.map((m) => m[1]).join(""); + if (b64.length !== Math.ceil(pixels.length / 3) * 4) { + throw new Error(`transmitted ${b64.length} base64 bytes`); + } + if (!chunks.at(-1)![0].includes("m=0")) throw new Error("no final chunk"); + if (!out.includes("\x1b_Ga=p,i=1,p=")) throw new Error("no placement"); + }); +}); + describe("graphics: resize", () => { it("next render deletes, redraws, re-transmits, and re-places", async () => { let t = await term(40, 12); From 2581387be7ef093371083431422264fe62cad112 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 22:11:13 -0500 Subject: [PATCH 3/4] examples: img tier ladder demo Adapted from spike/img-demo onto the shipped surface: the unicode tier, debug quiet level, and byte-returning update()/removeImage() are gone. One generated image renders through auto, forced kitty, forced ascii, and alt panels; a status line counts each frame's transmissions, placements, and deletions so the queued cleanup after a denial or removal is visible on the next frame. Colors use CSS strings, and exit removes every image and flushes the deletions with a final render. --- examples/README.md | 26 ++++ examples/img/images.ts | 132 +++++++++++++++++ examples/img/index.ts | 330 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 488 insertions(+) create mode 100644 examples/img/images.ts create mode 100644 examples/img/index.ts diff --git a/examples/README.md b/examples/README.md index af4930cd..00bb9f33 100644 --- a/examples/README.md +++ b/examples/README.md @@ -59,6 +59,32 @@ What it shows: feature indicator (green ● supported, red ■ not) pinned to the right edge - a final frame on exit that restores the default pointer (§7.9 restore) +## Images + +Path: `examples/img/index.ts` + +Run it with: + +```sh +deno run examples/img/index.ts +# or +node examples/img/index.ts +``` + +What it shows: + +- one generated image (shaded sphere, alpha checker, or animated plasma) in four + panels: the auto tier ladder, kitty forced, ascii forced, and alt text + (graphics-spec §9) +- kitty graphics pixels in terminals that answer the graphics probe (kitty, + ghostty, WezTerm); shape-aware ascii art everywhere else +- a status line counting each frame's transmissions, placements, and deletions: + denying the capability (`k`) or removing an image (`x`) emits nothing until + the next frame, which opens with the queued deletions (§5.7) +- the plasma re-set through `setImage()` every tick, re-transmitting and + re-placing each revision +- a final frame on exit that deletes every image from the terminal + ## Keyboard Path: `examples/keyboard/index.ts` diff --git a/examples/img/images.ts b/examples/img/images.ts new file mode 100644 index 00000000..6216519f --- /dev/null +++ b/examples/img/images.ts @@ -0,0 +1,132 @@ +// Generated in-process: the renderer consumes decoded RGBA only +// (graphics-spec INV-I1), so the demo performs no IO. +// +// sphere smooth gradients and a specular highlight +// checker saturated hues with round alpha holes +// plasma re-set through setImage() every tick (graphics-spec §4.4) + +export interface Image { + width: number; + height: number; + pixels: Uint8Array; // RGBA8, straight alpha +} + +export type ImageId = 1 | 2 | 3; + +export function sphere(size = 64): Image { + let pixels = new Uint8Array(size * size * 4); + let light = norm3(-0.45, -0.6, 0.66); + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + let u = ((x + 0.5) / size) * 2 - 1; + let v = ((y + 0.5) / size) * 2 - 1; + let i = (y * size + x) * 4; + if (u * u + v * v > 1) { + drawBackdrop(pixels, i, x, y); + continue; + } + let z = Math.sqrt(1 - u * u - v * v); + let diff = Math.max(0, u * light[0] + v * light[1] + z * light[2]); + let spec = Math.pow(diff, 48) * 0.9; + let rim = Math.pow(1 - z, 3) * 0.35; + let r = 60 * (0.25 + 0.75 * diff) + 255 * spec + 20 * rim; + let g = 120 * (0.25 + 0.75 * diff) + 255 * spec + 150 * rim; + let b = 220 * (0.25 + 0.75 * diff) + 255 * spec + 180 * rim; + pixels[i] = clamp8(r); + pixels[i + 1] = clamp8(g); + pixels[i + 2] = clamp8(b); + pixels[i + 3] = 255; + } + } + return { width: size, height: size, pixels }; +} + +export function checker(size = 64): Image { + let pixels = new Uint8Array(size * size * 4); + let hues = [ + [226, 60, 60], + [60, 178, 72], + [66, 118, 230], + [240, 200, 48], + [184, 78, 204], + [48, 200, 210], + ]; + let cell = size / 8; + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + let i = (y * size + x) * 4; + let cx = Math.floor(x / cell); + let cy = Math.floor(y / cell); + let [r, g, b] = hues[(cx + cy * 3) % hues.length]; + // every other diagonal cell carries a round alpha hole (soft edge) + let hole = (cx + cy) % 2 === 1; + let a = 255; + if (hole) { + let du = (x % cell) / cell - 0.5; + let dv = (y % cell) / cell - 0.5; + let d = Math.sqrt(du * du + dv * dv) * 2; + a = clamp8((0.72 - d) * 8); + a = Math.round(a * 2.55); + } + pixels[i] = r; + pixels[i + 1] = g; + pixels[i + 2] = b; + pixels[i + 3] = a; + } + } + return { width: size, height: size, pixels }; +} + +export function plasma(size = 64, t = 0): Image { + let pixels = new Uint8Array(size * size * 4); + // palette stops: deep blue → violet → orange → pale yellow + let stops = [ + [12, 16, 48], + [90, 40, 160], + [230, 120, 40], + [255, 230, 140], + ]; + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + let i = (y * size + x) * 4; + let v = Math.sin(x * 0.11 + t) + + Math.sin(y * 0.13 + t * 1.31) + + Math.sin((x + y) * 0.09 + t * 0.77) + + Math.sin(Math.sqrt(x * x + y * y) * 0.14 - t * 0.53); + let f = (v + 4) / 8; // [0, 1) + let seg = Math.min(2.999, f * 3); + let k = Math.floor(seg); + let mix = seg - k; + let [r0, g0, b0] = stops[k]; + let [r1, g1, b1] = stops[k + 1]; + pixels[i] = clamp8(r0 + (r1 - r0) * mix); + pixels[i + 1] = clamp8(g0 + (g1 - g0) * mix); + pixels[i + 2] = clamp8(b0 + (b1 - b0) * mix); + pixels[i + 3] = 255; + } + } + return { width: size, height: size, pixels }; +} + +function drawBackdrop( + pixels: Uint8Array, + i: number, + x: number, + y: number, +): void { + // near-black with a faint grid so the sphere's silhouette reads + let grid = x % 8 === 0 || y % 8 === 0; + pixels[i] = grid ? 62 : 44; + pixels[i + 1] = grid ? 62 : 44; + pixels[i + 2] = grid ? 76 : 52; + pixels[i + 3] = 255; +} + +function clamp8(v: number): number { + return v < 0 ? 0 : v > 255 ? 255 : Math.round(v); +} + +function norm3(x: number, y: number, z: number): [number, number, number] { + let n = Math.sqrt(x * x + y * y + z * z); + return [x / n, y / n, z / n]; +} diff --git a/examples/img/index.ts b/examples/img/index.ts new file mode 100644 index 00000000..5e551c2e --- /dev/null +++ b/examples/img/index.ts @@ -0,0 +1,330 @@ +/** + * img — the graphics tier ladder (graphics-spec). + * + * One registry image rendered four ways, side by side: + * + * auto the ladder: kitty pixels when the terminal answers the graphics + * probe, shape-aware ascii art otherwise + * kitty kitty forced; without evidence it falls through to ascii + * ascii forced character art + * alt forced alt text + * + * The status line counts what each frame wrote: transmissions, placements, + * and deletions. Cleanup never leaves through update() or removeImage(); + * it shows up as deletions at the head of the next frame (§5.7). + * + * Keys: + * 1/2/3 switch the image: sphere / alpha checker / plasma + * k fold a kitty-graphics denial (pixels deleted next frame) + * g re-send the probe to recover real evidence + * a pause/resume the plasma's per-tick setImage() + * x removeImage + setImage the active image (delete, re-send) + * q/Ctrl+C quit + * + * Run: deno run examples/img/index.ts + */ +import { Buffer } from "node:buffer"; +import process from "node:process"; +import { + createChannel, + each, + ensure, + main, + type Operation, + race, + resource, + sleep, + spawn, + type Stream, + until, +} from "effection"; +import { + close, + createTerm, + detectTerminal, + fixed, + grow, + img, + type Op, + open, + type RuntimeCapabilities, + text, +} from "../../mod.ts"; +import { alternateBuffer, cursor, settings } from "../../settings.ts"; +import { useInput } from "../use-input.ts"; +import { useStdin } from "../use-stdin.ts"; +import { checker, type Image, plasma, sphere } from "./images.ts"; + +const IMAGES: { id: number; name: string; alt: string; make(): Image }[] = [ + { + id: 1, + name: "sphere", + alt: "a shaded sphere on a dark grid", + make: () => sphere(64), + }, + { + id: 2, + name: "checker", + alt: "a saturated checkerboard with round holes", + make: () => checker(64), + }, + { + id: 3, + name: "plasma", + alt: "a drifting plasma field", + make: () => plasma(64), + }, +]; + +const PANELS = ["auto", "kitty", "ascii", "alt"] as const; + +interface State { + width: number; + height: number; + active: number; + animate: boolean; + last: string; +} + +await main(function* () { + let { columns, rows } = terminalSize(); + let info = yield* until(detectTerminal()); + + setRawMode(true); + let stdin = yield* useStdin(); + let input = useInput(stdin, { terminfo: info }); + + let term = yield* until( + createTerm({ width: columns, height: rows, terminfo: info }), + ); + + let tty = settings(alternateBuffer(), cursor(false)); + writeStdout(tty.apply); + // The kitty-graphics reply arrives through scan() as a CapabilityEvent + // and is folded into term.update() below. + writeStdout(info.probe); + + for (let image of IMAGES) { + term.setImage(image.id, image.make()); + } + + let state: State = { + width: columns, + height: rows, + active: 0, + animate: true, + last: "", + }; + + function draw(): void { + let { output } = term.render(frame(state, term.capabilities)); + state.last = describe(output); + writeStdout(output); + } + + yield* ensure(() => { + // Removal queues the terminal-side deletions; one last render flushes + // them before the screen is restored. + for (let image of IMAGES) term.removeImage(image.id); + writeStdout(term.render([]).output); + setRawMode(false); + writeStdout(tty.revert); + }); + + draw(); + + for (let event of yield* each(merge(input, ticker(100)))) { + if (typeof event === "number") { + if (state.animate && IMAGES[state.active].name === "plasma") { + term.setImage(3, plasma(64, event / 1000)); + draw(); + } + yield* each.next(); + continue; + } + + if (event.type === "keydown") { + if (event.key === "q" || (event.ctrl && event.key === "c")) break; + if (event.key === "1") state.active = 0; + if (event.key === "2") state.active = 1; + if (event.key === "3") state.active = 2; + if (event.key === "a") state.animate = !state.animate; + if (event.key === "g") writeStdout(info.probe); + if (event.key === "k") { + term.update([{ + type: "capability", + key: "kitty-graphics", + value: false, + }]); + } + if (event.key === "x") { + let image = IMAGES[state.active]; + term.removeImage(image.id); + term.setImage(image.id, image.make()); + } + } + if (event.type === "capability") { + term.update([event]); + } + if (event.type === "resize") { + state.width = event.width; + state.height = event.height; + term.update([event]); + } + + draw(); + yield* each.next(); + } +}); + +function frame(state: State, caps: RuntimeCapabilities): Op[] { + let { width, height } = state; + let image = IMAGES[state.active]; + let w4 = Math.floor(width / 4); + let panelH = Math.max(3, height - 4); + let ops: Op[] = [ + open("root", { + layout: { width: fixed(width), height: fixed(height), direction: "ttb" }, + }), + open("title", { + layout: { width: grow(), height: fixed(1) }, + bg: "#14141c", + }), + text( + ` img · ${image.name} · kitty-graphics ${ + caps.kittyGraphics ? "on" : "off" + } · sync-output ${caps.syncOutput ? "on" : "off"}`.slice(0, width - 1), + { color: "#e6e6eb" }, + ), + close(), + open("labels", { + layout: { width: grow(), height: fixed(1), direction: "ltr" }, + }), + ]; + for (let panel of PANELS) { + ops.push( + open(`label:${panel}`, { + layout: { width: fixed(w4), height: fixed(1) }, + }), + text(` ${label(panel, caps)}`, { color: "#96dca0" }), + close(), + ); + } + ops.push( + close(), + open("panels", { + layout: { width: grow(), height: fixed(panelH), direction: "ltr" }, + }), + ); + for (let panel of PANELS) { + ops.push( + open(`panel:${panel}`, { + layout: { + width: fixed(w4), + height: fixed(panelH), + alignX: "center", + alignY: "center", + }, + border: { color: "#464654", left: 1, right: 1, top: 1, bottom: 1 }, + }), + img(`img:${panel}`, { + image: image.id, + alt: image.alt, + variant: panel, + width: fixed(Math.max(4, w4 - 2)), + height: fixed(Math.max(1, panelH - 2)), + bg: "#0c0c10", + }), + close(), + ); + } + ops.push( + close(), + open("frame-stats", { layout: { width: grow(), height: fixed(1) } }), + text(` last frame: ${state.last}`.slice(0, width - 1), { + color: "#a0a0b4", + }), + close(), + open("status", { + layout: { width: grow(), height: fixed(1) }, + bg: "#14141c", + }), + text( + " 1/2/3 image · k deny · g probe · a animate · x remove+set · q quit" + .slice(0, width - 1), + { color: "#78788c" }, + ), + close(), + close(), + ); + return ops; +} + +function label(panel: (typeof PANELS)[number], caps: RuntimeCapabilities) { + if (panel === "auto") { + return caps.kittyGraphics ? "auto → kitty" : "auto → ascii"; + } + if (panel === "kitty") return caps.kittyGraphics ? "kitty" : "kitty → ascii"; + return panel; +} + +/** What a frame's bytes contain, counted from its kitty control blocks. */ +function describe(output: Uint8Array): string { + let s = new TextDecoder().decode(output); + let count = (block: string) => s.split(`\x1b_G${block}`).length - 1; + let tx = count("a=t,"); + let place = count("a=p,"); + let freed = count("a=d,d=I,"); + let scoped = count("a=d,d=i,"); + return `${output.length} bytes · ${tx} transmitted · ${place} placed · ${freed} freed · ${scoped} placement deletes`; +} + +function terminalSize(): { columns: number; rows: number } { + return process.stdout.isTTY + ? { columns: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 } + : { columns: 80, rows: 24 }; +} + +function setRawMode(enabled: boolean): void { + if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") { + process.stdin.setRawMode(enabled); + } +} + +function writeStdout(bytes: Uint8Array): void { + process.stdout.write(Buffer.from(bytes)); +} + +function ticker(interval: number): Stream { + return resource(function* (provide) { + let ch = createChannel(); + yield* spawn(function* () { + while (true) { + yield* sleep(interval); + yield* ch.send(performance.now()); + } + }); + let sub = yield* ch; + yield* race([provide(sub), drain(ch)]); + }); +} + +function* drain(stream: Stream): Operation { + for (let _ of yield* each(stream)) { + yield* each.next(); + } +} + +function merge( + a: Stream, + b: Stream, +): Stream { + return resource(function* (provide) { + let subscription = { a: yield* a, b: yield* b }; + return yield* provide({ + *next() { + return yield* race([subscription.a.next(), subscription.b.next()]); + }, + }); + }); +} From df5139d7a7751f5468f8a5ab318a715b023d8fe4 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Thu, 3 Dec 2026 22:27:16 -0500 Subject: [PATCH 4/4] test: kitty continuation framing and art under a declared bg --- test/graphics.test.ts | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/test/graphics.test.ts b/test/graphics.test.ts index a64c6360..c27b48b0 100644 --- a/test/graphics.test.ts +++ b/test/graphics.test.ts @@ -303,6 +303,52 @@ describe("graphics: capability invalidation", () => { }); }); +describe("graphics: kitty conformance", () => { + it("continuation chunks carry only m and q", async () => { + let t = await term(); + t.setImage(1, solid(64, 64, [255, 0, 0])); // 16 KiB: six chunks + t.update([KITTY_GRANT]); + let out = frame(t, [img("a", { image: 1, alt: "x" })]); + let blocks = out.split("\x1b_G").slice(1).map((b) => b.split("\x1b\\")[0]) + .filter((b) => b.includes(";")); + if (blocks.length < 2) throw new Error("expected a chunked transmission"); + for (let block of blocks.slice(1)) { + if (!/^m=[01],q=2;/.test(block)) { + throw new Error( + `malformed continuation ${JSON.stringify(block.slice(0, 16))}`, + ); + } + } + }); +}); + +describe("graphics: art under a declared bg", () => { + it("ascii art survives the element's background", async () => { + let t = await term(); + t.setImage(1, solid(8, 8, [255, 0, 0])); + let g = grid(t, [img("a", { image: 1, alt: "x", bg: "#0c0c10" })]); + if (g[0].slice(0, 8) !== "::::::::") { + throw new Error(`row 0: ${JSON.stringify(g[0].slice(0, 8))}`); + } + }); + + it("kitty letterbox margins carry the declared bg", async () => { + let t = await term(); + t.setImage(1, solid(4, 8, [255, 0, 0])); // tall: margins left and right + t.update([KITTY_GRANT]); + let out = frame(t, [ + img("a", { + image: 1, + alt: "x", + bg: "#102030", + width: { type: "fixed", value: 12 }, + height: { type: "fixed", value: 4 }, + }), + ]); + if (!out.includes("\x1b[48;2;16;32;48m")) throw new Error("bg missing"); + }); +}); + describe("graphics: output capacity", () => { it("a transmission larger than the text budget arrives whole", async () => { let t = await term(40, 12);