import { mkdirSync, writeFileSync } from "node:fs"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { createTestSession, type TestSession } from "../../../test/harness"; function extPath() { return path.resolve(import.meta.dirname, "../index.ts"); } function writeMode(t: TestSession, name: string, markdown: string): string { const home = t.env.HOME; if (!home) throw new Error("missing HOME"); 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; } async function command(t: TestSession, args: string): Promise { const cmd = t.session.extensionRunner.extensions[0].commands.get("mode"); await cmd.handler(args, t.session.extensionRunner.createCommandContext()); } describe("mode harness", () => { let t: TestSession | undefined; afterEach(() => { t?.dispose(); t = undefined; }); it("loads in real Pi extension runtime", async () => { t = await createTestSession({ extensions: [extPath()] }); expect(t.session.extensionRunner.extensions).toHaveLength(1); expect(t.session.extensionRunner.extensions[0].commands.has("mode")).toBe( true, ); }); it("lists global modes", async () => { t = await createTestSession({ extensions: [extPath()] }); writeMode(t, "plan", "---\ndescription: Read-only planning\n---\nbody"); writeMode(t, "plain", "body"); await command(t, "list"); let note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]); expect(note).toContain("active: normal"); expect(note).toContain("plan — Read-only planning"); expect(note).toContain("plain"); await command(t, ""); note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]); expect(note).toContain("active: normal"); await command(t, "status"); note = String(t.events.uiCallsFor("notify").at(-1)?.args[0]); expect(note).toContain("active: normal"); }); it("switches mode and filters tools", async () => { t = await createTestSession({ extensions: [extPath()] }); writeMode( t, "plan", "---\ntools: [read, grep, missing_tool]\nreminder: Stay read-only.\n---\n# Plan\n", ); await command(t, "plan"); const notes = t.events .uiCallsFor("notify") .map((call) => String(call.args[0])); expect( notes.some((note) => note.includes("unknown tool ignored: missing_tool")), ).toBe(true); expect( notes.some((note) => note.includes("mode plan: tools read, grep")), ).toBe(false); }); it("injects active mode prompt as system prompt", async () => { t = await createTestSession({ extensions: [extPath()] }); writeMode(t, "plan", "---\nreminder: Stay read-only.\n---\n# Plan body\n"); await command(t, "plan"); const result = await t.session.extensionRunner.emitBeforeAgentStart( "hello", undefined, "BASE", {} as never, ); expect(result?.systemPrompt).toContain("BASE\n\n# Plan body"); expect(result?.systemPrompt).toContain("active_mode: plan"); expect(result?.systemPrompt).toContain( "\nStay read-only.\n", ); expect(result?.messages).toBeUndefined(); }); it("turns off and injects neutralizer", async () => { t = await createTestSession({ extensions: [extPath()] }); let result = await t.session.extensionRunner.emitBeforeAgentStart( "hello", undefined, "BASE", {} as never, ); expect(result).toBeUndefined(); writeMode(t, "plan", "# Plan body\n"); await command(t, "plan"); await command(t, "off"); result = await t.session.extensionRunner.emitBeforeAgentStart( "hello", undefined, "BASE", {} as never, ); expect(result?.systemPrompt).toContain("active_mode: normal"); expect(result?.systemPrompt).not.toContain("# Plan body"); }); it("clears widget on off and does not persist state", async () => { t = await createTestSession({ extensions: [extPath()] }); writeMode(t, "plan", "# Plan body\n"); await command(t, "plan"); const widgets = t.events.uiCallsFor("setWidget"); expect(widgets.at(-1)?.args[0]).toBe("mode"); expect(widgets.at(-1)?.args[1]).toBeTypeOf("function"); await command(t, "off"); expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([ "mode", undefined, ]); const branches = t.session.sessionManager.getBranch() as Array<{ customType?: string; }>; expect(branches.some((entry) => entry.customType === "mode-state")).toBe( false, ); }); it("off when no mode is active notifies", async () => { t = await createTestSession({ extensions: [extPath()] }); await command(t, "off"); const notes = t.events .uiCallsFor("notify") .map((call) => String(call.args[0])); expect(notes).toContain("no mode active"); expect(t.events.uiCallsFor("setWidget")).toHaveLength(1); }); it("session_start resets active mode and clears widget", async () => { t = await createTestSession({ extensions: [extPath()] }); writeMode(t, "plan", "# Plan body\n"); await command(t, "plan"); await t.session.extensionRunner.emit({ type: "session_start", reason: "reload", } as never); expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([ "mode", undefined, ]); const result = await t.session.extensionRunner.emitBeforeAgentStart( "hello", undefined, "BASE", {} as never, ); expect(result).toBeUndefined(); }); it("session_shutdown restores baseline and clears widget", async () => { t = await createTestSession({ extensions: [extPath()] }); const baselineModelId = t.session.model?.id; const baselineThinking = t.session.thinkingLevel; writeMode( t, "deep", "---\nmodel: openai/gpt-5.2-codex\nthinking: high\n---\nbody", ); await command(t, "deep"); expect(t.session.model?.id).toBe("gpt-5.2-codex"); expect(t.session.thinkingLevel).toBe("high"); t.events.uiCallsFor("setWidget").length = 0; await t.session.extensionRunner.emit({ type: "session_shutdown", reason: "quit", } as never); expect(t.session.model?.id).toBe(baselineModelId); expect(t.session.thinkingLevel).toBe(baselineThinking); expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([ "mode", undefined, ]); }); it("warns for unresolved model and still applies thinking", async () => { t = await createTestSession({ extensions: [extPath()] }); await t.session.setModel( t.session.modelRegistry.find("openai", "gpt-5.2-codex"), ); writeMode(t, "deep", "---\nmodel: nope/missing\nthinking: high\n---\nbody"); await command(t, "deep"); let latestThinking = [...t.session.sessionManager.getBranch()] .reverse() .find( (entry: { type?: string }) => entry.type === "thinking_level_change", ) as { thinkingLevel?: string } | undefined; expect(latestThinking?.thinkingLevel).toBe("high"); writeMode(t, "badref", "---\nmodel: malformed\n---\nbody"); await command(t, "badref"); const notes = t.events .uiCallsFor("notify") .map((call) => String(call.args[0])); expect( notes.some((note) => note.includes("model not found: nope/missing")), ).toBe(true); expect( notes.some((note) => note.includes("model not found: malformed")), ).toBe(true); latestThinking = [...t.session.sessionManager.getBranch()] .reverse() .find( (entry: { type?: string }) => entry.type === "thinking_level_change", ) as { thinkingLevel?: string } | undefined; expect(latestThinking?.thinkingLevel).toBe("medium"); }); it("sets resolved model and thinking", async () => { t = await createTestSession({ extensions: [extPath()] }); const baselineModelId = t.session.model?.id; const baselineThinking = t.session.thinkingLevel; writeMode( t, "deep", "---\nmodel: openai/gpt-5.2-codex\nthinking: high\n---\nbody", ); await command(t, "deep"); expect(t.session.model?.id).toBe("gpt-5.2-codex"); expect(t.session.thinkingLevel).toBe("high"); await command(t, "off"); expect(t.session.model?.id).toBe(baselineModelId); expect(t.session.thinkingLevel).toBe(baselineThinking); }); it("warns when resolved model cannot be applied", async () => { t = await createTestSession({ extensions: [extPath()] }); t.session.extensionRunner.runtime.setModel = async () => false; writeMode(t, "deep", "---\nmodel: openai/gpt-5.2-codex\n---\nbody"); await command(t, "deep"); const notes = t.events .uiCallsFor("notify") .map((call) => String(call.args[0])); expect( notes.some((note) => note.includes("model unavailable: openai/gpt-5.2-codex"), ), ).toBe(true); }); it("reload-config reports counts and warnings", async () => { t = await createTestSession({ extensions: [extPath()] }); await command(t, "reload-config"); expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([ "mode config: 0 mode(s), 0 warning(s)", "info", ]); writeMode(t, "plan", "# Plan\n"); writeMode(t, "bad id", "# Bad\n"); await command(t, "reload-config"); const calls = t.events.uiCallsFor("notify"); expect( calls.some((call) => String(call.args[0]).includes("bad id.md")), ).toBe(true); expect(calls.at(-1)?.args).toEqual([ "mode config: 1 mode(s), 1 warning(s)", "warning", ]); }); });