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

Upgrade a shared forge to a dedicated one, keeping its data #17167

opened this

Check · Review · Land · Live — Its check is queued. Next: reviewer, no review yet.

Ready to land

scout/forge:scout/17024-upgrade-a-shared-forge-to-a-dedicated-on → main 3 commits fork

Review

Sign in to review this change.
10 files changed +444 −8
docs/features/shared-tier.md +3 −2
@@ -10,6 +10,7 @@ row: A shared, sleeping forge beside the dedicated one
1010 - **The count and the price.** Awake slots = (2 GiB − 1200 MiB kept for one build) ÷ awake memory; forges = slots ÷ (active fraction × 10 for the busiest moment), or 2 GiB ÷ 50 MiB of disk each, whichever is fewer. Price = Small's $19 × 2 ÷ forges, rounded up to whole dollars, at least $1. The disk share, the 10×, the 1200 MiB and the 2× are choices (`PROMISE`), not measurements, and are named as such in the code.
1111 - **Checkout.** Buying it is the ordinary order: the price is on the page before anything is paid. `whereFor` (`src/spawn/making.ts`) places a shared forge hosted whatever the paid placement is; only the dedicated plans go to a cloud machine.
1212 - **Terminal.** The Get a forge screen (`src/tui/screens/pricing.ts`) lists it with the same sentence.
13 - **Not done.** Upgrading a shared forge to a dedicated one is #17024: its data is one directory (`children/<bodyId>`), so the move is a copy of the same files, but nothing performs it. A plans list an admin has stored does not gain the plan; they add it at `/admin/limits`.
13 - **Upgrading (#17024).** A shared forge's data is one directory (`children/<bodyId>`), so the upgrade is the move to a dedicated machine (`spawn/move_machine.ts`: copy through the backup destination, start, switch the router) plus the billing change, in `src/actions/upgrade_shared.ts`. The preview says the plan, the machine, and the price before and after (`shared → small: $19.00 / month`); the plan changes only after the forge answers on the machine, so a failed move leaves it shared and billed as shared. A change is kept in `entitlement_change` and as a `billing.plan` event, and the forge is told its plan. Doors: the **Upgrade to a dedicated forge** button on `/forges` (`/forges/<name>/upgrade`, `?plan=&to=` previews), key `e` on the terminal's Forges screen, and MCP `forges` with `action: "upgrade"`, `forge`, `plan`, `to` (`dryRun: false` does it). Admins only, a person, never an agent. A forge whose subscription is at a payment provider is refused with the words to change it there: this forge cannot change what the provider bills. Needs a declared machine (`FORGE_MACHINES`) and a forge in a cell of its own.
14 - **Not done.** Changing the amount at the payment provider; an owner upgrading their own forge (admins do it). A plans list an admin has stored does not gain the plan; they add it at `/admin/limits`.
1415
15 Code: `src/billing/density.ts`, `src/settings/plans.ts`, `src/billing/plan_words.ts`. Tests: `test/shared-density.test.ts`, `test/shared-pricing.test.ts`, `test/tui-pricing.test.ts`.
16 Code: `src/actions/upgrade_shared.ts`, `src/web/pages/forge_upgrade.ts`, `src/billing/density.ts`, `src/settings/plans.ts`, `src/billing/plan_words.ts`. Tests: `test/upgrade-shared.test.ts`, `test/shared-density.test.ts`, `test/shared-pricing.test.ts`, `test/tui-pricing.test.ts`.
src/actions/upgrade_shared.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * Upgrade a shared forge to a dedicated one, keeping its data (#17024). A shared forge's data is
3 * one directory (`children/<bodyId>`), so the upgrade is the move of `spawn/move_machine.ts` (copy
4 * through the backup destination, start on the dedicated machine, switch the router) plus the
5 * billing change: the forge's entitlement goes from the shared plan to a dedicated one, kept in
6 * `entitlement_change` and on the outbox as `billing.plan`, and the forge is told its new plan.
7 *
8 * Order: the move first, since it is the step that can fail and leaves the forge where it was;
9 * the entitlement only once the forge answers on the dedicated machine, so nobody is charged the
10 * dedicated price for a forge that did not move. A forge whose subscription is at a payment
11 * provider is refused: this forge cannot change what the provider bills, so the amount is not
12 * changed here behind its back. Admins only, never an agent (a crew that could grant itself a
13 * plan would decide its own limits).
14 */
15
16 import type { App } from "../app.ts";
17 import { DEDICATED_USD, densityOf, SHARED } from "../billing/density.ts";
18 import { tellPlan } from "../billing/notice.ts";
19 import { centsOfUsd, perMonthWords } from "../billing/money.ts";
20 import { centsFor, changeLine, previewChange, type PlanChange } from "../billing/plan_change.ts";
21 import { entitlementOf, getStored, putEntitlement } from "../billing/store.ts";
22 import type { User } from "../core/users.ts";
23 import { FREE, getPlans, type Plan } from "../settings/plans.ts";
24 import { moveToMachine, planMove, type MoveReceipt } from "../spawn/move_machine.ts";
25 import { listChildren } from "./spawn.ts";
26
27 export type UpgradeKind = "not_found" | "invalid" | "failed";
28
29 export interface UpgradePlan {
30 readonly forge: string;
31 readonly machine: string;
32 readonly change: PlanChange;
33 /** What the forge pays a month now, in cents. */
34 readonly fromCents: number;
35 readonly steps: readonly string[];
36 readonly says: string;
37 }
38
39 export type Planned = { readonly ok: true; readonly plan: UpgradePlan } | { readonly ok: false; readonly kind: UpgradeKind; readonly says: string };
40 export type Upgraded =
41 | { readonly ok: true; readonly says: string; readonly change: PlanChange; readonly receipt: MoveReceipt }
42 | { readonly ok: false; readonly kind: UpgradeKind; readonly says: string };
43
44 export interface UpgradeOptions {
45 readonly now?: Date;
46 readonly move?: Parameters<typeof planMove>[3];
47 }
48
49 const bad = (kind: UpgradeKind, says: string) => ({ ok: false as const, kind, says });
50
51 /** The plans a shared forge may be upgraded to: priced, not free, not shared. */
52 export const dedicatedPlans = (app: App): Plan[] => getPlans(app.db).filter((p) => p.key !== FREE && p.key !== SHARED && p.priceUsd > 0);
53
54 const isPerson = (a: User | undefined): a is User => a?.isAdmin === true && a.kind !== "agent";
55
56 async function check(app: App, actor: User | undefined, forge: string, planKey: string, now: Date) {
57 if (!isPerson(actor)) return bad("not_found", "no such page");
58 const child = (await listChildren(app)).find((c) => c.name === forge);
59 if (child === undefined) return bad("not_found", `no forge named ${forge}`);
60 const held = entitlementOf(app.db, forge, child.size);
61 if (held.plan !== SHARED) return bad("invalid", `${forge} is on the ${held.plan} plan, not the shared one`);
62 const stored = getStored(app.db, forge);
63 if (stored !== undefined && stored.provider !== "none")
64 return bad("invalid", `${forge} pays through ${stored.provider}: change its subscription there; this forge cannot change what the provider bills`);
65 const plans = getPlans(app.db);
66 const to = dedicatedPlans(app).find((p) => p.key === planKey);
67 if (to === undefined) return bad("invalid", `plan is one of: ${dedicatedPlans(app).map((p) => p.key).join(", ") || "none offered"}`);
68 const change = previewChange(plans, forge, SHARED, to.key, now);
69 // A stored plans list may not carry the shared plan: its price is then the density's.
70 const fromCents = centsFor(plans, SHARED) || centsOfUsd(densityOf(DEDICATED_USD).priceUsd);
71 return { ok: true as const, child, to, change, fromCents };
72 }
73
74 /** What the upgrade would do and cost; nothing changes. */
75 export async function planUpgrade(app: App, actor: User | undefined, forge: string, planKey: string, machine: string, options: UpgradeOptions = {}): Promise<Planned> {
76 const c = await check(app, actor, forge, planKey, options.now ?? new Date());
77 if (!c.ok) return c;
78 const moved = await planMove(app, forge, machine, { ...options.move, ...(actor === undefined ? {} : { actorId: actor.id }) });
79 if (!moved.ok) return bad(moved.kind, moved.says);
80 const steps = [...moved.plan.steps, `Then its plan changes: ${changeLine(c.change)}.`];
81 const says = `${forge} keeps its data: it is copied to ${machine} and its plan goes from shared to ${c.to.name}, ${changeLine(c.change)} (it paid ${perMonthWords(c.fromCents)} before). ${moved.plan.says}`;
82 return { ok: true, plan: { forge, machine, change: c.change, fromCents: c.fromCents, steps, says } };
83 }
84
85 /** The upgrade: move the data, then change the plan. The plan changes only if the move did. */
86 export async function upgradeShared(app: App, actor: User | undefined, forge: string, planKey: string, machine: string, options: UpgradeOptions = {}): Promise<Upgraded> {
87 const c = await check(app, actor, forge, planKey, options.now ?? new Date());
88 if (!c.ok) return c;
89 const who = actor as User;
90 const moved = await moveToMachine(app, forge, machine, { ...options.move, actorId: who.id });
91 if (!moved.ok) return bad(moved.kind, `${moved.says}. It is still on the shared plan.`);
92 putEntitlement(app.db, { forge, plan: c.to.key, status: "active", source: "upgrade", provider: "none" }, c.child.size, who.id);
93 tellPlan(app, forge);
94 app.bus.append({ kind: "billing.plan", actorId: who.id, payload: { forge, from: SHARED, to: c.to.key, source: "upgrade" } });
95 return { ok: true, change: c.change, receipt: moved.receipt, says: `${forge} is on ${c.to.name} now, on ${machine}, with its data: ${changeLine(c.change)}. ${moved.says}` };
96 }
97
98 /**
99 * The forges, of the names given, that are on the shared plan now: the ones a page offers the
100 * upgrade on.
101 */
102 export function sharedForges(app: App, rows: readonly { readonly name: string; readonly size: string }[]): Set<string> {
103 return new Set(rows.filter((r) => entitlementOf(app.db, r.name, r.size).plan === SHARED).map((r) => r.name));
104 }
src/http/forges_routes.ts +3
@@ -12,6 +12,7 @@ import { forgeLinkForm, forgeRevokeConfirm, forgeLinkRevoke, forgeLinkSubmit, fo
1212 import { billDownload } from "./api/forge_bill.ts";
1313 import { forgeRecoveryForm, forgeRecoverySubmit } from "../web/pages/forges.ts";
1414 import { forgeMachineForm, forgeMachineSubmit } from "../web/pages/forge_machine.ts";
15 import { forgeUpgradeForm, forgeUpgradeSubmit } from "../web/pages/forge_upgrade.ts";
1516 import { forgesRefusedPage } from "../web/pages/forges-refused.ts";
1617 import { forgeReachAllow, forgeReachLater, forgeReachRevoke } from "../web/pages/hosted-forges.ts";
1718 import { pricingDone, pricingOrder, pricingPage, receiptHtml, receiptPage, resendPage, resendSubmit } from "../web/pages/pricing.ts";
@@ -42,6 +43,8 @@ export function forgesRoutes(router: Router<Handler>): void {
4243 router.add("POST", "/forges/:name/sandbox", forgeSandboxSubmit);
4344 router.add("GET", "/forges/:name/machine", forgeMachineForm);
4445 router.add("POST", "/forges/:name/machine", forgeMachineSubmit);
46 router.add("GET", "/forges/:name/upgrade", forgeUpgradeForm);
47 router.add("POST", "/forges/:name/upgrade", forgeUpgradeSubmit);
4548 // An admin's answers to what a hosted forge asked to reach (`web/pages/hosted-forges.ts`).
4649 router.add("POST", "/forges/:name/reach/allow", forgeReachAllow);
4750 router.add("POST", "/forges/:name/reach/later", forgeReachLater);
src/http/lazy_lists.ts +2
@@ -236,6 +236,8 @@ export const FORGES_ROUTES = [
236236 ["POST", "/forges/:name/sandbox"],
237237 ["GET", "/forges/:name/machine"],
238238 ["POST", "/forges/:name/machine"],
239 ["GET", "/forges/:name/upgrade"],
240 ["POST", "/forges/:name/upgrade"],
239241 ["POST", "/forges/:name/reach/allow"],
240242 ["POST", "/forges/:name/reach/later"],
241243 ["POST", "/forges/:name/reach/revoke"],
src/http/marks/forges.json +1
@@ -14,6 +14,7 @@
1414 "/forges/:name/stop": "admin",
1515 "/forges/:name/sandbox": "admin",
1616 "/forges/:name/machine": "admin",
17 "/forges/:name/upgrade": "admin",
1718 "/forges/:name/size": "admin",
1819 "/forges/:name/reach/allow": "admin",
1920 "/forges/:name/reach/later": "admin",
src/http/mcp/tools/forges.ts +14 −3
@@ -8,6 +8,7 @@ import { clientRows, listedKept } from "../../../spawn/clients.ts";
88 import { archiveForge, archivedForges, restoreForge } from "../../../spawn/archive.ts";
99 import { CHILD_NAME } from "../../../spawn/placement.ts";
1010 import { checkMove } from "../../../spawn/move_check.ts";
11 import { planUpgrade, upgradeShared } from "../../../actions/upgrade_shared.ts";
1112 import { moveToMachine, planMove, planRecover, recoverForge } from "../../../spawn/move_machine.ts";
1213 import { emptiest, machineLines, silentMachines } from "../../../spawn/machine_load.ts";
1314 import { moveToCell } from "../../../spawn/move_cell.ts";
@@ -20,10 +21,10 @@ const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet."
2021 export const tool: Tool = {
2122 name: "forges",
2223 listedTo: "admin",
23 doc: "the forges sent from here, one line each: \"name | state | version | billing\" (unopened links first), with `url` once as a pattern; `name`: that forge's whole row (address, whom for, apps, claimed, stage with stageAt and resend, last activity, claimed by and when, kept, archive reason, reachable, size, use, madeFrom, placement, where); `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link; `kind` machines: each machine's heartbeat (awake forges, memory, CPU), the silent ones named, and the emptiest, where a new forge goes; move + `forge` + `to` a machine (or `here`, the way back): copy, start, switch the router, receipt (unreachable under 60 s); recover + `forge` + `to`: the same from the bucket's last copy, previewed with the copy's time and what is lost",
24 doc: "the forges sent from here, one line each: \"name | state | version | billing\" (unopened links first), with `url` once as a pattern; `name`: that forge's whole row (address, whom for, apps, claimed, stage, last activity, claimed by, kept, archive reason, reachable, size, use, madeFrom, placement, where); `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link; `kind` machines: each machine's heartbeat (awake forges, memory, CPU), the silent ones named, and the emptiest, where a new forge goes; move + `forge` + `to` a machine (or `here`, the way back): copy, start, switch the router, receipt (unreachable under 60 s); upgrade + `forge` + `plan` + `to` a machine: a shared forge moves there with its data, then the plan changes; recover + `forge` + `to`: the same from the bucket's last copy, previewed with the copy's time and what is lost",
2425 description:
25 "Forges sent from here (admin).",
26 inputSchema: { type: "object", properties: { name: { type: "string" }, kind: { enum: ["refused", "clients", "machines"] }, action: { enum: ["resend", "move", "recover"] }, to: {}, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } },
26 "Forges sent from here.",
27 inputSchema: { type: "object", properties: { name: { type: "string" }, kind: { enum: ["refused", "clients", "machines"] }, action: { enum: ["resend", "move", "recover", "upgrade"] }, to: {}, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } },
2728 writes: true,
2829 tier: "delete",
2930 deletes: (args) => args["archive"] !== undefined,
@@ -33,6 +34,16 @@ export const tool: Tool = {
3334 async run(ctx, user, args) {
3435 if (!user.isAdmin)
3536 return bad("forbidden", "only an admin of this forge sees the forges it sent");
37 if (args["action"] === "upgrade") {
38 const [forge, plan, to] = [String(args["forge"] ?? ""), String(args["plan"] ?? ""), String(args["to"] ?? "")];
39 if (args["dryRun"] === false) {
40 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "upgrading a forge needs an admin token");
41 const done = await upgradeShared(ctx.app, user, forge, plan, to);
42 return done.ok ? good(done) : bad(done.kind, done.says);
43 }
44 const planned = await planUpgrade(ctx.app, user, forge, plan, to);
45 return planned.ok ? good({ ...planned.plan, says: `${planned.plan.says} Send dryRun: false to do it.` }) : bad(planned.kind, planned.says);
46 }
3647 if (args["action"] === "move" || args["action"] === "recover") {
3748 const [forge, to] = [String(args["forge"] ?? ""), String(args["to"] ?? "")];
3849 if (args["action"] === "recover" && args["dryRun"] === false) {
src/tui/screens/forges.ts +59 −1
@@ -23,6 +23,8 @@ import { archiveForge, archivedForges, destinationWords, restoreForge } from "..
2323 import { writeClientsCsv } from "../../spawn/clients_csv.ts";
2424 import { claimedWords, keepWords } from "../../spawn/keep_words.ts";
2525 import { changeLink, revokePreview, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts";
26 import { dedicatedPlans, planUpgrade, sharedForges, upgradeShared } from "../../actions/upgrade_shared.ts";
27 import { usdPerMonthWords } from "../../billing/money.ts";
2628 import { machinesOf } from "../../spawn/machines.ts";
2729 import { emptiest, machineLines, sampleBeats } from "../../spawn/machine_load.ts";
2830 import { moveToCell } from "../../spawn/move_cell.ts";
@@ -285,6 +287,61 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
285287 }),
286288 );
287289 };
290 // The page's "Upgrade to a dedicated forge", through the same actions (`planUpgrade`,
291 // `upgradeShared`): the plan, machine, price before and after, then the receipt.
292 const upgradeOne = (): void => {
293 const user = session?.user;
294 if (session === undefined || user?.isAdmin !== true) return;
295 const app = session.app;
296 const declared = machinesOf(app);
297 const shared = sharedForges(app, rows);
298 const items = rows.filter((r) => r.made && r.placement === "cell" && shared.has(r.name)).map((r) => ({ id: r.name, label: r.name, hint: "shared" }));
299 if (declared.length === 0) return ctx.toast("No other machine is declared (FORGE_MACHINES)");
300 if (items.length === 0) return ctx.toast("No forge on the shared plan runs in a sandbox of its own");
301 ctx.push(
302 pickerScreen(ctx, screen, {
303 title: "Upgrade which shared forge?",
304 items,
305 onPick: (ids) => {
306 const name = ids[0];
307 if (name === undefined) return;
308 ctx.push(
309 pickerScreen(ctx, screen, {
310 title: `Upgrade ${name} to which plan?`,
311 items: dedicatedPlans(app).map((p) => ({ id: p.key, label: p.name, hint: usdPerMonthWords(p.priceUsd) })),
312 onPick: (picked) => {
313 const plan = picked[0];
314 if (plan === undefined) return;
315 ctx.push(
316 pickerScreen(ctx, screen, {
317 title: `Upgrade ${name} on which machine?`,
318 items: declared.map((m) => ({ id: m.name, label: m.name, hint: m.root })),
319 onPick: (to) => {
320 const target = to[0];
321 if (target === undefined) return;
322 void planUpgrade(app, user, name, plan, target).then((planned) => {
323 if (!planned.ok) return ctx.toast(planned.says, "danger");
324 ctx.push(
325 confirmScreen(ctx, screen, {
326 title: `Upgrade ${name} to ${planned.plan.change.to}?`,
327 body: [planned.plan.says, ...planned.plan.steps],
328 actions: [{ label: "Upgrade it" }, { label: "Leave it" }],
329 onChoose: (i) => {
330 if (i === 0) void upgradeShared(app, user, name, plan, target).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger"));
331 },
332 }),
333 );
334 });
335 },
336 }),
337 );
338 },
339 }),
340 );
341 },
342 }),
343 );
344 };
288345 // Each machine's heartbeat and the emptiest, where a new forge goes (the MCP `kind: machines`).
289346 const machinesSeen = (): void => {
290347 if (session?.user?.isAdmin !== true) return;
@@ -333,7 +390,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
333390 };
334391 const screen: Screen = {
335392 title: "Forges you sent",
336 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["g"], "move to a machine"), binding(["v"], "restore from the newest copy"), binding(["h"], "machines' heartbeats"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")],
393 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["g"], "move to a machine"), binding(["v"], "restore from the newest copy"), binding(["e"], "upgrade a shared forge"), binding(["h"], "machines' heartbeats"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")],
337394 render(area, s) {
338395 const c = ctx.theme.c;
339396 const w = Math.min(100, Math.max(30, area.w - 6));
@@ -399,6 +456,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
399456 } else if (e.key === "m") sandboxOne();
400457 else if (e.key === "g") machineOne(false);
401458 else if (e.key === "v") machineOne(true);
459 else if (e.key === "e") upgradeOne();
402460 else if (e.key === "h") machinesSeen();
403461 else if (e.key === "w") raiseOne();
404462 else if (e.key === "x" && session !== undefined)
src/web/pages/forge_upgrade.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * Upgrade a shared forge to a dedicated one, on the page (#17024): `GET /forges/:name/upgrade`
3 * names the dedicated plans and machines; with `?plan=&to=` it shows what would happen and what
4 * the forge pays before and after, and asks. `POST` does it and shows the receipt. The words are
5 * `actions/upgrade_shared.ts`'s, the same the MCP `forges` tool and the terminal say.
6 */
7
8 import { dedicatedPlans, planUpgrade, upgradeShared } from "../../actions/upgrade_shared.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { usdPerMonthWords } from "../../billing/money.ts";
11 import { machinesOf } from "../../spawn/machines.ts";
12 import { notFoundPage, pageHead } from "../chrome.ts";
13 import { readForm } from "../form.ts";
14 import { html, type Html } from "../html.ts";
15 import { page } from "../layout.ts";
16 import { btn } from "../ui.ts";
17
18 const back = (name: string) => btn("Back to your forges", { href: `/forges#forge-${name}`, size: "sm" });
19
20 const wrap = (name: string, body: Html) =>
21 html`<div class="narrow-wide" data-forges>${pageHead(`Upgrade ${name} to a dedicated forge`)}<section class="settings-block">${body}<p class="mt">${back(name)}</p></section></div>`;
22
23 export async function forgeUpgradeForm(ctx: Ctx): Promise<Response> {
24 const user = ctx.auth.user;
25 if (!user?.isAdmin) return notFoundPage(ctx);
26 const name = ctx.params["name"] ?? "";
27 const plan = ctx.url.searchParams.get("plan") ?? "";
28 const to = ctx.url.searchParams.get("to") ?? "";
29 const planned = plan === "" || to === "" ? undefined : await planUpgrade(ctx.app, user, name, plan, to);
30 const plans = dedicatedPlans(ctx.app);
31 const machines = machinesOf(ctx.app).map((m) => m.name);
32 const body =
33 planned === undefined
34 ? html`<form method="get" action="/forges/${name}/upgrade" data-upgrade-choose>
35 <p>Move ${name} to a dedicated machine, keeping its data:</p>
36 <select name="plan" aria-label="Plan">${plans.map((p) => html`<option value="${p.key}">${p.name}, ${usdPerMonthWords(p.priceUsd)}</option>`)}</select>
37 <select name="to" aria-label="Machine">${machines.map((m) => html`<option value="${m}">${m}</option>`)}</select>
38 ${btn("See what it would do", { size: "sm" })}
39 </form>`
40 : planned.ok
41 ? html`<p data-preview>${planned.plan.says}</p>
42 ${planned.plan.steps.map((s) => html`<p data-step>${s}</p>`)}
43 <form method="post" action="/forges/${name}/upgrade">
44 <input type="hidden" name="plan" value="${plan}" />
45 <input type="hidden" name="to" value="${to}" />
46 ${btn(`Upgrade to ${planned.plan.change.to}`, { variant: "primary", title: "It stays on the shared plan if the move fails" })}
47 </form>`
48 : html`<p role="status" data-preview>${planned.says}</p>`;
49 const response = page({ ctx, title: "Upgrade to a dedicated forge", body: wrap(name, body) }, planned !== undefined && !planned.ok ? (planned.kind === "not_found" ? 404 : 409) : 200);
50 response.headers.set("cache-control", "no-store");
51 return response;
52 }
53
54 export async function forgeUpgradeSubmit(ctx: Ctx): Promise<Response> {
55 const user = ctx.auth.user;
56 if (!user?.isAdmin) return notFoundPage(ctx);
57 const form = await readForm(ctx, "admin");
58 if (form instanceof Response) return form;
59 const name = ctx.params["name"] ?? "";
60 const done = await upgradeShared(ctx.app, user, name, String(form.get("plan") ?? ""), String(form.get("to") ?? ""));
61 const title = done.ok ? "Forge upgraded" : "Forge not upgraded";
62 const response = page(
63 { ctx, title, body: html`<div class="narrow-wide" data-forges>${pageHead(title)}<section class="settings-block"><p role="status" data-upgraded="${done.ok ? "yes" : done.kind}">${done.says}</p><p class="mt">${back(name)}</p></section></div>` },
64 done.ok ? 200 : done.kind === "not_found" ? 404 : 409,
65 );
66 response.headers.set("cache-control", "no-store");
67 return response;
68 }
src/web/pages/forges.ts +6 −2
@@ -26,6 +26,7 @@ import { listChildren } from "../../actions/spawn.ts";
2626 import { ownCode, removeForge, resizeForge, stopForge, type Managed } from "../../spawn/manage.ts";
2727 import { sizesView } from "../../spawn/sizes.ts";
2828 import { readOwnCode } from "../../spawn/own_code.ts";
29 import { sharedForges } from "../../actions/upgrade_shared.ts";
2930 import { machinesOf } from "../../spawn/machines.ts";
3031 import { moveToCell } from "../../spawn/move_cell.ts";
3132 import { sealedAt } from "../../spawn/sealed.ts";
@@ -92,7 +93,7 @@ function activityNote(r: ClientRow, seenOnRow: boolean, now: number): Html | nul
9293
9394 const XLARGE_SAYS = `${sizeWords("xlarge")}. ${sizesView().sizes.find((x) => x.size === "xlarge")?.says ?? ""}`;
9495
95 export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = false, kept?: string, machines = false): Html {
96 export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = false, kept?: string, machines = false, shared = false): Html {
9697 const state = claimState(r);
9798 const daysLeft = state === "no" ? daysLeftWords(r.link, now) : null;
9899 const seen = seenOf(r);
@@ -186,6 +187,8 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f
186187 </form>`
187188 : null}${r.made && r.placement === "cell" && machines
188189 ? btn("Move to another machine", { size: "sm", href: `/forges/${r.name}/machine`, title: "See what it would do and the budget, then confirm; it stays where it is if any step fails" })
190 : null}${r.made && r.placement === "cell" && machines && shared
191 ? btn("Upgrade to a dedicated forge", { size: "sm", href: `/forges/${r.name}/upgrade`, title: "Copies its data to a dedicated machine and changes its plan; it stays shared if the move fails" })
189192 : null}${r.made && r.size !== "xlarge"
190193 ? html`<form method="post" action="/forges/${r.name}/size" class="inline">
191194 <input type="hidden" name="size" value="xlarge" />
@@ -290,6 +293,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
290293 // Sizes that together pass the machine's memory are said in one line; nothing is refused for it.
291294 const hostedKept = readHosted(ctx.app.config.dataDir);
292295 const machines = machinesOf(ctx.app).length > 0;
296 const sharedNames = machines ? sharedForges(ctx.app, rows) : new Set<string>();
293297 const over = memoryOverLine(forgesMemory(ctx.app, memoryOf(rows)));
294298 const rendering = performance.now();
295299 const action =
@@ -339,7 +343,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
339343 : state !== null && rows.length === 0
340344 ? html`<p data-empty>${CLIENT_STATE_EMPTY[state]}. <a href="/forges?sort=${sort}">All forges</a></p>`
341345 : html`<ul class="list setting-list">
342 ${rows.map((r) => forgeRow(r, now, reachOf.get(r.name), claimsBill(ctx.app.db, user, r.billTo), keptWords(hostedKept, r.name, now), machines))}
346 ${rows.map((r) => forgeRow(r, now, reachOf.get(r.name), claimsBill(ctx.app.db, user, r.billTo), keptWords(hostedKept, r.name, now), machines, sharedNames.has(r.name)))}
343347 </ul>`}
344348 </section>`}
345349 ${sealedLine(ctx)}
test/upgrade-shared.test.ts added +184
@@ -0,0 +1,184 @@
1 /**
2 * #17024: a shared forge is upgraded to a dedicated one keeping its data, and billed the dedicated
3 * price only if the move happened; the page, the MCP `forges` tool and the terminal say the same.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { dedicatedPlans, planUpgrade, upgradeShared } from "../src/actions/upgrade_shared.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { SHARED } from "../src/billing/density.ts";
12 import { entitlementOf, putEntitlement } from "../src/billing/store.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { getUserById, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { clientRows } from "../src/spawn/clients.ts";
17 import { forgetMachines, registerMachine, type Machine } from "../src/spawn/machines.ts";
18 import { forgetRoutes, routeOf } from "../src/spawn/routes.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import { forgesScreen } from "../src/tui/screens/forges.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { adminCookie } from "./helpers/admin.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { mcpTool } from "./helpers/mcp.ts";
25 import { waitFor } from "./helpers/poll.ts";
26 import { settleApp } from "./helpers/tui.ts";
27
28 quietLogs();
29
30 const root = mkdtempSync(join(tmpdir(), "upgrade-shared-"));
31 let app: App;
32 let servers: Servers;
33 let token = "";
34 let cookie = "";
35 let alice: User;
36 let up = true;
37 const was = process.env["FORGE_SNAPSHOT_DIR"];
38
39 /** A machine that runs nothing; `up` false makes its start fail, so the move fails. */
40 const machine: Machine = {
41 name: "m1",
42 root: join(root, "m1"),
43 start: async () => (up ? 4999 : Promise.reject(new Error("no room"))),
44 alive: () => false,
45 stop: async () => {},
46 };
47
48 function shared(name: string, plan: string = SHARED, provider: "none" | "stripe" = "none"): void {
49 const data = app.config.dataDir;
50 mkdirSync(join(data, "spawn"), { recursive: true });
51 mkdirSync(join(data, "children", `body-${name}`), { recursive: true });
52 writeFileSync(join(data, "children", `body-${name}`, "note.txt"), `data of ${name}`);
53 writeFileSync(join(data, "spawn", `${name}.json`), JSON.stringify({ name, bodyId: `body-${name}`, done: true, placement: "cell", size: "small", apps: [] }));
54 putEntitlement(app.db, { forge: name, plan, status: "active", source: "granted", provider }, "small", "");
55 }
56
57 /** The refusal's words, or "" when it went through. */
58 const says = (r: { ok: boolean; says?: string }): string => (r.ok ? "" : (r.says ?? ""));
59
60 const planOf = (name: string): string => entitlementOf(app.db, name, "small").plan;
61
62 beforeAll(async () => {
63 process.env["FORGE_SNAPSHOT_DIR"] = join(root, "bucket");
64 app = createApp({ dataDir: join(root, "parent"), url: "https://forge.test", port: 0 });
65 cookie = await adminCookie(app, { username: "alice", email: "[email protected]" });
66 const row = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!;
67 alice = getUserById(app.db, row.id)!;
68 token = createToken(app.db, alice.id, "t", "admin").token;
69 for (const n of ["one", "two", "three", "four"]) shared(n);
70 shared("paid", "small");
71 shared("card", SHARED, "stripe");
72 forgetMachines(app);
73 registerMachine(app, machine);
74 servers = await serve(app);
75 }, 30_000);
76
77 afterAll(() => {
78 servers.stop();
79 app.close();
80 forgetMachines(app);
81 forgetRoutes(app);
82 if (was === undefined) delete process.env["FORGE_SNAPSHOT_DIR"];
83 else process.env["FORGE_SNAPSHOT_DIR"] = was;
84 rmSync(root, { recursive: true, force: true });
85 });
86
87 test("the preview says the price before and after and changes nothing", async () => {
88 const planned = await planUpgrade(app, alice, "one", "small", "m1");
89 if (!planned.ok) throw new Error(planned.says);
90 expect(planned.plan.says).toContain("shared to Small");
91 expect(planned.plan.change.cents).toBe(1900);
92 expect(planned.plan.fromCents).toBeGreaterThan(0);
93 expect(planned.plan.fromCents).toBeLessThan(1900);
94 expect(planned.plan.steps.at(-1)).toContain("shared → small");
95 expect(planOf("one")).toBe(SHARED);
96 expect(routeOf(app, "one")).toBeUndefined();
97 });
98
99 test("a failed move leaves the forge on the shared plan", async () => {
100 up = false;
101 const done = await upgradeShared(app, alice, "one", "small", "m1");
102 up = true;
103 expect(done.ok).toBe(false);
104 expect(done.says).toContain("still on the shared plan");
105 expect(planOf("one")).toBe(SHARED);
106 });
107
108 test("the upgrade copies the data, switches the route and changes the plan once", async () => {
109 const done = await upgradeShared(app, alice, "one", "small", "m1");
110 if (!done.ok) throw new Error(done.says);
111 expect(done.says).toContain("one is on Small now");
112 expect(planOf("one")).toBe("small");
113 expect(routeOf(app, "one")?.machine).toBe("m1");
114 expect(readFileSync(join(machine.root, "children", "body-one", "note.txt"), "utf8")).toBe("data of one");
115 expect(existsSync(join(app.config.dataDir, "children", "body-one", "note.txt"))).toBe(true);
116 const again = await upgradeShared(app, alice, "one", "small", "m1");
117 expect(again.ok).toBe(false);
118 expect(again.says).toContain("not the shared one");
119 });
120
121 test("refusals: not shared, paid at a provider, an unknown plan, the free plan, a stranger", async () => {
122 expect((await planUpgrade(app, alice, "paid", "small", "m1")).ok).toBe(false);
123 const card = await planUpgrade(app, alice, "card", "small", "m1");
124 expect(says(card)).toContain("pays through stripe");
125 const unknown = await planUpgrade(app, alice, "two", "gold", "m1");
126 expect(says(unknown)).toContain("plan is one of");
127 expect(dedicatedPlans(app).map((p) => p.key)).not.toContain("free");
128 expect(dedicatedPlans(app).map((p) => p.key)).not.toContain(SHARED);
129 expect((await planUpgrade(app, alice, "two", "free", "m1")).ok).toBe(false);
130 expect((await planUpgrade(app, undefined, "two", "small", "m1")).ok).toBe(false);
131 expect((await planUpgrade(app, { ...alice, kind: "agent" }, "two", "small", "m1")).ok).toBe(false);
132 expect((await planUpgrade(app, alice, "nobody", "small", "m1")).ok).toBe(false);
133 expect(planOf("two")).toBe(SHARED);
134 });
135
136 test("the MCP tool previews, then upgrades with the same words", async () => {
137 const seen = await mcpTool(servers.url, token, "forges", { action: "upgrade", forge: "two", plan: "small", to: "m1" });
138 expect(seen.value.says).toContain("shared to Small");
139 expect(planOf("two")).toBe(SHARED);
140 const done = await mcpTool(servers.url, token, "forges", { action: "upgrade", forge: "two", plan: "small", to: "m1", dryRun: false });
141 expect(done.value.says).toContain("two is on Small now");
142 expect(planOf("two")).toBe("small");
143 });
144
145 test("the page offers it only on a shared forge, previews, and shows the receipt", async () => {
146 const list = await (await fetch(`${servers.url}/forges`, { headers: { cookie } })).text();
147 expect(list).toContain('href="/forges/three/upgrade"');
148 expect(list).not.toContain('href="/forges/paid/upgrade"');
149 const preview = await (await fetch(`${servers.url}/forges/three/upgrade?plan=small&to=m1`, { headers: { cookie } })).text();
150 expect(preview).toContain("shared to Small");
151 expect(planOf("three")).toBe(SHARED);
152 const bad = await fetch(`${servers.url}/forges/three/upgrade`, { method: "POST", headers: { cookie, origin: "https://evil.test" }, body: new URLSearchParams({ plan: "small", to: "m1" }) });
153 expect(bad.status).toBeGreaterThanOrEqual(400);
154 expect(planOf("three")).toBe(SHARED);
155 const res = await fetch(`${servers.url}/forges/three/upgrade`, { method: "POST", headers: { cookie, origin: "https://forge.test" }, body: new URLSearchParams({ plan: "small", to: "m1" }) });
156 expect(await res.text()).toContain("three is on Small now");
157 expect(planOf("three")).toBe("small");
158 });
159
160 test("the terminal drives the same plan and upgrade on e", async () => {
161 const terminal = headlessTerminal(140, 30);
162 const { app: tui, session } = createForgeApp(app, { sshUsername: alice.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: alice }, { terminal, exitHooks: false });
163 tui.start();
164 await settleApp(tui);
165 tui.push(forgesScreen(tui.ctx, await clientRows(app), session));
166 await settleApp(tui);
167 const press = async (key: string): Promise<string> => (terminal.feed(key), await settleApp(tui), tui.screen.toText());
168 expect(await press("e")).toContain("Upgrade which shared forge?");
169 // Shared forges left: four, and the stripe-paid card; the picker lists them by name: card, four.
170 await press("\x1b[B");
171 await press("\r");
172 expect(tui.screen.toText()).toContain("Upgrade four to which plan?");
173 await press("\r");
174 expect(tui.screen.toText()).toContain("on which machine?");
175 await press("\r");
176 const plan = tui.screen.toText();
177 expect(plan).toContain("Upgrade four to small?");
178 expect(plan).toContain("shared → small: $19.00");
179 expect(planOf("four")).toBe(SHARED);
180 await press("\r");
181 await waitFor(() => planOf("four") === "small", { every: 20, within: 3000 });
182 expect(routeOf(app, "four")?.machine).toBe("m1");
183 tui.stop();
184 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs