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

The app template is a repository: new apps start from trevato/app-template, and scaffold.ts's strings go #10307

Parked opened this in answer to
Closed without merging

torque/forge:torque/10305-the-app-template-is-a-repository-new-app → main 6 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
39 files changed +1163 −6148
Dockerfile +2
@@ -25,6 +25,8 @@ COPY docs/DESIGN.md ./docs/DESIGN.md
2525 COPY plugins/opencode ./plugins/opencode
2626 # The forge packs /packs lists and deploys (src/packs/catalog.ts reads packs/ at the root).
2727 COPY packs ./packs
28 # The app template every forge can make apps from (src/apps/template.ts).
29 COPY templates ./templates
2830 # src/ alone: nothing under it imports scripts/ or test/ (test/src-imports.test.ts),
2931 # and the boot proof below fails the build if that ever stops being so (#2652).
3032
docs/APPS.md +1 −1
@@ -920,7 +920,7 @@ generous because the first boot migrates.
920920 ## What a new app starts as
921921
922922 **New app** writes a small, complete app into the repository
923 (`src/apps/scaffold.ts`): notes behind a page, a JSON API, an MCP server
923 (the app-template repository, copied by `src/apps/template.ts`; docs/features/app-template.md): notes behind a page, a JSON API, an MCP server
924924 and a terminal, all over one set of actions, with no dependencies. What
925925 the forge already does for every app (identity, the grant, preview data,
926926 health polling, the terminal, the swap, sleep, the contract's wall) is not
docs/SPAWN.md +1 −1
@@ -78,7 +78,7 @@ A spawn may also name a `size`: `small`, `medium` or `large` (`src/spawn/sizes.t
7878
7979 ## Choosing a template (#7533)
8080
81 A template is a named starting point for a new forge's apps, listed in `src/spawn/templates.ts`: each has an `id`, a `title`, one sentence `says`, and a `source` — `builtin` (its files are this forge's code) or `repo` (read from `repo`, an `owner/name` on this forge; none yet, #7536). Built in are `blank`, the default and what a spawn has always made (the forked apps and an optional `fresh` one), and `starter`, the app `/apps/new` starts from (`scaffoldFiles`, `src/apps/scaffold.ts`).
81 A template is a named starting point for a new forge's apps, listed in `src/spawn/templates.ts`: each has an `id`, a `title`, one sentence `says`, and a `source` — `builtin` (its files are this forge's code) or `repo` (read from `repo`, an `owner/name` on this forge; none yet, #7536). Built in are `blank`, the default and what a spawn has always made (the forked apps and an optional `fresh` one), and `starter`, the app `/apps/new` starts from (the baked copy of the app template, `bakedFiles`, `src/apps/template.ts`; see `docs/features/app-template.md`).
8282
8383 `POST /api/v1/forges` and the MCP `spawn` take an optional `template` id. An unknown id is a 422 on `template` naming the valid ids. Absent or `blank`, the plan is the one it always was; any other id is named in the plan, the ledger line, `parent.json` and the child's row in `GET /api/v1/forges` (absent there means `blank`). Because it is in the plan, a retry with another template is refused as a different child. A `starter` child begins with the template's files (#7535, `src/spawn/template_birth.ts`): one commit, no history and no upstream, in a new private repo of the child's organisation named for the `fresh` sentence (which becomes its description; no second repo) or `app`. `parent.json` records `template: {id}`. Only tracked files travel, nothing from the "never copied" list; a retry finds the repo and leaves it.
8484
docs/design/audit.md +1
@@ -141,6 +141,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
141141 - `/settings/crew` — `pages/crew.ts` · the named agents and what each may do · `/settings/model`, `/settings/telemetry` · none seen.
142142 - `/settings/teams` — `pages/teams.ts` · the named crew teams, each with a charter, a dial and members · `/settings/crew` · none seen.
143143 - `/settings/origins` — `pages/origins.ts` (1,497 lines) · other forges this one reads and mirrors from · `/migrate` · none seen.
144 - `/settings/app-templates` — `pages/app_templates.ts` · the repositories New app copies, for an admin · `/settings/origins`, `/apps` · none seen.
144145 - `/settings/security` — `pages/security.ts` · the Shield and the evidence an admin needs to act with no AI · `/settings/traffic`, `/settings/backups` · none seen.
145146 - `/settings/traffic` — `pages/traffic.ts` · who used the answering time in the last 15 minutes · `/settings/usage`, `/settings/telemetry` · none seen.
146147 - `/settings/traffic/sources` — `pages/sources.ts` · where people come from and where they go: sources, campaigns, landing pages, exits, a path to a goal, GitHub traffic; each number links to its probe · `/settings/traffic`, `/settings/traffic/scrapes` · none seen.
docs/features/app-template.md added +9
@@ -0,0 +1,9 @@
1 # The app template is a repository
2
3 New app copies the tracked files of a template repository's default branch at its tip: one commit, no history (#10305).
4
5 - **Which.** `apps.template` (a `forge_setting`, default `trevato/app-template`) names it. Admins mark others under Settings → App templates (`apps.templates`), as rows with an Unmark button each, or in the terminal under "App templates" in the palette (`d` default, `m` mark, `u` unmark); both go through `setAppTemplates`, for an admin who is a person. New app then shows a "Start from" select with the default first, on the web and as a third prompt in the terminal. The same choice is `template` on `POST /api/v1/apps` and the `new_app` MCP tool. A name nobody marked is refused (`no_such_template`).
6 - **Name and description.** The template's `template.json` lists `files` and the literals `name` and `description` to replace in them (`.json` files get the JSON-escaped form). Nothing else is touched, so the template stays runnable and its own tests pass as they are. `template.json` is not copied into the new app. An empty description keeps the template's own line.
7 - **A copy in every forge.** `templates/app-template.json` is the template's files, carried in the image (`Dockerfile` copies `templates/`). A forge without the repository — a child, a pack forge, a fresh install — uses it, as does a repository whose `template.json` is unreadable. `src/spawn/template_birth.ts` uses it too. Refresh it with `bun scripts/take-template.ts <checkout of the template>`, which records the checkout's HEAD as `commit`. **Not done yet:** the file in the tree was generated from the strings this change removes, so its `commit` (1428266e) is the forge commit they were written at, not a commit of trevato/app-template, and the release build does not yet run `take-template.ts` against the repository at a pinned commit. Until it does, the baked copy and the repository can differ.
8 - **Checked both ways.** In the template's repository a pull runs its own `bun test`, then `bun scripts/birth-check.ts <checkout>` from this repository, which births an app from the tip with `fillTemplate` and boots it, waiting on `/healthz` and `/`.
9 - **Code.** `src/apps/template.ts` (read, fill, choose), `src/actions/app_templates.ts`, `src/web/pages/app_templates.ts` and `src/tui/screens/app_templates.ts` (marking). A template's `template.json` is untrusted: its paths are checked by `safePath` (no `..`, absolute, `.git`, backslash or control bytes; at most 50 listed), and a repository read is capped at 500 files, 1 MB each and 8 MB in all, by the bytes read. Tests: `test/app-template.test.ts`, `test/app-templates-surfaces.test.ts`.
scripts/birth-check.ts added +61
@@ -0,0 +1,61 @@
1 /**
2 * `bun scripts/birth-check.ts <checkout>`: the second half of a template
3 * pull's check (#10305). Births an app from the checkout's tracked files
4 * exactly as New app does (`fillTemplate`), writes it to a scratch
5 * directory, boots it on a free port with its own data directory and waits
6 * for `/healthz`. The template's own `bun test` is the first half and runs
7 * in the checkout itself. Exits 0 when the born app answers, 1 when not.
8 */
9
10 import { mkdtemp, mkdir, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { dirname, join } from "node:path";
13 import { fillTemplate } from "../src/apps/template.ts";
14
15 const [dir] = process.argv.slice(2);
16 if (dir === undefined) {
17 console.error("usage: bun scripts/birth-check.ts <checkout>");
18 process.exit(2);
19 }
20 const listed = Bun.spawnSync(["git", "-C", dir, "ls-files", "-z"], { stdout: "pipe", stderr: "pipe" });
21 if (listed.exitCode !== 0) {
22 console.error(`birth-check: not a git checkout: ${listed.stderr.toString().trim()}`);
23 process.exit(1);
24 }
25 const paths = listed.stdout.toString().split("\0").filter((p) => p !== "");
26 const files = await Promise.all(paths.map(async (path) => ({ path, content: new Uint8Array(await Bun.file(join(dir, path)).arrayBuffer()) })));
27 const born = fillTemplate({ files, from: "checkout", commit: "" }, { name: "born-from-template", description: "Born in the template check." });
28 if (born === undefined) {
29 console.error("birth-check: template.json is missing or unreadable");
30 process.exit(1);
31 }
32
33 const work = await mkdtemp(join(process.env["TMPDIR"] ?? tmpdir(), "birth-check-"));
34 let child: ReturnType<typeof Bun.spawn> | undefined;
35 try {
36 for (const f of born) {
37 const to = join(work, "app", f.path);
38 await mkdir(dirname(to), { recursive: true });
39 await Bun.write(to, f.content ?? "");
40 }
41 const port = 20000 + Math.floor(Math.random() * 20000);
42 child = Bun.spawn(["bun", "run", "src/server.ts"], {
43 cwd: join(work, "app"),
44 env: { PATH: process.env["PATH"] ?? "", PORT: String(port), FORGE_APP_DATA: join(work, "data"), FORGE_APP_ENV: "preview" },
45 stdout: "ignore",
46 stderr: "inherit",
47 });
48 let up = false;
49 for (let i = 0; i < 100 && !up; i++) {
50 await Bun.sleep(100);
51 up = await fetch(`http://127.0.0.1:${port}/healthz`).then((r) => r.ok, () => false);
52 }
53 const home = up ? await fetch(`http://127.0.0.1:${port}/`).then((r) => r.text(), () => "") : "";
54 if (!up || !home.includes("born-from-template")) {
55 console.error(`birth-check: the born app ${up ? "answers / without its name" : "did not answer /healthz"}`);
56 process.exitCode = 1;
57 } else console.log(`birth-check: born from ${paths.length} files, booted, / answers`);
58 } finally {
59 child?.kill();
60 await rm(work, { recursive: true, force: true });
61 }
scripts/take-template.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * `bun scripts/take-template.ts <checkout> [owner/name]`: write
3 * `templates/app-template.json`, the copy of the app template every forge
4 * carries in its image (#10305), from a checkout of the template repository.
5 * The tracked files at HEAD are taken as they are and HEAD is recorded as
6 * `commit` in the bundle. It is meant to run on a checkout of
7 * trevato/app-template at the commit a release pins (the release build does
8 * not do so yet); a checkout without a
9 * readable `template.json` is refused.
10 */
11
12 import { parseTemplateSpec } from "../src/apps/template.ts";
13
14 const [dir, repo = "trevato/app-template"] = process.argv.slice(2);
15 if (dir === undefined) {
16 console.error("usage: bun scripts/take-template.ts <checkout> [owner/name]");
17 process.exit(2);
18 }
19 const git = (...args: string[]): string => {
20 const r = Bun.spawnSync(["git", "-C", dir, ...args], { stdout: "pipe", stderr: "pipe" });
21 if (r.exitCode !== 0) {
22 console.error(`take-template: git ${args[0]} failed: ${r.stderr.toString().trim()}`);
23 process.exit(1);
24 }
25 return r.stdout.toString();
26 };
27 const commit = git("rev-parse", "HEAD").trim();
28 const paths = git("ls-files", "-z").split("\0").filter((p) => p !== "").sort();
29 const files: Record<string, string> = {};
30 for (const p of paths) files[p] = await Bun.file(`${dir}/${p}`).text();
31 if (files["template.json"] === undefined || parseTemplateSpec(files["template.json"]) === undefined) {
32 console.error("take-template: the checkout has no readable template.json");
33 process.exit(1);
34 }
35 await Bun.write(
36 `${import.meta.dir}/../templates/app-template.json`,
37 `${JSON.stringify({ repo, commit, files }, null, 1)}\n`,
38 );
39 console.log(`took ${paths.length} files of ${repo} at ${commit}`);
src/actions/app_templates.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * Which repositories are app templates on this forge (#10305): the default
3 * (`apps.template`) and the others an admin has marked (`apps.templates`,
4 * comma separated). Each is one `forge_setting` row with its change kept
5 * (`writeSetting`). A marked name must be a repository that exists here and
6 * carries a readable `template.json`, so New app never offers a repository
7 * it cannot copy. A person who is a forge admin only: an agent that could
8 * mark templates would choose what every new app starts as.
9 */
10
11 import type { App } from "../app.ts";
12 import { loadTemplate, templateChoices, DEFAULT_TEMPLATE, TEMPLATE_SETTING, TEMPLATES_SETTING, isTemplateSlug, parseTemplateSpec } from "../apps/template.ts";
13 import { getRepo } from "../core/repos.ts";
14 import type { User } from "../core/users.ts";
15 import { err, ok, type Result } from "../kernel/result.ts";
16 import { writeSetting } from "../settings/limits.ts";
17
18 export type AppTemplateError = "not_found" | "bad_slug" | "not_a_template" | "too_many";
19
20 export const APP_TEMPLATE_WORDS: Record<Exclude<AppTemplateError, "not_found">, string> = {
21 bad_slug: "a template is named owner/name",
22 not_a_template: "that repository is not here or has no readable template.json at its default branch's tip",
23 too_many: "mark at most 20 templates",
24 };
25
26 export interface AppTemplatesView {
27 readonly defaultSlug: string;
28 readonly marked: readonly string[];
29 }
30
31 const MARKED_MAX = 20;
32
33 export function readAppTemplates(app: App, actor: User | undefined): Result<AppTemplatesView, "not_found"> {
outdated

Admin-only is correct, but nothing here shows the settings route checks CSRF/same-origin on the POST; confirm settings_routes.ts uses the same mutation guard as its neighbours, and add a test that a non-admin and an agent get not_found on set as well as read.

34 if (actor?.isAdmin !== true || actor.kind === "agent") return err("not_found");
35 const choices = templateChoices(app);
36 return ok({ defaultSlug: choices[0]!, marked: choices.slice(1) });
37 }
38
39 /**
40 * Change the templates: set the default (an empty one is `trevato/app-template`
41 * again), mark one more, or unmark one. Slugs compare without case.
42 */
43 export async function setAppTemplates(
44 app: App,
45 actor: User | undefined,
46 change: { readonly defaultSlug?: string; readonly mark?: string; readonly unmark?: string },
47 ): Promise<Result<AppTemplatesView, AppTemplateError>> {
48 const read = readAppTemplates(app, actor);
49 if (!read.ok) return read;
50 const was = { def: read.value.defaultSlug, marked: read.value.marked };
51 const def = canonical(app, change.defaultSlug === undefined ? was.def : change.defaultSlug.trim() || DEFAULT_TEMPLATE);
52 const add = canonical(app, (change.mark ?? "").trim());
outdated

Dead and confusing: this reads the template, skips if undefined, and then reads it again on the next line. Drop the first read and the continue. If the built-in default is meant to pass via the baked copy, make readTemplate return that copy and delete this special case. Also the marked list is deduplicated case-sensitively (line 47) but filtered case-insensitively below: lowercase once.

53 const drop = (change.unmark ?? "").trim().toLowerCase();
54 if (!isTemplateSlug(def) || (add !== "" && !isTemplateSlug(add))) return err("bad_slug");
55 const seen = new Set<string>([def.toLowerCase()]);
56 const marked: string[] = [];
57 for (const s of [...was.marked, ...(add === "" ? [] : [add])]) {
58 const key = s.toLowerCase();
59 if (key === drop || seen.has(key)) continue;
60 seen.add(key);
61 marked.push(s);
62 }
63 if (marked.length > MARKED_MAX) return err("too_many");
64 // Only what is newly named is read: a template that stopped being one
65 // must still be unmarkable.
66 for (const slug of [def, add].filter((s) => s !== "" && !was.marked.concat(was.def).includes(s))) {
67 if (!(await isTemplate(app, slug))) return err("not_a_template");
68 }
69 const id = actor!.id;
70 const list = marked.join(",");
71 if (was.def !== def) writeSetting(app.db, TEMPLATE_SETTING, def === DEFAULT_TEMPLATE ? null : def, was.def, def, id);
72 if (was.marked.join(",") !== list)
73 writeSetting(app.db, TEMPLATES_SETTING, list === "" ? null : list, was.marked.join(","), list, id);
74 return readAppTemplates(app, actor) as Result<AppTemplatesView, AppTemplateError>;
75 }
76
77 /** A repository's name as it is spelled here; any other string as given. */
78 function canonical(app: App, slug: string): string {
79 if (!isTemplateSlug(slug)) return slug;
80 const [owner, name] = slug.split("/") as [string, string];
81 const repo = getRepo(app.db, owner, name);
82 return repo ? `${repo.ownerName}/${repo.name}` : slug;
83 }
84
85 /** Whether `slug` is a repository here with a readable `template.json` (the default always is: the image carries it). */
86 async function isTemplate(app: App, slug: string): Promise<boolean> {
87 const copy = await loadTemplate(app, slug);
88 const spec = copy?.files.find((f) => f.path === "template.json");
89 if (spec === undefined) return false;
90 const body = typeof spec.content === "string" ? spec.content : new TextDecoder().decode(spec.content ?? new Uint8Array());
91 return parseTemplateSpec(body) !== undefined;
92 }
src/actions/apps.ts +18 −5
@@ -22,7 +22,7 @@ import { appVitals, type AppVitals } from "../apps/vitals.ts";
2222 import { appsRuntime, envsFor, type EnvStatus } from "../apps/runtime.ts";
2323 import { grantUrl, originFor, sideForViewer, sideReader } from "../apps/proxy.ts";
2424 import { plainLine } from "../apps/side.ts";
25 import { scaffoldFiles } from "../apps/scaffold.ts";
25 import { scaffoldFiles, templateChoices } from "../apps/template.ts";
2626 import {
2727 envBuild,
2828 isEnvName,
@@ -270,6 +270,8 @@ export interface NewAppInput {
270270 * also given.
271271 */
272272 pickAgent?: boolean;
273 /** An app template marked on this forge (`owner/name`); the forge's default when absent. */
274 template?: string;
273275 }
274276
275277 export interface NewAppResult {
@@ -285,6 +287,7 @@ export type NewAppError =
285287 | CreateRepoActionError
286288 | CreateAppError
287289 | "scaffold_failed"
290 | "no_such_template"
288291 | "no_such_agent"
289292 | "not_a_builder"
290293 | "app_limit";
@@ -312,6 +315,14 @@ export async function newApp(
312315 if (input.agent && !agent) return err("no_such_agent");
313316 if (agent && !agent.roles.includes("builder")) return err("not_a_builder");
314317
318 // A template is one an admin marked; any other slug is refused here, not read.
319 const choices = templateChoices(app);
320 const template =
321 input.template === undefined || input.template === ""
322 ? choices[0]
323 : choices.find((c) => c.toLowerCase() === input.template?.toLowerCase());
324 if (template === undefined) return err("no_such_template");
325
315326 // Refuse at the limit before a repository exists to take back.
316327 // The owner is resolved with the actor's rights, as createRepo does, so
317328 // the count of an account they may not create under is never told.
@@ -344,10 +355,11 @@ export async function newApp(
344355 if (!repo.ok) return repo;
345356 const committed = await commitToBranch(app, user.value, repo.value, {
346357 message: `Start ${input.name}`,
347 files: scaffoldFiles({
348 name: input.name,
349 description: input.description ?? "",
350 }),
358 files: await scaffoldFiles(
359 app,
360 { name: input.name, description: input.description ?? "" },
361 template,
362 ),
351363 });
352364 lap("scaffold");
353365 if (!committed.ok) {
@@ -462,6 +474,7 @@ export const NEW_APP_ERRORS: Record<string, string> = {
462474 "Another app already answers to that hostname. Pick another name.",
463475 already_app: "That repository is already an app.",
464476 scaffold_failed: "The starter app could not be committed.",
477 no_such_template: "That is not an app template on this forge.",
465478 no_such_agent: NO_SUCH_AGENT,
466479 not_a_builder: "That agent is not a builder, so it cannot be handed a new app. Pick a builder.",
467480 };
src/apps/scaffold.ts deleted −6112

Diff not shown — 6,112 changed lines (limit 5,000). −6112

View file
src/apps/template.ts added +211
@@ -0,0 +1,211 @@
1 /**
2 * The app a new app starts as is a repository (#10305): `apps.template`
3 * names it (default `trevato/app-template`), and New app copies its tracked
4 * files at the default branch's tip — one commit, no history. Where the
5 * forge has no such repository (a child forge, a pack forge, a fresh
6 * install) the copy baked into the image is used: `templates/app-template.json`,
7 * taken from the repository by `scripts/take-template.ts` (not yet at a release-pinned commit: see docs/features/app-template.md).
8 *
9 * `template.json` in the template says which files carry the app's name and
10 * description and the literals standing in for them; the forge replaces
11 * those and leaves the rest byte for byte, so the template stays runnable
12 * and its own tests pass as they are. `template.json` itself is not copied.
13 */
14
15 import { readFileSync } from "node:fs";
16 import type { App } from "../app.ts";
17 import { getRepo } from "../core/repos.ts";
18 import { listPaths, readerFor } from "../git/read.ts";
19 import { repoDir } from "../git/repos.ts";
20 import type { FileWrite } from "../git/write.ts";
21
22 export const DEFAULT_TEMPLATE = "trevato/app-template";
23 export const TEMPLATE_SETTING = "apps.template";
24 export const TEMPLATES_SETTING = "apps.templates";
25
26 const FILES_MAX = 500;
27 const FILE_BYTES_MAX = 1_000_000;
28 const TOTAL_BYTES_MAX = 8_000_000;
29 const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
30
31 export interface ScaffoldInput {
32 /** The repository name; also the title on the page. */
33 readonly name: string;
34 /** What the app should become. Shown on the page until it does. */
35 readonly description: string;
36 }
37
38 /** What `template.json` declares. */
39 export interface TemplateSpec {
40 /** The literal standing in for the app's name. */
41 readonly name: string;
42 /** The literal standing in for its description (also the default one). */
43 readonly description: string;
44 /** The files that carry those literals. */
45 readonly files: readonly string[];
46 }
47
48 /** A template as copied: its files, with `template.json` among them. */
49 export interface TemplateCopy {
50 readonly files: readonly FileWrite[];
51 /** Where it came from: `owner/name`, and the tip or pinned commit. */
52 readonly from: string;
53 readonly commit: string;
54 }
55
56 export const isTemplateSlug = (s: string): boolean => SLUG.test(s);
57
58 /** A safe relative path: no dot segments, no `.git`, no absolute or odd bytes. */
59 function safePath(path: string): boolean {
60 if (path === "" || path.length > 300 || path.startsWith("/") || /[\x00-\x1f\x7f\\]/.test(path)) return false;
61 return path.split("/").every((p) => p !== "" && p !== "." && p !== ".." && p.toLowerCase() !== ".git");
62 }
63
64 /** Parse `template.json`; undefined when it is not what the forge reads. */
65 export function parseTemplateSpec(text: string): TemplateSpec | undefined {
66 let raw: unknown;
67 try {
68 raw = JSON.parse(text);
69 } catch {
70 return undefined;
71 }
72 if (typeof raw !== "object" || raw === null) return undefined;
73 const { name, description, files } = raw as Record<string, unknown>;
74 if (typeof name !== "string" || name === "" || name.length > 100) return undefined;
75 if (typeof description !== "string" || description === "" || description.length > 500) return undefined;
76 if (!Array.isArray(files) || files.length > 50) return undefined;
77 if (!files.every((f) => typeof f === "string" && safePath(f))) return undefined;
78 return { name, description, files: files as string[] };
79 }
80
81 const text = (f: FileWrite): string =>
82 typeof f.content === "string" ? f.content : new TextDecoder().decode(f.content ?? new Uint8Array());
83
84 /** A literal as it sits inside a JSON string. */
85 const jsonInner = (s: string): string => JSON.stringify(s).slice(1, -1);
86
87 /**
88 * Replace the declared literals in the declared files, once each, as plain
89 * text (a `.json` file gets the JSON-escaped form). Everything else is the
90 * template's own bytes. Undefined when the template has no readable
91 * `template.json`.
92 */
93 export function fillTemplate(copy: TemplateCopy, input: ScaffoldInput): FileWrite[] | undefined {
94 const spec = copy.files.find((f) => f.path === "template.json");
95 const parsed = spec === undefined ? undefined : parseTemplateSpec(text(spec));
96 if (parsed === undefined) return undefined;
97 const description = input.description.trim() || parsed.description;
98 const carriers = new Set(parsed.files);
99 const out: FileWrite[] = [];
100 for (const f of copy.files) {
101 if (f.path === "template.json") continue;
102 if (!carriers.has(f.path) || f.content === null) {
103 out.push(f);
104 continue;
105 }
106 const json = f.path.endsWith(".json");
107 const esc = (s: string): string => (json ? jsonInner(s) : s);
108 // Description first: the name literal can sit inside it.
109 const body = text(f)
110 .split(esc(parsed.description))
111 .join("\u0000D\u0000")
112 .split(esc(parsed.name))
113 .join(esc(input.name))
114 .split("\u0000D\u0000")
115 .join(esc(description));
116 out.push({ ...f, content: body });
117 }
118 return out;
119 }
120
121 let baked: TemplateCopy | undefined;
122
123 /** The copy in the image. */
124 export function bakedTemplate(): TemplateCopy {
125 if (baked) return baked;
126 const raw = JSON.parse(
127 readFileSync(new URL("../../templates/app-template.json", import.meta.url), "utf8"),
128 ) as { repo: string; commit: string; files: Record<string, string> };
129 baked = {
130 from: raw.repo,
131 commit: raw.commit,
132 files: Object.entries(raw.files).map(([path, content]) => ({ path, content })),
133 };
134 return baked;
135 }
136
137 /** The baked copy filled in for an app, synchronously. */
138 export function bakedFiles(input: ScaffoldInput): FileWrite[] {
139 const files = fillTemplate(bakedTemplate(), input);
140 if (!files) throw new Error("the baked app template has no readable template.json");
141 return files;
142 }
143
144 /** The template this forge names, `owner/name`. */
145 export function templateSlug(app: App): string {
146 const row = app.db
147 .query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1")
148 .get(TEMPLATE_SETTING);
149 return row !== null && isTemplateSlug(row.value) ? row.value : DEFAULT_TEMPLATE;
150 }
151
152 /**
153 * The repositories admins have marked as app templates: the default first,
154 * then the marked ones in the order marked. Slugs only; whether each exists
155 * is for `readTemplate`.
156 */
157 export function templateChoices(app: App): string[] {
158 const row = app.db
159 .query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1")
160 .get(TEMPLATES_SETTING);
161 const marked = (row?.value ?? "").split(",").map((s) => s.trim()).filter(isTemplateSlug);
162 const first = templateSlug(app);
163 return [first, ...marked.filter((s) => s.toLowerCase() !== first.toLowerCase())];
164 }
165
166 /** The tracked files of `owner/name` at its default branch's tip, or undefined. */
167 export async function readTemplate(app: App, slug: string): Promise<TemplateCopy | undefined> {
168 if (!isTemplateSlug(slug)) return undefined;
169 const [owner, name] = slug.split("/") as [string, string];
170 const repo = getRepo(app.db, owner, name);
171 if (!repo) return undefined;
172 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
173 const rev = `refs/heads/${repo.defaultBranch}`;
174 const listed = await listPaths(dir, rev, FILES_MAX + 1);
175 if (!listed.ok || listed.value.truncated || listed.value.paths.length > FILES_MAX || listed.value.paths.length === 0)
176 return undefined;
177 const reader = readerFor(dir);
178 const commit = await reader.stat(rev);
179 if (!commit.ok) return undefined;
180 const files: FileWrite[] = [];
181 let total = 0;
182 for (const path of listed.value.paths) {
183 if (!safePath(path)) return undefined;
184 const obj = await reader.object(`${rev}:${path}`);
185 if (!obj.ok || obj.value.type !== "blob" || obj.value.body.length > FILE_BYTES_MAX) return undefined;
186 total += obj.value.body.length;
187 if (total > TOTAL_BYTES_MAX) return undefined;
188 files.push({ path, content: obj.value.body });
189 }
190 return { files, from: slug, commit: commit.value.oid };
191 }
192
193 /** `readTemplate`, or the image's copy for the default where this forge lacks the repository. */
194 export async function loadTemplate(app: App, slug: string): Promise<TemplateCopy | undefined> {
195 const copy = await readTemplate(app, slug);
196 return copy ?? (slug.toLowerCase() === DEFAULT_TEMPLATE ? bakedTemplate() : undefined);
197 }
198
199 /**
200 * The files for a new app: from the named template (default: the forge's),
201 * else the baked copy. A repository whose `template.json` is missing or
202 * unreadable is not a template, and the baked copy stands in.
203 */
204 export async function scaffoldFiles(
205 app: App,
206 input: ScaffoldInput,
207 slug: string = templateSlug(app),
208 ): Promise<FileWrite[]> {
209 const copy = await readTemplate(app, slug);
210 return (copy && fillTemplate(copy, input)) ?? bakedFiles(input);
211 }
src/contract/openapi/routes/postApiV1Apps.ts +1 −1
@@ -1,7 +1,7 @@
11 import type { Route } from "../shared.ts";
22
33 /** What `POST /api/v1/apps` reads from its body, and the refusals it answers. */
4 const APP_BODY = { name: "string", owner: "string", description: "string", sentence: "string", visibility: "string", agent: "string", pick: "boolean" };
4 const APP_BODY = { name: "string", owner: "string", description: "string", sentence: "string", visibility: "string", agent: "string", pick: "boolean", template: "string" };
55 const APP_REFUSALS = {
66 unverified: "the account has not verified its email",
77 no_name: "no `name`, and the `sentence` leaves nothing to make one from",
src/http/api.ts +1
@@ -3551,6 +3551,7 @@ export function apiRoutes(router: Router<Handler>): void {
35513551 ? { visibility: input.visibility }
35523552 : {}),
35533553 ...(typeof input.agent === "string" ? { agent: input.agent } : {}),
3554 ...(typeof input.template === "string" ? { template: input.template } : {}),
35543555 // Only a real boolean asks; like the other fields, anything else is ignored.
35553556 ...(input.pick === true ? { pickAgent: true } : {}),
35563557 };
src/http/mcp/tools/new_app.ts +4 −1
@@ -19,7 +19,7 @@ async function fromSentence(app: App, user: User, sentence: string, input: Omit<
1919
2020 export const tool: Tool = {
2121 name: "new_app",
22 doc: "`{ name?, sentence?, description?, owner?, visibility?, agent?, pick? }`: make an app from a sentence: with `sentence` and no `name` the name is derived from it (`-2`, `-3` when taken), as the web and terminal do; `name` and `sentence` together keep the name; the first issue is `description`, else `sentence`; answers `{ repo, url, issue, agent, run }` (`run` is the first run's state, or `none`) and draws the `ui://forge/app` card: name, production URL, first issue, agent, first run; refused as `POST /api/v1/apps` is (unverified, app_limit, no_such_agent, name_taken)",
22 doc: "`{ name?, sentence?, description?, owner?, visibility?, agent?, pick?, template? }`: make an app from a sentence: with `sentence` and no `name` the name is derived from it (`-2`, `-3` when taken), as the web and terminal do; `name` and `sentence` together keep the name; the first issue is `description`, else `sentence`; answers `{ repo, url, issue, agent, run }` (`run` is the first run's state, or `none`) and draws the `ui://forge/app` card: name, production URL, first issue, agent, first run; refused as `POST /api/v1/apps` is (unverified, app_limit, no_such_agent, name_taken)",
2323 description:
2424 "Make an app from a sentence: a repo, production, and with `description` a first issue.",
2525 inputSchema: {
@@ -32,6 +32,7 @@ export const tool: Tool = {
3232 visibility: { type: "string", enum: ["public", "private"] },
3333 agent: { type: "string", maxLength: 39 },
3434 pick: { type: "boolean" },
35 template: { type: "string", maxLength: 200, description: "An app template marked on this forge, owner/name." },
3536 },
3637 },
3738 writes: true,
@@ -42,10 +43,12 @@ export const tool: Tool = {
4243 const description = text("description");
4344 const agent = text("agent");
4445 const sentence = text("sentence");
46 const template = text("template");
4547 const rest: Omit<NewAppInput, "name" | "description"> = {
4648 ...(owner === undefined ? {} : { owner }),
4749 ...(visibility === "public" || visibility === "private" ? { visibility } : {}),
4850 ...(agent === undefined ? {} : { agent }),
51 ...(template === undefined ? {} : { template }),
4952 ...(args["pick"] === true ? { pickAgent: true } : {}),
5053 };
5154 const given = str(args["name"]).trim();
src/http/settings_routes.ts +3
@@ -15,6 +15,7 @@ import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1515 import { teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts";
1616 import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts";
1717 import { flagsPage, flagsSet } from "../web/pages/flags.ts";
18 import { appTemplatesPage, appTemplatesSet } from "../web/pages/app_templates.ts";
1819 import { economicsPage, economicsSet } from "../web/pages/economics.ts";
1920 import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts";
2021 import { usagePage } from "../web/pages/usage.ts";
@@ -183,6 +184,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
183184 router.add("POST", "/settings/capacity", capacitySet);
184185 router.add("GET", "/settings/economics", economicsPage);
185186 router.add("POST", "/settings/economics", economicsSet);
187 router.add("GET", "/settings/app-templates", appTemplatesPage);
188 router.add("POST", "/settings/app-templates", appTemplatesSet);
186189 router.add("GET", "/settings/flags", flagsPage);
187190 // Apps absorbed as the forge's own features, and their settings.
188191 router.add("GET", "/settings/features", featuresPage);
src/kernel/signin_words.ts +1 −1
@@ -2,7 +2,7 @@
22 * What a sign-in flow says when its return cannot be finished: the state
33 * did not come back to the browser that began, or the login it names is
44 * gone (spent, or past its time). The parent sign-in (`http/rp.ts`) and the
5 * sign-in an app's scaffold writes (`apps/scaffold.ts`) say the same thing,
5 * sign-in an app's scaffold writes (`templates/app-template.json`) say the same thing,
66 * so it is said here once.
77 */
88 export const SIGNIN_NOT_THIS_BROWSER = "This sign-in did not start in this browser.";
src/spawn/template_birth.ts +3 −3
@@ -8,7 +8,7 @@
88 */
99
1010 import type { App } from "../app.ts";
11 import { scaffoldFiles } from "../apps/scaffold.ts";
11 import { bakedFiles } from "../apps/template.ts";
1212 import { createRepo, getRepo, updateRepoSettings } from "../core/repos.ts";
1313 import { runGit } from "../git/env.ts";
1414 import { repoDir } from "../git/repos.ts";
@@ -23,9 +23,9 @@ export interface TemplateMark {
2323 readonly tip?: string;
2424 }
2525
26 /** The files a built-in template holds, for the app's name and description. */
26 /** The files the baked app template holds (`templates/app-template.json`, #10305), for the app's name and description. */
2727 export function templateFiles(id: string, name: string, description: string): FileWrite[] | undefined {
28 if (id === "starter") return scaffoldFiles({ name, description });
28 if (id === "starter") return bakedFiles({ name, description });
2929 return undefined;
3030 }
3131
src/tui/screens/app_templates.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * App templates in the terminal, a forge admin's who is a person: the
3 * repository New app copies by default and the others marked as templates,
4 * as Settings → App templates has them (#10305). `d` sets the default,
5 * `m` marks one more, `u` unmarks the one under the cursor — each through
6 * `setAppTemplates`, so the gate and the checks are the action's: anyone
7 * else sees nothing and changes nothing.
8 */
9
10 import { APP_TEMPLATE_WORDS, readAppTemplates, setAppTemplates, type AppTemplateError } from "../../actions/app_templates.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import { style } from "../term/style.ts";
14 import { truncate } from "../term/width.ts";
15 import type { Session } from "../session.ts";
16 import { fill, len, split } from "../ui/layout.ts";
17 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
18 import type { PaletteEntry } from "./entries.ts";
19
20 export function appTemplatesScreen(f: Session, ctx: Ctx): Screen {
21 const state = new ListState();
22 let note = "";
23 const read = () => readAppTemplates(f.app, f.user);
24 const slugs = (): string[] => {
25 const r = read();
26 return r.ok ? [r.value.defaultSlug, ...r.value.marked] : [];
27 };
28
29 const change = async (c: { defaultSlug?: string; mark?: string; unmark?: string }, done: string): Promise<void> => {
30 const made = await setAppTemplates(f.app, f.user, c);
31 note = made.ok
32 ? done
33 : made.error === "not_found"
34 ? "App templates are set by a forge admin."
35 : `${APP_TEMPLATE_WORDS[made.error as Exclude<AppTemplateError, "not_found">]}.`;
36 ctx.invalidate();
37 };
38
39 const ask = (title: string, label: string, run: (slug: string) => Promise<void>): void => {
40 ctx.push(
41 promptScreen(ctx, screen, {
42 title,
43 label,
44 placeholder: "owner/name",
45 onSubmit: (slug) => run(slug.trim()).then(() => undefined as void),
46 }),
47 );
48 };
49
50 const screen: Screen = {
51 title: "App templates",
52 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "set default"), binding(["m"], "mark"), binding(["u"], "unmark")],
53 render(area, s) {
54 const c = ctx.theme.c;
55 const [head, list] = split(area, "v", [len(1), fill(1)]);
56 const r = read();
57 const text =
58 note !== ""
59 ? note
60 : r.ok
61 ? "New app copies these. d default, m mark, u unmark."
62 : "App templates are set by a forge admin.";
63 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
64 const rows: ListRow[] = slugs().map((slug, i) => ({
65 title: slug,
66 secondary: i === 0 ? "default" : "marked",
67 }));
68 drawList(s, list!, c, state, rows);
69 },
70 key(e) {
71 const all = slugs();
72 if (state.key(e, all.length)) return true;
73 if (e.ctrl || e.alt) return false;
74 if (e.key === "d") {
75 ask("Default template", "owner/name, empty for trevato/app-template", (slug) =>
76 change({ defaultSlug: slug }, "The default template is set."),
77 );
78 return true;
79 }
80 if (e.key === "m") {
81 ask("Mark a template", "owner/name", (slug) => change({ mark: slug }, `${slug} is marked.`));
82 return true;
83 }
84 if (e.key === "u") {
85 const slug = all[state.index];
86 if (slug === undefined || state.index === 0) {
87 note = "The default is changed with d, not unmarked.";
88 ctx.invalidate();
89 return true;
90 }
91 void change({ unmark: slug }, `${slug} is unmarked.`);
92 return true;
93 }
94 return false;
95 },
96 };
97 return screen;
98 }
99
100 /** App templates, as Settings → App templates has them: an admin who is not an agent. */
101 export const entry: PaletteEntry = {
102 id: "app-templates",
103 title: "App templates",
104 hint: "the repositories New app copies; mark or unmark one",
105 after: ["limits", "economics"],
106 offered: (session) => session.user?.isAdmin === true && session.user.kind !== "agent",
107 run: (session, ctx) => ctx.push(appTemplatesScreen(session, ctx)),
108 };
src/tui/screens/entries.ts +2
@@ -36,6 +36,7 @@ import { entry as forges } from "./forges.ts";
3636 import { entry as homePins } from "./home_pins.ts";
3737 import { entry as invites } from "./invites.ts";
3838 import { entry as limits } from "./limits.ts";
39 import { entry as appTemplates } from "./app_templates.ts";
3940 import { entry as economics } from "./economics.ts";
4041 import { entry as loopStalls } from "./loopstalls.ts";
4142 import { entry as maintenance } from "./maintenance.ts";
@@ -104,6 +105,7 @@ export const ENTRIES: readonly PaletteEntry[] = [
104105 people,
105106 quotas,
106107 limits,
108 appTemplates,
107109 economics,
108110 flowsAll,
109111 scrapes,
src/tui/screens/newapp.ts +28 −9
@@ -3,13 +3,15 @@
33 * made from it, as the web form's blank-name path makes it —
44 * `newAppFromSentence` names it, scaffolds it, starts production and puts the
55 * crew on the first issue. When the person is in organizations a second
6 * prompt asks who owns it. The scaffold runs under `runAsync`, so no other
6 * prompt asks who owns it, and when an admin has marked more than one app
7 * template a third asks which to start from (#10305). The scaffold runs under `runAsync`, so no other
78 * session waits on it; success lands on the new repository.
89 */
910
1011 import { appLimitWords } from "../../actions/app_limit.ts";
1112 import { NEW_APP_ERRORS, NO_NAME_ERROR, newAppFromSentence } from "../../actions/apps.ts";
1213 import { repositoryLimitMessage } from "../../actions/repos.ts";
14 import { templateChoices } from "../../apps/template.ts";
1315 import { appsRuntime } from "../../apps/runtime.ts";
1416 import { listOrgsForUser } from "../../core/orgs.ts";
1517 import { storageLimitMessage } from "../../core/storage.ts";
@@ -33,10 +35,10 @@ export function newAppScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
3335 ? [f.user.username, ...listOrgsForUser(f.db, f.user.id).map((o) => o.username)]
3436 : [];
3537
36 const make = (sentence: string, owner: string): void => {
38 const make = (sentence: string, owner: string, template: string): void => {
3739 ctx.toast("Making your app… the crew starts on it next.");
3840 runAsync(ctx, async () => {
39 const made = await newAppFromSentence(f.app, f.user, { sentence, owner });
41 const made = await newAppFromSentence(f.app, f.user, { sentence, owner, ...(template === "" ? {} : { template }) });
4042 if (!made.ok) {
4143 ctx.toast(refusal(f, made.code, f.user!.id), "danger");
4244 return;
@@ -59,10 +61,28 @@ export function newAppScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
5961 hint: "One sentence; the app is named from it.",
6062 onSubmit: (sentence) => {
6163 if (deriveAppName(sentence) === undefined) return NO_NAME_ERROR;
62 if (owners.length < 2) {
63 make(sentence, owners[0] ?? "");
64 return undefined;
65 }
64 // Owner, then template, each asked only when there is a choice.
65 const askTemplate = (owner: string): string | undefined | Promise<void> => {
66 const choices = templateChoices(f.app);
67 if (choices.length < 2) {
68 make(sentence, owner, "");
69 return undefined;
70 }
71 return later(ctx, () =>
72 promptScreen(ctx, parent, {
73 title: "Start from",
74 label: `Which template? ${choices.join(", ")}`,
75 value: choices[0]!,
76 onSubmit: (picked) => {
77 const hit = choices.find((c) => c.toLowerCase() === picked.trim().toLowerCase());
78 if (hit === undefined) return `Pick one of: ${choices.join(", ")}.`;
79 make(sentence, owner, hit === choices[0] ? "" : hit);
80 return undefined;
81 },
82 }),
83 );
84 };
85 if (owners.length < 2) return askTemplate(owners[0] ?? "");
6686 return later(ctx, () =>
6787 promptScreen(ctx, parent, {
6888 title: "Owner",
@@ -70,8 +90,7 @@ export function newAppScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
7090 value: owners[0]!,
7191 onSubmit: (owner) => {
7292 if (!owners.includes(owner)) return `Pick one of: ${owners.join(", ")}.`;
73 make(sentence, owner);
74 return undefined;
93 return askTemplate(owner);
7594 },
7695 }),
7796 );
src/web/pages/app_templates.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * Settings → App templates, for a forge admin who is a person (#10305):
3 * the repository New app copies by default, and the others marked as app
4 * templates, which New app then offers in a picker. Server-rendered; the
5 * form is a same-origin POST. Anyone else gets the not-found page.
6 */
7
8 import { APP_TEMPLATE_WORDS, readAppTemplates, setAppTemplates } from "../../actions/app_templates.ts";
9 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
12 import { field, readForm } from "../form.ts";
13 import { html } from "../html.ts";
14 import { flashTo, page } from "../layout.ts";
15 import { icon } from "../icons.ts";
16 import { btn, row } from "../ui.ts";
17 import { accountSections } from "./origins.ts";
18
19 const PATH = "/settings/app-templates";
20
21 // GET /settings/app-templates
22 export function appTemplatesPage(ctx: Ctx): Response {
23 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
24 if (!ctx.auth.user) return signInFirst(ctx);
25 const read = readAppTemplates(ctx.app, ctx.auth.user);
26 if (!read.ok) return notFoundPage(ctx);
27 const t = read.value;
28 const body = html`<section class="settings-block">
29 <h2>App templates</h2>
30 <p class="muted small">
31 New app copies a template repository's files at the tip of its default branch, as one commit with no history,
32 and offers a choice when more than one is marked. A repository needs a
33 <span class="mono">template.json</span> naming the files that carry the app's name and description; where this
34 forge lacks the default, the copy baked into the image is used.
35 </p>
36 <ul class="list setting-list">
37 ${row({
38 lead: icon("rocket"),
39 title: html`<span class="mono">${t.defaultSlug}</span>`,
40 meta: html`Default: New app starts from it unless another is picked.`,
41 trail: html`<form class="row-fields" method="post" action="${PATH}">
42 <input class="input mono" type="text" name="default" maxlength="170" spellcheck="false" autocomplete="off"
43 value="${t.defaultSlug}" aria-label="Default template, owner/name" />
44 ${btn("Set default", { size: "sm", variant: "primary", label: "Set the default template" })}
45 </form>`,
46 })}
47 ${t.marked.map((slug) =>
48 row({
49 lead: icon("rocket"),
50 title: html`<span class="mono">${slug}</span>`,
51 meta: html`Marked: offered under Start from in New app.`,
52 trail: html`<form method="post" action="${PATH}">
53 <input type="hidden" name="unmark" value="${slug}" />
54 ${btn("Unmark", { size: "sm", label: `Unmark ${slug}` })}
55 </form>`,
56 }),
57 )}
58 </ul>
59 <form class="row-fields" method="post" action="${PATH}">
60 <input class="input mono" type="text" name="mark" maxlength="170" spellcheck="false" autocomplete="off"
61 placeholder="owner/name" aria-label="Mark a repository as an app template" />
62 ${btn("Mark", { size: "sm", variant: "primary", label: "Mark as an app template" })}
63 </form>
64 </section>`;
65 const rendering = performance.now();
66 const response = page({
67 ctx,
68 title: "App templates",
69 body: html`<div class="page-head"><h1>App templates</h1></div>
70 ${settingsLayout(accountSections("apptemplates", { admin: true }), body, "Account settings")}`,
71 });
72 notePhase(ctx.request, "render", performance.now() - rendering);
73 return response;
74 }
75
76 // POST /settings/app-templates
77 export async function appTemplatesSet(ctx: Ctx): Promise<Response> {
78 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return notFoundPage(ctx);
79 const form = await readForm(ctx, "admin");
80 if (form instanceof Response) return form;
81 // One change per post: the default, a mark, or an unmark.
82 const set = await setAppTemplates(ctx.app, ctx.auth.user, {
83 ...(form.has("default") ? { defaultSlug: field(form, "default") } : {}),
84 mark: field(form, "mark"),
85 unmark: field(form, "unmark"),
86 });
87 if (!set.ok && set.error === "not_found") return notFoundPage(ctx);
88 return flashTo(
89 ctx,
90 PATH,
91 set.ok
92 ? { message: `Saved: ${1 + set.value.marked.length} app template(s), ${set.value.defaultSlug} first.` }
93 : { tone: "danger", message: `${APP_TEMPLATE_WORDS[set.error as keyof typeof APP_TEMPLATE_WORDS]}.` },
94 );
95 }
src/web/pages/apps.ts +18
@@ -12,6 +12,7 @@
1212 * 404 for everyone.
1313 */
1414
15 import { templateChoices } from "../../apps/template.ts";
1516 import { storageLimitMessage } from "../../core/storage.ts";
1617 import { repositoryLimitMessage } from "../../actions/repos.ts";
1718 import { appLimitWords } from "../../actions/app_limit.ts";
@@ -275,6 +276,8 @@ interface NewAppValues {
275276 description: string;
276277 visibility: string;
277278 agent: string;
279 /** An app template's `owner/name`; empty is the forge's default. */
280 template?: string;
278281 }
279282
280283 /** The agent select's sentinel for "turn the sentence into a plan and pick". */
@@ -305,6 +308,7 @@ function newAppForm(
305308 );
306309 const crew = agents.ok ? agents.value : [];
307310 const domain = appsRuntime(ctx.app)?.options.domain;
311 const templates = templateChoices(ctx.app);
308312
309313 // An org's form stays the org's: carry the owner only when it is one the
310314 // select offers, and only when it is not the viewer's own default.
@@ -318,6 +322,18 @@ function newAppForm(
318322 sub: "Describe what it should do. You get a repository, a first issue, a crew member on it, a live app, and a preview for every change.",
319323 })}
320324 ${html`<form method="post" action="/apps/new">
325 ${templates.length < 2
326 ? html``
327 : selectField({
328 label: "Start from",
329 name: "template",
330 hint: "The app template this one is copied from: its files at their latest, as one commit.",
331 options: templates.map((slug, i) => ({
332 value: i === 0 ? "" : slug,
333 label: i === 0 ? `${slug} (default)` : slug,
334 selected: (values.template ?? "") === (i === 0 ? "" : slug),
335 })),
336 })}
321337 ${formField({
322338 label: "What should it do?",
323339 name: "description",
@@ -461,6 +477,7 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> {
461477 description: field(form, "description"),
462478 visibility: field(form, "visibility") === "public" ? "public" : "private",
463479 agent: field(form, "agent"),
480 template: field(form, "template"),
464481 };
465482 const pickAgent = values.agent === PICK_AGENT;
466483 // An explicit name is never second-guessed; left blank, the sentence
@@ -470,6 +487,7 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> {
470487 const rest = {
471488 owner: values.owner,
472489 visibility: values.visibility === "public" ? "public" : "private",
490 ...(values.template ? { template: values.template } : {}),
473491 ...(pickAgent
474492 ? { pickAgent: true }
475493 : values.agent === ""
src/web/pages/origins.ts +2
@@ -112,6 +112,7 @@ export type AccountSection =
112112 | "access"
113113 | "limits"
114114 | "economics"
115 | "apptemplates"
115116 | "flags"
116117 | "features"
117118 | "cloud";
@@ -158,6 +159,7 @@ const SECTION_ROWS: readonly (readonly [
158159 ["This forge", "People", "/settings/people", "users", (c) => c === "people", true],
159160 ["This forge", "Limits", "/admin/limits", "activity", (c) => c === "limits", true],
160161 ["This forge", "Economics", "/settings/economics", "activity", (c) => c === "economics", true],
162 ["This forge", "App templates", "/settings/app-templates", "rocket", (c) => c === "apptemplates", true],
161163 ["This forge", "Flows", "/admin/flows", "activity", (c) => c === "adminflows", true],
162164 ["This forge", "Flags", "/settings/flags", "activity", (c) => c === "flags", true],
163165 ["This forge", "Features", "/settings/features", "rocket", (c) => c === "features", true],
templates/app-template.json added +52

Diff not shown — 230,907 bytes of diff (limit 100,000). +52

View file
test/app-template.test.ts added +196
@@ -0,0 +1,196 @@
1 /**
2 * The app a new app starts as is a repository (#10305). The copy in the
3 * image fills in exactly the files `template.json` names; a repository the
4 * forge is told to use is copied at its tip; a name no admin marked is
5 * refused; and the template's own can.ts is the forge's.
6 */
7 import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test";
8 import { readFileSync } from "node:fs";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { newApp } from "../src/actions/apps.ts";
14 import { readAppTemplates, setAppTemplates } from "../src/actions/app_templates.ts";
15 import { bakedFiles, bakedTemplate, fillTemplate, parseTemplateSpec, templateChoices, scaffoldFiles } from "../src/apps/template.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { readerFor } from "../src/git/read.ts";
18 import { repoDir } from "../src/git/repos.ts";
19 import { commitFiles } from "../src/git/write.ts";
20
21 setDefaultTimeout(30_000);
22
23 const text = (c: string | Uint8Array | null | undefined): string =>
24 typeof c === "string" ? c : new TextDecoder().decode(c ?? new Uint8Array());
25
26 describe("the copy in the image", () => {
27 const copy = bakedTemplate();
28 const spec = parseTemplateSpec(text(copy.files.find((f) => f.path === "template.json")?.content));
29
30 test("declares its literals and the files that carry them", () => {
31 expect(spec?.name).toBe("app-template");
32 expect(spec?.files).toEqual(["package.json", "README.md", "contract/openapi.json"]);
33 for (const path of spec?.files ?? []) expect(copy.files.some((f) => f.path === path)).toBe(true);
34 });
35
36 test("filling replaces the literals in the named files and touches nothing else", () => {
37 const out = bakedFiles({ name: "hello-there", description: 'A "quoted" place' });
38 expect(out.some((f) => f.path === "template.json")).toBe(false);
39 const get = (path: string) => text(out.find((f) => f.path === path)?.content);
40 expect(JSON.parse(get("package.json"))).toMatchObject({ name: "hello-there", description: 'A "quoted" place' });
41 expect(get("README.md").startsWith("# hello-there\n\nA \"quoted\" place\n")).toBe(true);
42 const api = JSON.parse(get("contract/openapi.json"));
43 expect(api.info).toMatchObject({ title: "hello-there", description: 'A "quoted" place' });
44 const carriers = new Set(spec?.files);
45 for (const f of copy.files) {
46 if (f.path === "template.json" || carriers.has(f.path)) continue;
47 expect(get(f.path)).toBe(text(f.content));
48 }
49 });
50
51 test("an empty description keeps the template's own line", () => {
52 const out = bakedFiles({ name: "x", description: " " });
53 expect(text(out.find((f) => f.path === "README.md")?.content)).toContain("A new app on the forge.");
54 });
55
56 test("filling with its own literals gives back the template's files", () => {
57 const out = fillTemplate(copy, { name: "app-template", description: "A new app on the forge." }) ?? [];
58 for (const f of out) expect(text(f.content)).toBe(text(copy.files.find((c) => c.path === f.path)?.content));
59 });
60
61 test("its contract evaluator is the forge's own", () => {
62 const can = copy.files.find((f) => f.path === "src/can.ts")?.content;
63 expect(text(can)).toBe(require("node:fs").readFileSync(join(import.meta.dir, "..", "src/contract/can.ts"), "utf8"));
64 });
65
66 test("a template.json that names a path outside the tree is not read", () => {
67 expect(parseTemplateSpec('{"name":"a","description":"b","files":["../x"]}')).toBeUndefined();
68 expect(parseTemplateSpec("nope")).toBeUndefined();
69 });
70 });
71
72 describe("New app copies the repository the forge names", () => {
73 let dataDir: string;
74 let app: App;
75 let alice: User;
76
77 beforeAll(async () => {
78 dataDir = await mkdtemp(join(tmpdir(), "forge-template-"));
79 app = createApp({ dataDir, port: 0 });
80 const made = await createUser(app.db, {
81 origin: "seed",
82 trusted: true,
83 username: "alice",
84 email: "[email protected]",
85 password: "a-good-passphrase",
86 adminIfFirst: true,
87 });
88 if (!made.ok) throw new Error(made.error);
89 alice = made.value;
90 });
91 afterAll(async () => {
92 app.close();
93 await rm(dataDir, { recursive: true, force: true });
94 });
95
96 const readme = async (owner: string, name: string): Promise<string> => {
97 const got = await readerFor(repoDir(app.reposRoot, owner, name)).object("refs/heads/main:README.md");
98 return got.ok ? text(got.value.body) : "";
99 };
100
101 test("with no template repository the baked copy makes the app, and only the default is offered", async () => {
102 expect(templateChoices(app)).toEqual(["trevato/app-template"]);
103 const made = await newApp(app, alice, { name: "from-baked", description: "Baked" });
104 expect(made.ok).toBe(true);
105 expect(await readme("alice", "from-baked")).toStartWith("# from-baked\n\nBaked\n");
106 });
107
108 test("a marked repository is copied at its tip, one commit, and the picker offers it", async () => {
109 const src = await newApp(app, alice, { name: "my-template" });
110 expect(src.ok).toBe(true);
111 const dir = repoDir(app.reposRoot, "alice", "my-template");
112 const tpl = bakedTemplate().files.find((f) => f.path === "template.json")!;
113 const edited = text(bakedTemplate().files.find((f) => f.path === "README.md")?.content).replace(
114 "# app-template",
115 "# app-template\n\nTIP-MARKER",
116 );
117 await commitFiles(dir, {
118 branch: "main",
119 message: "Make it a template",
120 files: [{ path: "template.json", content: tpl.content }, ...[{ path: "README.md", content: edited }]],
121 author: { name: "alice", email: "[email protected]" },
122 });
123
124 const denied = await setAppTemplates(app, alice, { mark: "alice/not-here" });
125 expect(denied.ok ? "" : denied.error).toBe("not_a_template");
126 const saved = await setAppTemplates(app, alice, { mark: "alice/my-template" });
127 expect(saved.ok).toBe(true);
128 expect(templateChoices(app)).toEqual(["trevato/app-template", "alice/my-template"]);
129
130 const child = await newApp(app, alice, { name: "child-one", description: "Kid", template: "alice/my-template" });
131 expect(child.ok).toBe(true);
132 const body = await readme("alice", "child-one");
133 expect(body).toContain("TIP-MARKER");
134 expect(body).toStartWith("# child-one\n");
135 const log = Bun.spawnSync(["git", "-C", repoDir(app.reposRoot, "alice", "child-one"), "rev-list", "--count", "main"]);
136 expect(log.stdout.toString().trim()).toBe("1");
137 const files = await scaffoldFiles(app, { name: "z", description: "" }, "alice/my-template");
138 expect(files.some((f) => f.path === "template.json")).toBe(false);
139 });
140
141 test("a repository nobody marked is not a template", async () => {
142 const refused = await newApp(app, alice, { name: "child-two", template: "alice/child-one" });
143 expect(refused.ok ? "" : refused.error).toBe("no_such_template");
144 });
145
146 test("only a person who is an admin may read or change templates", async () => {
147 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
148 if (!bob.ok) throw new Error(bob.error);
149 expect(readAppTemplates(app, bob.value).ok).toBe(false);
150 expect(readAppTemplates(app, undefined).ok).toBe(false);
151 const r = await setAppTemplates(app, bob.value, { mark: "alice/my-template" });
152 expect(r.ok ? "" : r.error).toBe("not_found");
153 // An agent that is an admin is refused too.
154 const agent: User = { ...alice, kind: "agent" };
155 expect(readAppTemplates(app, agent).ok).toBe(false);
156 const a = await setAppTemplates(app, agent, { unmark: "alice/my-template" });
157 expect(a.ok ? "" : a.error).toBe("not_found");
158 expect(templateChoices(app)).toContain("alice/my-template");
159 });
160
161 test("a mark is deduplicated without case, a bad name refused, and an unmark removes it", async () => {
162 const bad = await setAppTemplates(app, alice, { mark: "../etc" });
163 expect(bad.ok ? "" : bad.error).toBe("bad_slug");
164 const again = await setAppTemplates(app, alice, { mark: "alice/MY-template" });
165 expect(again.ok).toBe(true);
166 expect(templateChoices(app)).toEqual(["trevato/app-template", "alice/my-template"]);
167 const gone = await setAppTemplates(app, alice, { unmark: "alice/my-template" });
168 expect(gone.ok).toBe(true);
169 expect(templateChoices(app)).toEqual(["trevato/app-template"]);
170 });
171
172 test("a template that is missing falls back to the image's copy, for the default only", async () => {
173 // trevato/app-template is not a repository on this forge, and still scaffolds.
174 const files = await scaffoldFiles(app, { name: "fallback", description: "" });
175 expect(files.some((f) => f.path === "README.md")).toBe(true);
176 const asked = await scaffoldFiles(app, { name: "fallback", description: "" }, "alice/not-here");
177 expect(asked.length).toBe(files.length);
178 const set = await setAppTemplates(app, alice, { defaultSlug: "trevato/app-template" });
179 expect(set.ok).toBe(true);
180 });
181
182 test("the template field reaches New app over the API and as an MCP argument", () => {
183 const api = readFileSync(join(import.meta.dir, "../src/http/api.ts"), "utf8");
184 expect(api).toContain('typeof input.template === "string" ? { template: input.template }');
185 const tool = readFileSync(join(import.meta.dir, "../src/http/mcp/tools/new_app.ts"), "utf8");
186 expect(tool).toContain("template: { type:");
187 expect(tool).toContain("...(template === undefined ? {} : { template })");
188 });
189
190 test("a template.json naming odd paths or too many files is not read", () => {
191 for (const bad of ["/abs", ".git/config", "a/../b", "a//b", "a\\b", "x/.GIT/y"])
192 expect(parseTemplateSpec(JSON.stringify({ name: "a", description: "b", files: [bad] }))).toBeUndefined();
193 const many = Array.from({ length: 51 }, (_, i) => `f${i}`);
194 expect(parseTemplateSpec(JSON.stringify({ name: "a", description: "b", files: many }))).toBeUndefined();
195 });
196 });
test/app-templates-surfaces.test.ts added +190
@@ -0,0 +1,190 @@
1 /**
2 * Both doors to marking app templates (#10305): Settings → App templates on
3 * the web and the same in the terminal. Admin and a person only; the POST is
4 * same-origin; a template that is not one is refused in the action's words;
5 * New app in the terminal asks which template when more than one is marked.
6 */
7 import { afterAll, beforeAll, describe, 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 { APP_TEMPLATE_WORDS } from "../src/actions/app_templates.ts";
12 import { newApp } from "../src/actions/apps.ts";
13 import { createApp, type App as Forge } from "../src/app.ts";
14 import { bakedTemplate, templateChoices } from "../src/apps/template.ts";
15 import { createUser, getUserByName } from "../src/core/users.ts";
16 import { repoDir } from "../src/git/repos.ts";
17 import { commitFiles } from "../src/git/write.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import type { TuiIdentity } from "../src/tui/session.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { settleApp } from "./helpers/tui.ts";
24
25 quietLogs();
26
27 describe("app templates: the web page and the terminal", () => {
28 let dataDir: string;
29 let forge: Forge;
30 let servers: Servers;
31
32 const login = async (username: string): Promise<string> => {
33 const res = await fetch(`${servers.url}/signin`, {
34 method: "POST",
35 redirect: "manual",
36 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
37 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
38 });
39 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
40 };
41 const post = (cookie: string, body: Record<string, string>, origin = servers.url) =>
42 fetch(`${servers.url}/settings/app-templates`, {
43 method: "POST",
44 redirect: "manual",
45 headers: { cookie, "content-type": "application/x-www-form-urlencoded", origin },
46 body: new URLSearchParams(body),
47 });
48
49 function boot(username: string) {
50 const terminal = headlessTerminal(180, 32);
51 const user = getUserByName(forge.db, username)!;
52 const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user };
53 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
54 app.start();
55 const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
56 return {
57 text: () => app.screen.toText(),
58 press: async (...keys: string[]) => {
59 keys.forEach(key);
60 await settleApp(app);
61 },
62 ctrl: async (k: string) => {
63 app.dispatch({ type: "key", key: k, ctrl: true, alt: false, shift: false });
64 await settleApp(app);
65 },
66 type: async (t: string) => {
67 for (const ch of t) key(ch);
68 await settleApp(app);
69 },
70 stop: () => app.stop(),
71 };
72 }
73 const until = async (ok: () => boolean): Promise<void> => {
74 const end = Date.now() + 15_000;
75 while (!ok() && Date.now() < end) await Bun.sleep(20);
76 };
77 const open = async (h: ReturnType<typeof boot>) => {
78 await h.ctrl("k");
79 await h.type("App templates");
80 await h.press("enter");
81 };
82
83 beforeAll(async () => {
84 dataDir = await mkdtemp(join(tmpdir(), "forge-app-templates-"));
85 forge = createApp({ dataDir, port: 0 });
86 servers = await serve(forge);
87 for (const [username, adminIfFirst] of [["alice", true], ["bob", false], ["carol", false]] as const) {
88 const made = await createUser(forge.db, {
89 origin: "seed",
90 trusted: true,
91 username,
92 email: `${username}@forge.local`,
93 password: "a-good-passphrase",
94 adminIfFirst,
95 });
96 if (!made.ok) throw new Error(made.error);
97 }
98 forge.db.query("UPDATE user SET is_admin = 1, is_agent = 1 WHERE username = 'carol'").run();
99 // A repository that is a template.
100 const alice = getUserByName(forge.db, "alice")!;
101 const src = await newApp(forge, alice, { name: "kit" });
102 if (!src.ok) throw new Error(src.error);
103 const spec = bakedTemplate().files.find((f) => f.path === "template.json")!;
104 await commitFiles(repoDir(forge.reposRoot, "alice", "kit"), {
105 branch: "main",
106 message: "Make it a template",
107 files: [{ path: "template.json", content: spec.content }],
108 author: { name: "alice", email: "[email protected]" },
109 });
110 });
111 afterAll(async () => {
112 servers.stop();
113 forge.close();
114 await rm(dataDir, { recursive: true, force: true });
115 });
116
117 test("the page is for a person who is an admin; the POST is same-origin and changes nothing otherwise", async () => {
118 const bob = await login("bob");
119 expect((await fetch(`${servers.url}/settings/app-templates`, { headers: { cookie: bob } })).status).toBe(404);
120 expect((await post(bob, { mark: "alice/kit" })).status).toBe(404);
121 const alice = await login("alice");
122 expect((await post(alice, { mark: "alice/kit" }, "https://elsewhere.example")).status).toBe(403);
123 expect(templateChoices(forge)).toEqual(["trevato/app-template"]);
124 });
125
126 test("marking and unmarking work without JavaScript, as rows with buttons", async () => {
127 const alice = await login("alice");
128 expect((await post(alice, { mark: "alice/kit" })).status).toBe(303);
129 expect(templateChoices(forge)).toEqual(["trevato/app-template", "alice/kit"]);
130 const page = await (await fetch(`${servers.url}/settings/app-templates`, { headers: { cookie: alice } })).text();
131 expect(page).toContain("alice/kit");
132 expect(page).toContain('name="unmark"');
133 expect(page).toContain("<button");
134 expect(page).not.toContain("<textarea");
135 expect((await post(alice, { mark: "alice/nope" })).status).toBe(303);
136 expect(templateChoices(forge)).toEqual(["trevato/app-template", "alice/kit"]);
137 expect((await post(alice, { unmark: "alice/kit" })).status).toBe(303);
138 expect(templateChoices(forge)).toEqual(["trevato/app-template"]);
139 });
140
141 test("the terminal marks, refuses a non-template in the action's words, and unmarks", async () => {
142 const h = boot("alice");
143 await open(h);
144 expect(h.text()).toContain("trevato/app-template");
145 await h.press("m");
146 await h.type("alice/kit");
147 await h.press("enter");
148 await until(() => templateChoices(forge).length === 2);
149 expect(templateChoices(forge)).toEqual(["trevato/app-template", "alice/kit"]);
150 await h.press("m");
151 await h.type("alice/nope");
152 await h.press("enter");
153 await until(() => h.text().includes("no readable"));
154 expect(h.text()).toContain(APP_TEMPLATE_WORDS.not_a_template.slice(0, 30));
155 expect(templateChoices(forge)).toEqual(["trevato/app-template", "alice/kit"]);
156 await h.press("j", "u");
157 await until(() => templateChoices(forge).length === 1);
158 expect(templateChoices(forge)).toEqual(["trevato/app-template"]);
159 h.stop();
160 }, 20_000);
161
162 test("New app in the terminal asks which template once two are marked", async () => {
163 const h = boot("alice");
164 await open(h);
165 await h.press("m");
166 await h.type("alice/kit");
167 await h.press("enter");
168 await until(() => templateChoices(forge).length === 2);
169 await h.press("esc");
170 await h.ctrl("k");
171 await h.type("New app");
172 await h.press("enter");
173 await h.type("a shared shopping list for the flat");
174 await h.press("enter");
175 await until(() => h.text().includes("Start from"));
176 expect(h.text()).toContain("Start from");
177 await Bun.sleep(100);
178 h.stop();
179 }, 20_000);
180
181 test("an agent, or anyone not an admin, has no command and drives nothing", async () => {
182 for (const who of ["bob", "carol"]) {
183 const h = boot(who);
184 await h.ctrl("k");
185 await h.type("App templates");
186 expect(h.text()).not.toContain("the repositories New app copies");
187 h.stop();
188 }
189 });
190 });
test/apps-measure.test.ts +1 −1
@@ -12,7 +12,7 @@ import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { newApp } from "../src/actions/apps.ts";
1414 import { AppsRuntime } from "../src/apps/runtime.ts";
15 import { scaffoldFiles } from "../src/apps/scaffold.ts";
15 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
1616 import { appVisitors } from "../src/actions/apps.ts";
1717 import { createToken } from "../src/core/tokens.ts";
1818 import { getRepo } from "../src/core/repos.ts";
test/apps-new.test.ts +1 −1
@@ -24,7 +24,7 @@ import { getRepo } from "../src/core/repos.ts";
2424 import { createUser, type User } from "../src/core/users.ts";
2525 import { serve, type Servers } from "../src/http/server.ts";
2626
27 import { scaffoldFiles } from "../src/apps/scaffold.ts";
27 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
2828 import { parseCheck } from "../src/apps/manifest.ts";
2929 import {
3030 appNameJs,
test/apps-token.test.ts +1 −1
@@ -23,7 +23,7 @@ import {
2323 renewAppToken,
2424 revokeAppToken,
2525 } from "../src/apps/token.ts";
26 import { scaffoldFiles } from "../src/apps/scaffold.ts";
26 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
2727 import { newApp } from "../src/actions/apps.ts";
2828 import { openIssue } from "../src/actions/issues.ts";
2929 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
test/contract.test.ts +1 −1
@@ -10,7 +10,7 @@
1010 */
1111 import { describe, expect, test } from "bun:test";
1212 import { readFileSync } from "node:fs";
13 import { scaffoldFiles } from "../src/apps/scaffold.ts";
13 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
1414 import { policyLines, taskPrompt } from "../src/crew/brief.ts";
1515 import {
1616 NOBODY,
test/feed-composer-language.test.ts +1 −1
@@ -81,7 +81,7 @@ test("a repository name with markup in it is escaped in the select, never raw",
8181 app.db.query("UPDATE repo SET name = ?1 WHERE id = ?2").run('x"><img src=x onerror=alert(1)>', made.value.id);
8282 const form = await composerOf(cookie);
8383 expect(form).not.toContain("<img");
84 expect(form).not.toContain('x">');
84 expect(form).not.toContain('alice/x">');
8585 expect(form).toContain("alice/x&quot;&gt;&lt;img src=x onerror=alert(1)&gt;");
8686 });
8787
test/palette-roster.test.ts +1
@@ -127,6 +127,7 @@ test("a site-admin person is offered the whole roster", () => {
127127 ["people", "People", "who is a guest, a member or an admin; promote or demote"],
128128 ["quotas", "Account quotas", "what one account may own, and who changed it"],
129129 ["limits", "Limits", "what the forge caps, with default and bounds; change one"],
130 ["app-templates", "App templates", "the repositories New app copies; mark or unmark one"],
130131 ["economics", "Economics", "the profit slider's position, the margin, the owned-node label and the prices; change one"],
131132 ["flows-all", "Flows across the forge", "every repository's flow lines, by kind and stale"],
132133 ["teams", "Crew teams", "each team's charter, dial and members"],
test/probe.test.ts +1 −1
@@ -12,7 +12,7 @@ import { createApp, type App } from "../src/app.ts";
1212 import { newApp } from "../src/actions/apps.ts";
1313 import { commitToBranch } from "../src/actions/repos.ts";
1414 import { AppsRuntime, appsRuntime } from "../src/apps/runtime.ts";
15 import { scaffoldFiles } from "../src/apps/scaffold.ts";
15 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
1616 import { audit } from "../src/contract/audit.ts";
1717 import { probe, type Probed } from "../src/contract/probe.ts";
1818 import { getAppByRepo } from "../src/core/apps.ts";
test/probes.test.ts +1 −1
@@ -11,7 +11,7 @@ import { createApp, type App } from "../src/app.ts";
1111 import { newApp } from "../src/actions/apps.ts";
1212 import { commitToBranch } from "../src/actions/repos.ts";
1313 import { AppsRuntime } from "../src/apps/runtime.ts";
14 import { scaffoldFiles } from "../src/apps/scaffold.ts";
14 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
1515 import {
1616 PROBE_ISSUE_TITLE,
1717 latestProbes,
test/scaffold-webspec.test.ts +1 −1
@@ -8,7 +8,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
88 import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { dirname, join } from "node:path";
11 import { scaffoldFiles } from "../src/apps/scaffold.ts";
11 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
1212 import { webspec, type Finding } from "../src/release/webspec.ts";
1313
1414 /** Today's gaps, each with its specification.website section. None: the scaffold meets it. */
test/scaffold.test.ts +1 −1
@@ -23,7 +23,7 @@ import { parseManifest } from "../src/apps/manifest.ts";
2323 import { createSession } from "../src/core/sessions.ts";
2424 import { createUser } from "../src/core/users.ts";
2525 import { serve } from "../src/http/server.ts";
26 import { scaffoldFiles } from "../src/apps/scaffold.ts";
26 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
2727
2828 /** How long the written-out app's `bun test` may take, wall clock. */
2929 const SUITE_BUDGET_MS = 3_000;
test/signin-words.test.ts +13 −3
@@ -1,14 +1,16 @@
11 /**
22 * A sign-in flow's expiry sentences are said from one place
3 * (`src/kernel/signin_words.ts`). Each is a real sentence, and neither the
4 * parent sign-in nor an app's scaffold types its own copy back in.
3 * (`src/kernel/signin_words.ts`). Each is a real sentence, and the
4 * parent sign-in does not type its own copy back in, and the app template
5 * (`templates/app-template.json`) carries the same words as written.
56 */
67 import { describe, expect, test } from "bun:test";
78 import { readFileSync } from "node:fs";
89 import { join } from "node:path";
10 import { bakedTemplate } from "../src/apps/template.ts";
911 import * as words from "../src/kernel/signin_words.ts";
1012
11 const READERS = ["src/http/rp.ts", "src/apps/scaffold.ts"];
13 const READERS = ["src/http/rp.ts"];
1214 const source = (path: string): string =>
1315 readFileSync(join(import.meta.dir, "..", path), "utf8");
1416
@@ -33,3 +35,11 @@ describe("a sign-in flow's expiry sentences", () => {
3335 }
3436 });
3537 });
38
39 describe("the app template says the same sentences", () => {
40 test("its sign-in carries each one verbatim", () => {
41 const signin = bakedTemplate().files.find((f) => f.path === "src/signin.ts")?.content;
42 expect(typeof signin).toBe("string");
43 for (const [, sentence] of Object.entries(words)) expect(signin as string).toContain(sentence);
44 });
45 });
test/spawn-template-birth.test.ts +1 −1
@@ -11,7 +11,7 @@ import { join } from "node:path";
1111 import { createRepo } from "../src/actions/repos.ts";
1212 import { childDirOf, spawnForge, type SpawnDeps } from "../src/actions/spawn.ts";
1313 import { createApp, type App } from "../src/app.ts";
14 import { scaffoldFiles } from "../src/apps/scaffold.ts";
14 import { bakedFiles as scaffoldFiles } from "../src/apps/template.ts";
1515 import { getAppByRepo } from "../src/core/apps.ts";
1616 import { getRepo } from "../src/core/repos.ts";
1717 import { createToken } from "../src/core/tokens.ts";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs