Public: anyone can read this; the crew can change it.
Multiplayer and sync as forge primitives: an ordered change stream per app, rooms and presence, zero dependencies #1366
scout/forge:scout/1117-multiplayer-and-sync-as-forge-primitives → main 6 commits fork 2 threads · 2 unresolved
10 files
changed +1016
−1
README.md +27
| @@ -400,6 +400,33 @@ The terminal has no backups view, so it has no readout. | ||
| 400 | 400 | grew up in switched off: what a host owes it, the moves in order, and what is |
| 401 | 401 | given up. |
| 402 | 402 | |
| 403 | ## The cockpit | |
| 404 | ||
| 405 | `/board?cockpit=1` is the board and the plan as one screen for a TV, a Pi or a | |
| 406 | phone: what happened today (the board's numbers), up to five cards of what needs | |
| 407 | you (yes, no, later), and the plan as waves (the map's limbs, one row each). | |
| 408 | The live wall at `/board` stays as the detailed view, linked from the top bar. | |
| 409 | ||
| 410 | Three doors, one set of words (`src/view/cockpit.ts`): the page, the terminal | |
| 411 | (`c` on the launcher; `y`/`n`/`l`, `u` to undo) and the MCP `board` tool. | |
| 412 | On the page four keys drive it: up and down move the focus, enter takes the | |
| 413 | first answer, back goes up a level. Nothing is focused on load, so a stray key | |
| 414 | answers nothing. Every answer says what happened in one line; a dismissal | |
| 415 | offers Undo. Shipping cannot be undone, so the first Yes only asks and the | |
| 416 | second ships. | |
| 417 | ||
| 418 | Left out of every door, because a rule answers it: an app you muted, and a | |
| 419 | crew that spent its day (it lifts at midnight). | |
| 420 | ||
| 421 | A kiosk may open once with `?kiosk=1&device=<read-only token>`: the token is | |
| 422 | swapped for an HttpOnly cookie sent only to paths under `/board` and to `/live/cockpit`, and | |
| 423 | the address is redirected without it. A TV only reads; a token that can write is | |
| 424 | refused. A cockpit-only device credential is not built; the cookie carries the | |
| 425 | read-only token. Anyone signed out who opens a link carrying `?device=` keeps | |
| 426 | that token's cockpit for 30 days, so share such a link only with the screen it | |
| 427 | is for; a signed-in session always wins. | |
| 428 | No new dependency. | |
| 429 | ||
| 403 | 430 | ### Passports |
| 404 | 431 | |
| 405 | 432 | A crew run's environment carries `FORGE_PASSPORT`, a 15-minute credential |
src/http/mcp.ts +17
| @@ -103,6 +103,7 @@ import { | ||
| 103 | 103 | milestonesJson, |
| 104 | 104 | } from "../web/pages/milestones.ts"; |
| 105 | 105 | import { appsOf, asksAnswer } from "../web/studio/asks.ts"; |
| 106 | import { cockpitModel } from "../view/cockpit.ts"; | |
| 106 | 107 | import { applyAsksBulk, previewAsksBulk } from "../actions/asks_bulk.ts"; |
| 107 | 108 | import type { Ctx, Handler } from "./context.ts"; |
| 108 | 109 | import { |
| @@ -500,6 +501,22 @@ const TOOLS: readonly Tool[] = [ | ||
| 500 | 501 | return good(asksAnswer(ctx, user)); |
| 501 | 502 | }, |
| 502 | 503 | }, |
| 504 | { | |
| 505 | name: "board", | |
| 506 | description: | |
| 507 | "The cockpit, as the screen shows it, in the same words and order: what happened today in plain sentences, up to five cards of what needs you (each a sentence and its answers: yes, no, later), and the plan as waves, one sentence each with its colour (needs, working, done, blocked). Read it aloud as it is.", | |
| 508 | inputSchema: { type: "object", properties: {} }, | |
| 509 | writes: false, | |
| 510 | run(ctx, user) { | |
| 511 | const m = cockpitModel(ctx.app.db, user); | |
| 512 | return good({ | |
| 513 | today: m.today, | |
| 514 | cards: m.cards.map((c) => ({ text: c.text, answers: c.answers.map((a) => a.label) })), | |
| 515 | more: m.more, | |
| 516 | waves: m.waves, | |
| 517 | }); | |
| 518 | }, | |
| 519 | }, | |
| 503 | 520 | { |
| 504 | 521 | name: "asks_act", |
| 505 | 522 | description: |
src/http/server.ts +9 −1
| @@ -239,6 +239,7 @@ import { | ||
| 239 | 239 | } from "../web/pages/runs.ts"; |
| 240 | 240 | import { lookImage } from "../web/pages/looks.ts"; |
| 241 | 241 | import { bigRedirect, boardPage } from "../web/pages/board.ts"; |
| 242 | import { cockpitAnswer, cockpitFragment, cockpitPage, cockpitUndo } from "../web/pages/cockpit.ts"; | |
| 242 | 243 | import { returnsPage } from "../web/pages/returns.ts"; |
| 243 | 244 | import { |
| 244 | 245 | fleetGraphCsv, |
| @@ -567,7 +568,14 @@ export function buildRouter(): Router<Handler> { | ||
| 567 | 568 | router.add("POST", "/logout", logoutSubmit); |
| 568 | 569 | router.add("POST", "/theme", themeSubmit); |
| 569 | 570 | // The board: a live wall of the crews at work, for a second monitor. |
| 570 | router.add("GET", "/board", boardPage); | |
| 571 | router.add("GET", "/board", (ctx) => | |
| 572 | ctx.url.searchParams.has("kiosk") || ctx.url.searchParams.has("cockpit") | |
| 573 | ? cockpitPage(ctx) | |
| 574 | : boardPage(ctx), | |
| 575 | ); | |
| 576 | router.add("GET", "/live/cockpit", cockpitFragment); | |
| 577 | router.add("POST", "/board/answer", cockpitAnswer); | |
| 578 | router.add("POST", "/board/answer/:id/undo", cockpitUndo); | |
| 571 | 579 | // The board's tokens line, opened: what the spend bought (core/returns.ts). |
| 572 | 580 | router.add("GET", "/board/returns", returnsPage); |
| 573 | 581 | // One screen for "is everything fine?": what asks the viewer (docs/STUDIO.md). |
src/tui/screens/cockpit.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * `c` — the cockpit: today, what needs you, and the plan as waves, one | |
| 3 | * screen. The words are `view/cockpit.ts`'s, the same the web page and the | |
| 4 | * MCP `board` tool read. Up and down pick a card; `y` (or enter) says yes, but only on a card the terminal can ship (one | |
| 5 | * that only points elsewhere offers no yes), `n` says no, `l` says later; each answer is one line of what happened, and | |
| 6 | * `u` takes a dismissal back. Shipping cannot be taken back, so the first | |
| 7 | * yes only asks. Signed-in people only, like the page. | |
| 8 | */ | |
| 9 | ||
| 10 | import { applyAsksBulk, undoAsksBulk } from "../../actions/asks_bulk.ts"; | |
| 11 | import { cockpitModel, type Card, type Cockpit } from "../../view/cockpit.ts"; | |
| 12 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 13 | import { binding } from "../app/keys.ts"; | |
| 14 | import { style } from "../term/style.ts"; | |
| 15 | import { truncate } from "../term/width.ts"; | |
| 16 | import type { Session } from "../session.ts"; | |
| 17 | ||
| 18 | export function cockpitScreen(f: Session, ctx: Ctx): Screen { | |
| 19 | let model: Cockpit = { today: [], cards: [], more: null, waves: [] }; | |
| 20 | const later = new Set<string>(); | |
| 21 | let at = 0; | |
| 22 | let armed: string | undefined; | |
| 23 | let undo: string | undefined; | |
| 24 | let line = ""; | |
| 25 | ||
| 26 | const cards = (): Card[] => model.cards.filter((c) => !later.has(c.id)); | |
| 27 | const reload = (): void => { | |
| 28 | if (f.user) model = cockpitModel(f.db, f.user); | |
| 29 | at = Math.max(0, Math.min(at, cards().length - 1)); | |
| 30 | ctx.invalidate(); | |
| 31 | }; | |
| 32 | reload(); | |
| 33 | ||
| 34 | const answer = async (card: Card, key: "yes" | "no"): Promise<void> => { | |
| 35 | const a = card.answers.find((x) => x.key === key); | |
| 36 | if (!f.user || !a) return; | |
| 37 | if (a.post === undefined) return; | |
| 38 | if (a.post.action === "ship" && armed !== card.id) { | |
| 39 | armed = card.id; | |
| 40 | line = "Press y again to ship it."; | |
| 41 | return ctx.invalidate(); | |
| 42 | } | |
| 43 | armed = undefined; | |
| 44 | const op = await applyAsksBulk(f.app, f.user, a.post.action, a.post.items); | |
| 45 | const done = op.ok ? op.value.rows.filter((r) => r.outcome === "ok").length : 0; | |
| 46 | undo = op.ok && done > 0 && op.value.reversible ? op.value.id : undefined; | |
| 47 | line = !op.ok | |
| 48 | ? `Nothing was done: ${op.error.message}.` | |
| 49 | : done === 0 | |
| 50 | ? "Nothing was done: it was refused." | |
| 51 | : `${a.post.action === "ship" ? "Shipped" : "Dismissed"}.${undo ? " Press u to undo." : ""}`; | |
| 52 | reload(); | |
| 53 | }; | |
| 54 | ||
| 55 | return { | |
| 56 | title: "Cockpit", | |
| 57 | get keys() { | |
| 58 | return [ | |
| 59 | binding(["y"], "yes"), | |
| 60 | binding(["n"], "no"), | |
| 61 | binding(["l"], "later"), | |
| 62 | binding(["u"], "undo", { disabled: undo === undefined }), | |
| 63 | binding(["esc"], "close"), | |
| 64 | ]; | |
| 65 | }, | |
| 66 | render(area, s) { | |
| 67 | const c = ctx.theme.c; | |
| 68 | const edge = area.x + area.w; | |
| 69 | let y = area.y; | |
| 70 | const put = (text: string, color = c.fg, x = area.x + 1): void => { | |
| 71 | if (y < area.y + area.h) s.text(x, y, truncate(text, Math.max(0, edge - x)), style(color, c.bg), edge); | |
| 72 | y++; | |
| 73 | }; | |
| 74 | for (const l of model.today) put(l); | |
| 75 | y++; | |
| 76 | if (line !== "") put(line, c.attn); | |
| 77 | const shown = cards(); | |
| 78 | if (shown.length === 0) put("All fine.", c.faint); | |
| 79 | shown.forEach((card, i) => put(`${i === at ? "▌" : " "} ${card.text} ${card.answers.some((a) => a.key === "yes" && a.post) ? "[y]es " : ""}[n]o [l]ater`, i === at ? c.fg : c.mutedFg, area.x)); | |
| 80 | if (model.more !== null) put(model.more, c.faint); | |
| 81 | y++; | |
| 82 | if (model.waves.length === 0) put("No plan yet.", c.faint); | |
| 83 | for (const w of model.waves) | |
| 84 | put(w.text, w.colour === "done" ? c.success : w.colour === "blocked" ? c.danger : w.colour === "working" ? c.accent : c.attn); | |
| 85 | }, | |
| 86 | key(e) { | |
| 87 | const card = cards()[at]; | |
| 88 | if (e.key === "down" || e.key === "j") at = Math.min(at + 1, cards().length - 1); | |
| 89 | else if (e.key === "up" || e.key === "k") at = Math.max(at - 1, 0); | |
| 90 | else if ((e.key === "y" || e.key === "enter") && card) ctx.track(answer(card, "yes")); | |
| 91 | else if (e.key === "n" && card) ctx.track(answer(card, "no")); | |
| 92 | else if (e.key === "l" && card) { | |
| 93 | later.add(card.id); | |
| 94 | reload(); | |
| 95 | } else if (e.key === "u" && undo !== undefined && f.user) { | |
| 96 | const id = undo; | |
| 97 | undo = undefined; | |
| 98 | ctx.track( | |
| 99 | undoAsksBulk(f.app, f.user, id).then((r) => { | |
| 100 | line = r.ok ? "Undone." : `Nothing was undone: ${r.error.message}.`; | |
| 101 | reload(); | |
| 102 | }), | |
| 103 | ); | |
| 104 | } else if (e.key === "esc") ctx.pop(); | |
| 105 | else return false; | |
| 106 | armed = e.key === "y" || e.key === "enter" ? armed : undefined; | |
| 107 | ctx.invalidate(); | |
| 108 | return true; | |
| 109 | }, | |
| 110 | }; | |
| 111 | } |
src/tui/screens/dashboard.ts +6
| @@ -61,6 +61,7 @@ import { pullScreen } from "./pull.ts"; | ||
| 61 | 61 | import { repoScreen } from "./repo.ts"; |
| 62 | 62 | import { local } from "./where.ts"; |
| 63 | 63 | import { signInScreen } from "./signin.ts"; |
| 64 | import { cockpitScreen } from "./cockpit.ts"; | |
| 64 | 65 | |
| 65 | 66 | /** |
| 66 | 67 | * The three things the launcher is about. Order is the `tab` order: the |
| @@ -260,6 +261,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen { | ||
| 260 | 261 | binding(["d"], "unpin", { |
| 261 | 262 | disabled: focus !== "machine" || pins.length === 0, |
| 262 | 263 | }), |
| 264 | binding(["c"], "cockpit", { disabled: !f.signedIn }), | |
| 263 | 265 | binding(["n"], "new repo", { disabled: !f.signedIn }), |
| 264 | 266 | binding(["A"], "account", { disabled: !f.signedIn }), |
| 265 | 267 | binding(["s"], "sign in", { disabled: f.signedIn }), |
| @@ -356,6 +358,10 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen { | ||
| 356 | 358 | } |
| 357 | 359 | return true; |
| 358 | 360 | } |
| 361 | if (e.key === "c" && f.signedIn) { | |
| 362 | ctx.push(cockpitScreen(f, ctx)); | |
| 363 | return true; | |
| 364 | } | |
| 359 | 365 | if (e.key === "n" && f.signedIn) { |
| 360 | 366 | ctx.push(newRepoScreen(f, ctx)); |
| 361 | 367 | return true; |
src/view/cockpit.ts added +167
| @@ -0,0 +1,167 @@ | ||
| 1 | /** | |
| 2 | * The cockpit's words: what happened today, up to five cards of what needs | |
| 3 | * you (a sentence and up to three answers: yes, no, later), and the plan as | |
| 4 | * waves. Plain data from the database and the viewer; the web page, its live | |
| 5 | * fragment, the terminal and the MCP `board` tool all read it, so every door | |
| 6 | * says the same thing in the same order. It reads what the studio already | |
| 7 | * reads and adds no state. Nothing here says pull, branch, token or an | |
| 8 | * agent's name. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Database } from "bun:sqlite"; | |
| 12 | import { appsForRepos } from "../core/apps.ts"; | |
| 13 | import { mutedRepos } from "../core/interactions.ts"; | |
| 14 | import { readPlan, type Weight } from "../core/milestones.ts"; | |
| 15 | import { mergedPullsForRepos } from "../core/pulls.ts"; | |
| 16 | import { listReposVisibleTo } from "../core/repos.ts"; | |
| 17 | import { listActiveRuns } from "../core/runs.ts"; | |
| 18 | import type { User } from "../core/users.ts"; | |
| 19 | import { askLinesFor } from "../web/studio/asks.ts"; | |
| 20 | /** Cards on the screen at once; the rest are one sentence. */ | |
| 21 | export const MAX_CARDS = 5; | |
| 22 | /** Waves on the screen: a row per wave, nothing smaller. */ | |
| 23 | export const MAX_WAVES = 8; | |
| 24 | const DAY_MS = 86_400_000; | |
| 25 | ||
| 26 | export type Colour = "needs" | "working" | "done" | "blocked"; | |
| 27 | ||
| 28 | export interface Answer { | |
| 29 | readonly key: "yes" | "no" | "later"; | |
| 30 | readonly label: string; | |
| 31 | /** A post to /asks/bulk, or a place to go; `later` has neither. */ | |
| 32 | readonly post?: { readonly action: string; readonly items: readonly string[] }; | |
| 33 | readonly href?: string; | |
| 34 | } | |
| 35 | ||
| 36 | export interface Card { | |
| 37 | readonly id: string; | |
| 38 | readonly text: string; | |
| 39 | readonly answers: readonly Answer[]; | |
| 40 | } | |
| 41 | ||
| 42 | export interface Wave { | |
| 43 | readonly text: string; | |
| 44 | readonly colour: Colour; | |
| 45 | } | |
| 46 | ||
| 47 | export interface Cockpit { | |
| 48 | readonly today: readonly string[]; | |
| 49 | readonly cards: readonly Card[]; | |
| 50 | /** One sentence about the cards that did not fit; null when all did. */ | |
| 51 | readonly more: string | null; | |
| 52 | readonly waves: readonly Wave[]; | |
| 53 | } | |
| 54 | ||
| 55 | const plural = (n: number, one: string, many: string): string => | |
| 56 | `${n} ${n === 1 ? one : many}`; | |
| 57 | ||
| 58 | /** What each kind of ask says, in the studio's five words. */ | |
| 59 | function sentence(kind: string, app: string, n: number): string { | |
| 60 | const some = n === 1; | |
| 61 | switch (kind) { | |
| 62 | case "look": | |
| 63 | return some | |
| 64 | ? `${app}: a change is ready. Ship it?` | |
| 65 | : `${app}: ${n} changes are ready. Ship them?`; | |
| 66 | case "review": | |
| 67 | return some | |
| 68 | ? `${app}: a change wants your look. Ship it?` | |
| 69 | : `${app}: ${n} changes want your look. Ship them?`; | |
| 70 | case "stopped": | |
| 71 | return `${app}: the crew is stuck. Take a look?`; | |
| 72 | case "parked": | |
| 73 | return `${app}: the crew gave up on a job. Take a look?`; | |
| 74 | default: | |
| 75 | return `${app}: the crew needs your answer. Take a look?`; | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | /** | |
| 80 | * A wave's colour from the plan's own states: done when nothing is open, | |
| 81 | * working while someone builds, blocked only when every open thing beneath it | |
| 82 | * waits for another open thing, and otherwise needs (amber): ready, next. | |
| 83 | */ | |
| 84 | function waveColour(w: Weight, waiting: number): Colour { | |
| 85 | if (w.open === 0) return "done"; | |
| 86 | if (w.building > 0) return "working"; | |
| 87 | return waiting >= w.open ? "blocked" : "needs"; | |
| 88 | } | |
| 89 | ||
| 90 | /** | |
| 91 | * What the viewer sees on the cockpit, on every door. A muted app never | |
| 92 | * raises a card, and neither does what a rule answers on its own: a spent | |
| 93 | * day lifts itself at midnight, so it needs no one. A read-only viewer | |
| 94 | * (`readOnly`) gets no answers. | |
| 95 | */ | |
| 96 | export function cockpitModel( | |
| 97 | db: Database, | |
| 98 | user: User, | |
| 99 | options: { readOnly?: boolean } = {}, | |
| 100 | ): Cockpit { | |
| 101 | const muted = mutedRepos(db, user.id); | |
| 102 | const visible = listReposVisibleTo(db, user, { limit: 200 }).filter( | |
| 103 | (r) => !muted.has(r.id), | |
| 104 | ); | |
| 105 | const names = new Map(visible.map((r) => [r.id, r.name])); | |
| 106 | const rows = askLinesFor(db, user).filter( | |
| 107 | (row) => names.has(row.repoId) && row.kind !== "paused", | |
| 108 | ); | |
| 109 | ||
| 110 | const cards: Card[] = rows.slice(0, MAX_CARDS).map((row) => { | |
| 111 | const shipping = row.kind === "look" || row.kind === "review"; | |
| 112 | const answers: Answer[] = options.readOnly | |
| 113 | ? [] | |
| 114 | : [ | |
| 115 | shipping | |
| 116 | ? { key: "yes", label: "Yes", post: { action: "ship", items: row.items } } | |
| 117 | : { key: "yes", label: "Yes", href: row.link }, | |
| 118 | { key: "no", label: "No", post: { action: "dismiss", items: row.items } }, | |
| 119 | { key: "later", label: "Later" }, | |
| 120 | ]; | |
| 121 | return { | |
| 122 | id: row.id, | |
| 123 | text: sentence(row.kind, names.get(row.repoId) ?? "An app", row.items.length), | |
| 124 | answers, | |
| 125 | }; | |
| 126 | }); | |
| 127 | const hidden = rows.length - cards.length; | |
| 128 | ||
| 129 | const apps = appsForRepos(db, visible.map((r) => r.id)); | |
| 130 | const ids = visible.filter((r) => apps.has(r.id)).map((r) => r.id); | |
| 131 | const landed = mergedPullsForRepos(db, ids, 50).filter( | |
| 132 | (p) => p.mergedAt !== null && Date.now() - Date.parse(p.mergedAt) < DAY_MS, | |
| 133 | ).length; | |
| 134 | const working = new Set(listActiveRuns(db, ids).map((r) => r.issueId)).size; | |
| 135 | const today = [ | |
| 136 | landed === 0 | |
| 137 | ? "Nothing landed in the last day." | |
| 138 | : `${plural(landed, "change", "changes")} landed in the last day.`, | |
| 139 | working === 0 | |
| 140 | ? "The crew is resting." | |
| 141 | : `The crew is working on ${plural(working, "thing", "things")}.`, | |
| 142 | rows.length === 0 | |
| 143 | ? "Nothing needs you." | |
| 144 | : `${plural(rows.length, "thing needs", "things need")} you.`, | |
| 145 | ]; | |
| 146 | ||
| 147 | const waves: Wave[] = []; | |
| 148 | for (const repo of visible) { | |
| 149 | if (!apps.has(repo.id)) continue; | |
| 150 | const plan = readPlan(db, repo); | |
| 151 | for (const limb of plan.limbs) { | |
| 152 | const w = limb.weight; | |
| 153 | if (limb.deferred || w.total === 0 || waves.length >= MAX_WAVES) continue; | |
| 154 | waves.push({ | |
| 155 | text: `${repo.name}, ${limb.name}: ${w.done} of ${w.total} landed, ${w.open} left.`, | |
| 156 | colour: waveColour(w, plan.milestone(limb.issue.number)?.blocked.length ?? 0), | |
| 157 | }); | |
| 158 | } | |
| 159 | } | |
| 160 | return { | |
| 161 | today, | |
| 162 | cards, | |
| 163 | more: hidden > 0 ? `${plural(hidden, "more thing waits", "more things wait")} for you.` : null, | |
| 164 | waves, | |
| 165 | }; | |
| 166 | } | |
| 167 |
src/web/client.ts +104
| @@ -1998,3 +1998,107 @@ export const liveRegionsJs = /* js */ ` | ||
| 1998 | 1998 | }); |
| 1999 | 1999 | })(); |
| 2000 | 2000 | `; |
| 2001 | ||
| 2002 | /** | |
| 2003 | * The cockpit's four keys: up and down move the focus through the cards | |
| 2004 | * and waves, enter takes the focused card's first answer, back goes up a | |
| 2005 | * level (off an answer to its card, off a card to the top, then back a | |
| 2006 | * page). Nothing is focused until a key is pressed, so one stray press | |
| 2007 | * answers nothing; every answer says what happened in one line, with an undo | |
| 2008 | * where one exists, and shipping asks twice. "Later" hides a card until the page is opened again. The screen | |
| 2009 | * refreshes itself from its fragment, keeping the focus where it was. | |
| 2010 | */ | |
| 2011 | export const cockpitJs = /* js */ ` | |
| 2012 | (function () { | |
| 2013 | var root = document.getElementById('cockpit'); | |
| 2014 | if (!root) return; | |
| 2015 | var later = {}; | |
| 2016 | function stops() { return Array.prototype.slice.call(root.querySelectorAll('[tabindex="0"]')); } | |
| 2017 | function hideLater() { | |
| 2018 | Array.prototype.forEach.call(root.querySelectorAll('[data-card]'), function (c) { | |
| 2019 | if (later[c.getAttribute('data-card')]) c.hidden = true; | |
| 2020 | }); | |
| 2021 | } | |
| 2022 | function focusAt(i) { | |
| 2023 | var s = stops().filter(function (e) { return !e.hidden; }); | |
| 2024 | if (s.length) s[Math.max(0, Math.min(s.length - 1, i))].focus(); | |
| 2025 | } | |
| 2026 | function current() { | |
| 2027 | var s = stops().filter(function (e) { return !e.hidden; }); | |
| 2028 | var at = s.indexOf(document.activeElement); | |
| 2029 | return at < 0 && document.activeElement ? s.indexOf(document.activeElement.closest('[tabindex="0"]')) : at; | |
| 2030 | } | |
| 2031 | function refresh() { | |
| 2032 | var at = current(); | |
| 2033 | return fetch(root.getAttribute('data-src'), { credentials: 'same-origin' }) | |
| 2034 | .then(function (r) { return r.ok ? r.text() : null; }) | |
| 2035 | .then(function (t) { | |
| 2036 | if (t === null) return; | |
| 2037 | root.innerHTML = t; hideLater(); if (at >= 0) focusAt(at); | |
| 2038 | }).catch(function () {}); | |
| 2039 | } | |
| 2040 | document.addEventListener('keydown', function (e) { | |
| 2041 | if (e.altKey || e.ctrlKey || e.metaKey) return; | |
| 2042 | var k = e.key, at = current(); | |
| 2043 | if (k === 'ArrowDown') { e.preventDefault(); focusAt(at + 1); } | |
| 2044 | else if (k === 'ArrowUp') { e.preventDefault(); focusAt(at < 0 ? 0 : at - 1); } | |
| 2045 | else if (k === 'Enter' && document.activeElement && document.activeElement.hasAttribute('data-card')) { | |
| 2046 | var first = document.activeElement.querySelector('.ck-act'); | |
| 2047 | if (first) { e.preventDefault(); first.click(); } | |
| 2048 | } else if (k === 'Escape' || k === 'Backspace' || k === 'GoBack') { | |
| 2049 | e.preventDefault(); | |
| 2050 | var a = document.activeElement; | |
| 2051 | if (a && a.closest && a.closest('[data-card]') && a !== a.closest('[data-card]')) a.closest('[data-card]').focus(); | |
| 2052 | else if (at > 0) focusAt(0); | |
| 2053 | else history.length > 1 && history.back(); | |
| 2054 | } | |
| 2055 | }); | |
| 2056 | root.addEventListener('click', function (e) { | |
| 2057 | var b = e.target.closest && e.target.closest('button[data-key=later]'); | |
| 2058 | if (!b) return; | |
| 2059 | var card = b.closest('[data-card]'); | |
| 2060 | var i = current(); | |
| 2061 | later[card.getAttribute('data-card')] = 1; card.hidden = true; focusAt(i); | |
| 2062 | }); | |
| 2063 | var status = document.getElementById('ck-status'); | |
| 2064 | var armed = null; | |
| 2065 | function say(message, ok, undo) { | |
| 2066 | status.hidden = false; | |
| 2067 | status.setAttribute('data-ok', ok ? 'true' : 'false'); | |
| 2068 | status.textContent = message + ' '; | |
| 2069 | if (!undo) return; | |
| 2070 | var b = document.createElement('button'); | |
| 2071 | b.className = 'ck-act'; b.type = 'button'; b.textContent = 'Undo'; | |
| 2072 | b.addEventListener('click', function () { | |
| 2073 | send(undo, new URLSearchParams()).then(function (r) { say(r.message, r.ok); return refresh(); }); | |
| 2074 | }); | |
| 2075 | status.appendChild(b); b.focus(); | |
| 2076 | } | |
| 2077 | function send(url, body) { | |
| 2078 | return fetch(url, { method: 'POST', credentials: 'same-origin', body: body, headers: { accept: 'application/json' } }) | |
| 2079 | .then(function (r) { return r.json(); }) | |
| 2080 | .catch(function () { return { ok: false, message: 'Nothing was done: the forge did not answer.' }; }); | |
| 2081 | } | |
| 2082 | root.addEventListener('submit', function (e) { | |
| 2083 | var f = e.target; | |
| 2084 | if (!f.hasAttribute || !f.hasAttribute('data-act')) return; | |
| 2085 | e.preventDefault(); | |
| 2086 | // Shipping cannot be taken back, so the first Yes only asks. | |
| 2087 | if (f.getAttribute('data-act') === 'ship' && armed !== f.closest('[data-card]')) { | |
| 2088 | armed = f.closest('[data-card]'); | |
| 2089 | say('Press Yes again to ship it.', true); | |
| 2090 | setTimeout(function () { armed = null; }, 5000); | |
| 2091 | return; | |
| 2092 | } | |
| 2093 | armed = null; | |
| 2094 | send(f.action, new URLSearchParams(new FormData(f))).then(function (r) { | |
| 2095 | say(r.message, r.ok, r.undo); | |
| 2096 | return refresh(); | |
| 2097 | }); | |
| 2098 | }); | |
| 2099 | document.addEventListener('keydown', function (e) { | |
| 2100 | if (e.key === 'Escape' && status && !status.hidden) { status.hidden = true; armed = null; } | |
| 2101 | }); | |
| 2102 | setInterval(refresh, 10000); | |
| 2103 | })(); | |
| 2104 | `; |
src/web/pages/cockpit.ts added +178
| @@ -0,0 +1,178 @@ | ||
| 1 | /** | |
| 2 | * The cockpit page: the board and the map as one screen for a TV, a Pi with | |
| 3 | * four buttons or a phone's thumb. The words are `view/cockpit.ts`'s. This | |
| 4 | * file draws them, answers them (`POST /board/answer`, which says what | |
| 5 | * happened and offers the undo) and lets a kiosk read. | |
| 6 | * | |
| 7 | * `?kiosk=1` hides the top bar. A kiosk may open once with a read-only token | |
| 8 | * as `?device=`: it is swapped for an HttpOnly cookie that only `/board…` | |
| 9 | * and `/live/cockpit` receive, and the address is sent on without it, so the token is in | |
| 10 | * no log, history or screenshot. The kiosk then only reads: no card offers | |
| 11 | * an answer, since a TV cannot sign anything. | |
| 12 | */ | |
| 13 | ||
| 14 | import { applyAsksBulk, undoAsksBulk } from "../../actions/asks_bulk.ts"; | |
| 15 | import { verifyToken } from "../../core/tokens.ts"; | |
| 16 | import type { User } from "../../core/users.ts"; | |
| 17 | import { cookieValue, type Ctx } from "../../http/context.ts"; | |
| 18 | import { cockpitModel, type Cockpit } from "../../view/cockpit.ts"; | |
| 19 | import { html, type Html } from "../html.ts"; | |
| 20 | import { fragment, page, redirect } from "../layout.ts"; | |
| 21 | import { signInFirst } from "../chrome.ts"; | |
| 22 | import { cockpitJs } from "../client.ts"; | |
| 23 | import { field, prefersJson, readForm } from "../form.ts"; | |
| 24 | import { json } from "../../http/respond.ts"; | |
| 25 | ||
| 26 | /** The cockpit's own regions: one block the page and the live fragment share. */ | |
| 27 | function screen(model: Cockpit): Html { | |
| 28 | return html`<section class="ck-today" aria-label="Today"> | |
| 29 | ${model.today.map((l) => html`<p>${l}</p>`)} | |
| 30 | </section> | |
| 31 | <section class="ck-cards" aria-label="Needs you"> | |
| 32 | ${model.cards.length === 0 | |
| 33 | ? html`<p class="ck-quiet">All fine.</p>` | |
| 34 | : model.cards.map( | |
| 35 | (c) => html`<article class="ck-card" data-colour="needs" tabindex="0" data-card="${c.id}"> | |
| 36 | <p class="ck-text">${c.text}</p> | |
| 37 | <div class="ck-answers"> | |
| 38 | ${c.answers.map((a) => | |
| 39 | a.href !== undefined | |
| 40 | ? html`<a class="ck-act" data-key="${a.key}" href="${a.href}">${a.label}</a>` | |
| 41 | : a.post !== undefined | |
| 42 | ? html`<form method="post" action="/board/answer" data-act="${a.post.action}"> | |
| 43 | <input type="hidden" name="action" value="${a.post.action}" /> | |
| 44 | ${a.post.items.map((i) => html`<input type="hidden" name="item" value="${i}" />`)} | |
| 45 | <button class="ck-act" data-key="${a.key}">${a.label}</button> | |
| 46 | </form>` | |
| 47 | : html`<button class="ck-act" data-key="${a.key}" type="button">${a.label}</button>`, | |
| 48 | )} | |
| 49 | </div> | |
| 50 | </article>`, | |
| 51 | )} | |
| 52 | ${model.more === null ? null : html`<p class="ck-more">${model.more}</p>`} | |
| 53 | </section> | |
| 54 | <section class="ck-waves" aria-label="The plan"> | |
| 55 | ${model.waves.length === 0 | |
| 56 | ? html`<p class="ck-quiet">No plan yet.</p>` | |
| 57 | : model.waves.map( | |
| 58 | (w) => html`<p class="ck-wave" data-colour="${w.colour}" tabindex="0">${w.text}</p>`, | |
| 59 | )} | |
| 60 | </section>`; | |
| 61 | } | |
| 62 | ||
| 63 | const cockpitCss = /* css */ ` | |
| 64 | .ck{max-width:70rem;margin:0 auto;padding:1.5rem;font-size:1.75rem;line-height:1.35} | |
| 65 | .ck-bar{display:flex;gap:1rem;font-size:1.25rem;margin-bottom:1rem} | |
| 66 | .ck-today p{margin:.2rem 0} | |
| 67 | .ck-cards,.ck-waves{margin-top:1.5rem;display:grid;gap:.75rem} | |
| 68 | .ck-card,.ck-wave{border-left:.6rem solid var(--c,88);padding:.75rem 1rem;background:;border-radius:.4rem} | |
| 69 | .ck-card[data-colour=needs],.ck-wave[data-colour=needs]{--c:} | |
| 70 | .ck-wave[data-colour=working]{--c:b82f6} | |
| 71 | .ck-wave[data-colour=done]{--c:2c55e} | |
| 72 | .ck-wave[data-colour=blocked]{--c:} | |
| 73 | .ck-card:focus,.ck-wave:focus{outline:.35rem solid ;outline-offset:.2rem} | |
| 74 | .ck-text{margin:0 0 .5rem} | |
| 75 | .ck-answers{display:flex;gap:1rem} | |
| 76 | .ck-act{font:inherit;font-size:1.5rem;padding:.3rem 1.2rem;border-radius:.4rem;border:.2rem solid ;background:none;color:inherit;text-decoration:none;cursor:pointer} | |
| 77 | .ck-card:focus .ck-act[data-key=yes]{background:;color:00} | |
| 78 | .ck-quiet,.ck-more{opacity:.7} | |
| 79 | -status{margin:0 0 1rem;padding:.6rem 1rem;border-left:.6rem solid ;background:;border-radius:.4rem} | |
| 80 | -status[hidden]{display:none} | |
| 81 | -status[data-ok=false]{border-color:} | |
| 82 | `; | |
| 83 | ||
| 84 | const KIOSK_COOKIE = "forge_kiosk"; | |
| 85 | /** Where the kiosk cookie goes: `/board` and everything under it, as tight as a path can be. */ | |
| 86 | const KIOSK_PATHS = ["/board", "/live/cockpit"] as const; | |
| 87 | ||
| 88 | const kioskCookie = (value: string, maxAge: number, url: URL, path: string): string => | |
| 89 | `${KIOSK_COOKIE}=${value}; Path=${path}; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${url.protocol === "https:" ? "; Secure" : ""}`; | |
| 90 | ||
| 91 | /** A read-only token's user, or nothing: a token that can write is not a TV's to hold. */ | |
| 92 | function readOnlyUser(ctx: Ctx, raw: string | null | undefined): User | undefined { | |
| 93 | if (!raw || raw.length > 200) return undefined; | |
| 94 | const checked = verifyToken(ctx.app.db, raw); | |
| 95 | return checked.ok && checked.value.scope === "ro" ? checked.value.user : undefined; | |
| 96 | } | |
| 97 | ||
| 98 | function who(ctx: Ctx): { user: User; readOnly: boolean } | undefined { | |
| 99 | if (ctx.auth.user) return { user: ctx.auth.user, readOnly: false }; | |
| 100 | const device = readOnlyUser(ctx, cookieValue(ctx.request, KIOSK_COOKIE)); | |
| 101 | return device ? { user: device, readOnly: true } : undefined; | |
| 102 | } | |
| 103 | ||
| 104 | /** GET /board?cockpit=1 or ?kiosk=1 — the cockpit. */ | |
| 105 | export function cockpitPage(ctx: Ctx): Response { | |
| 106 | const offered = ctx.url.searchParams.get("device"); | |
| 107 | if (offered !== null && !ctx.auth.user) { | |
| 108 | // Swap the token for a cookie once and leave it out of the address. | |
| 109 | if (!readOnlyUser(ctx, offered)) return signInFirst(ctx); | |
| 110 | const clean = new URL(ctx.url); | |
| 111 | clean.searchParams.delete("device"); | |
| 112 | const res = redirect(clean.pathname + clean.search); | |
| 113 | for (const path of KIOSK_PATHS) | |
| 114 | res.headers.append("set-cookie", kioskCookie(offered, 30 * 86_400, ctx.url, path)); | |
| 115 | return res; | |
| 116 | } | |
| 117 | const seen = who(ctx); | |
| 118 | if (!seen) return signInFirst(ctx); | |
| 119 | const kiosk = ctx.url.searchParams.get("kiosk") === "1"; | |
| 120 | const model = cockpitModel(ctx.app.db, seen.user, { readOnly: seen.readOnly }); | |
| 121 | const body = html`<div class="ck"> | |
| 122 | ${kiosk ? null : html`<nav class="ck-bar"><a href="/">Home</a><a href="/board">The wall</a></nav>`} | |
| 123 | <p id="ck-status" role="status" aria-live="assertive" hidden></p> | |
| 124 | <div id="cockpit" data-src="/live/cockpit" aria-live="polite">${screen(model)}</div> | |
| 125 | </div>`; | |
| 126 | return page({ ctx, title: "Cockpit", body, bare: true, theme: "dark", scriptJs: cockpitJs, styleCss: cockpitCss }); | |
| 127 | } | |
| 128 | ||
| 129 | /** GET /live/cockpit — the screen alone, for the page to swap in. */ | |
| 130 | export function cockpitFragment(ctx: Ctx): Response { | |
| 131 | const seen = who(ctx); | |
| 132 | if (!seen) return fragment(html``, { status: 404 }); | |
| 133 | return fragment(screen(cockpitModel(ctx.app.db, seen.user, { readOnly: seen.readOnly })), { | |
| 134 | request: ctx.request, | |
| 135 | }); | |
| 136 | } | |
| 137 | ||
| 138 | /** What the viewer is told after an answer: one line, and the undo when there is one. */ | |
| 139 | const said = (ok: boolean, message: string, undo?: string): { ok: boolean; message: string; undo?: string } => | |
| 140 | undo === undefined ? { ok, message } : { ok, message, undo }; | |
| 141 | ||
| 142 | function answered(ctx: Ctx, body: ReturnType<typeof said>): Response { | |
| 143 | return prefersJson(ctx) | |
| 144 | ? json(body, body.ok ? 200 : 422) | |
| 145 | : redirect(`/board?cockpit=1`); | |
| 146 | } | |
| 147 | ||
| 148 | /** POST /board/answer — the deed behind Yes and No, answered in a line, with the undo. */ | |
| 149 | export async function cockpitAnswer(ctx: Ctx): Promise<Response> { | |
| 150 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 151 | const form = await readForm(ctx, "rw"); | |
| 152 | if (form instanceof Response) return form; | |
| 153 | const action = field(form, "action"); | |
| 154 | const items = form.getAll("item").filter((i): i is string => typeof i === "string"); | |
| 155 | if (items.length === 0 || (action !== "ship" && action !== "dismiss")) | |
| 156 | return answered(ctx, said(false, "Nothing was done: nothing to answer.")); | |
| 157 | const op = await applyAsksBulk(ctx.app, ctx.auth.user, action, items); | |
| 158 | if (!op.ok) return answered(ctx, said(false, `Nothing was done: ${op.error.message}.`)); | |
| 159 | const done = op.value.rows.filter((r) => r.outcome === "ok").length; | |
| 160 | if (done === 0) return answered(ctx, said(false, "Nothing was done: it was refused.")); | |
| 161 | const word = action === "ship" ? "Shipped" : "Dismissed"; | |
| 162 | return answered( | |
| 163 | ctx, | |
| 164 | said(true, `${word}.`, op.value.reversible ? `/board/answer/${op.value.id}/undo` : undefined), | |
| 165 | ); | |
| 166 | } | |
| 167 | ||
| 168 | /** POST /board/answer/:id/undo — take the answer back, once. */ | |
| 169 | export async function cockpitUndo(ctx: Ctx): Promise<Response> { | |
| 170 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 171 | const form = await readForm(ctx, "rw"); | |
| 172 | if (form instanceof Response) return form; | |
| 173 | const op = await undoAsksBulk(ctx.app, ctx.auth.user, ctx.params.id ?? ""); | |
| 174 | return answered( | |
| 175 | ctx, | |
| 176 | op.ok ? said(true, "Undone.") : said(false, `Nothing was undone: ${op.error.message}.`), | |
| 177 | ); | |
| 178 | } |
test/cockpit.test.ts added +396
| @@ -0,0 +1,396 @@ | ||
| 1 | /** | |
| 2 | * The cockpit (#1152): the board and the map as one screen, on three doors. | |
| 3 | * It speaks the studio's words and nobody else's, a muted app and a spent day | |
| 4 | * raise no card, answers say what happened and can be undone, a kiosk reads | |
| 5 | * with a cookie swapped for its device token and never answers, and the page, | |
| 6 | * the terminal and the MCP `board` tool say the same thing. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 14 | import { openPull } from "../src/actions/pulls.ts"; | |
| 15 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 16 | import { recordInteraction } from "../src/core/interactions.ts"; | |
| 17 | import type { Pull } from "../src/core/pulls.ts"; | |
| 18 | import type { Repo } from "../src/core/repos.ts"; | |
| 19 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 20 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 21 | import { settleApp } from "./helpers/tui.ts"; | |
| 22 | import { claimRun, createRun, finishRun } from "../src/core/runs.ts"; | |
| 23 | import { createToken } from "../src/core/tokens.ts"; | |
| 24 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 25 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 26 | import { cockpitJs } from "../src/web/client.ts"; | |
| 27 | import { quietLogs } from "./helpers/globals.ts"; | |
| 28 | ||
| 29 | quietLogs(); | |
| 30 | ||
| 31 | /** Words of the developer's trade the cockpit never uses. */ | |
| 32 | const NERDY = | |
| 33 | /\b(pull requests?|PR|merged?|issues?|branch(es)?|commits?|repos?|repositories|agents?|tokens?|deploy(ed|ment)?|CI|runs?|ceiling|planner|breaker|webhook|ssh|scout|bot)\b/i; | |
| 34 | ||
| 35 | describe("the cockpit", () => { | |
| 36 | let dataDir = ""; | |
| 37 | let app: App; | |
| 38 | let servers: Servers; | |
| 39 | let alice: User; | |
| 40 | let cookie = ""; | |
| 41 | let ro = ""; | |
| 42 | let rw = ""; | |
| 43 | let loud: Repo; | |
| 44 | let quiet: Repo; | |
| 45 | let n = 0; | |
| 46 | ||
| 47 | const text = (html: string): string => | |
| 48 | html | |
| 49 | .replace(/<(script|style)[\s\S]*?<\/\1>/g, " ") | |
| 50 | .replace(/<[^>]+>/g, " ") | |
| 51 | .replace(/&#?\w+;/g, " ") | |
| 52 | .replace(/\s+/g, " "); | |
| 53 | ||
| 54 | const greenPull = async (repo: Repo, title: string): Promise<Pull> => { | |
| 55 | n++; | |
| 56 | await commitToBranch(app, alice, repo, { | |
| 57 | branch: `bot/${n}`, | |
| 58 | base: "main", | |
| 59 | message: title, | |
| 60 | files: [{ path: `F${n}.md`, content: `${n}\n` }], | |
| 61 | }); | |
| 62 | const opened = await openPull(app, getUserByName(app.db, "bot")!, repo, { | |
| 63 | title, | |
| 64 | body: "", | |
| 65 | baseBranch: "main", | |
| 66 | headBranch: `bot/${n}`, | |
| 67 | }); | |
| 68 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 69 | const run = createRun(app.db, { | |
| 70 | repoId: repo.id, | |
| 71 | kind: "check", | |
| 72 | issueId: opened.value.id, | |
| 73 | env: `pull-${opened.value.number}`, | |
| 74 | commitOid: opened.value.headOid, | |
| 75 | reason: "pull", | |
| 76 | }); | |
| 77 | claimRun(app.db, run.id); | |
| 78 | finishRun(app.db, run.id, { state: "ok", summary: "ok" }); | |
| 79 | return opened.value; | |
| 80 | }; | |
| 81 | ||
| 82 | const repoNamed = async (name: string): Promise<Repo> => { | |
| 83 | const made = await createRepo(app, alice, { name, visibility: "public" }); | |
| 84 | if (!made.ok) throw new Error(String(made.error)); | |
| 85 | await commitToBranch(app, alice, made.value, { | |
| 86 | message: "seed", | |
| 87 | files: [{ path: "README.md", content: `# ${name}\n` }], | |
| 88 | }); | |
| 89 | addToCrew(app, alice, made.value, "bot"); | |
| 90 | return made.value; | |
| 91 | }; | |
| 92 | ||
| 93 | const get = (path: string, headers: Record<string, string> = { cookie }) => | |
| 94 | fetch(`${servers.url}${path}`, { headers, redirect: "manual" }); | |
| 95 | ||
| 96 | const mcpBoard = async () => { | |
| 97 | const res = await fetch(`${servers.url}/mcp`, { | |
| 98 | method: "POST", | |
| 99 | headers: { | |
| 100 | "content-type": "application/json", | |
| 101 | accept: "application/json, text/event-stream", | |
| 102 | authorization: `Bearer ${ro}`, | |
| 103 | }, | |
| 104 | body: JSON.stringify({ | |
| 105 | jsonrpc: "2.0", | |
| 106 | id: 1, | |
| 107 | method: "tools/call", | |
| 108 | params: { name: "board", arguments: {} }, | |
| 109 | }), | |
| 110 | }); | |
| 111 | const body = (await res.json()) as { result: { content: { text: string }[] } }; | |
| 112 | return JSON.parse(body.result.content[0]!.text) as { | |
| 113 | today: string[]; | |
| 114 | cards: { text: string; answers: string[] }[]; | |
| 115 | waves: { text: string }[]; | |
| 116 | }; | |
| 117 | }; | |
| 118 | ||
| 119 | beforeAll(async () => { | |
| 120 | dataDir = await mkdtemp(join(process.env["COCKPIT_TMP"] ?? tmpdir(), "forge-cockpit-")); | |
| 121 | app = createApp({ dataDir, port: 0 }); | |
| 122 | servers = await serve(app); | |
| 123 | const a = await createUser(app.db, { | |
| 124 | trusted: true, | |
| 125 | username: "alice", | |
| 126 | email: "[email protected]", | |
| 127 | password: "a-good-passphrase", | |
| 128 | adminIfFirst: true, | |
| 129 | }); | |
| 130 | if (!a.ok) throw new Error(a.error); | |
| 131 | alice = a.value; | |
| 132 | const res = await fetch(`${servers.url}/signin`, { | |
| 133 | method: "POST", | |
| 134 | body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), | |
| 135 | redirect: "manual", | |
| 136 | }); | |
| 137 | cookie = `${(res.headers.get("set-cookie") ?? "").split(";")[0]!}`; | |
| 138 | ro = createToken(app.db, alice.id, "tv", "ro").token; | |
| 139 | rw = createToken(app.db, alice.id, "full", "rw").token; | |
| 140 | await createAgent(app, alice, { username: "bot" }); | |
| 141 | loud = await repoNamed("loud"); | |
| 142 | quiet = await repoNamed("quiet"); | |
| 143 | await greenPull(loud, "Louder"); | |
| 144 | await greenPull(quiet, "Quieter"); | |
| 145 | }, 30_000); | |
| 146 | ||
| 147 | afterAll(async () => { | |
| 148 | await servers.stop(); | |
| 149 | await rm(dataDir, { recursive: true, force: true }); | |
| 150 | }); | |
| 151 | ||
| 152 | test("anonymous is sent to sign in", async () => { | |
| 153 | const res = await get("/board?cockpit=1", {}); | |
| 154 | expect(res.status).toBe(303); | |
| 155 | }); | |
| 156 | ||
| 157 | test("the page has its three parts and speaks no jargon", async () => { | |
| 158 | const res = await get("/board?cockpit=1"); | |
| 159 | expect(res.status).toBe(200); | |
| 160 | const html = await res.text(); | |
| 161 | expect(html).toContain('aria-label="Today"'); | |
| 162 | expect(html).toContain('aria-label="Needs you"'); | |
| 163 | expect(html).toContain('aria-label="The plan"'); | |
| 164 | expect(html).toContain("loud: a change is ready. Ship it?"); | |
| 165 | expect(html).toContain("2 things need you."); | |
| 166 | expect(text(html)).not.toMatch(NERDY); | |
| 167 | }); | |
| 168 | ||
| 169 | test("a muted app's card does not appear", async () => { | |
| 170 | recordInteraction(app.db, { | |
| 171 | viewerId: alice.id, | |
| 172 | itemId: `repo:${quiet.id}`, | |
| 173 | kind: "muted", | |
| 174 | repoId: quiet.id, | |
| 175 | actorId: null, | |
| 176 | }); | |
| 177 | const html = await (await get("/board?cockpit=1")).text(); | |
| 178 | expect(html).toContain("loud: a change is ready"); | |
| 179 | expect(html).not.toContain("quiet: a change is ready"); | |
| 180 | expect(html).toContain("1 thing needs you."); | |
| 181 | }); | |
| 182 | ||
| 183 | test("every card can be reached and answered with the four keys", async () => { | |
| 184 | const html = await (await get("/board?cockpit=1")).text(); | |
| 185 | const cards = html.match(/<article[^>]*data-card=/g) ?? []; | |
| 186 | expect(cards.length).toBeGreaterThan(0); | |
| 187 | for (const c of cards) expect(c).toContain('tabindex="0"'); | |
| 188 | // yes, no and later are each a control; the first one is yes. | |
| 189 | const card = html.slice(html.indexOf("<article"), html.indexOf("</article>")); | |
| 190 | const keys = [...card.matchAll(/data-key="(\w+)"/g)].map((m) => m[1]); | |
| 191 | expect(keys).toEqual(["yes", "no", "later"]); | |
| 192 | for (const k of ["ArrowUp", "ArrowDown", "Enter", "Escape", "Backspace"]) | |
| 193 | expect(cockpitJs).toContain(`'${k}'`); | |
| 194 | expect(cockpitJs).toContain("querySelector('.ck-act')"); | |
| 195 | }); | |
| 196 | ||
| 197 | const answer = (path: string, body: Record<string, string>) => | |
| 198 | fetch(`${servers.url}${path}`, { | |
| 199 | method: "POST", | |
| 200 | headers: { cookie, origin: servers.url, accept: "application/json" }, | |
| 201 | body: new URLSearchParams(body), | |
| 202 | redirect: "manual", | |
| 203 | }); | |
| 204 | const firstCard = async (action: string) => { | |
| 205 | const html = await (await get("/board?cockpit=1")).text(); | |
| 206 | const form = html.match( | |
| 207 | new RegExp(`<form method="post" action="/board/answer" data-act="${action}">[\\s\\S]*?</form>`), | |
| 208 | )![0]; | |
| 209 | return { | |
| 210 | html, | |
| 211 | item: form.match(/name="item" value="([^"]+)"/)![1]!, | |
| 212 | card: html.match(/data-card="([^"]+)"/)![1]!, | |
| 213 | }; | |
| 214 | }; | |
| 215 | ||
| 216 | test("nothing is focused on load, so one stray key answers nothing", () => { | |
| 217 | expect(cockpitJs).not.toContain("focusAt(0);\n setInterval"); | |
| 218 | }); | |
| 219 | ||
| 220 | test("a dismissal says what happened, the card goes, and undo brings it back", async () => { | |
| 221 | const before = await firstCard("dismiss"); | |
| 222 | const res = await answer("/board/answer", { action: "dismiss", item: before.item }); | |
| 223 | expect(res.status).toBe(200); | |
| 224 | const said = (await res.json()) as { ok: boolean; message: string; undo?: string }; | |
| 225 | expect(said.ok).toBe(true); | |
| 226 | expect(said.undo).toMatch(/^\/board\/answer\/[^/]+\/undo$/); | |
| 227 | expect(await (await get("/board?cockpit=1")).text()).not.toContain(before.item); | |
| 228 | const undone = await answer(said.undo!, {}); | |
| 229 | expect(((await undone.json()) as { ok: boolean }).ok).toBe(true); | |
| 230 | expect(await (await get("/board?cockpit=1")).text()).toContain(before.item); | |
| 231 | }); | |
| 232 | ||
| 233 | test("yes ships, says so, and the card goes; a refusal says why", async () => { | |
| 234 | const before = await firstCard("ship"); | |
| 235 | const res = await answer("/board/answer", { action: "ship", item: before.item }); | |
| 236 | const said = (await res.json()) as { ok: boolean; message: string }; | |
| 237 | expect(said).toEqual({ ok: true, message: "Shipped." }); | |
| 238 | expect(await (await get("/board?cockpit=1")).text()).not.toContain(`data-card="${before.card}"`); | |
| 239 | const again = await answer("/board/answer", { action: "ship", item: before.item }); | |
| 240 | expect(again.status).toBe(422); | |
| 241 | expect(((await again.json()) as { message: string }).message).toStartWith("Nothing was done"); | |
| 242 | expect((await answer("/board/answer", { action: "ship" })).status).toBe(422); | |
| 243 | }); | |
| 244 | ||
| 245 | test("an answer is refused from another origin, and from a kiosk", async () => { | |
| 246 | const x = await fetch(`${servers.url}/board/answer`, { | |
| 247 | method: "POST", | |
| 248 | headers: { cookie, origin: "https://evil.example", accept: "application/json" }, | |
| 249 | body: new URLSearchParams({ action: "dismiss", item: "x" }), | |
| 250 | redirect: "manual", | |
| 251 | }); | |
| 252 | expect(x.status).toBeGreaterThanOrEqual(400); | |
| 253 | const k = await fetch(`${servers.url}/board/answer`, { | |
| 254 | method: "POST", | |
| 255 | headers: { cookie: "forge_kiosk=" + ro, origin: servers.url, accept: "application/json" }, | |
| 256 | body: new URLSearchParams({ action: "dismiss", item: "x" }), | |
| 257 | redirect: "manual", | |
| 258 | }); | |
| 259 | expect(k.status).not.toBe(200); | |
| 260 | }); | |
| 261 | ||
| 262 | test("the first Yes to a ship only asks; every answer is told in a line", () => { | |
| 263 | expect(cockpitJs).toContain("Press Yes again to ship it."); | |
| 264 | expect(cockpitJs).toContain("ck-status"); | |
| 265 | }); | |
| 266 | ||
| 267 | test("a device token is swapped once for a cookie and never stays in the address", async () => { | |
| 268 | const first = await get(`/board?kiosk=1&device=${ro}`, {}); | |
| 269 | expect(first.status).toBe(303); | |
| 270 | expect(first.headers.get("location")).toBe("/board?kiosk=1"); | |
| 271 | const cookies = first.headers.getSetCookie(); | |
| 272 | expect(cookies.map((c) => c.match(/Path=([^;]+)/)![1]).sort()).toEqual(["/board", "/live/cockpit"]); | |
| 273 | for (const c of cookies) { | |
| 274 | expect(c).toContain("HttpOnly"); | |
| 275 | expect(c).toContain("SameSite=Strict"); | |
| 276 | } | |
| 277 | const jar = cookies[0]!.split(";")[0]!; | |
| 278 | const kiosk = await get("/board?kiosk=1", { cookie: jar }); | |
| 279 | expect(kiosk.status).toBe(200); | |
| 280 | const html = await kiosk.text(); | |
| 281 | expect(html).not.toContain(ro); | |
| 282 | expect(html).not.toContain('class="ck-bar"'); | |
| 283 | expect(html).not.toContain('class="ck-act"'); | |
| 284 | expect(html).toContain('data-src="/live/cockpit"'); | |
| 285 | expect((await get("/live/cockpit?kiosk=1", { cookie: jar })).status).toBe(200); | |
| 286 | // A token that can write is not a TV's to hold, and a made-up one is nothing. | |
| 287 | expect((await get(`/board?kiosk=1&device=${rw}`, {})).status).toBe(303); | |
| 288 | expect((await get(`/board?kiosk=1&device=${rw}`, {})).headers.getSetCookie()).toEqual([]); | |
| 289 | expect((await get("/board?kiosk=1&device=nope", {})).headers.getSetCookie()).toEqual([]); | |
| 290 | expect((await get("/board?kiosk=1", { cookie: "forge_kiosk=" + rw })).status).toBe(303); | |
| 291 | }); | |
| 292 | ||
| 293 | test("a spent day raises no card on any door", async () => { | |
| 294 | const { askLinesFor } = await import("../src/web/studio/asks.ts"); | |
| 295 | const { cockpitModel } = await import("../src/view/cockpit.ts"); | |
| 296 | const capped = await repoNamed("capped"); | |
| 297 | app.db | |
| 298 | .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?1, autonomy_ceiling_usd = 1 WHERE id = ?2") | |
| 299 | .run(alice.id, capped.id); | |
| 300 | const run = createRun(app.db, { repoId: capped.id, kind: "agent", actorId: getUserByName(app.db, "bot")!.id, reason: "assigned" }); | |
| 301 | claimRun(app.db, run.id); | |
| 302 | finishRun(app.db, run.id, { state: "ok", summary: "done", costUsd: 5 }); | |
| 303 | // The studio does raise the pause; the cockpit does not, on any door. | |
| 304 | expect(askLinesFor(app.db, alice).some((r) => r.kind === "paused")).toBe(true); | |
| 305 | expect(cockpitModel(app.db, alice).cards.every((c) => !c.text.includes("capped"))).toBe(true); | |
| 306 | expect(text(await (await get("/board?cockpit=1")).text())).not.toContain("capped:"); | |
| 307 | expect((await mcpBoard()).cards.every((c) => !c.text.includes("capped"))).toBe(true); | |
| 308 | const terminal = headlessTerminal(120, 32); | |
| 309 | const { app: tui } = createForgeApp( | |
| 310 | app, | |
| 311 | { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice } as never, | |
| 312 | { terminal, exitHooks: false }, | |
| 313 | ); | |
| 314 | tui.start(); | |
| 315 | await settleApp(tui); | |
| 316 | tui.dispatch({ type: "key", key: "c", ctrl: false, alt: false, shift: false }); | |
| 317 | await settleApp(tui); | |
| 318 | expect(tui.screen.toText()).not.toContain("capped:"); | |
| 319 | tui.stop?.(); | |
| 320 | }); | |
| 321 | ||
| 322 | test("a wave nobody is building is next, not blocked", async () => { | |
| 323 | const { cockpitModel } = await import("../src/view/cockpit.ts"); | |
| 324 | const { openIssue } = await import("../src/actions/issues.ts"); | |
| 325 | const { linkIssue } = await import("../src/actions/dependencies.ts"); | |
| 326 | const { createApp: insertApp } = await import("../src/core/apps.ts"); | |
| 327 | const { getRepoById } = await import("../src/core/repos.ts"); | |
| 328 | const waves = await repoNamed("waves"); | |
| 329 | const record = insertApp(app.db, { repoId: waves.id, slug: "waves", access: "private" }); | |
| 330 | if (!record.ok) throw new Error(record.error); | |
| 331 | const open = (title: string) => { | |
| 332 | const r = openIssue(app, alice, getRepoById(app.db, waves.id)!, { title }); | |
| 333 | if (!r.ok) throw new Error(String(r.error)); | |
| 334 | return r.value; | |
| 335 | }; | |
| 336 | const top = open("Wave top"); | |
| 337 | const step = open("Wave step"); | |
| 338 | const linked = linkIssue(app, alice, getRepoById(app.db, waves.id)!, top, step); | |
| 339 | if (!linked.ok) throw new Error(String(linked.error)); | |
| 340 | const wave = cockpitModel(app.db, alice).waves.find((w) => w.text.startsWith("waves, ")); | |
| 341 | expect(wave).toBeDefined(); | |
| 342 | expect(wave!.colour).toBe("needs"); | |
| 343 | }); | |
| 344 | ||
| 345 | test("the terminal shows the same cockpit and answers a card", async () => { | |
| 346 | await greenPull(loud, "For the terminal"); | |
| 347 | const terminal = headlessTerminal(120, 32); | |
| 348 | const { app: tui } = createForgeApp( | |
| 349 | app, | |
| 350 | { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice } as never, | |
| 351 | { terminal, exitHooks: false }, | |
| 352 | ); | |
| 353 | tui.start(); | |
| 354 | const key = async (k: string) => { | |
| 355 | tui.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 356 | await settleApp(tui); | |
| 357 | }; | |
| 358 | await settleApp(tui); | |
| 359 | await key("c"); | |
| 360 | const screen = tui.screen.toText(); | |
| 361 | expect(screen).toContain("Nothing landed in the last day.".slice(0, 7)); | |
| 362 | expect(screen).toContain("loud: a change is ready"); | |
| 363 | await key("y"); | |
| 364 | expect(tui.screen.toText()).toContain("Press y again to ship it."); | |
| 365 | await key("y"); | |
| 366 | expect(tui.screen.toText()).toContain("Shipped."); | |
| 367 | tui.stop?.(); | |
| 368 | }); | |
| 369 | ||
| 370 | test("the live fragment is the screen alone", async () => { | |
| 371 | const res = await get("/live/cockpit?kiosk=1"); | |
| 372 | expect(res.status).toBe(200); | |
| 373 | const html = await res.text(); | |
| 374 | expect(html).toContain('aria-label="Today"'); | |
| 375 | expect(html).not.toContain("<html"); | |
| 376 | expect((await get("/live/cockpit", {})).status).toBe(404); | |
| 377 | }); | |
| 378 | ||
| 379 | test("the MCP board says what the page says, in the same order", async () => { | |
| 380 | await greenPull(loud, "Louder still"); | |
| 381 | const page = text(await (await get("/board?cockpit=1")).text()); | |
| 382 | const board = await mcpBoard(); | |
| 383 | expect(board.today.length).toBeGreaterThan(0); | |
| 384 | let at = 0; | |
| 385 | for (const line of [ | |
| 386 | ...board.today, | |
| 387 | ...board.cards.map((c) => c.text), | |
| 388 | ...board.waves.map((w) => w.text), | |
| 389 | ]) { | |
| 390 | const found = page.indexOf(line.replace(/\s+/g, " "), at); | |
| 391 | expect(found).toBeGreaterThanOrEqual(at); | |
| 392 | at = found; | |
| 393 | } | |
| 394 | expect(board.cards[0]!.answers).toEqual(["Yes", "No", "Later"]); | |
| 395 | }); | |
| 396 | }); |
test/mcp.test.ts +1
| @@ -163,6 +163,7 @@ describe("the forge over MCP", () => { | ||
| 163 | 163 | "pull", |
| 164 | 164 | "edit", |
| 165 | 165 | "asks", |
| 166 | "board", | |
| 166 | 167 | "asks_act", |
| 167 | 168 | "seal", |
| 168 | 169 | "now", |
new above
offline