@mushi-mushi/ux 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/cli.js +4963 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +1004 -0
- package/dist/index.js +4142 -0
- package/dist/index.js.map +1 -0
- package/package.json +78 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,4142 @@
|
|
|
1
|
+
// src/cursor-cloud.ts
|
|
2
|
+
import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "fs";
|
|
3
|
+
import { join as join2 } from "path";
|
|
4
|
+
|
|
5
|
+
// src/proc.ts
|
|
6
|
+
import { spawn, spawnSync } from "child_process";
|
|
7
|
+
function killTree(child) {
|
|
8
|
+
if (child.pid === void 0 || child.exitCode !== null) return;
|
|
9
|
+
if (process.platform === "win32") {
|
|
10
|
+
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
|
11
|
+
} else {
|
|
12
|
+
try {
|
|
13
|
+
process.kill(-child.pid, "SIGKILL");
|
|
14
|
+
} catch {
|
|
15
|
+
child.kill("SIGKILL");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function run(cmd, args, opts) {
|
|
20
|
+
const started = Date.now();
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const child = spawn(cmd, args, {
|
|
23
|
+
cwd: opts.cwd,
|
|
24
|
+
env: opts.env ?? process.env,
|
|
25
|
+
shell: opts.shell ?? false,
|
|
26
|
+
detached: process.platform !== "win32",
|
|
27
|
+
windowsHide: true,
|
|
28
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
29
|
+
});
|
|
30
|
+
let tail = "";
|
|
31
|
+
let stdout = "";
|
|
32
|
+
let partial = "";
|
|
33
|
+
let timedOut = false;
|
|
34
|
+
const onData = (chunk) => {
|
|
35
|
+
const text = chunk.toString("utf8");
|
|
36
|
+
tail = (tail + text).slice(-4096);
|
|
37
|
+
if (!opts.onLine) return;
|
|
38
|
+
partial += text;
|
|
39
|
+
const lines = partial.split(/\r?\n/);
|
|
40
|
+
partial = lines.pop() ?? "";
|
|
41
|
+
for (const line of lines) if (line.trim()) opts.onLine(line);
|
|
42
|
+
};
|
|
43
|
+
child.stdout?.on("data", (chunk) => {
|
|
44
|
+
if (stdout.length < 1e6) stdout += chunk.toString("utf8");
|
|
45
|
+
onData(chunk);
|
|
46
|
+
});
|
|
47
|
+
child.stderr?.on("data", onData);
|
|
48
|
+
child.on("error", reject);
|
|
49
|
+
const timer = opts.timeoutMs ? setTimeout(() => {
|
|
50
|
+
timedOut = true;
|
|
51
|
+
killTree(child);
|
|
52
|
+
}, opts.timeoutMs) : null;
|
|
53
|
+
const onAbort = () => killTree(child);
|
|
54
|
+
if (opts.signal?.aborted) onAbort();
|
|
55
|
+
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
56
|
+
child.on("close", (code) => {
|
|
57
|
+
if (timer) clearTimeout(timer);
|
|
58
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
59
|
+
if (partial.trim() && opts.onLine) opts.onLine(partial);
|
|
60
|
+
resolve({ exitCode: code, timedOut, durationMs: Date.now() - started, tail, stdout });
|
|
61
|
+
});
|
|
62
|
+
child.stdin?.on("error", () => {
|
|
63
|
+
});
|
|
64
|
+
child.stdin?.end(opts.stdin ?? "");
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function start(command, opts) {
|
|
68
|
+
const child = spawn(command, {
|
|
69
|
+
cwd: opts.cwd,
|
|
70
|
+
env: opts.env ?? process.env,
|
|
71
|
+
shell: true,
|
|
72
|
+
detached: process.platform !== "win32",
|
|
73
|
+
windowsHide: true,
|
|
74
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
75
|
+
});
|
|
76
|
+
const forward = (chunk) => {
|
|
77
|
+
for (const line of chunk.toString("utf8").split(/\r?\n/)) if (line.trim()) opts.onLine?.(line);
|
|
78
|
+
};
|
|
79
|
+
child.stdout?.on("data", forward);
|
|
80
|
+
child.stderr?.on("data", forward);
|
|
81
|
+
return { child, stop: () => killTree(child) };
|
|
82
|
+
}
|
|
83
|
+
var TOOL_SECRET_RE = /^(MUSHI_.*|CURSOR_API_KEY|ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN|OPENAI_API_KEY|CODEX_API_KEY|GITHUB_TOKEN|GH_TOKEN|ACTIONS_RUNTIME_TOKEN|ACTIONS_ID_TOKEN_REQUEST_TOKEN|ACTIONS_ID_TOKEN_REQUEST_URL)$/i;
|
|
84
|
+
function appEnv(base = process.env) {
|
|
85
|
+
const out = {};
|
|
86
|
+
for (const [k, v] of Object.entries(base)) {
|
|
87
|
+
if (v !== void 0 && !TOOL_SECRET_RE.test(k)) out[k] = v;
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
var SECRET_NAME_RE = /(^MUSHI_|^SUPABASE_|_TOKEN$|_KEY$|_SECRET$|PASSWORD|^GH_|^GITHUB_)/i;
|
|
92
|
+
function scrubbedEnv(keep, base = process.env) {
|
|
93
|
+
const out = {};
|
|
94
|
+
for (const [k, v] of Object.entries(base)) {
|
|
95
|
+
if (v === void 0) continue;
|
|
96
|
+
if (SECRET_NAME_RE.test(k) && !keep.includes(k)) continue;
|
|
97
|
+
out[k] = v;
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/worktree.ts
|
|
103
|
+
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "fs";
|
|
104
|
+
import { createServer } from "net";
|
|
105
|
+
import { dirname, isAbsolute, join, relative } from "path";
|
|
106
|
+
var SCRATCH_DIR = ".mushi-ux";
|
|
107
|
+
async function git(cwd, args) {
|
|
108
|
+
const res = await run("git", args, { cwd, timeoutMs: 12e4 });
|
|
109
|
+
if (res.exitCode !== 0) throw new Error(`git ${args.join(" ")} failed: ${res.tail.trim()}`);
|
|
110
|
+
return res.stdout.trim();
|
|
111
|
+
}
|
|
112
|
+
async function createWorktree(repoRoot, runId, baseRef = "HEAD") {
|
|
113
|
+
const branch = `mushi-ux/${runId}`;
|
|
114
|
+
const path = join(repoRoot, ".worktrees", `mushi-ux-${runId}`);
|
|
115
|
+
if (!/^[\w./@^~-]{1,200}$/.test(baseRef) || baseRef.startsWith("-")) throw new Error(`Not a git ref: ${baseRef}`);
|
|
116
|
+
const baseSha = await git(repoRoot, ["rev-parse", "--verify", `${baseRef}^{commit}`]);
|
|
117
|
+
await ensureLocalExcludes(repoRoot);
|
|
118
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
119
|
+
await git(repoRoot, ["worktree", "add", "-b", branch, path, baseSha]);
|
|
120
|
+
await copyEnvFiles(repoRoot, path);
|
|
121
|
+
return { path, branch, baseSha };
|
|
122
|
+
}
|
|
123
|
+
var LOCAL_EXCLUDES = ["/.mushi/", "/.worktrees/", `/${SCRATCH_DIR}/`];
|
|
124
|
+
async function ensureLocalExcludes(repoRoot) {
|
|
125
|
+
let common = await git(repoRoot, ["rev-parse", "--git-common-dir"]);
|
|
126
|
+
if (!isAbsolute(common)) common = join(repoRoot, common);
|
|
127
|
+
const file = join(common, "info", "exclude");
|
|
128
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
129
|
+
let current = "";
|
|
130
|
+
try {
|
|
131
|
+
current = readFileSync(file, "utf8");
|
|
132
|
+
} catch {
|
|
133
|
+
}
|
|
134
|
+
const lines = new Set(current.split(/\r?\n/).map((l) => l.trim()));
|
|
135
|
+
const missing = LOCAL_EXCLUDES.filter((p) => !lines.has(p));
|
|
136
|
+
if (missing.length === 0) return;
|
|
137
|
+
const lead = current && !current.endsWith("\n") ? "\n" : "";
|
|
138
|
+
appendFileSync(file, `${lead}# mushi-ux (local only)
|
|
139
|
+
${missing.join("\n")}
|
|
140
|
+
`);
|
|
141
|
+
}
|
|
142
|
+
async function copyEnvFiles(from, to, maxDepth = 4) {
|
|
143
|
+
const candidates = [];
|
|
144
|
+
const walk = (dir, depth) => {
|
|
145
|
+
if (depth > maxDepth) return;
|
|
146
|
+
for (const name of readdirSync(dir)) {
|
|
147
|
+
if (name === "node_modules" || name === ".git" || name === ".worktrees" || name === ".mushi") continue;
|
|
148
|
+
const abs = join(dir, name);
|
|
149
|
+
let isDir = false;
|
|
150
|
+
try {
|
|
151
|
+
isDir = statSync(abs).isDirectory();
|
|
152
|
+
} catch {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (isDir) walk(abs, depth + 1);
|
|
156
|
+
else if (/^\.env(\..+)?$/.test(name) && !name.endsWith(".example")) {
|
|
157
|
+
candidates.push(relative(from, abs).replace(/\\/g, "/"));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
walk(from, 0);
|
|
162
|
+
if (candidates.length === 0) return [];
|
|
163
|
+
const res = await run("git", ["check-ignore", "--", ...candidates], { cwd: from, timeoutMs: 6e4 });
|
|
164
|
+
const ignored = new Set(res.stdout.split(/\r?\n/).map((l) => l.trim().replace(/\\/g, "/")).filter(Boolean));
|
|
165
|
+
const copied = [];
|
|
166
|
+
for (const rel of candidates) {
|
|
167
|
+
if (!ignored.has(rel)) continue;
|
|
168
|
+
const dest = join(to, rel);
|
|
169
|
+
if (existsSync(dest)) continue;
|
|
170
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
171
|
+
copyFileSync(join(from, rel), dest);
|
|
172
|
+
copied.push(rel);
|
|
173
|
+
}
|
|
174
|
+
return copied;
|
|
175
|
+
}
|
|
176
|
+
async function changedFiles(wt) {
|
|
177
|
+
const res = await run("git", ["status", "--porcelain", "--untracked-files=all"], {
|
|
178
|
+
cwd: wt,
|
|
179
|
+
timeoutMs: 12e4
|
|
180
|
+
});
|
|
181
|
+
if (res.exitCode !== 0) throw new Error(`git status failed: ${res.tail.trim()}`);
|
|
182
|
+
return res.stdout.split(/\r?\n/).filter(Boolean).map((l) => l.slice(3).trim().replace(/^"|"$/g, ""));
|
|
183
|
+
}
|
|
184
|
+
async function diffText(wt, maxChars = 2e4) {
|
|
185
|
+
const tracked = await run("git", ["diff", "HEAD", "--", ".", `:(exclude)${SCRATCH_DIR}`], { cwd: wt, timeoutMs: 12e4 });
|
|
186
|
+
let out = tracked.stdout;
|
|
187
|
+
const untracked = await run("git", ["ls-files", "--others", "--exclude-standard"], { cwd: wt, timeoutMs: 12e4 });
|
|
188
|
+
for (const f of untracked.stdout.split(/\r?\n/).filter((x) => x && !x.startsWith(SCRATCH_DIR))) {
|
|
189
|
+
if (out.length >= maxChars) break;
|
|
190
|
+
try {
|
|
191
|
+
out += `
|
|
192
|
+
--- new file ${f} ---
|
|
193
|
+
${readFileSync(join(wt, f), "utf8").slice(0, 4e3)}
|
|
194
|
+
`;
|
|
195
|
+
} catch {
|
|
196
|
+
out += `
|
|
197
|
+
--- new file ${f} (unreadable) ---
|
|
198
|
+
`;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return out.slice(0, maxChars);
|
|
202
|
+
}
|
|
203
|
+
async function commitAll(wt, message) {
|
|
204
|
+
await git(wt, ["add", "-A"]);
|
|
205
|
+
await git(wt, ["-c", "user.name=mushi-ux", "-c", "user.email=mushi-ux@users.noreply.github.com", "commit", "--no-verify", "-m", message]);
|
|
206
|
+
return git(wt, ["rev-parse", "HEAD"]);
|
|
207
|
+
}
|
|
208
|
+
async function headSha(wt) {
|
|
209
|
+
return git(wt, ["rev-parse", "HEAD"]);
|
|
210
|
+
}
|
|
211
|
+
async function resetRunBranch(wt, sha) {
|
|
212
|
+
await git(wt, ["merge-base", "--is-ancestor", sha, "HEAD"]);
|
|
213
|
+
await git(wt, ["reset", "--hard", sha]);
|
|
214
|
+
}
|
|
215
|
+
async function revertAll(wt) {
|
|
216
|
+
await git(wt, ["checkout", "--", "."]);
|
|
217
|
+
await git(wt, ["clean", "-fd", "-e", SCRATCH_DIR]);
|
|
218
|
+
}
|
|
219
|
+
function detectInstallCommand(dir) {
|
|
220
|
+
if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm install --frozen-lockfile --prefer-offline";
|
|
221
|
+
if (existsSync(join(dir, "bun.lockb")) || existsSync(join(dir, "bun.lock"))) return "bun install --frozen-lockfile";
|
|
222
|
+
if (existsSync(join(dir, "yarn.lock"))) return "yarn install --frozen-lockfile";
|
|
223
|
+
if (existsSync(join(dir, "package-lock.json"))) return "npm ci";
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
async function freePort() {
|
|
227
|
+
return new Promise((resolve, reject) => {
|
|
228
|
+
const srv = createServer();
|
|
229
|
+
srv.unref();
|
|
230
|
+
srv.on("error", reject);
|
|
231
|
+
srv.listen(0, "127.0.0.1", () => {
|
|
232
|
+
const addr = srv.address();
|
|
233
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
234
|
+
srv.close(() => resolve(port));
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
async function startDevServer(wt, command, opts = {}) {
|
|
239
|
+
const port = opts.port ?? await freePort();
|
|
240
|
+
const cmd = command.replace(/\{port\}/g, String(port));
|
|
241
|
+
const recent = [];
|
|
242
|
+
const server = start(cmd, {
|
|
243
|
+
cwd: wt,
|
|
244
|
+
env: { ...appEnv(), PORT: String(port) },
|
|
245
|
+
onLine: (l) => {
|
|
246
|
+
recent.push(l);
|
|
247
|
+
if (recent.length > 40) recent.shift();
|
|
248
|
+
opts.onLine?.(l);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
const url = `http://localhost:${port}`;
|
|
252
|
+
const timeoutMs = opts.timeoutMs ?? 18e4;
|
|
253
|
+
const deadline = Date.now() + timeoutMs;
|
|
254
|
+
const tail = () => {
|
|
255
|
+
const lines = recent.map((l) => l.replace(/\u001b\[[0-9;]*m/g, ""));
|
|
256
|
+
const at = lines.findIndex((l) => /error|⨯|failed|cannot|can't/i.test(l));
|
|
257
|
+
return (at >= 0 ? lines.slice(at, at + 12) : lines.slice(-12)).join("\n");
|
|
258
|
+
};
|
|
259
|
+
let lastStatus = null;
|
|
260
|
+
while (Date.now() < deadline) {
|
|
261
|
+
if (server.child.exitCode !== null) throw new Error(`Dev server exited with code ${server.child.exitCode}: ${cmd}
|
|
262
|
+
${tail()}`);
|
|
263
|
+
lastStatus = await fetch(new URL(opts.path ?? "/", url), { redirect: "manual" }).then((r) => r.status).catch(() => lastStatus);
|
|
264
|
+
if (lastStatus !== null && lastStatus < 500) return { url, stop: server.stop };
|
|
265
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
266
|
+
}
|
|
267
|
+
server.stop();
|
|
268
|
+
const why = lastStatus !== null ? `answered HTTP ${lastStatus} on ${url}${opts.path ?? "/"}` : `did not answer on ${url}`;
|
|
269
|
+
throw new Error(`The dev server ${why} for ${Math.round(timeoutMs / 1e3)}s: ${cmd}
|
|
270
|
+
${tail()}`);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// src/cursor-cloud.ts
|
|
274
|
+
var API = "https://api.cursor.com";
|
|
275
|
+
var POLL_MS = 1e4;
|
|
276
|
+
var MAX_IMAGES = 4;
|
|
277
|
+
async function git2(cwd, args, stdin) {
|
|
278
|
+
return run("git", args, { cwd, stdin, timeoutMs: 12e4 });
|
|
279
|
+
}
|
|
280
|
+
function httpsRepoUrl(remote) {
|
|
281
|
+
const s = remote.trim();
|
|
282
|
+
const ssh = s.match(/^git@github\.com:([\w.-]+)\/([\w.-]+?)(\.git)?$/);
|
|
283
|
+
if (ssh) return `https://github.com/${ssh[1]}/${ssh[2]}`;
|
|
284
|
+
const https = s.match(/^https:\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(\.git)?\/?$/);
|
|
285
|
+
if (https) return `https://github.com/${https[1]}/${https[2]}`;
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
function cursorModel(spec) {
|
|
289
|
+
if (!spec) return void 0;
|
|
290
|
+
const [id, query] = spec.split("?");
|
|
291
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/.test(id)) return void 0;
|
|
292
|
+
const params = query ? query.split("&").filter(Boolean).map((p) => {
|
|
293
|
+
const [k, v] = p.split("=");
|
|
294
|
+
return { id: k, value: v ?? "" };
|
|
295
|
+
}) : [];
|
|
296
|
+
return params.length ? { id, params } : { id };
|
|
297
|
+
}
|
|
298
|
+
function promptAndImages(cwd) {
|
|
299
|
+
const dir = join2(cwd, SCRATCH_DIR);
|
|
300
|
+
const text = readFileSync2(join2(dir, "PROMPT.md"), "utf8");
|
|
301
|
+
const images = readdirSync2(dir).filter((f) => f.endsWith(".png")).slice(0, MAX_IMAGES).map((f) => ({ data: readFileSync2(join2(dir, f)).toString("base64"), mimeType: "image/png" }));
|
|
302
|
+
return { text: text.replace(/\.mushi-ux\/(desktop|mobile)\.png/g, "the attached $1 screenshot"), images };
|
|
303
|
+
}
|
|
304
|
+
function cursorCloudAdapter(deps = {}) {
|
|
305
|
+
const doFetch = deps.fetch ?? fetch;
|
|
306
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
307
|
+
return {
|
|
308
|
+
name: "cursor-cloud",
|
|
309
|
+
verified: false,
|
|
310
|
+
async run({ cwd, model, timeoutMs, onLine }) {
|
|
311
|
+
const started = Date.now();
|
|
312
|
+
const log = (l) => onLine?.(l);
|
|
313
|
+
const fail = (tail) => ({ exitCode: 1, timedOut: false, durationMs: Date.now() - started, tail, stdout: "" });
|
|
314
|
+
const apiKey = deps.apiKey ?? process.env.CURSOR_API_KEY;
|
|
315
|
+
if (!apiKey) return fail("CURSOR_API_KEY is not set. Create one at cursor.com/settings (Integrations \u2192 API keys).");
|
|
316
|
+
const branch = (await git2(cwd, ["rev-parse", "--abbrev-ref", "HEAD"])).stdout.trim();
|
|
317
|
+
const remote = deps.repoUrl ?? httpsRepoUrl((await git2(cwd, ["remote", "get-url", "origin"])).stdout);
|
|
318
|
+
if (!remote) return fail("cursor-cloud needs an `origin` remote on GitHub.");
|
|
319
|
+
log(`pushing ${branch} so the cloud agent can start from it`);
|
|
320
|
+
const push = await git2(cwd, ["push", "--force-with-lease", "origin", `HEAD:refs/heads/${branch}`]);
|
|
321
|
+
if (push.exitCode !== 0) return fail(`Could not push ${branch}: ${push.tail.trim()}`);
|
|
322
|
+
const { text, images } = promptAndImages(cwd);
|
|
323
|
+
const headers = { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" };
|
|
324
|
+
const body = (withImages) => JSON.stringify({
|
|
325
|
+
prompt: withImages && images.length ? { text, images } : { text },
|
|
326
|
+
repos: [{ url: remote, startingRef: branch }],
|
|
327
|
+
workOnCurrentBranch: true,
|
|
328
|
+
autoCreatePR: false,
|
|
329
|
+
name: `mushi-ux ${branch}`.slice(0, 100),
|
|
330
|
+
...cursorModel(model) ? { model: cursorModel(model) } : {}
|
|
331
|
+
});
|
|
332
|
+
let res = await doFetch(`${API}/v1/agents`, { method: "POST", headers, body: body(true) });
|
|
333
|
+
if (res.status === 400 && images.length) {
|
|
334
|
+
log("Cursor refused the inline screenshots; retrying with text only");
|
|
335
|
+
res = await doFetch(`${API}/v1/agents`, { method: "POST", headers, body: body(false) });
|
|
336
|
+
}
|
|
337
|
+
const created = await res.json().catch(() => null);
|
|
338
|
+
if (!res.ok || !created?.agent?.id || !created.run?.id) {
|
|
339
|
+
return fail(`Cursor did not start the agent (HTTP ${res.status}): ${created?.error?.message ?? "no agent id"}`);
|
|
340
|
+
}
|
|
341
|
+
const agentId = created.agent.id;
|
|
342
|
+
const runId = created.run.id;
|
|
343
|
+
log(`cloud agent ${agentId} running`);
|
|
344
|
+
let status = "CREATING";
|
|
345
|
+
let resultBranch = null;
|
|
346
|
+
let result = "";
|
|
347
|
+
while (Date.now() - started < timeoutMs) {
|
|
348
|
+
await sleep(POLL_MS);
|
|
349
|
+
const poll = await doFetch(`${API}/v1/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}`, { headers });
|
|
350
|
+
const r = await poll.json().catch(() => null);
|
|
351
|
+
status = r?.status ?? status;
|
|
352
|
+
log(`cloud agent ${status.toLowerCase()}`);
|
|
353
|
+
if (status === "FINISHED" || status === "ERROR" || status === "CANCELLED" || status === "EXPIRED") {
|
|
354
|
+
resultBranch = r?.git?.branches?.find((b) => b.branch)?.branch ?? null;
|
|
355
|
+
result = r?.result ?? "";
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (status !== "FINISHED") {
|
|
360
|
+
if (Date.now() - started >= timeoutMs) {
|
|
361
|
+
await doFetch(`${API}/v1/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/cancel`, { method: "POST", headers }).catch(() => void 0);
|
|
362
|
+
return { exitCode: null, timedOut: true, durationMs: Date.now() - started, tail: `Cloud agent still ${status.toLowerCase()} at the time box; cancelled.`, stdout: "" };
|
|
363
|
+
}
|
|
364
|
+
return fail(`Cloud agent ended ${status.toLowerCase()}. ${result}`.trim());
|
|
365
|
+
}
|
|
366
|
+
if (!resultBranch) return { exitCode: 0, timedOut: false, durationMs: Date.now() - started, tail: result || "Cloud agent made no edits.", stdout: "" };
|
|
367
|
+
const fetched = await git2(cwd, ["fetch", "origin", resultBranch]);
|
|
368
|
+
if (fetched.exitCode !== 0) return fail(`Could not fetch ${resultBranch}: ${fetched.tail.trim()}`);
|
|
369
|
+
const diff = await git2(cwd, ["diff", "--binary", "HEAD", "FETCH_HEAD"]);
|
|
370
|
+
if (diff.stdout.trim()) {
|
|
371
|
+
const applied = await git2(cwd, ["apply", "--whitespace=nowarn"], diff.stdout);
|
|
372
|
+
if (applied.exitCode !== 0) return fail(`The agent's change did not apply: ${applied.tail.trim()}`);
|
|
373
|
+
}
|
|
374
|
+
log(`applied the cloud agent's change from ${resultBranch}`);
|
|
375
|
+
return { exitCode: 0, timedOut: false, durationMs: Date.now() - started, tail: result.slice(-2e3), stdout: result };
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// src/agents.ts
|
|
381
|
+
var claudeCode = {
|
|
382
|
+
name: "claude-code",
|
|
383
|
+
verified: true,
|
|
384
|
+
run: ({ cwd, prompt, model, timeoutMs, onLine, signal }) => run(
|
|
385
|
+
"claude",
|
|
386
|
+
[
|
|
387
|
+
"-p",
|
|
388
|
+
"--output-format",
|
|
389
|
+
"stream-json",
|
|
390
|
+
"--verbose",
|
|
391
|
+
"--restricted",
|
|
392
|
+
"--strict-mcp-config",
|
|
393
|
+
"--permission-mode",
|
|
394
|
+
"acceptEdits",
|
|
395
|
+
"--no-session-persistence",
|
|
396
|
+
...model ? ["--model", model] : []
|
|
397
|
+
],
|
|
398
|
+
{
|
|
399
|
+
cwd,
|
|
400
|
+
stdin: prompt,
|
|
401
|
+
timeoutMs,
|
|
402
|
+
onLine,
|
|
403
|
+
signal,
|
|
404
|
+
env: scrubbedEnv(["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"])
|
|
405
|
+
}
|
|
406
|
+
)
|
|
407
|
+
};
|
|
408
|
+
var cursor = {
|
|
409
|
+
name: "cursor",
|
|
410
|
+
// Verified on Windows 2026-10-06 (2026.10.01, Grok 4.7), launched outside Git Bash.
|
|
411
|
+
verified: true,
|
|
412
|
+
canResume: true,
|
|
413
|
+
// Cursor's CLI takes the prompt as an argument in print mode; whether it
|
|
414
|
+
// reads stdin is a Phase 0 probe. The `.cmd` shim needs a shell on Windows.
|
|
415
|
+
// The loop's prompt is a one-line pointer to .mushi-ux/PROMPT.md, so it
|
|
416
|
+
// stays far below cmd.exe's command-line limit.
|
|
417
|
+
run: ({ cwd, prompt, model, timeoutMs, onLine, signal, resumeSession }) => run(
|
|
418
|
+
"agent",
|
|
419
|
+
[
|
|
420
|
+
"-p",
|
|
421
|
+
...resumeSession ? ["--resume", quoteArg(resumeSession)] : [],
|
|
422
|
+
"--force",
|
|
423
|
+
// Headless runs otherwise stop on the workspace-trust prompt in a fresh worktree.
|
|
424
|
+
"--trust",
|
|
425
|
+
"--output-format",
|
|
426
|
+
"stream-json",
|
|
427
|
+
"--workspace",
|
|
428
|
+
".",
|
|
429
|
+
...model ? ["--model", quoteArg(cursorCliModel(model))] : [],
|
|
430
|
+
quoteArg(prompt)
|
|
431
|
+
],
|
|
432
|
+
{ cwd, timeoutMs, onLine, signal, shell: true, env: scrubbedEnv(["CURSOR_API_KEY"]) }
|
|
433
|
+
)
|
|
434
|
+
};
|
|
435
|
+
var codex = {
|
|
436
|
+
name: "codex",
|
|
437
|
+
verified: false,
|
|
438
|
+
run: ({ cwd, prompt, model, timeoutMs, onLine, signal }) => run(
|
|
439
|
+
"codex",
|
|
440
|
+
["exec", "--json", "--full-auto", "-C", ".", ...model ? ["-m", quoteArg(model)] : [], "-"],
|
|
441
|
+
{ cwd, stdin: prompt, timeoutMs, onLine, signal, shell: true, env: scrubbedEnv(["OPENAI_API_KEY", "CODEX_API_KEY"]) }
|
|
442
|
+
)
|
|
443
|
+
};
|
|
444
|
+
function cursorCliModel(spec) {
|
|
445
|
+
const [id, query] = spec.split("?");
|
|
446
|
+
if (!query) return id;
|
|
447
|
+
const params = query.split("&").filter(Boolean);
|
|
448
|
+
return params.length ? `${id}[${params.join(",")}]` : id;
|
|
449
|
+
}
|
|
450
|
+
function quoteArg(s, platform = process.platform) {
|
|
451
|
+
if (/^[\w./:=@-]+$/.test(s)) return s;
|
|
452
|
+
const flat = s.replace(/\r?\n/g, " ");
|
|
453
|
+
if (platform === "win32") return `"${flat.replace(/"/g, "")}"`;
|
|
454
|
+
return `'${flat.replace(/'/g, `'\\''`)}'`;
|
|
455
|
+
}
|
|
456
|
+
var AGENTS = {
|
|
457
|
+
"claude-code": claudeCode,
|
|
458
|
+
cursor,
|
|
459
|
+
codex,
|
|
460
|
+
// Cursor Cloud: the edit runs on Cursor's machines (your plan pays), the
|
|
461
|
+
// measuring stays here. Needs CURSOR_API_KEY and a GitHub origin.
|
|
462
|
+
"cursor-cloud": cursorCloudAdapter()
|
|
463
|
+
};
|
|
464
|
+
function getAgent(name) {
|
|
465
|
+
const adapter = AGENTS[name];
|
|
466
|
+
if (!adapter) throw new Error(`Unknown agent "${name}". Use one of: ${Object.keys(AGENTS).join(", ")}`);
|
|
467
|
+
return adapter;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// src/capture.ts
|
|
471
|
+
import { chromium } from "playwright";
|
|
472
|
+
|
|
473
|
+
// src/guard.ts
|
|
474
|
+
var READ_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
475
|
+
function globToRegExp(glob) {
|
|
476
|
+
const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
477
|
+
return new RegExp(`^${escaped}$`);
|
|
478
|
+
}
|
|
479
|
+
function isRequestAllowed(method, url, allow) {
|
|
480
|
+
const m = method.toUpperCase();
|
|
481
|
+
if (READ_METHODS.has(m)) return true;
|
|
482
|
+
let path;
|
|
483
|
+
try {
|
|
484
|
+
const u = new URL(url);
|
|
485
|
+
path = u.pathname + u.search;
|
|
486
|
+
} catch {
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
return allow.some((rule) => {
|
|
490
|
+
const space = rule.indexOf(" ");
|
|
491
|
+
const ruleMethod = space > 0 ? rule.slice(0, space).toUpperCase() : null;
|
|
492
|
+
const ruleGlob = space > 0 ? rule.slice(space + 1).trim() : rule.trim();
|
|
493
|
+
if (ruleMethod && ruleMethod !== m) return false;
|
|
494
|
+
return globToRegExp(ruleGlob).test(path);
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
var DESTRUCTIVE_RE = /\b(delete|remove|destroy|erase|discard|revoke|disconnect|uninstall|archive|cancel (?:plan|subscription)|pay|purchase|buy|checkout|charge|send|submit|publish|merge|deploy|log ?out|sign ?out|reset)\b/i;
|
|
498
|
+
function isDestructiveLabel(label) {
|
|
499
|
+
return DESTRUCTIVE_RE.test(label);
|
|
500
|
+
}
|
|
501
|
+
var NO_SUBMIT_SCRIPT = `(() => {
|
|
502
|
+
addEventListener('submit', (e) => { e.preventDefault(); e.stopImmediatePropagation() }, true)
|
|
503
|
+
HTMLFormElement.prototype.submit = function () {}
|
|
504
|
+
HTMLFormElement.prototype.requestSubmit = function () {}
|
|
505
|
+
})()`;
|
|
506
|
+
async function installGuard(context, allow, log = { blocked: [] }) {
|
|
507
|
+
await context.addInitScript({ content: NO_SUBMIT_SCRIPT });
|
|
508
|
+
await context.route("**/*", async (route) => {
|
|
509
|
+
const req = route.request();
|
|
510
|
+
if (isRequestAllowed(req.method(), req.url(), allow)) return route.continue();
|
|
511
|
+
log.blocked.push({ method: req.method(), url: req.url() });
|
|
512
|
+
return route.abort("blockedbyclient");
|
|
513
|
+
});
|
|
514
|
+
return log;
|
|
515
|
+
}
|
|
516
|
+
function isGuardNoise(text) {
|
|
517
|
+
return /ERR_BLOCKED_BY_CLIENT/.test(text);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// src/ignore.ts
|
|
521
|
+
var DEFAULT_IGNORE = [
|
|
522
|
+
// Mark anything yourself
|
|
523
|
+
"[data-mushi-ux-ignore]",
|
|
524
|
+
// Next.js dev overlay and indicators
|
|
525
|
+
"nextjs-portal",
|
|
526
|
+
"[data-nextjs-toast]",
|
|
527
|
+
"[data-nextjs-dev-tools-button]",
|
|
528
|
+
"#__next-build-watcher",
|
|
529
|
+
// Vite / webpack dev overlays
|
|
530
|
+
"vite-error-overlay",
|
|
531
|
+
"#webpack-dev-server-client-overlay",
|
|
532
|
+
// Build / version stamps shown only in dev or QA builds
|
|
533
|
+
"[data-qa-build-stamp]",
|
|
534
|
+
"[data-build-stamp]",
|
|
535
|
+
// Mushi's own widget, rewards badge and consent banner (not the app's code)
|
|
536
|
+
"#mushi-mushi-widget",
|
|
537
|
+
"#mushi-tier-badge",
|
|
538
|
+
"#mushi-consent-banner"
|
|
539
|
+
];
|
|
540
|
+
function isSafeSelector(s) {
|
|
541
|
+
return s.length > 0 && s.length <= 200 && !/[{}<>;\\]/.test(s) && !/^[\s,]|,\s*$/.test(s);
|
|
542
|
+
}
|
|
543
|
+
function ignoreList(extra = []) {
|
|
544
|
+
return [.../* @__PURE__ */ new Set([...DEFAULT_IGNORE, ...extra.map((s) => s.trim()).filter(isSafeSelector)])];
|
|
545
|
+
}
|
|
546
|
+
function ignoreStyle(selectors) {
|
|
547
|
+
return selectors.length ? `${selectors.join(",\n")} { visibility: hidden !important; }` : "";
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// src/probes.ts
|
|
551
|
+
import { AxeBuilder } from "@axe-core/playwright";
|
|
552
|
+
var AXE_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];
|
|
553
|
+
var MAX_TARGETS = 5;
|
|
554
|
+
async function usableSelectors(page, selectors) {
|
|
555
|
+
if (!selectors.length) return [];
|
|
556
|
+
return page.evaluate((list) => {
|
|
557
|
+
return list.filter((sel) => {
|
|
558
|
+
try {
|
|
559
|
+
document.querySelector(sel);
|
|
560
|
+
return true;
|
|
561
|
+
} catch {
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
}, [...selectors]);
|
|
566
|
+
}
|
|
567
|
+
async function runProbes(page, consoleErrors, ignore = []) {
|
|
568
|
+
const skip = await usableSelectors(page, ignore);
|
|
569
|
+
let builder = new AxeBuilder({ page }).withTags(AXE_TAGS);
|
|
570
|
+
for (const sel of skip) builder = builder.exclude(sel);
|
|
571
|
+
const axe = await builder.analyze().then(
|
|
572
|
+
(r) => r.violations.map(
|
|
573
|
+
(v) => ({
|
|
574
|
+
id: v.id,
|
|
575
|
+
impact: v.impact ?? null,
|
|
576
|
+
help: v.help,
|
|
577
|
+
count: v.nodes.length,
|
|
578
|
+
targets: v.nodes.slice(0, MAX_TARGETS).map((n) => n.target.join(" "))
|
|
579
|
+
})
|
|
580
|
+
)
|
|
581
|
+
);
|
|
582
|
+
const layout = await page.evaluate((skipSelectors) => {
|
|
583
|
+
const root = document.documentElement;
|
|
584
|
+
const overflowX = root.scrollWidth > root.clientWidth + 1;
|
|
585
|
+
const interactive = document.querySelectorAll(
|
|
586
|
+
"a[href], button, input:not([type=hidden]), select, textarea, [role=button], [role=link], [role=tab], [role=checkbox], [role=switch], [role=menuitem]"
|
|
587
|
+
);
|
|
588
|
+
let smallTargets = 0;
|
|
589
|
+
for (const el of Array.from(interactive)) {
|
|
590
|
+
const style = getComputedStyle(el);
|
|
591
|
+
if (style.visibility === "hidden" || style.display === "none") continue;
|
|
592
|
+
if (skipSelectors.some((sel) => el.closest(sel))) continue;
|
|
593
|
+
if (style.pointerEvents === "none") continue;
|
|
594
|
+
if (el.tagName === "A" && style.display === "inline") continue;
|
|
595
|
+
const r = el.getBoundingClientRect();
|
|
596
|
+
if (r.width === 0 || r.height === 0) continue;
|
|
597
|
+
const clipped = style.clip.startsWith("rect(0") || style.clipPath.startsWith("inset(50%");
|
|
598
|
+
if (clipped || r.width <= 1 && r.height <= 1) continue;
|
|
599
|
+
if (r.width < 24 || r.height < 24) smallTargets++;
|
|
600
|
+
}
|
|
601
|
+
const cls = window.__mushiCls ?? 0;
|
|
602
|
+
return { overflowX, smallTargets, cls };
|
|
603
|
+
}, skip);
|
|
604
|
+
return {
|
|
605
|
+
axe,
|
|
606
|
+
overflowX: layout.overflowX,
|
|
607
|
+
smallTargets: layout.smallTargets,
|
|
608
|
+
consoleErrors: [...consoleErrors],
|
|
609
|
+
cls: Math.round(layout.cls * 1e3) / 1e3
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
var FRAMEWORK_NOISE = [
|
|
613
|
+
/Check the render method of `(OuterLayoutRouter|InnerLayoutRouter|LayoutRouter|SegmentViewNode|SegmentStateProvider|RenderFromTemplateContext|ScrollAndFocusHandler|HTTPAccessFallbackBoundary|RedirectBoundary|ErrorBoundaryHandler|AppRouter|HotReload|ReactDevOverlay)`/,
|
|
614
|
+
/\[(Fast Refresh|HMR)\]/,
|
|
615
|
+
/Download the React DevTools/,
|
|
616
|
+
/_next\/webpack-hmr|__nextjs_original-stack-frame/
|
|
617
|
+
];
|
|
618
|
+
function isFrameworkNoise(message) {
|
|
619
|
+
return FRAMEWORK_NOISE.some((re) => re.test(message));
|
|
620
|
+
}
|
|
621
|
+
var IMPACT_WEIGHT = { critical: 8, serious: 4, moderate: 2, minor: 1 };
|
|
622
|
+
function probePenalty(p) {
|
|
623
|
+
const axe = p.axe.reduce((sum, v) => sum + (IMPACT_WEIGHT[v.impact ?? ""] ?? 1) * Math.max(1, v.count), 0);
|
|
624
|
+
return axe + (p.overflowX ? 10 : 0) + p.smallTargets + p.consoleErrors.length * 5 + clsPenalty(p.cls);
|
|
625
|
+
}
|
|
626
|
+
var CLS_GOOD = 0.1;
|
|
627
|
+
function clsPenalty(cls) {
|
|
628
|
+
return cls > CLS_GOOD ? Math.ceil((cls - CLS_GOOD) * 20) : 0;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// src/capture.ts
|
|
632
|
+
var CLS_SCRIPT = `(() => {
|
|
633
|
+
window.__mushiCls = 0
|
|
634
|
+
try {
|
|
635
|
+
new PerformanceObserver((list) => {
|
|
636
|
+
for (const e of list.getEntries()) if (!e.hadRecentInput) window.__mushiCls += e.value
|
|
637
|
+
}).observe({ type: 'layout-shift', buffered: true })
|
|
638
|
+
} catch {}
|
|
639
|
+
})()`;
|
|
640
|
+
async function openSession(opts = {}) {
|
|
641
|
+
const headless = opts.headless ?? true;
|
|
642
|
+
let context;
|
|
643
|
+
let closeBrowser;
|
|
644
|
+
let browser;
|
|
645
|
+
if (opts.profileDir) {
|
|
646
|
+
context = await chromium.launchPersistentContext(opts.profileDir, { headless, serviceWorkers: "block" });
|
|
647
|
+
browser = await chromium.launch({ headless });
|
|
648
|
+
closeBrowser = async () => {
|
|
649
|
+
await context.close();
|
|
650
|
+
await browser.close();
|
|
651
|
+
};
|
|
652
|
+
} else {
|
|
653
|
+
browser = await chromium.launch({ headless });
|
|
654
|
+
context = await browser.newContext({ serviceWorkers: "block" });
|
|
655
|
+
closeBrowser = () => browser.close();
|
|
656
|
+
}
|
|
657
|
+
const guard = await installGuard(context, opts.allow ?? []);
|
|
658
|
+
await context.addInitScript({ content: CLS_SCRIPT });
|
|
659
|
+
let seed = await context.storageState({ indexedDB: true });
|
|
660
|
+
const warmUp = async (baseUrl, paths) => {
|
|
661
|
+
const page = await context.newPage();
|
|
662
|
+
try {
|
|
663
|
+
for (const p of paths) {
|
|
664
|
+
await gotoPatiently(page, surfaceUrl(baseUrl, p)).catch(() => null);
|
|
665
|
+
await settle(page).catch(() => void 0);
|
|
666
|
+
}
|
|
667
|
+
} finally {
|
|
668
|
+
await page.close();
|
|
669
|
+
}
|
|
670
|
+
seed = await context.storageState({ indexedDB: true });
|
|
671
|
+
};
|
|
672
|
+
const freshContext = async () => {
|
|
673
|
+
const fresh = await browser.newContext({ serviceWorkers: "block", storageState: seed });
|
|
674
|
+
await installGuard(fresh, opts.allow ?? [], guard);
|
|
675
|
+
await fresh.addInitScript({ content: CLS_SCRIPT });
|
|
676
|
+
return fresh;
|
|
677
|
+
};
|
|
678
|
+
return { context, freshContext, warmUp, guard, ignore: ignoreList(opts.ignore), close: closeBrowser };
|
|
679
|
+
}
|
|
680
|
+
async function settle(page, quietMs = 400, maxMs = 5e3) {
|
|
681
|
+
await page.waitForLoadState("networkidle", { timeout: Math.min(maxMs, 2500) }).catch(() => {
|
|
682
|
+
});
|
|
683
|
+
await page.evaluate(
|
|
684
|
+
([quiet, max]) => new Promise((resolve) => {
|
|
685
|
+
let timer = setTimeout(done, quiet);
|
|
686
|
+
const stop = setTimeout(done, max);
|
|
687
|
+
const mo = new MutationObserver(() => {
|
|
688
|
+
clearTimeout(timer);
|
|
689
|
+
timer = setTimeout(done, quiet);
|
|
690
|
+
});
|
|
691
|
+
mo.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
692
|
+
function done() {
|
|
693
|
+
mo.disconnect();
|
|
694
|
+
clearTimeout(timer);
|
|
695
|
+
clearTimeout(stop);
|
|
696
|
+
resolve();
|
|
697
|
+
}
|
|
698
|
+
}),
|
|
699
|
+
[quietMs, maxMs]
|
|
700
|
+
).catch(() => {
|
|
701
|
+
});
|
|
702
|
+
await page.evaluate(() => document.fonts?.ready).catch(() => {
|
|
703
|
+
});
|
|
704
|
+
await waitForContent(page);
|
|
705
|
+
}
|
|
706
|
+
async function waitForContent(page, maxMs = 2e4) {
|
|
707
|
+
await page.waitForFunction(
|
|
708
|
+
() => {
|
|
709
|
+
const visible = (el) => {
|
|
710
|
+
const r = el.getBoundingClientRect();
|
|
711
|
+
const s = getComputedStyle(el);
|
|
712
|
+
return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && s.display !== "none";
|
|
713
|
+
};
|
|
714
|
+
const busy = [...document.querySelectorAll('[aria-busy="true"], [role="progressbar"], .animate-spin, .spinner, [class*="spinner" i]')].some(visible);
|
|
715
|
+
const skeleton = [...document.querySelectorAll('[class*="skeleton" i], [class*="shimmer" i], .animate-pulse, [data-skeleton]')].some(visible) || (document.getAnimations?.() ?? []).some((a) => {
|
|
716
|
+
const name = a.animationName ?? "";
|
|
717
|
+
const target = a.effect?.target;
|
|
718
|
+
return /skeleton|shimmer|pulse|loading|placeholder/i.test(name) && !!target && visible(target);
|
|
719
|
+
});
|
|
720
|
+
if (skeleton) return false;
|
|
721
|
+
const text = (document.body?.innerText ?? "").replace(/\s+/g, " ").trim();
|
|
722
|
+
return !busy && text.length > 40;
|
|
723
|
+
},
|
|
724
|
+
void 0,
|
|
725
|
+
{ timeout: maxMs, polling: 250 }
|
|
726
|
+
).catch(() => {
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
async function replay(page, steps) {
|
|
730
|
+
for (const step of steps) {
|
|
731
|
+
await page.locator(step.selector).first().click({ timeout: 5e3 });
|
|
732
|
+
await settle(page);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
function surfaceUrl(baseUrl, path) {
|
|
736
|
+
return new URL(path, baseUrl).toString();
|
|
737
|
+
}
|
|
738
|
+
var NAV_TIMEOUT_MS = 9e4;
|
|
739
|
+
var RETRY_NAV_RE = /timeout|ERR_ABORTED|interrupted by another navigation/i;
|
|
740
|
+
async function gotoPatiently(page, url) {
|
|
741
|
+
const go = () => page.goto(url, { waitUntil: "domcontentloaded", timeout: NAV_TIMEOUT_MS });
|
|
742
|
+
try {
|
|
743
|
+
return await go() ?? await go();
|
|
744
|
+
} catch (err) {
|
|
745
|
+
if (!RETRY_NAV_RE.test(err.message)) throw err;
|
|
746
|
+
return go();
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
async function captureSurface(session, baseUrl, surface, viewport) {
|
|
750
|
+
const ctx = await session.freshContext();
|
|
751
|
+
const page = await ctx.newPage();
|
|
752
|
+
const consoleErrors = [];
|
|
753
|
+
page.on("console", (msg) => {
|
|
754
|
+
if (msg.type() === "error" && !isGuardNoise(msg.text()) && !isFrameworkNoise(msg.text())) consoleErrors.push(msg.text().slice(0, 300));
|
|
755
|
+
});
|
|
756
|
+
page.on("pageerror", (err) => consoleErrors.push(String(err.message).slice(0, 300)));
|
|
757
|
+
try {
|
|
758
|
+
await page.setViewportSize({ width: viewport.width, height: viewport.height });
|
|
759
|
+
await gotoPatiently(page, surfaceUrl(baseUrl, surface.path));
|
|
760
|
+
await settle(page);
|
|
761
|
+
await replay(page, surface.steps);
|
|
762
|
+
const png = await page.screenshot({
|
|
763
|
+
fullPage: true,
|
|
764
|
+
animations: "disabled",
|
|
765
|
+
caret: "hide",
|
|
766
|
+
style: ignoreStyle(session.ignore) || void 0
|
|
767
|
+
});
|
|
768
|
+
const probes = await runProbes(page, consoleErrors, session.ignore);
|
|
769
|
+
return { png, probes };
|
|
770
|
+
} finally {
|
|
771
|
+
await ctx.close();
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// src/dashboard.ts
|
|
776
|
+
import { randomBytes } from "crypto";
|
|
777
|
+
import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync4 } from "fs";
|
|
778
|
+
import { createServer as createServer2 } from "http";
|
|
779
|
+
import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
|
|
780
|
+
import { z } from "zod";
|
|
781
|
+
import { PNG as PNG2 } from "pngjs";
|
|
782
|
+
|
|
783
|
+
// src/agent-events.ts
|
|
784
|
+
var MAX_TEXT = 300;
|
|
785
|
+
var clip = (s, n = MAX_TEXT) => {
|
|
786
|
+
const one = s.replace(/\s+/g, " ").trim();
|
|
787
|
+
return one.length > n ? `${one.slice(0, n - 1)}\u2026` : one;
|
|
788
|
+
};
|
|
789
|
+
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
790
|
+
var str = (v) => typeof v === "string" && v ? v : void 0;
|
|
791
|
+
function shortPath(p, cwd) {
|
|
792
|
+
const norm = p.replace(/\\/g, "/");
|
|
793
|
+
if (cwd) {
|
|
794
|
+
const base = cwd.replace(/\\/g, "/").replace(/\/$/, "") + "/";
|
|
795
|
+
if (norm.toLowerCase().startsWith(base.toLowerCase())) return norm.slice(base.length);
|
|
796
|
+
}
|
|
797
|
+
return norm;
|
|
798
|
+
}
|
|
799
|
+
var EDIT_TOOLS = /^(write|edit|multiedit|strreplace|str_replace|searchreplace|applypatch|apply_patch|delete|notebookedit|create)/i;
|
|
800
|
+
var READ_TOOLS = /^(read|view|ls|list|readfile|readlints)/i;
|
|
801
|
+
var SEARCH_TOOLS = /^(grep|glob|search|find|codebasesearch|semanticsearch|websearch|webfetch)/i;
|
|
802
|
+
var RUN_TOOLS = /^(shell|bash|run|terminal|exec|command)/i;
|
|
803
|
+
function describeTool(name, args, cwd) {
|
|
804
|
+
const path = str(args.path) ?? str(args.file_path) ?? str(args.filePath) ?? str(args.target_file) ?? str(args.notebook_path);
|
|
805
|
+
const command = str(args.command) ?? (Array.isArray(args.command) ? args.command.join(" ") : void 0);
|
|
806
|
+
const pattern = str(args.pattern) ?? str(args.query) ?? str(args.globPattern) ?? str(args.glob_pattern) ?? str(args.url);
|
|
807
|
+
const label = name.replace(/ToolCall$/, "");
|
|
808
|
+
const p = path ? shortPath(path, cwd) : void 0;
|
|
809
|
+
if (EDIT_TOOLS.test(label)) return { kind: "edit", text: `${p ?? "(a file)"}${/^delete/i.test(label) ? " (deleted)" : ""}`, path: p };
|
|
810
|
+
if (RUN_TOOLS.test(label) && command) return { kind: "run", text: clip(command, 160) };
|
|
811
|
+
if (SEARCH_TOOLS.test(label)) return { kind: "search", text: clip(pattern ?? p ?? label, 160) };
|
|
812
|
+
if (READ_TOOLS.test(label)) return { kind: "read", text: p ?? (clip(pattern ?? "", 160) || "(a file)"), path: p };
|
|
813
|
+
return { kind: "tool", text: clip(`${label}${p ? ` ${p}` : pattern ? ` ${pattern}` : ""}`, 160) };
|
|
814
|
+
}
|
|
815
|
+
function textOf(content) {
|
|
816
|
+
if (typeof content === "string") return content;
|
|
817
|
+
if (!Array.isArray(content)) return "";
|
|
818
|
+
return content.filter((c) => isObj(c) && c.type === "text").map((c) => str(c.text) ?? "").join(" ");
|
|
819
|
+
}
|
|
820
|
+
function parseArgs(raw) {
|
|
821
|
+
if (isObj(raw)) return raw;
|
|
822
|
+
if (typeof raw === "string") {
|
|
823
|
+
try {
|
|
824
|
+
const v = JSON.parse(raw);
|
|
825
|
+
return isObj(v) ? v : {};
|
|
826
|
+
} catch {
|
|
827
|
+
return {};
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
return {};
|
|
831
|
+
}
|
|
832
|
+
function describeAgentLine(line, cwd) {
|
|
833
|
+
const trimmed = line.trim();
|
|
834
|
+
if (!trimmed) return [];
|
|
835
|
+
if (!trimmed.startsWith("{")) return [{ kind: "say", text: clip(trimmed) }];
|
|
836
|
+
let ev;
|
|
837
|
+
try {
|
|
838
|
+
const v = JSON.parse(trimmed);
|
|
839
|
+
if (!isObj(v)) return [];
|
|
840
|
+
ev = v;
|
|
841
|
+
} catch {
|
|
842
|
+
return [{ kind: "say", text: clip(trimmed) }];
|
|
843
|
+
}
|
|
844
|
+
const type = str(ev.type);
|
|
845
|
+
if (type === "system" && ev.subtype === "init") {
|
|
846
|
+
return [{ kind: "tool", text: `Started${str(ev.model) ? ` (${ev.model})` : ""}` }];
|
|
847
|
+
}
|
|
848
|
+
if (type === "assistant" && isObj(ev.message)) {
|
|
849
|
+
if (ev.model_call_id !== void 0) return [];
|
|
850
|
+
const content = ev.message.content;
|
|
851
|
+
const steps = [];
|
|
852
|
+
const said = clip(textOf(content));
|
|
853
|
+
if (said) steps.push({ kind: "say", text: said });
|
|
854
|
+
if (Array.isArray(content)) {
|
|
855
|
+
for (const c of content) {
|
|
856
|
+
if (isObj(c) && c.type === "tool_use" && str(c.name)) steps.push(describeTool(c.name, parseArgs(c.input), cwd));
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
return steps;
|
|
860
|
+
}
|
|
861
|
+
if (type === "tool_call") {
|
|
862
|
+
if (ev.subtype !== "started" || !isObj(ev.tool_call)) return [];
|
|
863
|
+
const [key, body] = Object.entries(ev.tool_call)[0] ?? [];
|
|
864
|
+
if (!key || !isObj(body)) return [];
|
|
865
|
+
if (key === "function") return [describeTool(str(body.name) ?? "tool", parseArgs(body.arguments), cwd)];
|
|
866
|
+
return [describeTool(key, parseArgs(body.args), cwd)];
|
|
867
|
+
}
|
|
868
|
+
if (type === "result") {
|
|
869
|
+
if (ev.is_error === true || str(ev.subtype) && ev.subtype !== "success") {
|
|
870
|
+
return [{ kind: "error", text: clip(str(ev.result) ?? str(ev.error) ?? `Finished with ${String(ev.subtype)}`) }];
|
|
871
|
+
}
|
|
872
|
+
return [{ kind: "done", text: "Finished" }];
|
|
873
|
+
}
|
|
874
|
+
if ((type === "item.started" || type === "item.completed") && isObj(ev.item)) {
|
|
875
|
+
const item = ev.item;
|
|
876
|
+
if (item.type === "command_execution" && type === "item.started" && str(item.command)) {
|
|
877
|
+
return [{ kind: "run", text: clip(item.command, 160) }];
|
|
878
|
+
}
|
|
879
|
+
if (item.type === "file_change" && type === "item.completed" && Array.isArray(item.changes)) {
|
|
880
|
+
return item.changes.filter((c) => isObj(c) && !!str(c.path)).map((c) => {
|
|
881
|
+
const p = shortPath(c.path, cwd);
|
|
882
|
+
return { kind: "edit", text: p, path: p };
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
if (item.type === "agent_message" && type === "item.completed" && str(item.text)) {
|
|
886
|
+
return [{ kind: "say", text: clip(item.text) }];
|
|
887
|
+
}
|
|
888
|
+
return [];
|
|
889
|
+
}
|
|
890
|
+
if (type === "error") return [{ kind: "error", text: clip(str(ev.message) ?? "Error") }];
|
|
891
|
+
return [];
|
|
892
|
+
}
|
|
893
|
+
function attemptLogBase(surfaceKey2, attempt) {
|
|
894
|
+
return `${surfaceKey2.replace(/[^\w.-]+/g, "_")}-${attempt}`;
|
|
895
|
+
}
|
|
896
|
+
function sessionIdOf(stdout) {
|
|
897
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
898
|
+
if (!line.startsWith("{")) continue;
|
|
899
|
+
try {
|
|
900
|
+
const id = JSON.parse(line).session_id;
|
|
901
|
+
if (typeof id === "string" && /^[\w-]{6,80}$/.test(id)) return id;
|
|
902
|
+
} catch {
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
return null;
|
|
906
|
+
}
|
|
907
|
+
var ICON = {
|
|
908
|
+
say: "\u203A",
|
|
909
|
+
read: "read",
|
|
910
|
+
edit: "edit",
|
|
911
|
+
run: "run",
|
|
912
|
+
search: "find",
|
|
913
|
+
tool: "tool",
|
|
914
|
+
done: "done",
|
|
915
|
+
error: "error"
|
|
916
|
+
};
|
|
917
|
+
function formatStep(step) {
|
|
918
|
+
return step.kind === "say" ? `\u203A ${step.text}` : `[${ICON[step.kind]}] ${step.text}`;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
// src/image.ts
|
|
922
|
+
import pixelmatch from "pixelmatch";
|
|
923
|
+
import { PNG } from "pngjs";
|
|
924
|
+
function decodePng(buf) {
|
|
925
|
+
return PNG.sync.read(buf);
|
|
926
|
+
}
|
|
927
|
+
function encodePng(png) {
|
|
928
|
+
return PNG.sync.write(png);
|
|
929
|
+
}
|
|
930
|
+
function padTo(src, width, height) {
|
|
931
|
+
if (src.width === width && src.height === height) return src;
|
|
932
|
+
const out = new PNG({ width, height });
|
|
933
|
+
out.data.fill(255);
|
|
934
|
+
PNG.bitblt(src, out, 0, 0, Math.min(src.width, width), Math.min(src.height, height), 0, 0);
|
|
935
|
+
return out;
|
|
936
|
+
}
|
|
937
|
+
function isDiffPixel(d, i) {
|
|
938
|
+
return d[i] === 255 && d[i + 1] === 0 && d[i + 2] === 0;
|
|
939
|
+
}
|
|
940
|
+
function changeRegions(diff, cell = 16, max = 4, pad = 24) {
|
|
941
|
+
const cols = Math.ceil(diff.width / cell);
|
|
942
|
+
const rows = Math.ceil(diff.height / cell);
|
|
943
|
+
const hit = new Uint8Array(cols * rows);
|
|
944
|
+
for (let y = 0; y < diff.height; y++) {
|
|
945
|
+
for (let x = 0; x < diff.width; x++) {
|
|
946
|
+
if (isDiffPixel(diff.data, (y * diff.width + x) * 4)) hit[Math.floor(y / cell) * cols + Math.floor(x / cell)] = 1;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
const seen = new Uint8Array(cols * rows);
|
|
950
|
+
const boxes = [];
|
|
951
|
+
for (let start2 = 0; start2 < hit.length; start2++) {
|
|
952
|
+
if (!hit[start2] || seen[start2]) continue;
|
|
953
|
+
let minC = cols, minR = rows, maxC = 0, maxR = 0, cells = 0;
|
|
954
|
+
const stack = [start2];
|
|
955
|
+
seen[start2] = 1;
|
|
956
|
+
while (stack.length) {
|
|
957
|
+
const i = stack.pop();
|
|
958
|
+
const c = i % cols;
|
|
959
|
+
const r = Math.floor(i / cols);
|
|
960
|
+
cells++;
|
|
961
|
+
minC = Math.min(minC, c);
|
|
962
|
+
maxC = Math.max(maxC, c);
|
|
963
|
+
minR = Math.min(minR, r);
|
|
964
|
+
maxR = Math.max(maxR, r);
|
|
965
|
+
for (let dr = -2; dr <= 2; dr++) {
|
|
966
|
+
for (let dc = -2; dc <= 2; dc++) {
|
|
967
|
+
const rr = r + dr;
|
|
968
|
+
const cc = c + dc;
|
|
969
|
+
if (rr < 0 || cc < 0 || rr >= rows || cc >= cols) continue;
|
|
970
|
+
const j = rr * cols + cc;
|
|
971
|
+
if (hit[j] && !seen[j]) {
|
|
972
|
+
seen[j] = 1;
|
|
973
|
+
stack.push(j);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
const x = Math.max(0, minC * cell - pad);
|
|
979
|
+
const y = Math.max(0, minR * cell - pad);
|
|
980
|
+
boxes.push({ x, y, w: Math.min(diff.width, (maxC + 1) * cell + pad) - x, h: Math.min(diff.height, (maxR + 1) * cell + pad) - y, cells });
|
|
981
|
+
}
|
|
982
|
+
return boxes.sort((a, b) => b.w * b.h - a.w * a.h).slice(0, max).map(({ x, y, w, h }) => ({ x, y, w, h }));
|
|
983
|
+
}
|
|
984
|
+
function pixelDiff(before, after, threshold = 0.1) {
|
|
985
|
+
const a = decodePng(before);
|
|
986
|
+
const b = decodePng(after);
|
|
987
|
+
const width = Math.max(a.width, b.width);
|
|
988
|
+
const height = Math.max(a.height, b.height);
|
|
989
|
+
const pa = padTo(a, width, height);
|
|
990
|
+
const pb = padTo(b, width, height);
|
|
991
|
+
const out = new PNG({ width, height });
|
|
992
|
+
const changedPixels = pixelmatch(pa.data, pb.data, out.data, width, height, { threshold });
|
|
993
|
+
const ink = contentPixels(a);
|
|
994
|
+
return {
|
|
995
|
+
ratio: changedPixels / (width * height),
|
|
996
|
+
changedPixels,
|
|
997
|
+
contentRatio: changedPixels / Math.max(ink, 1),
|
|
998
|
+
width,
|
|
999
|
+
height,
|
|
1000
|
+
diffPng: encodePng(out),
|
|
1001
|
+
regions: changedPixels ? changeRegions(out) : []
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
function cropTop(buf, maxHeight) {
|
|
1005
|
+
const src = decodePng(buf);
|
|
1006
|
+
if (src.height <= maxHeight) return buf;
|
|
1007
|
+
const out = new PNG({ width: src.width, height: maxHeight });
|
|
1008
|
+
PNG.bitblt(src, out, 0, 0, src.width, maxHeight, 0, 0);
|
|
1009
|
+
return encodePng(out);
|
|
1010
|
+
}
|
|
1011
|
+
function contentPixels(png) {
|
|
1012
|
+
const [r0, g0, b0] = [png.data[0], png.data[1], png.data[2]];
|
|
1013
|
+
let n = 0;
|
|
1014
|
+
for (let i = 0; i < png.data.length; i += 4) {
|
|
1015
|
+
if (Math.abs(png.data[i] - r0) + Math.abs(png.data[i + 1] - g0) + Math.abs(png.data[i + 2] - b0) > 24) n++;
|
|
1016
|
+
}
|
|
1017
|
+
return n;
|
|
1018
|
+
}
|
|
1019
|
+
function dHash(buf) {
|
|
1020
|
+
const png = decodePng(buf);
|
|
1021
|
+
const cols = 9;
|
|
1022
|
+
const rows = 8;
|
|
1023
|
+
const grey = [];
|
|
1024
|
+
for (let r = 0; r < rows; r++) {
|
|
1025
|
+
const y0 = Math.floor(r * png.height / rows);
|
|
1026
|
+
const y1 = Math.max(y0 + 1, Math.floor((r + 1) * png.height / rows));
|
|
1027
|
+
for (let c = 0; c < cols; c++) {
|
|
1028
|
+
const x0 = Math.floor(c * png.width / cols);
|
|
1029
|
+
const x1 = Math.max(x0 + 1, Math.floor((c + 1) * png.width / cols));
|
|
1030
|
+
let sum = 0;
|
|
1031
|
+
let n = 0;
|
|
1032
|
+
for (let y = y0; y < y1; y++) {
|
|
1033
|
+
for (let x = x0; x < x1; x++) {
|
|
1034
|
+
const i = (y * png.width + x) * 4;
|
|
1035
|
+
sum += 0.299 * png.data[i] + 0.587 * png.data[i + 1] + 0.114 * png.data[i + 2];
|
|
1036
|
+
n++;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
grey.push(sum / n);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
let hex = "";
|
|
1043
|
+
for (let r = 0; r < rows; r++) {
|
|
1044
|
+
let byte = 0;
|
|
1045
|
+
for (let c = 0; c < cols - 1; c++) {
|
|
1046
|
+
byte = byte << 1 | (grey[r * cols + c] > grey[r * cols + c + 1] ? 1 : 0);
|
|
1047
|
+
}
|
|
1048
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
1049
|
+
}
|
|
1050
|
+
return hex;
|
|
1051
|
+
}
|
|
1052
|
+
function hammingHex(a, b) {
|
|
1053
|
+
let d = 0;
|
|
1054
|
+
for (let i = 0; i < Math.min(a.length, b.length); i += 2) {
|
|
1055
|
+
let x = parseInt(a.slice(i, i + 2), 16) ^ parseInt(b.slice(i, i + 2), 16);
|
|
1056
|
+
while (x) {
|
|
1057
|
+
d += x & 1;
|
|
1058
|
+
x >>= 1;
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
return d;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// src/state.ts
|
|
1065
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, writeFileSync } from "fs";
|
|
1066
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
1067
|
+
function runDir(repoRoot, runId) {
|
|
1068
|
+
return join3(repoRoot, ".mushi", "ux", runId);
|
|
1069
|
+
}
|
|
1070
|
+
function newRunId(now = /* @__PURE__ */ new Date()) {
|
|
1071
|
+
const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");
|
|
1072
|
+
return `${stamp}-${Math.random().toString(36).slice(2, 6)}`;
|
|
1073
|
+
}
|
|
1074
|
+
function saveState(dir, state) {
|
|
1075
|
+
mkdirSync2(dir, { recursive: true });
|
|
1076
|
+
state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1077
|
+
const file = join3(dir, "state.json");
|
|
1078
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
1079
|
+
writeFileSync(tmp, JSON.stringify(state, null, 2));
|
|
1080
|
+
renameSync(tmp, file);
|
|
1081
|
+
}
|
|
1082
|
+
function loadState(dir) {
|
|
1083
|
+
const file = join3(dir, "state.json");
|
|
1084
|
+
if (!existsSync2(file)) return null;
|
|
1085
|
+
const parsed = JSON.parse(readFileSync3(file, "utf8"));
|
|
1086
|
+
if (parsed.version !== 1) throw new Error(`Unsupported run state version ${String(parsed.version)} in ${file}`);
|
|
1087
|
+
return parsed;
|
|
1088
|
+
}
|
|
1089
|
+
function savePng(dir, rel, png) {
|
|
1090
|
+
const abs = join3(dir, rel);
|
|
1091
|
+
mkdirSync2(dirname2(abs), { recursive: true });
|
|
1092
|
+
writeFileSync(abs, png);
|
|
1093
|
+
return rel.replace(/\\/g, "/");
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// src/studio-page.ts
|
|
1097
|
+
var STUDIO_PAGE = `<!doctype html>
|
|
1098
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1099
|
+
<title>Mushi UX studio</title>
|
|
1100
|
+
<style>
|
|
1101
|
+
:root{--bg:#f6f6f3;--panel:#fff;--fg:#1c1c1a;--muted:#66665f;--line:#e2e2dc;--accent:#4f7f22;--accentfg:#fff;
|
|
1102
|
+
--ok:#2f7d32;--okbg:#e6f3e6;--warn:#8a5a00;--warnbg:#fdf1d8;--bad:#a12a2a;--badbg:#fbe4e4;--info:#2b5c9a;--infobg:#e3edf9;--idle:#55554f;--idlebg:#ecece8}
|
|
1103
|
+
@media (prefers-color-scheme:dark){:root{--bg:#141413;--panel:#1d1d1b;--fg:#ececea;--muted:#a3a39c;--line:#2e2e2b;--accent:#9ccf5f;--accentfg:#14200a;
|
|
1104
|
+
--ok:#8fd394;--okbg:#1e3320;--warn:#f1c46b;--warnbg:#3a2e14;--bad:#f19a9a;--badbg:#3b1d1d;--info:#9cc2f2;--infobg:#1b2a3d;--idle:#c4c4bd;--idlebg:#2a2a27}}
|
|
1105
|
+
*{box-sizing:border-box}body{margin:0;font:14px/1.45 system-ui,-apple-system,Segoe UI,sans-serif;background:var(--bg);color:var(--fg)}
|
|
1106
|
+
button,select,input,textarea{font:inherit;color:inherit}
|
|
1107
|
+
header{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel)}
|
|
1108
|
+
h1{font-size:15px;margin:0;display:flex;gap:6px;align-items:center}h1 small{color:var(--muted);font-weight:400}
|
|
1109
|
+
.grow{flex:1}
|
|
1110
|
+
.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 12px;cursor:pointer}
|
|
1111
|
+
.btn.primary{background:var(--accent);color:var(--accentfg);border-color:transparent;font-weight:600}
|
|
1112
|
+
.btn:disabled{opacity:.5;cursor:not-allowed}.btn:focus-visible,select:focus-visible,input:focus-visible,nav button:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
|
|
1113
|
+
select,input[type=text],input[type=number],textarea{border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 8px;min-width:0}
|
|
1114
|
+
.status{padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel);display:grid;gap:6px}
|
|
1115
|
+
.status .top{display:flex;flex-wrap:wrap;gap:6px 12px;align-items:center}
|
|
1116
|
+
.meter{height:8px;background:var(--idlebg);border-radius:4px;overflow:hidden;display:flex}.meter i{display:block;height:100%}
|
|
1117
|
+
.chip{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:600;white-space:nowrap}
|
|
1118
|
+
.s-accepted,.p-done{background:var(--okbg);color:var(--ok)}.s-reverted,.p-failed{background:var(--badbg);color:var(--bad)}.s-regressed,.s-interrupted{background:var(--warnbg);color:var(--warn)}
|
|
1119
|
+
.s-iterating,.s-baseline,.p-working,.p-install,.p-worktree,.p-dev-server,.p-mapping,.p-reviewing,.p-starting{background:var(--infobg);color:var(--info)}.s-pending,.s-skipped,.s-blocked{background:var(--idlebg);color:var(--idle)}
|
|
1120
|
+
.dot{width:8px;height:8px;border-radius:50%;background:currentColor;display:inline-block}.live .dot{animation:pulse 1.2s infinite}@keyframes pulse{50%{opacity:.25}}
|
|
1121
|
+
@media (prefers-reduced-motion:reduce){.live .dot{animation:none}}
|
|
1122
|
+
.sub{color:var(--muted);font-size:12px}.mono{font-family:ui-monospace,monospace;font-size:12px}
|
|
1123
|
+
main{display:grid;grid-template-columns:minmax(240px,320px) 1fr;min-height:calc(100vh - 110px)}
|
|
1124
|
+
@media (max-width:860px){main{grid-template-columns:1fr}}
|
|
1125
|
+
nav{border-right:1px solid var(--line);overflow:auto;max-height:calc(100vh - 110px)}
|
|
1126
|
+
@media (max-width:860px){nav{max-height:260px;border-right:0;border-bottom:1px solid var(--line)}}
|
|
1127
|
+
nav button{all:unset;box-sizing:border-box;display:block;width:100%;padding:9px 14px;border-bottom:1px solid var(--line);cursor:pointer}
|
|
1128
|
+
nav button[aria-current=true]{background:var(--panel);box-shadow:inset 3px 0 0 var(--accent)}
|
|
1129
|
+
.row{display:flex;justify-content:space-between;gap:8px;align-items:center;min-width:0}.row .chip{flex-shrink:0}.label{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
1130
|
+
section.detail{padding:14px 18px;min-width:0}
|
|
1131
|
+
.toolbar{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0}
|
|
1132
|
+
.seg{display:inline-flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}.seg button{all:unset;box-sizing:border-box;padding:5px 10px;cursor:pointer;font-size:12px}
|
|
1133
|
+
.seg button[aria-pressed=true]{background:var(--fg);color:var(--bg)}
|
|
1134
|
+
.compare{position:relative;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--panel)}
|
|
1135
|
+
.compare.mobile{max-width:420px}
|
|
1136
|
+
.split{display:grid;gap:16px;align-items:start}.split>*{min-width:0}
|
|
1137
|
+
.att[aria-busy=true]{grid-column:1/-1;cursor:default}.att[aria-busy=true] .ph{height:36px}.att .mono{overflow-wrap:anywhere}
|
|
1138
|
+
@media (min-width:1100px){.split.mobile{grid-template-columns:minmax(0,420px) minmax(0,1fr)}.split.mobile .side h3:first-child{margin-top:0}}
|
|
1139
|
+
.compare img{display:block;width:100%;height:auto}.compare .after{position:absolute;inset:0;clip-path:inset(0 0 0 var(--cut,50%))}
|
|
1140
|
+
.compare .diff{position:absolute;inset:0;mix-blend-mode:multiply;opacity:.85}
|
|
1141
|
+
.pair{display:grid;grid-template-columns:1fr 1fr;gap:8px}.pair figure{margin:0;min-width:0}.pair figcaption{font-size:11px;color:var(--muted);margin-bottom:3px}
|
|
1142
|
+
.pair img{display:block;width:100%;height:auto;border:1px solid var(--line);border-radius:8px;background:var(--panel)}
|
|
1143
|
+
.crop{border:1px solid var(--line);border-radius:8px;background-repeat:no-repeat;background-color:var(--panel);width:100%}
|
|
1144
|
+
.changes{display:grid;gap:12px}.changes h4{margin:0 0 4px;font-size:12px;color:var(--muted);font-weight:600}
|
|
1145
|
+
.cap{display:flex;justify-content:space-between;font-size:12px;color:var(--muted);margin-top:4px;gap:8px}
|
|
1146
|
+
input[type=range]{width:100%;max-width:100%}
|
|
1147
|
+
.plan{list-style:none;margin:6px 0 4px;padding:0;display:grid;gap:6px}.plan li{display:flex;gap:8px;align-items:flex-start;font-size:13px;border:1px solid var(--line);border-radius:8px;padding:6px 8px;background:var(--panel)}.plan .mark{width:16px;flex:none;text-align:center;font-weight:600}.pl-done .mark{color:var(--ok)}.pl-failed .mark{color:var(--bad)}.pl-skipped .mark,.pl-pending .mark{color:var(--idle)}.pl-now{border-color:var(--info)}.pl-now .mark{color:var(--info)}
|
|
1148
|
+
.attempts{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px;margin-top:14px}
|
|
1149
|
+
.att{all:unset;box-sizing:border-box;cursor:pointer;border:1px solid var(--line);border-radius:10px;background:var(--panel);overflow:hidden;display:flex;flex-direction:column}
|
|
1150
|
+
.att[aria-pressed=true]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}
|
|
1151
|
+
.att img{width:100%;height:120px;object-fit:cover;object-position:top;background:var(--idlebg);display:block}
|
|
1152
|
+
.att .body{padding:8px 10px;display:grid;gap:4px}
|
|
1153
|
+
.ph{height:120px;display:grid;place-items:center;background:var(--idlebg);color:var(--muted);font-size:12px}
|
|
1154
|
+
.problems{margin:8px 0 0;padding-left:18px;font-size:13px}
|
|
1155
|
+
pre{white-space:pre-wrap;word-break:break-word;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px;max-height:260px;overflow:auto;font-size:12px;margin:0}
|
|
1156
|
+
h3{font-size:13px;margin:18px 0 6px}
|
|
1157
|
+
.empty{color:var(--muted);padding:24px}
|
|
1158
|
+
.form{max-width:860px;margin:0 auto;padding:18px 16px;display:grid;gap:14px}
|
|
1159
|
+
.card{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:14px 16px;display:grid;gap:10px}
|
|
1160
|
+
.card h2{font-size:14px;margin:0}
|
|
1161
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px}
|
|
1162
|
+
label.f{display:grid;gap:4px;font-size:12px;color:var(--muted)}label.f>span{font-weight:600;color:var(--fg)}
|
|
1163
|
+
.params{display:flex;flex-wrap:wrap;gap:10px}
|
|
1164
|
+
.pills{display:flex;flex-wrap:wrap;gap:6px}.pill{all:unset;cursor:pointer;border:1px solid var(--line);border-radius:999px;padding:2px 8px;font-size:12px}
|
|
1165
|
+
.pill[aria-pressed=true]{background:var(--fg);color:var(--bg)}
|
|
1166
|
+
.note{font-size:12px;color:var(--muted)}.warn{color:var(--warn)}.err{color:var(--bad)}
|
|
1167
|
+
.card h2 .n{display:inline-grid;place-items:center;width:20px;height:20px;border-radius:999px;background:var(--fg);color:var(--bg);font-size:11px;margin-right:6px}
|
|
1168
|
+
.lede{font-size:12px;color:var(--muted);margin:-4px 0 0}
|
|
1169
|
+
.choice{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:8px}
|
|
1170
|
+
.choice label{display:flex;gap:8px;align-items:flex-start;border:1px solid var(--line);border-radius:10px;padding:10px;cursor:pointer;font-size:12px;color:var(--muted)}
|
|
1171
|
+
.choice label b{display:block;color:var(--fg);font-size:13px}
|
|
1172
|
+
.choice label:has(input:checked){border-color:var(--fg)}
|
|
1173
|
+
.summary{border:1px dashed var(--line);border-radius:10px;padding:10px;font-size:12px;display:grid;gap:4px}
|
|
1174
|
+
.summary b{color:var(--fg)}
|
|
1175
|
+
details.adv summary{cursor:pointer;font-size:12px;color:var(--muted)}
|
|
1176
|
+
details.log{border-top:1px solid var(--line);background:var(--panel)}details.log summary{padding:8px 16px;cursor:pointer;font-size:12px;color:var(--muted)}details.log pre{border:0;border-radius:0;max-height:220px}details.steps{margin-top:8px}details.steps summary{cursor:pointer;font-size:12px;color:var(--muted)}details.steps pre{max-height:260px}
|
|
1177
|
+
[hidden]{display:none!important}
|
|
1178
|
+
</style></head><body>
|
|
1179
|
+
<header>
|
|
1180
|
+
<h1><svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M8 12l3 3 5-6" fill="none" stroke="var(--accent)" stroke-width="2.4" stroke-linecap="round"/></svg>Mushi UX <small id="repo"></small></h1>
|
|
1181
|
+
<div class="grow"></div>
|
|
1182
|
+
<label class="sub" for="runPick">Run</label><select id="runPick" aria-label="Run"></select>
|
|
1183
|
+
<button class="btn primary" id="newBtn" hidden>\uFF0B New run</button>
|
|
1184
|
+
</header>
|
|
1185
|
+
<div class="status" id="status" hidden>
|
|
1186
|
+
<div class="top"><span id="phase" class="chip"></span><span id="phaseDetail" class="sub"></span><span class="grow"></span><span id="clock" class="sub mono"></span><button class="btn" id="stopBtn" hidden>\u25A0 Stop</button><button class="btn primary" id="resumeBtn" hidden>\u25B6 Resume</button><button class="btn primary" id="prBtn" hidden>Open draft PR</button><a class="btn" id="prLink" hidden target="_blank" rel="noopener"></a><a class="btn" id="consoleLink" hidden target="_blank" rel="noopener" title="The run, its screens and the merge button in the Mushi console">Review in console \u2197</a></div>
|
|
1187
|
+
<div class="meter" id="meter" role="img"></div>
|
|
1188
|
+
<div class="sub" id="who"></div>
|
|
1189
|
+
</div>
|
|
1190
|
+
<div id="launcher" hidden></div>
|
|
1191
|
+
<main id="runview" hidden><nav id="list" aria-label="Screens"></nav><section class="detail" id="detail"><p class="empty">Pick a screen.</p></section></main>
|
|
1192
|
+
<details class="log" id="logbox" hidden><summary>Run log</summary><pre id="runlog"></pre></details>
|
|
1193
|
+
<script>
|
|
1194
|
+
const T = new URLSearchParams(location.search).get('t')
|
|
1195
|
+
const q = (p) => p + (p.includes('?') ? '&' : '?') + 't=' + T
|
|
1196
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c])
|
|
1197
|
+
const api = (p, init) => fetch(q(p), init).then(async (r) => { const b = await r.json().catch(() => ({})); if (!r.ok) throw new Error(b.error || ('HTTP ' + r.status)); return b })
|
|
1198
|
+
const STATUS = { accepted: 'Improved', reverted: 'Rolled back', regressed: 'Moved by another change', iterating: 'Agent working', baseline: 'Measuring', interrupted: 'Stopped mid-attempt', pending: 'Queued', skipped: 'No change needed', blocked: 'Not finished' }
|
|
1199
|
+
const PHASE = { starting: 'Starting', worktree: 'Creating worktree', install: 'Installing', 'dev-server': 'Starting dev server', mapping: 'Mapping screens', working: 'Working', reviewing: 'Reviewing', done: 'Done', failed: 'Failed' }
|
|
1200
|
+
const FINISHED = ['accepted', 'reverted', 'skipped', 'regressed', 'blocked']
|
|
1201
|
+
const store = { get(k) { try { return JSON.parse(localStorage.getItem('mushi-ux:' + k)) } catch { return null } }, set(k, v) { try { localStorage.setItem('mushi-ux:' + k, JSON.stringify(v)) } catch {} } }
|
|
1202
|
+
let meta = null, runs = [], runId = null, state = null, selected = null, vp = 'mobile', diffOn = false, pick = null, view = 'changes'
|
|
1203
|
+
const agentLog = {}, runLog = [], stepsFetched = new Set()
|
|
1204
|
+
const chip = (st) => '<span class="chip s-' + st + '">' + esc(STATUS[st] || st) + '</span>'
|
|
1205
|
+
const shot = (p) => q('/shot?run=' + encodeURIComponent(runId) + '&p=' + encodeURIComponent(p))
|
|
1206
|
+
const dur = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); return s < 60 ? s + 's' : Math.floor(s / 60) + 'm ' + String(s % 60).padStart(2, '0') + 's' }
|
|
1207
|
+
|
|
1208
|
+
// \u2500\u2500 Run view \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1209
|
+
function renderStatus() {
|
|
1210
|
+
const box = document.getElementById('status')
|
|
1211
|
+
if (!state) { box.hidden = true; return }
|
|
1212
|
+
box.hidden = false
|
|
1213
|
+
// A run that stopped mid-phase without saying so (process killed, machine slept) is not live.
|
|
1214
|
+
const unfinished = !['done', 'failed'].includes(state.phase || 'starting')
|
|
1215
|
+
// A run this studio did not start (another studio, mushi-ux run) is live while it checks in.
|
|
1216
|
+
const interrupted = unfinished && !(meta && runId === meta.active) && quietMinutes() > 0
|
|
1217
|
+
const ph = interrupted ? 'failed' : (state.phase || 'starting'), live = unfinished && !interrupted
|
|
1218
|
+
const el = document.getElementById('phase')
|
|
1219
|
+
el.className = 'chip p-' + ph + (live ? ' live' : '')
|
|
1220
|
+
el.innerHTML = (live ? '<span class="dot"></span>' : '') + esc(interrupted ? 'Interrupted' : (PHASE[ph] || ph))
|
|
1221
|
+
const pd = document.getElementById('phaseDetail')
|
|
1222
|
+
pd.textContent = interrupted
|
|
1223
|
+
? 'This run stopped while ' + (PHASE[state.phase] || 'working').toLowerCase() + '. ' + (resumable() ? 'Resume carries on from the first unfinished screen.' : 'Continue it with: mushi-ux run --resume ' + state.runId)
|
|
1224
|
+
: state.error ? state.error.split('\\n')[0] : (state.phaseDetail || '')
|
|
1225
|
+
const quiet = live ? quietMinutes() : 0
|
|
1226
|
+
if (quiet) pd.textContent += ' \xB7 No check-in for ' + quiet + ' min: the run may have stopped. Check the terminal that started it.'
|
|
1227
|
+
// A read-only view (mushi-ux open) has no Resume button: say how to carry on.
|
|
1228
|
+
if (state.phase === 'failed' && !resumable()) pd.textContent += ' \xB7 Continue it with: mushi-ux run --resume ' + state.runId
|
|
1229
|
+
pd.className = state.error || interrupted ? 'sub err' : quiet ? 'sub warn' : 'sub'
|
|
1230
|
+
const total = state.surfaces.length, counts = {}
|
|
1231
|
+
for (const s of state.surfaces) counts[shownStatus(s)] = (counts[shownStatus(s)] || 0) + 1
|
|
1232
|
+
const done = state.surfaces.filter((s) => FINISHED.includes(s.status)).length
|
|
1233
|
+
const seg = (k, color) => counts[k] ? '<i style="width:' + (counts[k] / Math.max(1, total) * 100) + '%;background:' + color + '" title="' + esc(STATUS[k]) + ' ' + counts[k] + '"></i>' : ''
|
|
1234
|
+
const meter = document.getElementById('meter')
|
|
1235
|
+
meter.innerHTML = seg('accepted', 'var(--ok)') + seg('regressed', 'var(--warn)') + seg('reverted', 'var(--bad)') + seg('skipped', 'var(--idle)') + seg('blocked', 'var(--idle)') + seg('iterating', 'var(--info)')
|
|
1236
|
+
meter.setAttribute('aria-label', done + ' of ' + total + ' screens finished')
|
|
1237
|
+
const parts = [done + ' of ' + total + ' screens done', state.agent + (state.model ? ' \xB7 ' + state.model : '')]
|
|
1238
|
+
if (state.skill) parts.push('skill ' + state.skill.name)
|
|
1239
|
+
if (state.branch) parts.push(state.branch + (state.baseRef ? ' (from ' + state.baseRef + ')' : ''))
|
|
1240
|
+
document.getElementById('who').innerHTML = parts.map(esc).join(' \xB7 ') + ' ' + Object.entries(counts).map(([k, n]) => chip(k).replace('</span>', ' ' + n + '</span>')).join(' ')
|
|
1241
|
+
const stop = document.getElementById('stopBtn')
|
|
1242
|
+
stop.hidden = !(meta && meta.canStop && live && runId === meta.active)
|
|
1243
|
+
stop.disabled = false
|
|
1244
|
+
// Interrupted, failed or stopped: carry on from where it stopped, with the settings it started with.
|
|
1245
|
+
const resumeBtn = document.getElementById('resumeBtn')
|
|
1246
|
+
resumeBtn.hidden = !((interrupted || state.phase === 'failed') && resumable())
|
|
1247
|
+
resumeBtn.disabled = false
|
|
1248
|
+
// A finished run with kept changes: open its PR (or add it to the PR its branch came from), then merge from the console.
|
|
1249
|
+
const kept = state.surfaces.some((x) => x.iterations.some((it) => it.outcome === 'accepted' && it.commitSha))
|
|
1250
|
+
const prBtn = document.getElementById('prBtn'), prLink = document.getElementById('prLink')
|
|
1251
|
+
prBtn.hidden = !(meta && meta.canOpenPr && state.phase === 'done' && kept && !state.pr)
|
|
1252
|
+
prBtn.textContent = (state.baseRef || '').startsWith('origin/mushi-ux/') ? 'Add to its pull request' : 'Open draft PR'
|
|
1253
|
+
prLink.hidden = !state.pr
|
|
1254
|
+
if (state.pr) { prLink.href = state.pr.url; prLink.textContent = 'PR #' + state.pr.number + (state.pr.added ? ' (added) \u2197' : ' \u2197'); prLink.title = 'Merge it from the Mushi console once its checks pass' }
|
|
1255
|
+
// A mirrored run is reviewed and merged in the console; link straight to it.
|
|
1256
|
+
const consoleLink = document.getElementById('consoleLink')
|
|
1257
|
+
consoleLink.hidden = !(meta && meta.consoleUrl && state.options && state.options.sync)
|
|
1258
|
+
if (!consoleLink.hidden) consoleLink.href = meta.consoleUrl + '/ux-runs?run=' + encodeURIComponent(state.runId)
|
|
1259
|
+
tick()
|
|
1260
|
+
}
|
|
1261
|
+
/** Minutes since the run last saved its state (it does every 30 s while alive); 0 while it is fresh. */
|
|
1262
|
+
function quietMinutes() {
|
|
1263
|
+
const hb = state && (state.updatedAt || (state.current && state.current.heartbeatAt))
|
|
1264
|
+
const gap = hb ? Date.now() - Date.parse(hb) : 0
|
|
1265
|
+
return gap > 3 * 60000 ? Math.floor(gap / 60000) : 0
|
|
1266
|
+
}
|
|
1267
|
+
/** The run is not going anywhere: it failed or stopped, or its process died without saying so. */
|
|
1268
|
+
function runIsDead() {
|
|
1269
|
+
if (!state) return false
|
|
1270
|
+
if (state.phase === 'failed') return true
|
|
1271
|
+
const unfinished = state.phase !== 'done'
|
|
1272
|
+
return unfinished && !(meta && runId === meta.active) && quietMinutes() > 0
|
|
1273
|
+
}
|
|
1274
|
+
/** A screen the agent was on when the run died shows that, not "Agent working". */
|
|
1275
|
+
function shownStatus(s) { return s.status === 'iterating' && runIsDead() ? 'interrupted' : s.status }
|
|
1276
|
+
function tick() {
|
|
1277
|
+
if (!state) return
|
|
1278
|
+
const dead = runIsDead()
|
|
1279
|
+
// A dead run's clock stops at its last check-in instead of counting on.
|
|
1280
|
+
const end = state.finishedAt ? Date.parse(state.finishedAt) : dead ? Date.parse(state.updatedAt) : Date.now()
|
|
1281
|
+
let txt = 'elapsed ' + dur(end - Date.parse(state.createdAt))
|
|
1282
|
+
if (state.current && !state.finishedAt && !dead) txt = 'this attempt ' + dur(Date.now() - Date.parse(state.current.startedAt)) + (state.current.timeoutMs ? ' of ' + dur(state.current.timeoutMs) : '') + ' \xB7 ' + txt
|
|
1283
|
+
document.getElementById('clock').textContent = txt
|
|
1284
|
+
}
|
|
1285
|
+
setInterval(tick, 1000)
|
|
1286
|
+
// Events can be missing (a run started elsewhere, a dropped stream): re-read an unfinished run's state.
|
|
1287
|
+
setInterval(() => { if (state && !['done', 'failed'].includes(state.phase || 'starting') && !document.hidden) loadState() }, 15000)
|
|
1288
|
+
|
|
1289
|
+
function workingCard(s) {
|
|
1290
|
+
const c = state.current && state.current.surface === s.surface.key ? state.current : null
|
|
1291
|
+
const n = c ? c.attempt : s.iterations.length + 1
|
|
1292
|
+
if (runIsDead()) {
|
|
1293
|
+
return '<div class="att"><div class="ph">Stopped</div><div class="body"><div class="row"><strong>Attempt ' + n + '</strong>' + chip('interrupted') + '</div><div class="sub">The run stopped during this attempt. Its unfinished edits are thrown away and it runs again on Resume.</div></div></div>'
|
|
1294
|
+
}
|
|
1295
|
+
let body = '<div class="row"><strong>Attempt ' + n + '</strong><span class="chip s-iterating">working</span></div>'
|
|
1296
|
+
if (c) {
|
|
1297
|
+
body += '<div class="sub">' + (c.steps ? c.steps + ' step' + (c.steps === 1 ? '' : 's') : 'Reading the brief') + (c.lastStep ? ' \xB7 ' + esc(c.lastStep) : '') + '</div>'
|
|
1298
|
+
if (c.files && c.files.length) body += '<div class="sub mono">Changed so far: ' + c.files.slice(0, 6).map(esc).join(', ') + (c.files.length > 6 ? ' +' + (c.files.length - 6) + ' more' : '') + '</div>'
|
|
1299
|
+
}
|
|
1300
|
+
return '<div class="att" aria-busy="true"><div class="ph live" style="color:var(--info)"><span><span class="dot"></span> In progress</span></div><div class="body">' + body + '</div></div>'
|
|
1301
|
+
}
|
|
1302
|
+
/** Steps mode: the screen's plan as a checklist, the step being worked on marked. */
|
|
1303
|
+
function planHtml(s) {
|
|
1304
|
+
if (!s.plan || !s.plan.steps || !s.plan.steps.length) return ''
|
|
1305
|
+
const working = shownStatus(s) === 'iterating'
|
|
1306
|
+
const now = working ? s.plan.steps.find((p) => p.status === 'pending') : null
|
|
1307
|
+
const MARK = { done: '\u2713', skipped: '\u2013', failed: '\u2717', pending: '\u25CB' }
|
|
1308
|
+
const LABEL = { done: 'kept', skipped: 'not needed', failed: 'rolled back', pending: 'to do' }
|
|
1309
|
+
return '<h3>Plan: ' + s.plan.steps.filter((p) => p.status === 'done').length + ' of ' + s.plan.steps.length + ' steps kept</h3><ol class="plan">' + s.plan.steps.map((p) => {
|
|
1310
|
+
const cur = p === now
|
|
1311
|
+
const why = p.reason ? p.reason.replace(/^Step \\d+\\/\\d+: /, '') : ''
|
|
1312
|
+
return '<li class="pl-' + (cur ? 'now' : p.status) + '"><span class="mark" aria-hidden="true">' + (cur ? '\u25B6' : MARK[p.status]) + '</span><div><div>' + esc(p.text) + ' <span class="sub">(' + (cur ? 'working now' : LABEL[p.status]) + ')</span></div>' + (why ? '<div class="sub">' + esc(why) + '</div>' : '') + '</div></li>'
|
|
1313
|
+
}).join('') + '</ol>'
|
|
1314
|
+
}
|
|
1315
|
+
function attemptsWithShots(s) { return s.iterations.filter((i) => i.after && (i.after.desktop || i.after.mobile)) }
|
|
1316
|
+
function renderRun() {
|
|
1317
|
+
renderStatus()
|
|
1318
|
+
const list = document.getElementById('list')
|
|
1319
|
+
if (!state) { list.innerHTML = ''; document.getElementById('detail').innerHTML = '<p class="empty">No run selected.</p>'; return }
|
|
1320
|
+
const cur = state.current && state.current.surface
|
|
1321
|
+
list.innerHTML = state.surfaces.map((s) =>
|
|
1322
|
+
'<button data-k="' + esc(s.surface.key) + '" aria-current="' + (s.surface.key === selected) + '"><div class="row"><span class="label">' + (s.surface.key === cur && !runIsDead() ? '<span class="live" style="color:var(--info)"><span class="dot"></span></span> ' : '') + esc(s.surface.label) + '</span>' + chip(shownStatus(s)) + '</div><div class="sub mono">' + esc(s.surface.path) + (s.surface.steps.length ? ' \u203A ' + esc(s.surface.steps.map((x) => x.label).join(' \u203A ')) : '') + (s.iterations.length ? ' \xB7 ' + s.iterations.length + ' attempt' + (s.iterations.length === 1 ? '' : 's') : '') + '</div></button>').join('') || '<p class="empty">' + (state.phase === 'mapping' ? 'Mapping screens\u2026' : 'No screens yet.') + '</p>'
|
|
1323
|
+
list.querySelectorAll('button').forEach((b) => b.onclick = () => { selected = b.dataset.k; pick = null; renderRun() })
|
|
1324
|
+
const s = state.surfaces.find((x) => x.surface.key === selected) || state.surfaces.find((x) => x.surface.key === cur) || state.surfaces[0]
|
|
1325
|
+
const box = document.getElementById('detail')
|
|
1326
|
+
if (!s) {
|
|
1327
|
+
box.innerHTML = state.error
|
|
1328
|
+
? '<h3>The run stopped</h3><pre>' + esc(state.error) + '</pre><p class="sub">The run log below has the full output. Fix the cause, then start a new run.</p>'
|
|
1329
|
+
: '<p class="empty">' + esc(PHASE[state.phase] || 'Waiting') + '\u2026</p>'
|
|
1330
|
+
if (state.error) document.getElementById('logbox').open = true
|
|
1331
|
+
return
|
|
1332
|
+
}
|
|
1333
|
+
selected = s.surface.key
|
|
1334
|
+
const atts = attemptsWithShots(s)
|
|
1335
|
+
const chosen = pick == null ? atts[atts.length - 1] : atts.find((a) => a.n === pick)
|
|
1336
|
+
const base = s.baseline[vp] || s.baseline.desktop, after = chosen && (chosen.after[vp] || null)
|
|
1337
|
+
let html = '<div class="row"><h2 style="margin:0;font-size:18px">' + esc(s.surface.label) + '</h2>' + chip(shownStatus(s)) + '</div>'
|
|
1338
|
+
if (s.note) html += '<p class="sub">' + esc(s.note) + '</p>'
|
|
1339
|
+
html += '<div class="toolbar"><div class="seg" role="group" aria-label="Viewport">' + ['mobile', 'desktop'].map((v) => '<button data-vp="' + v + '" aria-pressed="' + (v === vp) + '">' + v + '</button>').join('') + '</div>'
|
|
1340
|
+
if (after) html += '<div class="seg" role="group" aria-label="How to compare">' + [['changes', 'Changes'], ['side', 'Side by side'], ['slider', 'Slider']].map(([v, l]) => '<button data-view="' + v + '" aria-pressed="' + (v === view) + '">' + l + '</button>').join('') + '</div>'
|
|
1341
|
+
if (after && view === 'slider') html += '<label class="sub"><input type="checkbox" id="diff"' + (diffOn ? ' checked' : '') + '> Show changed pixels</label>'
|
|
1342
|
+
// Wide screens: the phone screenshot on the left, attempts and the agent's steps beside it.
|
|
1343
|
+
html += '</div><div class="split ' + vp + '"><div>'
|
|
1344
|
+
let problemsHtml = ''
|
|
1345
|
+
if (base) {
|
|
1346
|
+
// Before = the screen this attempt started from (the last kept step), so every view shows what THIS attempt changed.
|
|
1347
|
+
const prev = after ? startedFrom(s, chosen.n, vp) : null
|
|
1348
|
+
if (after && view === 'changes') html += changesHtml(prev, after, chosen, s)
|
|
1349
|
+
else if (after && view === 'side') html += '<div class="pair"><figure><figcaption>Before ' + esc(stepName(s, chosen.n, true)) + ' \xB7 problem score ' + prev.penalty + '</figcaption><img alt="Before" src="' + shot(prev.png) + '"></figure><figure><figcaption>' + esc(stepName(s, chosen.n)) + ' \xB7 problem score ' + after.penalty + '</figcaption><img alt="After" src="' + shot(after.png) + '"></figure></div>'
|
|
1350
|
+
else {
|
|
1351
|
+
html += '<div class="compare ' + vp + '" id="cmp"><img alt="Before" src="' + shot((prev || base).png) + '">' + (after ? '<img class="after" alt="After" src="' + shot(after.png) + '">' : '') + (after && diffOn && chosen.diffPng[vp] ? '<img class="diff" alt="Changed pixels" src="' + shot(chosen.diffPng[vp]) + '">' : '') + '</div>'
|
|
1352
|
+
if (after) html += '<input type="range" id="cut" min="0" max="100" value="50" aria-label="Before / after split"><div class="cap"><span>\u25C0 Before \xB7 problem score ' + prev.penalty + '</span><span>' + esc(stepName(s, chosen.n)) + ' \xB7 problem score ' + after.penalty + ' \u25B6</span></div><p class="sub">Drag the handle: left of it is before, right of it is after. One screenshot split in two, not cut off.</p>'
|
|
1353
|
+
else html += '<div class="cap"><span>Baseline \xB7 problem score ' + base.penalty + '</span><span>' + (shownStatus(s) === 'iterating' ? 'Agent working\u2026' : '') + '</span></div>'
|
|
1354
|
+
}
|
|
1355
|
+
const probes = (after || base).probes, lines = []
|
|
1356
|
+
for (const a of probes.axe || []) lines.push(a.help + ' (' + a.count + ')')
|
|
1357
|
+
if (probes.overflowX) lines.push('Scrolls sideways')
|
|
1358
|
+
if (probes.smallTargets) lines.push(probes.smallTargets + ' tap target(s) under 24 px')
|
|
1359
|
+
for (const e of (probes.consoleErrors || []).slice(0, 3)) lines.push('Console: ' + e)
|
|
1360
|
+
if (lines.length) problemsHtml = '<h3>Problems measured on ' + (after ? 'attempt ' + chosen.n : 'the baseline') + ' (' + vp + ')</h3><ul class="problems">' + lines.map((l) => '<li>' + esc(l) + '</li>').join('') + '</ul>'
|
|
1361
|
+
} else html += '<p class="empty">No screenshot yet.</p>'
|
|
1362
|
+
html += '</div><div class="side">' + planHtml(s) + '<h3>Attempts</h3><div class="attempts">' + s.iterations.map((i) => {
|
|
1363
|
+
const a = i.after[vp] || i.after.desktop || i.after.mobile
|
|
1364
|
+
const tone = i.outcome === 'accepted' ? 'accepted' : i.outcome === 'rejected' || i.outcome === 'capture_failed' ? 'reverted' : 'skipped'
|
|
1365
|
+
return '<button class="att" data-n="' + i.n + '" aria-pressed="' + (chosen && chosen.n === i.n) + '"' + (a ? '' : ' disabled') + '>' + (a ? '<img alt="Attempt ' + i.n + '" loading="lazy" src="' + shot(a.png) + '">' : '<div class="ph">no screenshot</div>') + '<div class="body"><div class="row"><strong>Attempt ' + i.n + '</strong>' + chip(tone).replace(/>[^<]+</, '>' + esc(i.outcome.replace('_', ' ')) + '<') + '</div>' + (i.needsReview ? '<div class="sub warn">Needs your review: nothing visible changed</div>' : '') + (i.checker ? '<div class="sub">' + esc(checkerLine(i.checker)) + '</div>' : '') + '<div class="sub">' + esc(i.reason) + '</div><div class="sub mono">' + dur(i.durationMs) + (i.pixelDiff[vp] != null ? ' \xB7 ' + (i.pixelDiff[vp] * 100).toFixed(1) + '% px' : '') + (i.commitSha ? ' \xB7 ' + i.commitSha.slice(0, 8) : '') + '</div></div></button>'
|
|
1366
|
+
}).join('') + (s.status === 'iterating' ? workingCard(s) : '') + '</div>'
|
|
1367
|
+
if (!s.iterations.length && s.status !== 'iterating') html += '<p class="sub">No attempts yet.</p>'
|
|
1368
|
+
const mine = (agentLog[selected] || []).slice(-80)
|
|
1369
|
+
const stepsTitle = { iterating: 'Agent steps (live)', interrupted: 'Agent steps before the run stopped' }[shownStatus(s)] || 'Agent steps, last attempt'
|
|
1370
|
+
if (mine.length) html += '<h3>' + stepsTitle + '</h3><pre id="agentout">' + esc(mine.join('\\n')) + '</pre>'
|
|
1371
|
+
else if (shownStatus(s) === 'iterating') html += '<h3>' + stepsTitle + '</h3><pre id="agentout" class="sub">Steps appear here as the agent reads and edits files.</pre>'
|
|
1372
|
+
html += problemsHtml
|
|
1373
|
+
const jv = (s.judge || []).find((v) => v.viewport === vp)
|
|
1374
|
+
if (jv) html += '<h3>Review by ' + esc(jv.model) + ' (advisory)</h3><p class="sub">' + esc(jv.error || ('Prefers ' + (jv.preferred === 'tie' ? 'neither' : jv.preferred === 'after' ? 'the new version' : 'the original') + ' (' + jv.confidence + ' confidence). ' + jv.summary)) + '</p>'
|
|
1375
|
+
for (const i of s.iterations) if (i.logTail) html += '<details class="steps"><summary>What the agent did in attempt ' + i.n + '</summary><pre>' + esc(i.logTail) + '</pre></details>'
|
|
1376
|
+
html += '</div></div>'
|
|
1377
|
+
box.innerHTML = html
|
|
1378
|
+
// After a reload the live stream has nothing yet: read the saved steps once.
|
|
1379
|
+
const stepsKey = runId + ' ' + selected
|
|
1380
|
+
if (s.status === 'iterating' && !mine.length && !stepsFetched.has(stepsKey)) {
|
|
1381
|
+
stepsFetched.add(stepsKey)
|
|
1382
|
+
const forRun = runId, forSurface = selected
|
|
1383
|
+
api('/api/steps?run=' + encodeURIComponent(forRun) + '&surface=' + encodeURIComponent(forSurface)).then(({ lines }) => {
|
|
1384
|
+
if (runId !== forRun || !lines.length || (agentLog[forSurface] || []).length) return
|
|
1385
|
+
agentLog[forSurface] = lines
|
|
1386
|
+
if (selected === forSurface) renderRun()
|
|
1387
|
+
}).catch(() => {})
|
|
1388
|
+
}
|
|
1389
|
+
box.querySelectorAll('[data-vp]').forEach((b) => b.onclick = () => { vp = b.dataset.vp; renderRun() })
|
|
1390
|
+
box.querySelectorAll('[data-view]').forEach((b) => b.onclick = () => { view = b.dataset.view; renderRun() })
|
|
1391
|
+
box.querySelectorAll('.att[data-n]').forEach((b) => b.onclick = () => { pick = Number(b.dataset.n); renderRun() })
|
|
1392
|
+
const d = document.getElementById('diff'); if (d) d.onchange = () => { diffOn = d.checked; renderRun() }
|
|
1393
|
+
const c = document.getElementById('cut'); if (c) c.oninput = () => document.getElementById('cmp').style.setProperty('--cut', c.value + '%')
|
|
1394
|
+
const out = document.getElementById('agentout'); if (out) out.scrollTop = out.scrollHeight
|
|
1395
|
+
}
|
|
1396
|
+
// \u2500\u2500 Before / after \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1397
|
+
/** The screenshot attempt n started from: the last kept attempt before it, else the baseline. */
|
|
1398
|
+
const changeCache = {}
|
|
1399
|
+
function checkerLine(c) {
|
|
1400
|
+
if (c.error) return c.model + ': review failed'
|
|
1401
|
+
const votes = (c.votes || []).map((v) => v.preferred).join(' / ')
|
|
1402
|
+
return c.model + ': ' + (c.verdict === 'revert' ? 'rolled back' : c.verdict === 'keep' ? 'agrees' : 'unsure') + (votes ? ' (' + votes + ')' : '')
|
|
1403
|
+
}
|
|
1404
|
+
function startedFrom(s, n, v) {
|
|
1405
|
+
const kept = s.iterations.filter((i) => i.n < n && i.outcome === 'accepted' && i.after[v]).pop()
|
|
1406
|
+
return (kept && kept.after[v]) || s.baseline[v] || s.baseline.desktop
|
|
1407
|
+
}
|
|
1408
|
+
function stepName(s, n, before) {
|
|
1409
|
+
const it = s.iterations.find((i) => i.n === n), steps = (s.plan && s.plan.steps) || []
|
|
1410
|
+
const k = it && it.step ? steps.findIndex((p) => p.text === it.step) : -1
|
|
1411
|
+
return k >= 0 ? (before ? 'step ' : 'Step ') + (k + 1) : (before ? 'attempt ' : 'Attempt ') + n
|
|
1412
|
+
}
|
|
1413
|
+
/** One changed area as a zoomed crop of a screenshot (CSS sprite maths, no canvas). */
|
|
1414
|
+
function cropHtml(png, box, size, label) {
|
|
1415
|
+
const sx = box.w >= size.width ? 0 : (box.x / (size.width - box.w)) * 100
|
|
1416
|
+
const sy = box.h >= size.height ? 0 : (box.y / (size.height - box.h)) * 100
|
|
1417
|
+
const style = 'aspect-ratio:' + box.w + '/' + box.h + ';background-image:url("' + shot(png) + '");background-size:' + (size.width / box.w) * 100 + '% auto;background-position:' + sx + '% ' + sy + '%'
|
|
1418
|
+
return '<figure><figcaption>' + esc(label) + '</figcaption><div class="crop" role="img" aria-label="' + esc(label) + '" style="' + style + '"></div></figure>'
|
|
1419
|
+
}
|
|
1420
|
+
function changesHtml(prev, after, it, s) {
|
|
1421
|
+
let ch = it.changes && it.changes[vp]
|
|
1422
|
+
const pct = it.pixelDiff[vp] != null ? (it.pixelDiff[vp] * 100).toFixed(1) + '% of the screen changed' : ''
|
|
1423
|
+
if (!ch && it.diffPng && it.diffPng[vp]) {
|
|
1424
|
+
// An older attempt: work the areas out from its saved diff image once.
|
|
1425
|
+
const key = runId + ' ' + it.diffPng[vp]
|
|
1426
|
+
ch = changeCache[key]
|
|
1427
|
+
if (!ch) {
|
|
1428
|
+
if (!changeCache[key + '?']) {
|
|
1429
|
+
changeCache[key + '?'] = true
|
|
1430
|
+
api('/api/changes?run=' + encodeURIComponent(runId) + '&p=' + encodeURIComponent(it.diffPng[vp])).then((c) => { changeCache[key] = c; renderRun() }).catch(() => {})
|
|
1431
|
+
}
|
|
1432
|
+
return '<p class="sub">Finding the changed areas\u2026</p>'
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
if (!ch) return '<p class="sub">No change areas for this attempt. Use Side by side.</p>'
|
|
1436
|
+
if (!ch.boxes.length) return '<p class="sub">Nothing changed on this screen in this attempt.</p>'
|
|
1437
|
+
return '<div class="changes"><p class="sub">' + ch.boxes.length + ' changed area' + (ch.boxes.length === 1 ? '' : 's') + (pct ? ' \xB7 ' + pct : '') + '. Each is shown before and after ' + esc(stepName(s, it.n, true)) + ', zoomed in.</p>' + ch.boxes.map((b, i) =>
|
|
1438
|
+
'<div><h4>Change ' + (i + 1) + ' \xB7 ' + b.w + '\xD7' + b.h + ' px at ' + b.x + ',' + b.y + '</h4><div class="pair">' + cropHtml(prev.png, b, ch, 'Before') + cropHtml(after.png, b, ch, 'After') + '</div></div>').join('') + '</div>'
|
|
1439
|
+
}
|
|
1440
|
+
async function loadState() { state = runId ? await api('/api/state?run=' + runId).catch(() => state) : null; renderRun() }
|
|
1441
|
+
async function loadRuns() {
|
|
1442
|
+
runs = (await api('/api/runs')).runs
|
|
1443
|
+
const sel = document.getElementById('runPick')
|
|
1444
|
+
sel.innerHTML = runs.map((r) => '<option value="' + esc(r.runId) + '"' + (r.runId === runId ? ' selected' : '') + '>' + esc(new Date(r.createdAt).toLocaleString()) + ' \xB7 ' + esc(r.agent) + (r.model ? ' ' + esc(r.model) : '') + ' \xB7 ' + r.done + '/' + r.total + '</option>').join('') || '<option>No runs yet</option>'
|
|
1445
|
+
sel.disabled = !runs.length
|
|
1446
|
+
}
|
|
1447
|
+
function showRun(id) {
|
|
1448
|
+
runId = id; selected = null; pick = null
|
|
1449
|
+
document.getElementById('launcher').hidden = true
|
|
1450
|
+
document.getElementById('runview').hidden = false
|
|
1451
|
+
document.getElementById('logbox').hidden = false
|
|
1452
|
+
const logEl = document.getElementById('runlog')
|
|
1453
|
+
logEl.textContent = ''
|
|
1454
|
+
history.replaceState(null, '', '?t=' + T + '&run=' + id)
|
|
1455
|
+
loadState()
|
|
1456
|
+
// The saved log first (past runs, a restarted studio), then live lines arrive over events.
|
|
1457
|
+
api('/api/log?run=' + id).then(({ lines }) => {
|
|
1458
|
+
if (runId !== id) return
|
|
1459
|
+
logEl.textContent = lines.join('\\n')
|
|
1460
|
+
logEl.scrollTop = logEl.scrollHeight
|
|
1461
|
+
}).catch(() => {})
|
|
1462
|
+
}
|
|
1463
|
+
document.getElementById('runPick').onchange = (e) => showRun(e.target.value)
|
|
1464
|
+
|
|
1465
|
+
// \u2500\u2500 Launcher \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1466
|
+
let options = null, models = null
|
|
1467
|
+
async function openLauncher() {
|
|
1468
|
+
document.getElementById('runview').hidden = true
|
|
1469
|
+
document.getElementById('logbox').hidden = true
|
|
1470
|
+
document.getElementById('status').hidden = true
|
|
1471
|
+
const box = document.getElementById('launcher')
|
|
1472
|
+
box.hidden = false
|
|
1473
|
+
box.innerHTML = '<div class="form"><div class="card"><h2>New run</h2><p class="note">Checking which coding agents are installed and signed in, this repo\u2019s branches and its pages. This takes up to 20 seconds.</p></div></div>'
|
|
1474
|
+
options = await api('/api/options').catch((e) => ({ error: e.message }))
|
|
1475
|
+
const last = store.get('last') || {}
|
|
1476
|
+
const agents = options.agents || []
|
|
1477
|
+
const agentOpt = (a) => '<option value="' + esc(a.name) + '"' + (a.name === (last.agent || options.defaultAgent) ? ' selected' : '') + (a.installed ? '' : ' disabled') + '>' + esc(a.label) + (a.installed ? '' : ' \u2014 ' + esc(a.note || 'not found')) + '</option>'
|
|
1478
|
+
const refOpt = (r) => '<option value="' + esc(r.ref) + '"' + (r.ref === (last.baseRef || options.defaultRef) ? ' selected' : '') + '>' + esc(r.label) + '</option>'
|
|
1479
|
+
const lastPaths = last.startPaths || (options.lastRun ? options.lastRun.startPaths : [])
|
|
1480
|
+
const whole = lastPaths.length === 0
|
|
1481
|
+
box.innerHTML = '<form class="form" id="lf" novalidate>' +
|
|
1482
|
+
'<div class="card"><h2><span class="n">1</span>What to improve</h2>' +
|
|
1483
|
+
'<p class="lede">The agent works one screen at a time on its own branch. Each change is measured (accessibility, layout, console) and kept only if nothing got worse.</p>' +
|
|
1484
|
+
'<div class="choice" role="radiogroup" aria-label="Which screens">' +
|
|
1485
|
+
'<label><input type="radio" name="f-scope" value="whole"' + (whole ? ' checked' : '') + '><span><b>The whole app</b>Map screens from the home page and the links it opens, up to the screen limit below.</span></label>' +
|
|
1486
|
+
'<label><input type="radio" name="f-scope" value="pages"' + (whole ? '' : ' checked') + '><span><b>Pages I pick</b>Only these pages, plus the tabs and dialogs they open.</span></label>' +
|
|
1487
|
+
'</div>' +
|
|
1488
|
+
'<div id="f-pages-box" class="card" style="padding:10px"' + (whole ? ' hidden' : '') + '>' +
|
|
1489
|
+
'<label class="f"><span>Pages (comma-separated, or click below)</span><input type="text" id="f-paths" autocomplete="off" value="' + esc(lastPaths.join(', ')) + '"></label>' +
|
|
1490
|
+
'<div class="pills" id="f-route-pills">' + (options.routes || []).slice(0, 40).map((r) => '<button type="button" class="pill" data-r="' + esc(r) + '" aria-pressed="false">' + esc(r) + '</button>').join('') + '</div>' +
|
|
1491
|
+
'<label class="sub"><input type="checkbox" id="f-crawl"' + (last.crawl ? ' checked' : '') + '> Also follow links from these pages</label>' +
|
|
1492
|
+
'</div>' +
|
|
1493
|
+
'<div class="grid">' +
|
|
1494
|
+
'<label class="f"><span>Skills: what the agent focuses on, applied in order (' + esc(options.skillsRepo || 'skills package') + ')</span><select id="f-skill"><option value="">Add a skill\u2026</option></select></label>' +
|
|
1495
|
+
'<label class="f"><span>\u2026or your own SKILL.md / folder</span><input type="text" id="f-skill-path" placeholder="./skills/my-skill" autocomplete="off"></label>' +
|
|
1496
|
+
'</div><div class="pills" id="f-chain" aria-label="Skill chain"></div><div class="pills" id="f-next"></div><div class="note" id="f-skill-note"></div>' +
|
|
1497
|
+
'<label class="sub"><input type="checkbox" id="f-steps"' + (last.steps === false ? '' : ' checked') + '> Small steps (recommended): plan each screen first, then one small change per attempt, each kept or rolled back on its own</label>' +
|
|
1498
|
+
'</div>' +
|
|
1499
|
+
'<div class="card"><h2><span class="n">2</span>Who does the work</h2><div class="grid">' +
|
|
1500
|
+
'<label class="f"><span>Coding agent</span><select id="f-agent">' + agents.map(agentOpt).join('') + '</select></label>' +
|
|
1501
|
+
'<label class="f"><span>Model</span><select id="f-model"><option>Loading\u2026</option></select></label>' +
|
|
1502
|
+
'<label class="f" id="f-custom-wrap" hidden><span>Model id</span><input type="text" id="f-custom" placeholder="e.g. grok-4.7" autocomplete="off"></label>' +
|
|
1503
|
+
'</div><div class="params" id="f-params"></div><div class="note" id="f-model-note"></div>' +
|
|
1504
|
+
'<div class="summary" id="f-account"><span class="note">Checking the account\u2026</span></div>' +
|
|
1505
|
+
'<div class="grid">' +
|
|
1506
|
+
'<label class="f"><span>Checker: a second model reviews each kept step and may roll it back</span><select id="f-checker">' + checkerOptions(agents, last) + '</select></label>' +
|
|
1507
|
+
'</div>' +
|
|
1508
|
+
'<div class="note">The checker sees the changed area before and after, twice with the order swapped, and rolls a step back only when both reviews prefer the original. It never keeps a step the measurements rejected. Each checked step costs about $0.20\u20130.50 of your Claude usage (two reviews; measured $0.46 on glot.it).</div>' +
|
|
1509
|
+
'<label class="sub"><input type="checkbox" id="f-invisible"' + (last.keepInvisible === false ? '' : ' checked') + '> Keep changes that are not visible in a screenshot (motion, haptics, press feedback) and flag them for your review</label>' +
|
|
1510
|
+
'<div class="row"><span class="sub mono" id="f-spec"></span><button type="button" class="btn" id="f-refresh">Refresh list</button></div></div>' +
|
|
1511
|
+
'<div class="card"><h2><span class="n">3</span>How much</h2><div class="grid">' +
|
|
1512
|
+
'<label class="f"><span>Screens at most</span><input type="number" id="f-max" min="1" max="100" value="' + (last.maxSurfaces || 8) + '"></label>' +
|
|
1513
|
+
'<label class="f"><span>Attempts (steps) per screen</span><input type="number" id="f-iter" min="1" max="5" value="' + (last.iterations || 4) + '"></label>' +
|
|
1514
|
+
'<label class="f"><span>Minutes per attempt</span><input type="number" id="f-timeout" min="1" max="60" value="' + (last.timeoutMin || 8) + '"></label>' +
|
|
1515
|
+
'</div><div class="summary" id="f-estimate"></div></div>' +
|
|
1516
|
+
'<div class="card"><h2><span class="n">4</span>Your app</h2><div class="grid">' +
|
|
1517
|
+
'<label class="f" style="grid-column:1/-1"><span>Dev command ({port} is replaced)</span><input type="text" id="f-dev" list="f-devs" autocomplete="off"><datalist id="f-devs">' + (options.devCommands || []).map((d) => '<option value="' + esc(d) + '">').join('') + '</datalist></label>' +
|
|
1518
|
+
'<label class="f"><span>Branch from</span><select id="f-base">' + (options.refs || [{ ref: 'HEAD', label: 'HEAD' }]).map(refOpt).join('') + '</select></label>' +
|
|
1519
|
+
'</div>' +
|
|
1520
|
+
(options.lastRun ? '<div class="note">Run ' + esc(options.lastRun.runId) + ' mapped screens with <code>' + esc(options.lastRun.devCommand) + '</code>, so it is first in the list.</div>' : '') +
|
|
1521
|
+
'<div class="note warn" id="f-dev-warn">' + esc(options.devWarning || '') + '</div>' +
|
|
1522
|
+
'<details class="adv"><summary>Advanced: parts of the page to leave out</summary>' +
|
|
1523
|
+
'<label class="f"><span>Not part of the app (CSS selectors, one per line): hidden in screenshots and skipped by every check</span><textarea id="f-ignore" rows="2" autocomplete="off" spellcheck="false" placeholder=".dev-badge">' + esc((last.ignore || []).join('\\n')) + '</textarea></label>' +
|
|
1524
|
+
'<div class="note">Dev overlays, build stamps and the Mushi widget are already skipped. Add your own here, or mark an element with <code>data-mushi-ux-ignore</code>.</div></details></div>' +
|
|
1525
|
+
'<div class="card"><h2>After the run</h2><div class="grid">' +
|
|
1526
|
+
'<label class="f"><span><input type="checkbox" id="f-judge"' + (options.judgeAvailable ? (last.judge === false ? '' : ' checked') : ' disabled') + '> Second-model review</span><input type="text" id="f-judge-model" value="' + esc(last.judgeModel || options.judgeModel || '') + '"' + (options.judgeAvailable ? '' : ' disabled') + '></label>' +
|
|
1527
|
+
'<label class="f"><span><input type="checkbox" id="f-sync"' + (options.syncAvailable ? (last.sync ? ' checked' : '') : ' disabled') + '> Mirror to the Mushi console</span><span class="note">' + esc(options.syncNote || '') + '</span></label>' +
|
|
1528
|
+
'</div>' + (options.judgeAvailable ? '' : '<div class="note">Review needs ANTHROPIC_API_KEY in this shell.</div>') + '</div>' +
|
|
1529
|
+
'<div class="row"><span class="note err" id="f-error"></span><button class="btn primary" id="f-start" type="submit">\u25B6 Start run</button></div></form>'
|
|
1530
|
+
document.getElementById('f-dev').value = last.devCommand || (options.devCommands || [])[0] || ''
|
|
1531
|
+
syncPills()
|
|
1532
|
+
document.getElementById('f-paths').oninput = syncPills
|
|
1533
|
+
box.querySelectorAll('input[name=f-scope]').forEach((r) => r.onchange = () => { document.getElementById('f-pages-box').hidden = scope() !== 'pages'; estimate() })
|
|
1534
|
+
;['f-max', 'f-iter', 'f-timeout', 'f-steps'].forEach((id) => document.getElementById(id).addEventListener('input', estimate))
|
|
1535
|
+
estimate()
|
|
1536
|
+
box.querySelectorAll('.pill').forEach((p) => p.onclick = () => {
|
|
1537
|
+
const input = document.getElementById('f-paths'), set = new Set(input.value.split(',').map((x) => x.trim()).filter(Boolean))
|
|
1538
|
+
set.has(p.dataset.r) ? set.delete(p.dataset.r) : set.add(p.dataset.r)
|
|
1539
|
+
input.value = [...set].join(', '); syncPills()
|
|
1540
|
+
})
|
|
1541
|
+
document.getElementById('f-agent').onchange = () => loadModels(false)
|
|
1542
|
+
document.getElementById('f-refresh').onclick = () => loadModels(true)
|
|
1543
|
+
document.getElementById('f-model').onchange = renderParams
|
|
1544
|
+
document.getElementById('f-custom').oninput = updateSpec
|
|
1545
|
+
document.getElementById('lf').onsubmit = (e) => { e.preventDefault(); start() }
|
|
1546
|
+
loadModels(false)
|
|
1547
|
+
loadSkills(last.skill)
|
|
1548
|
+
}
|
|
1549
|
+
function checkerOptions(agents, last) {
|
|
1550
|
+
const claude = agents.some((a) => a.name === 'claude-code' && a.installed)
|
|
1551
|
+
const opts = [['', 'None: measurements alone decide']]
|
|
1552
|
+
if (claude) opts.push(['claude-code|claude-opus-5-5', 'Claude Opus 5.5, via Claude Code (your sign-in)'], ['claude-code|claude-sonnet-5-5', 'Claude Sonnet 5.5, via Claude Code (cheaper)'])
|
|
1553
|
+
if (options.judgeAvailable) opts.push(['anthropic-api|claude-opus-5-5', 'Claude Opus 5.5, via the Anthropic API key'])
|
|
1554
|
+
const want = last.checkerModel ? (last.checkerVia || 'claude-code') + '|' + last.checkerModel : (claude ? 'claude-code|claude-opus-5-5' : '')
|
|
1555
|
+
return opts.map(([v, l]) => '<option value="' + esc(v) + '"' + (v === want ? ' selected' : '') + '>' + esc(l) + '</option>').join('') + (claude ? '' : '<option disabled>Claude Code not found: install it to use Claude as the checker</option>')
|
|
1556
|
+
}
|
|
1557
|
+
function checkerPick() {
|
|
1558
|
+
const v = document.getElementById('f-checker').value
|
|
1559
|
+
if (!v) return { model: null, via: 'claude-code' }
|
|
1560
|
+
const [via, model] = v.split('|')
|
|
1561
|
+
return { model, via }
|
|
1562
|
+
}
|
|
1563
|
+
function scope() { const r = document.querySelector('input[name=f-scope]:checked'); return r ? r.value : 'whole' }
|
|
1564
|
+
// Published per-million-token prices (cursor.com/docs/models-and-pricing, read 2026-10-07).
|
|
1565
|
+
const PRICES = [
|
|
1566
|
+
['grok-4.7', 'Grok 4.7: $2 in / $6 out per million tokens; the Fast tier, the default speed on Pro and above, is $4 / $12. A Cursor model, so it draws on the larger included pool first.'],
|
|
1567
|
+
['opus-5.5', 'Claude Opus 5.5: $4 in / $20 out per million tokens.'],
|
|
1568
|
+
['opus-5-5', 'Claude Opus 5.5: $4 in / $20 out per million tokens.'],
|
|
1569
|
+
['sonnet-5.5', 'Claude Sonnet 5.5: $2 in / $10 out per million tokens.'],
|
|
1570
|
+
['sonnet-5-5', 'Claude Sonnet 5.5: $2 in / $10 out per million tokens.'],
|
|
1571
|
+
['composer', 'A Cursor model: it draws on the larger included pool first.'],
|
|
1572
|
+
]
|
|
1573
|
+
function priceNote() {
|
|
1574
|
+
const spec = (modelSpec() || '').toLowerCase()
|
|
1575
|
+
const hit = PRICES.find(([k]) => spec.includes(k))
|
|
1576
|
+
return hit ? hit[1] : 'Billed at the model\u2019s API rate: first from your plan\u2019s included usage, then on-demand if you allow it.'
|
|
1577
|
+
}
|
|
1578
|
+
function estimate() {
|
|
1579
|
+
const num = (id, d) => { const n = parseInt(document.getElementById(id).value, 10); return Number.isFinite(n) && n > 0 ? n : d }
|
|
1580
|
+
const screens = num('f-max', 8), tries = num('f-iter', 4), mins = num('f-timeout', 8), steps = document.getElementById('f-steps').checked
|
|
1581
|
+
const worst = screens * (tries * mins + (steps ? 4 : 0)) + 5
|
|
1582
|
+
const h = Math.floor(worst / 60), m = worst % 60
|
|
1583
|
+
document.getElementById('f-estimate').innerHTML =
|
|
1584
|
+
'<span><b>Up to ' + screens * tries + ' attempts</b> (' + screens + ' screen' + (screens === 1 ? '' : 's') + ' \xD7 ' + tries + (steps ? ' steps, after a planning pass of up to 4 min each' : ' attempts') + ').</span>' +
|
|
1585
|
+
'<span>Worst case about <b>' + (h ? h + ' h ' : '') + m + ' min</b> of agent time, since every attempt stops at its time box. Runs usually end sooner: a step that needs no change moves on.</span>' +
|
|
1586
|
+
'<span class="note">' + (scope() === 'whole' ? 'Whole app: screens are mapped from the home page until the limit above.' : 'Pages you picked: at most ' + screens + ' of them are worked on.') + '</span>'
|
|
1587
|
+
}
|
|
1588
|
+
const accounts = {}
|
|
1589
|
+
async function loadAccount() {
|
|
1590
|
+
const agent = document.getElementById('f-agent').value, box = document.getElementById('f-account')
|
|
1591
|
+
// The CLI call takes a second or two; a model change only redraws the price.
|
|
1592
|
+
accounts[agent] = accounts[agent] || api('/api/account?agent=' + encodeURIComponent(agent)).catch(() => ({ account: null }))
|
|
1593
|
+
const r = await accounts[agent]
|
|
1594
|
+
const a = r.account
|
|
1595
|
+
const who = a ? '<span>Spends <b>' + esc(a.email || 'your account') + '</b>' + (a.plan ? ' \xB7 ' + esc(a.plan) + ' plan' : '') + '. To use a different account, sign in with that one in this shell (<code>agent login</code>) and restart the studio.</span>' : '<span>Spends the account this agent is signed in with in this shell.</span>'
|
|
1596
|
+
const usage = '<span class="note">No agent reports how much credit is left, so this cannot show a balance. ' + (a && a.usageUrl ? 'Check it on <a href="' + esc(a.usageUrl) + '" target="_blank" rel="noopener">your usage page</a>. ' : '') + 'If the account runs out mid-run, the run stops; resume it later or with another account.</span>'
|
|
1597
|
+
box.innerHTML = who + '<span>' + esc(priceNote()) + '</span>' + usage
|
|
1598
|
+
}
|
|
1599
|
+
function syncPills() {
|
|
1600
|
+
const set = new Set(document.getElementById('f-paths').value.split(',').map((x) => x.trim()))
|
|
1601
|
+
document.querySelectorAll('#f-route-pills .pill').forEach((p) => p.setAttribute('aria-pressed', String(set.has(p.dataset.r))))
|
|
1602
|
+
}
|
|
1603
|
+
async function loadModels(force) {
|
|
1604
|
+
const agent = document.getElementById('f-agent').value, sel = document.getElementById('f-model'), note = document.getElementById('f-model-note')
|
|
1605
|
+
sel.innerHTML = '<option>Loading\u2026</option>'; note.textContent = ''
|
|
1606
|
+
models = await api('/api/models?agent=' + encodeURIComponent(agent) + (force ? '&fresh=1' : '')).catch((e) => ({ models: [], note: e.message }))
|
|
1607
|
+
const last = store.get('last') || {}, lastModel = (last.agent === agent && last.model) ? last.model.split('?')[0] : null
|
|
1608
|
+
const def = models.models.find((m) => m.id === lastModel) || models.models.find((m) => m.isDefault)
|
|
1609
|
+
sel.innerHTML = '<option value="">Agent default</option>' + models.models.map((m) => '<option value="' + esc(m.id) + '"' + (def && def.id === m.id ? ' selected' : '') + '>' + esc(m.label === m.id ? m.id : m.label + ' \u2014 ' + m.id) + '</option>').join('') + '<option value="__custom">Other model id\u2026</option>'
|
|
1610
|
+
note.textContent = (models.source === 'live' ? models.models.length + ' models from your account. ' : '') + (models.note || '')
|
|
1611
|
+
note.className = models.source === 'none' && models.note ? 'note warn' : 'note'
|
|
1612
|
+
if (lastModel && !def) { sel.value = '__custom'; document.getElementById('f-custom').value = lastModel }
|
|
1613
|
+
renderParams()
|
|
1614
|
+
}
|
|
1615
|
+
function renderParams() {
|
|
1616
|
+
const id = document.getElementById('f-model').value
|
|
1617
|
+
document.getElementById('f-custom-wrap').hidden = id !== '__custom'
|
|
1618
|
+
const m = models && models.models.find((x) => x.id === id), last = store.get('last') || {}
|
|
1619
|
+
const lastParams = new URLSearchParams((last.model || '').split('?')[1] || '')
|
|
1620
|
+
document.getElementById('f-params').innerHTML = (m && m.params ? m.params : []).map((p) => '<label class="f"><span>' + esc(p.label) + '</span><select data-param="' + esc(p.id) + '"><option value="">default</option>' + p.values.map((v) => '<option value="' + esc(v.value) + '"' + (lastParams.get(p.id) === v.value ? ' selected' : '') + '>' + esc(v.label) + '</option>').join('') + '</select></label>').join('')
|
|
1621
|
+
document.querySelectorAll('[data-param]').forEach((s) => s.onchange = updateSpec)
|
|
1622
|
+
updateSpec()
|
|
1623
|
+
}
|
|
1624
|
+
function modelSpec() {
|
|
1625
|
+
const id = document.getElementById('f-model').value
|
|
1626
|
+
const base = id === '__custom' ? document.getElementById('f-custom').value.trim() : id
|
|
1627
|
+
if (!base) return null
|
|
1628
|
+
const params = [...document.querySelectorAll('[data-param]')].filter((s) => s.value).map((s) => s.dataset.param + '=' + s.value)
|
|
1629
|
+
return params.length ? base + '?' + params.join('&') : base
|
|
1630
|
+
}
|
|
1631
|
+
function updateSpec() { const s = modelSpec(); document.getElementById('f-spec').textContent = s ? 'model: ' + s : 'model: the agent\u2019s default'; loadAccount() }
|
|
1632
|
+
let chain = [], knownSkills = new Set()
|
|
1633
|
+
async function loadSkills(last) {
|
|
1634
|
+
const sel = document.getElementById('f-skill'), note = document.getElementById('f-skill-note')
|
|
1635
|
+
try {
|
|
1636
|
+
const { skills } = await api('/api/skills')
|
|
1637
|
+
knownSkills = new Set(skills.map((s) => s.name))
|
|
1638
|
+
const groups = {}
|
|
1639
|
+
for (const s of skills) (groups[s.group || 'Skills'] = groups[s.group || 'Skills'] || []).push(s.name)
|
|
1640
|
+
sel.innerHTML = '<option value="">Add a skill\u2026</option>' + Object.entries(groups).map(([g, names]) => '<optgroup label="' + esc(g) + '">' + names.map((n) => '<option>' + esc(n) + '</option>').join('') + '</optgroup>').join('')
|
|
1641
|
+
note.textContent = skills.length + ' skills. Each skill\\'s whole folder (references too) is given to the agent. With several, the agent applies them in this order.'
|
|
1642
|
+
} catch (e) { note.textContent = e.message; note.className = 'note warn' }
|
|
1643
|
+
if (last && /[\\\\/.]/.test(last)) document.getElementById('f-skill-path').value = last
|
|
1644
|
+
else chain = (last || '').split(',').map((x) => x.trim()).filter((x) => knownSkills.has(x))
|
|
1645
|
+
sel.onchange = () => { if (sel.value && !chain.includes(sel.value) && chain.length < 5) chain.push(sel.value); sel.value = ''; renderChain() }
|
|
1646
|
+
renderChain()
|
|
1647
|
+
}
|
|
1648
|
+
const relatedCache = {}
|
|
1649
|
+
async function renderChain() {
|
|
1650
|
+
const box = document.getElementById('f-chain'), next = document.getElementById('f-next')
|
|
1651
|
+
box.innerHTML = chain.length
|
|
1652
|
+
? chain.map((n, i) => '<button type="button" class="pill" aria-pressed="true" data-rm="' + esc(n) + '" title="Remove">' + (i + 1) + '. ' + esc(n) + ' \xD7</button>').join('')
|
|
1653
|
+
: '<span class="note">No skill: the agent uses the built-in UX guidance.</span>'
|
|
1654
|
+
box.querySelectorAll('[data-rm]').forEach((b) => b.onclick = () => { chain = chain.filter((x) => x !== b.dataset.rm); renderChain() })
|
|
1655
|
+
next.innerHTML = ''
|
|
1656
|
+
const lastSkill = chain[chain.length - 1]
|
|
1657
|
+
if (!lastSkill || chain.length >= 5) return
|
|
1658
|
+
relatedCache[lastSkill] = relatedCache[lastSkill] || api('/api/skill?name=' + encodeURIComponent(lastSkill)).catch(() => ({ related: [] }))
|
|
1659
|
+
const { related } = await relatedCache[lastSkill]
|
|
1660
|
+
const offer = (related || []).filter((n) => knownSkills.has(n) && !chain.includes(n)).slice(0, 6)
|
|
1661
|
+
if (chain[chain.length - 1] !== lastSkill) return
|
|
1662
|
+
next.innerHTML = offer.length ? '<span class="note">' + esc(lastSkill) + ' hands over to:</span>' + offer.map((n) => '<button type="button" class="pill" data-add="' + esc(n) + '">+ ' + esc(n) + '</button>').join('') : ''
|
|
1663
|
+
next.querySelectorAll('[data-add]').forEach((b) => b.onclick = () => { chain.push(b.dataset.add); renderChain() })
|
|
1664
|
+
}
|
|
1665
|
+
async function start() {
|
|
1666
|
+
const err = document.getElementById('f-error'), btn = document.getElementById('f-start')
|
|
1667
|
+
err.textContent = ''
|
|
1668
|
+
const num = (id, d) => { const n = parseInt(document.getElementById(id).value, 10); return Number.isFinite(n) ? n : d }
|
|
1669
|
+
const judgeOn = document.getElementById('f-judge').checked
|
|
1670
|
+
const body = {
|
|
1671
|
+
agent: document.getElementById('f-agent').value,
|
|
1672
|
+
model: modelSpec(),
|
|
1673
|
+
skill: document.getElementById('f-skill-path').value.trim() || chain.join(',') || null,
|
|
1674
|
+
devCommand: document.getElementById('f-dev').value.trim(),
|
|
1675
|
+
baseRef: document.getElementById('f-base').value,
|
|
1676
|
+
startPaths: scope() === 'whole' ? [] : document.getElementById('f-paths').value.split(',').map((x) => x.trim()).filter(Boolean),
|
|
1677
|
+
iterations: num('f-iter', 2), maxSurfaces: num('f-max', 8), timeoutMin: num('f-timeout', 15),
|
|
1678
|
+
judgeModel: judgeOn ? (document.getElementById('f-judge-model').value.trim() || null) : null,
|
|
1679
|
+
sync: document.getElementById('f-sync').checked,
|
|
1680
|
+
crawl: scope() === 'pages' && document.getElementById('f-crawl').checked,
|
|
1681
|
+
steps: document.getElementById('f-steps').checked,
|
|
1682
|
+
checkerModel: checkerPick().model,
|
|
1683
|
+
checkerVia: checkerPick().via,
|
|
1684
|
+
keepInvisible: document.getElementById('f-invisible').checked,
|
|
1685
|
+
ignore: document.getElementById('f-ignore').value.split('\\n').map((x) => x.trim()).filter(Boolean),
|
|
1686
|
+
}
|
|
1687
|
+
if (!body.devCommand) { err.textContent = 'Give the dev command.'; return }
|
|
1688
|
+
store.set('last', { ...body, judge: judgeOn })
|
|
1689
|
+
btn.disabled = true
|
|
1690
|
+
try {
|
|
1691
|
+
const { runId: id } = await api('/api/runs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
|
|
1692
|
+
if (meta) meta.active = id
|
|
1693
|
+
await loadRuns(); showRun(id)
|
|
1694
|
+
} catch (e) { err.textContent = e.message } finally { btn.disabled = false }
|
|
1695
|
+
}
|
|
1696
|
+
function resumable() { return !!(meta && meta.canResume && state && state.options && state.phase !== 'done') }
|
|
1697
|
+
document.getElementById('resumeBtn').onclick = async () => {
|
|
1698
|
+
const b = document.getElementById('resumeBtn'), pd = document.getElementById('phaseDetail')
|
|
1699
|
+
b.disabled = true
|
|
1700
|
+
b.textContent = 'Resuming\u2026'
|
|
1701
|
+
try {
|
|
1702
|
+
await api('/api/runs/' + runId + '/resume', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
|
|
1703
|
+
if (meta) meta.active = runId
|
|
1704
|
+
await loadRuns(); await loadState()
|
|
1705
|
+
} catch (e) { pd.textContent = e.message; pd.className = 'sub err' } finally { b.textContent = '\u25B6 Resume'; b.disabled = false }
|
|
1706
|
+
}
|
|
1707
|
+
document.getElementById('prBtn').onclick = async () => {
|
|
1708
|
+
const b = document.getElementById('prBtn'), pd = document.getElementById('phaseDetail'), label = b.textContent
|
|
1709
|
+
b.disabled = true
|
|
1710
|
+
b.textContent = 'Pushing\u2026'
|
|
1711
|
+
try {
|
|
1712
|
+
const pr = await api('/api/runs/' + runId + '/pr', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
|
|
1713
|
+
pd.textContent = (pr.added ? 'Added to PR #' : 'Opened draft PR #') + pr.number + '. Merge it from the Mushi console once its checks pass.'
|
|
1714
|
+
pd.className = 'sub'
|
|
1715
|
+
await loadState()
|
|
1716
|
+
} catch (e) { pd.textContent = e.message; pd.className = 'sub err' } finally { b.textContent = label; b.disabled = false }
|
|
1717
|
+
}
|
|
1718
|
+
document.getElementById('newBtn').onclick = openLauncher
|
|
1719
|
+
document.getElementById('stopBtn').onclick = async () => {
|
|
1720
|
+
const b = document.getElementById('stopBtn')
|
|
1721
|
+
b.disabled = true
|
|
1722
|
+
b.textContent = 'Stopping\u2026'
|
|
1723
|
+
await api('/api/runs/' + runId + '/stop', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }).catch((e) => { document.getElementById('phaseDetail').textContent = e.message })
|
|
1724
|
+
b.textContent = '\u25A0 Stop'
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
// \u2500\u2500 Live events \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1728
|
+
let stateTimer = null
|
|
1729
|
+
const es = new EventSource(q('/api/events'))
|
|
1730
|
+
es.onmessage = (m) => {
|
|
1731
|
+
const e = JSON.parse(m.data)
|
|
1732
|
+
if (e.type === 'started') { if (meta) meta.active = e.runId; loadRuns(); return }
|
|
1733
|
+
if (e.type === 'log') { runLog.push(e); if (e.runId === runId) { const p = document.getElementById('runlog'); p.textContent += (p.textContent ? '\\n' : '') + e.message; p.scrollTop = p.scrollHeight } }
|
|
1734
|
+
if (e.type === 'agent') { (agentLog[e.surface] = agentLog[e.surface] || []).push(e.line); if (agentLog[e.surface].length > 1500) agentLog[e.surface] = agentLog[e.surface].slice(-800); if (e.runId === runId && e.surface === selected) { const o = document.getElementById('agentout'); if (o) { if (o.classList.contains('sub')) { o.textContent = e.line; o.classList.remove('sub') } else o.textContent += '\\n' + e.line; o.scrollTop = o.scrollHeight } else renderRun() } }
|
|
1735
|
+
if ((e.type === 'state' || e.type === 'phase') && e.runId === runId) { clearTimeout(stateTimer); stateTimer = setTimeout(() => { loadState(); if (e.type === 'phase') loadRuns() }, 150) }
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
;(async () => {
|
|
1739
|
+
meta = await api('/api/meta')
|
|
1740
|
+
document.getElementById('repo').textContent = meta.repo
|
|
1741
|
+
document.getElementById('newBtn').hidden = !meta.launcher
|
|
1742
|
+
await loadRuns()
|
|
1743
|
+
const want = new URLSearchParams(location.search).get('run') || meta.active || meta.initial
|
|
1744
|
+
if (want && runs.some((r) => r.runId === want)) showRun(want)
|
|
1745
|
+
else if (meta.launcher) openLauncher()
|
|
1746
|
+
else if (runs[0]) showRun(runs[0].runId)
|
|
1747
|
+
})()
|
|
1748
|
+
</script></body></html>`;
|
|
1749
|
+
|
|
1750
|
+
// src/dashboard.ts
|
|
1751
|
+
var RUN_ID_RE = /^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/;
|
|
1752
|
+
function safeShotPath(runDirPath, requested) {
|
|
1753
|
+
if (!/^shots\/[\w./-]+\.png$/.test(requested) || requested.includes("..")) return null;
|
|
1754
|
+
const abs = normalize(join4(runDirPath, requested));
|
|
1755
|
+
return abs.startsWith(normalize(runDirPath) + sep) ? abs : null;
|
|
1756
|
+
}
|
|
1757
|
+
var LaunchInput = z.object({
|
|
1758
|
+
agent: z.string().regex(/^[a-z][a-z-]{1,30}$/),
|
|
1759
|
+
model: z.string().max(200).regex(/^[A-Za-z0-9][A-Za-z0-9._:/?=&-]*$/).nullable().default(null),
|
|
1760
|
+
skill: z.string().max(300).nullable().default(null),
|
|
1761
|
+
devCommand: z.string().min(1).max(500),
|
|
1762
|
+
baseRef: z.string().max(200).regex(/^[\w./@^~-]+$/).default("HEAD"),
|
|
1763
|
+
startPaths: z.array(z.string().regex(/^\/[^\s]{0,200}$/)).max(20).default([]),
|
|
1764
|
+
iterations: z.number().int().min(1).max(5).default(2),
|
|
1765
|
+
maxSurfaces: z.number().int().min(1).max(100).default(10),
|
|
1766
|
+
timeoutMin: z.number().int().min(1).max(60).default(10),
|
|
1767
|
+
judgeModel: z.string().max(120).nullable().default(null),
|
|
1768
|
+
/** Follow links from the start pages too; off visits only the pages named. */
|
|
1769
|
+
crawl: z.boolean().default(false),
|
|
1770
|
+
/** Plan each screen into small steps, then one step per attempt. */
|
|
1771
|
+
steps: z.boolean().default(false),
|
|
1772
|
+
/** A second model that may roll a kept step back (ADR 0021); null = measurements alone. */
|
|
1773
|
+
checkerModel: z.string().max(120).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/).nullable().default(null),
|
|
1774
|
+
checkerVia: z.enum(["claude-code", "anthropic-api"]).default("claude-code"),
|
|
1775
|
+
/** Keep edits with nothing visible, flagged for review. */
|
|
1776
|
+
keepInvisible: z.boolean().default(true),
|
|
1777
|
+
/** Selectors that are not the app's UI; added to DEFAULT_IGNORE. */
|
|
1778
|
+
ignore: z.array(z.string().trim().refine(isSafeSelector, "Not a usable CSS selector (no { } < > ; or backslash, at most 200 characters).")).max(20).default([]),
|
|
1779
|
+
sync: z.boolean().default(false)
|
|
1780
|
+
}).strict();
|
|
1781
|
+
function summarize(s) {
|
|
1782
|
+
const finished = /* @__PURE__ */ new Set(["accepted", "reverted", "skipped", "regressed", "blocked"]);
|
|
1783
|
+
return {
|
|
1784
|
+
runId: s.runId,
|
|
1785
|
+
createdAt: s.createdAt,
|
|
1786
|
+
agent: s.agent,
|
|
1787
|
+
model: s.model,
|
|
1788
|
+
skill: s.skill?.name ?? null,
|
|
1789
|
+
phase: s.phase ?? null,
|
|
1790
|
+
total: s.surfaces.length,
|
|
1791
|
+
done: s.surfaces.filter((x) => finished.has(x.status)).length
|
|
1792
|
+
};
|
|
1793
|
+
}
|
|
1794
|
+
async function readBody(req, limit = 64e3) {
|
|
1795
|
+
let size = 0;
|
|
1796
|
+
const chunks = [];
|
|
1797
|
+
for await (const chunk of req) {
|
|
1798
|
+
size += chunk.length;
|
|
1799
|
+
if (size > limit) throw new Error("Request too large");
|
|
1800
|
+
chunks.push(chunk);
|
|
1801
|
+
}
|
|
1802
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
1803
|
+
}
|
|
1804
|
+
async function startStudio(opts) {
|
|
1805
|
+
const token = randomBytes(16).toString("hex");
|
|
1806
|
+
const uxDir = join4(opts.repoRoot, ".mushi", "ux");
|
|
1807
|
+
const clients = /* @__PURE__ */ new Set();
|
|
1808
|
+
let active = null;
|
|
1809
|
+
const send = (payload) => {
|
|
1810
|
+
const data = `data: ${JSON.stringify(payload)}
|
|
1811
|
+
|
|
1812
|
+
`;
|
|
1813
|
+
for (const res of clients) res.write(data);
|
|
1814
|
+
};
|
|
1815
|
+
const subscribe = (runId, events) => {
|
|
1816
|
+
const onEvent = (e) => send({ ...e, runId });
|
|
1817
|
+
events.on("event", onEvent);
|
|
1818
|
+
return () => events.off("event", onEvent);
|
|
1819
|
+
};
|
|
1820
|
+
const unsubscribers = [];
|
|
1821
|
+
if (opts.events && opts.runId) {
|
|
1822
|
+
active = { runId: opts.runId, events: opts.events };
|
|
1823
|
+
unsubscribers.push(subscribe(opts.runId, opts.events));
|
|
1824
|
+
}
|
|
1825
|
+
const json = (res, status, body) => {
|
|
1826
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
1827
|
+
res.end(JSON.stringify(body));
|
|
1828
|
+
};
|
|
1829
|
+
const runDirOf = (runId) => runId && RUN_ID_RE.test(runId) ? join4(uxDir, runId) : null;
|
|
1830
|
+
const server = createServer2((req, res) => {
|
|
1831
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
1832
|
+
if (url.searchParams.get("t") !== token) {
|
|
1833
|
+
res.writeHead(403, { "content-type": "text/plain" });
|
|
1834
|
+
return res.end("Open the link printed by mushi-ux; it carries the access token.");
|
|
1835
|
+
}
|
|
1836
|
+
const handle = async () => {
|
|
1837
|
+
if (req.method === "GET" && url.pathname === "/") {
|
|
1838
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
1839
|
+
return res.end(STUDIO_PAGE);
|
|
1840
|
+
}
|
|
1841
|
+
if (req.method === "GET" && url.pathname === "/api/meta") {
|
|
1842
|
+
return json(res, 200, { launcher: Boolean(opts.launch), canStop: Boolean(opts.stop), canResume: Boolean(opts.resume), canOpenPr: Boolean(opts.openPr), consoleUrl: opts.consoleUrl ?? null, active: active?.runId ?? null, initial: opts.runId ?? null, repo: basename(opts.repoRoot) });
|
|
1843
|
+
}
|
|
1844
|
+
if (req.method === "GET" && url.pathname === "/api/runs") {
|
|
1845
|
+
const ids = existsSync3(uxDir) ? readdirSync3(uxDir).filter((d) => RUN_ID_RE.test(d)) : [];
|
|
1846
|
+
const runs = ids.map((id) => loadState(join4(uxDir, id))).filter((s) => s !== null).map(summarize).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
1847
|
+
return json(res, 200, { runs });
|
|
1848
|
+
}
|
|
1849
|
+
if (req.method === "GET" && url.pathname === "/api/state") {
|
|
1850
|
+
const dir = runDirOf(url.searchParams.get("run"));
|
|
1851
|
+
return json(res, 200, dir ? loadState(dir) : null);
|
|
1852
|
+
}
|
|
1853
|
+
if (req.method === "GET" && url.pathname === "/api/log") {
|
|
1854
|
+
const dir = runDirOf(url.searchParams.get("run"));
|
|
1855
|
+
const file = dir ? join4(dir, "run.log") : null;
|
|
1856
|
+
const lines = file && existsSync3(file) ? readFileSync4(file, "utf8").split("\n").filter(Boolean).slice(-400) : [];
|
|
1857
|
+
return json(res, 200, { lines });
|
|
1858
|
+
}
|
|
1859
|
+
if (req.method === "GET" && url.pathname === "/api/steps") {
|
|
1860
|
+
const dir = runDirOf(url.searchParams.get("run"));
|
|
1861
|
+
const key = url.searchParams.get("surface") ?? "";
|
|
1862
|
+
const n = url.searchParams.get("attempt");
|
|
1863
|
+
if (!dir || !/^[\w.:-]{1,160}$/.test(key) || n !== null && !/^[0-9]{1,2}$/.test(n)) return json(res, 400, { error: "bad request" });
|
|
1864
|
+
const agentDir = join4(dir, "agent");
|
|
1865
|
+
const prefix = attemptLogBase(key, 0).slice(0, -1);
|
|
1866
|
+
const attempts = existsSync3(agentDir) ? readdirSync3(agentDir).map((f) => f.startsWith(prefix) && f.endsWith(".steps.log") ? Number(f.slice(prefix.length, -".steps.log".length)) : NaN).filter((a) => Number.isInteger(a) && a > 0) : [];
|
|
1867
|
+
const attempt = n !== null ? Number(n) : attempts.length ? Math.max(...attempts) : null;
|
|
1868
|
+
const file = attempt !== null && attempts.includes(attempt) ? join4(agentDir, `${prefix}${attempt}.steps.log`) : null;
|
|
1869
|
+
const lines = file ? readFileSync4(file, "utf8").split("\n").filter(Boolean).slice(-200) : [];
|
|
1870
|
+
return json(res, 200, { attempt, lines });
|
|
1871
|
+
}
|
|
1872
|
+
if (req.method === "GET" && url.pathname === "/api/events") {
|
|
1873
|
+
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
|
|
1874
|
+
res.write(": connected\n\n");
|
|
1875
|
+
clients.add(res);
|
|
1876
|
+
req.on("close", () => clients.delete(res));
|
|
1877
|
+
return;
|
|
1878
|
+
}
|
|
1879
|
+
if (req.method === "GET" && url.pathname === "/shot") {
|
|
1880
|
+
const dir = runDirOf(url.searchParams.get("run"));
|
|
1881
|
+
const abs = dir ? safeShotPath(dir, url.searchParams.get("p") ?? "") : null;
|
|
1882
|
+
if (!abs || !existsSync3(abs)) {
|
|
1883
|
+
res.writeHead(404);
|
|
1884
|
+
return res.end();
|
|
1885
|
+
}
|
|
1886
|
+
res.writeHead(200, { "content-type": "image/png", "cache-control": "max-age=3600" });
|
|
1887
|
+
return res.end(readFileSync4(abs));
|
|
1888
|
+
}
|
|
1889
|
+
if (req.method === "GET" && url.pathname === "/api/changes") {
|
|
1890
|
+
const dir = runDirOf(url.searchParams.get("run"));
|
|
1891
|
+
const abs = dir ? safeShotPath(dir, url.searchParams.get("p") ?? "") : null;
|
|
1892
|
+
if (!abs || !existsSync3(abs)) return json(res, 404, { error: "No such diff image" });
|
|
1893
|
+
const png = PNG2.sync.read(readFileSync4(abs));
|
|
1894
|
+
return json(res, 200, { width: png.width, height: png.height, boxes: changeRegions(png) });
|
|
1895
|
+
}
|
|
1896
|
+
if (req.method === "GET" && url.pathname === "/api/options") {
|
|
1897
|
+
return json(res, 200, opts.options ? await opts.options() : {});
|
|
1898
|
+
}
|
|
1899
|
+
if (req.method === "GET" && url.pathname === "/api/models") {
|
|
1900
|
+
const agent = url.searchParams.get("agent") ?? "";
|
|
1901
|
+
if (!opts.listModels || !/^[a-z][a-z-]{1,30}$/.test(agent)) return json(res, 400, { error: "Unknown agent" });
|
|
1902
|
+
return json(res, 200, await opts.listModels(agent));
|
|
1903
|
+
}
|
|
1904
|
+
if (req.method === "GET" && url.pathname === "/api/skill") {
|
|
1905
|
+
const name = url.searchParams.get("name") ?? "";
|
|
1906
|
+
if (!/^[a-z0-9][a-z0-9-]{0,80}$/.test(name) || !opts.skillInfo) return json(res, 400, { error: "Unknown skill" });
|
|
1907
|
+
return json(res, 200, await opts.skillInfo(name).catch(() => ({ name, related: [] })));
|
|
1908
|
+
}
|
|
1909
|
+
if (req.method === "GET" && url.pathname === "/api/account") {
|
|
1910
|
+
const agent = url.searchParams.get("agent") ?? "";
|
|
1911
|
+
if (!/^[a-z][a-z-]{1,30}$/.test(agent)) return json(res, 400, { error: "Unknown agent" });
|
|
1912
|
+
return json(res, 200, { account: opts.account ? await opts.account(agent).catch(() => null) : null });
|
|
1913
|
+
}
|
|
1914
|
+
if (req.method === "GET" && url.pathname === "/api/skills") {
|
|
1915
|
+
if (!opts.listSkills) return json(res, 200, { skills: [] });
|
|
1916
|
+
const skills = await opts.listSkills().catch((err) => {
|
|
1917
|
+
throw new Error(`Could not list skills: ${err.message}`);
|
|
1918
|
+
});
|
|
1919
|
+
return json(res, 200, { skills });
|
|
1920
|
+
}
|
|
1921
|
+
const stopMatch = url.pathname.match(/^\/api\/runs\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\/stop$/);
|
|
1922
|
+
if (req.method === "POST" && stopMatch) {
|
|
1923
|
+
if (!String(req.headers["content-type"] ?? "").startsWith("application/json")) return json(res, 415, { error: "JSON only" });
|
|
1924
|
+
const origin = req.headers.origin;
|
|
1925
|
+
if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
|
|
1926
|
+
if (!opts.stop?.(stopMatch[1])) return json(res, 409, { error: "That run is not running in this studio." });
|
|
1927
|
+
return json(res, 202, { stopping: true });
|
|
1928
|
+
}
|
|
1929
|
+
const prMatch = url.pathname.match(/^\/api\/runs\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\/pr$/);
|
|
1930
|
+
if (req.method === "POST" && prMatch) {
|
|
1931
|
+
if (!opts.openPr) return json(res, 404, { error: "This view is read-only. Start the studio with `mushi-ux ui`." });
|
|
1932
|
+
if (!String(req.headers["content-type"] ?? "").startsWith("application/json")) return json(res, 415, { error: "JSON only" });
|
|
1933
|
+
const origin = req.headers.origin;
|
|
1934
|
+
if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
|
|
1935
|
+
const pr = await opts.openPr(prMatch[1]).catch((err) => err);
|
|
1936
|
+
if (pr instanceof Error) return json(res, 409, { error: pr.message });
|
|
1937
|
+
return json(res, 201, pr);
|
|
1938
|
+
}
|
|
1939
|
+
const resumeMatch = url.pathname.match(/^\/api\/runs\/([0-9]{8}-[0-9]{6}-[a-z0-9]{4})\/resume$/);
|
|
1940
|
+
if (req.method === "POST" && resumeMatch) {
|
|
1941
|
+
if (!opts.resume) return json(res, 404, { error: "This view is read-only. Start the studio with `mushi-ux ui`." });
|
|
1942
|
+
if (!String(req.headers["content-type"] ?? "").startsWith("application/json")) return json(res, 415, { error: "JSON only" });
|
|
1943
|
+
const origin = req.headers.origin;
|
|
1944
|
+
if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
|
|
1945
|
+
if (active && active.runId !== resumeMatch[1]) {
|
|
1946
|
+
const state = loadState(join4(uxDir, active.runId));
|
|
1947
|
+
if (state && !["done", "failed"].includes(state.phase ?? "")) return json(res, 409, { error: `Run ${active.runId} is still going. Stop it first.` });
|
|
1948
|
+
}
|
|
1949
|
+
const started = await opts.resume(resumeMatch[1]).catch((err) => err);
|
|
1950
|
+
if (started instanceof Error) return json(res, 409, { error: started.message });
|
|
1951
|
+
active = started;
|
|
1952
|
+
unsubscribers.push(subscribe(started.runId, started.events));
|
|
1953
|
+
send({ type: "started", runId: started.runId });
|
|
1954
|
+
return json(res, 202, { runId: started.runId });
|
|
1955
|
+
}
|
|
1956
|
+
if (req.method === "POST" && url.pathname === "/api/runs") {
|
|
1957
|
+
if (!opts.launch) return json(res, 404, { error: "This view is read-only. Start the studio with `mushi-ux ui`." });
|
|
1958
|
+
if (!String(req.headers["content-type"] ?? "").startsWith("application/json")) return json(res, 415, { error: "JSON only" });
|
|
1959
|
+
const origin = req.headers.origin;
|
|
1960
|
+
if (origin && origin !== `http://127.0.0.1:${server.address().port}`) return json(res, 403, { error: "Wrong origin" });
|
|
1961
|
+
if (active) {
|
|
1962
|
+
const state = loadState(join4(uxDir, active.runId));
|
|
1963
|
+
if (state && !["done", "failed"].includes(state.phase ?? "")) return json(res, 409, { error: `Run ${active.runId} is still going.` });
|
|
1964
|
+
}
|
|
1965
|
+
const parsed = LaunchInput.safeParse(await readBody(req));
|
|
1966
|
+
if (!parsed.success) return json(res, 400, { error: parsed.error.issues[0]?.message ?? "Invalid settings" });
|
|
1967
|
+
const started = await opts.launch(parsed.data);
|
|
1968
|
+
active = started;
|
|
1969
|
+
unsubscribers.push(subscribe(started.runId, started.events));
|
|
1970
|
+
send({ type: "started", runId: started.runId });
|
|
1971
|
+
return json(res, 201, { runId: started.runId });
|
|
1972
|
+
}
|
|
1973
|
+
res.writeHead(404);
|
|
1974
|
+
res.end();
|
|
1975
|
+
};
|
|
1976
|
+
handle().catch((err) => {
|
|
1977
|
+
if (!res.headersSent) json(res, 500, { error: err.message.slice(0, 500) });
|
|
1978
|
+
else res.end();
|
|
1979
|
+
});
|
|
1980
|
+
});
|
|
1981
|
+
await new Promise((r) => server.listen(opts.port ?? 0, "127.0.0.1", r));
|
|
1982
|
+
const { port: bound } = server.address();
|
|
1983
|
+
const initial = opts.runId ? `&run=${opts.runId}` : "";
|
|
1984
|
+
return {
|
|
1985
|
+
url: `http://127.0.0.1:${bound}/?t=${token}${initial}`,
|
|
1986
|
+
close: () => new Promise((r) => {
|
|
1987
|
+
for (const off of unsubscribers) off();
|
|
1988
|
+
for (const res of clients) res.end();
|
|
1989
|
+
server.close(() => r());
|
|
1990
|
+
})
|
|
1991
|
+
};
|
|
1992
|
+
}
|
|
1993
|
+
async function startDashboard(dir, events, port = 0) {
|
|
1994
|
+
const repoRoot = dirname3(dirname3(dirname3(dir)));
|
|
1995
|
+
return startStudio({ repoRoot, events, runId: basename(dir), port });
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
// src/discover.ts
|
|
1999
|
+
import { createHash } from "crypto";
|
|
2000
|
+
|
|
2001
|
+
// src/routes.ts
|
|
2002
|
+
import { closeSync, fstatSync, openSync, readdirSync as readdirSync4, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
|
|
2003
|
+
import { join as join5, relative as relative2 } from "path";
|
|
2004
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".turbo", ".worktrees", ".mushi", ".mushi-ux", "coverage", "__tests__"]);
|
|
2005
|
+
var SOURCE_RE = /\.(tsx|ts|jsx|js|mjs)$/;
|
|
2006
|
+
var MAX_FILES = 4e3;
|
|
2007
|
+
function isStatic(path) {
|
|
2008
|
+
return path.startsWith("/") && !/[:*[\]]/.test(path) && !path.includes("//");
|
|
2009
|
+
}
|
|
2010
|
+
function reactRouterPaths(source) {
|
|
2011
|
+
const out = [];
|
|
2012
|
+
const re = /\bpath\s*[=:]\s*(?:\{\s*)?(["'`])(\/[^"'`]*)\1/g;
|
|
2013
|
+
for (const m of source.matchAll(re)) if (isStatic(m[2])) out.push(m[2]);
|
|
2014
|
+
return out;
|
|
2015
|
+
}
|
|
2016
|
+
function nextRoutePath(relFile) {
|
|
2017
|
+
const parts = relFile.split(/[\\/]/);
|
|
2018
|
+
const appAt = parts.lastIndexOf("app");
|
|
2019
|
+
const pagesAt = parts.lastIndexOf("pages");
|
|
2020
|
+
let segs;
|
|
2021
|
+
if (appAt >= 0 && /^page\.(tsx|jsx|ts|js|mdx)$/.test(parts[parts.length - 1])) {
|
|
2022
|
+
segs = parts.slice(appAt + 1, -1).filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@"));
|
|
2023
|
+
} else if (pagesAt >= 0 && SOURCE_RE.test(parts[parts.length - 1])) {
|
|
2024
|
+
segs = parts.slice(pagesAt + 1);
|
|
2025
|
+
const last = segs.pop()?.replace(SOURCE_RE, "") ?? "";
|
|
2026
|
+
if (last.startsWith("_") || segs[0] === "api") return null;
|
|
2027
|
+
if (last !== "index") segs.push(last);
|
|
2028
|
+
} else {
|
|
2029
|
+
return null;
|
|
2030
|
+
}
|
|
2031
|
+
const path = "/" + segs.join("/");
|
|
2032
|
+
return isStatic(path) ? path : null;
|
|
2033
|
+
}
|
|
2034
|
+
function isWorthVisiting(route) {
|
|
2035
|
+
return route.startsWith("/") && !/[$[{:*]/.test(route) && !/^\/(api|_|404|500)(\/|$)|\/callback(\/|$)|^\/dev(\/|$)/.test(route);
|
|
2036
|
+
}
|
|
2037
|
+
function routesFromSource(root) {
|
|
2038
|
+
const found = /* @__PURE__ */ new Set();
|
|
2039
|
+
let files = 0;
|
|
2040
|
+
const walk = (dir, depth) => {
|
|
2041
|
+
if (depth > 8 || files > MAX_FILES) return;
|
|
2042
|
+
let names;
|
|
2043
|
+
try {
|
|
2044
|
+
names = readdirSync4(dir);
|
|
2045
|
+
} catch {
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
for (const name of names) {
|
|
2049
|
+
if (SKIP_DIRS.has(name)) continue;
|
|
2050
|
+
const abs = join5(dir, name);
|
|
2051
|
+
let fd;
|
|
2052
|
+
let isDir;
|
|
2053
|
+
let text = "";
|
|
2054
|
+
try {
|
|
2055
|
+
fd = openSync(abs, "r");
|
|
2056
|
+
} catch {
|
|
2057
|
+
continue;
|
|
2058
|
+
}
|
|
2059
|
+
try {
|
|
2060
|
+
const st = fstatSync(fd);
|
|
2061
|
+
isDir = st.isDirectory();
|
|
2062
|
+
if (!isDir && st.size < 4e5 && /\.(tsx|jsx|ts|js)$/.test(name) && !/\.(test|spec|stories)\./.test(name)) {
|
|
2063
|
+
text = readFileSync5(fd, "utf8");
|
|
2064
|
+
}
|
|
2065
|
+
} catch {
|
|
2066
|
+
continue;
|
|
2067
|
+
} finally {
|
|
2068
|
+
closeSync(fd);
|
|
2069
|
+
}
|
|
2070
|
+
if (isDir) {
|
|
2071
|
+
walk(abs, depth + 1);
|
|
2072
|
+
continue;
|
|
2073
|
+
}
|
|
2074
|
+
if (!SOURCE_RE.test(name) && !name.endsWith(".mdx")) continue;
|
|
2075
|
+
if (/\.(test|spec|stories)\./.test(name)) continue;
|
|
2076
|
+
files++;
|
|
2077
|
+
const rel = relative2(root, abs);
|
|
2078
|
+
const next = nextRoutePath(rel);
|
|
2079
|
+
if (next) found.add(next);
|
|
2080
|
+
if (text.includes("Route") || text.includes("createBrowserRouter") || text.includes("createRoutesFromElements")) {
|
|
2081
|
+
for (const p of reactRouterPaths(text)) found.add(p);
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
};
|
|
2085
|
+
walk(root, 0);
|
|
2086
|
+
return [...found].sort();
|
|
2087
|
+
}
|
|
2088
|
+
async function sitemapPaths(baseUrl) {
|
|
2089
|
+
try {
|
|
2090
|
+
const res = await fetch(new URL("/sitemap.xml", baseUrl), { signal: AbortSignal.timeout(1e4) });
|
|
2091
|
+
if (!res.ok || !(res.headers.get("content-type") ?? "").includes("xml")) return [];
|
|
2092
|
+
const xml = await res.text();
|
|
2093
|
+
const origin = new URL(baseUrl).origin;
|
|
2094
|
+
const out = /* @__PURE__ */ new Set();
|
|
2095
|
+
for (const m of xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)) {
|
|
2096
|
+
try {
|
|
2097
|
+
const u = new URL(m[1]);
|
|
2098
|
+
const path = u.pathname + u.search;
|
|
2099
|
+
if (u.origin === origin || isStatic(u.pathname)) out.add(path);
|
|
2100
|
+
} catch {
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
return [...out];
|
|
2104
|
+
} catch {
|
|
2105
|
+
return [];
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
var COMPONENT_DIRS = ["_components", "components"];
|
|
2109
|
+
var MAX_SCREEN_FILES = 12;
|
|
2110
|
+
function screenFiles(root, urlPath) {
|
|
2111
|
+
const want = urlPath.split(/[?#]/)[0].replace(/\/+$/, "") || "/";
|
|
2112
|
+
let page = null;
|
|
2113
|
+
let files = 0;
|
|
2114
|
+
const walk = (dir2, depth) => {
|
|
2115
|
+
if (page || depth > 8 || files > MAX_FILES) return;
|
|
2116
|
+
let names;
|
|
2117
|
+
try {
|
|
2118
|
+
names = readdirSync4(dir2);
|
|
2119
|
+
} catch {
|
|
2120
|
+
return;
|
|
2121
|
+
}
|
|
2122
|
+
for (const name of names) {
|
|
2123
|
+
if (page) return;
|
|
2124
|
+
if (SKIP_DIRS.has(name)) continue;
|
|
2125
|
+
const abs = join5(dir2, name);
|
|
2126
|
+
let st;
|
|
2127
|
+
try {
|
|
2128
|
+
st = statSync2(abs);
|
|
2129
|
+
} catch {
|
|
2130
|
+
continue;
|
|
2131
|
+
}
|
|
2132
|
+
if (st.isDirectory()) {
|
|
2133
|
+
walk(abs, depth + 1);
|
|
2134
|
+
continue;
|
|
2135
|
+
}
|
|
2136
|
+
files++;
|
|
2137
|
+
const rel = relative2(root, abs).replace(/\\/g, "/");
|
|
2138
|
+
if (nextRoutePath(rel) === want) page = rel;
|
|
2139
|
+
}
|
|
2140
|
+
};
|
|
2141
|
+
walk(root, 0);
|
|
2142
|
+
const found = page;
|
|
2143
|
+
if (!found) return [];
|
|
2144
|
+
const dir = found.includes("/") ? found.slice(0, found.lastIndexOf("/")) : "";
|
|
2145
|
+
const out = [found];
|
|
2146
|
+
const list = (d) => {
|
|
2147
|
+
try {
|
|
2148
|
+
return readdirSync4(join5(root, d));
|
|
2149
|
+
} catch {
|
|
2150
|
+
return [];
|
|
2151
|
+
}
|
|
2152
|
+
};
|
|
2153
|
+
for (const name of list(dir)) if (/^layout\.(tsx|jsx|ts|js)$/.test(name)) out.push(dir ? `${dir}/${name}` : name);
|
|
2154
|
+
for (const sub of COMPONENT_DIRS) {
|
|
2155
|
+
const d = dir ? `${dir}/${sub}` : sub;
|
|
2156
|
+
for (const name of list(d)) if (SOURCE_RE.test(name) && !/\.(test|spec|stories)\./.test(name)) out.push(`${d}/${name}`);
|
|
2157
|
+
}
|
|
2158
|
+
return out.slice(0, MAX_SCREEN_FILES);
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
// src/discover.ts
|
|
2162
|
+
var AUTH_WALL_REDIRECTS = 5;
|
|
2163
|
+
var MAX_REDIRECT_FOLLOWS = 3;
|
|
2164
|
+
var LOADS_PER_PAGE = 5;
|
|
2165
|
+
var SIGN_IN_PATH_RE = /\/(log-?in|sign-?in|auth)\b/i;
|
|
2166
|
+
var SIGN_OUT_PATH_RE = /\/(log-?out|sign-?out|logoff)\b/i;
|
|
2167
|
+
function normalizeLink(href, baseUrl) {
|
|
2168
|
+
let u;
|
|
2169
|
+
try {
|
|
2170
|
+
u = new URL(href, baseUrl);
|
|
2171
|
+
} catch {
|
|
2172
|
+
return null;
|
|
2173
|
+
}
|
|
2174
|
+
const base = new URL(baseUrl);
|
|
2175
|
+
if (u.origin !== base.origin) return null;
|
|
2176
|
+
if (!/^https?:$/.test(u.protocol)) return null;
|
|
2177
|
+
if (SIGN_OUT_PATH_RE.test(u.pathname)) return null;
|
|
2178
|
+
if (/\.(png|jpe?g|gif|svg|webp|ico|pdf|zip|csv|json|xml|txt|js|css|map)$/i.test(u.pathname)) return null;
|
|
2179
|
+
return u.pathname + u.search;
|
|
2180
|
+
}
|
|
2181
|
+
function surfaceKey(path, steps) {
|
|
2182
|
+
const raw = [path, ...steps.map((s) => s.label)].join(" > ");
|
|
2183
|
+
const slug = raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 80) || "root";
|
|
2184
|
+
return `${slug}-${createHash("sha1").update(raw).digest("hex").slice(0, 6)}`;
|
|
2185
|
+
}
|
|
2186
|
+
function globMatch(glob, path) {
|
|
2187
|
+
const re = new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
|
|
2188
|
+
return re.test(path);
|
|
2189
|
+
}
|
|
2190
|
+
async function domHash(page) {
|
|
2191
|
+
const shape = await page.evaluate(() => {
|
|
2192
|
+
function sig(el, depth) {
|
|
2193
|
+
const role = el.getAttribute("role");
|
|
2194
|
+
const head = el.tagName.toLowerCase() + (role ? `[${role}]` : "");
|
|
2195
|
+
if (depth >= 8 || el.tagName === "svg") return head;
|
|
2196
|
+
const kids = [];
|
|
2197
|
+
for (const child of Array.from(el.children)) {
|
|
2198
|
+
if (["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"].includes(child.tagName)) continue;
|
|
2199
|
+
if (child.hidden || getComputedStyle(child).display === "none") continue;
|
|
2200
|
+
const s = sig(child, depth + 1);
|
|
2201
|
+
if (kids[kids.length - 1] !== s) kids.push(s);
|
|
2202
|
+
}
|
|
2203
|
+
return kids.length ? `${head}(${kids.join(",")})` : head;
|
|
2204
|
+
}
|
|
2205
|
+
return sig(document.body, 0);
|
|
2206
|
+
});
|
|
2207
|
+
return createHash("sha1").update(shape).digest("hex").slice(0, 16);
|
|
2208
|
+
}
|
|
2209
|
+
function quoteAttr(value) {
|
|
2210
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
2211
|
+
}
|
|
2212
|
+
function triggerSelector(testId, role, label) {
|
|
2213
|
+
if (testId) return `[data-testid=${quoteAttr(testId)}]`;
|
|
2214
|
+
return role ? `role=${role}[name=${quoteAttr(label)}]` : "";
|
|
2215
|
+
}
|
|
2216
|
+
async function findTriggers(page) {
|
|
2217
|
+
const raw = await page.evaluate(() => {
|
|
2218
|
+
const found = [];
|
|
2219
|
+
const candidates = document.querySelectorAll(
|
|
2220
|
+
'[role="tab"]:not([aria-selected="true"]), [aria-haspopup="dialog"], [aria-haspopup="menu"], [aria-haspopup="true"], button[aria-expanded="false"]'
|
|
2221
|
+
);
|
|
2222
|
+
for (const el of Array.from(candidates)) {
|
|
2223
|
+
const r = el.getBoundingClientRect();
|
|
2224
|
+
if (r.width === 0 || r.height === 0) continue;
|
|
2225
|
+
const label = (el.getAttribute("aria-label") || el.innerText || "").trim().replace(/\s+/g, " ").slice(0, 60);
|
|
2226
|
+
if (!label) continue;
|
|
2227
|
+
const role = el.getAttribute("role") || (el.tagName === "BUTTON" ? "button" : el.tagName === "A" ? "link" : "");
|
|
2228
|
+
found.push({ testId: el.getAttribute("data-testid"), label, role });
|
|
2229
|
+
}
|
|
2230
|
+
return found;
|
|
2231
|
+
});
|
|
2232
|
+
const triggers = [];
|
|
2233
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2234
|
+
for (const { testId, label, role } of raw) {
|
|
2235
|
+
const selector = triggerSelector(testId, role, label);
|
|
2236
|
+
if (!selector || seen.has(selector)) continue;
|
|
2237
|
+
seen.add(selector);
|
|
2238
|
+
triggers.push({ selector, label, role });
|
|
2239
|
+
}
|
|
2240
|
+
return triggers;
|
|
2241
|
+
}
|
|
2242
|
+
async function openedKind(page, trigger) {
|
|
2243
|
+
return page.evaluate((role) => {
|
|
2244
|
+
const visible = (sel) => Array.from(document.querySelectorAll(sel)).some((el) => {
|
|
2245
|
+
const r = el.getBoundingClientRect();
|
|
2246
|
+
return r.width > 0 && r.height > 0;
|
|
2247
|
+
});
|
|
2248
|
+
if (visible('[role="dialog"], [role="alertdialog"], dialog[open]')) return "dialog";
|
|
2249
|
+
if (visible('[role="menu"], [role="listbox"]')) return "menu";
|
|
2250
|
+
if (role === "tab") return "tab";
|
|
2251
|
+
return null;
|
|
2252
|
+
}, trigger.role);
|
|
2253
|
+
}
|
|
2254
|
+
function pageLabel(title, path, others) {
|
|
2255
|
+
const t = title.trim();
|
|
2256
|
+
if (t && !others.some((o) => o.label === t)) return t;
|
|
2257
|
+
const parts = new URL(path, "http://x").pathname.split("/").filter(Boolean);
|
|
2258
|
+
const fromPath = parts.length ? parts.map((p) => decodeURIComponent(p).replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase())).join(" / ") : "Home";
|
|
2259
|
+
return others.some((o) => o.label === fromPath) ? `${fromPath} (${path})` : fromPath;
|
|
2260
|
+
}
|
|
2261
|
+
async function discover(session, opts) {
|
|
2262
|
+
const maxPages = opts.maxPages ?? 40;
|
|
2263
|
+
const maxStates = opts.maxStatesPerPage ?? 8;
|
|
2264
|
+
const exclude = opts.excludePaths ?? [];
|
|
2265
|
+
const progress = opts.onProgress ?? (() => {
|
|
2266
|
+
});
|
|
2267
|
+
const only = Boolean(opts.onlyStartPaths && opts.startPaths?.length);
|
|
2268
|
+
const seeded = [
|
|
2269
|
+
...opts.startPaths?.length ? opts.startPaths : ["/"],
|
|
2270
|
+
...only ? [] : (opts.sourceDir ? routesFromSource(opts.sourceDir) : []).filter(isWorthVisiting),
|
|
2271
|
+
...only ? [] : (await sitemapPaths(opts.baseUrl)).filter(isWorthVisiting)
|
|
2272
|
+
];
|
|
2273
|
+
const queue = [...new Set(seeded)];
|
|
2274
|
+
progress(only ? `${queue.length} page(s) you named` : `${queue.length} start path(s) from the source, sitemap and options`);
|
|
2275
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2276
|
+
const seenShapes = /* @__PURE__ */ new Set();
|
|
2277
|
+
const redirectsTo = /* @__PURE__ */ new Map();
|
|
2278
|
+
const surfaces = [];
|
|
2279
|
+
let loads = 0;
|
|
2280
|
+
const page = await session.context.newPage();
|
|
2281
|
+
await page.setViewportSize({ width: 1440, height: 900 });
|
|
2282
|
+
try {
|
|
2283
|
+
for (let pass = 1; pass <= 2; pass++) {
|
|
2284
|
+
if (pass === 2) {
|
|
2285
|
+
if (!only) break;
|
|
2286
|
+
const strip = (p) => p.replace(/\/(?=\?|$)/, "");
|
|
2287
|
+
const missing = [...new Set(seeded)].filter((p) => !surfaces.some((s) => s.kind === "page" && strip(s.path) === strip(p)));
|
|
2288
|
+
if (missing.length === 0) break;
|
|
2289
|
+
progress(`retrying ${missing.join(", ")}: not captured on the first pass`);
|
|
2290
|
+
for (const p of missing) {
|
|
2291
|
+
visited.delete(p);
|
|
2292
|
+
visited.delete(strip(p) + "/");
|
|
2293
|
+
visited.delete(strip(p));
|
|
2294
|
+
}
|
|
2295
|
+
queue.push(...missing);
|
|
2296
|
+
}
|
|
2297
|
+
while (queue.length > 0 && surfaces.filter((s) => s.kind === "page").length < maxPages) {
|
|
2298
|
+
if (opts.signal?.aborted) throw new Error("Stopped.");
|
|
2299
|
+
const path = queue.shift();
|
|
2300
|
+
if (++loads > maxPages * LOADS_PER_PAGE) {
|
|
2301
|
+
progress(`stopped mapping after ${loads - 1} page loads; ${queue.length + 1} path(s) not tried`);
|
|
2302
|
+
break;
|
|
2303
|
+
}
|
|
2304
|
+
if (visited.has(path)) {
|
|
2305
|
+
if (only) progress(`skipped ${path}: already visited`);
|
|
2306
|
+
continue;
|
|
2307
|
+
}
|
|
2308
|
+
visited.add(path);
|
|
2309
|
+
if (exclude.some((g) => globMatch(g, new URL(path, opts.baseUrl).pathname))) continue;
|
|
2310
|
+
const failed2 = (err) => {
|
|
2311
|
+
progress(`skipped ${path}: it did not load (${err.message.split("\n")[0].slice(0, 120)})`);
|
|
2312
|
+
return void 0;
|
|
2313
|
+
};
|
|
2314
|
+
const res = await gotoPatiently(page, surfaceUrl(opts.baseUrl, path)).catch(failed2);
|
|
2315
|
+
if (res === void 0) continue;
|
|
2316
|
+
if (res && res.status() >= 400) {
|
|
2317
|
+
progress(`skipped ${path}: HTTP ${res.status()}`);
|
|
2318
|
+
continue;
|
|
2319
|
+
}
|
|
2320
|
+
await settle(page);
|
|
2321
|
+
const landed = new URL(page.url());
|
|
2322
|
+
if (landed.origin !== new URL(opts.baseUrl).origin) {
|
|
2323
|
+
progress(`skipped ${path}: it leaves the app for ${landed.origin}`);
|
|
2324
|
+
continue;
|
|
2325
|
+
}
|
|
2326
|
+
const landedPath = landed.pathname + landed.search;
|
|
2327
|
+
const sameModuloSlash = (a, b) => a.replace(/\/(?=\?|$)/, "") === b.replace(/\/(?=\?|$)/, "");
|
|
2328
|
+
if (landedPath !== path && sameModuloSlash(landedPath, path)) {
|
|
2329
|
+
visited.add(landedPath);
|
|
2330
|
+
if (visited.has(landedPath) && surfaces.some((s) => s.kind === "page" && s.path === landedPath)) continue;
|
|
2331
|
+
} else if (landedPath !== path && only) {
|
|
2332
|
+
progress(`skipped ${path}: it opens ${landedPath} instead`);
|
|
2333
|
+
}
|
|
2334
|
+
if (landedPath !== path && !sameModuloSlash(landedPath, path)) {
|
|
2335
|
+
const n = (redirectsTo.get(landed.pathname) ?? 0) + 1;
|
|
2336
|
+
redirectsTo.set(landed.pathname, n);
|
|
2337
|
+
if (!visited.has(landedPath) && n <= MAX_REDIRECT_FOLLOWS) queue.unshift(landedPath);
|
|
2338
|
+
if (n === AUTH_WALL_REDIRECTS && SIGN_IN_PATH_RE.test(landed.pathname)) {
|
|
2339
|
+
const skipped = queue.filter((p) => p !== landedPath).length;
|
|
2340
|
+
queue.splice(0, queue.length, ...queue.filter((p) => p === landedPath));
|
|
2341
|
+
progress(
|
|
2342
|
+
`${n} paths redirect to ${landed.pathname}: the app needs a signed-in session. Skipping the other ${skipped} queued path(s). Run \`mushi-ux login --url ${opts.baseUrl}\` and pass --login-url.`
|
|
2343
|
+
);
|
|
2344
|
+
}
|
|
2345
|
+
continue;
|
|
2346
|
+
}
|
|
2347
|
+
const here = landedPath;
|
|
2348
|
+
let shape;
|
|
2349
|
+
let title;
|
|
2350
|
+
let links;
|
|
2351
|
+
try {
|
|
2352
|
+
shape = await domHash(page);
|
|
2353
|
+
if (seenShapes.has(shape) && !only) continue;
|
|
2354
|
+
title = pageLabel(await page.title(), here, surfaces);
|
|
2355
|
+
links = await page.$$eval(
|
|
2356
|
+
"a[href]",
|
|
2357
|
+
(as) => as.map((a) => ({ href: a.getAttribute("href") ?? "", label: a.innerText.trim() }))
|
|
2358
|
+
);
|
|
2359
|
+
} catch (err) {
|
|
2360
|
+
if (opts.signal?.aborted) throw err;
|
|
2361
|
+
progress(`skipped ${path}: it changed while being read (${err.message.split("\n")[0].slice(0, 120)})`);
|
|
2362
|
+
continue;
|
|
2363
|
+
}
|
|
2364
|
+
seenShapes.add(shape);
|
|
2365
|
+
surfaces.push({ key: surfaceKey(here, []), kind: "page", path: here, steps: [], label: title, domHash: shape });
|
|
2366
|
+
progress(`page ${here}`);
|
|
2367
|
+
for (const { href, label } of links) {
|
|
2368
|
+
if (isDestructiveLabel(label)) continue;
|
|
2369
|
+
const next = normalizeLink(href, page.url());
|
|
2370
|
+
if (!only && next && !visited.has(next) && !queue.includes(next)) queue.push(next);
|
|
2371
|
+
}
|
|
2372
|
+
const triggers = (await findTriggers(page).catch(() => [])).filter((t) => !isDestructiveLabel(t.label)).slice(0, maxStates);
|
|
2373
|
+
for (const trigger of triggers) {
|
|
2374
|
+
const step = { action: "click", selector: trigger.selector, label: trigger.label };
|
|
2375
|
+
try {
|
|
2376
|
+
await gotoPatiently(page, surfaceUrl(opts.baseUrl, here));
|
|
2377
|
+
await settle(page);
|
|
2378
|
+
await replay(page, [step]);
|
|
2379
|
+
} catch {
|
|
2380
|
+
continue;
|
|
2381
|
+
}
|
|
2382
|
+
const after = new URL(page.url());
|
|
2383
|
+
if (after.pathname + after.search !== here) {
|
|
2384
|
+
const next = normalizeLink(page.url(), opts.baseUrl);
|
|
2385
|
+
if (!only && next && !visited.has(next) && !queue.includes(next)) queue.push(next);
|
|
2386
|
+
continue;
|
|
2387
|
+
}
|
|
2388
|
+
let kind;
|
|
2389
|
+
let stateShape;
|
|
2390
|
+
try {
|
|
2391
|
+
kind = await openedKind(page, trigger);
|
|
2392
|
+
if (!kind) continue;
|
|
2393
|
+
stateShape = await domHash(page);
|
|
2394
|
+
} catch (err) {
|
|
2395
|
+
if (opts.signal?.aborted) throw err;
|
|
2396
|
+
continue;
|
|
2397
|
+
}
|
|
2398
|
+
if (seenShapes.has(stateShape)) continue;
|
|
2399
|
+
seenShapes.add(stateShape);
|
|
2400
|
+
surfaces.push({
|
|
2401
|
+
key: surfaceKey(here, [step]),
|
|
2402
|
+
kind,
|
|
2403
|
+
path: here,
|
|
2404
|
+
steps: [step],
|
|
2405
|
+
label: `${title} \u203A ${trigger.label}`,
|
|
2406
|
+
domHash: stateShape
|
|
2407
|
+
});
|
|
2408
|
+
progress(`${kind} ${here} \u203A ${trigger.label}`);
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
} finally {
|
|
2413
|
+
await page.close();
|
|
2414
|
+
}
|
|
2415
|
+
return tidyLabels(surfaces);
|
|
2416
|
+
}
|
|
2417
|
+
var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2418
|
+
function tidyLabels(surfaces) {
|
|
2419
|
+
const SEP = /\s+[|–—·:-]\s+/;
|
|
2420
|
+
const pages = surfaces.filter((s) => s.kind === "page");
|
|
2421
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2422
|
+
for (const s of pages) {
|
|
2423
|
+
const parts = s.label.split(SEP).map((p) => p.trim());
|
|
2424
|
+
if (parts.length < 2) continue;
|
|
2425
|
+
for (const p of /* @__PURE__ */ new Set([parts[0], parts[parts.length - 1]])) counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
2426
|
+
}
|
|
2427
|
+
const site = [...counts].filter(([, n]) => n >= 2 && n * 2 >= pages.length).sort((a, b) => b[1] - a[1])[0]?.[0];
|
|
2428
|
+
if (!site) return surfaces;
|
|
2429
|
+
const sep2 = String.raw`\s+[|–—·:-]\s+`;
|
|
2430
|
+
const trailing = new RegExp(`${sep2}${escapeRe(site)}(?=$|\\s\u203A)`);
|
|
2431
|
+
const leading = new RegExp(`^${escapeRe(site)}${sep2}`);
|
|
2432
|
+
const renamed = /* @__PURE__ */ new Map();
|
|
2433
|
+
for (const s of pages) {
|
|
2434
|
+
let next = s.label.replace(trailing, "");
|
|
2435
|
+
if (leading.test(next)) next = s.path === "/" ? "Home" : next.replace(leading, "");
|
|
2436
|
+
if (next && next !== s.label) renamed.set(s.label, next);
|
|
2437
|
+
}
|
|
2438
|
+
const taken = new Set(pages.map((s) => s.label));
|
|
2439
|
+
const finalName = /* @__PURE__ */ new Map();
|
|
2440
|
+
for (const [from, to] of renamed) {
|
|
2441
|
+
if (taken.has(to) || [...finalName.values()].includes(to)) continue;
|
|
2442
|
+
finalName.set(from, to);
|
|
2443
|
+
}
|
|
2444
|
+
return surfaces.map((s) => {
|
|
2445
|
+
const page = s.label.split(" \u203A ")[0];
|
|
2446
|
+
const to = finalName.get(page);
|
|
2447
|
+
return to ? { ...s, label: to + s.label.slice(page.length) } : s;
|
|
2448
|
+
});
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
// src/judge.ts
|
|
2452
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
2453
|
+
import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
|
|
2454
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
2455
|
+
import { join as join6 } from "path";
|
|
2456
|
+
import { z as z2 } from "zod";
|
|
2457
|
+
var DEFAULT_JUDGE_MODEL = "claude-opus-5-5";
|
|
2458
|
+
var MAX_DESIGN_CHARS = 16e3;
|
|
2459
|
+
var Box = z2.object({
|
|
2460
|
+
x: z2.number(),
|
|
2461
|
+
y: z2.number(),
|
|
2462
|
+
width: z2.number(),
|
|
2463
|
+
height: z2.number()
|
|
2464
|
+
});
|
|
2465
|
+
var Claim = z2.object({
|
|
2466
|
+
image: z2.enum(["A", "B"]),
|
|
2467
|
+
box: Box,
|
|
2468
|
+
what: z2.string(),
|
|
2469
|
+
why: z2.string()
|
|
2470
|
+
});
|
|
2471
|
+
var JudgeOutput = z2.object({
|
|
2472
|
+
preferred: z2.enum(["A", "B", "tie"]),
|
|
2473
|
+
confidence: z2.enum(["low", "medium", "high"]),
|
|
2474
|
+
summary: z2.string(),
|
|
2475
|
+
better: z2.array(Claim),
|
|
2476
|
+
worse: z2.array(Claim),
|
|
2477
|
+
design_system_breaks: z2.array(
|
|
2478
|
+
Claim.extend({
|
|
2479
|
+
token_or_rule: z2.string()
|
|
2480
|
+
})
|
|
2481
|
+
)
|
|
2482
|
+
});
|
|
2483
|
+
var RUBRIC = `You review UI changes for a solo developer. You will see two screenshots of the same screen, labelled A and B, in random order. One is the original and one was edited by a coding agent. You are not told which is which.
|
|
2484
|
+
|
|
2485
|
+
Decide which one is better for the person using this screen, judged on:
|
|
2486
|
+
1. Clarity: is the screen's purpose and primary action obvious within a few seconds?
|
|
2487
|
+
2. Hierarchy: does visual weight (size, colour, position) match importance?
|
|
2488
|
+
3. Density: is there less noise (duplicated info, wordy copy, competing calls to action) without losing needed information?
|
|
2489
|
+
4. Consistency with the design system given below (tokens, spacing scale, type scale, components). Ignore taste that the design system does not support.
|
|
2490
|
+
5. Accessibility you can see: contrast, text size, target size, focus or state indicators.
|
|
2491
|
+
|
|
2492
|
+
Measured numbers for both images are provided (accessibility violations, sideways scroll, small tap targets, console errors). Treat them as facts; do not contradict them.
|
|
2493
|
+
|
|
2494
|
+
Rules for claims:
|
|
2495
|
+
- Every claim points at a region with a box in that image's pixel coordinates (origin top-left).
|
|
2496
|
+
- Only claim what is visible in the screenshots. Do not guess about interactions, data, or other screens.
|
|
2497
|
+
- Prefer few, specific claims over many generic ones. Generic advice ("make it responsive", "add more whitespace") is not a claim.
|
|
2498
|
+
- If the two are equally good, or the difference is too small to matter, answer "tie".
|
|
2499
|
+
- "design_system_breaks" lists places in either image that visibly break the given tokens or rules; name the token or rule.`;
|
|
2500
|
+
function designContext(repoRoot, files) {
|
|
2501
|
+
let out = "";
|
|
2502
|
+
for (const f of files) {
|
|
2503
|
+
if (out.length >= MAX_DESIGN_CHARS) break;
|
|
2504
|
+
try {
|
|
2505
|
+
const text = readFileSync6(join6(repoRoot, f), "utf8");
|
|
2506
|
+
out += `
|
|
2507
|
+
--- ${f} ---
|
|
2508
|
+
${text.slice(0, MAX_DESIGN_CHARS - out.length)}
|
|
2509
|
+
`;
|
|
2510
|
+
} catch {
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
return out || "(No design-system files found. Judge consistency against the rest of the screen.)";
|
|
2514
|
+
}
|
|
2515
|
+
function probeLine(label, p) {
|
|
2516
|
+
const axe = p.axe.map((v) => `${v.id}\xD7${v.count}`).join(", ") || "none";
|
|
2517
|
+
return `${label}: accessibility violations ${axe}; sideways scroll ${p.overflowX ? "yes" : "no"}; small tap targets ${p.smallTargets}; console errors ${p.consoleErrors.length}; layout shift ${p.cls}`;
|
|
2518
|
+
}
|
|
2519
|
+
function pngSize(buf) {
|
|
2520
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
2521
|
+
}
|
|
2522
|
+
function unshuffle(out, aIsBefore, sizes, viewport, model) {
|
|
2523
|
+
const side = (img) => img === "A" === aIsBefore ? "before" : "after";
|
|
2524
|
+
let dropped = 0;
|
|
2525
|
+
const keep = (c) => {
|
|
2526
|
+
const size = sizes[c.image];
|
|
2527
|
+
const inside = c.box.width > 0 && c.box.height > 0 && c.box.x >= 0 && c.box.y >= 0 && c.box.x + c.box.width <= size.width + 2 && c.box.y + c.box.height <= size.height + 2;
|
|
2528
|
+
if (!inside) {
|
|
2529
|
+
dropped++;
|
|
2530
|
+
return [];
|
|
2531
|
+
}
|
|
2532
|
+
return [{ image: side(c.image), box: c.box, what: c.what, why: c.why, tokenOrRule: c.token_or_rule }];
|
|
2533
|
+
};
|
|
2534
|
+
return {
|
|
2535
|
+
viewport,
|
|
2536
|
+
model,
|
|
2537
|
+
preferred: out.preferred === "tie" ? "tie" : side(out.preferred),
|
|
2538
|
+
confidence: out.confidence,
|
|
2539
|
+
summary: out.summary,
|
|
2540
|
+
better: out.better.flatMap(keep),
|
|
2541
|
+
worse: out.worse.flatMap(keep),
|
|
2542
|
+
designBreaks: out.design_system_breaks.flatMap(keep),
|
|
2543
|
+
droppedClaims: dropped
|
|
2544
|
+
};
|
|
2545
|
+
}
|
|
2546
|
+
async function judgeSurface(s, viewport, opts) {
|
|
2547
|
+
const kept = [...s.iterations].reverse().find((i) => i.outcome === "accepted" && i.after[viewport]);
|
|
2548
|
+
const before = s.baseline[viewport];
|
|
2549
|
+
if (!kept || !before) return null;
|
|
2550
|
+
const after = kept.after[viewport];
|
|
2551
|
+
const model = opts.model ?? DEFAULT_JUDGE_MODEL;
|
|
2552
|
+
const client = opts.client ?? new Anthropic();
|
|
2553
|
+
const beforePng = readFileSync6(join6(opts.dir, before.png));
|
|
2554
|
+
const width = pngSize(beforePng).width;
|
|
2555
|
+
const maxHeight = Math.round(width * (viewport === "mobile" ? 2.5 : 1.25));
|
|
2556
|
+
const bImg = cropTop(beforePng, maxHeight);
|
|
2557
|
+
const aImg = cropTop(readFileSync6(join6(opts.dir, after.png)), maxHeight);
|
|
2558
|
+
const aIsBefore = (opts.random ?? Math.random)() < 0.5;
|
|
2559
|
+
const [imgA, imgB] = aIsBefore ? [bImg, aImg] : [aImg, bImg];
|
|
2560
|
+
const [probeA, probeB] = aIsBefore ? [before.probes, after.probes] : [after.probes, before.probes];
|
|
2561
|
+
const image = (png) => ({
|
|
2562
|
+
type: "image",
|
|
2563
|
+
source: { type: "base64", media_type: "image/png", data: png.toString("base64") }
|
|
2564
|
+
});
|
|
2565
|
+
try {
|
|
2566
|
+
const response = await client.beta.messages.parse({
|
|
2567
|
+
model,
|
|
2568
|
+
max_tokens: 16e3,
|
|
2569
|
+
betas: ["server-side-fallback-2026-07-01"],
|
|
2570
|
+
fallbacks: "default",
|
|
2571
|
+
output_config: { effort: "high", format: betaZodOutputFormat(JudgeOutput) },
|
|
2572
|
+
system: [
|
|
2573
|
+
{ type: "text", text: RUBRIC },
|
|
2574
|
+
{
|
|
2575
|
+
type: "text",
|
|
2576
|
+
text: `Design system of this repository:
|
|
2577
|
+
${designContext(opts.repoRoot, opts.designFiles)}`,
|
|
2578
|
+
// Same rubric + tokens for every screen in the run: cache the prefix.
|
|
2579
|
+
cache_control: { type: "ephemeral" }
|
|
2580
|
+
}
|
|
2581
|
+
],
|
|
2582
|
+
messages: [
|
|
2583
|
+
{
|
|
2584
|
+
role: "user",
|
|
2585
|
+
content: [
|
|
2586
|
+
{ type: "text", text: `Screen: ${s.surface.label} (${s.surface.path}), ${viewport} viewport.` },
|
|
2587
|
+
{ type: "text", text: "Image A:" },
|
|
2588
|
+
image(imgA),
|
|
2589
|
+
{ type: "text", text: "Image B:" },
|
|
2590
|
+
image(imgB),
|
|
2591
|
+
{ type: "text", text: `${probeLine("A", probeA)}
|
|
2592
|
+
${probeLine("B", probeB)}
|
|
2593
|
+
|
|
2594
|
+
Which is better, A or B?` }
|
|
2595
|
+
]
|
|
2596
|
+
}
|
|
2597
|
+
]
|
|
2598
|
+
});
|
|
2599
|
+
if (response.stop_reason === "refusal") {
|
|
2600
|
+
return failed(viewport, model, `The model declined (${response.stop_details?.category ?? "no category"}).`);
|
|
2601
|
+
}
|
|
2602
|
+
const parsed = response.parsed_output;
|
|
2603
|
+
if (!parsed) return failed(viewport, model, `No structured answer (stop reason ${response.stop_reason}).`);
|
|
2604
|
+
return unshuffle(parsed, aIsBefore, { A: pngSize(imgA), B: pngSize(imgB) }, viewport, response.model);
|
|
2605
|
+
} catch (err) {
|
|
2606
|
+
if (err instanceof Anthropic.AuthenticationError) {
|
|
2607
|
+
return failed(viewport, model, "No valid Anthropic credentials. Set ANTHROPIC_API_KEY or run `ant auth login`.");
|
|
2608
|
+
}
|
|
2609
|
+
if (err instanceof Anthropic.RateLimitError) return failed(viewport, model, "Rate limited by the Anthropic API.");
|
|
2610
|
+
if (err instanceof Anthropic.APIError) return failed(viewport, model, `Anthropic API error ${err.status}: ${err.message}`);
|
|
2611
|
+
throw err;
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
function failed(viewport, model, error) {
|
|
2615
|
+
return {
|
|
2616
|
+
viewport,
|
|
2617
|
+
model,
|
|
2618
|
+
preferred: "tie",
|
|
2619
|
+
confidence: "low",
|
|
2620
|
+
summary: "",
|
|
2621
|
+
better: [],
|
|
2622
|
+
worse: [],
|
|
2623
|
+
designBreaks: [],
|
|
2624
|
+
droppedClaims: 0,
|
|
2625
|
+
error
|
|
2626
|
+
};
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
// src/loop.ts
|
|
2630
|
+
import { appendFileSync as appendFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync9, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
|
|
2631
|
+
import { dirname as dirname5, join as join11 } from "path";
|
|
2632
|
+
|
|
2633
|
+
// src/checker.ts
|
|
2634
|
+
import Anthropic2 from "@anthropic-ai/sdk";
|
|
2635
|
+
import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
2636
|
+
import { join as join7 } from "path";
|
|
2637
|
+
import { PNG as PNG3 } from "pngjs";
|
|
2638
|
+
var MAX_CROP_HEIGHT = 1400;
|
|
2639
|
+
var MAX_DIFF_CHARS = 2e4;
|
|
2640
|
+
var CONTEXT_ROWS = 120;
|
|
2641
|
+
function unionBox(regions, width, height) {
|
|
2642
|
+
if (!regions.length) return { x: 0, y: 0, w: width, h: Math.min(height, MAX_CROP_HEIGHT) };
|
|
2643
|
+
const y0 = Math.min(...regions.map((r) => r.y));
|
|
2644
|
+
const y1 = Math.max(...regions.map((r) => r.y + r.h));
|
|
2645
|
+
const y = Math.max(0, y0 - CONTEXT_ROWS);
|
|
2646
|
+
return { x: 0, y, w: width, h: Math.max(1, Math.min(y1 + CONTEXT_ROWS - y, MAX_CROP_HEIGHT, height - y)) };
|
|
2647
|
+
}
|
|
2648
|
+
function crop(png, box) {
|
|
2649
|
+
const src = PNG3.sync.read(png);
|
|
2650
|
+
const w = Math.min(box.w, src.width - box.x);
|
|
2651
|
+
const h = Math.min(box.h, src.height - box.y);
|
|
2652
|
+
const out = new PNG3({ width: Math.max(1, w), height: Math.max(1, h) });
|
|
2653
|
+
out.data.fill(255);
|
|
2654
|
+
if (w > 0 && h > 0) PNG3.bitblt(src, out, box.x, box.y, w, h, 0, 0);
|
|
2655
|
+
return PNG3.sync.write(out);
|
|
2656
|
+
}
|
|
2657
|
+
function firstJson(text) {
|
|
2658
|
+
const start2 = text.indexOf("{");
|
|
2659
|
+
const end = text.lastIndexOf("}");
|
|
2660
|
+
if (start2 < 0 || end <= start2) return null;
|
|
2661
|
+
try {
|
|
2662
|
+
return JSON.parse(text.slice(start2, end + 1));
|
|
2663
|
+
} catch {
|
|
2664
|
+
return null;
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
var level = (v) => v === "high" || v === "medium" ? v : "low";
|
|
2668
|
+
function toVote(answer, aIsBefore) {
|
|
2669
|
+
if (!answer) return null;
|
|
2670
|
+
const v = answer.verdict;
|
|
2671
|
+
if (v !== "A" && v !== "B" && v !== "tie") return null;
|
|
2672
|
+
return {
|
|
2673
|
+
preferred: v === "tie" ? "tie" : v === "A" === aIsBefore ? "before" : "after",
|
|
2674
|
+
confidence: level(answer.confidence),
|
|
2675
|
+
difference: String(answer.difference ?? "").slice(0, 400),
|
|
2676
|
+
reason: String(answer.reason ?? "").slice(0, 600)
|
|
2677
|
+
};
|
|
2678
|
+
}
|
|
2679
|
+
function combineVotes(votes) {
|
|
2680
|
+
const firm = (v) => v.confidence !== "low";
|
|
2681
|
+
if (votes.length >= 2 && votes.every((v) => v.preferred === "before" && firm(v))) {
|
|
2682
|
+
return { verdict: "revert", summary: `Both reviews preferred the original: ${votes[0].reason}` };
|
|
2683
|
+
}
|
|
2684
|
+
if (votes.length >= 2 && votes.every((v) => v.preferred === "after")) {
|
|
2685
|
+
return { verdict: "keep", summary: `Both reviews preferred the change: ${votes[0].reason}` };
|
|
2686
|
+
}
|
|
2687
|
+
return { verdict: "unsure", summary: votes.length ? `The reviews disagreed or were unsure: ${votes.map((v) => v.preferred).join(" / ")}.` : "No review answered." };
|
|
2688
|
+
}
|
|
2689
|
+
var VISUAL_PROMPT = (step, screen) => `You review one small UI change made by a coding agent to the screen "${screen}".
|
|
2690
|
+
The change it was asked to make: ${step}
|
|
2691
|
+
|
|
2692
|
+
Read the two images a.png and b.png in the current folder. They show the same area of the screen; one is before the change and one is after, in an order you are not told.
|
|
2693
|
+
First describe the visible difference in one sentence. Then decide which is better for the person using this screen: clearer purpose and primary action, sensible visual weight, less noise, consistent with the rest of the screen, readable and tappable. If the difference is too small to matter, answer "tie".
|
|
2694
|
+
Answer with ONLY this JSON: {"difference":"...","verdict":"A"|"B"|"tie","confidence":"low"|"medium"|"high","reason":"..."} where A is a.png and B is b.png.`;
|
|
2695
|
+
var CODE_PROMPT = (step, screen, diff) => `You review one small change a coding agent made to the screen "${screen}" of a web app. It changed nothing visible in a still screenshot, so judge it from the code.
|
|
2696
|
+
The change it was asked to make: ${step}
|
|
2697
|
+
|
|
2698
|
+
The diff:
|
|
2699
|
+
${diff}
|
|
2700
|
+
|
|
2701
|
+
You may open at most 3 files from this repository (for example a class or component the diff uses) to check what it does; then answer. Do not search the repository.
|
|
2702
|
+
Keep it when the diff makes that change (or a reasonable part of it) without breaking behaviour, accessibility or the design system. Revert it when it does nothing useful, does something else, or risks breaking the screen.
|
|
2703
|
+
Answer with ONLY this JSON: {"verdict":"keep"|"revert","confidence":"low"|"medium"|"high","reason":"..."}`;
|
|
2704
|
+
async function askClaudeCode(prompt, cwd, model, signal, maxTurns = 4) {
|
|
2705
|
+
const args = ["-p", "--model", model, "--tools", "Read", "--disallowedTools", "mcp__*", "--permission-mode", "dontAsk", "--max-turns", String(maxTurns), "--no-session-persistence", "--output-format", "json"];
|
|
2706
|
+
let last = { text: null, costUsd: null, error: "Claude Code did not run." };
|
|
2707
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
2708
|
+
if (signal?.aborted) break;
|
|
2709
|
+
const res = await run("claude", args, { cwd, stdin: prompt, shell: process.platform === "win32", timeoutMs: 24e4, signal });
|
|
2710
|
+
if (res.timedOut) return { text: null, costUsd: null, error: "Claude Code did not answer within 4 minutes." };
|
|
2711
|
+
try {
|
|
2712
|
+
const j = JSON.parse(res.stdout);
|
|
2713
|
+
if (!j.is_error) return { text: String(j.result ?? ""), costUsd: typeof j.total_cost_usd === "number" ? j.total_cost_usd : null };
|
|
2714
|
+
last = { text: null, costUsd: null, error: `Claude Code: ${String(j.result ?? j.subtype ?? "error with no message").slice(0, 300)}` };
|
|
2715
|
+
if (j.subtype === "error_max_turns") return last;
|
|
2716
|
+
} catch {
|
|
2717
|
+
const said = `${res.stdout.trim().slice(0, 200)} ${res.tail.trim().slice(-300)}`.trim();
|
|
2718
|
+
last = { text: null, costUsd: null, error: `Claude Code exited ${res.exitCode}: ${said || "no output on stdout or stderr"}` };
|
|
2719
|
+
}
|
|
2720
|
+
if (attempt === 1) await new Promise((r) => setTimeout(r, 5e3));
|
|
2721
|
+
}
|
|
2722
|
+
return last;
|
|
2723
|
+
}
|
|
2724
|
+
async function askApi(prompt, images, model, client) {
|
|
2725
|
+
try {
|
|
2726
|
+
const msg = await client.messages.create({
|
|
2727
|
+
model,
|
|
2728
|
+
max_tokens: 2e3,
|
|
2729
|
+
messages: [
|
|
2730
|
+
{
|
|
2731
|
+
role: "user",
|
|
2732
|
+
content: [
|
|
2733
|
+
...images.flatMap((png, i) => [
|
|
2734
|
+
{ type: "text", text: i === 0 ? "a.png:" : "b.png:" },
|
|
2735
|
+
{ type: "image", source: { type: "base64", media_type: "image/png", data: png.toString("base64") } }
|
|
2736
|
+
]),
|
|
2737
|
+
{ type: "text", text: prompt }
|
|
2738
|
+
]
|
|
2739
|
+
}
|
|
2740
|
+
]
|
|
2741
|
+
});
|
|
2742
|
+
return { text: msg.content.map((b) => b.type === "text" ? b.text : "").join(""), costUsd: null };
|
|
2743
|
+
} catch (err) {
|
|
2744
|
+
return { text: null, costUsd: null, error: `Anthropic API: ${err.message.slice(0, 200)}` };
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
async function checkStep(input) {
|
|
2748
|
+
const { spec } = input;
|
|
2749
|
+
const base = join7(input.dir, "checker", input.name);
|
|
2750
|
+
const fail = (mode, error) => ({ model: spec.model, mode, verdict: "unsure", summary: "", votes: [], costUsd: null, error });
|
|
2751
|
+
let cost = 0;
|
|
2752
|
+
const ask = async (prompt, cwd, images, maxTurns) => {
|
|
2753
|
+
const a2 = spec.via === "claude-code" ? await askClaudeCode(prompt, cwd, spec.model, input.signal, maxTurns) : await askApi(prompt, images, spec.model, input.client ?? new Anthropic2());
|
|
2754
|
+
if (a2.costUsd) cost += a2.costUsd;
|
|
2755
|
+
return a2;
|
|
2756
|
+
};
|
|
2757
|
+
if (!input.visual) {
|
|
2758
|
+
const diff = input.diff.slice(0, MAX_DIFF_CHARS);
|
|
2759
|
+
mkdirSync3(base, { recursive: true });
|
|
2760
|
+
const a2 = await ask(CODE_PROMPT(input.step, input.screen, diff), input.repoDir ?? base, [], 20);
|
|
2761
|
+
if (a2.error || !a2.text) return fail("code", a2.error ?? "No answer.");
|
|
2762
|
+
const j = firstJson(a2.text);
|
|
2763
|
+
if (!j || j.verdict !== "keep" && j.verdict !== "revert") return fail("code", "The answer was not the expected JSON.");
|
|
2764
|
+
const confidence = level(j.confidence);
|
|
2765
|
+
const reason = String(j.reason ?? "").slice(0, 600);
|
|
2766
|
+
const verdict2 = j.verdict === "revert" && confidence !== "low" ? "revert" : j.verdict === "keep" ? "keep" : "unsure";
|
|
2767
|
+
return { model: spec.model, mode: "code", verdict: verdict2, summary: reason, votes: [{ preferred: j.verdict === "keep" ? "after" : "before", confidence, difference: "", reason }], costUsd: cost || null };
|
|
2768
|
+
}
|
|
2769
|
+
const { before, after, regions } = input.visual;
|
|
2770
|
+
const size = PNG3.sync.read(before);
|
|
2771
|
+
const box = unionBox(regions, size.width, size.height);
|
|
2772
|
+
const b = crop(before, box);
|
|
2773
|
+
const a = crop(after, box);
|
|
2774
|
+
const firstIsBefore = (input.random ?? Math.random)() < 0.5;
|
|
2775
|
+
const votes = [];
|
|
2776
|
+
for (const aIsBefore of [firstIsBefore, !firstIsBefore]) {
|
|
2777
|
+
const cwd = join7(base, aIsBefore ? "order-1" : "order-2");
|
|
2778
|
+
mkdirSync3(cwd, { recursive: true });
|
|
2779
|
+
const [imgA, imgB] = aIsBefore ? [b, a] : [a, b];
|
|
2780
|
+
writeFileSync2(join7(cwd, "a.png"), imgA);
|
|
2781
|
+
writeFileSync2(join7(cwd, "b.png"), imgB);
|
|
2782
|
+
const res = await ask(VISUAL_PROMPT(input.step, input.screen), cwd, [imgA, imgB]);
|
|
2783
|
+
if (res.error || !res.text) return fail("visual", res.error ?? "No answer.");
|
|
2784
|
+
const vote = toVote(firstJson(res.text), aIsBefore);
|
|
2785
|
+
if (!vote) return fail("visual", "The answer was not the expected JSON.");
|
|
2786
|
+
votes.push(vote);
|
|
2787
|
+
}
|
|
2788
|
+
const { verdict, summary } = combineVotes(votes);
|
|
2789
|
+
return { model: spec.model, mode: "visual", verdict, summary, votes, costUsd: cost || null };
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2792
|
+
// src/packet.ts
|
|
2793
|
+
import { closeSync as closeSync2, existsSync as existsSync4, fstatSync as fstatSync2, openSync as openSync2, readdirSync as readdirSync5, readFileSync as readFileSync7 } from "fs";
|
|
2794
|
+
import { join as join8, relative as relative3 } from "path";
|
|
2795
|
+
var MAX_PACKET_CHARS = 24e3;
|
|
2796
|
+
var MAX_SKILL_CHARS = 12e3;
|
|
2797
|
+
var DEFAULT_GUIDANCE = `Improve this one screen's UI and UX. In order of priority:
|
|
2798
|
+
1. Fix every measured problem listed below (accessibility violations, sideways scrolling, tap targets under 24\xD724 px, console errors).
|
|
2799
|
+
2. Make the primary action obvious: one clear call to action, visual hierarchy that matches importance.
|
|
2800
|
+
3. Cut noise: shorter copy, group related controls, remove duplicated information, use icons and colour to carry meaning where text is long.
|
|
2801
|
+
4. Spacing and alignment on the design system's scale; readable line length; consistent type sizes.
|
|
2802
|
+
5. The mobile screenshot must work as well as the desktop one.`;
|
|
2803
|
+
var GUARDRAILS = `Rules:
|
|
2804
|
+
- Change only what this screen needs. Shared components and design tokens affect every other screen; edit them only when the fix truly belongs there, and say so in your final message.
|
|
2805
|
+
- Use the existing design tokens, components and icon set. Do not add dependencies.
|
|
2806
|
+
- Do not change data fetching, API calls, auth, routing, state management or tests.
|
|
2807
|
+
- Do not run the dev server, install packages, or commit. The tool reviews and commits your edits.
|
|
2808
|
+
- Do not modify anything under .mushi-ux/. Read only the screenshots and skill files you are pointed to.
|
|
2809
|
+
- Do not read or change node_modules or the framework's own code. A problem that comes from there is not yours to fix: say so and move on.
|
|
2810
|
+
- If the screen is already good, make no edits and say why.`;
|
|
2811
|
+
var MAX_STEP_FILES = 6;
|
|
2812
|
+
var MAX_PLAN_STEPS = 5;
|
|
2813
|
+
var PLAN_READ_BUDGET = 6;
|
|
2814
|
+
function buildPlanPacket(input, maxSteps) {
|
|
2815
|
+
const { surface } = input;
|
|
2816
|
+
const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p));
|
|
2817
|
+
const sections = [
|
|
2818
|
+
`# UX plan \u2014 ${surface.label}`,
|
|
2819
|
+
`Screen: \`${surface.path}\` (${surface.kind}). Plan only: do not edit any file except \`.mushi-ux/PLAN.md\`.`,
|
|
2820
|
+
input.timeBudgetMin ? `## Time
|
|
2821
|
+
You have ${input.timeBudgetMin} minutes. Look, decide, write the list.` : "",
|
|
2822
|
+
input.entryFiles?.length ? `## Start here
|
|
2823
|
+
These files render this screen:
|
|
2824
|
+
${input.entryFiles.map((f) => `- ${f}`).join("\n")}` : "",
|
|
2825
|
+
`## Screenshots (read these images first)
|
|
2826
|
+
${Object.entries(input.shots).map(([vp, p]) => `- ${vp}: ${p}`).join("\n")}
|
|
2827
|
+
Your read tool opens them as images where they are: do not copy them anywhere.`,
|
|
2828
|
+
`## Measured problems
|
|
2829
|
+
${findings.length ? findings.join("\n") : "- None measured."}`,
|
|
2830
|
+
input.skillText ? `## Guidance
|
|
2831
|
+
Use this skill to choose what to improve on this one screen (its supporting files are in \`${input.skillDir ?? ".mushi-ux/skill"}/\`):
|
|
2832
|
+
|
|
2833
|
+
${input.skillText.slice(0, MAX_SKILL_CHARS)}` : `## Guidance
|
|
2834
|
+
${DEFAULT_GUIDANCE}`,
|
|
2835
|
+
`## What to do
|
|
2836
|
+
List 2 to ${maxSteps} small, separate improvements for this screen, most valuable first. Each must be one focused change a developer could make in a few minutes, touching at most 3 files, that does not depend on the others. Start each item with a short summary a user of the app would understand, without file or code names, then a colon, then the change, naming the component or file it changes (for example "- Make the caption readable: in \`x.tsx\`, ..."). Open at most ${PLAN_READ_BUDGET} source files besides the "Start here" ones; each step's own attempt reads the rest. Write them to \`.mushi-ux/PLAN.md\`, one per line starting with "- ", within your first 2 minutes, from the screenshots and the "Start here" files alone; then refine the file if you have time, and reply with the same list. You are stopped when the time is up, and a missing PLAN.md wastes the whole pass. Do not edit any other file: each item gets its own attempt later.`,
|
|
2837
|
+
`## Rules
|
|
2838
|
+
- Do not install anything, and do not run scripts on the screenshots: look at them.
|
|
2839
|
+
- Do not read or change node_modules or the framework's own code.
|
|
2840
|
+
- Do not plan changes to data fetching, API calls, auth, routing, state management or tests.
|
|
2841
|
+
- If the screen is already good, write fewer items.`
|
|
2842
|
+
];
|
|
2843
|
+
return sections.filter(Boolean).join("\n\n").slice(0, MAX_PACKET_CHARS);
|
|
2844
|
+
}
|
|
2845
|
+
function parsePlan(text, max = MAX_PLAN_STEPS) {
|
|
2846
|
+
const out = [];
|
|
2847
|
+
for (const line of text.split(/\r?\n/)) {
|
|
2848
|
+
const m = line.match(/^\s*(?:[-*•]|\d+[.)])\s+(?:\[[ xX]\]\s*)?(.+?)\s*$/);
|
|
2849
|
+
const item = m?.[1]?.replace(/\*\*/g, "").replace(/&(amp|lt|gt|quot|#39);/g, (_, e) => ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" })[e] ?? _).trim();
|
|
2850
|
+
if (!item || item.length < 8 || out.includes(item)) continue;
|
|
2851
|
+
out.push(cutAtWord(item, 280));
|
|
2852
|
+
if (out.length >= max) break;
|
|
2853
|
+
}
|
|
2854
|
+
return out;
|
|
2855
|
+
}
|
|
2856
|
+
function cutAtWord(text, max) {
|
|
2857
|
+
if (text.length <= max) return text;
|
|
2858
|
+
const head = text.slice(0, max - 1);
|
|
2859
|
+
const space = head.lastIndexOf(" ");
|
|
2860
|
+
let cut = (space > max / 2 ? head.slice(0, space) : head).replace(/[\s,;:.(-]+$/, "");
|
|
2861
|
+
if ((cut.match(/`/g)?.length ?? 0) % 2 === 1) cut = cut.slice(0, cut.lastIndexOf("`")).trimEnd();
|
|
2862
|
+
return `${cut}\u2026`;
|
|
2863
|
+
}
|
|
2864
|
+
var PLAN_POINTER_PROMPT = "Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It asks for a plan only: write .mushi-ux/PLAN.md and edit nothing else.";
|
|
2865
|
+
function describeProbes(viewport, p) {
|
|
2866
|
+
const lines = [];
|
|
2867
|
+
for (const v of p.axe) {
|
|
2868
|
+
lines.push(`- [${viewport}] ${v.id} (${v.impact ?? "n/a"}, ${v.count} node${v.count === 1 ? "" : "s"}): ${v.help} \u2014 e.g. ${v.targets.slice(0, 3).join(", ")}`);
|
|
2869
|
+
}
|
|
2870
|
+
if (p.overflowX) lines.push(`- [${viewport}] The page scrolls sideways at this width.`);
|
|
2871
|
+
if (p.smallTargets > 0) lines.push(`- [${viewport}] ${p.smallTargets} tap target(s) smaller than 24\xD724 px.`);
|
|
2872
|
+
for (const e of p.consoleErrors.slice(0, 5)) lines.push(`- [${viewport}] Console error: ${e}`);
|
|
2873
|
+
if (p.cls > CLS_GOOD) lines.push(`- [${viewport}] Layout shift ${p.cls} while loading (aim below ${CLS_GOOD}).`);
|
|
2874
|
+
return lines;
|
|
2875
|
+
}
|
|
2876
|
+
function buildPacket(input) {
|
|
2877
|
+
const { surface } = input;
|
|
2878
|
+
const steps = surface.steps.length ? ` then click ${surface.steps.map((s) => `"${s.label}"`).join(" \u2192 ")}` : "";
|
|
2879
|
+
const findings = Object.entries(input.probes).flatMap(([vp, p]) => describeProbes(vp, p));
|
|
2880
|
+
const skill = input.skillText ? [
|
|
2881
|
+
`Apply this skill to this one screen only. Skip its whole-app steps (stack detection, scoring every screen, app-wide inventories): another pass handles each other screen. Its supporting files (references, scorecards) are in \`${input.skillDir ?? ".mushi-ux/skill"}/\`; read only the ones this screen needs.`,
|
|
2882
|
+
input.skillText.slice(0, MAX_SKILL_CHARS)
|
|
2883
|
+
].join("\n\n") : DEFAULT_GUIDANCE;
|
|
2884
|
+
const sections = [
|
|
2885
|
+
`# UX pass \u2014 ${surface.label}`,
|
|
2886
|
+
`Screen: \`${surface.path}\`${steps} (${surface.kind}). Attempt ${input.iteration}.`,
|
|
2887
|
+
input.timeBudgetMin ? `## Time
|
|
2888
|
+
You have ${input.timeBudgetMin} minutes, then you are stopped and unsaved work is lost. Make your first edit within ${Math.max(1, Math.round(input.timeBudgetMin / 3))} minutes: an attempt that ends without an edit counts as a failure. Do not survey the whole design system; read only what the edit needs. A small, finished improvement beats a large unfinished one: make it, then stop.` : "",
|
|
2889
|
+
input.entryFiles?.length ? `## Start here
|
|
2890
|
+
These files render this screen. Read them first instead of searching the repo:
|
|
2891
|
+
${input.entryFiles.map((f) => `- ${f}`).join("\n")}` : "",
|
|
2892
|
+
`## Screenshots (read these images first)
|
|
2893
|
+
${Object.entries(input.shots).map(([vp, p]) => `- ${vp}: ${p}`).join("\n")}`,
|
|
2894
|
+
`## Measured problems
|
|
2895
|
+
${findings.length ? findings.join("\n") : "- None measured. Focus on hierarchy, clarity and density."}`,
|
|
2896
|
+
input.previousRejection ? `## Your previous attempt was rolled back
|
|
2897
|
+
${input.previousRejection}
|
|
2898
|
+
Try a different, smaller change.` : "",
|
|
2899
|
+
`## Design system (read before editing)
|
|
2900
|
+
${input.designFiles.length ? input.designFiles.map((f) => `- ${f}`).join("\n") : "- No token files found; match the styles already used on this screen."}`,
|
|
2901
|
+
input.step ? [
|
|
2902
|
+
`## This step (${input.step.index} of ${input.step.total})
|
|
2903
|
+
${input.step.text}`,
|
|
2904
|
+
`Make only this change, touching at most 3 files. ${input.step.done.length ? `Already done in earlier steps: ${input.step.done.map((d) => `"${d}"`).join("; ")}. ` : ""}Later steps come in their own attempts. If this step turns out to be unnecessary, make no edit and say why.`
|
|
2905
|
+
].join("\n") : "",
|
|
2906
|
+
input.step ? `## Guidance
|
|
2907
|
+
${skill}` : `## What to do
|
|
2908
|
+
${skill}`,
|
|
2909
|
+
`## ${GUARDRAILS}`
|
|
2910
|
+
];
|
|
2911
|
+
return sections.filter(Boolean).join("\n\n").slice(0, MAX_PACKET_CHARS);
|
|
2912
|
+
}
|
|
2913
|
+
var POINTER_PROMPT = "Read .mushi-ux/PROMPT.md in this repository and follow it exactly. It names the screenshots to look at and the screen to improve.";
|
|
2914
|
+
var SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".turbo", ".worktrees", ".mushi", ".mushi-ux", "coverage"]);
|
|
2915
|
+
function findDesignFiles(root, maxFiles = 12) {
|
|
2916
|
+
const found = [];
|
|
2917
|
+
const recipe = join8(root, "mushi.recipe.json");
|
|
2918
|
+
if (existsSync4(recipe)) found.push("mushi.recipe.json");
|
|
2919
|
+
const walk = (dir, depth) => {
|
|
2920
|
+
if (depth > 5 || found.length >= maxFiles) return;
|
|
2921
|
+
let names;
|
|
2922
|
+
try {
|
|
2923
|
+
names = readdirSync5(dir);
|
|
2924
|
+
} catch {
|
|
2925
|
+
return;
|
|
2926
|
+
}
|
|
2927
|
+
for (const name of names) {
|
|
2928
|
+
if (found.length >= maxFiles) return;
|
|
2929
|
+
if (SKIP_DIRS2.has(name)) continue;
|
|
2930
|
+
const abs = join8(dir, name);
|
|
2931
|
+
let fd;
|
|
2932
|
+
let isDir;
|
|
2933
|
+
let css = null;
|
|
2934
|
+
try {
|
|
2935
|
+
fd = openSync2(abs, "r");
|
|
2936
|
+
} catch {
|
|
2937
|
+
continue;
|
|
2938
|
+
}
|
|
2939
|
+
try {
|
|
2940
|
+
const st = fstatSync2(fd);
|
|
2941
|
+
isDir = st.isDirectory();
|
|
2942
|
+
if (!isDir && name.endsWith(".css") && st.size < 3e5) css = readFileSync7(fd, "utf8");
|
|
2943
|
+
} catch {
|
|
2944
|
+
continue;
|
|
2945
|
+
} finally {
|
|
2946
|
+
closeSync2(fd);
|
|
2947
|
+
}
|
|
2948
|
+
if (isDir) {
|
|
2949
|
+
walk(abs, depth + 1);
|
|
2950
|
+
continue;
|
|
2951
|
+
}
|
|
2952
|
+
const rel = relative3(root, abs).replace(/\\/g, "/");
|
|
2953
|
+
if (/^tailwind\.config\.(js|cjs|mjs|ts)$/.test(name) || /\.tokens\.json$|^tokens\.json$/.test(name)) {
|
|
2954
|
+
found.push(rel);
|
|
2955
|
+
} else if (css !== null) {
|
|
2956
|
+
if (/@theme\b/.test(css) || (css.match(/--[\w-]+\s*:/g)?.length ?? 0) > 20) found.push(rel);
|
|
2957
|
+
}
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
walk(root, 0);
|
|
2961
|
+
return found;
|
|
2962
|
+
}
|
|
2963
|
+
|
|
2964
|
+
// src/preflight.ts
|
|
2965
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
2966
|
+
import { mkdtempSync, rmSync, writeFileSync as writeFileSync3 } from "fs";
|
|
2967
|
+
import { tmpdir } from "os";
|
|
2968
|
+
import { join as join9 } from "path";
|
|
2969
|
+
|
|
2970
|
+
// src/verdict.ts
|
|
2971
|
+
var MIN_VISIBLE_RATIO = 5e-4;
|
|
2972
|
+
function agentFinalMessage(stdout) {
|
|
2973
|
+
let last = null;
|
|
2974
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
2975
|
+
if (!line.startsWith("{")) continue;
|
|
2976
|
+
try {
|
|
2977
|
+
const j = JSON.parse(line);
|
|
2978
|
+
if (j.type === "result" && typeof j.result === "string" && j.result.trim()) last = j.result.trim();
|
|
2979
|
+
} catch {
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
return last;
|
|
2983
|
+
}
|
|
2984
|
+
function assistantText(stdout) {
|
|
2985
|
+
const out = [];
|
|
2986
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
2987
|
+
if (!line.startsWith("{")) continue;
|
|
2988
|
+
try {
|
|
2989
|
+
const j = JSON.parse(line);
|
|
2990
|
+
if (j.type !== "assistant" || j.model_call_id !== void 0 || !Array.isArray(j.message?.content)) continue;
|
|
2991
|
+
for (const c of j.message.content) {
|
|
2992
|
+
if (c.type === "text" && typeof c.text === "string") out.push(c.text);
|
|
2993
|
+
}
|
|
2994
|
+
} catch {
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
return out.join("\n");
|
|
2998
|
+
}
|
|
2999
|
+
var AGENT_BLOCKED_RE = /\b(could ?n[o'’]t|can ?not|cannot|unable to) (read|open|access|run|use)\b|\bhooks?\b.*\b(fail|error|block)|\b(blocked|stopped) before\b/i;
|
|
3000
|
+
function explainNoEdit(final) {
|
|
3001
|
+
if (!final) return { outcome: "no_change", reason: "The agent made no edits." };
|
|
3002
|
+
const said = final.length > 400 ? `\u2026${final.slice(-400)}` : final;
|
|
3003
|
+
if (AGENT_BLOCKED_RE.test(final)) return { outcome: "agent_failed", reason: `The agent could not work on the screen: ${said}` };
|
|
3004
|
+
return { outcome: "no_change", reason: `The agent made no edits: ${said}` };
|
|
3005
|
+
}
|
|
3006
|
+
function clsNeedsSecondLook(before, after) {
|
|
3007
|
+
return Object.entries(after).some(([vp, now]) => now.cls > CLS_GOOD && now.cls > (before[vp]?.cls ?? 0));
|
|
3008
|
+
}
|
|
3009
|
+
function steadierCls(first, second) {
|
|
3010
|
+
return Object.fromEntries(
|
|
3011
|
+
Object.entries(first).map(([vp, p]) => [vp, second[vp] ? { ...p, cls: Math.min(p.cls, second[vp].cls) } : p])
|
|
3012
|
+
);
|
|
3013
|
+
}
|
|
3014
|
+
function whatRose(before, now) {
|
|
3015
|
+
const out = [];
|
|
3016
|
+
if (now.smallTargets > before.smallTargets) out.push(`tap targets under 24 px ${before.smallTargets} \u2192 ${now.smallTargets}`);
|
|
3017
|
+
if (now.cls > CLS_GOOD && now.cls > before.cls) out.push(`layout shift ${before.cls} \u2192 ${now.cls}`);
|
|
3018
|
+
const was = new Map(before.axe.map((v) => [v.id, v.count]));
|
|
3019
|
+
for (const v of now.axe) {
|
|
3020
|
+
if (v.count > (was.get(v.id) ?? 0)) out.push(`${v.id} ${was.get(v.id) ?? 0} \u2192 ${v.count} element(s)`);
|
|
3021
|
+
}
|
|
3022
|
+
return out;
|
|
3023
|
+
}
|
|
3024
|
+
function decide(input) {
|
|
3025
|
+
if (input.filesChanged === 0) return { outcome: "no_change", reason: "The agent made no edits." };
|
|
3026
|
+
if (!input.after) {
|
|
3027
|
+
return { outcome: "capture_failed", reason: "The screen could not be captured after the edit (it may no longer render)." };
|
|
3028
|
+
}
|
|
3029
|
+
const after = input.after;
|
|
3030
|
+
const worse = [];
|
|
3031
|
+
const summary = [];
|
|
3032
|
+
for (const [vp, before] of Object.entries(input.before)) {
|
|
3033
|
+
const now = after[vp];
|
|
3034
|
+
if (!now) {
|
|
3035
|
+
worse.push(`${vp}: no capture after the edit`);
|
|
3036
|
+
continue;
|
|
3037
|
+
}
|
|
3038
|
+
const pb = probePenalty(before);
|
|
3039
|
+
const pa = probePenalty(now);
|
|
3040
|
+
summary.push(`${vp} ${pb}\u2192${pa}`);
|
|
3041
|
+
if (now.consoleErrors.length > before.consoleErrors.length) {
|
|
3042
|
+
worse.push(`${vp}: new console error "${now.consoleErrors[now.consoleErrors.length - 1]}"`);
|
|
3043
|
+
}
|
|
3044
|
+
if (now.overflowX && !before.overflowX) worse.push(`${vp}: the page now scrolls sideways`);
|
|
3045
|
+
const beforeIds = new Set(before.axe.map((v) => v.id));
|
|
3046
|
+
const newRules = now.axe.filter((v) => !beforeIds.has(v.id)).map((v) => v.id);
|
|
3047
|
+
if (newRules.length) worse.push(`${vp}: new accessibility violations ${newRules.join(", ")}`);
|
|
3048
|
+
if (pa > pb && worse.length === 0) {
|
|
3049
|
+
const rose = whatRose(before, now);
|
|
3050
|
+
worse.push(`${vp}: ${rose.length ? rose.join(", ") : "measured problems rose"} (problem score ${pb} \u2192 ${pa})`);
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
if (worse.length) return { outcome: "rejected", reason: `Rolled back: ${worse.join("; ")}.` };
|
|
3054
|
+
const maxRatio = Math.max(0, ...Object.values(input.pixelRatios));
|
|
3055
|
+
if (maxRatio < MIN_VISIBLE_RATIO) {
|
|
3056
|
+
if (input.keepInvisible) {
|
|
3057
|
+
return {
|
|
3058
|
+
outcome: "accepted",
|
|
3059
|
+
needsReview: true,
|
|
3060
|
+
reason: `Kept, needs your review: the edit changed ${input.filesChanged} file(s) but nothing visible in a still screenshot (motion, haptics or another screen). Read the diff.`
|
|
3061
|
+
};
|
|
3062
|
+
}
|
|
3063
|
+
return { outcome: "no_change", reason: `The edits changed ${input.filesChanged} file(s) but nothing visible on this screen.` };
|
|
3064
|
+
}
|
|
3065
|
+
return {
|
|
3066
|
+
outcome: "accepted",
|
|
3067
|
+
reason: `Kept: problem score ${summary.join(", ")}; ${(maxRatio * 100).toFixed(1)}% of pixels changed.`
|
|
3068
|
+
};
|
|
3069
|
+
}
|
|
3070
|
+
|
|
3071
|
+
// src/preflight.ts
|
|
3072
|
+
var PREFLIGHT_TIMEOUT_MS = 3 * 6e4;
|
|
3073
|
+
var NOT_LOGGED_IN_RE = /not (logged|signed) in|log ?in required|please (log|sign) ?in|unauthori[sz]ed|invalid api key|authentication/i;
|
|
3074
|
+
var HOOK_RE = /\bhooks?\b/i;
|
|
3075
|
+
function preflightAdvice(agent, output, platform = process.platform) {
|
|
3076
|
+
if (NOT_LOGGED_IN_RE.test(output)) {
|
|
3077
|
+
const login = {
|
|
3078
|
+
cursor: "Run `agent login` (Cursor CLI), then start the run again.",
|
|
3079
|
+
"claude-code": "Run `claude` once and sign in, or set ANTHROPIC_API_KEY.",
|
|
3080
|
+
codex: "Run `codex login`, or set OPENAI_API_KEY."
|
|
3081
|
+
};
|
|
3082
|
+
return `The agent is not signed in. ${login[agent] ?? "Sign the agent in, then start the run again."}`;
|
|
3083
|
+
}
|
|
3084
|
+
if (agent === "cursor" && HOOK_RE.test(output)) {
|
|
3085
|
+
return "A hook refused the agent\u2019s tool calls. The Cursor CLI also runs the hooks in ~/.claude/settings.json; " + (platform === "win32" ? "on Windows a hook fails when the run is started from Git Bash. Start `mushi ux` from PowerShell or cmd, or fix the hook." : "fix the failing hook or remove it, then start the run again.");
|
|
3086
|
+
}
|
|
3087
|
+
return "Run the agent once by hand in this repo to see what it needs, then start the run again.";
|
|
3088
|
+
}
|
|
3089
|
+
async function preflightAgent(agent, opts = {}) {
|
|
3090
|
+
const dir = mkdtempSync(join9(tmpdir(), "mushi-ux-preflight-"));
|
|
3091
|
+
const word = randomBytes2(4).toString("hex");
|
|
3092
|
+
try {
|
|
3093
|
+
writeFileSync3(join9(dir, "PREFLIGHT.txt"), `The code word is ${word}.
|
|
3094
|
+
`);
|
|
3095
|
+
const timeoutMs = opts.timeoutMs ?? PREFLIGHT_TIMEOUT_MS;
|
|
3096
|
+
const res = await agent.run({
|
|
3097
|
+
cwd: dir,
|
|
3098
|
+
prompt: "Read the file PREFLIGHT.txt in this folder and reply with only the code word it contains. Do not edit anything.",
|
|
3099
|
+
model: opts.model,
|
|
3100
|
+
timeoutMs,
|
|
3101
|
+
signal: opts.signal
|
|
3102
|
+
});
|
|
3103
|
+
if (res.stdout.includes(word) || res.tail.includes(word)) return null;
|
|
3104
|
+
if (opts.signal?.aborted) return "Stopped.";
|
|
3105
|
+
const said = agentFinalMessage(res.stdout) ?? res.tail.trim();
|
|
3106
|
+
const output = `${said}
|
|
3107
|
+
${res.tail}`;
|
|
3108
|
+
const what = res.timedOut ? `did not answer within ${Math.round(timeoutMs / 1e3)} s` : res.exitCode !== 0 ? `exited with code ${res.exitCode}` : "answered without reading the file";
|
|
3109
|
+
const quote = said ? ` It said: \u201C${said.replace(/\s+/g, " ").slice(-300)}\u201D` : "";
|
|
3110
|
+
return `Agent check failed: ${agent.name}${opts.model ? ` (${opts.model})` : ""} ${what}.${quote} ${preflightAdvice(String(agent.name), output)}`;
|
|
3111
|
+
} catch (err) {
|
|
3112
|
+
return `Agent check failed: could not start ${agent.name}: ${err.message}. Is it installed and on PATH?`;
|
|
3113
|
+
} finally {
|
|
3114
|
+
rmSync(dir, { recursive: true, force: true });
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
|
|
3118
|
+
// src/resume.ts
|
|
3119
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync6, readFileSync as readFileSync8, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
|
|
3120
|
+
import { dirname as dirname4, join as join10, relative as relative4 } from "path";
|
|
3121
|
+
function saveSkillFiles(dir, skill) {
|
|
3122
|
+
const root = join10(dir, "skill");
|
|
3123
|
+
rmSync2(root, { recursive: true, force: true });
|
|
3124
|
+
for (const [rel, buf] of Object.entries(skill.files)) {
|
|
3125
|
+
const target = join10(root, ...rel.split("/"));
|
|
3126
|
+
mkdirSync4(dirname4(target), { recursive: true });
|
|
3127
|
+
writeFileSync4(target, buf);
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
function expectedHead(state) {
|
|
3131
|
+
const kept = state.surfaces.flatMap((s) => s.iterations).filter((i) => i.outcome === "accepted" && i.commitSha).sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt));
|
|
3132
|
+
return kept.length ? kept[kept.length - 1].commitSha : state.baseSha;
|
|
3133
|
+
}
|
|
3134
|
+
|
|
3135
|
+
// src/types.ts
|
|
3136
|
+
var VIEWPORTS = [
|
|
3137
|
+
{ name: "desktop", width: 1440, height: 900 },
|
|
3138
|
+
{ name: "mobile", width: 390, height: 844 }
|
|
3139
|
+
];
|
|
3140
|
+
|
|
3141
|
+
// src/loop.ts
|
|
3142
|
+
var REGRESSION_CONTENT_RATIO = 0.05;
|
|
3143
|
+
var REGRESSION_MIN_PIXELS = 200;
|
|
3144
|
+
var PLAN_TIMEOUT_MS = 6 * 6e4;
|
|
3145
|
+
var PLAN_NUDGE_MS = 3 * 6e4;
|
|
3146
|
+
var EDIT_NUDGE_MS = 3 * 6e4;
|
|
3147
|
+
var PLAN_NUDGE = 'Time is up. Do not read any more files. Write .mushi-ux/PLAN.md now with the improvements you found, one per line starting with "- ", then stop.';
|
|
3148
|
+
var EDIT_NUDGE = "Time is up. Do not read any more files. Make the one change you have decided on now, touching at most 3 files, then stop.";
|
|
3149
|
+
var HEARTBEAT_MS = 3e4;
|
|
3150
|
+
function emit(events, e) {
|
|
3151
|
+
events?.emit("event", e);
|
|
3152
|
+
}
|
|
3153
|
+
function referenceShot(s, viewport) {
|
|
3154
|
+
const kept = [...s.iterations].reverse().find((i) => i.outcome === "accepted");
|
|
3155
|
+
return kept?.after[viewport] ?? s.baseline[viewport];
|
|
3156
|
+
}
|
|
3157
|
+
function timeoutNote(timeoutMs) {
|
|
3158
|
+
const minutes = Math.round(timeoutMs / 6e4);
|
|
3159
|
+
return `It read for ${minutes} minutes without making any edit and was stopped. Start from the files under "Start here", pick one change, and make it within ${Math.max(1, Math.round(minutes / 3))} minutes.`;
|
|
3160
|
+
}
|
|
3161
|
+
function scrubFrameworkNoise(state) {
|
|
3162
|
+
const clean = (ref) => {
|
|
3163
|
+
if (!ref) return;
|
|
3164
|
+
const kept = ref.probes.consoleErrors.filter((e) => !isFrameworkNoise(e));
|
|
3165
|
+
if (kept.length === ref.probes.consoleErrors.length) return;
|
|
3166
|
+
ref.probes = { ...ref.probes, consoleErrors: kept };
|
|
3167
|
+
ref.penalty = probePenalty(ref.probes);
|
|
3168
|
+
};
|
|
3169
|
+
for (const s of state.surfaces) {
|
|
3170
|
+
Object.values(s.baseline).forEach(clean);
|
|
3171
|
+
for (const it of s.iterations) Object.values(it.after).forEach(clean);
|
|
3172
|
+
}
|
|
3173
|
+
}
|
|
3174
|
+
function noScreensMessage(skipped, devError) {
|
|
3175
|
+
const reasons = skipped.map((s) => s.replace(/^\S+:\s*/, ""));
|
|
3176
|
+
const unique = [...new Set(reasons)];
|
|
3177
|
+
const lines = [];
|
|
3178
|
+
if (skipped.length && unique.length === 1 && /HTTP 5\d\d/.test(unique[0])) {
|
|
3179
|
+
lines.push(`No screen to work on: every page returned ${unique[0]}, so the app's dev server is failing, not the pages.`);
|
|
3180
|
+
} else if (skipped.length) {
|
|
3181
|
+
lines.push(`No screen to work on: all ${new Set(skipped.map((s) => s.split(":")[0])).size} page(s) were skipped (${unique.slice(0, 3).join("; ")}).`);
|
|
3182
|
+
} else {
|
|
3183
|
+
lines.push("No screen to work on: mapping found no page. Name the pages to work on, or check that the home page loads.");
|
|
3184
|
+
}
|
|
3185
|
+
if (devError) lines.push(`The dev server said: ${devError}`);
|
|
3186
|
+
lines.push("Fix the app or the dev command (for example a different bundler flag), then start a new run. The full output is in run.log.");
|
|
3187
|
+
return lines.join("\n");
|
|
3188
|
+
}
|
|
3189
|
+
var SUMMARY_MAX = 72;
|
|
3190
|
+
var DANGLING = /[\s,]+(?:a|an|and|as|at|between|by|for|from|in|into|is|of|on|or|so|that|the|to|while|with)$/i;
|
|
3191
|
+
function commitMessage(path, screen, step, reason) {
|
|
3192
|
+
const name = screen.split(/\s+[—|–]\s+/)[0].trim() || path;
|
|
3193
|
+
const summary = (step ? stepSummary(step) : "") || `improve the ${name} screen`;
|
|
3194
|
+
const body = [step ? `${name} (${path}): ${step}` : `${name} (${path})`, reason];
|
|
3195
|
+
return [`fix(ux): ${lowerFirst(summary)}`, ...body.map((p) => wrapAt(p, BODY_WIDTH))].join("\n\n");
|
|
3196
|
+
}
|
|
3197
|
+
var BODY_WIDTH = 100;
|
|
3198
|
+
function wrapAt(text, width) {
|
|
3199
|
+
const lines = [];
|
|
3200
|
+
let line = "";
|
|
3201
|
+
for (const word of text.split(/\s+/).filter(Boolean)) {
|
|
3202
|
+
if (line && [...`${line} ${word}`].length > width) {
|
|
3203
|
+
lines.push(line);
|
|
3204
|
+
line = word;
|
|
3205
|
+
} else line = line ? `${line} ${word}` : word;
|
|
3206
|
+
}
|
|
3207
|
+
if (line) lines.push(line);
|
|
3208
|
+
for (let i = 1; i < lines.length; i++) {
|
|
3209
|
+
if (!FOOTER_TOKEN.test(lines[i])) continue;
|
|
3210
|
+
const prev = lines[i - 1].split(" ");
|
|
3211
|
+
if (prev.length < 2) continue;
|
|
3212
|
+
lines[i] = `${prev.pop()} ${lines[i]}`;
|
|
3213
|
+
lines[i - 1] = prev.join(" ");
|
|
3214
|
+
}
|
|
3215
|
+
return lines.join("\n");
|
|
3216
|
+
}
|
|
3217
|
+
var FOOTER_TOKEN = /^(?:[A-Za-z][\w-]*|BREAKING CHANGE): /;
|
|
3218
|
+
var lowerFirst = (s) => /^[A-Z][a-z]/.test(s) ? s[0].toLowerCase() + s.slice(1) : s;
|
|
3219
|
+
var isPath = (code) => code.includes("/") || /\.[a-z]{2,4}$/i.test(code);
|
|
3220
|
+
function stepSummary(step) {
|
|
3221
|
+
const lead = step.match(/^([^:`]{8,90}):\s/)?.[1];
|
|
3222
|
+
let s = lead ?? step.replace(/^(?:In\s+)?`[^`]+`(?:\s*\([^)]*\))?\s*[,:]?\s*/i, "").split(/(?<=\.)\s|;\s/)[0];
|
|
3223
|
+
s = s.replace(/\s*\(([^()]*)\)/g, (m, inner) => inner.includes("`") ? "" : m).replace(/\s+(?:in|from|of|on)\s+`([^`]*)`/gi, (m, inner) => isPath(inner) ? "" : m).replace(/`([^`]*)`/g, (_m, inner) => isPath(inner) ? " " : inner.replace(/["']/g, "")).replace(/\s{2,}/g, " ").trim();
|
|
3224
|
+
if (s.length > SUMMARY_MAX) {
|
|
3225
|
+
const cut = s.lastIndexOf(" ", SUMMARY_MAX);
|
|
3226
|
+
s = s.slice(0, cut > 0 ? cut : SUMMARY_MAX);
|
|
3227
|
+
const open = s.lastIndexOf("(");
|
|
3228
|
+
if (open > s.lastIndexOf(")")) s = s.slice(0, open);
|
|
3229
|
+
while (DANGLING.test(s)) s = s.replace(DANGLING, "");
|
|
3230
|
+
}
|
|
3231
|
+
s = s.replace(/^[\s,;:.—–-]+|[\s,;:.—–-]+$/g, "");
|
|
3232
|
+
return s ? s[0].toUpperCase() + s.slice(1) : "";
|
|
3233
|
+
}
|
|
3234
|
+
function startLoop(opts) {
|
|
3235
|
+
const runId = opts.resumeRunId ?? newRunId();
|
|
3236
|
+
const dir = runDir(opts.repoRoot, runId);
|
|
3237
|
+
const done = runLoop(opts, runId, dir);
|
|
3238
|
+
return { runId, dir, done };
|
|
3239
|
+
}
|
|
3240
|
+
async function runLoop(opts, runId, dir) {
|
|
3241
|
+
const events = opts.events;
|
|
3242
|
+
const log = (message) => {
|
|
3243
|
+
emit(events, { type: "log", message });
|
|
3244
|
+
try {
|
|
3245
|
+
mkdirSync5(dir, { recursive: true });
|
|
3246
|
+
appendFileSync2(join11(dir, "run.log"), `${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)} ${message}
|
|
3247
|
+
`);
|
|
3248
|
+
} catch {
|
|
3249
|
+
}
|
|
3250
|
+
};
|
|
3251
|
+
const agent = opts.agentAdapter ?? getAgent(opts.agent);
|
|
3252
|
+
const iterations = opts.iterations ?? 2;
|
|
3253
|
+
const timeoutMs = opts.agentTimeoutMs ?? 10 * 6e4;
|
|
3254
|
+
const state = loadState(dir) ?? {
|
|
3255
|
+
version: 1,
|
|
3256
|
+
runId,
|
|
3257
|
+
baseUrl: "",
|
|
3258
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3259
|
+
updatedAt: "",
|
|
3260
|
+
agent: agent.name,
|
|
3261
|
+
model: opts.model ?? null,
|
|
3262
|
+
skill: opts.skill ? { name: opts.skill.name, source: opts.skill.source } : null,
|
|
3263
|
+
baseRef: opts.baseRef ?? "HEAD",
|
|
3264
|
+
phase: "starting",
|
|
3265
|
+
worktree: null,
|
|
3266
|
+
branch: null,
|
|
3267
|
+
baseSha: null,
|
|
3268
|
+
surfaces: []
|
|
3269
|
+
};
|
|
3270
|
+
scrubFrameworkNoise(state);
|
|
3271
|
+
const resuming = Boolean(state.updatedAt);
|
|
3272
|
+
if (resuming) {
|
|
3273
|
+
state.error = null;
|
|
3274
|
+
state.finishedAt = null;
|
|
3275
|
+
state.stopped = false;
|
|
3276
|
+
state.current = null;
|
|
3277
|
+
}
|
|
3278
|
+
if (!state.options) {
|
|
3279
|
+
state.options = {
|
|
3280
|
+
agent: String(opts.agent),
|
|
3281
|
+
model: opts.model ?? null,
|
|
3282
|
+
devCommand: opts.devCommand,
|
|
3283
|
+
installCommand: opts.installCommand,
|
|
3284
|
+
startPaths: opts.startPaths,
|
|
3285
|
+
crawl: opts.crawl,
|
|
3286
|
+
iterations,
|
|
3287
|
+
checker: opts.checker ?? null,
|
|
3288
|
+
keepInvisible: opts.keepInvisible !== false,
|
|
3289
|
+
maxSurfaces: opts.maxSurfaces ?? 10,
|
|
3290
|
+
agentTimeoutMs: timeoutMs,
|
|
3291
|
+
ignore: opts.ignore,
|
|
3292
|
+
allow: opts.allow,
|
|
3293
|
+
judgeModel: opts.judgeModel ?? null,
|
|
3294
|
+
loginUrl: opts.loginUrl ?? null,
|
|
3295
|
+
sync: opts.sync,
|
|
3296
|
+
steps: opts.steps
|
|
3297
|
+
};
|
|
3298
|
+
}
|
|
3299
|
+
if (opts.skill) {
|
|
3300
|
+
state.skill = { name: opts.skill.name, source: opts.skill.source };
|
|
3301
|
+
try {
|
|
3302
|
+
saveSkillFiles(dir, opts.skill);
|
|
3303
|
+
} catch {
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
const persist = () => {
|
|
3307
|
+
saveState(dir, state);
|
|
3308
|
+
emit(events, { type: "state" });
|
|
3309
|
+
};
|
|
3310
|
+
const phase = (p, detail = null) => {
|
|
3311
|
+
state.phase = p;
|
|
3312
|
+
state.phaseDetail = detail;
|
|
3313
|
+
emit(events, { type: "phase", phase: p, detail });
|
|
3314
|
+
persist();
|
|
3315
|
+
};
|
|
3316
|
+
const skillText = opts.skill?.text ?? opts.skillText ?? null;
|
|
3317
|
+
const beat = setInterval(() => {
|
|
3318
|
+
try {
|
|
3319
|
+
persist();
|
|
3320
|
+
} catch {
|
|
3321
|
+
}
|
|
3322
|
+
}, HEARTBEAT_MS);
|
|
3323
|
+
try {
|
|
3324
|
+
return await runSteps();
|
|
3325
|
+
} catch (err) {
|
|
3326
|
+
const stopped = Boolean(opts.signal?.aborted);
|
|
3327
|
+
state.stopped = stopped;
|
|
3328
|
+
state.error = stopped ? "Stopped from the studio." : err.message.slice(0, 2e3);
|
|
3329
|
+
if (stopped && state.worktree) await revertAll(state.worktree).catch(() => void 0);
|
|
3330
|
+
state.current = null;
|
|
3331
|
+
state.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3332
|
+
phase("failed", state.error.split("\n")[0].slice(0, 200));
|
|
3333
|
+
throw err;
|
|
3334
|
+
} finally {
|
|
3335
|
+
clearInterval(beat);
|
|
3336
|
+
}
|
|
3337
|
+
async function runSteps() {
|
|
3338
|
+
if (opts.preflight !== false && !opts.agentAdapter && agent.name !== "cursor-cloud") {
|
|
3339
|
+
log(`Checking that ${agent.name} can read files\u2026`);
|
|
3340
|
+
phase("starting", "Checking the agent can read files");
|
|
3341
|
+
const problem = await preflightAgent(agent, { model: opts.model, signal: opts.signal });
|
|
3342
|
+
if (opts.signal?.aborted) throw new Error("Stopped.");
|
|
3343
|
+
if (problem) throw new Error(problem);
|
|
3344
|
+
log("Agent check passed.");
|
|
3345
|
+
}
|
|
3346
|
+
if (!state.worktree) {
|
|
3347
|
+
log("Creating a worktree for the agent\u2026");
|
|
3348
|
+
phase("worktree", `from ${state.baseRef ?? "HEAD"}`);
|
|
3349
|
+
const wt = await createWorktree(opts.repoRoot, runId, state.baseRef ?? "HEAD");
|
|
3350
|
+
state.worktree = wt.path;
|
|
3351
|
+
state.branch = wt.branch;
|
|
3352
|
+
state.baseSha = wt.baseSha;
|
|
3353
|
+
persist();
|
|
3354
|
+
} else if (!existsSync6(state.worktree)) {
|
|
3355
|
+
throw new Error(`The run's worktree ${state.worktree} is gone, so this run cannot continue. Start a new run.`);
|
|
3356
|
+
}
|
|
3357
|
+
if (state.installed === void 0 && state.surfaces.length > 0) state.installed = true;
|
|
3358
|
+
if (!state.installed) {
|
|
3359
|
+
const install = opts.installCommand === void 0 ? detectInstallCommand(state.worktree) : opts.installCommand;
|
|
3360
|
+
if (install) {
|
|
3361
|
+
log(`Installing dependencies: ${install}`);
|
|
3362
|
+
phase("install", install);
|
|
3363
|
+
const res = await run(install, [], { cwd: state.worktree, shell: true, timeoutMs: 15 * 6e4, env: appEnv() });
|
|
3364
|
+
if (res.exitCode !== 0) throw new Error(`Install failed in the worktree:
|
|
3365
|
+
${res.tail}`);
|
|
3366
|
+
}
|
|
3367
|
+
state.installed = true;
|
|
3368
|
+
persist();
|
|
3369
|
+
}
|
|
3370
|
+
const wtPath = state.worktree;
|
|
3371
|
+
if (resuming) await restoreWorktree(wtPath);
|
|
3372
|
+
const designFiles = findDesignFiles(wtPath);
|
|
3373
|
+
log(`Starting the dev server in the worktree: ${opts.devCommand}`);
|
|
3374
|
+
phase("dev-server", opts.devCommand);
|
|
3375
|
+
let devError = null;
|
|
3376
|
+
const server = await startDevServer(wtPath, opts.devCommand, {
|
|
3377
|
+
path: opts.startPaths?.[0],
|
|
3378
|
+
onLine: (l) => {
|
|
3379
|
+
log(`[dev] ${l.slice(0, 200)}`);
|
|
3380
|
+
if (!devError && /\b(error|module not found)\b/i.test(l)) devError = l.trim().slice(0, 300);
|
|
3381
|
+
}
|
|
3382
|
+
});
|
|
3383
|
+
state.baseUrl = server.url;
|
|
3384
|
+
persist();
|
|
3385
|
+
const session = await openSession({ profileDir: opts.profileDir, allow: opts.allow, ignore: opts.ignore });
|
|
3386
|
+
try {
|
|
3387
|
+
if (state.surfaces.length === 0) {
|
|
3388
|
+
log("Mapping screens\u2026");
|
|
3389
|
+
phase("mapping", null);
|
|
3390
|
+
if (opts.startPaths?.length) {
|
|
3391
|
+
const t0 = Date.now();
|
|
3392
|
+
await Promise.all(
|
|
3393
|
+
// Follow redirects: /chat answers 308 → /chat/ at once, and only the target compiles.
|
|
3394
|
+
opts.startPaths.map((p) => fetch(new URL(p, server.url), { signal: AbortSignal.timeout(18e4) }).then((r) => r.arrayBuffer()).catch(() => null))
|
|
3395
|
+
);
|
|
3396
|
+
log(`warmed ${opts.startPaths.length} page(s) in ${Math.round((Date.now() - t0) / 1e3)} s`);
|
|
3397
|
+
}
|
|
3398
|
+
const skipped = [];
|
|
3399
|
+
const found = await discover(session, {
|
|
3400
|
+
baseUrl: server.url,
|
|
3401
|
+
startPaths: opts.startPaths,
|
|
3402
|
+
onlyStartPaths: Boolean(opts.startPaths?.length) && !opts.crawl,
|
|
3403
|
+
sourceDir: wtPath,
|
|
3404
|
+
signal: opts.signal,
|
|
3405
|
+
onProgress: (m) => {
|
|
3406
|
+
log(`found ${m}`);
|
|
3407
|
+
if (m.startsWith("skipped ")) skipped.push(m.slice("skipped ".length));
|
|
3408
|
+
phase("mapping", m.slice(0, 200));
|
|
3409
|
+
}
|
|
3410
|
+
});
|
|
3411
|
+
if (found.length === 0) throw new Error(noScreensMessage(skipped, devError));
|
|
3412
|
+
state.surfaces = found.slice(0, opts.maxSurfaces ?? 10).map((surface) => ({
|
|
3413
|
+
surface,
|
|
3414
|
+
status: "pending",
|
|
3415
|
+
note: null,
|
|
3416
|
+
baseline: {},
|
|
3417
|
+
iterations: []
|
|
3418
|
+
}));
|
|
3419
|
+
log(`${state.surfaces.length} screen(s) on the burndown (${found.length} found).`);
|
|
3420
|
+
persist();
|
|
3421
|
+
}
|
|
3422
|
+
log("Opening every screen once, so each capture starts from a loaded app\u2026");
|
|
3423
|
+
await session.warmUp(server.url, [...new Set(state.surfaces.map((x) => x.surface.path))]);
|
|
3424
|
+
phase("working", null);
|
|
3425
|
+
for (const s of state.surfaces) {
|
|
3426
|
+
if (opts.signal?.aborted) throw new Error("Stopped.");
|
|
3427
|
+
if (!["pending", "baseline", "iterating"].includes(s.status)) continue;
|
|
3428
|
+
if (s.status === "iterating") await revertAll(wtPath);
|
|
3429
|
+
await processSurface(s);
|
|
3430
|
+
}
|
|
3431
|
+
state.current = null;
|
|
3432
|
+
if (opts.judgeModel) {
|
|
3433
|
+
phase("reviewing", opts.judgeModel);
|
|
3434
|
+
await runJudge(opts.judgeModel);
|
|
3435
|
+
}
|
|
3436
|
+
state.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3437
|
+
phase("done", null);
|
|
3438
|
+
log(`Done. Branch ${state.branch} holds every kept change; open a draft PR from it when you are happy.`);
|
|
3439
|
+
return state;
|
|
3440
|
+
} finally {
|
|
3441
|
+
await session.close();
|
|
3442
|
+
server.stop();
|
|
3443
|
+
persist();
|
|
3444
|
+
}
|
|
3445
|
+
async function restoreWorktree(wt) {
|
|
3446
|
+
const want = expectedHead(state);
|
|
3447
|
+
const head = await headSha(wt);
|
|
3448
|
+
if (want && head !== want) {
|
|
3449
|
+
try {
|
|
3450
|
+
await resetRunBranch(wt, want);
|
|
3451
|
+
} catch {
|
|
3452
|
+
throw new Error(
|
|
3453
|
+
`The run branch ${state.branch} no longer holds its last kept commit ${want.slice(0, 8)}: it was changed outside the run. Start a new run.`
|
|
3454
|
+
);
|
|
3455
|
+
}
|
|
3456
|
+
log(`The run branch was ahead of its last saved attempt (${head.slice(0, 8)}); moved it back to ${want.slice(0, 8)}. That attempt runs again.`);
|
|
3457
|
+
}
|
|
3458
|
+
await revertAll(wt);
|
|
3459
|
+
log("Resumed: unfinished edits cleared; carrying on from the first unfinished screen.");
|
|
3460
|
+
}
|
|
3461
|
+
async function runWithNudge(runOpts) {
|
|
3462
|
+
const { nudge, ...base } = runOpts;
|
|
3463
|
+
const first = await agent.run(base);
|
|
3464
|
+
if (!first.timedOut || !agent.canResume || opts.signal?.aborted) return first;
|
|
3465
|
+
const session2 = sessionIdOf(first.stdout);
|
|
3466
|
+
if (!session2 || !await nudge.needed()) return first;
|
|
3467
|
+
log(` time is up: asking the agent to finish now (${Math.round(nudge.ms / 6e4)} more min, same session)`);
|
|
3468
|
+
const second = await agent.run({ ...base, prompt: nudge.prompt, timeoutMs: nudge.ms, resumeSession: session2 });
|
|
3469
|
+
return {
|
|
3470
|
+
exitCode: second.exitCode,
|
|
3471
|
+
timedOut: second.timedOut,
|
|
3472
|
+
durationMs: first.durationMs + second.durationMs,
|
|
3473
|
+
tail: second.tail,
|
|
3474
|
+
stdout: `${first.stdout}
|
|
3475
|
+
${second.stdout}`
|
|
3476
|
+
};
|
|
3477
|
+
}
|
|
3478
|
+
function prepareScratch(current) {
|
|
3479
|
+
const scratch = join11(wtPath, SCRATCH_DIR);
|
|
3480
|
+
rmSync3(scratch, { recursive: true, force: true });
|
|
3481
|
+
mkdirSync5(scratch, { recursive: true });
|
|
3482
|
+
if (opts.skill) {
|
|
3483
|
+
for (const [rel, buf] of Object.entries(opts.skill.files)) {
|
|
3484
|
+
const target = join11(scratch, "skill", ...rel.split("/"));
|
|
3485
|
+
mkdirSync5(dirname5(target), { recursive: true });
|
|
3486
|
+
writeFileSync5(target, buf);
|
|
3487
|
+
}
|
|
3488
|
+
}
|
|
3489
|
+
const shots = {};
|
|
3490
|
+
for (const [vp, ref] of Object.entries(current)) {
|
|
3491
|
+
writeFileSync5(join11(scratch, `${vp}.png`), readFileSync9(join11(dir, ref.png)));
|
|
3492
|
+
shots[vp] = `${SCRATCH_DIR}/${vp}.png`;
|
|
3493
|
+
}
|
|
3494
|
+
return { shots, probes: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])) };
|
|
3495
|
+
}
|
|
3496
|
+
async function planSurface(s, current, entryFiles) {
|
|
3497
|
+
const planMs = Math.min(timeoutMs, PLAN_TIMEOUT_MS);
|
|
3498
|
+
const { shots, probes } = prepareScratch(current);
|
|
3499
|
+
const maxSteps = Math.min(MAX_PLAN_STEPS, iterations);
|
|
3500
|
+
writeFileSync5(
|
|
3501
|
+
join11(wtPath, SCRATCH_DIR, "PROMPT.md"),
|
|
3502
|
+
buildPlanPacket({ surface: s.surface, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, timeBudgetMin: Math.round(planMs / 6e4), entryFiles }, maxSteps)
|
|
3503
|
+
);
|
|
3504
|
+
s.status = "iterating";
|
|
3505
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3506
|
+
state.current = { surface: s.surface.key, attempt: 1, startedAt, timeoutMs: planMs, steps: 0, lastStep: null, files: [], heartbeatAt: startedAt };
|
|
3507
|
+
phase("working", `${s.surface.label}, planning small steps`);
|
|
3508
|
+
log(` planning ${s.surface.label} in small steps\u2026`);
|
|
3509
|
+
const planLog = join11(dir, "agent", `${attemptLogBase(s.surface.key, 0).slice(0, -2)}-plan.steps.log`);
|
|
3510
|
+
try {
|
|
3511
|
+
mkdirSync5(dirname5(planLog), { recursive: true });
|
|
3512
|
+
writeFileSync5(planLog, "");
|
|
3513
|
+
} catch {
|
|
3514
|
+
}
|
|
3515
|
+
const planFile = join11(wtPath, SCRATCH_DIR, "PLAN.md");
|
|
3516
|
+
const res = await runWithNudge({
|
|
3517
|
+
cwd: wtPath,
|
|
3518
|
+
prompt: PLAN_POINTER_PROMPT,
|
|
3519
|
+
model: opts.model,
|
|
3520
|
+
timeoutMs: planMs,
|
|
3521
|
+
signal: opts.signal,
|
|
3522
|
+
nudge: {
|
|
3523
|
+
prompt: PLAN_NUDGE,
|
|
3524
|
+
ms: PLAN_NUDGE_MS,
|
|
3525
|
+
needed: async () => !existsSync6(planFile) || parsePlan(readFileSync9(planFile, "utf8")).length === 0
|
|
3526
|
+
},
|
|
3527
|
+
onLine: (line) => {
|
|
3528
|
+
for (const step of describeAgentLine(line, wtPath)) {
|
|
3529
|
+
const text2 = formatStep(step);
|
|
3530
|
+
try {
|
|
3531
|
+
appendFileSync2(planLog, `${text2}
|
|
3532
|
+
`);
|
|
3533
|
+
} catch {
|
|
3534
|
+
}
|
|
3535
|
+
emit(events, { type: "agent", surface: s.surface.key, line: text2, kind: step.kind });
|
|
3536
|
+
}
|
|
3537
|
+
}
|
|
3538
|
+
});
|
|
3539
|
+
if (opts.signal?.aborted) throw new Error("Stopped.");
|
|
3540
|
+
const fromFile = existsSync6(planFile) ? readFileSync9(planFile, "utf8") : "";
|
|
3541
|
+
const text = parsePlan(fromFile).length ? fromFile : agentFinalMessage(res.stdout) ?? assistantText(res.stdout);
|
|
3542
|
+
await revertAll(wtPath);
|
|
3543
|
+
const items = parsePlan(text, maxSteps);
|
|
3544
|
+
if (items.length === 0) {
|
|
3545
|
+
log(` no plan came back${res.timedOut ? " (the agent ran out of time)" : ""}; working on the whole screen instead.`);
|
|
3546
|
+
return null;
|
|
3547
|
+
}
|
|
3548
|
+
log(` plan: ${items.map((t, i) => `${i + 1}. ${t}`).join(" ")}`);
|
|
3549
|
+
return { steps: items.map((t) => ({ text: t, status: "pending" })), session: agent.canResume ? sessionIdOf(res.stdout) : null };
|
|
3550
|
+
}
|
|
3551
|
+
function markStep(step, info, record, status) {
|
|
3552
|
+
if (!step || !info) return;
|
|
3553
|
+
step.status = status;
|
|
3554
|
+
step.attempt = record.n;
|
|
3555
|
+
record.step = step.text;
|
|
3556
|
+
record.reason = `Step ${info.index}/${info.total}: ${record.reason}`;
|
|
3557
|
+
step.reason = record.reason;
|
|
3558
|
+
}
|
|
3559
|
+
async function capture(s) {
|
|
3560
|
+
const shots = await Promise.all(VIEWPORTS.map((vp) => captureSurface(session, state.baseUrl, s.surface, vp)));
|
|
3561
|
+
return Object.fromEntries(VIEWPORTS.map((vp, i) => [vp.name, shots[i]]));
|
|
3562
|
+
}
|
|
3563
|
+
function shotRefs(s, label, shots) {
|
|
3564
|
+
const refs = {};
|
|
3565
|
+
for (const [vp, shot] of Object.entries(shots)) {
|
|
3566
|
+
refs[vp] = { png: savePng(dir, `shots/${s.surface.key}/${label}-${vp}.png`, shot.png), probes: shot.probes, penalty: probePenalty(shot.probes) };
|
|
3567
|
+
}
|
|
3568
|
+
return refs;
|
|
3569
|
+
}
|
|
3570
|
+
async function processSurface(s) {
|
|
3571
|
+
log(`\u25B6 ${s.surface.label}`);
|
|
3572
|
+
if (Object.keys(s.baseline).length === 0) {
|
|
3573
|
+
try {
|
|
3574
|
+
s.baseline = shotRefs(s, "baseline", await capture(s));
|
|
3575
|
+
} catch (err) {
|
|
3576
|
+
s.status = "blocked";
|
|
3577
|
+
s.note = `Could not capture the screen: ${err.message.slice(0, 200)}`;
|
|
3578
|
+
persist();
|
|
3579
|
+
return;
|
|
3580
|
+
}
|
|
3581
|
+
}
|
|
3582
|
+
s.status = "baseline";
|
|
3583
|
+
persist();
|
|
3584
|
+
const entryFiles = screenFiles(wtPath, s.surface.path);
|
|
3585
|
+
const lastKept2 = [...s.iterations].reverse().find((i) => i.outcome === "accepted");
|
|
3586
|
+
let current = lastKept2 ? lastKept2.after : s.baseline;
|
|
3587
|
+
const last = s.iterations[s.iterations.length - 1];
|
|
3588
|
+
let previousRejection = last?.outcome === "rejected" ? last.reason : last?.outcome === "agent_failed" && last.timedOut ? timeoutNote(timeoutMs) : null;
|
|
3589
|
+
if (opts.steps && (s.plan === void 0 || s.plan === null && s.iterations.every((i) => i.outcome === "agent_failed"))) {
|
|
3590
|
+
s.plan = await planSurface(s, current, entryFiles);
|
|
3591
|
+
persist();
|
|
3592
|
+
}
|
|
3593
|
+
const plan = opts.steps && s.plan?.steps.length ? s.plan : null;
|
|
3594
|
+
let carrySession = plan && agent.canResume && !s.iterations.some((i) => i.outcome !== "accepted") ? plan.session ?? null : null;
|
|
3595
|
+
const pending = plan ? plan.steps.filter((p) => p.status === "pending").length : 0;
|
|
3596
|
+
const settled = last?.outcome === "no_change" || last?.outcome === "agent_failed" && !last.timedOut;
|
|
3597
|
+
const first = s.iterations.length + 1;
|
|
3598
|
+
const lastAttempt = plan ? first + pending - 1 : settled ? 0 : iterations;
|
|
3599
|
+
for (let n = first; n <= lastAttempt; n++) {
|
|
3600
|
+
const step = plan?.steps.find((p) => p.status === "pending") ?? null;
|
|
3601
|
+
const stepInfo = step && plan ? { text: step.text, index: plan.steps.indexOf(step) + 1, total: plan.steps.length, done: plan.steps.filter((p) => p.status === "done").map((p) => p.text) } : null;
|
|
3602
|
+
const { shots, probes } = prepareScratch(current);
|
|
3603
|
+
writeFileSync5(
|
|
3604
|
+
join11(wtPath, SCRATCH_DIR, "PROMPT.md"),
|
|
3605
|
+
buildPacket({ surface: s.surface, iteration: n, shots, probes, designFiles, skillText, skillDir: `${SCRATCH_DIR}/skill`, previousRejection, timeBudgetMin: Math.round(timeoutMs / 6e4), entryFiles, step: stepInfo })
|
|
3606
|
+
);
|
|
3607
|
+
s.status = "iterating";
|
|
3608
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3609
|
+
const live = { surface: s.surface.key, attempt: n, startedAt, timeoutMs, steps: 0, lastStep: null, files: [], heartbeatAt: startedAt };
|
|
3610
|
+
state.current = live;
|
|
3611
|
+
phase("working", stepInfo ? `${s.surface.label}, step ${stepInfo.index} of ${stepInfo.total}` : `${s.surface.label}, attempt ${n} of ${iterations}`);
|
|
3612
|
+
const steps = [];
|
|
3613
|
+
const logDir = join11(dir, "agent");
|
|
3614
|
+
const logBase = join11(logDir, attemptLogBase(s.surface.key, n));
|
|
3615
|
+
try {
|
|
3616
|
+
mkdirSync5(logDir, { recursive: true });
|
|
3617
|
+
writeFileSync5(`${logBase}.steps.log`, "");
|
|
3618
|
+
} catch {
|
|
3619
|
+
}
|
|
3620
|
+
const heartbeat = setInterval(() => {
|
|
3621
|
+
void changedFiles(wtPath).then((f) => {
|
|
3622
|
+
if (state.current !== live) return;
|
|
3623
|
+
live.files = f.slice(0, 50);
|
|
3624
|
+
live.heartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3625
|
+
persist();
|
|
3626
|
+
}).catch(() => void 0);
|
|
3627
|
+
}, HEARTBEAT_MS);
|
|
3628
|
+
let res;
|
|
3629
|
+
try {
|
|
3630
|
+
res = await runWithNudge({
|
|
3631
|
+
cwd: wtPath,
|
|
3632
|
+
prompt: carrySession ? `${POINTER_PROMPT}
|
|
3633
|
+
|
|
3634
|
+
This continues your session for this screen: you have already read its files. Do not read them again unless you need a file you have not seen. Make this step's change now.` : POINTER_PROMPT,
|
|
3635
|
+
model: opts.model,
|
|
3636
|
+
timeoutMs,
|
|
3637
|
+
signal: opts.signal,
|
|
3638
|
+
resumeSession: carrySession ?? void 0,
|
|
3639
|
+
nudge: {
|
|
3640
|
+
prompt: EDIT_NUDGE,
|
|
3641
|
+
ms: EDIT_NUDGE_MS,
|
|
3642
|
+
needed: async () => (await changedFiles(wtPath).catch(() => [])).length === 0
|
|
3643
|
+
},
|
|
3644
|
+
onLine: (line) => {
|
|
3645
|
+
for (const step2 of describeAgentLine(line, wtPath)) {
|
|
3646
|
+
const text = formatStep(step2);
|
|
3647
|
+
steps.push(text);
|
|
3648
|
+
if (steps.length > 400) steps.splice(0, 200);
|
|
3649
|
+
live.steps++;
|
|
3650
|
+
live.lastStep = text;
|
|
3651
|
+
try {
|
|
3652
|
+
appendFileSync2(`${logBase}.steps.log`, `${text}
|
|
3653
|
+
`);
|
|
3654
|
+
} catch {
|
|
3655
|
+
}
|
|
3656
|
+
emit(events, { type: "agent", surface: s.surface.key, line: text, kind: step2.kind });
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
});
|
|
3660
|
+
} finally {
|
|
3661
|
+
clearInterval(heartbeat);
|
|
3662
|
+
}
|
|
3663
|
+
try {
|
|
3664
|
+
mkdirSync5(logDir, { recursive: true });
|
|
3665
|
+
writeFileSync5(`${logBase}.log`, res.stdout);
|
|
3666
|
+
} catch {
|
|
3667
|
+
}
|
|
3668
|
+
if (opts.signal?.aborted) throw new Error("Stopped.");
|
|
3669
|
+
const files = await changedFiles(wtPath);
|
|
3670
|
+
const record = {
|
|
3671
|
+
n,
|
|
3672
|
+
agent: agent.name,
|
|
3673
|
+
model: opts.model ?? null,
|
|
3674
|
+
startedAt,
|
|
3675
|
+
durationMs: res.durationMs,
|
|
3676
|
+
outcome: "no_change",
|
|
3677
|
+
reason: "",
|
|
3678
|
+
commitSha: null,
|
|
3679
|
+
pixelDiff: {},
|
|
3680
|
+
after: {},
|
|
3681
|
+
diffPng: {},
|
|
3682
|
+
logTail: (steps.length ? steps.join("\n") : res.tail).slice(-2e3)
|
|
3683
|
+
};
|
|
3684
|
+
if ((res.exitCode !== 0 || res.timedOut) && files.length === 0) {
|
|
3685
|
+
record.outcome = "agent_failed";
|
|
3686
|
+
record.timedOut = res.timedOut;
|
|
3687
|
+
const minutes = Math.round(timeoutMs / 6e4);
|
|
3688
|
+
record.reason = res.timedOut ? `The agent ran out of time (${minutes} min) after ${steps.length} steps without editing anything.` : `The agent exited with code ${res.exitCode}.`;
|
|
3689
|
+
markStep(step, stepInfo, record, "failed");
|
|
3690
|
+
s.iterations.push(record);
|
|
3691
|
+
persist();
|
|
3692
|
+
log(` attempt ${n}: ${record.reason}`);
|
|
3693
|
+
if (!res.timedOut) break;
|
|
3694
|
+
previousRejection = timeoutNote(timeoutMs);
|
|
3695
|
+
continue;
|
|
3696
|
+
}
|
|
3697
|
+
let afterShots = null;
|
|
3698
|
+
if (files.length > 0) {
|
|
3699
|
+
await new Promise((r) => setTimeout(r, 2e3));
|
|
3700
|
+
afterShots = await capture(s).catch(() => null);
|
|
3701
|
+
const beforeProbes = Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes]));
|
|
3702
|
+
const afterProbes = afterShots ? Object.fromEntries(Object.entries(afterShots).map(([vp, r]) => [vp, r.probes])) : null;
|
|
3703
|
+
if (afterShots && afterProbes && clsNeedsSecondLook(beforeProbes, afterProbes)) {
|
|
3704
|
+
await new Promise((r) => setTimeout(r, 2e3));
|
|
3705
|
+
const again = await capture(s).catch(() => null);
|
|
3706
|
+
if (again) {
|
|
3707
|
+
const steady = steadierCls(afterProbes, Object.fromEntries(Object.entries(again).map(([vp, r]) => [vp, r.probes])));
|
|
3708
|
+
for (const vp of Object.keys(afterShots)) afterShots[vp] = { ...afterShots[vp], probes: steady[vp] };
|
|
3709
|
+
}
|
|
3710
|
+
}
|
|
3711
|
+
}
|
|
3712
|
+
const ratios = {};
|
|
3713
|
+
if (afterShots) {
|
|
3714
|
+
record.after = shotRefs(s, `iter${n}`, afterShots);
|
|
3715
|
+
for (const [vp, shot] of Object.entries(afterShots)) {
|
|
3716
|
+
const before = readFileSync9(join11(dir, current[vp].png));
|
|
3717
|
+
const d = pixelDiff(before, shot.png);
|
|
3718
|
+
ratios[vp] = Math.round(d.ratio * 1e4) / 1e4;
|
|
3719
|
+
record.diffPng[vp] = savePng(dir, `shots/${s.surface.key}/iter${n}-${vp}-diff.png`, d.diffPng);
|
|
3720
|
+
record.changes = { ...record.changes, [vp]: { width: d.width, height: d.height, boxes: d.regions } };
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
record.pixelDiff = ratios;
|
|
3724
|
+
const verdict = decide({
|
|
3725
|
+
filesChanged: files.length,
|
|
3726
|
+
before: Object.fromEntries(Object.entries(current).map(([vp, r]) => [vp, r.probes])),
|
|
3727
|
+
after: afterShots ? Object.fromEntries(Object.entries(afterShots).map(([vp, r]) => [vp, r.probes])) : null,
|
|
3728
|
+
pixelRatios: ratios,
|
|
3729
|
+
keepInvisible: opts.keepInvisible !== false
|
|
3730
|
+
});
|
|
3731
|
+
record.outcome = verdict.outcome;
|
|
3732
|
+
record.reason = verdict.reason;
|
|
3733
|
+
if (verdict.outcome === "no_change" && files.length === 0) {
|
|
3734
|
+
const why = explainNoEdit(agentFinalMessage(res.stdout));
|
|
3735
|
+
record.outcome = why.outcome;
|
|
3736
|
+
record.reason = why.reason;
|
|
3737
|
+
}
|
|
3738
|
+
record.timedOut = res.timedOut || void 0;
|
|
3739
|
+
if (step && record.outcome === "accepted" && files.length > MAX_STEP_FILES) {
|
|
3740
|
+
record.outcome = "rejected";
|
|
3741
|
+
record.reason = `Too big for one step: ${files.length} files changed (at most ${MAX_STEP_FILES}). Make a smaller change.`;
|
|
3742
|
+
}
|
|
3743
|
+
if (record.outcome === "accepted") record.needsReview = verdict.needsReview || void 0;
|
|
3744
|
+
if (record.outcome === "accepted" && opts.checker) {
|
|
3745
|
+
log(` checking with ${opts.checker.model}\u2026`);
|
|
3746
|
+
phase("working", `${s.surface.label}: ${opts.checker.model} reviews the change`);
|
|
3747
|
+
const vp = afterShots?.mobile ? "mobile" : Object.keys(afterShots ?? {})[0];
|
|
3748
|
+
const visible = !record.needsReview && vp && afterShots?.[vp];
|
|
3749
|
+
const review = await checkStep({
|
|
3750
|
+
dir,
|
|
3751
|
+
name: `${s.surface.key}-iter${n}`,
|
|
3752
|
+
screen: s.surface.label,
|
|
3753
|
+
step: step?.text ?? "Improve this screen for the person using it.",
|
|
3754
|
+
visual: visible ? { before: readFileSync9(join11(dir, current[vp].png)), after: afterShots[vp].png, regions: record.changes?.[vp]?.boxes ?? [] } : null,
|
|
3755
|
+
diff: await diffText(wtPath).catch(() => ""),
|
|
3756
|
+
repoDir: wtPath,
|
|
3757
|
+
spec: opts.checker,
|
|
3758
|
+
signal: opts.signal
|
|
3759
|
+
});
|
|
3760
|
+
record.checker = review;
|
|
3761
|
+
if (review.verdict === "revert") {
|
|
3762
|
+
record.outcome = "rejected";
|
|
3763
|
+
record.reason = `Rolled back by ${review.model}: ${review.summary}`.slice(0, 600);
|
|
3764
|
+
} else if (review.error) {
|
|
3765
|
+
log(` ${review.model} review failed: ${review.error}`);
|
|
3766
|
+
record.reason += ` The ${review.model} review could not run (${review.error.slice(0, 160)}), so the measurements decided.`;
|
|
3767
|
+
} else {
|
|
3768
|
+
record.reason += ` ${review.model}: ${review.verdict === "keep" ? "agrees" : "unsure, kept on the measurements"}.`;
|
|
3769
|
+
}
|
|
3770
|
+
}
|
|
3771
|
+
markStep(step, stepInfo, record, record.outcome === "accepted" ? "done" : record.outcome === "no_change" ? "skipped" : "failed");
|
|
3772
|
+
log(` attempt ${n}: ${record.reason}`);
|
|
3773
|
+
if (record.outcome === "accepted") {
|
|
3774
|
+
record.commitSha = await commitAll(wtPath, commitMessage(s.surface.path, s.surface.label, step?.text ?? null, record.reason));
|
|
3775
|
+
current = record.after;
|
|
3776
|
+
s.status = "accepted";
|
|
3777
|
+
s.iterations.push(record);
|
|
3778
|
+
persist();
|
|
3779
|
+
carrySession = agent.canResume ? sessionIdOf(res.stdout) ?? carrySession : null;
|
|
3780
|
+
continue;
|
|
3781
|
+
}
|
|
3782
|
+
await revertAll(wtPath);
|
|
3783
|
+
s.iterations.push(record);
|
|
3784
|
+
persist();
|
|
3785
|
+
if (verdict.outcome === "no_change" && (!step || record.outcome === "agent_failed")) break;
|
|
3786
|
+
previousRejection = record.outcome === "rejected" ? record.reason : null;
|
|
3787
|
+
carrySession = null;
|
|
3788
|
+
}
|
|
3789
|
+
const kept = s.iterations.filter((i) => i.outcome === "accepted");
|
|
3790
|
+
if (kept.length > 0) await checkRegressions(s);
|
|
3791
|
+
if (kept.length > 0) {
|
|
3792
|
+
s.status = "accepted";
|
|
3793
|
+
s.note = kept[kept.length - 1].reason;
|
|
3794
|
+
} else {
|
|
3795
|
+
const rejected = s.iterations.some((i) => i.outcome === "rejected" || i.outcome === "capture_failed");
|
|
3796
|
+
const neverFinished = s.iterations.length > 0 && s.iterations.every((i) => i.outcome === "agent_failed");
|
|
3797
|
+
s.status = rejected ? "reverted" : neverFinished ? "blocked" : "skipped";
|
|
3798
|
+
s.note = s.iterations[s.iterations.length - 1]?.reason ?? null;
|
|
3799
|
+
}
|
|
3800
|
+
rmSync3(join11(wtPath, SCRATCH_DIR), { recursive: true, force: true });
|
|
3801
|
+
persist();
|
|
3802
|
+
}
|
|
3803
|
+
async function runJudge(model) {
|
|
3804
|
+
state.judgeModel = model;
|
|
3805
|
+
const changed = state.surfaces.filter((x) => x.iterations.some((i) => i.outcome === "accepted"));
|
|
3806
|
+
if (changed.length === 0) return;
|
|
3807
|
+
log(`Reviewing ${changed.length} changed screen(s) with ${model}\u2026`);
|
|
3808
|
+
for (const s of changed) {
|
|
3809
|
+
if (s.judge?.length) continue;
|
|
3810
|
+
const verdicts = [];
|
|
3811
|
+
for (const vp of VIEWPORTS) {
|
|
3812
|
+
const v = await judgeSurface(s, vp.name, { dir, repoRoot: wtPath, designFiles, model });
|
|
3813
|
+
if (v) verdicts.push(v);
|
|
3814
|
+
}
|
|
3815
|
+
s.judge = verdicts;
|
|
3816
|
+
const errors = verdicts.filter((v) => v.error);
|
|
3817
|
+
if (errors.length) log(` review of ${s.surface.label} failed: ${errors[0].error}`);
|
|
3818
|
+
const prefersBefore = verdicts.filter((v) => !v.error && v.preferred === "before" && v.confidence !== "low");
|
|
3819
|
+
if (prefersBefore.length) {
|
|
3820
|
+
log(` \u26A0 reviewer prefers the original ${s.surface.label} (${prefersBefore.map((v) => v.viewport).join(", ")}) \u2014 check it before merging`);
|
|
3821
|
+
}
|
|
3822
|
+
persist();
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3825
|
+
async function checkRegressions(changed) {
|
|
3826
|
+
const finished = state.surfaces.filter((x) => x !== changed && ["accepted", "reverted", "skipped"].includes(x.status)).slice(-(opts.regressionSample ?? 5));
|
|
3827
|
+
const desktop = VIEWPORTS[0];
|
|
3828
|
+
for (const other of finished) {
|
|
3829
|
+
const ref = referenceShot(other, desktop.name);
|
|
3830
|
+
if (!ref) continue;
|
|
3831
|
+
const refPng = readFileSync9(join11(dir, ref.png));
|
|
3832
|
+
const moved = (png) => {
|
|
3833
|
+
const diff = pixelDiff(refPng, png);
|
|
3834
|
+
return diff.contentRatio > REGRESSION_CONTENT_RATIO && diff.changedPixels > REGRESSION_MIN_PIXELS ? diff : null;
|
|
3835
|
+
};
|
|
3836
|
+
let now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null);
|
|
3837
|
+
if (!now || !moved(now.png)) continue;
|
|
3838
|
+
await new Promise((r) => setTimeout(r, 3e3));
|
|
3839
|
+
now = await captureSurface(session, state.baseUrl, other.surface, desktop).catch(() => null);
|
|
3840
|
+
const d = now ? moved(now.png) : null;
|
|
3841
|
+
if (now && d) {
|
|
3842
|
+
const pct = (d.contentRatio * 100).toFixed(0);
|
|
3843
|
+
other.status = "regressed";
|
|
3844
|
+
other.note = `${pct}% of this screen changed after "${changed.surface.label}" was kept. Check whether a shared component or token moved.`;
|
|
3845
|
+
savePng(dir, `shots/${other.surface.key}/regressed-${desktop.name}.png`, now.png);
|
|
3846
|
+
log(` \u26A0 ${other.surface.label}: ${pct}% of the screen moved \u2014 marked regressed`);
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3849
|
+
persist();
|
|
3850
|
+
}
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
|
|
3854
|
+
// src/sync.ts
|
|
3855
|
+
import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
|
|
3856
|
+
import { join as join12 } from "path";
|
|
3857
|
+
var CLOUD_API_ENDPOINT = "https://dxptnwrhwsqckaftyymj.supabase.co/functions/v1/api";
|
|
3858
|
+
var VIEWPORT_NAMES = ["desktop", "mobile"];
|
|
3859
|
+
var UPLOAD_BATCH = 40;
|
|
3860
|
+
function syncConfigFromEnv(env = process.env) {
|
|
3861
|
+
const apiKey = env.MUSHI_API_KEY?.trim();
|
|
3862
|
+
const projectId = env.MUSHI_PROJECT_ID?.trim();
|
|
3863
|
+
if (!apiKey || !projectId) return null;
|
|
3864
|
+
return {
|
|
3865
|
+
apiKey,
|
|
3866
|
+
projectId,
|
|
3867
|
+
endpoint: trimTrailingSlashes(env.MUSHI_API_ENDPOINT?.trim() || CLOUD_API_ENDPOINT),
|
|
3868
|
+
mode: env.GITHUB_ACTIONS === "true" ? "cloud" : "local"
|
|
3869
|
+
};
|
|
3870
|
+
}
|
|
3871
|
+
function trimTrailingSlashes(s) {
|
|
3872
|
+
let end = s.length;
|
|
3873
|
+
while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
|
|
3874
|
+
return s.slice(0, end);
|
|
3875
|
+
}
|
|
3876
|
+
function probeSummary(p) {
|
|
3877
|
+
if (!p) return null;
|
|
3878
|
+
return {
|
|
3879
|
+
axe: p.axe.map((v) => ({ id: v.id, impact: v.impact, help: v.help.slice(0, 300), count: v.count })).slice(0, 60),
|
|
3880
|
+
overflowX: p.overflowX,
|
|
3881
|
+
smallTargets: p.smallTargets,
|
|
3882
|
+
consoleErrors: p.consoleErrors.length,
|
|
3883
|
+
cls: p.cls
|
|
3884
|
+
};
|
|
3885
|
+
}
|
|
3886
|
+
function syncableStep(line) {
|
|
3887
|
+
if (/^\[(read|edit)\] \S/.test(line)) return line.slice(0, 300);
|
|
3888
|
+
if (line.startsWith("[run] ")) return "[run] a command";
|
|
3889
|
+
if (line.startsWith("[find] ")) return "[find] a search";
|
|
3890
|
+
if (line === "[done] Finished") return line;
|
|
3891
|
+
return null;
|
|
3892
|
+
}
|
|
3893
|
+
function syncableSteps(log) {
|
|
3894
|
+
const kept = (log ?? "").split("\n").map(syncableStep).filter((l) => l !== null);
|
|
3895
|
+
return kept.length ? kept.join("\n").slice(-2e3) : null;
|
|
3896
|
+
}
|
|
3897
|
+
function worstPenalty(shots) {
|
|
3898
|
+
const scores = Object.values(shots).flatMap((r) => r && typeof r.penalty === "number" ? [r.penalty] : []);
|
|
3899
|
+
return scores.length ? Math.max(...scores) : null;
|
|
3900
|
+
}
|
|
3901
|
+
function lastKept(s) {
|
|
3902
|
+
return [...s.iterations].reverse().find((i) => i.outcome === "accepted") ?? null;
|
|
3903
|
+
}
|
|
3904
|
+
function wantedShots(state) {
|
|
3905
|
+
const out = [];
|
|
3906
|
+
for (const s of state.surfaces) {
|
|
3907
|
+
const key = s.surface.key;
|
|
3908
|
+
const kept = lastKept(s);
|
|
3909
|
+
for (const vp of VIEWPORT_NAMES) {
|
|
3910
|
+
const before = s.baseline[vp]?.png;
|
|
3911
|
+
if (before) out.push({ name: `${key}/before-${vp}.png`, rel: before });
|
|
3912
|
+
const after = kept?.after[vp]?.png;
|
|
3913
|
+
if (after) out.push({ name: `${key}/after-${vp}.png`, rel: after });
|
|
3914
|
+
const diff = kept?.diffPng[vp];
|
|
3915
|
+
if (diff) out.push({ name: `${key}/diff-${vp}.png`, rel: diff });
|
|
3916
|
+
for (const it of s.iterations) {
|
|
3917
|
+
if (it.after[vp]?.png) out.push({ name: `${key}/iter${it.n}-after-${vp}.png`, rel: it.after[vp].png });
|
|
3918
|
+
if (it.diffPng[vp]) out.push({ name: `${key}/iter${it.n}-diff-${vp}.png`, rel: it.diffPng[vp] });
|
|
3919
|
+
}
|
|
3920
|
+
}
|
|
3921
|
+
}
|
|
3922
|
+
return out;
|
|
3923
|
+
}
|
|
3924
|
+
function toSnapshot(state, finished, uploaded, mode = "local") {
|
|
3925
|
+
const have = (name) => uploaded.has(name) ? name : null;
|
|
3926
|
+
const status = state.stopped ? "stopped" : state.phase === "failed" ? "failed" : finished ? "done" : "running";
|
|
3927
|
+
return {
|
|
3928
|
+
mode,
|
|
3929
|
+
status,
|
|
3930
|
+
agent: state.agent,
|
|
3931
|
+
model: state.model,
|
|
3932
|
+
judge_model: state.judgeModel ?? null,
|
|
3933
|
+
skill: state.skill?.name?.slice(0, 120) ?? null,
|
|
3934
|
+
base_ref: state.baseRef?.slice(0, 200) ?? null,
|
|
3935
|
+
phase: state.phase ?? null,
|
|
3936
|
+
phase_detail: state.phaseDetail?.slice(0, 300) ?? null,
|
|
3937
|
+
current_surface: state.current?.surface ?? null,
|
|
3938
|
+
current_attempt: state.current?.attempt ?? null,
|
|
3939
|
+
current_progress: state.current ? {
|
|
3940
|
+
steps: state.current.steps ?? 0,
|
|
3941
|
+
last_step: state.current.lastStep ? syncableStep(state.current.lastStep) : null,
|
|
3942
|
+
files: (state.current.files ?? []).slice(0, 20).map((f) => f.slice(0, 300)),
|
|
3943
|
+
started_at: state.current.startedAt,
|
|
3944
|
+
timeout_ms: state.current.timeoutMs ?? null
|
|
3945
|
+
} : null,
|
|
3946
|
+
error: state.error?.slice(0, 1e3) ?? null,
|
|
3947
|
+
branch: state.branch,
|
|
3948
|
+
base_sha: state.baseSha,
|
|
3949
|
+
cli_version: null,
|
|
3950
|
+
...state.pr ? { pr: { url: state.pr.url, number: state.pr.number } } : {},
|
|
3951
|
+
started_at: state.createdAt,
|
|
3952
|
+
finished_at: finished || status === "failed" ? state.finishedAt ?? (/* @__PURE__ */ new Date()).toISOString() : null,
|
|
3953
|
+
surfaces: state.surfaces.map((s) => {
|
|
3954
|
+
const kept = lastKept(s);
|
|
3955
|
+
const key = s.surface.key;
|
|
3956
|
+
const shots = {};
|
|
3957
|
+
for (const vp of VIEWPORT_NAMES) {
|
|
3958
|
+
for (const kind of ["before", "after", "diff"]) {
|
|
3959
|
+
const name = have(`${key}/${kind}-${vp}.png`);
|
|
3960
|
+
if (name) shots[`${kind}-${vp}`] = name;
|
|
3961
|
+
}
|
|
3962
|
+
}
|
|
3963
|
+
return {
|
|
3964
|
+
surface_key: key,
|
|
3965
|
+
kind: s.surface.kind,
|
|
3966
|
+
path: s.surface.path,
|
|
3967
|
+
label: s.surface.label.slice(0, 300),
|
|
3968
|
+
status: s.status,
|
|
3969
|
+
note: s.note?.slice(0, 1e3) ?? null,
|
|
3970
|
+
// Small-steps mode: the plan as a checklist (the step texts are the agent's own plan, file names included).
|
|
3971
|
+
plan: s.plan?.steps.length ? s.plan.steps.slice(0, 8).map((p) => ({ text: p.text.slice(0, 300), status: p.status, attempt: p.attempt ?? null })) : null,
|
|
3972
|
+
penalty_before: worstPenalty(s.baseline),
|
|
3973
|
+
penalty_after: kept ? worstPenalty(kept.after) : null,
|
|
3974
|
+
probe_before: probeSummary(s.baseline.desktop?.probes),
|
|
3975
|
+
probe_after: probeSummary(kept?.after.desktop?.probes),
|
|
3976
|
+
judge: s.judge?.length ? s.judge.map((j) => ({
|
|
3977
|
+
viewport: j.viewport,
|
|
3978
|
+
model: j.model,
|
|
3979
|
+
preferred: j.preferred,
|
|
3980
|
+
confidence: j.confidence,
|
|
3981
|
+
summary: j.summary.slice(0, 2e3),
|
|
3982
|
+
better: j.better.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),
|
|
3983
|
+
worse: j.worse.slice(0, 20).map((c) => ({ what: c.what.slice(0, 500), why: c.why.slice(0, 500) })),
|
|
3984
|
+
...j.error ? { error: j.error.slice(0, 500) } : {}
|
|
3985
|
+
})) : null,
|
|
3986
|
+
thumbs: { before: shots["before-desktop"] ?? null, after: shots["after-desktop"] ?? null, diff: shots["diff-desktop"] ?? null },
|
|
3987
|
+
shots,
|
|
3988
|
+
iterations: s.iterations.map((it) => {
|
|
3989
|
+
const itShots = {};
|
|
3990
|
+
for (const vp of VIEWPORT_NAMES) {
|
|
3991
|
+
for (const kind of ["after", "diff"]) {
|
|
3992
|
+
const name = have(`${key}/iter${it.n}-${kind}-${vp}.png`);
|
|
3993
|
+
if (name) itShots[`${kind}-${vp}`] = name;
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
return {
|
|
3997
|
+
n: it.n,
|
|
3998
|
+
agent: it.agent,
|
|
3999
|
+
model: it.model,
|
|
4000
|
+
duration_ms: it.durationMs,
|
|
4001
|
+
outcome: it.outcome,
|
|
4002
|
+
reason: it.reason.slice(0, 1e3),
|
|
4003
|
+
commit_sha: it.commitSha,
|
|
4004
|
+
pixel_diff: it.pixelDiff,
|
|
4005
|
+
penalty_after: worstPenalty(it.after),
|
|
4006
|
+
steps: syncableSteps(it.logTail),
|
|
4007
|
+
step: it.step?.slice(0, 300) ?? null,
|
|
4008
|
+
shots: itShots
|
|
4009
|
+
};
|
|
4010
|
+
})
|
|
4011
|
+
};
|
|
4012
|
+
})
|
|
4013
|
+
};
|
|
4014
|
+
}
|
|
4015
|
+
function startSync(dir, cfg, events, log) {
|
|
4016
|
+
const uploaded = /* @__PURE__ */ new Map();
|
|
4017
|
+
let timer = null;
|
|
4018
|
+
let running = Promise.resolve();
|
|
4019
|
+
let lastError = null;
|
|
4020
|
+
let warned = false;
|
|
4021
|
+
const headers = {
|
|
4022
|
+
Authorization: `Bearer ${cfg.apiKey}`,
|
|
4023
|
+
"X-Mushi-Api-Key": cfg.apiKey,
|
|
4024
|
+
"X-Mushi-Project": cfg.projectId,
|
|
4025
|
+
"Content-Type": "application/json"
|
|
4026
|
+
};
|
|
4027
|
+
async function api(method, path, body) {
|
|
4028
|
+
const res = await fetch(`${cfg.endpoint}/v1/admin/projects/${cfg.projectId}/ux-runs/${path}`, {
|
|
4029
|
+
method,
|
|
4030
|
+
headers,
|
|
4031
|
+
body: JSON.stringify(body),
|
|
4032
|
+
signal: AbortSignal.timeout(3e4)
|
|
4033
|
+
});
|
|
4034
|
+
const json = await res.json().catch(() => null);
|
|
4035
|
+
if (json?.error?.code === "INSUFFICIENT_SCOPE") {
|
|
4036
|
+
throw new Error("this Mushi key cannot write to the console. Run `mushi login` (browser sign-in) for a key that can, then retry");
|
|
4037
|
+
}
|
|
4038
|
+
if (!res.ok || !json?.ok) throw new Error(json?.error?.message ?? `HTTP ${res.status}`);
|
|
4039
|
+
return json.data;
|
|
4040
|
+
}
|
|
4041
|
+
async function uploadShots(state) {
|
|
4042
|
+
const todo = wantedShots(state).filter((w) => uploaded.get(w.name) !== w.rel);
|
|
4043
|
+
for (let i = 0; i < todo.length; i += UPLOAD_BATCH) {
|
|
4044
|
+
const batch = todo.slice(i, i + UPLOAD_BATCH);
|
|
4045
|
+
const data = await api("POST", `${state.runId}/uploads`, { names: batch.map((w) => w.name) });
|
|
4046
|
+
for (const u of data.uploads) {
|
|
4047
|
+
const want = batch.find((w) => w.name === u.name);
|
|
4048
|
+
if (!want) continue;
|
|
4049
|
+
const png = cropTop(readFileSync10(join12(dir, want.rel)), 2400);
|
|
4050
|
+
const put = await fetch(u.signedUrl, {
|
|
4051
|
+
method: "PUT",
|
|
4052
|
+
headers: { "Content-Type": "image/png", "x-upsert": "true" },
|
|
4053
|
+
body: new Uint8Array(png),
|
|
4054
|
+
signal: AbortSignal.timeout(6e4)
|
|
4055
|
+
});
|
|
4056
|
+
if (!put.ok) throw new Error(`screenshot upload failed (HTTP ${put.status})`);
|
|
4057
|
+
uploaded.set(want.name, want.rel);
|
|
4058
|
+
}
|
|
4059
|
+
}
|
|
4060
|
+
}
|
|
4061
|
+
async function syncOnce(finished) {
|
|
4062
|
+
const state = loadState(dir);
|
|
4063
|
+
if (!state) return;
|
|
4064
|
+
try {
|
|
4065
|
+
await api("PUT", state.runId, toSnapshot(state, false, uploaded, cfg.mode));
|
|
4066
|
+
await uploadShots(state);
|
|
4067
|
+
await api("PUT", state.runId, toSnapshot(state, finished, uploaded, cfg.mode));
|
|
4068
|
+
lastError = null;
|
|
4069
|
+
} catch (err) {
|
|
4070
|
+
lastError = err.message;
|
|
4071
|
+
if (!warned) {
|
|
4072
|
+
log(`Console sync failed (will retry): ${lastError}`);
|
|
4073
|
+
warned = true;
|
|
4074
|
+
}
|
|
4075
|
+
}
|
|
4076
|
+
}
|
|
4077
|
+
const schedule = () => {
|
|
4078
|
+
if (timer) return;
|
|
4079
|
+
timer = setTimeout(() => {
|
|
4080
|
+
timer = null;
|
|
4081
|
+
running = running.then(() => syncOnce(false));
|
|
4082
|
+
}, 1500);
|
|
4083
|
+
};
|
|
4084
|
+
events.on("event", (e) => {
|
|
4085
|
+
if (e.type === "state" || e.type === "phase") schedule();
|
|
4086
|
+
});
|
|
4087
|
+
return {
|
|
4088
|
+
async finish() {
|
|
4089
|
+
if (timer) clearTimeout(timer);
|
|
4090
|
+
timer = null;
|
|
4091
|
+
await running;
|
|
4092
|
+
await syncOnce(true);
|
|
4093
|
+
return lastError;
|
|
4094
|
+
}
|
|
4095
|
+
};
|
|
4096
|
+
}
|
|
4097
|
+
export {
|
|
4098
|
+
AGENTS,
|
|
4099
|
+
DEFAULT_JUDGE_MODEL,
|
|
4100
|
+
POINTER_PROMPT,
|
|
4101
|
+
VIEWPORTS,
|
|
4102
|
+
buildPacket,
|
|
4103
|
+
captureSurface,
|
|
4104
|
+
cropTop,
|
|
4105
|
+
cursorCloudAdapter,
|
|
4106
|
+
cursorModel,
|
|
4107
|
+
dHash,
|
|
4108
|
+
decide,
|
|
4109
|
+
discover,
|
|
4110
|
+
findDesignFiles,
|
|
4111
|
+
getAgent,
|
|
4112
|
+
hammingHex,
|
|
4113
|
+
httpsRepoUrl,
|
|
4114
|
+
installGuard,
|
|
4115
|
+
isDestructiveLabel,
|
|
4116
|
+
isRequestAllowed,
|
|
4117
|
+
judgeSurface,
|
|
4118
|
+
loadState,
|
|
4119
|
+
newRunId,
|
|
4120
|
+
nextRoutePath,
|
|
4121
|
+
normalizeLink,
|
|
4122
|
+
openSession,
|
|
4123
|
+
pixelDiff,
|
|
4124
|
+
probePenalty,
|
|
4125
|
+
quoteArg,
|
|
4126
|
+
reactRouterPaths,
|
|
4127
|
+
routesFromSource,
|
|
4128
|
+
runDir,
|
|
4129
|
+
runProbes,
|
|
4130
|
+
safeShotPath,
|
|
4131
|
+
saveState,
|
|
4132
|
+
settle,
|
|
4133
|
+
sitemapPaths,
|
|
4134
|
+
startDashboard,
|
|
4135
|
+
startLoop,
|
|
4136
|
+
startSync,
|
|
4137
|
+
surfaceKey,
|
|
4138
|
+
syncConfigFromEnv,
|
|
4139
|
+
toSnapshot,
|
|
4140
|
+
unshuffle
|
|
4141
|
+
};
|
|
4142
|
+
//# sourceMappingURL=index.js.map
|