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

A held box says "held" for a world's import, restore and snapshot too #17778

opened this

Merged 14h 45m ago, live in production

sold/held-worlds → main 0 commits 1 thread · 1 unresolved

  • Merged. sold/held-worlds was merged into main as 8d747cf.

Review

Sign in to review this change.
7 files changed +73 −15
docs/features/games.md +1 −1
@@ -176,4 +176,4 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p
176176
177177 `/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.
178178
179 **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.
179 **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 (`src/games/power.ts`), and a world's import, restore and snapshot (`src/games/worlds.ts`: each ends by starting the server), say "held" and are refused at every door, 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/hold.ts +7 −1
@@ -10,7 +10,7 @@ import type { Database } from "bun:sqlite";
1010 import type { User } from "../core/users.ts";
1111 import { agoWords } from "../kernel/ago.ts";
1212 import { holdOf } from "./diag.ts";
13 import { mayDo, roleOn, type GameBox } from "./store.ts";
13 import { boxById, mayDo, roleOn, type GameBox } from "./store.ts";
1414
1515 /** Said after "Held: ". */
1616 export interface Held {
@@ -51,3 +51,9 @@ export function heldOn(db: Database, viewer: User | undefined, box: GameBox, now
5151
5252 /** The same as lines, for a door with no link. */
5353 export const heldLines = (h: Held | undefined): string[] => (h === undefined ? [] : h.next === "" ? [`Held: ${h.says}`] : [`Held: ${h.says}`, `Next: ${h.next} ${HELD_STEPS}`]);
54
55 /** Why `what` ("Restart hub") is not asked of a held box, or undefined to ask. The box is read again: a screen's copy may be old. */
56 export function heldRefusal(db: Database, by: User | undefined, box: GameBox, what: string, now = Date.now()): string | undefined {
57 const current = boxById(db, box.id) ?? box;
58 return startsNothing(current, now) ? `${what} was not asked. ${heldLines(heldOn(db, by, current, now)).join(" ")}` : undefined;
59 }
src/games/power.ts +7 −6
@@ -7,19 +7,20 @@
77
88 import type { Database } from "bun:sqlite";
99 import type { User } from "../core/users.ts";
10 import { heldLines, heldOn, startsNothing } from "./hold.ts";
11 import { boxById, queueCommand, type GameBox } from "./store.ts";
10 import { heldRefusal, startsNothing } from "./hold.ts";
11 import { queueCommand, type GameBox } from "./store.ts";
1212
1313 export const POWER = ["start", "stop", "restart", "recreate", "pull"] as const;
1414 export type Power = (typeof POWER)[number];
1515 export const isPower = (kind: string): kind is Power => (POWER as readonly string[]).includes(kind);
1616
17 const starts = (kind: Power): boolean => kind !== "stop" && kind !== "pull";
1718 /** 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 export const refusesNow = (box: GameBox, kind: Power): boolean => starts(kind) && startsNothing(box, Date.now());
1920
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 /** Ask the box for it, or say why it was not asked. */
2122 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(" ")}` };
23 const error = starts(kind) ? heldRefusal(db, by, box, `${kind[0]!.toUpperCase()}${kind.slice(1)} ${service}`) : undefined;
24 if (error !== undefined) return { ok: false, error };
2425 return { ok: true, id: queueCommand(db, box.id, service, kind, "", by?.id ?? "") };
2526 }
src/games/worlds.ts +5 −1
@@ -9,6 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import type { User } from "../core/users.ts";
12 import { heldRefusal } from "./hold.ts";
1213 import { linkShown, type Snapshot } from "./snapshots.ts";
1314 import { mayDo, queueCommand, roleOn, type GameBox } from "./store.ts";
1415
@@ -32,10 +33,13 @@ export function worldLinkRefusal(url: string): string | undefined {
3233 /**
3334 * Queue a world command for `service` on `box`, after checking it: the command's id, or why not.
3435 * Only an operator of the service may (each door asks here, so none can skip it); a restore names
35 * a snapshot the box has said it keeps.
36 * a snapshot the box has said it keeps. A held box is asked for none.
3637 */
3738 export function queueWorld(db: Database, box: GameBox, service: string, op: WorldOp, user: User | undefined): { ok: true; id: string } | { ok: false; error: string } {
3839 if (!mayDo(roleOn(db, user, box.id, service), "operator")) return { ok: false, error: `You are not an operator of ${service}.` };
40 // Each ends by starting the server, a snapshot too, so a held box's agent refuses all three.
41 const held = heldRefusal(db, user, box, `The ${op.op} on ${service}`);
42 if (held !== undefined) return { ok: false, error: held };
3943 const by = user!.id;
4044 if (op.op === "import") {
4145 const refused = worldLinkRefusal(op.url.trim());
src/tui/screens/games.ts +6 −1
@@ -309,6 +309,9 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
309309 note = words;
310310 ctx.invalidate();
311311 };
312 /** The screen's width as last drawn: why a box is held is read whole. */
313 let room = 80;
314 const held = (): string[] => heldLines(heldOn(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box)).flatMap((l) => wrap(l, room));
312315 const lines = (): string[] => {
313316 if (part === "console") {
314317 // A world command's link shows as host and path only: its query string may be a signed secret.
@@ -321,7 +324,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
321324 const { online, lists } = peopleOf(f.app.db, box.id, service);
322325 const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`;
323326 return [
324 ...heldLines(heldOn(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box)),
327 ...held(),
325328 nowWords(servicesOf(f.app.db, box.id).find((x) => x.name === service), powerNow(f.app.db, box.id, service)),
326329 figuresOf(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box, service),
327330 ...findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]),
@@ -340,6 +343,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
340343 const running = job?.running === true && job.label?.startsWith("world ") === true && job.label.endsWith(` ${service}`);
341344 const snaps = now.snapshots[service] ?? [];
342345 return [
346 ...held(),
343347 ...(running ? [`Working: ${job!.label}`, ...(now.diag.upLog ?? "").split("\n").filter(Boolean)] : []),
344348 ...(snaps.length === 0
345349 ? ["No snapshot yet: one is taken before every import or restore."]
@@ -390,6 +394,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
390394 const [head, body] = split(area, "v", [len(1), fill(1)]);
391395 const tabs = PARTS.map((p) => (p === part ? `[${p}]` : p)).join(" ");
392396 s.text(head!.x, head!.y, truncate(note === "" ? tabs : `${tabs} · ${note}`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
397 room = Math.max(10, body!.w);
393398 const all = lines();
394399 const shown = part === "console" ? all.slice(-body!.h) : all.slice(0, body!.h);
395400 shown.forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w));
src/web/pages/games.ts +7 −4
@@ -19,7 +19,7 @@ import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts";
1919 import { spareRow } from "../../games/spare_row.ts";
2020 import { healWords } from "../../games/heal.ts";
2121 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
22 import { HELD_DOC, heldOn } from "../../games/hold.ts";
22 import { HELD_DOC, heldOn, startsNothing } from "../../games/hold.ts";
2323 import { askPower, isPower, refusesNow, type Power } from "../../games/power.ts";
2424 import { docHref } from "./docs_link.ts";
2525 import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts";
@@ -1007,8 +1007,11 @@ function worldBlock(box: GameBox, service: string, act: boolean, commands: reado
10071007 const running = job?.running === true && job.label?.startsWith("world ") === true && job.label.endsWith(` ${service}`);
10081008 const snaps = box.snapshots[service] ?? [];
10091009 const base = `/games/${box.name}/${service}/world`;
1010 // Each starts the server when it ends, so a held box would refuse it.
1011 const held = startsNothing(box, Date.now());
1012 const say = (label: string): Html => btn(held ? `${label}: held` : label, { variant: "secondary", disabled: held });

Next step, not blocking: a disabled button that says "Import world: held" tells a keyboard or screen-reader user what is wrong, but not why or what to do. Put the Held sentence (heldOn / HELD_DOC) as a muted line under the World heading, so the reason sits next to the buttons.

10101013 const restore = (name: string, label: string): Html =>
1011 html`<form method="post" action="${base}" class="row-fields"><input type="hidden" name="op" value="restore" /><input type="hidden" name="snapshot" value="${name}" />${btn(label, { variant: "secondary" })}</form>`;
1014 html`<form method="post" action="${base}" class="row-fields"><input type="hidden" name="op" value="restore" /><input type="hidden" name="snapshot" value="${name}" />${say(label)}</form>`;
10121015 const undo = commands.filter((c) => c.kind === "world" && c.done && c.ok).map((c) => undoOf(box, service, c.id)).find((s) => s !== undefined);
10131016 return html`<section class="settings-block">
10141017 <h2>World</h2>
@@ -1018,7 +1021,7 @@ function worldBlock(box: GameBox, service: string, act: boolean, commands: reado
10181021 ? html`<form method="post" action="${base}" class="row-fields">
10191022 <input type="hidden" name="op" value="import" />
10201023 ${input({ name: "url", label: "Import a world from a link (.zip or .tar.gz with its level.dat)", required: true, mono: true })}
1021 ${btn("Import world", { variant: "secondary" })}
1024 ${say("Import world")}
10221025 </form>`
10231026 : null}
10241027 ${snaps.length === 0
@@ -1027,7 +1030,7 @@ function worldBlock(box: GameBox, service: string, act: boolean, commands: reado
10271030 ${snaps.length === 0
10281031 ? null
10291032 : rowList(snaps.map((s) => row({ title: html`<span class="mono">${s.name}</span>`, meta: html`${mb(s.bytes)}${s.at === "" ? "" : html` · ${time(s.at)}`}`, ...(act ? { after: restore(s.name, "Restore") } : {}) })))}
1030 ${act ? html`<form method="post" action="${base}" class="row-fields"><input type="hidden" name="op" value="snapshot" />${btn("Take a snapshot", { variant: "secondary" })}</form>` : null}
1033 ${act ? html`<form method="post" action="${base}" class="row-fields"><input type="hidden" name="op" value="snapshot" />${say("Take a snapshot")}</form>` : null}
10311034 </section>`;
10321035 }
10331036
test/game-hold.test.ts +40 −1
@@ -20,7 +20,7 @@ import { POWER, type Power } from "../src/games/power.ts";
2020 import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts";
2121 import { serve, type Servers } from "../src/http/server.ts";
2222 import { cloudLines } from "../src/tui/screens/cloudtree.ts";
23 import { gameBoxScreen, gamesScreen } from "../src/tui/screens/games.ts";
23 import { gameBoxScreen, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts";
2424 import { createForgeApp } from "../src/tui/forge.ts";
2525 import { headlessTerminal } from "../src/tui/term/terminal.ts";
2626 import { quietLogs } from "./helpers/globals.ts";
@@ -258,3 +258,42 @@ test("the buttons of a held box say held and press nothing, Stop stays, and both
258258 }
259259 sync(null);
260260 });
261
262 test("a world's import, restore and snapshot end by starting the server, so a held box is asked for none, and the terminal shows the reason whole", async () => {
263 const token = createToken(app.db, alice.id, "w", "admin").token;
264 const snap = { name: "20261201T000000Z-by-hand", bytes: 10, at: since };
265 app.db.query("UPDATE game_box SET snapshots_json = ?1 WHERE name = 'mc'").run(JSON.stringify({ hub: [snap] }));
266 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
267 const ops = { import: "op=import&url=https%3A%2F%2Fx.example%2Fw.zip", restore: `op=restore&snapshot=${snap.name}`, snapshot: "op=snapshot" };
268 const ask = async (): Promise<string[]> => {
269 const said: string[] = [];
270 for (const [op, body] of Object.entries(ops)) {
271 const res = await fetch(`${servers.url}/games/mc/hub/world`, { method: "POST", redirect: "manual", headers: { cookie, origin: new URL(servers.url).origin, "content-type": "application/x-www-form-urlencoded" }, body });
272 said.push(decodeURIComponent(res.headers.get("set-cookie") ?? "").replace(/\+/g, " "));
273 said.push(JSON.stringify(await mcpTool(servers.url, token, "games", { action: "world", box: "mc", service: "hub", op, url: "https://x.example/w.zip", snapshot: snap.name })));
274 }
275 return said;
276 };
277 sync({ why: "other-worlds", since });
278 asked();
279 (await ask()).forEach((said, i) => expect(said).toContain(`The ${Object.keys(ops)[Math.floor(i / 2)]!} on hub was not asked. Held: its volume holds data`));
280 const page = await get(alice, "/games/mc/hub");
281 for (const label of ["Import world", "Restore", "Take a snapshot"]) expect(page).toMatch(new RegExp(`<button[^>]*disabled[^>]*>\\s*(?:<span[^>]*>)?${label}: held`));
282 const terminal = headlessTerminal(70, 40);
283 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
284 tui.start();
285 tui.ctx.push(gameServiceScreen(session, tui.ctx, boxNamed(app.db, "mc")!, "hub"));
286 await settleApp(tui);
287 // n takes a snapshot, and its answer opens the world part.
288 terminal.feed("n");
289 await settleApp(tui);
290 const text = tui.screen.toText().replace(/\s+/g, " ");
291 tui.stop?.();
292 expect(text).toContain("The snapshot on hub was not asked.");
293 expect(text).toContain("move the other side aside. Nothing is deleted. The steps are in docs/features/game-box.md, under Held.");
294 expect(asked()).toEqual([]);
295 sync(null);
296 await ask();
297 expect(asked()).toEqual(Array(6).fill("world"));
298 expect(await get(alice, "/games/mc/hub")).not.toContain("snapshot: held");
299 });

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

Keyboard shortcuts

Docs