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

A template's page carries a share card and a plain link that starts a forge from it #13619

Merged opened this

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

Merged

scout/forge:scout/13593-a-template-s-page-carries-a-share-card-a → main 9 commits fork 6 threads · 6 unresolved

  • Merged. scout/13593-a-template-s-page-carries-a-share-card-a was merged into main as ed9b072.

Review

Sign in to review this change.
9 files changed +152 −17
docs/features/new-forge-template.md +5 −1
@@ -8,10 +8,14 @@ Code: `src/spawn/templates.ts` (ids and words), `src/spawn/forge_code.ts` (the f
88
99 ## The list: /templates
1010
11 `/templates` lists what a new forge can start from: the built-in templates, then the template repositories you can read. Each row has one sentence and one secondary button, "Start a forge from <name>", which opens `/forges/new?template=<id>` with that template chosen. Signed out works too: a stranger lands on the same form with the template kept. `?template=` is accepted only when spawn accepts it (`parseTemplate`); anything else leaves Blank chosen, and it is never echoed. The plan (`do=plan`) shows "It starts from the <b>…</b> template".
11 `/templates` lists what a new forge can start from: the built-in templates, then the template repositories you can read. Each row has one sentence and one secondary button, "Start a forge", which opens `/forges/new?template=<id>` with that template chosen. Signed out works too: a stranger lands on the same form with the template kept. `?template=` is accepted only when spawn accepts it (`parseTemplate`); anything else leaves Blank chosen, and it is never echoed. The plan (`do=plan`) shows "It starts from the <b>…</b> template".
1212
1313 The terminal has the same list: the "Templates" command (`src/tui/screens/templates.ts`) shows the same rows; Enter on a row opens New forge with that template chosen, for people signed in, and a guest is told to sign in. Both read `templateList` (`src/spawn/template_list.ts`), so a private template repository is listed only to people who can read it, on the page and in the terminal alike.
1414
1515 ### Filtering the list
1616
1717 `/templates?q=star` keeps the rows whose title or id contains the word, case-insensitively; the field keeps its value, `q` is trimmed and capped at 80 characters, and a word that matches nothing says "No template matches that name." with a link to `/templates` that clears it. In the terminal, `/` on the Templates screen types the same filter (Enter or Esc stops typing). Both use `filterTemplates` in `src/spawn/template_list.ts`.
18
19 ## One template's page: /templates/<name>
20
21 `/templates/<id>` (`/templates/starter`, `/templates/owner/name`) is a page to share: Open Graph and Twitter meta (title, the one-line sentence, and the card `/og/template/<id>.png`, `owner~name` for a repository), and one plain link, "Start a forge from <name>", to `/forges/new?template=<id>`. The card is the existing renderer and its cached PNG path, drawn only from what a signed-out reader is offered. A template not listed to the reader, or unknown, answers 404 alike. The terminal's Templates screen prints the same path under the row as "Share:". Code: `templatePage` in `src/web/pages/template.ts`; the id and card-ref pair in `src/spawn/template_list.ts`. Test: `test/template-share.test.ts`.
outdated

Wrong location: templatePage is in src/web/pages/template.ts, not templates.ts. Also name the hidden-template behaviour only once a test proves it.

src/http/server.ts +2
@@ -1579,6 +1579,8 @@ export function buildRouter(): Router<Handler> {
15791579 router.add("GET", "/og/pull/:ref.svg", ogCard("pull"));
15801580 router.add("GET", "/og/run/:ref.svg", ogCard("run"));
15811581 router.add("GET", "/og/map/:ref.svg", ogCard("map"));
1582 router.add("GET", "/og/template/:ref.svg", ogCard("template"));
1583 router.add("GET", "/og/template/:ref.png", ogCard("template", "png"));
15821584 router.add("GET", "/og/audit.svg", ogCard("audit"));
15831585 router.add("GET", "/og/repo/:ref.png", ogCard("repo", "png"));
15841586 router.add("GET", "/og/app/:ref.png", ogCard("app", "png"));
src/spawn/template_list.ts +23 −1
@@ -7,7 +7,7 @@
77 import type { Database } from "bun:sqlite";
88 import { listReposVisibleTo } from "../core/repos.ts";
99 import type { User } from "../core/users.ts";
10 import { TEMPLATES, templateOf } from "./templates.ts";
10 import { DEFAULT_TEMPLATE, TEMPLATES, templateOf } from "./templates.ts";
1111
1212 export interface TemplateRow {
1313 /** What `template` takes in a spawn: a built-in id or `owner/name`. */
@@ -24,6 +24,28 @@ export function templateList(db: Database, viewer: User | undefined): TemplateRo
2424 });
2525 }
2626
27 /** The path of a template's own page: a built-in id, or `owner/name`, as two segments. */
28 export const templatePath = (id: string): string => `/templates/${id}`;
29
30 /**
31 * A template id as a card ref, and back: `owner/name` is `owner~name`, as every other card says it.
32 */
33 export const templateCardRef = (id: string): string => id.replace("/", "~");
34 export const templateIdOfRef = (ref: string): string => ref.replace("~", "/");
35
36 /**
37 * The row for one template id a viewer may see, or nothing: the page and its card read this. A
38 * built-in id is answered without a query; a repository is one list read.
39 */
40 export function templateRow(db: Database, viewer: User | undefined, id: string): TemplateRow | undefined {
41 if (id === DEFAULT_TEMPLATE) return undefined; // the blank forge has no page of its own
42 if (TEMPLATES.some((t) => t.id === id)) {
43 const t = templateOf(id);
44 return { id, title: t.title, says: t.says };
45 }
46 return templateList(db, viewer).find((r) => r.id === id);
47 }
48
2749 export const TEMPLATES_QUERY_MAX = 80;
2850
2951 /** Rows whose title or id contains the query, case-insensitively; an empty query keeps all. */
src/tui/screens/templates.ts +3 −2
@@ -4,7 +4,8 @@
44 * the list and is told the form is for people signed in.
55 */
66
7 import { filterTemplates, TEMPLATES_QUERY_MAX, templateList } from "../../spawn/template_list.ts";
7 import { DEFAULT_TEMPLATE } from "../../spawn/templates.ts";
8 import { filterTemplates, TEMPLATES_QUERY_MAX, templateList, templatePath } from "../../spawn/template_list.ts";
89 import type { Ctx, Screen } from "../app/app.ts";
910 import { binding } from "../app/keys.ts";
1011 import { style } from "../term/style.ts";
@@ -31,7 +32,7 @@ export function templatesScreen(session: Session, ctx: Ctx): Screen {
3132 const on = i === at;
3233 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);
3334 y += 1;
outdated

The new 'Share:' line has no test. Add one in the existing template TUI suite.

34 if (on) for (const line of wrap(r.says, area.w - 6)) if (y < area.y + area.h) s.text(area.x + 5, y++, line, style(c.mutedFg, c.bg), area.x + area.w);
35 if (on) for (const line of [...wrap(r.says, area.w - 6), ...(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);
3536 });
3637 if (session.user === undefined && y < area.y + area.h)
3738 s.text(area.x + 1, y + 1, truncate("Sign in to start a forge from one, or use /templates on the web.", area.w - 2), style(c.mutedFg, c.bg), area.x + area.w);
src/web/pages/og.ts +15 −11
@@ -4,16 +4,14 @@
44 * Public by design — it is what a link preview fetches without a session —
55 * so it says only what an anonymous reader may already see: a public repo
66 * (`owner~name`; any other repo, private or not, is a title and the word
7 * "private", and a signed-in reader who may read it gets the full card), the public app of one (its slug), or an issue, pull or run
8 * of a public repo (`owner~name~number`, `owner~name~runid`) that an
9 * anonymous reader could open (not sealed, runs readable); a public repo's
10 * map (`owner~name`) drawn from only the issues and runs it may see; or the
11 * audit of the public apps. Anything else, or a
12 * ref that is not shaped like one, is the same 404. The ETag is the sha256
13 * of the card's inputs, so a changed repo is a new card and an unchanged
14 * one is a 304. The `.png` twin is the same card rasterized once per input
15 * hash and kept under the data directory; if the rasterizer is unavailable it
16 * answers 503 and nothing else is affected.
7 * "private", and a signed-in reader who may read it gets the full card), the public app of one (its
8 * slug), or an issue, pull or run of a public repo (`owner~name~number`, `owner~name~runid`) that
9 * an anonymous reader could open (not sealed, runs readable); a public repo's map (`owner~name`)
10 * drawn from only the issues and runs it may see; or the audit of the public apps. Anything else,
11 * or a ref that is not shaped like one, is the same 404. The ETag is the sha256 of the card's
12 * inputs, so a changed repo is a new card and an unchanged one is a 304. The `.png` twin is the
13 * same card rasterized once per input hash and kept under the data directory; if the rasterizer is
14 * unavailable it answers 503 and nothing else is affected.
1715 */
1816
1917 import { createHash } from "node:crypto";
@@ -48,6 +46,7 @@ import { auditInput, type AuditRow } from "../og/audit.ts";
4846 import { renderCard, signature, type CardInput } from "../og/card.ts";
4947 import { appImages, embedShots, pullImages } from "../og/looks.ts";
5048 import { mapInput } from "../og/map.ts";
49 import { templateIdOfRef, templateRow } from "../../spawn/template_list.ts";
5150 import { marksFor } from "./map.ts";
5251 import { Busy, pngCache, type PngCache } from "../og/png-cache.ts";
5352 import { drawer } from "../og/raster.ts";
@@ -149,7 +148,7 @@ function waiting(ctx: Ctx, repo: Repo, issue: Issue): string {
149148 return `waits on ${shown.join(", ")}${more > 0 ? ` +${more}` : ""}`;
150149 }
151150
152 export type OgKind = "repo" | "app" | "issue" | "pull" | "run" | "map" | "audit" | "site";
151 export type OgKind = "repo" | "app" | "issue" | "pull" | "run" | "map" | "audit" | "site" | "template";
153152
154153 /** The card for any page without a card of its own: the home page's own words, and where it is. */
155154 function siteCard(ctx: Ctx): CardInput {
@@ -366,6 +365,11 @@ async function resolve(ctx: Ctx, kind: OgKind, ref: string): Promise<CardInput |
366365 if (kind === "audit") return ref === "" ? auditCards(ctx.app).get("", () => auditCardInput(ctx)) : undefined;
367366 if (kind === "site") return ref === "" ? siteCard(ctx) : undefined;
368367 if (kind === "repo") return repoCard(ctx, ref);
368 if (kind === "template") {
369 // Only what an anonymous reader is offered: the card is public and cached.
370 const row = templateRow(db, undefined, templateIdOfRef(ref));
outdated

Hand-rolled ref.replace('~','/') duplicates templateCardRef. Keep one id<->ref pair in template_list.ts. This branch has no test (png route, owner/name, hidden template).

371 return row && { kind: "page", title: `${row.title} template`, lines: [row.says], stat: "Start a forge from it" };
372 }
369373 // An app's card is addressed by its repository, never by the slug the
370374 // platform runs it under; the slug form stays so cards already shared answer.
371375 const [owner, name, extra] = ref.split("~");
src/web/pages/template.ts +11 −2
@@ -15,6 +15,8 @@ import { DEFAULT_TEMPLATE, TEMPLATES } from "../../spawn/templates.ts";
1515 import { notFoundPage, pageHead } from "../chrome.ts";
1616 import { html } from "../html.ts";
1717 import { page } from "../layout.ts";
18 import { templateCardRef, templateRow } from "../../spawn/template_list.ts";
19 import { btn } from "../ui.ts";
1820 import { statusRow } from "./security.ts";
1921
2022 // GET /templates/:name (built-in) and /templates/:owner/:name
@@ -28,12 +30,19 @@ export async function templatePage(ctx: Ctx): Promise<Response> {
2830 if (!view) return notFoundPage(ctx);
2931 return timePhase(ctx.request, "render", () => {
3032 const line = templateTimingLine(ctx.app.db, ref);
33 const user = ctx.auth.user?.kind === "user" ? ctx.auth.user : undefined;
34 // What a signed-out reader is offered carries the card; only otherwise is the viewer's own list
35 // read.
outdated

Two full templateList queries per request. Look up once and derive the anonymous check only when needed.

36 const shared = templateRow(ctx.app.db, undefined, ref);
37 const row = shared ?? (user === undefined ? undefined : templateRow(ctx.app.db, user, ref));
3138 return page({
3239 ctx,
33 title: view.title,
34 ...(built ? { description: view.about } : {}),
40 title: built && row ? `${row.title} template` : view.title,
41 ...(built ? { description: row?.says ?? view.about } : {}),
42 ...(shared !== undefined ? { ogImage: `/og/template/${templateCardRef(ref)}.png` } : {}),
3543 body: html`${pageHead(view.title, { sub: view.about !== "" ? view.about : "The files a forge starts with." })}
outdated

Principle 1: the button and the next paragraph both say what the page is for. Say it once.

3644 <section>
45 ${row ? html`<p>${btn("Start a forge", { variant: "primary", href: `/forges/new?template=${encodeURIComponent(ref)}` })}</p>` : null}
3746 ${built ? null : html`<p>A forge started from this template begins with these files.</p>`}
3847 ${built
3948 ? null
test/pages-budget.test.ts +2
@@ -77,6 +77,8 @@ const FIXTURE: Record<string, string> = {
7777 "/api/v1/admin/machines/:machine/disks": "/api/v1/admin/machines/rack1/disks",
7878 "/claim/start/:token": "/claim/start/claim_fixture",
7979 "/templates/:owner/:name": "/templates/alice/forge", // marked a template in the setup below
80 "/og/template/:ref.svg": "/og/template/alice~forge.svg",
81 "/og/template/:ref.png": "/og/template/alice~forge.png",
8082 };
8183
8284 function registeredGets(): Set<string> {
test/template-share.test.ts added +81
@@ -0,0 +1,81 @@
1 /** /templates/<name> carries a share card and a link that starts a forge from it (#13593). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createRepo } from "../src/core/repos.ts";
8 import { createUser } from "../src/core/users.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10
11 let dir: string;
12 let app: App;
13 let servers: Servers;
14
15 beforeAll(async () => {
16 dir = await mkdtemp(join(tmpdir(), "forge-template-share-"));
17 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0, forgeRepo: "alice/forge-code" });
18 servers = await serve(app);
19 }, 30_000);
20
21 afterAll(async () => {
22 servers.stop();
23 app.close();
24 await rm(dir, { recursive: true, force: true });
25 });
26
27 test("a template's page has share meta and a link to New forge with it chosen", async () => {
28 const res = await fetch(`${servers.url}/templates/starter`);
29 const text = await res.text();
30 expect(res.status).toBe(200);
31 expect(text).toContain('property="og:title" content="Starter app template');
32 expect(text).toContain("A server, a page, tests and a forge.json, ready to change.");
33 expect(text).toContain('content="https://forge.test/og/template/starter.png"');
34 expect(text).toContain('name="twitter:image" content="https://forge.test/og/template/starter.png"');
35 expect(text).toContain('href="/forges/new?template=starter"');
36 });
37
38 test("its card is served, and an unknown template is 404 on page and card", async () => {
39 const card = await fetch(`${servers.url}/og/template/starter.svg`);
40 expect(card.status).toBe(200);
41 expect(await card.text()).toContain("Starter app template");
42 expect((await fetch(`${servers.url}/templates/nope`)).status).toBe(404);
43 expect((await fetch(`${servers.url}/templates/nobody/nothing`)).status).toBe(404);
44 expect((await fetch(`${servers.url}/og/template/nope.svg`)).status).toBe(404);
45 });
46
47 // A repository template: a public one carries the card as owner~name, a private one none.
48 test("an owner/name template: page and card use owner~name; a hidden one has neither", async () => {
49 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "tess", email: "[email protected]", password: "a-good-passphrase" });
50 if (!u.ok) throw new Error("no user");
51 for (const [name, visibility] of [["kit", "public"], ["vault", "private"]] as const) {
52 const r = await createRepo(app.db, app.reposRoot, { ownerId: u.value.id, name, visibility, description: "x", defaultBranch: "main" });
53 if (!r.ok) throw new Error(r.error);
54 app.db.query("UPDATE repo SET is_template = 1 WHERE name = ?").run(name);
55 }
56 const shown = await (await fetch(`${servers.url}/templates/tess/kit`)).text();
57 expect(shown).toContain('content="https://forge.test/og/template/tess~kit.png"');
58 expect(shown).toContain('href="/forges/new?template=tess%2Fkit"');
59 expect((await fetch(`${servers.url}/og/template/tess~kit.svg`)).status).toBe(200);
60 // Signed out, the private template is not there: page and card are the same 404 as an unknown
61 // one.
62 expect((await fetch(`${servers.url}/templates/tess/vault`)).status).toBe(404);
63 expect((await fetch(`${servers.url}/og/template/tess~vault.svg`)).status).toBe(404);
64 expect((await fetch(`${servers.url}/og/template/tess~vault.png`)).status).toBe(404);
65 });
66
67 test("the PNG card is an image for a listed template, and 404 for an unknown one", async () => {
68 const res = await fetch(`${servers.url}/og/template/starter.png`);
69 expect([200, 503]).toContain(res.status); // 503 only when the rasterizer cannot load
70 if (res.status === 200) {
71 expect(res.headers.get("content-type")).toBe("image/png");
72 expect([...new Uint8Array(await res.arrayBuffer()).slice(0, 4)]).toEqual([0x89, 0x50, 0x4e, 0x47]);
73 }
74 expect((await fetch(`${servers.url}/og/template/nope.png`)).status).toBe(404);
75 });
76
77 test("the page says what it is for once: one start link, titled by the template", async () => {
78 const text = await (await fetch(`${servers.url}/templates/starter`)).text();
79 expect(text.split("/forges/new?template=starter").length - 1).toBe(1);
80 expect(text).not.toContain("Start a forge from Starter app");
81 });
test/templates-tui.test.ts +10
@@ -101,3 +101,13 @@ test("/ filters by name in the terminal, as ?q= does on the page", async () => {
101101 expect(text).toContain("No template matches that name.");
102102 t.tui.stop?.();
103103 });
104
105 test("the selected row prints its share path, as the page's own URL", async () => {
106 const t = open(otto);
107 await settleApp(t.tui);
108 expect(t.tui.screen.toText()).not.toContain("Share: /templates/blank"); // the blank forge has no page
109 for (const k of ["/", "S", "T", "A", "R", "enter"]) t.screen.key(key(k));
110 await settleApp(t.tui);
111 expect(t.tui.screen.toText()).toContain("Share: /templates/starter");
112 t.tui.stop?.();
113 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs