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

/templates.json lists each template: name, one-line description, start count and last change #14734

Merged opened this

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

Merged

torque/forge:torque/14719-templates-json-lists-each-template-name → main 9 commits fork 2 threads · 2 unresolved

  • Merged. torque/14719-templates-json-lists-each-template-name was merged into main as 9cf0688.

Review

Sign in to review this change.
9 files changed +118 −3
docs/features/templates-json.md added +9
@@ -0,0 +1,9 @@
1 ---
2 topic: Agents: MCP, git, or the terminal
3 row: templates.json: choose a template without parsing HTML
4 ---
5 # templates.json: choose a template without parsing HTML
6
7 An agent that makes a forge for a client reads `GET /templates.json`. It lists the same templates as `/templates`, in the same order and with the same words. Each entry is `{id, name, description, starts, lastChange}`. `starts` is how many forges were started from it. `lastChange` is when the newest of those began (ISO 8601, UTC), or `null` when no start has a date (never started, or its records carry none). Descriptions are plain text.
8
9 It is public by the page's rule: a signed-out reader sees the built-in templates and the public template repositories, and a signed-in reader also sees the ones they can read. `?q=` filters by name or description, as on the page. A signed-out answer is cached like the page. Pass the `id` as `template` when starting a forge.
src/core/reserved.ts +1
@@ -131,6 +131,7 @@ export const SYSTEM_NAMES: readonly string[] = [
131131 "sitemap.xml",
132132 "releases",
133133 "releases.json",
134 "templates.json",
134135 "maintenance.json",
135136 "changelog.atom",
136137 "explore.atom",
src/http/edge_cache.ts +1 −1
@@ -28,7 +28,7 @@ export type IsPublicRepo = (owner: string, name: string) => boolean;
2828 * other path, however it is shaped (`/apps/new`, `/settings/x`), is not shared.
2929 */
3030 export function sharedPath(pathname: string, isPublicRepo: IsPublicRepo): boolean {
31 if (pathname === "/" || pathname === "/explore" || pathname === "/pricing" || pathname === "/templates") return true;
31 if (pathname === "/" || pathname === "/explore" || pathname === "/pricing" || pathname === "/templates" || pathname === "/templates.json") return true;
3232 const m = /^\/([^/]+)\/([^/]+)$/.exec(pathname);
3333 return m !== null && isPublicRepo(m[1]!, m[2]!);
3434 }
src/http/marks/templates.json.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/templates.json",
3 "mark": "open"
4 }
src/http/server.ts +2 −1
@@ -344,7 +344,7 @@ import { startForgeSubmit } from "../web/pages/start-forge.ts";
344344 import { redirect } from "../web/layout.ts";
345345 import { inventoryPage } from "../web/pages/inventory.ts";
346346 import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts";
347 import { templatesPage } from "../web/pages/templates.ts";
347 import { templatesJson, templatesPage } from "../web/pages/templates.ts";
348348 import { askedPage } from "../web/studio/asked_page.ts";
349349 import { notesOverrule, notesSave, notesView } from "../web/pages/notes.ts";
350350 import { reviewPage } from "../web/studio/review_page.ts";
@@ -1008,6 +1008,7 @@ export function buildRouter(): Router<Handler> {
10081008 router.add("GET", "/pricing/resend", resendPage);
10091009 router.add("POST", "/pricing/resend", resendSubmit);
10101010 router.add("GET", "/templates", templatesPage);
1011 router.add("GET", "/templates.json", templatesJson);
10111012 router.add("GET", "/forges/new", newForgePage);
10121013 router.add("POST", "/forges/new", newForgeSubmit);
10131014 router.add("POST", "/forges/start", startForgeSubmit);
src/web/pages/templates.ts +41
@@ -12,6 +12,8 @@ import { DEFAULT_TEMPLATE } from "../../spawn/templates.ts";
1212 import { HOLDS_BLANK, HOLDS_NONE, holdsRows, templateHolds, type TemplateHolds } from "../../spawn/template_holds.ts";
1313 import { filterTemplates, TEMPLATES_QUERY_MAX, templateList, type TemplateRow } from "../../spawn/template_list.ts";
1414 import { templateUse, useWords, type TemplateUse } from "../../spawn/template_use.ts";
15 import { json } from "../../http/respond.ts";
16 import { EDGE_VARY, sharedCache } from "../../http/edge_cache.ts";
1517 import { pageHead } from "../chrome.ts";
1618 import { html, type Html } from "../html.ts";
1719 import { page } from "../layout.ts";
@@ -76,3 +78,42 @@ export async function templatesPage(ctx: Ctx): Promise<Response> {
7678 }),
7779 );
7880 }
81
82 /** One template as an agent reads it: the page's words, as data. */
83 export interface TemplateJson {
84 readonly id: string;
85 readonly name: string;
86 readonly description: string;
87 /** Forges started from it (the spawn records). */
88 readonly starts: number;
outdated

Wrong when a start record has no timestamp: count>0 and newest null (seen on the preview for blank). Say null means no dated start, and test it.

89 /**
90 * When the newest start began, ISO 8601 UTC; null when no start has a date (never started, or its
91 * records carry none).
92 */
93 readonly lastChange: string | null;
94 }
95
96 /** The rows of `/templates`, same order and words, with use. Plain data in, plain data out. */
97 export function templatesJsonBody(rows: readonly TemplateRow[], used: ReadonlyMap<string, TemplateUse>): { templates: TemplateJson[] } {
98 return {
99 templates: rows.map((r) => {
100 const u = used.get(r.id);
101 return { id: r.id, name: r.title, description: r.says, starts: u?.count ?? 0, lastChange: u?.newest == null ? null : new Date(u.newest).toISOString() };
102 }),
103 };
104 }
105
106 /**
107 * GET /templates.json: public by the page's rule (the viewer's readable template repos), cached as
108 * it is.
109 */
110 export async function templatesJson(ctx: Ctx): Promise<Response> {
111 const user = ctx.auth.user;
112 const q = (ctx.url.searchParams.get("q") ?? "").trim().slice(0, TEMPLATES_QUERY_MAX);
113 const rows = filterTemplates(templateList(ctx.app.db, user?.kind === "user" ? user : undefined), q);
114 const used = templateUse(await listChildren(ctx.app));
115 return json(templatesJsonBody(rows, used), 200, {
116 "cache-control": sharedCache(ctx.request, "/templates.json", () => false),
117 vary: EDGE_VARY,
118 });
119 }
test/design-audit.test.ts +1 −1
@@ -17,7 +17,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1717
1818 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
1919 const NOT_PAGES =
20 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|maintenance\.json$|changelog\.atom$|explore\.atom$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
20 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.atom$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
2121
2222 const getRoutes = [
2323 ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g),
test/forge-looks.test.ts +1
@@ -27,6 +27,7 @@ const NOT_A_PAGE: Record<string, string> = {
2727 "/front": "no picture: its slot went to /settings/security/controls, the security controls (#13001); covered by its own tests",
2828 "/pricing": "no picture: not in app.looks; the page is covered by test/pricing-order.test.ts",
2929 "/templates": "no picture: not in app.looks; the page is covered by test/templates-page.test.ts",
30 "/templates.json": "data, not a page: the same rows as /templates; covered by test/templates-json.test.ts",
3031 "/terms": "no picture: not in app.looks; the page is covered by test/terms-page.test.ts",
3132 "/audit": "no picture: its slot went to /pinned; /audit.csv is its download, covered by test/audit.test.ts",
3233 "/deploy-to": "a form for a forge admin that fills from its link; covered by test/pinned-page.test.ts",
test/templates-json.test.ts added +58
@@ -0,0 +1,58 @@
1 /** /templates.json: the rows of /templates as data, same order and words (#14719). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { templatesJsonBody } from "../src/web/pages/templates.ts";
4 import { mkdtemp, rm } from "node:fs/promises";
outdated

Merge the two bun:test imports into one line.

5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9
10 test("two fixed templates give the exact JSON; a never-started one has null", () => {
11 const rows = [
12 { id: "blank", title: "Blank", says: "Only the apps you fork." },
13 { id: "starter", title: "Starter app", says: "A server and a page." },
14 ];
15 const used = new Map([["starter", { count: 3, newest: "2026-11-02T10:00:00Z" }]]);
16 expect(templatesJsonBody(rows, used)).toEqual({
17 templates: [
18 { id: "blank", name: "Blank", description: "Only the apps you fork.", starts: 0, lastChange: null },
19 { id: "starter", name: "Starter app", description: "A server and a page.", starts: 3, lastChange: "2026-11-02T10:00:00.000Z" },
20 ],
21 });
22 });
23
24 test("starts with no dated record: count above zero, lastChange null", () => {
25 const rows = [{ id: "blank", title: "Blank", says: "Only the apps you fork." }];
26 const used = new Map([["blank", { count: 1, newest: null }]]);
27 expect(templatesJsonBody(rows, used).templates[0]).toEqual({ id: "blank", name: "Blank", description: "Only the apps you fork.", starts: 1, lastChange: null });
28 });
29
30 let dir: string;
31 let app: App;
32 let servers: Servers;
33 beforeAll(async () => {
34 dir = await mkdtemp(join(tmpdir(), "forge-templates-json-"));
35 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0, forgeRepo: "alice/forge-code" });
36 servers = await serve(app);
37 }, 30_000);
38 afterAll(async () => {
39 servers.stop();
40 app.close();
41 await rm(dir, { recursive: true, force: true });
42 });
43
44 test("served signed out: same ids and words as the page, plain text, cacheable", async () => {
45 const res = await fetch(`${servers.url}/templates.json`);
46 expect(res.status).toBe(200);
47 expect(res.headers.get("content-type")).toContain("application/json");
48 expect(res.headers.get("cache-control")).toContain("s-maxage");
49 const body = (await res.json()) as { templates: { id: string; name: string; description: string }[] };
50 const page = await (await fetch(`${servers.url}/templates`)).text();
51 expect(body.templates.length).toBeGreaterThan(1);
52 const pageIds = [...page.matchAll(/data-template="([^"]+)"/g)].map((m) => m[1]!);
53 expect(body.templates.map((t) => t.id)).toEqual(pageIds);
54 for (const t of body.templates) {
55 expect(t.description).not.toMatch(/[<>&]/);
56 expect(page).toContain(t.name);
57 }
58 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs