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

The queue page numbers each row by its position and shows its chapter #16151

Merged opened this

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

Merged

scout/forge:scout/16136-the-queue-page-numbers-each-row-by-its-p → main 0 commits fork 7 threads · 7 unresolved

  • Merged. scout/16136-the-queue-page-numbers-each-row-by-its-p was merged into main as b738ca8.

Review

Sign in to review this change.
9 files changed +205 −13
docs/features/queue.md +5 −1
@@ -14,12 +14,16 @@ Each row has a `state`, derived from the dependency graph and not from the wordi
1414 - `blocked`: open work stands in front of it.
1515 - `held`: anything else that passes it over (a blocker closed as dropped, a hot file, an open pull, a reader's issue nobody adopted).
1616
17 ## Reading the order
18
19 The repository's queue page (`/<owner>/<name>/queue`) lists "Next to be taken": the rows the crew will take, numbered 1.. in the picker's order, each with its chapter when it has one. The queue API and the terminal's Next up use the same order and numbers.
20
1721 ## API
1822
1923 `GET /api/v1/repos/<owner>/<name>/queue` (anonymous for a public repository; a private one is 404 to a guest).
2024
2125 - `limit` (1 to 200, default 100) and `offset` (default 0) page through it.
22 - Answers `{ queue: [{ position, number, title, onIt, state, why }], total, limit, offset, notNow }`.
26 - Answers `{ queue: [{ position, number, title, chapter, onIt, state, why }], total, limit, offset, notNow }`.
2327 - A bad `limit` or `offset` is 422 `bad_page`.
2428
2529 ## The `next_up` tool
src/core/chapters.ts +24
@@ -176,6 +176,19 @@ export function patchName(name: string): string {
176176
177177 // ---- items ----
178178
179 /**
180 * The name of the chapter each of a repository's issues is in, by issue id; an issue in none is
181 * absent.
182 */
183 export function chapterNames(db: Database, repoId: string): Map<string, string> {
184 return new Map(
185 db
186 .query<{ issue_id: string; name: string }, [string]>("SELECT i.issue_id, c.name FROM chapter_item i JOIN chapter c ON c.id = i.chapter_id WHERE c.repo_id = ?1")
187 .all(repoId)
188 .map((r) => [r.issue_id, r.name] as const),
189 );
190 }
191
179192 /** The chapter an issue is in, if any. */
180193 export function chapterOfIssue(db: Database, issueId: string): Chapter | undefined {
181194 const row = db
@@ -227,6 +240,17 @@ export const orderFrom = (chapter: Chapter, items: readonly { readonly issueId:
227240 places: new Map(items.map((it, k) => [it.issueId, k + 1] as const)),
228241 });
229242
243 /**
244 * Rows in the order the crew takes them (#15762): the open chapter's items first, by the owner's
245 * position, ties by issue number; every other row after, in the order it had.
246 */
247 export function chapterFirst<T extends { readonly issue: { readonly id: string; readonly number: number } }>(rows: readonly T[], order: OpenOrder | null | undefined): T[] {

The unchaptered-outranks-chaptered branch has no test that fails without it. Add a direct unit test of chapterFirst.

248 if (order === null || order === undefined) return [...rows];
249 const place = (r: T) => order.places.get(r.issue.id);
250 const inside = rows.filter((r) => place(r) !== undefined).sort((a, b) => place(a)! - place(b)! || a.issue.number - b.issue.number);
251 return [...inside, ...rows.filter((r) => place(r) === undefined)];
252 }
253
230254 /**
231255 * The open chapter's order: the one the owner set (the place, then the issue number). Undefined
232256 * when no chapter is open. Pinned to one chapter, so two open could never interleave their
src/core/next_up.ts +2 −1
@@ -180,11 +180,12 @@ export function nextUp(
180180 }
181181
182182 /** The list as the API serves it: position from 1, in the dispatcher's order. */
183 export function queueJson(rows: readonly NextRow[]) {
183 export function queueJson(rows: readonly NextRow[], chapters: ReadonlyMap<string, string> = new Map()) {
184184 return rows.map((r, i) => ({
185185 position: i + 1,
186186 number: r.issue.number,
187187 title: r.issue.title,
188 chapter: chapters.get(r.issue.id) ?? null,
188189 onIt: r.onIt,
189190 state: r.state,
190191 why: r.why,
src/crew/take_order.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * The order the crew takes issues in (#16136): the next-up list with the open chapter's items
3 * first. The queue page, the queue API and the terminal's Next up all number their rows from this
4 * one function, so they cannot disagree.
5 *
6 * `why: false` skips the reasons a ready row is held (the costly reading): the order is the same,
7 * for a page that shows only the numbers.
8 *
9 * The chapter's order is read unscoped on purpose: the list is already cut to what the viewer may
10 * see, and a row that is absent takes no place.
11 */
12
13 import type { App } from "../app.ts";
14 import { chapterFirst, openOrder } from "../core/chapters.ts";
15 import { nextUp } from "../core/next_up.ts";
16 import type { Repo } from "../core/repos.ts";
17 import { notStartable } from "./not_startable.ts";
18
19 export function takeOrder(app: App, repo: Repo, scope: { sealed?: true; sealedBy?: string }, why = true): ReturnType<typeof nextUp> {
20 const open = openOrder(app.db, repo.id) ?? null;
21 const next = nextUp(app.db, repo, scope, why ? (ready) => notStartable(app, repo, ready, scope, open) : undefined);
22 return { ...next, rows: chapterFirst(next.rows, open) };
23 }
src/http/api.ts +5 −4
@@ -40,8 +40,7 @@ import { DOMAINS } from "../kernel/domains.ts";
4040 import { BODY_CAPS, readBounded } from "./limits.ts";
4141 import { FILE_TEXT } from "./parseable_request.ts";
4242 import { askCheck, askedWords } from "../checks/again.ts";
43 import { nextUp, queueJson } from "../core/next_up.ts";
44 import { notStartable } from "../crew/not_startable.ts";
43 import { queueJson } from "../core/next_up.ts";
4544 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
4645 import { crewNow } from "../actions/crew_now.ts";
4746 import { readScorecards } from "../actions/scorecard.ts";
@@ -347,6 +346,8 @@ import { flagsRoutes } from "./api/flags.ts";
347346 import { appTemplateRoutes } from "./api/app_templates.ts";
348347 import { issueRoutes, labelsHandler } from "./api/issues.ts";
349348 import { chapterRoutes } from "./api/chapters.ts";
349 import { chapterNames } from "../core/chapters.ts";
350 import { takeOrder } from "../crew/take_order.ts";
350351 import { forgeCarries } from "../origins/words.ts";
351352 import { forgeOriginRoutes } from "./api/forge_origin.ts";
352353 import { userRoutes } from "./api/user.ts";
@@ -2466,7 +2467,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
24662467 const repo = loadRepo(ctx);
24672468 if (!repo) return notFound();
24682469 const scope = sealedScope(ctx.app.db, repo, ctx.auth.user);
2469 const next = nextUp(ctx.app.db, repo, scope, (ready) => notStartable(ctx.app, repo, ready, scope));
2470 const next = takeOrder(ctx.app, repo, scope);
24702471 const total = next.rows.length + next.unlisted;
24712472 const bound = (name: string, fallback: number, max: number): number | undefined => {
24722473 const raw = ctx.url.searchParams.get(name);
@@ -2478,7 +2479,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
24782479 if (limit === undefined || limit < 1 || offset === undefined)
outdated

openOrder here takes no scope, while the page builds the order with the viewer scope (itemsOf(..., scope)). The two can disagree for sealed issues. Share one ordering function.

24792480 return apiError("bad_page", 422, `limit is 1 to ${QUEUE_PAGE_MAX} and offset is 0 or more`);
24802481 return json({
2481 queue: queueJson(next.rows).slice(offset, offset + limit),
2482 queue: queueJson(next.rows, chapterNames(ctx.app.db, repo.id)).slice(offset, offset + limit),
24822483 total,
24832484 limit,
24842485 offset,
src/tui/screens/next.ts +8 −5
@@ -13,9 +13,10 @@
1313 */
1414
1515 import { rankedWords, rankIssue, stepTo, type Place, placeOf } from "../../actions/next.ts";
16 import { listChapters, itemsOf, chapterLineWords } from "../../core/chapters.ts";
16 import { listChapters, itemsOf, chapterLineWords, chapterNames } from "../../core/chapters.ts";
17 import { takeOrder } from "../../crew/take_order.ts";
1718 import { nextAll, type NextGroup } from "../../core/next_all.ts";
18 import { nextUp, type NextRow } from "../../core/next_up.ts";
19 import { type NextRow } from "../../core/next_up.ts";
1920 import { batchWords, snoozeMany, undoMany } from "../../actions/next.ts";
2021 import { setPlannerSwitch } from "../../actions/planner_switch.ts";
2122 import { pauseAt, weekLine, type WeekLine } from "../../core/growth.ts";
@@ -23,7 +24,6 @@ import { pauseSentence } from "../../core/planner_pause.ts";
2324 import { canAdmin, canRead, canWrite, type Repo } from "../../core/repos.ts";
2425 import { pillarsOf, servedBy } from "../../core/pillars.ts";
2526 import { sealedScope } from "../../core/sealed.ts";
26 import { notStartable } from "../../crew/not_startable.ts";
2727 import { lineAfter, rangeWords, weekView, type WeekView } from "../../flow/week.ts";
2828 import { openPullStages } from "../../flow/read.ts";
2929 import type { Stage } from "../../flow/stage.ts";
@@ -58,6 +58,8 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5858 let loaded = false;
5959 // The page's /next chapter line, from the same words; undefined without chapters.
6060 let ranked: string | undefined;
61 // Each issue's chapter name by id, as the queue page badges its rows.
62 let chapters = new Map<string, string>();
6163 // The filter (#11867): a pillar (`P7`, `Later`) and/or words, as on the page. It hides rows
6264 // only; ranks and moves stay the whole list's.
6365 let asked = "";
@@ -76,7 +78,8 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7678 } else {
7779 const scope = sealedScope(f.db, repo, f.user);
7880 ranked = chapterLineWords(listChapters(f.db, repo.id), (ch) => itemsOf(f.db, ch, scope), new Date()) ?? undefined;
79 const next = nextUp(f.db, repo, scope, (ready) => notStartable(f.app, repo, ready, scope));
81 chapters = chapterNames(f.db, repo.id);
82 const next = takeOrder(f.app, repo, scope);
8083 rows = next.rows;
8184 away = next.notNowTotal;
8285 week = weekView(f.db, repo.id, rows, new Date());
@@ -203,7 +206,7 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
203206 const ends = line !== null && line > 0 && at < line && (shown[i + 1] ?? line) >= line;
204207 return {
205208 title: `${ticked.has(r.issue.number) ? "[x] " : ""}${at + 1}. #${r.issue.number} ${r.issue.title}`,
206 secondary: `${r.byOwner ? "Owner's pick · " : ""}${r.role === "blocker" ? "Blocker" : "Enabler"}`,
209 secondary: `${r.byOwner ? "Owner's pick · " : ""}${r.role === "blocker" ? "Blocker" : "Enabler"}${chapters.has(r.issue.id) ? ` · ${chapters.get(r.issue.id)}` : ""}`,
outdated

The rows here come from nextUp without chapterFirst, so at+1 is not the page's number. Use the same order. The test asserts only "no chapter", so also assert a chaptered row shows its name.

207210 meta: [stateWord(r, { stage: stages.get(r.issue.number) ?? "issue", waits: r.waits, held: r.state === "held", onIt: r.onIt !== null }), r.onIt ?? "next", estimate === undefined ? "" : rangeWords(estimate), r.why ?? ""]
208211 .filter((x) => x !== "")
209212 .join(" · "),
src/web/pages/queue.ts +17 −2
@@ -7,7 +7,9 @@
77
88 import { deferOldest, hasGate, recentDefer, undoDefer } from "../../actions/defer_aged.ts";
99 import { setCeiling, setPlannerSwitch, setPullsCeiling, SWITCH_REFUSED, switchInput } from "../../actions/planner_switch.ts";
10 import { openFlowWords } from "../../core/chapters.ts";
10 import { chapterNames, openFlowWords } from "../../core/chapters.ts";
11 import { TOP, type NextRow } from "../../core/next_up.ts";
12 import { takeOrder } from "../../crew/take_order.ts";
1113 import { growth, oldest, WHO, type Growth } from "../../core/growth.ts";
1214 import { openPullsCeiling, pullsCeilingHold, PULLS_CEILING_REASON, PULLS_HELD_NOTE } from "../../core/pulls_ceiling.ts";
1315 import { ceilingHold, CEILING_HELD_NOTE, CEILING_REASON, openCeiling, PAUSE_STOPS, pauseSentence, pausedUntil } from "../../core/planner_pause.ts";
@@ -19,7 +21,7 @@ import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repo
1921 import { backTo, field as formField, readForm } from "../form.ts";
2022 import { html, type Html } from "../html.ts";
2123 import { flashTo, page } from "../layout.ts";
22 import { badge, btn, field, row } from "../ui.ts";
24 import { badge, btn, field, listCard, row } from "../ui.ts";
2325
2426 export const DAYS = 14;
2527
@@ -101,6 +103,17 @@ function pullsForm(repo: Repo, ceiling: number, owner: boolean): Html | null {
101103 : null;
102104 }
103105
106 /**
107 * The rows the crew will take, numbered 1..n in the picker's order, each with its chapter when it
108 * has one.
109 */
110 export function takeRows(base: string, rows: readonly NextRow[], chapters: ReadonlyMap<string, string>): Html {
111 return listCard(
112 rows.map((r, k) => row({ href: `${base}/issues/${r.issue.number}`, nav: true, lead: html`${k + 1}`, title: html`#${r.issue.number} ${r.issue.title}`, ...(chapters.has(r.issue.id) ? { trail: badge(chapters.get(r.issue.id)!) } : {}) })),
outdated

Design (principles 4 and 8): a hand-rolled <span data-position> in lead, not a named component. Use an existing DESIGN.md component for a row number, or add one in docs/design/areas/. Also, a muted "no chapter" badge on every unchaptered row is noise. Show the chapter name only when there is one.

113 { attrs: html`data-take-order` },
114 );
115 }
116
104117 const ago = (iso: string, now: Date) => `${Math.max(0, Math.floor((now.getTime() - Date.parse(iso)) / 86_400_000))} days old`;
105118
106119 // GET /:owner/:name/queue
@@ -116,6 +129,7 @@ export function queuePage(ctx: Ctx): Response {
116129 const scope = sealedScope(ctx.app.db, repo, user);
117130 const g = growth(ctx.app.db, repo, DAYS, now, scope);
118131 const age = oldest(ctx.app.db, repo.id, scope);
132 const taking = takeOrder(ctx.app, repo, scope, false).rows.slice(0, TOP);
119133 const until = pausedUntil(ctx.app.db, repo.id, now);
120134 const base = repoBase(repo);
121135 const post = `${base}/queue/defer`;
@@ -133,6 +147,7 @@ export function queuePage(ctx: Ctx): Response {
133147 ${ceilingRow(repo, openCeiling(ctx.app.db, repo.id), ceilingHold(ctx.app.db, repo.id), owner, pullsRow(pullsCeiling, pullsCeilingHold(ctx.app.db, repo.id)))}
134148 ${pullsForm(repo, pullsCeiling, owner)}
135149 <p><a href="${base}/chapters">Chapters</a></p>
150 ${taking.length === 0 ? null : html`<h2>Next to be taken</h2><p class="muted">The next rows the crew takes, in order.</p>${takeRows(base, taking, chapterNames(ctx.app.db, repo.id))}`}
136151 ${aged.length === 0 ? null : html`<ul class="list setting-list" data-aged>${aged}</ul>`}
137152 ${growthRows(g, openFlowWords(ctx.app.db, repo.id, scope, now))}`;
outdated

Design (principle 1): the heading says nothing about what the list is for. One plain sentence would do ("The next rows the crew takes, in order."). Plain words per WRITING.md.

138153 const response = page({ ctx, title: `Queue · ${repo.name}`, crumbs: crumbsFor(repo), palette: repoPalette(ctx, repo), body });
test/queue-order.test.ts added +102
@@ -0,0 +1,102 @@
1 /**
2 * The queue page numbers each row by the crew's pick order and names its chapter, or none (#16136).
3 */
4 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { draft, fill, move, open } from "../src/actions/chapters.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createIssue } from "../src/core/issues.ts";
12 import { getRepo } from "../src/core/repos.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { chapterFirst, orderFrom, type Chapter } from "../src/core/chapters.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let alice: User;
21 const nums: number[] = [];
22 const repo = () => getRepo(app.db, "alice", "q")!;
23
24 beforeAll(async () => {
25 dataDir = await mkdtemp(join(tmpdir(), "forge-queue-order-"));
26 app = createApp({ dataDir, port: 0 });
27 servers = await serve(app);
28 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
29 if (!u.ok) throw new Error(u.error);
30 alice = u.value;
31 const made = await createRepo(app, alice, { name: "q", visibility: "public" });
32 if (!made.ok) throw new Error(String(made.error));
33 for (const t of ["one", "two", "three"]) {
34 const i = createIssue(app.db, { repoId: repo().id, authorId: alice.id, title: t, body: "" });
35 if (!i.ok) throw new Error("issue");
36 nums.push(i.value.number);
37 }
38 expect(draft(app, alice, repo(), { name: "v1" }).ok).toBe(true);
39 // The first issue stays outside the chapter: it ranks higher on its own and must come last.
40 expect(fill(app, alice, repo(), "v1", nums[1]!, true).ok).toBe(true);
41 expect(fill(app, alice, repo(), "v1", nums[2]!, true).ok).toBe(true);
42 expect(open(app, alice, repo(), "v1").ok).toBe(true);
43 }, 30_000);
44
45 afterAll(async () => {
46 servers.stop();
47 app.close();
48 await rm(dataDir, { recursive: true, force: true });
49 });
50
51 /** The page's numbered rows, read by the HTML rewriter: number, issue and chapter ("" for none). */
52 const rows = async () => {
53 const text = await (await fetch(`${servers.url}/alice/q/queue`)).text();
54 const out: { at: string; n: string; chapter: string }[] = [];
55 let inList = false;
56 let cls = "";
57 await new HTMLRewriter()
58 .on("[data-take-order]", { element: (e) => { inList = true; e.onEndTag(() => void (inList = false)); } })
59 .on("[data-take-order] li", { element: () => void out.push({ at: "", n: "", chapter: "" }) })
60 .on("[data-take-order] .row-lead, [data-take-order] .row-title, [data-take-order] .row-trail", {
61 element: (e) => void (cls = e.getAttribute("class")!),
62 text: (t) => {
63 const cur = out[out.length - 1];
64 if (!inList || cur === undefined) return;
65 if (cls === "row-lead") cur.at += t.text.trim();
66 else if (cls === "row-title") cur.n += t.text.trim().replace(/^#(\d+).*$/, "$1");
67 else cur.chapter += t.text.trim();
68 },
69 })
70 .transform(new Response(text))
71 .text();
72 return out.map((r) => ({ at: Number(r.at), n: Number(r.n), chapter: r.chapter }));
73 };
outdated

This assertion holds whatever the order is, so it proves nothing. Assert the two chaptered rows swapped by number, and also check the unchaptered row stays last.

74
75 const api = async () => ((await (await fetch(`${servers.url}/api/v1/repos/alice/q/queue`)).json()) as { queue: { position: number; number: number; chapter: string | null }[] }).queue;
76
77 test("an unchaptered row that ranks higher on its own comes after the chapter's rows, on the page and in the API", async () => {
78 const [a, b, c] = nums as [number, number, number];
79 const got = await rows();
80 expect(got.map((r) => r.at)).toEqual([1, 2, 3]);
81 expect(got.map((r) => r.n)).toEqual([b, c, a]);
82 expect(got.map((r) => r.chapter)).toEqual(["v1", "v1", ""]);
83 const q = await api();
84 expect(q.map((r) => [r.position, r.number, r.chapter])).toEqual([[1, b, "v1"], [2, c, "v1"], [3, a, null]]);
85 });
86
87 test("moving an item in the chapter swaps the numbers; the unchaptered row stays last", async () => {
88 const [a, b, c] = nums as [number, number, number];
89 expect(move(app, alice, repo(), "v1", c, "up").ok).toBe(true);
90 expect((await rows()).map((r) => r.n)).toEqual([c, b, a]);
91 expect((await api()).map((r) => r.number)).toEqual([c, b, a]);
92 });
93
94 test("chapterFirst puts the open chapter's rows first by place, then issue number, and keeps the rest in their order", () => {
95 const r = (number: number) => ({ issue: { id: `id${number}`, number } });
96 const chapter: Chapter = { id: "ch", repoId: "repo", name: "v1", means: "", state: "open", position: 1, patchOf: null, createdAt: "2026-01-01T00:00:00Z", openedAt: "2026-01-01T00:00:00Z", closedAt: null, tagOid: null, notes: "", costUsd: null };
97 // Places 1, 1, 2 become 1, 2, 3 by their order in the list; id5 and id9 are by issue number.
98 const order = orderFrom(chapter, [{ issueId: "id5" }, { issueId: "id9" }, { issueId: "id3" }]);
99 expect(chapterFirst([r(1), r(3), r(2), r(9), r(5)], order).map((x) => x.issue.number)).toEqual([5, 9, 3, 1, 2]);
100 expect(chapterFirst([r(2), r(1)], null).map((x) => x.issue.number)).toEqual([2, 1]);
101 expect(chapterFirst([r(2), r(1)], undefined).map((x) => x.issue.number)).toEqual([2, 1]);
102 });
test/tui-next-up.test.ts +19
@@ -13,6 +13,7 @@ import { openIssue } from "../src/actions/issues.ts";
1313 import { createRepo } from "../src/actions/repos.ts";
1414 import { rankIssue } from "../src/actions/next.ts";
1515 import { createApp, type App as Forge } from "../src/app.ts";
16 import { draft, fill, open as openChapter } from "../src/actions/chapters.ts";
1617 import { addDependency } from "../src/core/dependencies.ts";
1718 import { getIssue } from "../src/core/issues.ts";
1819 import { nextUp } from "../src/core/next_up.ts";
@@ -215,4 +216,22 @@ describe("next up in the terminal", () => {
215216 expect(h.text()).toContain("Work a");
216217 h.stop();
217218 });
219
220 test("a chaptered row is numbered first and shows its chapter, as the queue page does", async () => {
221 const made = await createRepo(forge, alice, { name: "chap", visibility: "public" });
222 if (!made.ok) throw new Error("repo");
223 const x = open(made.value, "Outside row");
224 const y = open(made.value, "Inside row");
225 expect(order(made.value)[0]).toBe(x);
226 expect(draft(forge, alice, made.value, { name: "wave-one" }).ok).toBe(true);
227 expect(fill(forge, alice, made.value, "wave-one", y, true).ok).toBe(true);
228 expect(openChapter(forge, alice, made.value, "wave-one").ok).toBe(true);
229 const h = boot(alice);
230 await h.toNext("alice/chap");
231 const text = h.text();
232 expect(text).toContain("wave-one");
233 expect(text.indexOf("1. #" + y)).toBeGreaterThan(-1);
234 expect(text.indexOf("2. #" + x)).toBeGreaterThan(-1);
235 h.stop();
236 });
218237 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs