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

The forge toolbar in an app shows the app's state word and the last landed change in one line #13177

Merged opened this

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

Merged

scout/forge:scout/13163-the-forge-toolbar-in-an-app-shows-the-ap → main 10 commits fork 5 threads · 5 unresolved

  • Merged. scout/13163-the-forge-toolbar-in-an-app-shows-the-ap was merged into main as a00842f.

Review

Sign in to review this change.
7 files changed +196 −10
src/apps/landed.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * The last landed change of each running environment: the subject of the
3 * commit it serves, noted once at the swap-in (where the deploy already reads
4 * git) so the toolbar's request path reads a map and runs no query.
5 */
6
7 /** Per forge (an app object), as the state rule asks: two forges never see each other's. */
8 const noted = new WeakMap<object, Map<string, { oid: string; subject: string }>>();
9
10 /** The longest change the toolbar carries: it rides in every app page. */
11 export const CHANGE_MAX = 60;
12
13 /** Note what the commit `oid` changed, as its subject line, for an app's environment. */
14 export function noteLanded(app: object, appId: string, env: string, oid: string, subject: string): void {
15 let subjects = noted.get(app);
16 if (subjects === undefined) noted.set(app, (subjects = new Map()));
17 const line = (subject.split("\n")[0] ?? "").trim();
18 if (line === "") subjects.delete(`${appId}/${env}`);

Entries are keyed by app/env and never removed when an environment is retired, so pull-N previews accumulate for the life of the process. Delete the entry when the environment is torn down.

19 else subjects.set(`${appId}/${env}`, { oid, subject: line.length > CHANGE_MAX ? line.slice(0, CHANGE_MAX - 1) + "…" : line });
20 }
21
22 /** The noted change, only while it is the commit named; otherwise undefined. */
23 export function landedChange(app: object, appId: string, env: string, oid: string): string | undefined {
24 const one = noted.get(app)?.get(`${appId}/${env}`);
25 return one?.oid === oid ? one.subject : undefined;
26 }
27
28 /** Drop the note for an environment that is gone, so retired previews do not pile up. */
29 export function forgetLanded(app: object, appId: string, env: string): void {
30 noted.get(app)?.delete(`${appId}/${env}`);
31 }
src/apps/proxy.ts +3
@@ -15,6 +15,7 @@
1515 * directory — so guessing a hostname yields the forge's own "not found".
1616 */
1717
18 import { landedChange } from "./landed.ts";
1819 import { expireCookie, setCookie } from "../auth/cookies.ts";
1920 import { compressBytes, MIN_BYTES, negotiate } from "../http/compress.ts";
2021 import type { Database } from "bun:sqlite";
@@ -576,6 +577,8 @@ export function pillWhere(
576577 const liveAt = live?.servingAt ?? live?.since;
577578 if (live?.state === "running" && live.commitOid !== "" && liveAt !== undefined)
578579 where.serving = { oid: live.commitOid, at: liveAt };
580 const change = live?.commitOid === undefined ? undefined : landedChange(runtime.app, target.app.id, target.env, live.commitOid);
581 if (where.serving !== undefined && change !== undefined) where.serving.change = change;
579582 const number = /^pull-(\d+)$/.exec(target.env)?.[1];
580583 if (number === undefined) return where;
581584 where.pull = Number(number);
src/apps/runtime.ts +34 −4
@@ -19,6 +19,8 @@ import { cellHides, grantsHere } from "../spawn/hosted-mark.ts";
1919 import { VERIFYING_NOTE } from "./env_phrase.ts";
2020 import { listEgressGrants } from "../core/egress_grants.ts";
2121 import { recordCarried } from "../core/carried.ts";
22 import { commitLog } from "../git/read.ts";
23 import { forgetLanded, noteLanded } from "./landed.ts";
2224 import { releaseOfCommit } from "../core/release_subject.ts";
2325 import { pullDir, runDir } from "../core/pulls.ts";
2426 import { accountActive } from "../core/accounts.ts";
@@ -184,7 +186,10 @@ export interface RuntimeOptions {
184186 * its own, so proving `app.example.com` needs no network in a test.
185187 */
186188 readonly dns?: DomainResolver | undefined;
187 /** What the registrar adapter calls (`apps/dns_provider.ts`); the global `fetch` unless a test hands in its own. */
189 /**
190 * What the registrar adapter calls (`apps/dns_provider.ts`); the global `fetch` unless a test
191 * hands in its own.
192 */
188193 readonly dnsFetch?: typeof fetch | undefined;
189194 /**
190195 * What a check asks of a verified domain to read its certificate's expiry:
@@ -447,7 +452,10 @@ interface Environment {
447452 buildOrder?: number | undefined;
448453 }
449454
450 /** How many build previews (`build-<sha7>`) one app runs at once; a newer one takes the oldest's place. */
455 /**
456 * How many build previews (`build-<sha7>`) one app runs at once; a newer one takes the oldest's
457 * place.
458 */
451459 export const BUILD_PREVIEWS_MAX = 3;
452460
453461 /** The deploy reasons that mean a person touched the change. */
@@ -855,8 +863,10 @@ export class AppsRuntime {
855863 ): Promise<void> {
856864 const dir = repoDir(this.app.reposRoot, repo.ownerName, repo.name);
857865 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
858 if (tip !== undefined && only !== "preview")
866 if (tip !== undefined && only !== "preview") {
867 if (reason === "boot") await this.noteChange(repo, record.id, "production", tip);
859868 this.requestDeploy(record, repo, "production", tip, reason);
869 }
860870 const open = new Set<EnvName>(["production"]);
861871 // A variant is a branch kept running: it stays while its row does, whatever
862872 // pulls are open (`core/variants.ts`).
@@ -898,7 +908,10 @@ export class AppsRuntime {
898908 this.hibernateAtBoot(record, env, head, idleSince);
899909 continue;
900910 }
901 if (this.settleAsleep(record, env, head)) continue;
911 if (this.settleAsleep(record, env, head)) {
912 await this.noteChange(repo, record.id, env, head);
913 continue;
914 }
902915 }
903916 this.requestDeploy(record, repo, env, head, reason);
904917 }
@@ -912,6 +925,21 @@ export class AppsRuntime {
912925 }
913926 }
914927
928 /**
929 * Note the subject of the commit an environment serves, for the toolbar's "what changed"
930 * (`apps/landed.ts`): at the swap-in, and at boot for one adopted asleep or about to come back,
931 * so a restart does not leave every app saying "no change yet". A nicety: git that cannot be
932 * read is logged, never thrown into the deploy or the boot.
933 */
934 private async noteChange(repo: Repo, appId: string, env: EnvName, oid: string): Promise<void> {
935 try {
936 const read = await commitLog(repoDir(this.app.reposRoot, repo.ownerName, repo.name), oid, { limit: 1 });
937 noteLanded(this.app, appId, env, oid, read.ok ? (read.value[0]?.subject ?? "") : "");
938 } catch (error) {
939 log.warn("could not read the landed change", { repo: repo.name, env, commit: oid.slice(0, 7), error: String(error) });
940 }
941 }
942
915943 /** Data on disk for apps that no longer exist. */
916944 private pruneDirs(known: Set<string>): void {
917945 const root = appsRoot(this.app.config.dataDir);
@@ -1444,6 +1472,7 @@ export class AppsRuntime {
14441472 ? `serving ${url} — ${elapsedSeconds(deployStartedAt, servingAt)} after the deploy started`
14451473 : `serving ${url}`,
14461474 );
1475 await this.noteChange(repo, state.app.id, state.env, live.commitOid);
14471476 // The same statement the log line above just made, on the bus: a
14481477 // subscriber (the looks service) must never be able to take the
14491478 // deploy path down with it.
@@ -2489,6 +2518,7 @@ export class AppsRuntime {
24892518 const state = this.envs.get(k);
24902519 if (state !== undefined) {
24912520 this.envs.delete(k);
2521 forgetLanded(this.app, record.id, env);
24922522 if (state.queued)
24932523 cancelRun(this.app.db, state.queued.id, "the environment was removed");
24942524 state.deploying?.abort.abort();
src/apps/toolbar.ts +5 −4
@@ -128,8 +128,8 @@ const toolbarSource = `(function () {
128128 var ago = function (iso) {
129129 var t = Date.parse(iso || "");
130130 if (!(t > 0)) return "";
131 var m = Math.max(0, Math.floor((Date.now() - t) / 60000));
132 return m < 1 ? "just now" : m < 60 ? m + " min ago" : m < 1440 ? Math.floor(m / 60) + " h ago" : Math.floor(m / 1440) + " d ago";
131 var m = Math.max(0, (Date.now() - t) / 60000 | 0);
132 return m < 1 ? "just now" : m < 60 ? m + " min ago" : m < 1440 ? (m / 60 | 0) + " h ago" : (m / 1440 | 0) + " d ago";
133133 };
134134 var liveAgo = "";
135135 if (/^[0-9a-f]{7,64}$/.test(d.commit || "") && (liveAgo = ago(d.live))) {
@@ -142,8 +142,8 @@ const toolbarSource = `(function () {
142142 try { cl = document.createElement("a"); cl.href = new URL("/" + d.repo + "/commit/" + d.commit, fo).href; cl.rel = "noopener"; cl.style.color = LC; cl.textContent = short; } catch (e) { cl = null; }
143143 }
144144 if (cl) sv.appendChild(cl); else part(short);
145 part(", live " + liveAgo);
146145 panel.appendChild(sv);
146 line("live \\u00b7 " + (d.change || "no change yet") + " \\u00b7 " + liveAgo);
outdated

When d.change is empty this omits the segment. The issue asks for live · no change yet · <ago>; emit that text instead of dropping it (and fix the matching test).

147147 }
148148 var link = document.createElement("a");
149149 link.textContent = "Home";
@@ -700,7 +700,7 @@ export type PillWhere = {
700700 * The commit the environment is serving and the instant it went live, from the forge's own
701701 * record.
702702 */
703 serving?: { oid: string; at: string };
703 serving?: { oid: string; at: string; change?: string };
704704 };
705705
706706 /** `text` safe inside a double-quoted HTML attribute. */
@@ -753,6 +753,7 @@ export function toolbarTag(
753753 ["check", where.check],
754754 ["commit", where.serving?.oid],
755755 ["live", where.serving?.at],
756 ["change", where.serving?.change],
756757 ["behind", where.behind === true ? "1" : undefined],
757758 ["deploying", where.deploying === true ? "1" : undefined],
758759 ["waits", where.waits === true ? PREVIEW_WAITS : undefined],
test/apps-landed-wiring.test.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * The toolbar's "what last changed" is wired end to end (#13163): the swap-in notes the served
3 * commit's subject, the pill's data carries it for a reader only, and a torn-down environment
4 * forgets it.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import type { AppRecord } from "../src/core/apps.ts";
8 import { newApp } from "../src/actions/apps.ts";
9 import { forgetLanded, landedChange } from "../src/apps/landed.ts";
10 import { pillWhere, type AppTarget } from "../src/apps/proxy.ts";
11 import type { AppsRuntime } from "../src/apps/runtime.ts";
12 import {
13 APPS_DOMAIN,
14 appsRuntime,
15 deploySettled,
16 startAppsForge,
17 stopAppsForge,
18 type AppsForge,
19 } from "./helpers/apps-forge.ts";
20
21 let forge: AppsForge;
22 let runtime: AppsRuntime;
23 let record: AppRecord;
24 let oid = "";
25
26 beforeAll(async () => {
27 forge = await startAppsForge();
28 runtime = forge.runtime;
29 const made = await newApp(forge.app, forge.alice, { name: "wired", description: "x", visibility: "private" });
30 if (!made.ok) throw new Error(String(made.error));
31 record = made.value.app;
32 const run = await deploySettled(forge.app, made.value.repo.id, (r) => r.env === "production");
33 expect(run.state).toBe("ok");
34 oid = run.commitOid;
35 }, 90_000);
36
37 afterAll(async () => {
38 await runtime.stop();
39 await stopAppsForge(forge);
40 });
41
42 const target = (): AppTarget => ({ app: record, env: "production" });
43
44 test("the swap-in notes the subject of the commit it serves", () => {
45 const change = landedChange(forge.app, record.id, "production", oid);
46 expect(typeof change).toBe("string");
47 expect(change!.length).toBeGreaterThan(0);
48 expect(landedChange(forge.app, record.id, "production", "b".repeat(40))).toBeUndefined();
49 });
50
51 test("pillWhere gives a reader the change on serving, and a stranger nothing", () => {
52 const reader = pillWhere(runtime, target(), { id: forge.alice.id, name: forge.alice.username, role: "user" });
53 expect(reader.serving?.oid).toBe(oid);
54 expect(reader.serving?.change).toBe(landedChange(forge.app, record.id, "production", oid));
55 const stranger = pillWhere(runtime, target(), undefined);
56 expect(stranger.serving).toBeUndefined();
57 expect(JSON.stringify(stranger)).not.toContain(landedChange(forge.app, record.id, "production", oid)!);
58 });
59
60 test("a forge coming back notes the change at boot, before any swap-in", async () => {
61 await runtime.stop();
62 // What a fresh process remembers: nothing.
63 forgetLanded(forge.app, record.id, "production");
64 runtime = appsRuntime(forge.app, forge.servers, APPS_DOMAIN, 2);
65 await runtime.start();
66 expect(landedChange(forge.app, record.id, "production", oid)).toBeTruthy();
67 });
68
69 test("tearing the environment down forgets the change", async () => {
70 await runtime.teardown(record, "production");
71 expect(landedChange(forge.app, record.id, "production", oid)).toBeUndefined();
72 });
test/apps-toolbar-state.test.ts added +47
@@ -0,0 +1,47 @@
1 /**
2 * The toolbar says live · what last changed · how long ago, from data the page already carries
3 * (#13163).
4 */
5 import { expect, test } from "bun:test";
6 import { CHANGE_MAX, landedChange, noteLanded } from "../src/apps/landed.ts";
7 import { boot } from "./helpers/toolbar-boot.ts";
8 import { toolbarJs, toolbarTag } from "../src/apps/toolbar.ts";
9
10 const oid = "a".repeat(40);
11 const where = (change?: string) => ({
12 app: "notes", env: "production",
13 serving: { oid, at: "2026-11-15T10:00:00Z", ...(change === undefined ? {} : { change }) },
14 });
15
16 test("the change rides in the tag, escaped", () => {
17 const tag = toolbarTag("https://forge.test", where('x" onload="y"><b>'), "p", "n0nce");
18 expect(tag).toContain('data-change="x&quot; onload=&quot;y&quot;&gt;&lt;b&gt;"');
19 expect(tag).not.toContain("<b>");
20 });
21
22 test("no landed change leaves the attribute out and the pill says there is none yet", () => {
outdated

This asserts a substring of the script source, so it would pass even if the rendering were broken. Render the script and check the text instead.

23 expect(toolbarTag("https://forge.test", where())).not.toContain("data-change");
24 const set = { app: "notes", env: "production", repo: "alice/notes", forge: "https://forge.test", commit: oid, live: new Date(Date.now() - 4 * 60000 - 5000).toISOString() };
25 expect(boot(null, 400, 800, set).texts()).toContain("live \u00b7 no change yet \u00b7 4 min ago");
26 expect(boot(null, 400, 800, { ...set, change: "Fix <b>the</b> thing" }).texts()).toContain("live \u00b7 Fix <b>the</b> thing \u00b7 4 min ago");
27 });
28
29 test("the addition stays under 300 bytes", () => {
30 const line = toolbarJs.slice(toolbarJs.indexOf('line("live'), toolbarJs.indexOf('line("live') + 200).split("\n")[0]!;
31 expect(Buffer.byteLength(line)).toBeLessThan(300);
32 const tag = toolbarTag("https://forge.test", where("x".repeat(CHANGE_MAX)), "p", "n");
33 const bare = toolbarTag("https://forge.test", where(), "p", "n");
34 expect(Buffer.byteLength(tag) - Buffer.byteLength(bare)).toBeLessThan(300);
35 });
36
37 const forgeApp = {};
38
39 test("the noted change is the first line, bounded, and only for the commit it names", () => {
40 noteLanded(forgeApp, "app1", "production", oid, "Fix the thing\n\nlong body");
41 expect(landedChange(forgeApp, "app1", "production", oid)).toBe("Fix the thing");
42 expect(landedChange(forgeApp, "app1", "production", "b".repeat(40))).toBeUndefined();
43 noteLanded(forgeApp, "app1", "production", oid, "y".repeat(500));
44 expect(landedChange(forgeApp, "app1", "production", oid)!.length).toBe(CHANGE_MAX);
45 noteLanded(forgeApp, "app1", "production", oid, "");
46 expect(landedChange(forgeApp, "app1", "production", oid)).toBeUndefined();
47 });
test/toolbar-serving.test.ts +4 −2
@@ -1,4 +1,6 @@
1 /** The panel says which commit the page is serving and since when, from the forge's record (#11480). */
1 /**
2 * The panel says which commit the page is serving and since when, from the forge's record (#11480).
3 */
24 import { afterAll, beforeAll, expect, test } from "bun:test";
35 import { mkdtemp, rm } from "node:fs/promises";
46 import { tmpdir } from "node:os";
@@ -27,7 +29,7 @@ test("with a record the panel says the short id, linked to the commit, and how l
2729 const { texts, anchors } = line({ ...base, commit: OID, live: ago(4 * 60000 + 5000) });
2830 expect(texts).toContain("Serving ");
2931 expect(texts).toContain("a1b2c3d");
30 expect(texts).toContain(", live 4 min ago");
32 expect(texts).toContain("live \u00b7 no change yet \u00b7 4 min ago");
3133 expect(anchors.find((a) => a.textContent === "a1b2c3d")?.href).toBe(`https://forge.test/alice/notes/commit/${OID}`);
3234 });
3335

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs