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

The template picker on New forge remembers nothing but shows each template's last-built date from the git log #16005

Merged opened this

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

Merged

scout/forge:scout/15983-the-template-picker-on-new-forge-remembe → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15983-the-template-picker-on-new-forge-remembe was merged into main as e552430.

Review

Sign in to review this change.
9 files changed +302 −73
docs/features/template-recency.md +4 −2
@@ -4,6 +4,8 @@ row: See when a template repository last changed
44 ---
55 # Template recency
66
7 A template that is a repository on this forge says `updated 3d ago` on its row at `/templates` and under the selected row of `/templates` in the terminal, from the merge time of its newest landed pull, or `no changes yet` when none has landed. Built-in templates (Blank, Starter) have no repository and show nothing. The time is the shared `<time>` element (`src/web/time_element.ts`): relative words, the exact instant in `datetime` and `title`; the terminal speaks the same `timeAgo` words.
7 A template that is a repository on this forge says `updated 3d ago` on its row at `/templates`, in the Template choices of New forge, and under the selected row of `/templates` in the terminal. The date is the committer date of the head commit of its default branch (`git log -1`), or `no changes yet` when the repository has no commit. Past 180 days the line adds `· stale`, in the same muted words. Built-in templates (Blank, Starter) have no repository and show nothing.
88
9 - Code: `src/spawn/template_recent.ts`, `src/web/pages/templates.ts`, `src/tui/screens/templates.ts`, `src/web/time_element.ts`. Test: `test/templates-alive.test.ts`, `test/templates-tui.test.ts`.
9 The read is held 60 seconds per repository and shared by the page, the picker and the terminal. A page waits at most 400 ms for a cold read; a repository not read by then shows no date until the next load. The terminal fills the line in after its first paint, never on a keypress. The time is the shared `<time>` element (`src/web/time_element.ts`): relative words, the exact instant in `datetime` and `title`; the picker and the terminal speak the same `timeAgo` words.
10
11 - Code: `src/spawn/template_head.ts`, `src/spawn/template_recent.ts`, `src/web/pages/templates.ts`, `src/web/pages/new-forge.ts`, `src/tui/screens/templates.ts`. Test: `test/template-head.test.ts`, `test/templates-alive.test.ts`, `test/templates-tui.test.ts`.
src/spawn/template_head.ts added +110
@@ -0,0 +1,110 @@
1 /**

The terminal screen needs to read this too (both doors). Also add a docs/features entry.

2 * When each template repository last changed: the committer date of its default branch's head
3 * commit, read from git and held for 60 seconds per repository so /templates and New forge share
4 * one read. Built-in templates have no repository and no entry. Plain data in, plain data out.
5 */
6
7 import type { App } from "../app.ts";
8 import { getRepo } from "../core/repos.ts";
9 import { runGit } from "../git/env.ts";
10 import { heldOf } from "../perf/held.ts";
11 import { repoDir } from "../git/repos.ts";
12 import { parseTemplateName } from "../apps/template_tip.ts";
13
14 /** How long a read is kept. */
15 export const HEAD_TTL_MS = 60_000;
16 /** A head older than this many days is called stale. */
17 export const STALE_DAYS = 180;
18 /** The one word a stale template carries. */
19 export const STALE_WORD = "stale";
20 /**
21 * How long a caller waits for cold reads; a slower repository is absent now and kept when it lands.
22 */
23 export const HEAD_WAIT_MS = 400;
24 /** Most repositories kept; a read past it drops the oldest. */
25 const MAX_KEPT = 500;
26
27 /** One read per repository: its promise, shared by every caller while it runs, then its result. */
28 interface Kept {
29 readonly at: number;
30 readonly read: Promise<string | undefined>;
31 done: boolean;
32 head: string | undefined;
33 }
34
35 const kept = new WeakMap<object, Map<string, Kept>>();
36
37 /**
38 * The one wording of a known head: `updated <date>`, then ` · stale` past `STALE_DAYS`. `date`
39 * shapes the date (a `<time>` on the web, `3d ago` in the terminal and the picker's plain label).
40 */
41 export function headWords<T>(at: string, date: (iso: string) => T, now: number = Date.now()): (string | T)[] {
42 return ["updated ", date(at), ...(isStale(at, now) ? [` · ${STALE_WORD}`] : [])];
43 }
44
45 /** Whether a head's date is over `STALE_DAYS` before `now`. */
46 export function isStale(iso: string, now: number = Date.now()): boolean {
47 const at = Date.parse(iso);
48 return !Number.isNaN(at) && now - at > STALE_DAYS * 86_400_000;
49 }
50
51 async function readHead(app: App, id: string): Promise<string | undefined> {
52 const parsed = parseTemplateName(id);
53 if (!parsed || parsed.folder !== undefined) return undefined;
54 const repo = getRepo(app.db, parsed.owner, parsed.name);
55 if (!repo) return undefined;
56 const got = await runGit(["log", "-1", "--format=%cI", `refs/heads/${repo.defaultBranch}`, "--"], {
57 cwd: repoDir(app.reposRoot, repo.ownerName, repo.name),
58 timeoutMs: 5_000,
59 maxBytes: 256,
60 });
61 if (!got.ok) return undefined;
62 const at = Date.parse(got.value.trim());
63 return Number.isNaN(at) ? undefined : new Date(at).toISOString();
64 }
65
66 /**
67 * The head commit's date (ISO) by `owner/name` for the ids given; a repository with no commit, an
68 * unreadable one, one not read within `waitMs` and a built-in template are absent.
69 */
outdated

A miss awaits readHead inline and stores only the result, so concurrent requests all spawn git for the same id. Store the in-flight promise in the cache so they share one read. Failed reads (head undefined) should be held too.

70 export async function templateHeads(app: App, ids: readonly string[], now: number = Date.now(), waitMs: number = HEAD_WAIT_MS): Promise<Map<string, string>> {
71 let cache = kept.get(app);
72 if (!cache) {
73 kept.set(app, (cache = new Map()));
74 const made = cache;
75 heldOf(app).add("template heads read", () => made.size);
76 }
77 const store = cache;
78 const out = new Map<string, string>();
79 const reads: Promise<void>[] = [];
80 for (const id of new Set(ids.filter((id) => id.includes("/")))) {
81 let hit = store.get(id);
82 if (!hit || now - hit.at >= HEAD_TTL_MS) {
83 // The promise is kept before it settles, so callers arriving meanwhile share this one read;
84 // an unreadable repository's undefined is kept for the same 60 s.
85 const fresh: Kept = { at: now, read: readHead(app, id).catch(() => undefined), done: false, head: undefined };
86 void fresh.read.then((head) => {
87 fresh.head = head;
88 fresh.done = true;
89 });
90 store.delete(id);
91 store.set(id, fresh);
92 if (store.size > MAX_KEPT) store.delete(store.keys().next().value!);
93 hit = fresh;
94 }
95 if (hit.done) {
96 if (hit.head !== undefined) out.set(id, hit.head);
97 } else {
98 reads.push(hit.read.then((head) => void (head !== undefined && out.set(id, head))));
99 }
100 }
101 if (reads.length > 0 && waitMs > 0) {
102 let timer: ReturnType<typeof setTimeout> | undefined;
103 const late = new Promise<void>((done) => {
104 timer = setTimeout(done, waitMs);
105 });
106 await Promise.race([Promise.all(reads), late]);
107 clearTimeout(timer);
108 }
109 return new Map(out);
110 }
src/spawn/template_recent.ts +2 −28
@@ -1,32 +1,6 @@
11 /**
2 * How recently each template repository changed: the merge time of its newest landed pull, one
3 * read for all of them. Built-in templates live in the forge's own code, have no repository and so
4 * no entry. Plain data in, plain data out.
2 * What a repository template with no commit says in place of its date. Built-in templates live in
3 * the forge's own code, have no repository and say nothing.
54 */
65
7 import type { Database } from "bun:sqlite";
8
9 /** What a repository template with no landed pull says in place of its recency. */
106 export const NO_CHANGES_YET = "no changes yet";
11
12 /**
13 * Newest `merged_at` (ISO) by `owner/name`, for the ids given; a repository with no landed pull is
14 * absent.
15 */
16 export function templateRecency(db: Database, ids: readonly string[]): Map<string, string> {
17 const out = new Map<string, string>();
18 const want = new Set(ids.filter((id) => id.includes("/")));
19 if (want.size === 0) return out;
20 const rows = db
21 .query<{ id: string; at: string }, []>(
22 `SELECT user.username || '/' || repo.name AS id, MAX(pull.merged_at) AS at FROM pull
23 JOIN issue ON issue.id = pull.issue_id
24 JOIN repo ON repo.id = issue.repo_id
25 JOIN user ON user.id = repo.owner_id
26 WHERE pull.merged_at IS NOT NULL AND repo.is_template = 1
27 GROUP BY repo.id`,
28 )
29 .all();
30 for (const r of rows) if (want.has(r.id) && !Number.isNaN(Date.parse(r.at))) out.set(r.id, r.at);
31 return out;
32 }
src/tui/screens/templates.ts +12 −6
@@ -14,21 +14,27 @@ import type { Session } from "../session.ts";
1414 import { listChildrenNow } from "../../actions/spawn.ts";
1515 import { withReadmeSays } from "../../spawn/template_says.ts";
1616 import { templateUse, useWords } from "../../spawn/template_use.ts";
17 import { NO_CHANGES_YET, templateRecency } from "../../spawn/template_recent.ts";
17 import { NO_CHANGES_YET } from "../../spawn/template_recent.ts";
18 import { headWords, templateHeads } from "../../spawn/template_head.ts";
1819 import { timeAgo } from "../../web/time_element.ts";
1920 import { newForgeScreen } from "./newforge.ts";
2021 import { templatePreviewScreen } from "./template_preview.ts";
2122
22 /** `updated 3d ago`, in the shared clock's words, or that nothing has landed. */
23 const recencyLine = (at: string | undefined): string => (at === undefined ? NO_CHANGES_YET : `updated ${timeAgo(at)}`);
23 /** `updated 3d ago` (and `stale` past 180 days) from the head commit, or that it has none. */
24 const recencyLine = (at: string | undefined): string => (at === undefined ? NO_CHANGES_YET : headWords(at, timeAgo).join(""));
2425
2526 export function templatesScreen(session: Session, ctx: Ctx): Screen {
2627 let at = 0;
2728 let q = "";
2829 let typing = false;
29 // Read once when the screen opens: a keypress must not hit the disk.
30 // Read when the screen opens: a keypress must not hit the disk.
3031 const used = templateUse(listChildrenNow(session.app));
31 const recent = templateRecency(session.app.db, templateList(session.app.db, session.user, used).map((r) => r.id));
32 let recent: ReadonlyMap<string, string> | undefined;
33 // Head dates come through the 60 s cache after the first paint, never on a keypress.
34 void templateHeads(session.app, templateList(session.app.db, session.user, used).map((r) => r.id)).then((m) => {
35 recent = m;
36 ctx.invalidate();
37 });
3238 // Each repository template's README sentence arrives after the first paint, then stays.
3339 let listed = templateList(session.app.db, session.user, used);
3440 void withReadmeSays(session.app, listed).then((r) => {
@@ -50,7 +56,7 @@ export function templatesScreen(session: Session, ctx: Ctx): Screen {
5056 const on = i === at;
5157 if (y < area.y + area.h) s.text(area.x + 1, y, truncate(`${on ? "> " : " "}${r.title} (${r.id})`, area.w - 2), style(on ? c.accent : c.fg, c.bg), area.x + area.w);
5258 y += 1;
53 if (on) for (const line of [...wrap(r.says, area.w - 6), [useWords(used.get(r.id)), ...(r.id.includes("/") ? [recencyLine(recent.get(r.id))] : [])].join(" · "), ...(r.id === DEFAULT_TEMPLATE ? [] : [`Share: ${templatePath(r.id)}`])]) if (y < area.y + area.h) s.text(area.x + 5, y++, truncate(line, area.w - 6), style(c.mutedFg, c.bg), area.x + area.w);
59 if (on) for (const line of [...wrap(r.says, area.w - 6), [useWords(used.get(r.id)), ...(r.id.includes("/") && recent !== undefined ? [recencyLine(recent.get(r.id))] : [])].join(" · "), ...(r.id === DEFAULT_TEMPLATE ? [] : [`Share: ${templatePath(r.id)}`])]) if (y < area.y + area.h) s.text(area.x + 5, y++, truncate(line, area.w - 6), style(c.mutedFg, c.bg), area.x + area.w);
5460 });
5561 if (q === "" && noRepoTemplates(listed) && y + 1 < area.y + area.h) {
5662 s.text(area.x + 1, y + 1, truncate(session.user?.isAdmin === true ? `${TEMPLATES_EMPTY_ADMIN}: repository settings, App card.` : TEMPLATES_EMPTY, area.w - 2), style(c.mutedFg, c.bg), area.x + area.w);
src/web/pages/new-forge.ts +21 −13
@@ -41,7 +41,9 @@ import { notFoundPage, pageHead } from "../chrome.ts";
4141 import { field, readForm, type Form } from "../form.ts";
4242 import { templateListUnsorted } from "../../spawn/template_list.ts";
4343 import { templateRows } from "./templates.ts";
44 import { headWords, templateHeads } from "../../spawn/template_head.ts";
4445 import { html, type Html } from "../html.ts";
46 import { timeAgo } from "../time_element.ts";
4547 import { noteForgeMade } from "../funnel_door.ts";
4648 import { page } from "../layout.ts";
4749 import { linkToSend, madeBody, madeJs } from "../forge_made.ts";
@@ -123,13 +125,15 @@ interface Reads {
123125 /** Repositories marked as templates that the viewer can read (`full_name`), listed in the
124126 * Template select. */
125127 readonly templates: readonly string[];
128 /** Each repository template's head commit date (ISO), when git could say. */
129 readonly heads: ReadonlyMap<string, string>;
126130 /** The signed-in person's saved recipes (`spawn/recipes.ts`). */
127131 readonly recipes: readonly Recipe[];
128132 }
129133
130 function readsFor(ctx: Ctx, user: User | undefined): Reads {
134 async function readsFor(ctx: Ctx, user: User | undefined): Promise<Reads> {
131135 const full = timePhase(ctx.request, "room", () => noRoom(ctx.app));
132 if (full) return { full, quota: undefined, repos: [], crew: [], templates: [], recipes: [] };
136 if (full) return { full, quota: undefined, repos: [], crew: [], templates: [], heads: new Map(), recipes: [] };
133137 const quota = quotaFull(ctx.app.config.dataDir);
134138 // Each repository once, as its source, and public only; a stranger sees
135139 // none and no crew: nothing private travels to a child they have not claimed.
@@ -144,7 +148,8 @@ function readsFor(ctx: Ctx, user: User | undefined): Reads {
144148 listReposVisibleTo(ctx.app.db, user, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`),
145149 );
146150 const recipes = user === undefined ? [] : listRecipes(ctx.app.config.dataDir, user.id);
147 return { full, quota, repos, crew, templates, recipes };
151 const heads = await templateHeads(ctx.app, templates);
152 return { full, quota, repos, crew, templates, heads, recipes };
148153 }
149154
150155 /** The three sizes, the one asked for chosen (small when the value is not one of them). */
@@ -160,10 +165,13 @@ function sizeOptions(chosen: string): { value: string; label: string; selected?:
160165 }));
161166 }
162167
168 /** ` · updated 3d ago` (and ` · stale` past 180 days) for a template whose head is known. */
169 const headLabel = (at: string | undefined): string => (at === undefined ? "" : ` · ${headWords(at, timeAgo).join("")}`);
170
163171 /**
164172 * The templates in order, Blank first; the one asked for chosen (Blank when it is not one of them).
165173 */
166 function templateOptions(chosen: string, repos: readonly string[]): { value: string; label: string; selected?: boolean }[] {
174 function templateOptions(chosen: string, repos: readonly string[], heads: ReadonlyMap<string, string> = new Map()): { value: string; label: string; selected?: boolean }[] {
167175 const known = TEMPLATES.some((t) => t.id === chosen) || repos.includes(chosen);
168176 const at = known ? chosen : DEFAULT_TEMPLATE;
169177 return [
@@ -172,7 +180,7 @@ function templateOptions(chosen: string, repos: readonly string[]): { value: str
172180 label: `${t.title}: ${lower(t.says)}`,
173181 selected: t.id === at,
174182 })),
175 ...repos.map((ref) => ({ value: ref, label: `${ref}: ${lower(templateOf(ref).says)}`, selected: ref === at })),
183 ...repos.map((ref) => ({ value: ref, label: `${ref}: ${lower(templateOf(ref).says)}${headLabel(heads.get(ref))}`, selected: ref === at })),
176184 ];
177185 }
178186
@@ -221,7 +229,7 @@ function formView(
221229 plan: Html | null,
222230 reads: Reads,
223231 ): Html {
224 const { full, quota, repos, crew, templates, recipes } = reads;
232 const { full, quota, repos, crew, templates, heads, recipes } = reads;
225233 if (full)
226234 return html`<div class="narrow-wide" data-forges>
227235 ${pageHead("New forge")}
@@ -304,7 +312,7 @@ function formView(
304312 ${modeRows(values, errors["modes"])}
305313 <fieldset class="field" id="f-template" aria-describedby="f-template-hint${errors["template"] ? " f-template-err" : ""}" ${errors["template"] ? html`data-invalid` : null}>
306314 <legend>Template</legend>
307 ${templateOptions(values.template, templates).map(
315 ${templateOptions(values.template, templates, heads).map(
308316 (o) => html`<label class="check">
309317 <input type="radio" name="template" value="${o.value}" ${o.selected ? html`checked` : null} />
310318 <span>${o.label}</span>
@@ -646,11 +654,11 @@ function askedTemplate(ctx: Ctx): string {
646654 const unaskedStarter = (budget: string, key: string, starter: string): boolean => key === "" && budget === starter;
647655
648656 // GET /forges/new — any signed-in person, or a stranger (agents are refused).
649 export function newForgePage(ctx: Ctx): Response {
657 export async function newForgePage(ctx: Ctx): Promise<Response> {
650658 const user = ctx.auth.user;
651659 if (user && user.kind !== "user") return notFoundPage(ctx);
652660 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
653 const reads = readsFor(ctx, user);
661 const reads = await readsFor(ctx, user);
654662 const rendering = performance.now();
655663 // A code in the address moves to a cookie and out of the address (the log and history never hold
656664 // it).
@@ -709,7 +717,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
709717 if (kept === undefined || !kept.ok) {
710718 const refusal = kept === undefined ? { field: "recipe", reason: "sign in to save a recipe" } : kept.error;
711719 const errors: Errors = { [refusal.field === "apps" ? "modes" : refusal.field]: plainError(refusal.reason) };
712 return page({ ctx, title: "New forge", body: formView(ctx, user, values, errors, null, readsFor(ctx, user)) }, 422);
720 return page({ ctx, title: "New forge", body: formView(ctx, user, values, errors, null, await readsFor(ctx, user)) }, 422);
713721 }
714722 saved = kept.value.name;
715723 }
@@ -742,7 +750,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
742750 }, { page: true });
743751 if (door.status === 404 && door.body["error"] === "unknown_template")
744752 return page(
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)) },
753 { 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)), await readsFor(ctx, user)) },
746754 404,
747755 );
748756 if (door.status >= 400) {
@@ -751,7 +759,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
751759 ctx,
752760 title: "New forge",
753761 keyboardResizes: true,
754 body: formView(ctx, user, values, errorsOf(door), null, readsFor(ctx, user)),
762 body: formView(ctx, user, values, errorsOf(door), null, await readsFor(ctx, user)),
755763 },
756764 door.status === 422 ? 422 : door.status,
757765 );
@@ -770,7 +778,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
770778 values,
771779 {},
772780 html`${saved === undefined ? null : html`<p class="small" role="status" id="saved">Saved as <b>${saved}</b>.</p>`}${planView(ctx, user, values, door.body)}`,
773 readsFor(ctx, user),
781 await readsFor(ctx, user),
774782 ),
775783 });
776784 noteForgeMade(ctx);
src/web/pages/templates.ts +4 −3
@@ -13,7 +13,8 @@ import { HOLDS_BLANK, HOLDS_NONE, holdsRows, templateHolds, type TemplateHolds }
1313 import { filterTemplates, TEMPLATES_EMPTY, noRepoTemplates, TEMPLATES_EMPTY_ADMIN, TEMPLATES_QUERY_MAX, templateList, type TemplateRow } from "../../spawn/template_list.ts";
1414 import { withReadmeSays } from "../../spawn/template_says.ts";
1515 import { templateUse, useWords, type TemplateUse } from "../../spawn/template_use.ts";
16 import { NO_CHANGES_YET, templateRecency } from "../../spawn/template_recent.ts";
16 import { NO_CHANGES_YET } from "../../spawn/template_recent.ts";
17 import { headWords, templateHeads } from "../../spawn/template_head.ts";
1718 import { json } from "../../http/respond.ts";
1819 import { EDGE_VARY, sharedCache } from "../../http/edge_cache.ts";
1920 import { pageHead } from "../chrome.ts";
@@ -55,7 +56,7 @@ function thumb(r: TemplateRow, src: string | undefined): Html {
5556 */
5657 function sentence(id: string, used: ReadonlyMap<string, TemplateUse> | undefined, recent: ReadonlyMap<string, string> | undefined): Html | null {
5758 const at = recent?.get(id);
58 const parts: (string | Html)[] = [...(used === undefined ? [] : [useWords(used.get(id))]), ...(recent === undefined || !id.includes("/") ? [] : [at === undefined ? NO_CHANGES_YET : html`updated ${time(at)}`])];
59 const parts: (string | Html)[] = [...(used === undefined ? [] : [useWords(used.get(id))]), ...(recent === undefined || !id.includes("/") ? [] : [at === undefined ? NO_CHANGES_YET : html`${headWords(at, time)}`])];
outdated

Principle 8/5: a new stale bold class is hand-rolled markup. Use the muted text already in the sentence, or add and document the class in docs/design/areas/templates.md.

5960 return parts.length === 0 ? null : html`<p class="small muted">${parts.map((p, i) => (i === 0 ? p : html` · ${p}`))}</p>`;
6061 }
6162
@@ -87,7 +88,7 @@ export async function templatesPage(ctx: Ctx): Promise<Response> {
8788 const rows = filterTemplates(all, q);
8889 const held = new Map<string, TemplateHolds | undefined>();
8990 await Promise.all(rows.map(async (r) => held.set(r.id, await templateHolds(ctx.app, r.id))));
90 const recent = templateRecency(ctx.app.db, rows.map((r) => r.id));
91 const recent = await timePhase(ctx.request, "heads", () => templateHeads(ctx.app, rows.map((r) => r.id)));
9192 const pictures = timePhase(ctx.request, "pictures", () => templatePictures(ctx, rows.map((r) => r.id)));
9293 return timePhase(ctx.request, "render", () =>
9394 page({
test/template-head.test.ts added +131
@@ -0,0 +1,131 @@
1 /**
2 * Each template offered on /templates and in New forge says `updated <date>` from its repository's
3 * head commit, says `stale` past 180 days, and the read is held for 60 s (#15983).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { createRepo } from "../src/core/repos.ts";
12 import { createUser, getUserByName } from "../src/core/users.ts";
13 import { createForgeApp } from "../src/tui/forge.ts";
14 import { templatesScreen } from "../src/tui/screens/templates.ts";
15 import { headlessTerminal } from "../src/tui/term/terminal.ts";
16 import { settleApp } from "./helpers/tui.ts";
17 import { expectWork, gitSpawns } from "./helpers/work.ts";
18 import { repoDir } from "../src/git/repos.ts";
19 import { HEAD_TTL_MS, isStale, templateHeads } from "../src/spawn/template_head.ts";
20
21 let dir: string;
22 let app: App;
23 let servers: Servers;
24
25 const day = 86_400_000;
26 const fresh = new Date(Date.now() - 3 * day).toISOString().slice(0, 19) + "Z";
27 const old = new Date(Date.now() - 400 * day).toISOString().slice(0, 19) + "Z";
28
29 /** Make a commit with no files dated `at` and point the repository's main at it. */
30 async function commitAt(name: string, at: string): Promise<void> {
31 const cwd = repoDir(app.reposRoot, "tess", name);
32 const who = { GIT_COMMITTER_DATE: at, GIT_AUTHOR_DATE: at, GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@x", GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@x" };
33 const empty = (await Bun.$`git hash-object -t tree /dev/null`.cwd(cwd).text()).trim();
34 const oid = (await Bun.$`git commit-tree ${empty} -m seed`.cwd(cwd).env({ PATH: process.env["PATH"] ?? "", ...who }).text()).trim();
35 await Bun.$`git update-ref refs/heads/main ${oid}`.cwd(cwd);
36 }
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-tplhead-"));
40 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
41 servers = await serve(app);
42 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "tess", email: "[email protected]", password: "a-good-passphrase" });
43 if (!made.ok) throw new Error(made.error);
44 for (const [name, at] of [["fresh-kit", fresh], ["old-kit", old]] as const) {
45 const r = await createRepo(app.db, app.reposRoot, { ownerId: made.value.id, name, visibility: "public", description: name, defaultBranch: "main" });
46 if (!r.ok) throw new Error(r.error);
47 app.db.query("UPDATE repo SET is_template = 1 WHERE name = ?1").run(name);
48 await commitAt(name, at);
49 }
50 }, 30_000);
51
52 afterAll(async () => {
53 servers.stop();
54 app.close();
55 await rm(dir, { recursive: true, force: true });
56 });
57
58 test("/templates says updated <date> for each, and stale only for the old one", async () => {
59 const text = await (await fetch(`${servers.url}/templates`)).text();
60 const row = (id: string) => text.split(`data-template="${id}"`)[1]!.split("</li>")[0]!;
61 expect(row("tess/fresh-kit")).toMatch(/updated <time datetime="[^"]+"[^>]*>3d ago<\/time/);
62 expect(row("tess/fresh-kit")).not.toContain("stale");
63 expect(row("tess/old-kit")).toMatch(/updated <time datetime="[^"]+"/);
64 expect(row("tess/old-kit")).toContain("stale");
65 });
66
67 test("the New forge picker carries the same lines", async () => {
68 const text = await (await fetch(`${servers.url}/forges/new`)).text();
69 const label = (id: string) => text.split(`value="${id}"`)[1]!.split("</label>")[0]!;
70 expect(label("tess/fresh-kit")).toContain("updated 3d ago");
71 expect(label("tess/fresh-kit")).not.toContain("stale");
72 expect(label("tess/old-kit")).toContain("updated 1y ago");
73 expect(label("tess/old-kit")).toContain("stale");
74 });
75
76 test("a read is held 60 s, then read again", async () => {
77 const t0 = Date.now() + 10 * HEAD_TTL_MS;
78 const first = await templateHeads(app, ["tess/fresh-kit", "starter"], t0);
79 expect([...first.keys()]).toEqual(["tess/fresh-kit"]);
80 await commitAt("fresh-kit", old);
81 expect((await templateHeads(app, ["tess/fresh-kit"], t0 + HEAD_TTL_MS - 1)).get("tess/fresh-kit")).toBe(first.get("tess/fresh-kit")!);
82 expect((await templateHeads(app, ["tess/fresh-kit"], t0 + HEAD_TTL_MS)).get("tess/fresh-kit")!.slice(0, 10)).toBe(old.slice(0, 10));
83 });
84
85 test("stale is over 180 days, not at it", () => {
86 const now = Date.parse("2026-11-23T00:00:00Z");
87 expect(isStale("2026-05-26T00:00:00Z", now)).toBe(true);
88 expect(isStale("2026-05-27T00:00:00Z", now)).toBe(false);
89 });
90
91 test("callers during a cold read share one read; a read result is held", async () => {
92 const t0 = Date.now() + 50 * HEAD_TTL_MS;
93 const ids = ["tess/fresh-kit", "tess/old-kit", "tess/no-such-kit"];
94 let all: Map<string, string>[] = [];
95 // Twenty callers at once: one git read per repository that exists, not twenty.
96 expect(await gitSpawns(async () => void (all = await Promise.all(Array.from({ length: 20 }, () => templateHeads(app, ids, t0)))))).toBe(2);
97 for (const m of all) expect([...m.keys()].sort()).toEqual(["tess/fresh-kit", "tess/old-kit"]);
98 expect(await gitSpawns(async () => void (await templateHeads(app, ids, t0 + 1)))).toBe(0);
99 });
100
101 test("a zero wait returns no unread heads; warm pages read only the cache", async () => {
102 const t0 = Date.now() + 100 * HEAD_TTL_MS;
103 const none = await templateHeads(app, ["tess/fresh-kit", "tess/old-kit"], t0, 0);
104 expect(none.size).toBe(0);
105 // Let the reads land, then the warm pages spawn no git.
106 expect((await templateHeads(app, ["tess/fresh-kit", "tess/old-kit"], t0)).size).toBe(2);
107 for (const path of ["/forges/new", "/templates"]) {
108 await (await fetch(`${servers.url}${path}`)).text();
109 let status = 0;
110 const git = await gitSpawns(async () => {
111 const res = await fetch(`${servers.url}${path}`);
112 await res.text();
113 status = res.status;
114 });
115 expect(status).toBe(200);
116 expectWork(git, { max: 0 });
117 }
118 });
119
120 test("the terminal's templates screen shows the head line once the read lands", async () => {
121 const user = getUserByName(app.db, "tess")!;
122 const { app: tui, session } = createForgeApp(app, { sshUsername: "tess", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, { terminal: headlessTerminal(120, 40), exitHooks: false });
123 tui.start();
124 const screen = templatesScreen(session, tui.ctx);
125 tui.ctx.push(screen);
126 await settleApp(tui);
127 for (const k of ["/", ..."old-kit", "enter"]) screen.key({ type: "key", key: k, ctrl: false, alt: false, shift: false });
128 await settleApp(tui);
129 expect(tui.screen.toText()).toMatch(/updated 1y ago · stale/);
130 tui.stop?.();
131 });
test/templates-alive.test.ts +17 −21
@@ -1,5 +1,6 @@
11 /**
2 * /templates says when a template repository last landed a change, or that it has none (#14492).
2 * /templates says when a template repository's head commit was made, or that it has none (#14492,
3 * #15983).
34 */
45 import { afterAll, beforeAll, expect, test } from "bun:test";
56 import { mkdtemp, rm } from "node:fs/promises";
@@ -8,9 +9,9 @@ import { join } from "node:path";
89 import { createApp, type App } from "../src/app.ts";
910 import { serve, type Servers } from "../src/http/server.ts";
1011 import { createRepo } from "../src/core/repos.ts";
11 import { createIssue } from "../src/core/issues.ts";
12 import { repoDir } from "../src/git/repos.ts";
13 import { NO_CHANGES_YET } from "../src/spawn/template_recent.ts";
1214 import { createUser } from "../src/core/users.ts";
13 import { NO_CHANGES_YET, templateRecency } from "../src/spawn/template_recent.ts";
1415 import type { TemplateRow } from "../src/spawn/template_list.ts";
1516 import { templateRows } from "../src/web/pages/templates.ts";
1617
@@ -29,12 +30,12 @@ beforeAll(async () => {
2930 if (!r.ok) throw new Error(r.error);
3031 app.db.query("UPDATE repo SET is_template = 1 WHERE name = ?1").run(name);
3132 if (name !== "lively-kit") continue;
32 const when = [new Date(Date.now() - 10 * 86400_000), new Date(Date.now() - 3 * 86400_000 - 3600_000)];
33 for (const at of when) {
34 const issue = createIssue(app.db, { repoId: r.value.id, authorId: made.value.id, title: "change", kind: "pull" });
35 if (!issue.ok) throw new Error(issue.error);
36 app.db.query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', 'b', '', '', ?2)`).run(issue.value.id, at.toISOString());
37 }
33 const cwd = repoDir(app.reposRoot, "tess", name);
34 const at = new Date(Date.now() - 3 * 86400_000).toISOString().slice(0, 19) + "Z";
35 const who = { PATH: process.env["PATH"] ?? "", GIT_COMMITTER_DATE: at, GIT_AUTHOR_DATE: at, GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@x", GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@x" };
36 const empty = (await Bun.$`git hash-object -t tree /dev/null`.cwd(cwd).text()).trim();
37 const oid = (await Bun.$`git commit-tree ${empty} -m seed`.cwd(cwd).env(who).text()).trim();
38 await Bun.$`git update-ref refs/heads/main ${oid}`.cwd(cwd);
3839 }
3940 }, 30_000);
4041
@@ -44,15 +45,6 @@ afterAll(async () => {
4445 await rm(dir, { recursive: true, force: true });
4546 });
4647
47 test("a template with history says when it last changed; one without says so", async () => {
48 const text = await (await fetch(`${servers.url}/templates`)).text();
49 const row = (id: string) => text.split(`data-template="${id}"`)[1]!.split("</li>")[0]!;
50 expect(row("tess/lively-kit")).toMatch(/updated <time datetime="[^"]+" title="[^"]+ UTC"\s*>3d ago<\/time/);
51 expect(row("tess/quiet-kit")).toContain(NO_CHANGES_YET);
52 expect(row("tess/quiet-kit")).not.toContain("1970");
53 expect(row("starter")).not.toContain("no changes yet");
54 });
55
5648 test("recency renders from `recent` alone, and not at all when it is not passed (the 404 listing)", () => {
5749 const rows: TemplateRow[] = [{ id: "tess/lively-kit", title: "Lively", says: "x" }, { id: "starter", title: "Starter", says: "y" }];
5850 const recent = new Map([["tess/lively-kit", "2026-11-17T00:00:00Z"]]);
@@ -62,7 +54,11 @@ test("recency renders from `recent` alone, and not at all when it is not passed
6254 expect(String(templateRows(rows))).not.toContain("updated");
6355 });
6456
65 test("one grouped read answers for many templates", () => {
66 const got = templateRecency(app.db, ["tess/lively-kit", "tess/quiet-kit", "starter", "nobody/none"]);
67 expect([...got.keys()]).toEqual(["tess/lively-kit"]);
57 test("a template with history says when it last changed; one without says so; a built-in says nothing", async () => {
58 const text = await (await fetch(`${servers.url}/templates`)).text();
59 const row = (id: string) => text.split(`data-template="${id}"`)[1]!.split("</li>")[0]!;
60 expect(row("tess/lively-kit")).toMatch(/updated <time datetime="[^"]+" title="[^"]+ UTC"\s*>3d ago<\/time/);
61 expect(row("tess/quiet-kit")).toContain(NO_CHANGES_YET);
62 expect(row("tess/quiet-kit")).not.toContain("1970");
63 expect(row("starter")).not.toContain(NO_CHANGES_YET);
6864 });
test/timers-named.test.ts +1
@@ -85,6 +85,7 @@ const ALLOWED: readonly Allowed[] = [
8585 ]),
8686 ...allow("setTimeout", `a shell session's resize debounce, ${PER_CONNECTION}`, [["src/machines/shell.ts", "() => session.size === resize"]]),
8787 ...allow("setTimeout", "the fork-offers list's size budget: one per page render, cleared when the render ends, resolves a promise and runs nothing", [["src/git/offer_size.ts", "done"]]),
88 ...allow("setTimeout", "the template-head wait's bound: one per page render, cleared when the reads land or the bound passes, resolves a promise and runs nothing", [["src/spawn/template_head.ts", "done"]]),
8889 ...allow("setTimeout", `an openai runner bash call's kill deadline, ${PER_CONNECTION}`, [["src/crew/openai_runner.ts", "() => { timedOut = true"]]),
8990 ...allow("setTimeout", SLEEP, [["src/crew/openai_runner.ts", "r"]]),
9091 ...allow("setTimeout", `a check.txt wait's deadline, ${PER_CONNECTION}`, [["src/http/check_text.ts", "() => changed.resolve()"]]),

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs