repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/neko/__tests__/lifecycle.test.ts

Raw
File outline
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";

type Handler = (event: any, ctx: any) => unknown | Promise<unknown>;
type Timer = { fn: () => void; ms: number; cleared: boolean; kind: "timeout" | "interval" };

type Harness = ReturnType<typeof createHarness>;

let agentDir = "";
let projectDir = "";
let nekoExtension: (pi: any) => void;

const originalSetTimeout = globalThis.setTimeout;
const originalClearTimeout = globalThis.clearTimeout;
const originalSetInterval = globalThis.setInterval;
const originalClearInterval = globalThis.clearInterval;

let timers: Timer[] = [];

function installFakeTimers(): void {
  timers = [];
  globalThis.setTimeout = ((fn: () => void, ms?: number) => {
    const timer: Timer = { fn, ms: ms ?? 0, cleared: false, kind: "timeout" };
    timers.push(timer);
    return timer as any;
  }) as any;
  globalThis.clearTimeout = ((timer?: Timer | null) => {
    if (timer) timer.cleared = true;
  }) as any;
  globalThis.setInterval = ((fn: () => void, ms?: number) => {
    const timer: Timer = { fn, ms: ms ?? 0, cleared: false, kind: "interval" };
    timers.push(timer);
    return timer as any;
  }) as any;
  globalThis.clearInterval = ((timer?: Timer | null) => {
    if (timer) timer.cleared = true;
  }) as any;
}

function restoreTimers(): void {
  globalThis.setTimeout = originalSetTimeout;
  globalThis.clearTimeout = originalClearTimeout;
  globalThis.setInterval = originalSetInterval;
  globalThis.clearInterval = originalClearInterval;
}

function writeSettings(settings: Record<string, unknown>): void {
  writeFileSync(join(agentDir, "settings.json"), JSON.stringify(settings, null, 2), "utf-8");
}

function stripAnsi(text: string): string {
  return text.replace(/\x1b\[[0-9;]*m/g, "");
}

function createHarness() {
  const handlers = new Map<string, Handler[]>();
  const commands = new Map<string, any>();
  const uiCalls: Array<{ method: string; args: any[] }> = [];

  const ui = {
    setWorkingVisible: (...args: any[]) => uiCalls.push({ method: "setWorkingVisible", args }),
    setEditorComponent: (...args: any[]) => uiCalls.push({ method: "setEditorComponent", args }),
    notify: (...args: any[]) => uiCalls.push({ method: "notify", args }),
  };

  const ctx = { hasUI: true, cwd: projectDir, ui };
  const pi = {
    on(event: string, handler: Handler) {
      const list = handlers.get(event) ?? [];
      list.push(handler);
      handlers.set(event, list);
    },
    registerCommand(name: string, options: any) {
      commands.set(name, options);
    },
    events: { on() {}, emit() {} },
  };

  nekoExtension(pi);

  return {
    handlers,
    commands,
    ctx,
    uiCalls,
    calls(method: string) {
      return uiCalls.filter((call) => call.method === method);
    },
    last(method: string) {
      return uiCalls.filter((call) => call.method === method).at(-1);
    },
    async emit(event: string, payload: any = {}) {
      for (const handler of handlers.get(event) ?? []) await handler(payload, ctx);
    },
    async command(name: string, args = "") {
      await commands.get(name).handler(args, ctx);
    },
    createEditor() {
      const factory = this.last("setEditorComponent")?.args[0];
      expect(typeof factory).toBe("function");
      return factory(
        { requestRender() {}, terminal: { rows: 30, cols: 80 } },
        { borderColor: (text: string) => text, selectList: {} },
        { matches: () => false },
      );
    },
  };
}

beforeAll(async () => {
  agentDir = mkdtempSync(join(tmpdir(), "neko-agent-"));
  projectDir = mkdtempSync(join(tmpdir(), "neko-project-"));
  process.env.PI_CODING_AGENT_DIR = agentDir;
  nekoExtension = (await import("../index.ts")).default;
});

beforeEach(() => {
  installFakeTimers();
  writeSettings({ neko: { enabled: true }, editorPaddingX: 1 });
});

afterEach(() => {
  restoreTimers();
});

afterAll(() => {
  rmSync(agentDir, { recursive: true, force: true });
  rmSync(projectDir, { recursive: true, force: true });
});

describe("neko lifecycle", () => {
  it("enabled session hides built-in working row and mounts editor", async () => {
    const h = createHarness();

    await h.emit("session_start");

    expect(h.last("setWorkingVisible")?.args).toEqual([false]);
    expect(typeof h.last("setEditorComponent")?.args[0]).toBe("function");
    expect(timers.filter((timer) => timer.kind === "interval" && !timer.cleared)).toHaveLength(0);
  });

  it("disabled session restores working row and default editor", async () => {
    writeSettings({ neko: { enabled: false } });
    const h = createHarness();

    await h.emit("session_start");

    expect(h.last("setWorkingVisible")?.args).toEqual([true]);
    expect(h.last("setEditorComponent")?.args).toEqual([undefined]);
  });

  it("/neko off and /neko on flip all UI ownership atomically", async () => {
    const h = createHarness();
    await h.emit("session_start");

    await h.command("neko", "off");
    expect(h.calls("setWorkingVisible").at(-1)?.args).toEqual([true]);
    expect(h.calls("setEditorComponent").at(-1)?.args).toEqual([undefined]);
    expect(h.calls("notify").at(-1)?.args).toEqual(["Neko OFF", "info"]);

    await h.command("neko", "on");
    expect(h.calls("setWorkingVisible").at(-1)?.args).toEqual([false]);
    expect(typeof h.calls("setEditorComponent").at(-1)?.args[0]).toBe("function");
    expect(h.calls("notify").at(-1)?.args).toEqual(["Neko ON", "info"]);
  });

  it("agent run does not create extra UI timers", async () => {
    const h = createHarness();
    await h.emit("session_start");

    await h.emit("agent_start");
    await h.emit("agent_end");

    expect(timers.find((timer) => timer.kind === "interval" && timer.ms !== 90)).toBeUndefined();
  });

  it("tracks compaction, clears successful compaction timer, renders normal cat again", async () => {
    const h = createHarness();
    await h.emit("session_start");
    const editor = h.createEditor();

    await h.emit("session_before_compact");
    const compactionTimer = timers.find((timer) => timer.kind === "timeout" && timer.ms === 180_000);
    expect(compactionTimer).toBeTruthy();
    expect(stripAnsi(editor.render(40)[0])).toContain("[");

    await h.emit("session_compact");
    expect(compactionTimer!.cleared).toBe(true);
    expect(stripAnsi(editor.render(40)[0])).toContain("(=^");
  });

  it("compaction fail-safe drops stuck compacting state after timeout", async () => {
    const h = createHarness();
    await h.emit("session_start");
    const editor = h.createEditor();

    await h.emit("session_before_compact");
    const compactionTimer = timers.find((timer) => timer.kind === "timeout" && timer.ms === 180_000)!;
    expect(stripAnsi(editor.render(40)[0])).toContain("[");

    compactionTimer.fn();
    expect(stripAnsi(editor.render(40)[0])).toContain("(=^");
  });

  it("restarting compaction clears stale fail-safe timer", async () => {
    const h = createHarness();
    await h.emit("session_start");

    await h.emit("session_before_compact");
    const first = timers.find((timer) => timer.kind === "timeout" && timer.ms === 180_000)!;
    await h.emit("session_before_compact");
    const compactionTimers = timers.filter((timer) => timer.kind === "timeout" && timer.ms === 180_000);

    expect(compactionTimers).toHaveLength(2);
    expect(first.cleared).toBe(true);
    expect(compactionTimers[1]!.cleared).toBe(false);
  });

  it("shutdown restores upstream UI and clears editor, error, compaction timers", async () => {
    const h = createHarness();
    await h.emit("session_start");
    h.createEditor();
    await h.emit("agent_start");
    await h.emit("tool_result", { isError: true });
    await h.emit("session_before_compact");

    await h.emit("session_shutdown");

    expect(h.calls("setWorkingVisible").at(-1)?.args).toEqual([true]);
    expect(h.calls("setEditorComponent").at(-1)?.args).toEqual([undefined]);
    expect(timers.every((timer) => timer.cleared)).toBe(true);
  });
});