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

The terminal's chapters screen prints the Next line and the ranked-for line the page prints #12993

Merged opened this

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

Merged

scout/forge:scout/12991-the-terminal-s-chapters-screen-prints-th → main 7 commits fork 5 threads · 5 unresolved

  • Merged. scout/12991-the-terminal-s-chapters-screen-prints-th was merged into main as 04f2878.

Review

Sign in to review this change.
9 files changed +194 −53
docs/features/chapters.md +1 −1
@@ -19,7 +19,7 @@ A closed chapter's list is frozen, so `itemsOf` keeps it in process memory (at m
1919
2020 - **On /next (#12288).** `/:owner/:name/next` has a Chapters section: each chapter with issues closed against its list, and, for the repository's owner, **Close chapter** on the open one (`POST …/chapters/:chapter/close`, same-origin, nothing moves). A chapter with issues still open says which ones are in its way and refuses the close with the same sentence. A close shows its receipt (name, tag) and an **Undo** for 60 seconds (`…/undo`: the tag goes, the chapter is open again); a close that moved items to the next chapter (Ship it) has no undo. The terminal does the same on `src/tui/screens/chapters.ts` (`c`, `u`); its acts append the same events, so an open web page follows.
2121
22 - **Next line (#12681).** A closed chapter's page ends with `Next: <earliest draft>` (linked), or says no chapter is drafted. `/next` carries a header line: `Ranked for <open chapter>: <progress sentence>`, or, when chapters exist and none is open, "No chapter is open" with a link to draft one. A repository with no chapters shows neither. The terminal has no chapter screen line for these two facts yet.
22 - **Next line (#12681).** A closed chapter's page ends with `Next: <earliest draft>` (linked), or says no chapter is drafted. `/next` carries a header line: `Ranked for <open chapter>: <progress sentence>`, or, when chapters exist and none is open, "No chapter is open" with a link to draft one. A repository with no chapters shows neither. The terminal prints the same words (`nextWords`, `chapterLineWords` in `src/core/chapters.ts`): `Next: <name>` under a closed chapter on its screen, and the ranked-for line, or "No chapter is open. Draft one.", under the heading on its /next screen; both wrap at narrow widths, and a repository with no chapters shows neither.
2323
2424 ## The first chapter: v1.0.0
2525
docs/features/next-up.md +1 −1
@@ -15,7 +15,7 @@
1515
1616 **Filter (#11867):** a plain GET form above the list narrows `/next` to one pillar (`?pillar=P7` or `Later`, typed in a box) and/or a word (`?q=cache`, matched without regard to case, shown as typed, at most 80 characters). A filter only hides rows: each keeps its real place in the whole ranking, the cut line stays where the whole list puts it (drawn only between shown rows), and a move made under a filter moves in the whole order and returns to the same filter. A line says "N of M shown", and that the week's capacity bar is left out while filtered. An unknown or malformed pillar shows an empty list that says so. **Terminal:** `/` asks for a pillar and/or a word (`P7 cache`); an empty answer clears it; ranks, `t` `u` `d` `l` and the header count behave as on the page.
1717
18 **The chapter line (#12681):** under the title, once the repository has chapters, `Ranked for <open chapter>: <progress sentence>` (linked), or "No chapter is open" with a link to draft one; a repository that never drafted a chapter shows no line. **Terminal:** the screen prints the same line under the title, from the same function (`chapterWords` in `web/pages/next_chapters.ts`) (#13254).
18 **The chapter line (#12681):** under the title, once the repository has chapters, `Ranked for <open chapter>: <progress sentence>` (linked), or "No chapter is open" with a link to draft one; a repository that never drafted a chapter shows no line. **Terminal:** the screen prints the same line under the title, from the same function (`chapterLineParts` in `core/chapters.ts`), wrapped to the width and never cut (#13254, #12991).
1919
2020 **The growth line (#12290):** under the title, two `dl` rows: *Week* (issues opened in the last seven days, who opened them, how many closed, and what is open now: "2 issues opened (2 by owner), 0 closed. 2 open (2 issues, 0 pulls).", #12867: one row, so the numbers are said once) and *Planner* (on, paused until a time in UTC, or paused until the owner switches it on). The owner (a person who administers the repository) also gets the switch in the Planner row: a button in a post form to the same `planner_switch` action as the queue page, sent back to `/next`, so the pause is one tap and the owner stays on the list. A reader sees both rows and no button. Both rows come from one read (`weekLine`, which also counts open issues and pulls and what opened and closed today), sealed issues left out for a viewer who may not see them. **Terminal:** Next up shows the same sentence (`growthWords`, `pauseSentence`) above the list, and the owner presses `p` to pause the planner until they switch it on, and `p` again to switch it on; for a reader and for an agent the key does nothing.
2121
src/core/chapters.ts +28
@@ -349,6 +349,34 @@ export function progressOf(chapter: Chapter, items: readonly Item[], now: Date):
349349 export const progressSentence = (p: Progress): string =>
350350 `${p.done} of ${p.total} done${p.finishesOn === null ? "" : `; at this pace it finishes ${p.finishesOn}`}.`;
351351
352 /**
353 * A sentence in three parts, so the page can link the middle one and the terminal print all three.
354 */
355 export type Parts = { lead: string; name: string | null; tail: string; chapter: Chapter | null };
356 const joined = (p: Parts): string => `${p.lead}${p.name ?? ""}${p.tail}`;
357
358 /** A closed chapter's last line: the earliest draft's name, or that none is drafted. */
359 export const NO_NEXT_WORDS = "Next: no chapter is drafted.";
360 export const nextParts = (later: Chapter | undefined): Parts =>
361 later === undefined ? { lead: NO_NEXT_WORDS, name: null, tail: "", chapter: null } : { lead: "Next: ", name: later.name, tail: "", chapter: later };
362 export const nextWords = (later: Chapter | undefined): string => joined(nextParts(later));
363
364 /**
365 * The line under /next's heading; null when there are no chapters. With none open, `name` is "Draft
366 * one".
367 */
368 export const NONE_OPEN_WORDS = "No chapter is open.";
369 export function chapterLineParts(all: readonly Chapter[], itemsFor: (c: Chapter) => readonly Item[], now: Date): Parts | null {
370 if (all.length === 0) return null;
371 const open = all.find((c) => c.state === "open");
372 if (open === undefined) return { lead: `${NONE_OPEN_WORDS} `, name: "Draft one", tail: ".", chapter: null };
373 return { lead: "Ranked for ", name: open.name, tail: `: ${progressSentence(progressOf(open, itemsFor(open), now))}`, chapter: open };
374 }
375 export function chapterLineWords(all: readonly Chapter[], itemsFor: (c: Chapter) => readonly Item[], now: Date): string | null {
376 const parts = chapterLineParts(all, itemsFor, now);
377 return parts === null ? null : joined(parts);
378 }
379
352380 /**
353381 * What the chapter's issues have cost so far (their runs and checks, and their pulls'), in dollars.
354382 */
src/tui/screens/chapters.ts +18 −4
@@ -10,13 +10,13 @@
1010 */
1111
1212 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords, undoableClose } from "../../actions/chapters.ts";
13 import { costSentence, getChapter, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
13 import { costSentence, getChapter, nextChapterOf, nextWords, itemsOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1414 import { canAdmin, type Repo } from "../../core/repos.ts";
1515 import type { Ctx, Screen } from "../app/app.ts";
1616 import type { Command } from "../app/palette.ts";
1717 import { binding } from "../app/keys.ts";
1818 import { style } from "../term/style.ts";
19 import { truncate } from "../term/width.ts";
19 import { truncate, wrap } from "../term/width.ts";
2020 import type { Session } from "../session.ts";
2121 import { fill as fillSpace, len, split } from "../ui/layout.ts";
2222 import { ListState, confirmScreen, drawList, live, promptScreen, type ListRow } from "./common.ts";
@@ -61,17 +61,31 @@ export function chapterScreen(f: Session, ctx: Ctx, repo: Repo, name: string): S
6161 const c = getChapter(f.app.db, repo.id, name);
6262 return c === undefined ? [] : itemsOf(f.app.db, c);
6363 };
64 // The page's Next line, read when the screen loads and when a chapter event arrives, not per
65 // frame.
66 let nextLine = "";
67 const refresh = (): void => {
68 const c = getChapter(f.app.db, repo.id, name);
69 nextLine = c?.state === "closed" ? nextWords(nextChapterOf(f.app.db, repo.id)) : "";
70 };
6471 const screen: Screen = {
6572 title: `${repo.ownerName}/${repo.name} — ${name}`,
6673 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "add an issue"), binding(["x"], "take it out"), binding(["o"], "open"), binding(["s"], "ship")],
6774 async load(signal) {
outdated

nextChapterOf is a database query run on every render frame, and the comment says wrapped, never cut but .slice(0, 2) cuts a long draft name. Read it once in the load/refresh path, as next.ts does for ranked, and either drop the cap or say the cut with an ellipsis.

68 live(f, signal, { repoId: repo.id, where: (e) => isChapterEvent(e.kind) }, () => ctx.invalidate());
75 refresh();
76 live(f, signal, { repoId: repo.id, where: (e) => isChapterEvent(e.kind) }, () => {
77 refresh();
78 ctx.invalidate();
79 });
6980 },
7081 render(area, s) {
7182 const c = ctx.theme.c;
7283 const chapter = getChapter(f.app.db, repo.id, name);
7384 const all = items();
74 const [head, list] = split(area, "v", [len(1), fillSpace(1)]);
85 // A closed chapter ends with the page's Next line, wrapped, never cut.
86 const next = nextLine === "" ? [] : wrap(nextLine, Math.max(area.w, 1));
87 const [head, nextArea, list] = split(area, "v", [len(1), len(next.length), fillSpace(1)]);
88 next.forEach((line, i) => s.text(nextArea!.x, nextArea!.y + i, line, style(c.mutedFg, c.bg), nextArea!.x + nextArea!.w));
7589 const p = chapter === undefined ? undefined : progressOf(chapter, all, new Date());
7690 s.text(
7791 head!.x,
src/tui/screens/next.ts +9 −12
@@ -12,12 +12,12 @@
1212 */
1313
1414 import { rankedWords, rankIssue, stepTo, type Place, placeOf } from "../../actions/next.ts";
15 import { listChapters, itemsOf, chapterLineWords } from "../../core/chapters.ts";
1516 import { nextUp, type NextRow } from "../../core/next_up.ts";
1617 import { setPlannerSwitch } from "../../actions/planner_switch.ts";
1718 import { pauseAt, weekLine, type WeekLine } from "../../core/growth.ts";
1819 import { pauseSentence } from "../../core/planner_pause.ts";
1920 import { canAdmin, canRead, canWrite, type Repo } from "../../core/repos.ts";
20 import { listChapters } from "../../core/chapters.ts";
2121 import { pillarsOf, servedBy } from "../../core/pillars.ts";
2222 import { sealedScope } from "../../core/sealed.ts";
2323 import { notStartable } from "../../crew/not_startable.ts";
@@ -26,13 +26,12 @@ import { openPullStages } from "../../flow/read.ts";
2626 import type { Stage } from "../../flow/stage.ts";
2727 import { countWords, filtered, matches, readFilter, MAX_Q } from "../../web/pages/next_filter.ts";
2828 import { GROWTH_DAYS, growthWords } from "../../web/pages/next_growth.ts";
29 import { chapterText, chapterWords } from "../../web/pages/next_chapters.ts";
3029 import { stateWord } from "../../web/pages/next_state.ts";
3130 import type { Ctx, Screen } from "../app/app.ts";
3231 import { binding } from "../app/keys.ts";
3332 import { fill, len, split } from "../ui/layout.ts";
3433 import { style } from "../term/style.ts";
35 import { truncate } from "../term/width.ts";
34 import { truncate, wrap } from "../term/width.ts";
3635 import type { Session } from "../session.ts";
3736 import { issueScreen } from "./issue.ts";
3837 import { local } from "./where.ts";
@@ -53,8 +52,8 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5352 let growing: { line: WeekLine; until: string | null } | undefined;
5453 let stages = new Map<number, Stage>();
5554 let loaded = false;
56 // The page's chapter line (#13254), from the same function.
57 let chapter: string | null = null;
55 // The page's /next chapter line, from the same words; undefined without chapters.
56 let ranked: string | undefined;
5857 // The filter (#11867): a pillar (`P7`, `Later`) and/or words, as on the page. It hides rows
5958 // only; ranks and moves stay the whole list's.
6059 let asked = "";
@@ -69,8 +68,9 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6968 away = 0;
7069 week = undefined;
7170 growing = undefined;
72 chapter = null;
71 ranked = undefined;
7372 } else {
73 ranked = chapterLineWords(listChapters(f.db, repo.id), (ch) => itemsOf(f.db, ch), new Date()) ?? undefined;
7474 const scope = sealedScope(f.db, repo, f.user);
7575 const next = nextUp(f.db, repo, scope, (ready) => notStartable(f.app, repo, ready, scope));
7676 rows = next.rows;
@@ -78,8 +78,6 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7878 week = weekView(f.db, repo.id, rows, new Date());
7979 const line = weekLine(f.db, repo, GROWTH_DAYS, new Date(), scope);
8080 growing = { line, until: pauseAt(line, new Date()) };
81 const words = chapterWords(f.db, listChapters(f.db, repo.id));
82 chapter = words === null ? null : chapterText(words);
8381 stages = openPullStages(f.db, repo, scope, new Date(), new Set(rows.map((r) => r.issue.number)));
8482 }
8583 loaded = true;
@@ -203,10 +201,9 @@ export function nextScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
203201 },
outdated

Principle 8 (plain words, never cut): .slice(0, 2) silently drops the end of a long open-chapter name or the progress sentence at narrow widths. Drop the slice and let the area take the full wrapped height, as chapters.ts does. Then add a test with a long open chapter name at 40 columns.

204202 render(area, s) {
205203 const c = ctx.theme.c;
206 const rects = split(area, "v", [...(chapter === null ? [] : [len(1)]), len(1), len(1), fill(1)]);
207 const line = chapter === null ? undefined : rects.shift();
208 const [grow, head, list] = rects;
209 if (line !== undefined && chapter !== null) s.text(line.x, line.y, truncate(chapter, line.w), style(c.fg, c.bg), line.x + line.w);
204 const rankedLines = ranked === undefined ? [] : wrap(ranked, Math.max(area.w, 1));
205 const [grow, head, rankedArea, list] = split(area, "v", [len(1), len(1), len(rankedLines.length), fill(1)]);
206 rankedLines.forEach((line, i) => s.text(rankedArea!.x, rankedArea!.y + i, line, style(c.mutedFg, c.bg), rankedArea!.x + rankedArea!.w));
210207 const note = !loaded
211208 ? "Loading…"
212209 : rows.length === 0
src/web/pages/chapters.ts +7 −4
@@ -7,7 +7,7 @@
77 */
88
99 import { CHAPTER_WORDS, close, draft, fill, open, patch, reopen, refusalWords } from "../../actions/chapters.ts";
10 import { costSentence, getChapter, itemsOf, nextChapterOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
10 import { costSentence, nextParts, getChapter, itemsOf, nextChapterOf, listChapters, progressOf, progressSentence, type Chapter, type Item } from "../../core/chapters.ts";
1111 import { canAdmin, type Repo } from "../../core/repos.ts";
1212 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1313 import type { Ctx } from "../../http/context.ts";
@@ -77,6 +77,11 @@ export function chaptersPage(ctx: Ctx): Response {
7777
7878 const fact = (name: string, value: string): Html => html`<div class="status-row"><dt>${name}</dt><dd>${value}</dd></div>`;
7979
80 function nextLine(repo: Repo, later: Chapter | undefined): Html {
81 const p = nextParts(later);
82 return p.chapter === null ? html`${p.lead}` : html`${p.lead}<a href="${hrefOf(repo, p.chapter)}">${p.name}</a>${p.tail}`;
83 }
84
8085 function finished(repo: Repo, c: Chapter, items: readonly Item[], may: boolean, later: Chapter | undefined): Html {
8186 const done = items.filter((i) => i.status === "done");
8287 const days = c.openedAt === null || c.closedAt === null ? 0 : Math.max(1, Math.round((Date.parse(c.closedAt) - Date.parse(c.openedAt)) / 86_400_000));
@@ -92,9 +97,7 @@ function finished(repo: Repo, c: Chapter, items: readonly Item[], may: boolean,
9297 ${may
9398 ? html`<form method="post" action="${hrefOf(repo, c)}/patch">${btn(`Open a patch chapter for ${c.name}`, { variant: "primary" })}</form>`
9499 : null}
95 <p data-next-chapter>${later === undefined
96 ? "Next: no chapter is drafted."
97 : html`Next: <a href="${hrefOf(repo, later)}">${later.name}</a>`}</p>`;
100 <p data-next-chapter>${nextLine(repo, later)}</p>`;
98101 }
99102
100103 // GET /:owner/:name/chapters/:chapter
src/web/pages/next_chapters.ts +5 −26
@@ -4,9 +4,8 @@
44 * are in its way; one closed in the last minute shows its receipt and an Undo. The acts are
55 * `actions/chapters.ts`.
66 */
7 import type { Database } from "bun:sqlite";
87 import { CLOSE_UNDO_MS, stopsClose, undoableClose } from "../../actions/chapters.ts";
9 import { itemsOf, progressOf, progressSentence, type Chapter } from "../../core/chapters.ts";
8 import { chapterLineParts, itemsOf, progressOf, progressSentence, type Chapter } from "../../core/chapters.ts";
109 import { canAdmin, type Repo } from "../../core/repos.ts";
1110 import type { Ctx } from "../../http/context.ts";
1211 import { repoBase } from "../chrome.ts";
@@ -61,34 +60,14 @@ export function chaptersSection(ctx: Ctx, repo: Repo, back: string, all: readonl
6160 ${all.length > SHOWN ? html`<p class="muted small"><a href="${base}/chapters">All ${String(all.length)} chapters</a></p>` : null}</section>`;
6261 }
6362
64 /**
65 * What the chapter line says, in words both the page and the terminal print: the open chapter's
66 * name (null when none is open) and the rest of the sentence.
67 */
68 export interface ChapterWords {
69 name: string | null;
70 tail: string;
71 }
72
73 /** The words of the line under the /next heading, or null for a repository with no chapters. */
74 export function chapterWords(db: Database, all: readonly Chapter[]): ChapterWords | null {
75 if (all.length === 0) return null; // no chapter, no change: a repo that never drafted one flows on
76 const open = all.find((c) => c.state === "open");
77 if (open === undefined) return { name: null, tail: "No chapter is open." };
78 return { name: open.name, tail: progressSentence(progressOf(open, itemsOf(db, open), new Date())) };
79 }
80
81 /** The line as plain text: the terminal's. */
82 export const chapterText = (w: ChapterWords): string => (w.name === null ? w.tail : `Ranked for ${w.name}: ${w.tail}`);
83
8463 /**
8564 * The line under the /next heading: the open chapter and where it stands, or that none is open once
8665 * chapters exist.
8766 */
8867 export function chapterLine(ctx: Ctx, repo: Repo, all: readonly Chapter[]): Html | null {
89 const w = chapterWords(ctx.app.db, all);
90 if (w === null) return null;
9168 const base = repoBase(repo);
92 if (w.name === null) return html`<p class="muted" data-chapter-line>${w.tail} <a href="${base}/chapters">Draft one</a>.</p>`;
93 return html`<p data-chapter-line>Ranked for <a href="${base}/chapters/${encodeURIComponent(w.name)}">${w.name}</a>: ${w.tail}</p>`;
69 const p = chapterLineParts(all, (c) => itemsOf(ctx.app.db, c), new Date());
70 if (p === null) return null;
71 if (p.chapter === null) return html`<p class="muted" data-chapter-line>${p.lead}<a href="${base}/chapters">${p.name}</a>${p.tail}</p>`;
outdated

chapterLineWords is not used by the page. Here the ranked-for sentence is still built by hand, so there are two builders of one line. Derive the page's text from the shared function, or build both from a shared parts function, and keep the link markup around it.

72 return html`<p data-chapter-line>${p.lead}<a href="${base}/chapters/${encodeURIComponent(p.chapter.name)}">${p.name}</a>${p.tail}</p>`;
9473 }
test/chapter-next.test.ts +3 −5
@@ -70,8 +70,7 @@ test("/next names the open chapter and its progress sentence", async () => {
7070 });
7171
7272 const terminalNext = async () => {
73 const { chapterText, chapterWords } = await import("../src/web/pages/next_chapters.ts");
74 const { listChapters } = await import("../src/core/chapters.ts");
73 const { chapterLineWords, itemsOf, listChapters } = await import("../src/core/chapters.ts");
7574 const { createForgeApp } = await import("../src/tui/forge.ts");
7675 const { headlessTerminal } = await import("../src/tui/term/terminal.ts");
7776 const { settleApp } = await import("./helpers/tui.ts");
@@ -95,8 +94,7 @@ const terminalNext = async () => {
9594 };
9695 const line = (slug: string) => {
9796 const r = getRepo(app.db, "alice", slug)!;
98 const w = chapterWords(app.db, listChapters(app.db, r.id));
99 return w === null ? null : chapterText(w);
97 return chapterLineWords(listChapters(app.db, r.id), (c) => itemsOf(app.db, c), new Date());
10098 };
10199 return { screenOf, line };
102100 };
@@ -111,7 +109,7 @@ test("the terminal's Next up prints the page's chapter line for an open chapter"
111109 test("the terminal's Next up prints the page's chapter line when none is open", async () => {
112110 const { screenOf, line } = await terminalNext();
113111 app.db.query("UPDATE chapter SET state = 'closed', closed_at = ?2, notes = 'n' WHERE repo_id = ?1 AND state = 'open'").run(repo.id, "2026-11-02T00:00:00.000Z");
114 expect(line("shop")).toBe("No chapter is open.");
112 expect(line("shop")).toBe("No chapter is open. Draft one.");
115113 expect(await screenOf("alice/shop")).toContain("No chapter is open.");
116114 }, 30_000);
117115
test/tui-chapter-lines.test.ts added +122
@@ -0,0 +1,122 @@
1 /** The terminal prints the page's Next line and ranked-for line, same words (#12991). */
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 { draftChapter, getChapter, startChapter } from "../src/core/chapters.ts";
9 import type { Repo } from "../src/core/repos.ts";
10 import { createUser, type User } from "../src/core/users.ts";
11 import { createForgeApp } from "../src/tui/forge.ts";
12 import { chapterScreen } from "../src/tui/screens/chapters.ts";
13 import { nextScreen } from "../src/tui/screens/next.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 quietLogs();
21
22 let dir: string;
23 let app: App;
24 let servers: Servers;
25 let repo: Repo;
26 let owner: User;
27 let token = "";
28 const guest = { sshUsername: "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test" };
29 const page = (p: string) => fetch(`${servers.url}${p}`, { headers: { authorization: `Bearer ${token}` } }).then((r) => r.text());
30 const plain = (html: string) => html.replace(/<[^>]*>/g, "").replace(/\s+/g, " ");
31
32 beforeAll(async () => {
33 dir = await mkdtemp(join(tmpdir(), "forge-tui-chlines-"));
34 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
35 servers = await serve(app);
36 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
37 if (!u.ok) throw new Error(u.error);
38 owner = u.value;
39 const made = await createRepo(app, owner, { name: "shop", visibility: "public" });
40 if (!made.ok) throw new Error(JSON.stringify(made.error));
41 repo = made.value;
42 token = createToken(app.db, owner.id, "t", "rw").token;
43 }, 60_000);
44
45 afterAll(async () => {
46 servers.stop();
47 app.close();
48 await rm(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
49 });
50
51 async function text(make: (f: Parameters<typeof nextScreen>[0], ctx: Parameters<typeof nextScreen>[1]) => ReturnType<typeof nextScreen>, cols = 100): Promise<string> {
52 const { app: tui, session } = createForgeApp(app, guest, { terminal: headlessTerminal(cols, 30), exitHooks: false });
53 tui.start();
54 tui.ctx.push(make(session, tui.ctx));
55 await settleApp(tui);
56 const out = tui.screen.toText();
57 tui.stop?.();
58 return out;
59 }
60 const squash = (s: string) => s.replace(/\s+/g, " ");
61
62 test("a repository with no chapter: neither line, on either door", async () => {
63 const next = await text((f, ctx) => nextScreen(f, ctx, repo));
64 expect(next).not.toContain("Ranked for");
65 expect(next).not.toContain("No chapter is open");
66 expect(await page("/alice/shop/next")).not.toContain("data-chapter-line");
67 });
68
69 test("a closed chapter: Next says none is drafted, then names the earliest draft, as the page does", async () => {
70 const one = draftChapter(app.db, repo.id, { name: "v1.0.0", means: "First" }, owner.id);
71 if (!one.ok) throw new Error("draft");
72 app.db.query("UPDATE chapter SET state = 'closed', opened_at = ?2, closed_at = ?2, notes = 'n' WHERE id = ?1").run(one.value.id, "2026-11-01T00:00:00.000Z");
73 const none = await text((f, ctx) => chapterScreen(f, ctx, repo, "v1.0.0"));
74 expect(none).toContain("Next: no chapter is drafted.");
75 expect(plain(await page("/alice/shop/chapters/v1.0.0"))).toContain("Next: no chapter is drafted.");
76 draftChapter(app.db, repo.id, { name: "v1.1.0" }, owner.id);
77 const named = await text((f, ctx) => chapterScreen(f, ctx, repo, "v1.0.0"));
78 expect(named).toContain("Next: v1.1.0");
79 expect(plain(await page("/alice/shop/chapters/v1.0.0"))).toContain("Next: v1.1.0");
80 });
81
82 test("/next with chapters and none open says so, as the page does", async () => {
83 const next = await text((f, ctx) => nextScreen(f, ctx, repo));
84 expect(next).toContain("No chapter is open. Draft one.");
85 expect(plain(await page("/alice/shop/next"))).toContain("No chapter is open. Draft one.");
86 });
87
88 test("/next with an open chapter prints the ranked-for line, at 40 columns too, as the page does", async () => {
89 startChapter(app.db, getChapter(app.db, repo.id, "v1.1.0")!, new Date());
90 const line = "Ranked for v1.1.0: 0 of 0 done.";
91 expect(squash(await text((f, ctx) => nextScreen(f, ctx, repo)))).toContain(line);
92 expect(plain(await page("/alice/shop/next"))).toContain(line);
93 const narrow = await text((f, ctx) => nextScreen(f, ctx, repo), 40);
94 expect(narrow).toContain("Ranked for v1.1.0: 0 of 0");
95 expect(narrow).toContain("done.");

The 40-column test never forces a wrap (the line is 31 characters), so it would pass without wrap. Use a longer chapter name so the line splits at 40 columns and assert both rows.

96 });
97
98 test("a long draft name wraps at 40 columns and is never cut", async () => {
99 const long = "release-candidate-for-the-spring-launch";
100 draftChapter(app.db, repo.id, { name: long }, owner.id);
101 const narrow = await text((f, ctx) => chapterScreen(f, ctx, repo, "v1.0.0"), 40);
102 const rows = narrow.split("\n").map((r) => r.trim());
103 expect(rows).toContain("Next:");
104 expect(rows).toContain(long);
105 expect(squash(narrow)).toContain(`Next: ${long}`);
106 });
107
108 test("/next with a long open chapter name wraps the ranked-for line at 40 columns and cuts none of it", async () => {
109 const made = await createRepo(app, owner, { name: "longshop", visibility: "public" });
110 if (!made.ok) throw new Error(JSON.stringify(made.error));
111 const long = "release-candidate-for-the-autumn-launch";
112 const drafted = draftChapter(app.db, made.value.id, { name: long }, owner.id);
113 if (!drafted.ok) throw new Error("draft");
114 startChapter(app.db, getChapter(app.db, made.value.id, long)!, new Date());
115 const line = `Ranked for ${long}: 0 of 0 done.`;
116 expect(line.length).toBeGreaterThan(40);
117 const narrow = await text((f, ctx) => nextScreen(f, ctx, made.value), 40);
118 const rows = narrow.split("\n").map((r) => r.trim());
119 expect(rows.some((r) => r.includes(long))).toBe(true);
120 expect(squash(narrow)).toContain(line);
121 expect(plain(await page("/alice/longshop/next"))).toContain(line);
122 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs