repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(the-system): persist and drive mockup iterations

14e8f104408365bf742139172724a39c61e9618d

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (7)

+1192 / −133 text lines

Diff layout

extensions/the-system/__e2e__/mockup.spec.ts

Modified

+83 / −22 text lines

1414 server = undefined;
1515});
17test("renders options and returns browser feedback", async ({ page }) => {
17test("iterates in one page with live Pi progress, stop, and optional selection", async ({
18 page,
19}) => {
20 let aborts = 0;
1821 server = await startMockupServer(
1922 {
2023 title: "Layout review",
3336 },
3437 ],
3538 },
36 { openBrowser: false },
39 {
40 openBrowser: false,
41 abortAgent: () => {
42 aborts++;
43 return true;
44 },
45 },
3746 );
3948 await page.goto(server.url);
49 const stableUrl = page.url();
4050 await expect(
4151 page.getByRole("heading", { name: "Layout review" }),
4252 ).toBeVisible();
4555 await expect(page.getByText("Dense content")).toBeVisible();
4757 await page.locator('[data-select-option="dense"]').check();
48 await expect(page.locator("#selection-summary")).toHaveText(
49 "Selected: dense",
50 );
5158 await page.locator("#global-notes").fill("keep dense");
5359 await page.locator('[data-pin-option="dense"]').click();
54 await page.locator('[data-fragment="dense"]').click({
55 position: { x: 40, y: 40 },
60 const fragment = page.locator('[data-fragment="dense"]');
61 const fragmentBox = await fragment.boundingBox();
62 expect(fragmentBox).not.toBeNull();
63 await fragment.click({
64 position: { x: (fragmentBox?.width ?? 20) - 10, y: 40 },
5665 });
5766 await page.getByLabel("Pin note").fill("tighten spacing");
67 const annotationGeometry = await fragment.evaluate((element) => {
68 const fragmentRect = element.getBoundingClientRect();
69 const bubbleRect = element.querySelector(".pin-bubble")?.getBoundingClientRect();
70 const pinRect = element.querySelector(".pin")?.getBoundingClientRect();
71 return {
72 clientWidth: element.clientWidth,
73 scrollWidth: element.scrollWidth,
74 bubbleWithin:
75 !!bubbleRect &&
76 bubbleRect.left >= fragmentRect.left &&
77 bubbleRect.right <= fragmentRect.right,
78 pinWithin:
79 !!pinRect &&
80 pinRect.left >= fragmentRect.left &&
81 pinRect.right <= fragmentRect.right,
82 };
83 });
84 expect(annotationGeometry).toEqual({
85 clientWidth: annotationGeometry.clientWidth,
86 scrollWidth: annotationGeometry.clientWidth,
87 bubbleWithin: true,
88 pinWithin: true,
89 });
59 const submitted = server.result;
60 await page.locator("#accept").click();
61 await expect(page.getByRole("heading", { name: "Sent to Pi" })).toBeVisible();
63 const result: MockupResult = await submitted;
64 expect(result).toMatchObject({
65 action: "accept",
91 const firstSubmission = server.result;
92 await page.locator("#iterate").click();
93 await expect(page.locator("#progress-title")).toHaveText(
94 "Feedback received. Pi is working.",
95 );
96 const first: MockupResult = await firstSubmission;
97 expect(first).toMatchObject({
98 action: "iterate",
6699 selected: ["dense"],
67100 notes: "keep dense",
68 annotations: [
101 annotations: [{ optionId: "dense", note: "tighten spacing" }],
102 review: { viewport: { devicePixelRatio: 1 } },
103 });
105 server.progress("Pi is working on the revision.");
106 await expect(page.locator("#progress-title")).toHaveText(
107 "Pi is working on the revision.",
108 );
109 await page.getByRole("button", { name: "Stop agent" }).click();
110 await expect.poll(() => aborts).toBe(1);
112 const secondSubmission = server.present({
113 title: "Layout revision",
114 question: "Does the denser revision work?",
115 options: [
69116 {
70 optionId: "dense",
71 note: "tighten spacing",
117 id: "dense-v2",
118 label: "Dense revision",
119 html: "<section>Revised dense content</section>",
72120 },
73121 ],
74122 });
75 expect(result.annotations[0].x).toBeGreaterThan(0);
76 expect(result.annotations[0].x).toBeLessThanOrEqual(1);
77 expect(result.annotations[0].y).toBeGreaterThan(0);
78 expect(result.annotations[0].y).toBeLessThanOrEqual(1);
123 await expect(
124 page.getByRole("heading", { name: "Layout revision" }),
125 ).toBeVisible();
126 expect(page.url()).toBe(stableUrl);
127 await expect(page.getByText("Revised dense content")).toBeVisible();
129 await page.locator("#accept").click();
130 await expect(page.locator("#progress-title")).toHaveText(
131 "Accepted. You can close this tab.",
132 );
133 const second = await secondSubmission;
134 expect(second).toMatchObject({
135 action: "accept",
136 selected: [],
137 notes: "",
138 annotations: [],
139 });
79140});

extensions/the-system/__tests__/mockup-tool.test.ts

Added
new file mode 100644

+270 / −0 text lines

1import assert from "node:assert";
2import {
3 access,
4 mkdtemp,
5 readdir,
6 readFile,
7 rm,
8 stat,
9 utimes,
10 writeFile,
11} from "node:fs/promises";
12import { tmpdir } from "node:os";
13import path from "node:path";
14import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
15import { afterEach, describe, it } from "vitest";
16import type { MockupRequest, MockupResult } from "../mockup.ts";
17import {
18 createMockupRuntime,
19 formatContextCapsule,
20 mockupCacheRoot,
21 persistMockupIteration,
22 pruneMockupCache,
23} from "../mockup-tool.ts";
25const request: MockupRequest = {
26 title: "Layout",
27 question: "Which layout?",
28 options: [
29 { id: "dense", label: "Dense", html: "<section>dense</section>" },
30 { id: "calm", label: "Calm", html: "<section>calm</section>" },
31 ],
32};
33const result: MockupResult = {
34 action: "iterate",
35 selected: ["dense"],
36 notes: "keep density",
37 annotations: [{ optionId: "dense", x: 0.25, y: 0.5, note: "tighten" }],
38 review: {
39 submittedAt: "2026-01-02T03:04:05.000Z",
40 userAgent: "test-browser/1",
41 viewport: { width: 1280, height: 720, devicePixelRatio: 1 },
42 },
43};
45const roots: string[] = [];
46afterEach(async () => {
47 await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true })));
48});
50async function temporaryRoot(): Promise<string> {
51 const root = await mkdtemp(path.join(tmpdir(), "pi-mockup-test-"));
52 roots.push(root);
53 return root;
54}
56async function exists(file: string): Promise<boolean> {
57 try {
58 await access(file);
59 return true;
60 } catch {
61 return false;
62 }
63}
65async function size(root: string): Promise<number> {
66 let bytes = 0;
67 for (const entry of await readdir(root, { withFileTypes: true })) {
68 const child = path.join(root, entry.name);
69 if (entry.isDirectory()) bytes += await size(child);
70 else if (entry.isFile()) bytes += (await stat(child)).size;
71 }
72 return bytes;
73}
75describe("mockup context cache", () => {
76 it("uses the native OS cache location", () => {
77 assert.strictEqual(
78 mockupCacheRoot("linux", { XDG_CACHE_HOME: "/cache" }, "/home/o"),
79 path.join("/cache", "pi", "mockups"),
80 );
81 assert.strictEqual(
82 mockupCacheRoot(
83 "win32",
84 { LOCALAPPDATA: "C:\\Users\\o\\AppData\\Local" },
85 "C:\\Users\\o",
86 ),
87 path.join("C:\\Users\\o\\AppData\\Local", "pi", "cache", "mockups"),
88 );
89 assert.strictEqual(
90 mockupCacheRoot("darwin", {}, "/Users/o"),
91 path.join("/Users/o", "Library", "Caches", "pi", "mockups"),
92 );
93 });
95 it("persists exact fragments, request, feedback, metadata, and lineage", async () => {
96 const root = await temporaryRoot();
97 const sessionFile = path.join(root, "session.jsonl");
98 await writeFile(sessionFile, "");
99 const first = await persistMockupIteration(root, {
100 sessionId: "session/one",
101 sessionFile,
102 chainId: "chain-one",
103 iteration: 1,
104 toolCallId: "tool/one",
105 request,
106 result,
107 });
108 const second = await persistMockupIteration(root, {
109 sessionId: "session/one",
110 sessionFile,
111 chainId: "chain-one",
112 iteration: 2,
113 toolCallId: "tool-two",
114 request,
115 result: { ...result, action: "accept", selected: [] },
116 previousManifest: first,
117 });
119 assert.strictEqual(
120 await readFile(path.join(path.dirname(first), "dense.html"), "utf8"),
121 request.options[0].html,
122 );
123 assert.deepStrictEqual(
124 JSON.parse(await readFile(path.join(path.dirname(first), "request.json"), "utf8")),
125 request,
126 );
127 assert.deepStrictEqual(
128 JSON.parse(await readFile(path.join(path.dirname(first), "feedback.json"), "utf8")),
129 result,
130 );
131 const manifest = JSON.parse(await readFile(second, "utf8"));
132 assert.strictEqual(manifest.previousManifest, first);
133 assert.strictEqual(manifest.options[0].html, "dense.html");
134 });
136 it("formats current feedback first and preserves earlier iteration context", () => {
137 const capsule = formatContextCapsule("chain", [
138 {
139 iteration: 1,
140 question: request.question,
141 options: request.options.map(({ id, label }) => ({ id, label })),
142 action: "iterate",
143 selected: ["dense"],
144 notes: "keep density",
145 annotations: result.annotations,
146 cacheManifest: "/cache/one/manifest.json",
147 },
148 {
149 iteration: 2,
150 question: "Now?",
151 options: request.options.map(({ id, label }) => ({ id, label })),
152 action: "accept",
153 selected: [],
154 notes: "none selected intentionally",
155 annotations: [],
156 cacheManifest: "/cache/two/manifest.json",
157 },
158 ]);
159 assert.ok(capsule.indexOf("Current: iteration 2, accept") < capsule.indexOf("Earlier iterations"));
160 assert.match(capsule, /Selected: none/);
161 assert.match(capsule, /never infer rejection from non-selection/);
162 assert.match(capsule, /1 iterate; selected dense \(Dense\); notes: keep density/);
163 assert.match(capsule, /annotation dense: tighten/);
164 });
166 it("injects cached context only into its owning session", async () => {
167 const root = await temporaryRoot();
168 const capsule = "owned mockup context";
169 const details = {
170 ...result,
171 sessionId: "owner",
172 chainId: "chain",
173 iteration: 1,
174 history: [],
175 contextCapsule: capsule,
176 };
177 const context = (sessionId: string) =>
178 ({
179 isIdle: () => true,
180 sessionManager: {
181 getSessionId: () => sessionId,
182 getBranch: () => [
183 {
184 type: "message",
185 message: {
186 role: "toolResult",
187 toolName: "mockup",
188 details,
189 },
190 },
191 ],
192 },
193 }) as unknown as ExtensionContext;
194 const runtime = createMockupRuntime({ cacheRoot: root, openBrowser: false });
195 assert.strictEqual(runtime.contextCapsule(context("owner")), capsule);
196 assert.strictEqual(runtime.contextCapsule(context("new-session")), undefined);
197 });
199 it("removes orphaned and expired entries while protecting the current session", async () => {
200 const root = await temporaryRoot();
201 const sessionFile = path.join(root, "live.jsonl");
202 await writeFile(sessionFile, "");
203 const live = await persistMockupIteration(root, {
204 sessionId: "live",
205 sessionFile,
206 chainId: "chain",
207 iteration: 1,
208 toolCallId: "one",
209 request,
210 result,
211 });
212 const orphan = await persistMockupIteration(root, {
213 sessionId: "orphan",
214 sessionFile: path.join(root, "missing.jsonl"),
215 chainId: "chain",
216 iteration: 1,
217 toolCallId: "one",
218 request,
219 result,
220 });
221 const old = new Date(Date.now() - 10_000);
222 await utimes(path.dirname(live), old, old);
224 await pruneMockupCache(root, "live", Date.now(), {
225 ttlMs: 1,
226 maxBytes: Number.MAX_SAFE_INTEGER,
227 });
228 assert.strictEqual(await exists(live), true);
229 assert.strictEqual(await exists(orphan), false);
230 await pruneMockupCache(root, undefined, Date.now(), {
231 ttlMs: 1,
232 maxBytes: Number.MAX_SAFE_INTEGER,
233 });
234 assert.strictEqual(await exists(live), false);
235 });
237 it("evicts least-recently-used iterations above the size cap", async () => {
238 const root = await temporaryRoot();
239 const sessionFile = path.join(root, "live.jsonl");
240 await writeFile(sessionFile, "");
241 const oldest = await persistMockupIteration(root, {
242 sessionId: "live",
243 sessionFile,
244 chainId: "chain",
245 iteration: 1,
246 toolCallId: "old",
247 request,
248 result,
249 });
250 const newest = await persistMockupIteration(root, {
251 sessionId: "live",
252 sessionFile,
253 chainId: "chain",
254 iteration: 2,
255 toolCallId: "new",
256 request,
257 result,
258 });
259 await utimes(path.dirname(oldest), new Date(1000), new Date(1000));
260 await utimes(path.dirname(newest), new Date(2000), new Date(2000));
261 const newestBytes = await size(path.dirname(newest));
263 await pruneMockupCache(root, undefined, Date.now(), {
264 ttlMs: Number.MAX_SAFE_INTEGER,
265 maxBytes: newestBytes,
266 });
267 assert.strictEqual(await exists(oldest), false);
268 assert.strictEqual(await exists(newest), true);
269 });
270});

extensions/the-system/__tests__/mockup.test.ts

Modified

+115 / −8 text lines

1010 validateMockupRequest,
1111} from "../mockup.ts";
13const client = {
14 userAgent: "mockup-test-browser/1",
15 viewport: { width: 1280, height: 720, devicePixelRatio: 1 },
16};
1318const baseRequest: MockupRequest = {
1419 title: "Pick layout",
1520 question: "Which option works?",
156161 assert.match(html, /closest\("label,button"\)/);
157162 });
164 it("keeps annotations inside the nearest fragment edge", () => {
165 const html = renderMockupPage(baseRequest, "tok");
166 assert.match(html, /if \(a\.x > 0\.5\) bubble\.style\.right/);
167 assert.match(html, /else bubble\.style\.left/);
168 assert.match(html, /button\.style\.left = "clamp\(14px,/);
169 });
159171 it("places pins relative to scrolled fragment content", () => {
160172 const html = renderMockupPage(baseRequest, "tok");
161173 assert.match(
170182});
172184describe("mockup browser opener", () => {
173 it("uses explorer directly on win32 to avoid cmd flashes", () => {
185 it("uses the native URL handler directly on win32 without cmd", () => {
174186 assert.deepStrictEqual(
175187 openerCandidates("http://127.0.0.1:1", {
176188 platform: "win32",
177189 env: {},
178190 })[0],
179191 {
180 command: "explorer.exe",
181 args: ["http://127.0.0.1:1"],
192 command: "rundll32.exe",
193 args: ["url.dll,FileProtocolHandler", "http://127.0.0.1:1"],
182194 windowsHide: true,
183195 },
184196 );
209221 selected: ["a", "b"],
210222 notes: "",
211223 annotations: [],
224 client,
212225 }),
213226 });
214227 assert.strictEqual(res.status, 400);
228241 selected: ["a"],
229242 notes: "before 😀 after",
230243 annotations: [],
244 client,
231245 }),
232246 );
233247 const split = body.indexOf(Buffer.from("😀")) + 1;
274288 selected: ["a"],
275289 notes: "keep A, denser drawer",
276290 annotations: [{ optionId: "a", x: 0.25, y: 0.5, note: "tighten" }],
291 client,
277292 }),
278293 });
279294 const res = await posted;
280295 assert.strictEqual(await res.text(), '{"ok":true}');
281296 const result = await server.result;
282 assert.deepStrictEqual(result, {
283 action: "iterate",
284 selected: ["a"],
285 notes: "keep A, denser drawer",
286 annotations: [{ optionId: "a", x: 0.25, y: 0.5, note: "tighten" }],
297 assert.deepStrictEqual(
298 {
299 action: result.action,
300 selected: result.selected,
301 notes: result.notes,
302 annotations: result.annotations,
303 userAgent: result.review.userAgent,
304 viewport: result.review.viewport,
305 },
306 {
307 action: "iterate",
308 selected: ["a"],
309 notes: "keep A, denser drawer",
310 annotations: [
311 { optionId: "a", x: 0.25, y: 0.5, note: "tighten" },
312 ],
313 userAgent: client.userAgent,
314 viewport: client.viewport,
315 },
316 );
317 assert.match(result.review.submittedAt, /^\d{4}-\d{2}-\d{2}T/);
318 } finally {
319 server.result.catch(() => undefined);
320 server.close("test");
321 }
322 });
324 it("keeps one URL across iterations and accepts no selection", async () => {
325 const server = await startMockupServer(baseRequest, { openBrowser: false });
326 try {
327 const first = server.result;
328 const firstResponse = await fetch(new URL("/api/submit", server.url), {
329 method: "POST",
330 headers: {
331 Authorization: `Bearer ${server.token}`,
332 "Content-Type": "application/json",
333 },
334 body: JSON.stringify({
335 action: "iterate",
336 selected: ["a"],
337 notes: "try again",
338 annotations: [],
339 client,
340 }),
287341 });
342 assert.strictEqual(firstResponse.status, 200);
343 assert.strictEqual((await first).action, "iterate");
345 const stableUrl = server.url;
346 const second = server.present({
347 ...baseRequest,
348 question: "Is this revision right?",
349 });
350 assert.strictEqual(server.url, stableUrl);
351 const page = await fetch(server.url);
352 assert.match(await page.text(), /Is this revision right\?/);
353 const secondResponse = await fetch(new URL("/api/submit", server.url), {
354 method: "POST",
355 headers: {
356 Authorization: `Bearer ${server.token}`,
357 "Content-Type": "application/json",
358 },
359 body: JSON.stringify({
360 action: "accept",
361 selected: [],
362 notes: "none works",
363 annotations: [],
364 client,
365 }),
366 });
367 assert.strictEqual(secondResponse.status, 200);
368 assert.deepStrictEqual((await second).selected, []);
369 } finally {
370 server.result.catch(() => undefined);
371 server.close("test");
372 }
373 });
375 it("authenticates browser requests that stop active Pi work", async () => {
376 let aborts = 0;
377 const server = await startMockupServer(baseRequest, {
378 openBrowser: false,
379 abortAgent: () => {
380 aborts++;
381 return true;
382 },
383 });
384 try {
385 const unauthorized = await fetch(new URL("/api/abort", server.url), {
386 method: "POST",
387 });
388 assert.strictEqual(unauthorized.status, 401);
389 const stopped = await fetch(new URL("/api/abort", server.url), {
390 method: "POST",
391 headers: { Authorization: `Bearer ${server.token}` },
392 });
393 assert.strictEqual(stopped.status, 200);
394 assert.strictEqual(aborts, 1);
288395 } finally {
289396 server.result.catch(() => undefined);
290397 server.close("test");

extensions/the-system/index.ts

Modified

+15 / −4 text lines

33 type ExtensionContext,
44 isToolCallEventType,
55} from "@earendil-works/pi-coding-agent";
6import { createMockupTool } from "./mockup-tool.js";
6import { createMockupRuntime } from "./mockup-tool.js";
77import { systemArgumentCompletions } from "./system-command-meta.js";
99function isStaleContextError(error: unknown): boolean {
1616export default function registerTheSystem(pi: ExtensionAPI): void {
1717 let generation = 0;
1818 let notified = false;
19 const mockup = createMockupRuntime();
2021 const notifyOnce = async (ctx: ExtensionContext, ticket: number) => {
2122 if (notified || ticket !== generation) return;
3435 pi.on("session_start", (_event, ctx) => {
3536 const ticket = ++generation;
3637 notified = false;
38 mockup.remember(ctx);
3739 const timer = setTimeout(() => {
3840 if (ticket === generation)
3941 void notifyOnce(ctx, ticket).catch((error) =>
4244 }, 0);
4345 timer.unref?.();
4446 });
45 pi.on("session_shutdown", () => {
47 pi.on("session_shutdown", (_event, ctx) => {
4648 generation++;
4749 notified = false;
50 mockup.shutdown(ctx);
4851 });
4952 pi.on("before_agent_start", async (event, ctx) => {
5053 void notifyOnce(ctx, generation).catch((error) =>
5154 console.error("The System startup check failed:", error),
5255 );
56 mockup.agentWorking(ctx);
5357 const { composeSystemPrompt } = await import("./system.js");
54 return { systemPrompt: composeSystemPrompt(ctx.cwd, event.systemPrompt) };
58 const systemPrompt = composeSystemPrompt(ctx.cwd, event.systemPrompt);
59 const capsule = mockup.contextCapsule(ctx);
60 return {
61 systemPrompt: capsule
62 ? `${systemPrompt}\n\n<mockup-context>\n${capsule}\n</mockup-context>`
63 : systemPrompt,
64 };
5565 });
66 pi.on("agent_settled", (_event, ctx) => mockup.agentSettled(ctx));
5667 pi.on("tool_call", async (event, ctx) => {
5768 if (
5869 !isToolCallEventType("write", event) &&
7081 return preflightFileMutation(ctx.cwd, "edit", event.input, ui);
7182 });
73 pi.registerTool(createMockupTool());
84 pi.registerTool(mockup.tool);
7485 pi.registerCommand("system", {
7586 description: "The System project governance",
7687 getArgumentCompletions: systemArgumentCompletions,

extensions/the-system/mise.toml

Modified

+10 / −0 text lines

1[tasks.fmt]
2description = "Format the-system"
3depends = ["//:install"]
4run = "npm exec -- biome check --write ."
5
6[tasks.lint]
7description = "Verify the-system formatting and lint"
8depends = ["//:install"]
9run = "npm exec -- biome ci ."
111[tasks.e2e]
212description = "Run mockup browser E2E tests"
313depends = ["//:install"]

extensions/the-system/mockup-tool.ts

Modified

+498 / −8 text lines

1import { defineTool, keyHint } from "@earendil-works/pi-coding-agent";
1import { randomUUID } from "node:crypto";
2import { access, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
3import { homedir } from "node:os";
4import path from "node:path";
5import {
6 defineTool,
7 type ExtensionContext,
8 keyHint,
9} from "@earendil-works/pi-coding-agent";
210import { Text } from "@earendil-works/pi-tui";
311import { Type } from "typebox";
4import type { MockupResult } from "./mockup.js";
12import {
13 type MockupRequest,
14 type MockupResult,
15 type MockupServer,
16 startMockupServer,
17 validateMockupRequest,
18} from "./mockup.js";
620const DESCRIPTION =
721 "Show HTML-fragment mockup options in a browser and return selected options, notes, annotations, and accept/iterate action.";
22const CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
23const CACHE_LIMIT_BYTES = 256 * 1024 * 1024;
925const parameters = Type.Object({
1026 title: Type.String({
4561 ),
4662});
48export function createMockupTool() {
49 return defineTool({
64export type MockupHistoryEntry = {
65 iteration: number;
66 question: string;
67 options: Array<{ id: string; label: string }>;
68 action: MockupResult["action"];
69 selected: string[];
70 notes: string;
71 annotations: MockupResult["annotations"];
72 cacheManifest?: string;
73};
75export type MockupToolDetails = MockupResult & {
76 sessionId: string;
77 chainId: string;
78 iteration: number;
79 cacheManifest?: string;
80 cacheError?: string;
81 history: MockupHistoryEntry[];
82 contextCapsule: string;
83};
85type ActiveChain = {
86 server: MockupServer;
87 chainId: string;
88};
90type RuntimeOptions = {
91 cacheRoot?: string;
92 openBrowser?: boolean;
93};
95export function createMockupRuntime(options: RuntimeOptions = {}) {
96 const active = new Map<string, ActiveChain>();
97 const contexts = new Map<string, ExtensionContext>();
98 const cacheRoot = options.cacheRoot ?? mockupCacheRoot();
100 const remember = (ctx: ExtensionContext): string => {
101 const sessionId = ctx.sessionManager.getSessionId();
102 contexts.set(sessionId, ctx);
103 return sessionId;
104 };
105 const abortAgent = (sessionId: string): boolean => {
106 const ctx = contexts.get(sessionId);
107 if (!ctx || ctx.isIdle()) return false;
108 try {
109 ctx.abort();
110 return true;
111 } catch {
112 return false;
113 }
114 };
115 const schedulePrune = (protectedSessionId?: string): void => {
116 const timer = setTimeout(() => {
117 void pruneMockupCache(cacheRoot, protectedSessionId).catch((error) =>
118 console.error("Mockup cache cleanup failed:", error),
119 );
120 }, 0);
121 timer.unref?.();
122 };
124 const tool = defineTool({
50125 name: "mockup",
51126 label: "Mockup",
52127 description: DESCRIPTION,
78153 return new Text(lines.join("\n"), 0, 0);
79154 },
80155 renderResult(result, context, theme) {
81 const details = result.details as Partial<MockupResult> | undefined;
156 const details = result.details as Partial<MockupToolDetails> | undefined;
82157 if (!details) return new Text("", 0, 0);
83158 const annotations = details.annotations ?? [];
84159 const summary = `${details.action ?? "submitted"} · ${(details.selected ?? []).join(", ") || "none"} · ${annotations.length} annotation${annotations.length === 1 ? "" : "s"}`;
85 if (!context.expanded) return new Text(theme.fg("dim", summary), 0, 0);
160 if (!context.expanded)
161 return new Text(theme.fg("dim", summary), 0, 0);
86162 return new Text(
87163 [
88164 theme.fg("dim", summary),
89165 details.notes ? `notes: ${details.notes}` : "notes: ",
166 details.cacheManifest
167 ? `cache: ${details.cacheManifest}`
168 : "cache: unavailable",
90169 ].join("\n"),
91170 0,
92171 );
93172 },
94 async execute(_toolCallId, params, signal, _onUpdate, ctx) {
95 return (await import("./mockup.js")).executeMockup(params, signal, ctx);
173 async execute(toolCallId, params, signal, _onUpdate, ctx) {
174 const request = validateMockupRequest(params);
175 const sessionId = remember(ctx);
176 const previous = latestMockupDetails(ctx);
177 const continuing =
178 previous?.sessionId === sessionId && previous.action === "iterate";
179 let chain = active.get(sessionId);
180 const created = !chain;
181 if (!chain) {
182 chain = {
183 chainId: continuing ? previous.chainId : randomUUID(),
184 server: await startMockupServer(request, {
185 openBrowser:
186 options.openBrowser ?? process.env.PI_MOCKUP_NO_OPEN !== "1",
187 abortAgent: () => abortAgent(sessionId),
188 }),
189 };
190 active.set(sessionId, chain);
191 if (ctx.hasUI)
192 ctx.ui.notify(`Mockup open: ${chain.server.url}`, "info");
193 }
194 const iteration = continuing ? previous.iteration + 1 : 1;
195 const history = continuing ? previous.history : [];
196 const resultPromise = created
197 ? chain.server.result
198 : chain.server.present(request);
199 try {
200 const result = await abortable(resultPromise, signal, () =>
201 chain?.server.close("aborted"),
202 );
203 let cacheManifest: string | undefined;
204 let cacheError: string | undefined;
205 try {
206 cacheManifest = await persistMockupIteration(cacheRoot, {
207 sessionId,
208 sessionFile: ctx.sessionManager.getSessionFile(),
209 chainId: chain.chainId,
210 iteration,
211 toolCallId,
212 request,
213 result,
214 previousManifest: continuing
215 ? previous.cacheManifest
216 : undefined,
217 });
218 } catch (error) {
219 cacheError = error instanceof Error ? error.message : String(error);
220 if (ctx.hasUI)
221 ctx.ui.notify(`Mockup cache unavailable: ${cacheError}`, "warning");
222 }
223 const current = historyEntry(iteration, request, result, cacheManifest);
224 const nextHistory = [...history, current];
225 const contextCapsule = formatContextCapsule(
226 chain.chainId,
227 nextHistory,
228 cacheError,
229 );
230 const details: MockupToolDetails = {
231 ...result,
232 sessionId,
233 chainId: chain.chainId,
234 iteration,
235 cacheManifest,
236 cacheError,
237 history: nextHistory,
238 contextCapsule,
239 };
240 if (result.action === "accept") {
241 chain.server.close("accepted");
242 active.delete(sessionId);
243 schedulePrune(sessionId);
244 }
245 return {
246 content: [
247 {
248 type: "text" as const,
249 text: JSON.stringify({
250 action: result.action,
251 selected: result.selected,
252 notes: result.notes,
253 annotations: result.annotations,
254 cacheManifest,
255 contextCapsule,
256 }),
257 },
258 ],
259 details,
260 };
261 } catch (error) {
262 chain.server.close("failed");
263 active.delete(sessionId);
264 schedulePrune(sessionId);
265 throw error;
266 }
96267 },
97268 });
270 return {
271 tool,
272 remember,
273 contextCapsule(ctx: ExtensionContext): string | undefined {
274 const sessionId = remember(ctx);
275 const details = latestMockupDetails(ctx);
276 return details?.sessionId === sessionId
277 ? details.contextCapsule
278 : undefined;
279 },
280 agentWorking(ctx: ExtensionContext): void {
281 const sessionId = remember(ctx);
282 active.get(sessionId)?.server.progress("Pi is working on the revision.");
283 },
284 agentSettled(ctx: ExtensionContext): void {
285 const sessionId = remember(ctx);
286 active.get(sessionId)?.server.settled();
287 },
288 shutdown(ctx: ExtensionContext): void {
289 const sessionId = ctx.sessionManager.getSessionId();
290 active.get(sessionId)?.server.close("session ended");
291 active.delete(sessionId);
292 contexts.delete(sessionId);
293 schedulePrune();
294 },
295 };
296}
298function latestMockupDetails(
299 ctx: ExtensionContext,
300): MockupToolDetails | undefined {
301 const branch = ctx.sessionManager.getBranch();
302 for (let index = branch.length - 1; index >= 0; index--) {
303 const entry = branch[index] as unknown as Record<string, unknown>;
304 if (entry.type !== "message") continue;
305 const message = entry.message;
306 if (!isRecord(message)) continue;
307 if (message.role !== "toolResult" || message.toolName !== "mockup") continue;
308 const details = message.details;
309 if (!isRecord(details) || typeof details.contextCapsule !== "string")
310 return undefined;
311 return details as unknown as MockupToolDetails;
312 }
313 return undefined;
314}
316function historyEntry(
317 iteration: number,
318 request: MockupRequest,
319 result: MockupResult,
320 cacheManifest?: string,
321): MockupHistoryEntry {
322 return {
323 iteration,
324 question: request.question,
325 options: request.options.map(({ id, label }) => ({ id, label })),
326 action: result.action,
327 selected: result.selected,
328 notes: result.notes,
329 annotations: result.annotations,
330 cacheManifest,
331 };
332}
334export function formatContextCapsule(
335 chainId: string,
336 history: MockupHistoryEntry[],
337 cacheError?: string,
338): string {
339 const latest = history.at(-1);
340 if (!latest) return "";
341 const lines = [
342 "Mockup context capsule",
343 `Chain: ${chainId}`,
344 `Current: iteration ${latest.iteration}, ${latest.action}`,
345 `Question: ${latest.question}`,
346 `Selected: ${selectedLabels(latest)}`,
347 `Notes: ${latest.notes || "none"}`,
348 ];
349 if (latest.annotations.length === 0) lines.push("Annotations: none");
350 else {
351 lines.push("Annotations:");
352 for (const annotation of latest.annotations)
353 lines.push(
354 `- ${annotation.optionId} @ ${Math.round(annotation.x * 100)}%,${Math.round(annotation.y * 100)}%: ${annotation.note}`,
355 );
356 }
357 lines.push(
358 "Rejected rationale: not recorded separately; never infer rejection from non-selection.",
359 `Cache manifest: ${latest.cacheManifest ?? `unavailable${cacheError ? ` (${cacheError})` : ""}`}`,
360 );
361 if (history.length > 1) {
362 lines.push("Earlier iterations, newest first:");
363 for (const entry of history.slice(0, -1).reverse()) {
364 lines.push(
365 `- ${entry.iteration} ${entry.action}; selected ${selectedLabels(entry)}; notes: ${entry.notes || "none"}`,
366 );
367 for (const annotation of entry.annotations)
368 lines.push(` annotation ${annotation.optionId}: ${annotation.note}`);
369 if (entry.cacheManifest) lines.push(` cache: ${entry.cacheManifest}`);
370 }
371 }
372 return lines.join("\n");
373}
375function selectedLabels(entry: MockupHistoryEntry): string {
376 if (entry.selected.length === 0) return "none";
377 const labels = new Map(entry.options.map((option) => [option.id, option.label]));
378 return entry.selected
379 .map((id) => `${id} (${labels.get(id) ?? id})`)
380 .join(", ");
381}
383export function mockupCacheRoot(
384 platform: NodeJS.Platform = process.platform,
385 env: NodeJS.ProcessEnv = process.env,
386 home: string = homedir(),
387): string {
388 if (platform === "win32")
389 return path.join(
390 env.LOCALAPPDATA ?? path.join(home, "AppData", "Local"),
391 "pi",
392 "cache",
393 "mockups",
394 );
395 if (platform === "darwin")
396 return path.join(home, "Library", "Caches", "pi", "mockups");
397 return path.join(env.XDG_CACHE_HOME ?? path.join(home, ".cache"), "pi", "mockups");
398}
400type PersistInput = {
401 sessionId: string;
402 sessionFile: string | undefined;
403 chainId: string;
404 iteration: number;
405 toolCallId: string;
406 request: MockupRequest;
407 result: MockupResult;
408 previousManifest?: string;
409};
411export async function persistMockupIteration(
412 root: string,
413 input: PersistInput,
414): Promise<string> {
415 const sessionDir = path.join(root, safeSegment(input.sessionId));
416 const iterationDir = path.join(
417 sessionDir,
418 safeSegment(input.chainId),
419 `${String(input.iteration).padStart(3, "0")}-${safeSegment(input.toolCallId)}`,
420 );
421 await mkdir(iterationDir, { recursive: true });
422 await Promise.all([
423 writeFile(
424 path.join(sessionDir, "session.json"),
425 `${JSON.stringify({ sessionId: input.sessionId, sessionFile: input.sessionFile }, null, 2)}\n`,
426 ),
427 writeFile(
428 path.join(iterationDir, "request.json"),
429 `${JSON.stringify(input.request, null, 2)}\n`,
430 ),
431 writeFile(
432 path.join(iterationDir, "feedback.json"),
433 `${JSON.stringify(input.result, null, 2)}\n`,
434 ),
435 ...input.request.options.map((option) =>
436 writeFile(path.join(iterationDir, `${safeSegment(option.id)}.html`), option.html),
437 ),
438 ]);
439 const manifest = path.join(iterationDir, "manifest.json");
440 await writeFile(
441 manifest,
442 `${JSON.stringify(
443 {
444 version: 1,
445 recordedAt: new Date().toISOString(),
446 sessionId: input.sessionId,
447 chainId: input.chainId,
448 iteration: input.iteration,
449 toolCallId: input.toolCallId,
450 previousManifest: input.previousManifest,
451 request: "request.json",
452 feedback: "feedback.json",
453 options: input.request.options.map((option) => ({
454 id: option.id,
455 label: option.label,
456 html: `${safeSegment(option.id)}.html`,
457 })),
458 },
459 null,
460 2,
461 )}\n`,
462 );
463 return manifest;
464}
466export async function pruneMockupCache(
467 root: string,
468 protectedSessionId?: string,
469 now = Date.now(),
470 policy: { ttlMs: number; maxBytes: number } = {
471 ttlMs: CACHE_TTL_MS,
472 maxBytes: CACHE_LIMIT_BYTES,
473 },
474): Promise<void> {
475 const sessions = await directories(root);
476 const candidates: Array<{ path: string; modified: number; bytes: number }> = [];
477 for (const session of sessions) {
478 if (session.name === safeSegment(protectedSessionId ?? "")) continue;
479 const metadataPath = path.join(session.path, "session.json");
480 const metadata = await readJson(metadataPath);
481 if (
482 isRecord(metadata) &&
483 typeof metadata.sessionFile === "string" &&
484 !(await exists(metadata.sessionFile))
485 ) {
486 await rm(session.path, { recursive: true, force: true });
487 continue;
488 }
489 for (const chain of await directories(session.path)) {
490 for (const iteration of await directories(chain.path)) {
491 const info = await stat(iteration.path);
492 if (now - info.mtimeMs >= policy.ttlMs) {
493 await rm(iteration.path, { recursive: true, force: true });
494 continue;
495 }
496 candidates.push({
497 path: iteration.path,
498 modified: info.mtimeMs,
499 bytes: await directorySize(iteration.path),
500 });
501 }
502 }
503 }
504 let total = candidates.reduce((sum, candidate) => sum + candidate.bytes, 0);
505 for (const candidate of candidates.sort(
506 (left, right) => left.modified - right.modified,
507 )) {
508 if (total <= policy.maxBytes) break;
509 await rm(candidate.path, { recursive: true, force: true });
510 total -= candidate.bytes;
511 }
512}
514async function directories(
515 root: string,
516): Promise<Array<{ name: string; path: string }>> {
517 try {
518 return (await readdir(root, { withFileTypes: true }))
519 .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
520 .map((entry) => ({ name: entry.name, path: path.join(root, entry.name) }));
521 } catch (error) {
522 if (isNotFound(error)) return [];
523 throw error;
524 }
525}
527async function directorySize(root: string): Promise<number> {
528 let bytes = 0;
529 for (const entry of await readdir(root, { withFileTypes: true })) {
530 if (entry.isSymbolicLink()) continue;
531 const child = path.join(root, entry.name);
532 if (entry.isDirectory()) bytes += await directorySize(child);
533 else if (entry.isFile()) bytes += (await stat(child)).size;
534 }
535 return bytes;
536}
538async function readJson(file: string): Promise<unknown> {
539 try {
540 return JSON.parse(await readFile(file, "utf8"));
541 } catch (error) {
542 if (isNotFound(error)) return undefined;
543 throw error;
544 }
545}
547async function exists(file: string): Promise<boolean> {
548 try {
549 await access(file);
550 return true;
551 } catch {
552 return false;
553 }
554}
556function safeSegment(value: string): string {
557 return value.replaceAll(/[^a-zA-Z0-9._-]/g, "_") || "unknown";
558}
560function isRecord(value: unknown): value is Record<string, unknown> {
561 return !!value && typeof value === "object" && !Array.isArray(value);
562}
564function isNotFound(error: unknown): boolean {
565 return isRecord(error) && error.code === "ENOENT";
566}
568function abortable<T>(
569 promise: Promise<T>,
570 signal: AbortSignal | undefined,
571 abort: () => void,
572): Promise<T> {
573 if (!signal) return promise;
574 if (signal.aborted) {
575 abort();
576 return Promise.reject(new Error("mockup aborted"));
577 }
578 return new Promise((resolve, reject) => {
579 const onAbort = () => {
580 abort();
581 reject(new Error("mockup aborted"));
582 };
583 signal.addEventListener("abort", onAbort, { once: true });
584 promise
585 .then(resolve, reject)
586 .finally(() => signal.removeEventListener("abort", onAbort));
587 });

extensions/the-system/mockup.ts

Modified

+201 / −91 text lines

2626 selected: string[];
2727 notes: string;
2828 annotations: Array<{ optionId: string; x: number; y: number; note: string }>;
29 review: {
30 submittedAt: string;
31 userAgent: string;
32 viewport: { width: number; height: number; devicePixelRatio: number };
33 };
2934};
3136export type MockupServer = {
3338 url: string;
3439 token: string;
3540 result: Promise<MockupResult>;
41 present(request: MockupRequest): Promise<MockupResult>;
42 progress(message: string): void;
43 settled(): void;
3644 close(reason: string): void;
3745};
4553 return `${path} must be an HTML fragment, not a full document. Remove <!doctype>, <html>, <head>, <body>; keep only content for the card.`;
48export async function executeMockup(
49 params: unknown,
50 signal: AbortSignal | undefined,
51 ctx: { hasUI: boolean; ui: { notify(message: string, level: "info"): void } },
52) {
53 const request = validateMockupRequest(params);
54 const server = await startMockupServer(request, {
55 openBrowser: process.env.PI_MOCKUP_NO_OPEN !== "1",
56 });
57 if (ctx.hasUI) ctx.ui.notify(`Mockup open: ${server.url}`, "info");
58 try {
59 const result = await abortable(server.result, signal, () =>
60 server.close("aborted"),
61 );
62 return {
63 content: [{ type: "text" as const, text: JSON.stringify(result) }],
64 details: result,
65 };
66 } finally {
67 server.close("done");
68 }
69}
7156export function validateMockupRequest(value: unknown): MockupRequest {
7257 if (!isRecord(value)) throw new Error("mockup args must be an object");
7358 assertKnownKeys(value, new Set(["title", "question", "options", "multi"]));
116101export async function startMockupServer(
117102 request: MockupRequest,
118 options: { openBrowser?: boolean } = {},
103 options: { openBrowser?: boolean; abortAgent?: () => boolean } = {},
119104): Promise<MockupServer> {
120 const normalized = validateMockupRequest(request);
105 let current = validateMockupRequest(request);
121106 const browserKey = `${randomUUID()}-${randomUUID()}`;
122107 const id = randomUUID();
108 const clients = new Set<ServerResponse>();
123109 let server!: Server;
124 let finished = false;
110 let closed = false;
125111 let timeout: NodeJS.Timeout | undefined;
126112 let resolveResult!: (result: MockupResult) => void;
127113 let rejectResult!: (error: Error) => void;
128 const result = new Promise<MockupResult>((resolve, reject) => {
129 resolveResult = resolve;
130 rejectResult = reject;
131 });
114 let result = round();
115 let waiting = true;
116 let stopRequested = false;
133 const finish = (result: MockupResult) => {
134 if (finished) return;
135 finished = true;
118 function round(): Promise<MockupResult> {
119 return new Promise<MockupResult>((resolve, reject) => {
120 resolveResult = resolve;
121 rejectResult = reject;
122 });
123 }
124 function clearRoundTimeout(): void {
136125 if (timeout) clearTimeout(timeout);
126 timeout = undefined;
127 }
128 function armRoundTimeout(): void {
129 clearRoundTimeout();
130 timeout = setTimeout(() =>
131 terminate(new Error("mockup timed out waiting for browser Submit")),
132 DEFAULT_TIMEOUT_MS);
133 timeout.unref();
134 }
135 function broadcast(type: string, data: unknown): void {
136 const event = `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`;
137 for (const client of clients) client.write(event);
138 }
139 function finish(value: MockupResult): void {
140 if (closed || !waiting) return;
141 waiting = false;
142 clearRoundTimeout();
143 resolveResult(value);
144 }
145 function terminate(error: Error): void {
146 if (closed) return;
147 closed = true;
148 clearRoundTimeout();
149 broadcast("progress", { message: error.message, terminal: true });
150 for (const client of clients) client.end();
151 clients.clear();
137152 server.close();
138 resolveResult(result);
139 };
140 const fail = (error: Error) => {
141 if (finished) return;
142 finished = true;
143 if (timeout) clearTimeout(timeout);
144 server.close();
145 rejectResult(error);
146 };
153 if (waiting) rejectResult(error);
154 }
148156 server = createServer(
149157 (req, res) =>
150158 void dispatch(req, res, {
151 request: normalized,
159 get request() {
160 return current;
161 },
152162 ["token"]: browserKey,
163 clients,
153164 finish,
165 abortAgent: () => {
166 stopRequested = options.abortAgent?.() === true;
167 return stopRequested;
168 },
154169 }),
155170 );
156171 await listen(server);
158173 if (!address || typeof address === "string")
159174 throw new Error("Failed to bind mockup server");
160175 const url = `http://127.0.0.1:${address.port}/?k=${browserKey}`;
161 timeout = setTimeout(
162 () => fail(new Error("mockup timed out waiting for browser Submit")),
163 DEFAULT_TIMEOUT_MS,
164 );
165 timeout.unref();
176 armRoundTimeout();
166177 if (options.openBrowser) void openBrowser(url);
167178 return {
168179 id,
169180 url,
170181 ["token"]: browserKey,
171182 result,
183 present(request: MockupRequest) {
184 if (closed) throw new Error("mockup server is closed");
185 if (waiting) throw new Error("mockup already awaits browser feedback");
186 current = validateMockupRequest(request);
187 result = round();
188 waiting = true;
189 stopRequested = false;
190 armRoundTimeout();
191 broadcast("revision", {});
192 return result;
193 },
194 progress(message: string) {
195 if (!closed) broadcast("progress", { message, terminal: false });
196 },
197 settled() {
198 if (closed || waiting) return;
199 broadcast("progress", {
200 message: stopRequested
201 ? "Agent stopped."
202 : "Agent finished without another mockup.",
203 terminal: true,
204 });
205 },
172206 close(reason: string) {
173 if (finished) return;
174 finished = true;
175 if (timeout) clearTimeout(timeout);
176 server.close();
177 rejectResult(new Error(`mockup closed: ${reason}`));
207 terminate(new Error(`mockup closed: ${reason}`));
178208 },
179209 };
222252 </section>
223253 </div>
224254</section>
255<section id="progress" class="progress" hidden aria-live="polite">
256 <div class="progress-card">
257 <div class="spinner" aria-hidden="true"></div>
258 <div>
259 <h2 id="progress-title">Feedback received</h2>
260 <p id="progress-time">0s elapsed</p>
261 </div>
262 <button id="stop-agent" type="button" class="secondary">Stop agent</button>
263 </div>
264</section>
225265<script>window.__MOCKUP_TOKEN__ = ${JSON.stringify(browserKey)};</script>
226266<script>${CLIENT_JS}</script>
227267</body>
242282type Ctx = {
243 request: MockupRequest;
283 readonly request: MockupRequest;
244284 token: string;
285 clients: Set<ServerResponse>;
245286 finish(result: MockupResult): void;
287 abortAgent(): boolean;
246288};
248290async function dispatch(req: IncomingMessage, res: ServerResponse, ctx: Ctx) {
259301 }
260302 if (!authorized(req, ctx.token))
261303 return json(res, 401, { error: "unauthorized" });
304 if (req.method === "GET" && url.pathname === "/api/events") {
305 res.writeHead(200, {
306 "Content-Type": "text/event-stream; charset=utf-8",
307 "Cache-Control": "no-store",
308 Connection: "keep-alive",
309 });
310 res.write(": connected\n\n");
311 ctx.clients.add(res);
312 res.once("close", () => ctx.clients.delete(res));
313 return;
314 }
262315 if (req.method === "POST" && url.pathname === "/api/submit") {
263316 const result = parseResult(JSON.parse(await readBody(req)), ctx.request);
264317 json(res, 200, { ok: true });
265318 ctx.finish(result);
266319 return;
267320 }
321 if (req.method === "POST" && url.pathname === "/api/abort") {
322 if (!ctx.abortAgent())
323 return json(res, 409, { error: "Pi has no active agent work" });
324 json(res, 200, { ok: true });
325 return;
326 }
268327 json(res, 404, { error: "not found" });
269328 } catch (error) {
270329 json(res, 400, {
299358 const annotations = value.annotations.map((raw, index) =>
300359 parseAnnotation(raw, index, optionIds),
301360 );
302 return { action, selected, notes, annotations };
361 const client = isRecord(value.client) ? value.client : {};
362 const viewport = isRecord(client.viewport) ? client.viewport : {};
363 const review = {
364 submittedAt: new Date().toISOString(),
365 userAgent: optionalString(client.userAgent, "client.userAgent") ?? "",
366 viewport: {
367 width: nonNegativeNumber(viewport.width, "client.viewport.width"),
368 height: nonNegativeNumber(viewport.height, "client.viewport.height"),
369 devicePixelRatio: nonNegativeNumber(
370 viewport.devicePixelRatio,
371 "client.viewport.devicePixelRatio",
372 ),
373 },
374 };
375 return { action, selected, notes, annotations, review };
305378function parseAnnotation(
396469 if (env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }];
397470 if (platform === "darwin") return [{ command: "open", args: [url] }];
398471 if (platform === "win32")
399 return [{ command: "explorer.exe", args: [url], windowsHide: true }];
472 return [
473 {
474 command: "rundll32.exe",
475 args: ["url.dll,FileProtocolHandler", url],
476 windowsHide: true,
477 },
478 ];
400479 return [
401480 { command: "xdg-open", args: [url] },
402481 { command: "wslview", args: [url] },
426505 });
429function abortable<T>(
430 promise: Promise<T>,
431 signal: AbortSignal | undefined,
432 abort: () => void,
433): Promise<T> {
434 if (!signal) return promise;
435 if (signal.aborted) {
436 abort();
437 return Promise.reject(new Error("mockup aborted"));
438 }
439 return new Promise((resolve, reject) => {
440 const onAbort = () => {
441 abort();
442 reject(new Error("mockup aborted"));
443 };
444 signal.addEventListener("abort", onAbort, { once: true });
445 promise
446 .then(resolve, reject)
447 .finally(() => signal.removeEventListener("abort", onAbort));
448 });
449}
451508function requiredString(value: unknown, name: string): string {
452509 if (typeof value !== "string") throw new Error(`${name} must be a string`);
453510 return value;
461518function unitNumber(value: unknown, name: string): number {
462 if (
463 typeof value !== "number" ||
464 !Number.isFinite(value) ||
465 value < 0 ||
466 value > 1
467 )
468 throw new Error(`${name} must be a number between 0 and 1`);
519 const number = nonNegativeNumber(value, name);
520 if (number > 1) throw new Error(`${name} must be a number between 0 and 1`);
521 return number;
522}
524function nonNegativeNumber(value: unknown, name: string): number {
525 if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
526 throw new Error(`${name} must be a non-negative number`);
469527 return value;
545603.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; }
546604.annotation-row textarea { width:100%; min-height:2.5rem; border:1px solid var(--line); background:var(--bg); color:var(--text); padding:.35rem; }
547605.empty { color:var(--muted); padding:.7rem; border:1px dashed var(--soft); }
606.progress { position:fixed; inset:0; z-index:20; background:color-mix(in srgb, var(--bg), transparent 12%); display:grid; place-items:center; padding:1rem; }
607.progress[hidden] { display:none; }
608.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%); }
609.progress-card h2 { margin:0; font-size:1rem; }
610.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; }
611.progress.terminal .spinner { animation:none; border-color:var(--accent); }
612@keyframes spin { to { transform:rotate(360deg); } }
548613@media (max-width:720px) {
549614 body { grid-template-rows:auto minmax(260px,1fr) auto; }
550615 .topbar { padding:.75rem; }
625690 if (!frag) return;
626691 const bubble = document.createElement("div");
627692 bubble.className = "pin-bubble";
628 bubble.style.left = Math.min(82, Math.max(2, a.x * 100)) + "%";
693 if (a.x > 0.5) bubble.style.right = Math.min(82, Math.max(2, (1 - a.x) * 100)) + "%";
694 else bubble.style.left = Math.min(82, Math.max(2, a.x * 100)) + "%";
629695 bubble.style.top = Math.min(82, Math.max(2, a.y * 100)) + "%";
630696 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>';
631697 const text = $("textarea", bubble);
645711 button.type = "button";
646712 button.className = "pin";
647713 button.textContent = String(i + 1);
648 button.style.left = (a.x * 100) + "%";
649 button.style.top = (a.y * 100) + "%";
714 button.style.left = "clamp(14px, " + (a.x * 100) + "%, calc(100% - 14px))";
715 button.style.top = "clamp(14px, " + (a.y * 100) + "%, calc(100% - 14px))";
650716 button.addEventListener("click", e => {
651717 e.stopPropagation();
652718 showBubble(i);
684750 $(".fragment", card).addEventListener("click", e => { if (armed === id) addPin(id, e); else select(id); });
685751});
686752reviveFragments();
687async function submit(action) {
688 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()) }) });
689 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>';
753let progressStarted = 0;
754let progressTimer = null;
755function showProgress(message, terminal = false) {
756 const progress = $("#progress");
757 progress.hidden = false;
758 progress.classList.toggle("terminal", terminal);
759 $("#progress-title").textContent = message;
760 $("#stop-agent").hidden = terminal;
761 if (!progressStarted) progressStarted = Date.now();
762 const updateTime = () => { $("#progress-time").textContent = Math.floor((Date.now() - progressStarted) / 1000) + "s elapsed"; };
763 updateTime();
764 if (progressTimer) clearInterval(progressTimer);
765 if (!terminal) progressTimer = setInterval(updateTime, 1000);
767const events = new EventSource("/api/events");
768events.addEventListener("revision", () => location.reload());
769events.addEventListener("progress", event => {
770 const state = JSON.parse(event.data);
771 showProgress(state.message, state.terminal === true);
772});
773async function submit(action) {
774 if (action === "iterate") showProgress("Feedback received. Pi is working.");
775 const body = {
776 action,
777 selected:[...selected],
778 notes:$("#global-notes").value.trim(),
779 annotations:annotations.filter(a => a.note.trim()),
780 client:{
781 userAgent:navigator.userAgent,
782 viewport:{ width:window.innerWidth, height:window.innerHeight, devicePixelRatio:window.devicePixelRatio },
783 },
784 };
785 const res = await fetch("/api/submit", { method:"POST", headers:{ Authorization:"Bearer " + window.__MOCKUP_TOKEN__, "Content-Type":"application/json" }, body:JSON.stringify(body) });
786 if (!res.ok) {
787 $("#progress").hidden = true;
788 alert(await res.text());
789 return;
790 }
791 if (action === "accept") {
792 showProgress("Accepted. You can close this tab.", true);
793 setTimeout(() => window.close(), 100);
794 }
795}
796$("#stop-agent").addEventListener("click", async () => {
797 showProgress("Stopping agent…");
798 const res = await fetch("/api/abort", { method:"POST", headers:{ Authorization:"Bearer " + window.__MOCKUP_TOKEN__ } });
799 if (!res.ok) showProgress("Pi has no active agent work.", true);
800});
691801$("#accept").addEventListener("click", () => submit("accept"));
692802$("#iterate").addEventListener("click", () => submit("iterate"));
693803sync();