import { fileURLToPath } from "node:url"; import { fauxAssistantMessage } from "@earendil-works/pi-ai"; import { type ExtensionUIContext, initTheme, } from "@earendil-works/pi-coding-agent"; import { visibleWidth } from "@earendil-works/pi-tui"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createPiSession, type PiSession, } from "../../../test/fixture/create-pi-session.ts"; const extensionPath = fileURLToPath(new URL("../index.ts", import.meta.url)); let fixture: PiSession | undefined; async function start(keys: string[], followUpKey = "\u001b\r") { initTheme(undefined, false); fixture = await createPiSession({ extensionPaths: [extensionPath] }); const session = fixture.session; const runner = session.extensionRunner; const ui = runner.createContext().ui; const rendered: string[][] = []; let opened = 0; let blocked: { kind: string; message: string } | undefined; const custom: ExtensionUIContext["custom"] = async ( factory: Parameters[0], options?: Parameters[1], ): Promise => { opened++; blocked = options?.blocked; let result: unknown; let completed = false; const component = await factory( { requestRender() {} } as Parameters[0], ui.theme, { getKeys: (action: string) => action === "tui.select.confirm" ? ["enter"] : action === "app.message.followUp" ? ["ctrl+enter"] : ["esc"], matches: (data: string, action: string) => action === "app.message.followUp" && data === followUpKey, } as Parameters[2], (value) => { result = value; completed = true; }, ); rendered.push(component.render(32)); if (!component.handleInput) throw new Error("picker has no input handler"); for (const key of keys) { component.handleInput(key); if (completed) break; } expect(completed).toBe(true); return result as T; }; runner.setUIContext({ ...ui, custom }, "tui"); const extension = fixture.extensions[0]; const command = extension?.commands.get("note"); const shortcut = extension?.shortcuts.get("ctrl+alt+enter"); if (!command || !shortcut) throw new Error("missing Notes entrypoint"); const add = (text: string) => command.handler(`add ${text}`, runner.createCommandContext()); const open = (entrypoint: "shortcut" | "command", busy: boolean) => { const ctx = runner.createCommandContext(); ctx.isIdle = () => !busy; return entrypoint === "shortcut" ? shortcut.handler(ctx) : command.handler("sendPicker", ctx); }; const pending = () => fixture!.session.sessionManager .getBranch() .flatMap((entry) => entry.type === "custom" && entry.customType === "notes-state" ? [entry.data] : [], ); return { session, add, open, pending, rendered, opened: () => opened, blocked: () => blocked, }; } afterEach(async () => { vi.restoreAllMocks(); await fixture?.dispose(); fixture = undefined; }); describe.each(["shortcut", "command"] as const)( "Notes %s picker", (entrypoint) => { it.each([ ["Enter idle", "\r", false, undefined], ["Enter busy", "\r", true, "followUp"], ["Alt+Enter idle", "\u001b\r", false, "followUp"], ["Alt+Enter busy", "\u001b\r", true, "followUp"], ["Kitty Alt+Enter", "\u001b[13;3u", true, "followUp"], ])( "%s sends the selected note once", async (_name, key, busy, deliverAs) => { const harness = await start(["\u001b[A", key]); const send = vi .spyOn(harness.session, "sendUserMessage") .mockResolvedValue(); await harness.add("first note"); await harness.add("second note"); await harness.open(entrypoint, busy); expect(send).toHaveBeenCalledExactlyOnceWith("first note", { expandPromptTemplates: true, deliverAs, }); expect(harness.pending().at(-1)).toEqual({ op: "remove", id: 1, removedAt: expect.any(Number), }); expect( harness .pending() .filter((entry) => (entry as { op: string }).op === "remove"), ).toHaveLength(1); expect(harness.blocked()).toEqual({ kind: "question", message: "Choose a note to send", }); expect(harness.rendered[0]?.join("\n")).toContain("Send note"); expect( harness.rendered[0]?.every((line) => visibleWidth(line) <= 32), ).toBe(true); expect(fixture?.errors).toEqual([]); }, ); it("uses Pi's remapped follow-up action", async () => { const harness = await start(["\u0011"], "\u0011"); const send = vi .spyOn(harness.session, "sendUserMessage") .mockResolvedValue(); await harness.add("remapped key"); await harness.open(entrypoint, true); expect(send).toHaveBeenCalledExactlyOnceWith("remapped key", { expandPromptTemplates: true, deliverAs: "followUp", }); }); it("cancels without sending or consuming the note", async () => { const harness = await start(["\u001b"]); const send = vi .spyOn(harness.session, "sendUserMessage") .mockResolvedValue(); await harness.add("keep pending"); await harness.open(entrypoint, true); expect(send).not.toHaveBeenCalled(); expect(harness.pending()).toHaveLength(1); }); it("does not open an empty picker", async () => { const harness = await start([]); const send = vi .spyOn(harness.session, "sendUserMessage") .mockResolvedValue(); await harness.open(entrypoint, false); expect(harness.opened()).toBe(0); expect(send).not.toHaveBeenCalled(); }); }, ); describe("Notes follow-up delivery", () => { it("queues Alt+Enter through Pi without interrupting current work", async () => { const harness = await start(["\u001b\r"]); vi.spyOn(harness.session, "isStreaming", "get").mockReturnValue(true); await harness.add("later"); await harness.open("shortcut", true); await expect .poll(() => harness.session.getFollowUpMessages()) .toEqual(["later"]); expect(harness.session.getSteeringMessages()).toEqual([]); expect(fixture?.providerState.callCount).toBe(0); expect(fixture?.errors).toEqual([]); }); it("starts the selected note normally when Pi is idle", async () => { const harness = await start(["\u001b\r"]); fixture!.setResponses([fauxAssistantMessage("done")]); await harness.add("send now"); await harness.open("shortcut", false); await expect .poll(() => harness.session.getLastAssistantText()) .toBe("done"); await expect.poll(() => harness.session.isIdle).toBe(true); expect(fixture?.providerState.callCount).toBe(1); expect(harness.session.getFollowUpMessages()).toEqual([]); expect(fixture?.errors).toEqual([]); }); });