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

The New forge form and the terminal's new-forge screen offer the size, and an unknown size is shown beside the field #4394

Closed opened this
Closed without merging

scout/forge:scout/2996-the-new-forge-form-and-the-terminal-s-ne → main 3 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +251 −5
README.md +1 −1
@@ -603,7 +603,7 @@ forge can be a parent. The terminal shows the count, not the release names.
603603
604604 A spawned forge's own code is a fork of its parent's (`<org>/forge`, chosen
605605 `followMode` `tell-me` or `take-updates`; in `take-updates` the hourly check puts what the parent gained in a pull.
606 A spawn may also name a `size`: `small`, `medium` or `large` (`src/spawn/sizes.ts` maps each to CPU, memory and disk). It is recorded in the plan only when given, so a plan without one hashes as it always did, and an unknown size is a 422 on `size`. Nothing enforces the limits yet, and the table's numbers are provisional. `GET /api/v1/forges/sizes` (no sign-in, ETag, cached for 5 minutes) and the MCP tool `sizes` give the same answer — each size's CPU, memory and disk, read from that table, and one sentence on what it is for — so a page or an agent offering a size reads it there.
606 A spawn may also name a `size`: `small`, `medium` or `large` (`src/spawn/sizes.ts` maps each to CPU, memory and disk). It is recorded in the plan only when given, so a plan without one hashes as it always did, and an unknown size is a 422 on `size`. Nothing enforces the limits yet, and the table's numbers are provisional. `GET /api/v1/forges/sizes` (no sign-in, ETag, cached for 5 minutes) and the MCP tool `sizes` give the same answer — each size's CPU, memory and disk, read from that table, and one sentence on what it is for — so a page or an agent offering a size reads it there. The New forge form offers the size as a select (small preselected, each size's sentence beside it; an unknown one is a 422 with the reason beside the select and a note that the default is shown), and the terminal's new-forge screen has a `Size` field (empty sends none; the door's refusal lands on it).
607607 Once an hour, and
608608 on demand, a forge that follows and has not severed fetches its parent's code into
609609 `refs/upstream/*` of its own `<org>/forge` (no branch of the fork moves) and keeps
src/tui/screens/newforge.ts +2
@@ -34,6 +34,7 @@ const SPECS: readonly Spec[] = [
3434 { key: "modelEndpoint", label: "API base URL", hint: "A gateway for the key; empty for Anthropic. Optional." },
3535 { key: "budgetUsd", label: "Budget in dollars", hint: `${MIN_BUDGET_USD}–${MAX_BUDGET_USD}, for the key's whole life. Needed with a key.` },
3636 { key: "followMode", label: "Follows this forge's code", hint: "tell-me (default) or take-updates. Recorded for now: nothing tells you or takes updates yet." },
37 { key: "size", label: "Size", hint: "small (default), medium or large." },
3738 ];
3839
3940 /** The door's "field: reason" refusal, as the field it names and the reason. */
@@ -59,6 +60,7 @@ export function newForgeScreen(f: Session, ctx: Ctx): Screen {
5960 name: val("name"),
6061 apps,
6162 ...(val("fresh") === "" ? {} : { fresh: val("fresh") }),
63 ...(val("size") === "" ? {} : { size: val("size") }),
6264 followMode: val("followMode") === "" ? "tell-me" : val("followMode"),
6365 ...(val("for") === "" ? {} : { for: val("for") }),
6466 ...(val("direction") === "" ? {} : { direction: val("direction") }),
src/web/pages/new-forge.ts +27 −1
@@ -26,7 +26,8 @@ import { notFoundPage, pageHead } from "../chrome.ts";
2626 import { field, readForm, type Form } from "../form.ts";
2727 import { html, type Html } from "../html.ts";
2828 import { page } from "../layout.ts";
29 import { btn, card, field as formField, row } from "../ui.ts";
29 import { btn, card, field as formField, row, selectField } from "../ui.ts";
30 import { DEFAULT_SIZE, isSize, sizesView, type Size } from "../../spawn/sizes.ts";
3031
3132 interface Values {
3233 readonly name: string;
@@ -39,6 +40,7 @@ interface Values {
3940 readonly keepAccess: boolean;
4041 readonly budgetUsd: string;
4142 readonly modelEndpoint: string;
43 readonly size: string;
4244 /** The last post carried a key: it is never sent back, so it is asked for again. */
4345 readonly hadKey: boolean;
4446 }
@@ -54,6 +56,7 @@ const EMPTY: Values = {
5456 keepAccess: false,
5557 budgetUsd: "",
5658 modelEndpoint: "",
59 size: DEFAULT_SIZE,
5760 hadKey: false,
5861 };
5962
@@ -117,6 +120,26 @@ function readsFor(ctx: Ctx, user: User | undefined): Reads {
117120 return { full, repos, crew };
118121 }
119122
123 /** The size choice: each size's own sentence from the table the API reads. */
124 function sizeField(chosen: string, error: string | undefined): Html {
125 const at: Size = isSize(chosen) ? chosen : DEFAULT_SIZE;
126 const { sizes } = sizesView();
127 return selectField({
outdated

Hand-rolled wrapper: put data-invalid and the error inside selectField (an error option wired with aria-describedby/aria-invalid) like field does.

128 label: "Size (optional)",
129 name: "size",
130 id: "f-size",
131 hint: error
132 ? `"${chosen}" is not a size, so ${at} is shown until you choose.`
133 : sizes.map((s) => `${s.size[0]!.toUpperCase()}${s.size.slice(1)}: ${s.says}`).join(" "),
134 ...(error ? { error } : {}),
135 options: sizes.map((s) => ({
136 value: s.size,
137 label: `${s.size[0]!.toUpperCase()}${s.size.slice(1)}`,
138 selected: s.size === at,
139 })),
140 });
141 }
142
120143 function formView(
121144 ctx: Ctx,
122145 user: User | undefined,
@@ -290,6 +313,7 @@ function formView(
290313 hint: "For the key's whole life; the child cannot raise it. Needed with a key.",
291314 ...(errors["budgetUsd"] ? { error: errors["budgetUsd"] } : {}),
292315 })}
316 ${sizeField(values.size, errors["size"])}
293317 <p class="muted small">
294318 Never copied: ${LEFT_BEHIND.join(", ")}. The child mints its own.
295319 </p>
@@ -421,6 +445,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
421445 keepAccess: asBool(form, "keepAccess"),
422446 budgetUsd: field(form, "budgetUsd").trim(),
423447 modelEndpoint: field(form, "modelEndpoint").trim(),
448 size: field(form, "size").trim() || DEFAULT_SIZE,
424449 hadKey: field(form, "modelKey").trim() !== "",
425450 };
426451 const key = field(form, "modelKey").trim();
@@ -437,6 +462,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
437462 ...(key === "" ? {} : { modelKey: key }),
438463 ...(values.modelEndpoint === "" ? {} : { modelEndpoint: values.modelEndpoint }),
439464 ...(values.budgetUsd === "" ? {} : { budgetUsd: Number(values.budgetUsd) }),
465 size: values.size,

The form always sends size, so every web-made child records one in its plan, unlike the terminal's empty field. Consider omitting it when it equals the default and was not chosen.

440466 dryRun: planOnly,
441467 });
442468 if (door.status >= 400)
src/web/ui.ts +14 −3
@@ -1205,9 +1205,13 @@ export function selectField(
12051205 },
12061206 ): Html {
12071207 const id = o.id ?? `f-${o.name}`;
1208 return html`<div class="field">
1208 // The hint is named only beside an error, so the refusal is read with it.
1209 const described = o.error ? [o.hint ? `${id}-hint` : "", `${id}-err`].filter(Boolean).join(" ") : "";
1210 return html`<div class="field" ${o.error ? raw("data-invalid") : null}>
12091211 <label for="${id}">${o.label}</label>
1210 <select class="input" id="${id}" name="${o.name}">
1212 <select class="input" id="${id}" name="${o.name}"
1213 ${described !== "" ? html`aria-describedby="${described}"` : null}
1214 ${o.error ? raw('aria-invalid="true"') : null}>
12111215 ${o.options.map(
12121216 (opt) =>
12131217 html`<option
@@ -1218,7 +1222,14 @@ export function selectField(
12181222 </option>`,
12191223 )}
12201224 </select>
1221 ${o.hint ? html`<span class="hint">${o.hint}</span>` : null}
1225 ${o.hint
1226 ? o.error
1227 ? html`<span class="hint" id="${id}-hint">${o.hint}</span>`
1228 : html`<span class="hint">${o.hint}</span>`
1229 : null}
1230 ${o.error
1231 ? html`<span class="error" id="${id}-err">${o.error}</span>`
1232 : null}
12221233 </div>`;
12231234 }
12241235
test/new-forge-size.test.ts added +207
@@ -0,0 +1,207 @@
1 /**
2 * The size on /forges/new (#2996): offered, small preselected; an unknown one
3 * is refused beside its field with the rest kept; a chosen one reaches
4 * `parent.json`.
5 */
6
7 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
8 import { mkdtemp, readdir, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { childDirOf } from "../src/actions/spawn.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { commitFiles } from "../src/git/write.ts";
16 import { repoDir } from "../src/git/repos.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import * as door from "../src/spawn/door.ts";
19 import { usePlacement, useProbe } from "../src/spawn/door.ts";
20 import { hostedPlacement } from "../src/spawn/placement.ts";
21 import { createForgeApp } from "../src/tui/forge.ts";
22 import { newForgeScreen } from "../src/tui/screens/newforge.ts";
23 import { headlessTerminal } from "../src/tui/term/terminal.ts";
24 import { settleApp } from "./helpers/tui.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26
27 quietLogs();
28
29 const PASSWORD = "a-long-new-forge-size-passphrase";
30
31 describe("the size on the New forge form", () => {
32 let dir = "";
33 let app: App;
34 let servers: Servers;
35 let cookie = "";
36
37 const post = (form: [string, string][]) =>
38 fetch(`${servers.url}/forges/new`, {
39 method: "POST",
40 headers: { cookie, origin: "https://forge.test" },
41 body: new URLSearchParams(form),
42 redirect: "manual",
43 });
44
45 beforeAll(async () => {
46 dir = await mkdtemp(join(tmpdir(), "forge-new-forge-size-"));
47 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
48 const a = await createUser(app.db, {
49 origin: "seed",
50 trusted: true,
51 username: "alice",
52 email: "[email protected]",
53 password: PASSWORD,
54 isAdmin: true,
55 });
56 if (!a.ok) throw new Error("user");
57 const r = await createRepo(app, a.value, { name: "bakery" });
58 if (!r.ok) throw new Error("repo");
59 const c = await commitFiles(repoDir(app.reposRoot, "alice", "bakery"), {
60 branch: "main",
61 message: "bakery",
62 files: [{ path: "README.md", content: "# bakery\n" }],
63 author: { name: "a", email: "[email protected]" },
64 });
65 if (!c.ok) throw new Error("commit");
66 servers = await serve(app);
67 const res = await fetch(`${servers.url}/signin`, {
68 method: "POST",
69 body: new URLSearchParams({ username: "alice", password: PASSWORD }),
70 redirect: "manual",
71 });
72 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
73 }, 30_000);
74
75 afterAll(async () => {
76 servers.stop();
77 app.close();
78 await rm(dir, { recursive: true, force: true });
79 });
80
81 test("the form offers small, medium and large, small preselected", async () => {
82 const html = (await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text()).replace(/\s+/g, " ");
83 expect(html).toMatch(/<select[^>]*name="size"/);
84 expect(html).toMatch(/<option value="small" selected\s*>/);
85 expect(html).toMatch(/<option value="medium"\s*>/);
86 expect(html).toMatch(/<option value="large"\s*>/);
87 });
88
89 test("an unknown size is a 422 with the message beside the field and the rest kept", async () => {
90 const res = await post([
91 ["name", "kai"],
92 ["apps", "alice/bakery"],
93 ["direction", "Run Kai's shop."],
94 ["size", "huge"],
95 ["do", "spawn"],
96 ]);
97 expect(res.status).toBe(422);
98 const html = await res.text();
99 expect(html).toMatch(/id="f-size-err">[^<]*size must be small, medium or large/);
100 expect(html).toMatch(/<div class="field" data-invalid>\s*<label for="f-size">/);
101 expect(html).toMatch(/<select[^>]*aria-describedby="f-size-hint f-size-err"[^>]*aria-invalid="true"|<select[^>]*aria-invalid="true"[^>]*aria-describedby="f-size-hint f-size-err"/);
102 expect(html).toContain("&quot;huge&quot; is not a size, so small is shown");
103 expect(html).toContain('value="kai"');
104 expect(html).toContain("Run Kai&#39;s shop.");
105 expect(html).toMatch(/value="alice\/bakery"[^>]*checked|checked[^>]*value="alice\/bakery"/);
106 expect(await readdir(join(dir, "spawn")).catch(() => [])).toEqual([]);
107 });
108
109 test("a chosen size reaches parent.json", async () => {
110 const res = await post([
111 ["name", "kai"],
112 ["apps", "alice/bakery"],
113 ["size", "large"],
outdated

This greps source text. Drive the screen and assert the size reaches the door, an unknown one is shown beside the field, and an empty one sends nothing.

114 ["do", "spawn"],
115 ]);
116 expect(res.status).toBe(201);
117 const ledger = await Bun.file(join(dir, "spawn", "kai.json")).json();
118 const meta = await Bun.file(join(childDirOf(app, ledger.bodyId), "parent.json")).json();
119 expect(meta.size).toBe("large");
120 });
121 });
122
123 describe("the size on the terminal's new-forge screen", () => {
124 let dir = "";
125 let app: App;
126
127 beforeAll(async () => {
128 dir = await mkdtemp(join(tmpdir(), "forge-tui-size-"));
129 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
130 const r = await createUser(app.db, {
131 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
132 password: PASSWORD, isAdmin: true,
133 });
134 if (!r.ok) throw new Error(r.error);
135 useProbe(app, () => async () => true);
136 usePlacement(app, hostedPlacement({ host: "forge.test" }));
137 (app as { _u?: unknown })._u = r.value;
138 });
139 afterAll(async () => {
140 app.db.close();
141 await rm(dir, { recursive: true, force: true });
142 });
143
144 async function withScreen(body: (h: { tui: any; terminal: any }) => Promise<void>) {
145 const user = (app as unknown as { _u: never })._u;
146 const terminal = headlessTerminal(120, 40);
147 const { app: tui, session } = createForgeApp(
148 app,
149 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
150 { terminal, exitHooks: false },
151 );
152 tui.start();
153 tui.ctx.push(newForgeScreen(session, tui.ctx));
154 try {
155 await settleApp(tui);
156 await body({ tui, terminal });
157 } finally {
158 tui.stop?.();
159 }
160 }
161 const toSize = "\t".repeat(9);
162 const parents = async () =>
163 Promise.all(
164 (await readdir(join(dir, "children")).catch(() => [] as string[])).map((d) =>
165 Bun.file(join(dir, "children", d, "parent.json")).json().catch(() => undefined),
166 ),
167 );
168
169 test("a typed size reaches the door and parent.json", () =>
170 withScreen(async ({ tui, terminal }) => {
171 terminal.feed(`sized${toSize}large\x10`);
172 await settleApp(tui);
173 expect(tui.screen.toText()).toContain("The plan");
174 terminal.feed("\r");
175 await settleApp(tui);
176 expect((await parents()).find((d) => d?.name === "sized")?.size).toBe("large");
177 }));
178
179 test("an unknown size is refused beside the field and nothing is made", () =>
180 withScreen(async ({ tui, terminal }) => {
181 terminal.feed(`huged${toSize}huge\x10`);
182 await settleApp(tui);
183 const text = tui.screen.toText();
184 expect(text).not.toContain("The plan");
185 expect(text).toContain("size must be small, medium or large");
186 expect((await parents()).find((d) => d?.name === "huged")).toBeUndefined();
187 }));
188
189 test("an empty size sends none", () =>
190 withScreen(async ({ tui, terminal }) => {
191 const sent: Record<string, unknown>[] = [];
192 const real = door.spawnDoor;
193 const spy = spyOn(door, "spawnDoor").mockImplementation((...a) => {
194 sent.push(a[2] as Record<string, unknown>);
195 return real(...a);
196 });
197 terminal.feed("nosize\x10");
198 await settleApp(tui);
199 terminal.feed("\r");
200 await settleApp(tui);
201 const doc = (await parents()).find((d) => d?.name === "nosize");
202 expect(doc).toBeDefined();
203 expect(sent.length).toBeGreaterThan(0);
204 spy.mockRestore();
205 for (const body of sent) expect("size" in body).toBe(false);
206 }));
207 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs