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

A command the box was not handed yet can be taken back #17933

opened this

Merged 23h 43m ago, live in production

sold/take-back → main 0 commits

  • Merged. sold/take-back was merged into main as 703a520.

Review

Sign in to review this change.
16 files changed +193 −25
docs/features/game-box.md +1 −1

Diff not shown — a line 2,237 characters wide (limit 2,000). +1 −1

View file
docs/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
181181
182182 `/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.
183183
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.
185185
186186 ## On a phone (#17656)
187187
src/core/event_audience.ts +2
@@ -265,6 +265,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
265265 kind.startsWith("runner.") ||
266266 // A shell on a game box and everything it said: its owner's, the forge admin's (`games/shell.ts`).
267267 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" ||
268270 // Which forges this one lends runners to is its admin's too (`actions/lending.ts`).
269271 kind.startsWith("lending.") ||
270272 // 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>> = {
334334 games: (a) => {
335335 const on = `${clause("", val(a, "service"), " on ")}${val(a, "box") || "a game box"}`;
336336 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`;
337338 if (a["action"] === "power") return `${val(a, "kind") || "Restart"} ${on}`.replace(/^./, (c) => c.toUpperCase());
338339 if (a["action"] === "env") return `Set ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that redeploys it`;
339340 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
370370
371371 export interface CommandState {
372372 readonly id: string;
373 readonly boxId: string;
373374 readonly kind: string;
374375 readonly service: string;
375376 readonly text: string;
376377 readonly handed: boolean;
377378 readonly done: boolean;
378379 readonly ok: boolean | null;
380 /** Taken back before the box was handed it: it never ran. */
381 readonly takenBack: boolean;
379382 readonly output: string;
380383 /** When the answer was recorded; empty until then. */
381384 readonly doneAt: string;
@@ -383,7 +386,7 @@ export interface CommandState {
383386 readonly afterLog: number | null;
384387 }
385388 /** 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.";
387390 /** 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. */
388391 const ANSWER_MS = 2 * 60_000;
389392 const JOB_ANSWER_MS = 2 * 3_600_000;
@@ -392,27 +395,34 @@ const JOB_ANSWER_MS = 2 * 3_600_000;
392395 export function commandOf(db: Database, id: string, now = Date.now()): CommandState | undefined {
393396 const r = db
394397 .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 },
396399 [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")
398401 .get(id);
399402 if (r === null) return undefined;
400403 const limit = ["rcon", "people", "tell", "shell"].includes(r.kind) ? ANSWER_MS : JOB_ANSWER_MS;
401404 const unanswered = r.done_at === "" && r.handed_at !== "" && now - Date.parse(r.handed_at) > limit;
402405 return {
403406 id: r.id,
407 boxId: r.box_id,
404408 kind: r.kind,
405409 service: r.service,
406410 text: r.text,
407411 handed: r.handed_at !== "",
408412 done: r.done_at !== "" || unanswered,
409413 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,
410416 output: unanswered ? NO_ANSWER : r.output,
411417 doneAt: r.done_at,
412418 afterLog: r.after_log,
413419 };
414420 }
415421
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
416426 /** A service's RCON commands as typed, newest first, each once: the console's history. */
417427 export const commandHistory = (db: Database, boxId: string, service: string, limit = 50): string[] =>
418428 db
@@ -742,8 +752,9 @@ export function recordSync(
742752 { id: string; kind: string; service: string; text: string },
743753 [string]
744754 >("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);
747758 // A world import's link is a secret (a signed URL): it goes to the box once, in this reply, and
748759 // what stays is its host and path (`worlds.ts`).
749760 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";
2020 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, swapGameBoxToken, type SyncBody } from "../games/store.ts";
2121 import { BODY_CAPS } from "../kernel/body_caps.ts";
2222 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,
2424 } from "../web/pages/games.ts";
2525 import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts";
2626 import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts";
@@ -138,6 +138,7 @@ export function gamesRoutes(router: Router<Handler>): void {
138138 // Before the service routes: no compose service can be named "@shell".
139139 router.add("POST", "/games/:box/@shell", gameShellSubmit);
140140 router.add("GET", "/games/:box/@shell/stream", gameShellStream);
141 router.add("POST", "/games/:box/take-back", gameTakeBackSubmit);
141142 router.add("POST", "/games/:box/servers", gameServersSubmit);
142143 router.add("GET", "/games/:box/:service", gameServicePage);
143144 router.add("GET", "/games/:box/:service/stream", gameServiceStream);
src/http/lazy_lists.ts +1
@@ -639,6 +639,7 @@ export const OPERATIONS_ROUTES = [
639639 ["POST", "/games/:box/lend"],
640640 ["POST", "/games/:box/@shell"],
641641 ["GET", "/games/:box/@shell/stream"],
642 ["POST", "/games/:box/take-back"],
642643 ["POST", "/games/:box/servers"],
643644 ["GET", "/games/:box/:service"],
644645 ["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 file
src/terminal/blocks.ts +9 −4
@@ -13,14 +13,14 @@ import { mayDo, NO_ANSWER, recentCommands, roleOn, type CommandState, type GameB
1313 export interface Block {
1414 readonly id: string;
1515 readonly text: string;
16 readonly state: "queued" | "sent" | "ok" | "failed" | "unanswered";
16 readonly state: "queued" | "sent" | "ok" | "failed" | "unanswered" | "back";
1717 /** A command that was typed, and may be again: an Edit, and up and down. World and power work is no command to type. */
1818 readonly typed: boolean;
1919 /** What it printed; empty until it is answered. */
2020 readonly output: string;
2121 /** 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. */
2222 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. */
2424 readonly at: string;
2525 }
2626
@@ -32,8 +32,8 @@ export const shellSays = (box: Pick<GameBox, "name">): string =>
3232 `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.`;
3333
3434 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 };
3737 }
3838
3939 /** 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
4545 .map((c) => blockOf(c, c.text, true));
4646 }
4747
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
4851 /** A block's state in words. */
4952 export function blockSays(b: Block, box: Pick<GameBox, "name">): string {
5053 switch (b.state) {
@@ -54,6 +57,8 @@ export function blockSays(b: Block, box: Pick<GameBox, "name">): string {
5457 return `${box.name} has it`;
5558 case "unanswered":
5659 return NO_ANSWER;
60 case "back":
61 return "Taken back; it never ran";
5762 default:
5863 return `${b.state === "ok" ? "Done" : "Failed"}${b.output === "" ? ", and it printed nothing" : ""}`;
5964 }
src/tui/screens/games.ts +20 −3
@@ -20,7 +20,8 @@ import { ageWords, type LogPage } from "../../logs/page.ts";
2020 import { LogPane } from "../ui/log_pane.ts";
2121 import { commitPolicy, policyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts";
2222 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";
2425 import { watchBox } from "../../games/notify.ts";
2526 import { containersIn, figuresOf } from "../../cloud/containers.ts";
2627 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 {
291292 const PARTS = ["console", "env", "people", "world"] as const;
292293 type Part = (typeof PARTS)[number];
293294
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
294303 /**
295304 * One service, as /games/<box>/<service>: `tab` moves between its console and env, `m` opens its
296305 * 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
396405 binding(["y"], "copy"),
397406 binding(["G"], "end of the log, and follow"),
398407 binding([":"], "rcon"),
408 binding(["t"], "take back a waiting command"),
399409 binding(["e"], "set env"),
400410 binding(["m"], "mods"),
401411 binding(["f"], "plugin config files"),
@@ -439,6 +449,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
439449 part = "console";
440450 return "Sent; the answer shows under the console.";
441451 }, commandHistory(f.app.db, box.id, service));
452 else if (e.key === "t") say(takeBackNewest(f, box, blocks()));
442453 else if (e.key === "e")
443454 ask("Env", `KEY=VALUE (an empty value removes the key). ${SAVE_WORDS}`, async (raw) => {
444455 const at = raw.indexOf("=");
@@ -700,7 +711,7 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
700711 const blocks = () => shellBlocks(f.app, f.user?.id, box) ?? [];
701712 const screen: Screen = {
702713 title: `${box.name} console`,
703 keys: [binding([":"], "run a command")],
714 keys: [binding([":"], "run a command"), binding(["t"], "take back a waiting one")],
704715 async load(signal) {
705716 // Each sync may bring an answer: redraw then, and stop listening when the screen goes.
706717 const off = watchBox(f.app, box.id, () => ctx.invalidate());
@@ -714,7 +725,13 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
714725 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));
715726 },
716727 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;
718735 ctx.push(
719736 promptScreen(ctx, screen, {
720737 title: "Console",
src/web/pages/games.ts +16
@@ -14,6 +14,7 @@ import { packRow } from "../../games/client_pack.ts";
1414 import { packCheckLines } from "../../games/pack_check.ts";
1515 import { playersBlock } from "./games_players.ts";
1616 import { queueShell } from "../../games/shell.ts";
17 import { takeBack } from "../../games/take_back.ts";
1718 import { getUserById, getUserByName } from "../../core/users.ts";
1819 import { blockChanges, serviceBlocks, shellBlocks, shellSays } from "../../terminal/blocks.ts";
1920 import { blockEvent, blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts";
@@ -29,6 +30,7 @@ import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, ty
2930 import {
3031 bootWords,
3132 boxNamed,
33 commandOf,
3234 grant,
3335 grantsOf,
3436 jarHref,
@@ -373,6 +375,20 @@ export async function gameShellSubmit(ctx: Ctx): Promise<Response> {
373375 return flashTo(ctx, `/games/${got.box.name}#shell`, queued.ok ? { message: "Sent; the answer shows in the console." } : { tone: "danger", message: queued.error });
374376 }
375377
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}#shell`;
389 return flashTo(ctx, back, took.ok ? { message: `Taken back, it never ran: ${took.value.text}` } : { tone: "danger", message: took.error });
390 }
391
376392 // GET /games/:box/@shell/stream: the console's answers as they come back, the owner's alone.
377393 export function gameShellStream(ctx: Ctx): Response {
378394 const got = boxOf(ctx, "owner");
src/web/terminal_blocks.ts +3 −3
@@ -3,13 +3,13 @@
33 * place as its state changes. With no script the same page works by reloading.
44 */
55
6 import { AUDIT_SAYS, blockSays, type Block } from "../terminal/blocks.ts";
6 import { AUDIT_SAYS, blockSays, mayTakeBack, type Block } from "../terminal/blocks.ts";
77 import { html, type Html } from "./html.ts";
88 import { btn, field } from "./ui.ts";
99
1010 /** One command: what was typed, its state, what it printed. */
1111 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">
1313 ${b.output}</pre>`}</div>`;
1414 }
1515
@@ -88,7 +88,7 @@ export const terminalBlocksJs = /* js */ `
8888 });
8989 // A phone has no arrows: a block's button puts its command in the input, and runs nothing.
9090 document.addEventListener('click', function (e) {
91 var again = e.target.closest('[data-command] button');
91 var again = e.target.closest('[data-command] [data-edit]');
9292 if (!again) return;
9393 input.value = again.closest('[data-command]').getAttribute('data-command');
9494 at = -1;
src/web/ui.ts +9 −4
@@ -157,6 +157,8 @@ export interface BtnOptions {
157157 /** A toggle: emits `aria-pressed` with its state. */
158158 pressed?: boolean;
159159 extra?: string;
160 /** `data-` attributes a page's script finds it by. */
161 data?: Readonly<Record<string, string>>;
160162 /** The element's id, for a script or a fragment link that finds it. */
161163 id?: string;
162164 /**
@@ -166,6 +168,11 @@ export interface BtnOptions {
166168 rel?: "next" | "prev";
167169 }
168170
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
169176 function btnAttrs(o: BtnOptions): Html {
170177 return html`${o.id ? html`id="${o.id}" ` : null}class="btn${o.extra ? ` ${o.extra}` : ""}"
171178 ${o.variant ? html`data-variant="${o.variant}"` : null}
@@ -173,7 +180,7 @@ function btnAttrs(o: BtnOptions): Html {
173180 ${o.title ? html`title="${o.title}"` : null}
174181 ${o.label ? html`aria-label="${o.label}"` : null}
175182 ${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)}
177184 ${o.pressed !== undefined ? html`aria-pressed="${o.pressed ? "true" : "false"}"` : null}${o.current ? raw('aria-current="page"') : null}`;
178185 }
179186
@@ -1077,9 +1084,7 @@ export function row(o: RowOptions): Html {
10771084 const attrs = html`class="row"
10781085 ${o.state ? html`data-state="${o.state}"` : null}
10791086 ${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);
10831088 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}>
10841089 ${o.fold !== undefined
10851090 ? 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])[] = [
524524 ["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."],
525525 ["games", { action: "power", box: "net", service: "hub", kind: "restart" }, "Restart hub on net."],
526526 ["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."],
527528 ["games", { action: "env", box: "net", service: "hub", key: "MOTD", value: "Hello" }, "Set MOTD on hub on net to Hello, a commit that redeploys it."],
528529 ["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."],
529530 ["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";
1010 import { Window } from "happy-dom";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { createSession } from "../src/core/sessions.ts";
13 import { createToken } from "../src/core/tokens.ts";
1314 import { createUser, type User } from "../src/core/users.ts";
1415 import { synced } from "../src/games/notify.ts";
1516 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";
1719 import { forgeHttp } from "../src/http/server.ts";
1820 import { serviceBlocks } from "../src/terminal/blocks.ts";
1921 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
180182 }
181183 });
182184
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
183250 test("the page says it is root and what the audit keeps, beside the input", async () => {
184251 const page = await open(ada);
185252 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
250317 expect(shown).toContain("$ free -m");
251318 expect(shown).toContain("(Waiting for mc's next check-in)");
252319 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)");
253324 terminal.feed(":");
254325 await settleApp(tui);
255326 expect(tui.screen.toText()).toContain("The audit keeps commands and output, secrets too.");

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

Keyboard shortcuts

Docs