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
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/16049-the-list-of-templates-a-new-forge-can-st → main 0 commits fork 2 threads · 2 unresolved
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 | ||
| 39 | 39 | ## Choosing on the page: radios |
| 40 | 40 | |
| 41 | 41 | 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 @@ | ||
| 7 | 7 | import type { Database } from "bun:sqlite"; |
| 8 | 8 | import { listReposVisibleTo } from "../core/repos.ts"; |
| 9 | 9 | import type { User } from "../core/users.ts"; |
| 10 | import type { TemplateUse } from "./template_use.ts"; | |
| 10 | 11 | import { DEFAULT_TEMPLATE, TEMPLATES, templateOf } from "./templates.ts"; |
| 11 | 12 | |
| 12 | 13 | export interface TemplateRow { |
| @@ -16,7 +17,36 @@ export interface TemplateRow { | ||
| 16 | 17 | readonly says: string; |
| 17 | 18 | } |
| 18 | 19 | |
| 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`. | |
| 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[] { | |
| 20 | 50 | const repos = listReposVisibleTo(db, viewer, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`); |
| 21 | 51 | return [...TEMPLATES.map((t) => t.id), ...repos].map((id) => { |
| 22 | 52 | const t = templateOf(id); |
| @@ -43,7 +73,7 @@ export function templateRow(db: Database, viewer: User | undefined, id: string): | ||
| 43 | 73 | const t = templateOf(id); |
| 44 | 74 | return { id, title: t.title, says: t.says }; |
| 45 | 75 | } |
| 46 | return templateList(db, viewer).find((r) => r.id === id); | |
| 76 | return templateListUnsorted(db, viewer).find((r) => r.id === id); | |
| 47 | 77 | } |
| 48 | 78 | |
| 49 | 79 | 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 { | ||
| 28 | 28 | let typing = false; |
| 29 | 29 | // Read once when the screen opens: a keypress must not hit the disk. |
| 30 | 30 | 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)); | |
| 32 | 32 | // 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); | |
| 34 | 34 | void withReadmeSays(session.app, listed).then((r) => { |
| 35 | 35 | listed = r; |
| 36 | 36 | ctx.invalidate(); |
src/web/pages/new-forge.ts +2 −2
| @@ -39,7 +39,7 @@ import { FOLLOW_LABELS, FOLLOW_WORDS } from "../../spawn/follow_words.ts"; | ||
| 39 | 39 | import { dropGift, keepGift, keptGift } from "../gift_cookie.ts"; |
| 40 | 40 | import { notFoundPage, pageHead } from "../chrome.ts"; |
| 41 | 41 | import { field, readForm, type Form } from "../form.ts"; |
| 42 | import { templateList } from "../../spawn/template_list.ts"; | |
| 42 | import { templateListUnsorted } from "../../spawn/template_list.ts"; | |
| 43 | 43 | import { templateRows } from "./templates.ts"; |
| 44 | 44 | import { html, type Html } from "../html.ts"; |
| 45 | 45 | import { noteForgeMade } from "../funnel_door.ts"; |
| @@ -742,7 +742,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> { | ||
| 742 | 742 | }, { page: true }); |
| 743 | 743 | if (door.status === 404 && door.body["error"] === "unknown_template") |
| 744 | 744 | 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)) }, | |
| 746 | 746 | 404, |
| 747 | 747 | ); |
| 748 | 748 | if (door.status >= 400) { |
src/web/pages/templates.ts +3 −3
| @@ -81,13 +81,13 @@ export async function templatesPage(ctx: Ctx): Promise<Response> { | ||
| 81 | 81 | const user = ctx.auth.user; |
| 82 | 82 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 83 | 83 | 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)); | |
| 85 | 86 | const all = await withReadmeSays(ctx.app, listed); |
| 86 | 87 | const rows = filterTemplates(all, q); |
| 87 | 88 | const held = new Map<string, TemplateHolds | undefined>(); |
| 88 | 89 | await Promise.all(rows.map(async (r) => held.set(r.id, await templateHolds(ctx.app, r.id)))); |
| 89 | 90 | const recent = templateRecency(ctx.app.db, rows.map((r) => r.id)); |
| 90 | const used = templateUse(await listChildren(ctx.app)); | |
| 91 | 91 | const pictures = timePhase(ctx.request, "pictures", () => templatePictures(ctx, rows.map((r) => r.id))); |
| 92 | 92 | return timePhase(ctx.request, "render", () => |
| 93 | 93 | page({ |
| @@ -144,8 +144,8 @@ export function templatesJsonBody(rows: readonly TemplateRow[], used: ReadonlyMa | ||
| 144 | 144 | export async function templatesJson(ctx: Ctx): Promise<Response> { |
| 145 | 145 | const user = ctx.auth.user; |
| 146 | 146 | 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); | |
| 148 | 147 | const used = templateUse(await listChildren(ctx.app)); |
| 148 | const rows = filterTemplates(templateList(ctx.app.db, user?.kind === "user" ? user : undefined, used), q); | |
| 149 | 149 | return json(templatesJsonBody(rows, used), 200, { |
| 150 | 150 | "cache-control": sharedCache(ctx.request, "/templates.json", () => false), |
| 151 | 151 | 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 |
||
| 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"; | ||
| 11 | 11 | import { createSession } from "../src/core/sessions.ts"; |
| 12 | 12 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 13 | 13 | 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"; | |
| 15 | 15 | |
| 16 | 16 | let dir: string; |
| 17 | 17 | let app: App; |
| @@ -69,7 +69,7 @@ test("a private template repository is hidden from a stranger and shown to its r | ||
| 69 | 69 | if (!r.ok) throw new Error(r.error); |
| 70 | 70 | app.db.query("UPDATE repo SET is_template = 1 WHERE name = ?1").run(name); |
| 71 | 71 | } |
| 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); | |
| 73 | 73 | expect(ids(undefined)).toContain("tess/open-kit"); |
| 74 | 74 | expect(ids(undefined)).not.toContain("tess/hidden-kit"); |
| 75 | 75 | 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 | ||
| 120 | 120 | await rec("b", "starter", "2026-11-05T10:00:00.000Z"); |
| 121 | 121 | const t = open(otto); |
| 122 | 122 | 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 | |
| 124 | 124 | t.screen.key(key("j")); |
| 125 | 125 | t.tui.ctx.invalidate(); |
| 126 | 126 | 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 | |
| 128 | 128 | await rec("c", "starter", "2026-11-09T10:00:00.000Z"); // after the open: not re-read on a keypress |
| 129 | 129 | t.screen.key(key("k")); |
| 130 | t.screen.key(key("j")); | |
| 131 | 130 | t.tui.ctx.invalidate(); |
| 132 | 131 | await settleApp(t.tui); |
| 133 | 132 | expect(t.tui.screen.toText()).toContain("2 forges started, newest 2026-11-05"); |
new above
offline
Make
usedrequired. 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.