sailfork / t3code-github / apps/ web/ src/ terminal/ ghostty/ core.test.ts

import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
  applyTerminalAttachStreamEvent,
  DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
  INITIAL_TERMINAL_OUTPUT_CURSOR,
  nextTerminalAttachSeedState,
  readTerminalOutputUpdate,
  terminalOutputText,
  type TerminalBufferState,
} from "@t3tools/client-runtime/state/terminal";

import { writeTerminalOutputUpdate } from "../../components/ThreadTerminalDrawer";
import { GHOSTTY_CELL_WIDE, GhosttyTerminalCore, ghosttyCellText } from "./core";
import { loadGhosttyRuntime } from "./runtime";
import { terminalNavigationShortcutData } from "../../keybindings";

vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
  default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
}));
vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
  default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
}));

function codepointView(codepoints: ReadonlyArray<number>): DataView {
  const view = new DataView(new ArrayBuffer(codepoints.length * 4));
  codepoints.forEach((codepoint, index) => view.setUint32(index * 4, codepoint, true));
  return view;
}

describe("ghosttyCellText", () => {
  it("converts oversized grapheme clusters without hitting engine spread limits", () => {
    const graphemeLength = 130_000;
    const view = new DataView(new ArrayBuffer(graphemeLength * 4));
    for (let index = 0; index < graphemeLength; index += 1) {
      view.setUint32(index * 4, index === 0 ? "a".codePointAt(0)! : 0x301, true);
    }
    const text = ghosttyCellText(view, graphemeLength);
    expect(text.length).toBe(graphemeLength);
    expect(text.codePointAt(0)).toBe("a".codePointAt(0));
    expect(text.codePointAt(1)).toBe(0x301);
    expect(text.codePointAt(graphemeLength - 1)).toBe(0x301);
  });

  // regression: #7809 oversized terminal graphemes crashed rendering
  it("converts small clusters including astral codepoints", () => {
    const text = ghosttyCellText(codepointView([0x1f642, 0x20e3]), 2);
    expect([...text]).toEqual(["\u{1F642}", "\u{20E3}"]);
  });
});

describe("GhosttyTerminalCore snapshots", () => {
  const cores = new Set<GhosttyTerminalCore>();

  async function createCore(onData: (data: string) => void = () => {}) {
    const core = await GhosttyTerminalCore.create(
      12,
      3,
      8,
      16,
      {
        foreground: { r: 255, g: 255, b: 255 },
        background: { r: 0, g: 0, b: 0 },
        cursor: { r: 255, g: 255, b: 255 },
      },
      onData,
    );
    cores.add(core);
    return core;
  }

  function createSession(history: string) {
    return applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
      type: "snapshot",
      snapshot: {
        threadId: "terminal-stream-test",
        terminalId: "term-1",
        cwd: "/repo",
        worktreePath: null,
        status: "running",
        pid: 123,
        history,
        exitCode: null,
        exitSignal: null,
        label: "Terminal",
        updatedAt: "2026-09-04T00:00:00.000Z",
      },
    });
  }

  function append(state: TerminalBufferState, data: string) {
    return applyTerminalAttachStreamEvent(state, {
      type: "output",
      threadId: "terminal-stream-test",
      terminalId: "term-1",
      data,
    });
  }

  afterEach(() => {
    for (const core of cores) core.dispose();
    cores.clear();
    vi.restoreAllMocks();
  });

  it.each([
    { key: "ArrowLeft", expected: "\x1b[1;5D" },
    { key: "ArrowRight", expected: "\x1b[1;5C" },
  ])("sends Ctrl+$key as a modified arrow instead of Alt+B/F", async ({ key, expected }) => {
    const core = await createCore();
    const event = {
      code: key,
      key,
      repeat: false,
      shiftKey: false,
      ctrlKey: true,
      altKey: false,
      metaKey: false,
      isComposing: false,
      getModifierState: () => false,
    } as unknown as KeyboardEvent;

    expect(terminalNavigationShortcutData(event, "Win32") ?? core.encodeKey(event)).toBe(expected);
  });

  it.each([
    { code: "", key: "Backspace", expected: "\x7f" },
    { code: "Unidentified", key: "Backspace", expected: "\x7f" },
    { code: "Backspace", key: "Backspace", expected: "\x7f" },
    { code: "Delete", key: "Backspace", expected: "\x1b[3~" },
    { code: "", key: "a", expected: "a" },
    { code: "", key: "Unidentified", expected: "" },
  ])("encodes key $key with physical code '$code'", async ({ code, key, expected }) => {
    const core = await createCore();
    const event = {
      code,
      key,
      repeat: false,
      shiftKey: false,
      ctrlKey: false,
      altKey: false,
      metaKey: false,
      isComposing: false,
      getModifierState: () => false,
    } as unknown as KeyboardEvent;

    expect(core.encodeKey(event)).toBe(expected);
  });

  it("preserves styles, wide cells, and selection after shared memory grows", async () => {
    const core = await createCore();
    const runtime = await loadGhosttyRuntime();
    const grapheme = `e${"\u0301".repeat(64)}`;
    core.write(`\x1b[1;3;4;8;9;53;38;2;123;45;67;48;2;9;8;7m${grapheme}\x1b[0m界🙂`);
    const cells = core.snapshot().rowData[0]!.cells;
    expect(cells[0]).toEqual({
      text: grapheme,
      wide: 0,
      foreground: { r: 123, g: 45, b: 67 },
      background: { r: 9, g: 8, b: 7 },
      bold: true,
      italic: true,
      invisible: true,
      strikethrough: true,
      overline: true,
      underline: true,
      selected: false,
    });
    expect(cells.slice(1, 5).map(({ text, wide }) => ({ text, wide }))).toEqual([
      { text: "界", wide: 0 },
      { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
      { text: "🙂", wide: 0 },
      { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
    ]);

    runtime.memory.grow(1);
    core.setSelection({ x: 0, y: 0 }, { x: 2, y: 0 });
    expect(core.snapshot().rowData[0]!.cells[0]).toEqual({ ...cells[0], selected: true });
    core.clearSelection();
    expect(core.snapshot().rowData[0]!.cells[0]).toEqual(cells[0]);

    core.resetAndWrite("\x1b[2;7;38;2;40;100;200;48;2;12;34;56mC\x1b[0m");
    expect(core.snapshot().rowData[0]!.cells[0]).toMatchObject({
      text: "C",
      foreground: { r: 22, g: 59, b: 112 },
      background: { r: 40, g: 100, b: 200 },
      bold: false,
      underline: false,
      selected: false,
    });
  });

  it("resolves foreground and background independently without retaining prior cell colors", async () => {
    const core = await createCore();
    core.write(
      "\x1b[38;2;123;45;67mF\x1b[39;48;2;9;8;7mB\x1b[0mD\x1b[38;2;12;34;56;48;2;78;90;123mC\x1b[0mE",
    );
    expect(
      core
        .snapshot()
        .rowData[0]!.cells.slice(0, 6)
        .map(({ text, foreground, background }) => ({ text, foreground, background })),
    ).toEqual([
      { text: "F", foreground: { r: 123, g: 45, b: 67 }, background: { r: 0, g: 0, b: 0 } },
      { text: "B", foreground: { r: 255, g: 255, b: 255 }, background: { r: 9, g: 8, b: 7 } },
      { text: "D", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
      { text: "C", foreground: { r: 12, g: 34, b: 56 }, background: { r: 78, g: 90, b: 123 } },
      { text: "E", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
      { text: "", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
    ]);
  });

  it("paints ANSI colors from the theme palette and repaints them on theme change", async () => {
    const core = await createCore();
    const theme = {
      foreground: { r: 255, g: 255, b: 255 },
      background: { r: 0, g: 0, b: 0 },
      cursor: { r: 255, g: 255, b: 255 },
    };
    const palette = Array.from({ length: 16 }, (_, index) => ({ r: index, g: 1, b: 2 }));
    core.write("\x1b[31mR\x1b[38;5;196mX\x1b[0m");
    core.setTheme({ ...theme, palette });
    let cells = core.snapshot().rowData[0]!.cells;
    expect(cells[0]!.foreground).toEqual({ r: 1, g: 1, b: 2 });
    expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });

    core.setTheme({ ...theme, palette: palette.map((color) => ({ ...color, g: 9 })) });
    cells = core.snapshot().rowData[0]!.cells;
    expect(cells[0]!.foreground).toEqual({ r: 1, g: 9, b: 2 });
    expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });
  });

  it("preserves Unicode and split ANSI parser state across batched renderer reads", async () => {
    const [core, reference] = await Promise.all([createCore(), createCore()]);
    let state = createSession("");
    const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
    writeTerminalOutputUpdate(core, first);
    let cursor = first.cursor;
    const reset = vi.spyOn(core, "resetAndWrite");
    const inputs = [
      `${"a".repeat(16_383)}🙂`,
      "\x1b[3",
      "1m",
      "e",
      "\u0301界🙂",
      "\x1b[0",
      "m\r\n",
      "\x1b]8;;https://t3.codes\x1b",
      "\\link",
      "\x1b]8;;\x1b",
      "\\\x1b[?1049h",
      "alternate",
      "\x1b[?1049l",
      "\r\nend",
    ];
    let received = "";
    for (const [index, data] of inputs.entries()) {
      state = append(state, data);
      if (index % 3 !== 0 && index !== inputs.length - 1) continue;
      const update = readTerminalOutputUpdate(state.output, cursor);
      if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
      received += update.data;
      writeTerminalOutputUpdate(core, update);
      cursor = update.cursor;
    }

    reference.write(inputs.join(""));
    expect(received).toBe(inputs.join(""));
    expect(reset).not.toHaveBeenCalled();
    expect(core.snapshot()).toEqual(reference.snapshot());
  });

  it("answers a live VT query when batched reads cross a chunk compaction", async () => {
    const replies: string[] = [];
    const core = await createCore((data) => replies.push(data));
    core.write("\x1b[5n");
    expect(replies).toEqual(["\x1b[0n"]);
    replies.length = 0;

    let state = createSession("");
    const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
    writeTerminalOutputUpdate(core, initial);
    let cursor = initial.cursor;
    for (let index = 0; index < 1000; index += 1) {
      state = append(state, "x");
      const update = readTerminalOutputUpdate(state.output, cursor);
      writeTerminalOutputUpdate(core, update);
      cursor = update.cursor;
    }
    for (let index = 0; index < 24; index += 1) state = append(state, "x");
    state = append(state, "\x1b[5n");
    const update = readTerminalOutputUpdate(state.output, cursor);
    writeTerminalOutputUpdate(core, update);

    expect({ type: update.type, replies }).toEqual({ type: "append", replies: ["\x1b[0n"] });
  });

  it("recovers a lagging renderer once from bounded output and resumes appending", async () => {
    const [core, reference] = await Promise.all([createCore(), createCore()]);
    let state = createSession("\x1b[31mold");
    const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
    writeTerminalOutputUpdate(core, initial);
    const reset = vi.spyOn(core, "resetAndWrite");
    const data = "line\r\n".repeat(8192);
    for (let index = 0; index < 16; index += 1) state = append(state, data);

    const recovery = readTerminalOutputUpdate(state.output, initial.cursor);
    if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`);
    expect(new TextEncoder().encode(recovery.data).byteLength).toBe(
      DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
    );
    writeTerminalOutputUpdate(core, recovery);
    reference.resetAndWrite(recovery.data);
    expect(core.snapshot()).toEqual(reference.snapshot());

    state = append(state, "\r\nlatest");
    const next = readTerminalOutputUpdate(state.output, recovery.cursor);
    expect(next.type).toBe("append");
    writeTerminalOutputUpdate(core, next);
    reference.write("\r\nlatest");
    expect(reset).toHaveBeenCalledTimes(1);
    expect(core.snapshot()).toEqual(reference.snapshot());
  });

  it("replays the latest retained output when WASM arrives after several events", async () => {
    const pendingCore = createCore();
    let state = createSession("before");
    state = append(state, "\r\nduring ");
    state = append(state, "🙂 load");
    const core = await pendingCore;
    const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
    writeTerminalOutputUpdate(core, first);
    const reference = await createCore();
    reference.resetAndWrite(terminalOutputText(state.output));
    const reset = vi.spyOn(core, "resetAndWrite");

    state = append(state, "\r\nafter");
    const next = readTerminalOutputUpdate(state.output, first.cursor);
    expect(next).toMatchObject({ type: "append", data: "\r\nafter" });
    writeTerminalOutputUpdate(core, next);
    reference.write("\r\nafter");
    expect(reset).not.toHaveBeenCalled();
    expect(core.snapshot()).toEqual(reference.snapshot());
  });

  it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
    const [core, reference] = await Promise.all([createCore(), createCore()]);
    let state = createSession("hello");
    const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
    writeTerminalOutputUpdate(core, initial);
    let cursor = initial.cursor;

    const snapshot = {
      threadId: "terminal-stream-test",
      terminalId: "term-1",
      cwd: "/repo",
      worktreePath: null,
      status: "running" as const,
      pid: 456,
      history: "hello",
      exitCode: null,
      exitSignal: null,
      label: "Terminal",
      updatedAt: "2026-09-04T00:00:01.000Z",
    };
    const events = [
      { type: "snapshot", snapshot },
      { type: "cleared", threadId: snapshot.threadId, terminalId: snapshot.terminalId },
      { type: "restarted", threadId: snapshot.threadId, terminalId: snapshot.terminalId, snapshot },
    ] as const;
    for (const event of events) {
      core.write("\r\nstale local text");
      state = applyTerminalAttachStreamEvent(state, event);
      const update = readTerminalOutputUpdate(state.output, cursor);
      expect(update.type).toBe("reset");
      writeTerminalOutputUpdate(core, update);
      cursor = update.cursor;
      reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
      expect(core.snapshot()).toEqual(reference.snapshot());
    }

    core.write("\r\nstale local text");
    state = createSession("hello");
    const reattached = readTerminalOutputUpdate(state.output, cursor);
    expect(reattached.type).toBe("reset");
    writeTerminalOutputUpdate(core, reattached);
    reference.resetAndWrite("hello");
    expect(core.snapshot()).toEqual(reference.snapshot());
  });
});