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

Capacity settings fit one view: a grouped table with each knob's live effect, details folded, one Save #14849

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/14841-capacity-settings-fit-one-view-a-grouped → main 5 commits fork

  • Merged. scout/14841-capacity-settings-fit-one-view-a-grouped was merged into main as b399094.

Review

Sign in to review this change.
15 files changed +499 −213
docs/design/areas/settings.md +3 −3
@@ -93,9 +93,9 @@ full width, when it has rows. Styled in `src/web/style/components.ts`.
9393 - `.segmented-on` — the state that is on, in `.segmented`.
9494 - `.setting-table` — a table of settings rows (Limits): name and reason, value and bounds, the form to change it; each row stacks on a phone.
9595
96 Settings › Capacity (`capacityPage()` in `src/web/pages/capacity.ts`, #9709) has no card: one line of what a change does,
97 the egress note when cells only report, then `.settings-block` sections — Capacity (the `.setting-list` of settings
98 rows), Changes, Errors and refused calls, Egress connections, Self-swap. No new class. Pinned by
96 Settings › Capacity (`capacityPage()` in `src/web/pages/capacity.ts`, #9709, #14841) has no card: one line of what a change does,
97 the egress note when cells only report, one line of load, then one `.setting-table` in four groups with one Save (each row
98 a `.hint.why` fold), then `.settings-block` sections — Changes, Errors and refused calls, Egress connections, Self-swap. No new class. Pinned by
9999 `test/capacity-rows.test.ts`.
100100
101101 ## Account (#9706)
docs/features/capacity.md +8 −2
@@ -10,12 +10,18 @@ A capacity count (`crew.concurrency`, `checks.concurrency`, `queue.depth` and th
1010 - **The terminal's Capacity screen** prints "below ceiling N" in the same row's meta line.
1111 - **The pace sentence** (Home, the terminal dashboard and Usage → Spend) says "Crew concurrency is set to X, below its ceiling of Y" while `crew.concurrency` is lowered, so the cap is not mistaken for pacing.
1212
13 **Reset:** the row's **Put back** button is the reset. It is one same-origin POST to `/settings/capacity` with `reset=1`, it takes effect on the next pick, and it is logged under Changes like any other capacity change.
13 **Reset:** the row's **Put back** button (inside its ⓘ) is the reset. It is one same-origin POST to `/settings/capacity` with `reset=<key>` (the older `key` + `reset=1` still lands), it takes effect on the next pick, and it is logged under Changes like any other capacity change.
1414
1515 ## Why each setting is there
1616
1717 Every capacity setting carries a required one-sentence `reason` (`CAPACITY` in
1818 `src/core/capacity.ts`; `test/settings-reasons.test.ts` fails without one, and
1919 holds the limits on `/admin/limits` to the same). `/settings/capacity` shows it
20 first on each row, and the terminal's Capacity screen shows it as a muted line
20 behind each row's ⓘ, and the terminal's Capacity screen shows it as a muted line
2121 under the row.
22
23 ## One grouped table (#14841)
24
25 `/settings/capacity` is one table in four groups (Crew, Checks, Hosted forges, Sign-in and safety): each row is the name, the value as an input, and its live effect in a few words ("6 running · 4 queued", "4 candidates"; `effectOf` in `src/actions/capacity_effects.ts`, one source: the MCP `knobs` tool's Speed, Pace floor and Queue depth rows call it too). Why, how it is computed, the key, the environment variable, the boot default and Put back fold behind one ⓘ. A changed setting shows "changed 22:33 by trevato" on its row, and the history is the Changes list below. Pace floor and queue depth are text that follows Crew runs at once, never inputs. One line on top is the load the knobs act on: machine load, checks, crew runs, merges in the last hour (`loadLine`).
26
27 **One Save** posts every input as `v.<key>`; the server writes only the rows that differ from what is in force and answers with each change and its effect. The terminal's Capacity screen prints the same effect and load line. Pinned by `test/capacity-first-view.test.ts` (under 800 words and 25 KB with every row folded).
src/actions/capacity.ts +33 −16
@@ -209,6 +209,31 @@ export function edgeOffDryRun(
209209 /** What a move to report, said without a reason, is told. */
210210 export const REASON_WORDS = "Say why: setting cells.egress to report is kept with who made it and the reason.";
211211
212 /** Every refusal `changeCapacity` can give, without writing: a Save checks all its rows first. */
213 export function checkCapacity(
214 app: App,
215 actor: User | undefined,
216 key: string,
217 value: string | null,
218 reason = "",
219 ): Result<
220 { who: User; key: CapacityKey; next: string | null; why: string },
221 "not_found" | "no_such_setting" | "invalid_value" | "no_credential" | "derived" | "reason_required"
222 > {
223 const who = admin(actor);
224 if (!who.ok) return who;
225 if (!isCapacityKey(key)) return err("no_such_setting");
226 if (followsSpeed(key)) return err("derived");
227 const next = value === null ? null : value.trim();
228 if (next !== null && next !== "" && !validCapacity(key, next))
229 return err("invalid_value");
230 if (key === "signin.edge" && next === "off" && !signsInWithoutEdge(app.db, who.value.id))
231 return err("no_credential");
232 const why = reason.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, REASON_MAX);
233 if (needsReason(key) && next === "report" && why === "") return err("reason_required");
234 return ok({ who: who.value, key, next, why });
235 }
236
212237 /**
213238 * Set `key` to `value`; `null` or `""` goes back to the boot default.
214239 * `reason` is kept beside who; a move of `cells.egress` to report is refused
@@ -224,28 +249,20 @@ export function changeCapacity(
224249 { key: CapacityKey; from: string; to: string },
225250 "not_found" | "no_such_setting" | "invalid_value" | "no_credential" | "derived" | "reason_required"
226251 > {
227 const who = admin(actor);
228 if (!who.ok) return who;
229 if (!isCapacityKey(key)) return err("no_such_setting");
230 if (followsSpeed(key)) return err("derived");
231 const next = value === null ? null : value.trim();
232 if (next !== null && next !== "" && !validCapacity(key, next))
233 return err("invalid_value");
234 if (key === "signin.edge" && next === "off" && !signsInWithoutEdge(app.db, who.value.id))
235 return err("no_credential");
236 const why = reason.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, REASON_MAX);
237 if (needsReason(key) && next === "report" && why === "") return err("reason_required");
252 const checked = checkCapacity(app, actor, key, value, reason);
253 if (!checked.ok) return checked;
254 const { who, key: slot, next, why } = checked.value;
238255 const changed = setCapacity(
239256 app.db,
240 key,
257 slot,
241258 next === "" ? null : next,
242 who.value.id,
259 who.id,
243260 why,
244261 );
245262 app.bus.append({
246263 kind: "capacity.changed",
247 actorId: who.value.id,
248 payload: { key, from: changed.from, to: changed.to, ...(why === "" ? {} : { reason: why }) },
264 actorId: who.id,
265 payload: { key: slot, from: changed.from, to: changed.to, ...(why === "" ? {} : { reason: why }) },
249266 });
250 return ok({ key, ...changed });
267 return ok({ key: slot, ...changed });
251268 }
src/actions/capacity_effects.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * What each capacity setting is doing now, in a few words (#14841): the live
3 * effect the capacity page prints beside a value, and the one line of load
4 * the knobs act on. Plain data out, read-only; the same words the MCP `knobs`
5 * tool uses for the crew rows (`crew/knobs.ts`).
6 */
7
8 import { availableParallelism, loadavg } from "node:os";
9 import type { App } from "../app.ts";
10 import { cpuLimit, queueDepth, paceFloor, type CapacityKey } from "../core/capacity.ts";
11 import { listActive } from "../core/runs.ts";
12 import { weekShare } from "../crew/week_read.ts";
13 import { awakeCount } from "../spawn/host.ts";
14
15 const HOUR_MS = 3_600_000;
16
17 function counts(app: App, kind: "agent" | "check"): { running: number; queued: number } {
18 const active = listActive(app.db, kind);
19 const running = active.filter((r) => r.state === "running").length;
20 return { running, queued: active.length - running };
21 }
22
23 /** "6 running · 4 queued". */
24 function busy(c: { running: number; queued: number }): string {
25 return `${c.running} running · ${c.queued} queued`;
26 }
27
28 /** The load the knobs act on, as one line: machine load, checks, crew runs, merges. */
29 export function loadLine(app: App, now = Date.now()): string {
30 const cores = cpuLimit() || availableParallelism();
31 const load = Math.round(loadavg()[0]! * 10) / 10;
32 // Merges in the last hour: how fast the queue is landing work.
33 const since = new Date(now - HOUR_MS).toISOString();
34 const n = app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM pull WHERE merged_at > ?1").get(since)?.n ?? 0;
35 return `Load ${load} on ${cores} cores · checks ${busy(counts(app, "check"))} · crew ${busy(counts(app, "agent"))} · ${n} merge${n === 1 ? "" : "s"} in the last hour`;
36 }
37
38 const WORDS: Partial<Record<CapacityKey, Record<string, string>>> = {
39 "cells.egress": { enforce: "undeclared hosts refused", report: "undeclared hosts let through, listed" },
40 "children.ownFilesystem": { on: "a child on a shared disk is refused", off: "children may share the disk" },
41 guard_new_accounts: { on: "accounts under 7 days cannot create", off: "no wait for new accounts" },
42 "signin.edge": { on: "edge sign-in offered", off: "passkey or password only" },
43 "children.modelEgress": { off: "no model provider", openrouter: "openrouter.ai", anthropic: "api.anthropic.com", both: "openrouter.ai and api.anthropic.com" },
44 "children.registryEgress": { off: "no package registry", npm: "registry.npmjs.org", build: "npm and build registries" },
45 "children.paymentEgress": { off: "no payment provider", stripe: "api.stripe.com" },
46 "children.originEgress": { off: "no public git hosts", git: "public git hosts" },
47 };
48
49 /** The live effect of `key` at `value` (the effective one: a derived row reads what it follows). */
50 export function effectOf(app: App, key: CapacityKey, value: string): string {
51 switch (key) {
52 case "crew.concurrency":
53 return busy(counts(app, "agent"));
54 case "pace.floor":
55 return `${paceFloor(app.db)} slots`;
56 case "queue.depth":
57 return `${queueDepth(app.db)} candidates`;
58 case "week.use": {
59 const week = weekShare(app);
60 return week === null ? "week not measured yet" : `${Math.round(week.usedPct)}% of the week used`;
61 }
62 case "checks.concurrency":
63 return busy(counts(app, "check"));
64 case "checks.shards":
65 return `${value} process${value === "1" ? "" : "es"} per check`;
66 case "queue.batch":
67 return `up to ${value} pulls per candidate`;
68 case "cells.servingCores":
69 return `${value} of ${cpuLimit()} cores kept`;
70 case "children.max":
71 return `${awakeCount(app)} awake`;
72 case "children.awake":
73 return `${awakeCount(app)} awake now`;
74 default:
75 return WORDS[key]?.[value] ?? value;
76 }
77 }
src/crew/knobs.ts +5 −5
@@ -9,6 +9,7 @@
99 * so it moves with that dial and not with Speed.
1010 */
1111
12 import { effectOf } from "../actions/capacity_effects.ts";
1213 import type { App } from "../app.ts";
1314 import { capacityValue, paceFloor, queueDepth, weekUse } from "../core/capacity.ts";
1415 import { labelsForIssues } from "../core/issues.ts";
@@ -67,10 +68,9 @@ export function autonomyWord(repo: Repo): AutonomyWord {
6768 return isGo(repo) ? "go" : "ask";
6869 }
6970
71 /** Speed's effect: the capacity page's words for crew.concurrency, one source. */
7072 function runsLine(app: App): string {
71 const active = listActive(app.db, "agent");
72 const running = active.filter((r) => r.state === "running").length;
73 return `${running} running · ${active.length - running} queued`;
73 return effectOf(app, "crew.concurrency", "");
7474 }
7575
7676 function polishWaiting(app: App, repos: readonly Repo[]): number {
@@ -119,7 +119,7 @@ export function readKnobs(app: App, now: Date = new Date()): KnobRow[] {
119119 value: String(paceFloor(app.db)),
120120 control: "derived",
121121 follows: "Speed",
122 effect: `${paceFloor(app.db)} slots`,
122 effect: effectOf(app, "pace.floor", ""),
123123 },
124124 {
125125 id: "depth",
@@ -128,7 +128,7 @@ export function readKnobs(app: App, now: Date = new Date()): KnobRow[] {
128128 value: String(queueDepth(app.db)),
129129 control: "derived",
130130 follows: "Speed",
131 effect: `${queueDepth(app.db)} candidates`,
131 effect: effectOf(app, "queue.depth", ""),
132132 },
133133 {
134134 id: "budget",
src/tui/screens/capacity.ts +3 −2
@@ -8,6 +8,7 @@
88
99 import type { SelfSwap } from "../../release/swap.ts";
1010 import { DERIVED_WORDS, REASON_WORDS, changeCapacity, listCapacity, type CapacityRow } from "../../actions/capacity.ts";
11 import { effectOf, loadLine } from "../../actions/capacity_effects.ts";
1112 import { SETTING_WORDS } from "../../actions/setting_words.ts";
1213 import { CAPACITY, belowCeiling, needsReason, validCapacity, type CapacityKey } from "../../core/capacity.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
@@ -66,14 +67,14 @@ export function capacityScreen(f: Session, ctx: Ctx): Screen {
6667 const low = belowCeiling(f.app.db, r.key);
6768 return {
6869 title: `${r.label} (${r.key})`,
69 meta: `${shown(r.value)} · ${r.source === "derived" ? "derived from Speed" : r.source} · takes ${boundsOf(r.key)}${r.source === "setting" ? ` · default ${shown(r.default)}` : ""}${low === null ? "" : ` · below ceiling ${low.ceiling}`}`,
70 meta: `${shown(r.value)} · ${effectOf(f.app, r.key, r.value)} · ${r.source === "derived" ? "derived from Speed" : r.source} · takes ${boundsOf(r.key)}${r.source === "setting" ? ` · default ${shown(r.default)}` : ""}${low === null ? "" : ` · below ceiling ${low.ceiling}`}`,
7071 note: r.reason,
7172 ...(low === null ? {} : { tone: "attn" as const }),
7273 };
7374 });
7475 // After the guards, so the cursor (bounded by the settings) never lands on it.
7576 const egress = egressReportedLine(f.app.db);
76 return [...guards, selfSwapRow(listed.value.selfSwap), ...(egress === null ? [] : [{ title: egress, tone: "attn" as const }])];
77 return [...guards, { title: loadLine(f.app) }, selfSwapRow(listed.value.selfSwap), ...(egress === null ? [] : [{ title: egress, tone: "attn" as const }])];
7778 };
7879
7980 const plan = (row: CapacityRow, typed: string, reason = ""): void => {
src/web/pages/capacity.ts +127 −148
@@ -6,8 +6,9 @@
66 * and each one is listed below the settings: who, when, from what to what.
77 */
88
9 import { DERIVED_WORDS, REASON_WORDS, changeCapacity, edgeOffDryRun, listCapacity, type CapacityRow } from "../../actions/capacity.ts";
10 import { CAPACITY, REASON_MAX, belowCeiling, needsReason, type CapacityKey } from "../../core/capacity.ts";
9 import { DERIVED_WORDS, REASON_WORDS, changeCapacity, checkCapacity, edgeOffDryRun, listCapacity, type CapacityRow } from "../../actions/capacity.ts";
10 import { CAPACITY, REASON_MAX, belowCeiling, bootDefault, needsReason, type CapacityKey } from "../../core/capacity.ts";
11 import { effectOf, loadLine } from "../../actions/capacity_effects.ts";
1112 import { EGRESS_REPORTED } from "../../system/egress_line.ts";
1213 import { bytes } from "../../system/format.ts";
1314 import { egressRowsFor } from "../../spawn/process_counters.ts";
@@ -18,7 +19,6 @@ import { field, readForm } from "../form.ts";
1819 import { html, when, type Html } from "../html.ts";
1920 import { flashTo } from "../layout.ts";
2021 import { badge, btn, row, time } from "../ui.ts";
21 import { why } from "../setting_line.ts";
2222 import { usageShell } from "./usage-tabs.ts";
2323 import { REACH_SETTINGS } from "../../actions/child_reach.ts";
2424
@@ -28,51 +28,43 @@ function requireAdmin(ctx: Ctx): Response | undefined {
2828 return undefined;
2929 }
3030
31 const DAY_MS = 86_400_000;
32
33 /** "today", "1 day ago", "9 days ago". */
34 export function daysAgo(at: string, now: number): string {
35 const days = Math.max(0, Math.floor((now - Date.parse(at)) / DAY_MS));
36 return days === 0 ? "today" : `${days} day${days === 1 ? "" : "s"} ago`;
37 }
38
39 /** One muted line beside a setting away from its default; Put back is in the row's trail form. */
40 function awayLine(s: CapacityRow, now: number) {
41 if (s.changed === undefined) return null;
42 return html`<span class="muted small">changed from
43 <span class="mono">${s.default === "" ? "auto" : s.default}</span>
44 ${daysAgo(s.changed.at, now)} by ${s.changed.by}</span>`;
45 }
31 /** The groups of the table, in order: each a heading and the keys it holds. */
32 const GROUPS: readonly { readonly title: string; readonly keys: readonly CapacityKey[] }[] = [
33 { title: "Crew", keys: ["crew.concurrency", "pace.floor", "week.use"] },
34 { title: "Checks", keys: ["checks.concurrency", "checks.shards", "queue.batch", "queue.depth", "cells.servingCores"] },
35 {
36 title: "Hosted forges",
37 keys: ["children.max", "children.awake", "children.ownFilesystem", "children.modelEgress", "children.registryEgress", "children.paymentEgress", "children.originEgress"],
38 },
39 { title: "Sign-in and safety", keys: ["cells.egress", "guard_new_accounts", "signin.edge"] },
40 ];
4641
4742 function input(key: CapacityKey, value: string) {
4843 const kind = CAPACITY[key].kind;
44 const label = CAPACITY[key].label;
4945 if (kind.type === "choice")
50 return html`<select
51 class="input"
52 name="value"
53 aria-label="${CAPACITY[key].label}"
54 >
55 ${kind.values.map(
56 (v) =>
57 html`<option value="${v}" ${v === value ? "selected" : ""}>
58 ${v}
59 </option>`,
60 )}
61 </select>`;
62 return html`<input
63 class="input mono"
64 type="number"
65 name="value"
66 min="${String(kind.min)}"
67 max="${String(kind.max)}"
68 value="${value}"
69 aria-label="${CAPACITY[key].label}"
70 />`;
46 return html`<select class="input" name="v.${key}" aria-label="${label}">${kind.values.map((v) => html`<option value="${v}" ${v === value ? "selected" : ""}>${v}</option>`)}</select>`;
47 return html`<input class="input mono" type="number" name="v.${key}" min="${String(kind.min)}" max="${String(kind.max)}" value="${value}" placeholder="auto" aria-label="${label}" />`;
7148 }
7249
73 /** A titled part of the page: a small heading over its rows, never a card box (docs/DESIGN.md §7). */
74 function block(title: string, content: Html) {
75 return html`<section class="settings-block"><h2>${title}</h2>${content}</section>`;
50 /**
51 * Everything that is not the live effect, one ⓘ away: why, how, the key,
52 * the variable, the default, put back.
53 */
54 function fold(s: CapacityRow, follows: Html | null) {
55 const dry = s.key === "signin.edge" ? btn("Dry run", { size: "sm", name: "dry", value: "1", form: "dry-run", label: "List who switching the edge off would lock out" }) : null;
56 const last = s.changed === undefined ? null : html` · changed ${time(s.changed.at)} by ${s.changed.by}`;
57 const back = s.source === "setting" ? btn("Put back", { size: "sm", name: "reset", value: s.key, form: `put-${s.key}`, label: `Put ${s.label} back to the default` }) : null;
58 const boot = s.source === "derived" ? "derived, never set here" : html`boot default <span class="mono">${s.default === "" ? "auto" : s.default}</span>${s.env === "" ? "" : html` (<span class="mono">${s.env}</span>)`}`;
59 return html`<details class="hint why" id="why-cap-${s.key}"><summary aria-label="About ${s.label}">ⓘ</summary><p>${s.reason}</p><p>${s.help}</p><p class="muted small"><span class="mono">${s.key}</span> · ${boot}${follows}${last}</p>${dry}${back}</details>`;
60 }
61
62 /** A titled part of the page: a small heading over its rows, never a card box (DESIGN.md §7). */
63 function block(title: string, content: Html, id?: string) {
64 const inner = html`<h2>${title}</h2>${content}`;
65 return id === undefined
66 ? html`<section class="settings-block">${inner}</section>`
67 : html`<section class="settings-block" id="${id}">${inner}</section>`;
7668 }
7769
7870 // GET /settings/capacity
@@ -91,79 +83,52 @@ export function capacityPage(ctx: Ctx): Response {
9183 const refused = timePhase(ctx.request, "refused", () =>
9284 ctx.app.signals.refused.recent(),
9385 );
94 const now = Date.now();
9586 const rendering = performance.now();
96 const rows = settings.map((s) => {
97 // It lives where a person looks for it now; this row says where, and holds no second control.
98 if (s.key === "children.originEgress")
99 return row({
100 title: html`<span id="children-origin-egress">${s.label}</span> <span class="muted small mono">${s.key}</span> ${why(`cap-${s.key}`, s.reason)}`,
101 meta: html`Now <span class="mono">${s.value === "git" ? "on" : "off"}</span>. This moved to
102 <a href="${REACH_SETTINGS}">Settings, Hosted forges</a>, with the other names a hosted forge may reach and what each one asked for.`,
103 trail: btn("Open it there", { href: REACH_SETTINGS, size: "sm" }),
104 });
87 const byKey = new Map(settings.map((s) => [s.key, s]));
88 const effects = timePhase(ctx.request, "effects", () =>
89 new Map(settings.map((s) => [s.key, effectOf(ctx.app, s.key, s.value)])),
90 );
91 const tableRow = (s: CapacityRow) => {
10592 const low = belowCeiling(ctx.app.db, s.key);
106 return row({
107 title: html`${s.label} <span class="muted small mono">${s.key}</span> ${why(`cap-${s.key}`, s.reason)}${when(
108 low !== null,
109 () => html` ${badge(`below ceiling ${low?.ceiling}`, { tone: "attn" })}`,
110 )}`,
111 meta: html`${s.help} Now <span class="mono">${s.value === "" ? "auto" : s.value}</span>. ${s.source === "setting"
112 ? html`Set here; the boot default is
113 <span class="mono">${s.default === "" ? "auto" : s.default}</span>${s.env === ""
114 ? "."
115 : html` (<span class="mono">${s.env}</span>).`}`
116 : s.source === "derived"
117 ? html`Derived from Speed (<span class="mono">crew.concurrency</span>); read-only here: change Speed and it moves.`
118 : s.env === ""
119 ? html`The default.`
120 : html`The boot default, from <span class="mono">${s.env}</span>.`}
121 ${awayLine(s, now)}`,
122 trail: s.source === "derived"
93 const follows = s.source === "derived" ? html` · follows ${byKey.get("crew.concurrency")?.label}` : null;
94 const name = html`<span ${s.key === "children.originEgress" ? html`id="children-origin-egress"` : ""}>${s.label}</span> ${fold(s, follows)}${when(
95 low !== null,
96 () => html` ${badge(`below ceiling ${low?.ceiling}`, { tone: "attn" })}`,
97 )}`;
98 if (s.key === "children.originEgress")
99 return html`<tr data-key="${s.key}"><td>${name}</td>
100 <td><span class="mono">${s.value === "git" ? "on" : "off"}</span></td>
101 <td><a href="${REACH_SETTINGS}">Set in Hosted forges</a></td></tr>`;
102 return html`<tr data-key="${s.key}"><td>${name}</td>
103 <td>${s.source === "derived"
123104 ? html`<span class="mono" data-derived="${s.key}">${s.value}</span>`
124 : html`<form
125 class="row-fields"
126 method="post"
127 action="/settings/capacity"
128 >
129 <input type="hidden" name="key" value="${s.key}" />
130 ${input(s.key, s.value)}
131 ${when(
132 // Inside the row's own form, posted with Save: a move to report says why (#10778).
133 needsReason(s.key),
134 () => html`<input
135 class="input"
136 id="cap-${s.key}-reason"
137 type="text"
138 name="reason"
139 maxlength="${String(REASON_MAX)}"
140 autocomplete="off"
141 placeholder="Why (needed to set report)"
142 aria-label="Why (needed to set report)"
143 />`,
144 )}
145 ${btn("Save", {
146 size: "sm",
147 variant: "primary",
148 label: `Save ${s.label}`,
149 })}
150 ${when(
151 s.key === "signin.edge",
152 () => html`${btn("Dry run", { size: "sm", name: "dry", value: "1", label: "List who switching the edge off would lock out" })}`,
153 )}
154 ${when(
155 s.source === "setting",
156 () =>
157 html`${btn(s.changed === undefined ? "Default" : "Put back", {
158 size: "sm",
159 name: "reset",
160 value: "1",
161 label: s.changed === undefined ? `Back to the default for ${s.label}` : `Put ${s.label} back to the default`,
162 })}`,
163 )}
164 </form>`,
165 });
166 });
105 : html`${input(s.key, s.value)}${when(
106 needsReason(s.key),
107 () => html`<input
108 class="input"
109 id="cap-${s.key}-reason"
110 type="text"
111 name="reason"
112 maxlength="${String(REASON_MAX)}"
113 autocomplete="off"
114 placeholder="Why (needed to set report)"
115 aria-label="Why (needed to set report)"
116 />`,
117 )}`}</td>
118 <td class="small">${effects.get(s.key)}</td></tr>`;
119 };
120 const table = html`<form method="post" action="/settings/capacity">
121 <table class="table setting-table" data-dense aria-label="Capacity settings">
122 <thead><tr><th>Setting</th><th>Value</th><th>Now</th></tr></thead>
123 ${GROUPS.map(
124 (g) => html`<tbody><tr><th colspan="3" scope="colgroup">${g.title}</th></tr>
125 ${g.keys.flatMap((k) => byKey.get(k) ?? []).map(tableRow)}</tbody>`,
126 )}
127 </table>
128 <p class="mt">${btn("Save", { variant: "primary", label: "Save the changed settings" })}</p>
129 </form>
130 ${settings.filter((s) => s.source === "setting").map((s) => html`<form id="put-${s.key}" method="post" action="/settings/capacity"></form>`)}
131 <form id="dry-run" method="post" action="/settings/capacity"><input type="hidden" name="key" value="signin.edge" /></form>`;
167132 const history = changes.map((c) =>
168133 row({
169134 title: html`<span class="mono">${c.key}</span>
@@ -240,22 +205,14 @@ export function capacityPage(ctx: Ctx): Response {
240205 </ul>`,
241206 );
242207 // The settings first: they are what this page is for; what happened follows.
243 const body = html`<p class="muted small mb">
244 How much the forge does at once. A change takes effect on the next crew
245 run, check or app start — running work is left to finish — and never
246 needs a restart.
247 </p>
208 const body = html`<p class="muted small mb">A change takes effect on the next run, check or app start; nothing restarts.</p>
248209 ${when(
249210 reported,
250211 () => html`<p class="muted small mb" id="egress-reported">${EGRESS_REPORTED}</p>`,
251212 )}
252 ${block("Capacity", html`<ul class="list setting-list">${rows}</ul>`)}
253 ${block(
254 "Changes",
255 history.length === 0
256 ? html`<p class="muted small">No change yet.</p>`
257 : html`<ul class="list">${history}</ul>`,
258 )}
213 <p class="small" id="load">${loadLine(ctx.app)}</p>
214 ${table}
215 ${block("Changes", history.length === 0 ? html`<p class="muted small">No change yet.</p>` : html`<ul class="list">${history}</ul>`, "changes")}
259216 ${happened}${connections}${swap}`;
260217 const response = usageShell(ctx, "capacity", body);
261218 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -290,28 +247,50 @@ export async function capacitySet(ctx: Ctx): Promise<Response> {
290247 }${d.youLockedOut ? " You would be too, so the switch is refused until you add a passkey." : ""}`,
291248 });
292249 }
293 const reset = field(form, "reset") === "1";
294 const changed = changeCapacity(
295 ctx.app,
296 ctx.auth.user,
297 key,
298 reset ? null : field(form, "value"),
299 field(form, "reason"),
300 );
301 if (!changed.ok && changed.error === "not_found") return notFoundPage(ctx);
302 return flashTo(
303 ctx,
304 "/settings/capacity",
305 changed.ok
306 ? {
307 message:
308 changed.value.from === changed.value.to
309 ? `${key} is already ${changed.value.to || "auto"}.`
310 : `${key}: ${changed.value.from || "auto"} → ${changed.value.to || "auto"}, from the next pick on.`,
311 }
312 : {
313 tone: "danger",
314 message: ERRORS[changed.error] ?? "That could not be set.",
315 },
316 );
250 // One Save: every `v.<key>` field that differs from what is in force is a change; the rest are
251 // left. A Put back button names its key; the older one-key form (`key`, `value`, `reset=1`) still
252 // lands.
253 const resetKey = field(form, "reset");
254 const reason = field(form, "reason");
255 const jobs: { key: string; value: string | null }[] = [];
256 if (resetKey === "1") jobs.push({ key, value: null });
257 else if (resetKey !== "") jobs.push({ key: resetKey, value: null });
258 else if (key !== "") jobs.push({ key, value: field(form, "value") });
259 else {
260 const listed = listCapacity(ctx.app, ctx.auth.user);
261 if (!listed.ok) return notFoundPage(ctx);
262 for (const s of listed.value.settings) {
263 if (!form.has(`v.${s.key}`) || s.source === "derived") continue;
264 const sent = field(form, `v.${s.key}`).trim();
265 if (sent !== s.value) jobs.push({ key: s.key, value: sent });
266 }
267 if (jobs.length === 0) return flashTo(ctx, "/settings/capacity", { message: "Nothing changed." });
268 }
269 // All or nothing: every row is checked before any is written.
270 for (const job of jobs) {
271 const checked = checkCapacity(ctx.app, ctx.auth.user, job.key, job.value, reason);
272 if (!checked.ok && checked.error === "not_found") return notFoundPage(ctx);
273 if (!checked.ok)
274 return flashTo(ctx, "/settings/capacity", {
275 tone: "danger",
276 message: `Nothing saved. ${job.key}: ${ERRORS[checked.error] ?? "That could not be set."}`,
277 });
278 }
279 const said: string[] = [];
280 for (const job of jobs) {
281 const changed = changeCapacity(ctx.app, ctx.auth.user, job.key, job.value, reason);
282 if (!changed.ok && changed.error === "not_found") return notFoundPage(ctx);
283 if (!changed.ok)
284 return flashTo(ctx, "/settings/capacity", {
285 tone: "danger",
286 message: `${said.length === 0 ? "" : `Saved ${said.join("; ")}. `}${job.key}: ${ERRORS[changed.error] ?? "That could not be set."}`,
287 });
288 const { from, to } = changed.value;
289 said.push(
290 from === to
291 ? `${job.key} is already ${to || "auto"}`
292 : `${job.key}: ${from || "auto"} → ${to || "auto"}, ${effectOf(ctx.app, changed.value.key, to === "" ? bootDefault(ctx.app.db, changed.value.key) : to)}, from the next pick on`,
293 );
294 }
295 return flashTo(ctx, "/settings/capacity", { message: `${said.join("; ")}.` });
317296 }
test/capacity-first-view.test.ts added +203
@@ -0,0 +1,203 @@
1 /**
2 * Settings › Capacity's first view (#14841): one grouped table with each setting's live effect, one
3 * Save, the load on top.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { capacityChanges, capacityValue } from "../src/core/capacity.ts";
12 import { seedAdmin } from "./helpers/admin.ts";
13
14 let dataDir = "";
15 let app: App, servers: Servers, bearer = "";
16
17 beforeAll(async () => {
18 dataDir = await mkdtemp(join(tmpdir(), "forge-capfirst-"));
19 app = createApp({ dataDir, port: 0 });
20 servers = await serve(app);
21 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
22 if (!admin.ok) throw new Error(admin.error);
23 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
24 method: "POST",
25 headers: { "content-type": "application/json" },
26 body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }),
27 });
28 bearer = ((await minted.json()) as { token: string }).token;
29 });
30
31 afterAll(async () => {
32 servers.stop();
33 app.close();
34 await rm(dataDir, { recursive: true, force: true });
35 });
36
37 const get = async (): Promise<string> =>
38 (await fetch(`${servers.url}/settings/capacity`, { headers: { authorization: `Bearer ${bearer}` } })).text();
39
40 const post = (body: Record<string, string>) =>
41 fetch(`${servers.url}/settings/capacity`, {
42 method: "POST",
43 redirect: "manual",
44 headers: { authorization: `Bearer ${bearer}`, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
45 body: new URLSearchParams(body),
46 });
47
48 /**
49 * The words a person reads with every fold closed: markup, scripts, styles and folded details taken
50 * out.
51 */
52 function words(page: string): number {
53 const main = page.slice(page.indexOf('class="settings-main"'), page.indexOf("</main>"));
54 const text = main
55 .replace(/<(script|style)\b[\s\S]*?<\/\1>/g, " ")
56 .replace(/<details\b[\s\S]*?<\/details>/g, " ")
57 .replace(/<[^>]+>/g, " ");
58 return text.split(/\s+/).filter((w) => w !== "").length;
59 }
60
61 test("the first view: under 800 words and 25 KB with every row folded, every setting beside its live effect", async () => {
62 const page = await get();
63 // The page's own part (what the shell around it is not): under 25 KB raw with every fold closed.
64 const main = page.slice(page.indexOf('class="settings-main"'), page.indexOf("</main>"));
65 expect(new TextEncoder().encode(main).length).toBeLessThan(25_000);
66 expect(words(page)).toBeLessThan(800);
67 const rows = [...page.matchAll(/<tr data-key="([^"]+)">/g)].map((m) => m[1]);
68 expect(rows.length).toBe(18);
69 // The rest is behind one ⓘ per row, closed.
70 expect(page.match(/<details class="hint why"/g)).toHaveLength(18);
71 expect(page).not.toMatch(/<details[^>]*\sopen/);
72 expect(page).toContain("running");
73 expect(page).toContain("queued");
74 });
75
76 test("the load the knobs act on is one line on top: load, checks, crew runs, merges", async () => {
77 const page = await get();
78 const line = /<p class="small" id="load">([^<]+)<\/p>/.exec(page)?.[1] ?? "";
79 expect(line).toMatch(/^Load [\d.]+ on \d+ cores · checks \d+ running · \d+ queued · crew \d+ running · \d+ queued · \d+ merges? in the last hour$/);
80 expect(page.indexOf('id="load"')).toBeLessThan(page.indexOf("<table"));
81 });
82
83 test("derived values read as text that follows Crew runs at once, never as inputs", async () => {
84 const page = await get();
85 for (const key of ["pace.floor", "queue.depth"]) {
86 const row = page.slice(page.indexOf(`<tr data-key="${key}">`), page.indexOf("</tr>", page.indexOf(`<tr data-key="${key}">`)));
87 expect(row).toContain(`data-derived="${key}"`);
88 expect(row).toContain("follows Crew runs at once");
89 expect(row).not.toContain("<input");
90 expect(row).not.toContain("<select");
91 }
92 });
93
94 test("one Save sends the whole table and only the rows that changed are written; the answer names each with its effect", async () => {
95 const before = capacityChanges(app.db).length;
96 const page = await get();
97 // The whole table as the browser sends it: every input at its shown value.
98 const sent: Record<string, string> = {};
99 for (const m of page.matchAll(/<input\b[^>]*>/g)) {
100 const attr = (n: string) => new RegExp(`\\s${n}="([^"]*)"`).exec(m[0])?.[1];
101 const name = attr("name");
102 if (attr("type") === "number" && name?.startsWith("v.")) sent[name] = attr("value") ?? "";
103 }
104 for (const m of page.matchAll(/<select[^>]*name="v\.([^"]+)"[\s\S]*?<\/select>/g)) {
105 const chosen = /<option value="([^"]+)"\s+selected/.exec(m[0])?.[1];
106 if (chosen !== undefined) sent[`v.${m[1]}`] = chosen;
107 }
108 expect(Object.keys(sent).length).toBeGreaterThan(10);
109 const none = await post(sent);
110 expect(none.status).toBe(303);
111 expect(capacityChanges(app.db).length).toBe(before);
112 const next = capacityValue(app.db, "crew.concurrency") === "5" ? "6" : "5";
113 const res = await post({ ...sent, "v.crew.concurrency": next, "v.queue.batch": "3" });
114 expect(res.status).toBe(303);
115 expect(capacityValue(app.db, "crew.concurrency")).toBe(next);
116 expect(capacityValue(app.db, "queue.batch")).toBe("3");
117 const changed = capacityChanges(app.db).slice(0, capacityChanges(app.db).length - before).map((c) => c.key).sort();
118 expect(changed).toEqual(["crew.concurrency", "queue.batch"]);
119 const said = decodeURIComponent((res.headers.get("set-cookie") ?? "").replace(/\+/g, " "));
120 expect(said).toContain("crew.concurrency:");
121 expect(said).toContain("running");
122 expect(said).toContain("queue.batch:");
123 expect(said).toContain("up to 3 pulls per candidate");
124 });
125
126 test("a value outside the range is refused and named; a derived row cannot be posted", async () => {
127 const bad = await post({ "v.checks.shards": "999" });
128 expect(bad.status).toBe(303);
129 expect(decodeURIComponent((bad.headers.get("set-cookie") ?? "").replace(/\+/g, " "))).toContain("checks.shards");
130 const derived = await post({ "v.pace.floor": "9" });
131 expect(derived.status).toBe(303);
132 expect(capacityChanges(app.db).some((c) => c.key === "pace.floor")).toBe(false);
133 });
134
135 test("Put back names its key and resets only that row", async () => {
136 expect((await post({ "v.queue.batch": "4" })).status).toBe(303);
137 expect(capacityValue(app.db, "queue.batch")).toBe("4");
138 expect(await get()).toMatch(/name="reset"\s+value="queue.batch"/);
139 expect((await post({ reset: "queue.batch" })).status).toBe(303);
140 expect(capacityValue(app.db, "queue.batch")).toBe("8");
141 });
142
143 test("Enter in a field saves: the table form's first submit button is Save, Put back and Dry run sit in forms of their own", async () => {
144 expect((await post({ "v.queue.batch": "4" })).status).toBe(303);
145 const page = await get();
146 const start = page.indexOf('<form method="post" action="/settings/capacity">');
147 expect(start).toBeGreaterThan(-1);
148 const form = page.slice(start, page.indexOf("</form>", start));
149 const submits = [...form.matchAll(/<button\b[^>]*>/g)].map((m) => m[0]);
150 // Buttons that carry a form= belong to another form: only Save is the table form's own.
151 const own = submits.filter((b) => !b.includes("form="));
152 expect(own[0]).not.toContain("name=");
153 expect(own).toHaveLength(1);
154 expect(page).toMatch(/<button[^>]*name="reset"[^>]*form="put-queue.batch"/);
155 expect(page).toContain('<form id="put-queue.batch" method="post"');
156 expect(page).toMatch(/<button[^>]*name="dry"[^>]*form="dry-run"/);
157 expect(page).toMatch(/<form id="dry-run"[^>]*><input type="hidden" name="key" value="signin.edge"/);
158 await post({ reset: "queue.batch" });
159 });
160
161 test("Dry run with its key lists who the edge going off would lock out", async () => {
162 const res = await post({ key: "signin.edge", dry: "1" });
163 expect(res.status).toBe(303);
164 const said = decodeURIComponent((res.headers.get("set-cookie") ?? "").replace(/\+/g, " "));
165 expect(said).toContain("accounts sign in without the edge");
166 });
167
168 test("a Save with one good row and one bad writes neither", async () => {
169 const before = capacityChanges(app.db).length;
170 const batch = capacityValue(app.db, "queue.batch");
171 const next = batch === "5" ? "6" : "5";
172 const res = await post({ "v.queue.batch": next, "v.checks.shards": "999" });
173 expect(res.status).toBe(303);
174 expect(capacityValue(app.db, "queue.batch")).toBe(batch);
175 expect(capacityChanges(app.db).length).toBe(before);
176 expect(decodeURIComponent((res.headers.get("set-cookie") ?? "").replace(/\+/g, " "))).toContain("Nothing saved");
177 });
178
179 test("the Now column is the effect alone: history sits in the fold", async () => {
180 expect((await post({ "v.queue.batch": "4" })).status).toBe(303);
181 const page = await get();
182 const row = page.slice(page.indexOf('<tr data-key="queue.batch">'), page.indexOf("</tr>", page.indexOf('<tr data-key="queue.batch">')));
183 const cell = row.slice(row.lastIndexOf('<td class="small">'));
184 expect(cell).not.toContain("changed");
185 expect(row.slice(0, row.lastIndexOf('<td class="small">'))).toContain("changed");
186 await post({ reset: "queue.batch" });
187 });
188
189 test("the page says it once: one line of purpose, no 'only rows you changed', Changes is a settings block", async () => {
190 const page = await get();
191 expect(page).not.toContain("Only rows you changed");
192 expect(page).not.toContain('href="#changes"');
193 expect(page).toContain('<section class="settings-block" id="changes"><h2>Changes</h2>');
194 });
195
196 test("the MCP knobs' Speed, Pace floor and Queue depth effects are effectOf's words: one source", async () => {
197 const { readKnobs } = await import("../src/crew/knobs.ts");
198 const { effectOf } = await import("../src/actions/capacity_effects.ts");
199 const knobs = new Map(readKnobs(app).map((k) => [k.id, k.effect]));
200 expect(knobs.get("speed")).toBe(effectOf(app, "crew.concurrency", ""));
201 expect(knobs.get("floor")).toBe(effectOf(app, "pace.floor", ""));
202 expect(knobs.get("depth")).toBe(effectOf(app, "queue.depth", ""));
203 });
test/capacity-nojs.test.ts +17 −16
@@ -55,27 +55,29 @@ test("the page's content carries no script and no inline handler", async () => {
5555 expect(body).not.toMatch(/javascript:/i);
5656 });
5757
58 test("every change is a plain POST form to /settings/capacity, crew size and CPUs among them; self-swap is read, not changed", async () => {
58 test("every change is one plain POST form to /settings/capacity with one Save, crew size and CPUs among its rows; self-swap is read, not changed", async () => {
5959 const body = main(await page());
6060 const forms = [...body.matchAll(/<form\b([^>]*)>([\s\S]*?)<\/form>/g)];
61 expect(forms.length).toBeGreaterThan(0);
62 for (const [, attrs] of forms) {
63 expect(attrs).toMatch(/method="post"/);
64 expect(attrs).toMatch(/action="\/settings\/capacity"/);
65 }
66 const keys = forms.map(([, , inner]) => /name="key" value="([^"]+)"/.exec(inner!)?.[1]);
67 // Crew size, and the two settings sized from the pod's CPUs.
68 expect(keys).toEqual(expect.arrayContaining(["crew.concurrency", "checks.concurrency", "checks.shards"]));
69 // Nothing outside a form asks to be pressed: a button out of a form needs a script.
61 // The table's one form, then a tiny one per Put back and one for Dry run, each pressed by a
62 // button's `form=`.
63 expect(forms.length).toBeGreaterThan(1);
64 for (const f of forms.slice(1)) expect(f[1]).toMatch(/id="(put-[^"]+|dry-run)"/);
65 const [, attrs, inner = ""] = forms[0]!;
66 expect(attrs).toMatch(/method="post"/);
67 expect(attrs).toMatch(/action="\/settings\/capacity"/);
68 for (const key of ["crew.concurrency", "checks.concurrency", "checks.shards"]) expect(inner).toContain(`name="v.${key}"`);
69 expect(inner.match(/>\s*Save\s*</g)).toHaveLength(1);
70 // Derived rows are text, never inputs.
71 expect(inner).not.toContain('name="v.pace.floor"');
72 expect(inner).not.toContain('name="v.queue.depth"');
73 // Nothing outside the form asks to be pressed: a button out of a form needs a script.
7074 const outside = body.replace(/<form\b[\s\S]*?<\/form>/g, "");
7175 expect(outside).not.toMatch(/<(button|input|select|textarea)\b/);
7276 expect(outside).toContain('id="self-swap"');
7377 });
7478
7579 test("a change from another origin is refused and changes nothing", async () => {
76 const before = await page();
77 const form = /<form\b[^>]*>([\s\S]*?)<\/form>/.exec(main(before))![1]!;
78 const key = /name="key" value="([^"]+)"/.exec(form)![1]!;
80 const key = "crew.concurrency";
7981 const res = await fetch(`${servers.url}/settings/capacity`, {
8082 method: "POST",
8183 redirect: "manual",
@@ -87,9 +89,8 @@ test("a change from another origin is refused and changes nothing", async () =>
8789 });
8890
8991 test("the same change from this origin lands, with no script involved", async () => {
90 const form = /<form\b[^>]*>([\s\S]*?)<\/form>/.exec(main(await page()))![1]!;
91 const key = /name="key" value="([^"]+)"/.exec(form)![1]!;
92 const value = /<input[^>]*type="number"[^>]*min="(\d+)"/.exec(form)?.[1];
92 const key = "crew.concurrency";
93 const value = "3";
9394 const res = await fetch(`${servers.url}/settings/capacity`, {
9495 method: "POST",
9596 redirect: "manual",
test/capacity-rows.test.ts +12 −9
@@ -46,26 +46,29 @@ test("the settings are rows under a Capacity heading, and no part of the page is
4646 const main = await page();
4747 expect(main).not.toMatch(/class="card[\s"]/);
4848 expect(main).not.toContain("card-head");
49 for (const title of ["Capacity", "Changes", "Errors and refused calls", "Egress connections", "Self-swap"])
49 for (const title of ["Errors and refused calls", "Egress connections", "Self-swap"])
5050 expect(main).toContain(`<section class="settings-block"><h2>${title}</h2>`);
51 const settings = main.slice(main.indexOf("<h2>Capacity</h2>"));
52 expect(settings).toMatch(/^<h2>Capacity<\/h2><ul class="list setting-list">/);
53 expect(settings.slice(0, settings.indexOf("</ul>"))).toContain('name="key" value="cells.egress"');
51 expect(main).toContain('<section class="settings-block" id="changes"><h2>Changes</h2>');
52 // One table, in four groups, with one Save.
53 for (const group of ["Crew", "Checks", "Hosted forges", "Sign-in and safety"]) expect(main).toContain(`scope="colgroup">${group}</th>`);
54 expect(main.match(/<table\b/g)).toHaveLength(1);
55 expect(main).toContain('name="v.cells.egress"');
5456 // The settings come before what happened.
55 expect(main.indexOf("<h2>Capacity</h2>")).toBeLessThan(main.indexOf("<h2>Errors and refused calls</h2>"));
57 expect(main.indexOf("<table")).toBeLessThan(main.indexOf("<h2>Errors and refused calls</h2>"));
5658 });
5759
5860 test("the egress row reads its true current state, and the reported note says so in plain words", async () => {
5961 const egressRow = (s: string) => {
60 const at = s.indexOf('value="cells.egress"');
61 return s.slice(s.lastIndexOf("<li", at), at);
62 const at = s.indexOf('name="v.cells.egress"');
63 return s.slice(s.lastIndexOf("<tr", at), s.indexOf("</tr>", at));
6264 };
6365 const before = await page();
6466 expect(before).not.toContain('id="egress-reported"');
65 const now = /Now <span class="mono">([^<]+)<\/span>/.exec(egressRow(before))?.[1];
67 const now = /<option value="(\w+)"\s+selected/.exec(egressRow(before))?.[1];
6668 expect(changeCapacity(app, alice, "cells.egress", "report", "a test says why").ok).toBe(true);
6769 const after = await page();
68 expect(egressRow(after)).toContain('Now <span class="mono">report</span>');
70 expect(egressRow(after)).toMatch(/<option value="report"\s+selected/);
71 expect(egressRow(after)).toContain("undeclared hosts let through");
6972 expect(now).not.toBe("report");
7073 expect(after).toContain('id="egress-reported"');
7174 });
test/capacity.test.ts +4 −5
@@ -521,15 +521,14 @@ describe("report mode is loud to admins, and to nobody else", () => {
521521 app.db.query("UPDATE forge_setting SET updated_by = ?1 WHERE key = 'crew.concurrency'").run(bob.id);
522522 app.db.query("UPDATE user SET username = ?2 WHERE id = ?1").run(bob.id, "bo<b>b");
523523 const shown = (await page()).replace(/\s+/g, " ");
524 expect(shown).toContain(`changed from <span class="mono">${capacityDefault("crew.concurrency")}</span> 3 days ago by bo&lt;b&gt;b`);
524 expect(shown).toContain("by bo&lt;b&gt;b");
525525 expect(shown).not.toContain("bo<b>b");
526 expect(shown.match(/changed from/g)).toHaveLength(1);
527 expect(shown).toContain('<span class="muted small">changed from');
528 expect(shown).not.toContain('class="away"');
526 expect(shown.match(/ · changed /g)).toHaveLength(1);
527 expect(shown).toContain(`boot default <span class="mono">${capacityDefault("crew.concurrency")}</span>`);
529528 expect(shown).toContain(`Put ${CAPACITY["crew.concurrency"].label} back to the default`);
530529 app.db.query("UPDATE user SET username = 'bob' WHERE id = ?1").run(bob.id);
531530 expect(changeCapacity(app, alice, "crew.concurrency", null).ok).toBe(true);
532 expect(await page()).not.toContain("changed from");
531 expect(await page()).not.toContain('<span class="muted">changed ');
533532 });
534533
535534 test("enforced: no warning anywhere", async () => {
test/egress-default.test.ts +1 −1
@@ -159,7 +159,7 @@ test("the page: report without a reason is refused, with one it holds, and Put b
159159 const page = await (await fetch(`${servers.url}/settings/capacity`, { headers: { cookie } })).text();
160160 const form = [...page.matchAll(/<form\b[\s\S]*?<\/form>/g)]
161161 .map((m) => m[0])
162 .find((f) => f.includes('value="cells.egress"'));
162 .find((f) => f.includes('name="v.cells.egress"'));
163163 expect(form).toContain('name="reason"');
164164 expect(form).toContain('aria-label="Why (needed to set report)"');
165165 });
test/keys-capacity.test.ts +2 −2
@@ -38,8 +38,8 @@ afterAll(async () => {
3838 });
3939
4040 test("the sections are the only rows; the setting forms are not", () => {
41 expect(html).toContain('class="row-fields"');
42 const settings = html.slice(html.indexOf('class="list setting-list"'));
41 expect(html).toContain('class="table setting-table"');
42 const settings = html.slice(html.indexOf('class="table setting-table"'));
4343 expect(settings).not.toContain("data-nav");
4444 expect(html).toContain("data-nav");
4545 });
test/settings-visible.test.ts +3 −3
@@ -55,7 +55,7 @@ const get = async (path: string) =>
5555
5656 // The list item of each setting, from its key to the next row.
5757 // A setting row is a list row or, on the denser pages, a table row.
58 const rowsOf = (page: string) => page.split(/<li>|<tr>/).slice(1);
58 const rowsOf = (page: string) => page.split(/<li>|<tr\b[^>]*>/).slice(1);
5959
6060 test("every limit row shows name, value, default, bounds and a control, hover-free", async () => {
6161 const page = await get("/admin/limits");
@@ -90,11 +90,11 @@ test("every capacity row shows its value and control, hover-free", async () => {
9090 continue;
9191 }
9292 // a row derived from Speed is read-only: its value, no form
93 const mark = s.source === "derived" ? `data-derived="${s.key}"` : `name="key" value="${s.key}"`;
93 const mark = s.source === "derived" ? `data-derived="${s.key}"` : `name="v.${s.key}"`;
9494 const row = rowsOf(page).find((r) => r.includes(mark));
9595 expect(row, s.key).toBeDefined();
9696 expect(row).toContain(s.label);
97 if (s.source !== "derived") expect(row).toContain("Now <span");
97 if (s.source === "derived") expect(row).toContain("follows Crew runs at once");
9898 expect(row).not.toContain("row-actions");
9999 }
100100 });
test/signin-edge-off.test.ts +1 −1
@@ -79,7 +79,7 @@ describe("signin.edge off: the owner signs in by passkey and turns it back on",
7979 test("Settings → Capacity shows signin.edge, on", async () => {
8080 expect(capacityValue(app.db, "signin.edge")).toBe("on");
8181 const page = await (await fetch(`${base}/settings/capacity`, { headers: { cookie: owner } })).text();
82 expect(page).toContain('name="key" value="signin.edge"');
82 expect(page).toContain('name="v.signin.edge"');
8383 expect((await who(asAda)).status).toBe(200);
8484 });
8585

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs