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

The list of templates a new forge can start from sorts by last-built, newest first, ties by name #16080

Merged opened this

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

Merged

torque/forge:torque/16049-the-list-of-templates-a-new-forge-can-st → main 0 commits fork 2 threads · 2 unresolved

  • Merged. torque/16049-the-list-of-templates-a-new-forge-can-st was merged into main as a56295d.

Review

Sign in to review this change.
8 files changed +108 −14
docs/features/new-forge-template.md +4
@@ -39,3 +39,7 @@ The terminal has the same list: the "Templates" command (`src/tui/screens/templa
3939 ## Choosing on the page: radios
4040
4141 The New forge page lists the built-in templates as radio buttons, Blank checked, and needs no script; `/forges/new?template=starter` opens the form with Starter app checked. Pick one and press Make. In the terminal the New forge screen cycles the same choices with left and right, so both doors offer the same list. Code: `src/web/pages/new-forge.ts`. Test: `test/new-forge-template.test.ts`.
42
43 ### Order of the list
44
45 `/templates` lists the most recently started template first (last built, newest first), ties by id, and templates never started last. The terminal's Templates screen shows the same order because both read `templateList`. Test: `test/template-list-order.test.ts`.
src/spawn/template_list.ts +32 −2
@@ -7,6 +7,7 @@
77 import type { Database } from "bun:sqlite";
88 import { listReposVisibleTo } from "../core/repos.ts";
99 import type { User } from "../core/users.ts";
10 import type { TemplateUse } from "./template_use.ts";
1011 import { DEFAULT_TEMPLATE, TEMPLATES, templateOf } from "./templates.ts";
1112
1213 export interface TemplateRow {
@@ -16,7 +17,36 @@ export interface TemplateRow {
1617 readonly says: string;
1718 }
1819
19 export function templateList(db: Database, viewer: User | undefined): TemplateRow[] {
20 /**
21 * Rows by last built, newest first: the newest start from each template (`templateUse`). Ties, and
22 * templates never built (or with no dated start), by id; never built sort last. Sorting only.
23 */
24 export function sortByLastBuilt<T extends { id: string }>(rows: readonly T[], used: ReadonlyMap<string, TemplateUse>): T[] {
25 const at = (id: string): number => {
26 const n = used.get(id)?.newest;
27 const t = n == null ? Number.NaN : Date.parse(n);
28 return Number.isNaN(t) ? Number.NEGATIVE_INFINITY : t;
29 };
30 return [...rows].sort((a, b) => {
31 const d = at(b.id) - at(a.id);
32 if (d !== 0 && !Number.isNaN(d)) return d;
33 return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
34 });
35 }
36
37 /**
38 * The rows in the order the doors show them: by last built (`sortByLastBuilt`). `used` is required
39 * so the order cannot be skipped by accident; a caller that wants the fixed order says so with
40 * `templateListUnsorted`.
outdated

Make used required. An optional argument means the sort can be skipped without anyone noticing, and the new-forge picker is the only caller that should not sort. Give that picker an explicit unsorted path instead.

41 */
42 export function templateList(db: Database, viewer: User | undefined, used: ReadonlyMap<string, TemplateUse>): TemplateRow[] {
43 return sortByLastBuilt(templateListUnsorted(db, viewer), used);
44 }
45
46 /**
47 * The rows in their fixed order, built-ins then repositories: for pickers and lookups, not lists.
48 */
49 export function templateListUnsorted(db: Database, viewer: User | undefined): TemplateRow[] {
2050 const repos = listReposVisibleTo(db, viewer, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`);
2151 return [...TEMPLATES.map((t) => t.id), ...repos].map((id) => {
2252 const t = templateOf(id);
@@ -43,7 +73,7 @@ export function templateRow(db: Database, viewer: User | undefined, id: string):
4373 const t = templateOf(id);
4474 return { id, title: t.title, says: t.says };
4575 }
46 return templateList(db, viewer).find((r) => r.id === id);
76 return templateListUnsorted(db, viewer).find((r) => r.id === id);
4777 }
4878
4979 export const TEMPLATES_QUERY_MAX = 80;
src/tui/screens/templates.ts +2 −2
@@ -28,9 +28,9 @@ export function templatesScreen(session: Session, ctx: Ctx): Screen {
2828 let typing = false;
2929 // Read once when the screen opens: a keypress must not hit the disk.
3030 const used = templateUse(listChildrenNow(session.app));
31 const recent = templateRecency(session.app.db, templateList(session.app.db, session.user).map((r) => r.id));
31 const recent = templateRecency(session.app.db, templateList(session.app.db, session.user, used).map((r) => r.id));
3232 // Each repository template's README sentence arrives after the first paint, then stays.
33 let listed = templateList(session.app.db, session.user);
33 let listed = templateList(session.app.db, session.user, used);
3434 void withReadmeSays(session.app, listed).then((r) => {
3535 listed = r;
3636 ctx.invalidate();
src/web/pages/new-forge.ts +2 −2
@@ -39,7 +39,7 @@ import { FOLLOW_LABELS, FOLLOW_WORDS } from "../../spawn/follow_words.ts";
3939 import { dropGift, keepGift, keptGift } from "../gift_cookie.ts";
4040 import { notFoundPage, pageHead } from "../chrome.ts";
4141 import { field, readForm, type Form } from "../form.ts";
42 import { templateList } from "../../spawn/template_list.ts";
42 import { templateListUnsorted } from "../../spawn/template_list.ts";
4343 import { templateRows } from "./templates.ts";
4444 import { html, type Html } from "../html.ts";
4545 import { noteForgeMade } from "../funnel_door.ts";
@@ -742,7 +742,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
742742 }, { page: true });
743743 if (door.status === 404 && door.body["error"] === "unknown_template")
744744 return page(
745 { ctx, title: "New forge", body: formView(ctx, user, { ...values, template: DEFAULT_TEMPLATE }, { form: String(door.body["message"]) }, templateRows(templateList(ctx.app.db, user?.kind === "user" ? user : undefined)), readsFor(ctx, user)) },
745 { ctx, title: "New forge", body: formView(ctx, user, { ...values, template: DEFAULT_TEMPLATE }, { form: String(door.body["message"]) }, templateRows(templateListUnsorted(ctx.app.db, user?.kind === "user" ? user : undefined)), readsFor(ctx, user)) },
746746 404,
747747 );
748748 if (door.status >= 400) {
src/web/pages/templates.ts +3 −3
@@ -81,13 +81,13 @@ export async function templatesPage(ctx: Ctx): Promise<Response> {
8181 const user = ctx.auth.user;
8282 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
8383 const q = (ctx.url.searchParams.get("q") ?? "").trim().slice(0, TEMPLATES_QUERY_MAX);
84 const listed = timePhase(ctx.request, "reads", () => templateList(ctx.app.db, user?.kind === "user" ? user : undefined));
84 const used = templateUse(await listChildren(ctx.app));
85 const listed = timePhase(ctx.request, "reads", () => templateList(ctx.app.db, user?.kind === "user" ? user : undefined, used));
8586 const all = await withReadmeSays(ctx.app, listed);
8687 const rows = filterTemplates(all, q);
8788 const held = new Map<string, TemplateHolds | undefined>();
8889 await Promise.all(rows.map(async (r) => held.set(r.id, await templateHolds(ctx.app, r.id))));
8990 const recent = templateRecency(ctx.app.db, rows.map((r) => r.id));
90 const used = templateUse(await listChildren(ctx.app));
9191 const pictures = timePhase(ctx.request, "pictures", () => templatePictures(ctx, rows.map((r) => r.id)));
9292 return timePhase(ctx.request, "render", () =>
9393 page({
@@ -144,8 +144,8 @@ export function templatesJsonBody(rows: readonly TemplateRow[], used: ReadonlyMa
144144 export async function templatesJson(ctx: Ctx): Promise<Response> {
145145 const user = ctx.auth.user;
146146 const q = (ctx.url.searchParams.get("q") ?? "").trim().slice(0, TEMPLATES_QUERY_MAX);
147 const rows = filterTemplates(templateList(ctx.app.db, user?.kind === "user" ? user : undefined), q);
148147 const used = templateUse(await listChildren(ctx.app));
148 const rows = filterTemplates(templateList(ctx.app.db, user?.kind === "user" ? user : undefined, used), q);
149149 return json(templatesJsonBody(rows, used), 200, {
150150 "cache-control": sharedCache(ctx.request, "/templates.json", () => false),
151151 vary: EDGE_VARY,
test/template-list-order.test.ts added +61
@@ -0,0 +1,61 @@
1 import { afterAll, beforeAll, expect, test } from "bun:test";
2 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { listChildren } from "../src/actions/spawn.ts";
7 import { serve, type Servers } from "../src/http/server.ts";
8 import { sortByLastBuilt, templateList } from "../src/spawn/template_list.ts";
9 import { templateUse } from "../src/spawn/template_use.ts";
10
11 const use = (newest: string | null, count = 1) => ({ count, newest });
12
13 test("newest build first, ties by id, never built last", () => {
14 const rows = [{ id: "zed/t" }, { id: "never" }, { id: "b" }, { id: "a" }, { id: "old" }, { id: "undated" }];
15 const used = new Map([
16 ["zed/t", use("2026-11-03T00:00:00Z")],
17 ["a", use("2026-11-02T00:00:00Z")],
18 ["b", use("2026-11-02T00:00:00Z")],
19 ["old", use("2026-01-01T00:00:00Z")],
20 ["undated", use(null)],
outdated

These tests only cover the pure helper. Add one that goes through templateList or /templates.json with recorded starts, so dropping used from the page or the JSON door fails a test.

21 ]);
22 expect(sortByLastBuilt(rows, used).map((r) => r.id)).toEqual(["zed/t", "a", "b", "old", "never", "undated"]);
23 });
24
25 test("nothing built: by id", () => {
26 expect(sortByLastBuilt([{ id: "b" }, { id: "a" }], new Map()).map((r) => r.id)).toEqual(["a", "b"]);
27 });
28
29 let dir: string;
30 let app: App;
31 let servers: Servers;
32 beforeAll(async () => {
33 dir = await mkdtemp(join(tmpdir(), "forge-template-order-"));
34 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0, forgeRepo: "alice/forge-code" });
35 // A recorded start of Starter, the way test/templates-tui.test.ts records one.
36 await mkdir(join(dir, "spawn"), { recursive: true });
37 await writeFile(join(dir, "spawn", "a.json"), JSON.stringify({ name: "a", bodyId: "ba", done: true, createdAt: "2026-11-05T10:00:00.000Z", template: "starter" }));
38 servers = await serve(app);
39 }, 30_000);
40 afterAll(async () => {
41 servers.stop();
42 app.close();
43 await rm(dir, { recursive: true, force: true });
44 });
45
46 test("templateList puts a started template before the never-started, built-ins by id after", async () => {
47 const used = templateUse(await listChildren(app));
48 const ids = templateList(app.db, undefined, used).map((r) => r.id);
49 expect(ids[0]).toBe("starter");
50 expect(ids.indexOf("starter")).toBeLessThan(ids.indexOf("blank"));
51 });
52
53 test("/templates and /templates.json both show the started template first", async () => {
54 const json = (await (await fetch(`${servers.url}/templates.json`)).json()) as { templates: { id: string; starts: number }[] };
55 expect(json.templates[0]).toMatchObject({ id: "starter", starts: 1 });
56 expect(json.templates.map((t) => t.id).indexOf("blank")).toBeGreaterThan(0);
57 const page = await (await fetch(`${servers.url}/templates`)).text();
58 const pageIds = [...page.matchAll(/data-template="([^"]+)"/g)].map((m) => m[1]!);
59 expect(pageIds[0]).toBe("starter");
60 expect(pageIds).toEqual(json.templates.map((t) => t.id));
61 });
test/templates-page.test.ts +2 −2
@@ -11,7 +11,7 @@ import { createRepo } from "../src/core/repos.ts";
1111 import { createSession } from "../src/core/sessions.ts";
1212 import { createUser, getUserByName } from "../src/core/users.ts";
1313 import { serve, type Servers } from "../src/http/server.ts";
14 import { templateList } from "../src/spawn/template_list.ts";
14 import { templateListUnsorted } from "../src/spawn/template_list.ts";
1515
1616 let dir: string;
1717 let app: App;
@@ -69,7 +69,7 @@ test("a private template repository is hidden from a stranger and shown to its r
6969 if (!r.ok) throw new Error(r.error);
7070 app.db.query("UPDATE repo SET is_template = 1 WHERE name = ?1").run(name);
7171 }
72 const ids = (u: Parameters<typeof templateList>[1]) => templateList(app.db, u).map((r) => r.id);
72 const ids = (u: Parameters<typeof templateListUnsorted>[1]) => templateListUnsorted(app.db, u).map((r) => r.id);
7373 expect(ids(undefined)).toContain("tess/open-kit");
7474 expect(ids(undefined)).not.toContain("tess/hidden-kit");
7575 expect(ids(other.value)).not.toContain("tess/hidden-kit");
test/templates-tui.test.ts +2 −3
@@ -120,14 +120,13 @@ test("the selected row says how many forges it started, read once when the scree
120120 await rec("b", "starter", "2026-11-05T10:00:00.000Z");
121121 const t = open(otto);
122122 await settleApp(t.tui);
123 expect(t.tui.screen.toText()).toContain("not used yet"); // Blank is selected
123 expect(t.tui.screen.toText()).toContain("2 forges started, newest 2026-11-05"); // Starter, last built, is first and selected
124124 t.screen.key(key("j"));
125125 t.tui.ctx.invalidate();
126126 await settleApp(t.tui);
127 expect(t.tui.screen.toText()).toContain("2 forges started, newest 2026-11-05");
127 expect(t.tui.screen.toText()).toContain("not used yet"); // Blank, never built, is last
128128 await rec("c", "starter", "2026-11-09T10:00:00.000Z"); // after the open: not re-read on a keypress
129129 t.screen.key(key("k"));
130 t.screen.key(key("j"));
131130 t.tui.ctx.invalidate();
132131 await settleApp(t.tui);
133132 expect(t.tui.screen.toText()).toContain("2 forges started, newest 2026-11-05");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs