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

Home tiles on a phone: thumbnails are 200×125 corner crops upscaled 1.8×, status badge stretches full width, hero CTA touches the grid #494

Closed opened this in answer to
Closed without merging

mason/forge:mason/473-home-tiles-on-a-phone-thumbnails-are-200 → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +520 −66
docs/APPS.md +9 −5
@@ -620,11 +620,15 @@ older ones are history, not status.
620620
621621 When a deploy comes up green the forge takes a picture of it — every page
622622 `app.looks` names, `/` alone when it names none — at a phone's width
623 (390×844), a laptop's (1280×800), and a thumb's (200×125, desktop's own
624 aspect, small), and keeps the pictures beside the commit they are of, so a
625 person judges a change from what it is rather than from what it says.
626 `app.looks` may name at most three pages: a browser start per picture per
627 width is the heaviest thing the forge does, and more is a manifest error
623 (390×844) and a laptop's (1280×800), scales the laptop's picture, whole,
624 to a 640×400 thumb (not a shot of its own: a browser window that small
625 keeps only the page's top-left corner), and keeps the pictures beside the
626 commit they are of, so a person judges a change from what it is rather than
627 from what it says. The front door's tiles draw the thumb with the desktop
628 picture as its 2× source, so a tile is sharp on a phone and a laptop alike;
629 thumbs taken before they were scaled are refit from their desktop picture
630 on boot. `app.looks` may name at most three pages: a browser start per
631 picture per width is the heaviest thing the forge does, and more is a manifest error
628632 rather than a silent, slower deploy. The pull page shows the phone and
629633 desktop pair under the checks, with the commit and a word when the head has
630634 moved since; more than one page gets one group per page, each labelled by
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/looks-thumb.test.ts test/home-tiles.test.ts",
1010 "timeout": 1800
1111 }
1212 }
src/core/looks.ts +6 −4
@@ -8,7 +8,8 @@
88 import type { Database } from "bun:sqlite";
99 import { id as newId } from "../kernel/id.ts";
1010
11 /** The three widths a page is pictured at. */
11 /** The three widths a page is pictured at — in the order they are made:
12 * the thumb is scaled from desktop, so desktop comes before it. */
1213 export type LookKind = "phone" | "desktop" | "thumb";
1314 export const LOOK_KINDS: readonly LookKind[] = ["phone", "desktop", "thumb"];
1415 export const isLookKind = (value: string): value is LookKind =>
@@ -16,15 +17,16 @@ export const isLookKind = (value: string): value is LookKind =>
1617
1718 /**
1819 * The three widths, as a person holds them: a phone, a laptop's window, and
19 * a thumbnail — taken at the size a slot actually shows, at desktop's own
20 * aspect, rather than a full picture squeezed into a small box.
20 * a thumbnail — the desktop picture, whole, at half its size
21 * (`looks/thumb.ts`): small enough for a slot, sharp enough for a phone's
22 * full-width tile, with the desktop picture as its 2× source.
2123 */
2224 export const LOOK_SIZES: Readonly<
2325 Record<LookKind, { readonly width: number; readonly height: number }>
2426 > = {
2527 phone: { width: 390, height: 844 },
2628 desktop: { width: 1280, height: 800 },
27 thumb: { width: 200, height: 125 },
29 thumb: { width: 640, height: 400 },
2830 };
2931
3032 /** A look with no page recorded — every row before `app.looks` existed. */
src/looks/service.ts +82 −10
@@ -22,6 +22,7 @@ import {
2222 readFileSync,
2323 renameSync,
2424 rmSync,
25 writeFileSync,
2526 } from "node:fs";
2627 import { dirname, join } from "node:path";
2728 import type { App } from "../app.ts";
@@ -36,6 +37,7 @@ import {
3637 LOOK_KINDS,
3738 LOOK_SIZES,
3839 lookSlot,
40 looksForApps,
3941 looksForEnv,
4042 recordLook,
4143 type LookKind,
@@ -43,8 +45,11 @@ import {
4345 import { getPull } from "../core/pulls.ts";
4446 import { getRepoById } from "../core/repos.ts";
4547 import { getUserById } from "../core/users.ts";
48 import { measure } from "../design/image/image.ts";
4649 import { createLog } from "../kernel/log.ts";
50 import { err, ok, type Result } from "../kernel/result.ts";
4751 import { findChromium, takeLook, type Capture } from "./capture.ts";
52 import { scaleThumb } from "./thumb.ts";
4853
4954 const log = createLog("looks");
5055
@@ -153,6 +158,16 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
153158 let stopped = false;
154159
155160 prune();
161 // Thumbs taken before they were scaled from desktop are corner crops;
162 // they are refit once, off the boot path, ahead of anything queued.
163 pumping = true;
164 pump = Bun.sleep(0)
165 .then(refit)
166 .catch((error) => log.error("thumb refit failed", { error: String(error) }))
167 .then(drain)
168 .finally(() => {
169 pumping = false;
170 });
156171
157172 const unsubscribe = app.bus.subscribe((event: ForgeEvent) => {
158173 try {
@@ -294,9 +309,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
294309 ? undefined
295310 : { id: owner.id, name: owner.username, role: "admin" };
296311 const host = runtime.hostFor(record.slug, item.env);
297 let allOk = true;
298 for (const { page, kind } of wanted) {
299 if (stopped) return;
312 const grantUrl = (page: string): string => {
300313 const token = signGrant(
301314 dataDir,
302315 { app: record, env: item.env },
@@ -304,7 +317,13 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
304317 Date.now(),
305318 who,
306319 );
307 const url = `http://${host}:${port}/__forge/grant?t=${encodeURIComponent(token)}&to=${encodeURIComponent(page)}`;
320 return `http://${host}:${port}/__forge/grant?t=${encodeURIComponent(token)}&to=${encodeURIComponent(page)}`;
321 };
322 let allOk = true;
323 /** Why each page's desktop picture failed this time: its thumb's reason too. */
324 const desktopFailed = new Map<string, string>();
325 for (const { page, kind } of wanted) {
326 if (stopped) return;
308327 const path = lookPath(item.appId, item.env, item.commitOid, page, kind);
309328 const out = join(dataDir, path);
310329 // Taken to one side and moved in whole. A pull that closes while its
@@ -316,12 +335,27 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
316335 `${item.appId}-${item.env}-${item.commitOid}-${lookSlot(page, kind)}.png`,
317336 );
318337 mkdirSync(dirname(staged), { recursive: true });
319 const taken = await capture({
320 url,
321 out: staged,
322 ...LOOK_SIZES[kind],
323 timeoutMs: CAPTURE_TIMEOUT_MS,
324 });
338 // The thumb is the desktop picture made small, not a shot of its
339 // own: `LOOK_KINDS` puts desktop first, so it is on disk by now —
340 // or it failed, and the thumb fails for the same reason.
341 const failedFirst = desktopFailed.get(page);
342 const taken =
343 kind === "thumb"
344 ? failedFirst !== undefined
345 ? err(failedFirst)
346 : writeThumb(
347 join(
348 dataDir,
349 lookPath(item.appId, item.env, item.commitOid, page, "desktop"),
350 ),
351 staged,
352 )
353 : await capture({
354 url: grantUrl(page),
355 out: staged,
356 ...LOOK_SIZES[kind],
357 timeoutMs: CAPTURE_TIMEOUT_MS,
358 });
325359 const row = {
326360 appId: item.appId,
327361 env: item.env,
@@ -346,6 +380,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
346380 } else {
347381 rmSync(staged, { force: true });
348382 allOk = false;
383 if (kind === "desktop") desktopFailed.set(page, taken.error);
349384 log.warn("no picture", {
350385 app: record.slug,
351386 env: item.env,
@@ -368,6 +403,15 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
368403 });
369404 }
370405
406 /** The thumb, scaled from the desktop picture at `from`, written to `to`. */
407 function writeThumb(from: string, to: string): Result<void, string> {
408 if (!existsSync(from)) return err("no desktop picture to scale");
409 const scaled = scaleThumb(readFileSync(from));
410 if (!scaled.ok) return scaled;
411 writeFileSync(to, scaled.value);
412 return ok();
413 }
414
371415 /** An environment is gone: so are its pictures, waiting or taken. */
372416 function forget(appId: string, env: EnvName): void {
373417 const at = queue.findIndex((q) => q.appId === appId && q.env === env);
@@ -384,6 +428,34 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
384428 if (look.path !== "") rmSync(join(dataDir, look.path), { force: true });
385429 }
386430
431 /**
432 * Every thumb that is not the size a thumb is now — a crop from before
433 * it was scaled from desktop — rescaled from its commit's desktop
434 * picture, in place. One with no desktop picture beside it is left as
435 * it was: a crop is better than nothing.
436 */
437 function refit(): void {
438 const ids = listApps(app.db).map((r) => r.id);
439 const want = LOOK_SIZES.thumb;
440 for (const look of looksForApps(app.db, ids)) {
441 if (stopped) return;
442 if (look.kind !== "thumb" || look.error !== null || look.path === "")
443 continue;
444 const path = join(dataDir, look.path);
445 if (!existsSync(path)) continue;
446 const size = measure(readFileSync(path));
447 if (size?.width === want.width && size.height === want.height) continue;
448 const desktop = join(
449 dataDir,
450 lookPath(look.appId, look.env as EnvName, look.commitOid, look.page, "desktop"),
451 );
452 const staged = join(stagingRoot(dataDir), `refit-${look.id}.png`);
453 mkdirSync(dirname(staged), { recursive: true });
454 if (writeThumb(desktop, staged).ok) renameSync(staged, path);
455 else rmSync(staged, { force: true });
456 }
457 }
458
387459 /**
388460 * Pictures on disk for apps that no longer exist, or previews whose pull
389461 * closed while no forge was listening, are nobody's: the same sweep the
src/looks/thumb.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * The thumb is not a picture of its own: it is the desktop picture, whole,
3 * made smaller. A browser window as small as a slot lays the page out at
4 * its own minimum width and the screenshot keeps only the corner that
5 * fits — a logo and half a headline — which a tile then has to blow up.
6 * Scaling the 1280×800 capture down to 640×400 keeps the whole first
7 * screen, sharp at a phone's tile width; the desktop picture itself is the
8 * 2× source beside it (`srcset`), so nothing is taken twice.
9 *
10 * Box filter (`thumbnail`), because text reduced by anything cheaper turns
11 * to noise. Plain bytes in, plain bytes out; the caller owns the files.
12 */
13
14 import { decode, thumbnail } from "../design/image/image.ts";
15 import { encodePng } from "../design/image/png.ts";
16 import { err, ok, type Result } from "../kernel/result.ts";
17 import { LOOK_SIZES } from "../core/looks.ts";
18
19 /** A desktop picture's bytes as the thumb's PNG bytes, or why not. */
20 export function scaleThumb(desktop: Uint8Array): Result<Uint8Array, string> {
21 const image = decode(desktop);
22 if (!image.ok) return err(`the desktop picture is ${image.error}`);
23 const { width, height } = LOOK_SIZES.thumb;
24 const small = thumbnail(
25 image.value.rgba,
26 image.value.width,
27 image.value.height,
28 width,
29 height,
30 );
31 return ok(encodePng(small.width, small.height, small.rgba));
32 }
src/web/studio/home.ts +43 −3
@@ -10,7 +10,13 @@
1010 import { appsRuntime, type EnvState } from "../../apps/runtime.ts";
1111 import { crewForRepos } from "../../core/agents.ts";
1212 import { listPublicApps } from "../../core/apps.ts";
13 import { DEFAULT_PAGE, LOOK_SIZES, looksForApps } from "../../core/looks.ts";
13 import {
14 DEFAULT_PAGE,
15 LOOK_SIZES,
16 looksForApps,
17 type Look,
18 type LookKind,
19 } from "../../core/looks.ts";
1420 import { getReposByIds, type Repo } from "../../core/repos.ts";
1521 import { type User } from "../../core/users.ts";
1622 import { isPausedAtCeiling, spentTodayForRepos } from "../../crew/autonomy.ts";
@@ -178,6 +184,38 @@ const LIVENESS: Record<EnvState, number> = {
178184 stopped: 4,
179185 };
180186
187 /** How wide a tile is drawn: the whole column on a phone, a grid cell
188 * (`.app-shelf`, at most 1040px across) on anything wider. */
189 const TILE_SIZES = "(max-width: 600px) 100vw, 360px";
190
191 /**
192 * A tile's picture: the thumb, with the desktop picture of the same
193 * commit as its 2× source, so the tile is sharp on a phone's full-width
194 * tile and on a dense screen alike. Either alone when it is all there is.
195 */
196 function tileLook(
197 base: string,
198 looks: readonly Look[],
199 ): { src: string; srcset: string; kind: LookKind } | undefined {
200 const thumb = pictured(looks, "thumb");
201 const desktop = pictured(looks, "desktop");
202 const url = (look: Look): string =>
203 lookUrl(base, "production", look.commitOid, DEFAULT_PAGE, look.kind);
204 const one = (look: Look) => ({
205 src: url(look),
206 srcset: `${url(look)} ${LOOK_SIZES[look.kind].width}w`,
207 kind: look.kind,
208 });
209 if (thumb === undefined) return desktop && one(desktop);
210 if (desktop === undefined || desktop.commitOid !== thumb.commitOid)
211 return one(thumb);
212 return {
213 src: url(thumb),
214 srcset: `${url(thumb)} ${LOOK_SIZES.thumb.width}w, ${url(desktop)} ${LOOK_SIZES.desktop.width}w`,
215 kind: thumb.kind,
216 };
217 }
218
181219 /**
182220 * The studio's door for a stranger: the public apps as a shelf of
183221 * pictures, name and one clamped line, live first — and when nothing
@@ -221,13 +259,15 @@ export function studioDoor(ctx: Ctx): Response {
221259 l.env === "production" &&
222260 l.page === DEFAULT_PAGE,
223261 );
224 const look = pictured(ofApp, "thumb") ?? pictured(ofApp, "desktop");
225262 const base = repoBase(repo);
263 const look = tileLook(base, ofApp);
226264 return html`<a class="app-tile" href="${base}">
227265 ${look
228266 ? html`<img
229267 class="app-tile-look"
230 src="${lookUrl(base, "production", look.commitOid, DEFAULT_PAGE, look.kind)}"
268 src="${look.src}"
269 srcset="${look.srcset}"
270 sizes="${TILE_SIZES}"
231271 width="${LOOK_SIZES[look.kind].width}"
232272 height="${LOOK_SIZES[look.kind].height}"
233273 alt=""
src/web/style/content.ts +9 −1
@@ -340,6 +340,8 @@ form.inline { display: inline; margin-left: auto; }
340340 .hero-terminal .mono { font-size: 15px; }
341341 .terminal-line { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 14px; }
342342 .hero .bar { justify-content: center; }
343 /* The call to action never touches what follows it, at any width. */
344 .hero > :last-child { margin-bottom: 32px; }
343345
344346 /* The studio's front door: the public apps, live first, as pictures. */
345347 .app-shelf {
@@ -351,12 +353,18 @@ form.inline { display: inline; margin-left: auto; }
351353 overflow: hidden; background: var(--card); color: inherit; text-decoration: none;
352354 }
353355 .app-tile:hover { border-color: var(--accent); }
354 .app-tile-look { display: block; width: 100%; height: auto; background: var(--muted); }
356 /* The whole first screen, scaled: a tile of any width shows its top. */
357 .app-tile-look {
358 display: block; width: 100%; height: auto; aspect-ratio: 1280 / 800;
359 object-fit: cover; object-position: top; background: var(--muted);
360 }
355361 .app-tile-blank {
356362 display: flex; align-items: center; justify-content: center;
357363 aspect-ratio: 1280 / 800; background: var(--muted); color: var(--muted-fg);
358364 }
359365 .app-tile-body { display: grid; gap: 6px; padding: 10px 12px; }
366 /* A grid cell stretches its child; a state is a word, not a bar. */
367 .app-tile-body > .badge { justify-self: start; }
360368 .app-tile-name { font-weight: 600; font-size: 14px; }
361369 .app-tile-desc { color: var(--muted-fg); font-size: 12.5px; }
362370
test/helpers/chrome.ts +61 −31
@@ -102,6 +102,13 @@ async function readDebuggerUrl(
102102 }
103103 }
104104
105 export interface Viewport {
106 width: number;
107 height: number;
108 /** Device pixels per CSS pixel. @default 1 */
109 deviceScaleFactor?: number;
110 }
111
105112 /**
106113 * Load `url` in headless Chromium at a `width`×`height` viewport, carrying
107114 * one cookie (a session), and report how wide the document ended up.
@@ -109,9 +116,50 @@ async function readDebuggerUrl(
109116 export async function measurePageWidth(
110117 binary: string,
111118 url: string,
112 viewport: { width: number; height: number },
119 viewport: Viewport,
113120 cookie: { name: string; value: string },
114121 ): Promise<PageWidth> {
122 return evaluateInPage<PageWidth>(
123 binary,
124 url,
125 viewport,
126 `(() => {
127 // documentElement.clientWidth, not window.innerWidth: after an
128 // in-process navigation under an active device-metrics override,
129 // headless Chromium leaves window.innerWidth stale while every
130 // other viewport-derived value (this one included) is current.
131 const vw = document.documentElement.clientWidth;
132 const overflowing = [...document.querySelectorAll("*")]
133 .filter((el) => el.getBoundingClientRect().right > vw + 1)
134 .slice(0, 8)
135 .map((el) =>
136 el.tagName.toLowerCase() +
137 (el.className && typeof el.className === "string"
138 ? "." + el.className.trim().split(/\\s+/).join(".")
139 : ""),
140 );
141 return JSON.stringify({
142 scrollWidth: document.documentElement.scrollWidth,
143 viewportWidth: vw,
144 overflowing,
145 });
146 })()`,
147 cookie,
148 );
149 }
150
151 /**
152 * Load `url` in headless Chromium at `viewport` — with one cookie, or as
153 * a stranger without — and return what `expression` (a JSON string, or a
154 * promise of one) says about the page once it has loaded.
155 */
156 export async function evaluateInPage<T>(
157 binary: string,
158 url: string,
159 viewport: Viewport,
160 expression: string,
161 cookie?: { name: string; value: string },
162 ): Promise<T> {
115163 const profile = mkdtempSync(join(tmpdir(), "forge-phone-"));
116164 const proc = Bun.spawn(
117165 [
@@ -147,49 +195,31 @@ export async function measurePageWidth(
147195 const cdp = new Cdp(ws);
148196 await cdp.send("Page.enable");
149197 await cdp.send("Network.enable");
150 // The viewport a real phone gives a page: window-size flags at launch
198 // The viewport a real device gives a page: window-size flags at launch
151199 // are not honoured without a display, so this is what actually sets it.
152200 await cdp.send("Emulation.setDeviceMetricsOverride", {
153201 width: viewport.width,
154202 height: viewport.height,
155203 screenWidth: viewport.width,
156204 screenHeight: viewport.height,
157 deviceScaleFactor: 1,
158 mobile: true,
159 });
160 await cdp.send("Network.setCookie", {
161 name: cookie.name,
162 value: cookie.value,
163 url,
205 deviceScaleFactor: viewport.deviceScaleFactor ?? 1,
206 mobile: viewport.width < 720,
164207 });
208 if (cookie !== undefined)
209 await cdp.send("Network.setCookie", {
210 name: cookie.name,
211 value: cookie.value,
212 url,
213 });
165214 const loaded = cdp.once("Page.loadEventFired");
166215 await cdp.send("Page.navigate", { url });
167216 await loaded;
168217 const { result } = await cdp.send("Runtime.evaluate", {
169 expression: `(() => {
170 // documentElement.clientWidth, not window.innerWidth: after an
171 // in-process navigation under an active device-metrics override,
172 // headless Chromium leaves window.innerWidth stale while every
173 // other viewport-derived value (this one included) is current.
174 const vw = document.documentElement.clientWidth;
175 const overflowing = [...document.querySelectorAll("*")]
176 .filter((el) => el.getBoundingClientRect().right > vw + 1)
177 .slice(0, 8)
178 .map((el) =>
179 el.tagName.toLowerCase() +
180 (el.className && typeof el.className === "string"
181 ? "." + el.className.trim().split(/\\s+/).join(".")
182 : ""),
183 );
184 return JSON.stringify({
185 scrollWidth: document.documentElement.scrollWidth,
186 viewportWidth: vw,
187 overflowing,
188 });
189 })()`,
218 expression,
219 awaitPromise: true,
190220 returnByValue: true,
191221 });
192 return JSON.parse(result.value as string) as PageWidth;
222 return JSON.parse(result.value as string) as T;
193223 } finally {
194224 ws?.close();
195225 proc.kill("SIGKILL");
test/home-tiles.test.ts added +191
@@ -0,0 +1,191 @@
1 /**
2 * The signed-out home in a real, headless Chromium at a phone's width and
3 * a laptop's (issue #473): the app tile's picture is the whole first
4 * screen and never drawn larger than it was taken, the state badge is a
5 * word rather than a bar across the tile, and the hero's call to action
6 * stands clear of the shelf. Measured in the browser — the layout, not
7 * the CSS text, is what a person sees.
8 */
9
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { mkdirSync, writeFileSync } from "node:fs";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { dirname, join } from "node:path";
15 import { createApp, type App } from "../src/app.ts";
16 import { createRepo } from "../src/actions/repos.ts";
17 import { createApp as createAppRecord } from "../src/core/apps.ts";
18 import { LOOK_SIZES, recordLook, type LookKind } from "../src/core/looks.ts";
19 import { createUser } from "../src/core/users.ts";
20 import { encodePng } from "../src/design/image/png.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { findChromium } from "../src/looks/capture.ts";
23 import { lookPath } from "../src/looks/service.ts";
24 import { scaleThumb } from "../src/looks/thumb.ts";
25 import { evaluateInPage, type Viewport } from "./helpers/chrome.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 const chromium = findChromium();
31 if (chromium === undefined) {
32 console.log(
33 "SKIPPING: no chromium on this machine, so the home tile test cannot run",
34 );
35 }
36
37 interface TileGeometry {
38 /** Every picture on the shelf has loaded. */
39 loaded: boolean;
40 /** The picture the browser chose, its pixel width, and what it is drawn at. */
41 currentSrc: string;
42 naturalWidth: number;
43 drawnWidth: number;
44 drawnHeight: number;
45 devicePixelRatio: number;
46 objectFit: string;
47 objectPosition: string;
48 badgeWidth: number;
49 bodyWidth: number;
50 /** From the bottom of the hero's last button to the top of the shelf. */
51 heroGap: number;
52 scrollWidth: number;
53 viewportWidth: number;
54 }
55
56 const MEASURE = `(async () => {
57 const shelf = document.querySelector(".app-shelf");
58 const img = document.querySelector(".app-tile-look");
59 const imgs = [...document.querySelectorAll(".app-shelf img")];
60 const loaded = await Promise.race([
61 Promise.all(imgs.map((i) => i.decode().then(() => true, () => false)))
62 .then((all) => all.every(Boolean)),
63 new Promise((resolve) => setTimeout(() => resolve(false), 5000)),
64 ]);
65 const badge = document.querySelector(".app-tile-body > .badge");
66 const body = document.querySelector(".app-tile-body");
67 const buttons = [...document.querySelectorAll(".hero .btn")];
68 const ctaBottom = Math.max(...buttons.map((b) => b.getBoundingClientRect().bottom));
69 // naturalWidth under a w-descriptor srcset is corrected by the chosen
70 // density; the file's own pixels are what a plain image of it reports.
71 const plain = new Image();
72 plain.src = img.currentSrc;
73 await plain.decode();
74 const style = getComputedStyle(img);
75 return JSON.stringify({
76 loaded,
77 currentSrc: img.currentSrc,
78 naturalWidth: plain.naturalWidth,
79 drawnWidth: img.getBoundingClientRect().width,
80 drawnHeight: img.getBoundingClientRect().height,
81 devicePixelRatio: window.devicePixelRatio,
82 objectFit: style.objectFit,
83 objectPosition: style.objectPosition,
84 badgeWidth: badge.getBoundingClientRect().width,
85 bodyWidth: body.getBoundingClientRect().width,
86 heroGap: shelf.getBoundingClientRect().top - ctaBottom,
87 scrollWidth: document.documentElement.scrollWidth,
88 viewportWidth: document.documentElement.clientWidth,
89 });
90 })()`;
91
92 describe.skipIf(chromium === undefined)(
93 "the signed-out home's app tiles, in Chromium",
94 () => {
95 let dataDir: string;
96 let app: App;
97 let servers: Servers;
98
99 beforeAll(async () => {
100 dataDir = await mkdtemp(join(tmpdir(), "forge-home-tiles-"));
101 app = createApp({ dataDir, port: 0 });
102 servers = await serve(app);
103 const alice = await createUser(app.db, {
104 username: "alice",
105 email: "[email protected]",
106 password: "a-good-passphrase",
107 adminIfFirst: true,
108 });
109 if (!alice.ok) throw new Error(alice.error);
110 const repo = await createRepo(app, alice.value, {
111 name: "www",
112 visibility: "public",
113 description: "Cheffry's Dungeon, a place for scrims",
114 });
115 if (!repo.ok) throw new Error(String(repo.error));
116 const made = createAppRecord(app.db, {
117 repoId: repo.value.id,
118 slug: "www",
119 access: "public",
120 });
121 if (!made.ok) throw new Error(made.error);
122 const record = made.value;
123 // Production's look, as the service leaves it: a desktop picture
124 // and the thumb scaled from it.
125 const commitOid = "a".repeat(40);
126 const { width, height } = LOOK_SIZES.desktop;
127 const rgba = new Uint8Array(width * height * 4);
128 for (let i = 0; i < rgba.length; i += 4) {
129 const x = (i / 4) % width;
130 rgba[i] = x % 2 === 0 ? 30 : 220;
131 rgba[i + 1] = 120;
132 rgba[i + 2] = 200;
133 rgba[i + 3] = 255;
134 }
135 const desktop = encodePng(width, height, rgba);
136 const thumb = scaleThumb(desktop);
137 if (!thumb.ok) throw new Error(thumb.error);
138 const pictures: [LookKind, Uint8Array][] = [
139 ["desktop", desktop],
140 ["thumb", thumb.value],
141 ];
142 for (const [kind, bytes] of pictures) {
143 const path = lookPath(record.id, "production", commitOid, "/", kind);
144 mkdirSync(dirname(join(dataDir, path)), { recursive: true });
145 writeFileSync(join(dataDir, path), bytes);
146 recordLook(app.db, {
147 appId: record.id,
148 env: "production",
149 commitOid,
150 kind,
151 path,
152 });
153 }
154 }, 20_000);
155
156 afterAll(async () => {
157 servers.stop();
158 app.close();
159 await rm(dataDir, { recursive: true, force: true });
160 });
161
162 const widths: [string, Viewport][] = [
163 ["an iPhone 15, 393px at 3×", { width: 393, height: 852, deviceScaleFactor: 3 }],
164 ["a laptop, 1280px at 1×", { width: 1280, height: 800, deviceScaleFactor: 1 }],
165 ["a laptop, 1280px at 2×", { width: 1280, height: 800, deviceScaleFactor: 2 }],
166 ];
167
168 for (const [name, viewport] of widths)
169 test(`on ${name}: a sharp whole picture, a word-sized badge, room under the hero`, async () => {
170 const page = await evaluateInPage<TileGeometry>(
171 chromium!,
172 `${servers.url}/`,
173 viewport,
174 MEASURE,
175 );
176 expect(page.loaded).toBe(true);
177 // Never drawn larger than it was taken: as many picture pixels as
178 // the screen has device pixels across the tile.
179 expect(page.naturalWidth).toBeGreaterThanOrEqual(
180 Math.floor(page.drawnWidth * page.devicePixelRatio * 0.95),
181 );
182 expect(page.drawnHeight / page.drawnWidth).toBeCloseTo(800 / 1280, 1);
183 expect(page.objectFit).toBe("cover");
184 expect(page.objectPosition).toMatch(/^50% 0%|^center top/);
185 // A state is a word: nowhere near the tile's width.
186 expect(page.badgeWidth).toBeLessThan(page.bodyWidth / 2);
187 expect(page.heroGap).toBeGreaterThanOrEqual(24);
188 expect(page.scrollWidth).toBeLessThanOrEqual(page.viewportWidth);
189 }, 30_000);
190 },
191 );
test/looks-thumb.test.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * The thumb is the desktop picture, whole, at half its size — not the
3 * corner a small browser window keeps (issue #473). What is at the far
4 * corner of the desktop picture is at the far corner of the thumb.
5 */
6
7 import { describe, expect, test } from "bun:test";
8 import { decode } from "../src/design/image/image.ts";
9 import { encodePng } from "../src/design/image/png.ts";
10 import { LOOK_SIZES } from "../src/core/looks.ts";
11 import { scaleThumb } from "../src/looks/thumb.ts";
12
13 /** A 1280×800 white picture with a black 40×40 square in its bottom-right corner. */
14 function desktopWithCornerMark(): Uint8Array {
15 const w = 1280;
16 const h = 800;
17 const rgba = new Uint8Array(w * h * 4).fill(255);
18 for (let y = h - 40; y < h; y++)
19 for (let x = w - 40; x < w; x++) rgba.fill(0, (y * w + x) * 4, (y * w + x) * 4 + 3);
20 return encodePng(w, h, rgba);
21 }
22
23 describe("the thumb", () => {
24 test("is the desktop picture scaled to 640×400, every corner of it", () => {
25 const scaled = scaleThumb(desktopWithCornerMark());
26 if (!scaled.ok) throw new Error(scaled.error);
27 const image = decode(scaled.value);
28 if (!image.ok) throw new Error(image.error);
29 const { width, height, rgba } = image.value;
30 expect([width, height]).toEqual([640, 400]);
31 expect(LOOK_SIZES.thumb).toEqual({ width: 640, height: 400 });
32 const at = (x: number, y: number) => rgba[(y * width + x) * 4]!;
33 // The mark survives, scaled, where a corner crop would never reach.
34 expect(at(width - 5, height - 5)).toBe(0);
35 expect(at(width - 30, height - 30)).toBe(255);
36 expect(at(5, 5)).toBe(255);
37 });
38
39 test("is half the desktop picture, so the desktop picture is its exact 2× source", () => {
40 expect(LOOK_SIZES.desktop.width).toBe(LOOK_SIZES.thumb.width * 2);
41 expect(LOOK_SIZES.desktop.height).toBe(LOOK_SIZES.thumb.height * 2);
42 });
43
44 test("says why when the desktop picture is not a picture", () => {
45 const scaled = scaleThumb(new TextEncoder().encode("not a png"));
46 expect(scaled.ok).toBe(false);
47 });
48 });
test/looks.test.ts +33 −8
@@ -30,6 +30,7 @@ import type { Repo } from "../src/core/repos.ts";
3030 import { listRuns, type Run } from "../src/core/runs.ts";
3131 import { createUser, type User } from "../src/core/users.ts";
3232 import { serve, type Servers } from "../src/http/server.ts";
33 import { encodePng } from "../src/design/image/png.ts";
3334 import { err, ok } from "../src/kernel/result.ts";
3435 import { quietLogs } from "./helpers/globals.ts";
3536 import {
@@ -50,6 +51,11 @@ const PNG = Buffer.from(
5051 "base64",
5152 );
5253
54 /** A desktop-sized picture: the thumb is scaled from it, so it must be one. */
55 const DESKTOP_PNG = Buffer.from(
56 encodePng(1280, 800, new Uint8Array(1280 * 800 * 4).fill(255)),
57 );
58
5359 /** A PNG's width and height, from its IHDR. */
5460 const pngSize = (path: string): [number, number] => {
5561 const head = readFileSync(path).subarray(0, 24);
@@ -75,7 +81,7 @@ describe("the look", () => {
7581 const fake: Capture = async (input) => {
7682 calls.push(input);
7783 if (mode === "fail") return err("the browser fell over");
78 writeFileSync(input.out, PNG);
84 writeFileSync(input.out, input.width === 1280 ? DESKTOP_PNG : PNG);
7985 return ok();
8086 };
8187
@@ -200,8 +206,11 @@ describe("the look", () => {
200206 expect(existsSync(join(dataDir, look.path))).toBe(true);
201207 }
202208 // The browser was pointed at the grant door on the forge's own port,
203 // and the grant names the owner as an admin.
204 expect(calls).toHaveLength(3);
209 // and the grant names the owner as an admin. Twice: the thumb is not
210 // a shot of its own but the desktop picture, whole, at half its size.
211 expect(calls).toHaveLength(2);
212 const thumb = rows.find((l) => l.kind === "thumb")!;
213 expect(pngSize(join(dataDir, thumb.path))).toEqual([640, 400]);
205214 // Taken to one side and moved in whole: nothing half-written lives
206215 // under the environment, and nothing is left behind on the side.
207216 for (const call of calls)
@@ -210,7 +219,7 @@ describe("the look", () => {
210219 const phone = calls.find((c) => c.width === 390)!;
211220 expect(phone.height).toBe(844);
212221 expect(calls.find((c) => c.width === 1280)?.height).toBe(800);
213 expect(calls.find((c) => c.width === 200)?.height).toBe(125);
222 expect(calls.some((c) => c.width < 390)).toBe(false);
214223 const url = new URL(phone.url);
215224 expect(url.host).toBe(`hello.${DOMAIN}:${servers.port}`);
216225 expect(url.pathname).toBe("/__forge/grant");
@@ -240,8 +249,8 @@ describe("the look", () => {
240249 const env = previewEnv(pull.number);
241250 expect((await settled((r) => r.env === env)).state).toBe("ok");
242251 expect(await pictured(env, first)).toHaveLength(3);
243 expect(calls).toHaveLength(6);
244 expect(new URL(calls[3]!.url).hostname).toBe(
252 expect(calls).toHaveLength(4);
253 expect(new URL(calls[2]!.url).hostname).toBe(
245254 `hello--${pull.number}.${DOMAIN}`,
246255 );
247256
@@ -251,7 +260,7 @@ describe("the look", () => {
251260 (await settled((r) => r.env === env && r.reason === "redeploy")).state,
252261 ).toBe("ok");
253262 await looks.idle();
254 expect(calls).toHaveLength(6);
263 expect(calls).toHaveLength(4);
255264 expect(looksForEnv(app.db, record.id, env)).toHaveLength(3);
256265
257266 // A newer head is pictured, and the older head's pictures go.
@@ -266,7 +275,7 @@ describe("the look", () => {
266275 (await settled((r) => r.env === env && r.commitOid === second)).state,
267276 ).toBe("ok");
268277 expect(await pictured(env, second)).toHaveLength(3);
269 expect(calls).toHaveLength(9);
278 expect(calls).toHaveLength(6);
270279 await until(() =>
271280 looksForEnv(app.db, record.id, env).every((l) => l.commitOid === second)
272281 ? true
@@ -464,6 +473,22 @@ describe("the look", () => {
464473 ).toBe(true);
465474 }, 30_000);
466475
476 test("a thumb from before thumbs were scaled — a small corner crop — is refit from its desktop picture on boot", async () => {
477 const thumb = looksForEnv(app.db, record.id, "production").find(
478 (l) => l.kind === "thumb" && l.error === null,
479 )!;
480 const path = join(dataDir, thumb.path);
481 writeFileSync(path, PNG);
482 expect(pngSize(path)).toEqual([1, 1]);
483 const before = calls.length;
484 await looks.stop();
485 looks = startLooks(app, { localUrl: servers.url, capture: fake });
486 await looks.idle();
487 expect(pngSize(path)).toEqual([640, 400]);
488 // Rescaled, not retaken: the browser was not asked again.
489 expect(calls.length).toBe(before);
490 });
491
467492 test("two events for one environment, back to back, leave one queued look — at the newer commit", async () => {
468493 const before = calls.length;
469494 const live = runtime.envStatus(record, "production");
test/studio.test.ts +5 −3
@@ -1423,9 +1423,11 @@ describe("the studio", () => {
14231423 ),
14241424 );
14251425 expect(tile).toBeDefined();
1426 expect(tile).toContain(`/looks/production/${commit}/thumb.png`);
1427 expect(tile).toContain('width="200"');
1428 expect(tile).toContain('height="125"');
1426 expect(tile).toContain(`src="/${created.value.ownerName}/${created.value.name}/looks/production/${commit}/thumb.png"`);
1427 expect(tile).toContain('width="640"');
1428 expect(tile).toContain('height="400"');
1429 // The desktop picture of the same commit is the thumb's 2× source.
1430 expect(tile).toContain(`/looks/production/${commit}/desktop.png 1280w`);
14291431 });
14301432
14311433 test("the front door's tile still renders at desktop's size for a commit from before thumbs existed (#287)", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs