Public: anyone can read this; the crew can change it.
Game pages: an operator on a phone finds the five things they came for #17664
Merged 17h 23m ago, live in production
scout/forge:scout/17656-game-pages-an-operator-on-a-phone-finds → main 0 commits fork
9 files
changed +356
−68
docs/features/games.md +5 −1
| @@ -29,7 +29,7 @@ The policy is the label `forge.sleep: "true"` with `restart: "no"` in the compos | ||
| 29 | 29 | - Velocity `read-timeout` at 120 s while anything sleeps (30 s again when nothing does), so the proxy holds a joining player through a boot. |
| 30 | 30 | - `forge-waker`, a Docker socket proxy and the boundary: the proxy may inspect, start and stop the sleeping servers' containers and nothing else, and it never holds the Docker socket. Its image is pinned by digest (`wollomatic/socket-proxy:1.14.0@sha256:fead157c…`), since it holds the socket as root. A sleeping server's container name must be letters, digits, `_`, `.` and `-` (anything else is refused before a commit), and each name is escaped in the allowlist, so no name can widen it. |
| 31 | 31 | |
| 32 | Warm again takes all of it away; the same labels always give the same file. Only an itzg/minecraft-server server can sleep; the proxy never does. Nothing chosen means warm. `/games/<box>` says "asleep (wakes on join)" for a sleeping server whose container has stopped. | |
| 32 | Warm again takes all of it away; the same labels always give the same file. Only an itzg/minecraft-server server can sleep; the proxy never does. Nothing chosen means warm. `/games/<box>` says "asleep, wakes on join" for a sleeping server whose container has stopped. | |
| 33 | 33 | |
| 34 | 34 | ## What the cloud says |
| 35 | 35 | |
| @@ -120,3 +120,7 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p | ||
| 120 | 120 | `/forge` typed as a command is heard like `!forge` ("Alice issued server command: /forge …" on Paper and Fabric); the server's own "Unknown command" shows to the player beside the forge's answer. |
| 121 | 121 | |
| 122 | 122 | **Quick commands.** Between full syncs the agent polls lightly every second (`FORGE_GAME_LIGHT_EVERY`): a body `{"agent":1,"light":true,"results":[…]}` that keeps only results and answers only `commands`, touching nothing else the forge knows. A command is handed out within a second of being queued, run, and its result sent at once, so a console command answers in under 3 s (measured in `test/game-findings.test.ts` against the real agent). A full sync that got no answer is sent again with `"retry":true`, and the forge skips the log lines it already holds, so the console does not show a line twice. The agent never asks `forge-waker` (sleep's proxy, with no shell) anything. |
| 123 | ||
| 124 | ## On a phone (#17656) | |
| 125 | ||
| 126 | `/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, memory, CPU, up since 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, 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. |
src/games/gist.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * What an operator on a phone comes for, in words a player knows (#17656): where a friend joins, | |
| 3 | * who is on and where, a server's state with the command still waiting on the server, its one main | |
| 4 | * button, and the names of the people changes with the game's own word beside them. The page and | |
| 5 | * the terminal both read these, so they say the same. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { peopleOf } from "./people.ts"; | |
| 10 | import type { GameService } from "./store.ts"; | |
| 11 | ||
| 12 | const POWER = ["start", "stop", "restart", "recreate", "pull"] as const; | |
| 13 | type Power = (typeof POWER)[number]; | |
| 14 | ||
| 15 | const DOING: Record<Power, string> = { start: "Starting", stop: "Stopping", restart: "Restarting", recreate: "Rebuilding", pull: "Updating" }; | |
| 16 | const DID: Record<Power, string> = { start: "Started", stop: "Stopped", restart: "Restarted", recreate: "Rebuilt", pull: "Updated" }; | |
| 17 | ||
| 18 | /** How long ago, to the second under a minute, then minutes, hours. */ | |
| 19 | function ago(iso: string, now: number): string { | |
| 20 | const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000)); | |
| 21 | if (Number.isNaN(s)) return "a while ago"; | |
| 22 | return s < 60 ? `${s} s ago` : s < 3600 ? `${Math.floor(s / 60)} min ago` : `${Math.floor(s / 3600)} h ago`; | |
| 23 | } | |
| 24 | ||
| 25 | /** | |
| 26 | * The newest start, stop or restart asked of a server: "Starting: asked 10 s ago" until the server | |
| 27 | * answers, then "Started" (or "Start failed: why") for ten minutes; nothing after. | |
| 28 | */ | |
| 29 | export function powerNow(db: Database, boxId: string, service: string, now = Date.now()): string | undefined { | |
| 30 | const r = db | |
| 31 | .query<{ kind: string; created_at: string; handed_at: string; done_at: string; ok: number | null; output: string }, [string, string]>( | |
| 32 | "SELECT kind, created_at, handed_at, done_at, ok, output FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind IN ('start', 'stop', 'restart', 'recreate', 'pull') ORDER BY created_at DESC LIMIT 1", | |
| 33 | ) | |
| 34 | .get(boxId, service); | |
| 35 | if (r === null) return undefined; | |
| 36 | const kind = r.kind as Power; | |
| 37 | if (r.done_at === "") return `${DOING[kind]}: asked ${ago(r.created_at, now)}${r.handed_at === "" ? "" : ", the server has it"}`; | |
| 38 | if (now - Date.parse(r.done_at) > 600_000) return undefined; | |
| 39 | return r.ok === 0 ? `${kind[0]!.toUpperCase()}${kind.slice(1)} failed${r.output === "" ? "" : `: ${r.output.split("\n")[0]}`}` : DID[kind]; | |
| 40 | } | |
| 41 | ||
| 42 | /** | |
| 43 | * A server's state in words, with what is asked of it: "asleep, wakes on join · Starting: asked 10 | |
| 44 | * s ago". | |
| 45 | */ | |
| 46 | export function nowWords(s: GameService | undefined, pending: string | undefined): string { | |
| 47 | const state = s?.asleep === true ? "asleep, wakes on join" : s === undefined || s.state === "" ? "not reported yet" : s.state; | |
| 48 | return pending === undefined ? state : `${state} · ${pending}`; | |
| 49 | } | |
| 50 | ||
| 51 | /** The one button a server leads with: Start while it is not running, else Restart. */ | |
| 52 | export const mainPower = (s: GameService | undefined): "start" | "restart" => (s?.state === "running" && s.asleep !== true ? "restart" : "start"); | |
| 53 | ||
| 54 | /** | |
| 55 | * Where a friend joins: the box's machine name (the game's own port, 25565, is the default), or | |
| 56 | * none yet. | |
| 57 | */ | |
| 58 | export const joinAddress = (host: string | undefined): string | undefined => (host !== undefined && /^[a-z0-9][a-z0-9.-]{0,252}$/i.test(host) ? host : undefined); | |
| 59 | ||
| 60 | /** Who is on, server by server. Servers nobody is on are left out. */ | |
| 61 | export function whoIsOn(db: Database, boxId: string, services: readonly string[]): { service: string; names: string[] }[] { | |
| 62 | return services.map((service) => ({ service, names: peopleOf(db, boxId, service).online.map((p) => p.name) })).filter((x) => x.names.length > 0); | |
| 63 | } | |
| 64 | ||
| 65 | /** | |
| 66 | * The player form's choices: the value, the plain word, the game's own word. No default is chosen. | |
| 67 | */ | |
| 68 | export const PEOPLE_CHOICES = [ | |
| 69 | ["whitelist-add", "Let in", "whitelist"], | |
| 70 | ["op", "Make operator", "op"], | |
| 71 | ["ban", "Ban", "ban"], | |
| 72 | ["pardon", "Lift a ban", "pardon"], | |
| 73 | ] as const; | |
| 74 | ||
| 75 | /** Button words for one player: the plain word first. */ | |
| 76 | export const PEOPLE_BUTTON: Record<string, string> = { | |
| 77 | op: "Make operator", | |
| 78 | deop: "Remove operator", | |
| 79 | "whitelist-add": "Let in", | |
| 80 | "whitelist-remove": "Remove from the list", | |
| 81 | kick: "Kick", | |
| 82 | ban: "Ban", | |
| 83 | pardon: "Lift the ban", | |
| 84 | }; |
src/games/sleep.ts −3
| @@ -263,6 +263,3 @@ export function commitPolicy( | ||
| 263 | 263 | edit: (text) => setPolicy(text, service, policy), |
| 264 | 264 | }); |
| 265 | 265 | } |
| 266 | ||
| 267 | /** A service's state in words: "asleep (wakes on join)" while its sleep has stopped it, else its own state. */ | |
| 268 | export const stateWords = (state: string, asleep: boolean): string => (asleep ? "asleep (wakes on join)" : state || "unknown"); |
src/tui/screens/games.ts +15 −7
| @@ -14,9 +14,10 @@ | ||
| 14 | 14 | import { movedKey } from "./moved_key.ts"; |
| 15 | 15 | import { emptyText } from "../../core/empty_words.ts"; |
| 16 | 16 | import { consoleText, crashOf } from "../../games/console.ts"; |
| 17 | import { commitPolicy, policyOf, STILL_BILLED, stateWords } from "../../games/sleep.ts"; | |
| 17 | import { commitPolicy, policyOf, STILL_BILLED } from "../../games/sleep.ts"; | |
| 18 | 18 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 19 | 19 | import { onSync } from "../../games/notify.ts"; |
| 20 | import { joinAddress, nowWords, powerNow } from "../../games/gist.ts"; | |
| 20 | 21 | import { findingLine, findingsOf as kickFindingsOf } from "../../games/findings.ts"; |
| 21 | 22 | import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts"; |
| 22 | 23 | import { findingsOf } from "../../games/player_events.ts"; |
| @@ -78,6 +79,12 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 78 | 79 | const line = row === undefined ? undefined : cloudLine(f.app, row); |
| 79 | 80 | return line === undefined ? [] : [{ title: `${b.name}'s machine`, secondary: line, meta: "" }]; |
| 80 | 81 | }); |
| 82 | /** How to join, as the page says it: the address of the first box's machine. */ | |
| 83 | const joinLine = (): string => { | |
| 84 | const box = listBoxes(f.app.db).find((b) => seesBox(f.app.db, f.user, b.id)); | |
| 85 | const address = box === undefined ? undefined : joinAddress(pinnedOfBox(f.app, box)?.host); | |
| 86 | return address === undefined ? "Each service of each game box you may see. There is no address to join yet: no machine name." : `To join, add this server in Minecraft: ${address}`; | |
| 87 | }; | |
| 81 | 88 | const rows = () => |
| 82 | 89 | listBoxes(f.app.db) |
| 83 | 90 | .filter((b) => seesBox(f.app.db, f.user, b.id)) |
| @@ -140,12 +147,12 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 140 | 147 | ? `${told.name}: ${lines(told)[0]}` |
| 141 | 148 | : all.length === 0 |
| 142 | 149 | ? emptyText("gameServices") |
| 143 | : "Each service of each game box you may see."; | |
| 150 | : joinLine(); | |
| 144 | 151 | 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); |
| 145 | 152 | const view: ListRow[] = all.map(({ box, service }) => ({ |
| 146 | 153 | title: `${box.name}/${service.name}`, |
| 147 | 154 | ...(service.state === "exited" ? { tone: "danger" as const } : {}), |
| 148 | secondary: `${stateWords(service.state, service.asleep)} · ${playersTps(f, box, service.name)}${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`, | |
| 155 | secondary: `${nowWords(service, powerNow(f.app.db, box.id, service.name))} · ${playersTps(f, box, service.name)}${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`, | |
| 149 | 156 | meta: box.seenAt.slice(11, 19), |
| 150 | 157 | })); |
| 151 | 158 | // The machines after the services: the cursor moves over the services only. |
| @@ -232,7 +239,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 232 | 239 | 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}.`; |
| 233 | 240 | else { |
| 234 | 241 | queueCommand(f.app.db, at.box.id, at.service.name, kind, "", f.user?.id ?? ""); |
| 235 | note = `${kind} ${at.box.name}/${at.service.name}: asked; the box does it on its next sync.`; | |
| 242 | note = `${kind} ${at.box.name}/${at.service.name}: asked. It shows on the server until the server answers.`; | |
| 236 | 243 | } |
| 237 | 244 | ctx.invalidate(); |
| 238 | 245 | return true; |
| @@ -276,13 +283,14 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 276 | 283 | const { online, lists } = peopleOf(f.app.db, box.id, service); |
| 277 | 284 | const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`; |
| 278 | 285 | return [ |
| 286 | nowWords(servicesOf(f.app.db, box.id).find((x) => x.name === service), powerNow(f.app.db, box.id, service)), | |
| 279 | 287 | ...findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]), |
| 280 | 288 | online.length === 0 ? `Nobody is on ${service} right now.` : `Online: ${online.map((p) => tag(p.name)).join(", ")}`, |
| 281 | `Whitelist ${lists.whitelistOn ? "on" : "off"} · ${lists.whitelist.length} listed · ${lists.ops.length} ops · ${lists.bans.length} banned`, | |
| 289 | `${lists.whitelistOn ? "Only listed players may join" : "Anyone may join"} · ${lists.whitelist.length} listed · ${lists.ops.length} operators · ${lists.bans.length} banned`, | |
| 282 | 290 | ...lists.bans.map((b) => `banned: ${b.name}${b.reason === "" ? "" : ` (${b.reason})`}`), |
| 283 | 291 | ...kickFindingsOf(f.app.db, box.id, service).map(findingLine), |
| 284 | 292 | ...eventsOf(f.app.db, box.id, service, 20).map((e) => `${e.at.slice(11, 16)} ${eventWords(e, service)}`), |
| 285 | "p: op, deop, whitelist-add, whitelist-remove, ban, pardon, kick <player>, or move <player> <server>", | |
| 293 | "p: op (make operator), deop, whitelist-add (let in), whitelist-remove, ban, pardon (lift a ban), kick <player>, or move <player> <server>", | |
| 286 | 294 | ]; |
| 287 | 295 | } |
| 288 | 296 | if (part === "world") { |
| @@ -377,7 +385,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 377 | 385 | const [op = "", player = "", to = ""] = raw.trim().split(/\s+/); |
| 378 | 386 | const queued = await queuePeople(f.app, box, service, op, player, f.user, to); |
| 379 | 387 | part = "people"; |
| 380 | return queued.ok ? `Asked: ${peopleWords(JSON.stringify({ op, player, server: to }))}; the box does it on its next sync.` : queued.error; | |
| 388 | return queued.ok ? `Asked: ${peopleWords(JSON.stringify({ op, player, server: to }))}; it shows on the server until the server answers.` : queued.error; | |
| 381 | 389 | }); |
| 382 | 390 | else if (e.key === "m") ctx.push(gameModsScreen(f, ctx, box, service)); |
| 383 | 391 | else if (e.key === "i" || e.key === "u" || e.key === "n") { |
src/web/pages/games.ts +100 −52
| @@ -42,6 +42,7 @@ import { | ||
| 42 | 42 | dropJar, |
| 43 | 43 | type CommandKind, |
| 44 | 44 | type CommandState, |
| 45 | type GameService, | |
| 45 | 46 | type GameBox, |
| 46 | 47 | type Role, |
| 47 | 48 | } from "../../games/store.ts"; |
| @@ -59,7 +60,7 @@ import { avatar, badge, btn, disclosure, field as input, row, rowList, time } fr | ||
| 59 | 60 | import { onSync } from "../../games/notify.ts"; |
| 60 | 61 | import { accountLinks, chatLog, newLinkCode, playersOn, unlink } from "../../games/chat.ts"; |
| 61 | 62 | import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts"; |
| 62 | import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, STILL_BILLED, stateWords } from "../../games/sleep.ts"; | |
| 63 | import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, STILL_BILLED } from "../../games/sleep.ts"; | |
| 63 | 64 | import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 64 | 65 | import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts"; |
| 65 | 66 | import { defaultHeadResponse, headResponse } from "../../games/heads.ts"; |
| @@ -68,6 +69,7 @@ import { queueWorld, undoOf, worldWords } from "../../games/worlds.ts"; | ||
| 68 | 69 | import { emptyLine, emptyNote } from "../empty_words.ts"; |
| 69 | 70 | import { findingsOf, type GameFinding } from "../../games/player_events.ts"; |
| 70 | 71 | import { findingsOf as kickFindingsOf } from "../../games/findings.ts"; |
| 72 | import { joinAddress, mainPower, nowWords, PEOPLE_BUTTON, PEOPLE_CHOICES, powerNow, whoIsOn } from "../../games/gist.ts"; | |
| 71 | 73 | import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts"; |
| 72 | 74 | import { daySpark } from "../studio/kpi_row.ts"; |
| 73 | 75 | |
| @@ -87,7 +89,6 @@ const lastOf = (points: readonly Point[], pick: (p: Point) => number | null): nu | ||
| 87 | 89 | const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`; |
| 88 | 90 | const mib = (n: number | undefined): string => |
| 89 | 91 | n === undefined || n === 0 ? "?" : n >= 1024 ? `${(n / 1024).toFixed(1)} GiB` : `${Math.round(n)} MiB`; |
| 90 | const TONE: Record<string, "success" | "danger" | "default"> = { running: "success", exited: "danger", restarting: "danger" }; | |
| 91 | 92 | |
| 92 | 93 | /** |
| 93 | 94 | * New server: words in ("a void world with FAWE and bedwars"), the plan out (the service, its |
| @@ -219,19 +220,40 @@ export async function gameLinkRemove(ctx: Ctx): Promise<Response> { | ||
| 219 | 220 | return flashTo(ctx, "/settings", { message: `Unlinked ${field(form, "player")}.` }); |
| 220 | 221 | } |
| 221 | 222 | |
| 222 | const power = (box: GameBox, service: string): Html => | |
| 223 | html`<span class="row-fields" | |
| 224 | >${(["start", "stop", "restart"] as const).map( | |
| 225 | (kind) => | |
| 226 | html`<form method="post" action="/games/${box.name}/${service}/power"> | |
| 227 | <input type="hidden" name="kind" value="${kind}" />${btn(kind[0]!.toUpperCase() + kind.slice(1), { | |
| 228 | size: "sm", | |
| 229 | variant: "ghost", | |
| 230 | label: `${kind} ${service}`, | |
| 231 | })} | |
| 232 | </form>`, | |
| 233 | )}</span | |
| 234 | >`; | |
| 223 | const powerForm = (box: GameBox, service: string, kind: string, label: string, variant: "primary" | "ghost"): Html => | |
| 224 | html`<form method="post" action="/games/${box.name}/${service}/power"> | |
| 225 | <input type="hidden" name="kind" value="${kind}" />${btn(label, { size: "sm", variant, label: `${kind} ${service}` })} | |
| 226 | </form>`; | |
| 227 | ||
| 228 | /** | |
| 229 | * The server's one main button (Start while it is not running, else Restart), the rest a tap | |
| 230 | * further. | |
| 231 | */ | |
| 232 | const power = (box: GameBox, service: string, s: GameService | undefined, extra: Html | null = null, lead: "primary" | "ghost" = "primary"): Html => { | |
| 233 | const main = mainPower(s); | |
| 234 | const others = (["start", "stop", "restart"] as const).filter((k) => k !== main); | |
| 235 | return html`<span class="game-power">${powerForm(box, service, main, main === "start" ? "Start" : "Restart", lead)}<details class="game-menu"> | |
| 236 | <summary aria-label="More for ${service}">More</summary> | |
| 237 | <span class="row-fields">${others.map((k) => powerForm(box, service, k, k[0]!.toUpperCase() + k.slice(1), "ghost"))}${extra}</span> | |
| 238 | </details></span>`; | |
| 239 | }; | |
| 240 | ||
| 241 | /** | |
| 242 | * How to join and who is on, the box page's first lines: the address with Copy, then each server's | |
| 243 | * people. | |
| 244 | */ | |
| 245 | function joinBlock(ctx: Ctx, box: GameBox, names: readonly string[]): Html { | |
| 246 | const machine = pinnedOfBox(ctx.app, box); | |
| 247 | const address = joinAddress(machine?.host); | |
| 248 | const on = whoIsOn(ctx.app.db, box.id, names); | |
| 249 | return html`<section class="settings-block" id="join"> | |
| 250 | <h2>How to join</h2> | |
| 251 | ${address === undefined | |
| 252 | ? html`<p class="muted">There is no address to give yet: this box has no machine name, so a friend cannot join until it has one.</p>` | |
| 253 | : rowList([row({ title: html`<code class="mono" id="game-address">${address}</code>`, meta: html`In Minecraft: Multiplayer, Add Server, paste this.`, trail: btn("Copy", { type: "button", copy: "game-address", icon: "copy", size: "sm", label: "Copy the server address" }) })])} | |
| 254 | ${on.length === 0 ? html`<p class="muted small">Nobody is on right now.</p>` : html`<p>On now: ${on.map((x, i) => html`${i === 0 ? "" : "; "}<a href="/games/${box.name}/${x.service}">${x.service}</a>: ${x.names.join(", ")}`)}</p>`} | |
| 255 | </section>`; | |
| 256 | } | |
| 235 | 257 | |
| 236 | 258 | // GET /games/:box |
| 237 | 259 | export async function gameBoxPage(ctx: Ctx): Promise<Response> { |
| @@ -267,6 +289,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 267 | 289 | ${cloud === undefined |
| 268 | 290 | ? null |
| 269 | 291 | : html`<div id="game-machine" data-live="${CLOUD_EVENT},${GAME_CLOUD_EVENT}">${rowList([row({ title: "Its machine", facts: [cloud] })])}</div>`} |
| 292 | ${joinBlock(ctx, box, visible)} | |
| 270 | 293 | ${visible.length === 0 |
| 271 | 294 | ? emptyLine("gameServices") |
| 272 | 295 | : rowList( |
| @@ -279,12 +302,10 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 279 | 302 | return row({ |
| 280 | 303 | href: `/games/${box.name}/${n}`, |
| 281 | 304 | title: n, |
| 282 | trail: badge(stateWords(s?.state ?? "", s?.asleep === true), { tone: s?.asleep === true ? "default" : (TONE[s?.state ?? ""] ?? "default") }), | |
| 283 | meta: html`${players === null ? "" : `${players} online · `}${tps === null ? "" : `${tps.toFixed(1)} TPS · `}${mib(s?.memMiB)} · | |
| 284 | ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""} | |
| 305 | meta: html`${nowWords(s, powerNow(ctx.app.db, box.id, n))}${players === null ? "" : ` · ${players} online`}${tps === null ? "" : ` · ${tps.toFixed(1)} TPS`}${s === undefined ? "" : ` · ${mib(s.memMiB)} · ${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""} | |
| 285 | 306 | ${day.length === 0 ? "" : html`<span class="bar muted">${sparkOf(day, (p) => p.players, `${n}: players over 24 hours`)}${sparkOf(day, (p) => p.tps, `${n}: TPS over 24 hours`)}${sparkOf(day, (p) => p.memMiB, `${n}: memory over 24 hours`)}</span>`}`, |
| 286 | 307 | ...(act |
| 287 | ? { after: html`${power(box, n)}${removable(n) ? btn("Remove", { size: "sm", variant: "ghost", href: `/games/${box.name}?remove=${encodeURIComponent(n)}`, label: `Remove ${n}` }) : null}` } | |
| 308 | ? { after: power(box, n, s, removable(n) ? btn("Remove", { size: "sm", variant: "ghost", href: `/games/${box.name}?remove=${encodeURIComponent(n)}`, label: `Remove ${n}` }) : null, "ghost") } | |
| 288 | 309 | : {}), |
| 289 | 310 | }); |
| 290 | 311 | }), |
| @@ -467,6 +488,8 @@ export const gamesConsoleJs = /* js */ ` | ||
| 467 | 488 | if (log.hasAttribute('data-raw')) (d.lines || []).forEach(function (l) { log.appendChild(document.createTextNode(l + '\\n')); }); |
| 468 | 489 | else (d.html || []).forEach(function (h) { log.insertAdjacentHTML('beforeend', h + '\\n'); }); |
| 469 | 490 | if (stick) log.scrollTop = log.scrollHeight; |
| 491 | var now = document.getElementById('game-now'); | |
| 492 | if (now && d.now) now.textContent = d.now; | |
| 470 | 493 | (d.results || []).forEach(function (r) { |
| 471 | 494 | var el = document.getElementById('cmd-' + r.id); |
| 472 | 495 | if (el) el.textContent = (r.ok ? 'ok: ' : 'failed: ') + r.output; |
| @@ -533,13 +556,16 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 533 | 556 | return timePhase(ctx.request, "render", () => page({ |
| 534 | 557 | ctx, |
| 535 | 558 | title: `${service} · ${box.name}`, |
| 559 | styleCss: TOPOLOGY_CSS, | |
| 536 | 560 | scriptJs: gamesConsoleJs, |
| 537 | body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service) : undefined })} | |
| 561 | body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service, seen) : undefined })} | |
| 562 | <p class="game-now" id="game-now" aria-live="polite">${nowWords(seen, powerNow(ctx.app.db, box.id, service))}</p> | |
| 538 | 563 | ${findingsBlock(findings)} |
| 539 | ${numbersBlock(ctx, box, service)} | |
| 564 | ${joinTrouble(ctx, box, service)} | |
| 540 | 565 | ${peopleBlock(ctx, box, service, act)} |
| 566 | ${fold("Console", "console", rawView || shared !== "", html` | |
| 541 | 567 | <section class="settings-block"> |
| 542 | <h2>Console <a class="small" href="${rawView ? base : `${base}?raw=1`}">${rawView ? "Colour" : "Raw"}</a></h2> | |
| 568 | <p class="small"><a href="${rawView ? base : `${base}?raw=1`}">${rawView ? "Show it in colour" : "Show it as the game wrote it (raw)"}</a></p> | |
| 543 | 569 | ${crash === undefined |
| 544 | 570 | ? null |
| 545 | 571 | : html`<div class="notice danger" role="alert"> |
| @@ -594,10 +620,11 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta | ||
| 594 | 620 | }), |
| 595 | 621 | ), |
| 596 | 622 | )} |
| 597 | </section> | |
| 598 | ${compose === undefined || !canSleep(compose.text, service) ? null : sleepBlock(box, service, compose.text, seen?.asleep === true, act)} | |
| 599 | ${worldBlock(box, service, act, commands)} | |
| 600 | <section class="settings-block"> | |
| 623 | </section>`)} | |
| 624 | ${numbersBlock(ctx, box, service)} | |
| 625 | ${compose === undefined || !canSleep(compose.text, service) ? null : fold("Sleep", "sleep", false, sleepBlock(box, service, compose.text, seen?.asleep === true, act))} | |
| 626 | ${fold("World", "world", commands.some((c) => c.kind === "world" && !c.done), worldBlock(box, service, act, commands))} | |
| 627 | ${fold("Environment", "environment", false, html`<section class="settings-block"> | |
| 601 | 628 | <h2>Environment</h2> |
| 602 | 629 | ${Object.keys(env).length === 0 |
| 603 | 630 | ? html`<p class="muted small">None set in ${box.path}.</p>` |
| @@ -615,9 +642,9 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta | ||
| 615 | 642 | ${input({ name: "value", label: "Value (empty removes it)", mono: true })} ${btn("Commit", { variant: "secondary" })} |
| 616 | 643 | </form>` |
| 617 | 644 | : null} |
| 618 | </section> | |
| 619 | ${settingsBlock({ base, act, settings, preview, sha: compose?.sha ?? "", wanted })} | |
| 620 | ${modsBlock({ base, act, mods, hits, ups, preview: modPreview, query, adding })} | |
| 645 | </section>`)} | |
| 646 | ${fold("Settings", "settings", preview !== undefined, html`${settingsBlock({ base, act, settings, preview, sha: compose?.sha ?? "", wanted })}`)} | |
| 647 | ${fold("Mods and plugins", "mods", query !== null || adding !== "" || packQuery !== null || packing !== "", html`${modsBlock({ base, act, mods, hits, ups, preview: modPreview, query, adding })} | |
| 621 | 648 | ${mods?.ok && mods.value.target.kind === "mod" |
| 622 | 649 | ? packBlock({ |
| 623 | 650 | base, |
| @@ -630,10 +657,31 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta | ||
| 630 | 657 | packing, |
| 631 | 658 | checked: packCheckLines(ctx.app, box.id).find((l) => l.startsWith(`${service}: `))?.slice(service.length + 2), |
| 632 | 659 | }) |
| 633 | : null}`, | |
| 660 | : null}`)}`, | |
| 634 | 661 | })); |
| 635 | 662 | } |
| 636 | 663 | |
| 664 | /** A section kept one tap away: nothing removed, the page opens on what an operator came for. */ | |
| 665 | const fold = (title: string, id: string, open: boolean, body: Html): Html => disclosure(title, html`<div class="fold-body">${body}</div>`, { id, extra: "fold", open }); | |
| 666 | ||
| 667 | /** Why someone could not join: each cause with who, how often and what to tell them. */ | |
| 668 | function joinTrouble(ctx: Ctx, box: GameBox, service: string): Html | null { | |
| 669 | const found = kickFindingsOf(ctx.app.db, box.id, service); | |
| 670 | if (found.length === 0) return null; | |
| 671 | return html`<section class="settings-block" id="refused"> | |
| 672 | <h2>Why someone could not join</h2> | |
| 673 | ${rowList( | |
| 674 | found.map((f) => | |
| 675 | row({ | |
| 676 | title: f.says, | |
| 677 | meta: html`${f.count} ${f.count === 1 ? "time" : "times"}: ${f.players.join(", ")}. <span class="mono">${f.last}</span>`, | |
| 678 | facts: [{ label: "Tell them", value: f.fix }], | |
| 679 | }), | |
| 680 | ), | |
| 681 | )} | |
| 682 | </section>`; | |
| 683 | } | |
| 684 | ||
| 637 | 685 | /** What keeps going wrong for players here, each with its fix. */ |
| 638 | 686 | const findingsBlock = (findings: readonly GameFinding[]): Html | null => |
| 639 | 687 | findings.length === 0 ? null : html`<section class="settings-block" id="findings"><h2>Findings</h2>${findings.map((f) => html`<p><strong>${f.says}</strong></p>${f.fix.map((l) => html`<p>${l}</p>`)}<p class="muted small">${time(f.at)}</p>`)}</section>`; |
| @@ -648,12 +696,12 @@ function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html { | ||
| 648 | 696 | const now = lastOf(day, pick); |
| 649 | 697 | return row({ title: label, meta: html`${now === null ? "not reported" : `${now}${unit} now`} <span class="bar muted">${sparkOf(day, pick, `${label} over 24 hours`)}</span>` }); |
| 650 | 698 | }; |
| 651 | return html`<section class="settings-block"> | |
| 699 | return fold("Numbers, last 24 hours", "numbers", false, html`<section class="settings-block"> | |
| 652 | 700 | <h2>Numbers, last 24 hours</h2> |
| 653 | 701 | ${rowList([line("Players", (p) => p.players, ""), line("TPS", (p) => p.tps, ""), line("Tick time", (p) => p.mspt, " ms"), line("Memory", (p) => p.memMiB, " MiB"), line("Errors a bucket", (p) => p.errors, "")])} |
| 654 | 702 | ${joins.length === 0 ? null : html`<h3>Joins and leaves</h3>${rowList(joins.map((j) => row({ title: j.player, meta: html`${j.kind === "join" ? "joined" : "left"} ${time(j.at)}` })))}`} |
| 655 | 703 | ${errors.length === 0 ? null : html`<h3>Latest errors</h3>${rowList(errors.map((e) => row({ title: html`<span class="mono">${e.line}</span>`, meta: time(e.at) })))}`} |
| 656 | </section>`; | |
| 704 | </section>`); | |
| 657 | 705 | } |
| 658 | 706 | |
| 659 | 707 | /** What a change does, line by line, with the one button that commits it on the commit shown. */ |
| @@ -895,6 +943,7 @@ export function gameServiceStream(ctx: Ctx): Response { | ||
| 895 | 943 | const got = boxOf(ctx, "viewer", service); |
| 896 | 944 | if (got instanceof Response) return got; |
| 897 | 945 | const { box } = got; |
| 946 | let shown = ""; | |
| 898 | 947 | let after = Number(ctx.url.searchParams.get("after") ?? "0") || 0; |
| 899 | 948 | const pending = new Set( |
| 900 | 949 | recentCommands(ctx.app.db, box.id, service, 10) |
| @@ -909,8 +958,11 @@ export function gameServiceStream(ctx: Ctx): Response { | ||
| 909 | 958 | for (const c of recentCommands(ctx.app.db, box.id, service, 10)) if (!c.done) pending.add(c.id); |
| 910 | 959 | const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done); |
| 911 | 960 | for (const r of results) pending.delete(r!.id); |
| 912 | if (got.lines.length > 0 || results.length > 0) | |
| 913 | emit("lines", { html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: r!.output })) }); | |
| 961 | const now = nowWords(servicesOf(ctx.app.db, box.id).find((x) => x.name === service), powerNow(ctx.app.db, box.id, service)); | |
| 962 | const shownBefore = shown; | |
| 963 | shown = now; | |
| 964 | if (got.lines.length > 0 || results.length > 0 || now !== shownBefore) | |
| 965 | emit("lines", { now, html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: r!.output })) }); | |
| 914 | 966 | }), |
| 915 | 967 | ); |
| 916 | 968 | } |
| @@ -1010,7 +1062,7 @@ export async function gamePowerSubmit(ctx: Ctx): Promise<Response> { | ||
| 1010 | 1062 | ) |
| 1011 | 1063 | return notFoundPage(ctx); |
| 1012 | 1064 | queueCommand(ctx.app.db, got.box.id, got.service, kind, "", ctx.auth.user!.id); |
| 1013 | return flashTo(ctx, `/games/${got.box.name}`, { message: `${kind} ${got.service}: asked; the box does it on its next sync.` }); | |
| 1065 | 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.` }); | |
| 1014 | 1066 | } |
| 1015 | 1067 | |
| 1016 | 1068 | /** The settings a form or a query asks for: its `s.<key>` fields. */ |
| @@ -1184,31 +1236,27 @@ function peopleBlock(ctx: Ctx, box: GameBox, service: string, act: boolean): Htm | ||
| 1184 | 1236 | const listed = (n: string) => lists.whitelist.some((w) => w.name === n); |
| 1185 | 1237 | const toggles = (n: string): Html | null => |
| 1186 | 1238 | act |
| 1187 | ? html`<span class="row-fields">${peopleButton(base, isOp(n) ? "deop" : "op", n, isOp(n) ? "Deop" : "Op")}${lists.whitelistOn ? peopleButton(base, listed(n) ? "whitelist-remove" : "whitelist-add", n, listed(n) ? "Unlist" : "Whitelist") : null}${peopleButton(base, "kick", n, "Kick")}${peopleButton(base, "ban", n, "Ban")}</span>` | |
| 1239 | ? html`<span class="row-fields">${peopleButton(base, isOp(n) ? "deop" : "op", n, PEOPLE_BUTTON[isOp(n) ? "deop" : "op"]!)}${lists.whitelistOn ? peopleButton(base, listed(n) ? "whitelist-remove" : "whitelist-add", n, PEOPLE_BUTTON[listed(n) ? "whitelist-remove" : "whitelist-add"]!) : null}${peopleButton(base, "kick", n, "Kick")}${peopleButton(base, "ban", n, "Ban")}</span>` | |
| 1188 | 1240 | : null; |
| 1189 | const found = kickFindingsOf(ctx.app.db, box.id, service); | |
| 1190 | 1241 | return html`<section class="settings-block"> |
| 1191 | <h2>People</h2> | |
| 1192 | ${found.length === 0 | |
| 1193 | ? null | |
| 1194 | : rowList(found.map((f) => row({ title: f.says, meta: html`${f.count} ${f.count === 1 ? "time" : "times"}: ${f.players.join(", ")}. <span class="mono">${f.last}</span>`, after: html`<span class="muted small">${f.fix}</span>` })))} | |
| 1242 | <h2>Who is on</h2> | |
| 1195 | 1243 | ${online.length === 0 |
| 1196 | 1244 | ? html`<p class="muted small">Nobody is on ${service} right now.</p>` |
| 1197 | : rowList(online.map((p) => row({ title: who(p.name, p.uuid), meta: html`${isOp(p.name) ? "op" : ""}`, ...(act ? { after: toggles(p.name) ?? html`` } : {}) })))} | |
| 1245 | : rowList(online.map((p) => row({ title: who(p.name, p.uuid), meta: html`${isOp(p.name) ? "operator" : ""}`, ...(act ? { after: toggles(p.name) ?? html`` } : {}) })))} | |
| 1198 | 1246 | ${act |
| 1199 | 1247 | ? html`<form method="post" action="${base}/people" class="row-fields"> |
| 1200 | ${input({ name: "player", label: "Player", required: true, mono: true })} | |
| 1201 | <select class="input" name="op" aria-label="What to do"> | |
| 1202 | <option value="whitelist-add">Whitelist</option><option value="op">Op</option><option value="ban">Ban</option><option value="pardon">Pardon</option> | |
| 1248 | ${input({ name: "player", label: "A player's name", required: true, mono: true })} | |
| 1249 | <select class="input" name="op" required aria-label="What to do with them"> | |
| 1250 | <option value="" selected disabled>Choose what to do…</option>${PEOPLE_CHOICES.map(([v, plain, game]) => html`<option value="${v}">${plain} (${game})</option>`)} | |
| 1203 | 1251 | </select> |
| 1204 | ${btn("Do it", { variant: "secondary" })} | |
| 1252 | ${btn("Apply", { variant: "secondary" })} | |
| 1205 | 1253 | </form> |
| 1206 | ${peopleButton(base, lists.whitelistOn ? "whitelist-off" : "whitelist-on", "", lists.whitelistOn ? "Turn the whitelist off" : "Turn the whitelist on")}` | |
| 1254 | ${peopleButton(base, lists.whitelistOn ? "whitelist-off" : "whitelist-on", "", lists.whitelistOn ? "Let anyone join" : "Only listed players may join")}` | |
| 1207 | 1255 | : null} |
| 1208 | <p class="muted small">Whitelist ${lists.whitelistOn ? "on" : "off"} · ${lists.whitelist.length} listed · ${lists.ops.length} ops · ${lists.bans.length} banned</p> | |
| 1209 | ${lists.bans.length === 0 ? null : html`<h3>Banned</h3>${rowList(lists.bans.map((b) => row({ title: who(b.name, b.uuid), meta: html`${b.reason}`, ...(act ? { after: peopleButton(base, "pardon", b.name, "Pardon") } : {}) })))}`} | |
| 1210 | ${lists.ops.length === 0 ? null : html`<h3>Ops</h3>${rowList(lists.ops.map((o) => row({ title: who(o.name, o.uuid), meta: html`level ${o.level}`, ...(act ? { after: peopleButton(base, "deop", o.name, "Deop") } : {}) })))}`} | |
| 1211 | ${lists.whitelistOn && lists.whitelist.length > 0 ? html`<h3>Whitelist</h3>${rowList(lists.whitelist.map((w) => row({ title: who(w.name, w.uuid), ...(act ? { after: peopleButton(base, "whitelist-remove", w.name, "Unlist") } : {}) })))}` : null} | |
| 1256 | <p class="muted small">${lists.whitelistOn ? "Only listed players may join" : "Anyone may join"} · ${lists.whitelist.length} listed · ${lists.ops.length} operators · ${lists.bans.length} banned</p> | |
| 1257 | ${lists.bans.length === 0 ? null : html`<h3>Banned</h3>${rowList(lists.bans.map((b) => row({ title: who(b.name, b.uuid), meta: html`${b.reason}`, ...(act ? { after: peopleButton(base, "pardon", b.name, PEOPLE_BUTTON["pardon"]!) } : {}) })))}`} | |
| 1258 | ${lists.ops.length === 0 ? null : html`<h3>Operators</h3>${rowList(lists.ops.map((o) => row({ title: who(o.name, o.uuid), meta: html`level ${o.level}`, ...(act ? { after: peopleButton(base, "deop", o.name, PEOPLE_BUTTON["deop"]!) } : {}) })))}`} | |
| 1259 | ${lists.whitelistOn && lists.whitelist.length > 0 ? html`<h3>Allowed to join</h3>${rowList(lists.whitelist.map((w) => row({ title: who(w.name, w.uuid), ...(act ? { after: peopleButton(base, "whitelist-remove", w.name, PEOPLE_BUTTON["whitelist-remove"]!) } : {}) })))}` : null} | |
| 1212 | 1260 | ${events.length === 0 |
| 1213 | 1261 | ? null |
| 1214 | 1262 | : html`<h3>Latest</h3>${rowList(events.map((e) => row({ title: e.kind === "chat" ? html`<span class="mono"><${e.player}></span> ${e.text}` : eventWords(e, service), meta: time(e.at) })))}`} |
| @@ -1226,7 +1274,7 @@ export async function gamePeopleSubmit(ctx: Ctx): Promise<Response> { | ||
| 1226 | 1274 | return flashTo( |
| 1227 | 1275 | ctx, |
| 1228 | 1276 | `/games/${got.box.name}/${got.service}`, |
| 1229 | queued.ok ? { message: `Asked: ${peopleWords(JSON.stringify({ op, player, server: field(got.form, "to") }))}, on the box's next sync.${undo === undefined ? "" : " Its opposite undoes it."}` } : { tone: "danger", message: queued.error }, | |
| 1277 | queued.ok ? { message: `Asked: ${peopleWords(JSON.stringify({ op, player, server: field(got.form, "to") }))}. It shows on the server until the server answers.${undo === undefined ? "" : " Its opposite undoes it."}` } : { tone: "danger", message: queued.error }, | |
| 1230 | 1278 | ); |
| 1231 | 1279 | } |
| 1232 | 1280 |
src/web/pages/games_topology.ts +5
| @@ -39,6 +39,11 @@ export const TOPOLOGY_CSS = `/* ---- the network (#17284 G5): the proxy, a line | ||
| 39 | 39 | .net-head > summary { list-style: none; display: inline-flex; align-items: center; gap: 4px; cursor: pointer; font-size: 13px; } |
| 40 | 40 | .net-head > summary::-webkit-details-marker { display: none; } |
| 41 | 41 | .net-head > summary img { border-radius: var(--radius-sm); } |
| 42 | .game-power { display: inline-flex; flex-wrap: wrap; align-items: flex-start; gap: 8px; } | |
| 43 | .game-menu > summary { cursor: pointer; font-size: 13px; padding: 6px 8px; min-height: 44px; display: inline-flex; align-items: center; } | |
| 44 | .game-menu[open] > .row-fields { display: flex; flex-wrap: wrap; gap: 8px; } | |
| 45 | .game-now { margin: 0 0 12px; font-weight: 600; } | |
| 46 | .fold > .fold-body { padding-top: 8px; } | |
| 42 | 47 | .net-head form { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; } |
| 43 | 48 | `; |
| 44 | 49 |
test/game-gist.test.ts added +144
| @@ -0,0 +1,144 @@ | ||
| 1 | /** | |
| 2 | * What an operator on a phone comes for (#17656): the address, who is on, a state with the command | |
| 3 | * still waiting on the server, one main button, the player form with no default action. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtempSync } from "node:fs"; | |
| 7 | import { rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { createSession } from "../src/core/sessions.ts"; | |
| 12 | import { createUser } from "../src/core/users.ts"; | |
| 13 | import { joinAddress, mainPower, nowWords, PEOPLE_CHOICES, powerNow } from "../src/games/gist.ts"; | |
| 14 | import { synced } from "../src/games/notify.ts"; | |
| 15 | import { boxNamed, createGameBox, grant, queueCommand, servicesOf } from "../src/games/store.ts"; | |
| 16 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | describe("the words", () => { | |
| 22 | test("joinAddress and the choices", () => { | |
| 23 | expect(joinAddress("play.example.com")).toBe("play.example.com"); | |
| 24 | expect(joinAddress("bad host; rm")).toBeUndefined(); | |
| 25 | expect(joinAddress("")).toBeUndefined(); | |
| 26 | expect(joinAddress(undefined)).toBeUndefined(); | |
| 27 | expect(PEOPLE_CHOICES.map((c) => c[2])).toEqual(["whitelist", "op", "ban", "pardon"]); | |
| 28 | }); | |
| 29 | }); | |
| 30 | ||
| 31 | describe("on a forge", () => { | |
| 32 | let dataDir = ""; | |
| 33 | let app: App; | |
| 34 | let http: ForgeHttp; | |
| 35 | let cookie = ""; | |
| 36 | let token = ""; | |
| 37 | beforeAll(async () => { | |
| 38 | dataDir = mkdtempSync(join(tmpdir(), "forge-game-gist-")); | |
| 39 | app = createApp({ dataDir, port: 0 }); | |
| 40 | http = forgeHttp(app); | |
| 41 | const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true }); | |
| 42 | if (!u.ok) throw new Error(u.error); | |
| 43 | token = createGameBox(app.db, { name: "mc" }).token; | |
| 44 | cookie = `forge_session=${createSession(app.db, u.value.id).token}`; | |
| 45 | const sync = await http.handle( | |
| 46 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 47 | method: "POST", | |
| 48 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 49 | body: JSON.stringify({ agent: 1, services: [{ name: "survival", state: "exited" }] }), | |
| 50 | }), | |
| 51 | ); | |
| 52 | expect(sync.status).toBe(200); | |
| 53 | }, 30_000); | |
| 54 | afterAll(async () => { | |
| 55 | app.close(); | |
| 56 | await rm(dataDir, { recursive: true, force: true }); | |
| 57 | }); | |
| 58 | const get = async (path: string) => (await http.handle(new Request(`http://forge.test${path}`, { headers: { cookie } }))).text(); | |
| 59 | ||
| 60 | test("a command asked shows as Starting until the box answers, then as Started", () => { | |
| 61 | const box = boxNamed(app.db, "mc")!; | |
| 62 | const s = servicesOf(app.db, box.id).find((x) => x.name === "survival"); | |
| 63 | expect(mainPower(s)).toBe("start"); | |
| 64 | expect(nowWords(s, powerNow(app.db, box.id, "survival"))).toBe("exited"); | |
| 65 | const id = queueCommand(app.db, box.id, "survival", "start", "", ""); | |
| 66 | const asked = powerNow(app.db, box.id, "survival", Date.now() + 10_000); | |
| 67 | expect(asked).toMatch(/^Starting: asked (9|10|11) s ago$/); | |
| 68 | app.db.query("UPDATE game_command SET done_at = ?2, ok = 1, output = '' WHERE id = ?1").run(id, new Date().toISOString()); | |
| 69 | expect(powerNow(app.db, box.id, "survival")).toBe("Started"); | |
| 70 | expect(powerNow(app.db, box.id, "survival", Date.now() + 700_000)).toBeUndefined(); | |
| 71 | }); | |
| 72 | ||
| 73 | test("the box page leads with how to join and each server's state and one main button; the server page folds the rest", async () => { | |
| 74 | const box = await get("/games/mc"); | |
| 75 | expect(box).toContain("How to join"); | |
| 76 | expect(box).toContain("no address to give yet"); | |
| 77 | expect(box).toContain("game-menu"); | |
| 78 | expect(box.indexOf('aria-label="start survival"')).toBeLessThan(box.indexOf('class="game-menu"')); | |
| 79 | expect(box).toContain("% CPU"); | |
| 80 | expect(box).toContain("players over 24 hours"); | |
| 81 | expect(box).not.toContain('data-variant="primary"'); | |
| 82 | const page = await get("/games/mc/survival"); | |
| 83 | expect(page).toContain('id="game-now"'); | |
| 84 | for (const id of ["console", "environment", "settings", "mods"]) expect(page).toContain(`id="${id}"`); | |
| 85 | expect(page).toContain("<h2>Who is on</h2>"); | |
| 86 | }); | |
| 87 | ||
| 88 | test("the player form has no default action", async () => { | |
| 89 | const page = await get("/games/mc/survival"); | |
| 90 | expect(page).toContain("Choose what to do…"); | |
| 91 | expect(page).toMatch(/<option value="" selected disabled>/); | |
| 92 | expect(page).toContain("Make operator (op)"); | |
| 93 | expect(page).not.toContain("Do it"); | |
| 94 | }); | |
| 95 | test("the stream says the state when only the state changed", async () => { | |
| 96 | const box = boxNamed(app.db, "mc")!; | |
| 97 | const res = await http.handle(new Request("http://forge.test/games/mc/survival/stream", { headers: { cookie } })); | |
| 98 | const reader = res.body!.getReader(); | |
| 99 | const next = async (): Promise<string> => { | |
| 100 | for (;;) { | |
| 101 | const got = await Promise.race([reader.read(), new Promise<never>((_, no) => setTimeout(() => no(new Error("no event")), 3000))]); | |
| 102 | const text = new TextDecoder().decode(got.value); | |
| 103 | if (text.includes("event:")) return text; | |
| 104 | } | |
| 105 | }; | |
| 106 | synced(app, box.id); | |
| 107 | const first = await next(); | |
| 108 | expect(first).toContain("event: lines"); | |
| 109 | app.db.query("UPDATE game_service SET state = 'running' WHERE box_id = ?1 AND name = 'survival'").run(box.id); | |
| 110 | synced(app, box.id); | |
| 111 | const second = await next(); | |
| 112 | expect(second).toContain("event: lines"); | |
| 113 | expect(second).toContain('"now":"running'); | |
| 114 | expect(second).toContain('"lines":[]'); | |
| 115 | await reader.cancel(); | |
| 116 | }); | |
| 117 | ||
| 118 | test("the power POST goes back to the server's page with the flash in a capital", async () => { | |
| 119 | const res = await http.handle( | |
| 120 | new Request("http://forge.test/games/mc/survival/power", { | |
| 121 | method: "POST", | |
| 122 | headers: { cookie, origin: "http://forge.test", "content-type": "application/x-www-form-urlencoded" }, | |
| 123 | body: "kind=stop", | |
| 124 | }), | |
| 125 | ); | |
| 126 | expect(res.status).toBe(303); | |
| 127 | expect(res.headers.get("location")).toBe("/games/mc/survival"); | |
| 128 | expect(decodeURIComponent(res.headers.get("set-cookie") ?? "").replace(/\+/g, " ")).toContain("Stop survival: asked"); | |
| 129 | }); | |
| 130 | ||
| 131 | test("a viewer gets no power buttons and no player form", async () => { | |
| 132 | const made = await createUser(app.db, { username: "vi", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: false, trusted: true }); | |
| 133 | if (!made.ok) throw new Error(made.error); | |
| 134 | grant(app.db, boxNamed(app.db, "mc")!.id, made.value.id, "viewer", "survival"); | |
| 135 | const viewer = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 136 | const read = async (path: string) => (await http.handle(new Request(`http://forge.test${path}`, { headers: { cookie: viewer } }))).text(); | |
| 137 | for (const page of [await read("/games/mc"), await read("/games/mc/survival")]) { | |
| 138 | expect(page).not.toContain("/power"); | |
| 139 | expect(page).not.toContain('class="game-menu"'); | |
| 140 | expect(page).not.toContain("Choose what to do"); | |
| 141 | } | |
| 142 | expect(await read("/games/mc/survival")).toContain('id="game-now"'); | |
| 143 | }); | |
| 144 | }); |
test/game-people.test.ts +2 −2
| @@ -183,13 +183,13 @@ describe("on a forge", () => { | ||
| 183 | 183 | expect(networkOf(app.db, box.id)).toEqual({ hub: ["Alice", ".Steve"] }); |
| 184 | 184 | expect(eventsOf(app.db, box.id, "hub").map((e) => e.kind)).toEqual(["death", "chat", "join"]); |
| 185 | 185 | const page = await (await http.handle(new Request("http://forge.test/games/mc/hub", { headers: { cookie } }))).text(); |
| 186 | expect(page).toContain("<h2>People</h2>"); | |
| 186 | expect(page).toContain("<h2>Who is on</h2>"); | |
| 187 | 187 | expect(page).toContain(`/games/head/${ALICE}`); |
| 188 | 188 | expect(page).toContain("Bedrock"); |
| 189 | 189 | expect(page).toContain("welcome back"); |
| 190 | 190 | expect(page).toContain("Alice was slain by Zombie"); |
| 191 | 191 | expect(page).toContain("griefing"); |
| 192 | expect(page).toMatch(/>\s*Deop\s*</); | |
| 192 | expect(page).toMatch(/>\s*Remove operator\s*</); | |
| 193 | 193 | // Who is where is the box page's network picture now, which needs the box's compose file: test/game-topology.test.ts. |
| 194 | 194 | }); |
| 195 | 195 |
test/game-sleep.test.ts +1 −3
| @@ -16,7 +16,7 @@ import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | ||
| 16 | 16 | import { createToken } from "../src/core/tokens.ts"; |
| 17 | 17 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 18 | 18 | import { readCompose, setServiceEnv } from "../src/games/compose.ts"; |
| 19 | import { AUTOSTOPPER, canSleep, policyOf, setPolicy, sleeping, stateWords, syncSleep, WAKER, WAKER_CONFIG, WAKER_IMAGE } from "../src/games/sleep.ts"; | |
| 19 | import { AUTOSTOPPER, canSleep, policyOf, setPolicy, sleeping, syncSleep, WAKER, WAKER_CONFIG, WAKER_IMAGE } from "../src/games/sleep.ts"; | |
| 20 | 20 | import { boxNamed, createGameBox, markAsleep } from "../src/games/store.ts"; |
| 21 | 21 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; |
| 22 | 22 | import { quietLogs } from "./helpers/globals.ts"; |
| @@ -195,8 +195,6 @@ describe("a stopped sleeper, as the box reports it", () => { | ||
| 195 | 195 | { name: "hunting", asleep: 1 }, |
| 196 | 196 | { name: "survival", asleep: 0 }, |
| 197 | 197 | ]); |
| 198 | expect(stateWords("exited", true)).toBe("asleep (wakes on join)"); | |
| 199 | expect(stateWords("exited", false)).toBe("exited"); | |
| 200 | 198 | }); |
| 201 | 199 | }); |
| 202 | 200 |
new above
offline