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

A deployed forge answers in about a minute, not twelve: a prepared machine im… #16363

Merged opened this in answer to

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

Merged

mason/forge:mason/16362-a-deployed-forge-answers-in-about-a-minu → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/16362-a-deployed-forge-answers-in-about-a-minu was merged into main as 7a8e7a5.

Review

Sign in to review this change.
12 files changed +351 −6
docs/features/cloud.md +10
@@ -32,3 +32,13 @@ Not done: the route only lists. Attaching, rotating and removing stay on the pag
3232 **In the terminal:** the palette's *Places* (`src/tui/screens/places.ts`) shows the rule, each plan's default and why, and every place by price in dollars. Anyone signed in reads it; a forge admin who is a person also presses `p` to pin a plan (plan, then place id; empty clears) through `pinPlace`, the same act as the API. Opening it as an admin refreshes a stale catalog first.
3333
3434 Not done: deploying by place id, the buyer's "Choose where it runs" disclosure and the owner's margin page; they build on this catalog.
35
36 ## The warm pool (#16362)
37
38 A prepared machine already booted and waiting, unclaimed and with no name, answers a purchase in seconds. It costs money while it waits, so none is kept by default: each place (`provider:datacenter:size`) of an account has a configured most, 0 until a forge admin sets it (about 3 once customers come).
39
40 - `wantedWarm` (`src/cloud/warm_pool.ts`) says how many to hold now: 0 when the setting is 0; otherwise one, raised to cover two hours of purchases at the last day's rate, never past the setting and never past what the account's ceiling leaves room for. Falling demand lowers it; nothing is torn down to save money by this rule alone.
41 - A warm machine is a pinned row in state `warm`, so the ceiling counts every one (`rowCents`) and the account's cost already includes them; Settings → Cloud and the terminal screen show each place's held count, setting and cost beside the ceiling.

The terminal screen shows only held/configured and the place, not the cost. Fix the doc or show the cost.

42 - Set it with the MCP `cloud_account` verb `set_warm` (`place`, `count` 0 to 10, admin scope); it is recorded as `cloud.warm_target`.
43
44 Not done: making and refilling the machines themselves, and a form on the page and a key in the terminal to set the count; this lands the policy, the setting, the counting and the display.
src/actions/cloud_ceiling.ts +14
@@ -7,6 +7,7 @@
77 import type { App } from "../app.ts";
88 import { getCloudAccount, setCeilingDollars } from "../core/cloud_account.ts";
99 import type { User } from "../core/users.ts";
10 import { MAX_WARM, setWarmTarget, warmTargets } from "../cloud/warm_pool.ts";
1011 import { err, ok, type Result } from "../kernel/result.ts";
1112
1213 export const MAX_CEILING_DOLLARS = 100_000;
@@ -20,3 +21,16 @@ export function setCeiling(app: App, actor: User | undefined, provider: string,
2021 app.bus.append({ kind: "cloud.ceiling", actorId: actor.id, payload: { provider, name, from: before.ceilingDollars, to: dollars } });
2122 return ok(`ceiling is $${dollars} a month`);
2223 }
24
25 const PLACE = /^[a-z]{3,20}:[a-z0-9-]{2,20}:[a-z0-9._-]{2,40}$/;
26
27 export function setWarm(app: App, actor: User | undefined, provider: string, name: string, place: unknown, count: unknown): Result<string, string> {
28 if (actor?.isAdmin !== true) return err("not_found");
29 if (typeof place !== "string" || !PLACE.test(place) || !place.startsWith(`${provider}:`)) return err(`A place is provider:datacenter:size on ${provider}, as Places lists it.`);
30 if (typeof count !== "number" || !Number.isInteger(count) || count < 0 || count > MAX_WARM) return err(`A warm count is a whole number from 0 to ${MAX_WARM}.`);
31 if (!getCloudAccount(app.db, provider, name)) return err("No such credential.");
32 const from = warmTargets(app.db, provider, name).get(place) ?? 0;
33 setWarmTarget(app.db, provider, name, place, count);
34 app.bus.append({ kind: "cloud.warm_target", actorId: actor.id, payload: { provider, name, place, from, to: count } });
35 return ok(count === 0 ? `no machine is kept warm at ${place}` : `up to ${count} machine${count === 1 ? "" : "s"} kept warm at ${place}, as purchases and the ceiling allow`);
36 }
src/cloud/overview.ts +7
@@ -13,6 +13,7 @@ import type { User } from "../core/users.ts";
1313 import { err, ok, type Result } from "../kernel/result.ts";
1414 import { usedFor, type VendorUse } from "./declared.ts";
1515 import { spendOf } from "./ceiling.ts";
16 import { warmOf, type WarmPlace } from "./warm_pool.ts";
1617 import { VENDOR_OF, type Provider } from "./providers.ts";
1718
1819 export interface AccountRow {
@@ -31,6 +32,11 @@ export interface AccountRow {
3132 readonly ceilingDollars: number;
3233 readonly monthlyCents: number;
3334 readonly leftCents: number;
35 /**
36 * The warm pool, a place at a time: what is set, held and wanted, and what the held cost (already
37 * in monthlyCents). Empty by default.
38 */
39 readonly warm: WarmPlace[];
3440 }
3541
3642 export interface CloudOverview {
@@ -57,6 +63,7 @@ export function cloudOverview(
5763 writeAllowed: a.writeAllowed,
5864 callsToday: today.filter((r) => r.provider === a.provider && r.account === a.name).length,
5965 ...spendOf(app.db, a.provider, a.name),
66 warm: warmOf(app.db, a.provider, a.name),
6067 }));
6168 return ok({ accounts, today });
6269 }
src/cloud/warm_pool.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * The warm pool (#16362): prepared machines already booted and waiting, unclaimed and with no
3 * name, so a purchase takes one in seconds. A pool, not one machine: each place has a configured
4 * most (table `warm_pool`, 0 until an admin says otherwise, about 3 once customers come), and
5 * this module decides how many of those are worth holding now.
6 *
7 * Cost comes first. With a configured 0 nothing is wanted, ever. With more, the pool keeps one
8 * and follows the recent purchase rate: enough to cover `COVER_HOURS` of purchases at the rate of
9 * the last day, never more than configured, and never more than the account's ceiling leaves room
10 * for. A warm machine is a pinned row in state `warm` (`WARM_STATE`), so the ceiling already counts
11 * every one (`rowCents`); `warmOf` reads them back to show beside it. Plain data in, plain data
12 * out.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import { listPinned, placeIdOf } from "../core/pinned.ts";
17 import { priced, rowCents, spendOf, type Priced } from "./ceiling.ts";
18
19 /** The most a place may be told to keep warm. */
20 export const MAX_WARM = 10;
21
22 export function warmTargets(db: Database, provider: string, account: string): Map<string, number> {
23 const rows = db
24 .query<{ place: string; target: number }, [string, string]>("SELECT place, target FROM warm_pool WHERE provider = ?1 AND account = ?2 AND target > 0 ORDER BY place")
25 .all(provider, account);
26 return new Map(rows.map((r) => [r.place, r.target]));
27 }
28
29 export function setWarmTarget(db: Database, provider: string, account: string, place: string, target: number): void {
30 db.query(
31 `INSERT INTO warm_pool (provider, account, place, target) VALUES (?1, ?2, ?3, ?4)
32 ON CONFLICT (provider, account, place) DO UPDATE SET target = excluded.target`,
33 ).run(provider, account, place, target);
34 }
35
36 export const WARM_STATE = "warm";
37 /** The window the purchase rate is read over. */
38 export const RATE_HOURS = 24;
39 /** How many hours of purchases the pool should be able to answer before it is refilled. */
40 export const COVER_HOURS = 2;
41
42 export interface WarmInput {
43 /** The most this place may hold, as an admin set it. */
44 readonly configured: number;
45 /** Machines held now. */
46 readonly held: number;
47 /** Purchases of this place in the last `RATE_HOURS`. */
48 readonly purchases: number;
49 /** What one machine costs a month, cents; undefined when the catalog has no price. */
50 readonly perMachineCents: number | undefined;
51 /** Cents left under the account's ceiling; negative when over. */
52 readonly leftCents: number;
53 }
54
55 /** How many warm machines to hold for a place: raised and lowered from the purchase rate. */
56 export function wantedWarm(i: WarmInput): number {
57 if (i.configured <= 0) return 0;
58 const byRate = Math.max(1, Math.ceil((i.purchases / RATE_HOURS) * COVER_HOURS));
59 const want = Math.min(i.configured, byRate);
60 // Growing is bounded by the ceiling's room; an unpriced place never grows. Shrinking is free.
61 const room = i.perMachineCents === undefined || i.perMachineCents <= 0 ? 0 : Math.floor(Math.max(0, i.leftCents) / i.perMachineCents);
62 return Math.min(want, i.held + room);
63 }
64
65 export interface WarmPlace {
66 readonly place: string;
67 readonly configured: number;
68 readonly held: number;
69 readonly wanted: number;
70 /** What the held machines cost a month, cents: already inside the account's reckoning. */
71 readonly cents: number;
72 }
73
74 /** Each place of an account that has a target or a warm machine, as the doors show it. */
75 export function warmOf(db: Database, provider: string, account: string, now: number = Date.now(), prices: Priced = priced(db)): WarmPlace[] {
76 const configured = warmTargets(db, provider, account);
77 const rows = listPinned(db).filter((p) => p.target === provider && p.account === account);
78 const since = now - RATE_HOURS * 3_600_000;
79 const left = spendOf(db, provider, account, prices).leftCents;
80 const places = new Set([...configured.keys(), ...rows.filter((p) => p.state === WARM_STATE).map(placeIdOf)]);
81 return [...places].sort().map((place) => {
82 const held = rows.filter((p) => p.state === WARM_STATE && placeIdOf(p) === place);
83 const purchases = rows.filter((p) => p.state !== WARM_STATE && placeIdOf(p) === place && p.claimedAt !== "" && Date.parse(p.claimedAt) >= since).length;
84 const target = configured.get(place) ?? 0;
85 return {
86 place,
87 configured: target,
88 held: held.length,
89 wanted: wantedWarm({ configured: target, held: held.length, purchases, perMachineCents: prices.forge(place), leftCents: left }),
90 cents: held.reduce((sum, p) => sum + rowCents(p, prices), 0),
91 };
92 });
93 }
src/core/event_audience.ts +3
@@ -302,6 +302,9 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
302302 kind === "forge.updates_taken" ||
303303 kind === "cloud.write_allowed" ||
304304 kind === "cloud.ceiling" ||
305 // How many prepared machines a plan keeps waiting is a spend choice (`cloud/warm_pool.ts`,
306 // #16362).
307 kind === "cloud.warm_target" ||
305308 // A plan's pinned default place is an admin's act (`actions/places.ts`, #16203).
306309 kind === "cloud.place_pinned" ||
307310 // A bet's name, share and what is left are the owner's plan (#8713).
src/core/migration-pins/20261125010000-warm-pool.pin added +1
@@ -0,0 +1,1 @@
1 970c47b5e2269dac0465a243c890d5eb9a78fb45cf37a1fda3f9d38bdc7b69eb
src/core/migrations/20261125010000-warm-pool.ts added +12
@@ -0,0 +1,12 @@
1 // How many prepared machines a cloud account keeps booted and waiting for each place (#16362): the
2 // most the forge may hold, 0 until an admin says otherwise, so no warm machine costs anything by
3 // default. One row a place that was ever set; none means 0. Additive.
4 export default `
5 CREATE TABLE warm_pool (
6 provider TEXT NOT NULL,
7 account TEXT NOT NULL,
8 place TEXT NOT NULL,
9 target INTEGER NOT NULL DEFAULT 0 CHECK (target >= 0 AND target <= 10),
10 PRIMARY KEY (provider, account, place)
11 );
12 `;
src/http/mcp/tools/cloud_account.ts +8 −4
@@ -1,5 +1,5 @@
11 import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../../actions/cloud.ts";
2 import { setCeiling } from "../../../actions/cloud_ceiling.ts";
2 import { setCeiling, setWarm } from "../../../actions/cloud_ceiling.ts";
33 import { PROVIDERS } from "../../../cloud/providers.ts";
outdated

Stray blank line inside the import block; remove it.

44 import { scopeAllows } from "../../../core/tokens.ts";
55 import { good, bad, type Tool, str } from "../shared.ts";
@@ -7,19 +7,21 @@ import { good, bad, type Tool, str } from "../shared.ts";
77 export const tool: Tool = {
88 name: "cloud_account",
99 listedTo: "admin",
10 doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`",
10 doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars?, place?, count? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) `set_warm` (`place`, `count`: how many prepared machines to keep booted and waiting at a place, 0 until set, counted against the ceiling and shown beside it), or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`",
1111 description:
1212 "Change a cloud account by `verb` (admin).",
1313 inputSchema: {
1414 type: "object",
1515 properties: {
16 verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "audit"] },
16 verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "set_warm", "audit"] },
1717 provider: { type: "string", enum: [...PROVIDERS] },
1818 name: { type: "string", maxLength: 32 },
1919 value: { type: "string", maxLength: 4096, description: "For attach, rotate." },
2020 to: { type: "string", maxLength: 32 },
2121 allowed: { type: "boolean" },
2222 repo: { type: "string", maxLength: 200 },
23 place: { type: "string", maxLength: 100, description: "For set_warm: provider:datacenter:size." },
24 count: { type: "integer", minimum: 0, maximum: 10, description: "For set_warm." },
2325 dollars: { type: "integer", minimum: 0, maximum: 100000, description: "For set_ceiling." },
2426 },
2527 required: ["verb", "provider", "name"],
@@ -52,10 +54,12 @@ export const tool: Tool = {
5254 ? allowWrite(ctx.app, user, provider, name, args["allowed"] === true)
5355 : verb === "set_ceiling"
5456 ? setCeiling(ctx.app, user, provider, name, args["dollars"])
57 : verb === "set_warm"
58 ? setWarm(ctx.app, user, provider, name, args["place"], args["count"])
5559 : verb === "audit"
5660 ? await auditAccount(ctx.app, user, provider, name, str(args["repo"]))
5761 : undefined;
58 if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling or audit");
62 if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling, set_warm or audit");
5963 if (!done.ok) return bad("refused", done.error);
6064 const v = done.value as unknown;
6165 const said =
src/tui/screens/cloud.ts +2 −1
@@ -10,6 +10,7 @@
1010 import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../actions/cloud.ts";
1111 import { usesByVendor, type VendorUse } from "../../cloud/declared.ts";
1212 import { cloudOverview } from "../../cloud/overview.ts";
13 import { dollars } from "../../cloud/prices.ts";
1314 import { LABEL, PROVIDERS } from "../../cloud/providers.ts";
1415 import type { Ctx, Screen } from "../app/app.ts";
1516 import { binding } from "../app/keys.ts";
@@ -86,7 +87,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
8687 accounts().map((a) => ({
8788 title: `${a.provider}/${a.name}`,
8889 secondary: `verified ${day(a.verifiedAt)} · used ${day(a.lastUsedAt)} · ${a.callsToday} call${a.callsToday === 1 ? "" : "s"} today`,
89 meta: a.writeAllowed ? "writes allowed" : "read-only",
90 meta: `${a.writeAllowed ? "writes allowed" : "read-only"}${a.warm.length === 0 ? "" : ` · warm ${a.warm.map((w) => `${w.held}/${w.configured} ${w.place} ${dollars(w.cents)} a month`).join(", ")}`}`,
9091 }));
9192
9293 const attach = (parent: Screen): Screen =>
src/web/pages/cloud.ts +12
@@ -20,6 +20,7 @@ import {
2020 import { LABEL, PROVIDERS, VENDOR_OF, isProvider, shape } from "../../cloud/providers.ts";
2121 import { HOME, usedFor, usesByVendor, type VendorUse } from "../../cloud/declared.ts";
2222 import { spendOf } from "../../cloud/ceiling.ts";
23 import { warmOf } from "../../cloud/warm_pool.ts";
2324 import { dollars } from "../../cloud/prices.ts";
2425 import { auditToday } from "../../core/cloud_audit.ts";
2526 import {
@@ -55,6 +56,16 @@ const hidden = (provider: string, name: string): Html =>
5556 html`<input type="hidden" name="provider" value="${provider}" />
5657 <input type="hidden" name="name" value="${name}" />`;
5758
59 /**
60 * The warm pool of an account, a place a fact: how many are kept, the most set, and what they cost.
outdated

Principles 1, 7 and 8: this is a facts list jammed into a sentence. Use dl rows per place in plain words.

61 */
62 function warmFacts(db: Database, a: CloudAccount): { label: string; value: string }[] {
63 return warmOf(db, a.provider, a.name).map((p) => ({
64 label: `Warm at ${p.place}`,
65 value: `${p.held} kept now, at most ${p.configured}, ${dollars(p.cents)} a month (already in the total above)`,
66 }));
67 }
68
5869 function ceilingLine(db: Database, a: CloudAccount): string {
5970 const s = spendOf(db, a.provider, a.name);
6071 return `ceiling $${s.ceilingDollars} a month · the forge reckons ${dollars(s.monthlyCents)} now · ${s.leftCents >= 0 ? `${dollars(s.leftCents)} left` : `${dollars(-s.leftCents)} over`}`;
@@ -69,6 +80,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[]
6980 meta: html`${a.summary}<br />${usedFor(uses.get(VENDOR_OF[a.provider]))}<br />${HOME[a.provider]}<br />verified ${a.verifiedAt ? time(a.verifiedAt) : "never"} ·
7081 ${last ? html`last used ${time(last.at)} by ${runWords(last.run)}` : "never used"} ·
7182 ${a.writeAllowed ? "writes allowed" : "read-only"}<br />${ceilingLine(db, a)}`,
83 facts: warmFacts(db, a),
7284 trail: html`<div class="row-fields">
7385 <form method="post" action="/settings/cloud/verify">
7486 ${hidden(a.provider, a.name)}${btn("Verify", { size: "sm", label: `Verify ${a.name}` })}
test/mcp-cloud-account.test.ts +1 −1
@@ -20,7 +20,7 @@ quietLogs();
2020
2121 const TOKEN = "do-live-9Zq4TxLm7Kp2Vb8nWcR5";
2222 const realFetch = net.fetch;
23 const VERBS = ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "audit"];
23 const VERBS = ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_warm", "audit"];
2424
2525 describe("MCP cloud_account", () => {
2626 let dataDir: string;
test/warm-pool.test.ts added +188
@@ -0,0 +1,188 @@
1 /**

No test covers the MCP set_warm verb, the page line, or the terminal meta. Each would survive removal. Add them.

2 * The warm pool (#16362): none by default, a pool that follows purchases, held to the ceiling, set
3 * by an admin only.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { setWarm } from "../src/actions/cloud_ceiling.ts";
11 import { cloudOverview } from "../src/cloud/overview.ts";
12 import { wantedWarm, WARM_STATE } from "../src/cloud/warm_pool.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { createForgeApp } from "../src/tui/forge.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { settleApp } from "./helpers/tui.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { seedPlaces } from "./helpers/places-fixture.ts";
21
22 quietLogs();
23
24 const base = { configured: 3, held: 0, purchases: 0, perMachineCents: 1000, leftCents: 100_000 };
25
26 describe("wantedWarm", () => {
27 test("none by default, whatever the demand or the room", () => {
28 expect(wantedWarm({ ...base, configured: 0, purchases: 500 })).toBe(0);
29 expect(wantedWarm({ ...base, configured: 0, held: 2 })).toBe(0);
30 });
31 test("one when set and quiet, more as purchases rise, never past the setting", () => {
32 expect(wantedWarm(base)).toBe(1);
33 expect(wantedWarm({ ...base, purchases: 24 })).toBe(2);
34 expect(wantedWarm({ ...base, purchases: 36 })).toBe(3);
35 expect(wantedWarm({ ...base, purchases: 480 })).toBe(3);
36 });
37 test("it comes back down when purchases stop", () => {
38 expect(wantedWarm({ ...base, held: 3, purchases: 0 })).toBe(1);
39 });
40 test("growth stops at the ceiling's room, and an unpriced place never grows", () => {
41 expect(wantedWarm({ ...base, purchases: 480, held: 1, leftCents: 1500 })).toBe(2);
42 expect(wantedWarm({ ...base, purchases: 480, held: 0, leftCents: -5 })).toBe(0);
43 expect(wantedWarm({ ...base, purchases: 480, held: 1, perMachineCents: undefined })).toBe(1);
44 });
45 });
46
47 describe("the warm pool at the doors", () => {
48 let dataDir = "";
49 let app: App;
50 const place = "digitalocean:nyc3:s-1vcpu-2gb";
51 beforeAll(async () => {
52 dataDir = await mkdtemp(join(tmpdir(), "forge-warm-"));
53 app = createApp({ dataDir, port: 0 });
54 await seedPlaces(app.db);
55 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
56 if (!made.ok) throw new Error(made.error);
57 await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
58 app.db.run("INSERT INTO cloud_account (provider, name, summary) VALUES ('digitalocean', 'main', 'x')");
59 });
60 afterAll(async () => {
61 app.db.close();
62 await rm(dataDir, { recursive: true, force: true });
63 });
64 const admin = () => getUserByName(app.db, "alice")!;
65 const warm = () => {
66 const r = cloudOverview(app, admin());
67 if (!r.ok) throw new Error(r.error);
68 return r.value.accounts[0]!.warm;
69 };
70
71 test("an account shows no warm machine until one is set", () => {
72 expect(warm()).toEqual([]);
73 });
74 test("only an admin sets it, and only a whole count at a place of that cloud", () => {
75 const bob = getUserByName(app.db, "bob");
76 expect(setWarm(app, bob, "digitalocean", "main", place, 3)).toEqual({ ok: false, error: "not_found" });
77 expect(setWarm(app, admin(), "digitalocean", "main", place, 11).ok).toBe(false);
78 expect(setWarm(app, admin(), "digitalocean", "main", place, 1.5).ok).toBe(false);
79 expect(setWarm(app, admin(), "digitalocean", "main", "hetzner:nbg1:cx23", 1).ok).toBe(false);
80 expect(setWarm(app, admin(), "digitalocean", "main", "not a place", 1).ok).toBe(false);
81 expect(setWarm(app, admin(), "digitalocean", "nope", place, 1).ok).toBe(false);
82 expect(warm()).toEqual([]);
83 });
84 test("a set pool is shown, and a warm machine is counted against the ceiling and shown", () => {
85 expect(setWarm(app, admin(), "digitalocean", "main", place, 3).ok).toBe(true);
86 expect(warm()).toEqual([{ place, configured: 3, held: 0, wanted: 1, cents: 0 }]);
87 const before = cloudOverview(app, admin());
88 const spent = before.ok ? before.value.accounts[0]!.monthlyCents : -1;
89 app.db.run(
90 `INSERT INTO pinned_forge (id, name, target, account, app, source, version, config, remote, volume, state, created_at)
91 VALUES ('w1', 'warm-1', 'digitalocean', 'main', 'a/b', 'https://f.test/a/b', ?1, '{}', 'm1', 'v1', ?2, '2026-11-25T00:00:00Z')`,
92 ["a".repeat(40), WARM_STATE],
93 );
94 app.db.run("INSERT INTO pinned_size (pinned_id, size, datacenter) VALUES ('w1', 's-1vcpu-2gb', 'nyc3')");
95 const after = cloudOverview(app, admin());
96 const acct = after.ok ? after.value.accounts[0]! : undefined;
97 expect(acct?.warm[0]?.held).toBe(1);
98 expect(acct?.warm[0]?.cents).toBeGreaterThan(0);
99 expect(acct!.monthlyCents - spent).toBe(acct!.warm[0]!.cents);
100 });
101 test("setting it back to 0 stops wanting any", () => {
102 expect(setWarm(app, admin(), "digitalocean", "main", place, 0).ok).toBe(true);
103 expect(warm()[0]?.wanted).toBe(0);
104 });
105 });
106
107 describe("the warm pool through the MCP tool, the page and the terminal", () => {
108 let dataDir = "";
109 let app: App;
110 let servers: Servers;
111 let adminToken = "";
112 let bobToken = "";
113 const place = "digitalocean:nyc3:s-1vcpu-2gb";
114 beforeAll(async () => {
115 dataDir = await mkdtemp(join(tmpdir(), "forge-warm-doors-"));
116 app = createApp({ dataDir, port: 0 });
117 await seedPlaces(app.db);
118 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
119 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
120 if (!made.ok) throw new Error(made.error);
121 }
122 adminToken = createToken(app.db, getUserByName(app.db, "alice")!.id, "admin", "admin").token;
123 bobToken = createToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token;
124 app.db.run("INSERT INTO cloud_account (provider, name, summary) VALUES ('digitalocean', 'main', 'x')");
125 servers = await serve(app);
126 });
127 afterAll(async () => {
128 servers.stop();
129 app.close();
130 await rm(dataDir, { recursive: true, force: true });
131 });
132
133 const setWarmVia = async (token: string, args: Record<string, unknown>) => {
134 const res = await fetch(`${servers.url}/mcp`, {
135 method: "POST",
136 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
137 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "cloud_account", arguments: { verb: "set_warm", provider: "digitalocean", name: "main", ...args } } }),
138 });
139 const body = (await res.json()) as any;
140 return { error: body.error !== undefined || body.result.isError === true, text: String(body.error?.message ?? body.result.content[0].text) };
141 };
142 const held = () => app.db.query("SELECT target FROM warm_pool").all().map((r) => (r as { target: number }).target);
143
144 test("the MCP verb sets it for an admin scope, refuses another, and records the change", async () => {
145 expect((await setWarmVia(bobToken, { place, count: 2 })).error).toBe(true);
146 expect((await setWarmVia(adminToken, { place, count: 11 })).error).toBe(true);
147 expect(held()).toEqual([]);
148 const done = await setWarmVia(adminToken, { place, count: 2 });
149 expect(done.error).toBe(false);
150 expect(held()).toEqual([2]);
151 const ev = app.db.query("SELECT COUNT(*) AS n FROM event WHERE kind = 'cloud.warm_target'").get() as { n: number };
152 expect(ev.n).toBe(1);
153 });
154
155 test("Settings → Cloud shows each place as a labelled fact with its cost, and nothing without a pool", async () => {
156 const r = await fetch(`${servers.url}/signin`, { method: "POST", redirect: "manual", headers: { origin: servers.url }, body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }) });
157 const cookie = (r.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
158 const page = await (await fetch(`${servers.url}/settings/cloud`, { headers: { cookie } })).text();
159 expect(page).toContain(`Warm at ${place}`);
160 expect(page).toContain("0 kept now, at most 2, $0.00 a month");
161 expect(setWarm(app, getUserByName(app.db, "alice"), "digitalocean", "main", place, 0).ok).toBe(true);
162 app.db.run("DELETE FROM warm_pool");
163 const bare = await (await fetch(`${servers.url}/settings/cloud`, { headers: { cookie } })).text();
164 expect(bare).not.toContain("Warm at");
165 });
166
167 test("the terminal's Cloud accounts screen shows held, most and cost, and nothing without a pool", async () => {
168 const show = async () => {
169 const user = getUserByName(app.db, "alice")!;
170 const { app: tui } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user }, { terminal: headlessTerminal(160, 32), exitHooks: false });
171 tui.start();
172 const key = (k: string) => tui.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
173 tui.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
174 await settleApp(tui);
175 for (const ch of "Cloud accounts") key(ch);
176 await settleApp(tui);
177 key("enter");
178 await settleApp(tui);
179 const text = tui.screen.toText();
180 tui.stop();
181 return text;
182 };
183 expect(await show()).not.toContain("warm ");
184 expect(setWarm(app, getUserByName(app.db, "alice"), "digitalocean", "main", place, 2).ok).toBe(true);
185 const text = await show();
186 expect(text).toContain(`warm 0/2 ${place} $0.00 a month`);
187 });
188 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs