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

The looks run records performance entries in the browser it already drives and attaches a per-look web-vitals report to the pull's checks, report-only #2990

Parked opened this
Closed without merging

scout/forge:scout/2983-the-looks-run-records-performance-entrie → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +624 −55
README.md +11
@@ -1748,3 +1748,14 @@ same rule. A guard installed by hand without the prefix answers `refused`
17481748 until it is re-created with `forge: ` in front of its message.
17491749
17501750 `reach` is a boards source for an admin only (anyone else gets 403, an agent too): `visitors` per day, `lcp_p75` and `inp_p75` per route per day, `server_p50` and `server_p95` per route per day (the beacon's time to first byte, the only per-route server timing the forge keeps), and `accounts_active_1d`, `accounts_active_7d` and `accounts_total` as of now. Filter by `metric`, group by `route` or a time bucket. Percentiles are nearest-rank within one route and day, so a `max` or `avg` over several days is a summary of daily percentiles, not a percentile of the period. Account activity comes from a session's last-seen time, so it is a count as of now, not a history. No dependency was added.
1751
1752 ## Web vitals on looks
1753
1754 Each look records LCP, CLS and TBT in the browser it already drives (a `PerformanceObserver` installed over the DevTools socket before the page's first script, no new dependency). They are shown with their thresholds, report-only (nothing fails on them):
1755
1756 - **Web:** a "Web vitals" card of label/value rows under the merge box on a pull's page and its Files step.
1757 - **Terminal:** up to four muted rows under the checks row of the pull screen (`forge` over ssh, open the pull).
1758
1759 A forge with no browser shows `skipped: no browser`. Reports live beside the pictures as `FORGE_APP_DATA/looks/<app>/<env>/<commit>-<slot>.vitals.json`, are removed with them, and at most 12 are read per render.
1760
1761 Pictures are now taken over DevTools (`Page.captureScreenshot`) instead of `--screenshot`. The viewport is set with `Emulation.setDeviceMetricsOverride`, with `mobile` on for the phone look (width ≤ 480): it is meant to be a phone's viewport, which is a deliberate change from the old plain `--window-size`.
src/checks/summary.ts +46
@@ -9,6 +9,7 @@
99
1010 import type { CheckDetail, Run } from "../core/runs.ts";
1111 import { parseBunTestFailure } from "./bun-test.ts";
12 import { webvitals, type Entries, type Vital } from "../release/webvitals.ts";
1213 import { oneLine } from "./words.ts";
1314
1415 /**
@@ -199,3 +200,48 @@ export const stepWord = (state: StepState): string => STEP_WORDS[state];
199200 export function stepsWords(steps: readonly CheckStep[]): string {
200201 return steps.map((s) => `${s.name} ${stepWord(s.state)}`).join(" · ");
201202 }
203
204 /** What one look recorded: its entries, or why it has none. Plain data from `looks/vitals.ts`. */
205 export interface LookVitals {
206 readonly page: string;
207 readonly kind: string;
208 readonly entries?: Entries | undefined;
209 /** Set when the look had no browser to record in: `no browser`. */
210 readonly skipped?: string | undefined;
211 }
212
213 function vitalWords(name: string, v: Vital): string {
214 const unit = v.unit === "" ? "" : ` ${v.unit}`;
215 const value = v.value === null ? "n/a" : `${v.value}${unit}`;
216 const bounds = `good ≤ ${v.good}${unit}, poor > ${v.poor}${unit}`;
217 return `${name} ${value}${v.grade === null ? "" : ` ${v.grade}`} (${bounds})`;
218 }
219
220 /** A look's label and its value: what a row shows as title and meta. */
221 export interface VitalsRow {
222 readonly label: string;
223 readonly value: string;
224 }
225
226 /**
227 * One row per look for a pull's checks: LCP, CLS and TBT with their
228 * thresholds, or `skipped: no browser`. Report-only — nothing here changes
229 * whether a check passes. A look whose browser lacked an entry type shows
230 * `n/a` for it rather than a made-up number.
231 */
232 export function vitalsRows(looks: readonly LookVitals[]): VitalsRow[] {
233 return looks.map((look) => {
234 const label = `${look.kind} ${look.page}`;
235 if (look.skipped !== undefined)
236 return { label, value: `skipped: ${look.skipped}` };
237 const v = webvitals(look.entries ?? {});
238 return {
239 label,
240 value: [vitalWords("LCP", v.lcpMs), vitalWords("CLS", v.cls), vitalWords("TBT", v.tbtMs)].join(" · "),
241 };
242 });
243 }
244
245 /** The same rows as plain lines, for the terminal. */
246 export const vitalsLines = (looks: readonly LookVitals[]): string[] =>
247 vitalsRows(looks).map((r) => `${r.label}: ${r.value}`);
src/looks/capture.ts +202 −49
@@ -5,39 +5,38 @@
55 * served the way a person would be served it — through the proxy, the
66 * grant, and the identity headers — without an edge in the way.
77 *
8 * Chromium's `--screenshot` sets no headers and no cookies. So the URL is
9 * not the page but the app's grant door (`/__forge/grant?t=…&to=/`): that
8 * The browser is driven over its DevTools socket (Bun's own WebSocket, no
9 * dependency) so a PerformanceObserver can be installed before the page's
10 * first script and read after load. It sets no headers and no cookies. So
11 * the URL is not the page but the app's grant door (`/__forge/grant?t=…&to=/`): that
1012 * one navigation sets the grant cookie and lands on the page as the person
1113 * the grant names. Chromium follows the redirect and pictures where it
1214 * lands.
1315 *
14 * The picture is taken as the page loads, bounded by `--timeout` for a
15 * page that never finishes — not after a virtual-time budget: a page that
16 * holds an event stream open (the scaffold's live script does) never goes
17 * idle, and a budget waits forever for it. What an app draws after load is
18 * not in the picture; what it serves is. And the picture, not the
19 * browser's exit, is what is waited for: a PNG whose IEND chunk is on disk
20 * is complete, and a browser that has written it is killed rather than
21 * asked to leave — Chrome 144 on macOS writes the file and then sits.
16 * The picture is taken at load, bounded by `LOAD_MS` for a page that never
17 * finishes — not after a virtual-time budget: a page that holds an event
18 * stream open (the scaffold's live script does) never goes idle, and a
19 * budget waits forever for it. What an app draws after load is not in the
20 * picture; what it serves is. The browser is killed once the picture is
21 * written, never asked to leave.
2222 *
2323 * One picture at a time, forge-wide: a browser is the heaviest thing this
2424 * process starts, and a pod that holds two agent runs has room for one.
2525 */
2626
2727 import {
28 closeSync,
2928 existsSync,
3029 mkdtempSync,
31 openSync,
32 readSync,
30 readFileSync,
3331 rmSync,
34 statSync,
32 writeFileSync,
3533 } from "node:fs";
3634 import { tmpdir } from "node:os";
3735 import { join } from "node:path";
3836 import { childEnv } from "../apps/process.ts";
3937 import { Gate } from "../git/env.ts";
4038 import { err, ok, type Result } from "../kernel/result.ts";
39 import type { Entries } from "../release/webvitals.ts";
4140
4241 export interface LookInput {
4342 /** The URL to open — the grant door of the app's hostname, on the forge's own port. */
@@ -48,6 +47,13 @@ export interface LookInput {
4847 readonly height: number;
4948 /** A browser that has no picture by then is killed; the look fails. */
5049 readonly timeoutMs: number;
50 /**
51 * Told what the page recorded while it loaded — `largest-contentful-paint`,
52 * `layout-shift` and `longtask` entries as plain data. A browser that
53 * lacks an entry type leaves its list empty; a page that could not be
54 * read never calls this.
55 */
56 readonly onEntries?: ((entries: Entries) => void) | undefined;
5157 }
5258
5359 /** What takes the picture: the real browser, or a test's stand-in. */
@@ -55,6 +61,8 @@ export type Capture = (input: LookInput) => Promise<Result<void, string>>;
5561
5662 /** How long a page gets to load before it is pictured as it stands. */
5763 const LOAD_MS = 3_000;
64 /** How long after load the paint and layout entries are given to arrive. */
65 const SETTLE_MS = 300;
5866
5967 /** The Chromium binary: `FORGE_CHROMIUM`, else the usual names on `PATH`, else the Mac's own. */
6068 export function findChromium(): string | undefined {
@@ -94,22 +102,151 @@ export async function takeLook(
94102 }
95103 }
96104
97 /** The last eight bytes of every PNG: the IEND chunk and its CRC. */
98 const PNG_END = Buffer.from([0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82]);
105 /** Runs in the page before any of its own script: records the three entry types the vitals read. */
106 export const OBSERVER = `(() => {
107 const seen = { lcp: [], layoutShift: [], longtask: [] };
108 const watch = (type, key) => {
109 try {
110 new PerformanceObserver((list) => {
111 for (const e of list.getEntries())
112 seen[key].push({
113 startTime: e.startTime,
114 size: e.size,
115 value: e.value,
116 hadRecentInput: e.hadRecentInput,
117 duration: e.duration,
118 });
119 }).observe({ type, buffered: true });
120 } catch (_) {}
121 };
122 watch("largest-contentful-paint", "lcp");
123 watch("layout-shift", "layoutShift");
124 watch("longtask", "longtask");
125 window.__forgeVitals = () => JSON.stringify(seen);
126 })();`;
99127
100 /** Whether a complete picture is on disk at `path`. */
101 function pictureDone(path: string): boolean {
102 if (!existsSync(path)) return false;
103 const size = statSync(path).size;
104 if (size < 64) return false;
105 const fd = openSync(path, "r");
106 try {
107 const tail = Buffer.alloc(8);
108 readSync(fd, tail, 0, 8, size - 8);
109 return tail.equals(PNG_END);
110 } finally {
111 closeSync(fd);
128 /** A minimal DevTools client: ids out, results in, events by name. */
129 class Devtools {
130 private next = 1;
131 private readonly waiting = new Map<
132 number,
133 { resolve: (v: any) => void; reject: (e: Error) => void }
134 >();
135 private readonly events = new Map<string, (() => void)[]>();
136
137 constructor(private readonly socket: WebSocket) {
138 socket.addEventListener("message", (m) => {
139 let msg: any;
140 try {
141 msg = JSON.parse(String(m.data));
142 } catch {
143 return;
144 }
145 if (typeof msg.id === "number") {
146 const w = this.waiting.get(msg.id);
147 this.waiting.delete(msg.id);
148 if (msg.error) w?.reject(new Error(String(msg.error.message)));
149 else w?.resolve(msg.result ?? {});
150 } else if (typeof msg.method === "string") {
151 for (const f of this.events.get(msg.method) ?? []) f();
152 }
153 });
154 socket.addEventListener("close", () => {
155 for (const w of this.waiting.values()) w.reject(new Error("devtools closed"));
156 this.waiting.clear();
157 });
112158 }
159
160 send(method: string, params: object = {}): Promise<any> {
161 return new Promise((resolve, reject) => {
162 const id = this.next++;
163 this.waiting.set(id, { resolve, reject });
164 this.socket.send(JSON.stringify({ id, method, params }));
165 });
166 }
167
168 once(method: string): Promise<void> {
169 return new Promise((resolve) => {
170 const list = this.events.get(method) ?? [];
171 list.push(resolve);
172 this.events.set(method, list);
173 });
174 }
175
176 close(): void {
177 try {
178 this.socket.close();
179 } catch {
180 // Already gone.
181 }
182 }
183 }
184
185 /** The browser's DevTools port, which it writes to its profile once it listens. */
186 async function devtoolsPort(
187 profile: string,
188 gone: () => boolean,
189 deadline: number,
190 ): Promise<number | undefined> {
191 const file = join(profile, "DevToolsActivePort");
192 while (Date.now() < deadline && !gone()) {
193 if (existsSync(file)) {
194 const port = Number(readFileSync(file, "utf8").split("\n")[0]);
195 if (Number.isInteger(port) && port > 0) return port;
196 }
197 await Bun.sleep(50);
198 }
199 return undefined;
200 }
201
202 async function connect(port: number): Promise<Devtools> {
203 const res = await fetch(`http://127.0.0.1:${port}/json/list`);
204 const targets = (await res.json()) as { type?: string; webSocketDebuggerUrl?: string }[];
205 const page = targets.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
206 if (page?.webSocketDebuggerUrl === undefined) throw new Error("no page target");
207 const socket = new WebSocket(page.webSocketDebuggerUrl);
208 await new Promise<void>((resolve, reject) => {
209 socket.addEventListener("open", () => resolve());
210 socket.addEventListener("error", () => reject(new Error("devtools refused")));
211 });
212 return new Devtools(socket);
213 }
214
215 /** Load the page with the observer installed, wait for load, read the entries, picture it. */
216 async function drive(dt: Devtools, input: LookInput): Promise<void> {
217 await dt.send("Page.enable");
218 await dt.send("Page.addScriptToEvaluateOnNewDocument", { source: OBSERVER });
219 await dt.send("Emulation.setDeviceMetricsOverride", {
220 width: input.width,
221 height: input.height,
222 deviceScaleFactor: 1,
223 // The phone look is a phone: touch, overlay scrollbars, a mobile viewport.
224 mobile: input.width <= 480,
225 });
226 const loaded = dt.once("Page.loadEventFired");
227 await dt.send("Page.navigate", { url: input.url });
228 // A page that never finishes loading is pictured as it stands.
229 await Promise.race([loaded, Bun.sleep(LOAD_MS)]);
230 // Paint and layout entries land a beat after load.
231 await Bun.sleep(SETTLE_MS);
232 if (input.onEntries !== undefined) {
233 try {
234 const read = await dt.send("Runtime.evaluate", {
235 expression: "window.__forgeVitals ? window.__forgeVitals() : ''",
236 returnByValue: true,
237 });
238 const value = read?.result?.value;
239 if (typeof value === "string" && value !== "") {
240 const parsed = JSON.parse(value) as Entries;
241 input.onEntries(parsed);
242 }
243 } catch {
244 // The vitals are a bonus; the picture is the look.
245 }
246 }
247 const shot = await dt.send("Page.captureScreenshot", { format: "png" });
248 if (typeof shot?.data !== "string") throw new Error("no screenshot data");
249 writeFileSync(input.out, Buffer.from(shot.data, "base64"));
113250 }
114251
115252 async function shoot(
@@ -143,9 +280,9 @@ async function shoot(
143280 `--window-size=${input.width},${input.height}`,
144281 "--force-device-scale-factor=1",
145282 "--js-flags=--max-old-space-size=256",
146 `--timeout=${LOAD_MS}`,
147 `--screenshot=${input.out}`,
148 input.url,
283 // Loopback only, on a port the browser picks and writes to its profile.
284 "--remote-debugging-port=0",
285 "about:blank",
149286 ],
150287 {
151288 env: childEnv({}),
@@ -169,32 +306,48 @@ async function shoot(
169306 }
170307 })().catch(() => {});
171308 const deadline = Date.now() + input.timeoutMs;
309 let dt: Devtools | undefined;
172310 try {
173 for (;;) {
174 if (pictureDone(input.out)) return ok();
311 const port = await devtoolsPort(profile, () => exited !== undefined, deadline);
312 if (port === undefined) {
175313 if (exited !== undefined) {
176314 // The browser's last words reach the pipe a beat after it exits.
177315 await Bun.sleep(150);
178 break;
179 }
180 if (Date.now() >= deadline)
316 // Chromium narrates its own housekeeping on stderr; the last line is
317 // the one that says what went wrong, when anything did.
318 const last = said
319 .join("")
320 .split("\n")
321 .map((l) => l.trim())
322 .filter((l) => l !== "" && !/crashpad|ProcessSingleton/i.test(l))
323 .at(-1);
181324 return err(
182 `the picture took longer than ${Math.round(input.timeoutMs / 1000)}s`,
325 `chromium exited ${exited} without a picture${last === undefined ? "" : `: ${last.slice(0, 300)}`}`,
183326 );
184 await Bun.sleep(100);
327 }
328 return err(
329 `the picture took longer than ${Math.round(input.timeoutMs / 1000)}s`,
330 );
185331 }
186 // Chromium narrates its own housekeeping on stderr; the last line is
187 // the one that says what went wrong, when anything did.
188 const last = said
189 .join("")
190 .split("\n")
191 .map((l) => l.trim())
192 .filter((l) => l !== "" && !/crashpad|ProcessSingleton/i.test(l))
193 .at(-1);
194 return err(
195 `chromium exited ${exited} without a picture${last === undefined ? "" : `: ${last.slice(0, 300)}`}`,
196 );
332 const budget = deadline - Date.now();
333 const work = (async () => {
334 dt = await connect(port);
335 await drive(dt, input);
336 })();
337 // The timeout may win the race below; a later rejection has no listener.
338 work.catch(() => {});
339 const late = Symbol("late");
340 const result = await Promise.race([
341 work.then(() => ok(), (e) => err(`the browser could not be driven: ${String(e?.message ?? e)}`)),
342 Bun.sleep(Math.max(0, budget)).then(() => late),
343 ]);
344 if (result === late)
345 return err(
346 `the picture took longer than ${Math.round(input.timeoutMs / 1000)}s`,
347 );
348 return result as Result<void, string>;
197349 } finally {
350 dt?.close();
198351 if (exited === undefined) proc.kill("SIGKILL");
199352 await proc.exited.catch(() => {});
200353 reader.cancel().catch(() => {});
src/looks/service.ts +17 −1
@@ -62,6 +62,8 @@ 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";
6464 import { findChromium, takeLook, type Capture } from "./capture.ts";
65 import type { Entries } from "../release/webvitals.ts";
66 import { boundEntries, NO_BROWSER, vitalsPath, writeVitals } from "./vitals.ts";
6567
6668 const log = createLog("looks");
6769
@@ -391,9 +393,11 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
391393 `${item.appId}-${item.env}-${item.commitOid}-${lookSlot(page, kind)}.png`,
392394 );
393395 mkdirSync(dirname(staged), { recursive: true });
396 let entries: Entries | undefined;
394397 const shot = await capture({
395398 url,
396399 out: staged,
400 onEntries: (e) => (entries = boundEntries(e)),
397401 ...LOOK_WINDOWS[kind],
398402 timeoutMs: CAPTURE_TIMEOUT_MS,
399403 });
@@ -425,6 +429,8 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
425429 path,
426430 takenAs: asNobody(kind) ? "nobody" : "owner",
427431 });
432 if (entries !== undefined)
433 writeVitals(dataDir, path, { page, kind, entries });
428434 } else {
429435 rmSync(staged, { force: true });
430436 allOk = false;
@@ -436,6 +442,13 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
436442 error: taken.error,
437443 });
438444 recordLook(app.db, { ...row, kind, path: "", error: taken.error });
445 // Report-only: a forge with no browser says so, and stays green.
446 if (taken.error.startsWith("no chromium"))
447 writeVitals(dataDir, lookPath(item.appId, item.env, item.commitOid, page, kind), {
448 page,
449 kind,
450 skipped: NO_BROWSER,
451 });
439452 }
440453 }
441454 // A full set at this head is the environment's look now; the pictures
@@ -558,7 +571,10 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
558571
559572 function remove(looks: readonly { path: string }[]): void {
560573 for (const look of looks)
561 if (look.path !== "") rmSync(join(dataDir, look.path), { force: true });
574 if (look.path !== "") {
575 rmSync(join(dataDir, look.path), { force: true });
576 rmSync(join(dataDir, vitalsPath(look.path)), { force: true });
577 }
562578 }
563579
564580 /**
src/looks/vitals.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * The web-vitals a look recorded, kept beside its picture as
3 * `<commit>-<slot>.vitals.json` under FORGE_APP_DATA. Report-only: written
4 * when the look is taken, read to word a pull's checks, never a gate. A
5 * file that is missing or unreadable is no report, not an error.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
10 import { join } from "node:path";
11 import { previewEnv } from "../apps/data.ts";
12 import { getAppByRepo } from "../core/apps.ts";
13 import type { LookVitals } from "../checks/summary.ts";
14 import type { Entries } from "../release/webvitals.ts";
15
16 export const NO_BROWSER = "no browser";
17 const SUFFIX = ".vitals.json";
18 /** A page that shifts or stalls ten thousand times is no more graded than one that does five hundred. */
19 const KEEP = 500;
20 /** Reports read per render: pages times kinds, bounded however many pages a repository lists. */
21 const MAX_REPORTS = 12;
22
23 /** Where a look's report lives, given the path of its picture (relative to the data directory). */
24 export const vitalsPath = (picture: string): string =>
25 picture.replace(/\.png$/, SUFFIX);
26
27 const keep = (v: unknown): unknown[] => (Array.isArray(v) ? v.slice(0, KEEP) : []);
28
29 /** Entries cut down to the three lists, each bounded. */
30 export function boundEntries(raw: unknown): Entries {
31 const r = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
32 return {
33 lcp: keep(r["lcp"]),
34 layoutShift: keep(r["layoutShift"]),
35 longtask: keep(r["longtask"]),
36 };
37 }
38
39 export function writeVitals(
40 dataDir: string,
41 picture: string,
42 look: LookVitals,
43 ): void {
44 const file = join(dataDir, vitalsPath(picture));
45 mkdirSync(join(file, ".."), { recursive: true });
46 writeFileSync(file, JSON.stringify(look));
47 }
48
49 /** Every report of one commit in one environment, phone before desktop before thumb. */
50 export function readVitals(
51 dataDir: string,
52 appId: string,
53 env: string,
54 commitOid: string,
55 ): LookVitals[] {
56 const dir = join(dataDir, "looks", appId, env);
57 let names: string[];
58 try {
59 names = readdirSync(dir).filter((n) => n.startsWith(`${commitOid}-`)).slice(0, MAX_REPORTS);
60 } catch {
61 return [];
62 }
63 const order = ["phone", "desktop", "thumb"];
64 const out: LookVitals[] = [];
65 for (const name of names.sort()) {
66 if (!name.startsWith(`${commitOid}-`) || !name.endsWith(SUFFIX)) continue;
67 try {
68 const j = JSON.parse(readFileSync(join(dir, name), "utf8"));
69 if (typeof j?.page !== "string" || typeof j?.kind !== "string") continue;
70 out.push({
71 page: j.page,
72 kind: j.kind,
73 entries: j.entries === undefined ? undefined : boundEntries(j.entries),
74 skipped: typeof j.skipped === "string" ? j.skipped : undefined,
75 });
76 } catch {
77 // Unreadable: no report.
78 }
79 }
80 return out.sort((a, b) => order.indexOf(a.kind) - order.indexOf(b.kind));
81 }
82
83 /** The reports for a pull's preview at its head; none when the repository is no app. */
84 export function pullVitals(
85 db: Database,
86 dataDir: string,
87 repoId: string,
88 number: number,
89 headOid: string,
90 ): LookVitals[] {
91 const record = getAppByRepo(db, repoId);
92 return record === undefined || headOid === ""
93 ? []
94 : readVitals(dataDir, record.id, previewEnv(number), headOid);
95 }
src/tui/screens/pull.ts +21 −1
@@ -53,7 +53,8 @@ import { isProposed, pullMayRun } from "../../core/pull_trust.ts";
5353 import { runningProgress, stepsLine } from "../../checks/progress.ts";
5454 import { askCheck } from "../../checks/again.ts";
5555 import { checkStale, checksHold } from "../../checks/stale.ts";
56 import { checkWords } from "../../checks/summary.ts";
56 import { checkWords, vitalsLines } from "../../checks/summary.ts";
57 import { pullVitals } from "../../looks/vitals.ts";
5758 import { oneLine } from "../../checks/words.ts";
5859 import { resolveOid } from "../../git/merge.ts";
5960 import { getPull, pullDir, variantSiblings, type Pull } from "../../core/pulls.ts";
@@ -247,6 +248,8 @@ export function pullScreen(
247248 /** The pull's base branch, to name what the check was merged with. */
248249 let checkBase = "";
249250 let checkProgress = "";
251 /** `vitalsLines` of the looks taken of this head; empty when there are none. */
252 let vitals: string[] = [];
250253 /** The run page's three step rows as a line; empty when the log is hidden. */
251254 let checkSteps = "";
252255 /** The check's green was against a base that has since moved. */
@@ -300,6 +303,11 @@ export function pullScreen(
300303 : checkSummary(f.db, row.id, row.headOid || (facts?.headOid ?? ""));
301304 checkBase = row?.baseBranch ?? facts?.baseBranch ?? "";
302305 checkProgress = runningProgress(f.app.config.dataDir, check);
306 vitals = isApp
307 ? vitalsLines(
308 pullVitals(f.db, f.app.config.dataDir, repo?.id ?? "", number, row?.headOid || (facts?.headOid ?? "")),
309 ).slice(0, VITALS_ROWS)
310 : [];
303311 checkSteps =
304312 settings === undefined
305313 ? ""
@@ -822,6 +830,7 @@ export function pullScreen(
822830 3 +
823831 (standingText(standing(), requireReview) === "" ? 0 : 1) +
824832 (checksLine === "" ? 0 : 1) +
833 vitals.length +
825834 teams.length;
826835 const [strip, head, previewRow, boxRow, tabRow, body, comp] = split(
827836 area,
@@ -877,6 +886,7 @@ export function pullScreen(
877886 checkOld,
878887 check,
879888 checksLine,
889 vitals,
880890 standing: standing(),
881891 required: requireReview,
882892 teams,
@@ -1287,6 +1297,9 @@ export function checksText(
12871297 return line === "" || steps === "" ? line : `${line} · ${steps}`;
12881298 }
12891299
1300 /** The most look rows the merge box gives the vitals. */
1301 const VITALS_ROWS = 4;
1302
12901303 function checksLine(
12911304 check: CheckSummary,
12921305 required: boolean,
@@ -1395,6 +1408,7 @@ function drawMergeBox(
13951408 check: CheckSummary;
13961409 /** The checks row, already worded; "" draws none. */
13971410 checksLine: string;
1411 vitals: readonly string[];
13981412 standing: Standing;
13991413 required: boolean;
14001414 teams: readonly TeamVerdict[];
@@ -1499,6 +1513,12 @@ function drawMergeBox(
14991513 );
15001514 y++;
15011515 }
1516 // What each look recorded, report-only: muted, one row per look.
1517 for (const line of o.vitals) {
1518 if (y >= inner.y + inner.h) break;
1519 s.text(inner.x, y, truncate(line, inner.w), style(c.mutedFg, c.card), inner.x + inner.w);
1520 y++;
1521 }
15021522 // The teams the issue names, one row each: who still owes a review.
15031523 for (const v of o.teams) {
15041524 if (y >= inner.y + inner.h) break;
src/web/pages/pull.ts +22 −1
@@ -35,7 +35,8 @@ import {
3535 type PullStatus,
3636 } from "../../core/pulls.ts";
3737 import { isProposed, pullMayRun } from "../../core/pull_trust.ts";
38 import { checkWords } from "../../checks/summary.ts";
38 import { checkWords, vitalsRows } from "../../checks/summary.ts";
39 import { pullVitals } from "../../looks/vitals.ts";
3940 import { runningProgress } from "../../checks/progress.ts";
4041 import { checkStale, checksHold } from "../../checks/stale.ts";
4142 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
@@ -84,6 +85,7 @@ import {
8485 icon,
8586 labelCss,
8687 queuedPhrase,
88 row,
8789 sha,
8890 time,
8991 } from "../ui.ts";
@@ -366,6 +368,24 @@ function pullChecksLine(
366368 );
367369 }
368370
371 /**
372 * The web-vitals each look recorded for this head's preview: a card of rows,
373 * label and value, wrapping on a phone. Report-only; empty when there are none.
374 */
375 export function vitalsCard(ctx: Ctx, repo: Repo, pull: Pull, headOid: string): Html {
376 const rows = vitalsRows(
377 pullVitals(ctx.app.db, ctx.app.config.dataDir, repo.id, pull.number, headOid),
378 );
379 return rows.length === 0
380 ? html``
381 : card(
382 html`<ul class="list setting-list">
383 ${rows.map((v) => row({ title: v.label, meta: html`${v.value}` }))}
384 </ul>`,
385 { head: html`Web vitals`, pad: false },
386 );
387 }
388
369389 /**
370390 * Six states, six cards. Every one names the situation, gives the reason,
371391 * and offers exactly the actions that are actually available.
@@ -916,6 +936,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
916936 ${holdCard(ctx, repo, pull, { act: false })}
917937 ${teamsCard(teamVerdicts(ctx.app.db, { ...pull, headOid: status.headOid }))}
918938 ${mergeBox(ctx, repo, pull, status, mayMerge, by, check, isApp, tier, stale)}
939 ${vitalsCard(ctx, repo, pull, status.headOid)}
919940 <div class="split">
920941 <div>
921942 ${approveHereCard(ctx, repo, pull, status.headOid, `${thread}/approve-here`)}
src/web/studio/change.ts +2 −2
@@ -64,7 +64,7 @@ import {
6464 } from "../ui.ts";
6565 import { previewCard } from "../pages/apps.ts";
6666 import { lookCard } from "../pages/looks.ts";
67 import { approveHereCard, pullChecksLineFor, teamsCard } from "../pages/pull.ts";
67 import { approveHereCard, pullChecksLineFor, teamsCard, vitalsCard } from "../pages/pull.ts";
6868 import { teamVerdicts } from "../../core/issue_teams.ts";
6969 import { liveRegionsJs } from "../client.ts";
7070 import { pullState } from "../pages/pulls.ts";
@@ -588,7 +588,7 @@ async function changeConversation(
588588 </p>`,
589589 )}
590590 <div id="pull-check">${checkLine}</div>
591 ${when(runLine, (l) => l)} ${holdCard(ctx, repo, pull, { act: true })}
591 ${when(runLine, (l) => l)} ${status === undefined ? "" : vitalsCard(ctx, repo, pull, status.headOid)} ${holdCard(ctx, repo, pull, { act: true })}
592592 ${approveHereCard(ctx, repo, pull, headOid, `${thread}/approve-here`)}
593593 ${teamsCard(teamVerdicts(db, { ...pull, headOid }))}
594594 ${when(wall, (w) => wallCard(w))} ${decisionSection}
test/looks-vitals.test.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * The per-look web-vitals report (#2983): recorded entries go through the
3 * summary and come out as numbers with their thresholds; a look with no
4 * browser says so; a browser that lacks an entry type is tolerated.
5 */
6
7 import { expect, test } from "bun:test";
8 import { mkdtempSync, rmSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { vitalsLines } from "../src/checks/summary.ts";
12 import { NO_BROWSER, readVitals, vitalsPath, writeVitals } from "../src/looks/vitals.ts";
13
14 const entries = {
15 lcp: [{ startTime: 1200, size: 5000 }, { startTime: 3300, size: 90000 }],
16 layoutShift: [
17 { startTime: 100, value: 0.04, hadRecentInput: false },
18 { startTime: 400, value: 0.03, hadRecentInput: false },
19 ],
20 longtask: [{ startTime: 50, duration: 130 }, { startTime: 900, duration: 40 }],
21 };
22
23 test("recorded entries render as LCP, CLS and TBT with their thresholds", () => {
24 const [line] = vitalsLines([{ page: "/", kind: "desktop", entries }]);
25 expect(line).toBe(
26 "desktop /: LCP 3300 ms needs-improvement (good ≤ 2500 ms, poor > 4000 ms)" +
27 " · CLS 0.07 good (good ≤ 0.1, poor > 0.25)" +
28 " · TBT 80 ms good (good ≤ 200 ms, poor > 600 ms)",
29 );
30 });
31
32 test("a browser without an entry type shows n/a, not a number", () => {
33 const [line] = vitalsLines([{ page: "/", kind: "phone", entries: {} }]);
34 expect(line).toContain("LCP n/a (good ≤ 2500 ms, poor > 4000 ms)");
35 expect(line).toContain("CLS 0 good");
36 });
37
38 test("a look without a browser is skipped, and says why", () => {
39 expect(vitalsLines([{ page: "/", kind: "phone", skipped: NO_BROWSER }])).toEqual([
40 "phone /: skipped: no browser",
41 ]);
42 });
43
44 test("reports round-trip beside the picture, phone before desktop", () => {
45 const dir = mkdtempSync(join(tmpdir(), "vitals-"));
46 try {
47 const pic = (k: string) => `looks/app1/production/abc123-${k}.png`;
48 expect(vitalsPath(pic("x"))).toBe("looks/app1/production/abc123-x.vitals.json");
49 writeVitals(dir, pic("desktop"), { page: "/", kind: "desktop", entries });
50 writeVitals(dir, pic("phone"), { page: "/", kind: "phone", skipped: NO_BROWSER });
51 writeVitals(dir, "looks/app1/production/other-phone.png", { page: "/", kind: "phone", skipped: NO_BROWSER });
52 const got = readVitals(dir, "app1", "production", "abc123");
53 expect(got.map((g) => g.kind)).toEqual(["phone", "desktop"]);
54 expect(vitalsLines(got)[1]).toContain("LCP 3300 ms");
55 expect(readVitals(dir, "app1", "production", "nope")).toEqual([]);
56 } finally {
57 rmSync(dir, { recursive: true, force: true });
58 }
59 });
test/looks.test.ts +37 −1
@@ -8,6 +8,8 @@
88 * Chromium, when this machine has one, proves the browser end.
99 */
1010
11 import { readVitals } from "../src/looks/vitals.ts";
12 import { vitalsLines } from "../src/checks/summary.ts";
1113 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1214 import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
1315 import { mkdtemp, rm } from "node:fs/promises";
@@ -77,11 +79,14 @@ describe("the look", () => {
7779 let bobCookie: string;
7880
7981 // The stand-in browser: writes a picture, or falls over, as told.
80 let mode: "ok" | "fail" = "ok";
82 let mode: "ok" | "fail" | "nobrowser" = "ok";
8183 const calls: LookInput[] = [];
8284 const fake: Capture = async (input) => {
8385 calls.push(input);
8486 if (mode === "fail") return err("the browser fell over");
87 if (mode === "nobrowser")
88 return err("no chromium on this forge: install one, or set FORGE_CHROMIUM");
89 input.onEntries?.({ lcp: [{ startTime: 1200, size: 10 }] });
8590 writeFileSync(input.out, input.width === 1280 ? DESKTOP_PNG : PNG);
8691 return ok();
8792 };
@@ -214,6 +219,10 @@ describe("the look", () => {
214219 for (const call of calls)
215220 expect(call.out).toContain(join("looks", ".taking"));
216221 expect(readdirSync(join(dataDir, "looks", ".taking"))).toEqual([]);
222 // What the page recorded is kept beside each picture, report-only.
223 const reports = readVitals(dataDir, record.id, "production", production.commitOid);
224 expect(reports.map((r) => r.kind)).toEqual(["phone", "desktop", "thumb"]);
225 expect(vitalsLines(reports)[0]).toContain("LCP 1200 ms good (good ≤ 2500 ms, poor > 4000 ms)");
217226 const phone = calls.find((c) => c.width === 390)!;
218227 expect(phone.height).toBe(844);
219228 // Desktop and thumb are both taken in desktop's window: a browser does
@@ -401,6 +410,28 @@ describe("the look", () => {
401410 expect(none).toContain("No picture of");
402411 expect(none).toContain("the browser fell over");
403412 expect(none).not.toContain(`/looks/${env2}/`);
413 // No reports, no card.
414 expect(none).not.toContain("Web vitals");
415
416 // A forge with no browser: each look says so on the pull, and the
417 // check stays green.
418 mode = "nobrowser";
419 const bare = await commitToBranch(app, alice, repo, {
420 branch: "second",
421 message: "No browser",
422 files: [{ path: "BARE.md", content: "3\n" }],
423 });
424 if (!bare.ok) throw new Error(JSON.stringify(bare.error));
425 expect(
426 (await settled((r) => r.env === env2 && r.commitOid === bare.value.commitOid)).state,
427 ).toBe("ok");
428 await pictured(env2, bare.value.commitOid);
429 const skipped = (
430 await (await web(`/alice/hello/pulls/${unpictured.number}`, aliceCookie)).text()
431 ).replace(/\s+/g, " ");
432 expect(skipped).toContain("Web vitals");
433 expect(skipped).toContain("skipped: no browser");
434 expect(readVitals(dataDir, record.id, env2, bare.value.commitOid)).toHaveLength(3);
404435 mode = "ok";
405436 }, 120_000);
406437
@@ -995,14 +1026,19 @@ describe("the look", () => {
9951026 const door = openEnvUrl(app, alice, peek, "production");
9961027 if (!door.ok) throw new Error(String(door.error));
9971028 const out = join(dataDir, "real-phone.png");
1029 let recorded: unknown;
9981030 const taken = await takeLook({
9991031 url: door.value,
10001032 out,
10011033 width: 390,
10021034 height: 844,
10031035 timeoutMs: 30_000,
1036 onEntries: (e) => (recorded = e),
10041037 });
10051038 expect(taken).toEqual({ ok: true, value: undefined });
1039 // The observer was installed before the page: the lists exist, and
1040 // the page painted something.
1041 expect(Object.keys(recorded as object).sort()).toEqual(["layoutShift", "lcp", "longtask"]);
10061042 expect(pngSize(out)).toEqual([390, 844]);
10071043 // The browser arrived through the grant: the app was told who it was.
10081044 const seen = readFileSync(
test/pull-tui-vitals.test.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * The terminal's pull screen shows the web vitals each look recorded for
3 * the head's preview (#2983), the same words as the page — and nothing
4 * when none were recorded.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { previewEnv } from "../src/apps/data.ts";
14 import { createApp as insertApp } from "../src/core/apps.ts";
15 import { getPull } from "../src/core/pulls.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { lookPath } from "../src/looks/service.ts";
18 import { NO_BROWSER, writeVitals } from "../src/looks/vitals.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import { pullScreen } from "../src/tui/screens/pull.ts";
21 import { local } from "../src/tui/screens/where.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { settleApp } from "./helpers/tui.ts";
25
26 quietLogs();
27
28 let dataDir: string;
29 let app: App;
30
31 beforeAll(async () => {
32 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-vitals-"));
33 app = createApp({ dataDir, port: 0, host: "forge.test" });
34 });
35
36 afterAll(async () => {
37 app.close();
38 await rm(dataDir, { recursive: true, force: true });
39 });
40
41 test("the pull screen lists each look's vitals, and nothing before there are any", async () => {
42 const made = await createUser(app.db, {
43 origin: "seed",
44 trusted: true,
45 username: "alice",
46 email: "[email protected]",
47 password: "a-good-passphrase",
48 adminIfFirst: true,
49 });
50 if (!made.ok) throw new Error(String(made.error));
51 const alice = made.value;
52 const r = await createRepo(app, alice, { name: "lib", visibility: "public" });
53 if (!r.ok) throw new Error(String(r.error));
54 const repo = r.value;
55 for (const branch of ["main", "feat"]) {
56 const done = await commitToBranch(app, alice, repo, {
57 branch,
58 message: branch,
59 files: [{ path: "code.txt", content: branch }],
60 });
61 if (!done.ok) throw new Error(JSON.stringify(done.error));
62 }
63 const opened = await openPull(app, alice, repo, {
64 title: "Feat",
65 baseBranch: "main",
66 headBranch: "feat",
67 });
68 if (!opened.ok) throw new Error(String(opened.error));
69 const pull = getPull(app.db, repo.id, opened.value.number)!;
70 const inserted = insertApp(app.db, { repoId: repo.id, slug: "lib", access: "public" });
71 if (!inserted.ok) throw new Error(inserted.error);
72 const env = previewEnv(pull.number);
73
74 const { app: tui, session } = createForgeApp(
75 app,
76 {
77 sshUsername: "alice",
78 remoteAddress: "127.0.0.1",
79 fingerprint: "SHA256:alice",
80 user: alice,
81 },
82 { terminal: headlessTerminal(200, 44), exitHooks: false },
83 );
84 tui.start();
85 try {
86 const open = async () => {
87 tui.ctx.push(pullScreen(session, tui.ctx, local(session, repo), pull.number));
88 for (let i = 0; i < 20; i++) {
89 await settleApp(tui);
90 await Bun.sleep(20);
91 }
92 };
93 await open();
94 expect(tui.screen.toText()).not.toContain("LCP");
95 tui.ctx.pop?.();
96
97 const at = (kind: "phone" | "desktop") =>
98 lookPath(inserted.value.id, env, pull.headOid, "/", kind);
99 writeVitals(dataDir, at("phone"), {
100 page: "/",
101 kind: "phone",
102 entries: { lcp: [{ startTime: 3300, size: 9 }] },
103 });
104 writeVitals(dataDir, at("desktop"), { page: "/", kind: "desktop", skipped: NO_BROWSER });
105 await open();
106 const text = tui.screen.toText();
107 expect(text).toContain("phone /: LCP 3300 ms needs-improvement (good ≤ 2500 ms, poor > 4000 ms)");
108 expect(text).toContain("desktop /: skipped: no browser");
109 } finally {
110 tui.stop();
111 }
112 }, 60_000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs