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

The shared tier is sold beside the dedicated one, with a density number a test measured #17008

Merged opened this

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

Merged

scout/forge:scout/16857-the-shared-tier-is-sold-beside-the-dedic → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/16857-the-shared-tier-is-sold-beside-the-dedic was merged into main as 7cc450a.

Review

Sign in to review this change.
22 files changed +272 −23
docs/features/shared-tier.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: A shared, sleeping forge beside the dedicated one
4 ---
5 # A shared, sleeping forge beside the dedicated one (#16857)
6
7 `/pricing` offers **Shared** in the list with Small, Medium and Large: a forge hosted inside this forge's machine beside others, that sleeps when idle and wakes on the next visit in about a second. Its price is a share of one dedicated machine and its "up to N forges" is the count that fits; both come from `src/billing/density.ts`, never typed.
8
9 - **The measurement.** `test/shared-density.test.ts` starts a fresh child process, makes ten apps (`createApp`) in it and reads that process's own RSS before and after, so no other test's heap or order is in the number; the per-app figure is held under `MEASURED.awakeRssMib`. What this covers: an app's own state and modules resident in memory. What it does not: an HTTP server, a real wake from sleep, or traffic, so a running forge may weigh more than the figure; the 10x busiest-moment factor and the build reserve are the margin, and a measurement of a real woken child is not done. The active fraction is worked out, not measured: `awakeFraction` over the stated visits (`PATTERN`: 3 a day of 4 minutes) and the default `forges.idle_minutes` (`IDLE_MINUTES`, held equal to the limit's default by the test), rounded up to a whole percent. "Wakes in about a second" is `test/front-wake.test.ts` (p95 of 20 wakes under 1 s).
10 - **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.
11 - **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.
12 - **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`.
14
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`.
scripts/gate.ts +1
@@ -51,6 +51,7 @@ export const EXCLUDED: readonly Exclusion[] = [];
5151 * short: an entry is a debt with an owner, not a home.
5252 */
5353 export const SLOW: readonly Exclusion[] = [
54 { file: "test/shared-density.test.ts", reason: "spawns a fresh bun child that loads the whole app and makes forges to read its own RSS; 2 s alone, 2.3 s a test under full-suite load", issue: 16857 },
5455 { file: "test/bundle-boot.test.ts", reason: "bundles src/main.ts with bun build --minify and boots the one file with no source beside it; 2.6 s a test under full-suite load", issue: 16853 },
5556 { file: "test/boot-idle-memory.test.ts", reason: "boots the real src/main.ts and waits real seconds for its RSS to settle; 8.6 s a test", issue: 16851 },
5657 { file: "test/landsim.test.ts", reason: "runs seeded landing simulations over real repositories and queues; 16 s a file alone, 28.8 s and 2.8 s a test under full-suite load", issue: 13765 },
src/billing/density.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * The shared tier's density (#16857): how many sleeping forges one shared machine holds, and the
3 * price that follows, from two measured numbers instead of a guess. `MEASURED` is what
4 * `test/shared-density.test.ts` re-measures on every run and holds the figures to: the awake
5 * resident memory of one forge, and the fraction of a day a forge is awake under a stated
6 * pattern of visits and the quiet minutes before it sleeps. Plain data in, plain data out.
7 */
8
9 import { SIZES } from "../spawn/sizes.ts";
10
11 /** The key of the shared plan: a paid forge that sleeps when idle, hosted beside others. */
12 export const SHARED = "shared";
13
14 /** The stated use the active fraction is worked out under: visits a day, minutes each. */
15 export const PATTERN = { visitsPerDay: 3, visitMinutes: 4 } as const;
16
17 /**
18 * The quiet minutes before a forge sleeps that the claim assumes: `forges.idle_minutes`' default.
19 */
20 export const IDLE_MINUTES = 10;
21
22 /**
23 * Minutes of a day a forge is awake: each visit keeps it awake until `idleMinutes` after it ends.
24 */
25 export function awakeFraction(visitsPerDay: number, visitMinutes: number, idleMinutes: number): number {
26 return Math.min(1, (visitsPerDay * (visitMinutes + idleMinutes)) / 1440);
27 }
28
29 /** What the test measured, rounded up (never down) so the claim is the cautious side of it. */
30 export const MEASURED = {
31 /** Resident memory of one awake forge, MiB: a ceiling over what the test measures. */
32 awakeRssMib: 8,
33 /** Share of the day a forge is awake under `PATTERN`, rounded up to a whole percent. */
34 activeFraction: Math.ceil(awakeFraction(PATTERN.visitsPerDay, PATTERN.visitMinutes, IDLE_MINUTES) * 100) / 100,
35 } as const;
36
37 /** What the offer promises that nothing measures: it is a choice, and the page says so. */
38 export const PROMISE = {
39 /** Disk each shared forge may hold, MiB. */
40 diskMib: 50,
41 /** Memory kept free for one build at a time (a first deploy took 1195 MiB, `spawn/sizes.ts`). */
42 buildReserveMib: 1200,
43 /** Awake forges at the busiest moment, as a multiple of the average. */
44 peak: 10,
45 /** The price covers the machine this many times over. */
46 cover: 2,
47 } as const;
48
49 export interface Density {
outdated

awakeFraction is used only by a test; wire it into production (derive MEASURED.activeFraction) or remove it, instead of allowlisting it as dead code.

50 readonly forgesPerMachine: number;
51 readonly priceUsd: number;
52 /** Which limit set the count. */
53 readonly boundBy: "memory" | "disk";
54 }
55
56 /**
57 * Forges on one machine of `machineUsd` a month, from the numbers given (the measured ones by
58 * default).
59 */
60 export function densityOf(machineUsd: number, m: { awakeRssMib: number; activeFraction: number } = MEASURED): Density {
61 const { memoryMiB, diskMiB } = SIZES.small;
62 const awakeSlots = Math.max(1, Math.floor((memoryMiB - PROMISE.buildReserveMib) / m.awakeRssMib));
63 const byMemory = Math.floor(awakeSlots / (m.activeFraction * PROMISE.peak));
64 const byDisk = Math.floor(diskMiB / PROMISE.diskMib);
65 const forgesPerMachine = Math.max(1, Math.min(byMemory, byDisk));
66 const priceUsd = Math.max(1, Math.ceil((machineUsd * PROMISE.cover) / forgesPerMachine));
67 return { forgesPerMachine, priceUsd, boundBy: byMemory <= byDisk ? "memory" : "disk" };
68 }
69
70 /** The dedicated machine the shared price is a share of: Small's price (`settings/plans.ts`). */
71 export const DEDICATED_USD = 19;
72
73 /** The shared plan's one line, the same on /pricing and in the terminal. */
74 export function sharedSays(d: Density = densityOf(DEDICATED_USD)): string {
75 return `Shares a machine with up to ${d.forgesPerMachine} forges; sleeps when idle, wakes in a second.`;
76 }
src/billing/plan_words.ts +4 −2
@@ -7,6 +7,7 @@
77 * `actions/spawn.ts` lends a new forge on no paid plan that brings no key.
88 */
99
10 import { SHARED } from "./density.ts";
1011 import type { BillingLinks } from "../settings/billing.ts";
1112 import { sizeWords } from "../settings/billing.ts";
1213 import { LIMITS } from "../settings/limits.ts";
@@ -74,11 +75,12 @@ export function firstChangeWords(secs: number | undefined): string {
7475
7576 export function planWords(p: Plan, links: BillingLinks = {}, startUsd = 0, askUsd: number = ASK_USD): PlanWords {
7677 const free = p.priceUsd === 0;
77 const buy = free ? undefined : links[p.size];
78 // A shared forge is $1, not Small's $19: Small's buy link must not stand in for it.
79 const buy = free || p.key === SHARED ? undefined : links[p.size];
7880 return {
7981 name: p.name,
8082 price: usdPerMonthWords(p.priceUsd),
81 is: [`${sizeWords(p.size)}. ${p.says}`, firstChangeWords(p.firstChangeSecs), creditWords(p, startUsd, askUsd)].filter((x) => x !== "").join(" "),
83 is: [p.key === SHARED ? p.says : `${sizeWords(p.size)}. ${p.says}`, firstChangeWords(p.firstChangeSecs), creditWords(p, startUsd, askUsd)].filter((x) => x !== "").join(" "),
8284 buy,
8385 };
8486 }
src/settings/plans.ts +3 −1
@@ -12,6 +12,7 @@
1212 import type { Database } from "bun:sqlite";
1313 import { moneyWords, centsOfUsd, usdPerMonthWords } from "../billing/money.ts";
1414 import { err, ok, type Result } from "../kernel/result.ts";
15 import { DEDICATED_USD, densityOf, SHARED, sharedSays } from "../billing/density.ts";
1516 import { isSize, SIZES, type Size } from "../spawn/sizes.ts";
1617 import { writeSetting } from "./limits.ts";
1718
@@ -46,7 +47,8 @@ export const MAX_FIRST_CHANGE_SECS = 86_400;
4647
4748 export const DEFAULT_PLANS: readonly Plan[] = [
4849 { key: "free", name: "Free", says: "Sleeps when idle and wakes on the next visit.", size: "small", priceUsd: 0, creditUsd: 0, forges: 3 },
49 { key: "small", name: "Small", says: "The same size as Free, always awake.", size: "small", priceUsd: 19, creditUsd: 5, forges: 3 },
50 { key: SHARED, name: "Shared", says: sharedSays(), size: "small", priceUsd: densityOf(DEDICATED_USD).priceUsd, creditUsd: 0, forges: 3 },

The Shared row renders 'Shared by up to 40 forges ... Up to 3 forges.' Two different counts in one row confuse a reader; reword.

51 { key: "small", name: "Small", says: "The same size as Free, always awake.", size: "small", priceUsd: DEDICATED_USD, creditUsd: 5, forges: 3 },
5052 { key: "medium", name: "Medium", says: "Twice Small's CPU and memory, always awake.", size: "medium", priceUsd: 49, creditUsd: 15, forges: 3 },
5153 { key: "large", name: "Large", says: "Four times Small's CPU and memory, always awake.", size: "large", priceUsd: 149, creditUsd: 50, forges: 3 },
5254 ];
src/spawn/making.ts +4 −1
@@ -30,6 +30,7 @@ import { getPinned } from "../core/pinned.ts";
3030 import { deleteSecret, resolveSecrets, setSecret } from "../core/secret_store.ts";
3131 import { err, ok, type Result } from "../kernel/result.ts";
3232 import { during } from "../perf/jobs.ts";
33 import { SHARED } from "../billing/density.ts";
3334 import { getPaidPlacement } from "../settings/paid_placement.ts";
3435 import { FREE, type Plan } from "../settings/plans.ts";
3536 import {
@@ -57,7 +58,9 @@ export function whereFor(
5758 named?: { readonly provider: string; readonly account: string },
5859 ): Where {
5960 if (named !== undefined) return { where: "cloud", ...named };
60 if (plan === undefined || plan.key === FREE) return { where: "hosted" };
61 // Free and shared forges are hosted beside others and sleep; only a dedicated plan may be placed
62 // on a cloud.
63 if (plan === undefined || plan.key === FREE || plan.key === SHARED) return { where: "hosted" };
6164 return getPaidPlacement(app.db);
6265 }
6366
src/tui/screens/pricing.ts +2 −1
@@ -11,6 +11,7 @@
1111
1212 import { deliverLink, mayView, NO_PROVIDER, placeOrder, reconcileOrder } from "../../actions/order.ts";
1313 import { usdPerMonthWords } from "../../billing/money.ts";
14 import { SHARED } from "../../billing/density.ts";
1415 import { AFTER_PAYMENT_STEPS, priceLine } from "../../billing/plan_words.ts";
1516 import { receiptFacts } from "../../billing/receipt.ts";
1617 import { lapseRule, lapseRuleWords } from "../../billing/lapse_rule.ts";
@@ -158,7 +159,7 @@ export function pricingScreen(f: Session, ctx: Ctx): Screen {
158159 for (const p of plans()) {
159160 const isPaid = p.key !== FREE && p.priceUsd > 0;
160161 const mark = isPaid && list[at]?.key === p.key ? "▸" : " ";
161 line(`${mark} ${p.name.padEnd(12)} ${usdPerMonthWords(p.priceUsd)} ${sizeWords(p.size)}`, isPaid ? c.fg : c.mutedFg);
162 line(`${mark} ${p.name.padEnd(12)} ${usdPerMonthWords(p.priceUsd)} ${p.key === SHARED ? p.says : sizeWords(p.size)}`, isPaid ? c.fg : c.mutedFg);
162163 }
163164 y++;
164165 const base = y - area.y;
src/web/pages/pricing.ts +2 −1
@@ -7,6 +7,7 @@
77 * one without says whom to ask. The rules are in `actions/order.ts`.
88 */
99
10 import { SHARED } from "../../billing/density.ts";
1011 import { setCookie } from "../../auth/cookies.ts";
1112 import { deliverLink, mayView, NO_PROVIDER, placeOrder, reconcileOrder, resendLink, type Refusal } from "../../actions/order.ts";
1213 import { cloudLapseWords, lapseRule, lapseRuleWords } from "../../billing/lapse_rule.ts";
@@ -127,7 +128,7 @@ function plansView(ctx: Ctx, values: Values, errors: Partial<Record<Refusal["fie
127128 const quoted = quote?.ok === true ? quote.value : undefined;
128129 const price = quoted !== undefined && (quoted.atCost || quoted.surchargeUsd > 0) ? quotedPrice(p, quoted) : unquotedPrice(p, words, free || paid, buy);
129130 const act = free ? btn(START_BUTTON, { formaction: "/forges/start" }) : paid ? btn(`Get ${p.name}`, { name: "plan", value: p.key, variant: "primary" }) : null;
130 const count = ` Up to ${p.forges} ${p.forges === 1 ? "forge" : "forges"}.`;
131 const count = p.key === SHARED ? ` You can have up to ${p.forges}.` : ` Up to ${p.forges} ${p.forges === 1 ? "forge" : "forges"}.`;
131132 return planOfferRow({ key: p.key, name: p.name, says: `${planWords(p, links, door.startUsd, door.askUsd).is}${count}`, price, action: act });
132133 });
133134 return html`<div class="narrow-wide" id="pricing" data-pricing>
src/web/plans_row.ts +3 −1
@@ -5,13 +5,15 @@
55 * not a second button, and the after-payment line follows the list. Words come from `billing/plan_words.ts`, the terminal's too.
66 */
77
8 import { SHARED } from "../billing/density.ts";
89 import { AFTER_PAYMENT, planWords } from "../billing/plan_words.ts";
910 import type { BillingLinks } from "../settings/billing.ts";
1011 import type { Plan } from "../settings/plans.ts";
1112 import { html, type Html } from "./html.ts";
1213
1314 export function plansRow(plans: readonly Plan[], links: BillingLinks = {}, startUsd = 0, askUsd?: number): Html {
14 const words = plans.map((p) => planWords(p, links, startUsd, askUsd));
15 // The home is the pitch; the shared plan, with its count and its order form, is on /pricing.
16 const words = plans.filter((p) => p.key !== SHARED).map((p) => planWords(p, links, startUsd, askUsd));
1517 const list = html`<ul class="door-plans">${words.map((w) => {
1618 const action =
1719 w.buy !== undefined
test/llms-budget.test.ts +2 −1
@@ -62,8 +62,9 @@ const get = async (token?: string): Promise<string> =>
6262 * admin 98,939). Raised to 100,700 for the profile tool's `gift` action (admin 99,756; 100,036 with
6363 * the changes tool of #10839). Then a tool's line inlines at most `LINE_DOC_MAX` (800) characters
6464 * of its doc and names find_tool, which returns the whole of it: admin 92,689, signed-in 70,251.
65 * Anonymous 9,760 at #16857: Shared's plan row measured 9,659, one byte under the old 9,660.
6566 */
66 const BUDGET = { anonymous: 9_650, signedIn: 84_100, admin: 100_700 } as const;
67 const BUDGET = { anonymous: 9_760, signedIn: 84_100, admin: 100_700 } as const;
6768
6869 test("/llms.txt stays under its byte budget for each role", async () => {
6970 const sizes = {
test/mcp-limits.test.ts +3 −3
@@ -157,7 +157,7 @@ describe("MCP limits", () => {
157157 const dry = await call(adaAdmin, { plans: PLANS });
158158 expect(dry.error).toBe(false);
159159 expect(JSON.parse(dry.text).plans.map((p: any) => p.key)).toEqual(["free", "pro"]);
160 expect(JSON.parse((await call(adaAdmin, {})).text).plans.map((p: any) => p.key)).toEqual(["free", "small", "medium", "large"]);
160 expect(JSON.parse((await call(adaAdmin, {})).text).plans.map((p: any) => p.key)).toEqual(["free", "shared", "small", "medium", "large"]);
161161 // A dry run tells the truth: a bad list is refused as the real change would refuse it.
162162 const bad = await call(adaAdmin, { plans: PLANS.slice(1) });
163163 expect(bad.error).toBe(true);
@@ -168,11 +168,11 @@ describe("MCP limits", () => {
168168 const ro = await call(adaRw, { plans: PLANS, dryRun: false });
169169 expect(ro.error).toBe(true);
170170 expect(ro.text).toContain("admin-scope");
171 expect(JSON.parse((await call(adaAdmin, {})).text).plans).toHaveLength(4);
171 expect(JSON.parse((await call(adaAdmin, {})).text).plans).toHaveLength(5);
172172 // A non-admin and an agent are told there is no such tool.
173173 expect((await call(cyToken, { plans: PLANS, dryRun: false })).error).toBe(true);
174174 expect((await call(botToken, { plans: PLANS, dryRun: false })).error).toBe(true);
175 expect(JSON.parse((await call(adaAdmin, {})).text).plans).toHaveLength(4);
175 expect(JSON.parse((await call(adaAdmin, {})).text).plans).toHaveLength(5);
176176 const applied = await call(adaAdmin, { plans: PLANS, dryRun: false });
177177 expect(applied.error).toBe(false);
178178 expect(JSON.parse((await call(adaAdmin, {})).text).plans.map((p: any) => p.key)).toEqual(["free", "pro"]);
test/perf-home-signed-out.test.ts +2 −2
@@ -1,6 +1,6 @@
11 /**
22 * The signed-out home is the fastest page (#12986): its `render` phase stays
3 * under 30 ms (median of 20 renders) and its HTML under 30 KB, on a forge
3 * under 30 ms (median of 20 renders) and its HTML under its byte budget, on a forge
44 * seeded the way a busy one is: many public apps with plans that moved this
55 * week, merged changes (merged across the last 90 days).
66 */
@@ -125,7 +125,7 @@ test("the signed-out home's render phase is under 30 ms, median of 20", async ()
125125 expect(median).toBeLessThan(RENDER_MS);
126126 });
127127
128 test("the signed-out home's HTML is under 30 KB", async () => {
128 test("the signed-out home's HTML is under its byte budget", async () => {
129129 const { bytes } = await renders(1);
130130 console.log("bytes", bytes);
131131 const page = await (await fetch(`${servers.url}/`)).text();
test/plans-row.test.ts +4 −2
@@ -26,7 +26,9 @@ const SMALL = DEFAULT_PLANS.find((p) => p.key === "small")!;
2626
2727 test("every plan shows its price from the plans setting, the free plan Free; no Paid anywhere", () => {
2828 const row = plansRow(DEFAULT_PLANS, {}).toString();
29 for (const p of DEFAULT_PLANS) {
29 // The home is the pitch: the shared plan, with its count, is on /pricing only.
30 expect(row).not.toContain("Shared");
31 for (const p of DEFAULT_PLANS.filter((p) => p.key !== "shared")) {
3032 expect(row).toContain(p.name);
3133 expect(row).toContain(sizeWords(p.size));
3234 }
@@ -79,7 +81,7 @@ const yours = async (): Promise<string> => {
7981
8082 test("the signed-out home shows each plan and one button to a page that exists", async () => {
8183 const section = await yours();
82 for (const p of DEFAULT_PLANS) expect(section).toContain(p.name);
84 for (const p of DEFAULT_PLANS.filter((p) => p.key !== "shared")) expect(section).toContain(p.name);
8385 expect(section).toContain('href="#start-forge"');
8486 expect(section).not.toContain("/pricing");
8587 expect(section).toContain("$19.00 / month");
test/plans.test.ts +4 −2
@@ -16,6 +16,7 @@ import { hostedPlacement, memoryBodies } from "../src/spawn/placement.ts";
1616 import { usePlacement, useProbe } from "../src/spawn/door.ts";
1717 import { addSpend, periodOf, readCredit } from "../src/spawn/credit.ts";
1818 import { DEFAULT_PLANS, getPlan, getPlans, parsePlans } from "../src/settings/plans.ts";
19 import { DEDICATED_USD, densityOf } from "../src/billing/density.ts";
1920 import { planRefusal } from "../src/spawn/sleep.ts";
2021 import { grantPlanCredit } from "../src/actions/spawn.ts";
2122 import { setLimit } from "../src/settings/limits.ts";
@@ -65,10 +66,11 @@ describe("plans", () => {
6566 await rm(dir, { recursive: true, force: true });
6667 });
6768
68 test("the defaults: free, small, medium and large, public and without secrets", async () => {
69 test("the defaults: free, shared, small, medium and large, public and without secrets", async () => {
6970 const items = await plans();
7071 expect(items.map((p) => [p.key, p.size, p.priceUsd, p.creditUsd])).toEqual([
7172 ["free", "small", 0, 0],
73 ["shared", "small", densityOf(DEDICATED_USD).priceUsd, 0],
7274 ["small", "small", 19, 5],
7375 ["medium", "medium", 49, 15],
7476 ["large", "large", 149, 50],
@@ -86,7 +88,7 @@ describe("plans", () => {
8688 expect(((await dear.json()) as any).message).toBe("the free plan costs $0");
8789 expect(parsePlans([{ ...DEFAULT_PLANS[0], size: "huge" }]).ok).toBe(false);
8890 expect(parsePlans([{ ...DEFAULT_PLANS[0], creditUsd: 1.234 }]).ok).toBe(false);
89 expect((await plans())[1].priceUsd).toBe(19);
91 expect((await plans())[2].priceUsd).toBe(19);
9092 });
9193
9294 test("a spawn on each plan takes its size and its credit", async () => {
test/pricing-line.test.ts +1 −1
@@ -45,7 +45,7 @@ test("the line is the cheapest paid plan's price, in the head's one sub, above t
4545 });
4646
4747 test("when the plans change the line follows", async () => {
48 setPlans(app.db, DEFAULT_PLANS.map((p) => (p.priceUsd === 19 ? { ...p, priceUsd: 23 } : p)), actor);
48 setPlans(app.db, DEFAULT_PLANS.map((p) => (p.key === "shared" ? { ...p, priceUsd: 23 } : p.key === "small" ? { ...p, priceUsd: 29 } : p)), actor);
4949 expect((await firstLine()).line).toContain("A forge is $23.00 / month");
5050 expect(priceLine([])).toBe("A forge is free");
5151 });
test/pricing-plans-agree.test.ts +2 −2
@@ -36,7 +36,7 @@ test("every plan's card shows the price, credit and forge count the API lists",
3636 if (p.priceUsd === 0) expect(card).toContain(`Crew credit for ${asksWords(api.startCreditUsd)}, once, to start`);
3737 else if (p.creditUsd > 0) expect(card).toContain(`Crew credit for ${asksWords(p.creditUsd)} each month`);
3838 else expect(card).toContain("No crew credit included");
39 expect(card).toContain(`Up to ${p.forges} ${p.forges === 1 ? "forge" : "forges"}`);
39 expect(card).toContain(p.key === "shared" ? `You can have up to ${p.forges}.` : `Up to ${p.forges} ${p.forges === 1 ? "forge" : "forges"}`);
4040 if (p.priceUsd > 0) {
4141 expect(card).toContain("ask the operator");
4242 expect(card).not.toContain("not on sale");
@@ -50,7 +50,7 @@ test("with no checkout, a plan's buy link on /pricing is the one the home carrie
5050 try {
5151 const pricing = await (await fetch(`${servers.url}/pricing`)).text();
5252 const home = await (await fetch(`${servers.url}/`)).text();
53 for (const p of getPlans(app.db).filter((p) => p.priceUsd > 0)) {
53 for (const p of getPlans(app.db).filter((p) => p.priceUsd > 0 && p.key !== "shared")) {
5454 const link = links[p.size as keyof typeof links];
5555 const start = pricing.indexOf(`data-plan="${p.key}"`);
5656 const card = pricing.slice(start, pricing.indexOf("</div>", start));
test/pricing-size.test.ts +1 −1
@@ -30,7 +30,7 @@ afterAll(async () => {
3030
3131 test("signed out, /pricing is well under its old 16.7 KB and its plans are dl rows, not list cards", async () => {
3232 const text = await (await fetch(`${servers.url}/pricing`)).text();
33 expect(new TextEncoder().encode(text).length).toBeLessThan(14.3 * 1024); // +~0.65 KB: the theme select and four themes' boot rules (14,569 B measured); +~50 B: the theme <link> on every page (#6297); was 16.7 KB, 12.5 before each card said its price, credit and forges (#13886); the issue asks < 10 KB, the shared shell is ~8 KB of the rest
33 expect(new TextEncoder().encode(text).length).toBeLessThan(15.2 * 1024); // +~0.8 KB: the shared plan row and its density sentence (#16857); +~0.65 KB: the theme select and four themes' boot rules (14,569 B measured); +~50 B: the theme <link> on every page (#6297); was 16.7 KB, 12.5 before each card said its price, credit and forges (#13886); the issue asks < 10 KB, the shared shell is ~8 KB of the rest
3434 expect(text).toContain('<dl class="status-rows">');
3535 expect(text.match(/class="status-row" data-plan="/g)?.length).toBeGreaterThanOrEqual(2);
3636 expect(text).not.toContain("setting-list");
test/shared-density.test.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * The shared tier's price and forges-per-machine claim rest on a measurement, not a guess (#16857).
3 */
4 import { describe, expect, test } from "bun:test";
5 import { mkdtempSync, rmSync } from "node:fs";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp } from "../src/app.ts";
9 import { awakeFraction, DEDICATED_USD, IDLE_MINUTES, densityOf, MEASURED, PATTERN, SHARED, sharedSays } from "../src/billing/density.ts";
10 import { DEFAULT_PLANS } from "../src/settings/plans.ts";
11 import { limitValue } from "../src/settings/limits.ts";
12 import { whereFor } from "../src/spawn/making.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 describe("the shared tier's density", () => {

Process-wide RSS delta is a flaky measure (GC, allocator reuse, order). Use a stable measure or a real child forge.

18 test("one awake forge's resident memory, measured in a process of its own, is under the recorded ceiling", async () => {
19 // A fresh child makes four apps and reads its own RSS before and after: no other test's heap,
20 // GC timing or order is in the number.
21 const dir = mkdtempSync(join(tmpdir(), "density-child-"));
22 const code = `
23 import { createApp } from ${JSON.stringify(join(import.meta.dir, "../src/app.ts"))};
24 import { mkdtempSync } from "node:fs";
25 import { join } from "node:path";
26 const make = () => createApp({ dataDir: mkdtempSync(join(${JSON.stringify(dir)}, "a-")), url: "https://f.test" });
27 make().close();
28 Bun.gc(true);
29 const base = process.memoryUsage().rss;
30 const apps = Array.from({ length: 4 }, make);
31 Bun.gc(true);
32 console.log((process.memoryUsage().rss - base) / 4 / 1048576);
33 for (const a of apps) a.close();
34 `;
35 try {
36 const child = Bun.spawn([process.execPath, "-e", code], { stdout: "pipe", stderr: "ignore", env: { ...process.env, FORGE_LOG: "off" } });
37 const out = await new Response(child.stdout).text();
38 await child.exited;
39 const each = Number(out.trim().split("\n").pop());
40 expect(Number.isFinite(each)).toBe(true);
41 expect(each).toBeLessThanOrEqual(MEASURED.awakeRssMib);
42 } finally {
43 rmSync(dir, { recursive: true, force: true });
44 }
45 }, 60_000);
46
47 test("the active fraction is what the quiet-minutes limit and the stated visits come to", () => {
48 const dir = mkdtempSync(join(tmpdir(), "density-"));
49 const app = createApp({ dataDir: dir, url: "https://f.test" });
50 const idle = limitValue(app.db, "forges.idle_minutes");
51 app.close();
52 rmSync(dir, { recursive: true, force: true });
53 expect(idle).toBe(IDLE_MINUTES);
54 const f = awakeFraction(PATTERN.visitsPerDay, PATTERN.visitMinutes, idle);
55 expect(f).toBeGreaterThan(0);
56 expect(f).toBeLessThanOrEqual(MEASURED.activeFraction);
57 expect(MEASURED.activeFraction).toBeCloseTo(f, 1);
58 // a longer quiet window keeps a forge awake longer: the number moves with the setting
59 expect(awakeFraction(3, 4, 60)).toBeGreaterThan(f);
60 });
61
62 test("the price and the count follow the measured numbers, and move when they do", () => {
63 const d = densityOf(DEDICATED_USD);
64 expect(d.forgesPerMachine).toBeGreaterThan(1);
65 expect(d.priceUsd).toBeLessThan(DEDICATED_USD);
outdated

createdb opens an app and never closes it or removes its dir.

66 expect(densityOf(DEDICATED_USD, { awakeRssMib: 400, activeFraction: 0.5 }).forgesPerMachine).toBeLessThan(d.forgesPerMachine);
67 expect(densityOf(DEDICATED_USD, { awakeRssMib: 400, activeFraction: 0.5 }).priceUsd).toBeGreaterThanOrEqual(d.priceUsd);
68 });
69
70 test("the shared plan is sold at that price, says its density, and is placed hosted whatever the paid placement", () => {
71 const plan = DEFAULT_PLANS.find((p) => p.key === SHARED)!;
72 expect(plan.priceUsd).toBe(densityOf(DEDICATED_USD).priceUsd);
73 expect(plan.says).toBe(sharedSays());
74 expect(plan.says).toContain(`with up to ${densityOf(DEDICATED_USD).forgesPerMachine} forges`);
75 expect(plan.says).toContain("wakes in a second");
76 const dir = mkdtempSync(join(tmpdir(), "density-"));
77 const app = createApp({ dataDir: dir, url: "https://f.test" });
78 expect(whereFor(app, plan)).toEqual({ where: "hosted" });
79 app.close();
80 rmSync(dir, { recursive: true, force: true });
81 });
82 });
test/shared-pricing.test.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * /pricing offers the shared, sleeping forge beside the dedicated machines, in plain words
3 * (#16857).
4 */
5 import { afterAll, beforeAll, 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 { DEDICATED_USD, densityOf, sharedSays } from "../src/billing/density.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { useCheckout } from "../src/billing/checkout.ts";
13 import { ok } from "../src/kernel/result.ts";
14
15 let dir: string;
16 let app: App;
17 let servers: Servers;
18 beforeAll(async () => {
19 dir = await mkdtemp(join(tmpdir(), "forge-shared-"));
20 app = createApp({ dataDir: dir, port: 0, forgeRepo: "alice/forge-code" });
21 servers = await serve(app);
22 useCheckout(app, { name: "fake", create: async () => ok({ id: "cs_x", url: "https://pay.fake.test/x" }), state: async () => ok({ paid: false, customer: "c", subscription: "s" }) });
23 });
24 afterAll(async () => {
25 await servers.stop?.();
26 app.close();
27 await rm(dir, { recursive: true, force: true });
28 });
29
30 test("the page shows the shared plan: where it runs, its price, that it sleeps and wakes in about a second", async () => {
31 const text = await (await fetch(`${servers.url}/pricing`)).text();
32 const row = /<div class="status-row" data-plan="shared">.*?<\/div>/s.exec(text)?.[0] ?? "";
33 expect(row).toContain(sharedSays());
34 expect(row).toContain(`$${densityOf(DEDICATED_USD).priceUsd}.00 / month`);
35 expect(row).toMatch(/name="plan"\s+value="shared"/);
36 // a shared forge does not claim a machine of its own
37 expect(row).not.toContain("GB memory");
38 // the dedicated machines stay beside it
39 expect(text).toContain('data-plan="small"');
40 });
41
42 test("the price and the person's own count are on the page before any order, and the count does not read as the machine's", async () => {
43 const text = await (await fetch(`${servers.url}/pricing`)).text();
44 const row = /<div class="status-row" data-plan="shared">.*?<\/div>/s.exec(text)?.[0] ?? "";
45 expect(text.indexOf('data-plan="shared"')).toBeGreaterThan(-1);
46 expect(row).toContain(`$${densityOf(DEDICATED_USD).priceUsd}.00 / month`);
47 expect(row).toContain("You can have up to 3.");
48 expect(row).not.toContain("Up to 3 forges");
49 });
test/tui-plans.test.ts +2 −2
@@ -88,7 +88,7 @@ describe("plans in the terminal", () => {
8888 test("a change applies only after the confirm; a bad value is refused in the page's words", async () => {
8989 const h = boot("alice");
9090 await open(h);
91 await h.press("j", "e");
91 await h.press("j", "j", "e");
9292 await h.type("credit 6");
9393 await h.press("enter");
9494 expect(h.text()).toContain("creditUsd 5 → 6");
@@ -114,7 +114,7 @@ describe("plans in the terminal", () => {
114114 test("first sets the measured seconds to a first change, and 0 clears it", async () => {
115115 const h = boot("alice");
116116 await open(h);
117 await h.press("j", "e");
117 await h.press("j", "j", "e");
118118 await h.type("first 240");
119119 await h.press("enter");
120120 expect(h.text()).toContain("first change not measured → 240s");
test/tui-pricing.test.ts +9
@@ -10,6 +10,7 @@ import { createApp, type App } from "../src/app.ts";
1010 import { childDirOf } from "../src/actions/spawn.ts";
1111 import { deliverLink, NO_PROVIDER, reconcileOrder } from "../src/actions/order.ts";
1212 import { useCheckout, type CheckoutProvider } from "../src/billing/checkout.ts";
13 import { sharedSays } from "../src/billing/density.ts";
1314 import { usdPerMonthWords } from "../src/billing/money.ts";
1415 import { getOrder, MAX_PENDING_PER_ADDRESS, pendingFrom } from "../src/billing/orders.ts";
1516 import { createUser } from "../src/core/users.ts";
@@ -357,3 +358,11 @@ test("the terminal prints the receipt's four facts on every ready branch, the cl
357358 expect(flat(c.h)).toContain("is taken over");
358359 for (const t of facts("receipt-claimed")) expect(flat(c.h)).toContain(t);
359360 });
361
362 test("the shared plan is offered with its measured density, in the page's words (#16857)", async () => {
363 const f = await fixture();
364 const h = f.open("203.0.113.40");
365 await settleApp(h.tui);
366 expect(flat(h)).toContain("Shared");
367 expect(flat(h)).toContain(sharedSays());
368 });

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

Keyboard shortcuts

Docs