Public: anyone can read this; the crew can change it.
A command the box was not handed yet can be taken back #17933
Merged 23h 43m ago, live in production
sold/take-back → main 0 commits
16 files
changed +193
−25
- docs/features/game-box.md
- docs/features/games.md
- src/core/event_audience.ts
- src/crew/conversation_ask.ts
- src/games/store.ts
- src/games/take_back.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/http/mcp/tools/games.ts
- src/terminal/blocks.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- src/web/terminal_blocks.ts
- src/web/ui.ts
- test/conversation-ask.test.ts
- test/terminal-blocks.test.ts
docs/features/game-box.md +1 −1
Diff not shown — a line 2,237 characters wide (limit 2,000). +1 −1
View filedocs/features/games.md +1 −1
| @@ -181,7 +181,7 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p | ||
| 181 | 181 | |
| 182 | 182 | `/forge` typed as a command is heard like `!forge` ("Alice issued server command: /forge …" on Paper and Fabric); the server's own "Unknown command" shows to the player beside the forge's answer. |
| 183 | 183 | |
| 184 | **Quick commands.** Between full syncs the agent polls lightly every second (`FORGE_GAME_LIGHT_EVERY`): a body `{"agent":1,"light":true,"results":[…]}` that keeps only results and answers only `commands`, touching nothing else the forge knows. A command is handed out within a second of being queued, run, and its result sent at once, so a console command answers in under 3 s (measured in `test/game-findings.test.ts` against the real agent). A full sync that got no answer is sent again with `"retry":true`, and the forge skips the log lines it already holds, so the console does not show a line twice. The agent never asks `forge-waker` (sleep's proxy, with no shell) anything. A command handed out and not answered (2 minutes for a console, player or shell command, 2 hours for a job) says "No answer came back; it may have run." An open page or terminal screen looks every 15 s, so it says so for a box that stopped syncing too; a page without JavaScript says it on the next look. It is never sent again; an answer that comes late replaces the words. | |
| 184 | **Quick commands.** Between full syncs the agent polls lightly every second (`FORGE_GAME_LIGHT_EVERY`): a body `{"agent":1,"light":true,"results":[…]}` that keeps only results and answers only `commands`, touching nothing else the forge knows. A command is handed out within a second of being queued, run, and its result sent at once, so a console command answers in under 3 s (measured in `test/game-findings.test.ts` against the real agent). A full sync that got no answer is sent again with `"retry":true`, and the forge skips the log lines it already holds, so the console does not show a line twice. The agent never asks `forge-waker` (sleep's proxy, with no shell) anything. A command handed out and not answered (2 minutes for a console, player or shell command, 2 hours for a job) says "No answer came back; not known whether it ran." An open page or terminal screen looks every 15 s, so it says so for a box that stopped syncing too; a page without JavaScript says it on the next look. It is never sent again; an answer that comes late replaces the words. | |
| 185 | 185 | |
| 186 | 186 | ## On a phone (#17656) |
| 187 | 187 |
src/core/event_audience.ts +2
| @@ -265,6 +265,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 265 | 265 | kind.startsWith("runner.") || |
| 266 | 266 | // A shell on a game box and everything it said: its owner's, the forge admin's (`games/shell.ts`). |
| 267 | 267 | kind.startsWith("game.shell.") || |
| 268 | // A command taken back keeps its text, which may be a shell one (`games/take_back.ts`). | |
| 269 | kind === "game.command.taken_back" || | |
| 268 | 270 | // Which forges this one lends runners to is its admin's too (`actions/lending.ts`). |
| 269 | 271 | kind.startsWith("lending.") || |
| 270 | 272 | // A snapshot moving is the forge owner's too, and has no repository. |
src/crew/conversation_ask.ts +1
| @@ -334,6 +334,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 334 | 334 | games: (a) => { |
| 335 | 335 | const on = `${clause("", val(a, "service"), " on ")}${val(a, "box") || "a game box"}`; |
| 336 | 336 | if (a["action"] === "console") return `Run ${quote(a, "text") || "a command"} in the console of ${on}`; |
| 337 | if (a["action"] === "take_back") return `Take back a command ${val(a, "box") || "a game box"} was not handed yet`; | |
| 337 | 338 | if (a["action"] === "power") return `${val(a, "kind") || "Restart"} ${on}`.replace(/^./, (c) => c.toUpperCase()); |
| 338 | 339 | if (a["action"] === "env") return `Set ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that redeploys it`; |
| 339 | 340 | if (a["action"] === "mods_install") return `Install ${val(a, "project") || "a Modrinth project"} and what it requires on ${on}, a commit that restarts it`; |
src/games/store.ts +16 −5
| @@ -370,12 +370,15 @@ export function tell(db: Database, box: Pick<GameBox, "id">, service: string, pl | ||
| 370 | 370 | |
| 371 | 371 | export interface CommandState { |
| 372 | 372 | readonly id: string; |
| 373 | readonly boxId: string; | |
| 373 | 374 | readonly kind: string; |
| 374 | 375 | readonly service: string; |
| 375 | 376 | readonly text: string; |
| 376 | 377 | readonly handed: boolean; |
| 377 | 378 | readonly done: boolean; |
| 378 | 379 | readonly ok: boolean | null; |
| 380 | /** Taken back before the box was handed it: it never ran. */ | |
| 381 | readonly takenBack: boolean; | |
| 379 | 382 | readonly output: string; |
| 380 | 383 | /** When the answer was recorded; empty until then. */ |
| 381 | 384 | readonly doneAt: string; |
| @@ -383,7 +386,7 @@ export interface CommandState { | ||
| 383 | 386 | readonly afterLog: number | null; |
| 384 | 387 | } |
| 385 | 388 | /** What a command handed to the box and never answered says: it is not sent again, since running one twice is worse. */ |
| 386 | export const NO_ANSWER = "No answer came back; it may have run."; | |
| 389 | export const NO_ANSWER = "No answer came back; not known whether it ran."; | |
| 387 | 390 | /** How long an answer is waited for: a quick command or a shell one ends in 30 s, a job (a pull, a world) can take an hour. */ |
| 388 | 391 | const ANSWER_MS = 2 * 60_000; |
| 389 | 392 | const JOB_ANSWER_MS = 2 * 3_600_000; |
| @@ -392,27 +395,34 @@ const JOB_ANSWER_MS = 2 * 3_600_000; | ||
| 392 | 395 | export function commandOf(db: Database, id: string, now = Date.now()): CommandState | undefined { |
| 393 | 396 | const r = db |
| 394 | 397 | .query< |
| 395 | { id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string; after_log: number | null }, | |
| 398 | { id: string; box_id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string; after_log: number | null }, | |
| 396 | 399 | [string] |
| 397 | >("SELECT id, kind, service, text, handed_at, done_at, ok, output, after_log FROM game_command WHERE id = ?1") | |
| 400 | >("SELECT id, box_id, kind, service, text, handed_at, done_at, ok, output, after_log FROM game_command WHERE id = ?1") | |
| 398 | 401 | .get(id); |
| 399 | 402 | if (r === null) return undefined; |
| 400 | 403 | const limit = ["rcon", "people", "tell", "shell"].includes(r.kind) ? ANSWER_MS : JOB_ANSWER_MS; |
| 401 | 404 | const unanswered = r.done_at === "" && r.handed_at !== "" && now - Date.parse(r.handed_at) > limit; |
| 402 | 405 | return { |
| 403 | 406 | id: r.id, |
| 407 | boxId: r.box_id, | |
| 404 | 408 | kind: r.kind, |
| 405 | 409 | service: r.service, |
| 406 | 410 | text: r.text, |
| 407 | 411 | handed: r.handed_at !== "", |
| 408 | 412 | done: r.done_at !== "" || unanswered, |
| 409 | 413 | ok: r.ok === null ? null : r.ok === 1, |
| 414 | // An answer always says ok or not (`recordResults`); only `takeFromQueue` ends one with neither. | |
| 415 | takenBack: r.done_at !== "" && r.ok === null, | |
| 410 | 416 | output: unanswered ? NO_ANSWER : r.output, |
| 411 | 417 | doneAt: r.done_at, |
| 412 | 418 | afterLog: r.after_log, |
| 413 | 419 | }; |
| 414 | 420 | } |
| 415 | 421 | |
| 422 | /** Take a command out of the queue, in one statement: false when it was handed out (or taken back) first. */ | |
| 423 | export const takeFromQueue = (db: Database, id: string, at = new Date().toISOString()): boolean => | |
| 424 | db.query("UPDATE game_command SET handed_at = ?2, done_at = ?2 WHERE id = ?1 AND handed_at = ''").run(id, at).changes === 1; | |
| 425 | ||
| 416 | 426 | /** A service's RCON commands as typed, newest first, each once: the console's history. */ |
| 417 | 427 | export const commandHistory = (db: Database, boxId: string, service: string, limit = 50): string[] => |
| 418 | 428 | db |
| @@ -742,8 +752,9 @@ export function recordSync( | ||
| 742 | 752 | { id: string; kind: string; service: string; text: string }, |
| 743 | 753 | [string] |
| 744 | 754 | >("SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' ORDER BY created_at LIMIT 32") |
| 745 | .all(box.id); | |
| 746 | for (const c of due) db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(c.id, at); | |
| 755 | .all(box.id) | |
| 756 | // Only what this statement took is handed out: one taken back meanwhile is not. | |
| 757 | .filter((c) => db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1 AND handed_at = ''").run(c.id, at).changes === 1); | |
| 747 | 758 | // A world import's link is a secret (a signed URL): it goes to the box once, in this reply, and |
| 748 | 759 | // what stays is its host and path (`worlds.ts`). |
| 749 | 760 | for (const c of due) if (c.kind === "world") db.query("UPDATE game_command SET text = ?2 WHERE id = ?1").run(c.id, keptWorldText(c.text)); |
src/games/take_back.ts added +29
| @@ -0,0 +1,29 @@ | ||
| 1 | /** | |
| 2 | * Take back a typed command (an rcon or a shell one) the box was not handed yet (#17151). The forge | |
| 3 | * decides in one statement: the command leaves the queue there, or it was already handed out. The | |
| 4 | * row stays, done with `ok` null, and the audit keeps the command and that it was taken back. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { getUserById } from "../core/users.ts"; | |
| 9 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 10 | import { synced } from "./notify.ts"; | |
| 11 | import { commandOf, mayDo, roleOn, takeFromQueue, type GameBox } from "./store.ts"; | |
| 12 | ||
| 13 | /** Who may type it may take it back: the box's owner a shell command, a service's operator its rcon. The service is the answer's. */ | |
| 14 | export function takeBack(app: App, actorId: string | undefined, box: GameBox, id: string): Result<{ service: string; text: string }, string> { | |
| 15 | const actor = actorId === undefined ? undefined : getUserById(app.db, actorId); | |
| 16 | const c = commandOf(app.db, id); | |
| 17 | const role = actor === undefined || c === undefined ? undefined : roleOn(app.db, actor, box.id, c.service); | |
| 18 | if (actor === undefined || c === undefined || c.boxId !== box.id || (c.kind !== "shell" && c.kind !== "rcon") || !mayDo(role, c.kind === "shell" ? "owner" : "operator")) | |
| 19 | return err("No command of yours to take back here."); | |
| 20 | if (!takeFromQueue(app.db, id)) { | |
| 21 | const now = commandOf(app.db, id); | |
| 22 | // Answered, or refused before it was queued: that one the box never had. | |
| 23 | if (now !== undefined && now.ok !== null) return err("It has already ended."); | |
| 24 | return err(now?.takenBack === true ? "It was already taken back." : "It was already handed to the box."); | |
| 25 | } | |
| 26 | app.bus.append({ kind: "game.command.taken_back", actorId: actor.id, payload: { box: box.name, service: c.service, command: id, text: c.text } }); | |
| 27 | synced(app, box.id); | |
| 28 | return ok({ service: c.service, text: c.text }); | |
| 29 | } |
src/http/games_routes.ts +2 −1
| @@ -20,7 +20,7 @@ import { jarsOf } from "../games/proxy_jars.ts"; | ||
| 20 | 20 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, swapGameBoxToken, type SyncBody } from "../games/store.ts"; |
| 21 | 21 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 22 | 22 | import { |
| 23 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage, | |
| 23 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gameTakeBackSubmit, gamesPage, | |
| 24 | 24 | } from "../web/pages/games.ts"; |
| 25 | 25 | import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts"; |
| 26 | 26 | import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts"; |
| @@ -138,6 +138,7 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 138 | 138 | // Before the service routes: no compose service can be named "@shell". |
| 139 | 139 | router.add("POST", "/games/:box/@shell", gameShellSubmit); |
| 140 | 140 | router.add("GET", "/games/:box/@shell/stream", gameShellStream); |
| 141 | router.add("POST", "/games/:box/take-back", gameTakeBackSubmit); | |
| 141 | 142 | router.add("POST", "/games/:box/servers", gameServersSubmit); |
| 142 | 143 | router.add("GET", "/games/:box/:service", gameServicePage); |
| 143 | 144 | router.add("GET", "/games/:box/:service/stream", gameServiceStream); |
src/http/lazy_lists.ts +1
| @@ -639,6 +639,7 @@ export const OPERATIONS_ROUTES = [ | ||
| 639 | 639 | ["POST", "/games/:box/lend"], |
| 640 | 640 | ["POST", "/games/:box/@shell"], |
| 641 | 641 | ["GET", "/games/:box/@shell/stream"], |
| 642 | ["POST", "/games/:box/take-back"], | |
| 642 | 643 | ["POST", "/games/:box/servers"], |
| 643 | 644 | ["GET", "/games/:box/:service"], |
| 644 | 645 | ["GET", "/games/:box/:service/stream"], |
src/http/mcp/tools/games.ts +10 −2
Diff not shown — a line 2,821 characters wide (limit 2,000). +10 −2
View filesrc/terminal/blocks.ts +9 −4
| @@ -13,14 +13,14 @@ import { mayDo, NO_ANSWER, recentCommands, roleOn, type CommandState, type GameB | ||
| 13 | 13 | export interface Block { |
| 14 | 14 | readonly id: string; |
| 15 | 15 | readonly text: string; |
| 16 | readonly state: "queued" | "sent" | "ok" | "failed" | "unanswered"; | |
| 16 | readonly state: "queued" | "sent" | "ok" | "failed" | "unanswered" | "back"; | |
| 17 | 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 | 18 | readonly typed: boolean; |
| 19 | 19 | /** What it printed; empty until it is answered. */ |
| 20 | 20 | readonly output: string; |
| 21 | 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 | 22 | readonly after: number | null; |
| 23 | /** When the answer was recorded; empty until then. */ | |
| 23 | /** When the answer was recorded; empty until then, and for one taken back. */ | |
| 24 | 24 | readonly at: string; |
| 25 | 25 | } |
| 26 | 26 | |
| @@ -32,8 +32,8 @@ export const shellSays = (box: Pick<GameBox, "name">): string => | ||
| 32 | 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.`; |
| 33 | 33 | |
| 34 | 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 }; | |
| 35 | const state = c.takenBack ? "back" : !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.takenBack ? "" : c.doneAt }; | |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | 39 | /** The box's last shell commands, oldest first. The role is read now, so a lost one ends the list: undefined. */ |
| @@ -45,6 +45,9 @@ export function shellBlocks(app: App, viewerId: string | undefined, box: GameBox | ||
| 45 | 45 | .map((c) => blockOf(c, c.text, true)); |
| 46 | 46 | } |
| 47 | 47 | |
| 48 | /** Whether this reader may take it back: one they could type, not handed to the box yet (`games/take_back.ts`). */ | |
| 49 | export const mayTakeBack = (b: Block): boolean => b.typed && b.state === "queued"; | |
| 50 | ||
| 48 | 51 | /** A block's state in words. */ |
| 49 | 52 | export function blockSays(b: Block, box: Pick<GameBox, "name">): string { |
| 50 | 53 | switch (b.state) { |
| @@ -54,6 +57,8 @@ export function blockSays(b: Block, box: Pick<GameBox, "name">): string { | ||
| 54 | 57 | return `${box.name} has it`; |
| 55 | 58 | case "unanswered": |
| 56 | 59 | return NO_ANSWER; |
| 60 | case "back": | |
| 61 | return "Taken back; it never ran"; | |
| 57 | 62 | default: |
| 58 | 63 | return `${b.state === "ok" ? "Done" : "Failed"}${b.output === "" ? ", and it printed nothing" : ""}`; |
| 59 | 64 | } |
src/tui/screens/games.ts +20 −3
| @@ -20,7 +20,8 @@ import { ageWords, type LogPage } from "../../logs/page.ts"; | ||
| 20 | 20 | import { LogPane } from "../ui/log_pane.ts"; |
| 21 | 21 | import { commitPolicy, policyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts"; |
| 22 | 22 | import { queueShell } from "../../games/shell.ts"; |
| 23 | import { AUDIT_SAYS, blockSays, serviceBlocks, shellBlocks, shellSays, type Block } from "../../terminal/blocks.ts"; | |
| 23 | import { takeBack } from "../../games/take_back.ts"; | |
| 24 | import { AUDIT_SAYS, blockSays, mayTakeBack, serviceBlocks, shellBlocks, shellSays, type Block } from "../../terminal/blocks.ts"; | |
| 24 | 25 | import { watchBox } from "../../games/notify.ts"; |
| 25 | 26 | import { containersIn, figuresOf } from "../../cloud/containers.ts"; |
| 26 | 27 | import { joinAddress, NO_ADDRESS, nowWords, powerNow, PREVIEW_WORDS, privateWords, SAVE_WORDS } from "../../games/gist.ts"; |
| @@ -291,6 +292,14 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 291 | 292 | const PARTS = ["console", "env", "people", "world"] as const; |
| 292 | 293 | type Part = (typeof PARTS)[number]; |
| 293 | 294 | |
| 295 | /** Take back the newest command the box was not handed yet, and what came of it in words. */ | |
| 296 | function takeBackNewest(f: Session, box: GameBox, blocks: readonly Block[]): string { | |
| 297 | const b = blocks.findLast(mayTakeBack); | |
| 298 | if (b === undefined) return "No command waits: the box has each one already."; | |
| 299 | const took = takeBack(f.app, f.user?.id, box, b.id); | |
| 300 | return took.ok ? `Taken back, it never ran: ${b.text}` : took.error; | |
| 301 | } | |
| 302 | ||
| 294 | 303 | /** |
| 295 | 304 | * One service, as /games/<box>/<service>: `tab` moves between its console and env, `m` opens its |
| 296 | 305 | * Modrinth projects. Each change goes through the action the page's form calls, with the page's refusals in its words. |
| @@ -396,6 +405,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 396 | 405 | binding(["y"], "copy"), |
| 397 | 406 | binding(["G"], "end of the log, and follow"), |
| 398 | 407 | binding([":"], "rcon"), |
| 408 | binding(["t"], "take back a waiting command"), | |
| 399 | 409 | binding(["e"], "set env"), |
| 400 | 410 | binding(["m"], "mods"), |
| 401 | 411 | binding(["f"], "plugin config files"), |
| @@ -439,6 +449,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 439 | 449 | part = "console"; |
| 440 | 450 | return "Sent; the answer shows under the console."; |
| 441 | 451 | }, commandHistory(f.app.db, box.id, service)); |
| 452 | else if (e.key === "t") say(takeBackNewest(f, box, blocks())); | |
| 442 | 453 | else if (e.key === "e") |
| 443 | 454 | ask("Env", `KEY=VALUE (an empty value removes the key). ${SAVE_WORDS}`, async (raw) => { |
| 444 | 455 | const at = raw.indexOf("="); |
| @@ -700,7 +711,7 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 700 | 711 | const blocks = () => shellBlocks(f.app, f.user?.id, box) ?? []; |
| 701 | 712 | const screen: Screen = { |
| 702 | 713 | title: `${box.name} console`, |
| 703 | keys: [binding([":"], "run a command")], | |
| 714 | keys: [binding([":"], "run a command"), binding(["t"], "take back a waiting one")], | |
| 704 | 715 | async load(signal) { |
| 705 | 716 | // Each sync may bring an answer: redraw then, and stop listening when the screen goes. |
| 706 | 717 | const off = watchBox(f.app, box.id, () => ctx.invalidate()); |
| @@ -714,7 +725,13 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 714 | 725 | lines.slice(-body!.h).forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w)); |
| 715 | 726 | }, |
| 716 | 727 | key(e) { |
| 717 | if (e.ctrl || e.alt || e.key !== ":") return false; | |
| 728 | if (e.ctrl || e.alt) return false; | |
| 729 | if (e.key === "t") { | |
| 730 | note = takeBackNewest(f, box, blocks()); | |
| 731 | ctx.invalidate(); | |
| 732 | return true; | |
| 733 | } | |
| 734 | if (e.key !== ":") return false; | |
| 718 | 735 | ctx.push( |
| 719 | 736 | promptScreen(ctx, screen, { |
| 720 | 737 | title: "Console", |
src/web/pages/games.ts +16
| @@ -14,6 +14,7 @@ import { packRow } from "../../games/client_pack.ts"; | ||
| 14 | 14 | import { packCheckLines } from "../../games/pack_check.ts"; |
| 15 | 15 | import { playersBlock } from "./games_players.ts"; |
| 16 | 16 | import { queueShell } from "../../games/shell.ts"; |
| 17 | import { takeBack } from "../../games/take_back.ts"; | |
| 17 | 18 | import { getUserById, getUserByName } from "../../core/users.ts"; |
| 18 | 19 | import { blockChanges, serviceBlocks, shellBlocks, shellSays } from "../../terminal/blocks.ts"; |
| 19 | 20 | import { blockEvent, blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts"; |
| @@ -29,6 +30,7 @@ import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, ty | ||
| 29 | 30 | import { |
| 30 | 31 | bootWords, |
| 31 | 32 | boxNamed, |
| 33 | commandOf, | |
| 32 | 34 | grant, |
| 33 | 35 | grantsOf, |
| 34 | 36 | jarHref, |
| @@ -373,6 +375,20 @@ export async function gameShellSubmit(ctx: Ctx): Promise<Response> { | ||
| 373 | 375 | return flashTo(ctx, `/games/${got.box.name}`, queued.ok ? { message: "Sent; the answer shows in the console." } : { tone: "danger", message: queued.error }); |
| 374 | 376 | } |
| 375 | 377 | |
| 378 | // POST /games/:box/take-back: a typed command not handed to the box yet. Who may is the command's own (`takeBack`). | |
| 379 | export async function gameTakeBackSubmit(ctx: Ctx): Promise<Response> { | |
| 380 | const box = boxNamed(ctx.app.db, ctx.params.box ?? ""); | |
| 381 | if (box === undefined || !seesBox(ctx.app.db, ctx.auth.user, box.id)) return notFoundPage(ctx); | |
| 382 | const form = await readForm(ctx, "rw"); | |
| 383 | if (form instanceof Response) return form; | |
| 384 | const took = takeBack(ctx.app, ctx.auth.user?.id, box, field(form, "command")); | |
| 385 | // Its own page, also when it was refused: only who may see the command is sent there. | |
| 386 | const c = commandOf(ctx.app.db, field(form, "command")); | |
| 387 | const service = c?.boxId === box.id ? c.service : ""; | |
| 388 | const back = service !== "" && roleOn(ctx.app.db, ctx.auth.user, box.id, service) !== undefined ? `/games/${box.name}/${service}#console` : `/games/${box.name}`; | |
| 389 | return flashTo(ctx, back, took.ok ? { message: `Taken back, it never ran: ${took.value.text}` } : { tone: "danger", message: took.error }); | |
| 390 | } | |
| 391 | ||
| 376 | 392 | // GET /games/:box/@shell/stream: the console's answers as they come back, the owner's alone. |
| 377 | 393 | export function gameShellStream(ctx: Ctx): Response { |
| 378 | 394 | const got = boxOf(ctx, "owner"); |
src/web/terminal_blocks.ts +3 −3
| @@ -3,13 +3,13 @@ | ||
| 3 | 3 | * place as its state changes. With no script the same page works by reloading. |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | import { AUDIT_SAYS, blockSays, type Block } from "../terminal/blocks.ts"; | |
| 6 | import { AUDIT_SAYS, blockSays, mayTakeBack, type Block } from "../terminal/blocks.ts"; | |
| 7 | 7 | import { html, type Html } from "./html.ts"; |
| 8 | 8 | 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}" ${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"> | |
| 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", data: { edit: "" }, label: `Edit ${b.text} in the input` })}` : null}</p><p class="muted small" data-says>${blockSays(b, box)}</p>${mayTakeBack(b) ? html`<form method="post" action="/games/${box.name}/take-back">${btn("Take back", { size: "sm", variant: "secondary", name: "command", value: b.id, label: `Take back ${b.text}` })}</form>` : null}${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 | |
| @@ -88,7 +88,7 @@ export const terminalBlocksJs = /* js */ ` | ||
| 88 | 88 | }); |
| 89 | 89 | // A phone has no arrows: a block's button puts its command in the input, and runs nothing. |
| 90 | 90 | document.addEventListener('click', function (e) { |
| 91 | var again = e.target.closest('[data-command] button'); | |
| 91 | var again = e.target.closest('[data-command] [data-edit]'); | |
| 92 | 92 | if (!again) return; |
| 93 | 93 | input.value = again.closest('[data-command]').getAttribute('data-command'); |
| 94 | 94 | at = -1; |
src/web/ui.ts +9 −4
| @@ -157,6 +157,8 @@ export interface BtnOptions { | ||
| 157 | 157 | /** A toggle: emits `aria-pressed` with its state. */ |
| 158 | 158 | pressed?: boolean; |
| 159 | 159 | extra?: string; |
| 160 | /** `data-` attributes a page's script finds it by. */ | |
| 161 | data?: Readonly<Record<string, string>>; | |
| 160 | 162 | /** The element's id, for a script or a fragment link that finds it. */ |
| 161 | 163 | id?: string; |
| 162 | 164 | /** |
| @@ -166,6 +168,11 @@ export interface BtnOptions { | ||
| 166 | 168 | rel?: "next" | "prev"; |
| 167 | 169 | } |
| 168 | 170 | |
| 171 | const dataAttrs = (data: Readonly<Record<string, string>> = {}): Html[] => | |
| 172 | Object.entries(data) | |
| 173 | .filter(([key]) => /^[a-z][a-z-]*$/.test(key)) | |
| 174 | .map(([key, value]) => html` data-${raw(key)}="${value}"`); | |
| 175 | ||
| 169 | 176 | function btnAttrs(o: BtnOptions): Html { |
| 170 | 177 | return html`${o.id ? html`id="${o.id}" ` : null}class="btn${o.extra ? ` ${o.extra}` : ""}" |
| 171 | 178 | ${o.variant ? html`data-variant="${o.variant}"` : null} |
| @@ -173,7 +180,7 @@ function btnAttrs(o: BtnOptions): Html { | ||
| 173 | 180 | ${o.title ? html`title="${o.title}"` : null} |
| 174 | 181 | ${o.label ? html`aria-label="${o.label}"` : null} |
| 175 | 182 | ${o.shortcut ? html`data-shortcut="${o.shortcut}" ${hintAttr(o.shortcut)}` : null} |
| 176 | ${o.copy ? html`data-copy="${o.copy}"` : null} | |
| 183 | ${o.copy ? html`data-copy="${o.copy}"` : null}${dataAttrs(o.data)} | |
| 177 | 184 | ${o.pressed !== undefined ? html`aria-pressed="${o.pressed ? "true" : "false"}"` : null}${o.current ? raw('aria-current="page"') : null}`; |
| 178 | 185 | } |
| 179 | 186 | |
| @@ -1077,9 +1084,7 @@ export function row(o: RowOptions): Html { | ||
| 1077 | 1084 | const attrs = html`class="row" |
| 1078 | 1085 | ${o.state ? html`data-state="${o.state}"` : null} |
| 1079 | 1086 | ${o.nav ? raw('data-nav tabindex="-1"') : null}${treeAttrs}`; |
| 1080 | const data = Object.entries(o.data ?? {}) | |
| 1081 | .filter(([key]) => /^[a-z][a-z-]*$/.test(key)) | |
| 1082 | .map(([key, value]) => html` data-${raw(key)}="${value}"`); | |
| 1087 | const data = dataAttrs(o.data); | |
| 1083 | 1088 | return html`<li${o.id === undefined ? null : html` id="${o.id}"`}${o.after === undefined ? null : raw(' class="has-after"')}${data}${o.apart === undefined ? null : html` data-apart="${o.apart}"`}${o.tree !== undefined ? raw(' role="none"') : o.current ? raw(' aria-current="true"') : null}> |
| 1084 | 1089 | ${o.fold !== undefined |
| 1085 | 1090 | ? html`<details id="${o.fold.id}" ${o.fold.open ? raw("open") : null}> |
test/conversation-ask.test.ts +1
| @@ -524,6 +524,7 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 524 | 524 | ["infra", { action: "apply", id: "plan-0123456789abcdef", names: ["canary1", "trevato"] }, "Clear the dead rows canary1, trevato: nothing exists at the provider for them, so only the forge's rows go and nothing is deleted there."], |
| 525 | 525 | ["games", { action: "power", box: "net", service: "hub", kind: "restart" }, "Restart hub on net."], |
| 526 | 526 | ["games", { action: "console", box: "net", service: "hub", text: "say hi" }, 'Run "say hi" in the console of hub on net.'], |
| 527 | ["games", { action: "take_back", box: "net", command: "01x" }, "Take back a command net was not handed yet."], | |
| 527 | 528 | ["games", { action: "env", box: "net", service: "hub", key: "MOTD", value: "Hello" }, "Set MOTD on hub on net to Hello, a commit that redeploys it."], |
| 528 | 529 | ["games", { action: "mods_install", box: "net", service: "survival", project: "waystones" }, "Install waystones and what it requires on survival on net, a commit that restarts it."], |
| 529 | 530 | ["games", { action: "config_set", box: "net", service: "hub", key: "view-distance", value: "12", dryRun: false }, "Set the setting view-distance on hub on net to 12, a commit that restarts it."], |
test/terminal-blocks.test.ts +72 −1
| @@ -10,10 +10,12 @@ import { join } from "node:path"; | ||
| 10 | 10 | import { Window } from "happy-dom"; |
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 12 | import { createSession } from "../src/core/sessions.ts"; |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 13 | 14 | import { createUser, type User } from "../src/core/users.ts"; |
| 14 | 15 | import { synced } from "../src/games/notify.ts"; |
| 15 | 16 | import { queueShell } from "../src/games/shell.ts"; |
| 16 | import { boxNamed, createGameBox, grant, queueCommand, recordSync } from "../src/games/store.ts"; | |
| 17 | import { boxNamed, commandOf, createGameBox, grant, queueCommand, recentCommands, recordSync } from "../src/games/store.ts"; | |
| 18 | import { takeBack } from "../src/games/take_back.ts"; | |
| 17 | 19 | import { forgeHttp } from "../src/http/server.ts"; |
| 18 | 20 | import { serviceBlocks } from "../src/terminal/blocks.ts"; |
| 19 | 21 | import { createForgeApp } from "../src/tui/forge.ts"; |
| @@ -180,6 +182,71 @@ test("up and down walk the blocks on the page, one sent since too, each command | ||
| 180 | 182 | } |
| 181 | 183 | }); |
| 182 | 184 | |
| 185 | test("a waiting command is taken back in one statement: never handed out, said on the page and in the audit", async () => { | |
| 186 | const id = ask("rm -r old"); | |
| 187 | const post = (command: string, who: User): Promise<Response> => | |
| 188 | Promise.resolve(http.handle(new Request("http://forge.test/games/mc/take-back", { method: "POST", headers: { cookie: `forge_session=${createSession(app.db, who.id).token}`, origin: "http://forge.test" }, body: new URLSearchParams({ command }) }))); | |
| 189 | const page = await open(ada); | |
| 190 | try { | |
| 191 | const doc = page.win.document; | |
| 192 | const form = doc.querySelector(`#block-${id} form`)!; | |
| 193 | expect(form.getAttribute("action")).toBe("/games/mc/take-back"); | |
| 194 | expect(form.querySelector("button")!.getAttribute("value")).toBe(id); | |
| 195 | // Its click is the form's, not Edit's. | |
| 196 | (form.querySelector("button") as unknown as { dispatchEvent(e: unknown): void }).dispatchEvent(new page.win.MouseEvent("click", { bubbles: true, cancelable: true })); | |
| 197 | expect((doc.getElementById("shell-command") as unknown as { value: string }).value).toBe(""); | |
| 198 | // One who may not run it may not take it back, and is told nothing of it. | |
| 199 | grant(app.db, box().id, bob.id, "operator"); | |
| 200 | await post(id, bob); | |
| 201 | expect(commandOf(app.db, id)).toMatchObject({ handed: false, takenBack: false }); | |
| 202 | const res = await post(id, ada); | |
| 203 | expect([res.status, res.headers.get("location")]).toEqual([303, "/games/mc#shell"]); | |
| 204 | await pollUntil(() => doc.querySelector(`#block-${id} [data-says]`)?.textContent === "Taken back; it never ran", "the block says so"); | |
| 205 | expect(doc.querySelector(`#block-${id} form`) === null).toBe(true); | |
| 206 | } finally { | |
| 207 | await page.close(); | |
| 208 | } | |
| 209 | expect(recordSync(app.db, box(), { light: true }).map((c) => c.id)).not.toContain(id); | |
| 210 | const said = app.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'game.command.taken_back'").all(); | |
| 211 | expect(said.map((e) => JSON.parse(e.payload))).toEqual([{ box: "mc", service: "", command: id, text: "rm -r old" }]); | |
| 212 | expect(takeBack(app, ada.id, box(), id)).toEqual({ ok: false, error: "It was already taken back." }); | |
| 213 | }); | |
| 214 | ||
| 215 | test("the box was first: the race is lost in words, and the command keeps its answer", () => { | |
| 216 | const id = ask("date"); | |
| 217 | expect(recordSync(app.db, box(), { light: true }).map((c) => c.id)).toContain(id); | |
| 218 | expect(takeBack(app, ada.id, box(), id)).toEqual({ ok: false, error: "It was already handed to the box." }); | |
| 219 | recordSync(app.db, box(), { light: true, results: [{ id, ok: true, output: "today" }] }); | |
| 220 | expect(commandOf(app.db, id)).toMatchObject({ takenBack: false, ok: true, output: "today" }); | |
| 221 | expect(takeBack(app, ada.id, box(), id)).toEqual({ ok: false, error: "It has already ended." }); | |
| 222 | }); | |
| 223 | ||
| 224 | test("a refused command is no one's to take back: it ended as it was refused, and the box never had it", () => { | |
| 225 | expect(queueShell(app, ada, box(), "less /etc/os-release").ok).toBe(false); | |
| 226 | const refused = recentCommands(app.db, box().id, "").find((c) => c.text === "less /etc/os-release")!; | |
| 227 | expect(takeBack(app, ada.id, box(), refused.id)).toEqual({ ok: false, error: "It has already ended." }); | |
| 228 | expect(commandOf(app.db, refused.id)).toMatchObject({ ok: false, takenBack: false }); | |
| 229 | }); | |
| 230 | ||
| 231 | test("a service's operator takes back its rcon over MCP; power work and another box's command are not theirs to take", async () => { | |
| 232 | grant(app.db, box().id, bob.id, "operator"); | |
| 233 | createGameBox(app.db, { name: "other" }); | |
| 234 | const other = boxNamed(app.db, "other")!; | |
| 235 | const rcon = queueCommand(app.db, box().id, "hub", "rcon", "say hi", bob.id); | |
| 236 | const no = { ok: false as const, error: "No command of yours to take back here." }; | |
| 237 | expect(takeBack(app, bob.id, box(), queueCommand(app.db, box().id, "hub", "restart", "", bob.id))).toEqual(no); | |
| 238 | expect(takeBack(app, ada.id, other, rcon)).toEqual(no); | |
| 239 | const got = await http.handle( | |
| 240 | new Request("http://forge.test/mcp", { | |
| 241 | method: "POST", | |
| 242 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${createToken(app.db, bob.id, "w", "admin").token}` }, | |
| 243 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { action: "take_back", box: "mc", command: rcon } } }), | |
| 244 | }), | |
| 245 | ); | |
| 246 | expect(await got.text()).toContain("Taken back, it never ran: say hi"); | |
| 247 | expect(commandOf(app.db, rcon)).toMatchObject({ takenBack: true }); | |
| 248 | }); | |
| 249 | ||
| 183 | 250 | test("the page says it is root and what the audit keeps, beside the input", async () => { |
| 184 | 251 | const page = await open(ada); |
| 185 | 252 | expect(page.shell()).toContain("A shell on mc, as root"); |
| @@ -250,6 +317,10 @@ test("the terminal draws the same blocks, and its prompt says what the audit kee | ||
| 250 | 317 | expect(shown).toContain("$ free -m"); |
| 251 | 318 | expect(shown).toContain("(Waiting for mc's next check-in)"); |
| 252 | 319 | expect(shown).toContain("(Failed, and it printed nothing)"); |
| 320 | terminal.feed("t"); | |
| 321 | await settleApp(tui); | |
| 322 | expect(tui.screen.toText()).toContain("Taken back, it never ran: free -m"); | |
| 323 | expect(tui.screen.toText()).toContain("(Taken back; it never ran)"); | |
| 253 | 324 | terminal.feed(":"); |
| 254 | 325 | await settleApp(tui); |
| 255 | 326 | expect(tui.screen.toText()).toContain("The audit keeps commands and output, secrets too."); |
new above
offline