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

In a preview, the forge pill's panel says the pull's check: green, red with its first failing test, or running #16738

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/6381-in-a-preview-the-forge-pill-s-panel-says → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/6381-in-a-preview-the-forge-pill-s-panel-says was merged into main as c904595.

Review

Sign in to review this change.
7 files changed +214 −2
docs/features/forge-toolbar.md +1
@@ -18,6 +18,7 @@ preview), so you always know where you are and can get back to the forge.
1818 - **What it says:** the app, the environment and, on a preview, a link
1919 "Pull #N: <state>" to the pull's page on the forge; Home goes to the forge.
2020 - **The preview line:** on a preview the pill's panel has one link to the pull, "Pull #N: checking", "Pull #N: green" or "Pull #N: red" (running or queued reads checking; also "cancelled" and "no check yet"), with the title as its tooltip, set as text. The state is the newest check of the pull's head, read when the page loads: it updates on reload only, never polled. Production has no such line.
21 - **The check line (#6381):** on a preview, the comment script (fetched when the panel first opens) asks the app's own `/__forge/check` and adds one line to the panel: `check green`, `check red: <first failing test>` or `check running`, linking to the run's log on the forge. The route answers `{ state, test?, log }` for the newest check of the pull's head, only to someone who may read that pull (else 404), and names the phases `session`, `pull` and `render`. Production has none; a pull with no check says nothing.
2122 - **Comment on the pull:** a preview's panel also has a comment box, built by a small script of its own (`src/apps/toolbar_comment.ts`, under 4 KB) that the pill fetches from the app's host the first time a preview's panel opens; production pages and a closed pill never load it, and the pill keeps its 24 KB budget. A viewer the tag names as signed out (`data-in` absent) sees "Sign in to comment on this pull", which goes through `/__forge/signin` and back to the page, instead of a box. The box posts `POST /__forge/comment` with `{ text }`, same-origin and with the page's proof, and the comment lands on the pull the environment's name gives (`pull-N`; never a number from the body), as the person the app's grant names. Words: signed out is `401` ("Sign in to the forge to comment on this pull."); production, an unknown number or a non-pull is `404`; empty text is `400`, and so is text over 4000 characters (`COMMENT_MAX`, the box's `maxLength` too) with `body_too_long`; too many is `429` with `Retry-After` (6 a minute for a person, 20 for a socket address, so a script holding one proof cannot flood the pull's author). A refused comment keeps what was typed and says why under the box; only a posted one clears it, and its "Commented on pull #N." links to the address the door answered with (only when that is on the forge's origin). The terminal already comments on a pull (`src/tui/screens/pull.ts`), so this is a page-only surface. See `src/apps/pull_comment.ts`.
2223 - **Which commit:** one more line, `Serving a1b2c3d`, then `Live since 4 min ago` (its title is the exact UTC time; ` · behind main` follows on production when its default branch has moved on, from `data-lagging`), the short
2324 id linked to the commit on the forge. The id and the instant come from the
src/apps/pill_check_say.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * What the pill's panel says of a preview's pull check (#6381): `{ state, test?, log }`, green,
3 * red with its first failing test, or running. Plain data from the newest check run of the pull's
4 * head; the route that serves it (`/__forge/check`) decides who may ask.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import type { CheckDetail } from "../core/runs.ts";
9
10 export type CheckSay = {
11 state: "green" | "red" | "running";
12 /** The first failing test's name, for a red check whose output named one. */
13 test?: string;
14 /** The forge path of the run's log page, to be read on the forge's own origin. */
15 log: string;
16 };
17
18 /** The longest test name the panel is handed. */
19 export const TEST_MAX = 200;
20
21 /** The newest check run of this head, said; undefined when there is none or it was cancelled. */
22 export function checkSay(db: Database, repoPath: string, issueId: string, headOid: string): CheckSay | undefined {
23 const row = db
24 .query<{ id: string; state: string; check_detail: string | null }, [string, string]>(
25 `SELECT id, state, check_detail FROM run WHERE kind = 'check' AND issue_id = ?1 AND commit_oid = ?2 ORDER BY id DESC LIMIT 1`,
26 )
27 .get(issueId, headOid);
28 if (row === null) return undefined;
29 const log = `/${repoPath}/runs/${encodeURIComponent(row.id)}`;
30 if (row.state === "ok") return { state: "green", log };
31 if (row.state === "queued" || row.state === "running") return { state: "running", log };
32 if (row.state !== "failed") return undefined;
33 let test: unknown;
34 try {
35 test = (JSON.parse(row.check_detail ?? "null") as CheckDetail | null)?.names?.[0];
36 } catch {
37 test = undefined;
38 }
39 return typeof test === "string" && test !== ""
40 ? { state: "red", test: test.slice(0, TEST_MAX), log }
41 : { state: "red", log };
42 }
src/apps/proxy.ts +32
@@ -63,6 +63,7 @@ import { DOOR_PULL_LIMIT, doorPage, type DoorPullLine } from "./door.ts";
6363 import { checkWord } from "./check_word.ts";
6464 import { servingWords } from "./serving_words.ts";
6565 import { pillCheck } from "./pill_check.ts";
66 import { checkSay } from "./pill_check_say.ts";
6667 import { openPulls } from "./door_pulls.ts";
6768 import { notePhase, startedAt, takePhases, timePhase } from "../core/route_timing.ts";
6869 import { readServing } from "./serving.ts";
@@ -1086,6 +1087,37 @@ async function proxyAppAnswer(
10861087 };
10871088 return withPhases(request, securityFloor(new Response(null, { status: 204, headers })));
10881089 }
1090 // The pill's check door (#6381): a preview's pull check, green, red with its first failing test,
1091 // or running, only to a viewer who may read that pull. Production has none.
1092 if (url.pathname === "/__forge/check" && !target.nested) {
1093 const signed = timePhase(request, "session", () => {
1094 const cookie = cookieValue(request, grantCookieName(target));
1095 return cookie === undefined ? undefined : readGrant(runtime.app.config.dataDir, cookie, target);
1096 });
1097 const said = timePhase(request, "pull", () => {
1098 const db = runtime.app.db;
1099 const number = /^pull-(\d+)$/.exec(target.env)?.[1];
1100 const repo = getRepoById(db, target.app.repoId);
1101 if (number === undefined || repo === undefined) return undefined;
1102 const viewer = signed?.who === undefined ? undefined : getUserById(db, signed.who.id);
1103 const user = viewer !== undefined && isActive(viewer) ? viewer : undefined;
1104 const pull = getIssue(db, target.app.repoId, Number(number));
1105 const head = getPull(db, target.app.repoId, Number(number));
1106 if (pull === undefined || pull.kind !== "pull" || head === undefined || head.headOid === "") return undefined;
1107 if (!canRead(db, repo, user) || !mayView(db, repo, pull, user)) return undefined;
1108 return checkSay(db, `${repo.ownerName}/${repo.name}`, pull.id, head.headOid);
1109 });
1110 if (said === undefined) return withPhases(request, notFound());
1111 const body = timePhase(request, "render", () => JSON.stringify(said));
1112 return withPhases(
1113 request,
1114 securityFloor(
1115 new Response(body, {
1116 headers: { "content-type": "application/json;charset=utf-8", "cache-control": "no-store" },
1117 }),
1118 ),
1119 );
1120 }
10891121 // The pill's fourth door: who of the crew is working on this app now,
10901122 // for the person the app's own grant names, read once as the pill opens.
10911123 if (url.pathname === "/__forge/crew" && !target.nested) {
src/apps/toolbar.ts +1 −1
@@ -155,7 +155,7 @@ const toolbarSource = `(function () {
155155 window.__forgeComment = function (b) {
156156 if (!cx || document.currentScript !== cx) return;
157157 window.__forgeComment = null;
158 b({ mount: cm, call: call, pull: d.pull, signedIn: d.in === "1", forge: fo, ls: LS });
158 b({ mount: cm, call: call, pull: d.pull, signedIn: d.in === "1", forge: fo, ls: LS, check: d.check });
159159 };
160160 }
161161 if (pv) line("Environment: preview");
src/apps/toolbar_comment.ts +14
@@ -24,6 +24,20 @@ const commentSource = `(function () {
2424 if (typeof take !== "function") return;
2525 take(function (k) {
2626 var m = k.mount;
27 // The pull's check in one line (#6381): green, red with its first failing test, or running,
28 // linked to its log on the forge. Text only; the forge answers only a reader of the pull.
29 if (k.check && k.check !== "none") fetch("/__forge/check", { credentials: "same-origin", cache: "no-store", signal: AbortSignal.timeout(5000) })
30 .then(function (r) { return r.ok ? r.json() : null; })
31 .then(function (c) {
32 if (!c || !/^(green|red|running)$/.test(c.state)) return;
33 var ca = document.createElement("a");
34 ca.textContent = "check " + c.state + (c.state === "red" && typeof c.test === "string" && c.test ? ": " + c.test : "");
35 ca.rel = "noopener";
36 ca.style.cssText = k.ls;

cssText leaves a style attribute in the DOM. It matches the rest of this file, but the issue says none; prefer a class if the pill has a stylesheet.

37 try { var cu = new URL(c.log, k.forge); if (cu.origin === k.forge) ca.href = cu.href; } catch (e) {}
38 m.insertBefore(ca, m.firstChild);
39 })
40 .catch(function () {});
2741 // A signed-out visitor is shown the way in, not a box that refuses after they have typed.
2842 if (!k.signedIn) {
2943 var si = document.createElement("a");
test/apps-pill-check-route.test.ts added +121
@@ -0,0 +1,121 @@
1 /** `/__forge/check` on a preview: the pull's check as { state, test?, log } (#6381). */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { newApp } from "../src/actions/apps.ts";
9 import { signGrant, type AppTarget } from "../src/apps/proxy.ts";
10 import { checkSay } from "../src/apps/pill_check_say.ts";
11 import { commentJs } from "../src/apps/toolbar_comment.ts";
12 import { AppsRuntime } from "../src/apps/runtime.ts";
13 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
14 import { createIssue } from "../src/core/issues.ts";
15 import { setSealed } from "../src/core/sealed.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 const DOMAIN = "apps.test";
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let runtime: AppsRuntime;
27 let record: AppRecord;
28 let alice: string;
29 let repoId: string;
30 let open: { number: number; id: string };
31 let sealed: { number: number; id: string };
32
33 const pullRow = (issueId: string) =>
34 app.db.run(
35 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', 'x', 'b', 'h1', ?2)`,
36 [issueId, repoId],
37 );
38
39 beforeAll(async () => {
40 dataDir = await mkdtemp(join(tmpdir(), "forge-pillcheck-"));
41 app = createApp({ dataDir, port: 0, host: "forge.test" });
42 servers = await serve(app);
43 runtime = new AppsRuntime(app, { domain: DOMAIN, scheme: "http", publicPort: servers.port, forgeUrl: servers.url, concurrency: 1 });
44 await runtime.start();
45 const u = await createUser(app.db, {
46 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
47 password: "a-good-passphrase", adminIfFirst: true,
48 });
49 if (!u.ok) throw new Error(u.error);
50 alice = u.value.id;
51 const made = await newApp(app, u.value, { name: "notes", description: "x", visibility: "public" });
52 if (!made.ok) throw new Error(String(made.error));
53 repoId = made.value.repo.id;
54 record = getAppByRepo(app.db, repoId)!;
55 const a = createIssue(app.db, { repoId, authorId: alice, title: "a", kind: "pull" });
56 const b = createIssue(app.db, { repoId, authorId: alice, title: "b", kind: "pull" });
57 if (!a.ok || !b.ok) throw new Error("issue");
58 open = a.value;
59 sealed = b.value;
60 pullRow(open.id);
61 pullRow(sealed.id);
62 setSealed(app.db, sealed.id, true);
63 }, 120_000);
64
65 afterAll(async () => {
66 await runtime.stop();
67 servers.stop();
68 app.close();
69 await rm(dataDir, { recursive: true, force: true });
70 });
71
72 let n = 0;
73 const run = (issueId: string, state: string, detail?: object) =>
74 app.db.run(
75 `INSERT INTO run (id, repo_id, kind, issue_id, commit_oid, state, check_detail) VALUES (?1, ?2, 'check', ?3, 'h1', ?4, ?5)`,
76 [`01run${String(++n).padStart(4, "0")}`, repoId, issueId, state, detail ? JSON.stringify(detail) : ""],
77 );
78 const ask = (num: number, cookie?: string) =>
79 fetch(`${servers.url}/__forge/check`, { headers: { host: `notes--${num}.${DOMAIN}`, ...(cookie ? { cookie } : {}) } });
80
81 test("green, red with its first failing test, and running, each linking the run's log", async () => {
82 expect((await ask(open.number)).status).toBe(404);
83 run(open.id, "ok");
84 let j: any = await (await ask(open.number)).json();
85 expect(j.state).toBe("green");
86 expect(j.log).toMatch(/^\/alice\/notes\/runs\/01run0001$/);
87 expect(j.test).toBeUndefined();
88 run(open.id, "failed", { passed: 3, failed: 2, names: ["adds <two>", "second"] });
89 j = await (await ask(open.number)).json();
90 expect(j).toMatchObject({ state: "red", test: "adds <two>" });
91 run(open.id, "running");
92 j = await (await ask(open.number)).json();
93 expect(j.state).toBe("running");
94 expect(j.log).toContain("01run0003");
95 expect(checkSay(app.db, "alice/notes", open.id, "other")).toBeUndefined();
96 });
97
98 test("names its phases, and refuses a pull the viewer may not see", async () => {
99 await (await ask(open.number)).text();
100 const res = await ask(open.number);
101 const header = res.headers.get("server-timing") ?? "";
102 expect(header.split(", ").map((p) => p.split(";")[0]).sort()).toEqual(["pull", "render", "session"]);
103 run(sealed.id, "ok");
104 const guest = await ask(sealed.number);

Assert .toBe(404) for the guest on a sealed pull; not.toBe(200) would also pass on a 500.

105 expect(guest.status).not.toBe(200);
106 const target = { app: record, env: `pull-${sealed.number}` } as AppTarget;
107 const cookie = `forge_grant_${record.id.slice(-8)}=${signGrant(dataDir, target, 60_000, Date.now(), { id: alice, name: "alice", role: "admin" })}`;
108 expect((await ask(sealed.number, cookie)).status).toBe(200);
109 });
110
111 test("production answers nothing", async () => {
112 const res = await fetch(`${servers.url}/__forge/check`, { headers: { host: `notes.${DOMAIN}` } });
113 expect(res.status).toBe(404);
114 });
115
116 test("the client names the three words and sets no inline style or script", () => {
117 expect(commentJs).toContain('"check " + c.state');
118 expect(commentJs).toMatch(/green\|red\|running/);
119 expect(commentJs).toContain("/__forge/check");
120 expect(commentJs).not.toMatch(/setAttribute\("style"|innerHTML|eval\(|<script/);
121 });
test/apps-toolbar-state.test.ts +3 −1
@@ -48,9 +48,11 @@ const HOME_ALLOWANCE = 30;
4848 const FOLD_ALLOWANCE = 280;
4949 // Clearing the page's own fixed bars and the fold's cookie fallback (#16310): 654 bytes.
5050 const BAR_ALLOWANCE = 670;
51 // The comment script is handed the pull's check state (#6381), allowed by name: 17 bytes.
52 const CHECK_HANDOFF_ALLOWANCE = 20;
5153
5254 test("the addition stays under 300 bytes", () => {
53 expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE + YOURS_WHY_ALLOWANCE + TELL_CONTEXT_ALLOWANCE + HOME_ALLOWANCE + FOLD_ALLOWANCE + BAR_ALLOWANCE);
55 expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE + YOURS_WHY_ALLOWANCE + TELL_CONTEXT_ALLOWANCE + HOME_ALLOWANCE + FOLD_ALLOWANCE + BAR_ALLOWANCE + CHECK_HANDOFF_ALLOWANCE);
5456 const tag = toolbarTag("https://forge.test", where("x".repeat(CHANGE_MAX)), "p", "n");
5557 const bare = toolbarTag("https://forge.test", where(), "p", "n");
5658 expect(Buffer.byteLength(tag) - Buffer.byteLength(bare)).toBeLessThan(300);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs