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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15983-the-template-picker-on-new-forge-remembe → main 0 commits fork 3 threads · 3 unresolved
9 files
changed +302
−73
docs/features/template-recency.md +4 −2
| @@ -4,6 +4,8 @@ row: See when a template repository last changed | ||
| 4 | 4 | --- |
| 5 | 5 | # Template recency |
| 6 | 6 | |
| 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. | |
| 8 | 8 | |
| 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 | /** | |
| 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 @@ | ||
| 1 | 1 | /** |
| 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. | |
| 5 | 4 | */ |
| 6 | 5 | |
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | ||
| 9 | /** What a repository template with no landed pull says in place of its recency. */ | |
| 10 | 6 | 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"; | ||
| 14 | 14 | import { listChildrenNow } from "../../actions/spawn.ts"; |
| 15 | 15 | import { withReadmeSays } from "../../spawn/template_says.ts"; |
| 16 | 16 | 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"; | |
| 18 | 19 | import { timeAgo } from "../../web/time_element.ts"; |
| 19 | 20 | import { newForgeScreen } from "./newforge.ts"; |
| 20 | 21 | import { templatePreviewScreen } from "./template_preview.ts"; |
| 21 | 22 | |
| 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("")); | |
| 24 | 25 | |
| 25 | 26 | export function templatesScreen(session: Session, ctx: Ctx): Screen { |
| 26 | 27 | let at = 0; |
| 27 | 28 | let q = ""; |
| 28 | 29 | 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. | |
| 30 | 31 | 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 | }); | |
| 32 | 38 | // Each repository template's README sentence arrives after the first paint, then stays. |
| 33 | 39 | let listed = templateList(session.app.db, session.user, used); |
| 34 | 40 | void withReadmeSays(session.app, listed).then((r) => { |
| @@ -50,7 +56,7 @@ export function templatesScreen(session: Session, ctx: Ctx): Screen { | ||
| 50 | 56 | const on = i === at; |
| 51 | 57 | 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); |
| 52 | 58 | 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); | |
| 54 | 60 | }); |
| 55 | 61 | if (q === "" && noRepoTemplates(listed) && y + 1 < area.y + area.h) { |
| 56 | 62 | 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"; | ||
| 41 | 41 | import { field, readForm, type Form } from "../form.ts"; |
| 42 | 42 | import { templateListUnsorted } from "../../spawn/template_list.ts"; |
| 43 | 43 | import { templateRows } from "./templates.ts"; |
| 44 | import { headWords, templateHeads } from "../../spawn/template_head.ts"; | |
| 44 | 45 | import { html, type Html } from "../html.ts"; |
| 46 | import { timeAgo } from "../time_element.ts"; | |
| 45 | 47 | import { noteForgeMade } from "../funnel_door.ts"; |
| 46 | 48 | import { page } from "../layout.ts"; |
| 47 | 49 | import { linkToSend, madeBody, madeJs } from "../forge_made.ts"; |
| @@ -123,13 +125,15 @@ interface Reads { | ||
| 123 | 125 | /** Repositories marked as templates that the viewer can read (`full_name`), listed in the |
| 124 | 126 | * Template select. */ |
| 125 | 127 | readonly templates: readonly string[]; |
| 128 | /** Each repository template's head commit date (ISO), when git could say. */ | |
| 129 | readonly heads: ReadonlyMap<string, string>; | |
| 126 | 130 | /** The signed-in person's saved recipes (`spawn/recipes.ts`). */ |
| 127 | 131 | readonly recipes: readonly Recipe[]; |
| 128 | 132 | } |
| 129 | 133 | |
| 130 | function readsFor(ctx: Ctx, user: User | undefined): Reads { | |
| 134 | async function readsFor(ctx: Ctx, user: User | undefined): Promise<Reads> { | |
| 131 | 135 | 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: [] }; | |
| 133 | 137 | const quota = quotaFull(ctx.app.config.dataDir); |
| 134 | 138 | // Each repository once, as its source, and public only; a stranger sees |
| 135 | 139 | // 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 { | ||
| 144 | 148 | listReposVisibleTo(ctx.app.db, user, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`), |
| 145 | 149 | ); |
| 146 | 150 | 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 }; | |
| 148 | 153 | } |
| 149 | 154 | |
| 150 | 155 | /** 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?: | ||
| 160 | 165 | })); |
| 161 | 166 | } |
| 162 | 167 | |
| 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 | ||
| 163 | 171 | /** |
| 164 | 172 | * The templates in order, Blank first; the one asked for chosen (Blank when it is not one of them). |
| 165 | 173 | */ |
| 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 }[] { | |
| 167 | 175 | const known = TEMPLATES.some((t) => t.id === chosen) || repos.includes(chosen); |
| 168 | 176 | const at = known ? chosen : DEFAULT_TEMPLATE; |
| 169 | 177 | return [ |
| @@ -172,7 +180,7 @@ function templateOptions(chosen: string, repos: readonly string[]): { value: str | ||
| 172 | 180 | label: `${t.title}: ${lower(t.says)}`, |
| 173 | 181 | selected: t.id === at, |
| 174 | 182 | })), |
| 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 })), | |
| 176 | 184 | ]; |
| 177 | 185 | } |
| 178 | 186 | |
| @@ -221,7 +229,7 @@ function formView( | ||
| 221 | 229 | plan: Html | null, |
| 222 | 230 | reads: Reads, |
| 223 | 231 | ): Html { |
| 224 | const { full, quota, repos, crew, templates, recipes } = reads; | |
| 232 | const { full, quota, repos, crew, templates, heads, recipes } = reads; | |
| 225 | 233 | if (full) |
| 226 | 234 | return html`<div class="narrow-wide" data-forges> |
| 227 | 235 | ${pageHead("New forge")} |
| @@ -304,7 +312,7 @@ function formView( | ||
| 304 | 312 | ${modeRows(values, errors["modes"])} |
| 305 | 313 | <fieldset class="field" id="f-template" aria-describedby="f-template-hint${errors["template"] ? " f-template-err" : ""}" ${errors["template"] ? html`data-invalid` : null}> |
| 306 | 314 | <legend>Template</legend> |
| 307 | ${templateOptions(values.template, templates).map( | |
| 315 | ${templateOptions(values.template, templates, heads).map( | |
| 308 | 316 | (o) => html`<label class="check"> |
| 309 | 317 | <input type="radio" name="template" value="${o.value}" ${o.selected ? html`checked` : null} /> |
| 310 | 318 | <span>${o.label}</span> |
| @@ -646,11 +654,11 @@ function askedTemplate(ctx: Ctx): string { | ||
| 646 | 654 | const unaskedStarter = (budget: string, key: string, starter: string): boolean => key === "" && budget === starter; |
| 647 | 655 | |
| 648 | 656 | // 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> { | |
| 650 | 658 | const user = ctx.auth.user; |
| 651 | 659 | if (user && user.kind !== "user") return notFoundPage(ctx); |
| 652 | 660 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 653 | const reads = readsFor(ctx, user); | |
| 661 | const reads = await readsFor(ctx, user); | |
| 654 | 662 | const rendering = performance.now(); |
| 655 | 663 | // A code in the address moves to a cookie and out of the address (the log and history never hold |
| 656 | 664 | // it). |
| @@ -709,7 +717,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> { | ||
| 709 | 717 | if (kept === undefined || !kept.ok) { |
| 710 | 718 | const refusal = kept === undefined ? { field: "recipe", reason: "sign in to save a recipe" } : kept.error; |
| 711 | 719 | 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); | |
| 713 | 721 | } |
| 714 | 722 | saved = kept.value.name; |
| 715 | 723 | } |
| @@ -742,7 +750,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> { | ||
| 742 | 750 | }, { page: true }); |
| 743 | 751 | if (door.status === 404 && door.body["error"] === "unknown_template") |
| 744 | 752 | 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)) }, | |
| 746 | 754 | 404, |
| 747 | 755 | ); |
| 748 | 756 | if (door.status >= 400) { |
| @@ -751,7 +759,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> { | ||
| 751 | 759 | ctx, |
| 752 | 760 | title: "New forge", |
| 753 | 761 | 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)), | |
| 755 | 763 | }, |
| 756 | 764 | door.status === 422 ? 422 : door.status, |
| 757 | 765 | ); |
| @@ -770,7 +778,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> { | ||
| 770 | 778 | values, |
| 771 | 779 | {}, |
| 772 | 780 | 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), | |
| 774 | 782 | ), |
| 775 | 783 | }); |
| 776 | 784 | noteForgeMade(ctx); |
src/web/pages/templates.ts +4 −3
| @@ -13,7 +13,8 @@ import { HOLDS_BLANK, HOLDS_NONE, holdsRows, templateHolds, type TemplateHolds } | ||
| 13 | 13 | import { filterTemplates, TEMPLATES_EMPTY, noRepoTemplates, TEMPLATES_EMPTY_ADMIN, TEMPLATES_QUERY_MAX, templateList, type TemplateRow } from "../../spawn/template_list.ts"; |
| 14 | 14 | import { withReadmeSays } from "../../spawn/template_says.ts"; |
| 15 | 15 | 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"; | |
| 17 | 18 | import { json } from "../../http/respond.ts"; |
| 18 | 19 | import { EDGE_VARY, sharedCache } from "../../http/edge_cache.ts"; |
| 19 | 20 | import { pageHead } from "../chrome.ts"; |
| @@ -55,7 +56,7 @@ function thumb(r: TemplateRow, src: string | undefined): Html { | ||
| 55 | 56 | */ |
| 56 | 57 | function sentence(id: string, used: ReadonlyMap<string, TemplateUse> | undefined, recent: ReadonlyMap<string, string> | undefined): Html | null { |
| 57 | 58 | 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 |
||
| 59 | 60 | return parts.length === 0 ? null : html`<p class="small muted">${parts.map((p, i) => (i === 0 ? p : html` · ${p}`))}</p>`; |
| 60 | 61 | } |
| 61 | 62 | |
| @@ -87,7 +88,7 @@ export async function templatesPage(ctx: Ctx): Promise<Response> { | ||
| 87 | 88 | const rows = filterTemplates(all, q); |
| 88 | 89 | const held = new Map<string, TemplateHolds | undefined>(); |
| 89 | 90 | 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))); | |
| 91 | 92 | const pictures = timePhase(ctx.request, "pictures", () => templatePictures(ctx, rows.map((r) => r.id))); |
| 92 | 93 | return timePhase(ctx.request, "render", () => |
| 93 | 94 | 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 @@ | ||
| 1 | 1 | /** |
| 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). | |
| 3 | 4 | */ |
| 4 | 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 5 | 6 | import { mkdtemp, rm } from "node:fs/promises"; |
| @@ -8,9 +9,9 @@ import { join } from "node:path"; | ||
| 8 | 9 | import { createApp, type App } from "../src/app.ts"; |
| 9 | 10 | import { serve, type Servers } from "../src/http/server.ts"; |
| 10 | 11 | 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"; | |
| 12 | 14 | import { createUser } from "../src/core/users.ts"; |
| 13 | import { NO_CHANGES_YET, templateRecency } from "../src/spawn/template_recent.ts"; | |
| 14 | 15 | import type { TemplateRow } from "../src/spawn/template_list.ts"; |
| 15 | 16 | import { templateRows } from "../src/web/pages/templates.ts"; |
| 16 | 17 | |
| @@ -29,12 +30,12 @@ beforeAll(async () => { | ||
| 29 | 30 | if (!r.ok) throw new Error(r.error); |
| 30 | 31 | app.db.query("UPDATE repo SET is_template = 1 WHERE name = ?1").run(name); |
| 31 | 32 | 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); | |
| 38 | 39 | } |
| 39 | 40 | }, 30_000); |
| 40 | 41 | |
| @@ -44,15 +45,6 @@ afterAll(async () => { | ||
| 44 | 45 | await rm(dir, { recursive: true, force: true }); |
| 45 | 46 | }); |
| 46 | 47 | |
| 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 | ||
| 56 | 48 | test("recency renders from `recent` alone, and not at all when it is not passed (the 404 listing)", () => { |
| 57 | 49 | const rows: TemplateRow[] = [{ id: "tess/lively-kit", title: "Lively", says: "x" }, { id: "starter", title: "Starter", says: "y" }]; |
| 58 | 50 | 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 | ||
| 62 | 54 | expect(String(templateRows(rows))).not.toContain("updated"); |
| 63 | 55 | }); |
| 64 | 56 | |
| 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); | |
| 68 | 64 | }); |
test/timers-named.test.ts +1
| @@ -85,6 +85,7 @@ const ALLOWED: readonly Allowed[] = [ | ||
| 85 | 85 | ]), |
| 86 | 86 | ...allow("setTimeout", `a shell session's resize debounce, ${PER_CONNECTION}`, [["src/machines/shell.ts", "() => session.size === resize"]]), |
| 87 | 87 | ...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"]]), | |
| 88 | 89 | ...allow("setTimeout", `an openai runner bash call's kill deadline, ${PER_CONNECTION}`, [["src/crew/openai_runner.ts", "() => { timedOut = true"]]), |
| 89 | 90 | ...allow("setTimeout", SLEEP, [["src/crew/openai_runner.ts", "r"]]), |
| 90 | 91 | ...allow("setTimeout", `a check.txt wait's deadline, ${PER_CONNECTION}`, [["src/http/check_text.ts", "() => changed.resolve()"]]), |
new above
offline
The terminal screen needs to read this too (both doors). Also add a docs/features entry.