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

Each release on /releases leads with one plain sentence of what changed for the owner, then the version #13186

Merged opened this

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

Merged

scout/forge:scout/13145-each-release-on-releases-leads-with-one → main 7 commits fork 3 threads · 3 unresolved

  • Merged. scout/13145-each-release-on-releases-leads-with-one was merged into main as 7cfd53f.

Review

Sign in to review this change.
5 files changed +239 −10
src/release/story.ts added +81
@@ -0,0 +1,81 @@
1 /**
2 * What a release changed, in one plain sentence, and which version it is.
3 * The release record keeps neither, so both are read from where they are
4 * kept: the commit's `Release X.Y.Z: <title> (#N);…` subject (the first
5 * change's title leads), else the landed pull's own title. A sha's subject
6 * never changes, so it is read once per process.
7 */
8
9 import type { App } from "../app.ts";
10 import { getIssue } from "../core/issues.ts";
11 import type { Repo } from "../core/repos.ts";
12 import { parseReleaseSubject } from "../core/release_subject.ts";
13 import { commitLog } from "../git/read.ts";
14 import { repoDir } from "../git/repos.ts";
15 import type { Release } from "./record.ts";
16
17 export interface Story {
18 readonly summary?: string;
19 readonly version?: string;
20 }
21
22 const subjectsByApp = new WeakMap<App, Map<string, string | null>>();
23
24 function subjectsOf(app: App): Map<string, string | null> {
25 let m = subjectsByApp.get(app);
26 if (m === undefined) subjectsByApp.set(app, (m = new Map()));
27 return m;
28 }
29
30 async function subjectOf(app: App, repo: Repo, sha: string): Promise<string | null> {
31 const key = `${repo.id}/${sha}`;
32 const subjects = subjectsOf(app);
33 const known = subjects.get(key);
34 if (known !== undefined) return known;
35 const log = await commitLog(repoDir(app.reposRoot, repo.ownerName, repo.name), sha, { limit: 1 });
36 if (!log.ok) return null; // not cached: the commit may arrive later
37 const subject = log.value[0]?.subject ?? null;
38 subjects.set(key, subject);
39 return subject;
40 }

Cold path: one git spawn per release per forge on first paint. Bound it (principle: first paint under 50 ms).

41
42 /** One sentence, no line breaks, bounded; undefined when nothing is left. */
43 function sentence(text: string): string | undefined {
44 const one = text.replace(/\s+/g, " ").trim();
45 return one === "" ? undefined : one.length > 140 ? `${one.slice(0, 139)}…` : one;
46 }
47
48 export async function releaseStory(app: App, repo: Repo | undefined, r: Release, liveVersion?: string): Promise<Story> {
49 let summary: string | undefined;
50 let version = liveVersion;
51 if (repo !== undefined) {
52 const parsed = parseReleaseSubject((await subjectOf(app, repo, r.sha)) ?? "");
53 if (parsed !== undefined) {
54 version = parsed.version;
55 summary = sentence(parsed.pulls[0]?.title ?? "");
56 }
57 if (summary === undefined && r.pullNumber !== null) summary = sentence(getIssue(app.db, r.repoId, r.pullNumber)?.title ?? "");
58 }
59 return { ...(summary === undefined ? {} : { summary }), ...(version === undefined || version === "dev" ? {} : { version }) };
60 }
61
62 /** Only this many of the newest releases are read for a story: each cold one is a git spawn. */
63 export const STORIES_READ = 8;
64
65 /** The stories of a list of releases, newest first as listed; rows past the bound get none. */
66 export async function releaseStories(
67 app: App,
68 repoOf: (r: Release) => Repo | undefined,
69 releases: readonly Release[],
70 liveSha: string | null,
71 liveVersion: string,
72 ): Promise<Story[]> {
73 return Promise.all(
74 releases.map((r, i) => {
75 const isLive = liveSha !== null && r.sha === liveSha;
76 return i < STORIES_READ || isLive
77 ? releaseStory(app, repoOf(r), r, isLive ? liveVersion : undefined)
78 : Promise.resolve({});
79 }),
80 );
81 }
src/tui/screens/releases.ts +21 −4
@@ -9,6 +9,7 @@
99 import { getRepoById } from "../../core/repos.ts";
1010 import { running } from "../../kernel/version.ts";
1111 import { BOOTED, canRollBackTo, mayRead, mayRollBack, rollBackTo } from "../../release/gate.ts";
12 import { releaseStories, type Story } from "../../release/story.ts";
1213 import { listReleases, type Release } from "../../release/record.ts";
1314 import { lastProof, proveAgain } from "../../release/prove.ts";
1415 import { journeyLine, liveSince, NO_RELEASES_YET, plain } from "../../release/words.ts";
@@ -26,6 +27,8 @@ export interface ReleaseLine {
2627 readonly live: boolean;
2728 /** Whether Enter may roll back to it, for this person. */
2829 readonly rollable: boolean;
30 /** The one sentence and the version, as the page shows them. */
31 readonly story: Story;
2932 }
3033
3134 /** The live line (`liveSince`), or nothing when no release is known to be live. */
@@ -34,7 +37,10 @@ export function liveText(f: Session): string | undefined {
3437 return live === null || !mayRead(f.app, f.user) ? undefined : liveSince(plain, live.slice(0, 7), ago(BOOTED));
3538 }
3639
37 /** The proven stranger's journey line for the serving version (`journeyLine`), or undefined without timings. */
40 /**
41 * The proven stranger's journey line for the serving version (`journeyLine`), or undefined without
42 * timings.
43 */
3844 export function journeyText(f: Session): string | undefined {
3945 const p = lastProof(f.app.config.dataDir);
4046 if (p === undefined || !p.ok || p.version !== running().version || !mayRead(f.app, f.user)) return undefined;
@@ -46,26 +52,37 @@ export async function readReleases(f: Session): Promise<ReleaseLine[]> {
4652 if (!mayRead(f.app, f.user)) return [];
4753 const live = running().commit;
4854 const writer = mayRollBack(f.app, f.user);
55 const releases = listReleases(f.db);
56 const stories = await releaseStories(
57 f.app,
58 (r) => (r.pullNumber === null ? undefined : getRepoById(f.db, r.repoId)),
59 releases,
60 live,
61 running().version,
62 );
4963 const lines: ReleaseLine[] = [];
50 for (const release of listReleases(f.db)) {
64 for (const [i, release] of releases.entries()) {
5165 const isLive = live !== null && release.sha === live;
5266 lines.push({
5367 release,
5468 live: isLive,
5569 rollable: writer && !isLive && (await canRollBackTo(f.app, release)),
70 story: stories[i]!,
5671 });
5772 }
5873 return lines;
5974 }
6075
6176 export function releaseRows(f: Session, lines: readonly ReleaseLine[]): ListRow[] {
62 return lines.map(({ release: r, live }) => {
77 return lines.map(({ release: r, live, story }) => {
6378 const repo = getRepoById(f.db, r.repoId);
6479 const pull = r.pullNumber === null ? "no pull" : `${repo ? `${repo.ownerName}/${repo.name}` : "pull"} #${r.pullNumber}`;
6580 return {
66 title: r.sha.slice(0, 7),
81 title: story.summary ?? r.sha.slice(0, 7),
6782 tone: live ? "success" : r.ok ? "default" : "danger",
6883 meta: metaOf(
84 story.version === undefined ? "" : `v${story.version}`,
85 story.summary === undefined ? "" : r.sha.slice(0, 7),
6986 pull,
7087 `landed ${ago(r.createdAt)}`,
7188 live ? `healthy since ${ago(BOOTED)}` : "",
src/web/pages/releases.ts +17 −6
@@ -13,6 +13,7 @@ import { running } from "../../kernel/version.ts";
1313 import type { Ctx } from "../../http/context.ts";
1414 import { lastProof, proofNotice, proveAgain } from "../../release/prove.ts";
1515 import { listReleases } from "../../release/record.ts";
16 import { releaseStories } from "../../release/story.ts";
1617 import { BOOTED, canRollBackTo, mayRead, mayRollBack, rollBackTo } from "../../release/gate.ts";
1718 import { journeyLine, liveSince, NO_RELEASES_YET } from "../../release/words.ts";
1819 import { notFoundPage, signInFirst, NOT_ADMIN_HERE, SIGN_IN_TO_DO, forbiddenPage } from "../chrome.ts";
@@ -33,7 +34,10 @@ export function liveLine(ctx: Ctx): Html | undefined {
3334 </p>`;
3435 }
3536
36 /** The proven stranger's journey line for the version serving, or nothing when the last proof kept no timings. */
37 /**

Unrelated comment rewrap; revert it so the diff holds only the story (box 2).

38 * The proven stranger's journey line for the version serving, or nothing when the last proof kept
39 * no timings.
40 */
3741 export function journeyCard(ctx: Ctx): Html | undefined {
3842 const p = lastProof(ctx.app.config.dataDir);
3943 if (p === undefined || !p.ok || p.version !== running().version) return undefined;
@@ -77,7 +81,8 @@ export async function proveAgainSubmit(ctx: Ctx): Promise<Response> {
7781 if (user === undefined) return forbiddenPage(ctx, SIGN_IN_TO_DO);
7882 const form = await readForm(ctx, "rw");
7983 if (form instanceof Response) return form;
80 // Anyone who may read the releases may ask for a proof again: it changes nothing but when the next one runs.
84 // Anyone who may read the releases may ask for a proof again: it changes nothing but when the
85 // next one runs.
8186 if (user.kind === "agent" || !mayRead(ctx.app, user)) return forbiddenPage(ctx, NOT_ADMIN_HERE);
8287 return proveAgain(ctx.app.config.dataDir)
8388 ? flashTo(ctx, "/releases", { message: "Asked: the forge proves this release again at its next tick, within a minute." })
@@ -86,7 +91,8 @@ export async function proveAgainSubmit(ctx: Ctx): Promise<Response> {
8691
8792 /**
8893 * An owner's hold reason and a keeper's reason are free text: inside
89 * `[data-releases]` they break anywhere, so the page never scrolls sideways at 390 px. No new class.
94 * `[data-releases]` they break anywhere, so the page never scrolls sideways at 390 px. No new
95 * class.
9096 */
9197 export const RELEASES_CSS = `[data-releases] { overflow-wrap: anywhere; }
9298 [data-releases] input[name="reason"] { max-width: 100%; }`;
@@ -109,18 +115,20 @@ export async function releasesPage(ctx: Ctx): Promise<Response> {
109115 ? await Promise.all(releases.map((r) => (live !== null && r.sha === live ? false : canRollBackTo(ctx.app, r))))
110116 : releases.map(() => false);
111117 notePhase(ctx.request, "rollback", performance.now() - checking);
118 const stories = await releaseStories(ctx.app, (r) => (r.pullNumber === null ? undefined : repos.get(r.repoId)), releases, live, running().version);
112119 const rendering = performance.now();
113120 const rows: Html[] = [];
114121 for (const [i, r] of releases.entries()) {
115122 const isLive = live !== null && r.sha === live;
116123 const repo = r.pullNumber === null ? undefined : repos.get(r.repoId);
124 const story = stories[i]!;
117125 rows.push(
outdated

Principle 1/8: sentence, version, sha and badges all in the title. Keep the title to the sentence; version and sha go in meta so a phone wraps cleanly.

118126 row({
119127 nav: true,
120128 ...(repo === undefined || r.pullNumber === null ? {} : { href: `/${repo.ownerName}/${repo.name}/pulls/${r.pullNumber}` }),
121 title: html`${sha(r.sha)} ${when(isLive, () => badge("live", { tone: "success" }))}
129 title: html`${story.summary ?? sha(r.sha)} ${when(isLive, () => badge("live", { tone: "success" }))}
122130 ${when(!r.ok, () => badge("preflight failed", { tone: "danger" }))}`,
123 meta: html`${r.pullNumber === null ? null : html`#${r.pullNumber} · `}landed ${time(r.createdAt)}${isLive ? html` · healthy since ${time(BOOTED)}` : null}`,
131 meta: html`${story.version === undefined ? null : html`v${story.version} · `}${story.summary === undefined ? null : html`${sha(r.sha)} · `}${r.pullNumber === null ? null : html`#${r.pullNumber} · `}landed ${time(r.createdAt)}${isLive ? html` · healthy since ${time(BOOTED)}` : null}`,
124132 ...(rollable[i] === true
125133 ? { after: html`<form method="post" action="/releases/${r.sha}/rollback">${btn("Roll back", { type: "submit" })}</form>` }
126134 : {}),
@@ -166,7 +174,10 @@ export async function releaseHoldSubmit(ctx: Ctx): Promise<Response> {
166174 : flashTo(ctx, "/releases", { tone: "danger", message: held.message });
167175 }
168176
169 /** POST /releases/now: cut at the keeper's next tick, with a reason, through the function MCP calls (#11839). */
177 /**
178 * POST /releases/now: cut at the keeper's next tick, with a reason, through the function MCP calls
179 * (#11839).
180 */
170181 export async function releaseNowSubmit(ctx: Ctx): Promise<Response> {
171182 const form = await readForm(ctx, "rw");
172183 if (form instanceof Response) return form;
test/releases-story.test.ts added +99
@@ -0,0 +1,99 @@
1 /**
2 * Each release row on /releases leads with one plain sentence of what changed,
3 * then the version: the release commit's first change when its subject names
4 * one, else the landed pull's title; no sentence and no version when neither is known.
5 */
6 import { afterAll, beforeAll, expect, setDefaultTimeout, test } from "bun:test";
7 import { mkdtempSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createIssue } from "../src/core/issues.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { getUserById } from "../src/core/users.ts";
15 import { markVerified } from "../src/core/verify.ts";
16 import { repoDir } from "../src/git/repos.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { recordRelease } from "../src/release/record.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22 setDefaultTimeout(30_000);
23
24 let root = "";
25 let app: App;
26 let servers: Servers;
27 let cookie = "";
28 let withSubject = "";
29 const LIVE = "d".repeat(40);
30 const was = process.env["FORGE_COMMIT"];
31
32 const git = (dir: string, args: string[], input?: string): string => {
33 const p = Bun.spawnSync(["git", ...args], {
34 cwd: dir,
35 stdin: input === undefined ? undefined : new TextEncoder().encode(input),
36 env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" },
37 });
38 if (p.exitCode !== 0) throw new Error(p.stderr.toString());
39 return p.stdout.toString().trim();
40 };
41
42 beforeAll(async () => {
43 process.env["FORGE_COMMIT"] = LIVE;
44 root = mkdtempSync(join(tmpdir(), "forge-releases-story-"));
45 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
46 app.db.query("INSERT INTO user (id, username, email, password_hash, is_admin) VALUES ('u-alice','alice','[email protected]','x',1)").run();
47 markVerified(app.db, "u-alice", new Date().toISOString());
48 const made = await createRepo(app, getUserById(app.db, "u-alice")!, { name: "forge" });
49 if (!made.ok) throw new Error(made.error);
50 const repo = app.db.query<{ id: string }, []>("SELECT id FROM repo WHERE name='forge'").get()!;
51 const dir = repoDir(app.reposRoot, "alice", "forge");
52 const tree = git(dir, ["hash-object", "-t", "tree", "-w", "--stdin"], "");
53 withSubject = git(dir, ["commit-tree", tree, "-m", "Release 1.2.3: Faster feed <b>x</b> (#5);Other (#6)"]);
54 // One release names its change in its commit; one has only a pull with a title; one has neither.
55 const pull = createIssue(app.db, { repoId: repo.id, authorId: "u-alice", title: "Owners see their crew first", kind: "pull" });
56 if (!pull.ok) throw new Error("pull");
57 recordRelease(app.db, { sha: withSubject, repoId: repo.id, pullNumber: 5, ok: true, line: "ok" });
58 recordRelease(app.db, { sha: "e".repeat(40), repoId: repo.id, pullNumber: pull.value.number, ok: true, line: "ok" });
59 const long = createIssue(app.db, { repoId: repo.id, authorId: "u-alice", title: `Long ${"word ".repeat(35)}`, kind: "pull" });
60 if (!long.ok) throw new Error("pull");
61 recordRelease(app.db, { sha: "9".repeat(40), repoId: repo.id, pullNumber: long.value.number, ok: true, line: "ok" });
62 recordRelease(app.db, { sha: "f".repeat(40), repoId: repo.id, pullNumber: null, ok: true, line: "ok" });
63 servers = await serve(app);
64 cookie = `forge_session=${createSession(app.db, "u-alice").token}`;
65 }, 60_000);
66
67 afterAll(() => {
68 if (was === undefined) delete process.env["FORGE_COMMIT"];
69 else process.env["FORGE_COMMIT"] = was;
70 servers.stop();
71 app.close();
72 rmSync(root, { recursive: true, force: true });
73 });
74
75 test("a release leads with its first change, then the version, then the sha; a pull's title stands in; bare ones stay as they were", async () => {
76 const body = await (await fetch(`${servers.url}/releases`, { headers: { cookie } })).text();
77 const items = body.slice(body.indexOf('<ul class="list setting-list">')).split("<li").slice(1);
78 const rowOf = (s: string) => items.find((i) => i.includes(s))!;
79 const metaOf = (s: string) => rowOf(s).replace(/^[\s\S]*?<(?:p|div|span)[^>]*meta[^>]*>/, "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ");
80 const text = (s: string) => rowOf(s).replace(/<[^>]*>/g, " ").replace(/\s+/g, " ");
81 // Escaped, and the first change only.
82 expect(text(withSubject.slice(0, 7))).toContain("Faster feed &lt;b&gt;x&lt;/b&gt;");
83 // The title is the sentence alone; the version and the sha ride the meta line.
84 expect(metaOf(withSubject.slice(0, 7))).toMatch(new RegExp(`^v1\\.2\\.3 · ${withSubject.slice(0, 7)} · #5 · landed`));
85 expect(rowOf(withSubject.slice(0, 7))).not.toContain("<b>x</b>");
86 expect(text(withSubject.slice(0, 7))).not.toContain("Other");
87 // No subject to read: the landed pull's title, and no invented version.
88 expect(text("eeeeeee")).toMatch(/^[\s>]*Owners see their crew first/);
89 expect(text("eeeeeee")).not.toMatch(/ v\d/);
90 // A long title is cut to one bounded sentence with an ellipsis.
91 const longText = text("9999999");
92 expect(longText).toContain("…");
93 expect(longText).not.toContain("word ".repeat(30));
94 // Neither: the row begins with the sha as before.
95 expect(text("fffffff")).toMatch(/^[\s>]*fffffff/);
96 // The order is unchanged: newest first.
97 expect(body.indexOf("fffffff")).toBeLessThan(body.indexOf("eeeeeee"));
98 expect(body.indexOf("eeeeeee")).toBeLessThan(body.indexOf(withSubject.slice(0, 7)));
99 });
test/tui-releases.test.ts +21
@@ -8,6 +8,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
88 import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
11 import { createIssue } from "../src/core/issues.ts";
1112 import { createRepo } from "../src/actions/repos.ts";
1213 import { createApp, type App } from "../src/app.ts";
1314 import { setMember } from "../src/core/roles.ts";
@@ -205,4 +206,24 @@ describe("the releases screen", () => {
205206 rmSync(join(root, "release", "proof.json"), { force: true });
206207 }
207208 });
209
210 test("a release with a landed pull shows its sentence, then the version line, as the page does; a long title is cut", async () => {
211 const repoId = app.db.query<{ id: string }, []>("SELECT id FROM repo WHERE name='forge'").get()!.id;
212 const pull = createIssue(app.db, { repoId, authorId: alice.id, title: "Owners see their crew first", kind: "pull" });
213 const long = createIssue(app.db, { repoId, authorId: alice.id, title: `Long ${"word ".repeat(35)}`, kind: "pull" });
214 if (!pull.ok || !long.ok) throw new Error("pull");
215 recordRelease(app.db, { sha: "c".repeat(40), repoId, pullNumber: pull.value.number, ok: true, line: "ok" });
216 recordRelease(app.db, { sha: "d".repeat(40), repoId, pullNumber: long.value.number, ok: true, line: "ok" });
217 const lines = await readReleases(new Session(app, identity(alice)));
218 const of = (c: string) => lines.find((l) => l.release.sha === c.repeat(40))!;
219 expect(of("c").story.summary).toBe("Owners see their crew first");
220 expect(of("d").story.summary!.length).toBeLessThanOrEqual(140);
221 expect(of("d").story.summary).toContain("…");
222 const text = await open(alice);
223 expect(text).toContain("Owners see their crew first");
224 expect(text).toContain("ccccccc");
225 expect(text).not.toContain("word ".repeat(30));
226 // Without a story the row is as it was: the sha leads.
227 expect(text).toContain("bbbbbbb");
228 });
208229 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs