import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { AutocompleteItem } from "@earendil-works/pi-tui"; import { describe, expect, it } from "vitest"; import modeExtension, { __modeTest } from "../index.ts"; type Fake = ReturnType; function fakeRuntime() { const commands = new Map< string, { handler: (args: string, ctx: any) => Promise; getArgumentCompletions?: ( prefix: string, ) => AutocompleteItem[] | null | Promise; } >(); const events = new Map unknown>(); const notes: Array<[string, string]> = []; const widgets: unknown[] = []; const pickerInputs: string[][] = []; const pickerRenders: string[][][] = []; const statuses: unknown[][] = []; const shortcuts = new Map Promise }>(); const activeTools: string[][] = []; const defaultTools = ["read", "grep", "edit", "write"]; const selections: Array = []; let setModelResult = true; let modelFindResult: unknown; let thinking: string | undefined = "medium"; const ctx: any = { hasUI: true, model: { provider: "prov", id: "model" }, modelRegistry: { find: () => modelFindResult }, sessionManager: { getBranch: () => [] }, ui: { custom: async (factory: any) => { let done = false; let result: string | undefined; const component = await factory( { requestRender: () => undefined }, ctx.ui.theme, {}, (value: string | undefined) => { done = true; result = value; }, ); const renders = [component.render(80)]; for (const input of pickerInputs.shift() ?? []) { component.handleInput?.(input); renders.push(component.render(80)); if (done) break; } pickerRenders.push(renders); return result; }, notify: (message: string, severity: string) => notes.push([message, severity]), select: async () => selections.shift(), setStatus: (...args: unknown[]) => statuses.push(args), setWidget: (...args: unknown[]) => widgets.push(args), theme: { bg: (_color: string, text: string) => text, bold: (text: string) => text, fg: (_color: string, text: string) => text, }, }, }; modeExtension({ events: { emit: () => undefined }, getActiveTools: () => defaultTools, getThinkingLevel: () => thinking, getAllTools: () => [ { name: "read" }, { name: "grep" }, { name: "edit" }, { name: "write" }, ], on: (name: string, handler: (event: any, ctx: any) => unknown) => events.set(name, handler), registerCommand: ( name: string, command: { handler: (args: string, ctx: any) => Promise; getArgumentCompletions?: ( prefix: string, ) => AutocompleteItem[] | null | Promise; }, ) => commands.set(name, command), registerShortcut: ( key: string, shortcut: { handler: (ctx: any) => Promise }, ) => shortcuts.set(key, shortcut), 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), complete: (prefix: string) => commands.get("mode")?.getArgumentCompletions?.(prefix), ctx, events, pick: (...inputs: string[]) => pickerInputs.push(inputs), pickerRenders, widgets, modelFindResult: () => modelFindResult, notes, select: (choice: string | undefined) => selections.push(choice), shortcut: (key: string) => shortcuts.get(key)?.handler(ctx), shortcuts, statuses, setModelFindResult: (model: unknown) => { modelFindResult = model; }, setModelResult: (result: boolean) => { setModelResult = result; }, thinking: () => thinking, }; } async function withHome(fn: (home: string) => T | Promise): Promise { 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 coverage", () => { 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("\nr\n"); expect( __modeTest.modePromptAddition({ id: "plan", body: "body\n" }), ).not.toContain("mode_reminder"); expect(__modeTest.normalPromptAddition()).toContain("active_mode: normal"); expect(__modeTest.buildWidget(null)).toBeUndefined(); const factory = __modeTest.buildWidget({ 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.widgets.at(-1)).toEqual(["mode", 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"]); expect((await f.complete("pln"))?.[0]).toEqual({ value: "plan", label: "plan", description: "d", }); expect(await f.complete("of")).toEqual([ { value: "off", label: "off", description: "Turn mode off" }, ]); await f.command("plan"); expect(f.activeTools.at(-1)).toEqual(["read", "grep"]); await f.command("unknown"); expect(f.statuses.at(-1)).toEqual(["mode", "mode:plan"]); expect(f.widgets.at(-1)?.[0]).toBe("mode"); expect(typeof f.widgets.at(-1)?.[1]).toBe("function"); 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.activeTools.at(-1)).toEqual(["read", "grep", "edit", "write"]); expect(f.widgets.at(-1)).toEqual(["mode", undefined]); 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("next"); expect(f.activeTools.at(-1)).toEqual(["read", "grep", "edit", "write"]); expect(f.statuses.at(-1)).toEqual(["mode", "mode:plain"]); f.pick("d", "\r"); await f.command("select"); expect(f.statuses.at(-1)).toEqual(["mode", "mode:plan"]); expect(f.shortcuts.has("alt+m")).toBe(true); f.pick("p", "l", "a", "i", "\r"); await f.shortcut("alt+m"); expect(f.statuses.at(-1)).toEqual(["mode", "mode:plain"]); f.pick("o", "f", "\r"); await f.command("select"); expect(f.activeTools.at(-1)).toEqual(["read", "grep", "edit", "write"]); expect(f.thinking()).toBe("medium"); expect(f.statuses.at(-1)).toEqual(["mode", undefined]); await f.command("plan"); rmSync(path.join(home, ".pi", "agent", "modes"), { recursive: true, force: true, }); await f.command("reload-config"); expect( f.events.get("before_agent_start")?.({ systemPrompt: "BASE" }, f.ctx), ).toEqual({ systemPrompt: expect.stringContaining("active_mode: plan") }); f.pick("o", "f", "\r"); await f.command("select"); expect(f.statuses.at(-1)).toEqual(["mode", undefined]); await f.command("plan"); await f.command("none"); expect(f.widgets.at(-1)).toEqual(["mode", 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.widgets.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"); expect(f.thinking()).toBe("high"); await f.events.get("session_start")?.({ reason: "reload" }, f.ctx); expect(f.thinking()).toBe("medium"); expect(f.widgets.at(-1)).toEqual(["mode", undefined]); expect(f.statuses.at(-1)).toEqual(["mode", undefined]); await f.events.get("session_shutdown")?.({}, f.ctx); expect(f.widgets.at(-1)).toEqual(["mode", undefined]); expect(f.statuses.at(-1)).toEqual(["mode", 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.widgets.at(-1)).toEqual(["mode", undefined]); }); });