repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/mode/__tests__/coverage.test.ts
RawFile outline
- custom line 7
- Fake line 13
- fakeRuntime line 15
- handler line 18
- customType line 21
- data line 21
- type line 21
- handler line 50
- withHome line 76
- writeMode line 94
- mode 100% coverage gate line 102
- covers pure helpers line 103
- covers extension runtime directly line 271
- covers model, restore, compaction, shutdown line 335
- covers no-ui direct events line 390
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";
const custom = (data: unknown) => ({
type: "custom",
customType: "mode-state",
data,
});
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 entries: Array<{ type: string; customType: string; data: unknown }> =
[];
const notes: Array<[string, string]> = [];
const statuses: Array<[string, string | undefined]> = [];
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: () => entries },
ui: {
notify: (message: string, severity: string) =>
notes.push([message, severity]),
setStatus: (key: string, value: string | undefined) =>
statuses.push([key, value]),
},
};
modeExtension({
appendEntry: (type: string, data: unknown) =>
entries.push({ type: "custom", customType: type, data }),
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,
entries,
events,
notes,
setModelFindResult: (model: unknown) => {
modelFindResult = model;
},
setModelResult: (result: boolean) => {
setModelResult = result;
},
statuses,
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\nmodel: p/m\nreminder: r\nthinking: high\ntools: [read]\n---\nbody",
),
).toEqual({
id: "plan",
description: "d",
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", "---\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.latestModeState([
{ type: "message", customType: "mode-state", data: {} },
{ type: "custom", customType: "other", data: {} },
custom({ broken: true }),
custom({
schemaVersion: 1,
activeMode: "plan",
neutralize: false,
reason: "switch",
}),
]),
).toEqual({
schemaVersion: 1,
activeMode: "plan",
neutralize: false,
reason: "switch",
});
expect(
__modeTest.latestModeState([
{ type: "custom", customType: "other", data: {} },
]),
).toBeUndefined();
expect(
__modeTest.latestModeState([
custom(null),
custom({
schemaVersion: 2,
activeMode: "plan",
neutralize: false,
reason: "switch",
}),
]),
).toBeUndefined();
expect(
__modeTest.latestModeState([
custom({
schemaVersion: 1,
activeMode: null,
neutralize: true,
reason: "compaction",
}),
]),
).toEqual({
schemaVersion: 1,
activeMode: null,
neutralize: true,
reason: "compaction",
});
expect(__modeTest.statusText("plan")).toBe("MODE plan");
expect(__modeTest.statusText(null)).toBeUndefined();
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);
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.entries.at(-1)?.data).toMatchObject({
activeMode: null,
neutralize: false,
reason: "off",
provider: "prov",
model: "model",
});
writeMode(home, "plain", "body");
writeMode(
home,
"plan",
"---\ndescription: d\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(f.statuses.at(-1)).toEqual(["mode", "MODE plan"]);
expect(
f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx),
).toEqual({ systemPrompt: expect.stringContaining("active_mode: plan") });
await f.command("normal");
expect(f.statuses.at(-1)).toEqual(["mode", 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.entries.at(-1)?.data).toMatchObject({
activeMode: null,
neutralize: true,
reason: "off",
});
});
});
it("covers model, restore, compaction, shutdown", async () => {
await withHome(async (home) => {
const f = fakeRuntime();
writeMode(home, "badref", "---\nmodel: bad\n---\nbody");
await f.command("badref");
expect(f.notes.at(-2)).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(-2)).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.statuses.at(-1)).toEqual(["mode", "MODE deep"]);
const gone = writeMode(home, "gone", "body");
await f.command("gone");
rmSync(gone);
await f.events.get("session_start")?.({ reason: "reload" }, f.ctx);
expect(f.entries.at(-1)?.data).toMatchObject({
activeMode: null,
neutralize: true,
reason: "off",
});
f.events.get("session_compact")?.(
{ compactionEntry: { id: "c1" } },
f.ctx,
);
expect(f.entries.at(-1)?.data).toMatchObject({
reason: "compaction",
compactionEntryId: "c1",
});
f.events.get("session_shutdown")?.({}, f.ctx);
expect(f.statuses.at(-1)).toEqual(["mode", undefined]);
});
});
it("covers no-ui direct events", () => {
const f: Fake = fakeRuntime();
f.ctx.hasUI = false;
f.ctx.model = undefined;
f.events.get("session_shutdown")?.({}, f.ctx);
f.events.get("session_compact")?.({ compactionEntry: { id: "c1" } }, f.ctx);
expect(f.entries.at(-1)?.data).toEqual({
schemaVersion: 1,
activeMode: null,
neutralize: false,
reason: "compaction",
compactionEntryId: "c1",
});
});
});