repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/mode/__tests__/coverage.test.ts
RawFile outline
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import modeExtension, { __modeTest } from "../index.ts";
type Fake = ReturnType<typeof fakeRuntime>;
function fakeRuntime() {
const commands = new Map<
string,
{ handler: (args: string, ctx: any) => Promise<void> }
>();
const events = new Map<string, (event: any, ctx: any) => unknown>();
const notes: Array<[string, string]> = [];
const headers: unknown[] = [];
const activeTools: string[][] = [];
let setModelResult = true;
let modelFindResult: unknown;
let thinking: string | undefined;
const ctx: any = {
hasUI: true,
model: { provider: "prov", id: "model" },
modelRegistry: { find: () => modelFindResult },
sessionManager: { getBranch: () => [] },
ui: {
notify: (message: string, severity: string) =>
notes.push([message, severity]),
setHeader: (...args: unknown[]) => headers.push(args),
},
};
modeExtension({
events: { emit: () => undefined },
getAllTools: () => [{ name: "read" }, { name: "grep" }],
on: (name: string, handler: (event: any, ctx: any) => unknown) =>
events.set(name, handler),
registerCommand: (
name: string,
command: { handler: (args: string, ctx: any) => Promise<void> },
) => commands.set(name, command),
setActiveTools: (tools: string[]) => activeTools.push(tools),
setModel: async () => setModelResult,
setThinkingLevel: (level: string) => {
thinking = level;
},
} as never);
return {
activeTools,
command: (args: string) => commands.get("mode")?.handler(args, ctx),
ctx,
events,
headers,
modelFindResult: () => modelFindResult,
notes,
setModelFindResult: (model: unknown) => {
modelFindResult = model;
},
setModelResult: (result: boolean) => {
setModelResult = result;
},
thinking: () => thinking,
};
}
async function withHome<T>(fn: (home: string) => T | Promise<T>): Promise<T> {
const oldHome = process.env.HOME;
const oldUserProfile = process.env.USERPROFILE;
const root = mkdtempSync(path.join(tmpdir(), "mode-cov-home-"));
const home = path.join(root, "home");
process.env.HOME = home;
process.env.USERPROFILE = home;
try {
return await fn(home);
} finally {
if (oldHome === undefined) delete process.env.HOME;
else process.env.HOME = oldHome;
if (oldUserProfile === undefined) delete process.env.USERPROFILE;
else process.env.USERPROFILE = oldUserProfile;
rmSync(root, { recursive: true, force: true });
}
}
function writeMode(home: string, name: string, markdown: string): string {
const dir = path.join(home, ".pi", "agent", "modes");
mkdirSync(dir, { recursive: true });
const file = path.join(dir, `${name}.md`);
writeFileSync(file, markdown, "utf8");
return file;
}
describe("mode 100% coverage gate", () => {
it("covers pure helpers", async () => {
expect(__modeTest.frontmatterSplit("body")).toEqual({
frontmatter: "",
body: "body",
});
expect(__modeTest.frontmatterSplit("---\nopen")).toEqual({
frontmatter: "",
body: "---\nopen",
});
expect(__modeTest.frontmatterSplit("---\na: 1\n---\nbody")).toEqual({
frontmatter: "a: 1",
body: "body",
});
expect(__modeTest.frontmatterSplit("---\na: 1\n---\n\nbody")).toEqual({
frontmatter: "a: 1",
body: "body",
});
expect(
__modeTest.parseModeMarkdown(
"plan",
"---\ndescription: d\naccent: warning\nmodel: p/m\nreminder: r\nthinking: high\ntools: [read]\n---\nbody",
),
).toEqual({
id: "plan",
description: "d",
accent: "warning",
model: "p/m",
reminder: "r",
thinking: "high",
tools: ["read"],
body: "body",
});
expect(__modeTest.parseModeMarkdown("empty", "---\n---\n")).toEqual({
id: "empty",
body: "",
});
expect(
__modeTest.parseModeMarkdown("comment", "---\n# comment\n---\nbody"),
).toEqual({ id: "comment", body: "body" });
expect(() => __modeTest.parseModeMarkdown("bad", "---\n[\n---\n")).toThrow(
"invalid YAML",
);
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\n[1]\n---\n"),
).toThrow("frontmatter must be a mapping");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\ndescription: 1\n---\n"),
).toThrow("description must be a string");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\naccent: nope\n---\n"),
).toThrow("accent must be one of");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\naccent: 1\n---\n"),
).toThrow("accent must be one of");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nmodel: 1\n---\n"),
).toThrow("model must be a string");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nreminder: 1\n---\n"),
).toThrow("reminder must be a string");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\n"),
).toThrow("tools must be an array of strings");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\ntools: [read, 1]\n---\n"),
).toThrow("tools must be an array of strings");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\n"),
).toThrow("thinking must be one of");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nthinking: 1\n---\n"),
).toThrow("thinking must be one of");
expect(__modeTest.isValidModeId("a_1-b")).toBe(true);
expect(__modeTest.isValidModeId("bad id")).toBe(false);
expect(__modeTest.parseModelRef("p/m/x")).toEqual({
provider: "p",
modelId: "m/x",
});
expect(__modeTest.parseModelRef("bad")).toBeUndefined();
expect(__modeTest.parseModelRef("/m")).toBeUndefined();
expect(__modeTest.parseModelRef("p/")).toBeUndefined();
expect(
__modeTest.modePromptAddition({
id: "plan",
body: "body\n",
reminder: "r",
}),
).toContain("<mode_reminder>\nr\n</mode_reminder>");
expect(
__modeTest.modePromptAddition({ id: "plan", body: "body\n" }),
).not.toContain("mode_reminder");
expect(__modeTest.normalPromptAddition()).toContain("active_mode: normal");
expect(__modeTest.buildHeader(null)).toBeUndefined();
const factory = __modeTest.buildHeader({
id: "plan",
body: "body",
description: "d",
accent: "warning",
tools: ["read"],
model: "openai/gpt",
thinking: "high",
});
expect(factory).toBeDefined();
if (!factory) throw new Error("expected factory");
const identity = (text: string) => text;
const passthrough = (_color: string, text: string) => text;
const lines = factory(
{} as never,
{ fg: passthrough, bold: identity } as never,
).render(120);
const flat = lines.join("\n");
expect(flat).toContain("MODE: plan");
expect(flat).toContain("d");
expect(flat).toContain("tools: read");
expect(flat).toContain("model: openai/gpt");
expect(flat).toContain("thinking: high");
const agentDir = mkdtempSync(path.join(tmpdir(), "mode-cov-"));
try {
const modes = path.join(agentDir, "modes");
mkdirSync(modes);
writeFileSync(path.join(modes, "plan.md"), "# Plan\n", "utf8");
writeFileSync(path.join(modes, "skip.txt"), "skip", "utf8");
writeFileSync(path.join(modes, "bad id.md"), "bad", "utf8");
writeFileSync(
path.join(modes, "bad.md"),
"---\ntools: read\n---\n",
"utf8",
);
const loaded = await __modeTest.loadModes(agentDir);
expect([...loaded.modes.keys()]).toEqual(["plan"]);
expect(loaded.warnings).toHaveLength(2);
} finally {
rmSync(agentDir, { recursive: true, force: true });
}
const missing = mkdtempSync(path.join(tmpdir(), "mode-cov-"));
try {
expect(await __modeTest.loadModes(missing)).toEqual({
modes: new Map(),
warnings: [],
});
writeFileSync(path.join(missing, "modes"), "file", "utf8");
await expect(__modeTest.loadModes(missing)).rejects.toThrow();
} finally {
rmSync(missing, { recursive: true, force: true });
}
});
it("covers extension runtime directly", async () => {
await withHome(async (home) => {
const f = fakeRuntime();
expect(
f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
).toBeUndefined();
await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
expect(f.headers.at(-1)).toEqual([undefined]);
await f.command("reload-config");
expect(f.notes.at(-1)).toEqual([
"mode config: 0 mode(s), 0 warning(s)",
"info",
]);
await f.command("");
expect(f.notes.at(-1)?.[0]).toContain("modes: none");
await f.command("off");
expect(f.notes.at(-1)).toEqual(["no mode active", "info"]);
writeMode(home, "plain", "body");
writeMode(
home,
"plan",
"---\ndescription: d\naccent: warning\ntools: [read, grep, missing]\nreminder: r\n---\nbody",
);
writeMode(home, "bad id", "bad");
await f.command("");
await f.command("status");
await f.command("list");
expect(f.notes.at(-1)?.[0]).toContain("plain");
expect(f.notes.at(-1)?.[0]).toContain("plan — d");
await f.command("reload-config");
expect(f.notes.at(-1)).toEqual([
"mode config: 2 mode(s), 1 warning(s)",
"warning",
]);
await f.command("unknown");
expect(f.notes.at(-1)).toEqual(["unknown mode: unknown", "warning"]);
await f.command("plan");
expect(f.activeTools.at(-1)).toEqual(["read", "grep"]);
expect(typeof f.headers.at(-1)?.[0]).toBe("function");
expect(
f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
).toEqual({ systemPrompt: expect.stringContaining("active_mode: plan") });
await f.command("normal");
expect(f.headers.at(-1)).toEqual([undefined]);
expect(
f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
).toEqual({
systemPrompt: expect.stringContaining("active_mode: normal"),
});
await f.command("plan");
await f.command("none");
expect(f.headers.at(-1)).toEqual([undefined]);
});
});
it("covers model and shutdown paths", async () => {
await withHome(async (home) => {
const f = fakeRuntime();
await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
f.headers.length = 0;
writeMode(home, "badref", "---\nmodel: bad\n---\nbody");
await f.command("badref");
expect(f.notes.at(-1)).toEqual([
"mode badref: model not found: bad",
"warning",
]);
writeMode(
home,
"missing",
"---\nmodel: nope/missing\nthinking: high\n---\nbody",
);
await f.command("missing");
expect(f.thinking()).toBe("high");
f.setModelFindResult({ id: "gpt", provider: "openai" });
f.setModelResult(false);
writeMode(home, "blocked", "---\nmodel: openai/gpt\n---\nbody");
await f.command("blocked");
expect(f.notes.at(-1)).toEqual([
"mode blocked: model unavailable: openai/gpt",
"warning",
]);
f.setModelResult(true);
writeMode(
home,
"deep",
"---\nmodel: openai/gpt\nthinking: high\n---\nbody",
);
await f.command("deep");
await f.events.get("session_start")?.({ reason: "reload" }, f.ctx);
expect(f.headers.at(-1)).toEqual([undefined]);
await f.events.get("session_shutdown")?.({}, f.ctx);
expect(f.headers.at(-1)).toEqual([undefined]);
});
});
it("covers no-ui session handlers", async () => {
const f: Fake = fakeRuntime();
await f.events.get("session_start")?.({ reason: "startup" }, f.ctx);
f.ctx.hasUI = false;
f.ctx.model = undefined;
await f.events.get("session_shutdown")?.({}, f.ctx);
expect(f.headers.at(-1)).toEqual([undefined]);
});
});