Files
plan2code/scripts/capture-app-shots.mjs
T

323 lines
13 KiB
JavaScript

// The desktop app's five pictures for the docs, taken by
// `node scripts/capture-screenshots.mjs --app`. Dev-only.
//
// The app's own page (plan2code-app/ui: the bar, the launch card, the loop
// banner, the terminal panel) runs in Chrome from a small static server, with
// a stand-in for the Rust side of window.__TAURI__: `invoke` answers from a
// fixed table, `listen` keeps the handlers so a scene can fire `console-page`
// and the agent's output channel. The dashboard in its frame is a real console
// session staged the same way as every other shot (capture-screenshots.mjs),
// with PLAN2CODE_IN_APP and PLAN2CODE_EMBED_ORIGIN set so it may be framed and
// draws its app-only parts (the loop cards, the loop setup, the stop screen).
// The terminal text is written by the scene: no agent runs.
//
// Each shot is dark only, 1280x800 at twice the pixel density, Ocean highlight.
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
export const APP_SHOTS = ["app-launch", "app-terminal", "loop-setup", "loop-banner", "loop-stop"];
const TYPES = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png", ".woff2": "font/woff2" };
/** Serves plan2code-app/ui on 127.0.0.1. Resolves { origin, close }. */
export function serveAppUi(root) {
const dir = path.join(root, "plan2code-app", "ui");
for (const f of ["xterm.js", "addon-fit.js", "xterm.css", "tokens.css"]) {
if (!fs.existsSync(path.join(dir, "vendor", f))) {
throw new Error(`plan2code-app/ui/vendor/${f} is missing: run \`npm install\` and \`node scripts/vendor.mjs\` in plan2code-app first.`);
}
}
const server = http.createServer((req, res) => {
const rel = decodeURIComponent(new URL(req.url, "http://x").pathname).replace(/^\/+/, "") || "index.html";
const abs = path.join(dir, rel);
if (!abs.startsWith(dir + path.sep) || !fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
res.writeHead(404);
return res.end();
}
res.writeHead(200, { "content-type": TYPES[path.extname(abs)] || "application/octet-stream", "cache-control": "no-store" });
fs.createReadStream(abs).pipe(res);
});
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
resolve({ origin: `http://127.0.0.1:${server.address().port}`, close: () => new Promise((r) => server.close(r)) });
});
});
}
// The launch card's agents, the way the Rust side lists them: the three
// built-ins, installed, with the shipped model menu.
function availability(root) {
const models = JSON.parse(fs.readFileSync(path.join(root, "src", "launcher", "models.json"), "utf8"));
const entry = (id, label) => ({ id, label, installed: true, state: "found", path: null, folder: null, installHint: "", installUrl: null, hasEffort: id !== "devin", custom: false, models: models[id] || [] });
return { agents: [entry("claude", "Claude Code"), entry("codex", "Codex"), entry("devin", "Devin")], warnings: [] };
}
// Runs in the app page only (the console's frame gets nothing): the stand-in
// for the Tauri globals. `config` comes from the scene.
function tauriStub(config) {
if (window.top !== window) return;
const hub = { listeners: {}, channel: null, config };
window.__p2c = hub;
class Channel {
constructor() {
this.onmessage = null;
}
}
const answers = {
app_state: () => ({
projectDir: config.projectDir,
firstRunDone: true,
nodeChecked: true,
nodeVersion: "22.11.0",
// Nothing saved: the app's own default split for this window width.
termPanel: null,
// One step under the default, so the scenes' lines fit the default pane.
terminalFontSize: 12,
copyOnSelect: false,
lastAgent: "claude",
launchModel: "",
}),
agent_availability: () => config.availability,
platform_info: () => ({ os: "windows", windowsBuild: 26100 }),
agent_reattach: (args) => {
hub.channel = args.onOutput;
return { state: "idle", generation: 0 };
},
loop_state: () => config.loopState,
loop_facts: () => config.loopFacts,
console_status: () => ({ state: "running" }),
console_start: () => ({ url: hub.consoleUrl }),
version_status: () => ({ mismatch: false }),
check_new_release: () => ({ latest: null, problem: null }),
recent_folders: () => [],
};
const windowApi = new Proxy({}, { get: (_, name) => (name === "setTitle" ? async (t) => { document.title = t; } : async () => {}) });
window.__TAURI__ = {
core: {
Channel,
invoke: async (cmd, args) => (answers[cmd] ? answers[cmd](args || {}) : null),
},
event: {
listen: async (name, cb) => {
(hub.listeners[name] ||= []).push(cb);
return () => {};
},
},
window: { getCurrentWindow: () => windowApi },
};
hub.emit = (name, payload) => (hub.listeners[name] || []).forEach((cb) => cb({ payload }));
hub.agent = (state) => hub.channel && hub.channel.onmessage(state);
hub.write = (text) => hub.channel && hub.channel.onmessage(new TextEncoder().encode(text).buffer);
}
// What the terminal shows in each scene. Plain words in the shape of an agent's
// session, not any agent's real screen.
const DIM = "\x1b[2m";
const OFF = "\x1b[0m";
const BLUE = "\x1b[38;5;75m";
const GREEN = "\x1b[32m";
const RED = "\x1b[31m";
const lines = (...rows) => rows.join("\r\n") + "\r\n";
const TERM_DASHBOARD = lines(
`${DIM}~/code/task-api${OFF}`,
"",
`${BLUE}>${OFF} /plan2code`,
"",
"● Opening the dashboard.",
"",
"● Bash(console.mjs open)",
` ${DIM}⎿ → See the dashboard${OFF}`,
` ${DIM}beside this terminal.${OFF}`,
"",
"● The dashboard is open.",
" Phases 1 and 2 are done.",
" Implement is next, for",
" Phase 3. Pick a card",
" when you are ready.",
"",
`${DIM} Waiting for your pick...${OFF}`,
);
const TERM_BUILDING = lines(
`${DIM}Phase 3 of 4, by the loop${OFF}`,
"",
"● Read(phase-3.md)",
"",
"● Update(routes.js)",
` ${DIM}⎿ GET /tasks, paged${OFF}`,
"",
"● Update(tasks.test.js)",
` ${DIM}⎿ 6 tests for paging${OFF}`,
"",
"● Bash(npm test)",
` ${DIM}⎿${OFF} ${GREEN}✔ 41 passed${OFF} ${DIM}(1.8s)${OFF}`,
"",
"● Task 3.1 done.",
" Next: POST /tasks.",
"",
"● Update(routes.js)",
` ${DIM}⎿ POST /tasks with Zod${OFF}`,
);
const TERM_STOPPED = lines(
`${DIM}Phase 3 of 4, by the loop${OFF}`,
"",
"● Update(routes.js)",
` ${DIM}⎿ PATCH, DELETE /tasks/:id${OFF}`,
"",
"● Bash(npm test)",
` ${DIM}⎿${OFF} ${RED}✖ 2 failed${OFF}, 46 passed`,
"",
"● Still failing after a fix",
" round. Reporting to the",
" loop.",
);
const LOOP_FACTS = { agent: "claude", agentLabel: "Claude Code", model: "opus", effort: "high", permissionMode: "bypass", promptSupport: true, running: false };
const LOOP_RUNNING = {
running: true,
kind: "phases",
phase: 3,
phases: 4,
phaseName: "API endpoints",
step: "Building",
specName: "task-api",
strength: "balanced",
model: "sonnet",
effort: "high",
retriesUsed: 0,
canStopAfter: true,
};
const LOOP_STOPPED = {
kind: "stopped",
reason: "Phase 3 stopped: its tests still failed after a fix round.",
line: "npm test failed twice in Phase 3: PATCH /tasks/:id answers 200 for a deleted task, and a second DELETE answers 204 (test/tasks.test.js)",
advice: "Decide whether a deleted task should answer 404 or 410, then fix it together with an agent.",
recommend: "fix",
phase: 3,
phases: [
{ n: 3, name: "API endpoints", commit: null, unfixed: 0, retries: 1 },
{ n: 4, name: "Authentication", commit: null, unfixed: 0, retries: 0 },
],
uncommitted: ["src/tasks/routes.js", "test/tasks.test.js"],
can: ["ask", "resume", "fix", "dashboard"],
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/**
* Takes one app shot. `h` carries what capture-screenshots.mjs owns: the
* browser, the app page's origin, the sample project, `cli`, `post`, `stage`
* and the output folder.
*/
export async function captureAppShot(name, h) {
const { browser, origin, project, cli, post, stage, root, out } = h;
const config = { projectDir: project, availability: availability(root), loopFacts: LOOP_FACTS, loopState: null };
let sid = null;
let url = null;
if (name === "app-terminal" || name === "loop-setup") {
({ sid, url } = stage(project, { workflow: "dashboard", posts: ["dashboard"] }));
} else if (name === "loop-banner" || name === "loop-stop") {
// A loop phase's page: opened with --loop, which only works under the app.
const r = cli(project, "open", "--workflow", "implement", "--spec", "specs/task-api", "--loop", "--no-open");
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open --loop failed (${r.code}): ${r.err.trim()}`);
({ sid, url } = { sid: r.out.sid, url: r.out.url });
post(project, sid, "build");
if (name === "loop-banner") config.loopState = { ...LOOP_RUNNING, startedAtMs: 0 };
else {
const file = path.join(path.dirname(r.out.session), `loop-end-${sid}.json`);
fs.writeFileSync(file, JSON.stringify({ loopEnd: LOOP_STOPPED, agent: { status: "waiting" } }));
const p = cli(project, "post", "--session", sid, "--file", file);
if (p.code !== 0) throw new Error(`posting the loop's end failed (${p.code}): ${p.err.trim()}`);
}
}
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2, colorScheme: "dark" });
try {
await ctx.addInitScript(tauriStub, config);
const page = await ctx.newPage();
page.on("pageerror", (e) => console.log(` page error: ${e.message}`));
await page.goto(origin + "/index.html", { waitUntil: "domcontentloaded" });
await page.waitForFunction(() => window.__p2c && window.__p2c.channel, null, { timeout: 15000 });
// The banner's clock: started 23 minutes ago, set once the page is up.
if (config.loopState) {
await page.evaluate(() => {
const s = { ...window.__p2c.config.loopState, startedAtMs: Date.now() - 23 * 60 * 1000 - 12000 };
window.__p2c.emit("loop-state", s);
});
}
if (name === "app-launch") {
await page.locator("#launch-card:not([hidden])").waitFor({ timeout: 10000 });
await page.selectOption("#launch-model", "opus");
await page.selectOption("#launch-effort", "high");
await sleep(800);
} else {
const ended = name === "loop-stop";
await page.evaluate(
({ text, ended, loop }) => {
const p = window.__p2c;
p.agent({ state: "running", kind: "claude", generation: 1, mode: "bypass", model: loop ? "sonnet" : "opus", effort: "high" });
p.write(text);
if (ended) p.agent({ state: "ended", kind: "claude", generation: 1, mode: "bypass", model: "sonnet", effort: "high", reason: "exited with code 0" });
},
{ text: name === "loop-banner" ? TERM_BUILDING : name === "loop-stop" ? TERM_STOPPED : TERM_DASHBOARD, ended, loop: name.startsWith("loop-") && name !== "loop-setup" },
);
await page.evaluate((u) => {
window.__p2c.consoleUrl = u;
window.__p2c.emit("console-page", { url: u, sid: "", workflow: "" });
}, url);
const frame = page.frameLocator("iframe");
// The dashboard in the app opens on Planny asleep: wake him the way a
// person would, past the intro.
if (name === "app-terminal" || name === "loop-setup") {
const skip = frame.getByRole("button", { name: "Skip the intro" });
await skip.waitFor({ timeout: 20000 });
await skip.click();
await skip.waitFor({ state: "hidden" });
}
// Anything drawn in the main column: cards, the loop's end, or a phase's
// build-in-progress heading.
const drawn = frame.locator(".dash-card, .card, .handoff, .loop-end, #main h1, #main h2").first();
await drawn.waitFor({ timeout: 20000 }).catch(async () => {
const text = await frame.locator("body").innerText().catch(() => "");
console.log(` warning: ${name}: nothing known drew in the frame; it reads: ${text.slice(0, 300).replace(/\s+/g, " ")}`);
});
// The cards' entrance.
await sleep(3500);
// The dashboard: the suggested card in view, as in the console's own shot.
if (name === "app-terminal") {
await frame.locator(".dash-toggle").evaluate((n) => n.scrollIntoView({ block: "start", behavior: "instant" }));
await sleep(400);
}
if (name === "loop-setup") {
// The card is the button itself.
await frame.locator(".dash-card", { hasText: "Implementation Loop" }).first().click();
await frame.locator("#loop-start").waitFor({ timeout: 10000 });
await sleep(1500);
// From its top: the spec, the phases left and the strength.
await frame.locator(".loop-setup, #main").first().evaluate((n) => n.scrollIntoView({ block: "start", behavior: "instant" }));
await sleep(400);
}
if (name === "loop-stop") await frame.locator(".loop-end-actions").waitFor({ timeout: 10000 });
}
const cdp = await ctx.newCDPSession(page);
const clip = { x: 0, y: 0, width: 1280, height: 800, scale: 2 };
const { data } = await cdp.send("Page.captureScreenshot", { format: "webp", quality: 85, captureBeyondViewport: false, clip });
await cdp.detach();
const file = path.join(out, `${name}-dark.webp`);
fs.writeFileSync(file, Buffer.from(data, "base64"));
console.log(`${path.basename(file)} ${Math.round(fs.statSync(file).size / 1024)} KB`);
return file;
} finally {
await ctx.close();
if (sid) cli(project, "stop", "--session", sid);
}
}