Public: anyone can read this; the crew can change it.
One log reader for a game service, on the page and in the terminal; its commands and answers are its operators' #17768
Merged 16h 39m ago, live in production
sold/log-reader → main 0 commits
21 files
changed +1068
−212
- docs/features/game-box.md
- docs/features/games.md
- docs/features/log-reader.md
- src/core/migration-pins/20261202235500-game-command-after-log.pin
- src/core/migrations/20261202235500-game-command-after-log.ts
- src/games/store.ts
- src/logs/game.ts
- src/logs/page.ts
- src/terminal/blocks.ts
- src/tui/screens/games.ts
- src/tui/ui/log_pane.ts
- src/web/log_reader.ts
- src/web/pages/games.ts
- src/web/terminal_blocks.ts
- test/game-answer.test.ts
- test/game-console-colour.test.ts
- test/game-gist.test.ts
- test/job-slices.test.ts
- test/log-reader.test.ts
- test/terminal-blocks.test.ts
- test/tui-games.test.ts
docs/features/game-box.md +1 −1
| @@ -38,7 +38,7 @@ experiment. | ||
| 38 | 38 | - **DNS:** an A record, not proxied, for the box's `host` in any Cloudflare zone a connected token can write; with none, the plan says to set it by hand. |
| 39 | 39 | |
| 40 | 40 | Code: `src/games/store.ts` (the `game_box` row and its token, the games store's), `src/games/boot.ts` (the boot config), `src/games/agent.sh`, `gameWant` in `src/actions/infra.ts`, and `bootRow` in `src/actions/pinned.ts`. |
| 41 | - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. It runs as root (the agent's unit names no user), and both doors say so. Each command is a block (`src/terminal/blocks.ts`): what was typed, its state in words (waiting, the box has it, done, failed, no answer came back) and what it printed; the page replaces a block in place as its state changes, and up and down in the input walk the commands of the blocks on the page, each once; a block's Edit puts its command in the input, for a phone with no arrows. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read, so a secret a command prints stays there: one line at the input says it. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`. | |
| 41 | - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. It runs as root (the agent's unit names no user), and both doors say so. Each command is a block (`src/terminal/blocks.ts`): what was typed, its state in words (waiting, the box has it, done, failed, no answer came back) and what it printed; the page replaces a block in place as its state changes, and up and down in the input walk the commands of the blocks on the page, each once; a block's Edit puts its command in the input, for a phone with no arrows. Each answer keeps the last line of its service's log that the forge held when it was recorded (`game_command.after_log`, 0 for none, null for one from before it was kept), sent as `after` in the stream's `blocks` event, so a reader can place it among the lines. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read, so a secret a command prints stays there: one line at the input says it. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`. | |
| 42 | 42 | |
| 43 | 43 | - **Spare while servers sleep (#17576):** `/games/<box>` has two `dl` rows (the `status-rows` of the security page), and the terminal's box screen (`b` on a service) the same two as its first line: "Spare while servers sleep: N core-hours a week, M GB (samples of 7 days). Forge checks, same week: C core-hours." (`src/games/spare.ts`, read by `spare_row.ts`, which keeps the pair a minute per box so a redraw or reload reads nothing). Spare memory = the box's memory − what is awake − a reserve that always fits the largest sleeping server (its highest memory seen awake in the window); spare core-hours = the idle cores (the box's vCPUs − awake servers' CPU, 100 % being a core) of each minute a server sleeps, scaled from the minutes sampled to a week. A box with everything awake has 0. Fewer than 24 hours of samples, or a size or sleeper's memory not known, says "unknown", never 0. The checks' figure is the `cpu_s` of the cost ledger's `check` entries that ended in the last 7 days (read from the end of the month files, stopping at the window's start, at most 4 MiB, not walking the chain; "not measured" when none carried it). A server counts as asleep in a minute that it held no memory. |
| 44 | 44 | - **Run checks while servers sleep (#17577):** the box's owner (forge admins own every box) sees a switch on `/games/<box>` (`POST /games/<box>/lend`, same-origin) and as `l` on the terminal's box screen, off by default, in the same words (`src/games/lend.ts`). Switching it on enrols a scoped `lent-box-<name>` runner for the box ([](lent-runners.md)); switching it off revokes it at once. Its authors are the people who write the box's repository (its owner, teams and crew), read at each claim (a writer removed later is out at once), never a box owner who does not write it; a box with none names nobody, never anyone. The runner's token is not kept: it is held in the forge's memory until the box's next sync carries it over, once (see below). |
docs/features/games.md +2 −2
| @@ -9,8 +9,8 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`, | ||
| 9 | 9 | ## Where |
| 10 | 10 | |
| 11 | 11 | - **In the navigation:** Games is in the top bar, at `g p` (`g P` inside a repository), in Cmd/Ctrl K and in the terminal's palette, for a forge admin and anyone with a grant on a box. With no box, an admin's `/games` has Start a game box: it asks Talk for a plan, which builds nothing until approved. In the terminal `n` on an empty Games screen sends the same words. |
| 12 | - **Web:** `/games` lists the boxes you may see; `/games/<box>` is the network, one row a service with Start, Stop and Restart; `/games/<box>/<service>` is the console (a live log over SSE in the game's own colours: the agent and the sync route turn each colour escape into its § code before they drop every other escape, and the page draws § codes through the one renderer, with Raw for the lines as kept; an RCON input whose answer shows inline, with the service's earlier commands on up and down; a crash found in the log leads in one line, "Crashed: Fabric could not load the mods: Install fabric-api", with the crash folded under it and a Share on mclo.gs button that says it publishes the log where anyone with the link can read it, and posts only on that click), the environment editor (commits `games: <service> env: <keys>`), the settings ([](game-settings.md)) and its mods or plugins (Modrinth, below; Upload jar for `PLUGINS`). Pages: `src/web/pages/games.ts`. | |
| 13 | - **Terminal:** the Games screen (`src/tui/screens/games.ts`): each service, `s`, `x`, `r`; `enter` opens its console and env, `c` there its settings, and `m` its mods (`/` search, `a` install, `u` update all, `d` remove, then `y` commits the preview shown); a service's console reads its log with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down. | |
| 12 | - **Web:** `/games` lists the boxes you may see; `/games/<box>` is the network, one row a service with Start, Stop and Restart; `/games/<box>/<service>` is the console (a live log over SSE in the game's own colours: the agent and the sync route turn each colour escape into its § code before they drop every other escape, and the page draws § codes through the one renderer, with Raw for the lines as kept, through the [](log-reader.md); an RCON input under it, each command a block whose state and answer come in place over the log's one stream, with the service's earlier commands on up and down; a crash found in the log leads in one line, "Crashed: Fabric could not load the mods: Install fabric-api", with the crash folded under it and a Share on mclo.gs button that says it publishes the log where anyone with the link can read it, and posts only on that click), the environment editor (commits `games: <service> env: <keys>`), the settings ([](game-settings.md)) and its mods or plugins (Modrinth, below; Upload jar for `PLUGINS`). Pages: `src/web/pages/games.ts`. | |
| 13 | - **Terminal:** the Games screen (`src/tui/screens/games.ts`): each service, `s`, `x`, `r`; `enter` opens its console and env, `c` there its settings, and `m` its mods (`/` search, `a` install, `u` update all, `d` remove, then `y` commits the preview shown); a service's console is the [](log-reader.md) with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down. | |
| 14 | 14 | - **MCP:** `games` (admin-listed): `list`, `console`, `power`, `env`, `config`, `config_set`, and `mods`, `mods_search`, `mods_install`, `mods_update`, `mods_remove` (each change planned first; `dryRun: false` commits), with the same grants. |
| 15 | 15 | - **Agent:** `POST /api/v1/games/agent/sync` with the box token as bearer (`src/http/games_routes.ts`, `src/games/store.ts`): status, a log tail (2,000 lines a service), command results in; the compose (only when its sha differs), env files and queued commands (each handed out once) out. |
| 16 | 16 |
docs/features/log-reader.md added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: The log reader | |
| 4 | --- | |
| 5 | ||
| 6 | # The log reader | |
| 7 | ||
| 8 | One reader for a log, drawn the same on a page (`src/web/log_reader.ts`) and in the terminal (`src/tui/ui/log_pane.ts`) from one model (`src/logs/page.ts`). Its first source is a game service's console (`src/logs/game.ts`): `/games/<box>/<service>` and the terminal's service screen. | |
| 9 | ||
| 10 | - **Age, always said:** "Live. Last line just now.", "Last line 14 minutes ago; the box is sending its log.", or "Not known since …" once the box has not sent its log for 2 minutes. A quiet server and a silent box never read the same. The time is the sync's that brought the line, not the line's own. | |
| 11 | - **What matters first:** a crash the server did not come back from leads in one line, with a link to it in the log. | |
| 12 | - **Find:** plain words, every one of them in the line, over all that is kept (2,000 lines a service), with the count ("14 of 2,000 kept lines"). On the page the filter is in the address (`?log=`), so a search is a link. A match opens in its place with the lines around it (`?at=<id>`; `enter` in the terminal), and the way back keeps the filter (`esc`). `level:` and the other fields of the list language are not read yet. | |
| 13 | - **Copy:** the page's Copy takes the lines shown, without their link marks. In the terminal `y` copies the line and `v` picks a range first. | |
| 14 | - **Nothing skipped unsaid:** a page that was away gets every kept line since, each once; when more came than are kept, a row says some may be missing. Scrolled up, the page holds its place and "38 newer" goes to the end. | |
| 15 | - **Masked once:** `src/logs/game.ts` passes every line through `redactHeld` before any reader, filter or Share on mclo.gs sees it: credential shapes, and values a run holds now. A secret with no known shape that a game prints itself is not caught. | |
| 16 | - **One stream:** `/games/<box>/<service>/stream` sends `lines` (rows, the state line and the age) and `blocks` (the commands' states and answers). The person is read again at each look: it ends when they are no longer a viewer, and one who is no longer an operator gets no command or answer from then on. | |
| 17 | - **Answers in their place:** a command's answer stands under the last line the forge held when it was recorded (`game_command.after_log`; one from before that was kept, under the last line its time had), and stays there: later output goes below it. What still waits is by the input. A filtered log, or one shown at a line, keeps them all by the input. World and power work has no Edit and is not in up and down: it is nothing to type. **Who sees them:** the service's operators and the box's owner, on the page, its stream and in the terminal. A viewer reads the log and the server's state, never a command or what it printed. MCP `games` gives no one a command's answer. |
src/core/migration-pins/20261202235500-game-command-after-log.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | eefcfe1f3cac58b0be46db0257c85f42c0bfc1546cdd1ca1bce73b64fb5fb64f |
src/core/migrations/20261202235500-game-command-after-log.ts added +5
| @@ -0,0 +1,5 @@ | ||
| 1 | // Where a command's answer stands in its service's log (#17151): the id of the last line the forge | |
| 2 | // held when the answer was recorded, 0 for none. Null for an answer recorded before this. Additive. | |
| 3 | export default ` | |
| 4 | ALTER TABLE game_command ADD COLUMN after_log INTEGER; | |
| 5 | `; |
src/games/store.ts +13 −32
| @@ -370,6 +370,10 @@ export interface CommandState { | ||
| 370 | 370 | readonly done: boolean; |
| 371 | 371 | readonly ok: boolean | null; |
| 372 | 372 | readonly output: string; |
| 373 | /** When the answer was recorded; empty until then. */ | |
| 374 | readonly doneAt: string; | |
| 375 | /** The last line of its service's log held when the answer was recorded, 0 for none; null until then, and for an answer from before it was kept. */ | |
| 376 | readonly afterLog: number | null; | |
| 373 | 377 | } |
| 374 | 378 | /** What a command handed to the box and never answered says: it is not sent again, since running one twice is worse. */ |
| 375 | 379 | export const NO_ANSWER = "No answer came back; it may have run."; |
| @@ -381,9 +385,9 @@ const JOB_ANSWER_MS = 2 * 3_600_000; | ||
| 381 | 385 | export function commandOf(db: Database, id: string, now = Date.now()): CommandState | undefined { |
| 382 | 386 | const r = db |
| 383 | 387 | .query< |
| 384 | { id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string }, | |
| 388 | { id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string; after_log: number | null }, | |
| 385 | 389 | [string] |
| 386 | >("SELECT id, kind, service, text, handed_at, done_at, ok, output FROM game_command WHERE id = ?1") | |
| 390 | >("SELECT id, kind, service, text, handed_at, done_at, ok, output, after_log FROM game_command WHERE id = ?1") | |
| 387 | 391 | .get(id); |
| 388 | 392 | if (r === null) return undefined; |
| 389 | 393 | const limit = ["rcon", "people", "tell", "shell"].includes(r.kind) ? ANSWER_MS : JOB_ANSWER_MS; |
| @@ -397,35 +401,8 @@ export function commandOf(db: Database, id: string, now = Date.now()): CommandSt | ||
| 397 | 401 | done: r.done_at !== "" || unanswered, |
| 398 | 402 | ok: r.ok === null ? null : r.ok === 1, |
| 399 | 403 | output: unanswered ? NO_ANSWER : r.output, |
| 400 | }; | |
| 401 | } | |
| 402 | ||
| 403 | /** What became of a command, in words: "ok: …", "failed: …", that no answer came, or that it waits. */ | |
| 404 | export const commandSays = (c: Pick<CommandState, "done" | "ok" | "handed" | "output">): string => | |
| 405 | !c.done ? (c.handed ? "sent to the box" : "queued") : c.ok === null ? c.output : `${c.ok ? "ok" : "failed"}: ${c.output}`; | |
| 406 | ||
| 407 | /** | |
| 408 | * For a stream of a service's answers: each call gives the commands settled since the last one, among | |
| 409 | * those unsettled when the stream began or queued since. One told "no answer came" is told again if | |
| 410 | * its answer comes late. | |
| 411 | */ | |
| 412 | export function answersOf(db: Database, boxId: string, service: string): (now?: number) => CommandState[] { | |
| 413 | const pending = new Map<string, "waiting" | "unanswered">(); | |
| 414 | const look = (now: number): void => { | |
| 415 | for (const c of recentCommands(db, boxId, service, 10, now)) if ((!c.done || c.ok === null) && !pending.has(c.id)) pending.set(c.id, c.done ? "unanswered" : "waiting"); | |
| 416 | }; | |
| 417 | look(Date.now()); | |
| 418 | return (now = Date.now()) => { | |
| 419 | look(now); | |
| 420 | const settled: CommandState[] = []; | |
| 421 | for (const [id, was] of [...pending]) { | |
| 422 | const c = commandOf(db, id, now); | |
| 423 | if (c === undefined || c.ok !== null) pending.delete(id); | |
| 424 | else if (!c.done || was === "unanswered") continue; | |
| 425 | else pending.set(id, "unanswered"); | |
| 426 | if (c !== undefined) settled.push(c); | |
| 427 | } | |
| 428 | return settled; | |
| 404 | doneAt: r.done_at, | |
| 405 | afterLog: r.after_log, | |
| 429 | 406 | }; |
| 430 | 407 | } |
| 431 | 408 | |
| @@ -687,7 +664,11 @@ function recordResults(db: Database, boxId: string, results: SyncBody["results"] | ||
| 687 | 664 | const asked = db.query<{ kind: string; service: string; text: string }, [string, string]>("SELECT kind, service, text FROM game_command WHERE id = ?1 AND box_id = ?2 AND done_at = ''").get(id, boxId); |
| 688 | 665 | if (asked === null) continue; |
| 689 | 666 | const { ok, output } = outcomeOf(db, boxId, asked, { ok: r.ok === true, output: str(r.output, OUTPUT_MAX) }); |
| 690 | db.query("UPDATE game_command SET done_at = ?2, ok = ?3, output = ?4 WHERE id = ?1").run(id, at, ok ? 1 : 0, output); | |
| 667 | // A full sync's own lines are in by now (`recordSync`): the answer stands after them. | |
| 668 | db.query( | |
| 669 | `UPDATE game_command SET done_at = ?2, ok = ?3, output = ?4, | |
| 670 | after_log = coalesce((SELECT id FROM game_log WHERE box_id = ?5 AND service = ?6 ORDER BY id DESC LIMIT 1), 0) WHERE id = ?1`, | |
| 671 | ).run(id, at, ok ? 1 : 0, output, boxId, asked.service); | |
| 691 | 672 | } |
| 692 | 673 | } |
| 693 | 674 |
src/logs/game.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** A game service's kept log, masked here and nowhere else (`redactHeld`), for every reader. */ | |
| 2 | ||
| 3 | import type { Database } from "bun:sqlite"; | |
| 4 | import { consoleText, crashOf } from "../games/console.ts"; | |
| 5 | import { LOG_KEEP, servicesOf } from "../games/store.ts"; | |
| 6 | import { redactHeld } from "../kernel/log.ts"; | |
| 7 | import type { LogAge, LogLine, LogPage } from "./page.ts"; | |
| 8 | ||
| 9 | const OLDER_GONE = `Older lines are dropped: ${LOG_KEEP.toLocaleString("en-US")} are kept.`; | |
| 10 | ||
| 11 | /** The lines that came after `after`, oldest first, all of them, and whether some between may be gone. */ | |
| 12 | export function gameLogAfter(db: Database, boxId: string, service: string, after: number): { lines: LogLine[]; gone: boolean } { | |
| 13 | const lines = db | |
| 14 | .query<{ id: number; line: string }, [string, string, number]>("SELECT id, line FROM game_log WHERE box_id = ?1 AND service = ?2 AND id > ?3 ORDER BY id") | |
| 15 | .all(boxId, service, after) | |
| 16 | .map((r) => ({ id: r.id, text: redactHeld(r.line) })); | |
| 17 | // Every kept line is newer than the mark, and the log is full: what came first may be dropped. | |
| 18 | return { lines, gone: after > 0 && lines.length >= LOG_KEEP }; | |
| 19 | } | |
| 20 | ||
| 21 | /** The whole kept log, and its crash when the server did not come back from it. */ | |
| 22 | export function gameLogPage(db: Database, boxId: string, service: string): LogPage { | |
| 23 | const { lines } = gameLogAfter(db, boxId, service, 0); | |
| 24 | const texts = lines.map((l) => l.text); | |
| 25 | const crash = crashOf(texts); | |
| 26 | const at = crash === undefined ? -1 : texts.lastIndexOf(crash.lines[0]!); | |
| 27 | return { | |
| 28 | lines, | |
| 29 | older: lines.length >= LOG_KEEP ? OLDER_GONE : undefined, | |
| 30 | finding: crash === undefined ? undefined : { says: crash.summary, detail: crash.lines, line: lines[at]?.id ?? null }, | |
| 31 | }; | |
| 32 | } | |
| 33 | ||
| 34 | /** When the last line came, and when the box last sent its services and their logs (a light sync sends neither). */ | |
| 35 | export function gameLogAge(db: Database, boxId: string, service: string): LogAge { | |
| 36 | const last = db | |
| 37 | .query<{ at: string }, [string, string]>("SELECT at FROM game_log WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT 1") | |
| 38 | .get(boxId, service); | |
| 39 | return { lastLine: last?.at ?? "", lastHeard: servicesOf(db, boxId).find((s) => s.name === service)?.seenAt ?? "" }; | |
| 40 | } | |
| 41 | ||
| 42 | /** | |
| 43 | * The line an answer stands after, 0 for before the first; null while there is none. One from before | |
| 44 | * the line was kept with it stands after the last line its time had. | |
| 45 | */ | |
| 46 | export function answerAfter(db: Database, boxId: string, service: string, b: { readonly after: number | null; readonly at: string }): number | null { | |
| 47 | if (b.after !== null || b.at === "") return b.after; | |
| 48 | return db.query<{ id: number | null }, [string, string, string]>("SELECT MAX(id) AS id FROM game_log WHERE box_id = ?1 AND service = ?2 AND at <= ?3").get(boxId, service, b.at)?.id ?? 0; | |
| 49 | } | |
| 50 | ||
| 51 | /** | |
| 52 | * The page with each answer's lines under the line it stands after, for a reader that draws text. An | |
| 53 | * answer's line has an id between two kept lines' (no whole number), so it is found and copied as they are. | |
| 54 | */ | |
| 55 | export function withAnswerLines(page: LogPage, answers: readonly { readonly after: number; readonly lines: readonly string[] }[]): LogPage { | |
| 56 | const last = new Map<number, number>(); | |
| 57 | const drawn = answers.flatMap((a) => | |
| 58 | a.lines.map((text) => { | |
| 59 | const n = (last.get(a.after) ?? 0) + 1; | |
| 60 | last.set(a.after, n); | |
| 61 | return { id: a.after + n / 1e6, text }; | |
| 62 | }), | |
| 63 | ); | |
| 64 | return drawn.length === 0 ? page : { ...page, lines: [...page.lines, ...drawn].sort((a, b) => a.id - b.id) }; | |
| 65 | } | |
| 66 | ||
| 67 | /** A line as a person reads it, its colour codes gone: what is searched and copied. */ | |
| 68 | export const plainLine = (text: string): string => consoleText([text])[0]!; |
src/logs/page.ts added +55
| @@ -0,0 +1,55 @@ | ||
| 1 | /** | |
| 2 | * A log as its readers draw it: the lines, how old they are, what is missing, what matters. The page | |
| 3 | * (`web/log_reader.ts`) and the terminal (`tui/ui/log_pane.ts`) draw the same one. | |
| 4 | */ | |
| 5 | ||
| 6 | import { agoWords } from "../kernel/ago.ts"; | |
| 7 | ||
| 8 | export interface LogLine { | |
| 9 | /** The line's own id: it never moves, so a link to it keeps its place. */ | |
| 10 | readonly id: number; | |
| 11 | readonly text: string; | |
| 12 | } | |
| 13 | ||
| 14 | export interface LogPage { | |
| 15 | /** All that is kept, oldest first. */ | |
| 16 | readonly lines: readonly LogLine[]; | |
| 17 | /** Said above the first line when older ones are gone. */ | |
| 18 | readonly older: string | undefined; | |
| 19 | /** What matters, with the line it starts at. */ | |
| 20 | readonly finding: { readonly says: string; readonly detail: readonly string[]; readonly line: number | null } | undefined; | |
| 21 | } | |
| 22 | ||
| 23 | export interface LogAge { | |
| 24 | /** When the last line came, and when its source last sent its log; "" when never. */ | |
| 25 | readonly lastLine: string; | |
| 26 | readonly lastHeard: string; | |
| 27 | } | |
| 28 | ||
| 29 | /** A source not heard from for this long is silent: what it logs now is not known. */ | |
| 30 | const SILENT_MS = 120_000; | |
| 31 | ||
| 32 | /** The age of a log in one sentence: a quiet log and a silent source never read the same. */ | |
| 33 | export function ageWords(age: LogAge, now: number = Date.now()): string { | |
| 34 | if (age.lastHeard === "") return "Not known: the box has not sent its log yet."; | |
| 35 | if (now - Date.parse(age.lastHeard) > SILENT_MS) | |
| 36 | return `Not known since ${age.lastHeard.slice(0, 16).replace("T", " ")} UTC: the box last sent its log ${agoWords(age.lastHeard, now)}.`; | |
| 37 | if (age.lastLine === "") return "Nothing has been written yet; the box is sending its log."; | |
| 38 | return now - Date.parse(age.lastLine) < 60_000 ? "Live. Last line just now." : `Last line ${agoWords(age.lastLine, now)}; the box is sending its log.`; | |
| 39 | } | |
| 40 | ||
| 41 | const wordsIn = (q: string): string[] => q.toLowerCase().split(/\s+/).filter((w) => w !== ""); | |
| 42 | ||
| 43 | /** Whether every word of `q` is somewhere in the text. */ | |
| 44 | export function matchesLog(text: string, q: string): boolean { | |
| 45 | const low = text.toLowerCase(); | |
| 46 | return wordsIn(q).every((w) => low.includes(w)); | |
| 47 | } | |
| 48 | ||
| 49 | /** The text in pieces, the ones that match a word of `q` marked. */ | |
| 50 | export function markLog(text: string, q: string): { text: string; hit: boolean }[] { | |
| 51 | const words = wordsIn(q).sort((a, b) => b.length - a.length); | |
| 52 | if (words.length === 0) return [{ text, hit: false }]; | |
| 53 | const found = new RegExp(`(${words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "gi"); | |
| 54 | return text.split(found).map((t, i) => ({ text: t, hit: i % 2 === 1 })).filter((p) => p.text !== ""); | |
| 55 | } |
src/terminal/blocks.ts +23 −5
| @@ -7,14 +7,21 @@ | ||
| 7 | 7 | import type { App } from "../app.ts"; |
| 8 | 8 | import { getUserById } from "../core/users.ts"; |
| 9 | 9 | import { SHELL_SERVICE } from "../games/shell.ts"; |
| 10 | import { mayDo, NO_ANSWER, recentCommands, roleOn, type GameBox } from "../games/store.ts"; | |
| 10 | import { worldWords } from "../games/worlds.ts"; | |
| 11 | import { mayDo, NO_ANSWER, recentCommands, roleOn, type CommandState, type GameBox } from "../games/store.ts"; | |
| 11 | 12 | |
| 12 | 13 | export interface Block { |
| 13 | 14 | readonly id: string; |
| 14 | 15 | readonly text: string; |
| 15 | 16 | readonly state: "queued" | "sent" | "ok" | "failed" | "unanswered"; |
| 17 | /** A command that was typed, and may be again: an Edit, and up and down. World and power work is no command to type. */ | |
| 18 | readonly typed: boolean; | |
| 16 | 19 | /** What it printed; empty until it is answered. */ |
| 17 | 20 | readonly output: string; |
| 21 | /** The log line it stands after, 0 for before the first; null for not answered, or answered before this was kept: then `at` places it. */ | |
| 22 | readonly after: number | null; | |
| 23 | /** When the answer was recorded; empty until then. */ | |
| 24 | readonly at: string; | |
| 18 | 25 | } |
| 19 | 26 | |
| 20 | 27 | /** Said beside the input on every door, short enough for the terminal's prompt (50 cells): the audit takes the output whole (`auditShellResults`). */ |
| @@ -24,16 +31,18 @@ export const AUDIT_SAYS = "The audit keeps commands and output, secrets too."; | ||
| 24 | 31 | export const shellSays = (box: Pick<GameBox, "name">): string => |
| 25 | 32 | `A shell on ${box.name}, as root: each command runs as bash -lc for at most 30 s, with no terminal, and says back at most 16 KB.`; |
| 26 | 33 | |
| 34 | function blockOf(c: CommandState, text: string, typed: boolean): Block { | |
| 35 | const state = !c.done ? (c.handed ? "sent" : "queued") : c.ok === null ? "unanswered" : c.ok ? "ok" : "failed"; | |
| 36 | return { id: c.id, text, state, typed, output: state === "ok" || state === "failed" ? c.output : "", after: c.afterLog, at: c.doneAt }; | |
| 37 | } | |
| 38 | ||
| 27 | 39 | /** The box's last shell commands, oldest first. The role is read now, so a lost one ends the list: undefined. */ |
| 28 | 40 | export function shellBlocks(app: App, viewerId: string | undefined, box: GameBox): Block[] | undefined { |
| 29 | 41 | const viewer = viewerId === undefined ? undefined : getUserById(app.db, viewerId); |
| 30 | 42 | if (viewer === undefined || !mayDo(roleOn(app.db, viewer, box.id), "owner")) return undefined; |
| 31 | 43 | return recentCommands(app.db, box.id, SHELL_SERVICE, 10) |
| 32 | 44 | .reverse() |
| 33 | .map((c) => { | |
| 34 | const state = !c.done ? (c.handed ? "sent" : "queued") : c.ok === null ? "unanswered" : c.ok ? "ok" : "failed"; | |
| 35 | return { id: c.id, text: c.text, state, output: state === "ok" || state === "failed" ? c.output : "" }; | |
| 36 | }); | |
| 45 | .map((c) => blockOf(c, c.text, true)); | |
| 37 | 46 | } |
| 38 | 47 | |
| 39 | 48 | /** A block's state in words. */ |
| @@ -50,6 +59,15 @@ export function blockSays(b: Block, box: Pick<GameBox, "name">): string { | ||
| 50 | 59 | } |
| 51 | 60 | } |
| 52 | 61 | |
| 62 | /** | |
| 63 | * A service's last commands as blocks, oldest first, for who may `act` on it: its operators and the | |
| 64 | * box's owner. A viewer reads the log, never the commands or what they printed. | |
| 65 | */ | |
| 66 | export const serviceBlocks = (app: App, boxId: string, service: string, act: boolean): Block[] => | |
| 67 | (act ? recentCommands(app.db, boxId, service, 10) : []) | |
| 68 | .reverse() | |
| 69 | .map((c) => blockOf(c, c.kind === "world" ? worldWords(c.text) : c.kind === "rcon" ? c.text : `${c.kind} ${c.text}`.trim(), c.kind === "rcon")); | |
| 70 | ||
| 53 | 71 | /** |
| 54 | 72 | * For a stream: each call gives the blocks whose state is not the one last told. `known` is what |
| 55 | 73 | * the reader already shows (`id:state`, with commas), so an answer between its page and its stream, |
src/tui/screens/games.ts +37 −15
| @@ -15,17 +15,19 @@ | ||
| 15 | 15 | import { movedKey } from "./moved_key.ts"; |
| 16 | 16 | import { TALK_WORDS, talk } from "../../actions/talk.ts"; |
| 17 | 17 | import { emptyText, START_BOX } from "../../core/empty_words.ts"; |
| 18 | import { consoleText, crashOf } from "../../games/console.ts"; | |
| 18 | import { answerAfter, gameLogAge, gameLogPage, plainLine, withAnswerLines } from "../../logs/game.ts"; | |
| 19 | import { ageWords, type LogPage } from "../../logs/page.ts"; | |
| 20 | import { LogPane } from "../ui/log_pane.ts"; | |
| 19 | 21 | import { commitPolicy, policyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts"; |
| 20 | 22 | import { queueShell } from "../../games/shell.ts"; |
| 21 | import { AUDIT_SAYS, blockSays, shellBlocks, shellSays } from "../../terminal/blocks.ts"; | |
| 23 | import { AUDIT_SAYS, blockSays, serviceBlocks, shellBlocks, shellSays, type Block } from "../../terminal/blocks.ts"; | |
| 22 | 24 | import { watchBox } from "../../games/notify.ts"; |
| 23 | 25 | import { containersIn, figuresOf } from "../../cloud/containers.ts"; |
| 24 | 26 | import { joinAddress, NO_ADDRESS, nowWords, powerNow, PREVIEW_WORDS, privateWords, SAVE_WORDS } from "../../games/gist.ts"; |
| 25 | 27 | import { findingLine, findingsOf as kickFindingsOf } from "../../games/findings.ts"; |
| 26 | 28 | import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts"; |
| 27 | 29 | import { findingsOf } from "../../games/player_events.ts"; |
| 28 | import { queueWorld, worldWords, type WorldOp } from "../../games/worlds.ts"; | |
| 30 | import { queueWorld, type WorldOp } from "../../games/worlds.ts"; | |
| 29 | 31 | import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts"; |
| 30 | 32 | import { spareRow } from "../../games/spare_row.ts"; |
| 31 | 33 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| @@ -36,7 +38,6 @@ import { getUserByName } from "../../core/users.ts"; | ||
| 36 | 38 | import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts"; |
| 37 | 39 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| 38 | 40 | import { |
| 39 | commandSays, | |
| 40 | 41 | SERVICE_NAME, |
| 41 | 42 | boxNamed, |
| 42 | 43 | bootTroubled, |
| @@ -44,11 +45,9 @@ import { | ||
| 44 | 45 | grant, |
| 45 | 46 | grantsOf, |
| 46 | 47 | listBoxes, |
| 47 | logsOf, | |
| 48 | 48 | mayDo, |
| 49 | 49 | commandHistory, |
| 50 | 50 | queueCommand, |
| 51 | recentCommands, | |
| 52 | 51 | roleOn, |
| 53 | 52 | seesAnyBox, |
| 54 | 53 | seesBox, |
| @@ -294,6 +293,24 @@ type Part = (typeof PARTS)[number]; | ||
| 294 | 293 | */ |
| 295 | 294 | export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: string): Screen { |
| 296 | 295 | let part: Part = "console"; |
| 296 | const blocks = (): Block[] => serviceBlocks(f.app, box.id, service, operator()); | |
| 297 | const blockLines = (b: Block): string[] => [`${b.typed ? "$ " : ""}${b.text}`, ...(b.output === "" ? [] : b.output.split("\n")), `(${blockSays(b, box)})`]; | |
| 298 | // The kept log is read again when the box sent it again, not at each key. | |
| 299 | let kept: { of: string; page: LogPage } | undefined; | |
| 300 | const pane = new LogPane( | |
| 301 | ctx, | |
| 302 | () => { | |
| 303 | const age = gameLogAge(f.app.db, box.id, service); | |
| 304 | const answered = blocks().flatMap((b) => { | |
| 305 | const after = answerAfter(f.app.db, box.id, service, b); | |
| 306 | return after === null ? [] : [{ after, id: b.id, lines: blockLines(b) }]; | |
| 307 | }); | |
| 308 | const of = `${age.lastLine} ${age.lastHeard} ${answered.map((a) => a.id).join(" ")}`; | |
| 309 | if (kept?.of !== of) kept = { of, page: withAnswerLines(gameLogPage(f.app.db, box.id, service), answered) }; | |
| 310 | return { page: kept.page, age: ageWords(age) }; | |
| 311 | }, | |
| 312 | plainLine, | |
| 313 | ); | |
| 297 | 314 | let note = ""; |
| 298 | 315 | let compose: string | undefined; |
| 299 | 316 | let loaded = false; |
| @@ -309,13 +326,9 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 309 | 326 | ctx.invalidate(); |
| 310 | 327 | }; |
| 311 | 328 | const lines = (): string[] => { |
| 312 | if (part === "console") { | |
| 313 | // A world command's link shows as host and path only: its query string may be a signed secret. | |
| 314 | const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.kind === "world" ? worldWords(c.text) : c.text} ${commandSays(c).split("\n")[0]}`); | |
| 315 | // The game's colour codes read as plain text here; a crash leads, in one line. | |
| 316 | const crash = crashOf(logsOf(f.app.db, box.id, service, 2_000).lines); | |
| 317 | return [...(crash === undefined ? [] : [crash.summary]), ...consoleText(logsOf(f.app.db, box.id, service, 200).lines), ...done]; | |
| 318 | } | |
| 329 | if (part === "console") | |
| 330 | // What still waits; an answer stands in the log, under the line it came after. | |
| 331 | return blocks().filter((b) => b.at === "").flatMap(blockLines); | |
| 319 | 332 | if (part === "people") { |
| 320 | 333 | const { online, lists } = peopleOf(f.app.db, box.id, service); |
| 321 | 334 | const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`; |
| @@ -369,6 +382,11 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 369 | 382 | title: `${box.name}/${service}`, |
| 370 | 383 | keys: [ |
| 371 | 384 | binding(["tab"], "console, env, people, world"), |
| 385 | binding(["/"], "find in the log"), | |
| 386 | binding(["enter"], "a line in its place, or whole"), | |
| 387 | binding(["v"], "pick lines"), | |
| 388 | binding(["y"], "copy"), | |
| 389 | binding(["G"], "end of the log, and follow"), | |
| 372 | 390 | binding([":"], "rcon"), |
| 373 | 391 | binding(["e"], "set env"), |
| 374 | 392 | binding(["m"], "mods"), |
| @@ -390,10 +408,14 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 390 | 408 | const tabs = PARTS.map((p) => (p === part ? `[${p}]` : p)).join(" "); |
| 391 | 409 | s.text(head!.x, head!.y, truncate(note === "" ? tabs : `${tabs} · ${note}`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
| 392 | 410 | const all = lines(); |
| 393 | const shown = part === "console" ? all.slice(-body!.h) : all.slice(0, body!.h); | |
| 394 | shown.forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w)); | |
| 411 | // The log, with the commands that still wait under it. | |
| 412 | const foot = part === "console" ? Math.min(all.length, body!.h >> 1) : body!.h; | |
| 413 | const [log, under] = part === "console" ? split(body!, "v", [fill(1), len(foot)]) : [undefined, body]; | |
| 414 | if (log !== undefined) pane.render(log, s); | |
| 415 | all.slice(0, foot).forEach((l, i) => s.text(under!.x, under!.y + i, truncate(l, under!.w), style(c.fg, c.bg), under!.x + under!.w)); | |
| 395 | 416 | }, |
| 396 | 417 | key(e) { |
| 418 | if (part === "console" && pane.key(e)) return true; | |
| 397 | 419 | if (e.ctrl || e.alt) return false; |
| 398 | 420 | if (e.key === "tab") { |
| 399 | 421 | part = PARTS[(PARTS.indexOf(part) + 1) % PARTS.length]!; |
src/tui/ui/log_pane.ts added +134
| @@ -0,0 +1,134 @@ | ||
| 1 | /** | |
| 2 | * A log in the terminal (`logs/page.ts`): its age, what matters, the filter, the lines. `enter` on a | |
| 3 | * match shows it in its place, `esc` goes back; `y` copies, `v` picks a range first. | |
| 4 | */ | |
| 5 | ||
| 6 | import { matchesLog, type LogLine, type LogPage } from "../../logs/page.ts"; | |
| 7 | import type { Ctx } from "../app/app.ts"; | |
| 8 | import type { KeyEvent } from "../term/input.ts"; | |
| 9 | import type { Rect, Screen as Surface } from "../term/screen.ts"; | |
| 10 | import { style } from "../term/style.ts"; | |
| 11 | import { truncate, wrap } from "../term/width.ts"; | |
| 12 | import { Filter, Scroll } from "../screens/common.ts"; | |
| 13 | ||
| 14 | /** The log's own lines: an answer's, between two of them, is not one it keeps. */ | |
| 15 | const kept = (lines: readonly { readonly id: number }[]): number => lines.filter((l) => Number.isInteger(l.id)).length; | |
| 16 | ||
| 17 | export class LogPane { | |
| 18 | private readonly filter = new Filter(); | |
| 19 | private readonly scroll = new Scroll(); | |
| 20 | /** The line the keys act on, by id; null follows the end. */ | |
| 21 | private at: number | null = null; | |
| 22 | private from: number | null = null; | |
| 23 | /** The match shown in its place, and so the way back. */ | |
| 24 | private placed: number | null = null; | |
| 25 | /** The long line shown whole. */ | |
| 26 | private whole: number | null = null; | |
| 27 | ||
| 28 | /** `read` is called at each draw; `plain` is a line as a person reads it. */ | |
| 29 | constructor( | |
| 30 | private readonly ctx: Pick<Ctx, "copy" | "toast" | "invalidate" | "theme">, | |
| 31 | private readonly read: () => { page: LogPage; age: string }, | |
| 32 | private readonly plain: (text: string) => string, | |
| 33 | ) {} | |
| 34 | ||
| 35 | /** Whether a typed letter belongs to the filter. */ | |
| 36 | get typing(): boolean { | |
| 37 | return this.filter.active; | |
| 38 | } | |
| 39 | ||
| 40 | private lines(): { id: number; text: string }[] { | |
| 41 | const all = this.read().page.lines.map((l: LogLine) => ({ id: l.id, text: this.plain(l.text) })); | |
| 42 | return this.filter.query === "" || this.placed !== null ? all : all.filter((l) => matchesLog(l.text, this.filter.query)); | |
| 43 | } | |
| 44 | ||
| 45 | private index(lines: readonly { id: number }[]): number { | |
| 46 | if (this.at === null) return lines.length - 1; | |
| 47 | const i = lines.findIndex((l) => l.id >= this.at!); | |
| 48 | return i < 0 ? lines.length - 1 : i; | |
| 49 | } | |
| 50 | ||
| 51 | render(area: Rect, s: Surface): void { | |
| 52 | const c = this.ctx.theme.c; | |
| 53 | const right = area.x + area.w; | |
| 54 | let y = area.y; | |
| 55 | const say = (text: string, fg = c.mutedFg): void => { | |
| 56 | if (y < area.y + area.h) s.text(area.x, y++, truncate(text, area.w), style(fg, c.bg), right); | |
| 57 | }; | |
| 58 | const { page, age } = this.read(); | |
| 59 | const lines = this.lines(); | |
| 60 | say(age); | |
| 61 | if (page.finding !== undefined) say(page.finding.says, c.danger); | |
| 62 | if (this.filter.on) | |
| 63 | say(`/${this.filter.query}${this.filter.active ? "_" : ""} ${this.placed !== null ? "in its place, esc goes back" : `${String(kept(lines))} of ${String(kept(page.lines))} kept lines`}`); | |
| 64 | if (lines.length === 0) return say(this.filter.query === "" ? "Nothing has been written yet." : `No line matches "${this.filter.query}".`); | |
| 65 | const height = Math.max(1, area.y + area.h - y); | |
| 66 | const at = this.index(lines); | |
| 67 | const top = Math.max(0, Math.min(this.at === null ? lines.length : at - (height >> 1), lines.length - height)); | |
| 68 | this.scroll.window(height, lines.length); | |
| 69 | if (top === 0 && page.older !== undefined && this.at !== null && at < height >> 1) say(page.older); | |
| 70 | const picked = this.from === null ? at : Math.max(0, lines.findIndex((l) => l.id === this.from)); | |
| 71 | const [lo, hi] = [Math.min(at, picked), Math.max(at, picked)]; | |
| 72 | for (let i = top; i < lines.length && y < area.y + area.h; i++) { | |
| 73 | const l = lines[i]!; | |
| 74 | const on = this.at !== null && i >= lo && i <= hi; | |
| 75 | for (const part of l.id === this.whole ? wrap(l.text, Math.max(1, area.w - 2)) : [l.text]) say(`${on ? "> " : " "}${part}`, c.fg); | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | /** True when the key was the log's. */ | |
| 80 | key(e: KeyEvent): boolean { | |
| 81 | const was = this.filter.active; | |
| 82 | if (was || (e.key === "/" && !e.ctrl && !e.alt)) { | |
| 83 | if (!this.filter.key(e)) return false; | |
| 84 | this.at = this.from = this.placed = null; | |
| 85 | this.ctx.invalidate(); | |
| 86 | return true; | |
| 87 | } | |
| 88 | if (!this.act(e)) return false; | |
| 89 | this.ctx.invalidate(); | |
| 90 | return true; | |
| 91 | } | |
| 92 | ||
| 93 | private act(e: KeyEvent): boolean { | |
| 94 | const lines = this.lines(); | |
| 95 | if (e.key === "esc") { | |
| 96 | if (this.from !== null) this.from = null; | |
| 97 | else if (this.whole !== null) this.whole = null; | |
| 98 | else if (this.placed !== null) [this.at, this.placed] = [this.placed, null]; | |
| 99 | else if (this.filter.query !== "") [this.filter.query, this.at] = ["", null]; | |
| 100 | else return false; | |
| 101 | return true; | |
| 102 | } | |
| 103 | if (lines.length === 0) return false; | |
| 104 | const at = this.index(lines); | |
| 105 | this.scroll.top = at; | |
| 106 | if (this.scroll.key(e, lines.length)) { | |
| 107 | // The end follows; with a range begun it stays a line, so the range keeps its end. | |
| 108 | this.at = this.from === null && this.scroll.top >= lines.length - 1 && e.key !== "k" && e.key !== "up" ? null : lines[this.scroll.top]!.id; | |
| 109 | return true; | |
| 110 | } | |
| 111 | if (e.ctrl || e.alt) return false; | |
| 112 | const here = lines[at]!.id; | |
| 113 | if (e.key === "enter") { | |
| 114 | if (this.filter.query !== "" && this.placed === null) this.at = this.placed = here; | |
| 115 | else { | |
| 116 | this.at = here; | |
| 117 | this.whole = this.whole === here ? null : here; | |
| 118 | } | |
| 119 | return true; | |
| 120 | } | |
| 121 | if (e.key === "v") { | |
| 122 | this.at = here; | |
| 123 | this.from = this.from === null ? here : null; | |
| 124 | return true; | |
| 125 | } | |
| 126 | if (e.key !== "y") return false; | |
| 127 | const from = this.from === null ? at : Math.max(0, lines.findIndex((l) => l.id === this.from)); | |
| 128 | const picked = lines.slice(Math.min(at, from), Math.max(at, from) + 1); | |
| 129 | this.ctx.copy(picked.map((l) => l.text).join("\n")); | |
| 130 | this.ctx.toast(`Sent ${picked.length === 1 ? "a line" : `${String(picked.length)} lines`} to your clipboard.`); | |
| 131 | this.from = null; | |
| 132 | return true; | |
| 133 | } | |
| 134 | } |
src/web/log_reader.ts added +166
| @@ -0,0 +1,166 @@ | ||
| 1 | /** | |
| 2 | * A log on a page (`logs/page.ts`): how old it is, what matters, the filter, the lines. The forge draws | |
| 3 | * and masks every line; the script only adds the ones that come, so with no script a reload does it. | |
| 4 | */ | |
| 5 | ||
| 6 | import { consoleHtml } from "../games/console.ts"; | |
| 7 | import { plainLine } from "../logs/game.ts"; | |
| 8 | import { ageWords, markLog, matchesLog, type LogAge, type LogLine, type LogPage } from "../logs/page.ts"; | |
| 9 | import { html, raw, type Html } from "./html.ts"; | |
| 10 | import { btn, disclosure } from "./ui.ts"; | |
| 11 | ||
| 12 | /** Lines a page opens with, and the lines around one opened in its place. */ | |
| 13 | const FIRST = 300; | |
| 14 | const AROUND = 150; | |
| 15 | ||
| 16 | export interface LogView { | |
| 17 | /** The page's own address: the filter is `?log=` on it, a line `?at=<id>`. */ | |
| 18 | readonly base: string; | |
| 19 | readonly name: string; | |
| 20 | readonly q: string; | |
| 21 | /** A line to show in its place, with everything around it; the filter stays in the address for the way back. */ | |
| 22 | readonly at: number | null; | |
| 23 | /** The lines as kept, § codes and all. */ | |
| 24 | readonly raw: boolean; | |
| 25 | } | |
| 26 | ||
| 27 | /** The view an address asks for. */ | |
| 28 | export function logViewOf(url: URL, base: string, name: string): LogView { | |
| 29 | const at = Number(url.searchParams.get("at")); | |
| 30 | return { base, name, q: (url.searchParams.get("log") ?? "").trim().slice(0, 200), at: Number.isSafeInteger(at) && at > 0 ? at : null, raw: url.searchParams.get("raw") === "1" }; | |
| 31 | } | |
| 32 | ||
| 33 | const hrefOf = (v: LogView, change: { q?: string; at?: number; raw?: boolean }): string => { | |
| 34 | const p = new URLSearchParams(); | |
| 35 | const q = change.q ?? v.q; | |
| 36 | if (q !== "") p.set("log", q); | |
| 37 | if (change.at !== undefined) p.set("at", String(change.at)); | |
| 38 | if (change.raw ?? v.raw) p.set("raw", "1"); | |
| 39 | return `${v.base}${p.size === 0 ? "" : `?${p.toString()}`}#${change.at === undefined ? "console" : `l${String(change.at)}`}`; | |
| 40 | }; | |
| 41 | ||
| 42 | /** The lines a view holds: while one is shown in its place, nothing is filtered. */ | |
| 43 | const held = (v: LogView, lines: readonly LogLine[]): readonly LogLine[] => | |
| 44 | v.q === "" || v.at !== null ? lines : lines.filter((l) => matchesLog(plainLine(l.text), v.q)); | |
| 45 | ||
| 46 | /** One row a line, as the first paint and the stream both draw it. A line's address comes first and is never copied. */ | |
| 47 | export function logRows(v: LogView, lines: readonly LogLine[]): { id: number; html: string }[] { | |
| 48 | const finding = v.q !== "" && v.at === null; | |
| 49 | return held(v, lines).map((l) => { | |
| 50 | const text = v.raw | |
| 51 | ? html`${l.text}` | |
| 52 | : finding | |
| 53 | ? html`${markLog(plainLine(l.text), v.q).map((p) => (p.hit ? html`<mark>${p.text}</mark>` : html`${p.text}`))}` | |
| 54 | : raw(consoleHtml([l.text])[0]!); | |
| 55 | const id = String(l.id); | |
| 56 | return { id: l.id, html: html`<span class="log-row" id="l${id}"><a class="log-at" href="${hrefOf(v, { at: l.id })}" aria-label="This line in its place"${finding ? null : raw(' tabindex="-1"')}></a>${text} | |
| 57 | </span>`.toString() }; | |
| 58 | }); | |
| 59 | } | |
| 60 | ||
| 61 | /** The rows with each answer under the line it stands after; one older than every row shown leads them. */ | |
| 62 | function withAnswers(rows: readonly { id: number; html: string }[], answers: readonly { after: number; html: string }[]): string { | |
| 63 | const left = [...answers].sort((a, b) => a.after - b.after); | |
| 64 | const out: string[] = []; | |
| 65 | for (const r of rows) { | |
| 66 | while (left.length > 0 && left[0]!.after < r.id) out.push(left.shift()!.html); | |
| 67 | out.push(r.html); | |
| 68 | } | |
| 69 | return [...out, ...left.map((a) => a.html)].join(""); | |
| 70 | } | |
| 71 | ||
| 72 | /** Whether a view has a place for answers among its lines: all the lines, up to the newest. */ | |
| 73 | export const placesAnswers = (v: LogView): boolean => v.q === "" && v.at === null; | |
| 74 | ||
| 75 | /** The reader. `answers` are drawn blocks, for a view that places them; `footer` is what is typed at the log's source, when anything is. */ | |
| 76 | export function logReader(asked: LogView, page: LogPage, age: LogAge, o: { stream: string; answers?: readonly { after: number; html: string }[]; findingExtra?: Html | null; footer?: Html | null }): Html { | |
| 77 | const at = asked.at === null ? -1 : page.lines.findIndex((l) => l.id === asked.at); | |
| 78 | const placed = at >= 0; | |
| 79 | // A line no longer kept: the view is the one without it, and says so. | |
| 80 | const v = placed ? asked : { ...asked, at: null }; | |
| 81 | const all = held(v, page.lines); | |
| 82 | const shown = placed ? all.slice(Math.max(0, at - AROUND), at + AROUND) : all.slice(-FIRST); | |
| 83 | const kept = `${page.lines.length.toLocaleString("en-US")} kept ${page.lines.length === 1 ? "line" : "lines"}`; | |
| 84 | const found = v.q === "" || v.at !== null ? "" : `${all.length.toLocaleString("en-US")} of ${kept}${all.length > shown.length ? `, the newest ${String(shown.length)} shown` : ""}.`; | |
| 85 | const f = page.finding; | |
| 86 | return html`<div class="log-reader"> | |
| 87 | <p id="log-age" class="muted small">${ageWords(age)}</p> | |
| 88 | ${f === undefined | |
| 89 | ? null | |
| 90 | : html`<div class="notice danger" role="alert"> | |
| 91 | <p><strong>${f.says}</strong>${f.line === null ? null : html` <a href="${hrefOf(v, { at: f.line })}">Show it in the log</a>`}</p> | |
| 92 | ${disclosure("The crash", html`<pre class="run-log mono" tabindex="0" aria-label="The crash of ${v.name}">${raw(consoleHtml(f.detail).join("\n"))}</pre>`, { small: true })} | |
| 93 | ${o.findingExtra ?? null} | |
| 94 | </div>`} | |
| 95 | <form method="get" action="${v.base}#console" class="row-fields" role="search"> | |
| 96 | ${v.raw ? html`<input type="hidden" name="raw" value="1" />` : null} | |
| 97 | <input class="input" type="search" name="log" value="${v.q}" maxlength="200" placeholder="Find in the log" aria-label="Find in the log of ${v.name}" autocomplete="off" /> | |
| 98 | ${btn("Find", { type: "submit", variant: "secondary" })} | |
| 99 | <button type="button" class="btn" data-copy="log">Copy</button> | |
| 100 | </form> | |
| 101 | <p class="small"> | |
| 102 | <span role="status">${found}</span> | |
| 103 | ${asked.at !== null && !placed ? html`<span>That line is no longer kept; the newest are shown.</span>` : null} | |
| 104 | ${v.at !== null ? html`<a href="${hrefOf(v, {})}">${v.q === "" ? "Back to the newest" : "Back to the matches"}</a>` : v.q === "" ? null : html`<a href="${hrefOf(v, { q: "" })}">Clear the filter</a>`} | |
| 105 | <a href="${hrefOf(v, { raw: !v.raw })}">${v.raw ? "Show it in colour" : "Show it as the game wrote it (raw)"}</a> | |
| 106 | </p> | |
| 107 | ${page.older === undefined || shown[0]?.id !== page.lines[0]?.id ? null : html`<p class="log-gap muted small">${page.older}</p>`} | |
| 108 | <pre id="log" class="run-log mono" tabindex="0" aria-label="Console of ${v.name}"${v.raw ? raw(' data-raw="1"') : null}${placed ? raw(` data-at="l${String(v.at)}"`) : html` data-stream="${o.stream}" data-last="${String(page.lines.at(-1)?.id ?? 0)}" data-q="${v.q}"`}>${raw(withAnswers(logRows(v, shown), o.answers ?? []))}</pre> | |
| 109 | ${shown.length > 0 ? null : html`<p id="log-empty" class="muted small">${v.q === "" ? "Nothing has been written yet." : `No line matches "${v.q}".`}</p>`} | |
| 110 | <p><button type="button" id="log-newer" class="btn" hidden></button></p> | |
| 111 | ${o.footer ?? null} | |
| 112 | </div>`; | |
| 113 | } | |
| 114 | ||
| 115 | /** Said in the lines where a reader was away for more than is kept. */ | |
| 116 | export const LOG_GONE = '<span class="log-gap muted">Some lines may be missing here: more came than are kept.\n</span>'; | |
| 117 | ||
| 118 | export const LOG_READER_CSS = `.log-row { display: block; white-space: pre-wrap; } | |
| 119 | .log-at { user-select: none; -webkit-user-select: none; color: var(--faint); text-decoration: none; } | |
| 120 | .log-at::before { content: "\\203A\\00A0"; } | |
| 121 | .log-row:target { outline: 1px solid var(--attn); } | |
| 122 | .log-row mark { font-weight: 700; } | |
| 123 | > [data-block] { white-space: normal; } | |
| 124 | `; | |
| 125 | ||
| 126 | /** Opens the page's one stream, kept on `` for the blocks of a footer (`terminal_blocks.ts`). */ | |
| 127 | export const logReaderJs = /* js */ ` | |
| 128 | (function () { | |
| 129 | var log = document.getElementById('log'); | |
| 130 | if (!log) return; | |
| 131 | var at = log.getAttribute('data-at') && document.getElementById(log.getAttribute('data-at')); | |
| 132 | if (at) { log.scrollTop = at.offsetTop - log.offsetTop - log.clientHeight / 3; return; } | |
| 133 | log.scrollTop = log.scrollHeight; | |
| 134 | if (typeof EventSource === 'undefined') return; | |
| 135 | var last = Number(log.getAttribute('data-last')) || 0, newer = 0; | |
| 136 | var age = document.getElementById('log-age'), more = document.getElementById('log-newer'); | |
| 137 | var blocks = document.querySelectorAll('[data-block]'); | |
| 138 | var known = Array.prototype.map.call(blocks, function (b) { return b.getAttribute('data-block'); }).join(','); | |
| 139 | var es = new EventSource(log.getAttribute('data-stream') + '?after=' + last + '&known=' + encodeURIComponent(known) + | |
| 140 | '&log=' + encodeURIComponent(log.getAttribute('data-q') || '') + (log.hasAttribute('data-raw') ? '&raw=1' : '')); | |
| 141 | log.forgeStream = es; | |
| 142 | function say() { if (more) { more.hidden = newer === 0; more.textContent = newer + ' newer'; } } | |
| 143 | function end() { log.scrollTop = log.scrollHeight; newer = 0; say(); } | |
| 144 | if (more) more.addEventListener('click', end); | |
| 145 | function atEnd() { return log.scrollTop + log.clientHeight >= log.scrollHeight - 8; } | |
| 146 | log.addEventListener('scroll', function () { if (newer && atEnd()) { newer = 0; say(); } }); | |
| 147 | es.addEventListener('lines', function (e) { | |
| 148 | var d; try { d = JSON.parse(e.data); } catch (_) { return; } | |
| 149 | var stick = atEnd(), added = 0; | |
| 150 | // Drawn and escaped by the forge. A reconnect asks from the page's first mark, so what is here is skipped. | |
| 151 | var rows = (d.rows || []).filter(function (r) { return r.id > last; }); | |
| 152 | if (rows.length && d.gone) log.insertAdjacentHTML('beforeend', d.gone); | |
| 153 | rows.forEach(function (r) { log.insertAdjacentHTML('beforeend', r.html); last = r.id; added++; }); | |
| 154 | while (log.children.length > 2000) log.removeChild(log.firstElementChild); | |
| 155 | var empty = added && document.getElementById('log-empty'); | |
| 156 | if (empty) empty.remove(); | |
| 157 | if (stick) log.scrollTop = log.scrollHeight; else if (added) { newer += added; say(); } | |
| 158 | if (age && d.age) age.textContent = d.age; | |
| 159 | var now = document.getElementById('game-now'); | |
| 160 | if (now && d.now) now.textContent = d.now; | |
| 161 | var figures = document.getElementById('game-figures'); | |
| 162 | if (figures && typeof d.figures === 'string') figures.textContent = d.figures; | |
| 163 | }); | |
| 164 | es.onerror = function () { if (age) age.textContent = 'Reconnecting.'; }; | |
| 165 | })(); | |
| 166 | `; |
src/web/pages/games.ts +64 −127
| @@ -12,8 +12,9 @@ import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate | ||
| 12 | 12 | import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts"; |
| 13 | 13 | import { packCheckLines } from "../../games/pack_check.ts"; |
| 14 | 14 | import { queueShell } from "../../games/shell.ts"; |
| 15 | import { blockChanges, blockSays, shellBlocks, shellSays } from "../../terminal/blocks.ts"; | |
| 16 | import { blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts"; | |
| 15 | import { getUserById, getUserByName } from "../../core/users.ts"; | |
| 16 | import { blockChanges, serviceBlocks, shellBlocks, shellSays } from "../../terminal/blocks.ts"; | |
| 17 | import { blockEvent, blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts"; | |
| 17 | 18 | import { statusRow } from "./security.ts"; |
| 18 | 19 | import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts"; |
| 19 | 20 | import { spareRow } from "../../games/spare_row.ts"; |
| @@ -23,8 +24,6 @@ import { askPower, isPower, refusesNow, type Power } from "../../games/power.ts" | ||
| 23 | 24 | import { docHref } from "./docs_link.ts"; |
| 24 | 25 | import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts"; |
| 25 | 26 | import { |
| 26 | answersOf, | |
| 27 | commandSays, | |
| 28 | 27 | bootWords, |
| 29 | 28 | boxNamed, |
| 30 | 29 | grant, |
| @@ -37,7 +36,6 @@ import { | ||
| 37 | 36 | listBoxes, |
| 38 | 37 | logsOf, |
| 39 | 38 | mayDo, |
| 40 | commandHistory, | |
| 41 | 39 | queueCommand, |
| 42 | 40 | recentCommands, |
| 43 | 41 | roleOn, |
| @@ -53,14 +51,16 @@ import { | ||
| 53 | 51 | } from "../../games/store.ts"; |
| 54 | 52 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 55 | 53 | import { MASK, secretKey } from "../../core/secret_text.ts"; |
| 56 | import { getUserByName } from "../../core/users.ts"; | |
| 57 | 54 | import { BODY_CAPS } from "../../kernel/body_caps.ts"; |
| 58 | 55 | import type { Ctx } from "../../http/context.ts"; |
| 59 | 56 | import { eventStream } from "../../http/sse.ts"; |
| 60 | 57 | import { notFoundPage, pageHead, signInFirst } from "../chrome.ts"; |
| 61 | 58 | import { field, readForm, type Form } from "../form.ts"; |
| 62 | import { html, raw, type Html } from "../html.ts"; | |
| 63 | import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "../../games/console.ts"; | |
| 59 | import { html, type Html } from "../html.ts"; | |
| 60 | import { consoleText, shareOnMclogs } from "../../games/console.ts"; | |
| 61 | import { answerAfter, gameLogAfter, gameLogAge, gameLogPage } from "../../logs/game.ts"; | |
| 62 | import { ageWords } from "../../logs/page.ts"; | |
| 63 | import { LOG_GONE, logReader, LOG_READER_CSS, logReaderJs, logRows, logViewOf, placesAnswers } from "../log_reader.ts"; | |
| 64 | 64 | import { flashTo, page } from "../layout.ts"; |
| 65 | 65 | import { avatar, badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts"; |
| 66 | 66 | import { watchBox } from "../../games/notify.ts"; |
| @@ -72,7 +72,7 @@ import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../ac | ||
| 72 | 72 | import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts"; |
| 73 | 73 | import { defaultHeadResponse, headResponse } from "../../games/heads.ts"; |
| 74 | 74 | import { eventsOf, eventWords, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts"; |
| 75 | import { queueWorld, undoOf, worldWords } from "../../games/worlds.ts"; | |
| 75 | import { queueWorld, undoOf } from "../../games/worlds.ts"; | |
| 76 | 76 | import { START_BOX } from "../../core/empty_words.ts"; |
| 77 | 77 | import { emptyLine, emptyNote } from "../empty_words.ts"; |
| 78 | 78 | import { findingsOf, type GameFinding } from "../../games/player_events.ts"; |
| @@ -382,7 +382,7 @@ export function gameShellStream(ctx: Ctx): Response { | ||
| 382 | 382 | // No longer the box's owner: nothing more is said. |
| 383 | 383 | if (blocks === undefined) return close(); |
| 384 | 384 | const changed = changes(blocks); |
| 385 | if (changed.length > 0) emit("blocks", { blocks: changed.map((b) => ({ id: b.id, says: blockSays(b, box), html: blockHtml(b, box).toString() })) }); | |
| 385 | if (changed.length > 0) emit("blocks", { blocks: changed.map((b) => blockEvent(b, box)) }); | |
| 386 | 386 | }), |
| 387 | 387 | ); |
| 388 | 388 | } |
| @@ -493,46 +493,6 @@ function grantsBlock(ctx: Ctx, box: GameBox): Html { | ||
| 493 | 493 | </section>`; |
| 494 | 494 | } |
| 495 | 495 | |
| 496 | /** The console's client: the live log over the page's own stream, appended in place. */ | |
| 497 | export const gamesConsoleJs = /* js */ ` | |
| 498 | (function () { | |
| 499 | var log = document.getElementById('game-log'); | |
| 500 | if (!log || typeof EventSource === 'undefined') return; | |
| 501 | var es = new EventSource(log.getAttribute('data-stream') + '?after=' + (log.getAttribute('data-last') || '0')); | |
| 502 | es.addEventListener('lines', function (e) { | |
| 503 | var d; try { d = JSON.parse(e.data); } catch (_) { return; } | |
| 504 | var stick = log.scrollTop + log.clientHeight >= log.scrollHeight - 8; | |
| 505 | // Each line comes drawn by the forge (escaped markup in fixed colour classes). | |
| 506 | // Raw: the lines as kept, as text; else as the forge drew them (escaped markup in fixed classes). | |
| 507 | if (log.hasAttribute('data-raw')) (d.lines || []).forEach(function (l) { log.appendChild(document.createTextNode(l + '\\n')); }); | |
| 508 | else (d.html || []).forEach(function (h) { log.insertAdjacentHTML('beforeend', h + '\\n'); }); | |
| 509 | if (stick) log.scrollTop = log.scrollHeight; | |
| 510 | var now = document.getElementById('game-now'); | |
| 511 | if (now && d.now) now.textContent = d.now; | |
| 512 | var figures = document.getElementById('game-figures'); | |
| 513 | if (figures && typeof d.figures === 'string') figures.textContent = d.figures; | |
| 514 | (d.results || []).forEach(function (r) { | |
| 515 | var el = document.getElementById('cmd-' + r.id); | |
| 516 | if (el) el.textContent = r.says; | |
| 517 | }); | |
| 518 | }); | |
| 519 | // The command box walks its history with up and down, as a terminal does. | |
| 520 | var input = document.getElementById('game-command'); | |
| 521 | var list = document.getElementById('game-history'); | |
| 522 | if (!input || !list) return; | |
| 523 | var at = -1, typed = ''; | |
| 524 | input.addEventListener('keydown', function (e) { | |
| 525 | if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return; | |
| 526 | var past = Array.prototype.map.call(list.options, function (o) { return o.value; }); | |
| 527 | if (past.length === 0) return; | |
| 528 | e.preventDefault(); | |
| 529 | if (at === -1) typed = input.value; | |
| 530 | at = Math.max(-1, Math.min(past.length - 1, at + (e.key === 'ArrowUp' ? 1 : -1))); | |
| 531 | input.value = at === -1 ? typed : past[at]; | |
| 532 | }); | |
| 533 | })(); | |
| 534 | `; | |
| 535 | ||
| 536 | 496 | // GET /games/:box/:service |
| 537 | 497 | export async function gameServicePage(ctx: Ctx): Promise<Response> { |
| 538 | 498 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| @@ -542,12 +502,6 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 542 | 502 | const { box, role } = got; |
| 543 | 503 | if (!SERVICE_NAME.test(service)) return notFoundPage(ctx); |
| 544 | 504 | const act = mayDo(role, "operator"); |
| 545 | const tail = logsOf(ctx.app.db, box.id, service, 300); | |
| 546 | // A crash is looked for in the whole kept log, so a long report is not missed by the tail. | |
| 547 | const crash = crashOf(logsOf(ctx.app.db, box.id, service, 2_000).lines); | |
| 548 | const history = act ? commandHistory(ctx.app.db, box.id, service) : []; | |
| 549 | // Raw: the lines exactly as kept, § codes and all; the console's own view draws them. | |
| 550 | const rawView = ctx.url.searchParams.get("raw") === "1"; | |
| 551 | 505 | const shared = /^[A-Za-z0-9]{1,32}$/.test(ctx.url.searchParams.get("shared") ?? "") ? ctx.url.searchParams.get("shared")! : ""; |
| 552 | 506 | const compose = await readCompose(ctx.app, box); |
| 553 | 507 | const held = await heldNotice(ctx, box, compose); |
| @@ -571,6 +525,15 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 571 | 525 | const pinned = compose !== undefined && act && proxyOf(compose.text) === service ? await pinnedBlock(ctx, box, base, mayDo(role, "owner")) : undefined; |
| 572 | 526 | const commands = recentCommands(ctx.app.db, box.id, service, 5); |
| 573 | 527 | const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service); |
| 528 | const view = logViewOf(ctx.url, base, service); | |
| 529 | // An answer stands among the lines where the view shows them all, else by the input with what still waits. | |
| 530 | const blocks = serviceBlocks(ctx.app, box.id, service, act); | |
| 531 | const placed = !placesAnswers(view) | |
| 532 | ? [] | |
| 533 | : blocks.flatMap((b) => { | |
| 534 | const after = answerAfter(ctx.app.db, box.id, service, b); | |
| 535 | return after === null ? [] : [{ ...b, after }]; | |
| 536 | }); | |
| 574 | 537 | const findings = findingsOf(ctx.app.db, box.id, service); |
| 575 | 538 | // Settings: each as the compose file says; a "Preview" (s.<key>=value in the query) planned on it. |
| 576 | 539 | const settings = compose === undefined ? [] : settingsOf(compose.text, service, env); |
| @@ -579,8 +542,8 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 579 | 542 | return timePhase(ctx.request, "render", () => page({ |
| 580 | 543 | ctx, |
| 581 | 544 | title: `${service} · ${box.name}`, |
| 582 | styleCss: TOPOLOGY_CSS, | |
| 583 | scriptJs: gamesConsoleJs, | |
| 545 | styleCss: TOPOLOGY_CSS + LOG_READER_CSS, | |
| 546 | scriptJs: logReaderJs + terminalBlocksJs, | |
| 584 | 547 | body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service, seen) : undefined })} |
| 585 | 548 | ${holdNotice(ctx, box)} |
| 586 | 549 | <p class="game-now" id="game-now" aria-live="polite">${nowWords(seen, powerNow(ctx.app.db, box.id, service))}</p> |
| @@ -589,63 +552,27 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 589 | 552 | ${findingsBlock(findings)} |
| 590 | 553 | ${joinTrouble(ctx, box, service)} |
| 591 | 554 | ${peopleBlock(ctx, box, service, act)} |
| 592 | ${fold("Console", "console", rawView || shared !== "", html` | |
| 555 | ${fold("Console", "console", view.raw || view.q !== "" || view.at !== null || shared !== "", html` | |
| 593 | 556 | <section class="settings-block"> |
| 594 | <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> | |
| 595 | ${crash === undefined | |
| 596 | ? null | |
| 597 | : html`<div class="notice danger" role="alert"> | |
| 598 | <p><strong>${crash.summary}</strong></p> | |
| 599 | ${disclosure("The crash", html`<pre class="run-log mono" tabindex="0" aria-label="The crash of ${service}">${raw(consoleHtml(crash.lines).join("\n"))}</pre>`, { small: true })} | |
| 600 | ${shared !== "" | |
| 601 | ? html`<p>Shared publicly: <a href="https://mclo.gs/${shared}" rel="noreferrer noopener" target="_blank">mclo.gs/${shared}</a></p>` | |
| 602 | : act | |
| 603 | ? html`<form method="post" action="${base}/crash/share" class="row-fields"> | |
| 604 | ${btn("Share on mclo.gs", { variant: "secondary", size: "sm" })} | |
| 605 | <span class="muted small">This publishes the crash log on mclo.gs, where anyone with the link can read it.</span> | |
| 606 | </form>` | |
| 607 | : null} | |
| 608 | </div>`} | |
| 609 | <pre | |
| 610 | id="game-log" | |
| 611 | class="run-log mono" | |
| 612 | tabindex="0" | |
| 613 | aria-label="Console of ${service}" | |
| 614 | data-stream="${base}/stream" | |
| 615 | data-last="${String(tail.last)}" | |
| 616 | ${rawView ? html`data-raw="1"` : null} | |
| 617 | > | |
| 618 | ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${tail.lines.length > 0 ? "\n" : ""}</pre | |
| 619 | > | |
| 620 | ${act | |
| 621 | ? html`<form method="post" action="${base}/command" class="row-fields"> | |
| 622 | <input | |
| 623 | id="game-command" | |
| 624 | class="input mono" | |
| 625 | name="text" | |
| 626 | required | |
| 627 | maxlength="1000" | |
| 628 | placeholder="say hello" | |
| 629 | aria-label="Command for ${service}" | |
| 630 | autocomplete="off" | |
| 631 | list="game-history" | |
| 632 | /> | |
| 633 | <datalist id="game-history">${history.map((h) => html`<option value="${h}"></option>`)}</datalist> | |
| 634 | ${btn("Send", { variant: "secondary" })} | |
| 635 | </form>` | |
| 636 | : null} | |
| 637 | ${commands.length === 0 | |
| 638 | ? null | |
| 639 | : rowList( | |
| 640 | commands.map((c) => | |
| 641 | row({ | |
| 642 | title: c.kind === "world" ? worldWords(c.text) : html`<span class="mono">${c.kind} ${c.text}</span>`, | |
| 643 | meta: html`<span id="cmd-${c.id}" | |
| 644 | >${commandSays(c)}</span | |
| 645 | >`, | |
| 646 | }), | |
| 647 | ), | |
| 648 | )} | |
| 557 | ${logReader(view, gameLogPage(ctx.app.db, box.id, service), gameLogAge(ctx.app.db, box.id, service), { | |
| 558 | stream: `${base}/stream`, | |
| 559 | findingExtra: shared !== "" | |
| 560 | ? html`<p>Shared publicly: <a href="https://mclo.gs/${shared}" rel="noreferrer noopener" target="_blank">mclo.gs/${shared}</a></p>` | |
| 561 | : act | |
| 562 | ? html`<form method="post" action="${base}/crash/share" class="row-fields"> | |
| 563 | ${btn("Share on mclo.gs", { variant: "secondary", size: "sm" })} | |
| 564 | <span class="muted small">This publishes the crash log on mclo.gs, where anyone with the link can read it.</span> | |
| 565 | </form>` | |
| 566 | : null, | |
| 567 | answers: placed.map((b) => ({ after: b.after, html: blockHtml(b, box).toString() })), | |
| 568 | footer: blocksForm(blocks.filter((b) => !placed.some((p) => p.id === b.id)), box, `${base}/command`, { | |
| 569 | stream: `${base}/stream`, | |
| 570 | input: act, | |
| 571 | label: `Command for ${service}`, | |
| 572 | placeholder: "say hello", | |
| 573 | says: `Each command goes to ${service}'s own console at the box's next check-in.`, | |
| 574 | }), | |
| 575 | })} | |
| 649 | 576 | </section>`)} |
| 650 | 577 | ${numbersBlock(ctx, box, service)} |
| 651 | 578 | ${compose === undefined || !canSleep(compose.text, service) ? null : fold("Sleep", "sleep", false, sleepBlock(box, service, compose.text, seen?.asleep === true, act))} |
| @@ -977,20 +904,30 @@ export function gameServiceStream(ctx: Ctx): Response { | ||
| 977 | 904 | if (got instanceof Response) return got; |
| 978 | 905 | const { box } = got; |
| 979 | 906 | let shown = ""; |
| 980 | let after = Number(ctx.url.searchParams.get("after") ?? "0") || 0; | |
| 981 | const answers = answersOf(ctx.app.db, box.id, service); | |
| 982 | return eventStream(ctx.app, ctx.request, (emit, _close, ready) => | |
| 907 | // With no mark (a line shown in its place follows nothing), only what comes from now on. | |
| 908 | const mark = ctx.url.searchParams.get("after"); | |
| 909 | let after = mark === null ? logsOf(ctx.app.db, box.id, service, 1).last : Number(mark) || 0; | |
| 910 | const view = logViewOf(ctx.url, `/games/${box.name}/${service}`, service); | |
| 911 | const changes = blockChanges(ctx.url.searchParams.get("known") ?? ""); | |
| 912 | return eventStream(ctx.app, ctx.request, (emit, close, ready) => | |
| 983 | 913 | watchBox(ctx.app, box.id, () => { |
| 984 | 914 | if (!ready()) return; |
| 985 | const got = logsOf(ctx.app.db, box.id, service, 500, after); | |
| 986 | after = got.last; | |
| 987 | const results = answers(); | |
| 915 | // The person is read again at each look: one no longer a viewer of the service is told nothing | |
| 916 | // more, and one no longer an operator no command or answer. | |
| 917 | const viewer = ctx.auth.user === undefined ? undefined : getUserById(ctx.app.db, ctx.auth.user.id); | |
| 918 | const role = roleOn(ctx.app.db, viewer, box.id, service); | |
| 919 | if (role === undefined) return close(); | |
| 920 | const got = gameLogAfter(ctx.app.db, box.id, service, after); | |
| 921 | after = got.lines.at(-1)?.id ?? after; | |
| 922 | const rows = logRows(view, got.lines); | |
| 988 | 923 | const now = nowWords(servicesOf(ctx.app.db, box.id).find((x) => x.name === service), powerNow(ctx.app.db, box.id, service)); |
| 989 | const figures = figuresOf(ctx.app.db, ctx.auth.user, boxNamed(ctx.app.db, box.name) ?? box, service); | |
| 990 | const shownBefore = shown; | |
| 991 | shown = `${now}\n${figures}`; | |
| 992 | if (got.lines.length > 0 || results.length > 0 || shown !== shownBefore) | |
| 993 | emit("lines", { now, figures, html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r.id, ok: r.ok, output: r.output, says: commandSays(r) })) }); | |
| 924 | const age = ageWords(gameLogAge(ctx.app.db, box.id, service)); | |
| 925 | const figures = figuresOf(ctx.app.db, viewer, boxNamed(ctx.app.db, box.name) ?? box, service); | |
| 926 | const said = `${now}\n${age}\n${figures}`; | |
| 927 | if (rows.length > 0 || said !== shown) emit("lines", { now, age, figures, rows, ...(got.gone ? { gone: LOG_GONE } : {}) }); | |
| 928 | shown = said; | |
| 929 | const changed = changes(serviceBlocks(ctx.app, box.id, service, mayDo(role, "operator"))); | |
| 930 | if (changed.length > 0) emit("blocks", { blocks: changed.map((b) => blockEvent(b, box)) }); | |
| 994 | 931 | }), |
| 995 | 932 | ); |
| 996 | 933 | } |
| @@ -1062,9 +999,9 @@ export async function gameCrashShare(ctx: Ctx): Promise<Response> { | ||
| 1062 | 999 | const got = await operatorForm(ctx); |
| 1063 | 1000 | if (got instanceof Response) return got; |
| 1064 | 1001 | const back = `/games/${got.box.name}/${got.service}`; |
| 1065 | const crash = crashOf(logsOf(ctx.app.db, got.box.id, got.service, 2_000).lines); | |
| 1002 | const crash = gameLogPage(ctx.app.db, got.box.id, got.service).finding; | |
| 1066 | 1003 | if (crash === undefined) return flashTo(ctx, back, { tone: "danger", message: "There is no crash in the log to share." }); |
| 1067 | const shared = await shareOnMclogs(ctx.app, consoleText(crash.lines).join("\n")); | |
| 1004 | const shared = await shareOnMclogs(ctx.app, consoleText(crash.detail).join("\n")); | |
| 1068 | 1005 | if (!shared.ok) return flashTo(ctx, back, { tone: "danger", message: shared.error }); |
| 1069 | 1006 | return flashTo(ctx, `${back}?shared=${shared.id}`, { message: `Shared publicly on mclo.gs: https://mclo.gs/${shared.id}` }); |
| 1070 | 1007 | } |
src/web/terminal_blocks.ts +37 −11
| @@ -9,19 +9,33 @@ import { btn, field } from "./ui.ts"; | ||
| 9 | 9 | |
| 10 | 10 | /** One command: what was typed, its state, what it printed. */ |
| 11 | 11 | export function blockHtml(b: Block, box: { readonly name: string }): Html { |
| 12 | return html`<div id="block-${b.id}" data-block="${b.id}:${b.state}" data-command="${b.text}"><p class="mono break">$ ${b.text} ${btn("Edit", { type: "button", size: "sm", variant: "ghost", extra: "js-only", label: `Edit ${b.text} in the input` })}</p><p class="muted small" data-says>${blockSays(b, box)}</p>${b.output === "" ? null : html`<pre class="run-log mono" tabindex="0" aria-label="What ${b.text} printed"> | |
| 12 | return html`<div id="block-${b.id}" data-block="${b.id}:${b.state}" ${b.typed ? html` data-command="${b.text}"` : null}><p class="mono break">${b.typed ? "$ " : ""}${b.text}${b.typed ? html` ${btn("Edit", { type: "button", size: "sm", variant: "ghost", extra: "js-only", label: `Edit ${b.text} in the input` })}` : null}</p><p class="muted small" data-says>${blockSays(b, box)}</p>${b.output === "" ? null : html`<pre class="run-log mono" tabindex="0" aria-label="What ${b.text} printed"> | |
| 13 | 13 | ${b.output}</pre>`}</div>`; |
| 14 | 14 | } |
| 15 | 15 | |
| 16 | /** A block as a stream sends it: drawn, with the log line it stands after. */ | |
| 17 | export const blockEvent = (b: Block, box: { readonly name: string }): { id: string; says: string; html: string; after: number | null } => ({ | |
| 18 | id: b.id, | |
| 19 | says: blockSays(b, box), | |
| 20 | html: blockHtml(b, box).toString(), | |
| 21 | after: b.after, | |
| 22 | }); | |
| 23 | ||
| 16 | 24 | /** The blocks, and the input under them with what the audit keeps. */ |
| 17 | export function blocksForm(blocks: readonly Block[], box: { readonly name: string }, action: string): Html { | |
| 18 | return html`<div id="shell-blocks" data-stream="${action}/stream">${blocks.map((b) => blockHtml(b, box))}</div> | |
| 25 | export function blocksForm( | |
| 26 | blocks: readonly Block[], | |
| 27 | box: { readonly name: string }, | |
| 28 | action: string, | |
| 29 | // A service's console: its own words, its log's stream, and no input for who may not act. | |
| 30 | o: { label?: string; placeholder?: string; says?: string; stream?: string; input?: boolean } = {}, | |
| 31 | ): Html { | |
| 32 | return html`<div id="shell-blocks" data-stream="${o.stream ?? `${action}/stream`}">${blocks.map((b) => blockHtml(b, box))}</div> | |
| 19 | 33 | <p id="shell-said" class="sr-only" role="status"></p> |
| 20 | <form method="post" action="${action}"> | |
| 21 | ${field({ id: "shell-command", name: "text", label: "Command", labelHidden: true, mono: true, placeholder: "df -h /; docker ps", autocomplete: "off", autocorrect: false, spellcheck: false, describedby: "shell-audit" })} | |
| 34 | ${o.input === false ? null : html`<form method="post" action="${action}"> | |
| 35 | ${field({ id: "shell-command", name: "text", label: o.label ?? "Command", labelHidden: true, mono: true, placeholder: o.placeholder ?? "df -h /; docker ps", autocomplete: "off", autocorrect: false, spellcheck: false, describedby: "shell-audit", ...(o.input === undefined ? {} : { required: true, maxlength: 1000 }) })} | |
| 22 | 36 | ${btn("Run", { type: "submit" })} |
| 23 | 37 | </form> |
| 24 | <p id="shell-audit" class="muted small">${AUDIT_SAYS}</p>`; | |
| 38 | <p id="shell-audit" class="muted small">${o.says ?? AUDIT_SAYS}</p>`}`; | |
| 25 | 39 | } |
| 26 | 40 | |
| 27 | 41 | /** The page's script: blocks over the stream, and up and down through the earlier commands. */ |
| @@ -32,13 +46,25 @@ export const terminalBlocksJs = /* js */ ` | ||
| 32 | 46 | if (!box) return; |
| 33 | 47 | if (typeof EventSource !== 'undefined') { |
| 34 | 48 | var known = Array.prototype.map.call(box.querySelectorAll('[data-block]'), function (b) { return b.getAttribute('data-block'); }); |
| 35 | var es = new EventSource(box.getAttribute('data-stream') + '?known=' + encodeURIComponent(known.join(','))); | |
| 49 | // A log on the page has the one stream open already. | |
| 50 | var log = document.getElementById('log'); | |
| 51 | var es = (log && log.forgeStream) || new EventSource(box.getAttribute('data-stream') + '?known=' + encodeURIComponent(known.join(','))); | |
| 36 | 52 | es.addEventListener('blocks', function (e) { |
| 37 | 53 | var d; try { d = JSON.parse(e.data); } catch (_) { return; } |
| 38 | 54 | d.blocks.forEach(function (b) { |
| 39 | 55 | // Drawn and escaped by the forge, as the page's own blocks are. |
| 40 | 56 | var old = document.getElementById('block-' + b.id); |
| 41 | if (old) old.outerHTML = b.html; else box.insertAdjacentHTML('beforeend', b.html); | |
| 57 | // An answer joins the log under the last line held when it came, and stays there. A filtered | |
| 58 | // log, or one shown at a line, has no such place: it stays by the input. | |
| 59 | var row = null; | |
| 60 | if (b.after !== null && log && log.hasAttribute('data-stream') && !log.getAttribute('data-q') && !(old && log.contains(old))) { | |
| 61 | var stick = log.scrollTop + log.clientHeight >= log.scrollHeight - 8; | |
| 62 | if (old) old.remove(); | |
| 63 | row = log.lastElementChild; | |
| 64 | while (row && row.id.charAt(0) === 'l' && Number(row.id.slice(1)) > b.after) row = row.previousElementSibling; | |
| 65 | if (row) row.insertAdjacentHTML('afterend', b.html); else log.insertAdjacentHTML('afterbegin', b.html); | |
| 66 | if (stick) log.scrollTop = log.scrollHeight; | |
| 67 | } else if (old) old.outerHTML = b.html; else box.insertAdjacentHTML('beforeend', b.html); | |
| 42 | 68 | if (said) said.textContent = b.says; |
| 43 | 69 | }); |
| 44 | 70 | }); |
| @@ -47,7 +73,7 @@ export const terminalBlocksJs = /* js */ ` | ||
| 47 | 73 | if (!input) return; |
| 48 | 74 | // The blocks are the history: newest first, each command once. |
| 49 | 75 | function commands() { |
| 50 | return Array.prototype.map.call(box.querySelectorAll('[data-command]'), function (c) { return c.getAttribute('data-command'); }) | |
| 76 | return Array.prototype.map.call(document.querySelectorAll('[data-command]'), function (c) { return c.getAttribute('data-command'); }) | |
| 51 | 77 | .reverse().filter(function (c, i, all) { return all.indexOf(c) === i; }); |
| 52 | 78 | } |
| 53 | 79 | var at = -1, typed = '', past = []; |
| @@ -61,8 +87,8 @@ export const terminalBlocksJs = /* js */ ` | ||
| 61 | 87 | input.value = at === -1 ? typed : past[at]; |
| 62 | 88 | }); |
| 63 | 89 | // A phone has no arrows: a block's button puts its command in the input, and runs nothing. |
| 64 | box.addEventListener('click', function (e) { | |
| 65 | var again = e.target.closest('button'); | |
| 90 | document.addEventListener('click', function (e) { | |
| 91 | var again = e.target.closest('[data-command] button'); | |
| 66 | 92 | if (!again) return; |
| 67 | 93 | input.value = again.closest('[data-command]').getAttribute('data-command'); |
| 68 | 94 | at = -1; |
test/game-answer.test.ts +10 −11
| @@ -11,8 +11,9 @@ import { createApp } from "../src/app.ts"; | ||
| 11 | 11 | import { createSession } from "../src/core/sessions.ts"; |
| 12 | 12 | import { createUser } from "../src/core/users.ts"; |
| 13 | 13 | import { LOOK_MS } from "../src/games/notify.ts"; |
| 14 | import { answersOf, boxNamed, commandOf, commandSays, createGameBox, NO_ANSWER, queueCommand, recordSync, type CommandKind } from "../src/games/store.ts"; | |
| 14 | import { boxNamed, commandOf, createGameBox, NO_ANSWER, queueCommand, recordSync, type CommandKind } from "../src/games/store.ts"; | |
| 15 | 15 | import { forgeHttp } from "../src/http/server.ts"; |
| 16 | import { blockChanges, blockSays, serviceBlocks } from "../src/terminal/blocks.ts"; | |
| 16 | 17 | import { quietLogs } from "./helpers/globals.ts"; |
| 17 | 18 | |
| 18 | 19 | quietLogs(); |
| @@ -23,29 +24,27 @@ test("a command whose answer never comes says so, is not sent again, and a late | ||
| 23 | 24 | try { |
| 24 | 25 | createGameBox(app.db, { name: "mc" }); |
| 25 | 26 | const box = boxNamed(app.db, "mc")!; |
| 26 | const answers = answersOf(app.db, box.id, "hub"); | |
| 27 | const changes = blockChanges(""); | |
| 28 | const answers = () => changes(serviceBlocks(app, box.id, "hub", true)).map((b) => `${blockSays(b, box)}${b.output === "" ? "" : `: ${b.output}`}`); | |
| 27 | 29 | const queue = (kind: CommandKind, text: string): string => queueCommand(app.db, box.id, "hub", kind, text, ""); |
| 28 | const says = (id: string): string => commandSays(commandOf(app.db, id)!); | |
| 29 | 30 | const handed = (id: string, secondsAgo: number): void => { |
| 30 | 31 | app.db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(id, new Date(Date.now() - secondsAgo * 1_000).toISOString()); |
| 31 | 32 | }; |
| 32 | 33 | const id = queue("rcon", "say once"); |
| 33 | expect(says(id)).toBe("queued"); | |
| 34 | expect(answers()).toEqual(["Waiting for mc's next check-in"]); | |
| 34 | 35 | expect(recordSync(app.db, box, { light: true }).map((c) => c.id)).toEqual([id]); |
| 35 | expect(says(id)).toBe("sent to the box"); | |
| 36 | expect(answers()).toEqual([]); | |
| 36 | expect(answers()).toEqual(["mc has it"]); | |
| 37 | 37 | handed(id, 121); |
| 38 | 38 | expect(commandOf(app.db, id)).toMatchObject({ done: true, ok: null }); |
| 39 | expect(says(id)).toBe(NO_ANSWER); | |
| 40 | expect(answers().map(commandSays)).toEqual([NO_ANSWER]); | |
| 39 | expect(answers()).toEqual([NO_ANSWER]); | |
| 41 | 40 | expect(answers()).toEqual([]); |
| 42 | 41 | expect(recordSync(app.db, box, { light: true })).toEqual([]); |
| 43 | 42 | recordSync(app.db, box, { light: true, results: [{ id, ok: true, output: "said" }] }); |
| 44 | expect(answers().map(commandSays)).toEqual(["ok: said"]); | |
| 43 | expect(answers()).toEqual(["Done: said"]); | |
| 45 | 44 | // A restart may take long: it is still waited for. |
| 46 | 45 | const restart = queue("restart", ""); |
| 47 | 46 | handed(restart, 600); |
| 48 | expect(says(restart)).toBe("sent to the box"); | |
| 47 | expect(answers()).toEqual(["mc has it"]); | |
| 49 | 48 | } finally { |
| 50 | 49 | app.close(); |
| 51 | 50 | await rm(dir, { recursive: true, force: true }); |
| @@ -53,7 +52,7 @@ test("a command whose answer never comes says so, is not sent again, and a late | ||
| 53 | 52 | }); |
| 54 | 53 | |
| 55 | 54 | for (const [door, path, service, kind, event] of [ |
| 56 | ["a service's page", "/games/mc/hub/stream", "hub", "rcon", "lines"], | |
| 55 | ["a service's page", "/games/mc/hub/stream", "hub", "rcon", "blocks"], | |
| 57 | 56 | ["the owner's console", "/games/mc/@shell/stream", "", "shell", "blocks"], |
| 58 | 57 | ] as const) |
| 59 | 58 | test(`with no sync at all, ${door} is told that no answer came, and the look ends with the stream`, async () => { |
test/game-console-colour.test.ts +2 −3
| @@ -122,9 +122,8 @@ describe("the service page", () => { | ||
| 122 | 122 | expect(page).toContain('<span class="ansi-green">alice joined the game</span>'); |
| 123 | 123 | expect(page).not.toContain("§a"); |
| 124 | 124 | expect(page).toContain("Crashed: Exception in server tick loop · IllegalStateException: boom"); |
| 125 | // Newest first, each once. | |
| 126 | expect(page.indexOf('<option value="say one">')).toBeLessThan(page.indexOf('<option value="op alice">')); | |
| 127 | expect(page.split('<option value="say one">')).toHaveLength(2); | |
| 125 | // Up and down walk the blocks on the page, kept in the order they were typed. | |
| 126 | expect([...page.matchAll(/data-command="([^"]*)"/g)].map((m) => m[1])).toEqual(["say one", "op alice", "say one"]); | |
| 128 | 127 | }); |
| 129 | 128 | |
| 130 | 129 | test("a colour escape from the box is kept as its § code and drawn; Raw shows the line as kept", async () => { |
test/game-gist.test.ts +3 −2
| @@ -148,7 +148,8 @@ describe("on a forge", () => { | ||
| 148 | 148 | for (;;) { |
| 149 | 149 | const got = await Promise.race([reader.read(), new Promise<never>((_, no) => setTimeout(() => no(new Error("no event")), 3000))]); |
| 150 | 150 | const text = new TextDecoder().decode(got.value); |
| 151 | if (text.includes("event:")) return text; | |
| 151 | // The same stream brings the commands' blocks. | |
| 152 | if (text.includes("event: lines")) return text; | |
| 152 | 153 | } |
| 153 | 154 | }; |
| 154 | 155 | synced(app, box.id); |
| @@ -159,7 +160,7 @@ describe("on a forge", () => { | ||
| 159 | 160 | const second = await next(); |
| 160 | 161 | expect(second).toContain("event: lines"); |
| 161 | 162 | expect(second).toContain('"now":"running'); |
| 162 | expect(second).toContain('"lines":[]'); | |
| 163 | expect(second).toContain('"rows":[]'); | |
| 163 | 164 | await reader.cancel(); |
| 164 | 165 | }); |
| 165 | 166 |
test/job-slices.test.ts +1 −1
| @@ -113,7 +113,7 @@ beforeAll(async () => { | ||
| 113 | 113 | for (let n = 1; n <= 5_000; n++) line.run(gameBox, `[12:00:00 INFO]: line ${n}`, at); |
| 114 | 114 | })(); |
| 115 | 115 | const page = await forgeHttp(app).handle( |
| 116 | new Request("http://forge.test/games/mc/hub/stream", { headers: { cookie: `forge_session=${createSession(app.db, "own").token}` } }), | |
| 116 | new Request("http://forge.test/games/mc/hub/stream?after=0", { headers: { cookie: `forge_session=${createSession(app.db, "own").token}` } }), | |
| 117 | 117 | ); |
| 118 | 118 | const reader = page.body!.getReader(); |
| 119 | 119 | closeGamePage = () => reader.cancel(); |
test/log-reader.test.ts added +389
| @@ -0,0 +1,389 @@ | ||
| 1 | /** | |
| 2 | * The log reader on a game service, in the page and the terminal: the age said, found and copied, | |
| 3 | * every line masked, nothing skipped after a long absence. The page's own script runs over the real stream. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, 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 { Window } from "happy-dom"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createSession } from "../src/core/sessions.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { synced } from "../src/games/notify.ts"; | |
| 16 | import { boxNamed, createGameBox, grant, LOG_KEEP, queueCommand, recordSync } from "../src/games/store.ts"; | |
| 17 | import { forgeHttp } from "../src/http/server.ts"; | |
| 18 | import { holdValues, releaseValues } from "../src/kernel/log.ts"; | |
| 19 | import { ageWords } from "../src/logs/page.ts"; | |
| 20 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 21 | import { gameServiceScreen } from "../src/tui/screens/games.ts"; | |
| 22 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | import { pollUntil } from "./helpers/poll.ts"; | |
| 25 | import { settleApp } from "./helpers/tui.ts"; | |
| 26 | ||
| 27 | quietLogs(); | |
| 28 | ||
| 29 | let dir = ""; | |
| 30 | let app: App; | |
| 31 | let http: ReturnType<typeof forgeHttp>; | |
| 32 | let ada: User; | |
| 33 | let bob: User; | |
| 34 | const box = () => boxNamed(app.db, "mc")!; | |
| 35 | const get = async (path: string, who: User = ada): Promise<Response> => | |
| 36 | http.handle(new Request(`http://forge.test${path}`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } })); | |
| 37 | const page = async (path: string): Promise<string> => (await get(path)).text(); | |
| 38 | const sync = (service: string, lines: string[]): void => { | |
| 39 | recordSync(app.db, box(), { services: [{ name: service, state: "running" }], logs: { [service]: lines } }); | |
| 40 | synced(app, box().id); | |
| 41 | }; | |
| 42 | ||
| 43 | beforeAll(async () => { | |
| 44 | dir = mkdtempSync(join(tmpdir(), "forge-log-reader-")); | |
| 45 | app = createApp({ dataDir: dir, port: 0 }); | |
| 46 | http = forgeHttp(app); | |
| 47 | const make = async (username: string, adminIfFirst: boolean): Promise<User> => { | |
| 48 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 49 | if (!made.ok) throw new Error(made.error); | |
| 50 | return made.value; | |
| 51 | }; | |
| 52 | ada = await make("ada", true); | |
| 53 | bob = await make("bob", false); | |
| 54 | createGameBox(app.db, { name: "mc" }); | |
| 55 | }); | |
| 56 | afterAll(async () => { | |
| 57 | app.close(); | |
| 58 | await rm(dir, { recursive: true, force: true }); | |
| 59 | }); | |
| 60 | ||
| 61 | /** The page with its own script and an EventSource over the forge's stream; `again` connects as a reconnect does. */ | |
| 62 | async function open(path: string, who: User = ada) { | |
| 63 | const body = await (await get(path, who)).text(); | |
| 64 | const win = new Window({ url: `http://forge.test${path}` }); | |
| 65 | win.document.write(body.replace(/<script[\s\S]*?<\/script>/g, "")); | |
| 66 | const readers: { cancel(): Promise<void> }[] = []; | |
| 67 | const urls: string[] = []; | |
| 68 | let ended = 0; | |
| 69 | let again = async (): Promise<void> => {}; | |
| 70 | class Source { | |
| 71 | readonly on = new Map<string, (e: { data: string }) => void>(); | |
| 72 | constructor(url: string) { | |
| 73 | urls.push(url); | |
| 74 | again = () => this.read(url); | |
| 75 | void this.read(url); | |
| 76 | } | |
| 77 | addEventListener(kind: string, f: (e: { data: string }) => void): void { | |
| 78 | this.on.set(kind, f); | |
| 79 | } | |
| 80 | async read(url: string): Promise<void> { | |
| 81 | const reader = (await get(url, who)).body!.getReader(); | |
| 82 | readers.push(reader); | |
| 83 | let text = ""; | |
| 84 | for (let got = await reader.read(); !got.done; got = await reader.read()) { | |
| 85 | text += new TextDecoder().decode(got.value); | |
| 86 | for (let end = text.indexOf("\n\n"); end >= 0; end = text.indexOf("\n\n")) { | |
| 87 | const [, kind, data] = /^event: (.*)\ndata: (.*)$/m.exec(text.slice(0, end)) ?? []; | |
| 88 | text = text.slice(end + 2); | |
| 89 | if (kind !== undefined) this.on.get(kind)?.({ data: data! }); | |
| 90 | } | |
| 91 | } | |
| 92 | ended++; | |
| 93 | } | |
| 94 | } | |
| 95 | const src = /<script src="([^"]*\/page-[^"]+)"/.exec(body)?.[1]; | |
| 96 | if (src === undefined) throw new Error("the page ships no script of its own"); | |
| 97 | new Function("document", "EventSource", await (await get(src, who)).text())(win.document, Source); | |
| 98 | win.document.dispatchEvent(new win.Event("DOMContentLoaded")); | |
| 99 | await pollUntil(() => readers.length > 0, "the stream opens"); | |
| 100 | return { | |
| 101 | win, | |
| 102 | urls, | |
| 103 | ended: () => ended, | |
| 104 | log: () => win.document.getElementById("log")!.textContent, | |
| 105 | again: async () => { | |
| 106 | const had = readers.length; | |
| 107 | void again(); | |
| 108 | await pollUntil(() => readers.length > had, "the stream opens again"); | |
| 109 | }, | |
| 110 | close: async () => { | |
| 111 | for (const r of readers) await r.cancel(); | |
| 112 | await win.happyDOM.close(); | |
| 113 | }, | |
| 114 | }; | |
| 115 | } | |
| 116 | ||
| 117 | test("a quiet log, a silent box and an empty log each say their own sentence", () => { | |
| 118 | const now = Date.parse("2026-12-02T16:10:00Z"); | |
| 119 | const ago = (s: number): string => new Date(now - s * 1_000).toISOString(); | |
| 120 | expect(ageWords({ lastLine: ago(5), lastHeard: ago(5) }, now)).toBe("Live. Last line just now."); | |
| 121 | expect(ageWords({ lastLine: ago(840), lastHeard: ago(4) }, now)).toBe("Last line 14 minutes ago; the box is sending its log."); | |
| 122 | expect(ageWords({ lastLine: ago(840), lastHeard: ago(360) }, now)).toBe("Not known since 2026-12-02 16:04 UTC: the box last sent its log 6 minutes ago."); | |
| 123 | expect(ageWords({ lastLine: "", lastHeard: ago(4) }, now)).toBe("Nothing has been written yet; the box is sending its log."); | |
| 124 | expect(ageWords({ lastLine: "", lastHeard: "" }, now)).toBe("Not known: the box has not sent its log yet."); | |
| 125 | }); | |
| 126 | ||
| 127 | test("a filter keeps the matching lines and counts them; a match opens in its place, and the way back keeps the filter", async () => { | |
| 128 | sync("find", ["one", "§aAlice <b>joined</b>", "three", "Alice left"]); | |
| 129 | const found = await page("/games/mc/find?log=alice"); | |
| 130 | expect(found).toContain("2 of 4 kept lines."); | |
| 131 | expect(found).toContain("<mark>Alice</mark> <b>joined</b>"); | |
| 132 | expect(found).not.toContain("three"); | |
| 133 | const id = /id="l(\d+)"/.exec(found)![1]!; | |
| 134 | const placed = await page(`/games/mc/find?log=alice&at=${id}`); | |
| 135 | expect(placed).toContain("three"); | |
| 136 | expect(placed).toContain("Back to the matches"); | |
| 137 | expect(placed).toContain("/games/mc/find?log=alice#console"); | |
| 138 | expect(await page("/games/mc/find?at=999999")).toContain("That line is no longer kept"); | |
| 139 | expect(await page("/games/mc/find?log=nobody")).toContain("No line matches "nobody"."); | |
| 140 | }); | |
| 141 | ||
| 142 | test("a held value and a credential shape are masked in the page, the stream, a filter and the terminal", async () => { | |
| 143 | const value = "s3cr3t-Value-91x"; | |
| 144 | const shape = `forge_${"a1B2".repeat(10)}`; | |
| 145 | holdValues("log-reader", [value]); | |
| 146 | const open1 = await open("/games/mc/mask"); | |
| 147 | try { | |
| 148 | sync("mask", [`first ${value}`, `then ${shape}`]); | |
| 149 | await pollUntil(() => open1.log().includes("then [redacted]"), "the lines come"); | |
| 150 | expect(open1.log()).not.toContain(value); | |
| 151 | expect(open1.log()).not.toContain(shape); | |
| 152 | for (const path of ["/games/mc/mask", "/games/mc/mask?raw=1", "/games/mc/mask?log=first"]) { | |
| 153 | const body = await page(path); | |
| 154 | expect(body).toContain("first"); | |
| 155 | expect(body).not.toContain(value); | |
| 156 | expect(body).not.toContain(shape); | |
| 157 | } | |
| 158 | // Searching for the secret does not say that it is there. | |
| 159 | expect(await page(`/games/mc/mask?log=${value}`)).toContain("0 of 2 kept lines."); | |
| 160 | const t = terminal("mask"); | |
| 161 | await settleApp(t.tui); | |
| 162 | expect(t.text()).toContain("first [redacted]"); | |
| 163 | expect(t.text()).not.toContain(value); | |
| 164 | t.tui.stop?.(); | |
| 165 | } finally { | |
| 166 | await open1.close(); | |
| 167 | releaseValues("log-reader"); | |
| 168 | } | |
| 169 | }); | |
| 170 | ||
| 171 | test("a reader away for more than 500 lines gets them all, once, and one away for more than is kept is told", async () => { | |
| 172 | sync("long", ["start"]); | |
| 173 | const p = await open("/games/mc/long"); | |
| 174 | try { | |
| 175 | const insert = app.db.query("INSERT INTO game_log (box_id, service, line, at) VALUES (?1, 'long', ?2, ?3)"); | |
| 176 | for (let i = 0; i < 900; i++) insert.run(box().id, `n${String(i)}.`, new Date().toISOString()); | |
| 177 | sync("long", ["end one"]); | |
| 178 | await pollUntil(() => p.log().includes("end one"), "all of it comes"); | |
| 179 | expect(p.log()).toContain("n0."); | |
| 180 | expect(p.log().split("n450.")).toHaveLength(2); | |
| 181 | await p.again(); | |
| 182 | sync("long", ["end two"]); | |
| 183 | await pollUntil(() => p.log().includes("end two"), "the reconnect goes on"); | |
| 184 | expect(p.log().split("n450.")).toHaveLength(2); | |
| 185 | expect(p.log().split("end one")).toHaveLength(2); | |
| 186 | for (let i = 0; i < LOG_KEEP + 10; i++) insert.run(box().id, "flood", new Date().toISOString()); | |
| 187 | sync("long", ["end three"]); | |
| 188 | await pollUntil(() => p.log().includes("end three"), "the flood comes"); | |
| 189 | expect(p.win.document.querySelectorAll("#log > *").length).toBeLessThanOrEqual(LOG_KEEP); | |
| 190 | expect(await page("/games/mc/long")).not.toContain("Older lines are dropped"); | |
| 191 | } finally { | |
| 192 | await p.close(); | |
| 193 | } | |
| 194 | }, 30_000); | |
| 195 | ||
| 196 | test("one stream brings the lines and a command's answer; a filtered page takes only what matches", async () => { | |
| 197 | sync("one", ["hello"]); | |
| 198 | const id = queueCommand(app.db, box().id, "one", "rcon", "list", ada.id); | |
| 199 | const p = await open("/games/mc/one?log=keep"); | |
| 200 | try { | |
| 201 | expect(p.urls).toHaveLength(1); | |
| 202 | recordSync(app.db, box(), { light: true }); | |
| 203 | recordSync(app.db, box(), { light: true, results: [{ id, ok: true, output: "<b>2 players</b>" }] }); | |
| 204 | sync("one", ["drop this", "keep this"]); | |
| 205 | await pollUntil(() => p.log().includes("keep this"), "the match comes"); | |
| 206 | expect(p.log()).not.toContain("drop this"); | |
| 207 | await pollUntil(() => p.win.document.getElementById(`block-${id}`)!.textContent.includes("<b>2 players</b>"), "the answer comes"); | |
| 208 | } finally { | |
| 209 | await p.close(); | |
| 210 | } | |
| 211 | }); | |
| 212 | ||
| 213 | test("a viewer reads the log with no input, and one who loses the role is told nothing more", async () => { | |
| 214 | sync("role", ["before"]); | |
| 215 | grant(app.db, box().id, bob.id, "viewer"); | |
| 216 | const p = await open("/games/mc/role", bob); | |
| 217 | try { | |
| 218 | expect(p.win.document.getElementById("shell-command")).toBeNull(); | |
| 219 | app.db.query("DELETE FROM game_grant WHERE user_id = ?1").run(bob.id); | |
| 220 | sync("role", ["after"]); | |
| 221 | await pollUntil(() => p.ended() === 1, "the forge ends the stream"); | |
| 222 | expect(p.log()).toContain("before"); | |
| 223 | expect(p.log()).not.toContain("after"); | |
| 224 | } finally { | |
| 225 | await p.close(); | |
| 226 | } | |
| 227 | }); | |
| 228 | ||
| 229 | test("a forge admin who is made an ordinary account is told nothing more on a stream already open", async () => { | |
| 230 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "cyd", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: false }); | |
| 231 | if (!made.ok) throw new Error(made.error); | |
| 232 | app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.id); | |
| 233 | sync("admin", ["before"]); | |
| 234 | const p = await open("/games/mc/admin", made.value); | |
| 235 | try { | |
| 236 | app.db.query("UPDATE user SET is_admin = 0 WHERE id = ?1").run(made.value.id); | |
| 237 | sync("admin", ["after"]); | |
| 238 | await pollUntil(() => p.ended() === 1, "the forge ends the stream"); | |
| 239 | expect(p.log()).not.toContain("after"); | |
| 240 | } finally { | |
| 241 | await p.close(); | |
| 242 | } | |
| 243 | }); | |
| 244 | ||
| 245 | test("an answer stands under the last line held when it came, and later output goes below it, on the page, after a reload and in the terminal", async () => { | |
| 246 | sync("place", ["one", "two"]); | |
| 247 | const id = queueCommand(app.db, box().id, "place", "rcon", "list", ada.id); | |
| 248 | const power = queueCommand(app.db, box().id, "place", "restart", "", ada.id); | |
| 249 | const p = await open("/games/mc/place"); | |
| 250 | const inOrder = (text: string, ...parts: string[]): void => { | |
| 251 | const at = parts.map((x) => text.indexOf(x)); | |
| 252 | expect(at).not.toContain(-1); | |
| 253 | expect(at).toEqual([...at].sort((a, b) => a - b)); | |
| 254 | }; | |
| 255 | try { | |
| 256 | const block = () => p.win.document.getElementById(`block-${id}`)!; | |
| 257 | expect(p.log()).not.toContain("$ list"); | |
| 258 | expect(block().querySelector("button")).not.toBeNull(); | |
| 259 | expect(p.win.document.getElementById(`block-${power}`)!.querySelector("button")).toBeNull(); | |
| 260 | recordSync(app.db, box(), { light: true }); | |
| 261 | recordSync(app.db, box(), { light: true, results: [{ id, ok: true, output: "2 players" }] }); | |
| 262 | synced(app, box().id); | |
| 263 | await pollUntil(() => p.log().includes("2 players"), "the answer joins the log"); | |
| 264 | sync("place", ["three"]); | |
| 265 | await pollUntil(() => p.log().includes("three"), "the next line comes"); | |
| 266 | inOrder(p.log(), "two", "$ list", "2 players", "three"); | |
| 267 | expect(p.win.document.querySelectorAll(`#block-${id}`).length).toBe(1); | |
| 268 | const again = await open("/games/mc/place"); | |
| 269 | inOrder(again.log(), "two", "$ list", "2 players", "three"); | |
| 270 | await again.close(); | |
| 271 | // Filtered, the answer is by the input. | |
| 272 | const found = await open("/games/mc/place?log=three"); | |
| 273 | expect(found.log()).not.toContain("$ list"); | |
| 274 | expect(found.win.document.querySelector(`#shell-blocks #block-${id}`)).not.toBeNull(); | |
| 275 | await found.close(); | |
| 276 | const t = terminal("place"); | |
| 277 | await settleApp(t.tui); | |
| 278 | inOrder(t.text(), "two", "$ list", "2 players", "three"); | |
| 279 | t.tui.stop?.(); | |
| 280 | } finally { | |
| 281 | await p.close(); | |
| 282 | } | |
| 283 | }); | |
| 284 | ||
| 285 | for (const role of ["viewer", "operator", "owner"] as const) | |
| 286 | test(`${role}: ${role === "viewer" ? "the log, and no command or answer" : "the log, the commands and their answers"}, on the page, the stream, in the terminal and over MCP`, async () => { | |
| 287 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: `as-${role}`, email: `as-${role}@f.test`, password: "a-good-passphrase", adminIfFirst: false }); | |
| 288 | if (!made.ok) throw new Error(made.error); | |
| 289 | const who = made.value; | |
| 290 | grant(app.db, box().id, who.id, role); | |
| 291 | const service = `for-${role}`; | |
| 292 | sync(service, ["a log line"]); | |
| 293 | const answer = (text: string, output: string): void => { | |
| 294 | const id = queueCommand(app.db, box().id, service, "rcon", text, ada.id); | |
| 295 | recordSync(app.db, box(), { light: true }); | |
| 296 | recordSync(app.db, box(), { light: true, results: [{ id, ok: true, output }] }); | |
| 297 | synced(app, box().id); | |
| 298 | }; | |
| 299 | answer("typed-before", "printed-before"); | |
| 300 | const said = (text: string, ...words: string[]): void => { | |
| 301 | for (const w of words) role === "viewer" ? expect(text).not.toContain(w) : expect(text).toContain(w); | |
| 302 | }; | |
| 303 | const body = await (await get(`/games/mc/${service}`, who)).text(); | |
| 304 | expect(body).toContain("a log line"); | |
| 305 | said(body, "typed-before", "printed-before"); | |
| 306 | const reader = (await get(`/games/mc/${service}/stream?after=0`, who)).body!.getReader(); | |
| 307 | answer("typed-now", "printed-now"); | |
| 308 | sync(service, ["the last line"]); | |
| 309 | let text = ""; | |
| 310 | while (!text.includes("the last line") || (role !== "viewer" && !text.includes("printed-now"))) text += new TextDecoder().decode((await reader.read()).value); | |
| 311 | await reader.cancel(); | |
| 312 | expect(text).toContain("a log line"); | |
| 313 | said(text, "typed-before", "printed-before", "typed-now", "printed-now"); | |
| 314 | const t = terminal(service, who); | |
| 315 | await settleApp(t.tui); | |
| 316 | expect(t.text()).toContain("the last line"); | |
| 317 | said(t.text(), "typed-now", "printed-now"); | |
| 318 | t.tui.stop?.(); | |
| 319 | // MCP reads no answer back, whoever asks; a viewer may not type a command there. | |
| 320 | const call = async (args: Record<string, unknown>): Promise<string> => | |
| 321 | ( | |
| 322 | await http.handle( | |
| 323 | new Request("http://forge.test/mcp", { | |
| 324 | method: "POST", | |
| 325 | headers: { authorization: `Bearer ${createToken(app.db, who.id, "t", "rw").token}`, "content-type": "application/json", accept: "application/json" }, | |
| 326 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: args } }), | |
| 327 | }), | |
| 328 | ) | |
| 329 | ).text(); | |
| 330 | const list = await call({ action: "list" }); | |
| 331 | expect(list).toContain(service); | |
| 332 | for (const w of ["typed-", "printed-"]) expect(list).not.toContain(w); | |
| 333 | const typed = await call({ action: "console", box: "mc", service, text: "list" }); | |
| 334 | if (role === "viewer") expect(typed).toContain("you are not an operator"); | |
| 335 | else expect(typed).toContain("Queued"); | |
| 336 | }, 20_000); | |
| 337 | ||
| 338 | test("an operator made a viewer while the stream is open is told no further command or answer, and still the log", async () => { | |
| 339 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "dee", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: false }); | |
| 340 | if (!made.ok) throw new Error(made.error); | |
| 341 | grant(app.db, box().id, made.value.id, "operator"); | |
| 342 | sync("less", ["before"]); | |
| 343 | const p = await open("/games/mc/less", made.value); | |
| 344 | try { | |
| 345 | grant(app.db, box().id, made.value.id, "viewer"); | |
| 346 | queueCommand(app.db, box().id, "less", "rcon", "typed-since", ada.id); | |
| 347 | sync("less", ["after"]); | |
| 348 | await pollUntil(() => p.log().includes("after"), "the log goes on"); | |
| 349 | expect(p.win.document.body.textContent).not.toContain("typed-since"); | |
| 350 | } finally { | |
| 351 | await p.close(); | |
| 352 | } | |
| 353 | }); | |
| 354 | ||
| 355 | /** The service's screen; `copied` is what it sent to the clipboard. */ | |
| 356 | function terminal(service: string, who: User = ada) { | |
| 357 | const term = headlessTerminal(120, 30); | |
| 358 | const { app: tui, session } = createForgeApp(app, { sshUsername: who.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: who }, { terminal: term, exitHooks: false }); | |
| 359 | const copied: string[] = []; | |
| 360 | tui.start(); | |
| 361 | tui.ctx.push(gameServiceScreen(session, { ...tui.ctx, copy: (t: string) => void copied.push(t) }, box(), service)); | |
| 362 | return { tui, term, copied, text: () => tui.screen.toText() }; | |
| 363 | } | |
| 364 | ||
| 365 | test("the terminal finds, opens a match in its place, goes back, and copies a line and a range", async () => { | |
| 366 | sync("term", ["one", "§aAlice joined", "three", "Alice left"]); | |
| 367 | const t = terminal("term"); | |
| 368 | const press = async (keys: string): Promise<void> => { | |
| 369 | for (const k of keys) { | |
| 370 | t.term.feed(k); | |
| 371 | await settleApp(t.tui); | |
| 372 | } | |
| 373 | }; | |
| 374 | await settleApp(t.tui); | |
| 375 | expect(t.text()).toContain("Live. Last line just now."); | |
| 376 | await press("/alice\r"); | |
| 377 | expect(t.text()).toContain("2 of 4 kept lines"); | |
| 378 | expect(t.text()).not.toContain("three"); | |
| 379 | await press("ky"); | |
| 380 | expect(t.copied).toEqual(["Alice joined"]); | |
| 381 | await press("\r"); | |
| 382 | expect(t.text()).toContain("> Alice joined"); | |
| 383 | expect(t.text()).toContain("three"); | |
| 384 | await press("vjy"); | |
| 385 | expect(t.copied.at(-1)).toBe("Alice joined\nthree"); | |
| 386 | t.term.feed("\x1b"); | |
| 387 | await pollUntil(() => t.text().includes("2 of 4 kept lines"), "esc goes back to the matches"); | |
| 388 | t.tui.stop?.(); | |
| 389 | }); |
test/terminal-blocks.test.ts +39 −1
| @@ -13,8 +13,9 @@ import { createSession } from "../src/core/sessions.ts"; | ||
| 13 | 13 | import { createUser, type User } from "../src/core/users.ts"; |
| 14 | 14 | import { synced } from "../src/games/notify.ts"; |
| 15 | 15 | import { queueShell } from "../src/games/shell.ts"; |
| 16 | import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts"; | |
| 16 | import { boxNamed, createGameBox, grant, queueCommand, recordSync } from "../src/games/store.ts"; | |
| 17 | 17 | import { forgeHttp } from "../src/http/server.ts"; |
| 18 | import { serviceBlocks } from "../src/terminal/blocks.ts"; | |
| 18 | 19 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 19 | 20 | import { gameShellScreen } from "../src/tui/screens/games.ts"; |
| 20 | 21 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| @@ -199,6 +200,43 @@ test("an owner who loses the role is told nothing more", async () => { | ||
| 199 | 200 | expect(text).not.toContain("private"); |
| 200 | 201 | }); |
| 201 | 202 | |
| 203 | test("an answer stands after the last log line the forge held when it was recorded, and stays there", async () => { | |
| 204 | const b = box(); | |
| 205 | const lastLine = (service: string): number => | |
| 206 | app.db.query<{ id: number | null }, [string, string]>("SELECT max(id) AS id FROM game_log WHERE box_id = ?1 AND service = ?2").get(b.id, service)!.id ?? 0; | |
| 207 | const of = (id: string) => serviceBlocks(app, b.id, "hub", true).find((x) => x.id === id)!; | |
| 208 | const rcon = (): string => queueCommand(app.db, b.id, "hub", "rcon", "list", ada.id); | |
| 209 | recordSync(app.db, b, { services: [{ name: "hub", state: "running" }] }); | |
| 210 | // No line yet: before the first. | |
| 211 | const first = rcon(); | |
| 212 | expect(of(first)).toMatchObject({ after: null, at: "" }); | |
| 213 | recordSync(app.db, b, { light: true }); | |
| 214 | recordSync(app.db, b, { light: true, results: [{ id: first, ok: true, output: "none" }] }); | |
| 215 | expect(of(first).after).toBe(0); | |
| 216 | // A full sync brings lines and an answer together: the answer stands after them; another service's lines count for nothing. | |
| 217 | const full = rcon(); | |
| 218 | recordSync(app.db, b, { services: [{ name: "hub", state: "running" }], logs: { hub: ["one", "two"], lobby: ["else"] }, results: [{ id: full, ok: true, output: "there" }] }); | |
| 219 | const two = lastLine("hub"); | |
| 220 | expect(two).toBeGreaterThan(0); | |
| 221 | expect(of(full).after).toBe(two); | |
| 222 | // A light sync brings none: what the command wrote comes later, and below it. | |
| 223 | const light = rcon(); | |
| 224 | const stream = (await get(`/games/mc/hub/stream?known=${first}:ok,${full}:ok`, ada)).body!.getReader(); | |
| 225 | recordSync(app.db, b, { light: true, results: [{ id: light, ok: true, output: "here" }] }); | |
| 226 | synced(app, b.id); | |
| 227 | let text = ""; | |
| 228 | while (!text.includes("event: blocks")) text += new TextDecoder().decode((await stream.read()).value); | |
| 229 | await stream.cancel(); | |
| 230 | expect(text).toContain(`"after":${String(two)}`); | |
| 231 | recordSync(app.db, b, { services: [{ name: "hub", state: "running" }], logs: { hub: ["three"] } }); | |
| 232 | expect(lastLine("hub")).toBeGreaterThan(two); | |
| 233 | expect(of(light).after).toBe(two); | |
| 234 | // One from before the column: no line is made up, its time places it. | |
| 235 | app.db.query("UPDATE game_command SET after_log = NULL WHERE id = ?1").run(first); | |
| 236 | expect(of(first).after).toBeNull(); | |
| 237 | expect(of(first).at).not.toBe(""); | |
| 238 | }); | |
| 239 | ||
| 202 | 240 | test("the terminal draws the same blocks, and its prompt says what the audit keeps and has the history", async () => { |
| 203 | 241 | ask("free -m"); |
| 204 | 242 | const terminal = headlessTerminal(120, 40); |
test/tui-games.test.ts +1 −1
| @@ -170,7 +170,7 @@ test("the console tab shows an import's link as host and path, never its query s | ||
| 170 | 170 | tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub")); |
| 171 | 171 | await settleApp(tui); |
| 172 | 172 | const text = tui.screen.toText(); |
| 173 | expect(text).toContain("> import a world from x.supabase.co/storage/hub-world.tar.gz"); | |
| 173 | expect(text).toContain("import a world from x.supabase.co/storage/hub-world.tar.gz"); | |
| 174 | 174 | expect(text).not.toContain("s3cr3t"); |
| 175 | 175 | expect(text).not.toContain("?token"); |
| 176 | 176 | tui.stop?.(); |
new above
offline