import { afterEach, describe, expect, it, vi } from "bun:test"; import { __animationSchedulerTestHooks, Container, getCellDimensions, ImageProtocol, type PostRenderFrameInfo, resetTmuxPaneOffsetCache, resetTmuxSixelOwnershipCache, setCellDimensions, setTmuxOverlayImageProtocol, TERMINAL, type TUI, } from "@sayknow-cli/tui"; import type { CustomEditor } from "../src/modes/components/custom-editor"; import { PetFramedEditor, SayknowPetWidget } from "../src/modes/components/sayknow-pet-widget"; function makeStubs(columns = 80, rows = 30) { const written: string[] = []; let renderedWidth = 0; const editor = { setTopBorder(_border: unknown) {}, getTopBorderAvailableWidth(terminalWidth: number) { return Math.max(0, terminalWidth - 4); }, render(width: number) { renderedWidth = width; return [`+${"-".repeat(Math.max(0, width - 2))}+`, `| input${" ".repeat(Math.max(0, width - 9))}-+`]; }, invalidate() {}, } as unknown as CustomEditor; let emitter: ((frame?: PostRenderFrameInfo) => string | null) | undefined; let available = true; let failWrites = false; const pendingTerminalCleanup: Array<{ payload: string; onDelivered?: () => void }> = []; const flushTerminalCleanup = () => { while (available && pendingTerminalCleanup.length > 0) { const pending = pendingTerminalCleanup[0]; try { terminal.write(pending.payload); } catch { return; } pendingTerminalCleanup.shift(); pending.onDelivered?.(); } }; const terminal = { columns, rows, write: (data: string) => { if (failWrites) throw new Error("injected terminal write failure"); written.push(data); }, }; const ui = { requestRender: () => {}, setPostRenderEmitter: (fn?: (frame?: PostRenderFrameInfo) => string | null) => { emitter = fn; }, queueTerminalCleanup: (payload: string, onDelivered?: () => void) => { pendingTerminalCleanup.push({ payload, onDelivered }); flushTerminalCleanup(); }, get terminalAvailable() { return available; }, terminal, } as unknown as TUI; const editorContainer = new Container(); const floorContainer = new Container(); editorContainer.addChild(editor); return { editor, ui, editorContainer, floorContainer, written, getEmitter: () => emitter, getRenderedWidth: () => renderedWidth, setTerminalSize: (nextColumns: number, nextRows: number) => { terminal.columns = nextColumns; terminal.rows = nextRows; }, setTerminalAvailable: (value: boolean) => { available = value; }, setWriteFailure: (value: boolean) => { failWrites = value; }, flushTerminalCleanup, getPendingTerminalCleanupCount: () => pendingTerminalCleanup.length, }; } function makeWidget( columns = 80, rows = 30, options: { bottomOffset?: number; isWorking?: () => boolean; autoFlexGapMs?: [number, number] | null; protocol?: "sixel" | "kitty" | null; } = {}, ) { const stubs = makeStubs(columns, rows); const widget = new SayknowPetWidget({ ui: stubs.ui, editor: stubs.editor, editorContainer: stubs.editorContainer, floorContainer: stubs.floorContainer, isWorking: options.isWorking ?? (() => false), getComposerBottomOffset: () => stubs.floorContainer.render(columns).length + (options.bottomOffset ?? 0), forcePixelProtocol: options.protocol === null ? undefined : (options.protocol ?? "sixel"), autoFlexGapMs: options.autoFlexGapMs !== undefined ? options.autoFlexGapMs : null, }); return { ...stubs, widget }; } describe("SayknowPetWidget", () => { afterEach(() => { __animationSchedulerTestHooks.reset(); vi.useRealTimers(); vi.restoreAllMocks(); }); it("on: reserves a side area and registers the overlay emitter", () => { const { widget, editorContainer, getEmitter, getRenderedWidth } = makeWidget(); try { widget.setMode("red"); editorContainer.render(80); // The 36px pet reserves its 4 sprite columns + a 1-column side margin, so // the editor renders 5 columns narrower than the terminal. expect(getRenderedWidth()).toBe(80 - 5); expect(getEmitter()).toBeDefined(); const payload = getEmitter()?.(); expect(payload).toContain("\x1bP0;1;0q"); // Pet is inset one column from the right edge (x = 80 - 4 - 1 = 75 -> col 76). expect(payload).toContain(`;${80 - 4 - 1 + 1}H`); } finally { widget.dispose(); } }); it("owns and deletes a distinct Kitty image ID per widget", () => { const first = makeWidget(80, 30, { protocol: "kitty" }); const second = makeWidget(80, 30, { protocol: "kitty" }); try { first.widget.setMode("red"); second.widget.setMode("red"); const firstPayload = first.getEmitter()?.(); const secondPayload = second.getEmitter()?.(); const firstId = firstPayload?.match(/i=(\d+)/)?.[1]; const secondId = secondPayload?.match(/i=(\d+)/)?.[1]; expect(firstId).toBeDefined(); expect(secondId).toBeDefined(); expect(firstId).not.toBe(secondId); expect(Number(firstId)).toBeGreaterThan(0); expect(Number(secondId)).toBeGreaterThan(0); first.written.length = 0; first.widget.setMode("off"); expect(first.written.some(chunk => chunk.includes(`a=d,d=I,i=${firstId}`))).toBe(true); expect(first.written.some(chunk => chunk.includes(`i=${secondId}`))).toBe(false); } finally { first.widget.dispose(); second.widget.dispose(); } }); it("clears the last Sixel footprint when disabled", () => { const { widget, written, getEmitter } = makeWidget(); try { widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1bP0;1;0q"); written.length = 0; widget.setMode("off"); expect(written.some(chunk => chunk.includes("\x1b[28;76H\x1b[4X"))).toBe(true); } finally { widget.dispose(); } }); it("clears the previous Sixel footprint after the terminal becomes too narrow", () => { const { widget, getEmitter, setTerminalSize } = makeWidget(); try { widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1b[28;76H"); setTerminalSize(12, 30); const cleanup = getEmitter()?.(); expect(cleanup).toContain("\x1b[28;76H\x1b[4X"); expect(cleanup).not.toContain("\x1bP0;1;0q"); expect(getEmitter()?.()).toBeNull(); } finally { widget.dispose(); } }); it("retains cleanup authority when the render write that carried it fails, and dispose retries", () => { const { widget, written, getEmitter, setTerminalSize, setTerminalAvailable } = makeWidget(); widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1bP0;1;0q"); setTerminalSize(12, 30); // The emitter hands the cleanup payload to the TUI, but the enclosing // render write fails (availability drops), so delivery is never // acknowledged and the authority must survive. expect(getEmitter()?.()).toContain("\x1b[28;76H\x1b[4X"); setTerminalAvailable(false); expect(getEmitter()?.()).toBeNull(); written.length = 0; setTerminalAvailable(true); widget.dispose(); expect(written.some(chunk => chunk.includes("\x1b[28;76H\x1b[4X"))).toBe(true); }); it("re-emits the retained cleanup through the emitter once the terminal recovers", () => { const { widget, getEmitter, setTerminalSize, setTerminalAvailable } = makeWidget(); try { widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1bP0;1;0q"); setTerminalSize(12, 30); expect(getEmitter()?.()).toContain("\x1b[28;76H\x1b[4X"); // Frame write fails; authority is retained. setTerminalAvailable(false); expect(getEmitter()?.()).toBeNull(); // Recovered terminal: the emitter carries the erase again, and the // following pass acknowledges the successful delivery. setTerminalAvailable(true); expect(getEmitter()?.()).toContain("\x1b[28;76H\x1b[4X"); expect(getEmitter()?.()).toBeNull(); } finally { widget.dispose(); } }); it("retries Sixel cleanup that fails during final disposal", () => { const { flushTerminalCleanup, getEmitter, getPendingTerminalCleanupCount, setWriteFailure, widget, written } = makeWidget(); widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1bP0;1;0q"); written.length = 0; setWriteFailure(true); widget.dispose(); expect(getPendingTerminalCleanupCount()).toBe(1); expect(written).toHaveLength(0); setWriteFailure(false); flushTerminalCleanup(); expect(getPendingTerminalCleanupCount()).toBe(0); expect(written.some(chunk => chunk.includes("\x1b[28;76H\x1b[4X"))).toBe(true); }); it("reserves a Kitty image ID until failed final-disposal cleanup is delivered", () => { const imageIds = [101, 101, 202, 101]; vi.spyOn(crypto, "getRandomValues").mockImplementation(values => { if (!values) throw new Error("Expected a typed array"); const ids = new Uint32Array( values.buffer, values.byteOffset, values.byteLength / Uint32Array.BYTES_PER_ELEMENT, ); ids[0] = imageIds.shift() ?? 303; return values; }); const stubs = makeStubs(); const makeKitty = () => new SayknowPetWidget({ ui: stubs.ui, editor: stubs.editor, editorContainer: stubs.editorContainer, floorContainer: stubs.floorContainer, isWorking: () => false, getComposerBottomOffset: () => 0, forcePixelProtocol: "kitty", autoFlexGapMs: null, }); const first = makeKitty(); first.setMode("red"); expect(stubs.getEmitter()?.()).toContain("i=101"); stubs.setWriteFailure(true); first.dispose(); expect(stubs.getPendingTerminalCleanupCount()).toBe(1); const second = makeKitty(); second.setMode("red"); expect(stubs.getEmitter()?.()).toContain("i=202"); stubs.setWriteFailure(false); stubs.flushTerminalCleanup(); expect(stubs.getPendingTerminalCleanupCount()).toBe(0); expect(stubs.written.some(chunk => chunk.includes("a=d,d=I,i=101"))).toBe(true); const third = makeKitty(); third.setMode("red"); expect(stubs.getEmitter()?.()).toContain("i=101"); second.dispose(); third.dispose(); }); it("completes logical teardown when the cleanup write throws", () => { const { widget, editorContainer, getEmitter, getRenderedWidth, setWriteFailure } = makeWidget(); widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1bP0;1;0q"); setWriteFailure(true); widget.dispose(); // The thrown write must not abort teardown: the shared emitter slot is // released, the composer is unframed, and the widget is terminal. expect(getEmitter()).toBeUndefined(); expect(widget.mode).toBe("off"); editorContainer.render(80); expect(getRenderedWidth()).toBe(80); widget.setMode("red"); expect(getEmitter()).toBeUndefined(); }); it("keeps a disposed widget from clearing its successor's overlay emitter", () => { const stubs = makeStubs(); const make = () => new SayknowPetWidget({ ui: stubs.ui, editor: stubs.editor, editorContainer: stubs.editorContainer, floorContainer: stubs.floorContainer, isWorking: () => false, getComposerBottomOffset: () => stubs.floorContainer.render(80).length, forcePixelProtocol: "sixel", autoFlexGapMs: null, }); const first = make(); first.setMode("red"); first.dispose(); const second = make(); try { second.setMode("red"); const successorEmitter = stubs.getEmitter(); expect(successorEmitter).toBeDefined(); first.dispose(); expect(stubs.getEmitter()).toBe(successorEmitter); } finally { second.dispose(); } }); it("keeps a stale first-time dispose from stealing a successor's emitter or composer mount", () => { const stubs = makeStubs(); const make = () => new SayknowPetWidget({ ui: stubs.ui, editor: stubs.editor, editorContainer: stubs.editorContainer, floorContainer: stubs.floorContainer, isWorking: () => false, getComposerBottomOffset: () => stubs.floorContainer.render(80).length, forcePixelProtocol: "sixel", autoFlexGapMs: null, }); // The predecessor is never disposed before the successor takes over. const first = make(); first.setMode("red"); const second = make(); try { second.setMode("red"); const successorEmitter = stubs.getEmitter(); expect(successorEmitter).toBeDefined(); first.dispose(); expect(stubs.getEmitter()).toBe(successorEmitter); // The successor's framed composer stays mounted (editor still narrowed). stubs.editorContainer.render(80); expect(stubs.getRenderedWidth()).toBe(80 - 5); } finally { second.dispose(); } }); it("places the Kitty image once per pose and screen shape, not on every render write", () => { const { widget, getEmitter } = makeWidget(80, 30, { protocol: "kitty" }); try { widget.setMode("red"); const frame: PostRenderFrameInfo = { totalLines: 40, fullRedraws: 1, columns: 80, rows: 30 }; expect(getEmitter()?.(frame)).toContain("\x1b_G"); // In-place writes (the working-message shimmer, typing): no re-send. for (let i = 0; i < 5; i++) expect(getEmitter()?.({ ...frame })).toBeNull(); // A new line count may have scrolled the image away: place it again, once. expect(getEmitter()?.({ ...frame, totalLines: 41 })).toContain("\x1b_G"); expect(getEmitter()?.({ ...frame, totalLines: 41 })).toBeNull(); // A full redraw may have cleared it. expect(getEmitter()?.({ ...frame, totalLines: 41, fullRedraws: 2 })).toContain("\x1b_G"); // So may a resize. expect(getEmitter()?.({ ...frame, totalLines: 41, fullRedraws: 2, rows: 31 })).toContain("\x1b_G"); } finally { widget.dispose(); } }); it("keeps redrawing Sixel pets on every write (their pixels live in the text cells)", () => { const { widget, getEmitter } = makeWidget(80, 30); try { widget.setMode("red"); const frame: PostRenderFrameInfo = { totalLines: 40, fullRedraws: 1, columns: 80, rows: 30 }; expect(getEmitter()?.(frame)).toContain("\x1bP0;1;0q"); expect(getEmitter()?.({ ...frame })).toContain("\x1bP0;1;0q"); } finally { widget.dispose(); } }); it("re-arms Kitty cleanup when the pet is re-placed after a narrow-terminal pass consumed it", () => { const { widget, written, getEmitter, setTerminalSize } = makeWidget(12, 30, { protocol: "kitty" }); try { widget.setMode("red"); // Too narrow: the emitter returns the delete escape and consumes the // pending cleanup. expect(getEmitter()?.()).toContain("\x1b_Ga=d"); expect(getEmitter()?.()).toBeNull(); // Wide again: the next frame re-places the image. setTerminalSize(80, 30); expect(getEmitter()?.()).toContain("\x1b_G"); written.length = 0; widget.dispose(); expect(written.some(chunk => chunk.includes("\x1b_Ga=d,d=I,i="))).toBe(true); } finally { widget.dispose(); } }); it("retains Sixel cleanup authority while the terminal is unavailable and erases once it returns", () => { const { widget, written, getEmitter, setTerminalAvailable } = makeWidget(); widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1bP0;1;0q"); written.length = 0; setTerminalAvailable(false); widget.setMode("off"); expect(written).toHaveLength(0); setTerminalAvailable(true); widget.dispose(); expect(written.some(chunk => chunk.includes("\x1b[28;76H\x1b[4X"))).toBe(true); }); it("retains Sixel cleanup authority when the erase write throws and retries on dispose", () => { const { widget, written, getEmitter, setWriteFailure } = makeWidget(); widget.setMode("red"); expect(getEmitter()?.()).toContain("\x1bP0;1;0q"); written.length = 0; setWriteFailure(true); widget.setMode("off"); expect(written).toHaveLength(0); setWriteFailure(false); widget.dispose(); expect(written.some(chunk => chunk.includes("\x1b[28;76H\x1b[4X"))).toBe(true); }); it("hides the overlay instead of covering editor text on a narrow terminal", () => { const { widget, editorContainer, getEmitter, getRenderedWidth } = makeWidget(12, 30); try { widget.setMode("red"); editorContainer.render(12); expect(getRenderedWidth()).toBe(12); expect(getEmitter()?.()).toBeNull(); } finally { widget.dispose(); } }); it("lifts the pet so its feet align with the composer's visual bottom edge", () => { // 2 hook rows below the composer; no floor row is reserved. const { widget, getEmitter } = makeWidget(80, 30, { bottomOffset: 2 }); try { widget.setMode("red"); // composerBottom = 30 - 2 hooks = 28; the two-row pet lifted one safety // row sits at zero-based row 25 -> cursor row 26. expect(getEmitter()?.()).toContain("\x1b[26;"); } finally { widget.dispose(); } }); it("drops the kitty pet by a sub-cell Y offset instead of a full-row jump", () => { // 2 hook rows below the composer; no pet floor row is reserved. const { widget, getEmitter } = makeWidget(80, 30, { bottomOffset: 2, protocol: "kitty" }); try { widget.setMode("red"); const payload = getEmitter()?.(); // composerBottom = 30 - 2 hooks = 28; the two-row pet lifted one safety // row draws at zero-based row 25 -> cursor row 26... expect(payload).toContain("\x1b[26;"); // ...then nudged back down within the cell by a native kitty Y offset // proportional to the cell height (round(18 * 0.45) = 8 at the 18px default // cell) so the sprite tracks the composer border at any font size. expect(payload).toContain("\x1b_Ga=T"); expect(payload).toContain(",Y=8,"); } finally { widget.dispose(); } }); it("rebuilds the kitty pet when the terminal cell size changes (font resize)", () => { vi.useFakeTimers(); const original = getCellDimensions(); const { widget, getEmitter } = makeWidget(80, 30, { protocol: "kitty", autoFlexGapMs: null }); try { widget.setMode("red"); // default 18px cell -> Y = floor(18 * 0.45) = 8 expect(getEmitter()?.()).toContain(",Y=8,"); // A font/zoom change resizes the cells; the next tick must rebuild. setCellDimensions({ widthPx: 9, heightPx: 30 }); vi.advanceTimersByTime(100); // 30px cell -> Y = floor(30 * 0.45) = 13, tracking the new metrics. expect(getEmitter()?.()).toContain(",Y=13,"); expect(getEmitter()?.()).not.toContain(",Y=8,"); } finally { setCellDimensions(original); widget.dispose(); } }); it("writes frames directly to the terminal when the UI is quiet", () => { vi.useFakeTimers(); const { widget, written } = makeWidget(); try { widget.setMode("red"); written.length = 0; // Idle loop leaves "base" at 1100ms; advance into the gazeL window. vi.advanceTimersByTime(1200); expect(written.length).toBeGreaterThan(0); expect(written.some(chunk => chunk.includes("\x1b[?2026h\x1b7") && chunk.includes("\x1bP0;1;0q"))).toBe(true); // Transparent sixel frames clear only the reserved pet cells inside // the same synchronized write, avoiding opaque image rectangles. expect(written.some(chunk => chunk.includes("\x1b[0m") && chunk.includes("\x1b[4X"))).toBe(true); } finally { widget.dispose(); } }); it("reserves no floor row so the composer stays pinned to the terminal bottom", () => { const { widget, getEmitter, floorContainer } = makeWidget(80, 30); // sixel try { widget.setMode("red"); // No floor row is reserved, so enabling the pet does not push the composer // up. composerBottom stays at row 30 and the pet overlays its bottom rows. expect(floorContainer.render(80).length).toBe(0); expect(getEmitter()?.()).toContain("\x1b[28;"); } finally { widget.dispose(); } }); it("reserves no floor row for kitty either", () => { const { widget, getEmitter, floorContainer } = makeWidget(80, 30, { protocol: "kitty" }); try { widget.setMode("red"); expect(floorContainer.render(80).length).toBe(0); expect(getEmitter()?.()).toContain("\x1b[28;"); } finally { widget.dispose(); } }); it("auto-flexes randomly in both idle and working states", () => { vi.useFakeTimers(); const idle = makeWidget(80, 30, { autoFlexGapMs: [500, 500] }); const busy = makeWidget(80, 30, { autoFlexGapMs: [500, 500], isWorking: () => true }); try { idle.widget.setMode("red"); busy.widget.setMode("red"); // First tick schedules; the flex fires ~500ms later. vi.advanceTimersByTime(700); expect(idle.widget.isFlexing).toBe(true); expect(busy.widget.isFlexing).toBe(true); // The multi-beat burst (~2.6s) ends before the next scheduled flex (~3.7s). vi.advanceTimersByTime(2800); expect(idle.widget.isFlexing).toBe(false); expect(busy.widget.isFlexing).toBe(false); } finally { idle.widget.dispose(); busy.widget.dispose(); } }); it("runs a para-para-then-sob burst for BlueOctopus", () => { vi.useFakeTimers(); const { widget } = makeWidget(80, 30, { autoFlexGapMs: [500, 500] }); try { widget.setMode("blue"); // Burst fires ~500ms in; the para-para (~1.6s) plus sobbing tail (~1s) keeps // it flexing at the 2s mark, well into the burst. vi.advanceTimersByTime(2000); expect(widget.isFlexing).toBe(true); // The whole ~2.6s burst clears before the next scheduled burst. vi.advanceTimersByTime(1400); expect(widget.isFlexing).toBe(false); } finally { widget.dispose(); } }); it("demos the signature burst shortly after a skin is previewed", () => { vi.useFakeTimers(); const { widget } = makeWidget(80, 30, { autoFlexGapMs: [12_000, 40_000] }); try { widget.previewMode("red"); // Live auto-flex is 12-40s out; a preview forces the demo burst right after // the idle eye-roll (~2.3s) so the selector shows the animation immediately. vi.advanceTimersByTime(2600); expect(widget.isFlexing).toBe(true); } finally { widget.dispose(); } }); it("cycles the para-para dance sequence while working", () => { vi.useFakeTimers(); const { widget, written } = makeWidget(80, 30, { isWorking: () => true, autoFlexGapMs: null }); try { widget.setMode("red"); written.length = 0; // 1500ms spans 450ms steps L -> R -> both-up -> rest, so the working pet // must emit at least three distinct dance frames. vi.advanceTimersByTime(1500); const danceFrames = new Set(written.filter(chunk => chunk.includes("\x1b[?2026h"))); expect(danceFrames.size).toBeGreaterThanOrEqual(3); } finally { widget.dispose(); } }); it("off: unregisters emitter, floor, width and timers", () => { const { widget, editorContainer, floorContainer, getEmitter, getRenderedWidth } = makeWidget(); widget.setMode("red"); widget.setMode("off"); expect(getEmitter()).toBeUndefined(); expect(floorContainer.render(80).length).toBe(0); editorContainer.render(80); expect(getRenderedWidth()).toBe(80); expect(__animationSchedulerTestHooks.getRegistrantCount(80)).toBe(0); }); it("stays off when no pixel protocol is available", () => { vi.spyOn(SayknowPetWidget, "pixelProtocol").mockReturnValue(null); const stubs = makeStubs(); const widget = new SayknowPetWidget({ ui: stubs.ui, editor: stubs.editor, editorContainer: stubs.editorContainer, floorContainer: stubs.floorContainer, isWorking: () => false, getComposerBottomOffset: () => 0, }); widget.setMode("red"); expect(widget.mode).toBe("off"); expect(stubs.getEmitter()).toBeUndefined(); widget.dispose(); }); }); describe("SayknowPetWidget tmux passthrough delivery", () => { const originalTmux = Bun.env.TMUX; const originalTmuxPane = Bun.env.TMUX_PANE; const originalTmuxLaunched = Bun.env.SKC_TMUX_LAUNCHED; const originalTmuxCommand = Bun.env.SKC_TMUX_COMMAND; const originalProtocol = TERMINAL.imageProtocol; const mutableTerminal = TERMINAL as unknown as { imageProtocol: ImageProtocol | null }; const paneOffsetStub = `${import.meta.dir}/fixtures/tui/tmux-pane-offset-stub.sh`; function underTmux(tmuxCommand: string): void { Bun.env.TMUX = "/tmp/tmux-1000/default,1234,0"; Bun.env.TMUX_PANE = "%1"; Bun.env.SKC_TMUX_COMMAND = tmuxCommand; resetTmuxSixelOwnershipCache(); resetTmuxPaneOffsetCache(); } afterEach(() => { __animationSchedulerTestHooks.reset(); setTmuxOverlayImageProtocol(null); mutableTerminal.imageProtocol = originalProtocol; for (const [key, value] of [ ["TMUX", originalTmux], ["TMUX_PANE", originalTmuxPane], ["SKC_TMUX_LAUNCHED", originalTmuxLaunched], ["SKC_TMUX_COMMAND", originalTmuxCommand], ] as const) { if (value === undefined) delete Bun.env[key]; else Bun.env[key] = value; } resetTmuxSixelOwnershipCache(); resetTmuxPaneOffsetCache(); }); it("wraps the kitty overlay in the passthrough envelope and addresses the outer screen", () => { // `false` answers nothing: tmux neither owns sixel nor reports a pane origin. underTmux("false"); mutableTerminal.imageProtocol = null; setTmuxOverlayImageProtocol(ImageProtocol.Kitty); const { widget, getEmitter } = makeWidget(80, 30, { protocol: "kitty" }); try { widget.setMode("red"); const payload = getEmitter()?.() ?? ""; expect(payload.startsWith("\x1bPtmux;")).toBe(true); expect(payload.endsWith("\x1b\\")).toBe(true); // Save/restore must sit inside the envelope: the outer cursor is the one // that has to come back, and tmux would swallow a bare \x1b7/\x1b8. expect(payload).toContain("\x1bPtmux;\x1b\x1b7"); // Every inner ESC is doubled, so the raw kitty APC never appears verbatim. expect(payload).toContain("\x1b\x1b_G"); // Strip the doubled pairs: no bare APC escape may survive, or tmux would // terminate the envelope early and eat the rest of the frame. expect(payload.replaceAll("\x1b\x1b", "").includes("\x1b_G")).toBe(false); // Pane origin unknown -> pane-relative position, one column of inset. expect(payload).toContain(`;${80 - 4 - 1 + 1}H`); } finally { widget.dispose(); } }); it("offsets the overlay by the pane origin reported by tmux", () => { underTmux(paneOffsetStub); mutableTerminal.imageProtocol = null; setTmuxOverlayImageProtocol(ImageProtocol.Kitty); const { widget, getEmitter } = makeWidget(80, 30, { protocol: "kitty" }); try { widget.setMode("red"); const payload = getEmitter()?.() ?? ""; // Stub pane: 11 rows down, 40 columns right, one top status line. expect(payload).toContain(`;${80 - 4 - 1 + 40 + 1}H`); } finally { widget.dispose(); } }); it("sends the kitty delete through passthrough so the outer terminal drops the image", () => { underTmux("false"); mutableTerminal.imageProtocol = null; setTmuxOverlayImageProtocol(ImageProtocol.Kitty); const { widget, written, getEmitter } = makeWidget(80, 30, { protocol: "kitty" }); try { widget.setMode("red"); const imageId = getEmitter()?.()?.match(/i=(\d+)/)?.[1]; expect(imageId).toBeDefined(); written.length = 0; widget.setMode("off"); const cleanup = written.find(chunk => chunk.includes("a=d,d=I")); expect(cleanup).toBeDefined(); expect(cleanup).toContain("\x1bPtmux;"); expect(cleanup).toContain(`\x1b\x1b_Ga=d,d=I,i=${imageId},q=2`); } finally { widget.dispose(); } }); it("keeps inline kitty delivery unwrapped when the terminal renders images itself", () => { underTmux("false"); mutableTerminal.imageProtocol = ImageProtocol.Kitty; setTmuxOverlayImageProtocol(null); const { widget, getEmitter } = makeWidget(80, 30, { protocol: "kitty" }); try { widget.setMode("red"); const payload = getEmitter()?.() ?? ""; expect(payload.startsWith("\x1bPtmux;")).toBe(false); expect(payload).toContain("\x1b_G"); } finally { widget.dispose(); } }); }); describe("PetFramedEditor", () => { it("passes through untouched when no reserve is set", () => { const { editor } = makeStubs(80); const framed = new PetFramedEditor(editor); expect(framed.render(80)).toEqual(editor.render(80)); }); });