@blackbelt-technology/frontend-mockup-loop 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.pi/skills/frontend-mockup-loop/SKILL.md +87 -8
- package/README.md +47 -2
- package/package.json +43 -4
- package/references/live-mock-site.md +332 -0
- package/site/Site.tsx +627 -0
- package/site/clock.ts +39 -0
- package/site/fixtures.ts +144 -0
- package/site/frame-env.ts +59 -0
- package/site/kit.tsx +175 -0
- package/site/main.tsx +11 -0
- package/site/pane-runtime.ts +230 -0
- package/site/pane-scroll-guard.ts +70 -0
- package/site/ring-line.ts +100 -0
- package/site/script.ts +201 -0
- package/site/site.css +179 -0
- package/site/step-gate.ts +138 -0
- package/site/tsconfig.json +16 -0
- package/site/virtual.d.ts +16 -0
- package/src/extension.ts +189 -58
- package/src/mock-site/base.d.mts +2 -0
- package/src/mock-site/base.mjs +28 -0
- package/src/mock-site/browser.d.mts +8 -0
- package/src/mock-site/browser.mjs +72 -0
- package/src/mock-site/capture.d.mts +8 -0
- package/src/mock-site/capture.mjs +221 -0
- package/src/mock-site/check.mjs +8 -0
- package/src/mock-site/cli.d.mts +3 -0
- package/src/mock-site/cli.mjs +96 -0
- package/src/mock-site/decisions.d.mts +6 -0
- package/src/mock-site/decisions.mjs +71 -0
- package/src/mock-site/discover.d.mts +7 -0
- package/src/mock-site/discover.mjs +137 -0
- package/src/mock-site/env.d.mts +15 -0
- package/src/mock-site/env.mjs +228 -0
- package/src/mock-site/frameworks.d.mts +5 -0
- package/src/mock-site/frameworks.mjs +27 -0
- package/src/mock-site/headless.d.mts +9 -0
- package/src/mock-site/headless.mjs +207 -0
- package/src/mock-site/locate.d.mts +3 -0
- package/src/mock-site/locate.mjs +30 -0
- package/src/mock-site/options.d.mts +19 -0
- package/src/mock-site/options.mjs +45 -0
- package/src/mock-site/plugin.d.mts +21 -0
- package/src/mock-site/plugin.mjs +191 -0
- package/src/mock-site/refs.d.mts +7 -0
- package/src/mock-site/refs.mjs +65 -0
- package/src/mock-site/serve-cli.mjs +43 -0
- package/src/mock-site/video.mjs +8 -0
- package/src/mock-site-serve.ts +186 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// GENERIC step gate (framework-free): the pause / hidden / step-forward / step-back state
|
|
2
|
+
// machine of one scripted pane. Indices count COMPLETED steps `k` (0..N). The runner calls
|
|
3
|
+
// `wait(k)` before step k+1 and `wait(N)` at the end of a loop; a held wait resolves when a
|
|
4
|
+
// step is released and rejects with `Rewind(to)` when the reviewer steps back.
|
|
5
|
+
// States: playing | held(k) | running(k, q) | rewinding | stopped.
|
|
6
|
+
// See change: mock-player-step-controls (design D2).
|
|
7
|
+
|
|
8
|
+
/** Thrown into the runner by a step back: remount, replay `to` steps silently, hold. */
|
|
9
|
+
export class Rewind extends Error {
|
|
10
|
+
constructor(readonly to: number) {
|
|
11
|
+
super(`rewind to step ${to}`);
|
|
12
|
+
this.name = "Rewind";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type GateState =
|
|
17
|
+
| { kind: "playing" }
|
|
18
|
+
| { kind: "held"; k: number }
|
|
19
|
+
| { kind: "running"; k: number; q: number }
|
|
20
|
+
| { kind: "rewinding" }
|
|
21
|
+
| { kind: "stopped" };
|
|
22
|
+
|
|
23
|
+
/** What the shell sees (`mkGate`): running and rewinding are both `busy`. */
|
|
24
|
+
export type GateView = "playing" | "held" | "busy" | "stopped";
|
|
25
|
+
|
|
26
|
+
export interface StepGate {
|
|
27
|
+
readonly state: GateState;
|
|
28
|
+
readonly view: GateView;
|
|
29
|
+
/** Before step k+1 (or at the loop end, k = N). `hold` = rest even when playing (finished one-shot). */
|
|
30
|
+
wait(k: number, hold?: boolean): Promise<void>;
|
|
31
|
+
/** Reviewer input (`mkStep`). */
|
|
32
|
+
step(dir: 1 | -1): void;
|
|
33
|
+
setPaused(on: boolean): void;
|
|
34
|
+
setHidden(on: boolean): void;
|
|
35
|
+
/** After a failed loop: every input is dropped. */
|
|
36
|
+
stop(): void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface StepGateOptions {
|
|
40
|
+
/** Script length N. */
|
|
41
|
+
steps: number;
|
|
42
|
+
/** Forward at N starts the next loop (else a no-op). */
|
|
43
|
+
loop: boolean;
|
|
44
|
+
/** Entered `held(k)`. */
|
|
45
|
+
onHeld?: (k: number) => void;
|
|
46
|
+
onChange?: (view: GateView) => void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const viewOf = (s: GateState): GateView =>
|
|
50
|
+
s.kind === "running" || s.kind === "rewinding" ? "busy" : s.kind;
|
|
51
|
+
|
|
52
|
+
export function createStepGate(o: StepGateOptions): StepGate {
|
|
53
|
+
let paused = false;
|
|
54
|
+
let hidden = false;
|
|
55
|
+
let st: GateState = { kind: "playing" };
|
|
56
|
+
let view: GateView = "playing";
|
|
57
|
+
let pending: { resolve: () => void; reject: (e: Rewind) => void } | null = null;
|
|
58
|
+
/** Holding a finished one-shot: unpause does not release it. */
|
|
59
|
+
let forced = false;
|
|
60
|
+
/** A step released (or queued) while hidden: runs once visible. */
|
|
61
|
+
let credit = false;
|
|
62
|
+
/** Back pressed while a step ran: rewind when it ends. */
|
|
63
|
+
let back = false;
|
|
64
|
+
let lastK = 0;
|
|
65
|
+
|
|
66
|
+
const set = (s: GateState) => {
|
|
67
|
+
st = s;
|
|
68
|
+
const v = viewOf(s);
|
|
69
|
+
if (v !== view) { view = v; o.onChange?.(v); }
|
|
70
|
+
};
|
|
71
|
+
const take = () => { const p = pending; pending = null; credit = false; return p; };
|
|
72
|
+
/** Release the held step k+1 (or the next loop at k = N). */
|
|
73
|
+
const go = (k: number) => { const p = take(); set({ kind: "running", k, q: 0 }); p?.resolve(); };
|
|
74
|
+
const play = () => { const p = take(); set({ kind: "playing" }); p?.resolve(); };
|
|
75
|
+
/** Forward while held(k): one step (at N: next loop when looping), or a credit while hidden. */
|
|
76
|
+
const forward = (k: number) => {
|
|
77
|
+
if (credit || (k >= o.steps && (!o.loop || forced))) return;
|
|
78
|
+
if (hidden) credit = true;
|
|
79
|
+
else go(k);
|
|
80
|
+
};
|
|
81
|
+
/** Back while held(k): rewind to the step before. */
|
|
82
|
+
const backward = (k: number) => {
|
|
83
|
+
const p = take();
|
|
84
|
+
set({ kind: "rewinding" });
|
|
85
|
+
p?.reject(new Rewind(Math.max(0, k - 1)));
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
get state() { return st; },
|
|
90
|
+
get view() { return view; },
|
|
91
|
+
wait(k, hold = false) {
|
|
92
|
+
lastK = k;
|
|
93
|
+
forced = hold;
|
|
94
|
+
if (st.kind === "stopped") return Promise.resolve();
|
|
95
|
+
if (st.kind === "running" && back) {
|
|
96
|
+
back = false;
|
|
97
|
+
set({ kind: "rewinding" });
|
|
98
|
+
return Promise.reject(new Rewind(Math.max(0, k - 1)));
|
|
99
|
+
}
|
|
100
|
+
const queued = st.kind === "running" && st.q > 0 && (k < o.steps || o.loop) && !forced;
|
|
101
|
+
if (!forced && !paused && !hidden) { set({ kind: "playing" }); return Promise.resolve(); }
|
|
102
|
+
if (queued && !hidden) { set({ kind: "running", k, q: 0 }); return Promise.resolve(); }
|
|
103
|
+
return new Promise<void>((resolve, reject) => {
|
|
104
|
+
pending = { resolve, reject };
|
|
105
|
+
credit = queued;
|
|
106
|
+
set({ kind: "held", k });
|
|
107
|
+
o.onHeld?.(k);
|
|
108
|
+
});
|
|
109
|
+
},
|
|
110
|
+
step(dir) {
|
|
111
|
+
if (st.kind === "held") (dir === 1 ? forward : backward)(st.k);
|
|
112
|
+
else if (st.kind === "running") {
|
|
113
|
+
if (dir === 1) set({ ...st, q: 1 });
|
|
114
|
+
else { back = true; set({ ...st, q: 0 }); }
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
setPaused(on) {
|
|
118
|
+
paused = on;
|
|
119
|
+
if (on) {
|
|
120
|
+
if (st.kind === "playing") set({ kind: "running", k: lastK, q: 0 });
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
back = false;
|
|
124
|
+
if (st.kind === "running") set({ kind: "playing" });
|
|
125
|
+
else if (st.kind === "held") {
|
|
126
|
+
credit = false;
|
|
127
|
+
if (!hidden && !forced) play();
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
setHidden(on) {
|
|
131
|
+
hidden = on;
|
|
132
|
+
if (on || st.kind !== "held") return;
|
|
133
|
+
if (credit) go(st.k);
|
|
134
|
+
else if (!paused && !forced) play();
|
|
135
|
+
},
|
|
136
|
+
stop() { pending = null; back = false; credit = false; set({ kind: "stopped" }); },
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
|
5
|
+
"module": "ESNext",
|
|
6
|
+
"moduleResolution": "bundler",
|
|
7
|
+
"jsx": "react-jsx",
|
|
8
|
+
"strict": true,
|
|
9
|
+
"noEmit": true,
|
|
10
|
+
"allowJs": true,
|
|
11
|
+
"allowImportingTsExtensions": true,
|
|
12
|
+
"skipLibCheck": true,
|
|
13
|
+
"isolatedModules": true
|
|
14
|
+
},
|
|
15
|
+
"include": ["*.tsx", "*.ts", "__tests__/*.ts", "../src/mock-site/refs.mjs"]
|
|
16
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Types of the mock-site plugin's virtual modules + the kit alias.
|
|
2
|
+
declare module "virtual:mock-site/config" {
|
|
3
|
+
export const MOCK_CONFIG: { title: string; themes: Array<{ id: string; label: string; attrs?: Record<string, string | null>; system?: { dark: string; light: string } }> };
|
|
4
|
+
}
|
|
5
|
+
declare module "virtual:mock-site/mocks" {
|
|
6
|
+
import type { Mock } from "./kit.tsx";
|
|
7
|
+
export const MOCKS: Array<{ id: string; mock: Mock }>;
|
|
8
|
+
export const ERRORS: string[];
|
|
9
|
+
}
|
|
10
|
+
declare module "virtual:mock-site/app" {
|
|
11
|
+
import type { ComponentType, ReactNode } from "react";
|
|
12
|
+
export const setup: (() => void | Promise<void>) | undefined;
|
|
13
|
+
export const Providers: ComponentType<{ children: ReactNode }>;
|
|
14
|
+
}
|
|
15
|
+
interface ImportMeta { readonly hot?: { on(event: string, cb: () => void): void }; readonly env?: { readonly BASE_URL?: string } }
|
|
16
|
+
declare module "*.css";
|
package/src/extension.ts
CHANGED
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
* desktop widths via Playwright (dynamic, optional)
|
|
12
12
|
* and return them plus a scoring rubric for the
|
|
13
13
|
* agent's vision pass.
|
|
14
|
+
* - `serve_mock_site` — start the project's live-component mock site
|
|
15
|
+
* (real app components, rings, read-only decisions)
|
|
16
|
+
* on an isolated port through the project's own
|
|
17
|
+
* launcher and inherited build config.
|
|
14
18
|
* - `init_ui_contract` — scaffold a token-referencing ui-contract.md
|
|
15
19
|
* control plane (the cross-screen consistency
|
|
16
20
|
* source of truth) if one is absent.
|
|
@@ -22,15 +26,19 @@
|
|
|
22
26
|
* React/Tailwind/shadcn (or plain HTML) project.
|
|
23
27
|
*/
|
|
24
28
|
|
|
25
|
-
import
|
|
26
|
-
import { Type } from "typebox";
|
|
27
|
-
import * as http from "node:http";
|
|
29
|
+
import { randomBytes } from "node:crypto";
|
|
28
30
|
import * as fs from "node:fs";
|
|
29
31
|
import * as fsp from "node:fs/promises";
|
|
30
|
-
import * as
|
|
32
|
+
import * as http from "node:http";
|
|
31
33
|
import * as os from "node:os";
|
|
32
|
-
import
|
|
34
|
+
import * as path from "node:path";
|
|
35
|
+
import { pipeline } from "node:stream";
|
|
36
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
37
|
+
import { Type } from "typebox";
|
|
38
|
+
import { INSTALL_HINT, launchChromium } from "./mock-site/browser.mjs";
|
|
39
|
+
import { DEFAULT_MOCK_SITE_PORT, children as mockSiteChildren, type ReservationEvents, startMockSite, stopAllMockSites, stopMockSite } from "./mock-site-serve.js";
|
|
33
40
|
import { loadContract, refreshContract } from "./presets/contract.js";
|
|
41
|
+
import { listPresets, resolvePreset } from "./presets/registry.js";
|
|
34
42
|
import { loadRubric, validateMockup } from "./presets/validators.js";
|
|
35
43
|
|
|
36
44
|
// ──────────────────────────────────────────────────────────────────────────
|
|
@@ -72,44 +80,91 @@ function lanIp(): string | null {
|
|
|
72
80
|
return null;
|
|
73
81
|
}
|
|
74
82
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
const
|
|
83
|
+
/** True when `target` is `root` or below it (real paths; not a string prefix, so `<root>-x` is outside). */
|
|
84
|
+
function isWithin(root: string, target: string): boolean {
|
|
85
|
+
const rel = path.relative(root, target);
|
|
86
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Exact loopback Host forms (host part case-insensitive) carrying the bound port. */
|
|
90
|
+
function isLoopbackHost(host: string | undefined, port: number): boolean {
|
|
91
|
+
const m = /^(localhost|127\.0\.0\.1|\[::1\])(?::(\d+))?$/i.exec(host ?? "");
|
|
92
|
+
// A browser drops the default port from `Host`, so an omitted port means 80.
|
|
93
|
+
return !!m && (m[2] === undefined ? port === 80 : Number(m[2]) === port);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Static server. Check order: token (404) → loopback Host (421, loopback mode
|
|
98
|
+
* only) → path (400 malformed, 403 escaping `..`, 404 dotfile segment) →
|
|
99
|
+
* realpath confinement (404 ELOOP/ENOENT, 403 other failure or outside root).
|
|
100
|
+
* The realpath-then-open race is a named residual (the agent already writes
|
|
101
|
+
* the served directory).
|
|
102
|
+
*/
|
|
103
|
+
function startStaticServer(rootDir: string, port: number, opts: { lan: boolean; token: string }): Promise<http.Server> {
|
|
104
|
+
// `rootDir` is the canonical root the tool already admitted against the session cwd; never re-resolve it here.
|
|
105
|
+
const root = rootDir;
|
|
106
|
+
const prefix = `/${opts.token}/`;
|
|
107
|
+
const send = (res: http.ServerResponse, status: number, body = ""): void => {
|
|
108
|
+
res.writeHead(status, { "content-type": "text/plain" }).end(body);
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/** realpath + confinement; returns the real path or the status to answer. */
|
|
112
|
+
async function resolveInside(target: string): Promise<string | number> {
|
|
113
|
+
let real: string;
|
|
78
114
|
try {
|
|
79
|
-
|
|
80
|
-
let rel = path.normalize(urlPath).replace(/^(\.\.[/\\])+/, "");
|
|
81
|
-
let target = path.join(root, rel);
|
|
82
|
-
// Confine to root — reject traversal escapes.
|
|
83
|
-
if (!target.startsWith(root)) {
|
|
84
|
-
res.writeHead(403).end("Forbidden");
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
let stat: fs.Stats | null = null;
|
|
88
|
-
try {
|
|
89
|
-
stat = fs.statSync(target);
|
|
90
|
-
} catch {
|
|
91
|
-
stat = null;
|
|
92
|
-
}
|
|
93
|
-
if (stat?.isDirectory()) {
|
|
94
|
-
target = path.join(target, "index.html");
|
|
95
|
-
}
|
|
96
|
-
if (!fs.existsSync(target)) {
|
|
97
|
-
res.writeHead(404, { "content-type": "text/plain" }).end(`Not found: ${rel}`);
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
const ext = path.extname(target).toLowerCase();
|
|
101
|
-
res.writeHead(200, {
|
|
102
|
-
"content-type": MIME[ext] ?? "application/octet-stream",
|
|
103
|
-
"cache-control": "no-store",
|
|
104
|
-
});
|
|
105
|
-
fs.createReadStream(target).pipe(res);
|
|
115
|
+
real = await fsp.realpath(target);
|
|
106
116
|
} catch (err) {
|
|
107
|
-
|
|
117
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
118
|
+
return code === "ELOOP" || code === "ENOENT" || code === "ENOTDIR" ? 404 : 403;
|
|
108
119
|
}
|
|
120
|
+
return isWithin(root, real) ? real : 403;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function handle(req: http.IncomingMessage, res: http.ServerResponse, boundPort: number): Promise<void> {
|
|
124
|
+
const rawPath = (req.url ?? "/").split(/[?#]/)[0];
|
|
125
|
+
if (!rawPath.startsWith(prefix)) return send(res, 404);
|
|
126
|
+
if (!opts.lan && !isLoopbackHost(req.headers.host, boundPort)) return send(res, 421, "Misdirected Request");
|
|
127
|
+
|
|
128
|
+
let rel: string;
|
|
129
|
+
try {
|
|
130
|
+
rel = decodeURIComponent(rawPath.slice(prefix.length));
|
|
131
|
+
} catch {
|
|
132
|
+
return send(res, 400, "Bad Request");
|
|
133
|
+
}
|
|
134
|
+
if (rel.includes("\0")) return send(res, 400, "Bad Request");
|
|
135
|
+
|
|
136
|
+
const segments = rel.split(/[\\/]/).filter(Boolean);
|
|
137
|
+
let depth = 0;
|
|
138
|
+
for (const seg of segments) {
|
|
139
|
+
depth += seg === ".." ? -1 : seg === "." ? 0 : 1;
|
|
140
|
+
if (depth < 0) return send(res, 403, "Forbidden");
|
|
141
|
+
}
|
|
142
|
+
if (segments.some((seg) => seg.startsWith("."))) return send(res, 404, `Not found: ${rel}`);
|
|
143
|
+
|
|
144
|
+
let real = await resolveInside(path.join(root, ...segments));
|
|
145
|
+
if (typeof real === "string" && (await fsp.stat(real)).isDirectory()) {
|
|
146
|
+
real = await resolveInside(path.join(real, "index.html"));
|
|
147
|
+
}
|
|
148
|
+
if (typeof real === "number") return send(res, real, real === 404 ? `Not found: ${rel}` : "Forbidden");
|
|
149
|
+
if (!(await fsp.stat(real)).isFile()) return send(res, 404, `Not found: ${rel}`);
|
|
150
|
+
|
|
151
|
+
res.writeHead(200, {
|
|
152
|
+
"content-type": MIME[path.extname(real).toLowerCase()] ?? "application/octet-stream",
|
|
153
|
+
"cache-control": "no-store",
|
|
154
|
+
});
|
|
155
|
+
pipeline(fs.createReadStream(real), res, () => {});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const server = http.createServer((req, res) => {
|
|
159
|
+
const addr = server.address();
|
|
160
|
+
handle(req, res, typeof addr === "object" && addr ? addr.port : port).catch(() => {
|
|
161
|
+
if (!res.headersSent) send(res, 500, "Internal Server Error");
|
|
162
|
+
else res.destroy();
|
|
163
|
+
});
|
|
109
164
|
});
|
|
110
165
|
return new Promise((resolve, reject) => {
|
|
111
166
|
server.once("error", reject);
|
|
112
|
-
server.listen(port, "0.0.0.0", () => resolve(server));
|
|
167
|
+
server.listen(port, opts.lan ? "0.0.0.0" : "127.0.0.1", () => resolve(server));
|
|
113
168
|
});
|
|
114
169
|
}
|
|
115
170
|
|
|
@@ -197,19 +252,28 @@ export default function frontendMockupLoop(pi: ExtensionAPI): void {
|
|
|
197
252
|
name: "serve_mockup",
|
|
198
253
|
label: "Serve Mockup",
|
|
199
254
|
description:
|
|
200
|
-
"Serve a directory of static mockup files over HTTP
|
|
255
|
+
"Serve a directory of static mockup files over HTTP, bound to loopback (127.0.0.1) by default so the URL works only on this machine; pass lan:true to also reach it from the LAN (e.g. a phone). `dir` must be inside the session working directory. Every URL carries a private path token; use relative asset links (style.css) — root-relative links (/style.css) drop the token and 404. Hand the returned URL to the human for live review instead of a screenshot. Pass stop:true with a port to stop a running server.",
|
|
201
256
|
parameters: Type.Object({
|
|
202
257
|
dir: Type.Optional(
|
|
203
|
-
Type.String({ description: "Directory to serve (required unless stopping)." }),
|
|
258
|
+
Type.String({ description: "Directory to serve, inside the session working directory (required unless stopping)." }),
|
|
204
259
|
),
|
|
205
260
|
port: Type.Optional(
|
|
206
261
|
Type.Number({ description: "Port to bind. Omit for an ephemeral free port." }),
|
|
207
262
|
),
|
|
263
|
+
lan: Type.Optional(
|
|
264
|
+
Type.Boolean({ description: "Also listen on the LAN (0.0.0.0) for a phone check. Default false: loopback only." }),
|
|
265
|
+
),
|
|
208
266
|
stop: Type.Optional(
|
|
209
267
|
Type.Boolean({ description: "Stop the server bound to `port` instead of starting one." }),
|
|
210
268
|
),
|
|
211
269
|
}),
|
|
212
|
-
async execute(
|
|
270
|
+
async execute(
|
|
271
|
+
_id: string,
|
|
272
|
+
params: { dir?: string; port?: number; lan?: boolean; stop?: boolean },
|
|
273
|
+
_signal?: unknown,
|
|
274
|
+
_onUpdate?: unknown,
|
|
275
|
+
ctx?: { cwd?: string },
|
|
276
|
+
): ToolReturn {
|
|
213
277
|
try {
|
|
214
278
|
if (params.stop) {
|
|
215
279
|
if (params.port == null) {
|
|
@@ -227,25 +291,46 @@ export default function frontendMockupLoop(pi: ExtensionAPI): void {
|
|
|
227
291
|
if (!params.dir) {
|
|
228
292
|
return { content: [{ type: "text", text: "Error: dir required to start a server." }], details: {} };
|
|
229
293
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
294
|
+
// Root follows the session cwd (ctx.cwd), never the server's; process.cwd() only without ctx.
|
|
295
|
+
const cwd = ctx?.cwd ?? process.cwd();
|
|
296
|
+
const resolved = path.resolve(cwd, params.dir);
|
|
297
|
+
let root: string;
|
|
298
|
+
try {
|
|
299
|
+
root = await fsp.realpath(resolved);
|
|
300
|
+
if (!(await fsp.stat(root)).isDirectory()) throw new Error("not a directory");
|
|
301
|
+
} catch {
|
|
302
|
+
return { content: [{ type: "text", text: `Error: not a directory: ${resolved}` }], details: {} };
|
|
233
303
|
}
|
|
234
|
-
const
|
|
304
|
+
const realCwd = await fsp.realpath(cwd);
|
|
305
|
+
if (!isWithin(realCwd, root)) {
|
|
306
|
+
return {
|
|
307
|
+
content: [{ type: "text", text: `Error: dir must be inside the session working directory (${cwd}); ${root} is outside it. Move the mockup into the project and serve it from there.` }],
|
|
308
|
+
details: {},
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const lan = params.lan === true;
|
|
312
|
+
const token = randomBytes(16).toString("hex");
|
|
313
|
+
const server = await startStaticServer(root, params.port ?? 0, { lan, token });
|
|
235
314
|
const addr = server.address();
|
|
236
315
|
const port = typeof addr === "object" && addr ? addr.port : params.port ?? 0;
|
|
237
316
|
servers.set(port, server);
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const
|
|
317
|
+
// eslint-disable-next-line no-console
|
|
318
|
+
console.info(`[mockup-loop] serve_mockup bind=${lan ? "0.0.0.0" : "127.0.0.1"}:${port} lan=${lan} root=${root}`);
|
|
319
|
+
const local = `http://localhost:${port}/${token}/`;
|
|
320
|
+
const ip = lan ? lanIp() : null;
|
|
321
|
+
const lanUrl = lan ? (ip ? `http://${ip}:${port}/${token}/` : "(no LAN IPv4 detected)") : undefined;
|
|
322
|
+
const lines = [`Serving ${root}`, ` local: ${local}`];
|
|
323
|
+
if (lanUrl) lines.push(` LAN: ${lanUrl}`);
|
|
324
|
+
lines.push(
|
|
325
|
+
"",
|
|
326
|
+
lan
|
|
327
|
+
? "Show the local URL to the user. Use the LAN URL only for a phone check."
|
|
328
|
+
: "Show the local URL to the user. It is loopback-only (this machine); pass lan:true for a phone check.",
|
|
329
|
+
`Use relative asset links (style.css, not /style.css). Stop with serve_mockup{stop:true,port:${port}}.`,
|
|
330
|
+
);
|
|
241
331
|
return {
|
|
242
|
-
content: [
|
|
243
|
-
|
|
244
|
-
type: "text",
|
|
245
|
-
text: `Serving ${root}\n local: ${local}\n LAN: ${lan}\n\nOpen the LAN URL on a phone to check responsive. For canvas(), use the local URL. Stop with serve_mockup{stop:true,port:${port}}.`,
|
|
246
|
-
},
|
|
247
|
-
],
|
|
248
|
-
details: { port, root, local, lan },
|
|
332
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
333
|
+
details: { port, root, local, ...(lanUrl ? { lan: lanUrl } : {}) },
|
|
249
334
|
};
|
|
250
335
|
} catch (err) {
|
|
251
336
|
return { content: [{ type: "text", text: `serve_mockup failed: ${String(err)}` }], details: {} };
|
|
@@ -253,6 +338,39 @@ export default function frontendMockupLoop(pi: ExtensionAPI): void {
|
|
|
253
338
|
},
|
|
254
339
|
});
|
|
255
340
|
|
|
341
|
+
// ── serve_mock_site ──────────────────────────────────────────────────────
|
|
342
|
+
pi.registerTool({
|
|
343
|
+
name: "serve_mock_site",
|
|
344
|
+
label: "Serve Mock Site",
|
|
345
|
+
description:
|
|
346
|
+
"Start the project's live-component mock site (mockups/<id>/mock.tsx rendered with the app's real components, numbered rings, fixtures and scripted frames) through the project's own launcher and inherited build config (package.json mockSite, else detected). Show the returned URL to the user. Decisions are read-only in the site: record them with the mock-decide CLI. Localhost-only unless lan:true (LAN = view-only). Reserved ports are refused. Pass stop:true with a port to stop it.",
|
|
347
|
+
parameters: Type.Object({
|
|
348
|
+
dir: Type.Optional(Type.String({ description: "Project root (default: cwd)." })),
|
|
349
|
+
port: Type.Optional(Type.Number({ description: `Port (default ${DEFAULT_MOCK_SITE_PORT}).` })),
|
|
350
|
+
lan: Type.Optional(Type.Boolean({ description: "Also listen on the LAN for phone review (view-only)." })),
|
|
351
|
+
stop: Type.Optional(Type.Boolean({ description: "Stop the mock site on `port`." })),
|
|
352
|
+
base: Type.Optional(Type.String({ description: 'Serve the site under this URL path prefix, e.g. "/some/prefix/" (letters, digits, . _ ~ - segments; starts and ends with "/"). Omit it and the host may supply one; "/" means none.' })),
|
|
353
|
+
}),
|
|
354
|
+
async execute(_id: string, params: { dir?: string; port?: number; lan?: boolean; stop?: boolean; base?: unknown }): ToolReturn {
|
|
355
|
+
if (params.stop) {
|
|
356
|
+
const port = params.port ?? DEFAULT_MOCK_SITE_PORT;
|
|
357
|
+
const ok = await stopMockSite(port);
|
|
358
|
+
return { content: [{ type: "text", text: ok ? `Stopped mock site on port ${port}.` : `No mock site on port ${port}.` }], details: { port, stopped: ok } };
|
|
359
|
+
}
|
|
360
|
+
const r = await startMockSite({ ...params, events: (pi as { events?: ReservationEvents }).events });
|
|
361
|
+
if (!r.ok) return { content: [{ type: "text", text: `serve_mock_site failed: ${r.error}` }], details: { error: r.error } };
|
|
362
|
+
const lines = [`Mock site for ${r.root}`, ` local: ${r.local}`];
|
|
363
|
+
if (params.lan) {
|
|
364
|
+
lines.push(` LAN: ${r.lan ?? "(no LAN IPv4 detected)"}`);
|
|
365
|
+
lines.push("LAN clients are view-only. Project sources are readable on the LAN while it runs.");
|
|
366
|
+
}
|
|
367
|
+
lines.push(` launcher: ${r.launcher}`, ` app config: ${r.config}`);
|
|
368
|
+
if (r.note) lines.push(r.note);
|
|
369
|
+
lines.push("", `Show the URL to the user, with #ref links for anything you ask about. Record decisions with the CLI: mock-decide accept|reject <ref> [note]. Stop: serve_mock_site{stop:true,port:${r.port}}.`);
|
|
370
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { port: r.port, local: r.local, lan: r.lan, root: r.root, launcher: r.launcher, config: r.config } };
|
|
371
|
+
},
|
|
372
|
+
});
|
|
373
|
+
|
|
256
374
|
// ── score_mockup ───────────────────────────────────────────────────────
|
|
257
375
|
pi.registerTool({
|
|
258
376
|
name: "score_mockup",
|
|
@@ -317,7 +435,7 @@ export default function frontendMockupLoop(pi: ExtensionAPI): void {
|
|
|
317
435
|
{
|
|
318
436
|
type: "text",
|
|
319
437
|
text:
|
|
320
|
-
|
|
438
|
+
`Playwright not available. Install it to enable breakpoint capture:\n npm i -D playwright && ${INSTALL_HINT}\n\nMeanwhile, capture manually (e.g. the agent-browser CLI) at widths ` +
|
|
321
439
|
widths.join(", ") +
|
|
322
440
|
" and score against the rubric below." +
|
|
323
441
|
"\n" +
|
|
@@ -333,7 +451,17 @@ export default function frontendMockupLoop(pi: ExtensionAPI): void {
|
|
|
333
451
|
? path.resolve(params.outDir)
|
|
334
452
|
: await fsp.mkdtemp(path.join(os.tmpdir(), "mockup-shots-"));
|
|
335
453
|
await fsp.mkdir(outDir, { recursive: true });
|
|
336
|
-
|
|
454
|
+
let launched: { browser: any; build: string };
|
|
455
|
+
try {
|
|
456
|
+
launched = await launchChromium(pw.chromium);
|
|
457
|
+
} catch (e) {
|
|
458
|
+
const msg = String((e as Error).message ?? e);
|
|
459
|
+
return {
|
|
460
|
+
content: [{ type: "text", text: `${msg}\n\nMeanwhile, capture manually at widths ${widths.join(", ")} and score against the rubric below.\n${rubric}` }],
|
|
461
|
+
details: { playwright: true, browser: false, widths, error: msg },
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
const { browser, build } = launched;
|
|
337
465
|
const files: string[] = [];
|
|
338
466
|
for (const w of widths) {
|
|
339
467
|
const context = await browser.newContext({ viewport: { width: w, height: 900 } });
|
|
@@ -350,13 +478,13 @@ export default function frontendMockupLoop(pi: ExtensionAPI): void {
|
|
|
350
478
|
{
|
|
351
479
|
type: "text",
|
|
352
480
|
text:
|
|
353
|
-
`Captured ${files.length} screenshots — Read each, then fill the rubric:\n` +
|
|
481
|
+
`Captured ${files.length} screenshots${build === "pinned" ? "" : ` (cached browser ${build})`} — Read each, then fill the rubric:\n` +
|
|
354
482
|
files.map((f) => ` ${f}`).join("\n") +
|
|
355
483
|
"\n" +
|
|
356
484
|
rubric,
|
|
357
485
|
},
|
|
358
486
|
],
|
|
359
|
-
details: { playwright: true, files, outDir, widths },
|
|
487
|
+
details: { playwright: true, files, outDir, widths, browser: build },
|
|
360
488
|
};
|
|
361
489
|
} catch (err) {
|
|
362
490
|
return {
|
|
@@ -514,5 +642,8 @@ export default function frontendMockupLoop(pi: ExtensionAPI): void {
|
|
|
514
642
|
await new Promise<void>((r) => s.close(() => r()));
|
|
515
643
|
servers.delete(port);
|
|
516
644
|
}
|
|
645
|
+
await stopAllMockSites();
|
|
517
646
|
});
|
|
647
|
+
// Never orphan a Vite child holding the port when pi exits without a shutdown event.
|
|
648
|
+
process.once("exit", () => { for (const c of mockSiteChildren.values()) c.kill("SIGKILL"); });
|
|
518
649
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Base-path helpers for the mock site (D11). A `base` is explicit (`serve_mock_site{base}`, `--base`) or host-answered
|
|
3
|
+
// (`mock-site:base-reservation`); both pass the SAME allowlist. See change: serve-live-previews-on-capability-origin (D11).
|
|
4
|
+
|
|
5
|
+
/** Allowlist: `/seg/` repeated, segments of unreserved characters only (no `?`, `#`, `\`, `%`, spaces, control or non-ASCII). */
|
|
6
|
+
const BASE_SHAPE = /^\/([A-Za-z0-9._~-]+\/)+$/;
|
|
7
|
+
const BASE_MAX = 256;
|
|
8
|
+
const BASE_HELP = 'base must start and end with "/" and use only letters, digits and . _ ~ - in its segments, e.g. "/some/prefix/" (max 256 characters, no "." or ".." segment)';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `"/"` means "no base" (the site starts at root); anything else must match the allowlist.
|
|
12
|
+
* @param {unknown} v
|
|
13
|
+
* @returns {{ ok: true, base: string | null } | { ok: false, error: string }}
|
|
14
|
+
*/
|
|
15
|
+
export function validateBase(v) {
|
|
16
|
+
if (typeof v !== "string") return { ok: false, error: `invalid base: ${BASE_HELP}` };
|
|
17
|
+
if (v === "/") return { ok: true, base: null };
|
|
18
|
+
if (v.length > BASE_MAX || !BASE_SHAPE.test(v) || v.split("/").some((s) => s === "." || s === "..")) return { ok: false, error: `invalid base: ${BASE_HELP}` };
|
|
19
|
+
return { ok: true, base: v };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Join a site URL and a relative path with exactly one `/` between them.
|
|
24
|
+
* @param {string} url @param {string} rel
|
|
25
|
+
*/
|
|
26
|
+
export function joinUrl(url, rel) {
|
|
27
|
+
return `${url.replace(/\/+$/, "")}/${rel.replace(/^\/+/, "")}`;
|
|
28
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Types for browser.mjs (plain-JS module; see change: add-mock-site-exact-env).
|
|
2
|
+
export declare const INSTALL_HINT: string;
|
|
3
|
+
export declare function cachedChromiumBuilds(dir: string): { name: string; exe: string }[];
|
|
4
|
+
export declare function launchChromium(
|
|
5
|
+
chromium: { launch: (o: object) => Promise<any> },
|
|
6
|
+
launchOpts?: object,
|
|
7
|
+
deps?: { builds?: { name: string; exe: string }[] },
|
|
8
|
+
): Promise<{ browser: any; build: string }>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Chromium resolution for `score_mockup` and `mock-video`: launch Playwright's
|
|
3
|
+
// pinned build; when it is not installed, try the builds already in Playwright's
|
|
4
|
+
// browser cache, newest first, via `executablePath`. See change:
|
|
5
|
+
// add-mock-site-exact-env (design D7).
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as os from "node:os";
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
|
|
10
|
+
export const INSTALL_HINT = "npx playwright install chromium";
|
|
11
|
+
const EXE_CANDIDATES = [
|
|
12
|
+
"chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
|
|
13
|
+
"chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
|
|
14
|
+
"chrome-mac-arm64/Chromium.app/Contents/MacOS/Chromium",
|
|
15
|
+
"chrome-mac/Chromium.app/Contents/MacOS/Chromium",
|
|
16
|
+
"chrome-linux64/chrome",
|
|
17
|
+
"chrome-linux/chrome",
|
|
18
|
+
"chrome-win64/chrome.exe",
|
|
19
|
+
"chrome-win/chrome.exe",
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
/** Playwright's browser cache dir. @param {NodeJS.ProcessEnv} [env] @param {string} [platform] @param {string} [home] */
|
|
23
|
+
function playwrightCacheDir(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
24
|
+
if (env.PLAYWRIGHT_BROWSERS_PATH && env.PLAYWRIGHT_BROWSERS_PATH !== "0") return env.PLAYWRIGHT_BROWSERS_PATH;
|
|
25
|
+
if (platform === "darwin") return path.join(home, "Library", "Caches", "ms-playwright");
|
|
26
|
+
if (platform === "win32") return path.join(env.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), "ms-playwright");
|
|
27
|
+
return path.join(env.XDG_CACHE_HOME ?? path.join(home, ".cache"), "ms-playwright");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Cached `chromium-<build>` dirs holding a browser executable, newest first.
|
|
32
|
+
* @param {string} dir
|
|
33
|
+
* @returns {{ name: string, exe: string }[]}
|
|
34
|
+
*/
|
|
35
|
+
export function cachedChromiumBuilds(dir) {
|
|
36
|
+
if (!fs.existsSync(dir)) return [];
|
|
37
|
+
return fs.readdirSync(dir)
|
|
38
|
+
.filter((n) => /^chromium-\d+$/.test(n))
|
|
39
|
+
.sort((a, b) => Number(b.slice(9)) - Number(a.slice(9)))
|
|
40
|
+
.flatMap((name) => {
|
|
41
|
+
const exe = EXE_CANDIDATES.map((c) => path.join(dir, name, c)).find((p) => fs.existsSync(p));
|
|
42
|
+
return exe ? [{ name, exe }] : [];
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** @param {unknown} e */
|
|
47
|
+
const isMissingBrowser = (e) => /Executable doesn't exist|playwright install|browserType\.launch: .*not found/i.test(String(/** @type {Error} */ (e)?.message ?? e));
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {{ launch: (o: object) => Promise<any> }} chromium Playwright's `chromium`
|
|
51
|
+
* @param {object} [launchOpts]
|
|
52
|
+
* @param {{ builds?: { name: string, exe: string }[] }} [deps]
|
|
53
|
+
* @returns {Promise<{ browser: any, build: string }>} `build` = "pinned" or the cached dir used
|
|
54
|
+
*/
|
|
55
|
+
export async function launchChromium(chromium, launchOpts = {}, deps = {}) {
|
|
56
|
+
try {
|
|
57
|
+
return { browser: await chromium.launch(launchOpts), build: "pinned" };
|
|
58
|
+
} catch (e) {
|
|
59
|
+
if (!isMissingBrowser(e)) throw e;
|
|
60
|
+
}
|
|
61
|
+
const builds = deps.builds ?? cachedChromiumBuilds(playwrightCacheDir());
|
|
62
|
+
/** @type {string[]} */
|
|
63
|
+
const tried = [];
|
|
64
|
+
for (const b of builds) {
|
|
65
|
+
try {
|
|
66
|
+
return { browser: await chromium.launch({ ...launchOpts, executablePath: b.exe }), build: b.name };
|
|
67
|
+
} catch {
|
|
68
|
+
tried.push(b.name);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
throw new Error(`Playwright's pinned Chromium is not installed and no cached build launched (tried: ${tried.join(", ") || "none found"}). Install it: ${INSTALL_HINT}`);
|
|
72
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Types for capture.mjs (plain-JS module; see change: add-mock-site-exact-env).
|
|
2
|
+
export declare const REDACTED: string;
|
|
3
|
+
export declare const SECRET_PATTERNS: [string, RegExp][];
|
|
4
|
+
export declare function redactHar(har: any, extra?: string[]): any;
|
|
5
|
+
export declare function scanSecrets(har: any): { location: string; kind: string } | null;
|
|
6
|
+
export declare function harToFixtures(har: any, source: string): { version: 1; source: string; entries: { method: string; path: string; query: string; status: number; contentType: string; body: string }[] };
|
|
7
|
+
export declare function writeFixtures(har: any, o: { out: string; source: string; redact?: string[] }): { ok: true; file: string; count: number } | { ok: false; error: string };
|
|
8
|
+
export declare function run(argv: string[], deps?: { cwd?: string; record?: (url: string) => Promise<any>; redact?: string[] }): Promise<{ code: number; out: string }>;
|