repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/mode/__tests__/unit.test.ts
RawFile outline
- mockTheme line 8
- identity line 19
- passthrough line 20
- HeaderFactory line 32
- expectFactory line 39
- mode pure helpers line 45
- parses valid mode markdown line 46
- splits frontmatter variants line 63
- allows empty body, empty frontmatter, and unknown keys line 78
- rejects invalid frontmatter and field types line 87
- validates ids line 128
- splits model ref at first slash line 134
- renders active prompt addition line 143
- renders normal neutralizer line 161
- keeps malformed model refs unresolved line 167
- loads mode files and reports invalid files line 176
- returns no modes when the mode directory is absent line 212
- throws non-missing mode directory read errors line 223
- mode header factory line 234
- returns undefined for null to restore built-in line 235
- returns a component factory for a mode line 239
- applies theme color and bold to banner line 248
- defaults accent to accent color line 269
- includes description and meta when present line 285
- omits description and meta when absent line 306
- mode runtime event handlers line 321
- session_shutdown with no UI does not throw line 322
- session_start resets in-memory state and publishes no header line 339
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Component, Theme, TUI } from "@earendil-works/pi-tui";
import { describe, expect, it } from "vitest";
import modeExtension, { __modeTest } from "../index.ts";
function mockTheme(
overrides: {
fg?: (color: string, text: string) => string;
bg?: (color: string, text: string) => string;
bold?: (text: string) => string;
italic?: (text: string) => string;
underline?: (text: string) => string;
inverse?: (text: string) => string;
strikethrough?: (text: string) => string;
} = {},
) {
const identity = (text: string) => text;
const passthrough = (_color: string, text: string) => text;
return {
fg: overrides.fg ?? passthrough,
bg: overrides.bg ?? passthrough,
bold: overrides.bold ?? identity,
italic: overrides.italic ?? identity,
underline: overrides.underline ?? identity,
inverse: overrides.inverse ?? identity,
strikethrough: overrides.strikethrough ?? identity,
};
}
type HeaderFactory = (
tui: TUI,
theme: Theme,
) => Component & {
dispose?(): void;
};
function expectFactory(value: HeaderFactory | undefined): HeaderFactory {
expect(value).toBeDefined();
if (!value) throw new Error("expected header factory");
return value;
}
describe("mode pure helpers", () => {
it("parses valid mode markdown", () => {
const mode = __modeTest.parseModeMarkdown(
"plan",
`---\ndescription: Read-only planning\naccent: warning\nmodel: openai/gpt-5.2-codex\nthinking: high\ntools: [read, grep]\nreminder: Stay read-only.\n---\n\n# Plan\n\nBody.\n`,
);
expect(mode).toEqual({
id: "plan",
description: "Read-only planning",
accent: "warning",
model: "openai/gpt-5.2-codex",
thinking: "high",
tools: ["read", "grep"],
reminder: "Stay read-only.",
body: "# Plan\n\nBody.\n",
});
});
it("splits frontmatter variants", () => {
expect(__modeTest.frontmatterSplit("body")).toEqual({
frontmatter: "",
body: "body",
});
expect(__modeTest.frontmatterSplit("---\nmissing close")).toEqual({
frontmatter: "",
body: "---\nmissing close",
});
expect(__modeTest.frontmatterSplit("---\na: 1\n---\nbody")).toEqual({
frontmatter: "a: 1",
body: "body",
});
});
it("allows empty body, empty frontmatter, and unknown keys", () => {
expect(
__modeTest.parseModeMarkdown("empty", "---\nunknown: ok\n---\n"),
).toEqual({
id: "empty",
body: "",
});
});
it("rejects invalid frontmatter and field types", () => {
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\n[1]\n---\nbody"),
).toThrow("mode bad: frontmatter must be a mapping");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\ndescription: 1\n---\nbody"),
).toThrow("mode bad: description must be a string");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nmodel: 1\n---\nbody"),
).toThrow("mode bad: model must be a string");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nreminder: 1\n---\nbody"),
).toThrow("mode bad: reminder must be a string");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\ntools: read\n---\nbody"),
).toThrow("mode bad: tools must be an array of strings");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\ntools: [read, 1]\n---\nbody"),
).toThrow("mode bad: tools must be an array of strings");
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nthinking: huge\n---\nbody"),
).toThrow(
"mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
);
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\nthinking: 1\n---\nbody"),
).toThrow(
"mode bad: thinking must be one of off, minimal, low, medium, high, xhigh",
);
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\naccent: hotpink\n---\nbody"),
).toThrow(
`mode bad: accent must be one of ${__modeTest.ACCENT_COLORS.join(", ")}`,
);
expect(() =>
__modeTest.parseModeMarkdown("bad", "---\naccent: 1\n---\nbody"),
).toThrow(
`mode bad: accent must be one of ${__modeTest.ACCENT_COLORS.join(", ")}`,
);
});
it("validates ids", () => {
expect(__modeTest.isValidModeId("plan_1-build")).toBe(true);
expect(__modeTest.isValidModeId("../plan")).toBe(false);
expect(__modeTest.isValidModeId("plan mode")).toBe(false);
});
it("splits model ref at first slash", () => {
expect(__modeTest.parseModelRef("openai/gpt-5.2/codex")).toEqual({
provider: "openai",
modelId: "gpt-5.2/codex",
});
expect(__modeTest.parseModelRef("missing-slash")).toBeUndefined();
expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
});
it("renders active prompt addition", () => {
const text = __modeTest.modePromptAddition({
id: "plan",
body: "# Body\n",
reminder: "Stay read-only.",
});
expect(text).toContain("# Body");
expect(text).toContain("<mode_kernel>");
expect(text).toContain("active_mode: plan");
expect(text).toContain(
"<mode_reminder>\nStay read-only.\n</mode_reminder>",
);
expect(text.indexOf("# Body")).toBeLessThan(text.indexOf("<mode_kernel>"));
expect(
__modeTest.modePromptAddition({ id: "plain", body: "# Body\n" }),
).not.toContain("<mode_reminder>");
});
it("renders normal neutralizer", () => {
expect(__modeTest.normalPromptAddition()).toBe(
`<mode_kernel>\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n</mode_kernel>`,
);
});
it("keeps malformed model refs unresolved", () => {
expect(__modeTest.parseModelRef("/model")).toBeUndefined();
expect(__modeTest.parseModelRef("provider/")).toBeUndefined();
expect(__modeTest.parseModelRef("provider/model/name")).toEqual({
provider: "provider",
modelId: "model/name",
});
});
it("loads mode files and reports invalid files", async () => {
const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
try {
const modesDir = path.join(agentDir, "modes");
mkdirSync(modesDir);
writeFileSync(path.join(modesDir, "plan.md"), "# Plan\n", "utf8");
writeFileSync(path.join(modesDir, "notes.txt"), "skip", "utf8");
writeFileSync(path.join(modesDir, "bad id.md"), "# Bad\n", "utf8");
writeFileSync(
path.join(modesDir, "bad-yaml.md"),
"---\n[\n---\n",
"utf8",
);
writeFileSync(
path.join(modesDir, "bad-field.md"),
"---\ndescription: 1\n---\n",
"utf8",
);
const loaded = await __modeTest.loadModes(agentDir);
expect([...loaded.modes.keys()]).toEqual(["plan"]);
expect(loaded.warnings).toEqual(
expect.arrayContaining([
"ignored invalid mode id: bad id.md",
"mode bad-field: description must be a string",
]),
);
expect(
loaded.warnings.some((warning) => warning.includes("bad-yaml")),
).toBe(true);
} finally {
rmSync(agentDir, { recursive: true, force: true });
}
});
it("returns no modes when the mode directory is absent", async () => {
const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
try {
const loaded = await __modeTest.loadModes(agentDir);
expect(loaded.modes.size).toBe(0);
expect(loaded.warnings).toEqual([]);
} finally {
rmSync(agentDir, { recursive: true, force: true });
}
});
it("throws non-missing mode directory read errors", async () => {
const agentDir = mkdtempSync(path.join(tmpdir(), "mode-unit-"));
try {
writeFileSync(path.join(agentDir, "modes"), "not a dir", "utf8");
await expect(__modeTest.loadModes(agentDir)).rejects.toThrow();
} finally {
rmSync(agentDir, { recursive: true, force: true });
}
});
});
describe("mode header factory", () => {
it("returns undefined for null to restore built-in", () => {
expect(__modeTest.buildHeader(null)).toBeUndefined();
});
it("returns a component factory for a mode", () => {
const factory = __modeTest.buildHeader({
id: "plan",
body: "body",
accent: "warning",
});
expect(typeof factory).toBe("function");
});
it("applies theme color and bold to banner", () => {
const factory = expectFactory(
__modeTest.buildHeader({
id: "plan",
body: "body",
accent: "warning",
}),
);
const calls: Array<[string, string]> = [];
const theme = mockTheme({
fg: (color, text) => {
calls.push(["fg", color]);
return text;
},
bold: (text) => text,
});
const component = factory({} as never, theme as never);
component.render(80);
expect(calls).toContainEqual(["fg", "warning"]);
});
it("defaults accent to accent color", () => {
const factory = expectFactory(
__modeTest.buildHeader({ id: "plan", body: "body" }),
);
const calls: string[] = [];
const theme = mockTheme({
fg: (color) => {
calls.push(color);
return "";
},
bold: (text) => text,
});
factory({} as never, theme as never).render(80);
expect(calls).toContain("accent");
});
it("includes description and meta when present", () => {
const factory = expectFactory(
__modeTest.buildHeader({
id: "plan",
body: "body",
description: "Read-only planning",
tools: ["read", "grep"],
model: "openai/gpt-5.2-codex",
thinking: "high",
}),
);
const theme = mockTheme();
const lines = factory({} as never, theme as never).render(120);
const flat = lines.join("\n");
expect(flat).toContain("MODE: plan");
expect(flat).toContain("Read-only planning");
expect(flat).toContain("tools: read, grep");
expect(flat).toContain("model: openai/gpt-5.2-codex");
expect(flat).toContain("thinking: high");
});
it("omits description and meta when absent", () => {
const factory = expectFactory(
__modeTest.buildHeader({ id: "plan", body: "body" }),
);
const theme = mockTheme();
const flat = factory({} as never, theme as never)
.render(120)
.join("\n");
expect(flat).toContain("MODE: plan");
expect(flat).not.toContain("tools:");
expect(flat).not.toContain("model:");
expect(flat).not.toContain("thinking:");
});
});
describe("mode runtime event handlers", () => {
it("session_shutdown with no UI does not throw", () => {
const events = new Map<string, (...args: unknown[]) => unknown>();
modeExtension({
events: { emit: () => undefined },
getAllTools: () => [],
on: (name: string, handler: (...args: unknown[]) => unknown) =>
events.set(name, handler),
registerCommand: () => undefined,
setActiveTools: () => undefined,
setModel: async () => true,
setThinkingLevel: () => undefined,
} as never);
expect(() =>
events.get("session_shutdown")?.({}, { hasUI: false } as never),
).not.toThrow();
});
it("session_start resets in-memory state and publishes no header", async () => {
const events = new Map<string, (...args: unknown[]) => unknown>();
const commands = new Map<
string,
{ handler: (args: string, ctx: unknown) => Promise<void> }
>();
const headers: unknown[] = [];
const ctx = {
hasUI: true,
model: undefined,
modelRegistry: { find: () => undefined },
ui: {
notify: () => undefined,
setHeader: (...args: unknown[]) => headers.push(args),
},
};
modeExtension({
events: { emit: () => undefined },
getAllTools: () => [],
on: (name: string, handler: (...args: unknown[]) => unknown) =>
events.set(name, handler),
registerCommand: (
name: string,
command: { handler: (args: string, ctx: unknown) => Promise<void> },
) => commands.set(name, command),
setActiveTools: () => undefined,
setModel: async () => true,
setThinkingLevel: () => undefined,
} as never);
await events.get("session_start")?.({ reason: "startup" }, ctx);
expect(headers).toEqual([[undefined]]);
const beforeAgent = events.get("before_agent_start")?.(
{ systemPrompt: "BASE" },
ctx,
);
expect(beforeAgent).toBeUndefined();
});
});