Public: anyone can read this; the crew can change it.

A forge preview's look pictures every top-level page, desktop and phone, light and dark #2728

Parked opened this
Closed without merging

scout/forge:scout/2708-a-forge-preview-s-look-pictures-every-to → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +401 −13
docs/APPS.md +6
@@ -785,6 +785,12 @@ older ones are history, not status.
785785
786786 ### The look
787787
788 `"looks": "top-level"` is the forge's own set (`src/looks/pages.ts` lists the
789 pages, and a test holds the list to the router): every top-level page at
790 desktop and 360px, light and dark — the dark twin of a page is the same path
791 taken with `prefers-color-scheme: dark` and filed as `<page>+dark`. The pull
792 page sets each page's pictures beside main's. Best-effort like any look.
793
788794 When a deploy comes up green the forge takes a picture of it — every page
789795 `app.looks` names, `/` alone when it names none — at a phone's width
790796 (390×844), a laptop's (1280×800), and a thumb's (200×125, desktop's own
forge.json +1
@@ -6,6 +6,7 @@
66 "run": "bun run src/main.ts",
77 "install": "",
88 "health": "/healthz",
9 "looks": "top-level",
910 "ready": 90,
1011 "limits": {
1112 "memory": 2048,
src/apps/manifest.ts +2
@@ -253,6 +253,8 @@ function limitsField(
253253 function looksField(app: Json): Result<readonly string[], ManifestError> {
254254 const value = app["looks"];
255255 if (value === undefined) return ok(["/"]);
256 // The forge's own set: every top-level page, `looks/pages.ts` says which.
257 if (value === "top-level") return ok(["@top-level"]);
256258 if (!Array.isArray(value))
257259 return invalid("forge.json: app.looks must be an array of paths");
258260 if (value.length > LOOKS_MAX)
src/core/looks.ts +17 −2
@@ -57,8 +57,23 @@ export const DEFAULT_PAGE = "/";
5757 * with `-`. Compared against, never parsed back — the database's `page`
5858 * column is truth.
5959 */
60 const pageSlug = (page: string): string =>
61 page === DEFAULT_PAGE ? "" : page.slice(1).replace(/\//g, "-");
60 const pageSlug = (page: string): string => {
61 const dark = isDarkPage(page);
62 const slug = pageOf(page) === DEFAULT_PAGE ? "" : pageOf(page).slice(1).replace(/\//g, "-");
63 return dark ? `${slug}+dark` : slug;
64 };
65
66 /**
67 * The same page taken with the browser asking for its dark theme. The
68 * theme is part of the page's key, not a fourth kind: a `look` row's kind
69 * is one of three, and a migration may only add (`test/schema-additive`).
70 */
71 export const DARK_SUFFIX = "?theme=dark";
72 export const darkPage = (page: string): string => `${page}${DARK_SUFFIX}`;
73 export const isDarkPage = (page: string): boolean => page.endsWith(DARK_SUFFIX);
74 /** The page without its theme. */
75 export const pageOf = (page: string): string =>
76 isDarkPage(page) ? page.slice(0, -DARK_SUFFIX.length) : page;
6277
6378 /**
6479 * The fragment one picture is named by, on disk and in its URL: the page
src/looks/capture.ts +3
@@ -46,6 +46,8 @@ export interface LookInput {
4646 readonly out: string;
4747 readonly width: number;
4848 readonly height: number;
49 /** Ask the page for its dark theme, as a browser set to dark would. */
50 readonly dark?: boolean | undefined;
4951 /** A browser that has no picture by then is killed; the look fails. */
5052 readonly timeoutMs: number;
5153 }
@@ -140,6 +142,7 @@ async function shoot(
140142 `--user-data-dir=${profile}`,
141143 // The app's hostname is the forge's own listener: no DNS, no edge.
142144 `--host-resolver-rules=MAP ${host} 127.0.0.1`,
145 ...(input.dark === true ? ["--blink-settings=preferredColorScheme=1"] : []),
143146 `--window-size=${input.width},${input.height}`,
144147 "--force-device-scale-factor=1",
145148 "--js-flags=--max-old-space-size=256",
src/looks/pages.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * The forge's own look (#2708): which top-level pages are pictured, and at
3 * what. A builder cannot take a screenshot in its sandbox; the preview can,
4 * so the forge's `forge.json` says `"looks": "top-level"` and each preview
5 * is pictured here — every page below at desktop and 360px, light and dark
6 * — beside the same pages of main.
7 *
8 * `test/looks-pages.test.ts` holds this list to the router: a new top-level
9 * GET route must be named in `TOP_LEVEL_PAGES` or in `NOT_PAGES`, with the
10 * reason it has no picture.
11 */
12
13 import {
14 darkPage,
15 DEFAULT_PAGE,
16 LOOK_KINDS,
17 type LookKind,
18 } from "../core/looks.ts";
19
20 /** The window of the forge's narrow picture: a 360px column, as a small phone. */
21 export const NARROW = { width: 360, height: 740 } as const;
22
23 /** What `app.looks` holds in place of paths when the forge's set is wanted. */
24 export const TOP_LEVEL = "@top-level";
25
26 /** The pages worth a picture: each answers a signed-in owner with a page. */
27 export const TOP_LEVEL_PAGES: readonly string[] = [
28 DEFAULT_PAGE,
29 "/explore",
30 "/apps",
31 "/map",
32 "/boards",
33 "/board",
34 "/asks",
35 "/asked",
36 "/flow",
37 "/system",
38 "/contribute",
39 "/resilience",
40 "/forges",
41 "/family",
42 "/releases",
43 "/audit",
44 "/search",
45 ];
46
47 /** Top-level GET routes with no picture, and why. */
48 export const NOT_PAGES: Readonly<Record<string, string>> = {
49 "/llms.txt": "plain text",
50 "/robots.txt": "plain text",
51 "/releases.json": "data, not a page",
52 "/sitemap.xml": "data, not a page",
53 "/manifest.webmanifest": "data, not a page",
54 "/sw.js": "script",
55 "/audit.csv": "data, not a page",
56 "/mcp": "protocol endpoint",
57 "/events": "event stream",
58 "/claim": "one-time ceremony, gone once the forge is claimed",
59 "/first-admin": "one-time ceremony, gone once the forge has an admin",
60 "/signin": "redirects away for the signed-in owner the look is taken as",
61 "/signup": "redirects away for the signed-in owner the look is taken as",
62 "/verify": "needs a token from an email",
63 "/recover": "needs a token from an email",
64 "/front": "a door that redirects",
65 "/big": "a redirect",
66 "/new": "a form with nothing of the change in it",
67 "/settings": "the owner's account, not the product",
68 "/migrate": "a form with nothing of the change in it",
69 };
70
71 /**
72 * One picture to take. A `desktop` picture is the usual 1280px window and
73 * a `phone` one the forge's 360px column (`window`); the dark theme is the
74 * page's `darkPage` twin.
75 */
76 export interface Shot {
77 readonly page: string;
78 readonly kind: LookKind;
79 readonly window?: { readonly width: number; readonly height: number };
80 }
81
82 /**
83 * Every picture an app's `app.looks` asks for. Paths are taken at the base
84 * three widths, as ever; `TOP_LEVEL` is every page above at desktop and
85 * 360px in light and dark, and the home page's thumb too (the forge's tile
86 * on a front page).
87 */
88 export function lookPlan(pages: readonly string[]): Shot[] {
89 const shots: Shot[] = [];
90 for (const page of pages) {
91 if (page === TOP_LEVEL) {
92 for (const p of TOP_LEVEL_PAGES)
93 for (const q of [p, darkPage(p)]) {
94 shots.push({ page: q, kind: "desktop" });
95 shots.push({ page: q, kind: "phone", window: NARROW });
96 }
97 shots.push({ page: DEFAULT_PAGE, kind: "thumb" });
98 } else for (const kind of LOOK_KINDS) shots.push({ page, kind });
99 }
100 return shots;
101 }
src/looks/service.ts +10 −9
@@ -44,7 +44,8 @@ import {
4444 deleteLooks,
4545 DEFAULT_PAGE,
4646 LEGACY_THUMB_WIDTH,
47 LOOK_KINDS,
47 isDarkPage,
48 pageOf,
4849 LOOK_SIZES,
4950 LOOK_WINDOWS,
5051 lookSlot,
@@ -61,6 +62,7 @@ import { thumbnail } from "../design/image/image.ts";
6162 import { decodePng, encodePng, pngHeader } from "../design/image/png.ts";
6263 import { createLog } from "../kernel/log.ts";
6364 import { err, ok, type Result } from "../kernel/result.ts";
65 import { lookPlan, type Shot } from "./pages.ts";
6466 import { findChromium, takeLook, type Capture } from "./capture.ts";
6567
6668 const log = createLog("looks");
@@ -370,7 +372,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
370372 : { id: owner.id, name: owner.username, role: "admin" };
371373 const host = runtime.hostFor(record.slug, item.env);
372374 let allOk = true;
373 for (const { page, kind } of wanted) {
375 for (const { page, kind, window } of wanted) {
374376 if (stopped) return;
375377 const token = signGrant(
376378 dataDir,
@@ -379,7 +381,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
379381 Date.now(),
380382 asNobody(kind) ? undefined : asOwner,
381383 );
382 const url = `http://${host}:${port}/__forge/grant?t=${encodeURIComponent(token)}&to=${encodeURIComponent(page)}`;
384 const url = `http://${host}:${port}/__forge/grant?t=${encodeURIComponent(token)}&to=${encodeURIComponent(pageOf(page))}`;
383385 const path = lookPath(item.appId, item.env, item.commitOid, page, kind);
384386 const out = join(dataDir, path);
385387 // Taken to one side and moved in whole. A pull that closes while its
@@ -394,7 +396,8 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
394396 const shot = await capture({
395397 url,
396398 out: staged,
397 ...LOOK_WINDOWS[kind],
399 ...(window ?? LOOK_WINDOWS[kind]),
400 dark: isDarkPage(page),
398401 timeoutMs: CAPTURE_TIMEOUT_MS,
399402 });
400403 const taken =
@@ -461,7 +464,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
461464 commitOid: string,
462465 pages: readonly string[] | undefined,
463466 failedCounts = false,
464 ): { page: string; kind: LookKind }[] {
467 ): Shot[] {
465468 const have = new Set(
466469 looksForEnv(app.db, appId, env)
467470 .filter(
@@ -471,10 +474,8 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
471474 )
472475 .map((l) => lookSlot(l.page, l.kind)),
473476 );
474 return (pages ?? [DEFAULT_PAGE]).flatMap((page) =>
475 LOOK_KINDS.filter((kind) => !have.has(lookSlot(page, kind))).map(
476 (kind) => ({ page, kind }),
477 ),
477 return lookPlan(pages ?? [DEFAULT_PAGE]).filter(
478 ({ page, kind }) => !have.has(lookSlot(page, kind)),
478479 );
479480 }
480481
src/web/pages/looks.ts +97 −2
@@ -18,6 +18,9 @@ import { getAppByRepo } from "../../core/apps.ts";
1818 import {
1919 DEFAULT_PAGE,
2020 isAttached,
21 darkPage,
22 isDarkPage,
23 pageOf,
2124 LOOK_SIZES,
2225 lookSlot,
2326 looksForEnv,
@@ -31,6 +34,7 @@ import { canEnterApp, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
3134 import type { Ctx } from "../../http/context.ts";
3235 import { notFound } from "../../http/respond.ts";
3336 import { keepLook } from "../../looks/service.ts";
37 import { NARROW } from "../../looks/pages.ts";
3438 import { loadRepo, repoBase } from "../chrome.ts";
3539 import { html, when, type Html } from "../html.ts";
3640 import { card, icon, sha, time } from "../ui.ts";
@@ -163,7 +167,12 @@ export function lookCard(
163167 }
164168 // Home first, then the rest in the order the manifest is likeliest to
165169 // read them — alphabetically, since the row order says nothing about it.
166 const pages = [...new Set(taken.map((l) => l.page))].sort((a, b) =>
170 // A page taken at the forge's set is shown as a before/after grid below,
171 // not as a pair.
172 const setPages = new Set(taken.filter((l) => isDarkPage(l.page)).map((l) => pageOf(l.page)));
173 const pages = [...new Set(taken.map((l) => l.page))]
174 .filter((p) => !setPages.has(pageOf(p)))
175 .sort((a, b) =>
167176 a === DEFAULT_PAGE ? -1 : b === DEFAULT_PAGE ? 1 : a.localeCompare(b),
168177 );
169178 const labelled = pages.length > 1;
@@ -241,14 +250,100 @@ export function lookCard(
241250 </figcaption>
242251 </figure>`;
243252 };
253 const before = setPages.size === 0
254 ? []
255 : looksForEnv(ctx.app.db, record.id, "production").filter(
256 (l) => l.error === null && mayFetchLook(ctx, repo, record, l),
257 );
258 const grids = [...setPages].sort(byPage).map((page) =>
259 gridOf(base, repo.name, pull, headOid, page, taken, before),
260 );
244261 return card(
245 html`${pages.map(group)}${when(attached.length > 0, () =>
262 html`${grids}${pages.map(group)}${when(attached.length > 0, () =>
246263 html`<div class="look-pair look-attachments">${attached.map(person)}</div>`,
247264 )}`,
248265 { head, extra: "look-card" },
249266 );
250267 }
251268
269 const byPage = (a: string, b: string): number =>
270 a === DEFAULT_PAGE ? -1 : b === DEFAULT_PAGE ? 1 : a.localeCompare(b);
271
272 /** The four pictures of a page in the forge's set. */
273 const SET_CELLS: readonly {
274 readonly label: string;
275 readonly dark: boolean;
276 readonly kind: LookKind;
277 }[] = [
278 { label: "desktop", dark: false, kind: "desktop" },
279 { label: "desktop dark", dark: true, kind: "desktop" },
280 { label: "360px", dark: false, kind: "phone" },
281 { label: "360px dark", dark: true, kind: "phone" },
282 ];
283
284 /**
285 * One page of the forge's set: main's pictures (before) beside this pull's
286 * (after), one row per width and theme. A picture that could not be taken
287 * is a cell that says why.
288 */
289 function gridOf(
290 base: string,
291 name: string,
292 pull: Pull,
293 headOid: string,
294 page: string,
295 taken: readonly Look[],
296 main: readonly Look[],
297 ): Html {
298 const cell = (
299 side: string,
300 looks: readonly Look[],
301 c: (typeof SET_CELLS)[number],
302 ): Html => {
303 const key = c.dark ? darkPage(page) : page;
304 const ofPage = looks.filter((l) => l.page === key && l.kind === c.kind);
305 const shot = ofPage.find((l) => l.error === null);
306 if (shot === undefined) {
307 const failed = ofPage.find((l) => l.error !== null);
308 return html`<figure class="look-cell">
309 <figcaption class="muted small">${c.label} · ${side}</figcaption>
310 <p class="muted small">
311 ${failed === undefined
312 ? "No picture."
313 : html`No picture: ${failed.error}.`}
314 </p>
315 </figure>`;
316 }
317 const url = lookUrl(base, shot);
318 const size = c.kind === "phone" ? NARROW : LOOK_SIZES.desktop;
319 return html`<figure class="look-cell">
320 <figcaption class="muted small">
321 ${c.label} · ${side}${when(
322 side === "after" && shot.commitOid !== headOid,
323 () => html` · older head`,
324 )}
325 </figcaption>
326 <a class="look look-${c.kind}" href="${url}"
327 ><img
328 src="${url}"
329 width="${size.width}"
330 height="${size.height}"
331 alt="${name} ${page} ${c.label}, ${side === "after" ? `#${pull.number}` : "main"}"
332 loading="lazy"
333 /></a>
334 </figure>`;
335 };
336 return html`<section class="look-group look-set" data-page="${page}">
337 <p class="muted small look-page">${page}</p>
338 ${SET_CELLS.map(
339 (c) =>
340 html`<div class="look-pair">
341 ${cell("before", main, c)}${cell("after", taken, c)}
342 </div>`,
343 )}
344 </section>`;
345 }
346
252347 /** An attached picture's own size, read from its header; none if it cannot be. */
253348 function attachedSize(
254349 ctx: Ctx,
test/looks-pages.test.ts added +83
@@ -0,0 +1,83 @@
1 import { describe, expect, test } from "bun:test";
2 import { darkPage, lookSlot } from "../src/core/looks.ts";
3 import { buildRouter } from "../src/http/server.ts";
4 import {
5 lookPlan,
6 NOT_PAGES,
7 TOP_LEVEL,
8 TOP_LEVEL_PAGES,
9 } from "../src/looks/pages.ts";
10
11 /** The router's GET routes of exactly one literal segment, and "/". */
12 function topLevelRoutes(): string[] {
13 const routes = (
14 buildRouter() as unknown as {
15 routes: {
16 method: string;
17 pattern: string;
18 segments: { kind: string }[];
19 }[];
20 }
21 ).routes;
22 return [
23 ...new Set(
24 routes
25 .filter(
26 (r) =>
27 r.method === "GET" &&
28 r.segments.length === 1 &&
29 r.segments[0]!.kind === "literal",
30 )
31 .map((r) => r.pattern),
32 ),
33 ];
34 }
35
36 describe("the forge's look pages", () => {
37 test("every top-level route is a pictured page or says why it is not, and neither list names a route the router lacks", () => {
38 const routes = topLevelRoutes();
39 expect(routes).toContain("/");
40 const named = [...TOP_LEVEL_PAGES, ...Object.keys(NOT_PAGES)];
41 expect([...routes].sort()).toEqual([...new Set(named)].sort());
42 // Nothing is both.
43 expect(named.length).toBe(new Set(named).size);
44 for (const reason of Object.values(NOT_PAGES)) expect(reason).not.toBe("");
45 });
46
47 test("a plan holds one picture per page × width × theme, each with its own file name", () => {
48 const plan = lookPlan([TOP_LEVEL]);
49 const set = plan.filter((s) => s.kind !== "thumb");
50 expect(set).toHaveLength(TOP_LEVEL_PAGES.length * 4);
51 for (const page of TOP_LEVEL_PAGES)
52 for (const p of [page, darkPage(page)]) {
53 expect(set.find((s) => s.page === p && s.kind === "desktop")).toBeDefined();
54 const narrow = set.find((s) => s.page === p && s.kind === "phone");
55 expect(narrow?.window?.width).toBe(360);
56 }
57 expect(plan.filter((s) => s.kind === "thumb")).toEqual([
58 { page: "/", kind: "thumb" },
59 ]);
60 expect(new Set(plan.map((s) => lookSlot(s.page, s.kind))).size).toBe(
61 plan.length,
62 );
63 });
64
65 test("an app that names paths is pictured at the three widths, as ever", () => {
66 expect(lookPlan(["/", "/board"])).toHaveLength(6);
67 });
68 });
69
70 describe("forge.json asks for the set", () => {
71 test('"looks": "top-level" is the set; any other string is refused; this repository asks for it', async () => {
72 const { parseManifest } = await import("../src/apps/manifest.ts");
73 const parsed = parseManifest(
74 JSON.stringify({ app: { run: "x", looks: "top-level" } }),
75 undefined,
76 );
77 expect(parsed.ok && parsed.value.looks).toEqual([TOP_LEVEL]);
78 const bad = parseManifest(JSON.stringify({ app: { run: "x", looks: "all" } }), undefined);
79 expect(bad.ok).toBe(false);
80 const own = parseManifest(await Bun.file("forge.json").text(), undefined);
81 expect(own.ok && own.value.looks).toEqual([TOP_LEVEL]);
82 });
83 });
test/looks.test.ts +81
@@ -40,6 +40,7 @@ import {
4040 type Capture,
4141 type LookInput,
4242 } from "../src/looks/capture.ts";
43 import { TOP_LEVEL_PAGES } from "../src/looks/pages.ts";
4344 import { startLooks, type LooksHandle } from "../src/looks/service.ts";
4445
4546 quietLogs();
@@ -661,6 +662,86 @@ describe("the look", () => {
661662 expect(page).toContain(`alt="hello #${opened.value.number} on a phone"`);
662663 }, 120_000);
663664
665 test("`looks: top-level` pictures every top-level page at desktop and 360px, light and dark, and the pull page sets them beside main's", async () => {
666 const branch = await commitToBranch(app, alice, repo, {
667 branch: "forge-set",
668 base: repo.defaultBranch,
669 message: "Look at the forge's set",
670 files: [
671 {
672 path: "forge.json",
673 content: `${JSON.stringify(
674 {
675 app: {
676 run: "bun run src/server.ts",
677 test: "bun test",
678 tty: "bun run src/tty.ts",
679 looks: "top-level",
680 },
681 },
682 null,
683 2,
684 )}\n`,
685 },
686 ],
687 });
688 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
689 const opened = await openPull(app, alice, repo, {
690 title: "Look at the forge's set",
691 baseBranch: repo.defaultBranch,
692 headBranch: "forge-set",
693 });
694 if (!opened.ok) throw new Error(String(opened.error));
695 const env = `pull-${opened.value.number}`;
696 const commitOid = branch.value.commitOid;
697 expect((await settled((r) => r.env === env)).state).toBe("ok");
698
699 const want = TOP_LEVEL_PAGES.length * 4 + 1;
700 const rows = await until(() => {
701 const found = looksForEnv(app.db, record.id, env).filter(
702 (l) => l.commitOid === commitOid,
703 );
704 return found.length === want ? found : undefined;
705 }, 60_000);
706 expect(new Set(rows.map((l) => `${l.page} ${l.kind}`)).size).toBe(want);
707 for (const page of TOP_LEVEL_PAGES)
708 for (const p of [page, `${page}?theme=dark`])
709 expect(
710 rows
711 .filter((l) => l.page === p && l.kind !== "thumb")
712 .map((l) => l.kind)
713 .sort(),
714 ).toEqual(["desktop", "phone"]);
715 // The browser was asked for the dark theme exactly where the kind says,
716 // at 360px exactly where the kind says.
717 const taken = calls.filter((c) => c.out.includes(`-${commitOid}-`));
718 expect(taken).toHaveLength(want);
719 for (const c of taken) {
720 expect(c.dark === true).toBe(c.out.includes("+dark-"));
721 expect(c.width === 360).toBe(c.out.endsWith("-phone.png"));
722 }
723
724 const page = await (
725 await web(`/alice/hello/pulls/${opened.value.number}`, aliceCookie)
726 ).text();
727 expect(page).toContain(`data-page="/map"`);
728 expect(page).toContain(
729 `src="/alice/hello/looks/${env}/${commitOid}/map+dark-phone.png?v=`,
730 );
731 expect(page).toContain("360px dark · before");
732 expect(page).toContain("360px dark · after");
733
734 // A picture that could not be taken is a cell that says why.
735 const failed = rows.find((l) => l.page === "/map" && l.kind === "phone")!;
736 app.db
737 .query(`UPDATE look SET error = 'the browser fell over', path = '' WHERE id = ?1`)
738 .run(failed.id);
739 const again = await (
740 await web(`/alice/hello/pulls/${opened.value.number}`, aliceCookie)
741 ).text();
742 expect(again).toContain("No picture: the browser fell over.");
743 }, 180_000);
744
664745 test("the sweep pictures a running production missing one: a thumb from before thumbs were the page is retaken as a stranger; one that failed is not retried each sweep", async () => {
665746 const status = runtime.envStatus(record, "production")!;
666747 expect(status.state).toBe("running");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs