repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/neko/__tests__/lifecycle.test.ts
RawFile outline
- Handler line 15
- Timer line 16
- agentDir line 23
- projectDir line 24
- originalAgentDir line 25
- originalSetTimeout line 27
- originalClearTimeout line 28
- originalSetInterval line 29
- originalClearInterval line 30
- timers line 32
- installFakeTimers line 34
- restoreTimers line 54
- writeSettings line 61
- stripAnsi line 69
- createHarness line 73
- args line 82
- method line 82
- on line 94
- registerCommand line 99
- emit line 102
- on line 102
- calls line 112
- last line 115
- emit line 118
- command line 122
- createEditor line 125
- requestRender line 129
- beforeAll line 137
- beforeEach line 144
- afterEach line 149
- afterAll line 153
- neko lifecycle line 160
- enabled session hides built-in working row and mounts editor line 161
- disabled runtime setting restores working row and default editor line 173
- /neko off and /neko on flip all UI ownership atomically line 182
- agent run does not create extra UI timers line 199
- tracks compaction, clears successful compaction timer, renders normal cat again line 211
- compaction fail-safe drops stuck compacting state after timeout line 228
- restarting compaction clears stale fail-safe timer line 244
- shutdown restores upstream UI and clears editor, error, compaction timers line 263
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
} from "vitest";
import nekoExtension from "../index.ts";
type Handler = (event: any, ctx: any) => unknown | Promise<unknown>;
type Timer = {
fn: () => void;
ms: number;
cleared: boolean;
kind: "timeout" | "interval";
};
let agentDir = "";
let projectDir = "";
let originalAgentDir: string | undefined;
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(
runtimeSettings: Record<string, unknown> = {
neko: { enabled: true },
editorPaddingX: 1,
},
) {
writeSettings(runtimeSettings);
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(() => {
agentDir = mkdtempSync(join(tmpdir(), "neko-agent-"));
projectDir = mkdtempSync(join(tmpdir(), "neko-project-"));
originalAgentDir = process.env.PI_CODING_AGENT_DIR;
process.env.PI_CODING_AGENT_DIR = agentDir;
});
beforeEach(() => {
installFakeTimers();
writeSettings({ neko: { enabled: true }, editorPaddingX: 1 });
});
afterEach(() => {
restoreTimers();
});
afterAll(() => {
if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
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 runtime setting restores working row and default editor", async () => {
const h = createHarness({ neko: { enabled: false }, editorPaddingX: 2 });
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(compactionTimer).toBeDefined();
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,
);
expect(first).toBeDefined();
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);
});
});