import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; import { createPiSession, type PiSession, } from "../../../test/fixture/create-pi-session.ts"; import intellijExtension from "../index.ts"; import { launchIdea } from "../launch.ts"; vi.mock("../launch.ts", () => ({ launchIdea: vi.fn().mockResolvedValue(undefined), })); let session: PiSession | undefined; let root: string | undefined; afterEach(async () => { await session?.dispose(); session = undefined; if (root) rmSync(root, { recursive: true, force: true }); root = undefined; vi.mocked(launchIdea).mockReset().mockResolvedValue(undefined); }); async function setup(project: boolean) { root = mkdtempSync(join(tmpdir(), "intellij-launch-")); if (project) mkdirSync(join(root, ".idea")); const cwd = join(root, "src", "nested"); mkdirSync(cwd, { recursive: true }); session = await createPiSession({ cwd, extensionFactories: [intellijExtension], }); const ui = { ...session.session.extensionRunner.getUIContext() }; const notify = vi.spyOn(ui, "notify"); session.session.extensionRunner.setUIContext(ui, "print"); return notify; } it("launches nearest .idea root explicitly, without needing an MCP URL or changing cwd", async () => { await setup(true); expect(launchIdea).not.toHaveBeenCalled(); await session!.session.prompt("/intellij launch"); expect(launchIdea).toHaveBeenCalledExactlyOnceWith(root); expect(session!.session.extensionRunner.createContext().cwd).toBe( join(root!, "src", "nested"), ); expect(session!.errors).toEqual([]); }); it("does not launch without a project or for unsupported commands", async () => { const notify = await setup(false); await session!.session.prompt("/intellij launch"); expect(notify).toHaveBeenCalledWith( expect.stringContaining("No IntelliJ project"), "error", ); await session!.session.prompt("/intellij connect"); expect(notify).toHaveBeenCalledWith("Usage: /intellij launch", "error"); expect(launchIdea).not.toHaveBeenCalled(); }); it("reports launcher failures without failing the session", async () => { const notify = await setup(true); vi.mocked(launchIdea).mockRejectedValueOnce(new Error("launcher missing")); await session!.session.prompt("/intellij launch"); expect(notify).toHaveBeenCalledWith("launcher missing", "error"); expect(session!.errors).toEqual([]); });