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

Saving a template validates its forge.json and names the first thing wrong #13335

Merged opened this

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

Merged

scout/forge:scout/13304-saving-a-template-validates-its-forge-js → main 3 commits fork

  • Merged. scout/13304-saving-a-template-validates-its-forge-js was merged into main as e9f793c.

Review

Sign in to review this change.
12 files changed +313 −11
docs/features/repo-template.md +6
@@ -9,3 +9,9 @@ An admin of a repository marks it as a template for new forges (#12431). This is
99 - List: `GET /api/v1/templates` (`limit`, `cursor`), only repositories the reader may see, by the same rule as the repository list.
1010
1111 Only a person who administers the repository sets it; an agent is refused as `not_found`. Stored as `repo.is_template`; the change is in the `repo.settings_updated` event.
12
13 ## forge.json is checked when it is marked (#13304)
14
15 Marking reads `forge.json` at the default branch's tip and runs it through the manifest's own checks (run command, egress, tty and the rest, `src/apps/template_problem.ts`). A file that is missing or wrong refuses the mark with the first failing field named (API 422 `template_invalid`, the page's flash, the terminal's toast, the MCP error), and nothing changes. A repository already marked is never blocked: when its file stops passing, Settings › App says "Flagged as a template: <the field>" and the terminal screen shows the same line under it. Unmarking is never refused.
16
17 A `forge.json` with no `app` section (nothing for the forge to run) is refused too, as "forge.json: declares no app.run command"; add `app.run` before marking. The verdict is cached per commit, so the settings page reads the files once per head.
src/actions/repos.ts +15 −2
@@ -58,6 +58,7 @@ import {
5858 type Webhook,
5959 } from "../core/webhooks.ts";
6060 import { resolveOid } from "../git/merge.ts";
61 import { templateProblem } from "../apps/template_problem.ts";
6162 import { repoDir, setDefaultBranch } from "../git/repos.ts";
6263 import { isSafeRef } from "../git/guard.ts";
6364 import {
@@ -104,7 +105,8 @@ export type CreateRepoActionError =
104105 * The repositories limit (#2093): when the owner has set one, an account at
105106 * it makes no more, by create, fork or copy. Admins and agents are not held
106107 * to it. Only a repository the account owns itself is counted and asked: creating
107 * under an organisation is not, since the quota is per account. Returns the refusal sentence ("10 of 10 repositories") or nothing.
108 * under an organisation is not, since the quota is per account. Returns the refusal sentence ("10
109 * of 10 repositories") or nothing.
108110 */
109111 export function repositoryLimitRefusal(app: App, user: User, ownerId = user.id): string | undefined {
110112 if (user.isAdmin || user.kind === "agent") return undefined;
@@ -311,6 +313,11 @@ export async function privateRepoForSealed(
311313
312314 export type UpdateSettingsError = "not_found" | "unknown_branch" | "polish_share" | "origin_read_only";
313315
316 /**
317 * A mark refused because the template's forge.json fails: `message` names the first thing wrong.
318 */
319 export type TemplateRefused = { readonly ok: false; readonly error: "template_invalid"; readonly message: string };
320
314321 /** Each repository's archive transitions, one after another. */
315322 const archiveTurns = new WeakMap<App, Map<string, Promise<void>>>();
316323
@@ -407,7 +414,7 @@ export async function updateRepoSettings(
407414 actor: User | undefined,
408415 repo: Repo,
409416 settings: RepoSettings,
410 ): Promise<Result<Repo, UpdateSettingsError>> {
417 ): Promise<Result<Repo, UpdateSettingsError> | TemplateRefused> {
411418 const admin = requireRepoAdmin(app, actor, repo);
412419 if (!admin.ok) return admin;
413420 // Who the crew obeys, and whether the repository is archived, are a
@@ -432,6 +439,12 @@ export async function updateRepoSettings(
432439 return err("origin_read_only");
433440 if (settings.polishShare !== undefined && !validPolishShare(settings.polishShare))
434441 return err("polish_share");
442 // Marking a template runs its forge.json through the manifest's own checks and names the
443 // first thing wrong (`templateProblem`); one already marked is only flagged, never blocked.
444 if (settings.template === true && !repo.template) {
445 const message = await templateProblem(app, repo);
446 if (message !== undefined) return { ok: false, error: "template_invalid", message };
447 }
435448 const branch = settings.defaultBranch;
436449 if (branch !== undefined && branch !== repo.defaultBranch) {
437450 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
src/apps/template_problem.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * What is wrong with a template's `forge.json` (#13304): the first failing field, named, or
3 * `undefined` when the default branch's file is one the forge could run. Read from the
4 * default branch's tip, the way a new forge copies it; a repository with no file, or no commit
5 * yet, is told so, because a template nobody can run is not one to offer.
6 */
7
8 import type { App } from "../app.ts";
9 import type { Repo } from "../core/repos.ts";
10 import { repoDir } from "../git/repos.ts";
11 import { resolveOid } from "../git/merge.ts";
12 import { readFileAt } from "./checkout.ts";
13 import { parseManifest } from "./manifest.ts";
14
15 /** The verdict per commit: a commit never changes, so the settings page reads the files once. */
16 const kept = new WeakMap<App, Map<string, string | undefined>>();
17 const KEPT = 500;
18
19 export async function templateProblem(app: App, repo: Repo): Promise<string | undefined> {
20 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
21 const oid = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
22 if (!oid) return "forge.json: the default branch has no commit yet";
23 let verdicts = kept.get(app);
24 if (!verdicts) kept.set(app, (verdicts = new Map()));
25 const key = `${dir}@${oid}`;
26 if (verdicts.has(key)) return verdicts.get(key);
27 const said = await problemAt(dir, oid);
28 if (verdicts.size >= KEPT) verdicts.clear();
29 verdicts.set(key, said);
30 return said;
31 }
32
33 async function problemAt(dir: string, oid: string): Promise<string | undefined> {
34 const forgeJson = await readFileAt(dir, oid, "forge.json");
35 if (forgeJson === undefined) return "forge.json: not found on the default branch";
36 const parsed = parseManifest(forgeJson, await readFileAt(dir, oid, "package.json"));
37 if (parsed.ok) return undefined;
38 return parsed.error.kind === "invalid" ? parsed.error.message : "forge.json: declares no app.run command";
39 }
src/http/api.ts +1
@@ -1782,6 +1782,7 @@ export function apiRoutes(router: Router<Handler>): void {
17821782 : {}),
17831783 });
17841784 if (!updated.ok && updated.error === "origin_read_only") return apiError("origin_read_only", 409, "this repository mirrors a read-only origin, so it stays private to its owner; nothing was changed");
1785 if (!updated.ok && updated.error === "template_invalid") return apiError("template_invalid", 422, updated.message);
17851786 if (!updated.ok) return respondAccess(updated.error, 422);
17861787 // "Show where this came from" (#3293): an admin's, never an agent's.
17871788 if (typeof input.showProvenance === "boolean") {
src/http/mcp/tools/repo_settings.ts +2
@@ -86,6 +86,8 @@ export const tool: Tool = {
8686 ...(description !== undefined ? { description } : {}),
8787 ...(template !== undefined ? { template } : {}),
8888 });
89 if (!updated.ok && updated.error === "template_invalid")
90 return bad("invalid", updated.message);
8991 if (!updated.ok)
9092 return bad(updated.error === "not_found" ? "not_found" : "forbidden", updated.error);
9193 return good({
src/tui/screens/template.ts +14 −2
@@ -7,6 +7,7 @@
77 */
88
99 import { updateRepoSettings } from "../../actions/repos.ts";
10 import { templateProblem } from "../../apps/template_problem.ts";
1011 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
1112 import { templateSaid } from "../../core/template_words.ts";
1213 import type { Ctx, Screen } from "../app/app.ts";
@@ -22,11 +23,19 @@ export const mayMarkTemplate = (f: Session, repo: Repo): boolean => f.user !== u
2223
2324 export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
2425 const now = (): Repo => getRepoById(f.db, repo.id) ?? repo;
26 let flag: string | undefined;
27 const look = async (signal: AbortSignal): Promise<void> => {
28 const problem = now().template ? await templateProblem(f.app, now()) : undefined;
29 if (signal.aborted) return;
30 flag = problem;
31 ctx.invalidate();
32 };
2533 return {
2634 title: `${repo.ownerName}/${repo.name} — Template`,
2735 keys: [binding(["t"], "mark or unmark as a template")],
2836 async load(signal) {
29 live(f, signal, { repoId: repo.id, kinds: ["repo.settings_updated"] }, () => ctx.invalidate());
37 live(f, signal, { repoId: repo.id, kinds: ["repo.settings_updated"] }, () => void look(signal));
38 await look(signal);
3039 },
3140 render(area, s) {
3241 const c = ctx.theme.c;
@@ -37,6 +46,8 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3746 ? "New forges may start from this repository. t clears it."
3847 : "Not a template. t lets new forges start from this repository.";
3948 s.text(area.x, area.y, truncate(said, area.w), style(c.mutedFg, c.bg), area.x + area.w);
49 if (on && flag !== undefined && area.h > 1)
50 s.text(area.x, area.y + 1, truncate(`Flagged: ${flag}`, area.w), style(c.mutedFg, c.bg), area.x + area.w);
4051 },
4152 key(e) {
4253 if (e.ctrl || e.alt || e.key !== "t") return false;
@@ -44,7 +55,8 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4455 ? updateRepoSettings(f.app, f.user, now(), { template: !now().template })
4556 : undefined;
4657 void Promise.resolve(set).then((r) => {
47 ctx.toast(r?.ok ? templateSaid(r.value.template) : "An admin of this repository marks it a template.", r?.ok ? undefined : "danger");
58 const why = r && !r.ok && r.error === "template_invalid" ? r.message : undefined;
59 ctx.toast(r?.ok ? templateSaid(r.value.template) : why ?? "An admin of this repository marks it a template.", r?.ok ? undefined : "danger");
4860 ctx.invalidate();
4961 });
5062 return true;
src/web/pages/settings.ts +9 −2
@@ -10,6 +10,7 @@
1010
1111 import { blockedWay } from "../blocked.ts";
1212 import { privateDestinationBlocked } from "../../actions/blocked_words.ts";
13 import { templateProblem } from "../../apps/template_problem.ts";
1314 import { templateSaid } from "../../core/template_words.ts";
1415 import { POLISH_SHARE_DEFAULT, POLISH_SHARE_MAX } from "../../crew/polish_share.ts";
1516 import { appLimitWords } from "../../actions/app_limit.ts";
@@ -485,6 +486,8 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> {
485486 message:
486487 updated.error === "unknown_branch"
487488 ? "That branch does not exist in this repository."
489 : updated.error === "template_invalid"
490 ? `Not marked as a template. ${updated.message}`
488491 : updated.error === "polish_share"
489492 ? `Polish share is a whole number of percent, 0 to ${POLISH_SHARE_MAX}.`
490493 : "Those settings could not be saved.",
@@ -703,6 +706,7 @@ function appSettingsView(
703706 egress?: EgressView,
704707 blocked?: BlockedView,
705708 needs?: { needs: readonly NeedRow[]; grantable: { name: string; scope: "forge" | "org" }[] },
709 templateWhy?: string,
706710 ): Html {
707711 const base = repoBase(repo);
708712 const runtime = appsRuntime(ctx.app);
@@ -796,7 +800,9 @@ function appSettingsView(
796800 <h2>Statement</h2>
797801 <p><a href="${base}/settings/app/statement">This month's statement</a></p>
798802 </section>`;
799 if (record === undefined) return html`${form}<div class="mt">${statement}</div>`;
803 // A marked template whose forge.json no longer passes: one line, never a block.
804 const flagged = templateWhy === undefined ? html`` : html`<p class="muted mt">Flagged as a template: ${templateWhy}</p>`;
805 if (record === undefined) return html`${form}${flagged}<div class="mt">${statement}</div>`;
800806 const domains = timePhase(ctx.request, "domains", () =>
801807 listAppDomains(ctx.app, ctx.auth.user, repo),
802808 );
@@ -812,7 +818,7 @@ function appSettingsView(
812818 ],
813819 helpAsked(ctx.request.url),
814820 );
815 return html`${help}${form}
821 return html`${help}${form}${flagged}
816822 ${when(listed?.ok === true, () => html`<div class="mt">${appMembersView(base, values.access, named)}</div>`)}
817823 <div class="mt">${appVisitorsView(vitals)}</div>
818824 <div class="mt">${statement}</div>
@@ -1149,6 +1155,7 @@ export async function appSettingsPage(ctx: Ctx): Promise<Response> {
11491155 egress?.ok ? egress.value : undefined,
11501156 blocked?.ok ? blocked.value : undefined,
11511157 needs?.ok ? needs.value : undefined,
1158 repo.template ? await templateProblem(ctx.app, repo) : undefined,
11521159 );
11531160 const rendering = performance.now();
11541161 const response = settingsPageResponse(ctx, repo, "app", "App", view);
test/repo-template-flag.test.ts +4 −2
@@ -9,9 +9,9 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { updateRepoSettings } from "../src/actions/repos.ts";
12 import { commitToBranch, updateRepoSettings } from "../src/actions/repos.ts";
1313 import type { Agent } from "../src/core/agents.ts";
14 import { createRepo, getRepoById, type Repo } from "../src/core/repos.ts";
14 import { createRepo, getRepo, getRepoById, type Repo } from "../src/core/repos.ts";
1515 import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
1717 import { templateSaid } from "../src/core/template_words.ts";
@@ -95,6 +95,8 @@ beforeAll(async () => {
9595 stranger = await make("stranger");
9696 pub = ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "starter", visibility: "public" }));
9797 ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "secret", visibility: "private" }));
98 for (const r of [pub, getRepo(app.db, "maker", "secret")!])
99 ok(await commitToBranch(app, owner, r, { message: "seed", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] }));
98100 bot = ok(await createAgent(app, founder, { username: "bot" }));
99101 proveAll(app);
100102 expect(addToCrew(app, founder, pub, "bot").ok).toBe(true);
test/spawn-template-record.test.ts +1 −1
@@ -53,7 +53,7 @@ describe("a forge remembers its template", () => {
5353 auth.authorization = `Bearer ${rw}`;
5454 const kit = await createRepo(app, a.value, { name: "kit", visibility: "public", description: "" });
5555 if (!kit.ok) throw new Error("repo");
56 await commitToBranch(app, a.value, kit.value, { message: "seed", files: [{ path: "a.txt", content: "a" }] });
56 await commitToBranch(app, a.value, kit.value, { message: "seed", files: [{ path: "a.txt", content: "a" }, { path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] });
5757 const marked = await updateRepoSettings(app, a.value, kit.value, { template: true });
5858 if (!marked.ok) throw new Error("mark");
5959 const head = await runGit(["rev-parse", "HEAD"], { cwd: repoDir(app.reposRoot, "alice", "kit") });
test/spawn-template.test.ts +1 −1
@@ -63,7 +63,7 @@ describe("a new forge from a template repository", () => {
6363 for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) {
6464 const made = await createRepo(app, alice, { name, visibility });
6565 if (!made.ok) throw new Error(name);
66 await commitToBranch(app, alice, made.value, { message: "seed", files: [{ path: "kit.txt", content: name }] });
66 await commitToBranch(app, alice, made.value, { message: "seed", files: [{ path: "kit.txt", content: name }, { path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] });
6767 }
6868 for (const name of ["kit", "secret"]) {
6969 const r = getRepo(app.db, "alice", name)!;
test/template-forge-json.test.ts added +219
@@ -0,0 +1,219 @@
1 /**
2 * Marking a repository as a template runs its forge.json through the manifest's checks and names
3 * the first thing wrong (#13304); one already marked is only flagged on its settings page.
4 */
5 import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
10 import { templateProblem } from "../src/apps/template_problem.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { getRepoById, type Repo } from "../src/core/repos.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { repoScreen } from "../src/tui/screens/repo.ts";
17 import { templateScreen } from "../src/tui/screens/template.ts";
18 import { local } from "../src/tui/screens/where.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { settleApp } from "./helpers/tui.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { tokenFor } from "./helpers/tokens.ts";
23
24 quietLogs();
25 setDefaultTimeout(30_000);
26
27 let dir: string;
28 let app: App;
29 let servers: Servers;
30 let admin: User;
31
32 const make = async (name: string, forgeJson: string | undefined): Promise<Repo> => {
33 const made = await createRepo(app, admin, { name, visibility: "public", description: "" });
34 if (!made.ok) throw new Error(name);
35 const files = [{ path: "README.md", content: "x\n" }, ...(forgeJson === undefined ? [] : [{ path: "forge.json", content: forgeJson }])];
36 const done = await commitToBranch(app, admin, made.value, { message: "seed", files });
37 if (!done.ok) throw new Error(String(done.error));
38 return made.value;
39 };
40 const fresh = (r: Repo): Repo => getRepoById(app.db, r.id)!;
41
42 beforeAll(async () => {
43 dir = await mkdtemp(join(tmpdir(), "forge-tplvalid-"));
44 app = createApp({ dataDir: dir, port: 0 });
45 servers = await serve(app);
46 const made = await createUser(app.db, {
47 origin: "seed", trusted: true, username: "boss", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true,
48 });
49 if (!made.ok) throw new Error(made.error);
50 admin = made.value;
51 });
52
53 afterAll(async () => {
54 servers?.stop();
55 app?.close();
56 await rm(dir, { recursive: true, force: true });
57 });
58
59 describe("marking a template validates its forge.json", () => {
60 test("a valid one is marked", async () => {
61 const r = await make("good", '{"app":{"run":"bun main.ts","tty":"bun tui.ts"},"egress":["api.example.com"]}');
62 expect(await templateProblem(app, r)).toBeUndefined();
63 const done = await updateRepoSettings(app, admin, r, { template: true });
64 expect(done.ok).toBe(true);
65 expect(fresh(r).template).toBe(true);
66 });
67
68 test("an invalid one is refused, naming the first field, and stays unmarked", async () => {
69 const r = await make("bad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}');
70 const why = await templateProblem(app, r);
71 expect(why).toContain("egress");
72 const done = await updateRepoSettings(app, admin, r, { template: true });
73 expect(!done.ok && done.error).toBe("template_invalid");
74 expect(fresh(r).template).toBe(false);
75 const api = await fetch(`${servers.url}/api/v1/repos/boss/bad`, {
76 method: "PATCH",
77 headers: { authorization: `Bearer ${tokenFor(app, "boss", "admin")}`, "content-type": "application/json" },
78 body: JSON.stringify({ template: true }),
79 });
80 expect(api.status).toBe(422);
81 expect(JSON.stringify(await api.json())).toContain("egress");
82 expect(fresh(r).template).toBe(false);
83 });
84
85 test("a bad run command is named", async () => {
86 const r = await make("norun", '{"app":{"run":5}}');
87 expect(await templateProblem(app, r)).toMatch(/run/);
88 expect((await updateRepoSettings(app, admin, r, { template: true })).ok).toBe(false);
89 });
90
91 test("a missing forge.json is refused and says so", async () => {
92 const r = await make("none", undefined);
93 expect(await templateProblem(app, r)).toBe("forge.json: not found on the default branch");
94 expect((await updateRepoSettings(app, admin, r, { template: true })).ok).toBe(false);
95 expect(fresh(r).template).toBe(false);
96 });
97
98 test("unmarking is never refused, and a marked template that later fails is only flagged", async () => {
99 const r = await make("later", '{"app":{"run":"bun main.ts"}}');
100 expect((await updateRepoSettings(app, admin, r, { template: true })).ok).toBe(true);
101 const page = async (): Promise<string> => {
102 const signin = await fetch(`${servers.url}/signin`, {
103 method: "POST", headers: { origin: servers.url },
104 body: new URLSearchParams({ username: "boss", password: "a-good-passphrase" }), redirect: "manual",
105 });
106 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
107 return await (await fetch(`${servers.url}/boss/later/settings/app`, { headers: { cookie } })).text();
108 };
109 expect(await page()).not.toContain("Flagged as a template:");
110 const broke = await commitToBranch(app, admin, fresh(r), { message: "break", files: [{ path: "forge.json", content: '{"app":{"run":5}}' }] });
111 expect(broke.ok).toBe(true);
112 expect(fresh(r).template).toBe(true);
113 const flagged = await page();
114 expect(flagged).toContain("Flagged as a template: forge.json");
115 // Saving settings that leave the mark alone is not blocked.
116 expect((await updateRepoSettings(app, admin, fresh(r), { description: "still here" })).ok).toBe(true);
117 expect((await updateRepoSettings(app, admin, fresh(r), { template: false })).ok).toBe(true);
118 expect(fresh(r).template).toBe(false);
119 });
120 });
121
122 describe("every door names the field", () => {
123 const signedIn = async (): Promise<string> => {
124 const signin = await fetch(`${servers.url}/signin`, {
125 method: "POST", headers: { origin: servers.url },
126 body: new URLSearchParams({ username: "boss", password: "a-good-passphrase" }), redirect: "manual",
127 });
128 return (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
129 };
130 const openTui = async (repo: Repo) => {
131 const terminal = headlessTerminal(120, 40);
132 const { app: tui, session } = createForgeApp(
133 app,
134 { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin },
135 { terminal, exitHooks: false },
136 );
137 tui.start();
138 tui.ctx.push(repoScreen(session, tui.ctx, local(session, repo)));
139 tui.ctx.push(templateScreen(session, tui.ctx, repo));
140 await settleApp(tui);
141 return {
142 text: () => tui.screen.toText(),
143 press: async (k: string) => { terminal.feed(k); await settleApp(tui); },
144 stop: () => tui.stop?.(),
145 };
146 };
147
148 test("the MCP repo_settings tool answers invalid with the field", async () => {
149 const r = await make("mcpbad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}');
150 const res = await fetch(`${servers.url}/mcp`, {
151 method: "POST",
152 headers: {
153 "content-type": "application/json", accept: "application/json, text/event-stream",
154 authorization: `Bearer ${tokenFor(app, "boss", "admin")}`,
155 },
156 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "repo_settings", arguments: { repo: "boss/mcpbad", template: true } } }),
157 });
158 const body = (await res.json()) as any;
159 expect(body.result.isError).toBe(true);
160 const text: string = body.result.content[0].text;
161 expect(text).toContain("egress");
162 expect(text).toContain("invalid");
163 expect(fresh(r).template).toBe(false);
164 });
165
166 test("the settings form flashes why it did not mark", async () => {
167 const r = await make("flashbad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}');
168 const cookie = await signedIn();
169 const page = await fetch(`${servers.url}/boss/flashbad/settings/app`, { headers: { cookie } });
170 const html = await page.text();
171 const csrf = /name="csrf" value="([^"]+)"/.exec(html)?.[1];
172 const body = new URLSearchParams({ card: "template", templateShown: "1", template: "on", ...(csrf ? { csrf } : {}) });
173 const sent = await fetch(`${servers.url}/boss/flashbad/settings`, {
174 method: "POST", headers: { cookie, origin: servers.url }, body, redirect: "manual",
175 });
176 expect(sent.status).toBe(303);
177 expect(decodeURIComponent(sent.headers.get("set-cookie") ?? "")).toContain("Not marked as a template. forge.json: egress");
178 expect(fresh(r).template).toBe(false);
179 });
180
181 test("the terminal's t toasts the field, and a marked template that fails shows Flagged", async () => {
182 const r = await make("tuibad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}');
183 const h = await openTui(r);
184 await h.press("t");
185 expect(h.text()).toContain("egress");
186 expect(fresh(r).template).toBe(false);
187 h.stop();
188
189 const m = await make("tuiflag", '{"app":{"run":"bun main.ts"}}');
190 expect((await updateRepoSettings(app, admin, m, { template: true })).ok).toBe(true);
191 const ok = await openTui(fresh(m));
192 expect(ok.text()).not.toContain("Flagged:");
193 ok.stop();
194 await commitToBranch(app, admin, fresh(m), { message: "break", files: [{ path: "forge.json", content: '{"app":{"run":5}}' }] });
195 const flagged = await openTui(fresh(m));
196 expect(flagged.text()).toContain("Flagged: forge.json");
197 flagged.stop();
198 });
199
200 test("a screen that is gone ignores a late look", async () => {
201 const m = await make("tuigone", '{"app":{"run":"bun main.ts"}}');
202 expect((await updateRepoSettings(app, admin, m, { template: true })).ok).toBe(true);
203 const terminal = headlessTerminal(120, 40);
204 const { app: tui, session } = createForgeApp(
205 app,
206 { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin },
207 { terminal, exitHooks: false },
208 );
209 tui.start();
210 let invalidated = 0;
211 const screen = templateScreen(session, { ...tui.ctx, invalidate: () => void invalidated++ } as typeof tui.ctx, fresh(m));
212 const gone = new AbortController();
213 const loading = screen.load?.(gone.signal);
214 gone.abort();
215 await loading;
216 expect(invalidated).toBe(0);
217 tui.stop?.();
218 });
219 });
test/tui-newforge.test.ts +2 −1
@@ -6,7 +6,7 @@ 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, updateRepoSettings } from "../src/actions/repos.ts";
9 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { getRepo } from "../src/core/repos.ts";
1212 import { createUser, type User } from "../src/core/users.ts";
@@ -62,6 +62,7 @@ beforeAll(async () => {
6262 for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) {
6363 const made = await createRepo(app, admin, { name, visibility });
6464 if (!made.ok) throw new Error(name);
65 await commitToBranch(app, admin, made.value, { message: "seed", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] });
6566 }
6667 for (const name of ["kit", "secret"]) {
6768 const marked = await updateRepoSettings(app, admin, getRepo(app.db, "alice", name)!, { template: true });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs