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

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

opened this

Closed 3d 10h ago

revert-17778 → main 1 commit

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +15 −73
docs/features/games.md +1 −1
@@ -178,4 +178,4 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p
178178
179179 `/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.
180180
181 **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.
181 **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/hold.ts +1 −7
@@ -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 { boxById, mayDo, roleOn, type GameBox } from "./store.ts";
13 import { mayDo, roleOn, type GameBox } from "./store.ts";
1414
1515 /** Said after "Held: ". */
1616 export interface Held {
@@ -51,9 +51,3 @@ 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 +6 −7
@@ -7,20 +7,19 @@
77
88 import type { Database } from "bun:sqlite";
99 import type { User } from "../core/users.ts";
10 import { heldRefusal, startsNothing } from "./hold.ts";
11 import { queueCommand, type GameBox } from "./store.ts";
10 import { heldLines, heldOn, startsNothing } from "./hold.ts";
11 import { boxById, 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";
1817 /** Whether the box would refuse it now, as it last said. */
19 export const refusesNow = (box: GameBox, kind: Power): boolean => starts(kind) && startsNothing(box, Date.now());
18 export const refusesNow = (box: GameBox, kind: Power, now = Date.now()): boolean => kind !== "stop" && kind !== "pull" && startsNothing(box, now);
2019
21 /** Ask the box for it, or say why it was not asked. */
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. */
2221 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 } {
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 };
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(" ")}` };
2524 return { ok: true, id: queueCommand(db, box.id, service, kind, "", by?.id ?? "") };
2625 }
src/games/worlds.ts +1 −5
@@ -9,7 +9,6 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import type { User } from "../core/users.ts";
12 import { heldRefusal } from "./hold.ts";
1312 import { linkShown, type Snapshot } from "./snapshots.ts";
1413 import { mayDo, queueCommand, roleOn, type GameBox } from "./store.ts";
1514
@@ -33,13 +32,10 @@ export function worldLinkRefusal(url: string): string | undefined {
3332 /**
3433 * Queue a world command for `service` on `box`, after checking it: the command's id, or why not.
3534 * Only an operator of the service may (each door asks here, so none can skip it); a restore names
36 * a snapshot the box has said it keeps. A held box is asked for none.
35 * a snapshot the box has said it keeps.
3736 */
3837 export function queueWorld(db: Database, box: GameBox, service: string, op: WorldOp, user: User | undefined): { ok: true; id: string } | { ok: false; error: string } {
3938 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 };
4339 const by = user!.id;
4440 if (op.op === "import") {
4541 const refused = worldLinkRefusal(op.url.trim());
src/tui/screens/games.ts +1 −6
@@ -329,9 +329,6 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
329329 note = words;
330330 ctx.invalidate();
331331 };
332 /** The screen's width as last drawn: why a box is held is read whole. */
333 let room = 80;
334 const held = (): string[] => heldLines(heldOn(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box)).flatMap((l) => wrap(l, room));
335332 const lines = (): string[] => {
336333 if (part === "console")
337334 // What still waits; an answer stands in the log, under the line it came after.
@@ -340,7 +337,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
340337 const { online, lists } = peopleOf(f.app.db, box.id, service);
341338 const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`;
342339 return [
343 ...held(),
340 ...heldLines(heldOn(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box)),
344341 nowWords(servicesOf(f.app.db, box.id).find((x) => x.name === service), powerNow(f.app.db, box.id, service)),
345342 figuresOf(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box, service),
346343 ...findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]),
@@ -359,7 +356,6 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
359356 const running = job?.running === true && job.label?.startsWith("world ") === true && job.label.endsWith(` ${service}`);
360357 const snaps = now.snapshots[service] ?? [];
361358 return [
362 ...held(),
363359 ...(running ? [`Working: ${job!.label}`, ...(now.diag.upLog ?? "").split("\n").filter(Boolean)] : []),
364360 ...(snaps.length === 0
365361 ? ["No snapshot yet: one is taken before every import or restore."]
@@ -415,7 +411,6 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
415411 const [head, body] = split(area, "v", [len(1), fill(1)]);
416412 const tabs = PARTS.map((p) => (p === part ? `[${p}]` : p)).join(" ");
417413 s.text(head!.x, head!.y, truncate(note === "" ? tabs : `${tabs} · ${note}`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
418 room = Math.max(10, body!.w);
419414 const all = lines();
420415 // The log, with the commands that still wait under it.
421416 const foot = part === "console" ? Math.min(all.length, body!.h >> 1) : body!.h;
src/web/pages/games.ts +4 −7
@@ -20,7 +20,7 @@ import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts";
2020 import { spareRow } from "../../games/spare_row.ts";
2121 import { healWords } from "../../games/heal.ts";
2222 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
23 import { HELD_DOC, heldOn, startsNothing } from "../../games/hold.ts";
23 import { HELD_DOC, heldOn } from "../../games/hold.ts";
2424 import { askPower, isPower, refusesNow, type Power } from "../../games/power.ts";
2525 import { docHref } from "./docs_link.ts";
2626 import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts";
@@ -945,11 +945,8 @@ function worldBlock(box: GameBox, service: string, act: boolean, commands: reado
945945 const running = job?.running === true && job.label?.startsWith("world ") === true && job.label.endsWith(` ${service}`);
946946 const snaps = box.snapshots[service] ?? [];
947947 const base = `/games/${box.name}/${service}/world`;
948 // Each starts the server when it ends, so a held box would refuse it.
949 const held = startsNothing(box, Date.now());
950 const say = (label: string): Html => btn(held ? `${label}: held` : label, { variant: "secondary", disabled: held });
951948 const restore = (name: string, label: string): Html =>
952 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>`;
949 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>`;
953950 const undo = commands.filter((c) => c.kind === "world" && c.done && c.ok).map((c) => undoOf(box, service, c.id)).find((s) => s !== undefined);
954951 return html`<section class="settings-block">
955952 <h2>World</h2>
@@ -959,7 +956,7 @@ function worldBlock(box: GameBox, service: string, act: boolean, commands: reado
959956 ? html`<form method="post" action="${base}" class="row-fields">
960957 <input type="hidden" name="op" value="import" />
961958 ${input({ name: "url", label: "Import a world from a link (.zip or .tar.gz with its level.dat)", required: true, mono: true })}
962 ${say("Import world")}
959 ${btn("Import world", { variant: "secondary" })}
963960 </form>`
964961 : null}
965962 ${snaps.length === 0
@@ -968,7 +965,7 @@ function worldBlock(box: GameBox, service: string, act: boolean, commands: reado
968965 ${snaps.length === 0
969966 ? null
970967 : 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") } : {}) })))}
971 ${act ? html`<form method="post" action="${base}" class="row-fields"><input type="hidden" name="op" value="snapshot" />${say("Take a snapshot")}</form>` : null}
968 ${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}
972969 </section>`;
973970 }
974971
test/game-hold.test.ts +1 −40
@@ -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, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts";
23 import { gameBoxScreen, 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,42 +258,3 @@ 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