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

/templates lists the templates a new forge can start from: name, what is in it, one Start action #13081

Closed opened this
Closed without merging

scout/forge:scout/13067-templates-lists-the-templates-a-new-forg → main 11 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +360 −13
docs/design/audit.md +1
@@ -67,6 +67,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
6767 - `/review` — `studio/review_page.ts` · every ask waiting on me, one row each, newest first · `/asks` (same asks, with buttons) · none seen.
6868 - `/flow` — `pages/flow.ts` · the pipeline from ready issue to live deploy, and the bottleneck · `/system`, `/board`, `/` · none seen. A topbar button points here.
6969 - `/talk` — `pages/talk.ts` · the person's one conversation with the forge: history, composer, Confirm and Cancel; replies stream in over `/talk/stream` · `/settings/confirms` (the same yes, as a list), the home tell box (one line to an app's crew) · none seen; styles in `docs/design/areas/talk.md`.
70 - `/templates` — `pages/templates.ts` · what a new forge can start from, one row each with one Start · `/forges/new` ("See every template"), the terminal's `templates` command · none seen.
7071 - `/tell` — `studio/share_tell.ts` · where a phone's share sheet lands: the shared words in a form, the last repository chosen, nothing filed until Send · the phone's share sheet (manifest `share_target`) · none seen.
7172 - `/notes` — `pages/notes.ts` · what the person wrote, newest first, with the planner's verdict and live state in one line, and one tap to overrule it · the home tell box (Notes button), the user menu, the palette · none seen; styles in `docs/design/areas/notes.md`.
7273 - `/pipeline` — `pages/pipeline.ts` · the four steps a change follows (check, review, land, live), for a newcomer · a pull page's step line, `/flow` · none seen.
src/core/reserved.ts +1
@@ -127,6 +127,7 @@ export const SYSTEM_NAMES: readonly string[] = [
127127 "offline",
128128 "tell",
129129 "talk",
130 "templates",
130131 "notes",
131132 "theme",
132133 "verify",
src/http/route_marks.ts +13 −3
@@ -16,7 +16,10 @@ import { Router } from "./router.ts";
1616
1717 export type Mark = "admin" | "open";
1818
19 /** Every head of a registered route: one mark for all of it, or `mixed` when each route is listed below. */
19 /**
20 * Every head of a registered route: one mark for all of it, or `mixed` when each route is listed
21 * below.
22 */
2023 export const HEADS: Readonly<Record<string, Mark | "mixed">> = {
2124 "/": "open",
2225 "/-": "open",
@@ -157,6 +160,7 @@ export const HEADS: Readonly<Record<string, Mark | "mixed">> = {
157160 "/pipeline": "open",
158161 "/plugins": "open",
159162 "/pricing": "open",
163 "/templates": "open",
160164 "/privacy": "open",
161165 "/recover": "open",
162166 "/releases": "admin",
@@ -422,7 +426,10 @@ export function markOf(pattern: string): Mark | undefined {
422426 }
423427
424428 let listed: Router<Mark> | undefined;
425 /** ROUTES as a matcher, literal segments before parameters so `/packs/new` is not read as `/packs/:name`. */
429 /**
430 * ROUTES as a matcher, literal segments before parameters so `/packs/new` is not read as
431 * `/packs/:name`.
432 */
426433 function listedRoutes(): Router<Mark> {
427434 if (listed !== undefined) return listed;
428435 const params = (p: string) => p.split("/").filter((s) => s.startsWith(":") || s.startsWith("*")).length;
@@ -432,7 +439,10 @@ function listedRoutes(): Router<Mark> {
432439 return (listed = matcher);
433440 }
434441
435 /** Whether a request path falls on a route marked `admin`; unlisted under a `mixed` head counts as `admin`. */
442 /**
443 * Whether a request path falls on a route marked `admin`; unlisted under a `mixed` head counts as
444 * `admin`.
445 */
436446 export function isAdminRoute(path: string): boolean {
437447 const own = listedRoutes().match("*", path);
438448 if (own !== undefined) return own.handler === "admin";
src/http/server.ts +2
@@ -318,6 +318,7 @@ import { pricingDone, pricingOrder, pricingPage, resendPage, resendSubmit } from
318318 import { startForgeSubmit } from "../web/pages/start-forge.ts";
319319 import { redirect } from "../web/layout.ts";
320320 import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts";
321 import { templatesPage } from "../web/pages/templates.ts";
321322 import { askedPage } from "../web/studio/asked_page.ts";
322323 import { notesOverrule, notesSave, notesView } from "../web/pages/notes.ts";
323324 import { reviewPage } from "../web/studio/review_page.ts";
@@ -958,6 +959,7 @@ export function buildRouter(): Router<Handler> {
958959 router.add("GET", "/pricing/done", pricingDone);
959960 router.add("GET", "/pricing/resend", resendPage);
960961 router.add("POST", "/pricing/resend", resendSubmit);
962 router.add("GET", "/templates", templatesPage);
961963 router.add("GET", "/forges/new", newForgePage);
962964 router.add("POST", "/forges/new", newForgeSubmit);
963965 router.add("POST", "/forges/start", startForgeSubmit);
src/spawn/templates.ts +33 −1
@@ -5,6 +5,9 @@
55 * backed by a repository on this forge (`source: "repo"`, `repo`).
66 */
77
8 import type { Database } from "bun:sqlite";
9 import { listReposVisibleTo } from "../core/repos.ts";
10 import type { User } from "../core/users.ts";
811 import { err, ok, type Result } from "../kernel/result.ts";
912
1013 export interface Template {
@@ -13,6 +16,8 @@ export interface Template {
1316 /** What a forge made from it starts with, as a phrase that reads after the title. */
1417 readonly says: string;
1518 readonly source: "builtin" | "repo";
19 /** How many apps a forge made from it starts with, before any the person forks or describes. */
20 readonly apps: number;
1621 /** The repository a `repo` template is read from, as `owner/name`. */
1722 readonly repo?: string;
1823 }
@@ -27,15 +32,28 @@ export const TEMPLATES: readonly Template[] = [
2732 title: "Blank",
2833 says: "Only the apps you fork and the fresh one you describe.",
2934 source: "builtin",
35 apps: 0,
3036 },
3137 {
3238 id: "starter",
3339 title: "Starter app",
3440 says: "A server, a page, tests and a forge.json, ready to change.",
3541 source: "builtin",
42 apps: 1,
3643 },
3744 ];
3845
46 /**
47 * A template without one plain sentence cannot be listed or chosen: refused when this module
48 * loads (#13067).
49 */
50 export function checkTemplates(list: readonly Template[]): void {
51 for (const t of list) {
52 if (t.says.trim() === "") throw new Error(`template ${t.id} has no sentence`);
53 }
54 }
55 checkTemplates(TEMPLATES);
56
3957 /** A template repository, named `owner/name` (#12432). */
4058 const REPO_REF = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/[A-Za-z0-9._-]{1,100}$/;
4159
@@ -60,7 +78,7 @@ export function templateOf(id: string): Template {
6078 const built = TEMPLATES.find((t) => t.id === id);
6179 if (built !== undefined) return built;
6280 if (repoTemplateRef(id) !== undefined)
63 return { id, title: id, says: "The code and apps of that repository.", source: "repo", repo: id };
81 return { id, title: id, says: "The code and apps of that repository.", source: "repo", apps: 1, repo: id };
6482 return TEMPLATES[0]!;
6583 }
6684
@@ -75,3 +93,17 @@ export const templateNotReadable = (ref: string): string => `${ref} is not reada
7593 export function templatesView(): { templates: readonly Template[]; default: string } {
7694 return { templates: TEMPLATES, default: DEFAULT_TEMPLATE };
7795 }
96
97 /** Where Start leads: New forge with the template chosen. */
outdated

Orphaned doc comment: it describes templateList but sits above startHref, with a second doc comment right after. Remove it and put one comment on templateList.

98 export const startHref = (id: string): string => `/forges/new?template=${encodeURIComponent(id)}`;
99
100 export const appsWords = (n: number): string => (n === 0 ? "No apps of its own" : n === 1 ? "1 app" : `${n} apps`);
101
102 /** The templates one reader may start from: built-ins, then readable template repositories. */
103 export function templateList(db: Database, user: User | undefined): Template[] {
104 const repos = listReposVisibleTo(db, user, { templatesOnly: true, limit: 50 }).map((r) =>
105 templateOf(`${r.ownerName}/${r.name}`),
106 );
107 const seen = new Set<string>();
108 return [...TEMPLATES, ...repos].filter((t) => !seen.has(t.id) && seen.add(t.id));
109 }
src/tui/forge.ts +12 −5
@@ -18,6 +18,7 @@ import { sourceFor } from "../view/source.ts";
1818 import { fleetCommand } from "./screens/fleet.ts";
1919 import { dataCommand } from "./screens/data.ts";
2020 import { packsCommand } from "./screens/packs.ts";
21 import { templatesCommand } from "./screens/templates.ts";
2122 import { needsCommands } from "./screens/needs.ts";
2223 import { asksAdminCommands } from "./screens/asks_admin.ts";
2324 import { shareTellCommand } from "./screens/share_tell.ts";
@@ -264,6 +265,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
264265 ...needsCommands(session, ctx),
265266 ...asksAdminCommands(session, ctx),
266267 packsCommand(session, ctx),
268 templatesCommand(session, ctx),
267269 shareTellCommand(session, ctx),
268270 sendChangeCommand(ctx),
269271 interruptedOutCommand(session, ctx),
@@ -359,7 +361,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
359361 hint: "paste a link from another forge; it runs here",
360362 run: () => ctx.push(bringScreen(session, ctx, blank("Bring an app"))),
361363 });
362 // An organization you own, as /organizations/new and MCP `org_create` make it: a person's, never an agent's (#7260).
364 // An organization you own, as /organizations/new and MCP `org_create` make it: a person's,
365 // never an agent's (#7260).
363366 if (session.user !== undefined && session.user.kind !== "agent")
364367 commands.push({
365368 id: "new-org",
@@ -543,7 +546,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
543546 hint: "concurrency and guards, live; e changes a settable one",
544547 run: () => ctx.push(capacityScreen(session, ctx)),
545548 });
546 // What crawlers cost and who was refused, as GET /api/v1/admin/crawlers: the capacity screen's readers.
549 // What crawlers cost and who was refused, as GET /api/v1/admin/crawlers: the capacity screen's
550 // readers.
547551 if (mayCapacity(session))
548552 commands.push({
549553 id: "crawlers",
@@ -572,7 +576,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
572576 hint: "the last 30 releases and their pulls",
573577 run: () => ctx.push(changelogScreen(session, ctx)),
574578 });
575 // The live release and the kept ones, as /releases gates them: a site admin or a reader of FORGE_REPO.
579 // The live release and the kept ones, as /releases gates them: a site admin or a reader of
580 // FORGE_REPO.
576581 if (mayRead(session.app, session.user))
577582 commands.push({
578583 id: "releases",
@@ -620,7 +625,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
620625 hint: "internal hosts an origin may reach",
621626 run: () => ctx.push(trustedHostsPrompt(session, ctx, blank("Trusted hosts"))),
622627 });
623 // Usage: the forge's spend for any signed-in user (#8308); the route list stays the page's gate, the same as Flags (#1565).
628 // Usage: the forge's spend for any signed-in user (#8308); the route list stays the page's
629 // gate, the same as Flags (#1565).
624630 if (session.user !== undefined)
625631 commands.push({
626632 id: "usage",
@@ -652,7 +658,8 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
652658 hint: "what your crew may spend, and add your own subscription",
653659 run: () => ctx.push(modelScreen(session, ctx)),
654660 });
655 // The caller's own role and row of the roles table, as /settings and `whoami_can` have it (#2304).
661 // The caller's own role and row of the roles table, as /settings and `whoami_can` have it
662 // (#2304).
656663 if (session.user !== undefined)
657664 commands.push({
658665 id: "can",
src/tui/screens/templates.ts added +56
@@ -0,0 +1,56 @@
1 /**

Both doors need a how-to in docs/features/<name>.md. Extend docs/features/new-forge-template.md with a /templates section and the terminal templates command (no new file, so the cap holds).

2 * `/templates` in the terminal (#13067): the templates this reader may start a
3 * forge from, one per line, the same list the page reads (`templateList`).
4 * Enter, or s, opens New forge with that template chosen.
5 */
6
7 import type { Ctx, Screen } from "../app/app.ts";
8 import { binding } from "../app/keys.ts";
9 import type { Session } from "../session.ts";
10 import { style } from "../term/style.ts";
11 import { truncate } from "../term/width.ts";
12 import { appsWords, templateList } from "../../spawn/templates.ts";
13 import { newForgeScreen } from "./newforge.ts";
14
15 export function templatesScreen(session: Session, ctx: Ctx): Screen {
16 let at = 0;
17 const list = () => templateList(session.app.db, session.user);
18 const start = (): void => {
19 const t = list()[at];
20 if (t !== undefined) ctx.push(newForgeScreen(session, ctx, { template: t.id }));
21 };
22 return {
23 title: "Templates",
24 keys: [binding(["j", "k"], "move"), binding(["enter", "s"], "start a forge"), binding(["esc"], "back")],
25 render(area, s) {
26 const c = ctx.theme.c;
27 const rows = list();
28 at = Math.min(at, Math.max(0, rows.length - 1));
29 s.text(area.x + 1, area.y, "What a new forge can start from.", style(c.mutedFg, c.bg), area.x + area.w);
30 rows.forEach((t, i) => {
31 const y = area.y + 2 + i * 2;
32 if (y + 1 >= area.y + area.h) return;
33 const on = i === at;
34 s.text(area.x + 1, y, truncate(`${on ? "> " : " "}${t.title} (${t.id})`, area.w - 2), on ? style(c.accent, c.bg) : style(c.fg, c.bg), area.x + area.w);
35 s.text(area.x + 1, y + 1, truncate(` ${t.says} ${appsWords(t.apps)}.`, area.w - 2), style(c.mutedFg, c.bg), area.x + area.w);
36 });
37 },
38 key(e) {
39 if (e.ctrl || e.alt) return false;
40 const n = list().length;
41 if (e.key === "esc" || e.key === "q") ctx.pop();
42 else if (e.key === "j" || e.key === "down") at = Math.min(Math.max(0, n - 1), at + 1);
43 else if (e.key === "k" || e.key === "up") at = Math.max(0, at - 1);
44 else if (e.key === "enter" || e.key === "s") start();
45 else return false;
46 return true;
47 },
48 };
49 }
50
51 export const templatesCommand = (session: Session, ctx: Ctx) => ({
52 id: "templates",
53 title: "Templates",
54 hint: "what a new forge can start from, and start one",
55 run: () => ctx.push(templatesScreen(session, ctx)),
56 });
src/web/pages/new-forge.ts +6 −2
@@ -28,7 +28,7 @@ import {
2828 MIN_BUDGET_USD,
2929 } from "../../spawn/plan.ts";
3030 import { DEFAULT_SIZE, SIZES, sizesView } from "../../spawn/sizes.ts";
31 import { DEFAULT_TEMPLATE, TEMPLATES, templateOf } from "../../spawn/templates.ts";
31 import { DEFAULT_TEMPLATE, parseTemplate, TEMPLATES, templateOf } from "../../spawn/templates.ts";
3232 import { FOLLOW_LABELS, FOLLOW_WORDS } from "../../spawn/follow_words.ts";
3333 import { dropGift, keepGift, keptGift } from "../gift_cookie.ts";
3434 import { notFoundPage, pageHead } from "../chrome.ts";
@@ -141,6 +141,9 @@ function sizeOptions(chosen: string): { value: string; label: string; selected?:
141141 }));
142142 }
143143
144 /** The `?template=` asked for: a built-in id or `owner/name`, else the default; never echoed. */
145 const askedTemplate = (v: string | null): string => (v !== null && parseTemplate(v).ok ? v : DEFAULT_TEMPLATE);
146
144147 /**
145148 * The templates in order, Blank first; the one asked for chosen (Blank when it is not one of them).
146149 */
@@ -378,6 +381,7 @@ function formView(
378381 options: templateOptions(values.template, templates),
379382 ...(errors["template"] ? { error: errors["template"] } : {}),
380383 })}
384 <p class="hint"><a href="/templates">See every template</a></p>
381385 ${selectField({
382386 label: "Size (optional)",
383387 name: "size",
@@ -519,7 +523,7 @@ export function newForgePage(ctx: Ctx): Response {
519523 ctx,
520524 title: "New forge",
521525 keyboardResizes: true,
522 body: formView(ctx, user, { ...EMPTY, code, name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), ...fromPack(ctx, user) }, errors, gift, reads),
526 body: formView(ctx, user, { ...EMPTY, code, name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), template: askedTemplate(ctx.url.searchParams.get("template")), ...fromPack(ctx, user) }, errors, gift, reads),
523527 });
524528 notePhase(ctx.request, "render", performance.now() - rendering);
525529 return response;
src/web/pages/templates.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * `/templates` (#13067): what a new forge can start from, one row each: name,
3 * one plain sentence, how many apps it brings, and one Start that opens New
4 * forge with that template chosen. It reads the list the spawn path reads
5 * (`spawn/templates.ts` plus the repositories marked as templates that the
6 * viewer can read), so the page never offers what spawn would refuse.
7 * Signed out works: `/forges/new` is open, and a sign-in on the way keeps the
8 * address, `?template=` and all.
9 */
10
11 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { appsWords, startHref, templateList } from "../../spawn/templates.ts";
14 import { pageHead } from "../chrome.ts";
15 import { html } from "../html.ts";
16 import { page } from "../layout.ts";
17 import { btn, row } from "../ui.ts";
18
19 // GET /templates
20 export function templatesPage(ctx: Ctx): Response {
21 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
22 const rendering = performance.now();
23 const list = templateList(ctx.app.db, ctx.auth.user);
24 const rows = list.map((t) =>
25 row({
26 title: html`${t.title}`,
27 meta: html`${t.says} <span class="muted">${appsWords(t.apps)}.</span>`,
28 trail: btn("Start", { href: startHref(t.id), variant: "secondary", label: `Start from ${t.title}` }),
29 data: { template: t.id },
30 }),
31 );
32 const response = page({
33 ctx,
34 title: "Templates",
35 body: html`<div class="narrow-wide" data-templates>
36 ${pageHead("Templates", { sub: "What a new forge can start from." })}
37 <ul class="list">${rows}</ul>
38 </div>`,
outdated

Design principle 5: at most one accent per page. Every row carries a variant primary button, so a list of N templates shows N accent buttons. Use the quiet link/secondary variant for Start, and keep the accent for the single main action, if any. It must remain an <a>, since it navigates.

39 });
40 notePhase(ctx.request, "render", performance.now() - rendering);
41 return response;
42 }
test/forge-looks.test.ts +5 −1
@@ -21,6 +21,7 @@ quietLogs();
2121
2222 /** Top-level routes that are not pages, or are not worth a picture, and why. */
2323 const NOT_A_PAGE: Record<string, string> = {
24 "/templates": "no picture: the cap of 24 looks is spent; the page is covered by test/templates-page.test.ts",
2425 "/home": "the home's old address: a redirect to /, which is pictured",
2526 "/desk": "a POST that leaves a note on the desk; the desk is read on the home (/), which is pictured; covered by test/desk.test.ts",
2627 "/feed": "no picture: its slot went to /docs; the page is covered by its own tests",
@@ -122,7 +123,10 @@ const manifest = (): { looks: string[]; looksAsOwner: string[] } =>
122123 const isTopLevel = (p: string) => p === "/" || /^\/[^/?]+$/.test(p);
123124 /** A page's `?help` look: the page with its help open and focused (#11170). */
124125 const isHelpLook = (p: string) => p.endsWith("?help") && (isTopLevel(p.slice(0, -5)) || p === "/settings/crew?help");
125 /** The top-level pages; a deeper one is the preview seed's, taken as the owner (test/looks-owner.test.ts). */
126 /**
127 * The top-level pages; a deeper one is the preview seed's, taken as the owner
128 * (test/looks-owner.test.ts).
129 */
126130 const declared = (): string[] => manifest().looks.filter(isTopLevel);
127131
128132 const get = (path: string) =>
test/palette-roster.test.ts +6 −1
@@ -53,6 +53,7 @@ test("a site-admin person is offered the whole roster", () => {
5353 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
5454 ["mirror-packs", "Mirror the packs' upstreams", "bring each pack's upstream projects in as read-only repositories"],
5555 ["pack-repos", "Pack repositories", "which repositories /packs lists"],
56 ["templates", "Templates", "what a new forge can start from, and start one"],
5657 ["share-tell", "Share a link or text with the crew", "a draft, then where; nothing is sent until you confirm"],
5758 ["send-change", "Send a change", "fork, patch, pull: no forge of your own"],
5859 ["interrupted-out", "Stopped runs", "runs the host stopped five times, with Try again"],
@@ -225,6 +226,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
225226 ["needs", "How is my forge?", "what needs you, with a recommendation each; a takes a safe one"],
226227 ["asks-admin", "What stands in the way", "what waits on you and what stands in your way; a asks whoever can, o opens the control"],
227228 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
229 ["templates", "Templates", "what a new forge can start from, and start one"],
228230 ["share-tell", "Share a link or text with the crew", "a draft, then where; nothing is sent until you confirm"],
229231 ["send-change", "Send a change", "fork, patch, pull: no forge of your own"],
230232 ["interrupted-out", "Stopped runs", "runs the host stopped five times, with Try again"],
@@ -319,6 +321,7 @@ test("a member person is offered the signed-in roster without the admin entries"
319321 ["needs", "How is my forge?", "what needs you, with a recommendation each; a takes a safe one"],
320322 ["asks-admin", "What stands in the way", "what waits on you and what stands in your way; a asks whoever can, o opens the control"],
321323 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
324 ["templates", "Templates", "what a new forge can start from, and start one"],
322325 ["share-tell", "Share a link or text with the crew", "a draft, then where; nothing is sent until you confirm"],
323326 ["send-change", "Send a change", "fork, patch, pull: no forge of your own"],
324327 ["interrupted-out", "Stopped runs", "runs the host stopped five times, with Try again"],
@@ -408,6 +411,7 @@ test("signed out, the palette offers sign-in and the public entries", () => {
408411 ["explore", "Explore", "on the web"],
409412 ["explore-feed", "Explore feed", "Atom address"],
410413 ["packs", "Forge packs", "premade forges to deploy, and how to help build their apps"],
414 ["templates", "Templates", "what a new forge can start from, and start one"],
411415 ["share-tell", "Share a link or text with the crew", "a draft, then where; nothing is sent until you confirm"],
412416 ["send-change", "Send a change", "fork, patch, pull: no forge of your own"],
413417 ["interrupted-out", "Stopped runs", "runs the host stopped five times, with Try again"],
@@ -539,7 +543,8 @@ describe("on a pull's Files step the palette lists what the page offers this rea
539543 for (const [tab, path] of [["Conversation", thread], ["Files", `${thread}/files`]] as const) {
540544 test(`on the ${tab} tab a ${who}'s action rows are exactly the page's forms`, async () => {
541545 const { rows, forms } = await read(path, kind());
542 // The Files tab has no comment form of its own: its Comment row links to the Conversation's.
546 // The Files tab has no comment form of its own: its Comment row links to the
547 // Conversation's.
543548 const acts = rows.map((r) => r.t).filter((t) => !READING.includes(t) && !(tab === "Files" && t === "Comment"));
544549 const same = (t: string) => (t === "Bring up to date" ? "Ship" : t);
545550 expect(acts.map(same).sort()).toEqual([...new Set(forms)].sort());
test/templates-page.test.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * `/templates` (#13067): a signed-out reader sees one row per template the
3 * spawn path accepts (built in and marked repositories), each with a sentence,
4 * an app count and a Start that opens New forge with the template chosen; a
5 * template with no sentence is refused when the list loads.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { checkTemplates, TEMPLATES } from "../src/spawn/templates.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { promote } from "./helpers/members.ts";
19
20 quietLogs();
21
22 let dir = "";
23 let app: App;
24 let servers: Servers;
25
26 beforeAll(async () => {
27 dir = await mkdtemp(join(tmpdir(), "forge-templates-page-"));
28 app = createApp({ dataDir: dir, port: 0 });
29 servers = await serve(app);
30 });
31
32 afterAll(async () => {
33 await servers.stop?.();
34 app.close();
35 await rm(dir, { recursive: true, force: true });
36 });
37
38 test("signed out, one row per template, each with its sentence, app count and a Start that carries it", async () => {
39 const res = await fetch(`${servers.url}/templates`);
40 expect(res.status).toBe(200);
41 const body = await res.text();
42 // Under 10 KB as sent: measured on the body itself, compressed. The shared chrome alone is
43 // about 10 KB uncompressed, so the claim is about the wire, not the raw markup.
44 expect(Bun.gzipSync(Buffer.from(body)).length).toBeLessThan(10 * 1024);
45 // What this page adds to the chrome, raw: the head and the rows, under 2 KB.
46 const own = body.slice(body.indexOf("data-templates"), body.indexOf("</main>"));
47 expect(own.length).toBeGreaterThan(0);
48 expect(own.length).toBeLessThan(2 * 1024);
49 for (const t of TEMPLATES) {
50 expect(body).toContain(t.title);
51 expect(body).toContain(t.says);
52 expect(body).toContain(`/forges/new?template=${encodeURIComponent(t.id)}`);
53 }
54 expect(body).toContain("1 app");
55 expect(body.match(/data-template=/g)?.length).toBe(TEMPLATES.length);
56 });
57
outdated

Tests missing: (a) the template choice surviving sign-up (box 2): fetch /forges/new?template=starter signed out and assert that the sign-in redirect or link keeps the address; (b) a repo template appears for a reader who may read it and a private one does not for a stranger; (c) the size assertion should check the body bytes, not content-length, or the page should come under 10 KB uncompressed.

58 test("the Start link opens New forge with that template chosen", async () => {
59 const res = await fetch(`${servers.url}/forges/new?template=starter`);
60 expect(res.status).toBe(200);
61 expect(await res.text()).toMatch(/<option[^>]*value="starter"[^>]*selected/);
62 });
63
64 test("Start carries the choice through a sign-in and a sign-up", async () => {
65 const body = await (await fetch(`${servers.url}/forges/new?template=starter`)).text();
66 const next = encodeURIComponent("/forges/new?template=starter");
67 expect(body).toContain(`/signin?next=${next}`);
68 expect(body).toContain(`/signup?next=${next}`);
69 });
70
71 test("Start is quiet: no row carries the accent", async () => {
72 const body = await (await fetch(`${servers.url}/templates`)).text();
73 expect(body).not.toContain('data-variant="primary"');
74 });
75
76 test("an id spawn would not accept is not rendered back", async () => {
77 const res = await fetch(`${servers.url}/forges/new?template=${encodeURIComponent('"><b>x</b>')}`);
78 const body = await res.text();
79 expect(body).not.toContain("<b>x</b>");
80 expect(body).toMatch(/<option[^>]*value="blank"[^>]*selected/);
81 });
82
83 test("a marked repository is listed for who may read it; a private one is hidden from a stranger", async () => {
84 const mk = async (name: string) => {
85 const r = await createUser(app.db, {
86 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase",
87 });
88 if (!r.ok) throw new Error(r.error);
89 return r.value;
90 };
91 const olive = await mk("olive");
92 const rita = await mk("rita");
93 promote(app.db, olive, rita);
94 for (const [name, visibility] of [["pubtpl", "public"], ["privtpl", "private"]] as const) {
95 const r = await createRepo(app, olive, { name, visibility });
96 if (!r.ok) throw new Error(String(r.error));
97 app.db.query("UPDATE repo SET is_template = 1 WHERE id = ?").run(r.value.id);
98 }
99 const as = (u: typeof olive | undefined) =>
100 fetch(`${servers.url}/templates`, u ? { headers: { authorization: `Bearer ${createToken(app.db, u.id, "t", "admin").token}` } } : {}).then((r) => r.text());
101 const stranger = await as(undefined);
102 expect(stranger).toContain("olive/pubtpl");
103 expect(stranger).not.toContain("olive/privtpl");
104 const other = await as(rita);
105 expect(other).toContain("olive/pubtpl");
106 expect(other).not.toContain("olive/privtpl");
107 const owner = await as(olive);
108 expect(owner).toContain("olive/pubtpl");
109 expect(owner).toContain("olive/privtpl");
110 });
111
112 test("a template with no sentence is refused at load", () => {
113 expect(() => checkTemplates([{ id: "x", title: "X", says: " ", source: "builtin", apps: 0 }])).toThrow(/no sentence/);
114 });
test/tui-templates.test.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * The terminal's templates screen (#13067): the same list as `/templates`, and
3 * Enter opens New forge with the highlighted template chosen.
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 { createUser, type User } from "../src/core/users.ts";
11 import { TEMPLATES } from "../src/spawn/templates.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { templatesScreen } from "../src/tui/screens/templates.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let app: App;
22 let user: User;
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "forge-tui-templates-"));
26 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
27 const r = await createUser(app.db, {
28 origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase",
29 });
30 if (!r.ok) throw new Error(r.error);
31 user = r.value;
32 });
33 afterAll(async () => {
34 app.db.close();
35 await rm(dir, { recursive: true, force: true });
36 });
37
38 async function open(keys: string): Promise<string> {
39 const terminal = headlessTerminal(120, 40);
40 const { app: tui, session } = createForgeApp(
41 app,
42 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
43 { terminal, exitHooks: false },
44 );
45 tui.start();
46 tui.ctx.push(templatesScreen(session, tui.ctx));
47 try {
48 await settleApp(tui);
49 terminal.feed(keys);
50 await settleApp(tui);
51 return tui.screen.toText();
52 } finally {
53 tui.stop?.();
54 }
55 }
56
57 test("lists every template with its sentence", async () => {
58 const text = await open("");
59 for (const t of TEMPLATES) {
60 expect(text).toContain(t.title);
61 expect(text).toContain(t.says);
62 }
63 });
64
65 test("Enter on a row opens New forge with that template chosen", async () => {
66 const text = await open("j\r");
67 expect(text).toContain("Template");
68 expect(text).toContain("starter");
69 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs