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

A stalled flow step is a card on the home with the one action that unblocks it, never a silent wait #1772

Closed opened this
Closed without merging

scout/forge:scout/1475-a-stalled-flow-step-is-a-card-on-the-hom → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +285 −1
scripts/gate.ts +1
@@ -45,6 +45,7 @@ export const GATE: readonly string[] = [
4545 "test/webauthn.test.ts",
4646 "test/chaos.test.ts",
4747 "test/flow-stage.test.ts",
48 "test/flow-card.test.ts",
4849 "test/cluster-jobs.test.ts",
4950 "test/fuzz-found.test.ts",
5051 "test/fuzz-parsers.test.ts",
src/http/server.ts +2
@@ -8,6 +8,7 @@
88 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
99 import { unsealReleased } from "../actions/sealed.ts";
1010 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
11 import { stalledRerun } from "../web/studio/stalled.ts";
1112 import { flowPage } from "../web/pages/flow.ts";
1213 import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts";
1314 import { boardsPage } from "../web/pages/boards.ts";
@@ -631,6 +632,7 @@ export function buildRouter(): Router<Handler> {
631632 router.add("GET", "/map", globalMapPage);
632633 // The pipeline's stages and its bottleneck, for a forge admin (#1554); literal, above /:owner.
633634 router.add("GET", "/flow", flowPage);
635 router.add("POST", "/stalled/rerun", stalledRerun);
634636 // A selection's spend and runs over time; literal, above /:owner.
635637 router.add("GET", "/fleet/graph", fleetGraphPage);
636638 router.add("GET", "/fleet/graph/live", fleetGraphLive);
src/web/studio/home.ts +2 −1
@@ -51,6 +51,7 @@ import { homeTabs } from "./home_tabs.ts";
5151 import { crewKeyNote } from "./crew.ts";
5252 import { everydayCard } from "../pages/everyday.ts";
5353 import { nextStepsCard } from "../pages/next-steps.ts";
54 import { stalledSection } from "./stalled.ts";
5455 import { spawnedOrg } from "../../spawn/claim.ts";
5556
5657 /** The events that can change what is on you. */
@@ -191,7 +192,7 @@ export async function studioHome(
191192 ${homeTabs("feed")}
192193 <div class="dash">
193194 <div class="dash-main stack">
194 ${needsYou.body} ${composer(ctx, user)}
195 ${stalledSection(ctx, user)} ${needsYou.body} ${composer(ctx, user)}
195196 <div class="bar feed-head">
196197 <span class="spacer"></span>
197198 <a class="small muted" href="/asked">What you asked for</a>
src/web/studio/stalled.ts added +146
@@ -0,0 +1,146 @@
1 /**
2 * Stalled flow steps on the home (#1475): each step of the flow (`src/flow`)
3 * that has outlived its stage's threshold is one card — the issue, its stage,
4 * how long it has been stuck, and the one thing that unblocks it. A failed
5 * check's unblock is a button that asks for the check again; every other is
6 * the words, linked to where it is done. Read from the records on each
7 * render, so a step that moves on loses its card with the next one.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { askCheck } from "../../checks/again.ts";
12 import { canWrite, getRepo, listReposVisibleTo, type Repo } from "../../core/repos.ts";
13 import { getPull } from "../../core/pulls.ts";
14 import { sealedScope } from "../../core/sealed.ts";
15 import type { User } from "../../core/users.ts";
16 import { readFlow } from "../../flow/read.ts";
17 import type { FlowStage } from "../../flow/stage.ts";
18 import type { Ctx } from "../../http/context.ts";
19 import { notFoundPage, repoBase, signInFirst } from "../chrome.ts";
20 import { field, readForm } from "../form.ts";
21 import { html, type Html } from "../html.ts";
22 import { flashTo } from "../layout.ts";
23 import { btn, card } from "../ui.ts";
24
25 /** How many repositories the home looks at, and how many of those it reads the flow of. */
26 const REPOS_LOOKED_AT = 200;
27 const REPOS_READ = 10;
28 /** The shortest stall threshold (a check's), in minutes: nothing younger can be stalled. */
29 const SHORTEST_STALL = 30;
30 /** How far back a closed issue may still be in the flow (a merge awaiting its deploy). */
31 const WINDOW_DAYS = 7;
32
33 /**
34 * Of these repositories, the ones with anything old enough to be stalled — one
35 * statement however many repositories there are, so the home pays for the
36 * flow only where there is something to say, and never more than `REPOS_READ`.
37 */
38 function oldEnough(db: Database, repos: readonly Repo[], now: Date): Repo[] {
39 if (repos.length === 0) return [];
40 const young = new Date(now.getTime() - SHORTEST_STALL * 60_000).toISOString();
41 const window = new Date(now.getTime() - WINDOW_DAYS * 86_400_000).toISOString();
42 const marks = repos.map((_, i) => `?${i + 3}`).join(",");
43 const rows = db
44 .query<{ repo_id: string }, string[]>(
45 `SELECT DISTINCT repo_id FROM issue
46 WHERE created_at < ?1 AND (state = 'open' OR closed_at >= ?2) AND repo_id IN (${marks})`,
47 )
48 .all(young, window, ...repos.map((r) => r.id));
49 const keep = new Set(rows.map((r) => r.repo_id));
50 return repos.filter((r) => keep.has(r.id));
51 }
52
53 /** A stalled step, with where it is. */
54 export interface StalledStep {
55 readonly repo: Repo;
56 readonly step: FlowStage;
57 }
58
59 /** Whether the step's one action is asking for the check at the pull's head again. */
60 export const canRerun = (s: FlowStage): boolean =>
61 s.stage === "check" && s.pull !== null && s.unblock.startsWith("re-run");
62
63 /** Every stalled step in the repositories this person writes to, longest-stuck first. */
64 export function stalledSteps(ctx: Ctx, user: User, now = new Date()): StalledStep[] {
65 const out: StalledStep[] = [];
66 const visible = listReposVisibleTo(ctx.app.db, user, { limit: REPOS_LOOKED_AT });
67 for (const repo of oldEnough(ctx.app.db, visible, now).slice(0, REPOS_READ)) {
68 if (!canWrite(ctx.app.db, repo, user)) continue;
69 const flow = readFlow(ctx.app.db, repo, {
70 now,
71 scope: sealedScope(ctx.app.db, repo, user),
72 });
73 for (const step of flow.open) if (step.stalled) out.push({ repo, step });
74 }
75 return out.sort((a, b) => (a.step.since < b.step.since ? -1 : 1));
76 }
77
78 /** "3h" / "2d" / "45m": how long, in one unit. */
79 export function stuckFor(since: string, now: Date): string {
80 const minutes = Math.max(0, Math.floor((now.getTime() - Date.parse(since)) / 60_000));
81 if (minutes < 60) return `${minutes}m`;
82 if (minutes < 48 * 60) return `${Math.floor(minutes / 60)}h`;
83 return `${Math.floor(minutes / (24 * 60))}d`;
84 }
85
86 function stalledCard({ repo, step }: StalledStep, now: Date): Html {
87 const base = repoBase(repo);
88 const where = step.pull === null ? `${base}/issues/${step.number}` : `${base}/pulls/${step.pull}`;
89 const action = canRerun(step)
90 ? html`<form method="post" action="/stalled/rerun" class="inline">
91 <input type="hidden" name="owner" value="${repo.ownerName}" />
92 <input type="hidden" name="name" value="${repo.name}" />
93 <input type="hidden" name="number" value="${String(step.pull)}" />
94 ${btn("Re-run", { size: "sm", variant: "primary" })}
95 </form>`
96 : html`<a class="small" href="${where}">${step.unblock}</a>`;
97 return html`<li
98 class="row stalled-step"
99 data-stage="${step.stage}"
100 data-issue="${repo.ownerName}/${repo.name}#${String(step.number)}"
101 >
102 <a class="truncate" href="${base}/issues/${step.number}"
103 ><span class="muted">${repo.ownerName}/${repo.name}#${String(step.number)}</span>
104 ${step.title}</a
105 >
106 <span class="spacer"></span>
107 <span class="small muted">${step.stage} · stuck ${stuckFor(step.since, now)}</span>
108 ${action}
109 </li>`;
110 }
111
112 /** The stalled steps as one card; nothing at all when nothing is stalled. */
113 export function stalledSection(ctx: Ctx, user: User, now = new Date()): Html | null {
114 const steps = stalledSteps(ctx, user, now);
115 if (steps.length === 0) return null;
116 return card(
117 html`<ul class="list" aria-label="Stalled steps">
118 ${steps.map((s) => stalledCard(s, now))}
119 </ul>`,
120 { id: "stalled", head: html`<h2>Stalled</h2>`, pad: false },
121 );
122 }
123
124 // POST /stalled/rerun — ask for the stalled pull's check again.
125 export async function stalledRerun(ctx: Ctx): Promise<Response> {
126 const user = ctx.auth.user;
127 if (!user) return signInFirst(ctx);
128 const form = await readForm(ctx, "rw");
129 if (form instanceof Response) return form;
130 const number = Number(field(form, "number"));
131 const repo = getRepo(ctx.app.db, field(form, "owner"), field(form, "name"));
132 const pull =
133 repo !== undefined && Number.isSafeInteger(number) && number > 0
134 ? getPull(ctx.app.db, repo.id, number)
135 : undefined;
136 if (repo === undefined || pull === undefined || !canWrite(ctx.app.db, repo, user))
137 return notFoundPage(ctx);
138 const asked = await askCheck(ctx.app, user, repo, pull);
139 return flashTo(
140 ctx,
141 "/",
142 asked.ok
143 ? { message: `Check asked for on pull #${pull.number}.` }
144 : { tone: "danger", message: `No check was asked for: ${asked.message}.` },
145 );
146 }
test/flow-card.test.ts added +134
@@ -0,0 +1,134 @@
1 /**
2 * A stalled flow step is a card on the home with the one action that
3 * unblocks it (#1475): a failed check shows "Re-run", and once the check is
4 * asked for again the card is gone.
5 */
6 import { afterAll, beforeAll, describe, 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 { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { openPull } from "../src/actions/pulls.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createIssue } from "../src/core/issues.ts";
15 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { stuckFor } from "../src/web/studio/stalled.ts";
19
20 let dir: string;
21 let app: App;
22 let servers: Servers;
23 let cookie: string;
24 let alice: User;
25 let pr: { id: string; number: number; headOid: string };
26
27 const home = async () => (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
28 const cards = (page: string) => page.split('class="row stalled-step"').length - 1;
29
30 beforeAll(async () => {
31 dir = await mkdtemp(join(tmpdir(), "forge-flow-card-"));
32 app = createApp({ dataDir: dir, port: 0 });
33 servers = await serve(app);
34 const u = await createUser(app.db, {
35 trusted: true,
36 username: "alice",
37 email: "[email protected]",
38 password: "a-good-passphrase",
39 adminIfFirst: true,
40 });
41 if (!u.ok) throw new Error(u.error);
42 alice = u.value;
43 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
44 const made = await createRepo(app, alice, { name: "e", visibility: "private" });
45 if (!made.ok) throw new Error(String(made.error));
46 const repo = made.value;
47 await commitToBranch(app, alice, repo, {
48 message: "Start",
49 files: [{ path: "README.md", content: "# e\n" }],
50 });
51 const issue = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title: "Fix <b>it</b>" });
52 if (!issue.ok) throw new Error(String(issue.error));
53 await commitToBranch(app, alice, repo, {
54 branch: "feature/x",
55 base: "main",
56 message: "x",
57 files: [{ path: "x.txt", content: "x\n" }],
58 });
59 const opened = await openPull(app, alice, repo, {
60 title: "x",
61 body: `Closes #${issue.value.number}`,
62 baseBranch: "main",
63 headBranch: "feature/x",
64 });
65 if (!opened.ok) throw new Error(String(opened.error));
66 pr = opened.value;
67 // A check that failed two hours ago: past the 30 minutes a check may take.
68 const run = createRun(app.db, { repoId: repo.id, kind: "check", issueId: pr.id, commitOid: pr.headOid });
69 claimRun(app.db, run.id);
70 finishRun(app.db, run.id, { state: "failed", summary: "" });
71 const then = new Date(Date.now() - 2 * 3600_000).toISOString();
72 app.db.query("UPDATE run SET finished_at = ?2 WHERE id = ?1").run(run.id, then);
73 // The issue and pull are as old as the failure they carry.
74 app.db.query("UPDATE issue SET created_at = ?1").run(new Date(Date.now() - 3 * 3600_000).toISOString());
75 });
76
77 afterAll(async () => {
78 servers.stop();
79 app.close();
80 await rm(dir, { recursive: true, force: true });
81 });
82
83 describe("a stalled step on the home", () => {
84 test("a stalled check is a card with Re-run, escaped, and the card goes once it is re-run", async () => {
85 const before = await home();
86 expect(cards(before)).toBe(1);
87 expect(before).toContain('data-stage="check"');
88 expect(before).toContain("stuck 2h");
89 expect(before).toContain("Re-run");
90 expect(before).toContain('action="/stalled/rerun"');
91 expect(before).toContain("Fix &lt;b&gt;it&lt;/b&gt;");
92 expect(before).not.toContain("Fix <b>it</b>");
93
94 // What asking for the check again does: a new run at the same head.
95 createRun(app.db, {
96 repoId: app.db.query<{ repo_id: string }, [string]>("SELECT repo_id FROM issue WHERE id = ?1").get(pr.id)!.repo_id,
97 kind: "check",
98 issueId: pr.id,
99 commitOid: pr.headOid,
100 reason: "asked",
101 });
102 expect(cards(await home())).toBe(0);
103 });
104
105 test("the re-run is a same-origin, signed-in write", async () => {
106 const form = new URLSearchParams({ owner: "alice", name: "e", number: String(pr.number) });
107 const post = (headers: Record<string, string>) =>
108 fetch(`${servers.url}/stalled/rerun`, {
109 method: "POST",
110 redirect: "manual",
111 headers: { "content-type": "application/x-www-form-urlencoded", ...headers },
112 body: form,
113 });
114 expect((await post({ cookie, origin: "https://evil.example" })).status).toBe(403);
115 const anon = await post({ origin: servers.url });
116 expect(anon.headers.get("location") ?? "").toContain("/signin");
117 const ok = await post({ cookie, origin: servers.url });
118 expect(ok.status).toBe(303);
119 const missing = await fetch(`${servers.url}/stalled/rerun`, {
120 method: "POST",
121 redirect: "manual",
122 headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
123 body: new URLSearchParams({ owner: "alice", name: "e", number: "999" }),
124 });
125 expect(missing.status).toBe(404);
126 });
127
128 test("how long is said in one unit", () => {
129 const now = new Date("2026-10-15T12:00:00Z");
130 expect(stuckFor("2026-10-15T11:15:00Z", now)).toBe("45m");
131 expect(stuckFor("2026-10-15T09:00:00Z", now)).toBe("3h");
132 expect(stuckFor("2026-10-10T12:00:00Z", now)).toBe("5d");
133 });
134 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs