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

Plain words find Games and Infrastructure, and a player's home leads to their games #17704

opened this

Merged 17h 37m ago, live in production

sold/nav-two → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/nav-two was merged into main as 1ce8fec.

Review

Sign in to review this change.
39 files changed +356 −88
docs/design/areas/shell.md +1 −1
@@ -5,7 +5,7 @@ The chrome every page sits in: a skip link, the sticky top bar with the wordmark
55 - `.skip` — the "Skip to content" link, first in the document and hidden above the top until it has keyboard focus.
66 - `.topbar` — the `<header role="banner">` across the top of every page: wordmark, areas, crumbs, then the tools.
77 - `.wordmark` — the forge's name and mark, linking home (`g h`); the mark turns on hover. Also written by the board's own header in `src/web/pages/board.ts`.
8 - `.areas` — the top bar's `<nav aria-label="Areas">`, after the wordmark: Apps, Games, Infrastructure and Explore, the `GO_PAGES` rows marked `area` (`src/web/go_pages.ts`), each viewer only those they may use, the current one by weight (`aria-current`). Games needs a grant on a box (`seesAnyBox`, one read per 30 s a process). From 720px the links are in the bar, and up to 1199px the search field gives way to its icon. Under 720px they are the bar's first line, 44px and pinned with it, on every page with a bar: a repository's, a visitor's and one that passes `tools` too. `--areas-h` adds those 44px to `--topbar-h`, so what sticks or scrolls under the bar follows. A page with tabs of its own shows them under the bar as before.
8 - `.areas` — the top bar's `<nav aria-label="Areas">`, after the wordmark: Apps, Games, Infrastructure and Explore, the `GO_PAGES` rows marked `area` (`src/web/go_pages.ts`), each viewer only those they may use, Games first for a person with a game grant and no repository of their own (`playsOnly`), the current one by weight (`aria-current`). Games needs a grant on a box (`seesAnyBox`, one read per 30 s a process). From 720px the links are in the bar, and up to 1199px the search field gives way to its icon. Under 720px they are the bar's first line, 44px and pinned with it, on every page with a bar: a repository's, a visitor's and one that passes `tools` too. `--areas-h` adds those 44px to `--topbar-h`, so what sticks or scrolls under the bar follows. A page with tabs of its own shows them under the bar as before.
99 - `.topbar-tools` — the top bar's right-hand group (search, Asks, the new and user menus): one row that may shrink but never wraps, its bare `a.small` links 44px tall.
1010 - `.topbar-search` — the top bar's search form: an icon, a borderless input and its `/` key hint in one bordered pill, the border taking the accent on focus. Shown from 720px; below that the icon button carries search.
1111 - `.hide-lg` — shown under 720px, hidden from 720px: the narrow-screen stand-in for something `.hide-sm` shows on wide screens (the search icon button beside `.topbar-search`).
docs/design/attention-budget.json +3 −3
@@ -115,16 +115,16 @@
115115 },
116116 "settings": {
117117 "390": {
118 "words": 148,
118 "words": 149,
119119 "blocks": 32,
120120 "colours": 1
121121 },
122122 "1280": {
123 "words": 148,
123 "words": 149,
124124 "blocks": 32,
125125 "colours": 1
126126 },
127 "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word."
127 "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word; 149 since Settings \u203a Infrastructure, one word: an admin looked for the cloud bill here and found no way to it."
128128 },
129129 "search": {
130130 "390": {
docs/design/size-budget/board.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/board",
3 "js": 30208,
3 "js": 30464,
44 "css": 52992
55 }
docs/design/size-budget/map.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/map",
3 "js": 32768,
3 "js": 33024,
44 "css": 54784
55 }
docs/design/size-budget/owner-name-next.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name/next",
3 "js": 27392,
3 "js": 27648,
44 "css": 53504
55 }
docs/design/size-budget/owner-name-space.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name/space",
3 "js": 34304,
3 "js": 34560,
44 "css": 54272
55 }
docs/design/size-budget/system.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/system",
3 "js": 27392,
3 "js": 27648,
44 "css": 52992
55 }
docs/features/infra.md +2
@@ -9,6 +9,8 @@ What runs on your own cloud, what it's for, what it costs, and when it ends; and
99
1010 ## Where
1111
12 - **From an app:** its page's "Run it on its own machine" (admins) opens `/infra/build?app=owner/name` with the app chosen, for running the app itself, with no end; nothing is built until Build.
13 - **Getting there:** the top bar, the account menu, the settings sidebar under Connections, and a link on Cloud accounts, Connect a cloud, Deploy to and Forges you sent; admins only, like the page.
1214 - **Web:** `/infra` (`src/web/pages/infra.ts`, routes in `src/http/infra_routes.ts`). Each account's month against its ceiling, one sentence a line ("$13.00 of $50 a month on DigitalOcean"); a line for anything the hourly watch found at a provider that the forge did not make, linking that account's row on Cloud accounts; then each machine that bills, grouped by its experiment's question or by its app, with where it runs in plain words, its monthly cost and when it ends, Keep 7 more days and End now beside it; End now shows only where something exists at the provider (`existsAtProvider` in `src/cloud/billing.ts`, the same test Retire on Pinned forges uses), so a first deploy that made nothing offers none. What ended in the last 30 days, and anything retired that still bills, stays under a quiet **Ended** disclosure, each in the shared billing sentence with its day: "retired Mon 30 Nov; nothing bills", or "…; its kept disk still bills $1.00 a month" with a link to delete it on Pinned forges; older ones that bill nothing are one line with their count. A dead row (a first deploy that failed and left nothing at its provider) says "nothing exists at DigitalOcean; clear this row", with Clear this row through the confirm (`clearPinned`, event `pinned.cleared`). Build something opens the compose form: an app, a place (the cheapest two in each city, each a row of at least 44px; a filter of city, provider or size words narrows the whole catalog on the server, `/infra/live?part=places`, so the page never carries it; one that cannot be ordered is listed, dimmed, with why), what it is for (a new question, a running experiment, or running the app itself), and when it ends (1, 3, 7 or 30 days; no end only for an app). The plan tray sits at the foot of the form.
1315 - **Terminal:** the Infrastructure screen (`src/tui/screens/infra.ts`, after Cloud accounts in the palette, and `I` on the Cloud accounts screen). What ended is listed after what runs, each in its billing sentence. `n` composes one question at a time and shows the plan with Build; `l` looks at the DNS records against Cloudflare now; `m` makes one (type, name, host, what it points to, a port for SRV, then the plan with Make the record); `u` removes the selected record after a confirm; `+` keeps the selected machine 7 more days; `x` ends it now after a confirm (only where something exists at its provider), and `c` clears a dead row after a confirm. A build's steps lead the list as they happen.
1416 - **API:** `GET /api/v1/admin/infra` (`?plan=<id>` adds a build's steps), `POST /api/v1/admin/infra/plan`, `POST /api/v1/admin/infra/apply` (202). Keep is `POST /api/v1/admin/pinned/:name/keep`.
docs/features/living-home.md +1 −1
@@ -51,6 +51,6 @@ Each card says which of the three it is. The planner's standing direction is nev
5151
5252 **An ask ends.** One nobody touches for seven days is closed by the forge as dropped (`src/crew/ask_days.ts`, on the parked pulls' five-minute pass). The receipt is one comment that says why and how to undo it, posted by the forge as the repository's autonomy account (whoever turned its crew on), not written by a person; a repository with no one named closes nothing. **Reopen** on the issue brings it back as it was, and its seven days start again from that change; any word on it starts them again too. If the closed ask held up other work, that work is a plan to confirm where plans need a person (the Autonomy knob's ask), an ask with seven days of its own; on go it is simply the crew's.
5353
54 **With nothing to answer** the lane says "Nothing needs you." and is quiet.
54 **With nothing to answer** the lane says "Nothing needs you." and is quiet. A person who may see a game box, is not an admin and owns no repository gets one link after it, "Your games"; nobody else's home changes.
5555
5656 The terminal's home shows the same lane for the same person (`src/tui/screens/asks_lines.ts`): `Asked:` and the lane's words, the first four asks with what each asks, then the crew's one line.
docs/features/palette-rows.md +3 −1
@@ -10,9 +10,11 @@ Filtered on the server before the list exists (`src/web/palette_rows.ts`, `palet
1010
1111 Terminal: the palette itself is a web surface, but its app actions have their door. On an app's deploys screen (`src/tui/screens/deploys.ts`) a writer presses `D` to redeploy production and `S` to stop it, each after a one-line confirm, through the same `redeployEnv` and `stopEnv`; a stopped production offers only `D`, a reader neither. That is the terminal side of "Redeploy" and "Stop" here, gated the same way.
1212
13 **Plain words find an area.** An area's row carries search words (`words` in `src/web/go_pages.ts`), matched and never shown: Apps is `deploy app site`; Games `minecraft server players`; Infrastructure `cloud cost spend bill infra machine server aws deploy`. A word counts from its third letter, as a whole word or the start of one (`wordsHit`, `src/web/palette.ts`), a little under a title that says the same. So "server" shows Games and Infrastructure, each only to a person who may open it. The `:` prompt, the search page ("Go to Games") and the terminal's palette read the same words.
14
1315 The cap of eight apps: two rows an app, so at most sixteen rows, about one screen of the list; the page lists thirty repositories and a palette is a short list, not a table.
1416
15 Tests: `test/palette-rows.test.ts`.
17 Tests: `test/palette-rows.test.ts`, `test/areas.test.ts`.
1618
1719 ## A search that matches nothing sends nothing (#17647)
1820
src/apps/feature.ts +1 −1
@@ -33,7 +33,7 @@ export const SETTING_TYPES: readonly SettingType[] = ["bool", "int", "string", "
3333
3434 /** The labels the forge's own menus use: a feature may not borrow one. */
3535 const BUILT_IN_MENU_LABELS = [
36 "your profile", "repositories", "apps", "notes", "talk", "explore", "packs", "displays", "map", "features",
36 "your profile", "repositories", "apps", "games", "infrastructure", "notes", "talk", "explore", "packs", "displays", "map", "features",
3737 "new app", "new repository", "new issue", "new organization", "migrate", "settings", "access tokens", "ssh keys",
3838 "origins", "boards", "crew", "system memory", "help", "sign out", "log out", "sign in", "admin", "administration",
3939 "access codes", "computer keys", "connected accounts", "jump to anywhere",
src/games/store.ts +3
@@ -302,6 +302,9 @@ export function seesAnyBox(db: Database, user: User | undefined, now = Date.now(
302302 return held.ids.has(user.id);
303303 }
304304
305 /** A person here for a game box alone: a grant, no repository of their own (`owns` counts them), not an admin. */
306 export const herePlaying = (db: Database, user: User | undefined, owns: () => number): boolean => user?.isAdmin === false && seesAnyBox(db, user) && owns() === 0;
307
305308 export function grant(db: Database, boxId: string, userId: string, role: Role | "none", service = ""): void {
306309 players.delete(db);
307310 if (role === "none") db.query("DELETE FROM game_grant WHERE box_id = ?1 AND user_id = ?2 AND service = ?3").run(boxId, userId, service);
src/http/infra_routes.ts +14 −9
@@ -40,16 +40,20 @@ const composeOf = (get: (k: string) => string): ComposeState => ({
4040 q: get("q").slice(0, 80),
4141 });
4242
43 /** A first visit's compose: the first app that can run, the cheapest place, a new question, a week. */
44 function firstCompose(c: ComposeChoices): ComposeState {
45 const app = c.apps.find((a) => a.why === "")?.app ?? "";
43 /**
44 * A first visit's compose: the first app that can run, the cheapest place, a new question, a week.
45 * From an app's own page (`?app=owner/name`): that app, run for itself, with no end.
46 */
47 function firstCompose(c: ComposeChoices, asked = ""): ComposeState {
48 const named = c.apps.find((a) => a.app === asked)?.app;
49 const app = named ?? c.apps.find((a) => a.why === "")?.app ?? "";
4650 return {
4751 app,
4852 where: c.places.find((p) => p.orderable)?.value ?? "",
49 why: "question",
53 why: named === undefined ? "question" : "app",
5054 experiment: c.experiments[0]?.id ?? "",
5155 question: "",
52 days: String(c.defaultDays),
56 days: named === undefined ? String(c.defaultDays) : "none",
5357 name: nameFor(app),
5458 };
5559 }
@@ -91,7 +95,7 @@ function infraResource(ctx: Ctx): Response {
9195 async function render(
9296 ctx: Ctx,
9397 s: ComposeState | undefined,
94 o: { planId?: string; flash?: { tone: "danger" | "attn"; message: string } },
98 o: { planId?: string; app?: string; flash?: { tone: "danger" | "attn"; message: string } },
9599 status = 200,
96100 ): Promise<Response> {
97101 const user = ctx.auth.user;
@@ -102,7 +106,7 @@ async function render(
102106 let compose = html``;
103107 if (build === undefined) {
104108 const choices = timePhase(ctx.request, "choices", () => composeChoices(ctx.app));
105 const state = s ?? firstCompose(choices);
109 const state = s ?? firstCompose(choices, o.app);
106110 const planned = await timePhaseAsync(ctx.request, "plan", () => planCompose(ctx.app, user, state, choices));
107111 if (!planned.ok) return notFoundPage(ctx);
108112 compose = composeForm(choices, state, planTray(planned.value), domainOf(ctx.app));
@@ -141,12 +145,13 @@ function infraGet(ctx: Ctx): Response {
141145 return page({ ctx, title: "All clouds · Infrastructure", wide: true, scriptJs: SCRIPT, styleCss: INFRA_CSS, body: resourcesPage(tree, [], pane), noDock: true });
142146 }
143147
144 // GET /infra/build, and /infra/build?plan=<id> for a build's progress.
148 // GET /infra/build, /infra/build?app=owner/name from an app's page, and ?plan=<id> for a build's
149 // progress.
145150 function infraBuild(ctx: Ctx): Promise<Response> | Response {
146151 const denied = guard(ctx);
147152 if (denied) return denied;
148153 const planId = ctx.url.searchParams.get("plan") ?? undefined;
149 return render(ctx, undefined, planId === undefined ? {} : { planId });
154 return render(ctx, undefined, planId === undefined ? { app: ctx.url.searchParams.get("app") ?? "" } : { planId });
150155 }
151156
152157 // GET /infra/live?part=running | ?plan=<id>: a live region alone, refetched on an event.
src/tui/app/palette.ts +9 −1
@@ -15,6 +15,11 @@ import { center, split, len, fill } from "../ui/layout.ts";
1515 import type { Tokens } from "../ui/theme.ts";
1616 import { card, input, type CursorPos } from "../ui/widgets.ts";
1717 import type { KeyEvent } from "../term/input.ts";
18 import { GO_PAGES } from "../../web/go_pages.ts";
19 import { wordsHit } from "../../web/palette.ts";
20
21 /** An area's search words by its command (`games` is /games): the web palette's own list. */
22 const AREA_WORDS = new Map(GO_PAGES.flatMap((p) => (p.words === undefined ? [] : [[p.href.slice(1), p.words] as const])));
1823
1924 export interface Command {
2025 readonly id: string;
@@ -111,7 +116,10 @@ export function score(
111116 export function rank(commands: readonly Command[], query: string): Match[] {
112117 const out: Match[] = [];
113118 for (const command of commands) {
114 const hit = score(query, command.title);
119 // A search word counts just under a title that says the same; nothing is bold, since none of it is drawn.
120 const word = wordsHit(query, AREA_WORDS.get(command.id) ?? "") ? score(query, query) : null;
121 const title = score(query, command.title);
122 const hit = word !== null && (title === null || title.score < word.score - 1) ? { score: word.score - 1, indices: title?.indices ?? [] } : title;
115123 if (hit === null) continue;
116124 out.push({ command, score: hit.score, indices: hit.indices });
117125 }
src/tui/screens/asks_lines.ts +9 −3
@@ -6,23 +6,29 @@
66 * (`viewFor`), as on the page.
77 */
88 import type { Database } from "bun:sqlite";
9 import { listReposByOwner } from "../../core/repos.ts";
910 import type { User } from "../../core/users.ts";
1011 import { laneHealth, queueWords, viewFor, type LanePicture } from "../../flow/lanes.ts";
1112
13 import { herePlaying } from "../../games/store.ts";
14 import { GO } from "../../web/keymap.ts";
15
1216 /** How many asks the block lists before it says how many more are on home. */
1317 export const ASKS_SHOWN = 4;
1418
1519 /**
1620 * The block's lines: the lane's words, its first asks and the crew's line; none when nothing is asked
17 * and nothing waits, so a calm terminal home spends no row on it.
21 * and nothing waits, so a calm terminal home spends no row on it. A person here for a game box alone
22 * reads the way to their games instead, as the page's line has it.
1823 */
1924 export function asksLines(db: Database, viewer: User, picture: LanePicture, now = Date.now()): string[] {
2025 const viewing = viewFor(db, viewer, picture);
2126 const view = viewing.lanes.asked;
2227 const health = laneHealth(view, { now, builders: picture.builders, moved: picture.moved, idle: picture.idle });
2328 const queue = queueWords(viewing.queued, { builders: picture.builders, moved: picture.moved.asked + picture.moved.building, idle: picture.idle });
24 if (view.total === 0 && queue === null) return [];
25 const lines = [`Asked: ${health.words}`];
29 const games = view.total === 0 && herePlaying(db, viewer, () => listReposByOwner(db, viewer.username, viewer, { limit: 1, withoutArchived: true, withoutCounts: true }).length);
30 if (view.total === 0 && queue === null) return games ? [`Asked: ${health.words} Your games: g ${GO.global.games}`] : [];
31 const lines = [`Asked: ${health.words}${games ? ` Your games: g ${GO.global.games}` : ""}`];
2632 for (const i of view.items.slice(0, ASKS_SHOWN))
2733 lines.push(` ${i.repo}${i.number === null ? "" : `#${i.number}`} ${i.title}${i.hint === "" ? "" : ` · ${i.hint}`}`);
2834 if (view.total > ASKS_SHOWN) lines.push(` ${view.total - ASKS_SHOWN} more in the Asked lane on home`);
src/tui/screens/deploys.ts +8
@@ -143,6 +143,7 @@ import { envTone } from "./runwords.ts";
143143 import { pullScreen } from "./pull.ts";
144144 import { local } from "./where.ts";
145145 import { appMembersScreen } from "./appmembers.ts";
146 import { runOnItsOwnMachine } from "./infra.ts";
146147 import { contributorMay, contributorNow, linkOpens } from "../../text/contributor.ts";
147148 import { CONTRIBUTOR_WORDS, inviteContributor, inviteLinkTo, removeContributorFrom, repoPeople, type ContributorError } from "../../actions/invites.ts";
148149 import { publicOrigin } from "../../core/public_origin.ts";
@@ -254,6 +255,8 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
254255 let production: Production = { state: "", redeploy: false, stop: false, alwaysOn: false, note: "" };
255256 let members = false;
256257 // Inviting is the repository admin's (`inviteContributor` decides; this only shows the key).
258 /** As the app's page offers it: a forge admin, of a repository that is an app. */
259 const mayMachine = (): boolean => f.user?.isAdmin === true && isApp;
257260 const mayInvite = (): boolean => f.user !== undefined && f.user.kind === "user" && canAdmin(f.db, repo, f.user);
258261 let prompts = false;
259262 let stoppable = false;
@@ -436,6 +439,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
436439 ...(visitors !== "" ? [binding(["v"], withReaders ? "leave readers out" : "count readers")] : []),
437440 ...(mayInvite() ? [binding(["W"], "who works on it: invite, list, take off")] : []),
438441 ...(domains !== undefined ? [binding(["n"], "the app's own domains")] : []),
442 ...(mayMachine() ? [binding(["M"], "run it on its own machine")] : []),
439443 ...(prompts ? [binding(["i"], "prompt source (Instagram)")] : []),
440444 ...(stoppable ? [binding(["X"], STOP_APP.toLowerCase())] : []),
441445 ...(mayBuild ? [binding(["b"], "preview a commit")] : []),
@@ -612,6 +616,10 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
612616 ctx.push(contributorsScreen(f, ctx, repo));
613617 return true;
614618 }
619 if (e.key === "M" && mayMachine()) {
620 runOnItsOwnMachine(f, ctx, `${repo.ownerName}/${repo.name}`);
621 return true;
622 }
615623 if (e.key === "n" && domains !== undefined) {
616624 ctx.push(domainsScreen(f, ctx, repo, read));
617625 return true;
src/tui/screens/infra.ts +34 −15
@@ -39,7 +39,17 @@ import type { PaletteEntry } from "./entries.ts";
3939 const month = (cents: number): string => `${dollars(cents)}/mo`;
4040 const STEP = { waiting: "·", started: "…", done: "✓", failed: "✗" } as const;
4141
42 export function infraScreen(f: Session, ctx: Ctx): Screen {
42 export const infraScreen = (f: Session, ctx: Ctx): Screen => infraWithCompose(f, ctx).screen;
43
44 /** An app's own way in, as its page's "Run it on its own machine": the same compose with that app, for running it, with no end; where it runs is asked, then the plan. */
45 export function runOnItsOwnMachine(f: Session, ctx: Ctx, app: string): void {
46 const { screen, compose } = infraWithCompose(f, ctx);
47 ctx.push(screen);
48 const next = compose(screen, app);
49 if (next !== screen) ctx.push(next);
50 }
51
52 function infraWithCompose(f: Session, ctx: Ctx): { screen: Screen; compose: (parent: Screen, asked?: string) => Screen } {
4353 const state = new ListState();
4454 let note = "";
4555 let building: string | undefined;
@@ -153,8 +163,13 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
153163 };
154164
155165 /** The compose, one question at a time; each answer narrows the next, and the plan comes last. */
156 const compose = (parent: Screen): Screen => {
166 const compose = (parent: Screen, asked = ""): Screen => {
157167 const c = composeChoices(f.app);
168 const barred = c.apps.find((a) => a.app === asked && a.why !== "");
169 if (barred !== undefined) {
170 say(`${asked} cannot run on a machine: ${barred.why}.`);
171 return parent;
172 }
158173 const apps = c.apps.filter((a) => a.why === "");
159174 if (apps.length === 0) {
160175 say("No app can run on a machine yet: make one, and make it public.");
@@ -215,23 +230,27 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
215230 : later(ctx, howLong));
216231 },
217232 });
233 const where = (then: () => void): Screen =>
234 pickerScreen(ctx, parent, {
235 title: asked === "" ? "Where" : `Where ${asked} runs`,
236 items: c.places
237 .filter((p) => p.orderable)
238 .map((p) => ({ id: p.value, label: `${p.where} · ${p.label} ${p.size}`, hint: dollars(p.costCents) })),
239 onPick: ([at = ""]) => {
240 draft.where = at;
241 then();
242 },
243 });
244 if (asked !== "") {
245 Object.assign(draft, { app: asked, name: nameFor(asked), why: "app", days: "none" });
246 return where(() => void showPlan());
247 }
218248 return pickerScreen(ctx, parent, {
219249 title: "A machine running",
220250 items: apps.map((a) => ({ id: a.app, label: a.app })),
221251 onPick: ([app = ""]) => {
222252 Object.assign(draft, { app, name: nameFor(app) });
223 void later(ctx, () =>
224 pickerScreen(ctx, parent, {
225 title: "Where",
226 items: c.places
227 .filter((p) => p.orderable)
228 .map((p) => ({ id: p.value, label: `${p.where} · ${p.label} ${p.size}`, hint: dollars(p.costCents) })),
229 onPick: ([where = ""]) => {
230 draft.where = where;
231 void later(ctx, why);
232 },
233 }),
234 );
253 void later(ctx, () => where(() => void later(ctx, why)));
235254 },
236255 });
237256 };
@@ -652,7 +671,7 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
652671 return true;
653672 },
654673 };
655 return screen;
674 return { screen, compose };
656675 }
657676
658677 /** Infrastructure, as /infra and the `infra` tool have it: a forge admin. */
src/web/client.ts +1
@@ -2108,6 +2108,7 @@ ${whichStubJs(whichAsset().path)}
21082108 if (i.a === 1) r.a = 1;
21092109 if (i.d) r.d = String(i.d);
21102110 if (i.x) r.x = String(i.x);
2111 GO_PAGES.forEach(function (p) { if (p[1] === r.h) r.w = p[4]; });
21112112 if (i.o && String(i.o).charAt(0) === '/') r.o = String(i.o);
21122113 if (i.p && typeof i.p === 'object' && r.h.charAt(0) === '/') r.p = i.p;
21132114 return r;
src/web/go_pages.ts +16 −10
@@ -15,6 +15,8 @@ export interface GoPage {
1515 readonly who: "all" | "user" | "games" | "admin";
1616 /** One of the forge's areas: the top bar names it on every page. */
1717 readonly area?: true;
18 /** Plain words a person types for it, matched and never shown (`wordsHit`). */
19 readonly words?: string;
1820 /** Present when the Cmd/Ctrl K palette also lists it as a "Go to" row, in its longer wording. */
1921 readonly palette?: string;
2022 /** The letter that follows `g` to jump here from any page (`g e` Explore). One letter, once. */
@@ -23,9 +25,9 @@ export interface GoPage {
2325
2426 export const GO_PAGES: readonly GoPage[] = [
2527 { name: "Home", href: "/", who: "all", key: GO.global.home, palette: "Home" },
26 { name: "Apps", href: "/apps", who: "all", area: true, key: GO.global.apps, palette: "Apps" },
27 { name: "Games", href: "/games", who: "games", area: true, key: GO.global.games, palette: "Games" },
28 { name: "Infrastructure", href: "/infra", who: "admin", area: true, key: GO.global.infra, palette: "Infrastructure" },
28 { name: "Apps", href: "/apps", who: "all", area: true, words: "app deploy site", key: GO.global.apps, palette: "Apps" },
29 { name: "Games", href: "/games", who: "games", area: true, words: "minecraft server players", key: GO.global.games, palette: "Games" },
30 { name: "Infrastructure", href: "/infra", who: "admin", area: true, words: "cloud cost spend bill infra machine server aws deploy", key: GO.global.infra, palette: "Infrastructure" },
2931 { name: "Explore", href: "/explore", who: "all", area: true, key: GO.global.explore, palette: "Explore" },
3032 { name: "Packs", href: "/packs", who: "all", palette: "Forge packs" },
3133 { name: "Front page", href: "/front", who: "all", palette: "Front page" },
@@ -72,9 +74,9 @@ export const mayGo = (page: Pick<GoPage, "who">, viewer: GoViewer): boolean => N
7274 /** The pages this viewer may be sent to, in list order. */
7375 export const goPagesFor = (viewer: GoViewer): GoPage[] => GO_PAGES.filter((p) => mayGo(p, viewer));
7476
75 /** The list as the keys script carries it: [name, href, level needed, the letter after `g` or ""]. */
76 export function goPagesData(): [string, string, number, string][] {
77 return GO_PAGES.map((p) => [p.name, p.href, NEEDS[p.who], p.key ?? ""]);
77 /** The list as the keys script carries it: [name, href, level needed, the letter after `g` or "", its search words if any]. */
78 export function goPagesData(): [string, string, number, string, string?][] {
79 return GO_PAGES.map((p) => (p.words === undefined ? [p.name, p.href, NEEDS[p.who], p.key ?? ""] : [p.name, p.href, NEEDS[p.who], p.key ?? "", p.words]));
7880 }
7981
8082 /** The Cmd/Ctrl K palette's "Go to" rows, in list order, and which of them a stranger may see. */
@@ -91,12 +93,16 @@ export function goPaletteRows(): { t: string; h: string; visitor: boolean; who:
9193 * The filter, as the JavaScript the keys script ships: `goMatch(pages, q)`
9294 * takes [name, href, level] rows and returns those whose lower-cased name
9395 * contains the trimmed, lower-cased query, names that start with it first,
94 * ties in list order. The first element is what Enter opens. It lives here as
96 * ties in list order, then the pages one of whose search words starts with it
97 * (`wordsHit`, shipped beside it). The first element is what Enter opens. It lives here as
9598 * source so the test can run the very code the browser runs.
9699 */
97100 export const GO_MATCH_JS = `function goMatch(pages, q) {
98101 q = String(q).trim().toLowerCase();
99 var hits = pages.filter(function (p) { return q === '' || p[0].toLowerCase().indexOf(q) >= 0; });
100 var starts = hits.filter(function (p) { return p[0].toLowerCase().indexOf(q) === 0; });
101 return starts.concat(hits.filter(function (p) { return starts.indexOf(p) < 0; }));
102 return [0, 1, 2].reduce(function (out, tier) {
103 return out.concat(pages.filter(function (p) {
104 var at = p[0].toLowerCase().indexOf(q);
105 return tier === (at === 0 ? 0 : at > 0 ? 1 : p[4] && wordsHit(q, p[4]) ? 2 : 3);
106 }));
107 }, []);
102108 }`;
src/web/layout.ts +26 −12
@@ -14,7 +14,7 @@ import { sshOn } from "../settings/ssh.ts";
1414 import { hereAddress, returnTo, withReturn } from "./return_to.ts";
1515 import { countWaiting } from "../core/fence.ts";
1616 import { GO_PAGES, goLevel, goPaletteRows, mayGo, type GoViewer } from "./go_pages.ts";
17 import { seesAnyBox } from "../games/store.ts";
17 import { seesAnyBox, herePlaying } from "../games/store.ts";
1818 import { NEW_ISSUE_KEY } from "./script_keys.ts";
1919 import { newIssueHref } from "./issue_from.ts";
2020 import { OPENSEARCH_PATH, OPENSEARCH_TITLE, OPENSEARCH_TYPE } from "./opensearch.ts";
@@ -383,6 +383,7 @@ function userMenu(
383383 ? [
384384 { label: "People", href: "/settings/people", icon: "users" as const },
385385 { label: "Forges", href: "/forges", icon: "fork" as const },
386 { label: "Infrastructure", href: "/infra", icon: "globe" as const },
386387 ]
387388 : []),
388389 { separator: true, label: "" },
@@ -488,19 +489,14 @@ function paletteIndex(ctx: Ctx, extra: PaletteItem[]): Html {
488489 // One forge (#603): a conversation's remote row is built with the
489490 // studio's nouns, which answer for every repository.
490491 const studio = true;
491 // The viewer's own first, apps ahead of the rest in each half, thirty in
492 // all; archived ones
493 // are put away, found by typing the full name into search.
494 const wanted = { limit: 30, appsFirst: true, withoutArchived: true, withoutCounts: true };
495 const mine = ctx.auth.user
496 ? listReposByOwner(ctx.app.db, ctx.auth.user.username, ctx.auth.user, wanted)
497 : [];
492 // The viewer's own first, apps ahead of the rest in each half, thirty in all.
493 const mine = ownRepos(ctx);
498494 const taken = new Set(mine.map((r) => r.id));
499495 // A signed-out visitor is offered what the front door shows, no more.
500496 const repos = ctx.auth.user
501497 ? [
502498 ...mine,
503 ...listReposVisibleTo(ctx.app.db, ctx.auth.user, wanted).filter(
499 ...listReposVisibleTo(ctx.app.db, ctx.auth.user, LISTED).filter(
504500 (r) => !taken.has(r.id),
505501 ),
506502 ].slice(0, 30)
@@ -714,17 +710,35 @@ function talkButton(ctx: Ctx, user: User, about?: string): Html {
714710 }
715711
716712 /** Who is looking, for the pages they may be sent to. No read of its own: `seesAnyBox` keeps it. */
717 const goViewer = (ctx: Ctx): GoViewer => ({
713 export const goViewer = (ctx: Ctx): GoViewer => ({
718714 signedIn: ctx.auth.user !== undefined,
719715 admin: ctx.auth.user?.isAdmin === true,
720716 games: seesAnyBox(ctx.app.db, ctx.auth.user),
721717 });
722718
723 /** The areas this viewer may use (`GO_PAGES`), the one they are in marked. */
719 /** What the palette lists of a person's repositories; archived ones are put away, found by their full name in search. */
720 const LISTED = { limit: 30, appsFirst: true, withoutArchived: true, withoutCounts: true } as const;
721 const owned = new WeakMap<Ctx, Repo[]>();
722
723 /** The viewer's own repositories, read once a request: the palette lists them and `playsOnly` asks if there are any. */
724 function ownRepos(ctx: Ctx): Repo[] {
725 const user = ctx.auth.user;
726 if (user === undefined) return [];
727 let mine = owned.get(ctx);
728 if (mine === undefined) owned.set(ctx, (mine = listReposByOwner(ctx.app.db, user.username, user, LISTED)));
729 return mine;
730 }
731
732 /** `herePlaying`, with the repositories this request has read already. */
733 export const playsOnly = (ctx: Ctx): boolean => herePlaying(ctx.app.db, ctx.auth.user, () => ownRepos(ctx).length);
734
735 /** The areas this viewer may use (`GO_PAGES`), the one they are in marked; Games first for `playsOnly`. */
724736 function areas(ctx: Ctx): Html {
725737 const viewer = goViewer(ctx);
738 const shown = GO_PAGES.filter((p) => p.area === true && mayGo(p, viewer));
739 if (playsOnly(ctx)) shown.sort((a, b) => Number(b.who === "games") - Number(a.who === "games"));
726740 const at = ctx.url.pathname;
727 return html`<nav class="areas" aria-label="Areas">${GO_PAGES.filter((p) => p.area === true && mayGo(p, viewer)).map(
741 return html`<nav class="areas" aria-label="Areas">${shown.map(
728742 (p) => html`<a href="${p.href}"${at === p.href || at.startsWith(`${p.href}/`) ? raw(' aria-current="page"') : null}>${p.name}</a>`,
729743 )}</nav>`;
730744 }
src/web/pages/cloud.ts +3 −3
@@ -162,7 +162,7 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[]
162162 return html`<section class="settings-block">
163163 <h2>Cloud accounts</h2>
164164 <p class="muted small">Each account has a monthly spend ceiling, $50 until you change it: the forge refuses to make a machine or volume that would take it past. The cost shown is the forge's own reckoning from list prices; the provider's bill is the truth.</p>
165 <p class="muted small">Paste a credential once; the forge checks it read-only, seals it, and never shows it again. The quickest way: <a href="/cloud/connect">Connect a cloud</a>.</p>
165 <p class="muted small">Paste a credential once; the forge checks it read-only, seals it, and never shows it again. The quickest way: <a href="/cloud/connect">Connect a cloud</a>. What runs on them and what it costs: <a href="/infra">Infrastructure</a>.</p>
166166 ${rows.length > 0
167167 ? html`<ul class="list setting-list">${rows}</ul>`
168168 : emptyLine("cloudAccounts")}
@@ -462,12 +462,12 @@ export function cloudConnectPage(ctx: Ctx): Response {
462462 title: "Connect a cloud",
463463 body: html`${pageHead("Connect a cloud", { sub: "Paste one key and the forge can deploy, watch and manage what runs there." })}
464464 ${rowList(CONNECT.map((g) => row({ href: `${CONNECT_HOME}/${g.provider}`, title: LABEL[g.provider], meta: html`${g.can}${have.some((a) => a.provider === g.provider) ? " · connected" : ""}` })))}
465 <p class="muted small">Other providers, and every key the forge holds: <a href="${BACK}">cloud accounts</a>.</p>`,
465 <p class="muted small">Other providers, and every key the forge holds: <a href="${BACK}">cloud accounts</a>. What runs on them: <a href="/infra">Infrastructure</a>.</p>`,
466466 }));
467467 }
468468
469469 function connectView(ctx: Ctx, g: ConnectGuide, body: Html, status = 200): Response {
470 return timePhase(ctx.request, "render", () => page({ ctx, title: `Connect ${LABEL[g.provider]}`, body: html`${pageHead(`Connect ${LABEL[g.provider]}`, { sub: g.can })}${body}` }, status));
470 return timePhase(ctx.request, "render", () => page({ ctx, title: `Connect ${LABEL[g.provider]}`, body: html`${pageHead(`Connect ${LABEL[g.provider]}`, { sub: html`${g.can} What runs there is in <a href="/infra">Infrastructure</a>.` })}${body}` }, status));
471471 }
472472
473473 // GET /cloud/connect/:provider (?account=<name> once connected)
src/web/pages/forges.ts +1 −1
@@ -306,7 +306,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
306306 title: "Forges you sent",
307307 body: html`<div class="narrow-wide" data-forges>
308308 ${pageHead("Forges you sent", {
309 sub: "Each forge you sent, and what runs there.",
309 sub: html`Each forge you sent. Machines and cost: <a href="/infra">Infrastructure</a>.`,
310310 actions: html`${action}${btn("Move in", { href: "/forges/move-in", size: "sm", title: "Move a forge that runs in a browser onto this one by copying its files" })}`,
311311 })}
312312 ${over === undefined ? null : html`<p class="muted small" role="status" data-memory-over>${over}</p>`}
src/web/pages/home_flow.ts +11 −5
@@ -57,7 +57,7 @@ import { readSlots } from "../../flow/slots.ts";
5757 import { behaviorsJs } from "../behaviors.ts";
5858 import { liveRegionsJs } from "../client.ts";
5959 import { html, type Html } from "../html.ts";
60 import { fragment, page, redirect } from "../layout.ts";
60 import { fragment, page, playsOnly, redirect } from "../layout.ts";
6161 import { secureFor } from "../../http/cookie_secure.ts";
6262 import { cookieValue } from "../../http/context.ts";
6363 import { parseTable, tableParams, tableRows, type TableQuery } from "../../flow/lanes_table.ts";
@@ -192,6 +192,8 @@ export function laneRegion(
192192 times?: LaneTimes,
193193 /** The Asked lane's one line for the crew's queue (`queueLine`), under its asks. */
194194 queue: Html | null = null,
195 /** The Asked lane's link to a player's games (`gamesLink`), after its words. */
196 games: Html | null = null,
195197 ): Html {
196198 const key = view.key;
197199 const said = timeWords(times?.nows[key] ?? null, times?.typicals[key] ?? null, span);
@@ -233,7 +235,7 @@ export function laneRegion(
233235 ></span
234236 >${TONE_WORD[health.tone]}</span
235237 >
236 ${health.words}
238 ${health.words}${total === 0 ? games : null}
237239 </p>
238240 <p class="lane-times num">${said}</p>
239241 ${shown === 0
@@ -270,6 +272,9 @@ export function queueLine(viewing: Viewing, picture: LanePicture): Html | null {
270272 return said === null ? null : html`<p class="small muted" data-queue>${said} <a href="/next">See the list</a></p>`;
271273 }
272274
275 /** For a person here for a game box alone (`playsOnly`), their games: the pipeline has nothing of theirs. */
276 const gamesLink = (ctx: Ctx): Html | null => (playsOnly(ctx) ? html` <a href="/games" data-your-games>Your games</a>` : null);

Both doors: the terminal's home (src/tui/screens/asks_lines.ts) gives a player with no repository no way to Games. Add the same line there, or put No door: <why> in the commit.

277
273278 const healthOf = (view: LaneView, picture: LanePicture, now: number): Health => laneHealth(view, { now, builders: picture.builders, moved: picture.moved, idle: picture.idle });
274279
275280 // ---- the header's one line, and the strip: today's figures ----
@@ -478,7 +483,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited
478483 main = html`${tableTools(q)}${tableRegion(tableRows(viewing, tableInput(picture, now)), q, now)}`;
479484 } else {
480485 const times = timesFor(viewing, picture, user.isAdmin && user.kind !== "agent", now);
481 main = html`<div class="hf-lanes">${LANES.map((k) => laneRegion(viewing.lanes[k], healths.get(k)!, only, user.isAdmin, now, mine, times, k === "asked" ? queueLine(viewing, picture) : null))}</div>`;
486 main = html`<div class="hf-lanes">${LANES.map((k) => laneRegion(viewing.lanes[k], healths.get(k)!, only, user.isAdmin, now, mine, times, k === "asked" ? queueLine(viewing, picture) : null, k === "asked" ? gamesLink(ctx) : null))}</div>`;
482487 }
483488 // The first-wrong facts are read once, for the line and for the words above it.
484489 const tones = healths === undefined ? [] : [...healths.values()].map((h) => h.tone);
@@ -573,14 +578,15 @@ export async function liveLaneFragment(ctx: Ctx): Promise<Response> {
573578 if (picture === undefined) return fragment(readingLane(key, only), { request: ctx.request });
574579 const mine = waitsOf(ctx.url);
575580 const waits = mine ? waitingOnMe(ctx, user) : undefined;
576 const tag = laneTag(picture, key, user.isAdmin ? "admin" : user.id, only, now, waits === undefined ? "" : waitsDigest(waits));
581 const games = key === "asked" ? gamesLink(ctx) : null;
582 const tag = laneTag(picture, key, user.isAdmin ? "admin" : user.id, only, now, `${waits === undefined ? "" : waitsDigest(waits)}${games === null ? "" : "|games"}`);
577583 if (requestHolds(ctx.request, `"${tag}"`)) {
578584 notePhase(ctx.request, "render", performance.now() - rendering);
579585 return new Response(null, { status: 304, headers: { etag: `"${tag}"`, "cache-control": "no-store" } });
580586 }
581587 const viewing = timePhase(ctx.request, "viewing", () => viewFor(ctx.app.db, user, picture, only, waits));
582588 const view = viewing.lanes[key];
583 const res = fragment(laneRegion(view, healthOf(view, picture, now), only, user.isAdmin, now, mine, timesFor(viewing, picture, user.isAdmin && user.kind !== "agent", now), view.key === "asked" ? queueLine(viewing, picture) : null), { request: ctx.request, etag: tag });
589 const res = fragment(laneRegion(view, healthOf(view, picture, now), only, user.isAdmin, now, mine, timesFor(viewing, picture, user.isAdmin && user.kind !== "agent", now), view.key === "asked" ? queueLine(viewing, picture) : null, games), { request: ctx.request, etag: tag });
584590 notePhase(ctx.request, "render", performance.now() - rendering);
585591 return res;
586592 }
src/web/pages/home_flow_style.ts +1
@@ -48,6 +48,7 @@ export const homeFlowCss = /* css */ `
4848 .lane-count { font-size: 20px; font-weight: 600; line-height: 24px; letter-spacing: -0.01em; }
4949 .lane[data-count="0"] .lane-count { color: var(--faint); }
5050 .lane-health { margin: 0; padding-inline: 4px; font-size: 12.5px; line-height: 18px; color: var(--muted-fg); }
51 .lane-health a { color: var(--accent); }
5152 .lane-times { margin: 0; padding-inline: 4px; font-size: 12.5px; line-height: 18px; min-height: 18px; color: var(--muted-fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
5253 .lane-bottleneck { margin-left: auto; font-size: 12.5px; font-weight: 600; color: var(--fg); }
5354 .lane-state { display: inline-flex; align-items: center; gap: 4px; margin-right: 4px; font-weight: 600; color: var(--fg); white-space: nowrap; }
src/web/pages/machines.ts +2 −2
@@ -164,7 +164,7 @@ export function machineRows(
164164
165165 function render(ctx: Ctx, repo: Repo, list: readonly Machine[], sessions: readonly SessionRecord[], states: ReadonlyMap<string, MachineState>, disks: ReadonlyMap<string, readonly DeviceSummary[]>): Response {
166166 const machines = html`<section class="settings-block">
167 <h2>Machines</h2>
167 <h2>The crew's machines</h2>
168168 <ul class="list setting-list" id="machines">
169169 ${machineRows(repo, list, states, disks)}
170170 </ul>
@@ -189,7 +189,7 @@ function render(ctx: Ctx, repo: Repo, list: readonly Machine[], sessions: readon
189189 )}
190190 </ul>`}
191191 </section>`;
192 const body = html`${machines}${recent}`;
192 const body = html`${machines}${ctx.auth.user?.isAdmin === true ? html`<p class="small"><a href="/infra">Machines on your cloud</a></p>` : null}${recent}`;
193193 // The settings frame and its sections are an admin's; a writer who is not
194194 // one sees this pane alone, so no link offers them a page that refuses.
195195 if (canAdmin(ctx.app.db, repo, ctx.auth.user))
src/web/pages/origins.ts +1
@@ -177,6 +177,7 @@ const SECTION_ROWS: readonly (readonly [
177177 ["Crew and AI", "Usage", "/settings/spend", "activity", (c) => USAGE.has(c), true],
178178 ["Connections", "Connected accounts", "/settings/origins", "globe", (c) => c === "origins", false],
179179 ["Connections", "Cloud", "/settings/cloud", "key", (c) => c === "cloud", true],
180 ["Connections", "Infrastructure", "/infra", "globe", () => false, true], // what runs there and what it costs
180181 ["Connections", "Secrets", "/settings/secrets", "lock", (c) => c === "secrets", true],
181182 ["Connections", "Devices", "/settings/devices", "globe", (c) => c === "devices", true],
182183 ["Security", "Security", "/settings/security", "lock", (c) => c === "security", true],
src/web/pages/search.ts +7 −2
@@ -47,7 +47,9 @@ import { notFoundPage, pageHead } from "../chrome.ts";
4747 import { html, when, type Html } from "../html.ts";
4848 import { DELETE_REPO, STOP_APP, dangerDetail } from "../danger_words.ts";
4949 import { icon } from "../icons.ts";
50 import { page } from "../layout.ts";
50 import { goPagesFor } from "../go_pages.ts";
51 import { goViewer, page } from "../layout.ts";
52 import { wordsHit } from "../palette.ts";
5153 import { browseBase } from "../scope.ts";
5254 import { originIcon } from "../origin_icon.ts";
5355 import { appsOf } from "../studio/asks.ts";
@@ -551,7 +553,10 @@ export async function searchPage(ctx: Ctx): Promise<Response> {
551553 ...(guidesFirst ? [guides] : []),
552554 ...sections.flatMap((s) => (s.kind === "repos" && !guidesFirst ? [s.html, guides] : [s.html])),
553555 ];
554 const body = html`<div data-search>${pageHead(html`Results for “${echoed(a.query)}”`)} ${form}${trimmed}
556 // An area called by its name or by one of its search words ("minecraft" is Games) comes first.
557 const places = a.kind !== "all" ? [] : goPagesFor(goViewer(ctx)).filter((p) => p.area === true && (p.name.toLowerCase() === a.query.trim().toLowerCase() || wordsHit(a.query, p.words ?? "")));
558 const goTo = places.length === 0 ? null : html`<p data-places>Go to ${places.map((p, i) => html`${i > 0 ? " or " : ""}<a href="${p.href}">${p.name}</a>`)}</p>`;
559 const body = html`<div data-search>${pageHead(html`Results for “${echoed(a.query)}”`)} ${form}${trimmed}${goTo}
555560 <div class="bar mb">${chips}</div>
556561 ${liveToggle}
557562 ${when(
src/web/palette.ts +15 −3
@@ -29,6 +29,8 @@ export interface PaletteRow {
2929 readonly k?: number;
3030 /** An action: asks one confirmation before it runs. */
3131 readonly a?: 1;
32 /** An area's plain search words: scored (`wordsHit`), never shown. */
33 readonly w?: string;
3234 }
3335
3436 /** A heading and the rows under it, best first. */
@@ -81,6 +83,14 @@ export function fuzzyScore(query: string, text: string): number {
8183 return total;
8284 }
8385
86 /**
87 * Whether every word typed, from its third letter, is one of an area's search words or the start of
88 * one. Never letters in order: "server" must not find "observe".
89 */
90 export function wordsHit(query: string, words: string): boolean {
91 return query.toLowerCase().trim().split(/\s+/).every((w) => w.length > 2 && (" " + words).includes(" " + w));
92 }
93
8494 /**
8595 * The list the dialog shows: the rows that answer `query`, best first, cut
8696 * to `limit`, then folded into groups in the order their best row earned —
@@ -117,8 +127,10 @@ export function rankPalette(
117127 scored.push({ r, s, i });
118128 return;
119129 }
120 if (title === 0 && detail === 0) return;
121 s = title + detail / 2 + (recent.indexOf(r.h) === -1 ? 0 : 50);
130 // A search word counts a little under a title that says the same, so a page called that still leads.
131 const word = r.w && wordsHit(q, r.w) ? fuzzyScore(q, q) - 50 : 0;
132 if (title === 0 && detail === 0 && word === 0) return;
133 s = Math.max(title, word) + detail / 2 + (recent.indexOf(r.h) === -1 ? 0 : 50);
122134 // A repository named by what was typed beats every other kind of
123135 // landing: exact, then prefix; the viewer's own ahead of the rest.
124136 if (r.n !== undefined && !/\s/.test(q)) {
@@ -316,4 +328,4 @@ export function palettePool(
316328 * this module before it ever parses it, so `toString` is already the
317329 * browser's dialect. A test proves the string and the module agree.
318330 */
319 export const paletteHelpersJs = `${fuzzyScore.toString()}\n${rankPalette.toString()}\n${opensAsSheet.toString()}\n${sendsNothing.toString()}\n${frecencyOrder.toString()}\n${readUses.toString()}\n${recordUse.toString()}\n${recordVisit.toString()}\n${visitRows.toString()}\n${visitLoad.toString()}\n${palettePool.toString()}`;
331 export const paletteHelpersJs = `${fuzzyScore.toString()}\n${wordsHit.toString()}\n${rankPalette.toString()}\n${opensAsSheet.toString()}\n${sendsNothing.toString()}\n${frecencyOrder.toString()}\n${readUses.toString()}\n${recordUse.toString()}\n${recordVisit.toString()}\n${visitRows.toString()}\n${visitLoad.toString()}\n${palettePool.toString()}`;
src/web/pinned.ts +1 −1
@@ -77,7 +77,7 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Plac
7777 A pinned forge runs one version you choose, on a server in your own cloud account. It has no crew and
7878 never updates itself: it changes only when you press Update, and Rollback is one action back.
7979 </p>
80 <p class="muted small">${HOST_CAN}</p>
80 <p class="muted small">${HOST_CAN} What runs on your clouds is in <a href="/infra">Infrastructure</a>.</p>
8181 ${usable.length === 0
8282 ? html`<p class="small" role="status">No cloud account can write yet. Add a ${NAMES} account and allow writes on
8383 <a href="/settings/cloud">Cloud accounts</a>, then come back to this page: what the link carried is kept.</p>`
src/web/studio/app.ts +1
@@ -503,6 +503,7 @@ export async function studioApp(
503503 <a href="${base}/variants">Variants</a>
504504 ${when(canWrite(db, repo, ctx.auth.user), () => html`<a href="${base}/drop">Drop</a>`)}
505505 ${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>`)}

Both doors: "Run it on its own machine" opens Build on this app on the web only. The terminal's Infrastructure n cannot start from an app. Add that entry, or put No door: <why> in the commit.

506507 ${when(canAdmin(db, repo, ctx.auth.user), () => html`<a href="/-/confirm?to=${encodeURIComponent(`${base}/archive`)}">Archive</a>`)}
507508 </p>`;
508509
test/account-menu.test.ts +2 −2
@@ -63,9 +63,9 @@ test("a member's menu: their own pages, Settings, then this browser", async () =
6363 expect(html).toContain('aria-label="Account: ada"');
6464 });
6565
66 test("an admin's menu adds People and Forges beside Settings, and nothing else", async () => {
66 test("an admin's menu adds People, Forges and Infrastructure beside Settings, and nothing else", async () => {
6767 const { rows } = await menuRows("/", admin);
68 expect(rows).toEqual(["Your profile", "Repositories", "---", "Settings", "People", "Forges", ...SESSION]);
68 expect(rows).toEqual(["Your profile", "Repositories", "---", "Settings", "People", "Forges", "Infrastructure", ...SESSION]);
6969 });
7070
7171 test("a visitor's menu: no account rows, the same one row for appearance, and the way to every theme", async () => {
test/areas-fit.test.ts +1 −1
@@ -62,7 +62,7 @@ describe.skipIf(chromium === undefined)("the areas at 390x844", () => {
6262
6363 const PAGES: [string, string, string[]][] = [
6464 ...["/", "/feed", "/design", "/alice/site", "/apps", "/talk"].map((p): [string, string, string[]] => ["alice", p, ["Apps", "Games", "Infrastructure", "Explore"]]),
65 ...["/", "/games"].map((p): [string, string, string[]] => ["player", p, ["Apps", "Games", "Explore"]]),
65 ...["/", "/games"].map((p): [string, string, string[]] => ["player", p, ["Games", "Apps", "Explore"]]),
6666 ...["/", "/explore", "/alice/site"].map((p): [string, string, string[]] => ["", p, ["Apps", "Explore"]]),
6767 ];
6868 test("every page shows them in words, pinned, for 44 px", async () => {
test/areas.test.ts +86 −2
@@ -13,16 +13,23 @@ import { START_BOX } from "../src/core/empty_words.ts";
1313 import { listConversations, listTurns } from "../src/core/conversations.ts";
1414 import { createSession } from "../src/core/sessions.ts";
1515 import { createUser, type User } from "../src/core/users.ts";
16 import { lanePicture } from "../src/flow/lanes.ts";
1617 import { createGameBox, grant, PLAYERS_MS, seesAnyBox } from "../src/games/store.ts";
1718 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
19 import { createForgeApp } from "../src/tui/forge.ts";
20 import { asksLines } from "../src/tui/screens/asks_lines.ts";
1821 import { entry as gamesEntry, gamesScreen } from "../src/tui/screens/games.ts";
1922 import { entry as infraEntry } from "../src/tui/screens/infra.ts";
23 import { rank } from "../src/tui/app/palette.ts";
2024 import { whichRows } from "../src/tui/app/which.ts";
2125 import type { Session } from "../src/tui/session.ts";
2226 import type { KeyEvent } from "../src/tui/term/input.ts";
23 import { goPagesFor } from "../src/web/go_pages.ts";
27 import { headlessTerminal } from "../src/tui/term/terminal.ts";
28 import { GO_MATCH_JS, goPagesData, goPagesFor } from "../src/web/go_pages.ts";
29 import { rankPalette, wordsHit, type PaletteRow } from "../src/web/palette.ts";
2430 import { quietLogs } from "./helpers/globals.ts";
2531 import { shellPage } from "./helpers/shell-page.ts";
32 import { settleApp } from "./helpers/tui.ts";
2633 import { quietCtx, screenText, sessionFor } from "./helpers/tui-text.ts";
2734
2835 quietLogs();
@@ -102,7 +109,8 @@ test("every door names the areas a person may use, and no other", async () => {
102109 for (const [user, want] of who) {
103110 const page = await pageFor(user);
104111 const name = user?.username ?? "a stranger";
105 expect(named(page), `${name}: the bar`).toEqual(want);
112 // Games leads the bar for a person here for a game box alone.
113 expect(named(page), `${name}: the bar`).toEqual(user === player ? ["Games", "Apps", "Explore"] : want);
106114 expect(inPalette(page), `${name}: the palette`).toEqual(want);
107115 const viewer = { signedIn: user !== undefined, admin: user?.isAdmin === true, games: seesAnyBox(app.db, user) };
108116 expect(goPagesFor(viewer).filter((p) => p.area).map((p) => p.name), `${name}: the : list`).toEqual(want);
@@ -177,3 +185,79 @@ test("? names a place a repository's tab shadows by its capital, and the others
177185 expect(await listed("")).toEqual(["gaGotoApps", "gpGotoGames", "giGotoInfrastructure"]);
178186 expect(await listed('<a href="/p" data-shortcut="g p">Pulls</a><a href="/i" data-shortcut="g i">Issues</a>')).toEqual(["gaGotoApps", "gPGotoGames", "gIGotoInfrastructure"]);
179187 });
188
189 /** The palette's own ranking over the rows this viewer's page carries, with the words `openPalette` adds. */
190 async function found(user: User | undefined, q: string): Promise<string[]> {
191 const json = /id="palette-index">([\s\S]*?)<\/script>/.exec(await pageFor(user))![1]!;
192 const rows = (JSON.parse(json) as { items: (PaletteRow & { c?: string })[] }).items.map((i) => ({ ...i, g: i.c ?? "Go to", w: goPagesData().find((p) => p[1] === i.h)?.[4] ?? "" }));
193 return rankPalette(rows, q, [], 20).flatMap((g) => g.rows.map((r) => r.t));
194 }
195 const goMatch = new Function(`${wordsHit.toString()}; ${GO_MATCH_JS}; return goMatch;`)() as (pages: ReturnType<typeof goPagesData>, q: string) => ReturnType<typeof goPagesData>;
196
197 test("a plain word finds its area first: in the palette, : and the terminal", async () => {
198 const commands = [["apps", "Apps"], ["games", "Games"], ["infra", "Infrastructure"]].map(([id, title]) => ({ id: id!, title: title!, run: () => {} }));
199 for (const [word, area] of [["deploy", "Apps"], ["minecraft", "Games"], ["spend", "Infrastructure"], ["aws", "Infrastructure"]] as const) {
200 expect((await found(admin, word))[0], word).toBe(area);
201 expect(goMatch(goPagesData(), word)[0]?.[0], `: ${word}`).toBe(area);
202 expect(rank(commands, word)[0]?.command.title, `terminal ${word}`).toBe(area);
203 }
204 // "server" is both, and half a word is enough.
205 expect((await found(admin, "server")).slice(0, 2).sort()).toEqual(["Games", "Infrastructure"]);
206 expect(rank(commands, "server").map((m) => m.command.title).sort()).toEqual(["Games", "Infrastructure"]);
207 expect((await found(admin, "minecr"))[0]).toBe("Games");
208 });
209
210 test("a search word never names an area the person may not use", async () => {
211 expect(await found(player, "server")).toContain("Games");
212 expect(await found(player, "server")).not.toContain("Infrastructure");
213 for (const user of [member, undefined]) for (const word of ["minecraft", "server", "spend"]) {
214 const rows = await found(user, word);
215 expect(rows).not.toContain("Games");
216 expect(rows).not.toContain("Infrastructure");
217 }
218 // The search page says it too, for a desk's field and for no script.
219 const placed = async (user: User, q: string) => /<p data-places>[\s\S]*?<\/p>/.exec(await pageFor(user, `/search?q=${q}`))?.[0] ?? "";
220 expect(await placed(player, "minecraft")).toContain('<a href="/games">Games</a>');
221 expect(await placed(member, "minecraft")).toBe("");
222 expect(await placed(admin, "server")).toContain('href="/infra"');
223 expect(await placed(player, "server")).not.toContain('href="/infra"');
224 });
225
226 test("an admin's pages about the cloud link to Infrastructure in the page itself", async () => {
227 const main = (page: string): string => page.slice(page.indexOf("<main"), page.indexOf("</main>"));
228 for (const path of ["/settings", "/settings/cloud", "/cloud/connect", "/cloud/connect/hetzner", "/deploy-to", "/forges", "/settings/economics", "/settings/spend"])
229 expect(main(await pageFor(admin, path)), path).toContain('href="/infra"');
230 expect(await pageFor(member, "/settings")).not.toContain('href="/infra"');
231 });
232
233 test("the terminal's home names the way to their games for a player with no repository, and the keys open it; nobody else", async () => {
234 const picture = (await lanePicture(app.db, { dataDir: dir, ceilingUsd: null }, "lane"))!;
235 const says = (user: User) => asksLines(app.db, user, picture).join("\n").includes("Your games: g p");
236 expect([says(player), says(member), says(admin)]).toEqual([true, false, false]);
237 const terminal = headlessTerminal(160, 50);
238 const { app: tui } = createForgeApp(app, { sshUsername: "carol", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: player }, { terminal, exitHooks: false });
239 tui.start();
240 await settleApp(tui);
241 expect(tui.screen.toText()).toContain("Your games: g p");
242 terminal.feed("g");
243 await settleApp(tui);
244 terminal.feed("p");
245 await settleApp(tui);
246 // The Games screen's own key: the home has no such line.
247 expect(tui.screen.toText()).toContain("console, env, mods");
248 tui.stop();
249 });
250
251 test("the home links a player with no repository to their games, and nobody else", async () => {
252 const line = async (user: User) => (await pageFor(user, "/live/lane?s=asked")).includes("data-your-games");
253 // Its first read, awaited: the page after it is drawn from it.
254 await lanePicture(app.db, { dataDir: dir, ceilingUsd: null }, "lane");
255 expect(await pageFor(player, "/")).toMatch(/Nothing needs you\. <a href="\/games" data-your-games>Your games<\/a>/);
256 expect(await line(player)).toBe(true);
257 expect(await line(member)).toBe(false);
258 expect(await line(admin)).toBe(false);
259 const made = await createRepo(app.db, app.reposRoot, { ownerId: player.id, name: "mine", visibility: "private" });
260 expect(made.ok).toBe(true);
261 expect(await line(player)).toBe(false);
262 expect(named(await pageFor(player))).toEqual(["Apps", "Games", "Explore"]);
263 });
test/features.test.ts +5
@@ -540,6 +540,11 @@ describe("absorbing an app", () => {
540540 const src = readFileSync(new URL("../src/web/layout.ts", import.meta.url), "utf8");
541541 const labels = [...src.matchAll(/\blabel: "([^"]+)"/g)].map((m) => m[1]!);
542542 expect(labels.length).toBeGreaterThan(15);
543 // The areas in the top bar are named in `GO_PAGES`.
544 const { GO_PAGES } = await import("../src/web/go_pages.ts");
545 const areas = GO_PAGES.filter((p) => p.area === true).map((p) => p.name);
546 expect(areas).toContain("Games");
547 labels.push(...areas);
543548 for (const l of labels) expect({ l, refused: !parseFeature({ feature: { name: l } }).ok }).toEqual({ l, refused: true });
544549 });
545550
test/infra-page.test.ts +44 −1
@@ -22,7 +22,7 @@ import { READ_ONLY, setWriteAllowed } from "../src/core/cloud_account.ts";
2222 import { getPinned, listPinned, setRemote } from "../src/core/pinned.ts";
2323 import { listEvents } from "../src/core/events.ts";
2424 import { markStep, startWatchRow } from "../src/core/pinned_watch.ts";
25 import { createRepo } from "../src/core/repos.ts";
25 import { createRepo, getRepo } from "../src/core/repos.ts";
2626 import { createSession } from "../src/core/sessions.ts";
2727 import { createUser, type User } from "../src/core/users.ts";
2828 import type { Ctx } from "../src/http/context.ts";
@@ -31,6 +31,7 @@ import { tool } from "../src/http/mcp/tools/infra.ts";
3131 import { serve, type Servers } from "../src/http/server.ts";
3232 import { setBaseDomain } from "../src/settings/pinned_domain.ts";
3333 import { createForgeApp } from "../src/tui/forge.ts";
34 import { deploysScreen } from "../src/tui/screens/deploys.ts";
3435 import { infraScreen } from "../src/tui/screens/infra.ts";
3536 import { headlessTerminal } from "../src/tui/term/terminal.ts";
3637 import { quietLogs } from "./helpers/globals.ts";
@@ -196,6 +197,17 @@ describe("infrastructure", () => {
196197 expect(text).not.toContain("<html");
197198 });
198199
200 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 () => {
201 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>');
203 const form = (page: string) => page.slice(page.indexOf('id="compose"'));
204 const named = form(await (await get("/infra/build?app=ada%2Fshop")).text());
205 expect(named).toMatch(/<option value="ada\/shop"\s+selected/);
206 expect(named).toMatch(/name="why"\s+value="app"[^>]*checked/);
207 expect(named).toMatch(/name="days"\s+value="none"[^>]*checked/);
208 expect(form(await (await get("/infra/build?app=no%2Fsuch")).text())).toMatch(/name="why"\s+value="question"[^>]*checked/);
209 });
210
199211 test("Build refuses a plan that changed since it was shown, and builds the one that was", async () => {
200212 const stale = await post("/infra/apply", { ...compose(), plan: "plan-0000000000000000" });
201213 expect(stale.status).toBe(409);
@@ -315,6 +327,37 @@ describe("infrastructure", () => {
315327 tui.stop?.();
316328 });
317329
330 test("the terminal's app screen opens the same compose on that app: where is asked, then the plan; a private app says why", async () => {
331 const on = async (name: string, who: User, keys: string[]): Promise<string[]> => {
332 const terminal = headlessTerminal(200, 60);
333 const { app: tui, session } = createForgeApp(app, { sshUsername: who.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: who }, { terminal, exitHooks: false });
334 tui.start();
335 await settleApp(tui);
336 tui.push(deploysScreen(session, tui.ctx, getRepo(app.db, "ada", name)!));
337 await settleApp(tui);
338 const frames = [tui.screen.toText()];
339 for (const k of keys) {
340 terminal.feed(k);
341 await settleApp(tui);
342 frames.push(tui.screen.toText());
343 }
344 tui.stop();
345 return frames;
346 };
347 const before = listPinned(app.db).length;
348 const [, where, plan] = await on("shop", admin, ["M", "\r"]);
349 expect(where).toContain("Where ada/shop runs");
350 expect(plan).toMatch(/\+ 1 machine/);
351 expect(listPinned(app.db).length).toBe(before);
352 const [, barred] = await on("ledger", admin, ["M"]);
353 expect(barred).toContain("ada/ledger cannot run on a machine: private: a machine reads its code without a credential.");
354 // Offered to a forge admin alone.
355 const guest = await createUser(app.db, { origin: "seed", trusted: true, username: "gus", email: "[email protected]", password: "a-good-passphrase" });
356 if (!guest.ok) throw new Error(guest.error);
357 const [, still] = await on("shop", guest.value, ["M"]);
358 expect(still).not.toContain("Where ada/shop runs");
359 });
360
318361 /** An admin's MCP call, as the door builds its context. */
319362 const mcpCtx = (): Ctx => {
320363 const url = new URL("http://forge.test/mcp");
test/keys-palette.test.ts +3 −2
@@ -3,6 +3,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
33 import { readFileSync } from "node:fs";
44 import { snappyFixture, type SnappyFixture } from "../bench/snappy.ts";
55 import { GO_MATCH_JS, GO_PAGES, goLevel, goPagesData, goPagesFor, goPaletteRows } from "../src/web/go_pages.ts";
6 import { wordsHit } from "../src/web/palette.ts";
67
78 let f: SnappyFixture;
89 beforeAll(async () => {
@@ -12,9 +13,9 @@ afterAll(async () => {
1213 await f.close();
1314 });
1415
15 type Row = [string, string, number, string];
16 type Row = [string, string, number, string, string?];
1617 // The very source the browser receives, run here as a function.
17 const goMatch = new Function(`${GO_MATCH_JS}; return goMatch;`)() as (pages: Row[], q: string) => Row[];
18 const goMatch = new Function(`${wordsHit.toString()}; ${GO_MATCH_JS}; return goMatch;`)() as (pages: Row[], q: string) => Row[];
1819 const all = goPagesData();
1920 const hit = (q: string) => goMatch(all, q).map((p) => p[0]);
2021 const names = (v: { signedIn: boolean; admin: boolean }) => goPagesFor(v).map((p) => p.name);
test/machine-shell-page.test.ts +1 −1
@@ -171,7 +171,7 @@ test("Settings › Machines is headed sections of rows, never a card (#9788)", a
171171 const body = await (await get("/alice/lab/settings/machines", "alice")).text();
172172 const main = body.slice(body.indexOf("<main"), body.indexOf("</main>"));
173173 expect(main).toContain('<section class="settings-block">');
174 expect(main).toContain("<h2>Machines</h2>");
174 expect(main).toContain("<h2>The crew's machines</h2>");
175175 expect(main).toContain("<h2>Last sessions</h2>");
176176 const machines = main.slice(main.indexOf('id="machines"'));
177177 expect(machines.slice(0, machines.indexOf("</ul>"))).toContain('class="row-title"');
test/palette.test.ts +34
@@ -447,4 +447,38 @@ describe("a search that matches nothing (#17647)", () => {
447447 key("Enter");
448448 expect(tells().length).toBe(1);
449449 });
450
451 test("a match only the server knows: Enter sends nothing before its answer, and the answer's first row is selected", async () => {
452 const { Window } = await import("happy-dom");
453 const win = new Window({ url: "http://forge.test/search" });
454 const index = JSON.stringify({ items: [{ t: "Page a", h: "/a" }], tell: { app: "demo" } });
455 win.document.body.innerHTML = `<script type="application/json" id="palette-index">${index}</script>
456 <dialog class="dialog palette" id="palette"><input class="input palette-input" type="text" /><div class="palette-list" id="palette-list"></div></dialog>`;
457 (win.HTMLElement.prototype as any).scrollIntoView ??= () => {};
458 const sent: string[] = [];
459 const asked = Promise.withResolvers<void>();
460 const answer = Promise.withResolvers<unknown>();
461 new Function("document", "window", "location", "sessionStorage", "CSS", "fetch", "EventSource", shellJs)(
462 win.document, win, win.location, win.sessionStorage, { escape: (x: string) => x },
463 (url: string) => { sent.push(String(url)); asked.resolve(); return answer.promise; },
464 undefined,
465 );
466 const doc = win.document as any;
467 doc.dispatchEvent(new win.KeyboardEvent("keydown", { key: "k", ctrlKey: true, bubbles: true, cancelable: true }));
468 const input = doc.querySelector(".palette-input");
469 input.value = "lantern";
470 input.dispatchEvent(new win.Event("input", { bubbles: true }));
471 const enter = () => doc.querySelector("#palette").dispatchEvent(new win.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
472 const tells = () => sent.filter((u) => u.includes("/tell"));
473 enter(); // before the request leaves
474 expect(tells()).toEqual([]);
475 await asked.promise;
476 enter(); // while the server reads
477 expect(tells()).toEqual([]);
478 answer.resolve({ ok: true, status: 200, json: async () => ({ repos: [{ owner: "mira", name: "lantern", full_name: "mira/lantern" }], issues: [], code: [], docs: [] }) });
479 for (let i = 0; i < 10; i++) await Promise.resolve();
480 const first = doc.querySelector(".palette-item");
481 expect(first.hasAttribute("data-tell")).toBe(false);
482 expect(first.getAttribute("aria-selected")).toBe("true");
483 });
450484 });

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

Keyboard shortcuts

Docs