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

Terminal: make a client's forge (spawn) from src/tui, with the same fields as /forges/new #1909

Parked opened this
Closed without merging

scout/forge:scout/1782-terminal-make-a-client-s-forge-spawn-fro → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +344 −0
README.md +2
@@ -106,6 +106,8 @@ thoughts, then the issues you can write to that are not shipped, oldest first
106106 only, shows a guest nothing, and names nothing of a placement in a repository
107107 you cannot read.
108108
109 A client's forge: `Ctrl+K`, then **New forge** (a site admin's), is `/forges/new` in the terminal — name, for whom, what it is for, apps to fork (`owner/name`, comma-separated), a fresh one-line app, model key (hidden as typed), API base URL and budget, through the same `spawnDoor` as the page, `POST /api/v1/forges` and the MCP `spawn`. `Ctrl+P` shows the plan and makes nothing; `enter` on the plan spawns, and the claim link is shown once, in a dialog, never kept.
110
109111 The family across forges: `:` → Family in the terminal, `/family` on the web,
110112 `GET /api/v1/family` and the MCP `family` tool all give the same view. The
111113 forge that sent this one is shown to anyone; the forges it sent, only to a
scripts/gate.ts +1
@@ -426,6 +426,7 @@ export const EXCLUDED: readonly Exclusion[] = [
426426 { file: "test/tui-input.test.ts", reason: "not yet admitted", issue: 261 },
427427 { file: "test/tui-local.test.ts", reason: "not yet admitted", issue: 261 },
428428 { file: "test/tui-mouse.test.ts", reason: "not yet admitted", issue: 261 },
429 { file: "test/tui-newforge.test.ts", reason: "not yet admitted", issue: 261 },
429430 { file: "test/tui-render.test.ts", reason: "not yet admitted", issue: 261 },
430431 { file: "test/tui-screens.test.ts", reason: "not yet admitted", issue: 261 },
431432 { file: "test/tui-size.test.ts", reason: "not yet admitted", issue: 261 },
src/tui/forge.ts +9
@@ -41,6 +41,7 @@ import { stalledScreen } from "./screens/stalled.ts";
4141 import { issuesScreen, newIssueScreen } from "./screens/issues.ts";
4242 import { limbsScreen } from "./screens/limbs.ts";
4343 import { newPullScreen } from "./screens/newpull.ts";
44 import { newForgeScreen } from "./screens/newforge.ts";
4445 import { newRepoScreen } from "./screens/newrepo.ts";
4546 import { repoScreen } from "./screens/repo.ts";
4647 import { signInScreen } from "./screens/signin.ts";
@@ -170,6 +171,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
170171 ctx.push(signInScreen(session, ctx, () => ctx.invalidate())),
171172 },
172173 );
174 // A client's forge, as /forges/new makes it: a site admin's, as /forges is.
175 if (session.user?.isAdmin === true)
176 commands.push({
177 id: "new-forge",
178 title: "New forge",
179 hint: "spawn a client's forge and get its claim link",
180 run: () => ctx.push(newForgeScreen(session, ctx)),
181 });
173182 // What you asked for and what became of it, as /asked says it: a signed-in person's.
174183 if (session.signedIn)
175184 commands.push({
src/tui/screens/newforge.ts added +210
@@ -0,0 +1,210 @@
1 /**
2 * `/forges/new` in the terminal (#1782): a client's forge, with the page's
3 * fields. It goes through `spawnDoor` as the page and `POST /api/v1/forges`
4 * do, so every rule (names, budget, the key, the apps you may read) is the
5 * door's and not this screen's. **Ctrl+P** shows the plan and makes nothing;
6 * **Enter** on the plan spawns; the claim link is then shown once, in a
7 * dialog, and kept nowhere. A site admin's, as `/forges` is.
8 */
9
10 import { childUrlOf, spawnDoor } from "../../spawn/door.ts";
11 import { MAX_BUDGET_USD, MIN_BUDGET_USD } from "../../spawn/plan.ts";
12 import type { Ctx, Screen } from "../app/app.ts";
13 import { binding } from "../app/keys.ts";
14 import { style } from "../term/style.ts";
15 import { truncate } from "../term/width.ts";
16 import { field } from "../ui/widgets.ts";
17 import type { Session } from "../session.ts";
18 import { linkScreen, runAsync } from "./common.ts";
19
20 interface Spec {
21 readonly key: string;
22 readonly label: string;
23 readonly hint: string;
24 readonly secret?: boolean;
25 }
26
27 const SPECS: readonly Spec[] = [
28 { key: "name", label: "Name", hint: "Lowercase letters, digits and dashes." },
29 { key: "for", label: "For whom", hint: "A person or client, for your list of forges sent. Optional." },
30 { key: "direction", label: "What it is for", hint: "The crew's first direction. Optional." },
31 { key: "apps", label: "Apps to fork", hint: "owner/name, comma-separated. Optional." },
32 { key: "fresh", label: "Or a fresh app", hint: "One line on what it is. Optional." },
33 { key: "modelKey", label: "Model key", hint: "Sealed in the child, never shown again. Optional.", secret: true },
34 { key: "modelEndpoint", label: "API base URL", hint: "A gateway for the key; empty for Anthropic. Optional." },
35 { key: "budgetUsd", label: "Budget in dollars", hint: `${MIN_BUDGET_USD}–${MAX_BUDGET_USD}, for the key's whole life. Needed with a key.` },
36 ];
37
38 /** The door's "field: reason" refusal, as the field it names and the reason. */
39 function refusal(body: Record<string, unknown>): { key?: string; text: string } {
40 const text = String(body["message"] ?? "refused");
41 const m = /^([A-Za-z]+): (.*)$/.exec(text);
42 return m && body["error"] === "invalid" ? { key: m[1]!, text: m[2]! } : { text };
43 }
44
45 export function newForgeScreen(f: Session, ctx: Ctx): Screen {
46 const values: Record<string, string> = {};
47 let focus = 0;
48 let errorKey: string | undefined;
49 let error: string | undefined;
50 let plan: string[] | undefined;
51 let busy = false;
52
53 const val = (k: string): string => (values[k] ?? "").trim();
54
55 const request = (dryRun: boolean): Record<string, unknown> => {
56 const apps = val("apps").split(",").map((a) => a.trim()).filter((a) => a !== "");
57 return {
58 name: val("name"),
59 apps,
60 ...(val("fresh") === "" ? {} : { fresh: val("fresh") }),
61 ...(val("for") === "" ? {} : { for: val("for") }),
62 ...(val("direction") === "" ? {} : { direction: val("direction") }),
63 ...(val("modelKey") === "" ? {} : { modelKey: val("modelKey") }),
64 ...(val("modelEndpoint") === "" ? {} : { modelEndpoint: val("modelEndpoint") }),
65 ...(val("budgetUsd") === "" ? {} : { budgetUsd: Number(val("budgetUsd")) }),
66 dryRun,
67 };
68 };
69
70 const door = async (dryRun: boolean) => {
71 const url = new URL(f.app.config.url ?? `http://${f.app.config.host ?? "localhost"}`);
72 const hctx = {
73 app: f.app,
74 request: new Request(url.href, { method: "POST" }),
75 url,
76 params: {},
77 auth: { user: f.user, scope: undefined, via: "none" as const },
78 theme: undefined,
79 };
80 return spawnDoor(hctx, f.user, request(dryRun));
81 };
82
83 const refuse = (body: Record<string, unknown>): void => {
84 const r = refusal(body);
85 error = r.text;
86 errorKey = r.key;
87 const at = SPECS.findIndex((s) => s.key === r.key);
88 if (at >= 0) focus = at;
89 plan = undefined;
90 ctx.toast(r.text, "danger");
91 };
92
93 const run = (dryRun: boolean): void => {
94 if (busy) return;
95 busy = true;
96 error = undefined;
97 errorKey = undefined;
98 runAsync(ctx, async () => {
99 try {
100 const made = await door(dryRun);
101 if (made.status >= 400) return refuse(made.body);
102 const body = made.body;
103 if (dryRun) {
104 const copied = (body["copied"] as string[] | undefined) ?? [];
105 const bytes = Number(body["bytes"] ?? 0);
106 const budget = (body["plan"] as { budgetUsd?: number | null } | undefined)?.budgetUsd ?? null;
107 plan = [
108 `A forge at ${childUrlOf(f.app, val("name"))}.`,
109 "Whoever opens the link becomes its admin.",
110 ...(budget === null ? [] : [`Its crew runs on your key, up to $${budget} for the key's whole life.`]),
111 "Copied into it:",
112 ...copied.map((c) => ` ${c}`),
113 `About ${Math.max(1, Math.round(bytes / 1024))} KB. Nothing is made until you press enter.`,
114 ...(typeof body["keyNote"] === "string" ? [body["keyNote"]] : []),
115 ];
116 return;
117 }
118 values["modelKey"] = "";
119 const link = body["claimUrl"];
120 const name = String(body["name"] ?? val("name"));
121 if (typeof link === "string") {
122 ctx.toast(`${name} is ready`, "success");
123 ctx.replace(linkScreen(ctx, link));
124 } else {
125 ctx.toast(`${name} already exists; its link is not shown again`, "attn");
126 ctx.pop();
127 }
128 } finally {
129 busy = false;
130 ctx.invalidate();
131 }
132 });
133 };
134
135 return {
136 title: "New forge",
137 keys: [
138 binding(["tab"], "next field"),
139 binding(["ctrl+p"], "see the plan"),
140 binding(["enter"], "spawn (on the plan)"),
141 binding(["esc"], "back"),
142 ],
143 render(area, s) {
144 const c = ctx.theme.c;
145 if (plan !== undefined) {
146 s.text(area.x, area.y, truncate("The plan", area.w), style(c.accent, c.bg), area.x + area.w);
147 plan.forEach((line, i) => {
148 if (i + 2 < area.h)
149 s.text(area.x, area.y + 2 + i, truncate(line, area.w), style(c.fg, c.bg), area.x + area.w);
150 });
151 ctx.setCursor(null);
152 return;
153 }
154 // Three rows a field; the window scrolls so the focused one is in view.
155 const rows = Math.max(1, Math.floor(area.h / 3));
156 const first = Math.max(0, Math.min(focus - rows + 1, SPECS.length - rows));
157 let cursor: { x: number; y: number } | null = null;
158 SPECS.slice(first, first + rows).forEach((spec, n) => {
159 const i = first + n;
160 const raw = values[spec.key] ?? "";
161 const shown = spec.secret === true ? "•".repeat([...raw].length) : raw;
162 const at = field(s, { x: area.x, y: area.y + n * 3, w: Math.min(70, area.w), h: 3 }, c, {
163 label: spec.label,
164 value: shown,
165 focused: focus === i,
166 ...(focus === i ? { cursor: [...shown].length } : {}),
167 ...(error !== undefined && (errorKey === spec.key || (errorKey === undefined && focus === i))
168 ? { error }
169 : { hint: spec.hint }),
170 });
171 if (focus === i) cursor = at;
172 });
173 ctx.setCursor(cursor);
174 },
175 paste(text) {
176 if (plan !== undefined) return true;
177 const k = SPECS[focus]!.key;
178 values[k] = (values[k] ?? "") + text.replace(/\s+/g, " ").trim();
179 return true;
180 },
181 key(e) {
182 if (plan !== undefined) {
183 if (e.key === "enter") run(false);
184 else if (e.key === "esc") plan = undefined;
185 return true;
186 }
187 if (e.ctrl && e.key === "p") {
188 run(true);
189 return true;
190 }
191 if (e.key === "tab" || e.key === "enter") {
192 focus = (focus + 1) % SPECS.length;
193 return true;
194 }
195 if (e.key === "backspace") {
196 const k = SPECS[focus]!.key;
197 values[k] = [...(values[k] ?? "")].slice(0, -1).join("");
198 error = undefined;
199 return true;
200 }
201 if (!e.ctrl && !e.alt && [...e.key].length === 1) {
202 const k = SPECS[focus]!.key;
203 values[k] = (values[k] ?? "") + e.key;
204 error = undefined;
205 return true;
206 }
207 return false;
208 },
209 };
210 }
test/tui-newforge.test.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * "New forge" in the terminal (#1782): the page's fields through `spawnDoor`,
3 * the plan before the spawn, the claim link once, a site admin's.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, readdir, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { usePlacement } from "../src/spawn/door.ts";
13 import { hostedPlacement } from "../src/spawn/placement.ts";
14 import { createForgeApp, forgeCommands, Session } from "../src/tui/forge.ts";
15 import { newForgeScreen } from "../src/tui/screens/newforge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 quietLogs();
21
22 let dir: string;
23 let app: App;
24 let admin: User;
25 let bob: User;
26
27 const identity = (user?: User) => ({
28 sshUsername: user?.username ?? "git",
29 remoteAddress: "127.0.0.1",
30 fingerprint: "SHA256:test",
31 user,
32 });
33 const children = async () => (await readdir(join(dir, "spawn")).catch(() => [] as string[])).length;
34
35 function open(user: User) {
36 const terminal = headlessTerminal(120, 40);
37 const { app: tui, session } = createForgeApp(app, identity(user), { terminal, exitHooks: false });
38 tui.start();
39 tui.ctx.push(newForgeScreen(session, tui.ctx));
40 return { tui, terminal };
41 }
42
43 beforeAll(async () => {
44 dir = await mkdtemp(join(tmpdir(), "forge-tui-newforge-"));
45 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
46 const mk = async (username: string, isAdmin: boolean) => {
47 const r = await createUser(app.db, {
48 trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", isAdmin,
49 });
50 if (!r.ok) throw new Error(r.error);
51 return r.value;
52 };
53 admin = await mk("alice", true);
54 bob = await mk("bob", false);
55 const repo = await createRepo(app, admin, { name: "bakery", visibility: "public" });
56 if (!repo.ok) throw new Error("repo");
57 usePlacement(app, hostedPlacement({ host: "forge.test" }));
58 });
59 afterAll(async () => {
60 app.db.close();
61 await rm(dir, { recursive: true, force: true });
62 });
63
64 describe("the new forge screen", () => {
65 test("the palette offers it to a site admin only", () => {
66 const ids = (u?: User) => forgeCommands(new Session(app, identity(u)))({} as never).map((c) => c.id);
67 expect(ids(admin)).toContain("new-forge");
68 expect(ids(bob)).not.toContain("new-forge");
69 expect(ids()).not.toContain("new-forge");
70 });
71
72 test("the plan is shown first and makes nothing; enter spawns and shows the claim link once", async () => {
73 const { tui, terminal } = open(admin);
74 await settleApp(tui);
75 terminal.feed("kai\t\t\talice/bakery\r");
76 terminal.feed("\x10"); // ctrl+p
77 await settleApp(tui);
78 let text = tui.screen.toText();
79 expect(text).toContain("The plan");
80 expect(text).toContain("kai--forge.test");
81 expect(await children()).toBe(0);
82 terminal.feed("\r");
83 await settleApp(tui);
84 text = tui.screen.toText();
85 expect(await children()).toBe(1);
86 expect(text).toMatch(/https:\/\/kai--forge\.test\/claim#/);
87 tui.stop?.();
88 });
89
90 test("the door's refusal lands on the field it names, and nothing is made", async () => {
91 const { tui, terminal } = open(admin);
92 await settleApp(tui);
93 terminal.feed("Bad Name!\x10");
94 await settleApp(tui);
95 const text = tui.screen.toText();
96 expect(text).not.toContain("The plan");
97 expect(text.toLowerCase()).toContain("name");
98 expect(await children()).toBe(1);
99 tui.stop?.();
100 });
101
102 test("a key without a budget is refused by the door", async () => {
103 const { tui, terminal } = open(admin);
104 await settleApp(tui);
105 terminal.feed("lee\t\t\t\t\tsk-ant-api03-child-key-AAAAAAAAAAAAAAAAAAAAAAAA\x10");
106 await settleApp(tui);
107 const text = tui.screen.toText();
108 expect(text).not.toContain("The plan");
109 expect(text).toContain("budget");
110 expect(text).not.toContain("sk-ant-api03");
111 tui.stop?.();
112 });
113
114 test("a person who is not an admin cannot spawn through the screen", async () => {
115 const { tui, terminal } = open(bob);
116 await settleApp(tui);
117 terminal.feed("zed\x10\r");
118 await settleApp(tui);
119 expect(await children()).toBe(1);
120 tui.stop?.();
121 });
122 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs