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

OG designs for app, change/pull, run, repo and issue pages #2027

Parked opened this in answer to
Closed without merging

scout/forge:scout/455-og-designs-for-app-change-pull-run-repo → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +294 −27
src/core/dependencies.ts +19
@@ -664,3 +664,22 @@ export function levelAndFlow(
664664 }
665665 return out;
666666 }
667
668 /**
669 * Open, unsealed issues of a repository that wait for an open, unsealed
670 * issue. Sealed issues on either side are not counted, so the number never
671 * reveals one.
672 */
673 export function blockedOpenCount(db: Database, repoId: string): number {
674 return (
675 db
676 .query<{ n: number }, [string]>(
677 `SELECT COUNT(DISTINCT i.id) AS n FROM issue AS i
678 JOIN issue_dependency AS d ON d.issue_id = i.id
679 JOIN issue AS b ON b.id = d.blocked_by_id
680 WHERE i.repo_id = ?1 AND i.kind = 'issue' AND i.state = 'open' AND i.sealed = 0
681 AND b.state = 'open' AND b.sealed = 0`,
682 )
683 .get(repoId)?.n ?? 0
684 );
685 }
src/core/runs.ts +34
@@ -1111,3 +1111,37 @@ export function listRunning(
11111111 issue: r.issue_number,
11121112 }));
11131113 }
1114
1115 /** The state of a repository's newest production deploy, if it has had one. */
1116 export function productionDeployState(
1117 db: Database,
1118 repoId: string,
1119 ): RunState | undefined {
1120 return db
1121 .query<{ state: RunState }, [string]>(
1122 `SELECT state FROM run WHERE repo_id = ?1 AND kind = 'deploy' AND env = 'production'
1123 ORDER BY id DESC LIMIT 1`,
1124 )
1125 .get(repoId)?.state;
1126 }
1127
1128 /**
1129 * How many agents have a running run in this repository whose lease is not
1130 * lapsed: a crashed run that never finished stops counting after `staleMs`.
1131 */
1132 export function liveAgentCount(
1133 db: Database,
1134 repoId: string,
1135 staleMs: number,
1136 now = Date.now(),
1137 ): number {
1138 return (
1139 db
1140 .query<{ n: number }, [string, string]>(
1141 `SELECT COUNT(DISTINCT actor_id) AS n FROM run
1142 WHERE repo_id = ?1 AND kind = 'agent' AND state = 'running'
1143 AND heartbeat_at IS NOT NULL AND heartbeat_at >= ?2`,
1144 )
1145 .get(repoId, new Date(now - staleMs).toISOString())?.n ?? 0
1146 );
1147 }
src/web/og/designs.ts added +113
@@ -0,0 +1,113 @@
1 /**
2 * What each social card says — plain CardInput from rows an anonymous reader
3 * may already see. The caller has checked visibility of the thing itself;
4 * this module only adds what hangs off it (blockers, checks, the agent, the
5 * crew), and never names a sealed issue.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import type { Issue } from "../../core/issues.ts";
10 import { getIssueById } from "../../core/issues.ts";
11 import { blockedOpenCount, dependenciesOf } from "../../core/dependencies.ts";
12 import type { Pull } from "../../core/pulls.ts";
13 import type { Repo } from "../../core/repos.ts";
14 import type { Run } from "../../core/runs.ts";
15 import { checkSummary, liveAgentCount, productionDeployState } from "../../core/runs.ts";
16 import { STALE_AFTER_MS } from "../../runs/lease.ts";
17 import { mayView } from "../../core/sealed.ts";
18 import { getUserById } from "../../core/users.ts";
19 import type { CardInput } from "./card.ts";
20
21 const slug = (repo: Repo): string => `${repo.ownerName}/${repo.name}`;
22 const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? "" : "s"}`;
23
24 /** "waits for #3, #7" for the open, viewable blockers; "nothing blocks it" otherwise. */
25 function blockerLine(db: Database, repo: Repo, issue: Issue): string {
26 const open = dependenciesOf(db, issue.id).blockedBy.filter(
27 (b) => b.state === "open" && mayView(db, repo, b, undefined),
28 );
29 if (!open.length) return issue.state === "open" ? "Nothing blocks it" : "";
30 const shown = open.slice(0, 4).map((b) => `#${b.number}`).join(", ");
31 return `Waits for ${shown}${open.length > 4 ? ` +${open.length - 4}` : ""}`;
32 }
33
34 export function issueCard(db: Database, repo: Repo, issue: Issue): CardInput {
35 return {
36 kind: "issue",
37 title: issue.title,
38 lines: [slug(repo), `Filed by ${issue.authorName}`, blockerLine(db, repo, issue)],
39 stat: `#${issue.number} · ${issue.state}`,
40 };
41 }
42
43 export function pullCard(db: Database, repo: Repo, pull: Pull): CardInput {
44 const merged = pull.mergedAt !== null;
45 const checks = checkSummary(db, pull.id, pull.headOid).state;
46 const verdict =
47 checks === "none" ? "No checks yet" : checks === "ok" ? "Checks passed" : `Checks ${checks}`;
48 return {
49 kind: "pull",
50 title: pull.title,
51 lines: [
52 slug(repo),
53 `${merged ? "Shipped" : "Proposed"} by ${pull.authorName} · ${pull.headBranch} → ${pull.baseBranch}`,
54 merged ? "" : verdict,
55 merged ? "" : blockerLine(db, repo, pull),
56 ].filter(Boolean),
57 stat: `#${pull.number} · ${pull.state}${merged ? " · merged" : ""}`,
58 };
59 }
60
61 export function runCard(db: Database, repo: Repo, run: Run): CardInput {
62 const who = run.actorId ? getUserById(db, run.actorId)?.username : undefined;
63 const about = run.issueId ? getIssueById(db, run.issueId) : undefined;
64 const subject =
65 about && mayView(db, repo, about, undefined) ? `#${about.number} ${about.title}` : "";
66 return {
67 kind: "run",
68 title: run.summary || `${run.kind} run`,
69 lines: [
70 slug(repo),
71 who ? `${run.kind === "agent" ? "Agent" : "By"} ${who}` : "",
72 subject ? `On ${subject}` : "",
73 ].filter(Boolean),
74 stat: `${run.kind} · ${run.state}${run.costUsd > 0 ? ` · $${run.costUsd.toFixed(2)}` : ""}`,
75 };
76 }
77
78 export function repoCard(
79 db: Database,
80 repo: Repo,
81 counts: { openIssues: number; openPulls: number } | undefined,
82 ): CardInput {
83 const issues = counts?.openIssues ?? 0;
84 const blocked = blockedOpenCount(db, repo.id);
85 return {
86 kind: "repo",
87 title: slug(repo),
88 lines: [repo.description, blocked ? `${blocked} waiting on a blocker` : ""].filter(Boolean),
89 stat: `${plural(issues, "issue")} · ${plural(counts?.openPulls ?? 0, "pull")}`,
90 };
91 }
92
93 export function appCard(
94 db: Database,
95 repo: Repo,
96 appSlug: string,
97 counts: { openIssues: number; openPulls: number } | undefined,
98 ): CardInput {
99 const live = productionDeployState(db, repo.id);
100 const crew = liveAgentCount(db, repo.id, STALE_AFTER_MS);
101 const status =
102 live === undefined ? "Not deployed yet" : live === "ok" ? "Live" : `Deploy ${live}`;
103 return {
104 kind: "app",
105 title: appSlug,
106 lines: [
107 repo.description,
108 crew ? `Crew at work: ${plural(crew, "agent")}` : "Crew idle",
109 slug(repo),
110 ].filter(Boolean),
111 stat: `${status} · ${plural(counts?.openPulls ?? 0, "open pull")}`,
112 };
113 }
src/web/pages/og.ts +5 −26
@@ -33,6 +33,7 @@ import { notFound } from "../../http/respond.ts";
3333 import { renderCard, type CardInput } from "../og/card.ts";
3434 import { Busy, pngCache, type PngCache } from "../og/png-cache.ts";
3535 import { rasterizer } from "../og/raster.ts";
36 import { appCard, issueCard, pullCard, repoCard, runCard } from "../og/designs.ts";
3637
3738 /** What an anonymous reader may see of a repository, or nothing. */
3839 function publicRepo(ctx: Ctx, repo: Repo | undefined): Repo | undefined {
@@ -40,16 +41,6 @@ function publicRepo(ctx: Ctx, repo: Repo | undefined): Repo | undefined {
4041 return canRead(ctx.app.db, repo, undefined) ? repo : undefined;
4142 }
4243
43 function repoInput(ctx: Ctx, repo: Repo, kind: "repo" | "app"): CardInput {
44 const n = countsForRepos(ctx.app.db, [repo.id]).get(repo.id);
45 return {
46 kind,
47 title: `${repo.ownerName}/${repo.name}`,
48 lines: repo.description ? [repo.description] : [],
49 stat: `${n?.openIssues ?? 0} issues · ${n?.openPulls ?? 0} pulls`,
50 };
51 }
52
5344 export type OgKind = "repo" | "app" | "issue" | "pull" | "run";
5445
5546 const RUN_ID = /^[0-9a-z]{1,40}$/;
@@ -75,13 +66,7 @@ function threadInput(ctx: Ctx, kind: OgKind, ref: string): CardInput | undefined
7566 kind === "pull" ? getPull(db, at.repo.id, n) : getIssue(db, at.repo.id, n);
7667 if (!item || item.kind !== kind || !mayView(db, at.repo, item, undefined))
7768 return undefined;
78 const merged = "mergedAt" in item && item.mergedAt !== null;
79 return {
80 kind,
81 title: item.title,
82 lines: [`${at.repo.ownerName}/${at.repo.name}`],
83 stat: `#${item.number} · ${item.state}${merged ? " · merged" : ""}`,
84 };
69 return kind === "pull" ? pullCard(db, at.repo, item as Pull) : issueCard(db, at.repo, item);
8570 }
8671
8772 function runInput(ctx: Ctx, ref: string): CardInput | undefined {
@@ -89,13 +74,7 @@ function runInput(ctx: Ctx, ref: string): CardInput | undefined {
8974 if (!at || !RUN_ID.test(at.rest)) return undefined;
9075 const found = getRepoRun(ctx.app, undefined, at.repo, at.rest);
9176 if (!found.ok) return undefined;
92 const run = found.value;
93 return {
94 kind: "run",
95 title: run.summary || `${run.kind} run`,
96 lines: [`${at.repo.ownerName}/${at.repo.name}`],
97 stat: `${run.kind} · ${run.state}`,
98 };
77 return runCard(ctx.app.db, at.repo, found.value);
9978 }
10079
10180 function resolve(ctx: Ctx, kind: OgKind, ref: string): CardInput | undefined {
@@ -107,13 +86,13 @@ function resolve(ctx: Ctx, kind: OgKind, ref: string): CardInput | undefined {
10786 if (extra !== undefined || !owner || !name) return undefined;
10887 if (!isSafeName(owner) || !isSafeName(name)) return undefined;
10988 const repo = publicRepo(ctx, getRepo(db, owner, name));
110 return repo && repoInput(ctx, repo, "repo");
89 return repo && repoCard(db, repo, countsForRepos(db, [repo.id]).get(repo.id));
11190 }
11291 if (!isSlug(ref)) return undefined;
11392 const record = getAppBySlug(db, ref);
11493 if (!record || record.access !== "public") return undefined;
11594 const repo = publicRepo(ctx, getRepoById(db, record.repoId));
116 return repo && { ...repoInput(ctx, repo, "app"), title: record.slug };
95 return repo && appCard(db, repo, record.slug, countsForRepos(db, [repo.id]).get(repo.id));
11796 }
11897
11998 const caches = new WeakMap<App, PngCache>();
test/og-route.test.ts +123 −1
@@ -6,7 +6,8 @@ import { createApp as createForge, type App } from "../src/app.ts";
66 import { getRepo } from "../src/core/repos.ts";
77 import { createRepo } from "../src/actions/repos.ts";
88 import { createApp } from "../src/core/apps.ts";
9 import { createIssue } from "../src/core/issues.ts";
9 import { createIssue, getIssue } from "../src/core/issues.ts";
10 import { addDependency } from "../src/core/dependencies.ts";
1011 import { createRun } from "../src/core/runs.ts";
1112 import { createUser } from "../src/core/users.ts";
1213 import { serve, type Servers } from "../src/http/server.ts";
@@ -19,6 +20,8 @@ describe("og cards", () => {
1920 let runId = "";
2021 let privateRunId = "";
2122 let quietRunId = "";
23 let aliceId = "";
24 let shownId = "";
2225
2326 beforeAll(async () => {
2427 dataDir = await mkdtemp(join(tmpdir(), "forge-og-"));
@@ -85,7 +88,18 @@ describe("og cards", () => {
8588 mk("hidden", "A private issue", "issue"); // #1
8689 const run = (repo: string) =>
8790 createRun(app.db, { repoId: idOf(repo).id, kind: "agent", summary: "did a thing" }).id;
91 aliceId = u.value.id;
92 shownId = idOf("shown").id;
93 const blocker = getIssue(app.db, idOf("shown").id, 1)!;
94 mk("shown", "A waiting issue", "issue"); // #5
95 const waiting = getIssue(app.db, idOf("shown").id, 5)!;
96 const dep = addDependency(app.db, waiting, blocker, u.value.id);
97 if (!dep.ok) throw new Error(String(dep.error));
8898 runId = run("shown");
99 app.db
100 .query("UPDATE run SET cost_usd = 1.5, state = 'ok', actor_id = ?2 WHERE id = ?1")
101 .run(runId, u.value.id);
102 createRun(app.db, { repoId: idOf("shown").id, kind: "deploy", env: "production" });
89103 privateRunId = run("hidden");
90104 quietRunId = run("quiet");
91105 });
@@ -213,4 +227,112 @@ describe("og cards", () => {
213227 expect((await get(`/og/${path}.svg`)).status).toBe(404);
214228 });
215229 });
230
231 describe("designs", () => {
232 const text = async (path: string) => (await get(path)).text();
233
234 test("an issue says who filed it and what it waits for", async () => {
235 expect(await text("/og/issue/alice~shown~1.svg")).toContain("Nothing blocks it");
236 expect(await text("/og/issue/alice~shown~5.svg")).toContain("Waits for #1");
237 expect(await text("/og/issue/alice~shown~1.svg")).toContain("Filed by alice");
238 });
239
240 test("a pull says its checks and who proposed or shipped it", async () => {
241 const open = await text("/og/pull/alice~shown~2.svg");
242 expect(open).toContain("No checks yet");
243 expect(open).toContain("Proposed by alice");
244 expect(await text("/og/pull/alice~shown~4.svg")).toContain("Shipped by alice");
245 });
246
247 test("a run says its agent, its cost and its outcome", async () => {
248 const card = await text(`/og/run/alice~shown~${runId}.svg`);
249 expect(card).toContain("Agent alice");
250 expect(card).toContain("$1.50");
251 expect(card).toContain("agent · ok");
252 });
253
254 test("an app says it is idle and not live before a deploy succeeds", async () => {
255 const card = await text("/og/app/shown-app.svg");
256 expect(card).toContain("Deploy queued");
257 expect(card).toContain("Crew idle");
258 expect(card).not.toContain("Live");
259 });
260
261 test("an app is Live once its production deploy is ok", async () => {
262 app.db.query("UPDATE run SET state = 'ok' WHERE repo_id = ?1 AND kind = 'deploy'").run(shownId);
263 expect(await text("/og/app/shown-app.svg")).toContain("Live ·");
264 });
265
266 test("the crew is at work only while a running agent run still beats", async () => {
267 const r = createRun(app.db, { repoId: shownId, kind: "agent", actorId: aliceId });
268 const set = (state: string, beat: string | null) =>
269 app.db.query("UPDATE run SET state = ?2, heartbeat_at = ?3 WHERE id = ?1").run(r.id, state, beat);
270 set("running", new Date().toISOString());
271 expect(await text("/og/app/shown-app.svg")).toContain("Crew at work: 1 agent");
272 set("running", new Date(Date.now() - 10 * 60_000).toISOString()); // crashed
273 expect(await text("/og/app/shown-app.svg")).toContain("Crew idle");
274 set("running", null);
275 expect(await text("/og/app/shown-app.svg")).toContain("Crew idle");
276 set("ok", new Date().toISOString());
277 expect(await text("/og/app/shown-app.svg")).toContain("Crew idle");
278 });
279
280 test("an open pull says Checks failed, then Checks passed", async () => {
281 const pull = getIssue(app.db, shownId, 2)!;
282 const check = createRun(app.db, { repoId: shownId, kind: "check", issueId: pull.id, commitOid: "" });
283 app.db.query("UPDATE run SET state = 'failed' WHERE id = ?1").run(check.id);
284 expect(await text("/og/pull/alice~shown~2.svg")).toContain("Checks failed");
285 app.db.query("UPDATE run SET state = 'ok' WHERE id = ?1").run(check.id);
286 expect(await text("/og/pull/alice~shown~2.svg")).toContain("Checks passed");
287 });
288
289 test("a merged pull drops its checks line", async () => {
290 const pull = getIssue(app.db, shownId, 4)!;
291 const check = createRun(app.db, { repoId: shownId, kind: "check", issueId: pull.id, commitOid: "" });
292 app.db.query("UPDATE run SET state = 'failed' WHERE id = ?1").run(check.id);
293 const card = await text("/og/pull/alice~shown~4.svg");
294 expect(card).toContain("Shipped by alice");
295 expect(card).not.toContain("Checks");
296 expect(card).not.toContain("Waits for");
297 });
298
299 test("a sealed blocker is never counted or named", async () => {
300 const make = (title: string, sealed: boolean) => {
301 const i = createIssue(app.db, { repoId: shownId, authorId: aliceId, title, kind: "issue", sealed });
302 if (!i.ok) throw new Error(String(i.error));
303 return i.value;
304 };
305 const before = await text("/og/repo/alice~shown.svg");
306 const sealedBlocker = make("secret blocker", true);
307 const open = make("open waiter", false);
308 const sealedWaiter = make("secret waiter", true);
309 const visible = make("visible blocker", false);
310 for (const [a, b] of [[open, sealedBlocker], [sealedWaiter, visible]] as const)
311 expect(addDependency(app.db, a, b, aliceId).ok).toBe(true);
312 expect(await text("/og/repo/alice~shown.svg")).toContain("1 waiting on a blocker");
313 expect(before).toContain("1 waiting on a blocker");
314 const card = await text(`/og/issue/alice~shown~${open.number}.svg`);
315 expect(card).not.toContain(`#${sealedBlocker.number}`);
316 expect(card).toContain("Nothing blocks it");
317 });
318
319 test("more than four blockers are summarised as +N", async () => {
320 const waiter = createIssue(app.db, { repoId: shownId, authorId: aliceId, title: "many", kind: "issue" });
321 if (!waiter.ok) throw new Error(String(waiter.error));
322 const numbers: number[] = [];
323 for (let k = 0; k < 6; k++) {
324 const b = createIssue(app.db, { repoId: shownId, authorId: aliceId, title: `b${k}`, kind: "issue" });
325 if (!b.ok) throw new Error(String(b.error));
326 numbers.push(b.value.number);
327 expect(addDependency(app.db, waiter.value, b.value, aliceId).ok).toBe(true);
328 }
329 const card = await text(`/og/issue/alice~shown~${waiter.value.number}.svg`);
330 expect(card).toContain(numbers.slice(0, 4).map((n) => `#${n}`).join(", ") + " +2");
331 expect(card).not.toContain(`#${numbers[5]}`);
332 });
333
334 test("a repo counts what waits on a blocker", async () => {
335 expect(await text("/og/repo/alice~shown.svg")).toContain("2 waiting on a blocker");
336 });
337 });
216338 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs