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

Making a new forge can name a template, and its code and apps come from that repository #12831

Merged opened this

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

Merged

mason/forge:mason/12432-making-a-new-forge-can-name-a-template-a → main 8 commits fork 4 threads · 4 unresolved

  • Merged. mason/12432-making-a-new-forge-can-name-a-template-a was merged into main as 0e7f347.

Review

Sign in to review this change.
14 files changed +300 −46
docs/MCP.md +1 −1
@@ -204,7 +204,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
204204 | `signup` | — | Sign-ups: open (default); invite lets in only a person with an open invite link; closed refuses every new account | 324 |
205205 | `sizes` | — | A child forge's sizes: small, medium and large, each with CPU, memory and disk | 196 |
206206 | `snapshot_now` | — | Take a snapshot now, as Backups does (admin) | 133 |
207 | `spawn` | — | Spawn a child forge | 946 |
207 | `spawn` | — | Spawn a child forge | 980 |
208208 | `spend` | — | Report what your session spent outside forge runs: who, model, tokens or dollars, issue | 470 |
209209 | `ssh_keys` | `list`, `add`, `remove` | Your SSH keys; add: key, remove: id | 250 |
210210 | `steer` | — | Say a word to one crew run by its id | 224 |
docs/features/README.md +1
@@ -34,6 +34,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
3434 - [Plans on the home](home-plans.md)
3535 - [Returning visitors](returning-visitors.md)
3636 - [Template mark](repo-template.md)
37 - [A new forge can start from a template repository](new-forge-template.md)
3738 - [The explorer's sorts](explore.md)
3839 - [The feed pages by cursor](feed-cursor.md)
3940 - [The fork tree](fork-tree.md)
docs/features/new-forge-template.md added +7
@@ -0,0 +1,7 @@
1 # New forge from a template
2
3 A new forge can start from a template repository: one an admin marked at Settings → Templates and the maker can read. The New forge page has one Template select (default "The forge's own code", then Blank, Starter app and each readable template repository); the terminal's New forge screen cycles the same list with left and right, or takes `owner/name` typed. `POST /api/v1/forges` and the MCP spawn tool take `template: "owner/name"`. An unmarked or unreadable repository answers 422 saying which.
4
5 The template's code becomes the child's own `forge` repository. It keeps the template's visibility: a private template never becomes a public repository in the child.
6
7 Code: `src/spawn/templates.ts` (ids and words), `src/spawn/forge_code.ts` (the fork), `src/actions/spawn.ts` (the checks).
src/actions/spawn.ts +16 −2
@@ -44,6 +44,7 @@ import { commitFiles } from "../git/write.ts";
4444 import { adoptForgeCode, forkForgeCode } from "../spawn/forge_code.ts";
4545 import { lendIncludedCredit } from "../spawn/included_credit.ts";
4646 import { seedStarterCrew } from "../spawn/starter_crew.ts";
47 import { repoTemplateRef, templateNotMarked, templateNotReadable } from "../spawn/templates.ts";
4748 import { birthFromTemplate, type TemplateMark } from "../spawn/template_birth.ts";
4849 import { writePrivate } from "../kernel/file_modes.ts";
4950 import { sha256 } from "../kernel/hash.ts";
@@ -278,6 +279,15 @@ export async function spawnForge(
278279 if (!repo || !canRead(app.db, repo, owner))
279280 return err({ kind: "invalid", field: "apps", reason: `${a.ref} is not readable by you` });
280281 }
282 // The same read check the apps pass; a template is also marked.
283 const templateRef = plan.template === undefined ? undefined : repoTemplateRef(plan.template);
284 if (templateRef !== undefined) {
285 const [o, n] = templateRef.split("/") as [string, string];
286 const repo = getRepo(app.db, o, n);
287 if (!repo || !canRead(app.db, repo, owner))
288 return err({ kind: "invalid", field: "template", reason: templateNotReadable(templateRef) });
289 if (!repo.template) return err({ kind: "invalid", field: "template", reason: templateNotMarked(templateRef) });
290 }
281291 for (const b of plan.briefs) {
282292 if (b.text.length > BRIEF_MAX)
283293 return err({ kind: "invalid", field: "briefs", reason: `a brief is at most ${BRIEF_MAX} characters` });
@@ -524,7 +534,11 @@ async function copyInto(
524534 // smallest app that answers, committed once.
525535 // With a template, the sentence describes the template's app instead:
526536 // one repository, not two (`spawn/template_birth.ts`).
527 if (plan.template !== undefined) {
537 // A template repository supplies the code below instead; the sentence, if any, still
538 // begins a fresh app.
539 const fromRepo = plan.template === undefined ? undefined : repoTemplateRef(plan.template);
540 if (fromRepo !== undefined) templateMark = { id: fromRepo, repo: fromRepo };
541 if (plan.template !== undefined && fromRepo === undefined) {
528542 const born = await birthFromTemplate(child, org, {
529543 template: plan.template,
530544 ...(plan.fresh === undefined ? {} : { fresh: plan.fresh }),
@@ -543,7 +557,7 @@ async function copyInto(
543557 // A cross-forge fork: the history is copied by git, and the upstream
544558 // is recorded in parent.json for the child to pull from. Skipped when
545559 // the forge does not name its code repository (`forgeRepo`).
546 const forgeCode = await forkForgeCode(app, child, org.username, plan.followMode ?? DEFAULT_MODE);
560 const forgeCode = await forkForgeCode(app, child, org.username, plan.followMode ?? DEFAULT_MODE, fromRepo);
547561 if (!forgeCode.ok) return err(forgeCode.error);
548562
549563 for (const b of plan.briefs) {
src/http/mcp/tools/spawn.ts +1 −1
@@ -45,7 +45,7 @@ export const tool: Tool = {
4545 },
4646 template: {
4747 type: "string",
48 description: "From `templates`.",
48 description: "From `templates`, or owner/name of a template repo.",
4949 },
5050 keepAccess: {
5151 type: "boolean",
src/http/mcp/tools/templates.ts +1 −1
@@ -3,7 +3,7 @@ import { good, type Tool } from "../shared.ts";
33
44 export const tool: Tool = {
55 name: "templates",
6 doc: "the templates a child forge may start from (`blank` first, the default), each with id, title, one sentence and source; pass an id as `spawn`'s `template`",
6 doc: "the templates a child forge may start from (`blank` first, the default), each with id, title, one sentence and source; pass an id as `spawn`'s `template`; so may the `owner/name` of a repository marked as a template",
77 description: "The templates a child forge may start from.",
88 inputSchema: { type: "object", properties: {} },
99 writes: false,
src/spawn/forge_code.ts +9 −3
@@ -57,8 +57,10 @@ export async function forkForgeCode(
5757 child: App,
5858 orgName: string,
5959 mode: FollowMode,
60 /** A template repository (`owner/name`) whose code stands in for the forge's own (#12432). */
61 template?: string,
6062 ): Promise<Result<ForgeCode | undefined, string>> {
61 const ref = await forgeCodeRef(app);
63 const ref = template ?? (await forgeCodeRef(app));
6264 if (ref === undefined) return ok(undefined);
6365 const [o, n] = ref.split("/") as [string, string];
6466 const parent = getRepo(app.db, o, n);
@@ -69,8 +71,12 @@ export async function forkForgeCode(
6971 const made = await createRepo(child.db, child.reposRoot, {
7072 ownerId: org.id,
7173 name: FORGE_CODE_NAME,
72 visibility: "public",
73 description: `A fork of ${o}/${n}: the forge's own code, following its parent.`,
74 // A template's code is no more public in the child than it is here.
75 visibility: template === undefined ? "public" : parent.visibility,
outdated

HIGH: visibility stays "public" for the child's forge repo even when the template is private (the maker can read it, per the spawn check). That leaks a private repo's code to everyone. Copy the template's visibility (or force private) when template is set, and add a test.

76 description:
77 template === undefined
78 ? `A fork of ${o}/${n}: the forge's own code, following its parent.`
79 : `A fork of the template ${o}/${n}: this forge's code and apps.`,
7480 defaultBranch: parent.defaultBranch,
7581 });
7682 if (!made.ok) return err(`could not make the child's forge repo: ${made.error}`);
src/spawn/templates.ts +31 −8
@@ -36,18 +36,41 @@ export const TEMPLATES: readonly Template[] = [
3636 },
3737 ];
3838
39 /** A template id, or one sentence naming the valid ones. */
40 export function parseTemplate(v: unknown): Result<string, string> {
41 if (typeof v === "string" && TEMPLATES.some((t) => t.id === v)) return ok(v);
42 const ids = TEMPLATES.map((t) => t.id);
43 return err(`template must be ${ids.slice(0, -1).join(", ")} or ${ids[ids.length - 1]}`);
39 /** A template repository, named `owner/name` (#12432). */
40 const REPO_REF = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/[A-Za-z0-9._-]{1,100}$/;
41
42 /** The `owner/name` a template id names, or undefined for a built-in one. */
43 export function repoTemplateRef(id: string): string | undefined {
44 return REPO_REF.test(id) ? id : undefined;
4445 }
4546
46 /** The title of a template already validated by `parseTemplate`. */
47 export function templateOf(id: string): Template {
48 return TEMPLATES.find((t) => t.id === id) ?? TEMPLATES[0]!;
47 /**
48 * A template id (built in, or `owner/name` of a template repository), or one sentence naming
49 * the valid ones.
50 */
51 export function parseTemplate(v: unknown): Result<string, string> {
52 if (typeof v === "string" && TEMPLATES.some((t) => t.id === v)) return ok(v);
53 if (typeof v === "string" && repoTemplateRef(v) !== undefined) return ok(v);

The refusal for an invalid id still says 'template must be blank, starter' only; with owner/name now valid, the sentence is wrong. Update it and the tests that pin it.

54 const ids = TEMPLATES.map((t) => t.id);
55 return err(`template must be ${ids.join(", ")} or the owner/name of a template repository`);
4956 }
5057
58 /** The title of a template already validated by `parseTemplate`; a repository's is its name. */
59 export function templateOf(id: string): Template {
60 const built = TEMPLATES.find((t) => t.id === id);
61 if (built !== undefined) return built;
62 if (repoTemplateRef(id) !== undefined)
63 return { id, title: id, says: "The code and apps of that repository.", source: "repo", repo: id };
64 return TEMPLATES[0]!;
65 }
66
67 /**
68 * The refusal's words when a repository cannot serve as a template; one place, so the page,
69 * the door and the MCP say the same.
70 */
71 export const templateNotMarked = (ref: string): string => `${ref} is not marked as a template`;
72 export const templateNotReadable = (ref: string): string => `${ref} is not readable by you`;
73
5174 /** What each template is, for a page or an agent to offer. */
5275 export function templatesView(): { templates: readonly Template[]; default: string } {
5376 return { templates: TEMPLATES, default: DEFAULT_TEMPLATE };
src/tui/screens/newforge.ts +19 −12
@@ -7,8 +7,9 @@
77 * dialog, and kept nowhere. Any signed-in person's, as the page is.
88 */
99
10 import { listReposVisibleTo } from "../../core/repos.ts";
1011 import { DEFAULT_SIZE, SIZES, type Size } from "../../spawn/sizes.ts";
11 import { DEFAULT_TEMPLATE, TEMPLATES, templateOf } from "../../spawn/templates.ts";
12 import { DEFAULT_TEMPLATE, repoTemplateRef, TEMPLATES, templateOf } from "../../spawn/templates.ts";
1213 import { childUrlOf, spawnDoor } from "../../spawn/door.ts";
1314 import { quotaFull } from "../../spawn/quota.ts";
1415 import { FOLLOW_LINE, FOLLOW_WORDS } from "../../spawn/follow_words.ts";
@@ -35,7 +36,7 @@ const SIZE_CHOICES = Object.keys(SIZES) as Size[];
3536
3637 const TEMPLATE_CHOICES = TEMPLATES.map((t) => t.id);
3738
38 const TEMPLATE_HINT = "blank (default) or starter: left and right choose, or type it.";
39 const TEMPLATE_HINT = "blank (default), starter or a template repository as owner/name: left and right choose, or type it.";
3940
4041 const SPECS: readonly Spec[] = [
4142 { key: "name", label: "Name", hint: "Lowercase letters, digits and dashes." },
@@ -54,7 +55,8 @@ const SPECS: readonly Spec[] = [
5455 /** The chosen template's own sentence; a typed id that is no template keeps the general hint. */
5556 function templateHint(id: string): string {
5657 const t = TEMPLATES.find((x) => x.id === id);
57 return t === undefined ? TEMPLATE_HINT : t.says;
58 if (t !== undefined) return t.says;
59 return repoTemplateRef(id) === undefined ? TEMPLATE_HINT : templateOf(id).says;
5860 }
5961
6062 /** The door's "field: reason" refusal, as the field it names and the reason. */
@@ -65,6 +67,11 @@ function refusal(body: Record<string, unknown>): { key?: string; text: string }
6567 }
6668
6769 export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, string> = {}): Screen {
70 // The built-in templates, then the template repositories this person can read: the page's list.

New behaviour with no test: the choices list now includes the readable template repos, and a typed owner/name gets that repo sentence. Add a tui-newforge test that fails without this (cycle right to the repo; an unmarked or private-unreadable repo is absent).

71 const repoTemplates = listReposVisibleTo(f.app.db, f.user, { templatesOnly: true, limit: 50 }).map(
72 (r) => `${r.ownerName}/${r.name}`,
73 );
74 const specs = SPECS.map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s));
6875 const values: Record<string, string> = { ...initial };
6976 let focus = 0;
7077 let errorKey: string | undefined;
@@ -114,7 +121,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
114121 values["modelKey"] = "";
115122 error = r.text;
116123 errorKey = r.key;
117 const at = SPECS.findIndex((s) => s.key === r.key);
124 const at = specs.findIndex((s) => s.key === r.key);
118125 if (at >= 0) focus = at;
119126 plan = undefined;
120127 ctx.toast(r.text, "danger");
@@ -194,9 +201,9 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
194201 }
195202 // Three rows a field; the window scrolls so the focused one is in view.
196203 const rows = Math.max(1, Math.floor(area.h / 3));
197 const first = Math.max(0, Math.min(focus - rows + 1, SPECS.length - rows));
204 const first = Math.max(0, Math.min(focus - rows + 1, specs.length - rows));
198205 let cursor: { x: number; y: number } | null = null;
199 SPECS.slice(first, first + rows).forEach((spec, n) => {
206 specs.slice(first, first + rows).forEach((spec, n) => {
200207 const i = first + n;
201208 const raw = spec.choices === undefined ? (values[spec.key] ?? "") : (values[spec.key] || spec.choices[0]!);
202209 const shown = spec.secret === true ? "•".repeat([...raw].length) : raw;
@@ -215,7 +222,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
215222 },
216223 paste(text) {
217224 if (plan !== undefined) return true;
218 const k = SPECS[focus]!.key;
225 const k = specs[focus]!.key;
219226 values[k] = (values[k] ?? "") + text.replace(/\s+/g, " ").trim();
220227 return true;
221228 },
@@ -230,27 +237,27 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
230237 return true;
231238 }
232239 if (e.key === "tab" || e.key === "enter") {
233 focus = (focus + 1) % SPECS.length;
240 focus = (focus + 1) % specs.length;
234241 return true;
235242 }
236 const choices = SPECS[focus]!.choices;
243 const choices = specs[focus]!.choices;
237244 const step = e.key === "left" ? -1 : e.key === "right" || e.key === " " || e.key === "space" ? 1 : 0;
238245 if (choices !== undefined && step !== 0) {
239246 // A choice can be cycled or typed; both end in a value the door checks.
240 const k = SPECS[focus]!.key;
247 const k = specs[focus]!.key;
241248 const at = Math.max(0, choices.indexOf(values[k] || choices[0]!));
242249 values[k] = choices[(at + step + choices.length) % choices.length]!;
243250 error = undefined;
244251 return true;
245252 }
246253 if (e.key === "backspace") {
247 const k = SPECS[focus]!.key;
254 const k = specs[focus]!.key;
248255 values[k] = [...(values[k] ?? "")].slice(0, -1).join("");
249256 error = undefined;
250257 return true;
251258 }
252259 if (!e.ctrl && !e.alt && [...e.key].length === 1) {
253 const k = SPECS[focus]!.key;
260 const k = specs[focus]!.key;
254261 values[k] = (values[k] ?? "") + e.key;
255262 error = undefined;
256263 return true;
src/web/pages/new-forge.ts +22 −12
@@ -11,7 +11,7 @@
1111
1212 import { getPack, resolveRepos } from "../../packs/curated.ts";
1313 import { listAgents } from "../../core/agents.ts";
14 import { listReposToTake } from "../../core/repos.ts";
14 import { listReposToTake, listReposVisibleTo } from "../../core/repos.ts";
1515 import type { User } from "../../core/users.ts";
1616 import type { Ctx } from "../../http/context.ts";
1717 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
@@ -101,11 +101,14 @@ interface Reads {
101101 readonly quota: string | undefined;
102102 readonly repos: ReturnType<typeof listReposToTake>;
103103 readonly crew: ReturnType<typeof listAgents>;
104 /** Repositories marked as templates that the viewer can read (`full_name`), listed in the
105 * Template select. */
106 readonly templates: readonly string[];
104107 }
105108
106109 function readsFor(ctx: Ctx, user: User | undefined): Reads {
107110 const full = timePhase(ctx.request, "room", () => noRoom(ctx.app));
108 if (full) return { full, quota: undefined, repos: [], crew: [] };
111 if (full) return { full, quota: undefined, repos: [], crew: [], templates: [] };
109112 const quota = quotaFull(ctx.app.config.dataDir);
110113 // Each repository once, as its source, and public only; a stranger sees
111114 // none and no crew: nothing private travels to a child they have not claimed.
@@ -116,7 +119,10 @@ function readsFor(ctx: Ctx, user: User | undefined): Reads {
116119 user === undefined
117120 ? []
118121 : timePhase(ctx.request, "crew", () => listAgents(ctx.app.db));
119 return { full, quota, repos, crew };
122 const templates = timePhase(ctx.request, "templates", () =>
123 listReposVisibleTo(ctx.app.db, user, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`),
124 );
125 return { full, quota, repos, crew, templates };
120126 }
121127
122128 /** The three sizes, the one asked for chosen (small when the value is not one of them). */
@@ -133,13 +139,17 @@ function sizeOptions(chosen: string): { value: string; label: string; selected?:
133139 }
134140
135141 /** The templates in order, Blank first; the one asked for chosen (Blank when it is not one of them). */
136 function templateOptions(chosen: string): { value: string; label: string; selected?: boolean }[] {
137 const at = TEMPLATES.some((t) => t.id === chosen) ? chosen : DEFAULT_TEMPLATE;
138 return TEMPLATES.map((t) => ({
139 value: t.id,
140 label: `${t.title}: ${lower(t.says)}`,
141 selected: t.id === at,
142 }));
142 function templateOptions(chosen: string, repos: readonly string[]): { value: string; label: string; selected?: boolean }[] {
143 const known = TEMPLATES.some((t) => t.id === chosen) || repos.includes(chosen);
144 const at = known ? chosen : DEFAULT_TEMPLATE;
145 return [
146 ...TEMPLATES.map((t) => ({
147 value: t.id,

Issue box 3: the default option must read 'the forge's own code' (and the built-in Blank/Starter stay listed). Principle 1/8: plain words, one sentence per option. Label the default as the issue says.

148 label: t.id === DEFAULT_TEMPLATE ? `The forge's own code: ${lower(t.says)}` : `${t.title}: ${lower(t.says)}`,
149 selected: t.id === at,
150 })),
151 ...repos.map((ref) => ({ value: ref, label: `${ref}: ${lower(templateOf(ref).says)}`, selected: ref === at })),
152 ];
143153 }
144154
145155 /** The page's words for what the data names in the API's terms (#10787); the data keeps its own. */
@@ -188,7 +198,7 @@ function formView(
188198 plan: Html | null,
189199 reads: Reads,
190200 ): Html {
191 const { full, quota, repos, crew } = reads;
201 const { full, quota, repos, crew, templates } = reads;
192202 if (full)
193203 return html`<div class="narrow-wide" data-forges>
194204 ${pageHead("New forge")}
@@ -358,7 +368,7 @@ function formView(
358368 label: "Template",
359369 name: "template",
360370 hint: "What the new forge starts from besides the apps you fork. Blank is the default.",
361 options: templateOptions(values.template),
371 options: templateOptions(values.template, templates),
362372 ...(errors["template"] ? { error: errors["template"] } : {}),
363373 })}
364374 ${selectField({
test/new-forge.test.ts +2 −2
@@ -138,7 +138,7 @@ describe("+ New forge", () => {
138138 const at = page.indexOf('name="template"');
139139 expect(at).toBeGreaterThan(0);
140140 const field = page.slice(at, page.indexOf("</select>", at));
141 expect(field).toMatch(/<option value="blank" selected >\s*Blank/);
141 expect(field).toMatch(/<option value="blank" selected >\s*The forge&#39;s own code/);
142142 expect(field.indexOf('value="blank"')).toBeLessThan(field.indexOf('value="starter"'));
143143 expect(field).toContain("Starter app");
144144
@@ -154,7 +154,7 @@ describe("+ New forge", () => {
154154 const bad = await post(admin, [["name", "tpl"], ["do", "plan"], ["template", "nope"]]);
155155 expect(bad.status).toBe(422);
156156 const body = await bad.text();
157 expect(body).toContain("template must be blank or starter");
157 expect(body).toContain("template must be blank, starter or the owner/name of a template repository");
158158 expect(body).toContain('value="tpl"');
159159 expect(await children()).toBe(0);
160160 });
test/spawn-template-api.test.ts +2 −2
@@ -95,11 +95,11 @@ describe("choosing a template for a new forge", () => {
9595 expect(res.status).toBe(422);
9696 const body = (await res.json()) as any;
9797 expect(body.error).toBe("invalid");
98 expect(body.message).toBe("template: template must be blank or starter");
98 expect(body.message).toBe("template: template must be blank, starter or the owner/name of a template repository");
9999 }
100100 const viaMcp = await mcp("spawn", { name: "kid", template: "nope" });
101101 expect(viaMcp.error).toBe(true);
102 expect(viaMcp.text).toContain("template: template must be blank or starter");
102 expect(viaMcp.text).toContain("template: template must be blank, starter or the owner/name of a template repository");
103103 });
104104
105105 test("the templates list is public and ETagged", async () => {
test/spawn-template.test.ts added +148
@@ -0,0 +1,148 @@
1 /**
2 * A new forge may name a template (#12432): `owner/name` of a repository an
3 * admin marked, readable by the maker. Its code is the child's own code;
4 * without one the child is today's.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, readFile, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { getRepo } from "../src/core/repos.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { ok } from "../src/kernel/result.ts";
18 import { usePlacement, useProbe } from "../src/spawn/door.ts";
19 import { FORGE_CODE_NAME } from "../src/spawn/forge_code.ts";
20 import { templateNotMarked, templateNotReadable } from "../src/spawn/templates.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22
23 quietLogs();
24
25 describe("a new forge from a template repository", () => {
26 let dir = "";
27 let app: App;
28 let alice: User;
29 let bob: User;
30 let placed = 0;
31
32 let base = "";
33 let servers: Servers;
34 const tokens = new Map<string, string>();
35 /** The door's answer: `ok`, or the refusal's field and words. */
36 const spawn = async (who: User, input: Record<string, unknown>) => {
37 const res = await fetch(`${base}/api/v1/forges`, {
38 method: "POST",
39 headers: { "content-type": "application/json", authorization: `Bearer ${tokens.get(who.id)}` },
40 body: JSON.stringify({ apps: [], dryRun: false, ...input }),
41 });
42 const body = (await res.json()) as { message?: string };
43 return { status: res.status, message: body.message ?? "" };
44 };
45 const fake = {
46 place: async (plan: { name: string }) => ok({ url: `https://${plan.name}.fake.test`, bodyId: `fake-${++placed}` }),
47 retire: async () => ok(),
48 };
49
50 beforeAll(async () => {
51 dir = await mkdtemp(join(tmpdir(), "forge-spawn-template-"));
52 app = createApp({ dataDir: dir, port: 0 });
53 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
54 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
55 if (!a.ok || !b.ok) throw new Error("users");
56 alice = a.value;
57 bob = b.value;
58 for (const u of [alice, bob]) tokens.set(u.id, createToken(app.db, u.id, "rw", "rw").token);
59 servers = await serve(app);
60 base = servers.url;
61 useProbe(app, () => async () => true);
62 usePlacement(app, fake);
63 for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) {
64 const made = await createRepo(app, alice, { name, visibility });
65 if (!made.ok) throw new Error(name);
66 await commitToBranch(app, alice, made.value, { message: "seed", files: [{ path: "kit.txt", content: name }] });
67 }
68 for (const name of ["kit", "secret"]) {
69 const r = getRepo(app.db, "alice", name)!;
70 const done = await updateRepoSettings(app, alice, r, { template: true });
71 if (!done.ok) throw new Error("mark");
72 }
73 }, 30_000);
74
75 afterAll(async () => {
76 servers?.stop();
77 app?.close();
78 await rm(dir, { recursive: true, force: true });
79 });
80
81 test("none is today's path: no template, no template record", async () => {
82 const made = await spawn(alice, { name: "plainkid" });
83 expect(made.status).toBe(201);
84 const parent = JSON.parse(await readFile(join(dir, "children", "fake-1", "parent.json"), "utf8"));
85 expect(parent.template).toBeUndefined();
86 });
87
88 test("a marked template is used: recorded, and its code is the child's", async () => {
89 const made = await spawn(bob, { name: "fromkit", template: "alice/kit" });
90 expect(made.status).toBe(201);
91 const parent = JSON.parse(await readFile(join(dir, "children", `fake-${placed}`, "parent.json"), "utf8"));
92 expect(parent.template).toMatchObject({ id: "alice/kit", repo: "alice/kit" });
93 expect(parent.forgeCode?.upstream).toBe("alice/kit");
94 });
95
96 test("an unmarked repository is refused, and the refusal says which", async () => {
97 const made = await spawn(bob, { name: "fromplain", template: "alice/plain" });
98 expect(made.status).toBe(422);
99 expect(made.message).toContain(`template: ${templateNotMarked("alice/plain")}`);
100 });
101
102 test("a private template the maker cannot read is refused", async () => {
103 const made = await spawn(bob, { name: "fromsecret", template: "alice/secret" });
104 expect(made.status).toBe(422);
105 expect(made.message).toContain(`template: ${templateNotReadable("alice/secret")}`);
106 });
107
108 test("a private template the maker can read gives a child repository that is not public", async () => {
109 const made = await spawn(alice, { name: "fromsecretok", template: "alice/secret" });
110 expect(made.status).toBe(201);
111 const child = createApp({ dataDir: join(dir, "children", `fake-${placed}`) });
112 try {
113 const repo = getRepo(child.db, "fromsecretok", FORGE_CODE_NAME);
114 expect(repo).toBeDefined();
115 expect(repo?.visibility).toBe("private");
116 } finally {
117 child.close();
118 }
119 });
120
121 test("a public template stays public in the child", async () => {
122 const made = await spawn(bob, { name: "frompubkid", template: "alice/kit" });
123 expect(made.status).toBe(201);
124 const child = createApp({ dataDir: join(dir, "children", `fake-${placed}`) });
125 try {
126 expect(getRepo(child.db, "frompubkid", FORGE_CODE_NAME)?.visibility).toBe("public");
127 } finally {
128 child.close();
129 }
130 });
131
132 test("a name that is no repository is refused as unreadable", async () => {
133 const made = await spawn(bob, { name: "fromnone", template: "alice/none" });
134 expect(made.status).toBe(422);
135 expect(made.message).toContain("template: ");
136 });
137
138 test("the New forge page lists only template repositories, in one select", async () => {
139 {
140 const cookie = `forge_session=${createSession(app.db, bob.id).token}`;
141 const html = await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text();
142 expect(html.match(/<select[^>]*name="template"/g)?.length).toBe(1);
143 expect(html).toContain('value="alice/kit"');
144 expect(html).not.toContain('value="alice/plain"');
145 expect(html).not.toContain('value="alice/secret"');
146 }
147 });
148 });
test/tui-newforge.test.ts +40 −2
@@ -6,8 +6,9 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
66 import { mkdtemp, readdir, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
9 import { createRepo, updateRepoSettings } from "../src/actions/repos.ts";
1010 import { createApp, type App } from "../src/app.ts";
11 import { getRepo } from "../src/core/repos.ts";
1112 import { createUser, type User } from "../src/core/users.ts";
1213 import { usePlacement, useProbe } from "../src/spawn/door.ts";
1314 import { hostedPlacement } from "../src/spawn/placement.ts";
@@ -57,6 +58,15 @@ beforeAll(async () => {
5758 bob = await mk("bob", false);
5859 const repo = await createRepo(app, admin, { name: "bakery", visibility: "public" });
5960 if (!repo.ok) throw new Error("repo");
61 // Template repositories: one bob may read, one unmarked, one marked but private to alice.
62 for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) {
63 const made = await createRepo(app, admin, { name, visibility });
64 if (!made.ok) throw new Error(name);
65 }
66 for (const name of ["kit", "secret"]) {
67 const marked = await updateRepoSettings(app, admin, getRepo(app.db, "alice", name)!, { template: true });
68 if (!marked.ok) throw new Error("mark");
69 }
6070 useProbe(app, () => async () => true);
6171 usePlacement(app, hostedPlacement({ host: "forge.test" }));
6272 });
@@ -228,11 +238,39 @@ describe("the new forge screen", () => {
228238 expect(tui.screen.toText()).toContain("Template: Starter app.");
229239 }));
230240
241 test("right past starter chooses a readable template repository; unmarked and unreadable ones are not offered", () =>
242 withScreen(bob, async ({ tui, terminal }) => {
243 terminal.feed("tuikit" + "\t".repeat(10));
244 await settleApp(tui);
245 const seen: string[] = [tui.screen.toText()];
246 for (let i = 0; i < 4; i++) {
247 terminal.feed("\x1b[C"); // right arrow
248 await settleApp(tui);
249 seen.push(tui.screen.toText());
250 }
251 // blank, starter, then alice/kit with that repository's sentence, then round again.
252 expect(seen[1]).toContain("A server, a page, tests and a forge.json");
253 expect(seen[2]).toContain("alice/kit");
254 expect(seen[2]).toContain("The code and apps of that repository.");
255 expect(seen[3]).toContain("Only the apps you fork");
256 for (const text of seen) {
257 expect(text).not.toContain("alice/plain");
258 expect(text).not.toContain("alice/secret");
259 }
260 }));
261
262 test("a typed owner/name gets the repository sentence", () =>
263 withScreen(bob, async ({ tui, terminal }) => {
264 terminal.feed("tuityped" + "\t".repeat(10) + "alice/kit");
265 await settleApp(tui);
266 expect(tui.screen.toText()).toContain("The code and apps of that repository.");
267 }));
268
231269 test("an unknown template is refused beside the field", () =>
232270 withScreen(admin, async ({ tui, terminal }) => {
233271 terminal.feed("tuitpl" + "\t".repeat(10) + "nope\x10");
234272 await settleApp(tui);
235 expect(tui.screen.toText()).toContain("template must be blank or starter");
273 expect(tui.screen.toText()).toContain("template must be blank, starter or the owner/name of a template repository");
236274 }));
237275
238276 test("an unknown size is refused beside the field", () =>

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs