feat(the-system): persist and drive mockup iterations
14e8f104408365bf742139172724a39c61e9618d
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
- Parent 1: af24d79b3f32
bugabingas pi extensions
14e8f104408365bf742139172724a39c61e9618d
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
+1192 / −133 text lines
+83 / −22 text lines
test("renders options and returns browser feedback", async ({ page }) => { { openBrowser: false }, const stableUrl = page.url(); const annotationGeometry = await fragment.evaluate((element) => { const fragmentRect = element.getBoundingClientRect(); const bubbleRect = element.querySelector(".pin-bubble")?.getBoundingClientRect(); const pinRect = element.querySelector(".pin")?.getBoundingClientRect(); return { clientWidth: element.clientWidth, scrollWidth: element.scrollWidth, bubbleWithin: !!bubbleRect && bubbleRect.left >= fragmentRect.left && bubbleRect.right <= fragmentRect.right, pinWithin: !!pinRect && pinRect.left >= fragmentRect.left && pinRect.right <= fragmentRect.right, }; }); expect(annotationGeometry).toEqual({ clientWidth: annotationGeometry.clientWidth, scrollWidth: annotationGeometry.clientWidth, bubbleWithin: true, pinWithin: true, }); annotations: [ annotations: [{ optionId: "dense", note: "tighten spacing" }], review: { viewport: { devicePixelRatio: 1 } }, }); server.progress("Pi is working on the revision."); await expect(page.locator("#progress-title")).toHaveText( "Pi is working on the revision.", ); await page.getByRole("button", { name: "Stop agent" }).click(); await expect.poll(() => aborts).toBe(1); const secondSubmission = server.present({ title: "Layout revision", question: "Does the denser revision work?", options: [ expect(result.annotations[0].x).toBeGreaterThan(0); expect(result.annotations[0].x).toBeLessThanOrEqual(1); expect(result.annotations[0].y).toBeGreaterThan(0); expect(result.annotations[0].y).toBeLessThanOrEqual(1); await expect( page.getByRole("heading", { name: "Layout revision" }), ).toBeVisible(); expect(page.url()).toBe(stableUrl); await expect(page.getByText("Revised dense content")).toBeVisible(); await page.locator("#accept").click(); await expect(page.locator("#progress-title")).toHaveText( "Accepted. You can close this tab.", ); const second = await secondSubmission; expect(second).toMatchObject({ action: "accept", selected: [], notes: "", annotations: [], });new file mode 100644+270 / −0 text lines
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 } from "@earendil-works/pi-coding-agent";import { afterEach, 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: "<section>dense</section>" }, { id: "calm", label: "Calm", html: "<section>calm</section>" }, ],};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[] = [];afterEach(async () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true })));});async function temporaryRoot(): Promise<string> { const root = await mkdtemp(path.join(tmpdir(), "pi-mockup-test-")); roots.push(root); return root;}async function exists(file: string): Promise<boolean> { try { await access(file); return true; } catch { return false; }}async function size(root: string): Promise<number> { 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;}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); });});+115 / −8 text lines
it("keeps annotations inside the nearest fragment edge", () => { const html = renderMockupPage(baseRequest, "tok"); assert.match(html, /if \(a\.x > 0\.5\) bubble\.style\.right/); assert.match(html, /else bubble\.style\.left/); assert.match(html, /button\.style\.left = "clamp\(14px,/); }); it("uses explorer directly on win32 to avoid cmd flashes", () => { it("uses the native URL handler directly on win32 without cmd", () => { client, client, client, assert.deepStrictEqual(result, { action: "iterate", selected: ["a"], notes: "keep A, denser drawer", annotations: [{ optionId: "a", x: 0.25, y: 0.5, note: "tighten" }], assert.deepStrictEqual( { action: result.action, selected: result.selected, notes: result.notes, annotations: result.annotations, userAgent: result.review.userAgent, viewport: result.review.viewport, }, { action: "iterate", selected: ["a"], notes: "keep A, denser drawer", annotations: [ { optionId: "a", x: 0.25, y: 0.5, note: "tighten" }, ], userAgent: client.userAgent, viewport: client.viewport, }, ); assert.match(result.review.submittedAt, /^\d{4}-\d{2}-\d{2}T/); } finally { server.result.catch(() => undefined); server.close("test"); } }); it("keeps one URL across iterations and accepts no selection", async () => { const server = await startMockupServer(baseRequest, { openBrowser: false }); try { const first = server.result; const firstResponse = await fetch(new URL("/api/submit", server.url), { method: "POST", headers: { Authorization: `Bearer ${server.token}`, "Content-Type": "application/json", }, body: JSON.stringify({ action: "iterate", selected: ["a"], notes: "try again", annotations: [], client, }), assert.strictEqual(firstResponse.status, 200); assert.strictEqual((await first).action, "iterate"); const stableUrl = server.url; const second = server.present({ ...baseRequest, question: "Is this revision right?", }); assert.strictEqual(server.url, stableUrl); const page = await fetch(server.url); assert.match(await page.text(), /Is this revision right\?/); const secondResponse = await fetch(new URL("/api/submit", server.url), { method: "POST", headers: { Authorization: `Bearer ${server.token}`, "Content-Type": "application/json", }, body: JSON.stringify({ action: "accept", selected: [], notes: "none works", annotations: [], client, }), }); assert.strictEqual(secondResponse.status, 200); assert.deepStrictEqual((await second).selected, []); } finally { server.result.catch(() => undefined); server.close("test"); } }); it("authenticates browser requests that stop active Pi work", async () => { let aborts = 0; const server = await startMockupServer(baseRequest, { openBrowser: false, abortAgent: () => { aborts++; return true; }, }); try { const unauthorized = await fetch(new URL("/api/abort", server.url), { method: "POST", }); assert.strictEqual(unauthorized.status, 401); const stopped = await fetch(new URL("/api/abort", server.url), { method: "POST", headers: { Authorization: `Bearer ${server.token}` }, }); assert.strictEqual(stopped.status, 200); assert.strictEqual(aborts, 1);+15 / −4 text lines
import { createMockupTool } from "./mockup-tool.js";import { createMockupRuntime } from "./mockup-tool.js"; const mockup = createMockupRuntime(); mockup.remember(ctx); mockup.shutdown(ctx); mockup.agentWorking(ctx); return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) }; pi.on("agent_settled", (_event, ctx) => mockup.agentSettled(ctx));+10 / −0 text lines
+498 / −8 text lines
import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";import type { MockupResult } from "./mockup.js"; "Show HTML-fragment mockup options in a browser and return selected options, notes, annotations, and accept/iterate action.";export type MockupHistoryEntry = { iteration: number; question: string; options: Array<{ id: string; label: string }>; action: MockupResult["action"]; selected: string[]; notes: string; annotations: MockupResult["annotations"]; cacheManifest?: string;};export type MockupToolDetails = MockupResult & { sessionId: string; chainId: string; iteration: number; cacheManifest?: string; cacheError?: string; history: MockupHistoryEntry[]; contextCapsule: string;};type ActiveChain = { server: MockupServer; chainId: string;};type RuntimeOptions = { cacheRoot?: string; openBrowser?: boolean;};export function createMockupRuntime(options: RuntimeOptions = {}) { const active = new Map<string, ActiveChain>(); const contexts = new Map<string, ExtensionContext>(); const cacheRoot = options.cacheRoot ?? mockupCacheRoot(); const remember = (ctx: ExtensionContext): string => { const sessionId = ctx.sessionManager.getSessionId(); contexts.set(sessionId, ctx); return sessionId; }; const abortAgent = (sessionId: string): boolean => { const ctx = contexts.get(sessionId); if (!ctx || ctx.isIdle()) return false; try { ctx.abort(); return true; } catch { return false; } }; const schedulePrune = (protectedSessionId?: string): void => { const timer = setTimeout(() => { void pruneMockupCache(cacheRoot, protectedSessionId).catch((error) => console.error("Mockup cache cleanup failed:", error), ); }, 0); timer.unref?.(); }; const tool = defineTool({ const details = result.details as Partial<MockupResult> | undefined; const details = result.details as Partial<MockupToolDetails> | undefined; const summary = `${details.action ?? "submitted"} · ${(details.selected ?? []).join(", ") || "none"} · ${annotations.length} annotation${annotations.length === 1 ? "" : "s"}`; if (!context.expanded) return new Text(theme.fg("dim", summary), 0, 0); async execute(_toolCallId, params, signal, _onUpdate, ctx) { return (await import("./mockup.js")).executeMockup(params, signal, ctx); async execute(toolCallId, params, signal, _onUpdate, ctx) { const request = validateMockupRequest(params); const sessionId = remember(ctx); const previous = latestMockupDetails(ctx); const continuing = previous?.sessionId === sessionId && previous.action === "iterate"; let chain = active.get(sessionId); const created = !chain; if (!chain) { chain = { chainId: continuing ? previous.chainId : randomUUID(), server: await startMockupServer(request, { openBrowser: options.openBrowser ?? process.env.PI_MOCKUP_NO_OPEN !== "1", abortAgent: () => abortAgent(sessionId), }), }; active.set(sessionId, chain); if (ctx.hasUI) ctx.ui.notify(`Mockup open: ${chain.server.url}`, "info"); } const iteration = continuing ? previous.iteration + 1 : 1; const history = continuing ? previous.history : []; const resultPromise = created ? chain.server.result : chain.server.present(request); try { const result = await abortable(resultPromise, signal, () => chain?.server.close("aborted"), ); let cacheManifest: string | undefined; let cacheError: string | undefined; try { cacheManifest = await persistMockupIteration(cacheRoot, { sessionId, sessionFile: ctx.sessionManager.getSessionFile(), chainId: chain.chainId, iteration, toolCallId, request, result, previousManifest: continuing ? previous.cacheManifest : undefined, }); } catch (error) { cacheError = error instanceof Error ? error.message : String(error); if (ctx.hasUI) ctx.ui.notify(`Mockup cache unavailable: ${cacheError}`, "warning"); } const current = historyEntry(iteration, request, result, cacheManifest); const nextHistory = [...history, current]; const contextCapsule = formatContextCapsule( chain.chainId, nextHistory, cacheError, ); const details: MockupToolDetails = { ...result, sessionId, chainId: chain.chainId, iteration, cacheManifest, cacheError, history: nextHistory, contextCapsule, }; if (result.action === "accept") { chain.server.close("accepted"); active.delete(sessionId); schedulePrune(sessionId); } return { content: [ { type: "text" as const, text: JSON.stringify({ action: result.action, selected: result.selected, notes: result.notes, annotations: result.annotations, cacheManifest, contextCapsule, }), }, ], details, }; } catch (error) { chain.server.close("failed"); active.delete(sessionId); schedulePrune(sessionId); throw error; } return { tool, remember, contextCapsule(ctx: ExtensionContext): string | undefined { const sessionId = remember(ctx); const details = latestMockupDetails(ctx); return details?.sessionId === sessionId ? details.contextCapsule : undefined; }, agentWorking(ctx: ExtensionContext): void { const sessionId = remember(ctx); active.get(sessionId)?.server.progress("Pi is working on the revision."); }, agentSettled(ctx: ExtensionContext): void { const sessionId = remember(ctx); active.get(sessionId)?.server.settled(); }, shutdown(ctx: ExtensionContext): void { const sessionId = ctx.sessionManager.getSessionId(); active.get(sessionId)?.server.close("session ended"); active.delete(sessionId); contexts.delete(sessionId); schedulePrune(); }, };}function latestMockupDetails( ctx: ExtensionContext,): MockupToolDetails | undefined { const branch = ctx.sessionManager.getBranch(); for (let index = branch.length - 1; index >= 0; index--) { const entry = branch[index] as unknown as Record<string, unknown>; if (entry.type !== "message") continue; const message = entry.message; if (!isRecord(message)) continue; if (message.role !== "toolResult" || message.toolName !== "mockup") continue; const details = message.details; if (!isRecord(details) || typeof details.contextCapsule !== "string") return undefined; return details as unknown as MockupToolDetails; } return undefined;}function historyEntry( iteration: number, request: MockupRequest, result: MockupResult, cacheManifest?: string,): MockupHistoryEntry { return { iteration, question: request.question, options: request.options.map(({ id, label }) => ({ id, label })), action: result.action, selected: result.selected, notes: result.notes, annotations: result.annotations, cacheManifest, };}export function formatContextCapsule( chainId: string, history: MockupHistoryEntry[], cacheError?: string,): string { const latest = history.at(-1); if (!latest) return ""; const lines = [ "Mockup context capsule", `Chain: ${chainId}`, `Current: iteration ${latest.iteration}, ${latest.action}`, `Question: ${latest.question}`, `Selected: ${selectedLabels(latest)}`, `Notes: ${latest.notes || "none"}`, ]; if (latest.annotations.length === 0) lines.push("Annotations: none"); else { lines.push("Annotations:"); for (const annotation of latest.annotations) lines.push( `- ${annotation.optionId} @ ${Math.round(annotation.x * 100)}%,${Math.round(annotation.y * 100)}%: ${annotation.note}`, ); } lines.push( "Rejected rationale: not recorded separately; never infer rejection from non-selection.", `Cache manifest: ${latest.cacheManifest ?? `unavailable${cacheError ? ` (${cacheError})` : ""}`}`, ); if (history.length > 1) { lines.push("Earlier iterations, newest first:"); for (const entry of history.slice(0, -1).reverse()) { lines.push( `- ${entry.iteration} ${entry.action}; selected ${selectedLabels(entry)}; notes: ${entry.notes || "none"}`, ); for (const annotation of entry.annotations) lines.push(` annotation ${annotation.optionId}: ${annotation.note}`); if (entry.cacheManifest) lines.push(` cache: ${entry.cacheManifest}`); } } return lines.join("\n");}function selectedLabels(entry: MockupHistoryEntry): string { if (entry.selected.length === 0) return "none"; const labels = new Map(entry.options.map((option) => [option.id, option.label])); return entry.selected .map((id) => `${id} (${labels.get(id) ?? id})`) .join(", ");}export function mockupCacheRoot( platform: NodeJS.Platform = process.platform, env: NodeJS.ProcessEnv = process.env, home: string = homedir(),): string { if (platform === "win32") return path.join( env.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), "pi", "cache", "mockups", ); if (platform === "darwin") return path.join(home, "Library", "Caches", "pi", "mockups"); return path.join(env.XDG_CACHE_HOME ?? path.join(home, ".cache"), "pi", "mockups");}type PersistInput = { sessionId: string; sessionFile: string | undefined; chainId: string; iteration: number; toolCallId: string; request: MockupRequest; result: MockupResult; previousManifest?: string;};export async function persistMockupIteration( root: string, input: PersistInput,): Promise<string> { const sessionDir = path.join(root, safeSegment(input.sessionId)); const iterationDir = path.join( sessionDir, safeSegment(input.chainId), `${String(input.iteration).padStart(3, "0")}-${safeSegment(input.toolCallId)}`, ); await mkdir(iterationDir, { recursive: true }); await Promise.all([ writeFile( path.join(sessionDir, "session.json"), `${JSON.stringify({ sessionId: input.sessionId, sessionFile: input.sessionFile }, null, 2)}\n`, ), writeFile( path.join(iterationDir, "request.json"), `${JSON.stringify(input.request, null, 2)}\n`, ), writeFile( path.join(iterationDir, "feedback.json"), `${JSON.stringify(input.result, null, 2)}\n`, ), ...input.request.options.map((option) => writeFile(path.join(iterationDir, `${safeSegment(option.id)}.html`), option.html), ), ]); const manifest = path.join(iterationDir, "manifest.json"); await writeFile( manifest, `${JSON.stringify( { version: 1, recordedAt: new Date().toISOString(), sessionId: input.sessionId, chainId: input.chainId, iteration: input.iteration, toolCallId: input.toolCallId, previousManifest: input.previousManifest, request: "request.json", feedback: "feedback.json", options: input.request.options.map((option) => ({ id: option.id, label: option.label, html: `${safeSegment(option.id)}.html`, })), }, null, 2, )}\n`, ); return manifest;}export async function pruneMockupCache( root: string, protectedSessionId?: string, now = Date.now(), policy: { ttlMs: number; maxBytes: number } = { ttlMs: CACHE_TTL_MS, maxBytes: CACHE_LIMIT_BYTES, },): Promise<void> { const sessions = await directories(root); const candidates: Array<{ path: string; modified: number; bytes: number }> = []; for (const session of sessions) { if (session.name === safeSegment(protectedSessionId ?? "")) continue; const metadataPath = path.join(session.path, "session.json"); const metadata = await readJson(metadataPath); if ( isRecord(metadata) && typeof metadata.sessionFile === "string" && !(await exists(metadata.sessionFile)) ) { await rm(session.path, { recursive: true, force: true }); continue; } for (const chain of await directories(session.path)) { for (const iteration of await directories(chain.path)) { const info = await stat(iteration.path); if (now - info.mtimeMs >= policy.ttlMs) { await rm(iteration.path, { recursive: true, force: true }); continue; } candidates.push({ path: iteration.path, modified: info.mtimeMs, bytes: await directorySize(iteration.path), }); } } } let total = candidates.reduce((sum, candidate) => sum + candidate.bytes, 0); for (const candidate of candidates.sort( (left, right) => left.modified - right.modified, )) { if (total <= policy.maxBytes) break; await rm(candidate.path, { recursive: true, force: true }); total -= candidate.bytes; }}async function directories( root: string,): Promise<Array<{ name: string; path: string }>> { try { return (await readdir(root, { withFileTypes: true })) .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink()) .map((entry) => ({ name: entry.name, path: path.join(root, entry.name) })); } catch (error) { if (isNotFound(error)) return []; throw error; }}async function directorySize(root: string): Promise<number> { let bytes = 0; for (const entry of await readdir(root, { withFileTypes: true })) { if (entry.isSymbolicLink()) continue; const child = path.join(root, entry.name); if (entry.isDirectory()) bytes += await directorySize(child); else if (entry.isFile()) bytes += (await stat(child)).size; } return bytes;}async function readJson(file: string): Promise<unknown> { try { return JSON.parse(await readFile(file, "utf8")); } catch (error) { if (isNotFound(error)) return undefined; throw error; }}async function exists(file: string): Promise<boolean> { try { await access(file); return true; } catch { return false; }}function safeSegment(value: string): string { return value.replaceAll(/[^a-zA-Z0-9._-]/g, "_") || "unknown";}function isRecord(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value);}function isNotFound(error: unknown): boolean { return isRecord(error) && error.code === "ENOENT";}function abortable<T>( promise: Promise<T>, signal: AbortSignal | undefined, abort: () => void,): Promise<T> { if (!signal) return promise; if (signal.aborted) { abort(); return Promise.reject(new Error("mockup aborted")); } return new Promise((resolve, reject) => { const onAbort = () => { abort(); reject(new Error("mockup aborted")); }; signal.addEventListener("abort", onAbort, { once: true }); promise .then(resolve, reject) .finally(() => signal.removeEventListener("abort", onAbort)); });+201 / −91 text lines
return `${path} must be an HTML fragment, not a full document. Remove <!doctype>, <html>, <head>, <body>; keep only content for the card.`;export async function executeMockup( params: unknown, signal: AbortSignal | undefined, ctx: { hasUI: boolean; ui: { notify(message: string, level: "info"): void } },) { const request = validateMockupRequest(params); const server = await startMockupServer(request, { openBrowser: process.env.PI_MOCKUP_NO_OPEN !== "1", }); if (ctx.hasUI) ctx.ui.notify(`Mockup open: ${server.url}`, "info"); try { const result = await abortable(server.result, signal, () => server.close("aborted"), ); return { content: [{ type: "text" as const, text: JSON.stringify(result) }], details: result, }; } finally { server.close("done"); }} options: { openBrowser?: boolean } = {}, options: { openBrowser?: boolean; abortAgent?: () => boolean } = {}, const normalized = validateMockupRequest(request); let current = validateMockupRequest(request); const clients = new Set<ServerResponse>(); timeout = undefined; } function armRoundTimeout(): void { clearRoundTimeout(); timeout = setTimeout(() => terminate(new Error("mockup timed out waiting for browser Submit")), DEFAULT_TIMEOUT_MS); timeout.unref(); } function broadcast(type: string, data: unknown): void { const event = `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; for (const client of clients) client.write(event); } function finish(value: MockupResult): void { if (closed || !waiting) return; waiting = false; clearRoundTimeout(); resolveResult(value); } function terminate(error: Error): void { if (closed) return; closed = true; clearRoundTimeout(); broadcast("progress", { message: error.message, terminal: true }); for (const client of clients) client.end(); clients.clear(); clients, timeout = setTimeout( () => fail(new Error("mockup timed out waiting for browser Submit")), DEFAULT_TIMEOUT_MS, ); timeout.unref(); armRoundTimeout(); present(request: MockupRequest) { if (closed) throw new Error("mockup server is closed"); if (waiting) throw new Error("mockup already awaits browser feedback"); current = validateMockupRequest(request); result = round(); waiting = true; stopRequested = false; armRoundTimeout(); broadcast("revision", {}); return result; }, progress(message: string) { if (!closed) broadcast("progress", { message, terminal: false }); }, settled() { if (closed || waiting) return; broadcast("progress", { message: stopRequested ? "Agent stopped." : "Agent finished without another mockup.", terminal: true, }); }, if (finished) return; finished = true; if (timeout) clearTimeout(timeout); server.close(); rejectResult(new Error(`mockup closed: ${reason}`)); terminate(new Error(`mockup closed: ${reason}`));<section id="progress" class="progress" hidden aria-live="polite"> <div class="progress-card"> <div class="spinner" aria-hidden="true"></div> <div> <h2 id="progress-title">Feedback received</h2> <p id="progress-time">0s elapsed</p> </div> <button id="stop-agent" type="button" class="secondary">Stop agent</button> </div></section> clients: Set<ServerResponse>; abortAgent(): boolean; if (req.method === "GET" && url.pathname === "/api/events") { res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store", Connection: "keep-alive", }); res.write(": connected\n\n"); ctx.clients.add(res); res.once("close", () => ctx.clients.delete(res)); return; } return { action, selected, notes, annotations }; const client = isRecord(value.client) ? value.client : {}; const viewport = isRecord(client.viewport) ? client.viewport : {}; const review = { submittedAt: new Date().toISOString(), userAgent: optionalString(client.userAgent, "client.userAgent") ?? "", viewport: { width: nonNegativeNumber(viewport.width, "client.viewport.width"), height: nonNegativeNumber(viewport.height, "client.viewport.height"), devicePixelRatio: nonNegativeNumber( viewport.devicePixelRatio, "client.viewport.devicePixelRatio", ), }, }; return { action, selected, notes, annotations, review }; return [{ command: "explorer.exe", args: [url], windowsHide: true }];function abortable<T>( promise: Promise<T>, signal: AbortSignal | undefined, abort: () => void,): Promise<T> { if (!signal) return promise; if (signal.aborted) { abort(); return Promise.reject(new Error("mockup aborted")); } return new Promise((resolve, reject) => { const onAbort = () => { abort(); reject(new Error("mockup aborted")); }; signal.addEventListener("abort", onAbort, { once: true }); promise .then(resolve, reject) .finally(() => signal.removeEventListener("abort", onAbort)); });} if ( typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1 ) throw new Error(`${name} must be a number between 0 and 1`); const number = nonNegativeNumber(value, name); if (number > 1) throw new Error(`${name} must be a number between 0 and 1`); return number;}function nonNegativeNumber(value: unknown, name: string): number { if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error(`${name} must be a non-negative number`);.annotation-row { display:grid; grid-template-columns:max-content 1fr max-content; gap:.6rem; align-items:center; border:1px solid var(--soft); padding:.45rem; margin-bottom:.45rem; }.annotation-row textarea { width:100%; min-height:2.5rem; border:1px solid var(--line); background:var(--bg); color:var(--text); padding:.35rem; }.progress { position:fixed; inset:0; z-index:20; background:color-mix(in srgb, var(--bg), transparent 12%); display:grid; place-items:center; padding:1rem; }.progress[hidden] { display:none; }.progress-card { width:min(560px,100%); border:2px solid var(--line); background:var(--panel); padding:1rem; display:grid; grid-template-columns:auto 1fr auto; gap:1rem; align-items:center; box-shadow:8px 8px 0 color-mix(in srgb, var(--accent), transparent 45%); }.progress-card h2 { margin:0; font-size:1rem; }.spinner { width:1.4rem; height:1.4rem; border:3px solid var(--soft); border-top-color:var(--accent); border-radius:50%; animation:spin .8s linear infinite; }.progress.terminal .spinner { animation:none; border-color:var(--accent); }@keyframes spin { to { transform:rotate(360deg); } } bubble.style.left = Math.min(82, Math.max(2, a.x * 100)) + "%"; bubble.innerHTML = '<textarea aria-label="Pin note" placeholder="note for this spot"></textarea><div class="bubble-actions"><button type="button" class="secondary" data-close>Close</button><button type="button" data-delete>Delete pin</button></div>'; $(".fragment", card).addEventListener("click", e => { if (armed === id) addPin(id, e); else select(id); });async function submit(action) { const res = await fetch("/api/submit", { method:"POST", headers:{ Authorization:"Bearer " + window.__MOCKUP_TOKEN__, "Content-Type":"application/json" }, body:JSON.stringify({ action, selected:[...selected], notes:$("#global-notes").value.trim(), annotations:annotations.filter(a => a.note.trim()) }) }); if (!res.ok) alert(await res.text()); else document.body.innerHTML = '<main style="padding:2rem"><h1>Sent to Pi</h1><p>You can close this tab.</p></main>';let progressStarted = 0;let progressTimer = null;function showProgress(message, terminal = false) { const progress = $("#progress"); progress.hidden = false; progress.classList.toggle("terminal", terminal); $("#progress-title").textContent = message; $("#stop-agent").hidden = terminal; if (!progressStarted) progressStarted = Date.now(); const updateTime = () => { $("#progress-time").textContent = Math.floor((Date.now() - progressStarted) / 1000) + "s elapsed"; }; updateTime(); if (progressTimer) clearInterval(progressTimer); if (!terminal) progressTimer = setInterval(updateTime, 1000);const events = new EventSource("/api/events");events.addEventListener("revision", () => location.reload());events.addEventListener("progress", event => { const state = JSON.parse(event.data); showProgress(state.message, state.terminal === true);});async function submit(action) { if (action === "iterate") showProgress("Feedback received. Pi is working."); const body = { action, selected:[...selected], notes:$("#global-notes").value.trim(), annotations:annotations.filter(a => a.note.trim()), client:{ userAgent:navigator.userAgent, viewport:{ width:window.innerWidth, height:window.innerHeight, devicePixelRatio:window.devicePixelRatio }, }, }; const res = await fetch("/api/submit", { method:"POST", headers:{ Authorization:"Bearer " + window.__MOCKUP_TOKEN__, "Content-Type":"application/json" }, body:JSON.stringify(body) }); if (!res.ok) { $("#progress").hidden = true; alert(await res.text()); return; } if (action === "accept") { showProgress("Accepted. You can close this tab.", true); setTimeout(() => window.close(), 100); }}$("#stop-agent").addEventListener("click", async () => { showProgress("Stopping agent…"); const res = await fetch("/api/abort", { method:"POST", headers:{ Authorization:"Bearer " + window.__MOCKUP_TOKEN__ } }); if (!res.ok) showProgress("Pi has no active agent work.", true);});