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

A held game box says "held" where a start, restart or recreate would be refused #17759

opened this

Merged 16h 45m ago, live in production

sold/held-buttons → main 0 commits

  • Merged. sold/held-buttons was merged into main as 4629119.

Review

Sign in to review this change.
8 files changed +129 −30
docs/features/games.md +1 −1
@@ -172,4 +172,4 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p
172172
173173 `/games/<box>` opens on **How to join** (the box's machine name with Copy, and who is on, server by server), then one row a server: its name, its state in words, players, TPS, then memory, CPU and how long it has been up in the cloud tree's words (`containersIn` in `src/cloud/containers.ts`: "not known" for what the box did not say or once it is silent, nothing for a server that is not running) and the 24 h sparklines, and a quiet button (Start while it is not running, else Restart); Stop, Restart and Remove are behind **More**. A server's page leads with its state, the same memory, CPU and uptime line under it, which says so when the server is not running (the terminal's people part too), its main button (the page's one accent), who is on and **Why someone could not join** (each cause with who, how often and "Tell them": what to say). Console, Numbers, Sleep, World, Environment, Settings and Mods follow, each folded and one tap away; nothing was removed (the numbers stayed in the row). A start, stop or restart that was asked shows on the server ("Starting: asked 10 s ago", then "Started" or why not) until the server answers, and the page updates itself. The player form has no default: choose what to do, in the plain word with the game's own beside it in the choice only (Let in (whitelist), Make operator (op), Ban, Lift a ban (pardon)); headings and notes use the plain word. The terminal says the same: the state line, the address, the "Tell them" fixes and the plain words (`src/games/gist.ts`). No address shows when the box has no machine name.
174174
175 **Held** (`src/games/hold.ts`): a box whose agent starts nothing until a person has looked at its volume (docs/features/game-box.md) says so first, on `/games/<box>`, on each of its servers' pages, at the top of the terminal's Games and box screens, on its machine in the cloud tree and as `held` in the `games` tool. Its owner reads why, when the agent last looked and the next step; anyone else only that its owner has to look. The agent sends a code (`diag.hold`), never a sentence, and one the forge does not know is said as held without a reason. Held is not stopped: containers that already run are left alone. An older agent sends nothing, and nothing is said.
175 **Held** (`src/games/hold.ts`): a box whose agent starts nothing until a person has looked at its volume (docs/features/game-box.md) says so first, on `/games/<box>`, on each of its servers' pages, at the top of the terminal's Games and box screens, on its machine in the cloud tree and as `held` in the `games` tool. Its owner reads why, when the agent last looked and the next step; anyone else only that its owner has to look. The agent sends a code (`diag.hold`), never a sentence, and one the forge does not know is said as held without a reason. Held is not stopped: containers that already run are left alone. Start, Restart and Recreate say "held" and are refused at every door (`src/games/power.ts`), also when an old page or screen asks; Stop and Pull go through, as at the agent. A box that has gone silent is asked, and its agent answers. An older agent sends nothing, and nothing is said.
src/games/gist.ts +1 −3
@@ -9,11 +9,9 @@ import type { Database } from "bun:sqlite";
99 import { isIP } from "node:net";
1010 import { isPublicAddress } from "../apps/egress.ts";
1111 import { peopleOf } from "./people.ts";
12 import type { Power } from "./power.ts";
1213 import { commandOf, type GameService } from "./store.ts";
1314
14 const POWER = ["start", "stop", "restart", "recreate", "pull"] as const;
15 type Power = (typeof POWER)[number];
16
1715 const DOING: Record<Power, string> = { start: "Starting", stop: "Stopping", restart: "Restarting", recreate: "Rebuilding", pull: "Updating" };
1816 const DID: Record<Power, string> = { start: "Started", stop: "Stopped", restart: "Restarted", recreate: "Rebuilt", pull: "Updated" };
1917
src/games/hold.ts +5 −1
@@ -33,12 +33,16 @@ export const HELD_DOC = "features/game-box.md";
3333
3434 /** A box syncs every few seconds; past this it may have been let go since. */
3535 const SILENT_MS = 2 * 60_000;
36 const silent = (box: GameBox, now: number): boolean => now - Date.parse(box.seenAt) > SILENT_MS;
37
38 /** Held, as it said a moment ago. A silent box may have been let go since, so its agent answers for itself. */
39 export const startsNothing = (box: GameBox, now: number): boolean => holdOf(box.diag) !== undefined && !silent(box, now);
3640
3741 /** What a held box says to `viewer`; undefined when it is not held, or its agent is too old to say. */
3842 export function heldOn(db: Database, viewer: User | undefined, box: GameBox, now = Date.now()): Held | undefined {
3943 const hold = holdOf(box.diag);
4044 if (hold === undefined) return undefined;
41 const heard = now - Date.parse(box.seenAt) > SILENT_MS ? ` The box was last heard from ${agoWords(box.seenAt, now)}, so whether it is still held is not known.` : "";
45 const heard = silent(box, now) ? ` The box was last heard from ${agoWords(box.seenAt, now)}, so whether it is still held is not known.` : "";
4246 if (!mayDo(roleOn(db, viewer, box.id), "owner")) return { says: `nothing is started until its owner has looked.${heard}`, next: "" };
4347 const [why, next] = CASES[hold.why]!;
4448 const looked = hold.since === "" ? "" : ` The agent last looked ${agoWords(hold.since, now)}.`;
src/games/power.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * Start, stop, restart, recreate and pull, for the page, the terminal and the games tool alike: one
3 * question to the box, and one refusal. A held box starts nothing (`hold.ts`), so its agent would
4 * answer a start, a restart or a recreate with a refusal each time; it is refused here instead, with the reason. Stop
5 * and pull go through, as they do at the agent. Whether a person may ask is the door's own check.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import type { User } from "../core/users.ts";
10 import { heldLines, heldOn, startsNothing } from "./hold.ts";
11 import { boxById, queueCommand, type GameBox } from "./store.ts";
12
13 export const POWER = ["start", "stop", "restart", "recreate", "pull"] as const;
14 export type Power = (typeof POWER)[number];
15 export const isPower = (kind: string): kind is Power => (POWER as readonly string[]).includes(kind);
16
17 /** Whether the box would refuse it now, as it last said. */
18 export const refusesNow = (box: GameBox, kind: Power, now = Date.now()): boolean => kind !== "stop" && kind !== "pull" && startsNothing(box, now);
19
20 /** Ask the box for it, or say why it was not asked. The box is read again: a screen's copy may be old. */
21 export function askPower(db: Database, by: User | undefined, box: GameBox, service: string, kind: Power): { readonly ok: true; readonly id: string } | { readonly ok: false; readonly error: string } {
22 const current = boxById(db, box.id) ?? box;
23 if (refusesNow(current, kind)) return { ok: false, error: `${kind[0]!.toUpperCase()}${kind.slice(1)} ${service} was not asked. ${heldLines(heldOn(db, by, current)).join(" ")}` };
24 return { ok: true, id: queueCommand(db, box.id, service, kind, "", by?.id ?? "") };
25 }
src/http/mcp/tools/games.ts +6 −6

Diff not shown — a line 2,512 characters wide (limit 2,000). +6 −6

View file
src/tui/screens/games.ts +8 −7
@@ -30,6 +30,7 @@ import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts";
3030 import { spareRow } from "../../games/spare_row.ts";
3131 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
3232 import { heldLines, heldOn } from "../../games/hold.ts";
33 import { askPower, type Power } from "../../games/power.ts";
3334 import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts";
3435 import { getUserByName } from "../../core/users.ts";
3536 import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts";
@@ -52,7 +53,6 @@ import {
5253 seesAnyBox,
5354 seesBox,
5455 servicesOf,
55 type CommandKind,
5656 type GameBox,
5757 type Role,
5858 } from "../../games/store.ts";
@@ -162,8 +162,8 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
162162 const lines = (b: GameBox) => (mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag));
163163 const told = listBoxes(f.app.db).find((b) => seesBox(f.app.db, f.user, b.id) && lines(b).length > 0);
164164 // A held box comes before both: it starts nothing until a person has looked.
165 const held = note !== "" ? [] : listBoxes(f.app.db).filter((b) => seesBox(f.app.db, f.user, b.id)).flatMap((b) => heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => wrap(`${b.name}: ${l}`, area.w))).slice(0, 8);
166 const [head, list] = split(area, "v", [len(Math.max(1, held.length)), fill(1)]);
165 const held = listBoxes(f.app.db).filter((b) => seesBox(f.app.db, f.user, b.id)).flatMap((b) => heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => wrap(`${b.name}: ${l}`, area.w))).slice(0, 8);
166 const [head, list] = split(area, "v", [len(Math.max(1, held.length + (note === "" ? 0 : 1))), fill(1)]);
167167 const said =
168168 note !== ""
169169 ? note
@@ -177,7 +177,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
177177 ? emptyText("gameServices")
178178 : joinLine();
179179 held.forEach((l, i) => s.text(head!.x, head!.y + i, truncate(l, head!.w), style(c.danger, c.bg), head!.x + head!.w));
180 if (held.length === 0) s.text(head!.x, head!.y, truncate(said, head!.w), style(booting !== undefined && note === "" && bootTroubled(booting) ? c.danger : c.mutedFg, c.bg), head!.x + head!.w);
180 if (held.length === 0 || note !== "") s.text(head!.x, head!.y + held.length, truncate(said, head!.w), style(booting !== undefined && note === "" && bootTroubled(booting) ? c.danger : c.mutedFg, c.bg), head!.x + head!.w);
181181 const brief = new Map([...new Map(all.map(({ box }) => [box.id, box])).values()].flatMap((b) => containersIn(f.app.db, f.user, b).map((c) => [`${b.id}/${c.name}`, c.brief] as const)));
182182 const view: ListRow[] = all.map(({ box, service }) => ({
183183 title: `${box.name}/${service.name}`,
@@ -270,12 +270,13 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
270270 ctx.invalidate();
271271 return true;
272272 }
273 const kind: CommandKind | undefined = e.key === "s" ? "start" : e.key === "x" ? "stop" : e.key === "r" ? "restart" : undefined;
273 const kind: Power | undefined = e.key === "s" ? "start" : e.key === "x" ? "stop" : e.key === "r" ? "restart" : undefined;
274274 if (kind === undefined || at === undefined || e.ctrl || e.alt) return false;
275275 if (!mayDo(roleOn(f.app.db, f.user, at.box.id, at.service.name), "operator")) note = `You are not an operator of ${at.service.name}.`;
276276 else {
277 queueCommand(f.app.db, at.box.id, at.service.name, kind, "", f.user?.id ?? "");
278 note = `${kind} ${at.box.name}/${at.service.name}: asked. It shows on the server until the server answers.`;
277 const asked = askPower(f.app.db, f.user, at.box, at.service.name, kind);
278 // Why is above the list, on every draw.
279 note = !asked.ok ? `${kind} ${at.box.name}/${at.service.name}: not asked, ${at.box.name} is held.` : `${kind} ${at.box.name}/${at.service.name}: asked. It shows on the server until the server answers.`;
279280 }
280281 ctx.invalidate();
281282 return true;
src/web/pages/games.ts +10 −12
@@ -19,6 +19,7 @@ import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts";
1919 import { spareRow } from "../../games/spare_row.ts";
2020 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
2121 import { HELD_DOC, heldOn } from "../../games/hold.ts";
22 import { askPower, isPower, refusesNow, type Power } from "../../games/power.ts";
2223 import { docHref } from "./docs_link.ts";
2324 import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts";
2425 import {
@@ -26,7 +27,6 @@ import {
2627 commandSays,
2728 bootWords,
2829 boxNamed,
29 COMMAND_KINDS,
3030 grant,
3131 grantsOf,
3232 jarHref,
@@ -46,7 +46,6 @@ import {
4646 servicesOf,
4747 storeJar,
4848 dropJar,
49 type CommandKind,
5049 type CommandState,
5150 type GameService,
5251 type GameBox,
@@ -236,8 +235,11 @@ export async function gameLinkRemove(ctx: Ctx): Promise<Response> {
236235 return flashTo(ctx, "/settings", { message: `Unlinked ${field(form, "player")}.` });
237236 }
238237
239 const powerForm = (box: GameBox, service: string, kind: string, label: string, variant: "primary" | "ghost"): Html =>
240 html`<form method="post" action="/games/${box.name}/${service}/power">
238 /** A button that asks the box, or, where a held box would refuse it, the same button saying so and pressing nothing. */
239 const powerForm = (box: GameBox, service: string, kind: Power, label: string, variant: "primary" | "ghost"): Html =>
240 refusesNow(box, kind)
241 ? btn(`${label}: held`, { type: "button", size: "sm", variant: "ghost", disabled: true, label: `${kind} ${service}: held` })
242 : html`<form method="post" action="/games/${box.name}/${service}/power">
241243 <input type="hidden" name="kind" value="${kind}" />${btn(label, { size: "sm", variant, label: `${kind} ${service}` })}
242244 </form>`;
243245
@@ -1081,14 +1083,10 @@ export async function gameCommandSubmit(ctx: Ctx): Promise<Response> {
10811083 export async function gamePowerSubmit(ctx: Ctx): Promise<Response> {
10821084 const got = await operatorForm(ctx);
10831085 if (got instanceof Response) return got;
1084 const kind = field(got.form, "kind") as CommandKind;
1085 if (
1086 !(["start", "stop", "restart", "recreate", "pull"] as readonly string[]).includes(kind) ||
1087 !(COMMAND_KINDS as readonly string[]).includes(kind)
1088 )
1089 return notFoundPage(ctx);
1090 queueCommand(ctx.app.db, got.box.id, got.service, kind, "", ctx.auth.user!.id);
1091 return flashTo(ctx, `/games/${got.box.name}/${got.service}`, { message: `${kind[0]!.toUpperCase()}${kind.slice(1)} ${got.service}: asked. It shows on the server until the server answers.` });
1086 const kind = field(got.form, "kind");
1087 if (!isPower(kind)) return notFoundPage(ctx);
1088 const asked = askPower(ctx.app.db, ctx.auth.user, got.box, got.service, kind);
1089 return flashTo(ctx, `/games/${got.box.name}/${got.service}`, !asked.ok ? { tone: "danger", message: asked.error } : { message: `${kind[0]!.toUpperCase()}${kind.slice(1)} ${got.service}: asked. It shows on the server until the server answers.` });
10921090 }
10931091
10941092 /** The settings a form or a query asks for: its `s.<key>` fields. */
test/game-hold.test.ts +73
@@ -16,6 +16,7 @@ import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
1717 import { boxStatus, DIAG_MOST, holdOf, keptDiag, readDiag } from "../src/games/diag.ts";
1818 import { heldOn } from "../src/games/hold.ts";
19 import { POWER, type Power } from "../src/games/power.ts";
1920 import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts";
2021 import { serve, type Servers } from "../src/http/server.ts";
2122 import { cloudLines } from "../src/tui/screens/cloudtree.ts";
@@ -185,3 +186,75 @@ test("a box that sends markup or a control code as its hold is held without a re
185186 for (const path of ["/games/mc", "/games/mc/hub"]) expect(notice(await get(bob, path))).toBe("Held: nothing is started until its owner has looked.");
186187 sync(null);
187188 });
189
190 /** What the box was asked since the last look, and the queue emptied. */
191 const asked = (): string[] => {
192 const kinds = app.db.query<{ kind: string }, []>("SELECT kind FROM game_command ORDER BY created_at, rowid").all().map((r) => r.kind);
193 app.db.run("DELETE FROM game_command");
194 return kinds;
195 };
196 const press = async (kind: Power): Promise<string> => {
197 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
198 const res = await fetch(`${servers.url}/games/mc/hub/power`, { method: "POST", redirect: "manual", headers: { cookie, origin: new URL(servers.url).origin, "content-type": "application/x-www-form-urlencoded" }, body: `kind=${kind}` });
199 expect(res.status).toBe(303);
200 return decodeURIComponent(res.headers.get("set-cookie") ?? "").replace(/\+/g, " ");
201 };
202 const keys = async (typed: string): Promise<string> => {
203 const terminal = headlessTerminal(100, 40);
204 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
205 tui.start();
206 tui.ctx.push(gamesScreen(session, tui.ctx));
207 await settleApp(tui);
208 terminal.feed(typed);
209 await settleApp(tui);
210 const text = tui.screen.toText().replace(/\s+/g, " ");
211 tui.stop?.();
212 return text;
213 };
214
215 test("a held box is not asked to start, restart or recreate at any door, by an old page as well; stop and pull go through", async () => {
216 const token = createToken(app.db, alice.id, "p", "admin").token;
217 const tool = (kind: Power) => mcpTool(servers.url, token, "games", { action: "power", box: "mc", service: "hub", kind });
218 sync({ why: "other-worlds", since });
219 asked();
220 for (const kind of ["start", "restart", "recreate"] as const) {
221 expect(await press(kind)).toContain(`${kind[0]!.toUpperCase()}${kind.slice(1)} hub was not asked. Held: its volume holds data`);
222 expect(JSON.stringify(await tool(kind))).toContain("hub was not asked. Held: its volume holds data");
223 }
224 for (const key of ["s", "r"]) {
225 const text = await keys(key);
226 expect(text).toContain(`${key === "s" ? "start" : "restart"} mc/hub: not asked, mc is held.`);
227 // Why stays on the screen beside the answer.
228 expect(text).toContain("Nothing is deleted.");
229 }
230 expect(asked()).toEqual([]);
231 for (const kind of ["stop", "pull"] as const) {
232 expect(await press(kind)).toContain(`${kind[0]!.toUpperCase()}${kind.slice(1)} hub: asked.`);
233 await tool(kind);
234 }
235 expect(await keys("x")).toContain("stop mc/hub: asked.");
236 expect(asked()).toEqual(["stop", "stop", "pull", "pull", "stop"]);
237 });
238
239 test("the buttons of a held box say held and press nothing, Stop stays, and both come back when it is let go", async () => {
240 const pages = async (): Promise<string[]> => [await get(alice, "/games/mc"), await get(alice, "/games/mc/hub")];
241 sync({ why: "mount", since });
242 for (const page of await pages()) {
243 expect(page).toMatch(/<button[^>]*disabled[^>]*>\s*(?:<span[^>]*>)?Restart: held/);
244 expect(page).toContain("Start: held");
245 expect(page).toContain('name="kind" value="stop"');
246 for (const kind of ["start", "restart"]) expect(page).not.toContain(`name="kind" value="${kind}"`);
247 }
248 // Let go, and silent: the box answers for itself.
249 for (const free of [() => sync(null), () => sync({ why: "mount", since }, { at: new Date(Date.now() - 3 * 3_600_000) })]) {
250 free();
251 for (const page of await pages()) {
252 expect(page).not.toContain(": held<");
253 expect(page).toContain('name="kind" value="restart"');
254 }
255 asked();
256 for (const kind of POWER) expect(await press(kind)).toContain("asked. It shows");
257 expect(asked()).toEqual([...POWER]);
258 }
259 sync(null);
260 });

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

Keyboard shortcuts

Docs