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

New forge: choose where it runs, here or an admin's cloud, free for a site admin #16496

Merged opened this

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

Merged

sold/new-forge-where → main 0 commits 6 threads · 0 unresolved

  • Merged. sold/new-forge-where was merged into main as f276869.

Review

Sign in to review this change.
8 files changed +540 −21
docs/features/client-forge.md +1 −1
@@ -14,7 +14,7 @@ it from there. Each step names the route or MCP tool that does it.
1414 The sender opens `/forges/new`, names the forge, picks the apps and presses
1515 Spawn. An assistant does the same with MCP tool `spawn`. To have the crew
1616 rebuild each forked app in the new forge so it behaves like its copy here,
17 tick "Rebuild them there" under More options; the terminal's New forge screen
17 tick "Rebuild them there" under More settings; the terminal's New forge screen
1818 has the field "Mode of the forked apps" (`migration`), and `spawn` takes
1919 `migration: true`. Each forked app then gets the direction "run natively here
2020 with parity to its copy" and its origin row. The answer holds one claim link,
docs/features/cloud.md +13
@@ -33,6 +33,19 @@ Not done: the route only lists. Attaching, rotating and removing stay on the pag
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.
3535
36 ## Where it runs, on New forge
37
38 A site admin who has attached a cloud account that allows writes sees "Where it runs" on `/forges/new` and on the terminal's New forge screen (`src/spawn/clouds_offered.ts`). Anyone else sees no such choice, and a cloud named in a request from a non-admin is refused.
39
40 - **Here** is the default: the forge runs inside this forge.
41 - **A cloud account** runs the forge on its own machine. It is free to the admin; the cloud bills its own account. The page says "No charge to you; the cloud bills its account."
42 - **Each cloud option** shows the catalog's default place for the size, its price a month and the account's room under its ceiling, for example "New York · $14.00 a month; $36.00 of $50 left this month".
43 - **Change place**, under the option, lists the other orderable places on that provider, cheapest first. Pick one to run there instead of the default.
44 - **A refused deploy** is shown with the reason, and the option cannot be selected. The reasons are no account that allows writes, or a place that would go over the account's ceiling. The message links to Cloud accounts, where the account and its ceiling are set.
45 - **Terminal**: the "Where it runs" field is chosen with left and right. The first choice is empty and means here. The others are `<provider>/<account>`, then `<provider>/<account>@<place>` for each other place. The same value is what the page posts as `where`.
46
47 A forge on a cloud keeps its plan out of it: the place is chosen under Where it runs, not under Plan.
48
3649 ## The warm pool (#16362)
3750
3851 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).
docs/features/forges-side-by-side.md +1 −1
@@ -12,7 +12,7 @@ The table is for comparing; the list below it stays for what needs doing (claim
1212
1313 ## The pages' shape (#9647)
1414
15 `/forges` is plain rows, no boxed cards: each forge's line starts with who it is for and the apps it was given, then its state (awake, size, spend, last activity, claim state). `/forges/new` asks the name, who it is for, what it is for, the apps and an optional fresh app up front; follow mode, crew, owner access, AI account key, API base URL, budget, template and size sit behind "More options", inside the same form so they submit as before. The disclosure opens by itself when the door refuses a value in one of them. No field or action was removed. The terminal's forge form keeps its fields; its key field is labelled "AI account key", as on the page (#10787).
15 `/forges` is plain rows, no boxed cards: each forge's line starts with who it is for and the apps it was given, then its state (awake, size, spend, last activity, claim state). `/forges/new` asks the name, who it is for, what it is for, the apps and an optional fresh app up front; follow mode, crew, owner access, AI account key, API base URL, budget, template and size sit behind "More settings", inside the same form so they submit as before. The disclosure opens by itself when the door refuses a value in one of them. No field or action was removed. The terminal's forge form keeps its fields; its key field is labelled "AI account key", as on the page (#10787).
1616
1717 ## This month's cost (#12275)
1818
src/spawn/clouds_offered.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * Where a new forge can run, as "+ New forge" offers it (#16394): here, as a hosted child, or on a
3 * cloud account an admin attached that allows writes, at the catalog's default place or another
4 * it lists (`cloud/places.ts`, one price path). Only a site admin is offered a cloud: the door
5 * makes an admin's forge there as a $0 order (`spawn/making.ts`), whatever the plan or place.
6 * Each offer says the account's room under its ceiling, and the deploy's own refusal when the
7 * default place would not fit, so the form says it before anything is made.
8 */
9
10 import type { App } from "../app.ts";
11 import { defaultPlace, deployPlaces, deployRoom } from "../actions/pinned.ts";
12 import { spendOf, type Spend } from "../cloud/ceiling.ts";
13 import type { Place, PlanName } from "../cloud/places.ts";
14 import { dollars } from "../cloud/prices.ts";
15 import { target } from "../cloud/targets.ts";
16 import { listCloudAccounts } from "../core/cloud_account.ts";
17 import type { User } from "../core/users.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19
20 export interface CloudOffer {
21 /** `provider/account`: the `where` a form posts. */
22 readonly key: string;
23 readonly provider: string;
24 readonly account: string;
25 /** The provider's name, as people know it: "DigitalOcean". */
26 readonly label: string;
27 /** The catalog's default place for the size; none when the catalog has not been read. */
28 readonly place: Place | undefined;
29 /** Every orderable place on the provider for the size, cheapest first. */
30 readonly places: readonly Place[];
31 readonly spend: Spend;
32 /** Why the default place would be refused now, in the deploy's words; undefined when it fits. */
33 readonly refusal: string | undefined;
34 }
35
36 /** A `where` value: `provider/account`, then `@<place id>` when a place other than the default is chosen. */
37 export function parseWhere(
38 raw: string,
39 ): { provider: string; account: string; place: string } | undefined {
40 const m =
41 /^([a-z]+)\/([a-z][a-z0-9_]{0,31})(?:@([a-z0-9:._-]{1,200}))?$/.exec(
42 raw.trim(),
43 );
44 return m === null
45 ? undefined
46 : { provider: m[1]!, account: m[2]!, place: m[3] ?? "" };
47 }
48
49 /** The one line a cloud choice says about cost: the price is on the option, the bill is the cloud's. */
50 export const NO_CHARGE = "No charge to you; the cloud bills its account.";
51
52 /**
53 * What a `where` sends the door, the one place control for each case: here sends `place` (a paid
54 * plan's, chosen under Plan); a cloud names its account and only the place chosen with it, never
55 * `place`. A `where` that does not parse is refused here, never sent on.
56 */
57 export function whereFields(where: string, place: string): Result<Record<string, string>, string> {
58 if (where === "") return ok(place === "" ? {} : { place });
59 const at = parseWhere(where);
60 if (at === undefined) return err("must be here, or a cloud account offered here, as provider/account");
61 return ok({ target: at.provider, account: at.account, ...(at.place === "" ? {} : { place: at.place }) });
62 }
63
64 /** One line on a `where` choice: here, or the cloud at its place with its room, or why it is refused. */
65 export function whereHint(o: CloudOffer | undefined, placeId = ""): string {
66 if (o === undefined) return "Here: inside this forge.";
67 if (o.refusal !== undefined) return o.refusal;
68 const at = o.places.find((p) => p.id === placeId) ?? o.place;
69 return `${o.label}${at === undefined ? "" : ` · ${placeWords(at)}`}; ${roomWords(o.spend)}. ${NO_CHARGE}`;
70 }
71
72 /** Each offer's `where` values: its default place, then (unless refused) each other place. */
73 export const whereChoices = (offers: readonly CloudOffer[]): string[] =>
74 offers.flatMap((o) => [o.key, ...(o.refusal !== undefined ? [] : o.places.filter((p) => p.id !== o.place?.id).map((p) => `${o.key}@${p.id}`))]);
75
76 /** "$36.00 of $50 left this month". */
77 export const roomWords = (s: Spend): string =>
78 `${dollars(Math.max(0, s.leftCents))} of $${s.ceilingDollars} left this month`;
79
80 /** "New York · $14.00 a month". */
81 export const placeWords = (p: Place): string =>
82 `${p.city} · ${dollars(p.costCents)} a month`;
83
84 /** The clouds `user` may start a forge on, for a forge of `size`: none for anyone but a site admin. */
85 export function cloudsOffered(
86 app: App,
87 user: User | undefined,
88 size: PlanName = "small",
89 ): CloudOffer[] {
90 if (user?.isAdmin !== true) return [];
91 return listCloudAccounts(app.db)
92 .filter((a) => a.writeAllowed && target(a.provider)?.status === "first")
93 .map((a) => ({
94 key: `${a.provider}/${a.name}`,
95 provider: a.provider,
96 account: a.name,
97 label: target(a.provider)?.label ?? a.provider,
98 place: defaultPlace(app, a.provider, size).place,
99 places: deployPlaces(app, [a.provider], size),
100 spend: spendOf(app.db, a.provider, a.name),
101 refusal: deployRoom(app, a.provider, a.name, size),
102 }));
103 }
src/tui/screens/newforge.ts +28 −10
@@ -18,6 +18,7 @@ import { starterBudgetField } from "../../settings/starter_budget.ts";
1818 import { MAX_BUDGET_USD, MIN_BUDGET_USD } from "../../spawn/plan.ts";
1919 import { listRecipes, saveRecipe } from "../../spawn/recipes.ts";
2020 import { placeChoice } from "../../spawn/making.ts";
21 import { cloudsOffered, parseWhere, whereChoices, whereFields, whereHint } from "../../spawn/clouds_offered.ts";
2122 import { FREE, getPlan, getPlans } from "../../settings/plans.ts";
2223 import type { Ctx, Screen } from "../app/app.ts";
2324 import { binding } from "../app/keys.ts";
@@ -60,7 +61,8 @@ const SPECS: readonly Spec[] = [
6061
6162 /** An admin's: a paid plan runs where paid forges run, at the place chosen (`spawn/making.ts`). */
6263 const PLAN_SPEC: Spec = { key: "plan", label: "Plan", hint: "Free (default) or a paid plan, which runs where paid forges run. Left and right choose.", choices: [""] };
63 const PLACE_SPEC: Spec = { key: "place", label: "Where it runs", hint: "", choices: [""] };
64 const PLACE_SPEC: Spec = { key: "place", label: "Place", hint: "", choices: [""] };
65 const WHERE_SPEC: Spec = { key: "where", label: "Where it runs", hint: "", choices: [""] };
6466
6567 const RECIPE_SPEC: Spec = { key: "recipe", label: "Spawn from recipe", hint: "Left and right choose one of yours; its apps and budget replace the fields above.", choices: [""] };
6668
@@ -85,19 +87,32 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
8587 );
8688 // Your saved recipes, by name: only a signed-in person has any.
8789 const recipes = f.user === undefined ? [] : listRecipes(f.app.config.dataDir, f.user.id).map((r) => r.name);
90 // An admin's clouds, as the page's "Where it runs" (`spawn/clouds_offered.ts`): free, at any place.
91 const offers = cloudsOffered(f.app, f.user);
92 const paid = f.user?.isAdmin === true && getPlans(f.app.db).some((p) => p.key !== FREE);
8893 const specs = [
89 ...SPECS.map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s)),
94 ...SPECS.slice(0, 1),
95 ...(offers.length === 0 ? [] : [{ ...WHERE_SPEC, choices: ["", ...whereChoices(offers)] }]),
96 ...SPECS.slice(1).map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s)),
9097 ...(recipes.length === 0 ? [] : [{ ...RECIPE_SPEC, choices: ["", ...recipes] }]),
91 ...(f.user?.isAdmin === true && getPlans(f.app.db).some((p) => p.key !== FREE)
92 ? [{ ...PLAN_SPEC, choices: ["", ...getPlans(f.app.db).filter((p) => p.key !== FREE).map((p) => p.key)] }, PLACE_SPEC]
93 : []),
98 // A paid plan's place, for a forge here; a cloud's place is chosen with the cloud, under Where.
99 ...(paid ? [{ ...PLAN_SPEC, choices: ["", ...getPlans(f.app.db).filter((p) => p.key !== FREE).map((p) => p.key)] }, PLACE_SPEC] : []),
94100 ];
95101 /** Where a paid plan's forge may run: the default first, then the catalog's places for its size. */
96102 const where = () => placeChoice(f.app, getPlan(f.app.db, values["plan"] ?? ""), true);
97103 const choicesOf = (spec: Spec): readonly string[] | undefined =>
98104 spec.key === "place" ? ["", ...(where()?.places.map((p) => p.id) ?? [])] : spec.choices;
99 const hintOf = (spec: Spec): string =>
100 spec.key === "template" ? templateHint(values["template"] || DEFAULT_TEMPLATE) : spec.key === "place" ? (where()?.says ?? "A free forge runs inside this forge.") : spec.hint;
105 const chosenCloud = () => {
106 const at = parseWhere(values["where"] ?? "");
107 return whereHint(offers.find((o) => o.key === `${at?.provider}/${at?.account}`), at?.place);
108 };
109 /** The hint of a field whose words follow its value; any other says its own. */
110 const hints: Readonly<Record<string, () => string>> = {
111 template: () => templateHint(values["template"] || DEFAULT_TEMPLATE),
112 where: chosenCloud,
113 place: () => where()?.says ?? "A free forge runs inside this forge.",
114 };
115 const hintOf = (spec: Spec): string => hints[spec.key]?.() ?? spec.hint;
101116 const starter = starterBudgetField(f.app.db);
102117 const values: Record<string, string> = { budgetUsd: starter, ...initial };
resolved by ·
Show 1 comment
outdated

Nested ternaries with a ?? that binds oddly: the cloud() === undefined ? where()?.says : ... falls back to the free text only when says is undefined. Pull this into a small hintOf per key or a lookup. Also untested (see body).

103118 // The prefilled budget is replaced by the first thing typed, never appended to ('20' is not
@@ -124,7 +139,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
124139 return at < 0 ? a : { repo: a.slice(0, at), mode: a.slice(at + 1) };
125140 });
126141
127 const request = (dryRun: boolean): Record<string, unknown> => {
142 const request = (dryRun: boolean, where: Record<string, string>): Record<string, unknown> => {
128143 return {
129144 name: val("name"),
130145 ...(val("recipe") === "" ? { apps: appsOf() } : { recipe: val("recipe") }),
@@ -143,7 +158,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
143158 // Blank is the default: it is not recorded, as on the page.
144159 ...(val("template") === "" || val("template") === DEFAULT_TEMPLATE ? {} : { template: val("template") }),
145160 ...(val("plan") === "" ? {} : { plan: val("plan") }),
146 ...(val("place") === "" ? {} : { place: val("place") }),
161 ...where,
147162 dryRun,
148163 };
149164 };
@@ -171,7 +186,10 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
171186 if (kept === undefined || !kept.ok)
172187 return { status: 422, body: { error: "invalid", message: `saveAs: ${kept === undefined ? "sign in to save a recipe" : kept.error.reason}` } };
173188 }
174 return spawnDoor(hctx, f.user, request(dryRun));
189 // One place control for each case, as on the page; a `where` that does not parse is refused here.
190 const at = whereFields(val("where"), val("place"));
191 if (!at.ok) return { status: 422, body: { error: "invalid", message: `where: ${at.error}` } };
192 return spawnDoor(hctx, f.user, request(dryRun, at.value));
175193 };
176194
177195 const refuse = (body: Record<string, unknown>): void => {
src/web/pages/new-forge.ts +57 −6
@@ -53,6 +53,9 @@ import { FREE, getPlans, type Plan } from "../../settings/plans.ts";
5353 import { linkToSend, madeBody, madeJs } from "../forge_made.ts";
5454 import { pickList } from "../pick.ts";
5555 import { btn, field as formField, selectField } from "../ui.ts";
56 import { cloudsOffered, NO_CHARGE, placeWords, roomWords, whereFields, type CloudOffer } from "../../spawn/clouds_offered.ts";
57 import { catalogPlan } from "../../spawn/cloud_placement.ts";
58 import { CEILING_PAGE } from "../../cloud/ceiling.ts";
5659
5760 interface Values {
5861 readonly name: string;
@@ -79,6 +82,8 @@ interface Values {
7982 readonly giftPlan: string;
8083 /** A Places id (`spawn/making.ts`); empty for the plan's default. */
8184 readonly place: string;
85 /** "Where it runs": empty for here, else an admin's `provider/account[@place]` (`spawn/clouds_offered.ts`). */
86 readonly where: string;
8287 /** The last post carried a key: it is never sent back, so it is asked for again. */
8388 readonly hadKey: boolean;
8489 }
@@ -103,10 +108,11 @@ const EMPTY: Values = {
103108 plan: "",
104109 giftPlan: "",
105110 place: "",
111 where: "",
106112 hadKey: false,
107113 };
108114
109 /** The fields behind "More options": an error on one opens it. */
115 /** The fields behind "More settings": an error on one opens it. */
110116 const MORE_FIELDS = ["followMode", "crew", "keepAccess", "migration", "modelKey", "modelEndpoint", "budgetUsd", "size"];
111117
112118 type Errors = Partial<Record<string, string>>;
@@ -259,6 +265,10 @@ function formView(
259265 const includedUsd = limitValue(ctx.app.db, "spawn.included_credit_usd");
260266 const askUsd = limitValue(ctx.app.db, "billing.ask_cents") / 100;
261267 const freshErr = freshError(errors, repos.length);
268 // A place error is the control's that chose it: "Where it runs" on a cloud, the plan's list here.
269 const onCloud = values.where !== "";
270 const whereErr = errors["where"] ?? errors["target"] ?? errors["account"] ?? (onCloud ? errors["place"] : undefined);
271 const placeErr = onCloud ? undefined : errors["place"];
262272 const lead = repos.length === 0 ? "Pick a name, and say what it is for if you like" : "Pick a name and the apps to start from";
263273 return html`<div class="narrow-wide" data-forges>
264274 ${pageHead("New forge", {
@@ -268,7 +278,7 @@ function formView(
268278 })}
269279 ${quota ? html`<p role="status" id="quota-full">This forge has no room for another forge: ${quota}.</p>` : null}
270280 ${errors["form"]
271 ? html`<p class="error mb" role="alert">${errors["form"]}</p>`
281 ? html`<p class="error mb" role="alert">${errors["form"]}${values.where !== "" ? html` <a href="${CEILING_PAGE}">Cloud accounts</a>` : null}</p>`
272282 : null}
273283 ${plan}
274284 ${recipesView(recipes, errors)}
@@ -284,6 +294,7 @@ function formView(
284294 hint: `Its address: <name>--${childHost(ctx.app)}. Lowercase letters, digits and dashes.`,
285295 ...(errors["name"] ? { error: errors["name"] } : {}),
286296 })}
297 ${whereView(cloudsOffered(ctx.app, user, catalogPlan(values.size)), values.where, whereErr)}
287298 ${anon
288299 ? null
289300 : formField({
@@ -337,7 +348,7 @@ function formView(
337348 ${errors["template"] ? html`<span class="error" id="f-template-err">${errors["template"]}</span>` : null}
338349 </fieldset>
339350 <details class="disclosure" ${Object.keys(errors).some((k) => MORE_FIELDS.includes(k)) ? html`open` : null}>
340 <summary>More options</summary>
351 <summary>More settings</summary>
341352 <fieldset class="field" ${errors["followMode"] ? html`data-invalid` : null}>
342353 <legend>How it follows this forge's code</legend>
343354 <label class="check">
@@ -443,7 +454,7 @@ function formView(
443454 </details>
444455 ${codeField(values.code, errors["code"])}
445456 ${planField(plans, user, values.plan, errors["plan"])}
446 ${placeChoiceView(placeChoice(ctx.app, plans.find((p) => p.key === (values.plan || values.giftPlan)), user?.isAdmin === true), values.place, errors["place"])}
457 ${placeChoiceView(placeChoice(ctx.app, plans.find((p) => p.key === (values.plan || values.giftPlan)), user?.isAdmin === true), values.place, placeErr)}
447458 ${anon
448459 ? null
449460 : html`<details class="field"${values.saveAs !== "" || errors["recipe"] ? html` open` : null}>
@@ -654,7 +665,9 @@ const asBool = (form: Form, name: string): boolean =>
654665 * about a forge started from this one.
655666 */
656667 function fromPack(ctx: Ctx, user: User | undefined): Partial<Values> {
657 const pack = getPack(ctx.app.db, ctx.url.searchParams.get("pack") ?? "");
668 // No pack asked for reads nothing: the page's statements stay a handful (test/new-forge-pick-150).
669 const asked = ctx.url.searchParams.get("pack") ?? "";
670 const pack = asked === "" ? undefined : getPack(ctx.app.db, asked);
658671 if (pack === undefined) return {};
659672 const apps = resolveRepos(ctx.app.db, pack, user).filter((r) => r.left === undefined).map((r) => r.full);
660673 return { apps, direction: pack.brief.slice(0, MAX_DIRECTION_CHARS) };
@@ -729,6 +742,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
729742 plan: field(form, "plan").trim().slice(0, 40),
730743 giftPlan: "",
731744 place: field(form, "place").trim().slice(0, 200),
745 where: field(form, "where").trim().slice(0, 260),
732746 hadKey: field(form, "modelKey").trim() !== "",
733747 };
734748 const key = field(form, "modelKey").trim();
@@ -746,6 +760,8 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
746760 saved = kept.value.name;
747761 }
748762 const recipe = field(form, "recipe").trim();
763 const at = whereFields(values.where, values.place);
764 if (!at.ok) return page({ ctx, title: "New forge", keyboardResizes: true, body: formView(ctx, user, values, { where: at.error }, null, await readsFor(ctx, user)) }, 422);
749765 const door = await spawnDoor(ctx, user, {
750766 name: values.name,
751767 // A recipe carries its own apps, modes and budget; the form's are not mixed in.
@@ -771,7 +787,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
771787 ...(values.template === DEFAULT_TEMPLATE ? {} : { template: values.template }),
772788 ...(values.code === "" ? {} : { code: values.code }),
773789 ...(values.plan === "" ? {} : { plan: values.plan }),
774 ...(values.place === "" ? {} : { place: values.place }),
790 ...at.value,
775791 dryRun: planOnly,
776792 }, { page: true });
777793 if (door.status === 404 && door.body["error"] === "unknown_template")
@@ -837,6 +853,41 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
837853 return response;
838854 }
839855
856 /**
857 * "Where it runs", for a site admin with a cloud account attached: here, or a cloud at its default
858 * place and price, with the account's room under its ceiling; "Change place" lists the catalog's
859 * other places. A cloud the deploy would refuse is shown, not offered, with why and the setting.
resolved by ·
Show 1 comment
outdated

Principle 1 / one way to do it: the chosen @place overrides the form's own place here without telling the person. Two controls, one winner. Make a single place control and delete the other for the cloud case.

860 */
861 function whereView(offers: readonly CloudOffer[], chosen: string, error: string | undefined): Html | null {
862 // A cloud posted by someone offered none is refused in the door's words, never lost.
863 if (offers.length === 0) return error ? html`<p class="error" role="alert">${error}</p>` : null;
864 const radio = (value: string, refused = false) =>
865 html`<input type="radio" name="where" value="${value}"${chosen === value ? html` checked` : null}${refused ? html` disabled` : null} />`;
866 const offer = (o: CloudOffer) => {
867 const others = o.places.filter((p) => p.id !== o.place?.id);
868 return html`<label class="check">
869 ${radio(o.key, o.refusal !== undefined)}
870 <span>${o.label}${o.place === undefined ? null : ` · ${placeWords(o.place)}`} <span class="muted small">${roomWords(o.spend)}</span></span>
871 </label>
872 ${o.refusal === undefined
873 ? null
874 : html`<p class="error small" data-where-refused>${o.refusal} <a href="${CEILING_PAGE}">Cloud accounts</a></p>`}
875 ${o.refusal !== undefined || others.length === 0
876 ? null
resolved by ·
Show 1 comment
outdated

Principle 1 and 8: the page says the price three times ("· $14.00 a month", the room line, and "Free for a site admin" under the fieldset). Say the free part once, and in plain words ("No charge to you; the cloud bills its account"). "Ceiling" and "held to" come from the deploy: check them against docs/WRITING.md.

877 : html`<details class="field"${chosen.startsWith(`${o.key}@`) ? html` open` : null}>
878 <summary class="small">Change place</summary>
879 ${others.map((p) => html`<label class="check">${radio(`${o.key}@${p.id}`)} <span class="small">${placeWords(p)}</span></label>`)}
880 </details>`}`;
881 };
882 return html`<fieldset class="field" id="f-where" data-where ${error ? html`data-invalid` : null}>
883 <legend>Where it runs</legend>
884 <label class="check">${radio("")} <span>Here <span class="muted small">inside this forge</span></span></label>
885 ${offers.map(offer)}
886 <span class="muted small">${NO_CHARGE}</span>
887 ${error ? html`<span class="error" role="alert">${error}</span>` : null}
888 </fieldset>`;
889 }
890
840891 /** An admin's plan for the new forge: a paid one runs where paid forges run. Only with paid plans. */
841892 function planField(plans: readonly Plan[], user: User | undefined, chosen: string, error: string | undefined): Html | null {
842893 if (user?.isAdmin !== true || plans.every((p) => p.key === FREE)) return null;
test/new-forge-clouds.test.ts added +334
@@ -0,0 +1,334 @@
1 /**
2 * "Where it runs" on /forges/new (#16394): a site admin is offered here or each attached cloud
3 * account that allows writes, at the catalog's default place and price, with the account's room
4 * under its ceiling and the catalog's other places behind "Change place". An admin's cloud forge is
5 * free: the door writes a $0 order and the page goes to its making page, with no checkout. A cloud
6 * the ceiling would refuse is shown with the refusal and the way to the setting. Anyone else sees
7 * the form as before, and "Here" posts what the form posted before. A recorded fetch stands in for
8 * DigitalOcean.
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import {
16 addAccount,
17 allowWrite,
18 net as cloudNet,
19 } from "../src/actions/cloud.ts";
20 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
21 import { makingWatch, reconcileOrder } from "../src/actions/order.ts";
22 import { changeBaseDomain, net } from "../src/actions/pinned.ts";
23 import { createRepo } from "../src/actions/repos.ts";
24 import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts";
25 import { getOrder } from "../src/billing/orders.ts";
26 import { getPinned } from "../src/core/pinned.ts";
27 import { createUser, getUserByName, type User } from "../src/core/users.ts";
28 import type { Ctx } from "../src/http/context.ts";
29 import { ok } from "../src/kernel/result.ts";
30 import { usePlacement } from "../src/spawn/door.ts";
31 import { cloudsOffered, NO_CHARGE, parseWhere, whereChoices, whereFields, whereHint } from "../src/spawn/clouds_offered.ts";
32 import { newForgePage, newForgeSubmit } from "../src/web/pages/new-forge.ts";
33 import { pricingDone } from "../src/web/pages/pricing.ts";
34 import { quietLogs } from "./helpers/globals.ts";
35 import { seedPlaces } from "./helpers/places-fixture.ts";
36
37 quietLogs();
38 makingWatch.tries = 0;
39
40 const COMMIT = "d".repeat(40);
41 const NYC = "digitalocean:nyc3:s-1vcpu-2gb";
42 const AMS = "digitalocean:ams3:s-1vcpu-2gb";
43
44 describe("/forges/new: where it runs", () => {
45 let dir = "";
46 let app: App;
47 let checkouts = 0;
48 let hosted = 0;
49 const up = new Set<string>();
50 const before = process.env["FORGE_COMMIT"];
51 const admin = () => getUserByName(app.db, "alice")!;
52 const bob = () => getUserByName(app.db, "bob")!;
53 const fake: CheckoutProvider = {
54 name: "fake",
55 create: async () =>
56 ok({ id: `cs_${++checkouts}`, url: "https://pay.fake.test/x" }),
57 state: async () => ok({ paid: false, customer: "c", subscription: "s" }),
58 };
59 const ctxOf = (
60 user: User | undefined,
61 path: string,
62 init?: RequestInit,
63 ): Ctx =>
64 ({
65 app,
66 request: new Request(`https://forge.test${path}`, init),
67 url: new URL(`https://forge.test${path}`),
68 params: {},
69 auth: {
70 user,
71 scope: user === undefined ? undefined : "admin",
72 via: "none",
73 },
74 theme: undefined,
75 }) as Ctx;
76 const page = async (user: User) =>
77 (await newForgePage(ctxOf(user, "/forges/new"))).text();
78 const submit = (user: User, form: Record<string, string>) =>
79 newForgeSubmit(
80 ctxOf(user, "/forges/new", {
81 method: "POST",
82 headers: {
83 origin: "https://forge.test",
84 "content-type": "application/x-www-form-urlencoded",
85 },
86 body: new URLSearchParams(form),
87 }),
88 );
89
90 beforeAll(async () => {
91 process.env["FORGE_COMMIT"] = COMMIT;
92 dir = await mkdtemp(join(tmpdir(), "forge-new-forge-clouds-"));
93 app = createApp({
94 dataDir: dir,
95 port: 0,
96 forgeRepo: "alice/forge",
97 url: "https://forge.test",
98 });
99 useCheckout(app, fake);
100 usePlacement(app, {
101 place: async (plan) => (
102 ++hosted,
103 ok({
104 url: `https://${plan.name}.hosted.test`,
105 bodyId: `fake-${hosted}`,
106 })
107 ),
108 retire: async () => ok(),
109 });
110 await seedPlaces(app.db);
111 const a = await createUser(app.db, {
112 origin: "seed",
113 trusted: true,
114 username: "alice",
115 email: "[email protected]",
116 password: "a-good-passphrase",
117 adminIfFirst: true,
118 });
119 if (!a.ok) throw new Error(a.error);
120 const b = await createUser(app.db, {
121 origin: "seed",
122 trusted: true,
123 username: "bob",
124 email: "[email protected]",
125 password: "a-good-passphrase",
126 });
127 if (!b.ok) throw new Error(b.error);
128 if (
129 !(await createRepo(app, a.value, { name: "forge", visibility: "public" }))
130 .ok
131 )
132 throw new Error("repo");
133 cloudNet.fetch = async () =>
134 new Response(
135 JSON.stringify({ account: { email: "[email protected]", status: "active" } }),
136 { status: 200 },
137 );
138 const added = await addAccount(
139 app,
140 admin(),
141 "digitalocean",
142 "main",
143 "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5",
144 );
145 if (!added.ok) throw new Error(String(added.error));
146 allowWrite(app, admin(), "digitalocean", "main", true);
147 expect(setCeiling(app, admin(), "digitalocean", "main", 50).ok).toBe(true);
148 expect(changeBaseDomain(app, admin(), "forges.test").ok).toBe(true);
149 const json = (o: unknown, status = 200) =>
150 new Response(JSON.stringify(o), { status });
151 let droplets = 3000;
152 net.fetch = async (url, init) => {
153 const u = new URL(url);
154 const method = init?.method ?? "GET";
155 if (u.pathname.endsWith("/volumes"))
156 return json({ volume: { id: "vol-1" } }, 201);
157 if (u.pathname.endsWith("/account/keys"))
158 return json({ ssh_key: { id: 4242 } }, 201);
159 if (method === "DELETE") return new Response(null, { status: 204 });
160 if (method === "POST") return json({ droplet: { id: ++droplets } }, 202);
161 const id = Number(u.pathname.split("/").at(-1));
162 return json({
163 droplet: {
164 id,
165 status: "active",
166 networks: {
167 v4: [{ type: "public", ip_address: `203.0.113.${id % 250}` }],
168 },
169 },
170 });
171 };
172 net.resolve = async (host) => {
173 const p = getPinned(app.db, host.split(".")[0]!);
174 return p !== undefined && up.has(p.name) ? [p.address] : [];
175 };
176 net.probe = async (url) =>
177 String(url).includes("/api/v1/first-admin/claim")
178 ? json({ state: "waiting" })
179 : new Response("ok", { status: 200 });
180 }, 30_000);
181
182 afterAll(async () => {
183 if (before === undefined) delete process.env["FORGE_COMMIT"];
184 else process.env["FORGE_COMMIT"] = before;
185 app.close();
186 await rm(dir, { recursive: true, force: true });
187 });
188
189 test("a where value names an account and, after @, a place", () => {
190 expect(parseWhere("digitalocean/main")).toEqual({
191 provider: "digitalocean",
192 account: "main",
193 place: "",
194 });
195 expect(parseWhere(`digitalocean/main@${AMS}`)).toEqual({
196 provider: "digitalocean",
197 account: "main",
198 place: AMS,
199 });
200 for (const bad of ["", "main", "DigitalOcean/main", "digitalocean/main@"])
201 expect(parseWhere(bad)).toBeUndefined();
202 });
203
204 test("an admin is offered here and the cloud at its default place and price, its room, and the other places", async () => {
205 const html = await page(admin());
206 const where = html.slice(
207 html.indexOf('id="f-where"'),
208 html.indexOf("</fieldset>", html.indexOf('id="f-where"')),
209 );
210 expect(where).toContain("<legend>Where it runs</legend>");
211 expect(where).toMatch(/name="where" value="" checked/);
212 expect(where).toContain('value="digitalocean/main"');
213 expect(where).toMatch(/DigitalOcean · New York · \$\d+\.\d\d a month/);
214 expect(where).toContain("$50.00 of $50 left this month");
215 expect(where).toContain('<summary class="small">Change place</summary>');
216 expect(where).toContain(`value="digitalocean/main@${AMS}"`);
217 expect(where).toContain(NO_CHARGE);
218 expect(where.split("a month").length - 1).toBe(2);
219 // Right after the name; Template stays on the first screen, the optional rest under More settings.
220 expect(html.indexOf('name="name"')).toBeLessThan(
221 html.indexOf('id="f-where"'),
222 );
223 expect(html.indexOf('name="template"')).toBeLessThan(
224 html.indexOf("<summary>More settings</summary>"),
225 );
226 });
227
228 test("one place control each: here sends the plan's place, a cloud only its own, and a bad where is refused, never sent", () => {
229 expect(whereFields("", "")).toEqual({ ok: true, value: {} });
230 expect(whereFields("", NYC)).toEqual({ ok: true, value: { place: NYC } });
231 expect(whereFields("digitalocean/main", AMS)).toEqual({ ok: true, value: { target: "digitalocean", account: "main" } });
232 expect(whereFields(`digitalocean/main@${AMS}`, NYC)).toEqual({ ok: true, value: { target: "digitalocean", account: "main", place: AMS } });
233 expect(whereFields("nowhere", "")).toMatchObject({ ok: false });
234 });
235
236 test("the terminal's where hints and choices are the page's", () => {
237 const [o] = cloudsOffered(app, admin());
238 expect(whereHint(undefined)).toBe("Here: inside this forge.");
239 expect(whereHint(o)).toMatch(/^DigitalOcean · New York · \$\d+\.\d\d a month; \$[\d.]+ of \$\d+ left this month\. No charge to you/);
240 expect(whereHint(o, AMS)).toContain("Amsterdam");
241 expect(whereChoices([o!])).toEqual(["digitalocean/main", `digitalocean/main@${AMS}`]);
242 expect(whereHint({ ...o!, refusal: "held" })).toBe("held");
243 expect(whereChoices([{ ...o!, refusal: "held" }])).toEqual(["digitalocean/main"]);
244 expect(cloudsOffered(app, bob())).toEqual([]);
245 });
246
247 test("a bad where on the page is refused in words beside the choice, and nothing is made", async () => {
248 const res = await submit(admin(), { name: "badwhere", where: "nowhere" });
249 expect(res.status).toBe(422);
250 expect(await res.text()).toContain("must be here, or a cloud account offered here");
251 expect(getPinned(app.db, "badwhere")).toBeUndefined();
252 });
253
254 test("anyone else sees no cloud: the form is as before", async () => {
255 const html = await page(bob());
256 expect(html).not.toContain('name="where"');
257 expect(html).not.toContain("DigitalOcean");
258 expect(html).not.toContain("left this month");
259 });
260
261 test("Here posts what the form posted before: a hosted plan, no cloud", async () => {
262 const res = await submit(admin(), {
263 name: "herefirst",
264 where: "",
265 do: "plan",
266 });
267 const html = await res.text();
268 expect(res.status).toBe(200);
269 expect(html).toContain('id="plan"');
270 expect(html).not.toContain("data-runs-on");
271 });
272
273 test("a non-admin who posts a cloud anyway is refused in the door's words, and nothing is made", async () => {
274 const res = await submit(bob(), {
275 name: "bobcloud",
276 where: "digitalocean/main",
277 });
278 expect(res.status).toBe(422);
279 expect(await res.text()).toContain(
280 "only a site admin names the cloud account",
281 );
282 expect(getPinned(app.db, "bobcloud")).toBeUndefined();
283 });
284
285 test("an admin's cloud forge at a chosen place is a $0 order with no checkout, and goes to its making page with the claim link", async () => {
286 const n = checkouts;
287 const res = await submit(admin(), {
288 name: "freecloud",
289 where: `digitalocean/main@${AMS}`,
290 });
291 expect(res.status).toBe(303);
292 const to = res.headers.get("location") ?? "";
293 expect(to).toStartWith("/pricing/done?order=");
294 expect(checkouts).toBe(n);
295 const id = new URL(to, "https://forge.test").searchParams.get("order")!;
296 const o = getOrder(app.db, id)!;
297 expect(o).toMatchObject({
298 name: "freecloud",
299 priceUsd: 0,
300 state: "making",
301 });
302 expect(getPinned(app.db, "freecloud")).toMatchObject({
303 target: "digitalocean",
304 account: "main",
305 datacenter: "ams3",
306 });
307 const cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
308 up.add("freecloud");
309 app.db.query("UPDATE forge_order SET updated_at = 0 WHERE id = ?1").run(id);
310 await reconcileOrder(app, id);
311 const done = await (
312 await pricingDone(ctxOf(undefined, to, { headers: { cookie } }))
313 ).text();
314 expect(done).toContain("freecloud.forges.test/first-admin#");
315 });
316
317 test("a cloud the ceiling would refuse is shown, not offered, with the refusal and the setting; a post anyway is refused with the link", async () => {
318 expect(setCeiling(app, admin(), "digitalocean", "main", 1).ok).toBe(true);
319 const html = await page(admin());
320 expect(html).toMatch(/name="where" value="digitalocean\/main" disabled/);
321 expect(html).toContain("data-where-refused");
322 expect(html).toContain("is held to $1 a month");
323 expect(html).toContain('href="/settings/cloud">Cloud accounts</a>');
324 const res = await submit(admin(), {
325 name: "overcap",
326 where: `digitalocean/main@${NYC}`,
327 });
328 const body = await res.text();
329 expect(res.status).toBeGreaterThanOrEqual(400);
330 expect(body).toContain("is held to $1 a month");
331 expect(body).toContain('href="/settings/cloud">Cloud accounts</a>');
332 expect(getPinned(app.db, "overcap")).toBeUndefined();
333 });
334 });
test/new-forge.test.ts +3 −3
@@ -386,7 +386,7 @@ describe("+ New forge", () => {
386386 });
387387 });
388388
389 describe("/forges/new: More options (#9647)", () => {
389 describe("/forges/new: More settings (#9647)", () => {
390390 let dir = "";
391391 let app: App;
392392 let servers: Servers;
@@ -413,13 +413,13 @@ describe("/forges/new: More options (#9647)", () => {
413413 const html = await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text();
414414 expect(opening(html)).not.toContain("open");
415415 const form = html.slice(html.indexOf('id="new-forge"'));
416 const more = form.slice(form.indexOf("<summary>More options</summary>"), form.indexOf("</details>"));
416 const more = form.slice(form.indexOf("<summary>More settings</summary>"), form.indexOf("</details>"));
417417 expect(more.length).toBeGreaterThan(0);
418418 for (const name of ["followMode", "keepAccess", "modelKey", "modelEndpoint", "budgetUsd", "size"])
419419 expect(more).toContain(`name="${name}"`);
420420 expect(form.indexOf("</details>")).toBeLessThan(form.indexOf("</form>"));
421421 // The visible fields stay out of it.
422 expect(form.indexOf('name="direction"')).toBeLessThan(form.indexOf("<summary>More options</summary>"));
422 expect(form.indexOf('name="direction"')).toBeLessThan(form.indexOf("<summary>More settings</summary>"));
423423 });
424424 test("the API base field says once to leave off /v1", async () => {
425425 const html = await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs