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

The plans page says what each forge size is for, measured by the time to a first built change #16759

Merged opened this

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

Merged

scout/forge:scout/11562-the-plans-page-says-what-each-forge-size → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/11562-the-plans-page-says-what-each-forge-size was merged into main as a1bc223.

Review

Sign in to review this change.
11 files changed +128 −23
docs/features/plans.md +2
@@ -24,6 +24,8 @@ These are the defaults. A forge admin who is a person edits them:
2424
2525 `/pricing` says the same rule in one line, in text a probe can match: "If a payment lapses, you have 7 days of grace. After that your forge sleeps and keeps its data." The element carries `data-grace-days` with the number. The number is always the `billing.grace_days` setting (`src/billing/lapse_rule.ts`), never a second constant, so changing the setting changes the page and the API together.
2626
27 Each plan may also carry `firstChangeSecs`, the measured whole seconds from a first ask to a first built change on that plan's size. An admin sets it in the "Seconds to a first change" field of the Plans form, with `first <seconds>` in the terminal, or in `firstChangeSecs` through the API and MCP. Until it is set (0 clears it) nothing is said: the plans words and `GET /api/v1/plans` leave it out, and once set the words read "A first built change takes about 4 minutes."
28
2729 ## What a spawn gets
2830
2931 `POST /api/v1/forges` (and the MCP `spawn`) takes `plan`. The forge's size comes from the plan (a `size` that disagrees is refused), and its credit cap is the plan's `creditUsd`, lent as a monthly cap through `src/spawn/credit.ts`: the spend is counted again each UTC calendar month. Plans are read at spawn time, so an edit governs the next spawn; forges already made keep the credit they were given.
src/billing/plan_words.ts +12 −1
@@ -66,13 +66,24 @@ export const monthlyPrice = (usd: number): string => (usd === 0 ? "Free" : `$${u
6666 */
6767 export const surchargeParts = (planUsd: number, extraUsd: number): string => `$${planUsd} and $${extraUsd} for the place`;
6868
69 /**
70 * The measured time from a first ask to a built change on the stub journey, in words; empty when
71 * nobody has timed this size, so the page never states a number it does not have.
72 */
73 export function firstChangeWords(secs: number | undefined): string {
74 if (secs === undefined || secs <= 0) return "";
75 if (secs < 90) return `A first built change takes about ${secs} seconds.`;
76 const m = Math.round(secs / 60);
77 return `A first built change takes about ${m} ${m === 1 ? "minute" : "minutes"}.`;
78 }
79
6980 export function planWords(p: Plan, links: BillingLinks = {}, startUsd = 0, askUsd: number = ASK_USD): PlanWords {
7081 const free = p.priceUsd === 0;
7182 const buy = free ? undefined : links[p.size];
7283 return {
7384 name: p.name,
7485 price: monthlyPrice(p.priceUsd),
75 is: `${sizeWords(p.size)}. ${p.says} ${creditWords(p, startUsd, askUsd)}`,
86 is: [`${sizeWords(p.size)}. ${p.says}`, firstChangeWords(p.firstChangeSecs), creditWords(p, startUsd, askUsd)].filter((x) => x !== "").join(" "),
7687 buy,
7788 };
7889 }
src/contract/openapi/routes/getApiV1Plans.ts +1 −1
@@ -1,3 +1,3 @@
11 import type { Route } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: "/api/v1/plans", summary: "List the plans, with their price, credit and forge allowance", detail: "The plans (free, small, medium, large by default): key, name, says, size, priceUsd a month, creditUsd a month, forges one person may hold; beside them startCreditUsd (crew credit lent once to a new free forge that brings no model key, the spawn.included_credit_usd limit), graceDays (days a lapsed payment has, the billing.grace_days setting) and lapse sleep (the forge then sleeps and keeps its data); public, revalidated by ETag, no secrets", auth: false, role: "anonymous" };
3 export const route: Route = { method: "get", path: "/api/v1/plans", summary: "List the plans, with their price, credit and forge allowance", detail: "The plans (free, small, medium, large by default): key, name, says, size, priceUsd a month, creditUsd a month, forges one person may hold, and firstChangeSecs (measured seconds to a first built change) only once an admin has set it; beside them startCreditUsd (crew credit lent once to a new free forge that brings no model key, the spawn.included_credit_usd limit), graceDays (days a lapsed payment has, the billing.grace_days setting) and lapse sleep (the forge then sleeps and keeps its data); public, revalidated by ETag, no secrets", auth: false, role: "anonymous" };
src/contract/openapi/routes/putApiV1AdminPlans.ts +1 −1
@@ -7,7 +7,7 @@ export const route: Route = {
77 detail: "Replace the plans live (a person admin's token, admin scope); the next spawn and GET /api/v1/plans use them at once; answers { items }",
88 auth: true,
99 role: "admin",
10 body: { plans: "list of { key, name, says, size, priceUsd, creditUsd, forges }; one to eight, `free` among them at $0" },
10 body: { plans: "list of { key, name, says, size, priceUsd, creditUsd, forges, firstChangeSecs? }; one to eight, `free` among them at $0" },
1111 refusals: {
1212 not_found: "the token is not a person who administers the forge (404)",
1313 invalid_plans: "a plan is not valid, named in the message (422)",
src/http/mcp/tools/limits.ts +1 −1
@@ -8,7 +8,7 @@ import { good, bad, type Tool } from "../shared.ts";
88 export const tool: Tool = {
99 name: "limits",
1010 listedTo: "admin",
11 doc: "`{ key?, value?, plans?, dryRun? }` (forge admin): every limit the forge's owner can hit, with its value, default and bounds; with `key` and `value` (`\"\"` restores the default), planned first; a value out of bounds is refused, applying needs an admin-scope token; the answer lists the plans; `plans`, a list of `{ key, name, says, size, priceUsd, creditUsd, forges }`, replaces them",
11 doc: "`{ key?, value?, plans?, dryRun? }` (forge admin): every limit the forge's owner can hit, with its value, default and bounds; with `key` and `value` (`\"\"` restores the default), planned first; a value out of bounds is refused, applying needs an admin-scope token; the answer lists the plans; `plans`, a list of `{ key, name, says, size, priceUsd, creditUsd, forges, firstChangeSecs? }` (firstChangeSecs: measured whole seconds to a first built change, 0 or absent when not measured), replaces them",
1212 description:
1313 "Every limit the owner can hit. `key`+`value` (\"\" restores) plans.",
1414 inputSchema: {
src/settings/plans.ts +18 −6
@@ -25,6 +25,11 @@ export interface Plan {
2525 readonly creditUsd: number;
2626 /** How many forges one person may hold on this plan. */
2727 readonly forges: number;
28 /**
29 * Seconds from a first ask to a built change on the stub journey, as timed in production on this
30 * plan's size; absent until someone has measured it, and never a guess.
31 */
32 readonly firstChangeSecs?: number;
2833 }
2934
3035 /** The plan every forge has: its price is always 0 and its limits are the visitor and per-person limits. */
@@ -36,6 +41,7 @@ export const PLANS_KEY = "plans";
3641 export const MAX_PLANS = 8;
3742 export const MAX_USD = 100_000;
3843 export const MAX_FORGES = 1000;
44 export const MAX_FIRST_CHANGE_SECS = 86_400;
3945
4046 export const DEFAULT_PLANS: readonly Plan[] = [
4147 { key: "free", name: "Free", says: "Sleeps when idle and wakes on the next visit.", size: "small", priceUsd: 0, creditUsd: 0, forges: 3 },
@@ -75,9 +81,10 @@ function usd(v: unknown): number | undefined {
7581 return Math.abs(n * 100 - Math.round(n * 100)) > 1e-6 ? undefined : cents(n);
7682 }
7783
78 function count(v: unknown): number | undefined {
79 const n = typeof v === "string" && /^\d{1,4}$/.test(v.trim()) ? Number(v) : v;
80 return typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= MAX_FORGES ? n : undefined;
84 /** A whole number from `min` to `max`, from a number or its digits, or undefined. */
85 function whole(v: unknown, min: number, max: number): number | undefined {
86 const n = typeof v === "string" && /^\d{1,6}$/.test(v.trim()) ? Number(v) : v;
87 return typeof n === "number" && Number.isInteger(n) && n >= min && n <= max ? n : undefined;
8188 }
8289
8390 function line(v: unknown, max: number): string | undefined {
@@ -102,10 +109,13 @@ export function parsePlan(raw: unknown): Result<Plan, string> {
102109 if (priceUsd === undefined) return err(`${key}: priceUsd is dollars from 0 to ${MAX_USD}, at most two decimals`);
103110 const creditUsd = usd(p["creditUsd"]);
104111 if (creditUsd === undefined) return err(`${key}: creditUsd is dollars from 0 to ${MAX_USD}, at most two decimals`);
105 const forges = count(p["forges"]);
112 const forges = whole(p["forges"], 1, MAX_FORGES);
106113 if (forges === undefined) return err(`${key}: forges is a whole number from 1 to ${MAX_FORGES}`);
107114 if (key === FREE && priceUsd !== 0) return err("the free plan costs $0");
108 return ok({ key, name, says, size, priceUsd, creditUsd, forges });
115 const blank = p["firstChangeSecs"] === undefined || p["firstChangeSecs"] === null || p["firstChangeSecs"] === "";
116 const secs = blank ? 0 : whole(p["firstChangeSecs"], 0, MAX_FIRST_CHANGE_SECS);
117 if (secs === undefined) return err(`${key}: firstChangeSecs is whole seconds from 0 (not measured) to ${MAX_FIRST_CHANGE_SECS}`);
118 return ok({ key, name, says, size, priceUsd, creditUsd, forges, ...(secs > 0 ? { firstChangeSecs: secs } : {}) });
109119 }
110120
111121 /** A whole list of plans from untrusted input: one to eight, unique keys, `free` among them. */
@@ -158,5 +168,7 @@ export function setPlans(db: Database, plans: readonly Plan[], actorId: string):
158168
159169 /** The plans as the public sees them: only the named fields leave. */
160170 export function publicPlans(plans: readonly Plan[]): Plan[] {
161 return plans.map(({ key, name, says, size, priceUsd, creditUsd, forges }) => ({ key, name, says, size, priceUsd, creditUsd, forges }));
171 return plans.map(({ key, name, says, size, priceUsd, creditUsd, forges, firstChangeSecs }) => ({
172 key, name, says, size, priceUsd, creditUsd, forges, ...(firstChangeSecs === undefined ? {} : { firstChangeSecs }),
173 }));
162174 }
src/tui/screens/plans.ts +16 −8
@@ -1,10 +1,10 @@
11 /**
22 * The forge's plans in the terminal, a forge admin's: every plan with its
33 * size, price, monthly crew credit and forge count, as /admin/limits and MCP
4 * `limits` show them. `e` asks for `<field> <value>` (price, credit, forges,
5 * size, name or words), shows the change and applies it only after a confirm,
6 * through `editPlans`, so the words of a refusal are the page's and the MCP's.
7 * The gate is the action's: an admin who is a person; anyone else sees nothing.
4 * `limits` show them. `e` asks for `<field> <value>` (price, credit, forges, first (seconds to a
5 * first change), size, name or words), shows the change and
outdated

The phrase first (seconds to a first change) appears twice in this comment. Delete the duplicate. Also, the confirm body prints the raw field name firstChangeSecs (see the body: line below); use the plain words first change.

6 * applies it only after a confirm, through `editPlans`, so the words of a refusal are the page's
7 * and the MCP's. The gate is the action's: an admin who is a person; anyone else sees nothing.
88 */
99
1010 import { editPlans, readPlans } from "../../actions/plans.ts";
@@ -25,8 +25,16 @@ const FIELDS: Readonly<Record<string, keyof Plan>> = {
2525 price: "priceUsd",
2626 credit: "creditUsd",
2727 forges: "forges",
28 first: "firstChangeSecs",
2829 };
29 const NUMERIC = new Set<keyof Plan>(["priceUsd", "creditUsd", "forges"]);
30 const NUMERIC = new Set<keyof Plan>(["priceUsd", "creditUsd", "forges", "firstChangeSecs"]);
31 const first = (p: Plan): string => (p.firstChangeSecs === undefined ? "first change not measured" : `first change ${p.firstChangeSecs}s`);
32 /** `first change not measured → 240s`, or `creditUsd 5 → 6`: the change in plain words. */
33 function change(plan: Plan, field: keyof Plan, value: string | number): string {
34 if (field !== "firstChangeSecs") return `${field} ${String(plan[field])} → ${value}`;
35 const secs = (n: unknown): string => (typeof n === "number" && n > 0 ? `${n}s` : "not measured");
36 return `first change ${secs(plan.firstChangeSecs)} → ${secs(value)}`;
37 }
3038 const ASK = `${Object.keys(FIELDS).join(", ")} then a value, e.g. credit 6`;
3139
3240 /** `credit 6` as the plan field and the value the form would send, or the sentence that says what is wrong. */
@@ -59,7 +67,7 @@ export function plansScreen(f: Session, ctx: Ctx): Screen {
5967 promptScreen(ctx, screen, {
6068 title: plan.key,
6169 label: ASK,
62 hint: `now ${plan.size} · $${plan.priceUsd}/mo · $${plan.creditUsd} crew credit · ${plan.forges} forges`,
70 hint: `now ${plan.size} · $${plan.priceUsd}/mo · $${plan.creditUsd} crew credit · ${plan.forges} forges · ${first(plan)}`,
6371 onSubmit: (raw) => {
6472 const edit = parseEdit(raw);
6573 if (typeof edit === "string") return edit;
@@ -67,7 +75,7 @@ export function plansScreen(f: Session, ctx: Ctx): Screen {
6775 ctx.push(
6876 confirmScreen(ctx, screen, {
6977 title: "Change this plan",
70 body: [`${plan.key}: ${edit.field} ${String(plan[edit.field])} → ${edit.value}`],
78 body: [`${plan.key}: ${change(plan, edit.field, edit.value)}`],
7179 actions: [{ label: "Keep", variant: "ghost" }, { label: "Change" }],
7280 onChoose: (i) => {
7381 if (i === 1) apply(plan, edit.field, edit.value);
@@ -83,7 +91,7 @@ export function plansScreen(f: Session, ctx: Ctx): Screen {
8391 const rows = (plans: readonly Plan[]): ListRow[] =>
8492 plans.map((p) => ({
8593 title: `${p.key} · ${p.name}`,
86 secondary: `${p.size} · $${p.priceUsd}/mo · $${p.creditUsd} crew credit · ${p.forges} forges`,
94 secondary: `${p.size} · $${p.priceUsd}/mo · $${p.creditUsd} crew credit · ${p.forges} forges · ${first(p)}`,
8795 meta: p.says,
8896 }));
8997
src/web/settings/plans.ts +4 −2
@@ -14,7 +14,7 @@ import { html, type Html } from "../html.ts";
1414 import { flashTo } from "../layout.ts";
1515 import { btn, row } from "../ui.ts";
1616
17 const FIELDS = ["name", "says", "size", "priceUsd", "creditUsd", "forges"] as const;
17 const FIELDS = ["name", "says", "size", "priceUsd", "creditUsd", "forges", "firstChangeSecs"] as const;
1818
1919 export function plansRow(ctx: Ctx): Html {
2020 const rows = readPlans(ctx.app).map((p) =>
@@ -30,6 +30,7 @@ export function plansRow(ctx: Ctx): Html {
3030 { label: "Price $/mo", value: html`<input class="input mono" name="${p.key}.priceUsd" inputmode="decimal" value="${String(p.priceUsd)}" ${p.key === "free" ? "readonly" : ""} aria-label="${p.key} price a month in dollars" />` },
3131 { label: "Crew credit $/mo", value: html`<input class="input mono" name="${p.key}.creditUsd" inputmode="decimal" value="${String(p.creditUsd)}" aria-label="${p.key} crew credit a month in dollars" />` },
3232 { label: "Forges", value: html`<input class="input mono" name="${p.key}.forges" type="number" min="1" max="1000" step="1" value="${String(p.forges)}" aria-label="${p.key} forges one person may hold" />` },
33 { label: "Seconds to a first change", value: html`<input class="input mono" name="${p.key}.firstChangeSecs" inputmode="numeric" value="${String(p.firstChangeSecs ?? 0)}" aria-describedby="${p.key}-first-hint" aria-label="${p.key} measured seconds to a first built change" /> <span id="${p.key}-first-hint" class="muted small">0 or blank: not measured, and the plans page says nothing.</span>` },
outdated

Principle 8: 0 means not measured is only in aria-label, so a sighted admin has no way to know that 0 clears it. Put it in the visible label or hint. Also, this new form field has no test through the web form: add one that posts <key>.firstChangeSecs=240 and a blank, and reads the stored plan.

3334 ],
3435 }),
3536 );
@@ -55,7 +56,8 @@ export async function plansSet(ctx: Ctx): Promise<Response> {
5556 const mine: Record<string, unknown> = {};
5657 for (const f of FIELDS) {
5758 const v = field(form, `${p.key}.${f}`);
58 if (v !== "") mine[f] = v;
59 // A blank time clears it (not measured); any other blank keeps what is stored.
60 if (v !== "" || (f === "firstChangeSecs" && form.has(`${p.key}.${f}`))) mine[f] = v;
5961 }
6062 edits[p.key] = mine;
6163 }
test/plans-row.test.ts +22 −2
@@ -12,8 +12,8 @@ import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { createApp, type App } from "../src/app.ts";
1414 import { serve, type Servers } from "../src/http/server.ts";
15 import { AFTER_PAYMENT, planWords } from "../src/billing/plan_words.ts";
16 import { DEFAULT_PLANS } from "../src/settings/plans.ts";
15 import { AFTER_PAYMENT, firstChangeWords, planWords } from "../src/billing/plan_words.ts";
16 import { DEFAULT_PLANS, parsePlan, publicPlans } from "../src/settings/plans.ts";
1717 import { getDoorSettings } from "../src/settings/door.ts";
1818 import { sizeWords } from "../src/settings/billing.ts";
1919 import { SIGNUP_DEFAULT } from "../src/settings/signup.ts";
@@ -197,3 +197,23 @@ test("the anonymous home never says the forge is not taking accounts; /signin sa
197197 expect(signup).not.toContain("id=\"by-invitation\"");
198198 }
199199 });
200
201 const small = DEFAULT_PLANS[1]!;
202 test("says nothing until a time is measured", () => {
203 expect(firstChangeWords(undefined)).toBe("");
204 expect(planWords(small).is).not.toContain("first built change");
205 });
206 test("names the measured time once set, and it survives parsing and the public view", () => {
207 const p = parsePlan({ ...small, firstChangeSecs: "240" });
208 expect(p.ok && p.value.firstChangeSecs).toBe(240);
209 if (!p.ok) throw new Error(p.error);
210 expect(publicPlans([p.value])[0]!.firstChangeSecs).toBe(240);
211 expect(planWords(p.value).is).toContain("A first built change takes about 4 minutes.");
212 expect(firstChangeWords(45)).toBe("A first built change takes about 45 seconds.");
213 });
214 test("rejects a bad time and drops 0", () => {
215 expect(parsePlan({ ...small, firstChangeSecs: -1 }).ok).toBe(false);
216 expect(parsePlan({ ...small, firstChangeSecs: 1.5 }).ok).toBe(false);
217 const z = parsePlan({ ...small, firstChangeSecs: 0 });
218 expect(z.ok && "firstChangeSecs" in z.value).toBe(false);
219 });
test/plans.test.ts +32 −1
@@ -15,7 +15,7 @@ import { serve, type Servers } from "../src/http/server.ts";
1515 import { hostedPlacement, memoryBodies } from "../src/spawn/placement.ts";
1616 import { usePlacement, useProbe } from "../src/spawn/door.ts";
1717 import { addSpend, periodOf, readCredit } from "../src/spawn/credit.ts";
18 import { DEFAULT_PLANS, getPlans, parsePlans } from "../src/settings/plans.ts";
18 import { DEFAULT_PLANS, getPlan, getPlans, parsePlans } from "../src/settings/plans.ts";
1919 import { planRefusal } from "../src/spawn/sleep.ts";
2020 import { grantPlanCredit } from "../src/actions/spawn.ts";
2121 import { setLimit } from "../src/settings/limits.ts";
@@ -187,6 +187,37 @@ describe("plans", () => {
187187 expect([small.priceUsd, small.creditUsd]).toEqual([21, 6]);
188188 });
189189
190 test("the form sets the seconds to a first change, and a blank clears it", async () => {
191 const signin = await fetch(url("/signin"), { method: "POST", body: new URLSearchParams({ username: "alice", password: PASSWORD }), redirect: "manual" });
192 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
193 const page = await (await fetch(url("/admin/limits"), { headers: { cookie } })).text();
194 expect(page).toContain('name="small.firstChangeSecs"');
195 expect(page).toContain("0 or blank: not measured");
196 const post = (v: string) => fetch(url("/admin/plans"), { method: "POST", headers: { cookie, origin: "https://forge.test" }, body: new URLSearchParams({ "small.firstChangeSecs": v }), redirect: "manual" });
197 expect((await post("240")).status).toBe(303);
198 expect(getPlan(app.db, "small")!.firstChangeSecs).toBe(240);
199 expect((await plans()).find((p) => p.key === "small").firstChangeSecs).toBe(240);
200 await post("");
201 expect(getPlan(app.db, "small")!.firstChangeSecs).toBeUndefined();
202 expect("firstChangeSecs" in (await plans()).find((p) => p.key === "small")).toBe(false);
203 });
204
205 test("PUT /api/v1/admin/plans and the MCP limits tool set the seconds to a first change", async () => {
206 const withTime = (secs: number) => getPlans(app.db).map((p) => (p.key === "medium" ? { ...p, firstChangeSecs: secs } : p));
207 expect((await put(admin, withTime(300))).status).toBe(200);
208 expect(getPlan(app.db, "medium")!.firstChangeSecs).toBe(300);
209 expect((await put(admin, withTime(-5))).status).toBe(422);
210 const res = await fetch(url("/mcp"), {
211 method: "POST",
212 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${admin}` },
213 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "limits", arguments: { plans: withTime(120), dryRun: false } } }),
214 });
215 const body = (await res.json()) as any;
216 expect(body.error ?? body.result.isError).toBeFalsy();
217 expect(getPlan(app.db, "medium")!.firstChangeSecs).toBe(120);
218 expect((await plans()).find((p) => p.key === "medium").firstChangeSecs).toBe(120);
219 });
220
190221 test("a person who is not an admin cannot POST /admin/plans", async () => {
191222 const signin = await fetch(url("/signin"), { method: "POST", body: new URLSearchParams({ username: "bob", password: PASSWORD }), redirect: "manual" });
192223 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
test/tui-plans.test.ts +19
@@ -111,6 +111,25 @@ describe("plans in the terminal", () => {
111111 h.stop();
112112 });
113113
114 test("first sets the measured seconds to a first change, and 0 clears it", async () => {
115 const h = boot("alice");
116 await open(h);
117 await h.press("j", "e");
118 await h.type("first 240");
119 await h.press("enter");
120 expect(h.text()).toContain("first change not measured → 240s");
121 await h.press("right", "enter");
122 expect(getPlan(forge.db, "small")!.firstChangeSecs).toBe(240);
123 expect(h.text()).toContain("first change 240s");
124 await h.press("e");
125 await h.type("first 0");
126 await h.press("enter");
127 expect(h.text()).toContain("first change 240s → not measured");
128 await h.press("right", "enter");
129 expect(getPlan(forge.db, "small")!.firstChangeSecs).toBeUndefined();
130 h.stop();
131 });
132
114133 test("a plain person and an agent admin have no command", async () => {
115134 for (const who of ["bob", "carol"]) {
116135 const h = boot(who);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs