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

The home page shows the forge's KPIs, never a to-do list for the owner; the owner pins board panels to it #2672

Parked opened this
Closed without merging

scout/forge:scout/2665-the-home-page-shows-the-forge-s-kpis-nev → main 8 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
33 files changed +954 −67
README.md +1
@@ -1452,6 +1452,7 @@ work here.
14521452 A board with a refresh redraws its grid on that beat through the live-region swap
14531453 (`/boards/:slug/live`, etag'd). The same doors are in the API: `GET /api/v1/boards`, `GET|PUT|DELETE /api/v1/boards/:slug`
14541454 (an agent or anyone but an admin is 403; a panel whose query cannot run is refused with 422). The same four doors are MCP tools (`boards`, `board_write`, `board_delete`; `boards` with a `slug` reads one) and, for the same person, a **Boards** screen in the terminal that lists boards and shows a board's panels as text. No dependency was added.
1455 **The owner's home** (a person who is an admin) is the forge's vital signs, never a list of what waits on them: landings per hour (merged pulls into a default branch, last 24 h, as a sparkline), the live version and when it went live, median check time, builders at work of slots, today's spend of the daily ceiling, and the age of the last off-box backup, each linking to the board or page it comes from, and wrapping at 360 px. Every panel on a board has **Pin to home**; pinned panels draw under the KPIs, with Up/Down/Unpin, in the owner's order (`POST /home/panels`; one `user_setting` row of `board:place` pairs, so at most about five pins; a remove or move of a panel on its board rewrites the pins with it, deleting the board drops them, and a whole-board write drops pins past the new end). The same doors for a script or an agent working for the owner: `GET /api/v1/home` (the KPIs and the pinned panels with their current values) and `POST /api/v1/home/panels` with `{slug, index, action: pin|unpin|up|down}`, as the MCP tools `home` and `home_pin`; the terminal home also lists each pinned panel as a line of its title and value. What waits on the owner is on `/asks`, reached on purpose. In the terminal the same person's home has the KPIs as one line under the header, and on a board's view in **Boards** `n`/`N` mark a panel, `p` pins or unpins it and `[` / `]` move a pinned one earlier or later (the same `core/home_panels.ts` calls).
outdated

The README tells people how to use this on the page only. When the terminal gets pin, unpin and move and the KPI row, say so here, the way the Boards sentence above does.

14551456 - **Issues** — labels, threaded comments, close/reopen, markdown.
14561457 - **Pull requests** — open from a branch, a **beautiful diff viewer** (syntax
14571458 highlighting composed with intra-line word highlighting, mobile-first,
src/actions/boards.ts +19 −3
@@ -21,6 +21,7 @@ import { commitIdentity, forgeHost } from "../core/commit_identity.ts";
2121 import { createOrg } from "../core/orgs.ts";
2222 import { createRepo, getRepo } from "../core/repos.ts";
2323 import { getUserById, getUserByName, type User } from "../core/users.ts";
24 import { rewritePins } from "../core/home_panels.ts";
2425 import { err, ok, type Result } from "../kernel/result.ts";
2526
2627 export type BoardError = StoreError | "not_found" | "no_slug" | "repo" | { refused: string };
@@ -103,7 +104,10 @@ export async function writeBoard(
103104 if (!isSlug(slug)) return err("invalid");
104105 if (!(await ensureRepo(app, who.value))) return err("repo");
105106 const there = (await readBoard(app.reposRoot, slug)) !== undefined;
106 return save(app, who.value, slug, board, `${there ? "Write" : "Make"} board ${slug}`, there ? "update" : "create");
107 const saved = await save(app, who.value, slug, board, `${there ? "Write" : "Make"} board ${slug}`, there ? "update" : "create");
108 // A whole-board write cannot say where panels went: a pin past the new end is dropped.
109 if (saved.ok) rewritePins(app.db, slug, (i) => (i < saved.value.panels.length ? i : null));
110 return saved;
107111 }
108112
109113 /** Apply one edit to a board and commit it. */
@@ -116,7 +120,16 @@ export async function changeBoard(
116120 if (!board) return err("not_found");
117121 const next = applyEdit(board, edit);
118122 if (!next.ok) return err({ refused: next.error });
119 return save(app, who.value, slug, next.value, `Change board ${slug}: ${edit.kind}`, "update");
123 const saved = await save(app, who.value, slug, next.value, `Change board ${slug}: ${edit.kind}`, "update");
124 // The owners' home pins follow their panels through a remove or a move.
125 if (saved.ok && edit.kind === "remove")
126 rewritePins(app.db, slug, (i) => (i === edit.index ? null : i > edit.index ? i - 1 : i));
127 if (saved.ok && edit.kind === "move") {
128 const to = edit.index + edit.by;
129 if (to >= 0 && to < board.panels.length)
130 rewritePins(app.db, slug, (i) => (i === edit.index ? to : i === to ? edit.index : i));
131 }
132 return saved;
120133 }
121134
122135 /** Copy a board under a new slug (`<slug>-copy`, numbered if taken). */
@@ -140,7 +153,10 @@ export async function deleteBoard(app: App, actor: User | undefined, slug: strin
140153 const who = admin(actor);
141154 if (!who.ok) return who;
142155 const done = await removeBoard(app.reposRoot, slug, commitIdentity(app.config, who.value), `Delete board ${slug}`);
143 if (done.ok) app.bus.append({ kind: "board.deleted", actorId: who.value.id, payload: { slug } });
156 if (done.ok) {
157 app.bus.append({ kind: "board.deleted", actorId: who.value.id, payload: { slug } });
158 rewritePins(app.db, slug, () => null);
159 }
144160 return done;
145161 }
146162
src/actions/home.ts added +71
@@ -0,0 +1,71 @@
1 /**
2 * The owner's home as data, for every door that is not the page: the KPIs
3 * and the pinned panels with their current values (`homeView`), and the
4 * pin, unpin and move of a panel (`changeHomePin`). For a forge admin who is
5 * a person; anyone else is told `not_found`, as the boards are.
6 */
7 import type { App } from "../app.ts";
8 import { panelValue } from "../boards/summary.ts";
9 import { isOwner, movePin, pinPanel, pinsOf, unpinPanel } from "../core/home_panels.ts";
10 import { readKpis, type Kpi } from "../core/kpis.ts";
11 import type { User } from "../core/users.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13 import { BOOTED } from "../release/gate.ts";
14 import { isSlug } from "../boards/store.ts";
15 import { showBoard } from "./boards.ts";
16
17 export interface HomePanel {
18 readonly slug: string;
19 readonly index: number;
20 readonly title: string;
21 readonly chart: string;
22 readonly value: string;
23 }
24
25 export interface HomeView {
26 readonly kpis: readonly Kpi[];
27 readonly panels: readonly HomePanel[];
28 }
29
30 export const HOME_ACTIONS = ["pin", "unpin", "up", "down"] as const;
31 export type HomeAction = (typeof HOME_ACTIONS)[number];
32
33 /** The pinned panels that still exist, in the owner's order. */
34 export async function homePanels(app: App, user: User): Promise<HomePanel[]> {
35 const out: HomePanel[] = [];
36 for (const pin of pinsOf(app.db, user.id)) {
37 const shown = await showBoard(app, user, pin.slug);
38 const panel = shown.ok ? shown.value.panels[pin.index] : undefined;
39 if (shown.ok && panel !== undefined)
40 out.push({ ...pin, title: panel.title, chart: panel.chart, value: panelValue(app.db, shown.value, panel) });
41 }
42 return out;
43 }
44
45 export async function homeView(app: App, actor: User | undefined): Promise<Result<HomeView, "not_found">> {
46 if (actor === undefined || !isOwner(actor)) return err("not_found");
47 return ok({
48 kpis: readKpis(app.db, app.config.dataDir, actor.id, BOOTED),
49 panels: await homePanels(app, actor),
50 });
51 }
52
53 export async function changeHomePin(
54 app: App,
55 actor: User | undefined,
56 input: { slug: unknown; index: unknown; action: unknown },
57 ): Promise<Result<true, "not_found" | "full">> {
58 if (actor === undefined || !isOwner(actor)) return err("not_found");
59 const { slug, index, action } = input;
60 if (!isSlug(slug) || typeof index !== "number" || !Number.isInteger(index) || index < 0 || index > 99) return err("not_found");
61 if (typeof action !== "string" || !(HOME_ACTIONS as readonly string[]).includes(action)) return err("not_found");
62 const pin = { slug, index };
63 if (action === "pin") {
64 const shown = await showBoard(app, actor, slug);
65 if (!shown.ok || shown.value.panels[index] === undefined) return err("not_found");
66 return pinPanel(app.db, actor.id, pin) ? ok(true) : err("full");
67 }
68 if (action === "unpin") unpinPanel(app.db, actor.id, pin);
69 else movePin(app.db, actor.id, pin, action === "up" ? -1 : 1);
70 return ok(true);
71 }
src/boards/summary.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * A panel as one line of text, for a door that draws no chart (the terminal,
3 * the API): the board's range applied to the panel's query, run as the page
4 * runs it, and the answer said in a few words.
5 */
6 import type { Database } from "bun:sqlite";
7 import { usesSeries } from "./chart.ts";
8 import { runQuery } from "./query.ts";
9 import type { Board, Panel } from "./store.ts";
10
11 const RANGE_MS = { "1h": 3_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const;
12
13 /** The panel's query as asked, with the board's range as its start when it names none. */
14 export function ranged(query: Record<string, unknown>, range: Board["range"]): Record<string, unknown> {
15 if (range === "all" || query.from !== undefined) return query;
16 return { ...query, from: new Date(Date.now() - RANGE_MS[range]).toISOString() };
17 }
18
19 /** The panel's current value in words: one number, or the latest of several points. */
20 export function panelValue(db: Database, board: Board, panel: Panel): string {
21 let query = ranged(panel.query, board.range);
22 if (!usesSeries(panel.chart) && query.series !== undefined) {
23 const { series: _, ...rest } = query;
24 query = rest;
25 }
26 const answer = runQuery(db, query, { repoIds: "all" });
27 if (!answer.ok) return "unavailable";
28 const last = answer.rows[answer.rows.length - 1];
29 if (last === undefined) return "no rows";
30 const value = String(last.value ?? 0);
31 return answer.rows.length === 1 ? value : `${value} (latest of ${answer.rows.length})`;
32 }
src/core/home_panels.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * The board panels an owner pinned to their home, in their order. One
3 * `user_setting` row of `slug:index` pairs: a pin names a panel by its board
4 * and place, and a pin whose panel is gone is skipped when drawn, never an
5 * error. The row is bounded (`setUserSetting` keeps 200 characters), so a pin
6 * that would not fit is refused.
7 */
8 import type { Database } from "bun:sqlite";
9 import { isSlug } from "../boards/store.ts";
10 import type { User } from "./users.ts";
11 import { getUserSetting, setUserSetting } from "./settings.ts";
12
13 /** A person who administers the forge: the one whose home is the vital signs. */
14 export const isOwner = (user: User): boolean => user.isAdmin && user.kind !== "agent";
15
16 const KEY = "home_panels";
17 const MAX_LEN = 200;
18
19 export interface PanelPin {
20 readonly slug: string;
21 readonly index: number;

High: a pin is a board position. changeBoard with remove or move shifts every later panel, so the home then draws a different panel under this pin, with nothing to tell the owner. Key the pin to a stable panel id, or remap or drop the pins inside the board edit, and add a test for it.

22 }
23
24 export const samePin = (a: PanelPin, b: PanelPin): boolean => a.slug === b.slug && a.index === b.index;
25
26 export function pinsOf(db: Database, userId: string): PanelPin[] {
27 const out: PanelPin[] = [];
28 for (const part of (getUserSetting(db, userId, KEY) ?? "").split(";")) {
29 const [slug = "", n = ""] = part.split(":");
30 const index = /^\d{1,2}$/.test(n) ? Number(n) : -1;
31 if (isSlug(slug) && index >= 0) out.push({ slug, index });
32 }
33 return out;
34 }
35
36 const save = (db: Database, userId: string, pins: readonly PanelPin[]): boolean => {
37 const value = pins.map((p) => `${p.slug}:${p.index}`).join(";");
38 if (value.length > MAX_LEN) return false;
39 setUserSetting(db, userId, KEY, value);
40 return true;
41 };
42
43 /** Pin (idempotent, at the end); false when it does not fit. */
44 export function pinPanel(db: Database, userId: string, pin: PanelPin): boolean {
45 const pins = pinsOf(db, userId);
46 return pins.some((p) => samePin(p, pin)) || save(db, userId, [...pins, pin]);
47 }
48
49 export function unpinPanel(db: Database, userId: string, pin: PanelPin): void {
50 save(db, userId, pinsOf(db, userId).filter((p) => !samePin(p, pin)));
51 }
52
53 /** Move a pin one place earlier (-1) or later (1) in the owner's order. */
54 export function movePin(db: Database, userId: string, pin: PanelPin, by: -1 | 1): void {
55 const pins = pinsOf(db, userId);
56 const at = pins.findIndex((p) => samePin(p, pin));
57 const to = at + by;
58 if (at < 0 || to < 0 || to >= pins.length) return;
59 [pins[at], pins[to]] = [pins[to]!, pins[at]!];
60 save(db, userId, pins);
61 }
62
63 /**
64 * Keep every owner's pins on the board `slug` pointing at the panels they
65 * were made for when the board changes: `to` says where a panel went (its new
66 * index) or null when it is gone, and a pin on a gone panel is dropped.
67 */
68 export function rewritePins(db: Database, slug: string, to: (index: number) => number | null): void {
69 const rows = db
70 .query<{ user_id: string }, [string, string]>("SELECT user_id FROM user_setting WHERE key = ?1 AND value LIKE ?2")
71 .all(KEY, `%${slug}:%`);
72 for (const { user_id } of rows) {
73 const next: PanelPin[] = [];
74 for (const p of pinsOf(db, user_id)) {
75 if (p.slug !== slug) {
76 next.push(p);
77 continue;
78 }
79 const moved = to(p.index);
80 if (moved !== null) next.push({ slug, index: moved });
81 }
82 save(db, user_id, next);
83 }
84 }
src/core/kpis.ts added +152
@@ -0,0 +1,152 @@
1 /**
2 * The forge's vital signs, read live for the owner's home: real landings per
3 * hour, the live version, median check time, builders at work, today's spend,
4 * the age of the last off-box backup. Plain data out — a label, a value, a
5 * note, the page it comes from — so the page only draws. A handful of grouped
6 * queries and two small files; nothing is cached or shelled out.
7 */
8 import type { Database } from "bun:sqlite";
9 import { dayStart, getAccountCeiling } from "./account_ceiling.ts";
10 import { lastMirror } from "../snapshot/mirror.ts";
11 import { running } from "../kernel/version.ts";
12
13 export interface Kpi {
14 readonly key: string;
15 readonly label: string;
16 readonly value: string;
17 readonly note: string;
18 /** The board or page this number comes from. */
19 readonly href: string;
20 /** Twenty-four hourly counts, oldest first, for a sparkline. */
21 readonly spark?: readonly number[];
22 }
23
24 const HOUR = 3_600_000;
25
26 /** Merged pulls into a default branch, by hour for the last 24 h, oldest first. */
27 export function landingsByHour(db: Database, now: number): number[] {
28 const first = Math.floor(now / HOUR) * HOUR - 23 * HOUR;
29 const rows = db
30 .query<{ at: string }, [string]>(
31 `SELECT p.merged_at AS at FROM pull p
32 JOIN issue i ON i.id = p.issue_id JOIN repo r ON r.id = i.repo_id
33 WHERE p.merged_at >= ?1 AND p.base_branch = r.default_branch`,
34 )
35 .all(new Date(first).toISOString());
36 const counts = new Array<number>(24).fill(0);
37 for (const { at } of rows) {
38 const slot = Math.floor((Date.parse(at) - first) / HOUR);
39 if (slot >= 0 && slot < 24) counts[slot] = (counts[slot] ?? 0) + 1;
40 }
41 return counts;
42 }
43
44 /** The median of finished checks' wall time over the last day, in ms, or undefined. */
45 export function medianCheckMs(db: Database, now: number): number | undefined {
46 const rows = db
47 .query<{ started_at: string; finished_at: string }, [string]>(
48 `SELECT started_at, finished_at FROM run
49 WHERE kind = 'check' AND started_at IS NOT NULL AND finished_at >= ?1
50 ORDER BY finished_at DESC LIMIT 500`,
51 )
52 .all(new Date(now - 24 * HOUR).toISOString());
53 const spans = rows
54 .map((r) => Date.parse(r.finished_at) - Date.parse(r.started_at))
55 .filter((n) => Number.isFinite(n) && n >= 0)
56 .sort((a, b) => a - b);
57 if (spans.length === 0) return undefined;
58 const mid = Math.floor(spans.length / 2);
59 return spans.length % 2 === 1 ? spans[mid]! : (spans[mid - 1]! + spans[mid]!) / 2;
60 }
61
62 const span = (ms: number): string => {
63 const s = Math.round(ms / 1000);
64 if (s < 90) return `${s}s`;
65 const m = Math.round(s / 60);
66 return m < 90 ? `${m} min` : `${(m / 60).toFixed(1)} h`;
67 };
68
69 const age = (iso: string, now: number): string => {
70 const ms = now - Date.parse(iso);
71 return Number.isFinite(ms) ? `${span(Math.max(0, ms))} ago` : "unknown";
72 };
73
74 const usd = (n: number): string => `$${n.toFixed(n < 100 ? 2 : 0)}`;
75
76 export function readKpis(
77 db: Database,
78 dataDir: string,
79 userId: string,
80 booted: string,
81 now = Date.now(),
82 ): Kpi[] {
83 const spark = landingsByHour(db, now);
84 const total = spark.reduce((a, b) => a + b, 0);
85 const live = running();
86 const check = medianCheckMs(db, now);
87 const busy =
88 db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM run WHERE kind = 'agent' AND state = 'running'").get()?.n ?? 0;
89 const slots =
90 db
91 .query<{ n: number | null }, []>("SELECT SUM(autonomy_slots) AS n FROM repo WHERE autonomy != 'off'")
92 .get()?.n ?? 0;
93 const spent =
94 db
95 .query<{ n: number }, [string, string]>(
96 `SELECT COALESCE(SUM(u.cost_usd), 0) AS n FROM usage u JOIN repo r ON r.id = u.repo_id
97 WHERE r.owner_id = ?1 AND u.at >= ?2`,
98 )
99 .get(userId, dayStart(new Date(now)))?.n ?? 0;
100 const ceiling = getAccountCeiling(db, userId);
101 const mirror = lastMirror(dataDir);
102 const synced = mirror?.syncedAt;
103 return [
104 {
105 key: "landings",
106 label: "Landings per hour",
107 value: (total / 24).toFixed(1),
108 note: `${total} in the last 24 h`,
109 href: "/boards/data?source=stages&fcolumn=stage&fop=eq&fvalue=4+merged&by=hour&chart=bar",
110 spark,
111 },
112 {
113 key: "live",
114 label: "Live version",
115 value: live.version,
116 note: `live ${age(booted, now)}`,
117 href: "/releases",
118 },
119 {
120 key: "check",
121 label: "Median check",
122 value: check === undefined ? "none" : span(check),
123 note: "finished in the last 24 h",
124 href: "/boards/data?source=runs&fcolumn=kind&fop=eq&fvalue=check&by=day&chart=bar",
125 },
126 {
127 key: "builders",
128 label: "Builders at work",
129 value: `${busy} of ${slots}`,
130 note: "running now, of slots",
131 href: "/flow",
132 },
133 {
134 key: "spend",
135 label: "Spent today",
136 value: ceiling === undefined ? usd(spent) : `${usd(spent)} of ${usd(ceiling.dailyUsd)}`,
137 note: ceiling === undefined ? "no daily ceiling set" : "of today's ceiling",
138 href: "/boards/data?source=spend&aggregate=sum&column=cost_usd&by=day&chart=bar",
139 },
140 {
141 key: "backup",
142 label: "Off-box backup",
143 value: synced === undefined ? "none" : age(synced, now),
144 note: synced === undefined ? "no copy kept elsewhere" : "last confirmed good",
145 href: "/settings/backups",
146 },
147 ];
148 }
149
150 /** The KPIs as one line of plain text, for the terminal. */
151 export const kpiLine = (kpis: readonly Kpi[]): string =>
152 kpis.map((k) => `${k.label.toLowerCase()} ${k.value}`).join(" · ");
src/http/api.ts +18
@@ -16,6 +16,7 @@ import { storageLimitMessage } from "../core/storage.ts";
1616 import { voteVariant } from "../actions/variants.ts";
1717 import { parentForgeFor } from "../core/parent_releases.ts";
1818 import { readFlow } from "../flow/read.ts";
19 import { changeHomePin, homeView } from "../actions/home.ts";
1920 import { deleteBoard, listAllBoards, showBoard, writeBoard, type BoardError } from "../actions/boards.ts";
2021 import { runQuery } from "../boards/query.ts";
2122 import { recordDrill } from "../core/domain_drills.ts";
@@ -1503,6 +1504,23 @@ export function apiRoutes(router: Router<Handler>): void {
15031504 return done.ok ? json({ slug: ctx.params.slug, ...done.value }) : boardFailed(done.error);
15041505 });
15051506
1507 // The owner's home as data: the KPIs and the pinned panels (`actions/home.ts`).
1508 router.add("GET", "/api/v1/home", async (ctx) => {
1509 const denied = boardsAdmin(ctx);
1510 if (denied) return denied;
1511 const view = await homeView(ctx.app, ctx.auth.user);
1512 return view.ok ? json(view.value) : notFound();
1513 });
1514
1515 router.add("POST", "/api/v1/home/panels", async (ctx) => {
1516 const denied = boardsAdmin(ctx) ?? requireAccount(ctx, { adminToken: true });
1517 if (denied) return denied;
1518 const input = await body(ctx.request);
1519 const done = await changeHomePin(ctx.app, ctx.auth.user, { slug: input.slug, index: input.index, action: input.action });
1520 if (done.ok) return json({ ok: true });
1521 return done.error === "full" ? apiError("full", 409, "too many pins; unpin one first") : notFound();
1522 });
1523
15061524 router.add("DELETE", "/api/v1/boards/:slug", async (ctx) => {
15071525 const denied = boardsAdmin(ctx) ?? requireAccount(ctx, { adminToken: true });
15081526 if (denied) return denied;
src/http/mcp.ts +34
@@ -183,6 +183,7 @@ import type { Router } from "./router.ts";
183183 import { mayReadRuns } from "../actions/runs.ts";
184184 import { manifestFor } from "../actions/here.ts";
185185 import { clientBucket } from "./peer.ts";
186 import { changeHomePin, homeView } from "../actions/home.ts";
186187 import { deleteBoard, listAllBoards, showBoard, writeBoard, type BoardError } from "../actions/boards.ts";
187188 import { fileReport } from "../actions/reports.ts";
188189 import { BODY_MAX, REQUEST_MAX, TITLE_MAX } from "../core/reports.ts";
@@ -2868,6 +2869,39 @@ const TOOLS: readonly Tool[] = [
28682869 return shown.ok ? good({ slug: str(args["slug"]), ...shown.value }) : boardFailed(shown.error);
28692870 },
28702871 },
2872 {
2873 name: "home",
2874 description:
2875 "The owner's home as data, for a forge admin who is a person (an agent is refused): the KPIs (landings per hour, live version, median check time, builders at work, today's spend, off-box backup age, each with the page it comes from) and the board panels pinned to home with their current values. The same as / and GET /api/v1/home.",
2876 inputSchema: { type: "object", properties: {} },
2877 writes: false,
2878 async run(ctx, user) {
2879 if (!mayBoards(user)) return boardRefused();
2880 const view = await homeView(ctx.app, user);
2881 return view.ok ? good({ ...view.value }) : boardFailed(view.error);
2882 },
2883 },
2884 {
2885 name: "home_pin",
2886 description:
2887 "Pin a board panel to the owner's home, unpin it, or move a pinned one earlier or later in the owner's order. `slug` and `index` name the panel (see `boards`); `action` is pin, unpin, up or down. For a forge admin who is a person; an agent is refused. The same as POST /api/v1/home/panels.",
2888 inputSchema: {
2889 type: "object",
2890 properties: {
2891 slug: { type: "string", maxLength: 40 },
2892 index: { type: "integer", minimum: 0, maximum: 99 },
2893 action: { type: "string", enum: ["pin", "unpin", "up", "down"] },
2894 },
2895 required: ["slug", "index", "action"],
2896 },
2897 writes: true,
2898 async run(ctx, user, args) {
2899 if (!mayBoards(user)) return boardRefused();
2900 const done = await changeHomePin(ctx.app, user, { slug: args["slug"], index: args["index"], action: args["action"] });
2901 if (done.ok) return good({ ok: true });
2902 return done.error === "full" ? bad("full", "too many pins; unpin one first") : boardFailed(done.error);
2903 },
2904 },
28712905 {
28722906 name: "board_write",
28732907 description:
src/http/server.ts +2
@@ -23,6 +23,7 @@ import { usagePage } from "../web/pages/usage.ts";
2323 import { domainsPage } from "../web/pages/domains.ts";
2424 import { resiliencePage } from "../web/pages/resilience.ts";
2525 import { limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke } from "../web/pages/admin-limits.ts";
26 import { homePanels } from "../web/studio/home_owner.ts";
2627 import { boardsPage } from "../web/pages/boards.ts";
2728 import { boardNew, boardPin, boardPost } from "../web/pages/boards-edit.ts";
2829 import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts";
@@ -810,6 +811,7 @@ export function buildRouter(): Router<Handler> {
810811 router.add("GET", "/boards", boardsList);
811812 router.add("GET", "/boards/data", boardsPage);
812813 router.add("POST", "/boards/new", boardNew);
814 router.add("POST", "/home/panels", homePanels);
813815 router.add("POST", "/boards/pin", boardPin);
814816 router.add("GET", "/boards/:slug", boardShow);
815817 router.add("GET", "/boards/:slug/live", boardLive);
src/tui/screens/boards.ts +53 −9
@@ -7,6 +7,7 @@
77 * as its title, chart, size and the query that feeds it.
88 */
99
10 import { isOwner, movePin, pinPanel, pinsOf, unpinPanel } from "../../core/home_panels.ts";
1011 import type { Board } from "../../boards/store.ts";
1112 import { listAllBoards, showBoard } from "../../actions/boards.ts";
1213 import type { Ctx, Screen } from "../app/app.ts";
@@ -39,27 +40,60 @@ export async function boardRows(session: Session): Promise<BoardRow[]> {
3940 }));
4041 }
4142
42 /** A board, panel by panel, as lines of text. */
43 export function boardLines(board: Board): string[] {
43 /** A board, panel by panel, as lines of text; the panel at `at` is marked, and so is each pinned one. */
44 export function boardLines(board: Board, pinned: readonly boolean[] = [], at = -1): string[] {
4445 const lines = [
4546 plain(board.title),
4647 `range ${board.range} · refresh ${board.refresh} · ${plural(board.panels.length, "panel")}`,
4748 ];
48 for (const p of board.panels) {
49 board.panels.forEach((p, i) => {
4950 const query = Object.entries(p.query)
5051 .map(([k, v]) => `${plain(k)}=${plain(typeof v === "string" ? v : JSON.stringify(v))}`)
5152 .join(" ");
52 lines.push("", plain(p.title), ` ${p.chart} · ${p.w}×${p.h}`, ` ${query === "" ? "no query" : query}`);
53 }
53 lines.push(
54 "",
55 `${i === at ? "▸ " : ""}${plain(p.title)}${pinned[i] === true ? " [on home]" : ""}`,
56 ` ${p.chart} · ${p.w}×${p.h}`,
57 ` ${query === "" ? "no query" : query}`,
58 );
59 });
5460 return lines;
5561 }
5662
57 function boardScreen(ctx: Ctx, board: Board): Screen {
63 function boardScreen(f: Session, ctx: Ctx, slug: string, board: Board): Screen {
5864 const scroll = new Scroll();
59 const lines = boardLines(board);
65 const owner = f.user !== undefined && isOwner(f.user);
66 let at = board.panels.length > 0 ? 0 : -1;
67 const pinned = (): boolean[] => {
68 const pins = f.user === undefined ? [] : pinsOf(f.db, f.user.id);
69 return board.panels.map((_, i) => pins.some((p) => p.slug === slug && p.index === i));
70 };
71 let lines = boardLines(board, pinned(), at);
72 const redraw = (): void => {
73 lines = boardLines(board, pinned(), at);
74 ctx.invalidate();
75 };
76 /** Pin, unpin or move the panel under the marker; the owner's alone, as the page's door is. */
77 const act = (verb: "pin" | "up" | "down"): void => {
78 if (!owner || f.user === undefined || at < 0) return;
79 const pin = { slug, index: at };
80 const here = pinned()[at] === true;
81 if (verb === "pin") {
82 if (here) unpinPanel(f.db, f.user.id, pin);
83 else if (!pinPanel(f.db, f.user.id, pin)) ctx.toast("Too many pins; unpin one first", "default");
84 else ctx.toast("Pinned to home", "default");
85 } else if (here) movePin(f.db, f.user.id, pin, verb === "up" ? -1 : 1);
86 redraw();
87 };
6088 return {
6189 title: plain(board.title),
62 keys: [binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")],
90 keys: [
91 binding(["j", "k"], "scroll"),
92 ...(owner
93 ? [binding(["n", "N"], "panel"), binding(["p"], "pin to home"), binding(["[", "]"], "move pin")]
94 : []),
95 binding(["esc", "q"], "back"),
96 ],
6397 render(area, s) {
6498 const c = ctx.theme.c;
6599 const spans = lines.map((text, i) => [{ text, style: style(i === 0 ? c.fg : c.mutedFg, c.bg) }]);
@@ -72,6 +106,16 @@ function boardScreen(ctx: Ctx, board: Board): Screen {
72106 ctx.pop();
73107 return true;
74108 }
109 if (!owner) return false;
110 if (e.key === "n" || e.key === "N") {
111 const n = board.panels.length;
112 if (n > 0) at = (at + (e.key === "n" ? 1 : n - 1)) % n;
113 redraw();
114 return true;
115 }
116 if (e.key === "p") return act("pin"), true;
117 if (e.key === "[") return act("up"), true;
118 if (e.key === "]") return act("down"), true;
75119 return false;
76120 },
77121 };
@@ -90,7 +134,7 @@ export function boardsScreen(f: Session, ctx: Ctx): Screen {
90134 runAsync(ctx, async () => {
91135 const shown = await showBoard(f.app, f.user, row.slug);
92136 if (!shown.ok) ctx.toast("That board is gone", "default");
93 else ctx.push(boardScreen(ctx, shown.value));
137 else ctx.push(boardScreen(f, ctx, row.slug, shown.value));
94138 });
95139 };
96140 return {
src/tui/screens/dashboard.ts +29
@@ -14,6 +14,10 @@
1414 * whole of this screen's design.
1515 */
1616
17 import { homePanels } from "../../actions/home.ts";
18 import { isOwner } from "../../core/home_panels.ts";
19 import { kpiLine, readKpis } from "../../core/kpis.ts";
20 import { BOOTED } from "../../release/gate.ts";
1721 import { protectionNotice } from "../../kernel/protection.ts";
1822 import { holdWords, plannerHold } from "../../crew/autonomy.ts";
1923 import { forgeLane, forgeNeeds } from "../../actions/health.ts";
@@ -142,6 +146,9 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
142146 let lastArchive: string | undefined;
143147 /** Why planning is paused, for the autonomous apps where it is; as on the board. */
144148 let holds = new Map<string, string>();
149 let kpis: string | undefined;
150 /** One line per panel pinned to the owner's home: its title and current value. */
151 let pinLines: string[] = [];
145152 let forge: string[] | undefined;
146153 /** A client's apps, one sentence each on whether its agents work or wait (#1812). */
147154 let clientLines: string[] = [];
@@ -191,6 +198,16 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
191198 return hold === null ? [] : [[repo.id, holdWords(hold)] as const];
192199 }),
193200 );
201 // The owner's vital signs, the web home's KPI row as one line.
202 kpis =
203 f.user !== undefined && isOwner(f.user)
204 ? kpiLine(readKpis(f.db, f.app.config.dataDir, f.user.id, BOOTED))
205 : undefined;
206 if (f.user !== undefined && isOwner(f.user))
207 void homePanels(f.app, f.user).then((panels) => {
208 pinLines = panels.slice(0, 4).map((p) => `${p.title}: ${p.value}`);
209 ctx.invalidate();
210 });
194211 forge = forgeNeeds(f.app, f.user);
195212 if (forge !== undefined) {
196213 const fh = forgeHealth();
@@ -763,6 +780,18 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
763780 );
764781 body = rest!;
765782 }
783 if (kpis !== undefined) {
784 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
785 s.text(strip!.x, strip!.y, truncate(kpis, strip!.w), style(c.fg, c.bg), strip!.x + strip!.w);
786 body = rest!;
787 }
788 if (kpis !== undefined && pinLines.length > 0) {
789 const [strip, rest] = split(body, "v", [len(pinLines.length), fill(1)]);
790 pinLines.forEach((line, i) =>
791 s.text(strip!.x, strip!.y + i, truncate(` ${line}`, strip!.w), style(c.mutedFg, c.bg), strip!.x + strip!.w),
792 );
793 body = rest!;
794 }
766795 if (decider !== null) {
767796 const [strip, rest] = split(body, "v", [len(1), fill(1)]);
768797 s.text(
src/web/pages/board.ts +2 −2
@@ -394,7 +394,7 @@ function reviewStrip(ctx: Ctx, scope: BoardScope): Html | null {
394394 if (!none && waits.length === 0) return [];
395395 const oldest = waits.map((w) => w.since).sort()[0];
396396 return [
397 html`<a class="board-asks" href="/#needs-you"
397 html`<a class="board-asks" href="/asks"
398398 ><b>${repo.name}</b>: ${none ? "No reviewer: agent pulls wait for you" : "agent pulls wait for your review"}${waits.length === 0
399399 ? null
400400 : html` · <b>${waits.length}</b> waiting since ${oldest!.slice(0, 10)}`}</a
@@ -421,7 +421,7 @@ function asksStrip(ctx: Ctx): Html | null {
421421 const since = new Date(Date.now() - ASKS_WINDOW_DAYS * 86_400_000).toISOString();
422422 const m = askMeasure(ctx.app.db, user.id, since);
423423 if (m.raised + m.acted + m.dismissed + m.expired === 0) return null;
424 return html`<a class="board-asks" id="asks-measure" href="/#needs-you"
424 return html`<a class="board-asks" id="asks-measure" href="/asks"
425425 >Asks, ${ASKS_WINDOW_DAYS} days: <b>${m.raised}</b> raised · <b>${m.acted}</b> acted
426426 on · <b>${m.dismissed}</b> dismissed · <b>${m.expired}</b> went by themselves</a
427427 >`;
src/web/pages/boards-view.ts +19 −13
@@ -7,6 +7,8 @@
77 * the same swap the wall uses, no client framework. Every form posts to
88 * `boards-edit.ts`. Anyone but a person who is an admin gets the not-found page.
99 */
10 import { pinsOf, samePin, type PanelPin } from "../../core/home_panels.ts";
11 import { ranged } from "../../boards/summary.ts";
1012 import { listAllBoards, showBoard } from "../../actions/boards.ts";
1113 import { CHART_NAMES } from "../../boards/chart.ts";
1214 import { MAX_H, MAX_PANELS, MAX_TITLE, MAX_W, RANGES, REFRESHES, type Board, type Panel } from "../../boards/store.ts";
@@ -19,19 +21,13 @@ import { fragment, page } from "../layout.ts";
1921 import { btn, card, empty } from "../ui.ts";
2022 import { cellsOf, chartBox, paramsOf, queryFields, readParams, runFor } from "./boards.ts";
2123
22 const RANGE_MS = { "1h": 3_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const;
2324 const EVERY = { "10s": 10, "1m": 60 } as const;
2425
2526 const option = (value: string, selected: boolean) =>
2627 html`<option value="${value}" ${selected ? raw("selected") : null}>${value}</option>`;
2728
28 /** The panel's query as asked, with the board's range as its start when it names none. */
29 function ranged(query: Record<string, unknown>, range: Board["range"]): Record<string, unknown> {
30 if (range === "all" || query.from !== undefined) return query;
31 return { ...query, from: new Date(Date.now() - RANGE_MS[range]).toISOString() };
32 }
33
34 function drawPanel(app: App, board: Board, panel: Panel): Html {
29 /** One panel's card; `controls` sit in its head beside "explore". */
30 export function drawPanel(app: App, board: Board, panel: Panel, controls: Html | null = null): Html {
3531 const answer = runFor(app.db, panel.chart, ranged(panel.query, board.range));
3632 const q = paramsOf(panel.query, panel.chart);
3733 const body = !answer.ok
@@ -40,13 +36,13 @@ function drawPanel(app: App, board: Board, panel: Panel): Html {
4036 const explore = new URLSearchParams(Object.entries(q).filter(([k, v]) => v !== "" && k !== "rows"));
4137 return html`<div class="card bp-w${String(panel.w)} bp-h${String(panel.h)}">
4238 <div class="card-head"><h2>${panel.title}</h2>
43 <a class="muted small" href="/boards/data?${explore.toString()}">explore</a></div>
39 <a class="muted small" href="/boards/data?${explore.toString()}">explore</a>${controls}</div>
4440 <div class="card-body">${body}</div>
4541 </div>`;
4642 }
4743
4844 /** The grid alone: what the page shows and what the live address answers with. */
49 function grid(app: App, slug: string, board: Board): Html {
45 function grid(app: App, slug: string, board: Board, pins: readonly PanelPin[]): Html {
5046 const every = board.refresh === "off" ? null : EVERY[board.refresh];
5147 return html`<section
5248 class="bgrid"
@@ -57,10 +53,20 @@ function grid(app: App, slug: string, board: Board): Html {
5753 >
5854 ${board.panels.length === 0
5955 ? html`<p class="muted">No panels yet. Add one below.</p>`
60 : board.panels.map((p) => drawPanel(app, board, p))}
56 : board.panels.map((p, index) => {
57 const pinned = pins.some((x) => samePin(x, { slug, index }));
58 return drawPanel(app, board, p, html`<form method="post" action="/home/panels" class="inline">
59 <input type="hidden" name="slug" value="${slug}" /><input type="hidden" name="index" value="${String(index)}" />
60 <input type="hidden" name="back" value="/boards/${slug}" />
61 <button class="btn btn-sm btn-ghost" name="action" value="${pinned ? "unpin" : "pin"}"
62 >${pinned ? "Unpin from home" : "Pin to home"}</button>
63 </form>`);
64 })}
6165 </section>`;
6266 }
6367
68 const pinsFor = (ctx: Ctx): PanelPin[] => (ctx.auth.user ? pinsOf(ctx.app.db, ctx.auth.user.id) : []);
69
6470 const denied = (ctx: Ctx) => {
6571 const u = ctx.auth.user;
6672 return u?.isAdmin !== true || u.kind === "agent";
@@ -163,7 +169,7 @@ export async function boardShow(ctx: Ctx): Promise<Response> {
163169 title: board.title,
164170 body: html`<div class="page-head"><h1>${board.title}</h1>
165171 ${btn("All boards", { href: "/boards", variant: "ghost" })}</div>
166 ${grid(ctx.app, slug, board)}
172 ${grid(ctx.app, slug, board, pinsFor(ctx))}
167173 ${manage(slug, board, queryFields(readParams(ctx.url.searchParams)))}`,
168174 scriptJs: liveRegionsJs,
169175 });
@@ -175,5 +181,5 @@ export async function boardLive(ctx: Ctx): Promise<Response> {
175181 const slug = ctx.params.slug ?? "";
176182 const shown = await showBoard(ctx.app, ctx.auth.user, slug);
177183 if (!shown.ok) return fragment(html``, { status: 404 });
178 return fragment(grid(ctx.app, slug, shown.value), { request: ctx.request });
184 return fragment(grid(ctx.app, slug, shown.value, pinsFor(ctx)), { request: ctx.request });
179185 }
src/web/pages/site.ts +4
@@ -24,6 +24,7 @@ import { hasAnyUser, verifyPasswordThrottled, type User } from "../../core/users
2424 import { isThemeName } from "../../design/themes.ts";
2525 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
2626 import { studioDoor, studioHome } from "../studio/home.ts";
27 import { isOwner } from "../../core/home_panels.ts";
2728 import { homeTop } from "../studio/asks_page.ts";
2829 import { edgeLoginUrl } from "../../http/edge.ts";
2930 import { sshCommand } from "../../ssh/command.ts";
@@ -208,6 +209,9 @@ export function terminalCard(ctx: Ctx): Html {
208209 export async function home(ctx: Ctx): Promise<Response> {
209210 const user = ctx.auth.user;
210211 if (user === undefined) return studioDoor(ctx);
212 // A bulk step's receipt belongs to the asks, which the owner's home leaves out.
213 if (isOwner(user) && (ctx.url.searchParams.has("op") || ctx.url.searchParams.has("decided")))
214 return redirect(`/asks${ctx.url.search}`);
211215 return await studioHome(ctx, user, homeTop(ctx));
212216 }
213217
src/web/studio/asks_page.ts +7 −2
@@ -28,6 +28,7 @@ import type { Degraded } from "../../kernel/vitals.ts";
2828 import type { Ctx } from "../../http/context.ts";
2929 import type { User } from "../../core/users.ts";
3030 import { onYouAnswer, studioHome } from "./home.ts";
31 import { isOwner } from "../../core/home_panels.ts";
3132 import { notFoundPage, repoBase, signInFirst } from "../chrome.ts";
3233 import { backTo, field, readForm } from "../form.ts";
3334 import { MAX_BODY } from "../../core/issues.ts";
@@ -334,7 +335,11 @@ export interface AsksTop {
334335
335336 /** GET /asks — the home, scrolled to what needs you; `?op=<id>` (a bulk
336337 * action's receipt) rides along. */
337 export function asksPage(ctx: Ctx): Response {
338 export async function asksPage(ctx: Ctx): Promise<Response> {
339 const user = ctx.auth.user;
340 // The owner's home shows no list; their asks are here, on request.
341 if (user !== undefined && isOwner(user))
342 return await studioHome(ctx, user, homeTop(ctx), true);
338343 const op = ctx.url.searchParams.get("op");
339344 return redirect(
340345 op === null
@@ -492,7 +497,7 @@ export function needsYouSection(
492497 async function asksScreen(ctx: Ctx, top: AsksTop): Promise<Response> {
493498 const user = ctx.auth.user;
494499 if (!user) return signInFirst(ctx);
495 return await studioHome(ctx, user, top);
500 return await studioHome(ctx, user, top, isOwner(user));
496501 }
497502
498503 // ---- many at once: select, preview, do it, undo — all on this screen ----
src/web/studio/home.ts +17 −2
@@ -46,6 +46,8 @@ import {
4646 } from "../pages/site.ts";
4747 import { writableAppsOf } from "./asks.ts";
4848 import { needsYouSection, type AsksTop } from "./asks_page.ts";
49 import { kpiRow, pinnedPanels } from "./home_owner.ts";
50 import { isOwner } from "../../core/home_panels.ts";
4951 import { flowCards } from "./flow_card.ts";
5052 import { composer, feedJs, feedNote, feedRegion } from "./feed.ts";
5153 import { homeTabs } from "./home_tabs.ts";
@@ -206,8 +208,20 @@ export async function studioHome(
206208 ctx: Ctx,
207209 user: User,
208210 top?: AsksTop,
211 onlyAsks = false,
209212 ): Promise<Response> {
210 const needsYou = needsYouSection(ctx, user, top);
213 const owner = isOwner(user);
214 // The owner's home never lists what waits on them; `/asks` does, on purpose.
215 if (owner && onlyAsks) {
216 const needs = needsYouSection(ctx, user, top);
217 return page({
218 ctx,
219 title: "Asks",
220 body: html`<h1>Asks</h1>${onYouRegion(ctx, user, undefined, needs.body)}`,
221 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${needs.scriptJs}`,
222 });
223 }
224 const needsYou = owner ? { body: html``, scriptJs: "" } : needsYouSection(ctx, user, top);
211225 const { repos: appRepos } = writableAppsOf(ctx, user);
212226 // A spawned forge says where it lives: the address its person shares.
213227 const spawned = await spawnedOrg(ctx.app);
@@ -253,10 +267,11 @@ export async function studioHome(
253267 <a href="/">Just my apps</a>
254268 </p>`,
255269 )}
270 ${owner ? kpiRow(ctx, user) : null} ${owner ? await pinnedPanels(ctx, user) : null}
256271 ${homeTabs("feed")}
257272 <div class="dash">
258273 <div class="dash-main stack">
259 ${onYouRegion(ctx, user, undefined, needsYou.body)} ${composer(ctx, user)}
274 ${owner ? null : onYouRegion(ctx, user, undefined, needsYou.body)} ${composer(ctx, user)}
260275 <div class="bar feed-head">
261276 <span class="spacer"></span>
262277 <a class="small muted" href="/asked">What you asked for</a>
src/web/studio/home_owner.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * The owner's home: the forge's vital signs, then the board panels the owner
3 * pinned, in their order. Never a list of what waits on the owner — that
4 * list is `/asks`, reached on purpose. The owner is a person who administers
5 * the forge (boards are theirs alone). `POST /home/panels` pins, unpins and
6 * moves a pinned panel; same-origin checked by `readForm`.
7 */
8 import { changeHomePin } from "../../actions/home.ts";
9 import { showBoard } from "../../actions/boards.ts";
10 import { isOwner, pinsOf } from "../../core/home_panels.ts";
11 import { readKpis, type Kpi } from "../../core/kpis.ts";
12 import type { User } from "../../core/users.ts";
13 import type { Ctx } from "../../http/context.ts";
14 import { BOOTED } from "../../release/gate.ts";
15 import { notFoundPage } from "../chrome.ts";
16 import { isLocalPath } from "../flash.ts";
17 import { field, readForm } from "../form.ts";
18 import { html, type Html } from "../html.ts";
19 import { flashTo } from "../layout.ts";
20 import { drawPanel } from "../pages/boards-view.ts";
21 import { isSlug } from "../../boards/store.ts";
22
23 function spark(counts: readonly number[]): Html {
24 const top = Math.max(1, ...counts);
25 const pts = counts.map((n, i) => `${((i / (counts.length - 1)) * 100).toFixed(1)},${(18 - (n / top) * 16 - 1).toFixed(1)}`);
26 return html`<svg viewBox="0 0 100 18" preserveAspectRatio="none" aria-hidden="true"><polyline points="${pts.join(" ")}" /></svg>`;
27 }
28
29 function tile(k: Kpi): Html {
30 return html`<li><a class="kpi" id="kpi-${k.key}" href="${k.href}">
31 <span class="kpi-label">${k.label}</span>
32 <span class="kpi-value">${k.value}</span>
33 ${k.spark ? spark(k.spark) : null}
34 <span class="kpi-note">${k.note}</span>
35 </a></li>`;
36 }
37
38 export function kpiRow(ctx: Ctx, user: User): Html {
39 const kpis = readKpis(ctx.app.db, ctx.app.config.dataDir, user.id, BOOTED);
40 return html`<ul class="kpis" aria-label="How the forge is">${kpis.map(tile)}</ul>`;
41 }
42
43 const IDX = /^\d{1,2}$/;
44
45 /** The pinned panels, drawn; a pin whose board or panel is gone is skipped. */
46 export async function pinnedPanels(ctx: Ctx, user: User): Promise<Html | null> {
47 const cards: Html[] = [];
48 for (const pin of pinsOf(ctx.app.db, user.id)) {
49 const shown = await showBoard(ctx.app, user, pin.slug);
50 const panel = shown.ok ? shown.value.panels[pin.index] : undefined;
51 if (!shown.ok || panel === undefined) continue;
52 const act = (action: string, label: string) =>
53 html`<button class="btn btn-sm btn-ghost" name="action" value="${action}">${label}</button>`;
54 cards.push(
55 drawPanel(ctx.app, shown.value, panel, html`<form method="post" action="/home/panels" class="inline">
56 <input type="hidden" name="slug" value="${pin.slug}" /><input type="hidden" name="index" value="${String(pin.index)}" />
57 <input type="hidden" name="back" value="/" />
58 ${act("up", "Up")} ${act("down", "Down")} ${act("unpin", "Unpin")}
59 </form>`),
60 );
61 }
62 return cards.length === 0 ? null : html`<section class="bgrid home-pins" aria-label="Pinned panels">${cards}</section>`;
63 }
64
65 // POST /home/panels
66 export async function homePanels(ctx: Ctx): Promise<Response> {
67 const form = await readForm(ctx, "admin");
68 if (form instanceof Response) return form;
69 const user = ctx.auth.user;
outdated

This is the only door that writes the pins. Put the same pin, unpin and move calls on the terminal's Boards panel view, with the same owner-only check (isOwner), so both doors match.

70 if (user === undefined || !isOwner(user)) return notFoundPage(ctx);
71 const slug = field(form, "slug");
72 const index = field(form, "index");
73 const action = field(form, "action");
74 const asked = field(form, "back");
75 const back = isLocalPath(asked) ? asked : "/";
76 if (!isSlug(slug) || !IDX.test(index)) return notFoundPage(ctx);
77 const done = await changeHomePin(ctx.app, user, { slug, index: Number(index), action });
78 if (!done.ok)
79 return done.error === "full"
80 ? flashTo(ctx, back, { tone: "danger", message: "Too many pins; unpin one first." })
81 : notFoundPage(ctx);
82 return flashTo(ctx, back, { message: action === "pin" ? "Pinned to home." : action === "unpin" ? "Unpinned." : "Moved." });
83 }
src/web/style/content.ts +11
@@ -1315,4 +1315,15 @@ textarea.editor:focus { outline: none; }
13151315 .ask-more-acts[open] > summary { display: none; }
13161316 .ask-more-acts > .btn { min-height: 44px; flex: 1 1 auto; }
13171317 }
1318
1319 /* The owner's home: a row of vital signs that wraps, then pinned panels. */
1320 .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin: 0 0 16px; padding: 0; list-style: none; }
1321 .kpi { display: block; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; color: inherit; text-decoration: none; min-width: 0; min-height: 84px; }
1322 .kpi:hover { border-color: var(--border-strong); }
1323 .kpi-label { display: block; font-size: 12px; color: var(--muted-fg); }
1324 .kpi-value { display: block; font-size: 20px; font-weight: 600; overflow-wrap: anywhere; }
1325 .kpi-note { display: block; font-size: 12px; color: var(--muted-fg); }
1326 .kpi svg { display: block; width: 100%; height: 18px; }
1327 .kpi polyline { fill: none; stroke: currentColor; stroke-width: 1.5; vector-effect: non-scaling-stroke; }
1328 .home-pins { margin-bottom: 16px; }
13181329 `;
test/asks-bulk.test.ts +1 −1
@@ -77,7 +77,7 @@ describe("acting on many asks at once", () => {
7777 const location = res.headers.get("location");
7878 if (res.status === 303 && location !== null) {
7979 expect(location).toStartWith("/?op=");
80 const next = await fetch(`${servers.url}${location}`, { headers, redirect: "manual" });
80 const next = await fetch(`${servers.url}${location}`, { headers, redirect: "follow" });
8181 expect(next.status).toBe(200);
8282 return (await next.text()).replace(/\s+/g, " ");
8383 }
test/asks-expiry.test.ts +7 −7
@@ -126,7 +126,7 @@ describe("asks that expire, hold and collapse", () => {
126126 pears = await botPull("pears", [{ path: "PEARS.md", content: "pears\n" }]);
127127 green(apples);
128128 green(pears);
129 const page = await get("/");
129 const page = await get("/asks");
130130 expect(sentence(page)).toBe("1 thing needs you");
131131 expect(headerCount(page)).toBe(1);
132132 expect(page).toContain("2 green changes wait for your look");
@@ -152,7 +152,7 @@ describe("asks that expire, hold and collapse", () => {
152152 // card at all, so there is nothing to mute.
153153 const fragment = await get("/live/feed");
154154 expect(fragment).not.toContain('data-kind="ask"');
155 const home = await get("/");
155 const home = await get("/asks");
156156 expect(home).toContain('<section id="needs-you"');
157157 const at = home.indexOf('<section id="needs-you"');
158158 expect(home.slice(at, home.indexOf("</section>", at))).not.toContain(
@@ -169,7 +169,7 @@ describe("asks that expire, hold and collapse", () => {
169169 repoId: repo.id,
170170 actorId: null,
171171 });
172 let page = await get("/");
172 let page = await get("/asks");
173173 expect(sentence(page)).toBe("All fine");
174174 expect(headerCount(page)).toBe(0);
175175 expect(askLinesFor(app.db, aliceUser)).toHaveLength(0);
@@ -179,7 +179,7 @@ describe("asks that expire, hold and collapse", () => {
179179 // A new check on one of them: that one asks again, on its own.
180180 await tick();
181181 green(apples);
182 page = await get("/");
182 page = await get("/asks");
183183 expect(sentence(page)).toBe("1 thing needs you");
184184 const pinned = page.slice(
185185 page.indexOf('<section id="needs-you"'),
@@ -203,7 +203,7 @@ describe("asks that expire, hold and collapse", () => {
203203 repoId: repo.id,
204204 actorId: null,
205205 });
206 expect(sentence(await get("/"))).toBe("All fine");
206 expect(sentence(await get("/asks"))).toBe("All fine");
207207 // The merge box is the change's Files step (#628).
208208 const change = await get(
209209 `/${repo.ownerName}/${repo.name}/pulls/${apples.number}/files`,
@@ -231,7 +231,7 @@ describe("asks that expire, hold and collapse", () => {
231231 });
232232 await sweepStaleAsks(app);
233233 expect(askLinesFor(app.db, aliceUser)).toHaveLength(0);
234 expect(sentence(await get("/"))).toBe("All fine");
234 expect(sentence(await get("/asks"))).toBe("All fine");
235235 // The feed and the MCP's asks carry no green line for it either.
236236 expect(
237237 readFeed(app.db, aliceUser, { limit: 50 }).items.some(
@@ -241,7 +241,7 @@ describe("asks that expire, hold and collapse", () => {
241241 expect(JSON.stringify(asksAnswer({ app, auth: { user: aliceUser } } as never, aliceUser))).not.toContain("is green");
242242 // Assigned to alice, the home's one list says it conflicts, never ready.
243243 setAssignee(app.db, plums.id, aliceUser.id);
244 const home = await get("/");
244 const home = await get("/asks");
245245 expect(home).toContain("conflicts with main");
246246 expect(askLinesFor(app.db, aliceUser).map((l) => l.waitingFor.word)).toEqual(["conflicts with main"]);
247247 // Its own page still says why it cannot ship.
test/asks-mute.test.ts +1 −1
@@ -60,7 +60,7 @@ describe("muting a repository's asks", () => {
6060 return ((await res.json()) as { rows: unknown[] }).rows;
6161 };
6262 const home = async () =>
63 await fetch(`${servers.url}/`, { headers: headers(cookie) }).then((r) => r.text());
63 await fetch(`${servers.url}/asks`, { headers: headers(cookie) }).then((r) => r.text());
6464
6565 const signIn = async (username: string) => {
6666 const res = await fetch(`${servers.url}/signin`, {
test/asks-rank.test.ts +4 −4
@@ -204,7 +204,7 @@ describe("asks that earn their place", () => {
204204 expect(row.words).toEqual(ASK_WORDS.look);
205205 expect(row.words.options.length).toBeGreaterThan(0);
206206 }
207 const asks = await page("/");
207 const asks = await page("/asks");
208208 expect(asks).toContain("If nobody acts, it waits; nothing ships.");
209209 expect(asks).toContain("<b>security</b>");
210210 // The long sentence the card used to repeat is gone.
@@ -236,7 +236,7 @@ describe("asks that earn their place", () => {
236236 for (const name of ["r4", "r5", "r6"])
237237 await greenPull(name, `Work in ${name}`);
238238 // What needs you is pinned on the home (#634): count its own cards.
239 const home = await page("/");
239 const home = await page("/asks");
240240 const asks = home.slice(home.indexOf('<section id="needs-you"'));
241241 const cards = (s: string) => (s.match(/class="card[" ]/g) ?? []).length;
242242 // Two before the phone's "more", three more inside it before the wide
@@ -340,7 +340,7 @@ describe("asks that earn their place", () => {
340340 expect((await mcpAsks()).measure.raised).toBe(6);
341341 });
342342 test("a phone's ask is a full-width row: kind and repo on one line, the decider apart, the rest behind More", async () => {
343 const home = await page("/");
343 const home = await page("/asks");
344344 const asks = home.slice(home.indexOf('<section id="needs-you"'));
345345 expect(asks).toContain("ask-card");
346346 expect(asks).toContain('<b class="ask-kind">');
@@ -357,7 +357,7 @@ describe("asks that earn their place", () => {
357357 // The security pull went red above; a new green one joins it in a row of two.
358358 check(security, "ok");
359359 await greenPull("security", "Another change here");
360 const asks = await page("/");
360 const asks = await page("/asks");
361361 expect(asks).toContain("2 green changes wait for your look");
362362 expect(asks).toContain("<b>security</b>: \u201cWiden the board id\u201d");
363363 // On a phone the row is its head line, its two asks one tap away; a
test/asks-waiting-for.test.ts +1 −1
@@ -150,7 +150,7 @@ describe("the word on a row", () => {
150150 expect(text).toContain("ready to land");
151151 expect(text).toContain("waitingFor");
152152
153 const page = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
153 const page = await (await fetch(`${servers.url}/asks`, { headers: { cookie } })).text();
154154 expect(page).toContain('data-waiting="ready to land"');
155155 expect(page).toContain('<span class="sr-only">waiting for </span>ready to land');
156156 expect(page).toContain("ready to land · on you");
test/asks.test.ts +10 −10
@@ -104,10 +104,10 @@ describe("the asks page", () => {
104104 });
105105
106106 test("when nothing asks, it says All fine, and so does the header", async () => {
107 const page = await get(alice, "/");
107 const page = await get(alice, "/asks");
108108 expect(sentence(page)).toBe("All fine");
109109 expect(headerCount(page)).toBe(0);
110 expect(await get(alice, "/")).not.toContain('<section id="needs-you"');
110 expect(await get(alice, "/asks")).not.toContain('<section id="needs-you"');
111111 });
112112
113113 test("/asks lands on the home's pinned needs-you, and a signed-out reader there gets the door, no asks", async () => {
@@ -146,7 +146,7 @@ describe("the asks page", () => {
146146 claimRun(app.db, run.id);
147147 finishRun(app.db, run.id, { state: "failed", summary: "red" });
148148 // Failed but the crew is still trying: that is working, not an ask.
149 expect(sentence(await get(alice, "/"))).toBe("All fine");
149 expect(sentence(await get(alice, "/asks"))).toBe("All fine");
150150 recordDecision(app.db, {
151151 kind: "retry",
152152 repoId: repo.id,
@@ -157,13 +157,13 @@ describe("the asks page", () => {
157157 by: "rule",
158158 ms: 1,
159159 });
160 const page = await get(alice, "/");
160 const page = await get(alice, "/asks");
161161 expect(sentence(page)).toBe("1 thing needs you");
162162 expect(page).toContain("Bot did a thing");
163163 expect(headerCount(page)).toBe(1);
164164 // The home counts it in the header's Asks link; the dev dashboard's
165165 // own "needs you" line went with the dashboard (#625).
166 const home = await get(alice, "/");
166 const home = await get(alice, "/asks");
167167 expect(headerCount(home)).toBe(1);
168168 // Bob can read the public repository but cannot write it: not his ask.
169169 expect(sentence(await get(bob, "/"))).toBe("All fine");
@@ -174,7 +174,7 @@ describe("the asks page", () => {
174174 app.db
175175 .query("UPDATE run SET created_at = ?1 WHERE state = 'queued'")
176176 .run(new Date(Date.now() - 3 * 3_600_000).toISOString());
177 const admin = await get(alice, "/");
177 const admin = await get(alice, "/asks");
178178 expect(admin).toContain("behind one lane");
179179 expect(sentence(admin)).toBe("2 things need you");
180180 expect(headerCount(admin)).toBe(2);
@@ -224,17 +224,17 @@ describe("the asks page", () => {
224224 ms: 1,
225225 });
226226 const card = `id="ask-stopped:${pull.id}"`;
227 expect(await get(alice, "/")).toContain(card);
227 expect(await get(alice, "/asks")).toContain(card);
228228 // The re-run passes: the stop is answered, and the pull is green.
229229 check("ok");
230230 resolveOpen(app.db, pull.id, "retry", "green");
231 const green = await get(alice, "/");
231 const green = await get(alice, "/asks");
232232 expect(green).not.toContain(card);
233233 expect(green).toContain(`id="ask-look:${pull.id}"`);
234234 // Red again, before anything new is decided: the old stop is spent, and
235235 // the crew's tries are what the card is counted from.
236236 check("failed");
237 expect(await get(alice, "/")).not.toContain(card);
237 expect(await get(alice, "/asks")).not.toContain(card);
238238 });
239239
240240 test("a green change's card says what its tests did", async () => {
@@ -309,7 +309,7 @@ describe("the asks page", () => {
309309 expect(card.says).toContain("alice");
310310 expect(card.says).toContain("checks.concurrency");
311311 expect(ASK_WORDS.setting.options).toEqual(["Keep", "Put back"]);
312 const page = await get(alice, "/");
312 const page = await get(alice, "/asks");
313313 expect(page).toContain("Keep");
314314 expect(page).toContain("Put back");
315315 // not for a person who cannot put it back
test/holds.test.ts +1 −1
@@ -741,7 +741,7 @@ describe("a hold is set, shown and lifted", () => {
741741 // What needs you, pinned on the home (#634), is the part to read: the
742742 // feed below it may well mention the change as news.
743743 const asks = async (cookie: string) => {
744 const home = await page("/", cookie);
744 const home = await page("/asks", cookie);
745745 const at = home.indexOf('<section id="needs-you"');
746746 return at === -1 ? "" : home.slice(at, home.indexOf("</section>", at));
747747 };
test/home-kpis.test.ts added +208
@@ -0,0 +1,208 @@
1 /**
2 * The owner's home (#2665): KPIs read live, never a to-do list; a board
3 * panel pinned to it appears under them in order, and unpinning removes it.
4 * The asks stay one deliberate step away, on /asks.
5 */
6 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp } from "../src/app.ts";
11 import { makeBoard, changeBoard, deleteBoard } from "../src/actions/boards.ts";
12 import { landingsByHour, medianCheckMs, readKpis } from "../src/core/kpis.ts";
13 import { movePin, pinPanel, pinsOf, unpinPanel } from "../src/core/home_panels.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve } from "../src/http/server.ts";
17
18 let dir: string;
19 let app: ReturnType<typeof createApp>;
20 let servers: Awaited<ReturnType<typeof serve>>;
21 let admin: { id: string };
22 const tok: Record<string, string> = {};
23 const get = (path: string, who: string) =>
24 fetch(servers.url + path, { headers: { authorization: `Bearer ${tok[who]}` }, redirect: "manual" });
25 const post = (path: string, who: string, body: Record<string, string>) =>
26 fetch(servers.url + path, {
27 method: "POST",
28 headers: { authorization: `Bearer ${tok[who]}`, "content-type": "application/x-www-form-urlencoded" },
29 body: new URLSearchParams(body),
30 redirect: "manual",
31 });
32
33 beforeAll(async () => {
34 dir = await mkdtemp(join(tmpdir(), "forge-home-kpis-"));
35 app = createApp({ dataDir: dir, port: 0 });
36 servers = await serve(app);
37 const mk = async (username: string, adminIfFirst?: boolean) => {
38 const r = await createUser(app.db, {
39 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
40 password: "a-good-passphrase", ...(adminIfFirst ? { adminIfFirst } : {}),
41 });
42 if (!r.ok) throw new Error(r.error);
43 return r.value;
44 };
45 const alice = await mk("alice", true);
46 const bob = await mk("bob");
47 admin = alice;
48 tok.admin = createToken(app.db, alice.id, "t", "admin").token;
49 tok.bob = createToken(app.db, bob.id, "t", "admin").token;
50 const made = await makeBoard(app, alice, "Speed");
51 if (!made.ok) throw new Error(String(made.error));
52 const added = await changeBoard(app, alice, made.value, {
53 kind: "add",
54 panel: { title: "Runs a day", chart: "bar", query: { source: "runs", aggregate: "count", groupBy: { bucket: "day" } }, w: 1, h: 1 },
55 });
56 if (!added.ok) throw new Error(String(added.error));
57 });
58
59 // Every test starts with no pins, whatever the one before left.
60 beforeEach(() => {
61 for (const p of pinsOf(app.db, admin.id)) unpinPanel(app.db, admin.id, p);
62 });
63
64 afterAll(async () => {
65 servers.stop();
66 app.close();
67 await rm(dir, { recursive: true, force: true });
68 });
69
70 describe("the owner's home", () => {
71 test("shows the six KPIs, each linking to where it comes from, and no asks list", async () => {
72 const res = await get("/", "admin");
73 expect(res.status).toBe(200);
74 const body = await res.text();
75 for (const k of ["landings", "live", "check", "builders", "spend", "backup"])
76 expect(body).toMatch(new RegExp(`id="kpi-${k}" href="/[^"]+"`));
77 expect(body).not.toContain('id="needs-you"');
78 expect(body).not.toContain('id="live-on-you"');
79 expect(body).not.toContain("asks-sentence");
80 });
81
82 test("the asks stay reachable on /asks, and a receipt on / goes there", async () => {
83 const asks = await get("/asks", "admin");
84 expect(asks.status).toBe(200);
85 expect(await asks.text()).toContain("asks-sentence");
86 const receipt = await get("/?op=x", "admin");
87 expect(receipt.status).toBe(303);
88 expect(receipt.headers.get("location")).toBe("/asks?op=x");
89 });
90
91 test("another person's home keeps its asks list region", async () => {
92 expect(await (await get("/", "bob")).text()).toContain('id="live-on-you"');
93 });
94
95 test("a pinned panel appears on home, in order, and unpinning removes it", async () => {
96 const board = await (await get("/boards/speed", "admin")).text();
97 expect(board).toContain("Pin to home");
98 const pinned = await post("/home/panels", "admin", { slug: "speed", index: "0", action: "pin", back: "/boards/speed" });
99 expect(pinned.status).toBe(303);
100 expect(pinned.headers.get("location")).toStartWith("/boards/speed");
101 expect(await (await get("/boards/speed", "admin")).text()).toContain("Unpin from home");
102 const home = await (await get("/", "admin")).text();
103 expect(home).toContain("Runs a day");
104 expect(home).toContain('aria-label="Pinned panels"');
105 await post("/home/panels", "admin", { slug: "speed", index: "0", action: "unpin" });
106 expect(await (await get("/", "admin")).text()).not.toContain("Runs a day");
107 });
108
109 test("pinning is the owner's alone, same-origin only, and names a real panel", async () => {
110 expect((await post("/home/panels", "bob", { slug: "speed", index: "0", action: "pin" })).status).toBe(404);
111 expect((await post("/home/panels", "admin", { slug: "speed", index: "7", action: "pin" })).status).toBe(404);
112 expect((await post("/home/panels", "admin", { slug: "../x", index: "0", action: "pin" })).status).toBe(404);
113 const cross = await fetch(servers.url + "/home/panels", {
114 method: "POST",
115 headers: { authorization: `Bearer ${tok.admin}`, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" },
116 body: new URLSearchParams({ slug: "speed", index: "0", action: "pin" }),
117 });
118 expect(cross.status).toBe(403);
119 expect(pinsOf(app.db, admin.id)).toEqual([]);
120 const off = await post("/home/panels", "admin", { slug: "speed", index: "0", action: "pin", back: "//evil.example" });
121 expect(off.headers.get("location")).toStartWith("/");
122 expect(off.headers.get("location")).not.toStartWith("//");
123 unpinPanel(app.db, admin.id, { slug: "speed", index: 0 });
124 });
125
126 test("pins keep the owner's order and a pin that does not fit is refused", () => {
127 expect(pinPanel(app.db, admin.id, { slug: "a", index: 0 })).toBe(true);
128 expect(pinPanel(app.db, admin.id, { slug: "b", index: 1 })).toBe(true);
129 movePin(app.db, admin.id, { slug: "b", index: 1 }, -1);
130 expect(pinsOf(app.db, admin.id).map((p) => p.slug)).toEqual(["b", "a"]);
131 const fits = ["x", "y", "z", "w", "v"].map((c) => pinPanel(app.db, admin.id, { slug: c.repeat(40), index: 0 }));
132 expect(fits).toContain(false);
133 expect(fits[0]).toBe(true);
134 });
135 });
136
137 describe("the KPIs", () => {
138 test("landings count merged pulls by hour; the median check is of finished checks", () => {
139 const now = Date.parse("2026-10-19T12:30:00Z");
140 app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('rk', ?, 'k')", [admin.id]);
141 const run = app.db.prepare(
142 "INSERT INTO run (id, repo_id, kind, state, created_at, started_at, finished_at) VALUES (?1, 'rk', 'check', 'ok', ?2, ?2, ?3)",
143 );
144 run.run("c1", "2026-10-19T11:00:00.000Z", "2026-10-19T11:00:10.000Z");
145 run.run("c2", "2026-10-19T11:10:00.000Z", "2026-10-19T11:10:30.000Z");
146 run.run("c3", "2026-10-19T11:20:00.000Z", "2026-10-19T11:21:00.000Z");
147 expect(medianCheckMs(app.db, now)).toBe(30_000);
148 expect(landingsByHour(app.db, now)).toHaveLength(24);
149 const kpis = readKpis(app.db, dir, admin.id, "2026-10-19T12:00:00.000Z", now);
150 expect(kpis.find((k) => k.key === "check")?.value).toBe("30s");
151 expect(kpis.find((k) => k.key === "backup")?.value).toBe("none");
152 expect(kpis.find((k) => k.key === "live")?.note).toBe("live 30 min ago");
153 });
154 });
155
156 describe("a pin follows its panel", () => {
157 const panel = (title: string) => ({
158 title, chart: "bar", query: { source: "runs", aggregate: "count", groupBy: { bucket: "day" } }, w: 1, h: 1,
159 });
160 const onHome = async () => await (await get("/", "admin")).text();
161
162 test("removing or moving a panel before it does not repoint the pin; deleting the board drops it", async () => {
163 const slug = await makeBoard(app, admin as never, "Trio");
164 if (!slug.ok) throw new Error(String(slug.error));
165 for (const t of ["Alpha panel", "Bravo panel", "Charlie panel"])
166 expect((await changeBoard(app, admin as never, slug.value, { kind: "add", panel: panel(t) })).ok).toBe(true);
167 const pin = (index: number, action = "pin") => post("/home/panels", "admin", { slug: slug.value, index: String(index), action });
168 await pin(1);
169 let home = await onHome();
170 expect(home).toContain("Bravo panel");
171 // Remove panel 0: Bravo is now at 0 and the pin must have followed it.
172 await changeBoard(app, admin as never, slug.value, { kind: "remove", index: 0 });
173 expect(pinsOf(app.db, admin.id)).toEqual([{ slug: slug.value, index: 0 }]);
174 home = await onHome();
175 expect(home).toContain("Bravo panel");
176 expect(home).not.toContain("Alpha panel");
177 // Move Bravo down: the pin goes with it.
178 await changeBoard(app, admin as never, slug.value, { kind: "move", index: 0, by: 1 });
179 expect(pinsOf(app.db, admin.id)).toEqual([{ slug: slug.value, index: 1 }]);
180 expect(await onHome()).toContain("Bravo panel");
181 // Removing the pinned panel itself drops the pin.
182 await changeBoard(app, admin as never, slug.value, { kind: "remove", index: 1 });
183 expect(pinsOf(app.db, admin.id)).toEqual([]);
184 await pin(0);
185 expect(pinsOf(app.db, admin.id)).toHaveLength(1);
186 expect((await deleteBoard(app, admin as never, slug.value)).ok).toBe(true);
187 expect(pinsOf(app.db, admin.id)).toEqual([]);
188 });
189 });
190
191 describe("the home as data", () => {
192 const api = (path: string, who: string, init: RequestInit = {}) =>
193 fetch(servers.url + path, { ...init, headers: { authorization: `Bearer ${tok[who]}`, "content-type": "application/json" } });
194
195 test("GET /api/v1/home gives the KPIs and pinned panels; POST /api/v1/home/panels pins and unpins; others are refused", async () => {
196 expect((await api("/api/v1/home", "bob")).status).toBeGreaterThanOrEqual(403);
197 expect((await api("/api/v1/home/panels", "bob", { method: "POST", body: JSON.stringify({ slug: "speed", index: 0, action: "pin" }) })).status).toBeGreaterThanOrEqual(403);
198 const pinned = await api("/api/v1/home/panels", "admin", { method: "POST", body: JSON.stringify({ slug: "speed", index: 0, action: "pin" }) });
199 expect(pinned.status).toBe(200);
200 const view = (await (await api("/api/v1/home", "admin")).json()) as { kpis: { key: string }[]; panels: { title: string }[] };
201 expect(view.kpis).toHaveLength(6);
202 expect(view.panels.map((p) => p.title)).toEqual(["Runs a day"]);
203 const bad = await api("/api/v1/home/panels", "admin", { method: "POST", body: JSON.stringify({ slug: "speed", index: 9, action: "pin" }) });
204 expect(bad.status).toBe(404);
205 await api("/api/v1/home/panels", "admin", { method: "POST", body: JSON.stringify({ slug: "speed", index: 0, action: "unpin" }) });
206 expect(((await (await api("/api/v1/home", "admin")).json()) as { panels: unknown[] }).panels).toEqual([]);
207 });
208 });
test/mcp.test.ts +12
@@ -236,6 +236,8 @@ describe("the forge over MCP", () => {
236236 "quotas",
237237 "signup",
238238 "boards",
239 "home",
240 "home_pin",
239241 "board_write",
240242 "board_delete",
241243 "report",
@@ -825,6 +827,8 @@ describe("the forge over MCP", () => {
825827 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
826828 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
827829 for (const who of [bobRw, botToken]) {
830 expect((await tool(who, "home")).error).toContain("forbidden");
831 expect((await tool(who, "home_pin", { slug: "runs", index: 0, action: "pin" })).error).toContain("forbidden");
828832 expect((await tool(who, "boards")).error).toContain("forbidden");
829833 expect((await tool(who, "board_write", { slug: "runs", board })).error).toContain("forbidden");
830834 expect((await tool(who, "board_delete", { slug: "runs" })).error).toContain("forbidden");
@@ -838,6 +842,14 @@ describe("the forge over MCP", () => {
838842 expect(wrote.value).toMatchObject({ slug: "runs", title: "Runs" });
839843 expect((await tool(rw, "boards")).value.boards.map((b: any) => b.slug)).toEqual(["runs"]);
840844 expect((await tool(ro, "boards", { slug: "runs" })).value.panels[0].title).toBe("Failed");
845 // The owner's home as data: pin the panel, read it back with its value, unpin it.
846 expect((await tool(rw, "home_pin", { slug: "runs", index: 3, action: "pin" })).error).toContain("not_found");
847 expect((await tool(rw, "home_pin", { slug: "runs", index: 0, action: "pin" })).value).toEqual({ ok: true });
848 const home = (await tool(ro, "home")).value;
849 expect(home.kpis.map((k: any) => k.key)).toEqual(["landings", "live", "check", "builders", "spend", "backup"]);
850 expect(home.panels).toMatchObject([{ slug: "runs", index: 0, title: "Failed", chart: "number" }]);
851 expect((await tool(rw, "home_pin", { slug: "runs", index: 0, action: "unpin" })).value).toEqual({ ok: true });
852 expect((await tool(ro, "home")).value.panels).toEqual([]);
841853 expect((await tool(rw, "boards", { slug: "nope" })).error).toContain("not_found");
842854
843855 // A panel that cannot run, or a board that does not validate, is refused.
test/planner-declined.test.ts +1 −1
@@ -183,7 +183,7 @@ describe("the planner declined, waiting for a person", () => {
183183 expect(board).toContain(
184184 `action="/alice/garden/issues/${direction.number}/comments"`,
185185 );
186 const asks = await page(aliceCookie, "/");
186 const asks = await page(aliceCookie, "/asks");
187187 expect(asks).toContain("The planner declined the direction");
188188 expect(asks).toContain(
189189 `/alice/garden/issues/${direction.number}#comment-body`,
test/proposal-card.test.ts +3 −3
@@ -153,12 +153,12 @@ describe("a wave proposal is one inbox card", () => {
153153 expect(rows()).toHaveLength(0);
154154 });
155155
156 test("home shows the Redirect box on the card, and Later's way back", async () => {
156 test("the owner's asks show the Redirect box on the card, and Later's way back", async () => {
157157 const id = propose("Home wave");
158158 const get = async () =>
159 (await (await fetch(`${servers.url}/`, { headers: { cookie: `${aliceCookie}; forge_mode=studio` } })).text());
159 (await (await fetch(`${servers.url}/asks`, { headers: { cookie: `${aliceCookie}; forge_mode=studio` } })).text());
160160 expect(await get()).toContain(`/asks/proposal/${id}/redirect`);
161 await post(aliceCookie, `/asks/proposal/${id}/later`, [["back", "/"]]);
161 await post(aliceCookie, `/asks/proposal/${id}/later`, [["back", "/asks"]]);
162162 const page = await get();
163163 expect(page).not.toContain(`/asks/proposal/${id}/redirect`);
164164 expect(page).toContain("1 wave put aside");
test/review-wait.test.ts +1 −1
@@ -34,7 +34,7 @@ describe("a green agent pull and its reviewer", () => {
3434
3535 const home = async (): Promise<string> =>
3636 (
37 await (await fetch(`${servers.url}/`, { headers: { cookie } })).text()
37 await (await fetch(`${servers.url}/asks`, { headers: { cookie } })).text()
3838 ).replace(/\s+/g, " ");
3939 const wordCtx = (): WordCtx => ({ db: app.db }) as unknown as WordCtx;
4040
test/studio-door.test.ts +6 −2
@@ -613,7 +613,10 @@ describe("the studio home keeps itself current", () => {
613613 expect(res.headers.get("referrer-policy")).toBe("same-origin");
614614 const home = await res.text();
615615 expect(home).toMatch(/id="live-apps"\s*\n?\s*data-live="/);
616 expect(home).toMatch(/id="live-on-you"\s*\n?\s*data-live="/);
616 // The owner's home lists nothing that waits on them; /asks does.
617 expect(home).not.toContain('id="live-on-you"');
618 const asks = await (await fetch(`${base}/asks`, { headers: { cookie: `${cookie}; forge_mode=studio` } })).text();
619 expect(asks).toMatch(/id="live-on-you"\s*\n?\s*data-live="/);
617620 expect(home).toContain("new EventSource('/events')");
618621 expect(home).toContain("Write the README");
619622 });
@@ -628,7 +631,8 @@ describe("the studio home keeps itself current", () => {
628631 test("each region on the home has an address of its own, answering with that region alone and 304 when it has not changed", async () => {
629632 const page = await (await get()).text();
630633 expect(page).toContain('data-live-src="/live/apps"');
631 expect(page).toContain('data-live-src="/live/on-you"');
634 const asks = await (await fetch(`${base}/asks`, { headers: { cookie: `${cookie}; forge_mode=studio` } })).text();
635 expect(asks).toContain('data-live-src="/live/on-you"');
632636
633637 const headers = { cookie: `${cookie}; forge_mode=studio` };
634638 const apps = await fetch(`${base}/live/apps`, { headers });
test/tui-boards.test.ts +59 −3
@@ -10,6 +10,7 @@ import { join } from "node:path";
1010 import { writeBoard } from "../src/actions/boards.ts";
1111 import { createAgent } from "../src/actions/crew.ts";
1212 import { createApp, type App } from "../src/app.ts";
13 import { pinPanel, pinsOf, unpinPanel } from "../src/core/home_panels.ts";
1314 import { createUser, type User } from "../src/core/users.ts";
1415 import { createForgeApp, forgeCommands, Session } from "../src/tui/forge.ts";
1516 import { boardRows, boardsScreen } from "../src/tui/screens/boards.ts";
@@ -32,14 +33,15 @@ const identity = (user?: User) => ({
3233 user,
3334 });
3435
35 async function screenText(user?: User, keys = ""): Promise<string> {
36 async function screenText(user?: User, keys: string | string[] = ""): Promise<string> {
3637 const terminal = headlessTerminal(120, 30);
3738 const { app: tui, session } = createForgeApp(app, identity(user), { terminal, exitHooks: false });
3839 tui.start();
3940 tui.ctx.push(boardsScreen(session, tui.ctx));
4041 await settleApp(tui);
41 if (keys !== "") {
42 terminal.feed(keys);
42 // Each chunk settles before the next: opening a board is asynchronous.
43 for (const chunk of typeof keys === "string" ? (keys === "" ? [] : [keys]) : keys) {
44 terminal.feed(chunk);
4345 await settleApp(tui);
4446 }
4547 const text = tui.screen.toText();
@@ -106,4 +108,58 @@ describe("tui boards", () => {
106108 }
107109 expect(doors(carol)).toContain("boards");
108110 });
111
112 test("the owner pins, unpins and moves a panel from a board's view; nobody else can", async () => {
113 const wrote = await writeBoard(app, carol, "pair", {
114 title: "Pair",
115 range: "7d",
116 refresh: "off",
117 panels: [
118 { title: "First panel", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 },
119 { title: "Second panel", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 },
120 ],
121 });
122 expect(wrote.ok).toBe(true);
123 const rows = await boardRows(new Session(app, identity(carol)));
124 const at = rows.findIndex((r) => r.slug === "pair");
125 const open = "j".repeat(at) + "\r";
126 const run = (keys: string) => screenText(carol, [open, ...keys.split("")]);
127 // p pins the marked panel; n marks the next; p pins it too.
128 let text = await run("pnp");
129 expect(text).toContain("[on home]");
130 expect(pinsOf(app.db, carol.id)).toEqual([{ slug: "pair", index: 0 }, { slug: "pair", index: 1 }]);
131 // [ moves the marked (second) pin before the first.
132 await run("n[");
133 expect(pinsOf(app.db, carol.id).map((p) => p.index)).toEqual([1, 0]);
134 // p on a pinned panel unpins it.
135 await run("p");
136 expect(pinsOf(app.db, carol.id)).toEqual([{ slug: "pair", index: 1 }]);
137 await run("np");
138 expect(pinsOf(app.db, carol.id)).toEqual([]);
139 text = await run("");
140 expect(text).toContain("pin to home");
141 // Another admin who is an agent has no board, so no key to press.
142 expect(await boardRows(new Session(app, identity(bot)))).toEqual([]);
143 expect(pinsOf(app.db, bot.id)).toEqual([]);
144 });
145
146 test("the owner's terminal home carries the KPI row; another person's does not", async () => {
147 const home = async (user: User): Promise<string> => {
148 const terminal = headlessTerminal(160, 30);
149 const { app: tui } = createForgeApp(app, identity(user), { terminal, exitHooks: false });
150 tui.start();
151 await settleApp(tui);
152 const text = tui.screen.toText();
153 tui.stop?.();
154 return text;
155 };
156 const mine = await home(carol);
157 expect(mine).toContain("landings per hour");
158 expect(mine).toContain("off-box backup");
159 expect(await home(bob)).not.toContain("landings per hour");
160 // A pinned panel is a line of its title and current value.
161 pinPanel(app.db, carol.id, { slug: "pair", index: 1 });
162 expect(await home(carol)).toContain("Second panel: ");
163 unpinPanel(app.db, carol.id, { slug: "pair", index: 1 });
164 });
109165 });
test/web-apps.test.ts +1 −1
@@ -824,7 +824,7 @@ describe("apps, runs and the crew on the web", () => {
824824 form: { assignee: "alice" },
825825 });
826826 expect(assigned.status).toBe(303);
827 const dash = await bodyOf(alice, "/");
827 const dash = await bodyOf(alice, "/asks");
828828 expect(dash).toContain('<section id="needs-you"');
829829 expect(dash).toMatch(/<h2 id="asks-sentence">\d+ things? needs? you<\/h2>/);
830830 expect(dash).toContain("Say hello");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs