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

Website spec: Lighthouse lab LCP, CLS and INP for the looks pages, as a report (#2915 check 9) #2965

Parked opened this
Closed without merging

torque/forge:torque/2942-website-spec-lighthouse-lab-lcp-cls-and → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +1321 −20
docs/APPS.md +20
@@ -824,6 +824,26 @@ its pull closes. Files live under `<data>/looks/<app id>/<env>/`; rows in
824824 `look`. The browser is `chromium` (or `chromium-browser`, `google-chrome`)
825825 on `PATH`, `FORGE_CHROMIUM`, or the Mac's own; the image ships one. A forge
826826 without one says so once at boot, and on every pull.
827
828 **Lab vitals** (#2942, specification.website check 9 of #2915). After a
829 preview's pictures, each `app.looks` page is loaded once more in headless
830 Chromium, driven over its DevTools protocol (`src/looks/devtools.ts`; no
831 Lighthouse, no dependency), under Lighthouse's mobile conditions: 390×844,
832 CPU slowed 4×, 562.5 ms request latency, 1.47 Mbit/s down, 675 kbit/s up.
833 Performance observers put in before the page's own script report the
834 first contentful paint, LCP candidates, layout shifts and long tasks;
835 `src/looks/lab.ts` reduces them as Lighthouse does: LCP is the last
836 candidate, CLS the largest session window (1 s gap, 5 s cap, shifts after
837 input not counted), and TBT the long tasks' time past 50 ms after FCP. TBT
838 is the lab's proxy for INP. The pull shows a **Lab vitals** card under
839 the Look card. Each number sits beside the threshold specification.website
840 gives (LCP ≤ 2.5 s, CLS ≤ 0.1, INP ≤ 200 ms), and the card states the
841 conditions. It is a report only and never fails a check. The page is
842 loaded as the phone picture is, and seen by whoever may see that picture.
843 Each page is measured once per head, and a newer head's numbers replace
844 the older's. A load that fails is recorded with its reason. Production is
845 not measured. Rows are kept in `look_lab` and go with the preview.
846
827847 **A look a person attaches.** A person who can write the app (an agent
828848 cannot; the crew's looks come from the preview) attaches a picture to an
829849 open pull: `POST /api/v1/repos/:owner/:name/pulls/:number/looks` with JSON
docs/DESIGN.md +1 −1
@@ -377,7 +377,7 @@ gone, so this list only shrinks.
377377 - **`style/content.ts`, prose (markdown)** — table cell alignment, built by `markdown.ts` as `ta-${align}`: `.ta-c` `.ta-r`
378378 - **`style/content.ts`, diff viewer** — the diff table: its gutters, line kinds, file head and inline review comments: `.add` `.del` `.dh` `.diff` `.diff-body` `.diff-head` `.diff-note` `.diff-path` `.diff-stat` `.diff-stub` `.diff-summary` `.diff-table` `.dl` `.dl-review` `.dn` `.dn-comment` `.nonl` `.rc-body` `.rc-form` `.rc-head` `.rc-outdated` `.rc-resolved-line` `.wd`
379379 - **`style/content.ts`, review verdicts** — the body under a verdict: `.review-body`
380 - **`style/content.ts`, apps, runs, and the crew** — run pages, their logs, checks and look screenshots: `.app-url` `.check-progress` `.check-steps` `.ln-forge` `.ln-pulse` `.ln-say` `.ln-tool` `.ln-you` `.log-tail-row` `.look` `.look-attached` `.look-attached-phone` `.look-attachments` `.look-card` `.look-desktop` `.look-now` `.look-of` `.look-pair` `.look-phone` `.look-thumb` `.pinned-failures` `.pinned-slot` `.run-actions` `.run-jump` `.run-live` `.run-steer` `.run-summary` `.step-state` `.tests-bar` `.tests-words` `.txt` `.who`
380 - **`style/content.ts`, apps, runs, and the crew** — run pages, their logs, checks and look screenshots: `.app-url` `.check-progress` `.check-steps` `.lab-card` `.lab-good` `.lab-over` `.ln-forge` `.ln-pulse` `.ln-say` `.ln-tool` `.ln-you` `.log-tail-row` `.look` `.look-attached` `.look-attached-phone` `.look-attachments` `.look-card` `.look-desktop` `.look-now` `.look-of` `.look-pair` `.look-phone` `.look-thumb` `.pinned-failures` `.pinned-slot` `.run-actions` `.run-jump` `.run-live` `.run-steer` `.run-summary` `.step-state` `.tests-bar` `.tests-words` `.txt` `.who`
381381 - **`style/content.ts`, the code browser: explorer beside content** — the explorer column's own parts: `.code-main` `.code-split` `.ex-empty` `.ex-find` `.ex-head` `.ex-list` `.ex-name` `.ex-ref` `.ex-twist` `.explorer-toggle`
382382 - **`style/content.ts`, the finder** — the finder's footnote: `.finder-note`
383383 - **`style/content.ts`, the editor** — the editor's parts beyond the §5 row: `.editor-mirror` `.editor-path` `.editor-preview` `.editor-stack` `.editor-tab` `.mirrored` `.ml`
src/core/lab.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * Lab vitals on record (#2942): one row per page of an environment at a
3 * commit — the numbers one headless load came to (`looks/lab.ts`), or why
4 * there are none. Pure data: no authz, no events, no browser.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { id as newId } from "../kernel/id.ts";
9 import type { LabNumbers } from "../looks/lab.ts";
10
11 export interface Lab extends LabNumbers {
12 readonly appId: string;
13 readonly env: string;
14 readonly commitOid: string;
15 readonly page: string;
16 /** Why there are no numbers, when there are none. */
17 readonly error: string | null;
18 /** Who the page was loaded as: the owner (an admin), or nobody. */
19 readonly takenAs: "owner" | "nobody";
20 readonly createdAt: string;
21 }
22
23 interface Row {
24 app_id: string;
25 env: string;
26 commit_oid: string;
27 page: string;
28 fcp: number | null;
29 lcp: number | null;
30 cls: number | null;
31 tbt: number | null;
32 error: string | null;
33 taken_as: "owner" | "nobody";
34 created_at: string;
35 }
36
37 const toLab = (r: Row): Lab => ({
38 appId: r.app_id,
39 env: r.env,
40 commitOid: r.commit_oid,
41 page: r.page,
42 fcp: r.fcp,
43 lcp: r.lcp,
44 cls: r.cls ?? 0,
45 tbt: r.tbt ?? 0,
46 error: r.error,
47 takenAs: r.taken_as,
48 createdAt: r.created_at,
49 });
50
51 export interface RecordLabInput {
52 readonly appId: string;
53 readonly env: string;
54 readonly commitOid: string;
55 readonly page: string;
56 readonly takenAs: "owner" | "nobody";
57 /** The numbers, or the reason there are none. */
58 readonly numbers: LabNumbers | { readonly error: string };
59 }
60
61 /** Record one page's numbers, or why there are none. A remeasure replaces. */
62 export function recordLab(db: Database, input: RecordLabInput): void {
63 const n = "error" in input.numbers ? undefined : input.numbers;
64 db.query(
65 `INSERT INTO look_lab (id, app_id, env, commit_oid, page, fcp, lcp, cls, tbt, error, taken_as)
66 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
67 ON CONFLICT (app_id, env, commit_oid, page) DO UPDATE SET
68 fcp = excluded.fcp, lcp = excluded.lcp, cls = excluded.cls, tbt = excluded.tbt,
69 error = excluded.error, taken_as = excluded.taken_as,
70 created_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`,
71 ).run(
72 newId(),
73 input.appId,
74 input.env,
75 input.commitOid,
76 input.page,
77 n?.fcp ?? null,
78 n?.lcp ?? null,
79 n?.cls ?? null,
80 n?.tbt ?? null,
81 "error" in input.numbers ? input.numbers.error : null,
82 input.takenAs,
83 );
84 }
85
86 /** Every page's numbers for one environment, newest first. */
87 export function labForEnv(db: Database, appId: string, env: string): Lab[] {
88 return db
89 .query<Row, [string, string]>(
90 `SELECT * FROM look_lab WHERE app_id = ?1 AND env = ?2 ORDER BY created_at DESC, page`,
91 )
92 .all(appId, env)
93 .map(toLab);
94 }
95
96 /** Forget an environment's numbers — all of them, or all but one commit's. */
97 export function deleteLab(db: Database, appId: string, env: string, keepCommit?: string): void {
98 if (keepCommit === undefined)
99 db.query(`DELETE FROM look_lab WHERE app_id = ?1 AND env = ?2`).run(appId, env);
100 else
101 db.query(`DELETE FROM look_lab WHERE app_id = ?1 AND env = ?2 AND commit_oid != ?3`).run(
102 appId,
103 env,
104 keepCommit,
105 );
106 }
src/core/migrations/20261019233000-look-lab.ts added +21
@@ -0,0 +1,21 @@
1 // The lab vitals of a preview's look pages (#2942): one load of each page in
2 // headless Chromium, reduced to LCP, CLS and TBT, or the reason there are no
3 // numbers. A report beside the pictures, never a gate. Rows go with the app,
4 // and with the environment's pictures.
5 export default `
6 CREATE TABLE look_lab (
7 id TEXT PRIMARY KEY,
8 app_id TEXT NOT NULL REFERENCES app(id) ON DELETE CASCADE,
9 env TEXT NOT NULL,
10 commit_oid TEXT NOT NULL,
11 page TEXT NOT NULL,
12 fcp REAL,
13 lcp REAL,
14 cls REAL,
15 tbt REAL,
16 error TEXT,
17 taken_as TEXT NOT NULL CHECK (taken_as IN ('owner','nobody')),
18 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
19 UNIQUE (app_id, env, commit_oid, page)
20 );
21 `;
src/looks/capture.ts +32 −18
@@ -77,7 +77,11 @@ export function findChromium(): string | undefined {
7777 return undefined;
7878 }
7979
80 const gate = new Gate(1);
80 /**
81 * One browser at a time, forge-wide: a picture and a lab measurement
82 * (`devtools.ts`) take their turns at the same gate.
83 */
84 export const oneBrowser = new Gate(1);
8185
8286 /** Take one picture. Serialised: the second caller waits for the first. */
8387 export async function takeLook(
@@ -86,7 +90,7 @@ export async function takeLook(
8690 const binary = findChromium();
8791 if (binary === undefined)
8892 return err("no chromium on this forge: install one, or set FORGE_CHROMIUM");
89 const release = await gate.acquire();
93 const release = await oneBrowser.acquire();
9094 try {
9195 return await shoot(binary, input);
9296 } finally {
@@ -112,6 +116,31 @@ function pictureDone(path: string): boolean {
112116 }
113117 }
114118
119 /**
120 * How every browser here starts: headless, in a profile of its own, with the
121 * app's hostname pointed at the forge's own listener.
122 */
123 export function browserFlags(profile: string, host: string): string[] {
124 return [
125 "--headless=new",
126 // The forge runs as one unprivileged user with no user namespaces
127 // to give; the browser's own sandbox is not on offer here.
128 "--no-sandbox",
129 "--disable-gpu",
130 // Containers give /dev/shm 64 MB; the renderer must not depend on it.
131 "--disable-dev-shm-usage",
132 // No update checks, no push service, no safe-browsing fetches: the
133 // only network this browser needs is the forge's own port.
134 "--disable-background-networking",
135 "--disable-crash-reporter",
136 "--hide-scrollbars",
137 "--no-first-run",
138 `--user-data-dir=${profile}`,
139 // The app's hostname is the forge's own listener: no DNS, no edge.
140 `--host-resolver-rules=MAP ${host} 127.0.0.1`,
141 ];
142 }
143
115144 async function shoot(
116145 binary: string,
117146 input: LookInput,
@@ -124,22 +153,7 @@ async function shoot(
124153 const proc = Bun.spawn(
125154 [
126155 binary,
127 "--headless=new",
128 // The forge runs as one unprivileged user with no user namespaces
129 // to give; the browser's own sandbox is not on offer here.
130 "--no-sandbox",
131 "--disable-gpu",
132 // Containers give /dev/shm 64 MB; the renderer must not depend on it.
133 "--disable-dev-shm-usage",
134 // No update checks, no push service, no safe-browsing fetches: the
135 // only network this browser needs is the forge's own port.
136 "--disable-background-networking",
137 "--disable-crash-reporter",
138 "--hide-scrollbars",
139 "--no-first-run",
140 `--user-data-dir=${profile}`,
141 // The app's hostname is the forge's own listener: no DNS, no edge.
142 `--host-resolver-rules=MAP ${host} 127.0.0.1`,
156 ...browserFlags(profile, host),
143157 `--window-size=${input.width},${input.height}`,
144158 "--force-device-scale-factor=1",
145159 "--js-flags=--max-old-space-size=256",
src/looks/devtools.ts added +216
@@ -0,0 +1,216 @@
1 /**
2 * Measuring a page in a real browser (#2942): headless Chromium driven over
3 * its DevTools protocol, on the WebSocket the runtime already gives us — no
4 * Lighthouse, no dependency. One load, under the conditions `lab.ts` names
5 * (a phone's viewport, Lighthouse's mobile throttling), with performance
6 * observers put in the page before any of its own script; what they saw is
7 * read back once the page has loaded and settled, and reduced by `lab.ts`.
8 *
9 * The URL is the same grant door a picture is taken through
10 * (`capture.ts`), so the page measured is the page a person is served. The
11 * browser waits at the same gate as the pictures: one browser at a time.
12 */
13
14 import { mkdtempSync, rmSync } from "node:fs";
15 import { tmpdir } from "node:os";
16 import { join } from "node:path";
17 import { childEnv } from "../apps/process.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19 import { browserFlags, findChromium, oneBrowser } from "./capture.ts";
20 import {
21 LAB_CONDITIONS,
22 labNumbers,
23 OBSERVER_SCRIPT,
24 parseObserved,
25 type LabNumbers,
26 } from "./lab.ts";
27
28 export interface LabInput {
29 /** The URL to load — the grant door of the app's hostname, on the forge's own port. */
30 readonly url: string;
31 /** The whole allowance: a browser still at it by then is killed. */
32 readonly timeoutMs: number;
33 }
34
35 /** What measures a page: the real browser, or a test's stand-in. */
36 export type Measure = (input: LabInput) => Promise<Result<LabNumbers, string>>;
37
38 /** After the load event, how long late shifts and long tasks get to happen. */
39 export const SETTLE_MS = 2_000;
40
41 interface Message {
42 id?: number;
43 method?: string;
44 result?: Record<string, unknown>;
45 error?: { message?: string };
46 }
47
48 /** A DevTools session over one page's socket: commands answered by id, events waited for by name. */
49 class Session {
50 private next = 1;
51 private readonly answers = new Map<number, (m: Message) => void>();
52 private readonly events = new Map<string, () => void>();
53 private closed: string | undefined;
54
55 constructor(private readonly ws: WebSocket) {
56 ws.addEventListener("message", (event) => {
57 let m: Message;
58 try {
59 m = JSON.parse(String(event.data)) as Message;
60 } catch {
61 return;
62 }
63 if (typeof m.id === "number") {
64 this.answers.get(m.id)?.(m);
65 this.answers.delete(m.id);
66 } else if (typeof m.method === "string") {
67 this.events.get(m.method)?.();
68 this.events.delete(m.method);
69 }
70 });
71 ws.addEventListener("close", () => {
72 this.closed = "the browser closed its devtools socket";
73 for (const answer of this.answers.values()) answer({ error: { message: this.closed } });
74 this.answers.clear();
75 });
76 }
77
78 send(method: string, params: object = {}): Promise<Record<string, unknown>> {
79 if (this.closed !== undefined) return Promise.reject(new Error(this.closed));
80 const id = this.next++;
81 return new Promise((resolve, reject) => {
82 this.answers.set(id, (m) =>
83 m.error !== undefined
84 ? reject(new Error(`${method}: ${m.error.message ?? "refused"}`))
85 : resolve(m.result ?? {}),
86 );
87 this.ws.send(JSON.stringify({ id, method, params }));
88 });
89 }
90
91 /** The next time `method` fires. */
92 once(method: string): Promise<void> {
93 return new Promise((resolve) => this.events.set(method, resolve));
94 }
95 }
96
97 const sleep = (ms: number): Promise<"late"> => Bun.sleep(Math.max(0, ms)).then(() => "late");
98
99 /**
100 * Load `url` in the page behind `pageSocket` and come back with its numbers.
101 * Split from the browser's launch so the conversation can be held with a
102 * stand-in.
103 */
104 export async function measureOn(
105 pageSocket: string,
106 url: string,
107 deadline: number,
108 ): Promise<Result<LabNumbers, string>> {
109 const ws = new WebSocket(pageSocket);
110 try {
111 const opened = await Promise.race([
112 new Promise<"open" | "refused">((resolve) => {
113 ws.addEventListener("open", () => resolve("open"));
114 ws.addEventListener("error", () => resolve("refused"));
115 }),
116 sleep(deadline - Date.now()),
117 ]);
118 if (opened !== "open") return err("the browser's devtools socket did not open");
119 const s = new Session(ws);
120 await s.send("Page.enable");
121 await s.send("Network.enable");
122 await s.send("Emulation.setDeviceMetricsOverride", {
123 width: LAB_CONDITIONS.width,
124 height: LAB_CONDITIONS.height,
125 deviceScaleFactor: 1,
126 mobile: true,
127 });
128 await s.send("Emulation.setCPUThrottlingRate", { rate: LAB_CONDITIONS.cpuSlowdown });
129 await s.send("Network.emulateNetworkConditions", {
130 offline: false,
131 latency: LAB_CONDITIONS.latencyMs,
132 downloadThroughput: LAB_CONDITIONS.downloadBps,
133 uploadThroughput: LAB_CONDITIONS.uploadBps,
134 });
135 await s.send("Page.addScriptToEvaluateOnNewDocument", { source: OBSERVER_SCRIPT });
136 const loaded = s.once("Page.loadEventFired").then(() => "loaded" as const);
137 const nav = await s.send("Page.navigate", { url });
138 if (typeof nav["errorText"] === "string" && nav["errorText"] !== "")
139 return err(`the page did not load: ${nav["errorText"].slice(0, 200)}`);
140 if ((await Promise.race([loaded, sleep(deadline - Date.now())])) === "late")
141 return err("the page did not finish loading in the time it had");
142 await sleep(Math.min(SETTLE_MS, deadline - Date.now()));
143 const read = await s.send("Runtime.evaluate", {
144 expression: "window.__forgeLab()",
145 returnByValue: true,
146 });
147 if (read["exceptionDetails"] !== undefined) return err("the page's report could not be read");
148 const value = (read["result"] as { value?: unknown } | undefined)?.value;
149 const seen = parseObserved(value);
150 return typeof seen === "string" ? err(seen) : ok(labNumbers(seen));
151 } catch (error) {
152 return err(error instanceof Error ? error.message.slice(0, 300) : String(error));
153 } finally {
154 ws.close();
155 }
156 }
157
158 /** Chromium says where its devtools are on stderr, once it is ready. */
159 async function devtoolsAddress(stderr: ReadableStream<Uint8Array>): Promise<string> {
160 const reader = stderr.getReader();
161 const decoder = new TextDecoder();
162 let said = "";
163 try {
164 for (;;) {
165 const { done, value } = await reader.read();
166 if (done) throw new Error("chromium exited before it was ready to drive");
167 said += decoder.decode(value, { stream: true });
168 const found = /DevTools listening on (ws:\/\/(?:127\.0\.0\.1|\[::1\]|localhost):\d+\/\S+)/.exec(said);
169 if (found !== null) return found[1]!;
170 if (said.length > 64_000) said = said.slice(-1_000);
171 }
172 } finally {
173 reader.cancel().catch(() => {});
174 }
175 }
176
177 /** Measure one page. Serialised with the pictures: one browser at a time. */
178 export async function measureLab(input: LabInput): Promise<Result<LabNumbers, string>> {
179 const binary = findChromium();
180 if (binary === undefined)
181 return err("no chromium on this forge: install one, or set FORGE_CHROMIUM");
182 const release = await oneBrowser.acquire();
183 const deadline = Date.now() + input.timeoutMs;
184 const profile = mkdtempSync(join(tmpdir(), "forge-lab-"));
185 const proc = Bun.spawn(
186 [
187 binary,
188 ...browserFlags(profile, new URL(input.url).hostname),
189 // On loopback (the default), on a port the kernel picks.
190 "--remote-debugging-port=0",
191 "--js-flags=--max-old-space-size=256",
192 "about:blank",
193 ],
194 { env: childEnv({}), stdin: "ignore", stdout: "ignore", stderr: "pipe" },
195 );
196 try {
197 const address = await Promise.race([devtoolsAddress(proc.stderr), sleep(deadline - Date.now())]);
198 if (address === "late") return err("chromium was not ready to drive in time");
199 const http = address.replace(/^ws:/, "http:").replace(/\/devtools\/.*$/, "");
200 const targets = (await (await fetch(`${http}/json/list`)).json()) as {
201 type?: unknown;
202 webSocketDebuggerUrl?: unknown;
203 }[];
204 const page = targets.find((t) => t.type === "page");
205 if (page === undefined || typeof page.webSocketDebuggerUrl !== "string")
206 return err("chromium opened no page to drive");
207 return await measureOn(page.webSocketDebuggerUrl, input.url, deadline);
208 } catch (error) {
209 return err(error instanceof Error ? error.message.slice(0, 300) : String(error));
210 } finally {
211 proc.kill("SIGKILL");
212 await proc.exited.catch(() => {});
213 rmSync(profile, { recursive: true, force: true });
214 release();
215 }
216 }
src/looks/lab.ts added +233
@@ -0,0 +1,233 @@
1 /**
2 * Lab vitals (#2942, #2915 check 9): how fast a preview's look pages load in
3 * one headless Chromium run, as numbers beside the thresholds
4 * specification.website gives. A report, never a gate: nothing here fails a
5 * check.
6 *
7 * Plain data in, plain data out. The browser (`devtools.ts`) hands back the
8 * raw performance entries the page observed; this module validates them —
9 * they come from the app's own page, so they are an app's word, bounded like
10 * any other input — and reduces them the way Lighthouse does:
11 *
12 * - LCP: the `startTime` of the last `largest-contentful-paint` entry, in ms
13 * from navigation start (redirects included, as Lighthouse counts them).
14 * - CLS: the largest session window of `layout-shift` entries without recent
15 * input — a window closes after a 1 s gap or at 5 s long
16 * (web.dev/articles/evolving-cls).
17 * - TBT, the lab's stand-in for INP (web.dev/articles/tbt): for each long
18 * task after first contentful paint, the part of it past 50 ms; a task
19 * that straddles FCP counts from FCP on.
20 */
21
22 /** Where every finding points: the section of the specification it answers. */
23 export const LAB_SECTION = {
24 name: "Performance — Core Web Vitals",
25 url: "https://specification.website/",
26 } as const;
27
28 export type LabMetric = "lcp" | "cls" | "tbt";
29
30 export interface Threshold {
31 /** At or below this is good. */
32 readonly good: number;
33 /** How the threshold is written beside a number. */
34 readonly says: string;
35 }
36
37 /**
38 * The thresholds specification.website gives: LCP ≤ 2.5 s, CLS ≤ 0.1,
39 * INP ≤ 200 ms. TBT is judged against INP's: Lighthouse's own "good" TBT on
40 * mobile is the same 200 ms.
41 */
42 export const THRESHOLDS: Readonly<Record<LabMetric, Threshold>> = {
43 lcp: { good: 2500, says: "LCP ≤ 2.5 s" },
44 cls: { good: 0.1, says: "CLS ≤ 0.1" },
45 tbt: { good: 200, says: "INP ≤ 200 ms (TBT as its lab proxy)" },
46 };
47
48 /**
49 * How the page is loaded, written on the report so the numbers carry their
50 * conditions: a phone's viewport, and Lighthouse's mobile throttling
51 * (lighthouse-core/config/constants.js, `mobileSlow4G`, applied by devtools):
52 * 150 ms RTT × 3.75 = 562.5 ms of request latency, 1.6 Mbps × 0.9 down,
53 * 750 kbps × 0.9 up, and the CPU slowed 4×.
54 */
55 export const LAB_CONDITIONS = {
56 width: 390,
57 height: 844,
58 latencyMs: 562.5,
59 /** Bytes per second: 1638.4 kbit/s × 0.9 × 1024 / 8. */
60 downloadBps: (1638.4 * 0.9 * 1024) / 8,
61 /** Bytes per second: 750 kbit/s × 0.9 × 1024 / 8. */
62 uploadBps: (750 * 0.9 * 1024) / 8,
63 cpuSlowdown: 4,
64 } as const;
65
66 /** One line that says how the numbers were taken, in Lighthouse's units (1 kbit = 1024 bits). */
67 export const conditionsLine = (): string =>
68 `One load in headless Chromium at ${LAB_CONDITIONS.width}×${LAB_CONDITIONS.height}, ` +
69 `CPU slowed ${LAB_CONDITIONS.cpuSlowdown}×, network as Lighthouse's slow 4G ` +
70 `(${LAB_CONDITIONS.latencyMs} ms latency, ${((LAB_CONDITIONS.downloadBps * 8) / 1024 / 1000).toFixed(2)} Mbit/s down)`;
71
72 /** What the page observed, as it reported it — validated by {@link parseObserved}. */
73 export interface Observed {
74 readonly fcp: number | null;
75 readonly lcp: readonly number[];
76 readonly shifts: readonly {
77 readonly value: number;
78 readonly startTime: number;
79 readonly hadRecentInput: boolean;
80 }[];
81 readonly longTasks: readonly { readonly startTime: number; readonly duration: number }[];
82 }
83
84 /** The numbers one page load comes to. A metric the page never produced is null. */
85 export interface LabNumbers {
86 readonly fcp: number | null;
87 readonly lcp: number | null;
88 readonly cls: number;
89 readonly tbt: number;
90 }
91
92 /** A time no page load takes: past it an entry is not believed. */
93 const TIME_MAX = 600_000;
94 /** The most entries of one kind read from a page; the rest are dropped. */
95 const ENTRIES_MAX = 2_000;
96
97 const time = (v: unknown): number | undefined =>
98 typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= TIME_MAX ? v : undefined;
99
100 const list = (v: unknown): unknown[] | undefined =>
101 Array.isArray(v) ? v.slice(0, ENTRIES_MAX) : undefined;
102
103 const record = (v: unknown): Record<string, unknown> | undefined =>
104 typeof v === "object" && v !== null && !Array.isArray(v)
105 ? (v as Record<string, unknown>)
106 : undefined;
107
108 /** The page's report from its JSON text, or why it is not one. */
109 export function parseObserved(text: unknown): Observed | string {
110 if (typeof text !== "string" || text.length > 1_000_000) return "the page reported nothing";
111 let raw: unknown;
112 try {
113 raw = JSON.parse(text);
114 } catch {
115 return "the page's report is not JSON";
116 }
117 const body = record(raw);
118 if (body === undefined) return "the page's report is not an object";
119 const fcp = body["fcp"] === null ? null : time(body["fcp"]);
120 if (fcp === undefined) return "the page's first contentful paint is not a time";
121 const lcpRaw = list(body["lcp"]);
122 const shiftsRaw = list(body["shifts"]);
123 const tasksRaw = list(body["longTasks"]);
124 if (lcpRaw === undefined || shiftsRaw === undefined || tasksRaw === undefined)
125 return "the page's report is missing an entry list";
126 const lcp: number[] = [];
127 for (const v of lcpRaw) {
128 const t = time(v);
129 if (t === undefined) return "a largest contentful paint is not a time";
130 lcp.push(t);
131 }
132 const shifts: Observed["shifts"][number][] = [];
133 for (const v of shiftsRaw) {
134 const s = record(v);
135 const value = s === undefined ? undefined : s["value"];
136 const startTime = time(s?.["startTime"]);
137 if (
138 typeof value !== "number" ||
139 !Number.isFinite(value) ||
140 value < 0 ||
141 value > 100 ||
142 startTime === undefined ||
143 typeof s?.["hadRecentInput"] !== "boolean"
144 )
145 return "a layout shift is malformed";
146 shifts.push({ value, startTime, hadRecentInput: s["hadRecentInput"] });
147 }
148 const longTasks: Observed["longTasks"][number][] = [];
149 for (const v of tasksRaw) {
150 const t = record(v);
151 const startTime = time(t?.["startTime"]);
152 const duration = time(t?.["duration"]);
153 if (startTime === undefined || duration === undefined) return "a long task is malformed";
154 longTasks.push({ startTime, duration });
155 }
156 return { fcp, lcp, shifts, longTasks };
157 }
158
159 /** The largest session window of shifts without recent input (web.dev/articles/evolving-cls). */
160 export function clsOf(shifts: Observed["shifts"]): number {
161 const counted = shifts
162 .filter((s) => !s.hadRecentInput)
163 .toSorted((a, b) => a.startTime - b.startTime);
164 let best = 0;
165 let sum = 0;
166 let first = 0;
167 let last = 0;
168 for (const s of counted) {
169 if (sum > 0 && s.startTime - last < 1000 && s.startTime - first < 5000) {
170 sum += s.value;
171 } else {
172 sum = s.value;
173 first = s.startTime;
174 }
175 last = s.startTime;
176 best = Math.max(best, sum);
177 }
178 return best;
179 }
180
181 /** Long tasks' blocking time after first contentful paint (web.dev/articles/tbt). */
182 export function tbtOf(tasks: Observed["longTasks"], fcp: number | null): number {
183 let total = 0;
184 for (const task of tasks) {
185 const end = task.startTime + task.duration;
186 const from = fcp === null ? task.startTime : Math.max(task.startTime, fcp);
187 total += Math.max(0, end - from - 50);
188 }
189 return total;
190 }
191
192 /** What one load comes to. */
193 export function labNumbers(seen: Observed): LabNumbers {
194 return {
195 fcp: seen.fcp,
196 lcp: seen.lcp.length === 0 ? null : seen.lcp[seen.lcp.length - 1]!,
197 cls: clsOf(seen.shifts),
198 tbt: tbtOf(seen.longTasks, seen.fcp),
199 };
200 }
201
202 /** Whether a number is within its threshold. A metric never produced is unknown. */
203 export function rate(metric: LabMetric, value: number | null): "good" | "over" | "unknown" {
204 if (value === null) return "unknown";
205 return value <= THRESHOLDS[metric].good ? "good" : "over";
206 }
207
208 /** A number as the report writes it: seconds to two places, CLS to three, ms whole. */
209 export function shown(metric: LabMetric, value: number | null): string {
210 if (value === null) return "—";
211 if (metric === "lcp") return `${(value / 1000).toFixed(2)} s`;
212 if (metric === "cls") return value.toFixed(3);
213 return `${Math.round(value)} ms`;
214 }
215
216 /**
217 * What runs in the page before any of its own script: observers for each
218 * entry type, buffered so what happened before they were made is counted
219 * too, gathered on one global that `devtools.ts` reads back as JSON.
220 */
221 export const OBSERVER_SCRIPT = `(() => {
222 const seen = { fcp: null, lcp: [], shifts: [], longTasks: [] };
223 Object.defineProperty(window, "__forgeLab", { value: () => JSON.stringify(seen) });
224 const watch = (type, each) => {
225 try {
226 new PerformanceObserver((l) => l.getEntries().forEach(each)).observe({ type, buffered: true });
227 } catch {}
228 };
229 watch("paint", (e) => { if (e.name === "first-contentful-paint") seen.fcp = e.startTime; });
230 watch("largest-contentful-paint", (e) => seen.lcp.push(e.startTime));
231 watch("layout-shift", (e) => seen.shifts.push({ value: e.value, startTime: e.startTime, hadRecentInput: e.hadRecentInput }));
232 watch("longtask", (e) => seen.longTasks.push({ startTime: e.startTime, duration: e.duration }));
233 })();`;
src/looks/service.ts +65 −1
@@ -61,7 +61,9 @@ import { thumbnail } from "../design/image/image.ts";
6161 import { decodePng, encodePng, pngHeader } from "../design/image/png.ts";
6262 import { createLog } from "../kernel/log.ts";
6363 import { err, ok, type Result } from "../kernel/result.ts";
64 import { deleteLab, labForEnv, recordLab } from "../core/lab.ts";
6465 import { findChromium, takeLook, type Capture } from "./capture.ts";
66 import { measureLab, type Measure } from "./devtools.ts";
6567
6668 const log = createLog("looks");
6769
@@ -70,6 +72,12 @@ export interface LooksOptions {
7072 readonly localUrl: string;
7173 /** What takes the picture. Chromium unless a test says otherwise. */
7274 readonly capture?: Capture | undefined;
75 /**
76 * What measures a preview's pages (#2942). Chromium when the pictures are
77 * Chromium's; a test that stands in for the browser stands in for both,
78 * and without a stand-in here nothing is measured.
79 */
80 readonly measure?: Measure | undefined;
7381 /**
7482 * How full the process's memory is, 0 to 1, or undefined when unknown.
7583 * The container's cgroup unless a test says otherwise. A browser is the
@@ -135,6 +143,8 @@ const SWEEP_MS = 10 * 60_000;
135143 const FIRST_SWEEP_MS = 60_000;
136144 /** The browser's whole allowance for one picture. */
137145 const CAPTURE_TIMEOUT_MS = 20_000;
146 /** The browser's whole allowance for one lab load. */
147 const LAB_TIMEOUT_MS = 30_000;
138148 /** How long the grant in the URL is good for — the browser uses it at once. */
139149 const GRANT_TTL_MS = 60_000;
140150
@@ -202,6 +212,9 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
202212 const { dataDir } = app.config;
203213 const port = new URL(options.localUrl).port;
204214 const capture = options.capture ?? takeLook;
215 const measure =
216 options.measure ??
217 (options.capture === undefined ? measureLab : undefined);
205218 if (options.capture === undefined && findChromium() === undefined)
206219 log.warn(
207220 "no chromium on this forge: looks will say so instead of a picture (install one, or set FORGE_CHROMIUM)",
@@ -347,7 +360,18 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
347360 status.looks,
348361 item.swept === true,
349362 );
350 if (wanted.length === 0) return;
363 // Lab vitals are a pull's report: a preview's pages are measured, once
364 // per head, after their pictures.
365 const measured = new Set(
366 labForEnv(app.db, item.appId, item.env)
367 .filter((l) => l.commitOid === item.commitOid)
368 .map((l) => l.page),
369 );
370 const toMeasure =
371 measure === undefined || item.env === "production"
372 ? []
373 : (status.looks ?? [DEFAULT_PAGE]).filter((p) => !measured.has(p));
374 if (wanted.length === 0 && toMeasure.length === 0) return;
351375 // The phone and desktop pictures are what the owner sees: the app
352376 // renders for a signed-in admin, exactly as when they open it from the
353377 // forge. The thumb is what a stranger sees — it is the picture on the
@@ -438,6 +462,45 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
438462 recordLook(app.db, { ...row, kind, path: "", error: taken.error });
439463 }
440464 }
465 for (const page of toMeasure) {
466 if (stopped || measure === undefined) return;
467 const takenAs = asNobody("phone") ? "nobody" : "owner";
468 const token = signGrant(
469 dataDir,
470 { app: record, env: item.env },
471 GRANT_TTL_MS,
472 Date.now(),
473 takenAs === "nobody" ? undefined : asOwner,
474 );
475 const url = `http://${host}:${port}/__forge/grant?t=${encodeURIComponent(token)}&to=${encodeURIComponent(page)}`;
476 const numbers = await measure({ url, timeoutMs: LAB_TIMEOUT_MS });
477 // Numbers of a page nobody serves now are filed under no head.
478 const still = runtime.envStatus(record, item.env);
479 if (
480 stopped ||
481 still?.state !== "running" ||
482 still.commitOid !== item.commitOid
483 )
484 return;
485 if (!numbers.ok)
486 log.warn("no lab numbers", {
487 app: record.slug,
488 env: item.env,
489 page,
490 error: numbers.error,
491 });
492 recordLab(app.db, {
493 appId: item.appId,
494 env: item.env,
495 commitOid: item.commitOid,
496 page,
497 takenAs,
498 numbers: numbers.ok ? numbers.value : { error: numbers.error },
499 });
500 }
501 if (toMeasure.length > 0)
502 deleteLab(app.db, item.appId, item.env, item.commitOid);
503 if (wanted.length === 0) return;
441504 // A full set at this head is the environment's look now; the pictures
442505 // of heads before it have nothing left to say.
443506 if (allOk)
@@ -550,6 +613,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
550613 const at = queue.findIndex((q) => q.appId === appId && q.env === env);
551614 if (at !== -1) queue.splice(at, 1);
552615 deleteLooks(app.db, appId, env);
616 deleteLab(app.db, appId, env);
553617 rmSync(join(looksRoot(dataDir), appId, env), {
554618 recursive: true,
555619 force: true,
src/web/pages/lab.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * The lab vitals card on a pull (#2942, #2915 check 9): each look page's
3 * LCP, CLS and TBT from one headless load of the preview, each number with
4 * the threshold specification.website gives beside it, and the conditions
5 * the numbers were taken under. A report: it never fails the check above it.
6 *
7 * Who sees it is who sees the pictures (`looks.ts`, `mayFetchLook`): every
8 * writer; anyone else only numbers taken as nobody, of an app they may open,
9 * and never a sealed pull's.
10 */
11
12 import { previewEnv } from "../../apps/data.ts";
13 import type { AppRecord } from "../../core/apps.ts";
14 import { labForEnv, type Lab } from "../../core/lab.ts";
15 import { DEFAULT_PAGE } from "../../core/looks.ts";
16 import type { Pull } from "../../core/pulls.ts";
17 import { canEnterApp, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
18 import { sealedPreview } from "../../core/sealed.ts";
19 import type { Ctx } from "../../http/context.ts";
20 import {
21 conditionsLine,
22 LAB_SECTION,
23 rate,
24 shown,
25 THRESHOLDS,
26 type LabMetric,
27 } from "../../looks/lab.ts";
28 import { repoBase } from "../chrome.ts";
29 import { html, when, type Html } from "../html.ts";
30 import { card, icon, sha, time } from "../ui.ts";
31
32 const METRICS: readonly { metric: LabMetric; name: string }[] = [
33 { metric: "lcp", name: "LCP" },
34 { metric: "cls", name: "CLS" },
35 { metric: "tbt", name: "TBT" },
36 ];
37
38 /** The rows this viewer may read. */
39 export function labsFor(ctx: Ctx, repo: Repo, record: AppRecord, env: string): Lab[] {
40 const labs = labForEnv(ctx.app.db, record.id, env);
41 if (canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user)) return labs;
42 if (sealedPreview(ctx.app.db, repo.id, env)) return [];
43 if (!canEnterApp(ctx.app.db, repo, record, ctx.auth.user)) return [];
44 return labs.filter((l) => l.takenAs === "nobody");
45 }
46
47 /** One number, whether it is within its threshold, and the threshold. */
48 function cell(metric: LabMetric, value: number | null): Html {
49 const verdict = rate(metric, value);
50 return html`<td class="num">
51 <span class="${verdict === "unknown" ? "muted" : `lab-${verdict}`}">${shown(metric, value)}</span>
52 <span class="muted small"
53 >${verdict === "good" ? "within" : verdict === "over" ? "over" : "not measured;"}
54 ${THRESHOLDS[metric].says}</span
55 >
56 </td>`;
57 }
58
59 export function labCard(
60 ctx: Ctx,
61 repo: Repo,
62 record: AppRecord,
63 pull: Pull,
64 headOid: string,
65 ): Html {
66 const env = previewEnv(pull.number);
67 const writer = canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user);
68 const labs = labsFor(ctx, repo, record, env);
69 const head = html`${icon("activity")}
70 <h2>Lab vitals</h2>
71 <span class="muted small">report only — never fails the check</span>`;
72 if (labs.length === 0) {
73 if (!writer || pull.state !== "open" || pull.mergedAt !== null) return html``;
74 return card(
75 html`<p class="muted small">
76 No numbers yet. The preview's pages are measured after their pictures.
77 </p>`,
78 { head, extra: "lab-card" },
79 );
80 }
81 const base = repoBase(repo);
82 const rows = labs.toSorted((a, b) =>
83 a.page === DEFAULT_PAGE ? -1 : b.page === DEFAULT_PAGE ? 1 : a.page.localeCompare(b.page),
84 );
85 const of = rows[0]!;
86 return card(
87 html`<div class="table-scroll">
88 <table class="table">
89 <thead>
90 <tr>
91 <th>Page</th>
92 ${METRICS.map(({ name }) => html`<th class="num">${name}</th>`)}
93 </tr>
94 </thead>
95 <tbody>
96 ${rows.map((l) =>
97 l.error !== null
98 ? html`<tr>
99 <td><code>${l.page}</code></td>
100 <td colspan="3" class="muted">No numbers: ${l.error}</td>
101 </tr>`
102 : html`<tr>
103 <td><code>${l.page}</code></td>
104 ${cell("lcp", l.lcp)} ${cell("cls", l.cls)} ${cell("tbt", l.tbt)}
105 </tr>`,
106 )}
107 </tbody>
108 </table>
109 </div>
110 <p class="muted small mt">
111 at ${sha(of.commitOid, `${base}/commit/${of.commitOid}`)} · ${time(of.createdAt)}${when(
112 of.commitOid !== headOid,
113 () => html` · the head has moved since; new numbers follow its deploy`,
114 )}
115 </p>
116 <p class="muted small">
117 ${conditionsLine()}. TBT stands in for INP in the lab. Thresholds:
118 <a href="${LAB_SECTION.url}">specification.website</a>, ${LAB_SECTION.name}.
119 </p>`,
120 { head, extra: "lab-card" },
121 );
122 }
src/web/pages/variants.ts +2
@@ -24,6 +24,7 @@ import { flashTo, page } from "../layout.ts";
2424 import { changeHref } from "../studio/nouns.ts";
2525 import { btn, card } from "../ui.ts";
2626 import { previewCard } from "./apps.ts";
27 import { labCard } from "./lab.ts";
2728 import { lookCard } from "./looks.ts";
2829 import { parseNumber } from "./thread.ts";
2930
@@ -60,6 +61,7 @@ function deckCard(
6061 return html`<section class="variant-card" data-swipe>
6162 <h2><a href="${changeHref(base, pull.number)}">#${pull.number} ${pull.title}</a></h2>
6263 ${record === undefined ? null : lookCard(ctx, repo, record, pull, pull.headOid)}
64 ${record === undefined ? null : labCard(ctx, repo, record, pull, pull.headOid)}
6365 ${previewCard(ctx, repo, pull)}
6466 ${when(writer, () =>
6567 html`<div class="bar mt">
src/web/studio/change.ts +2
@@ -63,6 +63,7 @@ import {
6363 type Tone,
6464 } from "../ui.ts";
6565 import { previewCard } from "../pages/apps.ts";
66 import { labCard } from "../pages/lab.ts";
6667 import { lookCard } from "../pages/looks.ts";
6768 import { approveHereCard, pullChecksLineFor, teamsCard } from "../pages/pull.ts";
6869 import { teamVerdicts } from "../../core/issue_teams.ts";
@@ -594,6 +595,7 @@ async function changeConversation(
594595 ${when(wall, (w) => wallCard(w))} ${decisionSection}
595596 ${takeBackSection}
596597 ${when(record, (r) => lookCard(ctx, repo, r, pull, pull.headOid))}
598 ${when(record, (r) => labCard(ctx, repo, r, pull, pull.headOid))}
597599 <div class="split">
598600 <div>
599601 ${talk.node}
src/web/style/content.ts +5
@@ -886,6 +886,11 @@ form.inline { display: inline; margin-left: auto; }
886886 .look-thumb img { display: block; width: 100%; height: 100%; object-fit: cover; object-position: top; }
887887 .look-now { display: block; flex: none; width: 168px; border: 1px solid var(--border); border-radius: var(--radius-sm); overflow: hidden; background: var(--muted); }
888888 .look-now img { display: block; width: 100%; height: auto; }
889 /* Lab vitals: each number with its threshold beside it, coloured and worded
890 both, so the verdict never rests on colour alone. */
891 .lab-card .card-head { gap: 10px; flex-wrap: wrap; }
892 .lab-good { color: var(--success); white-space: nowrap; }
893 .lab-over { color: var(--danger); white-space: nowrap; }
889894 /* The checks line inside the merge box, in the reviews chip's voice. */
890895 .checks-line {
891896 display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
test/lab-service.test.ts added +213
@@ -0,0 +1,213 @@
1 /**
2 * Lab vitals on a pull (#2942): a preview that comes up green has its look
3 * pages measured once per head, through the same grant door as its
4 * pictures; production is not measured; the pull shows each number beside
5 * specification.website's threshold, as a report; the numbers go with the
6 * preview. A stand-in browser takes the pictures and the measurements.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { writeFileSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { newApp } from "../src/actions/apps.ts";
16 import { setIssueStateThrough } from "../src/actions/issues.ts";
17 import { openPull } from "../src/actions/pulls.ts";
18 import { commitToBranch } from "../src/actions/repos.ts";
19 import { previewEnv } from "../src/apps/data.ts";
20 import { readGrant } from "../src/apps/proxy.ts";
21 import { AppsRuntime } from "../src/apps/runtime.ts";
22 import type { AppRecord } from "../src/core/apps.ts";
23 import { labForEnv, type Lab } from "../src/core/lab.ts";
24 import type { Pull } from "../src/core/pulls.ts";
25 import type { Repo } from "../src/core/repos.ts";
26 import { listRuns, type Run } from "../src/core/runs.ts";
27 import { createUser, type User } from "../src/core/users.ts";
28 import { serve, type Servers } from "../src/http/server.ts";
29 import { err, ok } from "../src/kernel/result.ts";
30 import type { Capture } from "../src/looks/capture.ts";
31 import type { LabInput, Measure } from "../src/looks/devtools.ts";
32 import { startLooks, type LooksHandle } from "../src/looks/service.ts";
33 import { quietLogs } from "./helpers/globals.ts";
34
35 quietLogs();
36
37 const DOMAIN = "apps.test";
38 const PASSWORD = "a-good-passphrase";
39 const PNG = Buffer.from(
40 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
41 "base64",
42 );
43
44 describe("lab vitals on a pull", () => {
45 let dataDir: string;
46 let app: App;
47 let servers: Servers;
48 let runtime: AppsRuntime;
49 let looks: LooksHandle;
50 let alice: User;
51 let repo: Repo;
52 let record: AppRecord;
53 let cookie: string;
54 let pull: Pull;
55 let head = "";
56
57 const capture: Capture = async (input) => {
58 writeFileSync(input.out, PNG);
59 return ok();
60 };
61 let measuring: "ok" | "fail" = "ok";
62 const measured: LabInput[] = [];
63 const measure: Measure = async (input) => {
64 measured.push(input);
65 if (measuring === "fail") return err("the browser fell over");
66 return ok({ fcp: 400, lcp: 1200, cls: 0.02, tbt: 350 });
67 };
68
69 async function until<T>(read: () => T | undefined, timeoutMs = 60_000): Promise<T> {
70 const deadline = Date.now() + timeoutMs;
71 while (Date.now() < deadline) {
72 const value = read();
73 if (value !== undefined) return value;
74 await Bun.sleep(100);
75 }
76 throw new Error("did not happen in time");
77 }
78
79 const settled = (where: (run: Run) => boolean): Promise<Run> =>
80 until(() => {
81 const run = listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find(where);
82 return run && run.state !== "queued" && run.state !== "running" ? run : undefined;
83 });
84
85 const labOf = (env: string, commitOid: string): Promise<Lab> =>
86 until(() => labForEnv(app.db, record.id, env).find((l) => l.commitOid === commitOid), 30_000);
87
88 const page = async (path: string): Promise<string> =>
89 (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
90
91 beforeAll(async () => {
92 dataDir = await mkdtemp(join(tmpdir(), "forge-lab-"));
93 app = createApp({ dataDir, port: 0 });
94 servers = await serve(app);
95 runtime = new AppsRuntime(app, {
96 domain: DOMAIN,
97 scheme: "http",
98 publicPort: servers.port,
99 forgeUrl: servers.url,
100 concurrency: 2,
101 });
102 await runtime.start();
103 looks = startLooks(app, { localUrl: servers.url, capture, measure });
104 const a = await createUser(app.db, {
105 origin: "seed",
106 trusted: true,
107 username: "alice",
108 email: "[email protected]",
109 password: PASSWORD,
110 adminIfFirst: true,
111 });
112 if (!a.ok) throw new Error(a.error);
113 alice = a.value;
114 const signin = await fetch(`${servers.url}/signin`, {
115 method: "POST",
116 body: new URLSearchParams({ username: "alice", password: PASSWORD }),
117 redirect: "manual",
118 });
119 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
120 const made = await newApp(app, alice, { name: "hello", visibility: "private" });
121 if (!made.ok) throw new Error(String(made.error));
122 repo = made.value.repo;
123 record = made.value.app;
124 }, 30_000);
125
126 afterAll(async () => {
127 await looks.stop();
128 await runtime.stop();
129 servers.stop();
130 app.close();
131 await rm(dataDir, { recursive: true, force: true });
132 });
133
134 test("production is pictured, not measured; a preview is measured once per head, through the grant door, as the owner", async () => {
135 const production = await settled((r) => r.env === "production");
136 expect(production.state).toBe("ok");
137 await looks.idle();
138 expect(labForEnv(app.db, record.id, "production")).toEqual([]);
139 expect(measured).toHaveLength(0);
140
141 const committed = await commitToBranch(app, alice, repo, {
142 branch: "greeting",
143 base: repo.defaultBranch,
144 message: "Say hello",
145 files: [{ path: "GREETING.md", content: "hi\n" }],
146 });
147 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
148 head = committed.value.commitOid;
149 const opened = await openPull(app, alice, repo, {
150 title: "Say hello",
151 baseBranch: repo.defaultBranch,
152 headBranch: "greeting",
153 });
154 if (!opened.ok) throw new Error(String(opened.error));
155 pull = opened.value;
156 const env = previewEnv(pull.number);
157 expect((await settled((r) => r.env === env)).state).toBe("ok");
158 const lab = await labOf(env, head);
159 expect(lab).toMatchObject({ page: "/", fcp: 400, lcp: 1200, cls: 0.02, tbt: 350, error: null, takenAs: "owner" });
160 expect(measured).toHaveLength(1);
161 const url = new URL(measured[0]!.url);
162 expect(url.hostname).toBe(`hello--${pull.number}.${DOMAIN}`);
163 expect(url.pathname).toBe("/__forge/grant");
164 expect(url.searchParams.get("to")).toBe("/");
165 const grant = readGrant(dataDir, url.searchParams.get("t") ?? "", { app: record, env });
166 expect(grant?.who).toEqual({ id: alice.id, name: "alice", role: "admin" });
167
168 // The same head green again is not measured again.
169 runtime.requestDeploy(record, repo, env, head, "redeploy");
170 expect((await settled((r) => r.env === env && r.reason === "redeploy")).state).toBe("ok");
171 await looks.idle();
172 expect(measured).toHaveLength(1);
173 }, 120_000);
174
175 test("the pull shows each number beside specification.website's threshold, as a report", async () => {
176 const html = await page(`/alice/hello/pulls/${pull.number}`);
177 expect(html).toContain("<h2>Lab vitals</h2>");
178 expect(html).toContain("report only — never fails the check");
179 // 1.2 s is within LCP ≤ 2.5 s; 0.020 within CLS ≤ 0.1; 350 ms of TBT is over INP's 200 ms.
180 expect(html).toMatch(/lab-good">1\.20 s<\/span>\s*<span class="muted small"\s*>within\s*LCP ≤ 2\.5 s/);
181 expect(html).toMatch(/lab-good">0\.020<\/span>\s*<span class="muted small"\s*>within\s*CLS ≤ 0\.1/);
182 expect(html).toMatch(/lab-over">350 ms<\/span>\s*<span class="muted small"\s*>over\s*INP ≤ 200 ms/);
183 expect(html).toContain("https://specification.website/");
184 expect(html).toContain("CPU slowed 4×");
185 expect(html).toContain(head.slice(0, 7));
186 });
187
188 test("a measurement that fails says why on the pull, and a newer head's numbers replace the older's", async () => {
189 measuring = "fail";
190 const again = await commitToBranch(app, alice, repo, {
191 branch: "greeting",
192 message: "More greeting",
193 files: [{ path: "GREETING.md", content: "hi again\n" }],
194 });
195 if (!again.ok) throw new Error(JSON.stringify(again.error));
196 const env = previewEnv(pull.number);
197 const lab = await labOf(env, again.value.commitOid);
198 expect(lab.error).toBe("the browser fell over");
199 expect(labForEnv(app.db, record.id, env).map((l) => l.commitOid)).toEqual([again.value.commitOid]);
200 const html = await page(`/alice/hello/pulls/${pull.number}`);
201 expect(html).toContain("No numbers: the browser fell over");
202 measuring = "ok";
203 }, 120_000);
204
205 test("a closed pull's numbers go with its preview", async () => {
206 const env = previewEnv(pull.number);
207 expect(labForEnv(app.db, record.id, env).length).toBeGreaterThan(0);
208 const closed = await setIssueStateThrough(app, alice, repo, pull, "closed");
209 expect(closed.ok).toBe(true);
210 expect(labForEnv(app.db, record.id, env)).toEqual([]);
211 expect(await page(`/alice/hello/pulls/${pull.number}`)).not.toContain("Lab vitals");
212 });
213 });
test/lab.test.ts added +283
@@ -0,0 +1,283 @@
1 /**
2 * Lab vitals (#2942, #2915 check 9): the arithmetic against hand
3 * calculations, the page's report refused when it is not one, the DevTools
4 * conversation against a stand-in browser, and — where this machine has
5 * Chromium — one real load of a page that shifts and blocks on purpose.
6 */
7
8 import { afterAll, describe, expect, test } from "bun:test";
9 import {
10 clsOf,
11 conditionsLine,
12 LAB_CONDITIONS,
13 LAB_SECTION,
14 labNumbers,
15 OBSERVER_SCRIPT,
16 parseObserved,
17 rate,
18 shown,
19 tbtOf,
20 THRESHOLDS,
21 } from "../src/looks/lab.ts";
22 import { findChromium } from "../src/looks/capture.ts";
23 import { measureLab, measureOn } from "../src/looks/devtools.ts";
24
25 const shift = (startTime: number, value: number, hadRecentInput = false) => ({
26 startTime,
27 value,
28 hadRecentInput,
29 });
30
31 describe("the thresholds", () => {
32 test("are specification.website's: LCP ≤ 2.5 s, CLS ≤ 0.1, INP ≤ 200 ms, each written beside its number", () => {
33 expect(THRESHOLDS.lcp).toEqual({ good: 2500, says: "LCP ≤ 2.5 s" });
34 expect(THRESHOLDS.cls).toEqual({ good: 0.1, says: "CLS ≤ 0.1" });
35 expect(THRESHOLDS.tbt.good).toBe(200);
36 expect(THRESHOLDS.tbt.says).toContain("INP ≤ 200 ms");
37 expect(LAB_SECTION.url).toStartWith("https://specification.website/");
38 });
39
40 test("at the threshold is good, past it is over, unmeasured is unknown", () => {
41 expect(rate("lcp", 2500)).toBe("good");
42 expect(rate("lcp", 2500.1)).toBe("over");
43 expect(rate("cls", 0.1)).toBe("good");
44 expect(rate("cls", 0.1001)).toBe("over");
45 expect(rate("tbt", 200)).toBe("good");
46 expect(rate("tbt", 201)).toBe("over");
47 expect(rate("lcp", null)).toBe("unknown");
48 });
49
50 test("numbers are written in the threshold's unit", () => {
51 expect(shown("lcp", 1234)).toBe("1.23 s");
52 expect(shown("cls", 0.04567)).toBe("0.046");
53 expect(shown("tbt", 149.6)).toBe("150 ms");
54 expect(shown("lcp", null)).toBe("—");
55 });
56
57 test("the conditions are Lighthouse's mobile throttling, in the units the protocol takes", () => {
58 // 150 ms RTT × 3.75; 1.6 Mbit/s × 1024 × 0.9 / 8 bytes; 750 kbit/s × 1024 × 0.9 / 8 bytes.
59 expect(LAB_CONDITIONS.latencyMs).toBe(562.5);
60 expect(LAB_CONDITIONS.downloadBps).toBeCloseTo(188_743.68, 2);
61 expect(LAB_CONDITIONS.uploadBps).toBe(86_400);
62 expect(LAB_CONDITIONS.cpuSlowdown).toBe(4);
63 expect(conditionsLine()).toBe(
64 "One load in headless Chromium at 390×844, CPU slowed 4×, network as Lighthouse's slow 4G (562.5 ms latency, 1.47 Mbit/s down)",
65 );
66 });
67 });
68
69 describe("CLS: the largest session window", () => {
70 test("a gap of a second or more starts a new window; shifts after input do not count", () => {
71 // Window one: 0.05 + 0.05 = 0.10. The shift at 1600 is 1100 ms after
72 // the last: window two, 0.20 + 0.03 = 0.23 (the 0.5 at 1700 followed
73 // input). The largest is 0.23.
74 const cls = clsOf([
75 shift(0, 0.05),
76 shift(500, 0.05),
77 shift(1600, 0.2),
78 shift(1700, 0.5, true),
79 shift(2000, 0.03),
80 ]);
81 expect(cls).toBeCloseTo(0.23, 10);
82 });
83
84 test("a window is at most five seconds long", () => {
85 // Every 900 ms, 0.02 each: 0, 900 … 4500 are one window (6 × 0.02 =
86 // 0.12); 5400 is 5.4 s after the window opened and starts another.
87 const cls = clsOf(
88 [0, 900, 1800, 2700, 3600, 4500, 5400].map((t) => shift(t, 0.02)),
89 );
90 expect(cls).toBeCloseTo(0.12, 10);
91 });
92
93 test("order does not matter, and no shifts is zero", () => {
94 expect(clsOf([shift(500, 0.05), shift(0, 0.05)])).toBeCloseTo(0.1, 10);
95 expect(clsOf([])).toBe(0);
96 });
97 });
98
99 describe("TBT: blocking past 50 ms after first contentful paint", () => {
100 test("by hand: tasks before FCP do not count, one straddling it counts from FCP", () => {
101 // FCP at 1000 ms.
102 // 500 + 200 → ends at 700, before FCP: 0
103 // 900 + 300 → 1000..1200 counts, 200 − 50: 150
104 // 2000 + 120 → 120 − 50: 70
105 // 3000 + 50 → exactly 50, nothing past it: 0
106 // 220
107 const tasks = [
108 { startTime: 500, duration: 200 },
109 { startTime: 900, duration: 300 },
110 { startTime: 2000, duration: 120 },
111 { startTime: 3000, duration: 50 },
112 ];
113 expect(tbtOf(tasks, 1000)).toBe(220);
114 // With no paint, every task counts whole: 150 + 250 + 70 + 0.
115 expect(tbtOf(tasks, null)).toBe(470);
116 });
117
118 test("one load's numbers: LCP is the last candidate", () => {
119 expect(
120 labNumbers({
121 fcp: 400,
122 lcp: [420, 1800],
123 shifts: [shift(100, 0.02)],
124 longTasks: [{ startTime: 500, duration: 90 }],
125 }),
126 ).toEqual({ fcp: 400, lcp: 1800, cls: 0.02, tbt: 40 });
127 expect(labNumbers({ fcp: null, lcp: [], shifts: [], longTasks: [] })).toEqual({
128 fcp: null,
129 lcp: null,
130 cls: 0,
131 tbt: 0,
132 });
133 });
134 });
135
136 describe("the page's report is the app's word, validated", () => {
137 const good = { fcp: 10, lcp: [20], shifts: [shift(5, 0.01)], longTasks: [{ startTime: 1, duration: 60 }] };
138 test("a well-formed report is read", () => {
139 expect(parseObserved(JSON.stringify(good))).toEqual(good);
140 expect(parseObserved(JSON.stringify({ ...good, fcp: null }))).toEqual({ ...good, fcp: null });
141 });
142
143 test("anything else is refused with a reason", () => {
144 const refused = (v: unknown) => expect(typeof parseObserved(v)).toBe("string");
145 refused(undefined);
146 refused(42);
147 refused("not json");
148 refused("[]");
149 refused(JSON.stringify({ ...good, fcp: -1 }));
150 refused(JSON.stringify({ ...good, fcp: "10" }));
151 refused(JSON.stringify({ ...good, lcp: [1e12] }));
152 refused(JSON.stringify({ ...good, lcp: "20" }));
153 refused(JSON.stringify({ ...good, shifts: [{ value: 0.1, startTime: 1 }] }));
154 refused(JSON.stringify({ ...good, shifts: [{ value: -0.1, startTime: 1, hadRecentInput: false }] }));
155 refused(JSON.stringify({ ...good, longTasks: [{ startTime: 1 }] }));
156 refused(JSON.stringify({ fcp: 1, lcp: [] }));
157 refused("x".repeat(1_000_001));
158 });
159
160 test("a report of a million entries is read only to its bound", () => {
161 const many = { ...good, longTasks: Array.from({ length: 5000 }, (_, i) => ({ startTime: i, duration: 51 })) };
162 const seen = parseObserved(JSON.stringify(many));
163 if (typeof seen === "string") throw new Error(seen);
164 expect(seen.longTasks).toHaveLength(2000);
165 });
166 });
167
168 describe("the DevTools conversation, with a stand-in browser", () => {
169 type Said = { id: number; method: string; params: Record<string, unknown> };
170 const said: Said[] = [];
171 let behaviour: "ok" | "unreachable" | "never-loads" = "ok";
172 const report = JSON.stringify({
173 fcp: 300,
174 lcp: [350, 900],
175 shifts: [shift(400, 0.04), shift(800, 0.03)],
176 longTasks: [{ startTime: 1000, duration: 130 }],
177 });
178 const answerEvent = (ws: { send(s: string): unknown }): void => {
179 ws.send(JSON.stringify({ method: "Page.loadEventFired", params: { timestamp: 1 } }));
180 };
181 const browser = Bun.serve({
182 port: 0,
183 hostname: "127.0.0.1",
184 fetch(request, server) {
185 return server.upgrade(request) ? undefined : new Response("no", { status: 400 });
186 },
187 websocket: {
188 message(ws, data): void {
189 const m = JSON.parse(String(data)) as Said;
190 said.push(m);
191 const answer = (result: object): void => {
192 ws.send(JSON.stringify({ id: m.id, result }));
193 };
194 if (m.method === "Page.navigate") {
195 if (behaviour === "unreachable") return answer({ frameId: "f", errorText: "net::ERR_CONNECTION_REFUSED" });
196 answer({ frameId: "f" });
197 if (behaviour === "ok") answerEvent(ws);
198 return;
199 }
200 if (m.method === "Runtime.evaluate") return answer({ result: { type: "string", value: report } });
201 answer({});
202 },
203 },
204 });
205 afterAll(() => browser.stop(true));
206 const socket = `ws://127.0.0.1:${browser.port}/devtools/page/1`;
207
208 test("throttles like Lighthouse, observes before the page's own script, and reads back the numbers", async () => {
209 said.length = 0;
210 behaviour = "ok";
211 const got = await measureOn(socket, "http://hello.apps.test:1/__forge/grant?t=x&to=%2F", Date.now() + 10_000);
212 expect(got).toEqual({ ok: true, value: { fcp: 300, lcp: 900, cls: 0.07, tbt: 80 } });
213 const by = (method: string) => said.find((m) => m.method === method)?.params;
214 expect(by("Emulation.setCPUThrottlingRate")).toEqual({ rate: 4 });
215 expect(by("Network.emulateNetworkConditions")).toEqual({
216 offline: false,
217 latency: 562.5,
218 downloadThroughput: LAB_CONDITIONS.downloadBps,
219 uploadThroughput: 86_400,
220 });
221 expect(by("Emulation.setDeviceMetricsOverride")).toMatchObject({ width: 390, height: 844, mobile: true });
222 expect(by("Page.addScriptToEvaluateOnNewDocument")).toEqual({ source: OBSERVER_SCRIPT });
223 expect(by("Page.navigate")).toEqual({ url: "http://hello.apps.test:1/__forge/grant?t=x&to=%2F" });
224 // The observers go in before the page is asked for.
225 const order = said.map((m) => m.method);
226 expect(order.indexOf("Page.addScriptToEvaluateOnNewDocument")).toBeLessThan(order.indexOf("Page.navigate"));
227 expect(order.at(-1)).toBe("Runtime.evaluate");
228 }, 15_000);
229
230 test("a page that does not load is a reason, not numbers", async () => {
231 behaviour = "unreachable";
232 const refused = await measureOn(socket, "http://x.test/", Date.now() + 5_000);
233 expect(refused).toEqual({ ok: false, error: "the page did not load: net::ERR_CONNECTION_REFUSED" });
234 behaviour = "never-loads";
235 const late = await measureOn(socket, "http://x.test/", Date.now() + 300);
236 expect(late).toEqual({ ok: false, error: "the page did not finish loading in the time it had" });
237 }, 15_000);
238
239 test("a socket nobody answers is a reason", async () => {
240 const closed = await measureOn("ws://127.0.0.1:1/devtools/page/1", "http://x.test/", Date.now() + 2_000);
241 expect(closed.ok).toBe(false);
242 });
243 });
244
245 const chromium = findChromium();
246 test.skipIf(chromium === undefined)(
247 chromium === undefined
248 ? "a real load — skipped: no chromium on this machine (install one, or set FORGE_CHROMIUM)"
249 : `a real load of a page that shifts and blocks, with ${chromium}`,
250 async () => {
251 // Text paints, then 200 px is pushed in above it (a shift), then the
252 // main thread is held for 300 ms: a long task, 250 ms of it blocking.
253 const page = Bun.serve({
254 port: 0,
255 hostname: "127.0.0.1",
256 fetch: () =>
257 new Response(
258 `<!doctype html><html lang="en"><meta name="viewport" content="width=device-width">
259 <h1>Measured</h1><p style="height:400px">A page that moves.</p>
260 <script>
261 setTimeout(() => {
262 const d = document.createElement("div");
263 d.style.height = "200px";
264 document.body.prepend(d);
265 setTimeout(() => { const end = performance.now() + 300; while (performance.now() < end); }, 100);
266 }, 300);
267 </script>`,
268 { headers: { "content-type": "text/html" } },
269 ),
270 });
271 try {
272 const got = await measureLab({ url: `http://localhost:${page.port}/`, timeoutMs: 30_000 });
273 if (!got.ok) throw new Error(got.error);
274 expect(got.value.fcp).toBeGreaterThan(0);
275 expect(got.value.lcp).toBeGreaterThan(0);
276 expect(got.value.cls).toBeGreaterThan(0.05);
277 expect(got.value.tbt).toBeGreaterThan(100);
278 } finally {
279 page.stop(true);
280 }
281 },
282 60_000,
283 );

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs