Public: anyone can read this; the crew can change it.
Revert "Experiments: what the cloud spend buys, on /pinned and in one small tool" #16597
Check · Review · Land · Live — It conflicts with its base.
revert-16584 → main 1 commit
17 files
changed +8
−869
- docs/design/quiet-debt.json
- docs/features/experiments.md
- docs/features/pinned-forge.md
- src/cloud/experiments.ts
- src/core/migration-pins/20261127220000-experiment.pin
- src/core/migrations/20261127220000-experiment.ts
- src/http/mcp/tools/experiments.ts
- src/http/mcp/tools/index.ts
- src/http/pinned_routes.ts
- src/tui/screens/experiments.ts
- src/web/pages/pinned.ts
- test/conversation-confirm.test.ts
- test/experiments-routes.test.ts
- test/experiments.test.ts
- test/mcp-forge-protocol.test.ts
- test/mixed-actions-held.test.ts
- test/palette-roster.test.ts
docs/design/quiet-debt.json +3
docs/features/experiments.md deleted −26
| @@ -1,26 +0,0 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Experiments | |
| 4 | --- | |
| 5 | ||
| 6 | # Experiments (#16583) | |
| 7 | ||
| 8 | Every cloud dollar answers a question. An experiment is that question, the pinned forges it runs on, and its result. | |
| 9 | ||
| 10 | ## Where | |
| 11 | ||
| 12 | - **Web:** the top of `/pinned` (`src/web/pages/pinned.ts`). One row per experiment: its question, the machines it runs on, what they cost a month now, what it has cost, and its result, with Record result under it while it runs. It is a live region on `/events`: it updates in place when anyone changes an experiment, from any door. | |
| 13 | - **Terminal:** the Experiments screen (`src/tui/screens/experiments.ts`, after Pinned forges in the palette). `b` begins one, `a` attaches machines to the selected one, `r` records its result. | |
| 14 | - **Agents:** the `experiments` MCP tool: `list` (and `idle`), `show` by id or words of the question, `begin`, `attach`, `record_result`. | |
| 15 | ||
| 16 | All three read and write through `src/cloud/experiments.ts`, and only a forge admin sees them. | |
| 17 | ||
| 18 | ## How it counts | |
| 19 | ||
| 20 | - A machine costs what the cloud ceiling reckons it costs a month at list price (`rowCents`). The provider's bill is the truth. | |
| 21 | - **Has cost** is each machine's monthly cost now, over its days on the experiment. | |
| 22 | - A machine is on one experiment at a time. Attaching it to another closes its time on the first, which keeps what it spent there; attaching it back opens a new stretch. | |
| 23 | - Recording a result marks the experiment done and stops its cost counting. Its machines keep costing until they are retired; the row says so. | |
| 24 | - A pinned forge that costs money and is on no experiment shows as **idle spend**, with Attach and Retire. A retired forge's kept volume counts too. | |
| 25 | ||
| 26 | Each begin, attach and result is an event (`pinned.experiment_begun`, `pinned.experiment_attached`, `pinned.experiment_result`) naming who did it. Retiring a machine stays on the pinned forge itself. |
docs/features/pinned-forge.md −4
| @@ -101,10 +101,6 @@ An admin chooses where **paid forges run** on Pinned forges (`/pinned`; the term | ||
| 101 | 101 | |
| 102 | 102 | A test forge, or one whose buyer left, would bill forever without a way out. **Retire** (`POST /api/v1/admin/pinned/:name/retire`, the `pinned_forge` tool's `retire` verb, Retire on `/pinned`, `x` in the terminal) deletes the forge's machine and the DNS record the forge wrote for it (job above), and keeps its data volume: the answer says what keeping it costs a month at list price. The row ends `retired`, and the account's ceiling counts it at that volume's price alone. The volume is deleted only by the second word: `withData` on the API and the tool, **Retire and delete its data** on the page (which asks for the forge's name), and a second choice and the name in the terminal. That call is the data-destroying one under the delete tier (`tier: "delete"` on the tool, `test/delete-tier.test.ts`): the forge's own agent is refused it with the page to use. A **retired forge** can be retired again with its data, and nothing else: Update, Roll back, a new claim link and Check refuse it. It is idempotent: a machine or volume already gone at the cloud (a 404) is done, so asking again finishes a retire whose volume the cloud would not delete (the machine is gone and the forge `retired` by then, its data kept). A forge its buyer has claimed, as the forge itself says when asked (or as recorded), is refused with the sentence that its data is on that volume, unless `despiteClaim` says the owner means it (the page's form for a claimed forge carries it; the terminal asks in its question). One event, `pinned.retired`, says who, whether the data went, and what became of the record. |
| 103 | 103 | |
| 104 | ## Experiments | |
| 105 | ||
| 106 | What each forge's spend answers, and what it found: [](experiments.md). | |
| 107 | ||
| 108 | 104 | ## After the claim: what the host can still do (#16204) |
| 109 | 105 | |
| 110 | 106 | Nobody marks a forge claimed by hand: the deployed forge says so. Check, and every Update, Roll back and request for a new claim link, asks it first; when one hears `claimed` (The claim, above), the selling forge records it once (`pinned_forge.claimed_at`, event `pinned.claimed`). From then it refuses `update`, `rollback` and a new claim link for that forge, each with the same sentence (`CLAIMED_REFUSAL`): updates are the buyer's to take, and no machine of theirs is replaced from here. A forge that cannot be asked is never recorded as claimed, and is not taken as unclaimed either: once its current machine has answered about its claim (`pinned_forge.reached`), silence from it (a broken DNS record, a forge that is down) refuses Update, Roll back and a new claim link, with a sentence saying the forge could not be reached to confirm nobody claimed it and to run Check until it answers. A forge whose current machine has never answered (still booting, DNS not pointed yet, a first boot that failed) may still be replaced, or it could never be recovered. The question starts with a read of the machine at its cloud: when the cloud refuses that read the change is refused with the cloud's answer, before anything is recorded; a machine that is gone (404) has nobody to ask and is replaced. `/pinned` (once, when any forge is claimed) and `/deploy-to` say what the host still can while the machine is in the host's cloud account (`HOST_CAN` in `src/core/pinned.ts`): open its console, boot it into rescue, snapshot its disk, read its boot data. It never says "no access". The path that gives the host none is the buyer's own cloud account: deploy there (the account picker on `/deploy-to`; choosing it at purchase is #16203). |
src/cloud/experiments.ts deleted −213
| @@ -1,213 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Experiments: what the forge's cloud spend buys. An experiment is a question, the pinned forges | |
| 3 | * that run it and, once recorded, its result, which marks it done. A machine's time on an | |
| 4 | * experiment is a row of its own: moving it to another closes that row, so the first keeps what | |
| 5 | * it spent. A pinned forge that costs money and is on no experiment now is idle spend. Money is | |
| 6 | * the forge's own reckoning (`rowCents`, list prices): what each machine costs a month now, and | |
| 7 | * what it cost over its time on the experiment at that rate. The provider's bill is the truth. | |
| 8 | * | |
| 9 | * One read, `experiments`, answers the /pinned page, its terminal screen and the `experiments` MCP | |
| 10 | * tool alike. Each write appends a `pinned.experiment_*` event naming who did it, which the page's | |
| 11 | * live region (on /events) and the terminal follow. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { Database } from "bun:sqlite"; | |
| 15 | import type { App } from "../app.ts"; | |
| 16 | import { getPinned, listPinned, type Pinned } from "../core/pinned.ts"; | |
| 17 | import { id as newId } from "../kernel/id.ts"; | |
| 18 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 19 | import { priced, rowCents } from "./ceiling.ts"; | |
| 20 | ||
| 21 | const DAY_MS = 86_400_000; | |
| 22 | /** The month the reckoning bills by: 30 days. */ | |
| 23 | const MONTH_DAYS = 30; | |
| 24 | const QUESTION_MAX = 300; | |
| 25 | const RESULT_MAX = 500; | |
| 26 | ||
| 27 | /** The event kinds every write appends; the page's live region and the terminal follow them. */ | |
| 28 | export const EXPERIMENT_KINDS = ["pinned.experiment_begun", "pinned.experiment_attached", "pinned.experiment_result"] as const; | |
| 29 | ||
| 30 | export interface Machine { | |
| 31 | readonly name: string; | |
| 32 | /** `provider/account`, the cloud account it runs on. */ | |
| 33 | readonly account: string; | |
| 34 | /** The pinned forge's own state: running, failed, retired… */ | |
| 35 | readonly state: string; | |
| 36 | /** What it costs a month now, US cents; a retired forge counts only the data it kept. */ | |
| 37 | readonly monthlyCents: number; | |
| 38 | /** When it joined the experiment (for idle spend, when it was made). */ | |
| 39 | readonly since: string; | |
| 40 | /** When it moved to another experiment; empty while it is still on this one. */ | |
| 41 | readonly until: string; | |
| 42 | } | |
| 43 | ||
| 44 | export interface Experiment { | |
| 45 | readonly id: string; | |
| 46 | readonly question: string; | |
| 47 | readonly state: "running" | "done"; | |
| 48 | readonly result: string; | |
| 49 | readonly startedAt: string; | |
| 50 | /** When its result was recorded; empty while it runs. */ | |
| 51 | readonly endedAt: string; | |
| 52 | /** Every machine that ran it, those that moved on included (`until`). */ | |
| 53 | readonly machines: Machine[]; | |
| 54 | /** What the machines still on it cost a month now, US cents: owed after it is done until they retire. */ | |
| 55 | readonly monthlyCents: number; | |
| 56 | /** What it has cost, US cents: each machine's monthly cost now, over its days on the experiment. */ | |
| 57 | readonly spentCents: number; | |
| 58 | } | |
| 59 | ||
| 60 | export interface Experiments { | |
| 61 | readonly items: Experiment[]; | |
| 62 | /** Pinned forges that cost money and are on no experiment now. */ | |
| 63 | readonly idle: Machine[]; | |
| 64 | /** Every pinned forge's monthly cost now, US cents. */ | |
| 65 | readonly monthlyCents: number; | |
| 66 | } | |
| 67 | ||
| 68 | interface Row { | |
| 69 | id: string; | |
| 70 | question: string; | |
| 71 | result: string; | |
| 72 | started_at: string; | |
| 73 | ended_at: string; | |
| 74 | } | |
| 75 | interface Link { | |
| 76 | pinned_id: string; | |
| 77 | experiment_id: string; | |
| 78 | attached_at: string; | |
| 79 | detached_at: string; | |
| 80 | } | |
| 81 | ||
| 82 | const line = (s: string, max: number): string => | |
| 83 | s | |
| 84 | .replace(/[\u0000-\u001f\u007f]+/g, " ") | |
| 85 | .trim() | |
| 86 | .slice(0, max); | |
| 87 | ||
| 88 | /** Every experiment, newest first, with its machines and money, and the idle spend beside them. */ | |
| 89 | export function experiments(db: Database, now = new Date()): Experiments { | |
| 90 | const prices = priced(db); | |
| 91 | const forges = new Map(listPinned(db).map((p) => [p.id, p])); | |
| 92 | const links = db.query<Link, []>("SELECT pinned_id, experiment_id, attached_at, detached_at FROM experiment_machine ORDER BY id").all(); | |
| 93 | const machine = (p: Pinned, since: string, until: string): Machine => ({ | |
| 94 | name: p.name, | |
| 95 | account: `${p.target}/${p.account}`, | |
| 96 | state: p.state, | |
| 97 | monthlyCents: rowCents(p, prices), | |
| 98 | since, | |
| 99 | until, | |
| 100 | }); | |
| 101 | const items = db | |
| 102 | .query<Row, []>("SELECT id, question, result, started_at, ended_at FROM experiment ORDER BY started_at DESC, id") | |
| 103 | .all() | |
| 104 | .map((r): Experiment => { | |
| 105 | const ended = r.ended_at === "" ? now.getTime() : Date.parse(r.ended_at); | |
| 106 | let spentCents = 0; | |
| 107 | let monthlyCents = 0; | |
| 108 | const machines: Machine[] = []; | |
| 109 | for (const l of links) { | |
| 110 | const p = l.experiment_id === r.id ? forges.get(l.pinned_id) : undefined; | |
| 111 | if (p === undefined) continue; | |
| 112 | const m = machine(p, l.attached_at, l.detached_at); | |
| 113 | const from = Math.max(Date.parse(l.attached_at), Date.parse(p.createdAt)); | |
| 114 | const until = l.detached_at === "" ? ended : Math.min(ended, Date.parse(l.detached_at)); | |
| 115 | spentCents += Math.round((m.monthlyCents * Math.max(0, until - from)) / (MONTH_DAYS * DAY_MS)); | |
| 116 | if (l.detached_at === "") monthlyCents += m.monthlyCents; | |
| 117 | machines.push(m); | |
| 118 | } | |
| 119 | return { | |
| 120 | id: r.id, | |
| 121 | question: r.question, | |
| 122 | state: r.ended_at === "" ? "running" : "done", | |
| 123 | result: r.result, | |
| 124 | startedAt: r.started_at, | |
| 125 | endedAt: r.ended_at, | |
| 126 | machines, | |
| 127 | monthlyCents, | |
| 128 | spentCents, | |
| 129 | }; | |
| 130 | }); | |
| 131 | const busy = new Set(links.filter((l) => l.detached_at === "").map((l) => l.pinned_id)); | |
| 132 | const all = [...forges.values()].map((p) => machine(p, p.createdAt, "")); | |
| 133 | const idle = [...forges.values()] | |
| 134 | .filter((p) => !busy.has(p.id)) | |
| 135 | .map((p) => machine(p, p.createdAt, "")) | |
| 136 | .filter((m) => m.monthlyCents > 0); | |
| 137 | return { items, idle, monthlyCents: all.reduce((s, m) => s + m.monthlyCents, 0) }; | |
| 138 | } | |
| 139 | ||
| 140 | /** One experiment by id, or by words of its question (Talk asks "what did X find"). */ | |
| 141 | export function findExperiment(db: Database, key: string, now = new Date()): Experiment | undefined { | |
| 142 | const k = key.trim().toLowerCase(); | |
| 143 | if (k === "") return undefined; | |
| 144 | const all = experiments(db, now).items; | |
| 145 | return all.find((e) => e.id === key) ?? all.find((e) => e.question.toLowerCase().includes(k)); | |
| 146 | } | |
| 147 | ||
| 148 | export type ExperimentError = "no_question" | "no_experiment" | "no_machine" | "done" | "no_result"; | |
| 149 | ||
| 150 | /** | |
| 151 | * Put pinned forge `name` on running experiment `id`. A machine is on one experiment at a time: | |
| 152 | * its open row elsewhere is closed now, and that experiment keeps what the machine spent there. | |
| 153 | */ | |
| 154 | export function attachMachine(app: App, actorId: string, id: string, name: string, now = new Date()): Result<void, ExperimentError> { | |
| 155 | const db = app.db; | |
| 156 | const e = db.query<{ ended_at: string }, [string]>("SELECT ended_at FROM experiment WHERE id = ?1").get(id); | |
| 157 | if (e === null) return err("no_experiment"); | |
| 158 | if (e.ended_at !== "") return err("done"); | |
| 159 | const p = getPinned(db, name.trim()); | |
| 160 | if (p === undefined) return err("no_machine"); | |
| 161 | const open = db | |
| 162 | .query<{ experiment_id: string }, [string]>("SELECT experiment_id FROM experiment_machine WHERE pinned_id = ?1 AND detached_at = ''") | |
| 163 | .get(p.id); | |
| 164 | if (open?.experiment_id === id) return ok(); | |
| 165 | const at = now.toISOString(); | |
| 166 | db.transaction(() => { | |
| 167 | db.query("UPDATE experiment_machine SET detached_at = ?2 WHERE pinned_id = ?1 AND detached_at = ''").run(p.id, at); | |
| 168 | db.query("INSERT INTO experiment_machine (experiment_id, pinned_id, attached_at) VALUES (?1, ?2, ?3)").run(id, p.id, at); | |
| 169 | })(); | |
| 170 | app.bus.append({ kind: "pinned.experiment_attached", actorId, payload: { id, name: p.name, from: open?.experiment_id ?? "" } }); | |
| 171 | return ok(); | |
| 172 | } | |
| 173 | ||
| 174 | /** Begin an experiment on a question, on the pinned forges named (none is fine: attach later). */ | |
| 175 | export function beginExperiment( | |
| 176 | app: App, | |
| 177 | actorId: string, | |
| 178 | question: string, | |
| 179 | names: readonly string[], | |
| 180 | now = new Date(), | |
| 181 | ): Result<string, ExperimentError> { | |
| 182 | const q = line(question, QUESTION_MAX); | |
| 183 | if (q === "") return err("no_question"); | |
| 184 | const wanted = names.map((n) => n.trim()).filter((n) => n !== ""); | |
| 185 | if (wanted.some((n) => getPinned(app.db, n) === undefined)) return err("no_machine"); | |
| 186 | const id = newId(); | |
| 187 | app.db.query("INSERT INTO experiment (id, question, started_at) VALUES (?1, ?2, ?3)").run(id, q, now.toISOString()); | |
| 188 | app.bus.append({ kind: "pinned.experiment_begun", actorId, payload: { id, question: q } }); | |
| 189 | for (const n of wanted) attachMachine(app, actorId, id, n, now); | |
| 190 | return ok(id); | |
| 191 | } | |
| 192 | ||
| 193 | /** Record what the experiment found: it is done, and its cost stops counting. Its machines stay until retired. */ | |
| 194 | export function recordResult(app: App, actorId: string, id: string, result: string, now = new Date()): Result<void, ExperimentError> { | |
| 195 | const r = line(result, RESULT_MAX); | |
| 196 | if (r === "") return err("no_result"); | |
| 197 | const changed = app.db | |
| 198 | .query("UPDATE experiment SET result = ?2, ended_at = ?3 WHERE id = ?1 AND ended_at = ''") | |
| 199 | .run(id, r, now.toISOString()); | |
| 200 | if (changed.changes !== 1) | |
| 201 | return app.db.query("SELECT 1 FROM experiment WHERE id = ?1").get(id) === null ? err("no_experiment") : err("done"); | |
| 202 | app.bus.append({ kind: "pinned.experiment_result", actorId, payload: { id, result: r } }); | |
| 203 | return ok(); | |
| 204 | } | |
| 205 | ||
| 206 | /** Each refusal as the sentence a page, the terminal or a tool shows. */ | |
| 207 | export const EXPERIMENT_WORDS: Record<ExperimentError, string> = { | |
| 208 | no_question: "Say what question the experiment answers.", | |
| 209 | no_experiment: "No such experiment.", | |
| 210 | no_machine: "No pinned forge by that name.", | |
| 211 | done: "That experiment is done: its result is recorded.", | |
| 212 | no_result: "Say what it found in a line.", | |
| 213 | }; |
src/core/migration-pins/20261127220000-experiment.pin deleted −1
| @@ -1,1 +0,0 @@ | ||
| 1 | 9252443746a16e6f9ecda6d8c7596e30e7235528b40b7bf4cdf5264acebda7db |
src/core/migrations/20261127220000-experiment.ts deleted −20
| @@ -1,20 +0,0 @@ | ||
| 1 | // Experiments: a question the owner pays cloud machines to answer, and the result that ends it. | |
| 2 | // `experiment_machine` is each machine's time on an experiment: a machine moved to another one | |
| 3 | // closes its row (`detached_at`) and opens a new one, so the first keeps what it spent. A running | |
| 4 | // machine with no open row is idle spend. Both tables stay small; reads walk them whole. | |
| 5 | export default ` | |
| 6 | CREATE TABLE IF NOT EXISTS experiment ( | |
| 7 | id TEXT PRIMARY KEY, | |
| 8 | question TEXT NOT NULL, | |
| 9 | result TEXT NOT NULL DEFAULT '', | |
| 10 | started_at TEXT NOT NULL, | |
| 11 | ended_at TEXT NOT NULL DEFAULT '' | |
| 12 | ); | |
| 13 | CREATE TABLE IF NOT EXISTS experiment_machine ( | |
| 14 | id INTEGER PRIMARY KEY, | |
| 15 | experiment_id TEXT NOT NULL, | |
| 16 | pinned_id TEXT NOT NULL, | |
| 17 | attached_at TEXT NOT NULL, | |
| 18 | detached_at TEXT NOT NULL DEFAULT '' | |
| 19 | ); | |
| 20 | `; |
src/http/mcp/tools/experiments.ts deleted −53
| @@ -1,53 +0,0 @@ | ||
| 1 | import { EXPERIMENT_WORDS, attachMachine, beginExperiment, experiments, findExperiment, recordResult } from "../../../cloud/experiments.ts"; | |
| 2 | import { good, bad, type Tool, str } from "../shared.ts"; | |
| 3 | ||
| 4 | export const tool: Tool = { | |
| 5 | name: "experiments", | |
| 6 | listedTo: "admin", | |
| 7 | doc: "`{ action, id?, question?, names?, result? }`: cloud spend. `list` (and `idle`), `show` (`id` or words), `begin`, `attach` `names` to `id`, `record_result`.", | |
| 8 | description: "Cloud spend and what it answers (admin).", | |
| 9 | inputSchema: { | |
| 10 | type: "object", | |
| 11 | properties: { | |
| 12 | action: { type: "string", enum: ["list", "show", "begin", "attach", "record_result"] }, | |
| 13 | id: { type: "string", maxLength: 300 }, | |
| 14 | question: { type: "string", maxLength: 300 }, | |
| 15 | names: { type: "array", items: { type: "string", maxLength: 40 }, maxItems: 20 }, | |
| 16 | result: { type: "string", maxLength: 500 }, | |
| 17 | }, | |
| 18 | required: ["action"], | |
| 19 | }, | |
| 20 | // Marked a write so a `ro` token never reads the owner's spend. No action touches a machine | |
| 21 | // (retiring is pinned_forge's), so the forge's agent is never held on it. | |
| 22 | writes: true, | |
| 23 | heldNotWhen: () => true, | |
| 24 | async run(ctx, user, args) { | |
| 25 | if (!user.isAdmin) return bad("not_found", "no such tool here"); | |
| 26 | const db = ctx.app.db; | |
| 27 | const action = str(args["action"]); | |
| 28 | const names = Array.isArray(args["names"]) ? args["names"].map(String) : []; | |
| 29 | if (action === "list") return good(experiments(db)); | |
| 30 | if (action === "begin") { | |
| 31 | const made = beginExperiment(ctx.app, user.id, str(args["question"]), names); | |
| 32 | return made.ok ? good({ says: "Experiment started.", experiment: findExperiment(db, made.value) }) : bad(made.error, EXPERIMENT_WORDS[made.error]); | |
| 33 | } | |
| 34 | // A write names its experiment by id; only `show` takes question words. | |
| 35 | const id = str(args["id"]); | |
| 36 | if (action === "show") { | |
| 37 | const e = findExperiment(db, id); | |
| 38 | return e ? good({ experiment: e }) : bad("no_experiment", EXPERIMENT_WORDS.no_experiment); | |
| 39 | } | |
| 40 | if (action === "attach") { | |
| 41 | if (names.length === 0) return bad("no_machine", EXPERIMENT_WORDS.no_machine); | |
| 42 | for (const n of names) { | |
| 43 | const one = attachMachine(ctx.app, user.id, id, n); | |
| 44 | if (!one.ok) return bad(one.error, EXPERIMENT_WORDS[one.error]); | |
| 45 | } | |
| 46 | return good({ says: `Attached ${names.join(", ")}.`, experiment: findExperiment(db, id) }); | |
| 47 | } | |
| 48 | if (action !== "record_result") return bad("bad_action", "action is list, show, begin, attach or record_result"); | |
| 49 | const done = recordResult(ctx.app, user.id, id, str(args["result"])); | |
| 50 | if (!done.ok) return bad(done.error, EXPERIMENT_WORDS[done.error]); | |
| 51 | return good({ says: "Result recorded: the experiment is done.", experiment: findExperiment(db, id) }); | |
| 52 | }, | |
| 53 | }; |
src/http/mcp/tools/index.ts −1
| @@ -62,7 +62,6 @@ export { tool as egress_grants } from "./egress_grants.ts"; | ||
| 62 | 62 | export { tool as email_verify } from "./email_verify.ts"; |
| 63 | 63 | export { tool as estimate } from "./estimate.ts"; |
| 64 | 64 | export { tool as events } from "./events.ts"; |
| 65 | export { tool as experiments } from "./experiments.ts"; | |
| 66 | 65 | export { tool as explore } from "./explore.ts"; |
| 67 | 66 | export { tool as family } from "./family.ts"; |
| 68 | 67 | export { tool as features } from "./features.ts"; |
src/http/pinned_routes.ts +1 −27
| @@ -8,7 +8,6 @@ | ||
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, fileForge, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts"; |
| 11 | import { EXPERIMENT_WORDS, attachMachine, beginExperiment, experiments, recordResult } from "../cloud/experiments.ts"; | |
| 12 | 11 | import { TARGETS } from "../cloud/targets.ts"; |
| 13 | 12 | import { listCloudAccounts } from "../core/cloud_account.ts"; |
| 14 | 13 | import { lastCheckOf } from "../core/pinned.ts"; |
| @@ -17,7 +16,6 @@ import { getUsersByIds } from "../core/users.ts"; | ||
| 17 | 16 | import { notFoundPage, signInFirst } from "../web/chrome.ts"; |
| 18 | 17 | import { field, readForm } from "../web/form.ts"; |
| 19 | 18 | import { flashTo, page } from "../web/layout.ts"; |
| 20 | import { liveRegionsJs } from "../web/client.ts"; | |
| 21 | 19 | import { pinnedListPage } from "../web/pages/pinned.ts"; |
| 22 | 20 | import { deployPage, issuedPage, nameFor, type DeployForm } from "../web/pinned.ts"; |
| 23 | 21 | import type { Handler, Ctx } from "./context.ts"; |
| @@ -88,7 +86,7 @@ function listPage(ctx: Ctx): Response { | ||
| 88 | 86 | const at = lastCheckOf(ctx.app.db, p.name); |
| 89 | 87 | if (at) checks.set(p.name, at); |
| 90 | 88 | } |
| 91 | return page({ ctx, title: "Pinned forges", scriptJs: liveRegionsJs, body: pinnedListPage(forges.value, { names, checks, domain: getBaseDomain(ctx.app.db), paid: paidOf(ctx), experiments: experiments(ctx.app.db) }) }); | |
| 89 | return page({ ctx, title: "Pinned forges", body: pinnedListPage(forges.value, { names, checks, domain: getBaseDomain(ctx.app.db), paid: paidOf(ctx) }) }); | |
| 92 | 90 | } |
| 93 | 91 | |
| 94 | 92 | /** |
| @@ -127,29 +125,6 @@ async function pinnedAct(ctx: Ctx): Promise<Response> { | ||
| 127 | 125 | return flashTo(ctx, "/pinned", { tone: "success", message }); |
| 128 | 126 | } |
| 129 | 127 | |
| 130 | /** | |
| 131 | * `/pinned/experiment/<act>`: begin an experiment, attach a machine to one, or record its result, | |
| 132 | * through `cloud/experiments.ts` as the terminal and the `experiments` MCP tool do; admin only, | |
| 133 | * same-origin, each refusal its sentence. An act it does not know is not found. | |
| 134 | */ | |
| 135 | async function experimentAct(ctx: Ctx): Promise<Response> { | |
| 136 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 137 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 138 | const act = ctx.params.act ?? ""; | |
| 139 | if (act !== "begin" && act !== "attach" && act !== "result") return notFoundPage(ctx); | |
| 140 | const form = await readForm(ctx, "admin"); | |
| 141 | if (form instanceof Response) return form; | |
| 142 | const who = ctx.auth.user.id; | |
| 143 | const done = | |
| 144 | act === "begin" | |
| 145 | ? beginExperiment(ctx.app, who, field(form, "question"), form.getAll("names").map(String)) | |
| 146 | : act === "attach" | |
| 147 | ? attachMachine(ctx.app, who, field(form, "id"), field(form, "name")) | |
| 148 | : recordResult(ctx.app, who, field(form, "id"), field(form, "result")); | |
| 149 | const said = act === "begin" ? "Experiment begun." : act === "attach" ? `Attached ${field(form, "name")}.` : "Result recorded: the experiment is done."; | |
| 150 | return flashTo(ctx, "/pinned", done.ok ? { tone: "success", message: said } : { tone: "danger", message: EXPERIMENT_WORDS[done.error] }); | |
| 151 | } | |
| 152 | ||
| 153 | 128 | /** Save the domain deployed forges are served on: the same change the API, MCP and terminal make. */ |
| 154 | 129 | async function domainSubmit(ctx: Ctx): Promise<Response> { |
| 155 | 130 | if (!ctx.auth.user) return signInFirst(ctx); |
| @@ -181,7 +156,6 @@ export function pinnedRoutes(router: Router<Handler>): void { | ||
| 181 | 156 | router.add("GET", "/pinned", listPage); |
| 182 | 157 | router.add("POST", "/pinned/domain", domainSubmit); |
| 183 | 158 | router.add("POST", "/pinned/paid", paidSubmit); |
| 184 | router.add("POST", "/pinned/experiment/:act", experimentAct); | |
| 185 | 159 | router.add("POST", "/pinned/:name/:act", pinnedAct); |
| 186 | 160 | router.add("GET", "/deploy-to", deployToPage); |
| 187 | 161 | router.add("POST", "/deploy-to", deployToSubmit); |
src/tui/screens/experiments.ts deleted −155
| @@ -1,155 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Experiments in the terminal, a forge admin's (#16583): the same read as the /pinned page, each | |
| 3 | * experiment with its machines, what it costs a month now, what it has cost and its result, then | |
| 4 | * every machine that costs money on no experiment as idle spend. `b` begins one (a question, then | |
| 5 | * the machines it runs on), `a` attaches machines to the selected experiment, `r` records its | |
| 6 | * result, each through `cloud/experiments.ts`, so the event every write appends updates the page | |
| 7 | * of anyone watching /pinned. Retiring stays on the pinned forges screen. Anyone else sees nothing. | |
| 8 | */ | |
| 9 | ||
| 10 | import { | |
| 11 | EXPERIMENT_KINDS, | |
| 12 | EXPERIMENT_WORDS, | |
| 13 | attachMachine, | |
| 14 | beginExperiment, | |
| 15 | experiments, | |
| 16 | recordResult, | |
| 17 | type Experiment, | |
| 18 | } from "../../cloud/experiments.ts"; | |
| 19 | import { dollars } from "../../cloud/prices.ts"; | |
| 20 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 21 | import { binding } from "../app/keys.ts"; | |
| 22 | import { style } from "../term/style.ts"; | |
| 23 | import { truncate } from "../term/width.ts"; | |
| 24 | import type { Session } from "../session.ts"; | |
| 25 | import { fill, len, split } from "../ui/layout.ts"; | |
| 26 | import { ListState, drawList, later, live, promptScreen, type ListRow } from "./common.ts"; | |
| 27 | import type { PaletteEntry } from "./entries.ts"; | |
| 28 | ||
| 29 | const month = (cents: number): string => `${dollars(cents)}/mo`; | |
| 30 | const names = (raw: string): string[] => raw.split(/[\s,]+/).filter((n) => n !== ""); | |
| 31 | ||
| 32 | export function experimentsScreen(f: Session, ctx: Ctx): Screen { | |
| 33 | const state = new ListState(); | |
| 34 | let note = ""; | |
| 35 | const admin = (): boolean => f.user?.isAdmin === true; | |
| 36 | const read = () => experiments(f.app.db); | |
| 37 | const say = (text: string): void => { | |
| 38 | note = text; | |
| 39 | ctx.invalidate(); | |
| 40 | }; | |
| 41 | const who = (): string => f.user?.id ?? ""; | |
| 42 | ||
| 43 | const begin = (parent: Screen): Screen => | |
| 44 | promptScreen(ctx, parent, { | |
| 45 | title: "Begin an experiment", | |
| 46 | label: "the question this spend answers", | |
| 47 | onSubmit: (question) => | |
| 48 | later(ctx, () => | |
| 49 | promptScreen(ctx, parent, { | |
| 50 | title: "Runs on", | |
| 51 | label: "pinned forge names, space separated; empty to attach later", | |
| 52 | onSubmit: (raw) => { | |
| 53 | const made = beginExperiment(f.app, who(), question, names(raw)); | |
| 54 | if (!made.ok) return EXPERIMENT_WORDS[made.error]; | |
| 55 | say("Experiment begun."); | |
| 56 | return undefined; | |
| 57 | }, | |
| 58 | }), | |
| 59 | ), | |
| 60 | }); | |
| 61 | ||
| 62 | const screen: Screen = { | |
| 63 | title: "Experiments", | |
| 64 | keys: [binding(["j", "k"], "move cursor"), binding(["b"], "begin"), binding(["a"], "attach machines"), binding(["r"], "record result")], | |
| 65 | async load(signal) { | |
| 66 | live(f, signal, { kinds: [...EXPERIMENT_KINDS, "pinned.deployed", "pinned.retired"] }, () => ctx.invalidate()); | |
| 67 | }, | |
| 68 | render(area, s) { | |
| 69 | const c = ctx.theme.c; | |
| 70 | const [head, list] = split(area, "v", [len(1), fill(1)]); | |
| 71 | if (!admin()) { | |
| 72 | s.text(head!.x, head!.y, truncate("Experiments are a forge admin's.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 73 | return; | |
| 74 | } | |
| 75 | const x = read(); | |
| 76 | const text = | |
| 77 | note !== "" | |
| 78 | ? note | |
| 79 | : `Every pinned forge: ${month(x.monthlyCents)}. ${x.items.length === 0 ? "Press b to begin an experiment." : ""}`; | |
| 80 | s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 81 | const rows: ListRow[] = [ | |
| 82 | ...x.items.map((e) => ({ | |
| 83 | title: e.question, | |
| 84 | secondary: `${e.state} · ${ | |
| 85 | e.machines | |
| 86 | .filter((m) => m.until === "") | |
| 87 | .map((m) => m.name) | |
| 88 | .join(", ") || "no machine" | |
| 89 | } · ${month(e.monthlyCents)} now · ${dollars(e.spentCents)} so far${e.result === "" ? "" : ` · ${e.result}`}`, | |
| 90 | meta: e.startedAt.slice(0, 10), | |
| 91 | })), | |
| 92 | ...x.idle.map((m) => ({ | |
| 93 | title: `idle: ${m.name}`, | |
| 94 | tone: "danger" as const, | |
| 95 | secondary: `${m.account} · ${m.state} · ${month(m.monthlyCents)} · on no experiment`, | |
| 96 | meta: "", | |
| 97 | })), | |
| 98 | ]; | |
| 99 | drawList(s, list!, c, state, rows); | |
| 100 | }, | |
| 101 | key(e) { | |
| 102 | const x = read(); | |
| 103 | if (state.key(e, x.items.length + x.idle.length)) return true; | |
| 104 | if (e.ctrl || e.alt || !admin()) return false; | |
| 105 | if (e.key === "b") { | |
| 106 | ctx.push(begin(screen)); | |
| 107 | return true; | |
| 108 | } | |
| 109 | const picked: Experiment | undefined = x.items[state.index]; | |
| 110 | if (e.key !== "a" && e.key !== "r") return false; | |
| 111 | if (picked === undefined) { | |
| 112 | say("Select an experiment first."); | |
| 113 | return true; | |
| 114 | } | |
| 115 | ctx.push( | |
| 116 | e.key === "a" | |
| 117 | ? promptScreen(ctx, screen, { | |
| 118 | title: `Attach to: ${picked.question}`, | |
| 119 | label: "pinned forge names, space separated", | |
| 120 | onSubmit: (raw) => { | |
| 121 | for (const n of names(raw)) { | |
| 122 | const one = attachMachine(f.app, who(), picked.id, n); | |
| 123 | if (!one.ok) return EXPERIMENT_WORDS[one.error]; | |
| 124 | } | |
| 125 | say("Attached."); | |
| 126 | return undefined; | |
| 127 | }, | |
| 128 | }) | |
| 129 | : promptScreen(ctx, screen, { | |
| 130 | title: `What did it find? ${picked.question}`, | |
| 131 | label: "the result, in a line; it marks the experiment done", | |
| 132 | onSubmit: (result) => { | |
| 133 | const done = recordResult(f.app, who(), picked.id, result); | |
| 134 | if (!done.ok) return EXPERIMENT_WORDS[done.error]; | |
| 135 | say("Result recorded: the experiment is done."); | |
| 136 | return undefined; | |
| 137 | }, | |
| 138 | }), | |
| 139 | ); | |
| 140 | return true; | |
| 141 | }, | |
| 142 | }; | |
| 143 | return screen; | |
| 144 | } | |
| 145 | ||
| 146 | /** Experiments, as the /pinned page and the MCP have them: a forge admin. */ | |
| 147 | export const entry: PaletteEntry = { | |
| 148 | rank: 871, | |
| 149 | id: "experiments", | |
| 150 | title: "Experiments", | |
| 151 | hint: "what each cloud machine costs and answers", | |
| 152 | after: ["pinned"], | |
| 153 | offered: (session) => session.user?.isAdmin === true, | |
| 154 | run: (session, ctx) => ctx.push(experimentsScreen(session, ctx)), | |
| 155 | }; |
src/web/pages/pinned.ts +3 −68
| @@ -5,12 +5,10 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { PinnedView } from "../../actions/pinned.ts"; |
| 8 | import type { Experiment, Experiments, Machine } from "../../cloud/experiments.ts"; | |
| 9 | 8 | import { dollars } from "../../cloud/prices.ts"; |
| 10 | 9 | import { HOST_CAN } from "../../core/pinned.ts"; |
| 11 | import { pageHead } from "../chrome.ts"; | |
| 12 | 10 | import { html, type Html } from "../html.ts"; |
| 13 | import { badge, btn, field, row, rowList, time, type Tone } from "../ui.ts"; | |
| 11 | import { badge, btn, field, time, type Tone } from "../ui.ts"; | |
| 14 | 12 | |
| 15 | 13 | const TONE: Record<string, Tone> = { running: "success", failed: "danger" }; |
| 16 | 14 | |
| @@ -22,8 +20,6 @@ export interface PinnedFacts { | ||
| 22 | 20 | readonly domain: string; |
| 23 | 21 | /** Where paid forges run: `hosted` (when absent), or the cloud account named `provider/name`. */ |
| 24 | 22 | readonly paid?: string; |
| 25 | /** Every experiment and the idle spend, from `experiments`; absent shows no section. */ | |
| 26 | readonly experiments?: Experiments; | |
| 27 | 23 | } |
| 28 | 24 | |
| 29 | 25 | const fact = (label: string, value: Html): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`; |
| @@ -76,70 +72,10 @@ function actions(p: PinnedView): Html { | ||
| 76 | 72 | </div>`; |
| 77 | 73 | } |
| 78 | 74 | |
| 79 | const month = (cents: number): string => `${dollars(cents)} a month`; | |
| 80 | const machineLine = (m: Machine): Html => | |
| 81 | html`<a class="mono" href="#forge-${m.name}">${m.name}</a> on ${m.account}, ${m.until === "" ? m.state : "moved on"}, ${month(m.monthlyCents)}`; | |
| 82 | ||
| 83 | /** A select of the experiments still running, to move machine `name` onto one. */ | |
| 84 | function attachForm(name: string, running: Experiment[]): Html | null { | |
| 85 | if (running.length === 0) return null; | |
| 86 | return html`<form method="post" action="/pinned/experiment/attach" class="row-fields"> | |
| 87 | <input type="hidden" name="name" value="${name}" /> | |
| 88 | <select class="input" name="id" aria-label="Experiment for ${name}">${running.map((e) => html`<option value="${e.id}">${e.question}</option>`)}</select> | |
| 89 | ${btn("Attach", { size: "sm", variant: "secondary", label: `Attach ${name} to an experiment` })} | |
| 90 | </form>`; | |
| 91 | } | |
| 92 | ||
| 93 | /** One row an experiment: its question, then machines, cost now, what it has cost and its result. */ | |
| 94 | function experimentRow(e: Experiment): Html { | |
| 95 | return row({ | |
| 96 | title: e.question, | |
| 97 | data: { experiment: e.id }, | |
| 98 | trail: badge(e.state, { tone: e.state === "running" ? "success" : "default" }), | |
| 99 | facts: [ | |
| 100 | { label: "Runs on", value: e.machines.length === 0 ? "no machine yet" : html`${e.machines.map((m, i) => html`${i > 0 ? "; " : ""}${machineLine(m)}`)}` }, | |
| 101 | { label: "Costs now", value: month(e.monthlyCents) }, | |
| 102 | { label: "Has cost", value: `about ${dollars(e.spentCents)} since ${e.startedAt.slice(0, 10)}` }, | |
| 103 | { label: "Result", value: e.result === "" ? "not recorded" : e.result }, | |
| 104 | ], | |
| 105 | after: | |
| 106 | e.state === "running" | |
| 107 | ? html`<form method="post" action="/pinned/experiment/result" class="row-fields"> | |
| 108 | <input type="hidden" name="id" value="${e.id}" /> | |
| 109 | <input class="input" name="result" maxlength="500" required placeholder="What it found, in a line" aria-label="Result of: ${e.question}" /> | |
| 110 | ${btn("Record result", { size: "sm", variant: "secondary" })} | |
| 111 | </form>` | |
| 112 | : e.monthlyCents > 0 | |
| 113 | ? html`<p role="status">Done; its machines still cost ${month(e.monthlyCents)} until retired below.</p>` | |
| 114 | : html``, | |
| 115 | }); | |
| 116 | } | |
| 117 | ||
| 118 | /** | |
| 119 | * Experiments first: what the cloud spend buys, and the machines that buy nothing. The region | |
| 120 | * `#experiments` is a live region: the page's shared client (`liveRegionsJs`) swaps it in when | |
| 121 | * any `pinned.*` event reaches it on /events, so a change from any door shows in place. | |
| 122 | */ | |
| 123 | function experimentsSection(x: Experiments, forges: readonly Pick<PinnedView, "name" | "state">[]): Html { | |
| 124 | const running = x.items.filter((e) => e.state === "running"); | |
| 125 | const busy = new Set(x.items.flatMap((e) => e.machines.filter((m) => m.until === "").map((m) => m.name))); | |
| 126 | const free = forges.filter((p) => p.state !== "retired" && !busy.has(p.name)); | |
| 127 | return html`<section id="experiments" data-experiments data-live="pinned.*"> | |
| 128 | <h2>Experiments</h2> | |
| 129 | ${x.idle.length === 0 ? null : html`<h3>Idle spend</h3><div data-idle>${rowList(x.idle.map((m) => row({ title: machineLine(m), after: html`${m.state === "retired" ? null : attachForm(m.name, running)} <a href="#forge-${m.name}">Retire</a>` })))}</div>`} | |
| 130 | ${x.items.length === 0 ? html`<p role="status">No experiment yet.</p>` : rowList(x.items.map(experimentRow))} | |
| 131 | <form method="post" action="/pinned/experiment/begin" class="stack"> | |
| 132 | ${field({ name: "question", label: "New experiment", required: true, placeholder: "What question does this spend answer?", maxlength: 300 })} | |
| 133 | ${free.length === 0 ? null : html`<fieldset><legend>Runs on</legend>${free.map((p) => html`<label><input type="checkbox" name="names" value="${p.name}" /> <span class="mono">${p.name}</span></label> `)}</fieldset>`} | |
| 134 | ${btn("Begin experiment", { variant: "secondary" })} | |
| 135 | </form> | |
| 136 | </section>`; | |
| 137 | } | |
| 138 | ||
| 139 | 75 | function forge(p: PinnedView, f: PinnedFacts): Html { |
| 140 | 76 | const last = p.changes[0]; |
| 141 | 77 | const checked = f.checks.get(p.name); |
| 142 | return html`<section id="forge-${p.name}"> | |
| 78 | return html`<section> | |
| 143 | 79 | <h2 class="mono">${p.name}</h2> |
| 144 | 80 | <dl class="status-rows"> |
| 145 | 81 | ${fact("App", html`<span class="mono">${p.app}</span>`)} |
| @@ -160,9 +96,8 @@ function forge(p: PinnedView, f: PinnedFacts): Html { | ||
| 160 | 96 | } |
| 161 | 97 | |
| 162 | 98 | export function pinnedListPage(forges: PinnedView[], f: PinnedFacts): Html { |
| 163 | return html`${pageHead("Pinned forges", { sub: "The forges you run on your own cloud, and the question each one's spend answers." })} | |
| 99 | return html`<div class="page-head"><h1>Pinned forges</h1></div> | |
| 164 | 100 | <p><a href="/deploy-to">Deploy a pinned forge</a></p> |
| 165 | ${f.experiments === undefined ? null : experimentsSection(f.experiments, forges)} | |
| 166 | 101 | <form method="post" action="/pinned/domain" class="stack"> |
| 167 | 102 | ${field({ name: "domain", label: "Domain for deployed forges", value: f.domain, placeholder: "forges.example.com", mono: true, maxlength: 253, spellcheck: false, hint: "A forge deployed with no hostname is served on <name>.<domain>, so its buyer configures no DNS. With a Cloudflare account that allows writes and a token that can edit the zone, the forge writes the record itself, after every replace too. Empty for none." })} |
| 168 | 103 | ${btn("Save", { variant: "secondary", label: "Save the domain for deployed forges" })} |
test/conversation-confirm.test.ts +1 −1
| @@ -125,7 +125,7 @@ describe("the one list of what asks first", () => { | ||
| 125 | 125 | const NOT_ASKED = new Set([ |
| 126 | 126 | "access", "account_requests", "apps", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide", "atlas", |
| 127 | 127 | "asks", "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "valves", "cloud_accounts", "close", "confirm_wait", |
| 128 | "crew", "decisions_by", "desk", "detach", "economics", "edit", "experiments", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner", | |
| 128 | "crew", "decisions_by", "desk", "detach", "economics", "edit", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner", | |
| 129 | 129 | "follow_mode", "forge", "fork", "front_page", "hold", "issue_teams", "keep_plan", "knobs", "labels", "lift", "limb", "maintenance", "make_it_yours", "map", "merge", "new_app", |
| 130 | 130 | "next_up", "week", "notify", "open_pull", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports", |
| 131 | 131 | "repo", "restore_drill", "review", "say", "scorecard", "signup", "snapshot_now", "spend", "steer", "sync", "system", "take_back", "take_updates", |
test/experiments-routes.test.ts deleted −99
| @@ -1,99 +0,0 @@ | ||
| 1 | /** | |
| 2 | * The /pinned experiment routes (#16583): a guest is sent to sign in, anyone but an admin is | |
| 3 | * refused, a cross-origin POST is refused, each act's success and refusal land back on /pinned as | |
| 4 | * a flash, and an act it does not know is not found. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { experiments } from "../src/cloud/experiments.ts"; | |
| 12 | import { insertPinned, setRemote } from "../src/core/pinned.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 { quietLogs } from "./helpers/globals.ts"; | |
| 17 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | describe("experiment routes", () => { | |
| 22 | let dataDir = ""; | |
| 23 | let app: App; | |
| 24 | let servers: Servers; | |
| 25 | let adminTok = ""; | |
| 26 | let bobTok = ""; | |
| 27 | const post = (path: string, body: Record<string, string>, tok?: string, origin = servers.url) => | |
| 28 | fetch(servers.url + path, { | |
| 29 | method: "POST", redirect: "manual", | |
| 30 | headers: { ...(tok ? { authorization: `Bearer ${tok}` } : {}), origin, "content-type": "application/x-www-form-urlencoded" }, | |
| 31 | body: new URLSearchParams(body), | |
| 32 | }); | |
| 33 | /** The flash a redirect to /pinned carries in its cookie (`web/flash.ts`). */ | |
| 34 | const landed = async (r: Response, _tok: string): Promise<string> => { | |
| 35 | expect(r.status).toBe(303); | |
| 36 | expect(r.headers.get("location") ?? "").toStartWith("/pinned"); | |
| 37 | return decodeURIComponent(r.headers.get("set-cookie") ?? ""); | |
| 38 | }; | |
| 39 | ||
| 40 | beforeAll(async () => { | |
| 41 | dataDir = await mkdtemp(join(tmpdir(), "forge-experiment-routes-")); | |
| 42 | app = createApp({ dataDir, port: 0 }); | |
| 43 | await seedPlaces(app.db); | |
| 44 | servers = await serve(app); | |
| 45 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { | |
| 46 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 47 | if (!made.ok) throw new Error(made.error); | |
| 48 | } | |
| 49 | adminTok = createToken(app.db, getUserByName(app.db, "alice")!.id, "admin", "admin").token; | |
| 50 | bobTok = createToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token; | |
| 51 | insertPinned(app.db, { | |
| 52 | name: "friend1", target: "digitalocean", account: "main", app: "trevato/forge", source: "https://forge.example.org/trevato/forge", | |
| 53 | version: "a".repeat(40), config: {}, host: "friend1.forge.test", claimHash: "", claimExpires: "", datacenter: "nyc3", size: "s-1vcpu-2gb", | |
| 54 | }, getUserByName(app.db, "alice")!.id); | |
| 55 | setRemote(app.db, "friend1", { remote: "d-1", volume: "v-1", state: "running" }); | |
| 56 | }, 30_000); | |
| 57 | ||
| 58 | afterAll(async () => { | |
| 59 | servers.stop(); | |
| 60 | app.close(); | |
| 61 | await rm(dataDir, { recursive: true, force: true }); | |
| 62 | }); | |
| 63 | ||
| 64 | // As pinned-page.test.ts has it: signed out, /pinned sends to sign-in; a non-admin's admin-scope | |
| 65 | // token is refused (403) before any form route runs; a signed-out POST changes nothing. | |
| 66 | test("a guest is sent to sign in, and anyone but an admin is refused", async () => { | |
| 67 | const page = await fetch(`${servers.url}/pinned`, { redirect: "manual" }); | |
| 68 | expect(page.status, "a guest reading /pinned").toBe(303); | |
| 69 | expect(page.headers.get("location") ?? "", "where a guest is sent").toContain("/signin"); | |
| 70 | const guest = await post("/pinned/experiment/begin", { question: "q" }); | |
| 71 | expect([303, 401, 403], `a guest's POST answered ${guest.status}`).toContain(guest.status); | |
| 72 | expect(guest.headers.get("location") ?? "", "a guest's POST never lands on /pinned").not.toStartWith("/pinned"); | |
| 73 | expect((await post("/pinned/experiment/begin", { question: "q" }, bobTok)).status, "a non-admin's POST").toBe(403); | |
| 74 | expect((await fetch(`${servers.url}/pinned`, { redirect: "manual", headers: { authorization: `Bearer ${bobTok}` } })).status, "a non-admin reading /pinned").not.toBe(200); | |
| 75 | expect(experiments(app.db).items, "nothing was begun").toEqual([]); | |
| 76 | }); | |
| 77 | ||
| 78 | test("a cross-origin POST is refused and changes nothing", async () => { | |
| 79 | const r = await post("/pinned/experiment/begin", { question: "From elsewhere?" }, adminTok, "https://evil.example"); | |
| 80 | expect(r.status).toBe(403); | |
| 81 | expect(experiments(app.db).items).toEqual([]); | |
| 82 | }); | |
| 83 | ||
| 84 | test("an act it does not know is not found", async () => { | |
| 85 | expect((await post("/pinned/experiment/retire", { id: "x" }, adminTok)).status).toBe(404); | |
| 86 | }); | |
| 87 | ||
| 88 | test("begin, attach and result each say what happened, and each refusal says why", async () => { | |
| 89 | expect(await landed(await post("/pinned/experiment/begin", { question: "" }, adminTok), adminTok)).toContain("Say what question the experiment answers."); | |
| 90 | expect(await landed(await post("/pinned/experiment/begin", { question: "Will a friend use it?" }, adminTok), adminTok)).toContain("Experiment begun."); | |
| 91 | const id = experiments(app.db).items[0]!.id; | |
| 92 | expect(await landed(await post("/pinned/experiment/attach", { id, name: "ghost" }, adminTok), adminTok)).toContain("No pinned forge by that name."); | |
| 93 | expect(await landed(await post("/pinned/experiment/attach", { id, name: "friend1" }, adminTok), adminTok)).toContain("Attached friend1."); | |
| 94 | expect(await landed(await post("/pinned/experiment/result", { id, result: "" }, adminTok), adminTok)).toContain("Say what it found in a line."); | |
| 95 | expect(await landed(await post("/pinned/experiment/result", { id, result: "Not yet." }, adminTok), adminTok)).toContain("Result recorded: the experiment is done."); | |
| 96 | expect(await landed(await post("/pinned/experiment/result", { id, result: "Again." }, adminTok), adminTok)).toContain("That experiment is done"); | |
| 97 | expect(experiments(app.db).items[0]).toMatchObject({ state: "done", result: "Not yet." }); | |
| 98 | }); | |
| 99 | }); |
test/experiments.test.ts deleted −197
| @@ -1,197 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Experiments (#16583): what the cloud spend buys. The /pinned page shows an experiment with its | |
| 3 | * machine and monthly cost, a running pinned forge on no experiment as idle spend; a recorded | |
| 4 | * result marks it done; a machine moved to a second experiment leaves the first what it spent; | |
| 5 | * every write appends an event naming who did it; the `experiments` MCP tool and the terminal | |
| 6 | * screen read and write the same rows. No socket: the routes are in experiments-routes.test.ts. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { pinnedForges } from "../src/actions/pinned.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { EXPERIMENT_KINDS, attachMachine, beginExperiment, experiments, findExperiment, recordResult } from "../src/cloud/experiments.ts"; | |
| 15 | import { dollars } from "../src/cloud/prices.ts"; | |
| 16 | import type { ForgeEvent } from "../src/core/events.ts"; | |
| 17 | import { insertPinned, setRemote } from "../src/core/pinned.ts"; | |
| 18 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 19 | import { tool } from "../src/http/mcp/tools/experiments.ts"; | |
| 20 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 21 | import { experimentsScreen } from "../src/tui/screens/experiments.ts"; | |
| 22 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 23 | import { pinnedListPage } from "../src/web/pages/pinned.ts"; | |
| 24 | import { quietLogs } from "./helpers/globals.ts"; | |
| 25 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 26 | import { settleApp } from "./helpers/tui.ts"; | |
| 27 | ||
| 28 | quietLogs(); | |
| 29 | ||
| 30 | describe("experiments", () => { | |
| 31 | let dataDir = ""; | |
| 32 | let app: App; | |
| 33 | let admin: User; | |
| 34 | const seen: ForgeEvent[] = []; | |
| 35 | const render = (): string => { | |
| 36 | const forges = pinnedForges(app, admin); | |
| 37 | if (!forges.ok) throw new Error("not admin"); | |
| 38 | return String(pinnedListPage(forges.value, { names: new Map(), checks: new Map(), domain: "", experiments: experiments(app.db) })); | |
| 39 | }; | |
| 40 | const call = async (args: Record<string, unknown>): Promise<any> => | |
| 41 | tool.run({ app, auth: { user: admin, scope: "admin" } } as any, admin, args); | |
| 42 | const DAY = 86_400_000; | |
| 43 | ||
| 44 | beforeAll(async () => { | |
| 45 | dataDir = await mkdtemp(join(tmpdir(), "forge-experiments-")); | |
| 46 | app = createApp({ dataDir, port: 0 }); | |
| 47 | await seedPlaces(app.db); | |
| 48 | const made = await createUser(app.db, { | |
| 49 | origin: "seed", | |
| 50 | trusted: true, | |
| 51 | username: "alice", | |
| 52 | email: "[email protected]", | |
| 53 | password: "a-good-passphrase", | |
| 54 | adminIfFirst: true, | |
| 55 | }); | |
| 56 | if (!made.ok) throw new Error(made.error); | |
| 57 | admin = getUserByName(app.db, "alice")!; | |
| 58 | for (const name of ["friend1", "spare"]) { | |
| 59 | insertPinned( | |
| 60 | app.db, | |
| 61 | { | |
| 62 | name, | |
| 63 | target: "digitalocean", | |
| 64 | account: "main", | |
| 65 | app: "trevato/forge", | |
| 66 | source: "https://forge.example.org/trevato/forge", | |
| 67 | version: "a".repeat(40), | |
| 68 | config: {}, | |
| 69 | host: `${name}.forge.test`, | |
| 70 | claimHash: "", | |
| 71 | claimExpires: "", | |
| 72 | datacenter: "nyc3", | |
| 73 | size: "s-1vcpu-2gb", | |
| 74 | }, | |
| 75 | admin.id, | |
| 76 | ); | |
| 77 | setRemote(app.db, name, { remote: `d-${name}`, volume: `v-${name}`, state: "running" }); | |
| 78 | } | |
| 79 | app.bus.subscribe((e) => { | |
| 80 | if ((EXPERIMENT_KINDS as readonly string[]).includes(e.kind)) seen.push(e); | |
| 81 | }, "local"); | |
| 82 | }, 30_000); | |
| 83 | ||
| 84 | afterAll(async () => { | |
| 85 | app.close(); | |
| 86 | await rm(dataDir, { recursive: true, force: true }); | |
| 87 | }); | |
| 88 | ||
| 89 | test("two running machines on no experiment are both idle spend", () => { | |
| 90 | const x = experiments(app.db); | |
| 91 | expect(x.items).toEqual([]); | |
| 92 | expect(x.idle.map((m) => m.name)).toEqual(["friend1", "spare"]); | |
| 93 | expect(x.idle[0]!.monthlyCents).toBeGreaterThan(0); | |
| 94 | expect(x.monthlyCents).toBe(x.idle[0]!.monthlyCents * 2); | |
| 95 | }); | |
| 96 | ||
| 97 | test("the page shows an experiment as one row with its machine and monthly cost, the other machine as idle spend", () => { | |
| 98 | const begun = beginExperiment(app, admin.id, "Will a friend claim and use a forge?", ["friend1"]); | |
| 99 | expect(begun.ok).toBe(true); | |
| 100 | const x = experiments(app.db); | |
| 101 | const e = x.items[0]!; | |
| 102 | expect(e).toMatchObject({ question: "Will a friend claim and use a forge?", state: "running", result: "" }); | |
| 103 | expect(e.machines.map((m) => [m.name, m.account, m.until])).toEqual([["friend1", "digitalocean/main", ""]]); | |
| 104 | expect(e.monthlyCents).toBeGreaterThan(0); | |
| 105 | expect(x.idle.map((m) => m.name)).toEqual(["spare"]); | |
| 106 | ||
| 107 | const page = render(); | |
| 108 | expect(page).toContain("the question each one's spend answers"); | |
| 109 | expect(page).toContain(`data-experiment="${e.id}"`); | |
| 110 | expect(page).toContain(`${dollars(e.monthlyCents)} a month`); | |
| 111 | const region = page.slice(page.indexOf('id="experiments"'), page.indexOf("</section>", page.indexOf('id="experiments"'))); | |
| 112 | expect(region).not.toMatch(/status-rows|<section data-experiment/); | |
| 113 | expect(region).toContain('class="row-facts"'); | |
| 114 | const idle = page.slice(page.indexOf("data-idle"), page.indexOf("</ul>", page.indexOf("data-idle"))); | |
| 115 | expect(idle).toContain("spare"); | |
| 116 | expect(idle).not.toContain(">friend1<"); | |
| 117 | expect(idle).toContain("Retire"); | |
| 118 | expect(page).toContain('action="/pinned/experiment/result"'); | |
| 119 | }); | |
| 120 | ||
| 121 | test("a machine moved to a second experiment leaves the first what it spent, and a done one keeps its row", () => { | |
| 122 | const first = experiments(app.db).items[0]!; | |
| 123 | const t0 = new Date(Date.now() + 10 * DAY); | |
| 124 | const second = beginExperiment(app, admin.id, "Does Hetzner boot faster?", [], t0); | |
| 125 | if (!second.ok) throw new Error(second.error); | |
| 126 | expect(attachMachine(app, admin.id, second.value, "friend1", t0).ok).toBe(true); | |
| 127 | const later = new Date(Date.now() + 20 * DAY); | |
| 128 | const after = experiments(app.db, later); | |
| 129 | const was = after.items.find((e) => e.id === first.id)!; | |
| 130 | expect(was.machines.map((m) => m.name)).toEqual(["friend1"]); | |
| 131 | expect(was.machines[0]!.until).not.toBe(""); | |
| 132 | expect(was.monthlyCents).toBe(0); | |
| 133 | // About ten days at the monthly rate, and no more for the ten days after it moved. | |
| 134 | expect(was.spentCents).toBe(findExperiment(app.db, first.id, t0)!.spentCents); | |
| 135 | expect(was.spentCents).toBeGreaterThan(0); | |
| 136 | const now = after.items.find((e) => e.id === second.value)!; | |
| 137 | expect(now.machines.map((m) => [m.name, m.until])).toEqual([["friend1", ""]]); | |
| 138 | // Back again: the first experiment opens a new row and keeps the old one. | |
| 139 | expect(attachMachine(app, admin.id, first.id, "friend1", later).ok).toBe(true); | |
| 140 | expect(findExperiment(app.db, first.id, later)!.machines.map((m) => m.until === "")).toEqual([false, true]); | |
| 141 | expect(attachMachine(app, admin.id, "nope", "friend1").ok).toBe(false); | |
| 142 | }); | |
| 143 | ||
| 144 | test("recording a result marks it done, stops its cost counting, says its machines still cost, and refuses a move onto it", () => { | |
| 145 | const id = findExperiment(app.db, "friend claim")!.id; | |
| 146 | expect(recordResult(app, admin.id, id, "").ok).toBe(false); | |
| 147 | expect(recordResult(app, admin.id, id, "Nobody claimed it in five days; retire it.").ok).toBe(true); | |
| 148 | expect(recordResult(app, admin.id, id, "again")).toEqual({ ok: false, error: "done" }); | |
| 149 | expect(attachMachine(app, admin.id, id, "spare")).toEqual({ ok: false, error: "done" }); | |
| 150 | const e = findExperiment(app.db, "friend claim", new Date(Date.now() + 40 * DAY))!; | |
| 151 | expect(e).toMatchObject({ id, state: "done", result: "Nobody claimed it in five days; retire it." }); | |
| 152 | expect(e.spentCents).toBe(findExperiment(app.db, id)!.spentCents); | |
| 153 | const page = render(); | |
| 154 | expect(page).toContain("Nobody claimed it in five days; retire it."); | |
| 155 | expect(page).toContain("its machines still cost"); | |
| 156 | }); | |
| 157 | ||
| 158 | test("every write appended an event naming who did it", () => { | |
| 159 | expect(new Set(seen.map((e) => e.kind))).toEqual(new Set(EXPERIMENT_KINDS)); | |
| 160 | expect(seen.every((e) => e.actorId === admin.id)).toBe(true); | |
| 161 | expect(seen.find((e) => e.kind === "pinned.experiment_attached" && e.payload["from"] !== "")).toBeDefined(); | |
| 162 | }); | |
| 163 | ||
| 164 | test("the MCP tool reads the same as the page, begins, attaches and records by id, and is never held", async () => { | |
| 165 | expect(await call({ action: "list" })).toEqual({ ok: true, value: experiments(app.db) }); | |
| 166 | expect((await call({ action: "show", id: "friend claim" })).value.experiment.state).toBe("done"); | |
| 167 | expect((await call({ action: "show", id: "no such thing" })).ok).toBe(false); | |
| 168 | expect((await call({ action: "begin", question: "x", names: ["ghost"] })).ok).toBe(false); | |
| 169 | const begun = await call({ action: "begin", question: "Is a 1 GB machine enough?" }); | |
| 170 | const id = begun.value.experiment.id as string; | |
| 171 | expect((await call({ action: "attach", id, names: ["spare"] })).ok).toBe(true); | |
| 172 | expect(experiments(app.db).idle).toEqual([]); | |
| 173 | expect((await call({ action: "record_result", id: "1 GB", result: "Yes." })).ok).toBe(false); | |
| 174 | expect((await call({ action: "record_result", id, result: "Yes, under light use." })).value.experiment.state).toBe("done"); | |
| 175 | expect(["list", "show", "begin", "attach", "record_result"].filter((action) => tool.heldNotWhen?.({ action }) !== true)).toEqual([]); | |
| 176 | }); | |
| 177 | ||
| 178 | test("the terminal screen lists the same experiments and records a result an admin types", async () => { | |
| 179 | const id = beginExperiment(app, admin.id, "Does the terminal reach the page?", [], new Date(Date.now() + 100 * DAY)); | |
| 180 | if (!id.ok) throw new Error(id.error); | |
| 181 | const { app: tui, session } = createForgeApp( | |
| 182 | app, | |
| 183 | { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, | |
| 184 | { terminal: headlessTerminal(160, 24), exitHooks: false }, | |
| 185 | ); | |
| 186 | tui.start(); | |
| 187 | tui.ctx.push(experimentsScreen(session, tui.ctx)); | |
| 188 | await settleApp(tui); | |
| 189 | expect(tui.screen.toText()).toContain("Does the terminal reach the page?"); | |
| 190 | const before = seen.length; | |
| 191 | for (const key of ["r", ..."It does.", "enter"]) tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 192 | await settleApp(tui); | |
| 193 | expect(findExperiment(app.db, id.value)!).toMatchObject({ state: "done", result: "It does." }); | |
| 194 | expect(seen.slice(before).map((e) => e.kind)).toEqual(["pinned.experiment_result"]); | |
| 195 | tui.stop?.(); | |
| 196 | }); | |
| 197 | }); |
test/mcp-forge-protocol.test.ts −1
test/mixed-actions-held.test.ts −1
| @@ -48,7 +48,6 @@ const MIXED: Readonly< | ||
| 48 | 48 | maintenance: { key: "action", reads: [{ action: "status" }] }, |
| 49 | 49 | restore_drill: { key: "action", reads: [{ action: "status" }] }, |
| 50 | 50 | egress_grants: { key: "op", reads: [{ repo: "o/r", op: "list" }] }, |
| 51 | experiments: { key: "action", reads: [{ action: "list" }, { action: "show", id: "x" }] }, | |
| 52 | 51 | pinned_forge: { key: "verb", reads: [{ verb: "list" }] }, |
| 53 | 52 | proposal_tokens: { key: "verb", reads: [{ verb: "list" }] }, |
| 54 | 53 | app_env: { key: "action", reads: [{ repo: "o/r", action: "list" }] }, |
test/palette-roster.test.ts −2
| @@ -227,7 +227,6 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 227 | 227 | ["planner", "Planner", "its last pass, its spend this week and what became of what it filed"], |
| 228 | 228 | ["cloud", "Cloud accounts", "provider tokens, what they are used for, today's calls"], |
| 229 | 229 | ["pinned", "Pinned forges", "deploy, update and roll back a forge on your cloud"], |
| 230 | ["experiments", "Experiments", "what each cloud machine costs and answers"], | |
| 231 | 230 | ["bets", "Bets", "back, stop and finish a repository\'s bets"], |
| 232 | 231 | ["origins", "Connected accounts", "the hosts your mirrors come from"], |
| 233 | 232 | ["domains", "Failure domains", "failure domains and their last drill"], |
| @@ -342,7 +341,6 @@ test("a site-admin agent is offered the roster without the person-only entries", | ||
| 342 | 341 | ["planner", "Planner", "its last pass, its spend this week and what became of what it filed"], |
| 343 | 342 | ["cloud", "Cloud accounts", "provider tokens, what they are used for, today's calls"], |
| 344 | 343 | ["pinned", "Pinned forges", "deploy, update and roll back a forge on your cloud"], |
| 345 | ["experiments", "Experiments", "what each cloud machine costs and answers"], | |
| 346 | 344 | ["feed", "Feed", "what happened, ranked; r replies on a post about an issue or pull, l likes, h who liked, p its permalink, o a run's log"], |
| 347 | 345 | ["feature-feed", "Feature feeds", "the feed items about an absorbed app, as Settings › Features shows them"], |
| 348 | 346 | ["front", "Front page", "the apps a first visitor sees, ranked; an admin pins or hides"], |
new above
offline