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

A stalled flow step shows the one action that unblocks it on its card #14130

Merged opened this

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

Merged

scout/forge:scout/14086-a-stalled-flow-step-shows-the-one-action → main 7 commits fork 3 threads · 3 unresolved

  • Merged. scout/14086-a-stalled-flow-step-shows-the-one-action was merged into main as e039e6f.

Review

Sign in to review this change.
8 files changed +326 −42
docs/features/flow-waiting.md +4
@@ -11,3 +11,7 @@ Terminal: the palette entry "Pulls to land" (`src/tui/screens/waiting.ts`, for a
1111 Cost: the unproposed-work scan reads git for every crew fork, so `readWaiting` holds its result for 60 seconds per process; the other two sections are plain queries and are read each time. Stale pulls carry their repository, so two repositories with the same pull number and branch stay apart.
1212
1313 Code: `src/web/pages/flow-waiting.ts` (reads and draws), mounted by one line in `src/web/pages/flow.ts`. Test: `test/flow-waiting.test.ts`.
14
15 ## The one action (#14086)
16
17 Each stalled row carries one form button, never a silent wait: an approved pull waiting gets **Re-run check** (`POST /:owner/:name/pulls/:n/checks`, the oldest one), a stale crew pull gets **Close** (`POST …/pulls/:n/state`), and a crew branch that heads no pull gets **Open a pull**, a plain link to the compose page with the branch filled in. Each button's accessible name carries the repository and pull number, and a row for someone who cannot write to its repository shows a muted line instead. Both posts are same-origin only, need write access to the repository, and come back to `/flow` with the route's own receipt sentence. In the terminal, `n`/`p` pick a row and `enter` does its action (ask a check, close, or open the new-pull screen on that branch), through the same functions and write gate; a row the person cannot write to names no action.
src/tui/screens/newpull.ts +2 −2
@@ -21,12 +21,12 @@ import { local } from "./where.ts";
2121
2222 type Focus = 0 | 1 | 2 | 3 | 4;
2323
24 export function newPullScreen(f: Session, ctx: Ctx, head: Repo): Screen {
24 export function newPullScreen(f: Session, ctx: Ctx, head: Repo, from?: string): Screen {
2525 // A parent this person may no longer read is not offered (#831).
2626 const parent = forkParentFor(f.db, head, f.user);
2727 let base: Repo = parent ?? head;
2828 let baseBranch = base.defaultBranch;
29 let headBranch = head.defaultBranch;
29 let headBranch = from ?? head.defaultBranch;
3030 let title = "";
3131 const body = new Textarea("");
3232 let focus: Focus = 0;
src/tui/screens/waiting.ts +87 −18
@@ -2,12 +2,21 @@
22 * /flow's waiting section in the terminal (#11455): the web page's three
33 * lists, read by the same `readWaiting`, gated the same way: a forge admin who
44 * is a person; anyone else is offered nothing and, were the screen reached,
5 * sees no rows. A section with nothing to say draws nothing. Read-only.
5 * sees no rows. A section with nothing to say draws nothing. `n`/`p` pick a row and
6 * `enter` does its one action (re-run its check, close, open its pull), through the
7 * functions the page's routes call, for someone who can write to that repository.
68 */
79
810 import { readWaiting, type Waiting } from "../../web/pages/flow-waiting.ts";
911 import type { Ctx, Screen } from "../app/app.ts";
1012 import { binding } from "../app/keys.ts";
13 import { askCheck } from "../../checks/again.ts";
14 import { setIssueStateThrough } from "../../actions/issues.ts";
15 import { getIssue } from "../../core/issues.ts";
16 import { getPull } from "../../core/pulls.ts";
17 import { canWrite, getRepo } from "../../core/repos.ts";
18 import { errorText, runAsync } from "./common.ts";
19 import { newPullScreen } from "./newpull.ts";
1120 import type { Session } from "../session.ts";
1221 import { style } from "../term/style.ts";
1322 import { Scroll, drawLines, hitScroll } from "./common.ts";
@@ -17,48 +26,108 @@ const mayRead = (session: Session): boolean => session.user?.isAdmin === true &&
1726 const hours = (h: number): string => (h >= 48 ? `${String(Math.floor(h / 24))} d` : `${String(h)} h`);
1827 const plural = (n: number, one: string): string => `${String(n)} ${n === 1 ? one : `${one}s`}`;
1928
20 /** The sections as text lines, headings first; empty for anyone the gate refuses or when all three are quiet. */
21 export function waitingLines(session: Session, w: Waiting): string[] {
29 type Act = { kind: "check" | "close" | "open"; repo: string; number: number; branch?: string };
30 type Entry = { text: string; act?: Act };
31
outdated

Both doors: this only names the action in text. Add a key that performs it in the terminal, with the same write gate as the page. The same applies to the stale and unproposed rows below.

32 /**
33 * The sections as entries, headings first; a row the viewer can write to carries its one action.
34 */
35 function entries(session: Session, w: Waiting): Entry[] {
2236 if (!mayRead(session)) return [];
23 const out: string[] = [];
24 const section = (title: string, rows: string[]) => {
25 if (rows.length === 0) return;
26 if (out.length > 0) out.push("");
27 out.push(title, ...rows);
37 const writes = (name: string): boolean => {
38 const [o, n] = name.split("/");
39 const r = o === undefined || n === undefined ? undefined : getRepo(session.db, o, n);
40 return r !== undefined && canWrite(session.db, r, session.user);
2841 };
42 const out: Entry[] = [];
43 const section = (title: string, rows: Entry[]) => {
44 if (rows.length === 0) return;
45 if (out.length > 0) out.push({ text: "" });
46 out.push({ text: title }, ...rows);
47 };
48 const say = (repo: string, text: string, said: string, act: Act): Entry => (writes(repo) ? { text: `${text}; action: ${said}`, act } : { text });
2949 section(
3050 "Approved, waiting on the merge queue",
31 w.approved.map((a) => ` ${a.repo}: ${plural(a.waiting, "approved pull")} waiting; the oldest, #${String(a.oldest)}, for ${hours(a.oldestHours)}`),
51 w.approved.map((a) => say(a.repo, ` ${a.repo}: ${plural(a.waiting, "approved pull")} waiting; the oldest, #${String(a.oldest)}, for ${hours(a.oldestHours)}`, `re-run check on #${String(a.oldest)}`, { kind: "check", repo: a.repo, number: a.oldest })),
3252 );
3353 section(
3454 "Stale crew pulls",
3555 w.stale.flatMap((s) => [
36 ` ${s.repo} #${String(s.number)}: ${plural(s.days, "day")} without a push; a person closes it`,
37 s.note === null ? " No issue to fold back into." : ` Fold back into #${String(s.issueNumber)}: ${s.note}`,
56 say(s.repo, ` ${s.repo} #${String(s.number)}: ${plural(s.days, "day")} without a push; a person closes it`, "close", { kind: "close", repo: s.repo, number: s.number }),
57 { text: s.note === null ? " No issue to fold back into." : ` Fold back into #${String(s.issueNumber)}: ${s.note}` },
3858 ]),
3959 );
4060 section(
4161 "Work a crew fork never proposed",
42 w.unproposed.branches.map((b) => ` ${b.repo}: ${b.branch}, ${hours(Math.floor(b.ageMs / 3_600_000))} old, no pull`),
62 w.unproposed.branches.map((b) => say(b.repo, ` ${b.repo}: ${b.branch}, ${hours(Math.floor(b.ageMs / 3_600_000))} old, no pull`, "open its pull", { kind: "open", repo: b.repo, number: 0, branch: b.branch })),
4363 );
4464 return out;
4565 }
4666
4767 export function waitingScreen(session: Session, ctx: Ctx, w: Waiting): Screen {
4868 const scroll = new Scroll();
49 const lines = waitingLines(session, w);
50 const all = lines.length === 0 ? ["Nothing waiting."] : lines;
69 const all = entries(session, w);
70 const rows: Entry[] = all.length === 0 ? [{ text: "Nothing waiting." }] : all;
71 const actions = rows.flatMap((e, i) => (e.act === undefined ? [] : [i]));
72 let at = 0; // index into `actions`
73 const picked = (): number | undefined => actions[at];
74
75 /**
76 * Runs the selected row's action through the same function, and so the same gate, the page's
77 * route calls.
78 */
79 const run = (act: Act): void => {
80 const [o, n] = act.repo.split("/");
81 const repo = o === undefined || n === undefined ? undefined : getRepo(session.db, o, n);
82 if (repo === undefined || session.user === undefined || !canWrite(session.db, repo, session.user)) {
83 ctx.toast("only someone who can write to this repository can do this", "danger");
84 return;
85 }
86 const user = session.user;
87 if (act.kind === "open") {
88 ctx.push(newPullScreen(session, ctx, repo, act.branch));
89 return;
90 }
91 runAsync(ctx, async () => {
92 const row = getPull(session.db, repo.id, act.number);
93 if (row === undefined) return void ctx.toast("that pull is not here any more", "danger");
94 if (act.kind === "check") {
95 const asked = await askCheck(session.app, user, repo, row);
96 ctx.toast(asked.ok ? "check asked for at the current head" : `no check was asked for: ${asked.message}`, asked.ok ? "success" : "danger");
97 return;
98 }
99 const issue = getIssue(session.db, repo.id, act.number);
100 if (issue === undefined) return;
101 const changed = await setIssueStateThrough(session.app, user, repo, issue, "closed");
102 ctx.toast(changed.ok ? `closed #${String(act.number)}` : errorText(changed.error), changed.ok ? "success" : "danger");
103 });
104 };
105
51106 return {
52107 title: "Pulls to land",
53 keys: [binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")],
108 keys: [binding(["j", "k"], "scroll"), ...(actions.length > 0 ? [binding(["n", "p"], "pick a row"), binding(["enter"], "do its action")] : []), binding(["esc", "q"], "back")],
54109 render(area, s) {
55110 const c = ctx.theme.c;
56 const spans = all.map((text) => [{ text, style: style(text.startsWith(" ") || text === "Nothing waiting." ? c.mutedFg : c.fg, c.bg) }]);
111 const spans = rows.map((e, i) => {
112 const here = i === picked();
113 const text = e.act === undefined ? e.text : `${here ? ">" : " "}${e.text.slice(1)}`;
114 return [{ text, style: style(here ? c.fg : e.text.startsWith(" ") || e.text === "Nothing waiting." ? c.mutedFg : c.fg, c.bg) }];
115 });
57116 drawLines(s, area, c, scroll, spans);
58 hitScroll(ctx, area, scroll, all.length);
117 hitScroll(ctx, area, scroll, rows.length);
59118 },
60119 key(e) {
61 if (scroll.key(e, all.length)) return true;
120 if (scroll.key(e, rows.length)) return true;
121 if (e.key === "n" || e.key === "p") {
122 if (actions.length > 0) at = (at + (e.key === "n" ? 1 : actions.length - 1)) % actions.length;
123 return true;
124 }
125 if (e.key === "enter") {
126 const i = picked();
127 const act = i === undefined ? undefined : rows[i]?.act;
128 if (act !== undefined) run(act);
129 return true;
130 }
62131 if (e.key === "esc" || e.key === "q") {
63132 ctx.pop();
64133 return true;
src/web/pages/flow-waiting.ts +21 −5
@@ -12,7 +12,7 @@ import { alarmUnproposed, type UnproposedAlarm } from "../../flow/alarm_unpropos
1212 import { readWaitingRows, type Waiting } from "../../flow/waiting_rows.ts";
1313 export type { Waiting } from "../../flow/waiting_rows.ts";
1414 import { html, type Html } from "../html.ts";
15 import { row } from "../ui.ts";
15 import { btn, row } from "../ui.ts";
1616 import { span } from "../../flow/pipeline.ts";
1717
1818
@@ -47,28 +47,44 @@ const waitingList = (id: string, name: string, says: string, rows: readonly Html
4747 <ul class="list" id="${id}">${[...rows]}</ul>
4848 </section>`;
4949
50 /** The section; empty html when all three are quiet. */
51 export function waitingSection(w: Waiting): Html {
50 /**
51 * The one action of a stalled row: a form button, a POST on this origin that the route receipts,
52 * named for its row so a reader of buttons hears which one it is.
53 */
outdated

The helper builds a GET form for 'Open a pull'. Navigation should be an <a> (DESIGN.md). Also add an accessible name that is distinct per row (repo and number), since the buttons otherwise read identically.

54 const act = (action: string, label: string, name: string, fields: Readonly<Record<string, string>>): Html =>
55 html`<form method="post" action="${action}" class="bar">${Object.entries(fields).map(([k, v]) => html`<input type="hidden" name="${k}" value="${v}">`)}${btn(label, { size: "sm", label: name })}</form>`;
56
57 /** What a row shows someone who cannot write to its repository: no button that would be refused. */
58 const noWrite = html`<span class="valve-body muted small">You cannot write to this repository.</span>`;
59
60 /**
61 * The section; empty html when all three are quiet. `mayWrite` says whether the viewer can act on a
62 * repository.
63 */
64 export function waitingSection(w: Waiting, mayWrite: (repo: string) => boolean = () => true): Html {
5265 const parts: Html[] = [];
5366 if (w.approved.length > 0) {
5467 parts.push(waitingList("flow-approved", "Approved, waiting on the merge queue", "Reviewed and approved; the queue has not landed them yet.", w.approved.map((a) => row({
5568 title: html`<span class="valve-name"><a href="/${a.repo}/pulls/${String(a.oldest)}">${a.repo}</a>
5669 <span class="muted small">${plural(a.waiting, "approved pull")} waiting; the oldest, #${String(a.oldest)}, for ${span(a.oldestHours * 3_600_000)}</span></span>`,
70 meta: mayWrite(a.repo) ? act(`/${a.repo}/pulls/${String(a.oldest)}/checks`, `Re-run check #${String(a.oldest)}`, `Re-run check ${a.repo} #${String(a.oldest)}`, { next: "/flow" }) : noWrite,
5771 }))));
5872 }
5973 if (w.stale.length > 0) {
6074 parts.push(waitingList("flow-stale", "Stale crew pulls", "Open with no push for days; a person closes one, and its work can fold back into its issue.", w.stale.map((s) => row({
6175 title: html`<span class="valve-name"><a href="/${s.repo}/pulls/${String(s.number)}">${s.repo} #${String(s.number)}</a>
6276 <span class="muted small">${plural(s.days, "day")} without a push; a person closes it</span></span>`,
63 meta: s.note === null
77 meta: html`${s.note === null
6478 ? html`<span class="valve-body muted small">No issue to fold back into.</span>`
65 : html`<span class="valve-body small"><a href="/${s.repo}/issues/${String(s.issueNumber)}">Fold back into #${String(s.issueNumber)}</a>: <code>${s.note}</code></span>`,
79 : html`<span class="valve-body small"><a href="/${s.repo}/issues/${String(s.issueNumber)}">Fold back into #${String(s.issueNumber)}</a>: <code>${s.note}</code></span>`}
80 ${mayWrite(s.repo) ? act(`/${s.repo}/pulls/${String(s.number)}/state`, "Close", `Close ${s.repo} #${String(s.number)}`, { state: "closed", back: "/flow" }) : noWrite}`,
6681 }))));
6782 }
6883 if (w.unproposed.fires) {
6984 parts.push(waitingList("flow-unproposed", "Work a crew fork never proposed", "Branches with commits and no pull: work that was done and never offered.", w.unproposed.branches.map((b) => row({
7085 title: html`<span class="valve-name"><a class="mono" href="/${b.repo}/tree/${encodeURIComponent(b.branch)}">${b.repo}: ${b.branch}</a>
7186 <span class="muted small">${span(b.ageMs)} old, no pull</span></span>`,
87 meta: mayWrite(b.repo) ? btn("Open a pull", { href: `/${b.repo}/pulls/new?head=${encodeURIComponent(b.branch)}`, size: "sm", label: `Open a pull from ${b.repo}: ${b.branch}` }) : noWrite,
7288 }))));
7389 }
7490 return parts.length === 0 ? html`` : html`<div class="bd-live" id="flow-waiting">${parts}</div>`;
src/web/pages/flow.ts +9 −1
@@ -25,6 +25,7 @@ import { flashTo, page } from "../layout.ts";
2525 import { btn, icon, row, time } from "../ui.ts";
2626 import { handoverSection } from "./flow-handover.ts";
2727 import { waitingSection } from "./flow-waiting.ts";
28 import { canWrite, getRepo } from "../../core/repos.ts";
2829 import { estimatesSection } from "./flow-estimates.ts";
2930 import { clogSection } from "./flow-clog.ts";
3031 import { cpuStopsSection } from "./flow-cpu.ts";
@@ -119,6 +120,13 @@ function heldRows(held: readonly Held[]) {
119120 return html`<ul class="list mb" data-planner-held>${held.map((h) => row({ lead: icon("alert"), title: html`${h.repo}: ${h.cause}`, href: `/${h.repo}/queue`, nav: true }))}</ul>`;
120121 }
121122
123 /** Whether the viewer can write to `owner/name`: the gate the action's own route holds. */
124 function mayWriteRepo(ctx: Ctx, name: string): boolean {
125 const [owner, repo] = name.split("/");
126 const found = owner === undefined || repo === undefined ? undefined : getRepo(ctx.app.db, owner, repo);
127 return found !== undefined && canWrite(ctx.app.db, found, ctx.auth.user);
128 }
129
122130 // GET /flow
123131 export async function flowPage(ctx: Ctx): Promise<Response> {
124132 const waiting = ctx.url.search === "?wait=1";
@@ -163,7 +171,7 @@ export async function flowPage(ctx: Ctx): Promise<Response> {
163171 ${cpuStopsSection(cpuStops(ctx.app.db).stopped, picture.cpuClosed)}
164172 </section>
165173 ${p.valves.length === 0 ? null : strip}
166 ${waitingSection({ approved: picture.approved, stale: picture.stale, unproposed: picture.unproposed ?? { fires: false, says: "", branches: [] } })}
174 ${waitingSection({ approved: picture.approved, stale: picture.stale, unproposed: picture.unproposed ?? { fires: false, says: "", branches: [] } }, (name) => mayWriteRepo(ctx, name))}
167175 ${p.valves.length === 0
168176 ? null
169177 : html`<section class="pipes-block" aria-label="Where the week's money went">${pipesSvg(p)}</section>
src/web/pages/pull.ts +3 −3
@@ -1569,9 +1569,9 @@ export async function pullChecksSubmit(ctx: Ctx): Promise<Response> {
15691569 return forbiddenPage(ctx, "Only someone who can write to this repository can do this.");
15701570 const form = await readForm(ctx, "rw");
15711571 if (form instanceof Response) return form;
1572 // The home's card asks to come back to the home (only "/" is honoured).
1573 const dest =
1574 field(form, "next") === "/" ? "/" : `${repoBase(found.repo)}/pulls/${found.pull.number}`;
1572 // The home's card asks to come back to the home, /flow's to /flow (only those two are honoured).
1573 const next = field(form, "next");
1574 const dest = next === "/" || next === "/flow" ? next : `${repoBase(found.repo)}/pulls/${found.pull.number}`;
15751575 const asked = await askCheck(ctx.app, ctx.auth.user, found.repo, found.pull);

New behaviour (next=/flow is honoured) with no test that would fail without it. Add a post to /checks with next=/flow that expects a redirect to /flow.

15761576 return flashTo(
15771577 ctx,
test/flow-stall-action.test.ts added +126
@@ -0,0 +1,126 @@
1 /** A stalled step on /flow's waiting section carries its one action as a form button (#14086). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { createUser } from "../src/core/users.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { id } from "../src/kernel/id.ts";
11 import type { UnproposedAlarm } from "../src/flow/alarm_unproposed.ts";
12 import { waitingSection } from "../src/web/pages/flow-waiting.ts";
13
14 const NONE: UnproposedAlarm = { fires: false, says: "", branches: [] };
15 const approved = { repo: "alice/app", waiting: 2, oldestHours: 30, oldest: 7 };
16 const stale = { repo: "alice/app", number: 9, issueNumber: 3, branch: "b", lastPushAt: "", approved: false, days: 9, note: "n" };
17
18 test("an approved pull waiting offers one re-run, a post to its checks coming back to /flow", () => {
19 const out = String(waitingSection({ approved: [approved], stale: [], unproposed: NONE }));
20 expect(out).toContain('method="post" action="/alice/app/pulls/7/checks"');
21 expect(out).toContain('name="next" value="/flow"');
22 expect(out).toContain("Re-run check #7");
23 expect(out).toContain('aria-label="Re-run check alice/app #7"');
24 });
25
26 test("a stale pull offers one close, a post to its state coming back to /flow", () => {
27 const out = String(waitingSection({ approved: [], stale: [stale], unproposed: NONE }));
28 expect(out).toContain('method="post" action="/alice/app/pulls/9/state"');
29 expect(out).toContain('name="state" value="closed"');
30 expect(out).toContain('name="back" value="/flow"');
31 expect(out.match(/<form/g)?.length).toBe(1);
32 expect(out).toContain('aria-label="Close alice/app #9"');
33 });
34
35 test("a branch nobody proposed offers one ask to open its pull, naming the branch", () => {
36 const unproposed: UnproposedAlarm = { fires: true, says: "", branches: [{ repo: "bot/app", branch: "lonely", ageMs: 1, owner: "bot", oid: "abc" }] };
37 const out = String(waitingSection({ approved: [], stale: [], unproposed }));
38 expect(out).toContain('href="/bot/app/pulls/new?head=lonely"');
39 expect(out).toContain('aria-label="Open a pull from bot/app: lonely"');
40 expect(out).not.toContain("<form");
41 });
42
43 test("someone who cannot write sees a plain line, not a button", () => {
44 const unproposed: UnproposedAlarm = { fires: true, says: "", branches: [{ repo: "bot/app", branch: "lonely", ageMs: 1, owner: "bot", oid: "abc" }] };
45 const out = String(waitingSection({ approved: [approved], stale: [stale], unproposed }, () => false));
46 expect(out).not.toContain("<form");
47 expect(out).not.toContain("<button");
48 expect(out).not.toContain("pulls/new");
49 expect(out).toContain("You cannot write to this repository.");
50 });
51
52 let dataDir: string;
53 let app: App;
54 let servers: Servers;
55 let cookie = "";
56 let repoId = "";
57 let botId = "";
58
59 beforeAll(async () => {
60 dataDir = await mkdtemp(join(tmpdir(), "forge-stall-"));
61 app = createApp({ dataDir, port: 0 });
62 servers = await serve(app);
63 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
64 if (!r.ok) throw new Error(JSON.stringify(r.error));
65 return r.value;
66 };
67 const alice = must(await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }));
68 botId = must(await createUser(app.db, { origin: "seed", trusted: true, username: "bot", email: "[email protected]", agent: true })).id;
69 repoId = must(await createRepo(app, alice, { name: "app", visibility: "public" })).id;
70 const res = await fetch(`${servers.url}/signin`, {
71 method: "POST",
72 redirect: "manual",
73 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
74 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
75 });
76 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
77 }, 60_000);
78
79 afterAll(async () => {
80 servers.stop();
81 app.close();
82 await rm(dataDir, { recursive: true, force: true });
83 });
84
85 const post = (path: string, origin: string) =>
86 fetch(`${servers.url}${path}`, {
87 method: "POST",
88 redirect: "manual",
89 headers: { "content-type": "application/x-www-form-urlencoded", cookie, origin },
90 body: new URLSearchParams({ state: "closed", back: "/flow" }),
91 });
92
93 test("the page's close button closes the stale pull and lands back on /flow; from another origin it does nothing", async () => {
94 const issueId = id();
95 const old = new Date(Date.now() - 9 * 86_400_000).toISOString();
96 app.db.query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at) VALUES (?1, ?2, 55, 'pull', 'P', 'Closes #7', ?3, 'open', ?4)`).run(issueId, repoId, botId, old);
97 app.db.query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', 'old', '', 'o', ?2)`).run(issueId, repoId);
98 const page = await (await fetch(`${servers.url}/flow`, { headers: { cookie } })).text();
99 expect(page).toContain('action="/alice/app/pulls/55/state"');
100 const state = () => app.db.query<{ state: string }, [string]>("SELECT state FROM issue WHERE id = ?1").get(issueId)?.state;
101 const elsewhere = await post("/alice/app/pulls/55/state", "https://evil.example");
102 expect(elsewhere.status).toBe(403);
103 expect(state()).toBe("open");
104 const res = await post("/alice/app/pulls/55/state", servers.url);
105 expect(res.status).toBe(303);
106 expect(new URL(res.headers.get("location") ?? "", servers.url).pathname).toBe("/flow");
107 expect(state()).toBe("closed");
108 });
109
110 test("a check asked from /flow with next=/flow comes back to /flow; any other next goes to the pull", async () => {
111 const issueId = id();
112 app.db.query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at) VALUES (?1, ?2, 56, 'pull', 'P', '', ?3, 'open', ?4)`).run(issueId, repoId, botId, new Date().toISOString());
113 app.db.query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', 'x', '', 'o', ?2)`).run(issueId, repoId);
114 const ask = (next: string) =>
115 fetch(`${servers.url}/alice/app/pulls/56/checks`, {
116 method: "POST",
117 redirect: "manual",
118 headers: { "content-type": "application/x-www-form-urlencoded", cookie, origin: servers.url },
119 body: new URLSearchParams({ next }),
120 });
121 const flow = await ask("/flow");
122 expect(flow.status).toBe(303);
123 expect(new URL(flow.headers.get("location") ?? "", servers.url).pathname).toBe("/flow");
124 const other = await ask("https://evil.example/");
125 expect(new URL(other.headers.get("location") ?? "", servers.url).pathname).toBe("/alice/app/pulls/56");
126 });
test/flow-waiting.test.ts +74 −13
@@ -6,13 +6,16 @@ import { join } from "node:path";
66 import { createRepo, forkRepo } from "../src/actions/repos.ts";
77 import { createApp, type App } from "../src/app.ts";
88 import { createUser, type User } from "../src/core/users.ts";
9 import type { Repo } from "../src/core/repos.ts";
9 import { createRepo as createCoreRepo, type Repo } from "../src/core/repos.ts";
1010 import { serve, type Servers } from "../src/http/server.ts";
1111 import { id } from "../src/kernel/id.ts";
1212 import { repoDir } from "../src/git/repos.ts";
1313 import { forgetUnproposed, readWaiting } from "../src/web/pages/flow-waiting.ts";
14 import { waitingLines } from "../src/tui/screens/waiting.ts";
15 import type { Session } from "../src/tui/session.ts";
14 import { waitingScreen } from "../src/tui/screens/waiting.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { settleApp } from "./helpers/tui.ts";
18 import { PACKS_OWNER } from "../src/packs/owner.ts";
1619
1720 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
1821 if (!r.ok) throw new Error(JSON.stringify(r.error));
@@ -181,15 +184,73 @@ test("a non-admin, a guest and a crew member get no waiting card on the page", a
181184 }
182185 });
183186
187 /** The waiting screen in a headless terminal, as `user`. */
188 const terminal = async (user: User) => {
189 const term = headlessTerminal(160, 60);
190 const { app: tui, session } = createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, { terminal: term, exitHooks: false });
191 tui.start();
192 tui.ctx.push(waitingScreen(session, tui.ctx, await readWaiting(app.db, app.reposRoot, new Date())));
193 await settleApp(tui);
194 return {
195 text: () => tui.screen.toText(),
196 feed: async (k: string) => {
197 term.feed(k);
198 await settleApp(tui);
199 },
200 stop: () => tui.stop?.(),
201 };
202 };
203 const state = (num: number): string | undefined =>
204 app.db.query<{ state: string }, [string, number]>("SELECT state FROM issue WHERE repo_id = ?1 AND number = ?2").get(repoId, num)?.state;
205
184206 test("the terminal lists the three sections for an admin only", async () => {
185 const w = await readWaiting(app.db, app.reposRoot, new Date());
186 const as = (user: User | undefined) => ({ user }) as unknown as Session;
187 const lines = waitingLines(as(alice), w);
188 expect(lines).toContain("Approved, waiting on the merge queue");
189 expect(lines).toContain("Stale crew pulls");
190 expect(waitingLines(as(bot), w)).toEqual([]);
191 expect(waitingLines(as(undefined), w)).toEqual([]);
192 const bob = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'bob'").get();
193 expect(bob).not.toBeNull();
194 expect(waitingLines({ user: { ...alice, isAdmin: false } } as unknown as Session, w)).toEqual([]);
207 const a = await terminal(alice);
208 expect(a.text()).toContain("Approved, waiting on the merge queue");
209 expect(a.text()).toContain("Stale crew pulls");
210 expect(a.text()).toContain("action: ");
211 a.stop();
212 for (const u of [bot, { ...alice, isAdmin: false }]) {
213 const t = await terminal(u);
214 expect(t.text()).toContain("Nothing waiting.");
215 expect(t.text()).not.toContain("Stale crew pulls");
216 t.stop();
217 }
218 });
219
220 test("in the terminal a writer picks a stale row with n and closes its pull with enter", async () => {
221 const stale = pull(botId, "Closes #7", ago(24 * 9), repoId, 960);
222 const t = await terminal(alice);
223 const picked = () => t.text().split("\n").some((l) => l.includes(`> alice/app #${String(stale.number)}:`));
224 for (let i = 0; i < 20 && !picked(); i++) await t.feed("n");
225 expect(picked()).toBe(true);
226 expect(state(stale.number)).toBe("open");
227 await t.feed("\r");
228 expect(state(stale.number)).toBe("closed");
229 t.stop();
230 });
231
232 test("a row on a repository the viewer cannot write has no action, in the terminal and on the page", async () => {
233 // A forge admin writes everywhere but a packs mirror, which only its owner moves (#10530).
234 const packs = must(await createUser(app.db, { origin: "seed", trusted: true, allowReserved: true, username: PACKS_OWNER, email: "[email protected]" }));
235 const made = await createCoreRepo(app.db, app.reposRoot, { ownerId: packs.id, name: "mirror", visibility: "public", description: "", defaultBranch: "main" });
236 if (!made.ok) throw new Error(made.error);
237 const mirror = made.value;
238 const stale = pull(botId, "Closes #7", ago(24 * 9), mirror.id, 961);
239 const row = `${PACKS_OWNER}/mirror #${String(stale.number)}:`;
240 const t = await terminal(alice);
241 const line = t.text().split("\n").find((l) => l.includes(row));
242 expect(line).toBeDefined();
243 expect(line).not.toContain("action: ");
244 for (let i = 0; i < 20; i++) {
245 await t.feed("n");
246 expect(t.text()).not.toContain(`> ${row}`);
247 }
248 expect(app.db.query<{ state: string }, [string]>("SELECT state FROM issue WHERE id = ?1").get(stale.issueId)?.state).toBe("open");
249 t.stop();
250
251 const html = await page();
252 expect(html).toContain(`/${PACKS_OWNER}/mirror/pulls/${String(stale.number)}"`);
253 expect(html).toContain("You cannot write to this repository.");
254 expect(html).not.toContain(`/${PACKS_OWNER}/mirror/pulls/${String(stale.number)}/state"`);
255 expect(html).toContain('/alice/app/pulls/104/state"');
195256 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs