Files
brain-of-reese/frontend/assets/settings.js
T
ducoterra 1200437bf8
Build and Push Containers / build-and-push-app (push) Successful in 4m4s
Build and Push Containers / build-and-push-db (push) Successful in 15s
phase: 168_admin_settings_panel
**Phase 168 — Admin Settings panel — final verification: PASS**

1. **Implemented/verified:** `/settings.html` (admin-only) with the 75-field catalogue (`app/core/settings_catalog.py`), DB-over-env overrides in Postgres (`app_settings`, migration 0028 at head, `settings_overlay.py` resolver, `app/api/admin_settings.py` — 4 admin-only routes), live-apply on save with no restart + restart-required badges, Reset/Clear all, write-only secrets, `.env`-never-written, `BOR_SETTINGS_DB=0` kill switch.
2. **Phase E2E: 12/12** — run with `E2E_APP_PORT=8200` (ports 8123/8124 are held by an unrelated "undercooked" project; no process killed, no code change — the documented env override).
3. **Regression set: all 7 suites green in isolation** (theme tab, API tokens, configurable brand, global tuning, admin auth, cache busting, wide desktop column — 38 tests).
4. **Full suite: unit+integration exit 0 (4066 passed), app/ coverage 99%** (gate >90%); **ruff clean, pyright 0 errors / 0 warnings.**
5. **Log contract (rule 10) verified live:** per-turn + per-response byte-budget lines present; settings write lines carry key + action, **never the value**.
6. **Byte-budget audit: all endpoints under the 262,144 B budget**; settings catalogue 23,513 B (gzip 3,326).
7. **Defect fixed (one):** criterion 5 had no integration pin — added `test_bad_row_inserted_directly_never_bricks_boot` to `tests/integration/test_admin_settings_api.py` (malformed row inserted directly → fresh `create_app()` boots, row skipped with logged reason, rest of table applies, `/api/health` 200) — 12/12 green.
8. **Docs pass:** `README.md` and `AGENTS.md` reviewed in full — both consistent with the as-built feature (Settings page table, Settings section, Configuration-reference note, `.env.example` block); **no changes required**.
9. **Cleanup:** audit app killed (by PID); `app_settings` left empty (0 rows); all changes left in the working tree (no commit, per protocol).
10. **Completion criteria:** all 7 checkboxes verified green (criterion 7's commit is the harness's).
11. **Next pending phase:** `170_edit_bubble_sizing`.
2026-10-10 01:05:14 -04:00

643 lines
26 KiB
JavaScript

/* Brain of Reese — Settings view module (phase 168, task 05): the
* admin settings panel — "edit anything in .env and save it to the
* database. The database value should override the env var. The
* change should take effect on clicking 'save'" (TODO.md L3).
*
* The phase-76 shell-view-module contract (the theme.js / tokens.js
* shape): the router (assets/router.js) lazy-imports this module on
* FIRST show of #view-settings and calls mount(root) ONCE (mount-once,
* hide-forever — root is the view's <section id="view-settings">,
* every DOM lookup scoped to it). The initSharedHeader() call never
* happens here: in the shell the shared header boots exactly once,
* via the chat module (app.js) at shell boot.
*
* What the panel does:
*
* • gate — fetchIsAdmin() (the SAME cached /api/whoami promise
* header.js exports, zero extra requests): admin hides
* #settings-gate and reveals #settings-content; anonymous /
* token-user keeps the gate (the #nav-settings link is already
* hidden by header.js — the gate is the DIRECT-URL case, the
* #tokens-gate pattern). No /api/admin/settings request is ever
* made outside the admin branch (the router 403s them — the
* phase-79 contract).
* • load — GET /api/admin/settings → render the 75-row catalogue
* in the SERVER's order (GROUPS order — the stable order the
* E2E pins against): one <tr> per setting (the group band rows
* are created per group) + the ship-rebuilt no-match row, all
* through createElement + textContent (this file never builds
* HTML — the XSS-safe-by-construction house rule). A failed
* fetch keeps the last rendered catalogue (never a blanked panel)
* and shows the house error line.
* • rows — the Setting cell (the label in a .cell-clip ellipsis
* — the phase-156 contract with the full text in the control's
* aria-label — + the BOR_* name in <code class="settings-env">
* + the literal-text `restart required` .settings-flag for the
* boot-wired fields (text, never color alone, B5, with the
* title/aria-describedby copy explaining when it applies)),
* the Value cell (the control by the server's `type`: int/float
* → <input type=number> (step="any" for float), bool → a
* true/false <select>, json → a spellcheck=false <textarea>
* (the one list[str] field, K2), str → <input type=text> (a
* <textarea rows=2> for the CSV/path fields whose value exceeds
* 40 chars), secret → <input type=password
* autocomplete=new-password placeholder="•••••• (stored)"> with
* an aria-label naming the env var — an EMPTY secret input
* means "leave unchanged" (never an accidental wipe); every
* control is id=set-<key> with a <label for>), the Source cell
* (the literal-text DB / env / default badge — the color is
* decoration, B5), and the Actions cell (the per-row Reset —
* disabled with a title when there is nothing to reset or the
* field is read-only, LOCKED A3).
* • dirty tracking — module-state Map<key, value>: an input/
* change marks the row (.is-dirty + the "N unsaved changes"
* hint) and enables #settings-save; a row that returns to its
* served value un-marks.
* • Save — the §7.4 never-stale lifecycle (disabled + aria-busy +
* "Saving…", re-enabled on success AND failure — a click can
* never leave the button stuck): for each dirty row in DOM
* order PUT /api/admin/settings/<key> with { value }; STOP AT
* THE FIRST FAILURE (K4) — its server detail lands in
* #settings-error (role=alert), the catalogue re-GETs so the
* badges show the truth, the remaining rows' edits are
* re-applied to the re-rendered controls (they stay in the form
* for correction), and focus goes to the offending input. All
* good → one #settings-status line `Saved N settings.` (then
* role=status) — a saved restart-required row appends "—
* applies on the next restart" (the owner is never told
* "saved" and then sees nothing change) — + a re-GET so every
* badge/value is the settled server state.
* • Reset — per row: DELETE /api/admin/settings/<key> → the
* status line `BOR_X is back to the environment value.` + a
* re-GET.
* • Clear all overrides — the house two-step inline confirm
* (the history-confirm-* classes, focus moves to the confirm
* button, Escape / No cancels) → DELETE /api/admin/settings →
* the status line `Cleared N overrides.` (N from the
* response) + a re-GET.
* • search — #settings-filter: a case-insensitive substring over
* the label + BOR_* name cells, applied on input with NO fetch
* (the phase-101 tokens D4 contract) and RE-APPLIED after every
* load (the query lives in the input — it survives re-shows,
* the phase-77 contract). A group with no visible rows hides
* its group row; zero matches with a non-empty query → one
* no-match row `No settings match "<query>"` (textContent).
* • the kill-switch banner — while overlay_enabled is false
* (BOR_SETTINGS_DB=0, D6) the #settings-disabled alert explains
* that saving stores the value but it will not take effect
* (the mechanism is off, not the panel).
*
* Every value is rendered with textContent — this file never builds
* HTML (the XSS-safe-by-construction house rule; a full-file source
* pin enforces it).
*/
import { fetchIsAdmin } from "./header.js";
export async function mount(root) {
/* ---------- view elements (the view's section, scoped to root) ---------- */
const gateEl = root.querySelector("#settings-gate");
const contentEl = root.querySelector("#settings-content");
const disabledBanner = root.querySelector("#settings-disabled");
const statusEl = root.querySelector("#settings-status");
const errorEl = root.querySelector("#settings-error");
const filter = root.querySelector("#settings-filter");
const tbody = root.querySelector("#settings-tbody");
const saveBtn = root.querySelector("#settings-save");
const clearAllBtn = root.querySelector("#settings-clear-all");
const dirtyHint = root.querySelector("#settings-dirty");
const SAVE_LABEL = "Save settings";
/* Module state (the phase-76 mount-once contract — it survives
every switch): the last settled catalogue (the row meta for the
save's restart check), the pending edits (key → the value being
edited), and the in-flight save flag (the §7.4 guard). */
let lastItems = [];
const dirty = new Map();
let saveInFlight = false;
let clearAllEsc = null; // the armed Escape handler (null = disarmed)
/* The no-match row (rebuilt into the tbody on every render — the
<td> text is JS-filled; it is never a data row). */
const noMatchRow = document.createElement("tr");
noMatchRow.className = "settings-no-match";
noMatchRow.hidden = true;
const noMatchTd = document.createElement("td");
noMatchTd.colSpan = 4;
noMatchRow.appendChild(noMatchTd);
/* ---------- feedback lines (never stale, §7.4) ---------- */
function announce(message) {
if (statusEl) statusEl.textContent = message;
}
function showError(message) {
if (!errorEl) return;
errorEl.textContent = message; // textContent — the server detail is data
errorEl.hidden = false;
}
function clearError() {
if (!errorEl) return;
errorEl.textContent = "";
errorEl.hidden = true;
}
/* FastAPI error bodies: a string detail (the house 422s — the
detail names the offending field) or the validation-error array
(the first entry's msg). Same extraction as theme.js. */
async function apiDetail(r, fallback) {
try {
const data = await r.json();
if (Array.isArray(data.detail) && data.detail[0] && data.detail[0].msg) {
return String(data.detail[0].msg);
}
if (typeof data.detail === "string" && data.detail) return data.detail;
} catch {
/* non-JSON error body */
}
return fallback;
}
/* ---------- catalogue render (createElement + textContent only) ---------- */
const dataRows = () =>
tbody ? [...tbody.querySelectorAll("tr.settings-row")] : [];
function makeControl(item) {
let control;
if (item.secret) {
/* LOCKED A4: the secret is write-only — the input starts
EMPTY (the plaintext never leaves the server); an empty
value means "leave unchanged" (never an accidental wipe). */
control = document.createElement("input");
control.type = "password";
control.setAttribute("autocomplete", "new-password");
control.placeholder = "•••••• (stored)";
} else if (item.type === "int") {
control = document.createElement("input");
control.type = "number";
control.value = item.value;
} else if (item.type === "float") {
control = document.createElement("input");
control.type = "number";
control.step = "any";
control.value = item.value;
} else if (item.type === "bool") {
control = document.createElement("select");
for (const opt of ["true", "false"]) {
const option = document.createElement("option");
option.value = opt;
option.textContent = opt;
control.appendChild(option);
}
control.value = item.value;
} else if (item.type === "json") {
/* The one list[str] field (K2) — edited as a JSON array in a
textarea (the server's env-native string form, verbatim). */
control = document.createElement("textarea");
control.spellcheck = false;
control.rows = 2;
control.value = item.value;
} else if (item.type === "str" && (item.value || "").length > 40) {
/* A CSV / path field with a long value — the two-row
textarea (no single-line clip for 200-char lists). */
control = document.createElement("textarea");
control.rows = 2;
control.value = item.value;
} else {
control = document.createElement("input");
control.type = "text";
control.setAttribute("autocomplete", "off");
control.value = item.value;
}
control.id = "set-" + item.key;
control.classList.add("settings-control");
/* The full (unclipped) label stays reachable: the .cell-clip
ellipsis is visual only (the phase-156 contract), and the
secret's aria-label names the env var (the house pattern for
table-hosted inputs — the Setting cell's label is the
visible <label for>). */
control.setAttribute(
"aria-label",
item.secret ? item.env_var : `${item.label} — ${item.env_var}`,
);
return control;
}
function makeRow(item) {
const tr = document.createElement("tr");
tr.className = "settings-row";
tr.dataset.key = item.key;
/* The Setting cell: the label (the .cell-clip ellipsis — the
full text is the label's own textContent + the control's
aria-label), the BOR_* name (presentation only, D1), and —
when boot-wired (LOCKED A4) — the literal-text flag with
the when-it-applies copy (title + the shared
aria-describedby target). */
const nameTd = document.createElement("td");
nameTd.className = "settings-name-cell";
const label = document.createElement("label");
label.htmlFor = "set-" + item.key;
const clip = document.createElement("span");
clip.className = "cell-clip";
clip.textContent = item.label;
label.appendChild(clip);
const env = document.createElement("code");
env.className = "settings-env";
env.textContent = item.env_var;
nameTd.append(label, env);
if (item.restart_required) {
const flag = document.createElement("span");
flag.className = "settings-flag";
flag.textContent = "restart required"; // text, never color alone (B5)
flag.title =
"Applies on the next restart — the app reads this setting once at boot";
flag.setAttribute("aria-describedby", "settings-restart-desc");
nameTd.appendChild(flag);
}
tr.appendChild(nameTd);
/* The Value cell: the control by type (see makeControl). */
const valueTd = document.createElement("td");
valueTd.className = "settings-value-cell";
const control = makeControl(item);
valueTd.appendChild(control);
tr.appendChild(valueTd);
/* The Source cell: the literal-text badge (db → "DB", env,
default — the color is decoration, B5). */
const srcTd = document.createElement("td");
const src = document.createElement("span");
src.className =
"settings-src " +
({ db: "is-db", env: "is-env", default: "is-default" })[item.source];
src.textContent = item.source === "db" ? "DB" : item.source;
srcTd.appendChild(src);
tr.appendChild(srcTd);
/* The Actions cell: the per-row Reset — disabled with a title
when there is NOTHING to reset (no saved override) or the
field is READ-ONLY (LOCKED A3: the engine is built from it /
the dim is fixed at table creation). */
const actTd = document.createElement("td");
actTd.className = "settings-actions-cell";
const reset = document.createElement("button");
reset.type = "button";
reset.className = "settings-reset";
reset.textContent = "Reset";
reset.setAttribute("aria-label", `Reset ${item.env_var}`);
if (!item.overridable) {
reset.disabled = true;
reset.title = `read-only — ${item.env_var} is not settable from the database`;
} else if (!item.has_override) {
reset.disabled = true;
reset.title = "no saved override — the environment value is in effect";
}
reset.addEventListener("click", () => void resetRow(item.key, item.env_var));
actTd.appendChild(reset);
tr.appendChild(actTd);
/* Dirty tracking (input + change — the select/change pair). */
control.addEventListener("input", () => markDirty(item, control));
control.addEventListener("change", () => markDirty(item, control));
return tr;
}
/* GET /api/admin/settings → render the groups in the server's
order (re-entrant: the tbody is REPLACED — never a duplicate
set — and the no-match row is re-appended). A FAILED load
returns before the render (the last catalogue stays) and shows
the house error line. */
function render(items) {
if (!tbody) return;
const rows = [];
let currentGroup = null;
for (const item of items) {
if (item.group !== currentGroup) {
currentGroup = item.group;
const groupRow = document.createElement("tr");
groupRow.className = "settings-group-row";
const th = document.createElement("th");
th.colSpan = 4;
th.scope = "colgroup";
th.textContent = item.group;
groupRow.appendChild(th);
rows.push(groupRow);
}
rows.push(makeRow(item));
}
rows.push(noMatchRow);
tbody.replaceChildren(...rows);
}
async function loadSettings() {
let r;
try {
r = await fetch("/api/admin/settings");
} catch {
showError("Couldn't load the settings — is the app reachable?");
return false;
}
if (!r.ok) {
showError("Couldn't load the settings — try again.");
return false;
}
let data;
try {
data = await r.json();
} catch {
showError("Couldn't load the settings — try again.");
return false;
}
clearError();
lastItems = data.items;
/* The kill-switch banner (D6): the mechanism is off, not the
panel — a save stores the value but it will not take effect. */
if (disabledBanner) disabledBanner.hidden = data.overlay_enabled;
render(data.items);
/* A failed batch keeps the remaining edits in the form (K4):
re-apply every pending value to the re-rendered control and
re-mark the row. */
for (const [key, value] of dirty) {
const control = root.querySelector("#set-" + key);
if (!control) continue;
control.value = value;
const row = control.closest("tr");
if (row) row.classList.add("is-dirty");
}
applyFilter();
updateDirtyUI();
return true;
}
/* ---------- dirty tracking (module state) ---------- */
function markDirty(item, control) {
/* The served value: the effective value in env-native string
form — for a MASKED field it is "" (an empty input means
"leave unchanged", never an accidental wipe). */
const served = item.secret ? "" : item.value ?? "";
const value = control.value;
if (value === served) {
dirty.delete(item.key);
} else {
dirty.set(item.key, value);
}
updateDirtyUI();
}
function updateDirtyUI() {
for (const row of dataRows()) {
row.classList.toggle("is-dirty", dirty.has(row.dataset.key));
}
if (dirtyHint) {
dirtyHint.textContent = dirty.size
? `${dirty.size} unsaved changes`
: "";
}
if (saveBtn && !saveInFlight) saveBtn.disabled = dirty.size === 0;
}
/* ---------- the client-side search (phase-101 D4 contract) ----------
* Case-insensitive substring over the label + BOR_* name cells,
* applied on `input` with NO fetch and re-applied after every
* load (the query lives in the input — it survives re-shows).
* A group with no visible rows hides its group row; zero matches
* with a non-empty query → the one no-match row (textContent). */
function applyFilter() {
const query = (filter ? filter.value : "").trim().toLowerCase();
const children = tbody ? [...tbody.children] : [];
let visible = 0;
let currentGroupRow = null;
const groupVisible = new Map();
for (const tr of children) {
if (tr === noMatchRow) continue; // the state row is never a data row
if (tr.classList.contains("settings-group-row")) {
currentGroupRow = tr;
groupVisible.set(tr, false);
continue;
}
const nameCell = tr.querySelector(".settings-name-cell");
const labelEl = nameCell ? nameCell.querySelector("label") : null;
const envEl = nameCell
? nameCell.querySelector(".settings-env")
: null;
const haystack =
((labelEl ? labelEl.textContent : "") +
" " +
(envEl ? envEl.textContent : "")).toLowerCase();
const show = query === "" || haystack.includes(query);
tr.hidden = !show;
if (show) visible += 1;
if (currentGroupRow) groupVisible.set(currentGroupRow, true);
}
for (const [groupRow, hasVisible] of groupVisible) {
groupRow.hidden = !hasVisible;
}
const noMatch = query !== "" && visible === 0;
noMatchRow.hidden = !noMatch;
if (noMatch) {
noMatchTd.textContent = `No settings match "${
filter ? filter.value.trim() : ""
}".`;
}
}
/* ---------- Save (dirty rows only — stop at the first failure,
K4; the §7.4 never-stale lifecycle) ---------- */
async function saveSettings() {
if (!dirty.size || saveInFlight) return;
saveInFlight = true;
if (saveBtn) {
saveBtn.disabled = true;
saveBtn.setAttribute("aria-busy", "true");
saveBtn.textContent = "Saving…";
}
clearError();
const saved = [];
let failure = null;
for (const row of dataRows()) {
const key = row.dataset.key;
if (!key || !dirty.has(key)) continue;
const value = dirty.get(key);
try {
const r = await fetch(`/api/admin/settings/${key}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ value }),
});
if (!r.ok) {
failure = { key, r };
break; // stop at the first failure (K4)
}
saved.push(key);
dirty.delete(key);
} catch {
failure = { key, r: null };
break; // the app is unreachable — stop
}
}
if (failure) {
/* The 422 detail (it names the field) or the house network
line; the catalogue re-GETs first (the badges show the
truth, the remaining edits are re-applied — K4), and the
error is shown AFTER the re-GET (the re-GET's clearError
must not wipe it — the previous success line is cleared
with it, so the stale "Saved N settings." never lingers,
the §7.4 never-stale contract). Focus goes to the
offending input. */
await loadSettings();
if (statusEl) statusEl.textContent = "";
showError(
failure.r
? await apiDetail(failure.r, "Couldn't save the settings — try again.")
: "Couldn't save the settings — is the app reachable?",
);
const input = root.querySelector("#set-" + failure.key);
if (input) input.focus();
} else {
/* One status line (role=status) — a saved restart-required
row says so (the owner is never told "saved" and then sees
nothing change). */
const anyRestart = saved.some(
(key) => (lastItems.find((i) => i.key === key) || {}).restart_required,
);
announce(
`Saved ${saved.length} settings.` +
(anyRestart ? " — applies on the next restart" : ""),
);
await loadSettings(); // every badge/value is the settled state
}
saveInFlight = false;
if (saveBtn) {
saveBtn.removeAttribute("aria-busy");
saveBtn.textContent = SAVE_LABEL;
saveBtn.disabled = dirty.size === 0;
}
}
/* ---------- the per-row Reset (DELETE the row → env wins) ---------- */
async function resetRow(key, envVar) {
let r;
try {
r = await fetch(`/api/admin/settings/${key}`, { method: "DELETE" });
} catch {
announce(`Couldn't reset ${envVar} — is the app reachable?`);
return;
}
if (!r.ok) {
announce(`Couldn't reset ${envVar} — try again.`);
return;
}
announce(`${envVar} is back to the environment value.`);
await loadSettings(); // the badge falls back to env/default
}
/* ---------- Clear all overrides (the house two-step inline
confirm — the history-confirm-* classes; focus to Yes; Escape
/ No cancels) ---------- */
function restoreClearAll() {
if (clearAllEsc) {
document.removeEventListener("keydown", clearAllEsc, true);
clearAllEsc = null;
}
const wrap = root.querySelector(".settings-confirm");
if (wrap) wrap.replaceWith(clearAllBtn);
if (clearAllBtn) clearAllBtn.focus();
}
async function confirmClearAll(yesBtn, restore) {
yesBtn.disabled = true; // no double-fire while the request is in flight
let cleared = null;
try {
const r = await fetch("/api/admin/settings", { method: "DELETE" });
if (!r.ok) {
announce("Couldn't clear the overrides — try again.");
restore();
return;
}
const data = await r.json();
cleared = data.cleared;
} catch {
announce("Couldn't clear the overrides — is the app reachable?");
restore();
return;
}
restore();
announce(`Cleared ${cleared} overrides.`);
await loadSettings(); // every badge falls back to env/default
}
function showClearAllConfirm() {
if (!clearAllBtn) return;
const wrap = document.createElement("span");
wrap.className = "settings-confirm";
const label = document.createElement("span");
label.className = "history-confirm-text";
label.textContent = "Clear all overrides?";
const yes = document.createElement("button");
yes.type = "button";
yes.className = "history-confirm-yes";
yes.textContent = "Yes";
const no = document.createElement("button");
no.type = "button";
no.className = "history-confirm-no";
no.textContent = "No";
yes.addEventListener("click", () => void confirmClearAll(yes, restoreClearAll));
no.addEventListener("click", restoreClearAll);
wrap.append(label, yes, no);
clearAllBtn.replaceWith(wrap);
yes.focus(); // the confirm pair takes over the focus
/* Escape cancels (the task contract — the capture phase so the
page's own Esc handlers never race it). */
clearAllEsc = (e) => {
if (e.key === "Escape") {
e.stopPropagation();
restoreClearAll();
}
};
document.addEventListener("keydown", clearAllEsc, true);
}
/* ---------- view boot (phase 168 task 05) ----------
* The shared header is NOT booted here — in the shell it runs
* exactly once, via the chat module (app.js) at shell boot. The
* gate reads fetchIsAdmin() — the SAME cached whoami promise the
* header uses (zero extra requests). Anonymous / token-user: the
* gate in, the content out — and NO /api/admin/settings request
* at all (the router 403s them — the phase-79 contract). */
if (!(await fetchIsAdmin())) {
if (gateEl) gateEl.hidden = false;
if (contentEl) contentEl.hidden = true;
return;
}
if (gateEl) gateEl.hidden = true;
if (contentEl) contentEl.hidden = false;
/* Bindings — armed in the ADMIN branch only (like the refresh
listener): Save (the §7.4 lifecycle), Clear all (the two-step
confirm), the client-side search (NO fetch). */
if (saveBtn) saveBtn.addEventListener("click", () => void saveSettings());
if (clearAllBtn) clearAllBtn.addEventListener("click", showClearAllConfirm);
if (filter) filter.addEventListener("input", () => applyFilter());
/* Phase 77 (the re-show refresh contract): a user-initiated
re-show of this already-mounted view makes the router dispatch
bor:view-refresh on the section — re-run the load then (the
tab always shows the settled server state when re-shown; the
search query survives — it lives in the input). Armed ONLY
here, after the whoami gate passed. `started` flips true once
the first loadSettings() is made, so the listener can only
ever re-run a load the mount already did. */
let started = false;
root.addEventListener("bor:view-refresh", () => {
if (started) void loadSettings();
});
started = true;
void loadSettings(); // the first load (the catalogue)
}