import assert from "node:assert"; import { access, mkdtemp, readdir, readFile, rm, stat, utimes, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { type ExtensionContext, initTheme, } from "@earendil-works/pi-coding-agent"; import { afterEach, beforeAll, describe, it } from "vitest"; import type { MockupRequest, MockupResult } from "../mockup.ts"; import { createMockupRuntime, formatContextCapsule, mockupCacheRoot, persistMockupIteration, pruneMockupCache, } from "../mockup-tool.ts"; const request: MockupRequest = { title: "Layout", question: "Which layout?", options: [ { id: "dense", label: "Dense", html: "
dense
" }, { id: "calm", label: "Calm", html: "
calm
" }, ], }; const result: MockupResult = { action: "iterate", selected: ["dense"], notes: "keep density", annotations: [{ optionId: "dense", x: 0.25, y: 0.5, note: "tighten" }], review: { submittedAt: "2026-01-02T03:04:05.000Z", userAgent: "test-browser/1", viewport: { width: 1280, height: 720, devicePixelRatio: 1 }, }, }; const roots: string[] = []; beforeAll(() => initTheme("default", false)); afterEach(async () => { await Promise.all( roots.splice(0).map((root) => rm(root, { recursive: true })), ); }); async function temporaryRoot(): Promise { const root = await mkdtemp(path.join(tmpdir(), "pi-mockup-test-")); roots.push(root); return root; } async function exists(file: string): Promise { try { await access(file); return true; } catch { return false; } } async function size(root: string): Promise { let bytes = 0; for (const entry of await readdir(root, { withFileTypes: true })) { const child = path.join(root, entry.name); if (entry.isDirectory()) bytes += await size(child); else if (entry.isFile()) bytes += (await stat(child)).size; } return bytes; } function plainTheme() { return { fg: (_style: string, text: string) => text, bold: (text: string) => text, } as never; } function rendered(component: { render(width: number): string[] }): string { return component.render(120).join("\n"); } function renderContext(expanded: boolean, lastComponent?: unknown) { return { expanded, lastComponent, isError: false, } as never; } describe("mockup tool contract", () => { it("uses concise prompt metadata without duplicating its description", () => { const tool = createMockupRuntime({ openBrowser: false }).tool; assert.strictEqual(tool.label, "mockup"); assert.strictEqual(tool.promptSnippet, "Review HTML mockups in a browser"); assert.notStrictEqual(tool.promptSnippet, tool.description); assert.deepStrictEqual(tool.promptGuidelines, [ "Use mockup when visual comparison beats prose for UI, layout, styling, or interaction decisions.", "Pass HTML fragments only; never include , , , or .", "Provide 1-4 options; one option is valid when reviewing a single design.", "The tool owns browser review and feedback. Do not ask the user to repeat its result in chat.", "On iterate, revise the fragments and call mockup again. On accept, continue the design unless feedback requires another iteration.", ]); }); it("renders a compact call and reserves option details for expansion", () => { const tool = createMockupRuntime({ openBrowser: false }).tool; assert.ok(tool.renderCall); const collapsedComponent = tool.renderCall( request, plainTheme(), renderContext(false), ); const collapsed = rendered(collapsedComponent); const expandedComponent = tool.renderCall( request, plainTheme(), renderContext(true, collapsedComponent), ); const expanded = rendered(expandedComponent); assert.strictEqual(expandedComponent, collapsedComponent); assert.match(collapsed, /^mockup Layout · 2 options/); assert.match(collapsed, /to expand/); assert.doesNotMatch(collapsed, /Which layout\?/); assert.match(expanded, /Which layout\?/); assert.match(expanded, /dense Dense/); assert.match(expanded, /calm Calm/); assert.doesNotMatch(expanded, /
/); }); it("keeps feedback compact until expanded and renders errors", () => { const tool = createMockupRuntime({ openBrowser: false }).tool; assert.ok(tool.renderResult); const toolResult = { content: [{ type: "text" as const, text: "structured result" }], details: { ...result, sessionId: "session", chainId: "chain", iteration: 1, cacheManifest: "/cache/manifest.json", history: [], contextCapsule: "capsule", }, }; const collapsedComponent = tool.renderResult( toolResult, { expanded: false, isPartial: false }, plainTheme(), renderContext(false), ); const collapsed = rendered(collapsedComponent); const expandedComponent = tool.renderResult( toolResult, { expanded: true, isPartial: false }, plainTheme(), renderContext(true, collapsedComponent), ); const expanded = rendered(expandedComponent); assert.strictEqual(expandedComponent, collapsedComponent); assert.match(collapsed, /^↻ iterate · selected dense · 1 annotation/); assert.match(collapsed, /to expand/); assert.doesNotMatch(collapsed, /keep density|tighten|cache/); assert.match(expanded, /notes: keep density/); assert.match(expanded, /dense @ 25%,50% tighten/); assert.match(expanded, /cache: \/cache\/manifest\.json/); const accepted = rendered( tool.renderResult( { ...toolResult, details: { ...toolResult.details, action: "accept", selected: [], annotations: [], }, }, { expanded: false, isPartial: false }, plainTheme(), renderContext(false), ), ); assert.match(accepted, /^✓ accepted · selected none · 0 annotations/); const error = rendered( tool.renderResult( { content: [{ type: "text", text: "browser failed" }] }, { expanded: false, isPartial: false }, plainTheme(), { ...renderContext(false), isError: true } as never, ), ); assert.strictEqual(error.trimEnd(), "browser failed"); }); }); describe("mockup context cache", () => { it("uses the native OS cache location", () => { assert.strictEqual( mockupCacheRoot("linux", { XDG_CACHE_HOME: "/cache" }, "/home/o"), path.join("/cache", "pi", "mockups"), ); assert.strictEqual( mockupCacheRoot( "win32", { LOCALAPPDATA: "C:\\Users\\o\\AppData\\Local" }, "C:\\Users\\o", ), path.join("C:\\Users\\o\\AppData\\Local", "pi", "cache", "mockups"), ); assert.strictEqual( mockupCacheRoot("darwin", {}, "/Users/o"), path.join("/Users/o", "Library", "Caches", "pi", "mockups"), ); }); it("persists exact fragments, request, feedback, metadata, and lineage", async () => { const root = await temporaryRoot(); const sessionFile = path.join(root, "session.jsonl"); await writeFile(sessionFile, ""); const first = await persistMockupIteration(root, { sessionId: "session/one", sessionFile, chainId: "chain-one", iteration: 1, toolCallId: "tool/one", request, result, }); const second = await persistMockupIteration(root, { sessionId: "session/one", sessionFile, chainId: "chain-one", iteration: 2, toolCallId: "tool-two", request, result: { ...result, action: "accept", selected: [] }, previousManifest: first, }); assert.strictEqual( await readFile(path.join(path.dirname(first), "dense.html"), "utf8"), request.options[0].html, ); assert.deepStrictEqual( JSON.parse( await readFile(path.join(path.dirname(first), "request.json"), "utf8"), ), request, ); assert.deepStrictEqual( JSON.parse( await readFile(path.join(path.dirname(first), "feedback.json"), "utf8"), ), result, ); const manifest = JSON.parse(await readFile(second, "utf8")); assert.strictEqual(manifest.previousManifest, first); assert.strictEqual(manifest.options[0].html, "dense.html"); }); it("formats current feedback first and preserves earlier iteration context", () => { const capsule = formatContextCapsule("chain", [ { iteration: 1, question: request.question, options: request.options.map(({ id, label }) => ({ id, label })), action: "iterate", selected: ["dense"], notes: "keep density", annotations: result.annotations, cacheManifest: "/cache/one/manifest.json", }, { iteration: 2, question: "Now?", options: request.options.map(({ id, label }) => ({ id, label })), action: "accept", selected: [], notes: "none selected intentionally", annotations: [], cacheManifest: "/cache/two/manifest.json", }, ]); assert.ok( capsule.indexOf("Current: iteration 2, accept") < capsule.indexOf("Earlier iterations"), ); assert.match(capsule, /Selected: none/); assert.match(capsule, /never infer rejection from non-selection/); assert.match( capsule, /1 iterate; selected dense \(Dense\); notes: keep density/, ); assert.match(capsule, /annotation dense: tighten/); }); it("injects cached context only into its owning session", async () => { const root = await temporaryRoot(); const capsule = "owned mockup context"; const details = { ...result, sessionId: "owner", chainId: "chain", iteration: 1, history: [], contextCapsule: capsule, }; const context = (sessionId: string) => ({ isIdle: () => true, sessionManager: { getSessionId: () => sessionId, getBranch: () => [ { type: "message", message: { role: "toolResult", toolName: "mockup", details, }, }, ], }, }) as unknown as ExtensionContext; const runtime = createMockupRuntime({ cacheRoot: root, openBrowser: false, }); assert.strictEqual(runtime.contextCapsule(context("owner")), capsule); assert.strictEqual( runtime.contextCapsule(context("new-session")), undefined, ); }); it("removes orphaned and expired entries while protecting the current session", async () => { const root = await temporaryRoot(); const sessionFile = path.join(root, "live.jsonl"); await writeFile(sessionFile, ""); const live = await persistMockupIteration(root, { sessionId: "live", sessionFile, chainId: "chain", iteration: 1, toolCallId: "one", request, result, }); const orphan = await persistMockupIteration(root, { sessionId: "orphan", sessionFile: path.join(root, "missing.jsonl"), chainId: "chain", iteration: 1, toolCallId: "one", request, result, }); const old = new Date(Date.now() - 10_000); await utimes(path.dirname(live), old, old); await pruneMockupCache(root, "live", Date.now(), { ttlMs: 1, maxBytes: Number.MAX_SAFE_INTEGER, }); assert.strictEqual(await exists(live), true); assert.strictEqual(await exists(orphan), false); await pruneMockupCache(root, undefined, Date.now(), { ttlMs: 1, maxBytes: Number.MAX_SAFE_INTEGER, }); assert.strictEqual(await exists(live), false); }); it("evicts least-recently-used iterations above the size cap", async () => { const root = await temporaryRoot(); const sessionFile = path.join(root, "live.jsonl"); await writeFile(sessionFile, ""); const oldest = await persistMockupIteration(root, { sessionId: "live", sessionFile, chainId: "chain", iteration: 1, toolCallId: "old", request, result, }); const newest = await persistMockupIteration(root, { sessionId: "live", sessionFile, chainId: "chain", iteration: 2, toolCallId: "new", request, result, }); await utimes(path.dirname(oldest), new Date(1000), new Date(1000)); await utimes(path.dirname(newest), new Date(2000), new Date(2000)); const newestBytes = await size(path.dirname(newest)); await pruneMockupCache(root, undefined, Date.now(), { ttlMs: Number.MAX_SAFE_INTEGER, maxBytes: newestBytes, }); assert.strictEqual(await exists(oldest), false); assert.strictEqual(await exists(newest), true); }); });