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 nowEntry = (data: unknown) => ({ type: "custom", customType: "mode-state", data, }); describe("mode pure helpers", () => { it("parses valid mode markdown", () => { const mode = __modeTest.parseModeMarkdown( "plan", `---\ndescription: Read-only planning\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", 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", ); }); 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(""); expect(text).toContain("active_mode: plan"); expect(text).toContain( "\nStay read-only.\n", ); expect(text.indexOf("# Body")).toBeLessThan(text.indexOf("")); expect( __modeTest.modePromptAddition({ id: "plain", body: "# Body\n" }), ).not.toContain(""); }); it("renders normal neutralizer", () => { expect(__modeTest.normalPromptAddition()).toBe( `\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n`, ); }); it("restores latest mode state from current branch entries", () => { expect( __modeTest.latestModeState([ { type: "message", customType: "mode-state", data: {} }, nowEntry({ schemaVersion: 1, activeMode: "plan", neutralize: false, reason: "switch", }), ]), ).toEqual({ schemaVersion: 1, activeMode: "plan", neutralize: false, reason: "switch", }); expect( __modeTest.latestModeState([ nowEntry(null), nowEntry({ broken: true }), nowEntry({ schemaVersion: 1, activeMode: null, neutralize: true, reason: "compaction", }), ]), ).toEqual({ schemaVersion: 1, activeMode: null, neutralize: true, reason: "compaction", }); const badReasons = ["switch", "off", "compaction"].map((reason) => nowEntry({ schemaVersion: 2, activeMode: "plan", neutralize: false, reason, }), ); expect(__modeTest.latestModeState(badReasons)).toBeUndefined(); }); 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 }); } }); it("renders status text", () => { expect(__modeTest.statusText("plan")).toBe("MODE plan"); expect(__modeTest.statusText(null)).toBeUndefined(); }); it("handles no-UI shutdown and model-less compaction", () => { const events = new Map unknown>(); const entries: unknown[] = []; modeExtension({ appendEntry: (_type: string, data: unknown) => entries.push(data), 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(); events.get("session_compact")?.({ compactionEntry: { id: "c1" } }, { model: undefined, } as never); expect(entries).toEqual([ { schemaVersion: 1, activeMode: null, neutralize: false, reason: "compaction", compactionEntryId: "c1", }, ]); }); });