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

The starter budget for a client's forge is one setting with its reason beside it, used by the new-forge form #15771

Merged opened this

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

Merged

scout/forge:scout/15747-the-starter-budget-for-a-client-s-forge → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/15747-the-starter-budget-for-a-client-s-forge was merged into main as f545d23.

Review

Sign in to review this change.
8 files changed +189 −21
docs/features/client-forge.md +6 −6
@@ -25,15 +25,15 @@ shown once. `/forges` and MCP tool `forges` list the forges sent.
2525 Before anything is made, the plan lists the apps, the starter budget, the admin
2626 account's name and the words "This sends one link." That is `/forges/new` with
2727 See the plan, the terminal's Ctrl+P, and `spawn` with `dryRun` left true.
28
29 Confirming makes the forge once and answers a receipt (name, address, apps,
30 admin, `linkShown`, and the budget when kept), read from what was made.
31 Confirming again makes nothing: the same receipt, `linkShown: false`.
28 The budget field opens at the starter budget, set on Settings → Limits
29 (`spawn.starter_budget_usd`, 0 to 1,000; 0 opens it empty). The door checks every amount.
30 Confirming makes the forge once and answers a receipt (name, address, apps, admin, `linkShown`,
31 and the budget when kept). Confirming again makes nothing: the same receipt, `linkShown: false`.
3232
3333 ## Send the link
3434
35 The sender copies the claim link and sends it. The client opens `/claim` and makes an account with a
36 username and a password, or a passkey.
35 The sender copies the claim link and sends it. The client opens `/claim` and
36 makes an account with a username and a password, or a passkey.
3737
3838 ## First login
3939
src/settings/limits.ts +9
@@ -32,6 +32,7 @@ export type LimitKey =
3232 | "checks.concurrency"
3333 | "agent.budget_max_usd"
3434 | "spawn.included_credit_usd"
35 | "spawn.starter_budget_usd"
3536 | "subscription.budget_max_usd"
3637 | "app.members_max"
3738 | "front.pinned_max"
@@ -440,6 +441,14 @@ export const LIMITS: Record<LimitKey, LimitDef> = {
440441 max: 3_650,
441442 reason: "Issue, pull, push and account events are kept at any age; the rest feeds windows of 30 days at most, and kept longer they filled the database past the 2 GiB Bun maps.",
442443 },
444 "spawn.starter_budget_usd": {
445 label: "Starter budget for a new client forge",
446 unit: "dollars",
447 default: 5,
448 min: 0,
449 max: 1_000,
450 reason: "A client's forge gets its own key with a whole-life budget the client cannot raise, so the form starts at a small sum that lets the crew show something real; 0 leaves the budget empty for each forge to choose.",
451 },
443452 "retention.deploy_pull_days": {
444453 label: "Days a deploy keeps the list of pulls it carried",
445454 unit: "days",
src/settings/starter_budget.ts added +14
@@ -0,0 +1,14 @@
1 /**
2 * The starter budget for a client's forge (#15747): the `spawn.starter_budget_usd` limit, one
3 * setting on Settings → Limits with its reason beside it. The new-forge form (page and terminal)
4 * opens with it filled in; the plan still checks whatever is posted (`spawn/plan.ts`), so the
5 * value here is only a starting point, never trusted from the form.
6 */
7 import type { Database } from "bun:sqlite";
8 import { limitValue } from "./limits.ts";
9
10 /** The budget the form starts with, in dollars as text; empty when the setting is 0. */
11 export function starterBudgetField(db: Database): string {
12 const usd = limitValue(db, "spawn.starter_budget_usd");
13 return usd > 0 ? String(usd) : "";
14 }
src/tui/screens/newforge.ts +15 −4
@@ -14,6 +14,7 @@ import { childUrlOf, spawnDoor } from "../../spawn/door.ts";
1414 import { quotaFull } from "../../spawn/quota.ts";
1515 import { FOLLOW_LINE, FOLLOW_WORDS } from "../../spawn/follow_words.ts";
1616 import { isFollowMode } from "../../spawn/chain.ts";
17 import { starterBudgetField } from "../../settings/starter_budget.ts";
1718 import { MAX_BUDGET_USD, MIN_BUDGET_USD } from "../../spawn/plan.ts";
1819 import { listRecipes, saveRecipe } from "../../spawn/recipes.ts";
1920 import type { Ctx, Screen } from "../app/app.ts";
@@ -82,7 +83,14 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
8283 ...SPECS.map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s)),
8384 ...(recipes.length === 0 ? [] : [{ ...RECIPE_SPEC, choices: ["", ...recipes] }]),
8485 ];
85 const values: Record<string, string> = { ...initial };
86 const starter = starterBudgetField(f.app.db);
outdated

Prefilling makes typed digits append ('20' -> '520'). Fix the field to replace on first key; and add a test that the screen opens with the setting.

87 const values: Record<string, string> = { budgetUsd: starter, ...initial };
88 // The prefilled budget is replaced by the first thing typed, never appended to ('20' is not
89 // '520').
90 const untouched = new Set(values["budgetUsd"] === starter && starter !== "" ? ["budgetUsd"] : []);
91 const typed = (k: string, text: string): void => {
92 values[k] = (untouched.delete(k) ? "" : (values[k] ?? "")) + text;
93 };
8694 let focus = 0;
8795 let errorKey: string | undefined;
8896 let error: string | undefined;
@@ -111,7 +119,9 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
111119 ...(val("direction") === "" ? {} : { direction: val("direction") }),
112120 ...(val("modelKey") === "" ? {} : { modelKey: val("modelKey") }),
113121 ...(val("modelEndpoint") === "" ? {} : { modelEndpoint: val("modelEndpoint") }),
114 ...(val("budgetUsd") === "" || val("recipe") !== "" ? {} : { budgetUsd: Number(val("budgetUsd")) }),
122 ...(val("budgetUsd") === "" || val("recipe") !== "" || (val("modelKey") === "" && untouched.has("budgetUsd"))
123 ? {}
124 : { budgetUsd: Number(val("budgetUsd")) }),
115125 ...(val("migration") === "migration" ? { migration: true } : {}),
116126 // Small is the default: it is not recorded, as on the page.
117127 ...(val("size") === "" || val("size") === DEFAULT_SIZE ? {} : { size: val("size") }),
@@ -261,7 +271,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
261271 paste(text) {
262272 if (plan !== undefined) return true;
263273 const k = specs[focus]!.key;
264 values[k] = (values[k] ?? "") + text.replace(/\s+/g, " ").trim();
274 typed(k, text.replace(/\s+/g, " ").trim());
265275 return true;
266276 },
267277 key(e) {
@@ -290,13 +300,14 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
290300 }
291301 if (e.key === "backspace") {
292302 const k = specs[focus]!.key;
303 untouched.delete(k);
293304 values[k] = [...(values[k] ?? "")].slice(0, -1).join("");
294305 error = undefined;
295306 return true;
296307 }
297308 if (!e.ctrl && !e.alt && [...e.key].length === 1) {
298309 const k = specs[focus]!.key;
299 values[k] = (values[k] ?? "") + e.key;
310 typed(k, e.key);
300311 error = undefined;
301312 return true;
302313 }
src/web/pages/new-forge.ts +18 −5
@@ -17,6 +17,7 @@ import type { Ctx } from "../../http/context.ts";
1717 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1818 import { giftOf, REDEEM_WORDS } from "../../actions/codes.ts";
1919 import { limitValue } from "../../settings/limits.ts";
20 import { starterBudgetField } from "../../settings/starter_budget.ts";
2021 import { creditWords } from "../../billing/plan_words.ts";
2122 import { quotaFull } from "../../spawn/quota.ts";
2223 import { childHost, childUrlOf, doorHeaders, noRoom, spawnDoor, type Door } from "../../spawn/door.ts";
@@ -524,6 +525,7 @@ function planView(ctx: Ctx, user: User | undefined, values: Values, body: Record
524525 const plan = body["plan"] as { budgetUsd?: number | null; template?: string } | undefined;
525526 const budget = plan?.budgetUsd ?? null;
526527 const address = childUrlOf(ctx.app, values.name);
528 const starterDropped = budget === null && unaskedStarter(values.budgetUsd, values.hadKey ? "key" : "", starterBudgetField(ctx.app.db));
527529 return html`<section class="settings-block" id="plan">
528530 <h2>The plan</h2>
529531 ${previewLines(body["preview"])}
@@ -541,9 +543,11 @@ function planView(ctx: Ctx, user: User | undefined, values: Values, body: Record
541543 ${plan?.template === undefined
542544 ? null
543545 : html`<li>It starts from the <b>${templateOf(plan.template).title}</b> template.</li>`}
544 ${budget === null
545 ? null
546 : html`<li>Its crew runs on the key you give, up to $${budget} for the key's whole life.</li>`}
546 ${budget !== null
547 ? html`<li>Its crew runs on the key you give, up to $${budget} for the key's whole life.</li>`
outdated

Principle 1/8: claims 'the starter budget' even when the person typed a different sum. Make it conditional or remove.

548 : starterDropped
outdated

Principle 1: second sentence about the same budget; one line is enough. Also reads starterBudgetField twice here.

549 ? html`<li>The $${values.budgetUsd} budget is for a key: this forge gets none until you add one.</li>`
550 : null}
547551 </ul>
548552 <p class="mb">Copied into it:</p>
549553 <ul class="mb">
@@ -634,6 +638,13 @@ function askedTemplate(ctx: Ctx): string {
634638 return asked.ok ? asked.value : DEFAULT_TEMPLATE;
635639 }
636640
641 /**
642 * Whether a budget is only the starter figure the page opened with, on a submission with no key:
643 * a budget is for a key, so the untouched figure is dropped rather than refused; anything else is
644 * sent on and the door checks it.
645 */
646 const unaskedStarter = (budget: string, key: string, starter: string): boolean => key === "" && budget === starter;
647
637648 // GET /forges/new — any signed-in person, or a stranger (agents are refused).
638649 export function newForgePage(ctx: Ctx): Response {
639650 const user = ctx.auth.user;
@@ -654,7 +665,7 @@ export function newForgePage(ctx: Ctx): Response {
654665 ctx,
655666 title: "New forge",
656667 keyboardResizes: true,
657 body: formView(ctx, user, { ...EMPTY, code, name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), template: askedTemplate(ctx), ...fromPack(ctx, user) }, errors, gift, reads),
668 body: formView(ctx, user, { ...EMPTY, code, name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), template: askedTemplate(ctx), budgetUsd: starterBudgetField(ctx.app.db), ...fromPack(ctx, user) }, errors, gift, reads),
658669 });
659670 notePhase(ctx.request, "render", performance.now() - rendering);
660671 return response;
@@ -720,7 +731,9 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
720731 ...(values.direction.trim() === "" ? {} : { direction: values.direction }),
721732 ...(key === "" ? {} : { modelKey: key }),
722733 ...(values.modelEndpoint === "" ? {} : { modelEndpoint: values.modelEndpoint }),
723 ...(values.budgetUsd === "" || recipe !== "" ? {} : { budgetUsd: Number(values.budgetUsd) }),
734 ...(values.budgetUsd === "" || recipe !== "" || unaskedStarter(values.budgetUsd, key, starterBudgetField(ctx.app.db))

Silent drop of a budget the person may have typed on purpose. Needs a visible word on the plan and a direct test.

735 ? {}
736 : { budgetUsd: Number(values.budgetUsd) }),
724737 // Small is the default: it is not recorded, so the plan stays as it was.
725738 ...(values.size === DEFAULT_SIZE ? {} : { size: values.size }),
726739 ...(values.template === DEFAULT_TEMPLATE ? {} : { template: values.template }),
test/new-forge-words.test.ts +1 −1
@@ -73,7 +73,7 @@ describe("new forge words", () => {
7373 const cases: [string, [string, string][]][] = [
7474 ["modelKey", [["modelKey", "x".repeat(5000)], ["budgetUsd", "5"]]],
7575 ["budgetUsd", [["modelKey", "sk-ant-api03-abcdefghijklmnop"]]],
76 ["budgetUsd", [["budgetUsd", "5"]]],
76 ["budgetUsd", [["budgetUsd", "6"]]],
7777 ["modelEndpoint", [["modelEndpoint", "https://openrouter.ai/api"]]],
7878 ["modelEndpoint", [["modelKey", "sk-ant-oat01-abcdefghijklmnop"], ["budgetUsd", "5"], ["modelEndpoint", "https://openrouter.ai/api"]]],
7979 ];
test/starter-budget.test.ts added +102
@@ -0,0 +1,102 @@
1 /** The starter budget is one setting, and the new-forge form follows it (#15747). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createUser } from "../src/core/users.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { LIMITS, setLimit } from "../src/settings/limits.ts";
10 import { starterBudgetField } from "../src/settings/starter_budget.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12
13 quietLogs();
14
15 const PASSWORD = "a-long-new-forge-passphrase";
16 let dir = "";
17 let app: App;
18 let servers: Servers;
19 let cookie = "";
20 let adminId = "";
21
22 beforeAll(async () => {
23 dir = await mkdtemp(join(tmpdir(), "forge-starter-budget-"));
24 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
25 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: PASSWORD, isAdmin: true });
26 if (!a.ok) throw new Error("user");
27 adminId = a.value.id;
28 servers = await serve(app);
29 const res = await fetch(`${servers.url}/signin`, {
30 method: "POST",
31 body: new URLSearchParams({ username: "alice", password: PASSWORD }),
32 redirect: "manual",
33 });
34 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
35 }, 30_000);
36
37 afterAll(async () => {
38 servers.stop();
39 app.close();
40 await rm(dir, { recursive: true, force: true });
41 });
42
43 const budgetValue = async (): Promise<string | undefined> => {
44 const html = (await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text()).replace(/\s+/g, " ");
45 const input = /<input[^>]*name="budgetUsd"[^>]*>/.exec(html)?.[0] ?? "";
46 return /value="([^"]*)"/.exec(input)?.[1];
47 };
48
49 test("the setting has a default, a reason and a non-negative bound", () => {
50 const def = LIMITS["spawn.starter_budget_usd"];
51 expect(def.default).toBeGreaterThan(0);
52 expect(def.min).toBe(0);
53 expect(def.reason.length).toBeGreaterThan(20);
54 });
55
56 test("the form opens with the default, then follows a changed setting", async () => {
57 expect(await budgetValue()).toBe("5");
58 expect(setLimit(app.db, "spawn.starter_budget_usd", 12, adminId).ok).toBe(true);
59 expect(await budgetValue()).toBe("12");
60 expect(setLimit(app.db, "spawn.starter_budget_usd", 0, adminId).ok).toBe(true);
61 expect(starterBudgetField(app.db)).toBe("");
62 });
63
64 test("a negative or fractional amount is refused at the boundary", () => {
65 expect(setLimit(app.db, "spawn.starter_budget_usd", -1, adminId).ok).toBe(false);
66 expect(setLimit(app.db, "spawn.starter_budget_usd", 2.5, adminId).ok).toBe(false);
67 });
68
69 const planText = async (fields: Record<string, string>): Promise<string> => {
70 const res = await fetch(`${servers.url}/forges/new`, {
71 method: "POST",
72 headers: { cookie, origin: "https://forge.test" },
73 body: new URLSearchParams({ name: "client-one", do: "plan", followMode: "take-updates", template: "blank", ...fields }),
74 });
75 expect(res.status).toBe(200);
76 return (await res.text()).replace(/\s+/g, " ");
77 };
78
79 test("the starter figure sent with no key is said on the plan, not dropped in silence", async () => {
80 expect(setLimit(app.db, "spawn.starter_budget_usd", 7, adminId).ok).toBe(true);
81 const text = await planText({ budgetUsd: (await budgetValue()) ?? "" });
82 expect(text).toContain("The $7 budget is for a key: this forge gets none until you add one.");
83 expect(text).not.toContain("the key's whole life");
84 });
85
86 test("a budget other than the starter is refused with no key, never dropped", async () => {
87 expect(setLimit(app.db, "spawn.starter_budget_usd", 7, adminId).ok).toBe(true);
88 const res = await fetch(`${servers.url}/forges/new`, {
89 method: "POST",
90 headers: { cookie, origin: "https://forge.test" },
91 body: new URLSearchParams({ name: "client-one", do: "plan", budgetUsd: "9", followMode: "take-updates", template: "blank" }),
92 });
93 expect(res.status).toBeGreaterThanOrEqual(400);
94 expect(await res.text()).not.toContain("is for a key: this forge gets none");
95 });
96
97 test("with a key the plan states the amount sent and never calls it the starter", async () => {
98 expect(setLimit(app.db, "spawn.starter_budget_usd", 7, adminId).ok).toBe(true);
99 const text = await planText({ budgetUsd: "20", modelKey: "sk-ant-api03-child-key-AAAAAAAAAAAAAAAAAAAAAAAA" });
100 expect(text).toContain("up to $20 for the key's whole life.");
101 expect(text).not.toContain("starter budget");
102 });
test/tui-newforge.test.ts +24 −5
@@ -8,6 +8,7 @@ import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
1010 import { createApp, type App } from "../src/app.ts";
11 import { setLimit } from "../src/settings/limits.ts";
1112 import { getRepo } from "../src/core/repos.ts";
1213 import { createUser, type User } from "../src/core/users.ts";
1314 import { usePlacement, useProbe } from "../src/spawn/door.ts";
@@ -138,22 +139,40 @@ describe("the new forge screen", () => {
138139 expect(await children()).toBe(before);
139140 }));
140141
141 test("a key without a budget is refused by the door, naming the budget", () =>
142 withScreen(admin, async ({ tui, terminal }) => {
142 test("a key without a budget is refused by the door, naming the budget", () => {
143 return withScreen(admin, async ({ tui, terminal }) => {
143144 const before = await children();
144 terminal.feed("lee\t\t\t\t\tsk-ant-api03-child-key-AAAAAAAAAAAAAAAAAAAAAAAA\x10");
145 // The budget opens filled with the starter; backspace empties it, as a person who wants none
146 // would.
147 terminal.feed("lee\t\t\t\t\tsk-ant-api03-child-key-AAAAAAAAAAAAAAAAAAAAAAAA\t\t\x7f\x10");
145148 await settleApp(tui);
146149 const text = tui.screen.toText();
147150 expect(text).not.toContain("The plan");
148151 expect(text).toContain("budget");
149152 expect(text).not.toContain("sk-ant-api03");
150153 expect(await children()).toBe(before);
151 }));
154 });
155 });
156
157 test("the budget opens with the setting, and typing replaces it", () => {
158 setLimit(app.db, "spawn.starter_budget_usd", 12, admin.id);
159 return withScreen(admin, async ({ tui, terminal }) => {
160 terminal.feed("\t\t\t\t\t\t\t");
161 await settleApp(tui);
162 expect(tui.screen.toText()).toContain("12");
163 terminal.feed("20");
164 await settleApp(tui);
165 const text = tui.screen.toText();
166 expect(text).toContain("20");
167 expect(text).not.toContain("1220");
168 expect(text).not.toContain("120");
169 });
170 });
152171
153172 test("a budget without a key is refused, with the door's reason", () =>
154173 withScreen(admin, async ({ tui, terminal }) => {
155174 const before = await children();
156 terminal.feed("max\t\t\t\t\t\t\t5\x10");
175 terminal.feed("max\t\t\t\t\t\t\t6\x10");
157176 await settleApp(tui);
158177 const text = tui.screen.toText();
159178 expect(text).not.toContain("The plan");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs