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

Games, Infrastructure and the other areas are in the navigation, for everyone who may use them #17633

opened this in answer to

Merged 13h 33m ago, live in production

mason/forge:mason/17627-games-infrastructure-and-the-other-areas → main 0 commits fork

  • Merged. mason/17627-games-infrastructure-and-the-other-areas was merged into main as 3782234.

Review

Sign in to review this change.
27 files changed +455 −10
docs/features/areas.md added +23
@@ -0,0 +1,23 @@
1 ---
2 topic: Getting around: keys, the palette and search
3 row: Areas
4 ---
5 # Areas
6
7 How the forge's areas lead to one another. The top bar's own list of areas is `GO_PAGES` in `src/web/go_pages.ts`; this page is about the links that list does not draw.
8
9 ## Links between areas
10
11 - A game box's machine row opens that machine on Infrastructure (an admin).
12 - A machine on Infrastructure has a Game box or App button for what runs on it.
13 - An app's More menu has Cost, its last 30 days (`/<owner>/<app>/cost`); the terminal reads the same in Usage for that repository.
14
15 ## Your game servers on the first page
16
17 A person who was given a game box sees it on the first page, under "Your game servers", one tap to its page (`src/web/game_strip.ts`; an admin's reach over every box is not a grant, so for them `/games` is the way). The terminal's first screen has the same line, "Game servers: …".
18
19 ## Run an app on a machine of its own
20
21 An admin finds "Run it on its own machine" on the app's page (`src/web/studio/app.ts`); it opens Infrastructure's Build (`/infra/build?app=owner/name`) with the app chosen and the machine for running it, and says what the cheapest place costs a month before anything is built (`ownMachineOffer` in `src/actions/infra.ts`). In the terminal, the palette's "Run an app on its own machine" asks for the repository and opens the same compose at Where, the price on each place.
22
23 Search finds Infrastructure and Build for "machine", "server", "cloud", "infra" and "deploy" (an admin only; `src/core/area_pages.ts`), on the page under Pages and in the terminal's search. Settings, Machines is titled "The crew's machines": it is where the crew works, not where the app runs. Beside an app's awake split, "on the forge's own server" and "on cloud" are explained in a line (page and terminal's Money), and each Stop on an app reads "Stop production" or "Stop preview".
src/actions/infra.ts +27
@@ -441,6 +441,33 @@ export function composeChoices(app: App): ComposeChoices {
441441 return { apps, places, experiments: running, days: DAY_CHOICES, defaultDays: LIFETIME_DAYS };
442442 }
443443
444 /**
445 * "Run it on its own machine" for one app (#17627): where it leads and what it costs, for an admin
446 * and an app that can run on a machine; nothing otherwise. The cost is the cheapest place that can
447 * be ordered now, said before anything is built.
448 */
449 interface OwnMachineOffer {
450 readonly href: string;
451 readonly says: string;
452 }
453
454 /** The page that composes a machine for one app, the app already filled in. */
455 const ownMachineHref = (appName: string): string => `/infra/build?app=${encodeURIComponent(appName)}`;
456
457 export function ownMachineOffer(app: App, actor: User | undefined, appName: string): OwnMachineOffer | undefined {
458 if (actor?.isAdmin !== true) return undefined;
459 const c = composeChoices(app);
460 if (!c.apps.some((a) => a.app === appName && a.why === "")) return undefined;
461 const cheapest = c.places.find((p) => p.orderable);
462 return {
463 href: ownMachineHref(appName),
464 says:
465 cheapest === undefined
466 ? "No cloud account can make a machine yet: connect one that allows writes first."
467 : `From ${dollars(cheapest.costCents)} a month, billed to your cloud account. The plan shows the price and nothing is built until you press Build.`,
468 };
469 }
470
444471 /** A compose as every door sends it: plain strings, read by `wantOf`. */
445472 export interface Compose {
446473 readonly app: string;
src/actions/search.ts +4
@@ -40,6 +40,7 @@ import {
4040 import type { Repo } from "../core/repos.ts";
4141 import type { User } from "../core/users.ts";
4242 import { searchDocs } from "../view/docs.ts";
43 import { searchPages } from "../core/area_pages.ts";
4344 import { providerForOrigin } from "../origins/credential.ts";
4445 import { SEARCH_LIMIT, SEARCH_LIMIT_MAX } from "./search_limit.ts";
4546 export { SEARCH_LIMIT, SEARCH_LIMIT_MAX };
@@ -233,11 +234,14 @@ export async function search(
233234 ? searchDocs(q, MAX_DOC_HITS).map((h) => ({ title: h.title, path: `/docs/${h.name}`, snippet: h.snippet }))
234235 : [];
235236
237 const pages = kind === "all" && input.repo === undefined ? searchPages(q, actor?.isAdmin === true) : [];
238
236239 return {
237240 repos,
238241 issues,
239242 code: code.hits,
240243 docs,
244 ...(pages.length > 0 ? { pages } : {}),
241245 truncated: {
242246 repos: repos.length >= limit,
243247 issues: localIssueCount >= limit,
src/core/area_pages.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * Pages a search finds by what a person calls them (#17627): "machine", "server", "cloud", "infra"
3 * and "deploy" lead to Infrastructure and Build, which no title or guide says in those words. Plain
4 * data and one match; who may see a page is read here, so a search never offers a page that
5 * refuses its reader.
6 */
7
8 import type { DocsHit } from "./search.ts";
9
10 interface AreaPage {
11 readonly title: string;
12 readonly path: string;
13 readonly says: string;
14 /** The words a person may use for it, beside its title. */
15 readonly words: string;
16 }
17
18 const PAGES: readonly AreaPage[] = [
19 {
20 title: "Infrastructure",
21 path: "/infra",
22 says: "Every machine and resource on your cloud accounts, and what it costs",
23 words: "machine machines server servers cloud infra hosting vps deploy cost",
24 },
25 {
26 title: "Build a machine",
27 path: "/infra/build",
28 says: "Run an app on a machine of its own: pick where, see the price, then build",
29 words: "machine server cloud infra deploy build run own app vps",
30 },
31 ];
32
33 /** The pages whose title or words hold every word asked (as a word's start), for an admin. */
34 export function searchPages(query: string, admin: boolean): DocsHit[] {
35 if (!admin) return [];
36 const asked = query.toLowerCase().split(/\s+/).filter((w) => w !== "");
37 if (asked.length === 0) return [];
38 return PAGES.filter((p) => {
39 const have = `${p.title} ${p.words}`.toLowerCase().split(/\s+/);
40 return asked.every((w) => have.some((h) => h.startsWith(w)));
41 }).map((p) => ({ title: p.title, path: p.path, snippet: p.says }));
42 }
src/core/search.ts +4
@@ -186,6 +186,10 @@ export interface SearchResults {
186186 readonly code: readonly CodeHit[];
187187 /** Guides matching, from the index /docs uses: at most `MAX_DOC_HITS`; only for kind `all`. */
188188 readonly docs: readonly DocsHit[];
189 /**
190 * Pages an admin reaches by what they are for (Infrastructure, Build), kind `all` only (#17627).
191 */
192 readonly pages?: readonly DocsHit[];
189193 /** Which lists hit their ceiling — a client can say "and more". */
190194 readonly truncated: {
191195 readonly repos: boolean;
src/games/boxes_line.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * The line that names a person's given game boxes (#17627), for the terminal's first screen; the
3 * page's strip lists the same boxes, up to the same `SHOWN`.
4 */
5
6 import type { Database } from "bun:sqlite";
7 import type { User } from "../core/users.ts";
8 import { boxesGranted, type GameBox } from "./store.ts";
9
10 /** The most boxes the home lists; the rest are on /games. */
11 export const SHOWN = 5;
12
13 /** One line naming the boxes: "Game servers: a, b (+2 more). /games opens one."; "" for none. */
14 export function boxesLine(boxes: readonly GameBox[]): string {
15 if (boxes.length === 0) return "";
16 const names = boxes.slice(0, SHOWN).map((b) => b.name).join(", ");
17 return `Game servers: ${names}${boxes.length > SHOWN ? ` (+${boxes.length - SHOWN} more)` : ""}. /games opens one.`;
18 }
19
20 /** The boxes this person was given, none for an agent. */
21 export function givenBoxes(db: Database, user: User): GameBox[] {
22 return user.kind === "agent" ? [] : boxesGranted(db, user.id);
23 }
src/games/store.ts +10
@@ -727,3 +727,13 @@ export function recordSync(
727727 // The box runs a `tell` as the rcon command it is.
728728 return due.map((c) => (c.kind === "tell" ? { ...c, kind: "rcon" } : c));
729729 }
730
731 /**
732 * The boxes a person holds a grant on, by name: the ones the home puts one tap away (#17627).
733 * An admin's reach over every box is not a grant, so they are listed only for what they were given.
734 */
735 export const boxesGranted = (db: Database, userId: string): GameBox[] =>
736 db
737 .query<BoxRow, [string]>("SELECT * FROM game_box WHERE id IN (SELECT box_id FROM game_grant WHERE user_id = ?1) ORDER BY name")
738 .all(userId)
739 .map(toBox);
src/tui/forge_parts.ts +28
@@ -77,6 +77,7 @@ import { trustedHostsPrompt } from "./screens/trustedhosts.ts";
7777 import { flagsScreen } from "./screens/flags.ts";
7878 import { forgeUsageScreen } from "./screens/forge_usage.ts";
7979 import { usageScreen } from "./screens/usage.ts";
80 import { infraScreen, runOnItsOwnMachine } from "./screens/infra.ts";
8081 import { canScreen } from "./screens/can.ts";
8182 import { forkFlowsScreen } from "./screens/forkflows.ts";
8283 import { modelScreen } from "./screens/model.ts";
@@ -235,6 +236,20 @@ const REPO_VERBS: readonly {
235236 title: "Machines of a repository",
236237 open: (f, ctx, repo) => machinesScreen(f, ctx, repo),
237238 },
239 {
240 // The app's page has "Run it on its own machine": the same compose, the app already chosen
241 // (#17627).
242 id: "own-machine",
243 title: "Run an app on its own machine",
244 open: (f, ctx, repo) => {
245 if (f.user?.isAdmin !== true) {
246 openOnWeb(f, ctx, `/${repo.ownerName}/${repo.name}`, "The app");
247 return undefined;
248 }
249 runOnItsOwnMachine(f, ctx, `${repo.ownerName}/${repo.name}`);
250 return undefined;
251 },
252 },
238253 {
239254 // What the crew's tokens bought on one app, as MCP `returns` with `repo` (#7271).
240255 id: "repo-usage",
@@ -945,6 +960,19 @@ export function forgeSearch(session: Session): (ctx: Ctx) => PaletteSearch {
945960 });
946961 }
947962
963 // Pages found by what they are for: Infrastructure and Build open the terminal's
964 // Infrastructure.
965 for (const hit of found.pages ?? []) {
966 items.push({
967 id: `page:${hit.path}`,
968 section: "Pages",
969 mark: mark("terminal", G.dot),
970 title: hit.title,
971 hint: hit.snippet.slice(0, 60),
972 run: () => ctx.push(infraScreen(session, ctx)),
973 });
974 }
975
948976 // Guides: public, from the index /docs reads; Enter reads the guide.
949977 for (const hit of found.docs) {
950978 const entry = anyDocEntry(hit.path.replace(/^\/docs\//, ""));
src/tui/screens/dashboard.ts +7
@@ -14,6 +14,7 @@
1414 * whole of this screen's design.
1515 */
1616
17 import { boxesLine, givenBoxes } from "../../games/boxes_line.ts";
1718 import { movedKey } from "./moved_key.ts";
1819 import { readyAsk } from "../../spawn/template_record.ts";
1920 import { keyOf } from "../../web/keymap.ts";
@@ -1389,6 +1390,12 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
13891390 );
13901391 body = rest!;
13911392 }
1393 const gamesLine = f.user === undefined ? "" : boxesLine(givenBoxes(f.db, f.user));
1394 if (gamesLine !== "") {
1395 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
1396 s.text(strip!.x, strip!.y, truncate(gamesLine, strip!.w), style(c.fg, c.bg), strip!.x + strip!.w);
1397 body = rest!;
1398 }
13921399 if (panelLines.length > 0) {
13931400 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
13941401 s.text(strip!.x, strip!.y, truncate(panelLines[0]!, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w);
src/tui/screens/machines.ts +1 −1
@@ -56,7 +56,7 @@ export function machinesScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5656 const may = (): boolean => f.user !== undefined && canWrite(f.db, repo, f.user);
5757 const rows = (): SessionRecord[] => (may() ? lastSessions(f.db, repo.id) : []);
5858 return {
59 title: "Machines",
59 title: "The crew's machines",
6060 keys: [binding(["j", "k"], "move cursor"), binding(["esc"], "back")],
6161 async load() {
6262 if (may()) {
src/tui/screens/money.ts +2 −1
@@ -27,7 +27,7 @@ import type { Session } from "../session.ts";
2727 import { fill, len, split } from "../ui/layout.ts";
2828 import { ListState, drawList, type ListRow } from "./common.ts";
2929 import type { PaletteEntry } from "./entries.ts";
30 import { dollars, signed } from "../../web/studio/money_line.ts";
30 import { AWAKE_SPLIT_NOTE, dollars, signed } from "../../web/studio/money_line.ts";
3131 import { positionWord } from "../../core/slider.ts";
3232
3333 const figures = (m: MoneyLine): string => `cost ${dollars(m.cost)} · revenue ${dollars(m.revenue)} · gap ${signed(m.gap)}`;
@@ -59,6 +59,7 @@ export function appMoneyRows(m: AppMoney): ListRow[] {
5959 title: "Awake",
6060 meta: `${hours(awake)} · ${pct(m.ownedSeconds, awake)} on the forge's own server · ${pct(m.cloudSeconds, awake)} on cloud`,
6161 },
62 { title: "What that split means", meta: AWAKE_SPLIT_NOTE },
6263 { title: "Share of the forge's own server", meta: pct(m.ownedShare, 1) },
6364 ];
6465 }
src/web/game_strip.ts added +21
@@ -0,0 +1,21 @@
1 /**
2 * "Your game servers" on the first page (#17627): a person who was given a game box and nothing
3 * else finds it one tap from home, each box a link to its page, in place of a quiet board that
4 * says nothing about it. The terminal's first screen reads the same line (`boxesLine`, in
5 * `games/boxes_line.ts`).
6 */
7
8 import { SHOWN } from "../games/boxes_line.ts";
9 import type { GameBox } from "../games/store.ts";
10 import { html, type Html } from "./html.ts";
11 import { row, rowList } from "./ui.ts";
12
13 export function gameStrip(boxes: readonly GameBox[]): Html | null {
14 if (boxes.length === 0) return null;
15 return html`<section id="your-games" aria-labelledby="your-games-h">
16 <h2 id="your-games-h" class="small">Your game servers</h2>
17 <p class="muted small">Open a server, then start it or read its console.</p>
18 ${rowList(boxes.slice(0, SHOWN).map((b) => row({ href: `/games/${b.name}`, title: b.name, meta: html`${b.place === "" ? "no machine yet" : b.place}` })))}
19 ${boxes.length > SHOWN ? html`<p class="small"><a href="/games">All ${boxes.length} game servers</a></p>` : null}
20 </section>`;
21 }
src/web/pages/cost.ts +1 −1
@@ -24,7 +24,7 @@ export function costPage(ctx: Ctx): Response {
2424 const days = timePhase(ctx.request, "cost", () => costDays(ctx.app.db, repo.id));
2525 const left = creditDaysLine(ctx.app);
2626 const rendering = performance.now();
27 const body = html`${repoHeader(ctx, repo, "issues")}
27 const body = html`${repoHeader(ctx, repo, "cost")}
2828 <div class="page-head mt">
2929 <h1>Cost, last ${String(COST_DAYS)} days</h1>
3030 <a href="/${repo.ownerName}/${repo.name}/cost.csv" download>CSV</a>
src/web/pages/games.ts +3 −1
@@ -301,7 +301,9 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
301301 })}
302302 ${cloud === undefined
303303 ? null
304 : html`<div id="game-machine" data-live="${CLOUD_EVENT},${GAME_CLOUD_EVENT}">${rowList([row({ title: "Its machine", facts: [cloud] })])}</div>`}
304 // An admin goes on to the machine itself on Infrastructure, where its cost and end are
305 // (#17627).
306 : html`<div id="game-machine" data-live="${CLOUD_EVENT},${GAME_CLOUD_EVENT}">${rowList([row({ title: "Its machine", facts: [cloud], ...(user.isAdmin ? { href: `/infra#machine-${machine!.name}` } : {}) })])}</div>`}
305307 ${held}
306308 ${joinBlock(ctx, box, visible, compose?.text)}
307309 ${visible.length === 0
src/web/pages/home_flow.ts +3
@@ -69,6 +69,8 @@ import { waitingOnMe, waitsDigest } from "../studio/waiting_on_me.ts";
6969 import { chart } from "./home_figures.ts";
7070 import { homeRow, ROW_ALWAYS } from "../home_row.ts";
7171 import { tellBox } from "../studio/living.ts";
72 import { givenBoxes } from "../../games/boxes_line.ts";
73 import { gameStrip } from "../game_strip.ts";
7274 import { requestsCard } from "../requests_card.ts";
7375 import { asksToAnswer } from "../../actions/ask_admin.ts";
7476 import { untoldAnswer, markTold } from "../../core/requests.ts";
@@ -500,6 +502,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited
500502 ${forkFlowsLine(ctx, user)}
501503 ${firstWrongLine(says.wrong)}
502504 </header>
505 ${gameStrip(givenBoxes(ctx.app.db, user))}
503506 ${mine ? askedSection(ctx, user) : null}
504507 ${main}
505508 ${slots}
src/web/pages/infra.ts +9
@@ -136,9 +136,18 @@ export function consolePage(name: string, c: { wssUrl: string; password: string
136136 </section>`;
137137 }
138138
139 /** What the machine runs, one click on: its game box, else the app its address serves (#17627). */
140 const machineOwner = (r: Running): Html | null =>
141 r.game === true
142 ? btn("Game box", { href: `/games/${r.name}`, variant: "ghost", size: "sm", label: `The game box on ${r.name}` })
143 : !r.app.includes("/")
144 ? null
145 : btn("App", { href: `/${r.app}`, variant: "ghost", size: "sm", label: `The app ${r.app} runs on ${r.name}` });
146
139147 /** Keep and End now: Keep is reversible and posts at once; End now goes through the confirm. */
140148 const machineActions = (r: Running): Html =>
141149 html`<div class="row-fields">
150 ${machineOwner(r)}
142151 ${!r.atProvider ? null : btn("At the cloud", { href: `/infra/${r.name}/cloud`, variant: "ghost", size: "sm", label: `What the cloud says of ${r.name}` })}
143152 ${r.endsAt === null
144153 ? null
src/web/pages/search.ts +10 −1
@@ -328,6 +328,14 @@ function docsSection(docs: readonly DocsHit[]): Html {
328328 </section>`;
329329 }
330330
331 /** Pages found by what they are for, above everything: a heading over rows linking to them. */
332 function pagesSection(pages: readonly DocsHit[]): Html {
333 return html`<section id="pages" aria-labelledby="h-pages">
334 <h2 class="mt" id="h-pages">Pages</h2>
335 ${rowsUnderHeading(pages.map((d) => row({ href: d.path, nav: true, lead: icon("terminal"), title: d.title, meta: html`${d.snippet}` })))}
336 </section>`;
337 }
338
331339 function section(
332340 a: Asked,
333341 [kind, , title, emptyText]: Words,
@@ -543,13 +551,14 @@ export async function searchPage(ctx: Ctx): Promise<Response> {
543551
544552 const nothing =
545553 a.kind === "all" &&
546 found.repos.length + found.issues.length + found.code.length + found.docs.length === 0;
554 found.repos.length + found.issues.length + found.code.length + found.docs.length + (found.pages?.length ?? 0) === 0;
547555 const guides = found.docs.length === 0 ? null : docsSection(found.docs);
548556 const guidesFirst = guideTitleMatches(a.query, found.docs);
549557 const sections = WORDS
550558 .filter(([kind]) => kind !== "all" && (a.kind === "all" || a.kind === kind || (a.kind === "pulls" && kind === "issues")))
551559 .map((w) => ({ kind: w[0], html: section(a, w, ...rows[w[0]](), w[0] === "code" ? moreCode : null) }));
552560 const ordered = [
561 ...(found.pages === undefined ? [] : [pagesSection(found.pages)]),
553562 ...(guidesFirst ? [guides] : []),
554563 ...sections.flatMap((s) => (s.kind === "repos" && !guidesFirst ? [s.html, guides] : [s.html])),
555564 ];
src/web/repo_steps.ts +6 −1
@@ -11,7 +11,7 @@ import { REPO_TABS } from "./keymap.ts";
1111 import { appsRuntime } from "../apps/runtime_registry.ts";
1212 import { knownSpec, warmSpec } from "../apps/api_spec.ts";
1313 import { getAppByRepo } from "../core/apps.ts";
14 import { canAdmin, canEnterApp, canWrite, visibleForks, type Repo } from "../core/repos.ts";
14 import { canAdmin, canEnterApp, canSeeOwnerFacts, canWrite, visibleForks, type Repo } from "../core/repos.ts";
1515 import type { Ctx } from "../http/context.ts";
1616 import { sshCommand } from "../ssh/command.ts";
1717 import { changesHref, tellsHref } from "./studio/nouns.ts";
@@ -28,6 +28,7 @@ export type RepoTab =
2828 | "runs"
2929 | "events"
3030 | "data"
31 | "cost"
3132 | "flows"
3233 | "api"
3334 | "settings"
@@ -119,6 +120,10 @@ function work(ctx: Ctx, base: string, repo: Repo | undefined): Steps {
119120 // An app's databases, for the people who can write the app.
120121 if (record !== undefined && canWrite(ctx.app.db, repo, ctx.auth.user))
121122 steps.push({ key: "data", label: "Data", href: `${base}/data` });
123 // What the app costs, for the one whose spend it is (#17627); the page gates itself the same
124 // way.
125 if (record !== undefined && canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user))
126 steps.push({ key: "cost", label: "Cost", href: `${base}/cost` });
122127 steps.push({ key: "events", label: "Events", href: `${base}/events` });
123128 // What flows in and out: origin, sources, pins, forks (#9434). The page gates itself like the repo.
124129 steps.push({ key: "flows", label: "Flows", href: `${base}/flows` });
src/web/studio/app.ts +9 −2
@@ -58,6 +58,7 @@ import {
5858 icon,
5959 listCard,
6060 row,
61 rowList,
6162 } from "../ui.ts";
6263 import { answersRegion } from "./answers.ts";
6364 import { appMilestones } from "./milestone_lines.ts";
@@ -89,6 +90,7 @@ import { copySteps, noteAppOpened } from "../../core/next-steps.ts";
8990 import { mayReadStatement } from "../../actions/statement.ts";
9091 import { appPicture } from "../../flow/pages.ts";
9192 import { moneyRows } from "./money_line.ts";
93 import { ownMachineOffer } from "../../actions/infra.ts";
9294
9395 /** What a seat does, as the rail's Crew card says it. */
9496 const CREW_VERB: Record<CrewRole, string> = {
@@ -496,6 +498,11 @@ export async function studioApp(
496498 <h2>This month</h2>`,
497499 extra: "about",
498500 });
501 // Run it on a machine of its own: an admin's way from the app to the choice, the app filled in
502 // and the price said before anything is built (#17627).
503 const own = ownMachineOffer(ctx.app, ctx.auth.user, `${repo.ownerName}/${repo.name}`);
504 const ownMachineCard =
505 own === undefined ? null : rowList([row({ href: own.href, title: "Run it on its own machine", meta: html`${own.says}` })]);
499506 // The rest of the app's environment — its variables, hostname, access and
500507 // domains — is the admin's, on the app's settings page.
501508 // Issues, Pulls and the map are the head's own tabs; only what it lacks is here.
@@ -503,7 +510,6 @@ export async function studioApp(
503510 <a href="${base}/variants">Variants</a>
504511 ${when(canWrite(db, repo, ctx.auth.user), () => html`<a href="${base}/drop">Drop</a>`)}
505512 ${when(canAdmin(db, repo, ctx.auth.user), () => html`<a href="${base}/settings/app">Environment settings</a>`)}
506 ${when(ctx.auth.user?.isAdmin === true, () => html`<a href="/infra/build?app=${encodeURIComponent(`${repo.ownerName}/${repo.name}`)}">Run it on its own machine</a>`)}
507513 ${when(canAdmin(db, repo, ctx.auth.user), () => html`<a href="/-/confirm?to=${encodeURIComponent(`${base}/archive`)}">Archive</a>`)}
508514 </p>`;
509515
@@ -553,6 +559,7 @@ export async function studioApp(
553559 <div id="app-previews"></div>
554560 ${nowRegion(repo, now)}
555561 ${appMilestones(ctx, repo, picture.milestones)}
562 ${ownMachineCard}
556563 ${disclosure("Operator detail", html`<div class="stack">${more}</div>`, {
557564 id: "app-details",
558565 })}
@@ -596,7 +603,7 @@ export async function studioApp(
596603 ${errorsCard(ctx, repo, record)}
597604 </div>
598605 <aside class="stack">
599 ${adapter} ${schedules} ${forksCard(ctx, repo)} ${crewCard} ${weekCard} ${moneyCard} ${ownCard} ${more}
606 ${adapter} ${schedules} ${forksCard(ctx, repo)} ${crewCard} ${weekCard} ${moneyCard} ${ownMachineCard} ${ownCard} ${more}
600607 </aside>
601608 </div>
602609 ${liveMount({ repo: base, app: true })}`;
src/web/studio/money_line.ts +5
@@ -120,6 +120,10 @@ export function forgeMoneyLine(m: ForgeMoney): Html {
120120
121121 // ---- one app ----
122122
123 /** What the awake split means for the cost, said beside it on both doors (#17627). */
124 export const AWAKE_SPLIT_NOTE =
125 "Time on the forge's own server adds no cloud charge: its monthly cost is shared by use. Time on cloud is billed by the hour.";
126
123127 const hours = (s: number): string => `${(s / 3600).toFixed(1)} h`;
124128 const pct = (part: number, whole: number): string => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "0%");
125129
@@ -143,6 +147,7 @@ export function moneyRows(m: AppMoney, statementHref: string): Html {
143147 ${pct(m.cloudSeconds, awake)} on cloud
144148 </dd>
145149 </dl>
150 <p class="muted small">${AWAKE_SPLIT_NOTE}</p>
146151 <p class="muted small">
147152 Its cost includes ${pct(m.ownedShare * 100, 100)} of the forge's own server for the month, its share of the time apps ran there.
148153 </p>`;
src/web/ui.ts +2 −1
@@ -653,7 +653,8 @@ export function envActions(
653653 () =>
654654 confirmAction({
655655 action: `${base}/app/${env.env}/stop`,
656 verb: "Stop",
656 // Which one it stops, said on the button: production's or a preview's (#17627).
657 verb: env.env === "production" ? "Stop production" : "Stop preview",
657658 size: "sm",
658659 }),
659660 )}`,
test/confirm-app-stop.test.ts +9
@@ -16,6 +16,7 @@ import { AppsRuntime } from "../src/apps/runtime.ts";
1616 import { getAppByRepo } from "../src/core/apps.ts";
1717 import type { Repo } from "../src/core/repos.ts";
1818 import { createUser } from "../src/core/users.ts";
19 import { envActions } from "../src/web/ui.ts";
1920 import { serve, type Servers } from "../src/http/server.ts";
2021 import { promote } from "./helpers/members.ts";
2122 import { withScripts } from "./helpers/page-script.ts";
@@ -132,6 +133,14 @@ describe("Stop on an app's environment goes through the confirm page", () => {
132133 expect(html).toContain('action="/alice/notes/app/production/redeploy"');
133134 });
134135
136 test("the button says which environment it stops: production or a preview", () => {
137 const status = (env: "production" | "pull-3"): Parameters<typeof envActions>[1] => ({ env, state: "running", commitOid: "a".repeat(40), url: "http://x.test" });
138 expect(envActions("/alice/notes", status("production"), true).text).toContain("Stop production");
139 const preview = envActions("/alice/notes", status("pull-3"), true).text;
140 expect(preview).toContain("Stop preview");
141 expect(preview).not.toContain("Stop production");
142 });
143
135144 test("the confirm page words a Stop of production for a writer, and knows no made-up env", async () => {
136145 const page = await get(alice, CONFIRM);
137146 expect(page.status).toBe(200);
test/infra-page.test.ts +2 −1
@@ -199,7 +199,8 @@ describe("infrastructure", () => {
199199
200200 test("from an app's page, Build opens on that app, run for itself with no end; an unknown app is a first visit", async () => {
201201 const home = await (await get("/ada/shop")).text();
202 expect(home).toContain('href="/infra/build?app=ada%2Fshop">Run it on its own machine</a>');
202 expect(home).toContain('href="/infra/build?app=ada%2Fshop"');
203 expect(home).toContain("Run it on its own machine");
203204 const form = (page: string) => page.slice(page.indexOf('id="compose"'));
204205 const named = form(await (await get("/infra/build?app=ada%2Fshop")).text());
205206 expect(named).toMatch(/<option value="ada\/shop"\s+selected/);
test/own-machine.test.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * Run an app on a machine of its own (#17627): the app's page leads to the Infrastructure compose
3 * with the app already chosen and says what it costs; search finds Infrastructure and Build by
4 * what a person calls them; the crew's machines, the awake split and each Stop say what they are.
5 */
6 import { afterAll, beforeAll, 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 { createApp as createAppRecord } from "../src/core/apps.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { openIssue } from "../src/actions/issues.ts";
14 import { ownMachineOffer } from "../src/actions/infra.ts";
15 import { search } from "../src/actions/search.ts";
16 import { searchPages } from "../src/core/area_pages.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, getUserByName, type User } from "../src/core/users.ts";
19 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
20 import { AWAKE_SPLIT_NOTE } from "../src/web/studio/money_line.ts";
21 import type { AppMoney } from "../src/actions/money.ts";
22 import { appMoneyRows } from "../src/tui/screens/money.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 const ORIGIN = "http://forge.test";
28 const MONEY: AppMoney = { month: "2026-12", thisMonth: { cost: 1, revenue: 0, gap: -1 }, ownedSeconds: 3600, cloudSeconds: 0, ownedShare: 0.1 };
29 let dataDir = "";
30 let app: App;
31 let http: ForgeHttp;
32 let alice: User;
33 let bob: User;
34 const tokens: Record<string, string> = {};
35 const get = async (who: string, path: string) =>
36 (await http.handle(new Request(ORIGIN + path, { headers: { authorization: `Bearer ${tokens[who]}` } }))).text();
37
38 beforeAll(async () => {
39 dataDir = await mkdtemp(join(tmpdir(), "forge-own-machine-"));
40 app = createApp({ dataDir, port: 0, url: ORIGIN });
41 http = forgeHttp(app);
42 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
43 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
44 if (!made.ok) throw new Error(made.error);
45 tokens[username] = createToken(app.db, getUserByName(app.db, username)!.id, "rw", "rw").token;
46 }
47 alice = getUserByName(app.db, "alice")!;
48 bob = getUserByName(app.db, "bob")!;
49 const repo = await createRepo(app, alice, { name: "notes", visibility: "public" });
50 if (!repo.ok) throw new Error(String(repo.error));
51 createAppRecord(app.db, { repoId: repo.value.id, slug: "notes", access: "public" });
52 // A change shipped, so the page is the app's whole page and not a new app's progress alone.
53 const opened = openIssue(app, alice, repo.value, { title: "first" });
54 if (!opened.ok) throw new Error(String(opened.error));
55 app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', 'f1', 'a', 'b', ?2)").run(opened.value.id, new Date().toISOString());
56 app.db.query("UPDATE issue SET kind = 'pull', state = 'closed' WHERE id = ?1").run(opened.value.id);
57 });
58 afterAll(async () => {
59 app.close();
60 await rm(dataDir, { recursive: true, force: true });
61 });
62
63 test("the app's page leads an admin to the compose with the app chosen, and says what it costs", async () => {
64 const page = await get("alice", "/alice/notes");
65 expect(page).toContain("Run it on its own machine");
66 expect(page).toContain('href="/infra/build?app=alice%2Fnotes"');
67 expect(page).toContain("No cloud account can make a machine yet");
68 expect(await get("bob", "/alice/notes")).not.toContain("Run it on its own machine");
69 expect(ownMachineOffer(app, bob, "alice/notes")).toBeUndefined();
70 expect(ownMachineOffer(app, alice, "alice/nothing")).toBeUndefined();
71 });
72
73 test("the compose opens with that app selected and for running it", async () => {
74 const build = await get("alice", "/infra/build?app=alice%2Fnotes");
75 expect(build).toMatch(/<option value="alice\/notes"\s+selected/);
76 expect(build).toMatch(/<input[^>]*value="app"[^>]*checked|<input[^>]*checked[^>]*value="app"/);
77 });
78
79 test("search finds Infrastructure and Build for what a person calls them, for an admin only", async () => {
80 for (const q of ["machine", "server", "cloud", "infra", "deploy"]) {
81 expect(searchPages(q, true).map((p) => p.path)).toEqual(["/infra", "/infra/build"]);
82 expect(searchPages(q, false)).toEqual([]);
83 }
84 expect(searchPages("zebra", true)).toEqual([]);
85 const found = await search(app, alice, { q: "machine" });
86 expect(found.pages?.map((p) => p.title)).toEqual(["Infrastructure", "Build a machine"]);
87 expect((await search(app, bob, { q: "machine" })).pages).toBeUndefined();
88 const page = await get("alice", "/search?q=machine");
89 expect(page).toContain('href="/infra/build"');
90 expect(page).toContain('href="/infra"');
91 });
92
93 test("Settings > Machines says in its title that these are the crew's", async () => {
94 expect(await get("alice", "/alice/notes/settings/machines")).toContain("The crew's machines");
95 });
96
97 test("the awake split says what it means for the cost, on the page and in the terminal", () => {
98 expect(AWAKE_SPLIT_NOTE).toContain("no cloud charge");
99 const rows = appMoneyRows(MONEY);
100 expect(rows.map((r) => r.meta)).toContain(AWAKE_SPLIT_NOTE);
101 });
test/palette-roster.test.ts +4
@@ -89,6 +89,7 @@ test("a site-admin person is offered the whole roster", () => {
8989 ["flows", "Flows of a repository", "owner/name"],
9090 ["findings", "Findings in a repository", "owner/name"],
9191 ["machines", "Machines of a repository", "owner/name"],
92 ["own-machine", "Run an app on its own machine", "owner/name"],
9293 ["repo-usage", "Usage of a repository", "owner/name"],
9394 ["new-issue", "New issue", "owner/name"],
9495 ["new-pull", "New pull request", "owner/name"],
@@ -308,6 +309,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
308309 ["flows", "Flows of a repository", "owner/name"],
309310 ["findings", "Findings in a repository", "owner/name"],
310311 ["machines", "Machines of a repository", "owner/name"],
312 ["own-machine", "Run an app on its own machine", "owner/name"],
311313 ["repo-usage", "Usage of a repository", "owner/name"],
312314 ["new-issue", "New issue", "owner/name"],
313315 ["new-pull", "New pull request", "owner/name"],
@@ -429,6 +431,7 @@ test("a member person is offered the signed-in roster without the admin entries"
429431 ["flows", "Flows of a repository", "owner/name"],
430432 ["findings", "Findings in a repository", "owner/name"],
431433 ["machines", "Machines of a repository", "owner/name"],
434 ["own-machine", "Run an app on its own machine", "owner/name"],
432435 ["repo-usage", "Usage of a repository", "owner/name"],
433436 ["new-issue", "New issue", "owner/name"],
434437 ["new-pull", "New pull request", "owner/name"],
@@ -544,6 +547,7 @@ test("signed out, the palette offers sign-in and the public entries", () => {
544547 ["flows", "Flows of a repository", "owner/name"],
545548 ["findings", "Findings in a repository", "owner/name"],
546549 ["machines", "Machines of a repository", "owner/name"],
550 ["own-machine", "Run an app on its own machine", "owner/name"],
547551 ["repo-usage", "Usage of a repository", "owner/name"],
548552 ["new-issue", "New issue", "owner/name"],
549553 ["new-pull", "New pull request", "owner/name"],
test/tui-money.test.ts +1
@@ -113,6 +113,7 @@ describe("the terminal's money screen", () => {
113113 expect(appMoneyRows(m.value)).toEqual([
114114 { title: "This month (2026-11)", meta: "cost $95.00 · revenue $1.00 · gap -$94.00" },
115115 { title: "Awake", meta: "10.0 h · 100% on the forge's own server · 0% on cloud" },
116 { title: "What that split means", meta: "Time on the forge's own server adds no cloud charge: its monthly cost is shared by use. Time on cloud is billed by the hour." },
116117 { title: "Share of the forge's own server", meta: "100%" },
117118 ]);
118119 });

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

Keyboard shortcuts

Docs