dashboard: single save-all button for the permissions page

Replace the per-row save buttons on the P3RM1SS10NS tab with one
page-level "save all (N agents)" button covering both the capabilities
and tool-groups matrices.

Toggling cells stages edits in the DOM; each checkbox carries its
render-time baseline (data-baseline). On save we diff against the
baseline and POST only the perm-types that actually changed per agent
to the new combined endpoint:

  POST /api/permissions { changes: [ { agent, tool_groups?, capabilities? } ] }

An omitted field leaves that perm-type untouched (no commit, no diff);
an included array fully replaces it. The backend coalesces caps + groups
for one agent into a single rebuild — no more double-rebuild when an
operator changes both for the same agent. The batch is atomic: on a
clean 200 the bar shows queued -> rebuilding and re-fetches (resetting
baselines); on any validation error nothing is applied and an error note
is shown.

Live capabilities_changed / tool_groups_changed re-renders are skipped
while the section has unsaved edits so a half-finished edit set is not
clobbered; the tab-activation and post-save re-fetches are the recovery
paths.

Pairs with the hive-c0re combined-PermPayload half (damocles).
This commit is contained in:
iris 2026-06-17 17:53:03 +02:00 committed by mara
commit 4297436d94
4 changed files with 208 additions and 91 deletions

View file

@ -1,5 +1,5 @@
// Dashboard P3RM1SS10NS tab — the per-agent capabilities + tool-groups
// matrices.
// matrices, with a single page-level "save all" button.
//
// Both tables are fetched on tab activation (`GET /api/capabilities`,
// `GET /api/tool-groups`) and after each save. Columns (caps / groups)
@ -13,25 +13,56 @@
// payload. The agent roster (`containersState`) is the only shared state
// it reads — to union live containers with agents already named in the
// assignments map.
//
// Editing model (the save-all issue): the operator toggles any number of
// checkboxes across BOTH matrices, then clicks the single "save all (N)"
// button. We diff each checkbox against the baseline captured at render
// time (stored on `data-baseline`) and POST only the perm-types that
// actually changed per agent to `POST /api/permissions`:
//
// { changes: [ { agent, tool_groups?, capabilities? } ] }
//
// Omitted field = leave that perm-type untouched (no commit, no diff);
// an included array fully replaces that perm-type for that agent. The
// backend coalesces caps+groups for one agent into ONE combined queue
// entry → one rebuild per agent (no more double-rebuilds). The batch is
// atomic: validated whole, applied whole, or rejected whole with
// `{error}` — so the saved→rebuilding transition only fires on a clean
// 200.
import { $, el } from './common.js';
import { containersState } from './state.js';
// ── SSE re-render guards ────────────────────────────────────────────
// Skip the live re-render when the operator has unsaved edits in that
// section (or a checkbox focused) — clobbering a half-finished edit set
// is worse than a brief staleness window. The tab-activation re-fetch
// and the post-save re-fetch are the recovery paths; both clear dirty.
export function applyCapabilitiesChanged(ev) {
const root = $('capabilities-section');
if (!root) return;
// Skip re-render while operator has a checkbox focused in this
// section — the tab-activation re-fetch is the recovery path.
if (root.contains(document.activeElement)) return;
if (sectionHasDirty(root)) return;
renderCapabilities(root, ev);
}
export function applyToolGroupsChanged(ev) {
const root = $('tool-groups-section');
if (!root) return;
if (root.contains(document.activeElement)) return;
if (sectionHasDirty(root)) return;
renderToolGroups(root, ev);
}
// A section is dirty if any checkbox diverges from its render-time
// baseline. Cheap DOM scan; no module-level mirror to drift.
function sectionHasDirty(root) {
for (const cb of root.querySelectorAll('input[type=checkbox]')) {
if (cb.checked !== (cb.dataset.baseline === '1')) return true;
}
return false;
}
export async function fetchAndRenderCapabilities() {
const root = $('capabilities-section');
if (!root) return;
@ -53,6 +84,7 @@ function renderCapabilities(root, data) {
const { caps, descriptions = {}, assignments, effective = {} } = data;
if (!caps || !caps.length) {
root.append(el('p', { class: 'meta' }, '(no capabilities defined)'));
updateSaveBar();
return;
}
@ -68,6 +100,7 @@ function renderCapabilities(root, data) {
if (!agentNames.length) {
root.append(el('p', { class: 'meta' }, '(no agents)'));
updateSaveBar();
return;
}
@ -81,7 +114,6 @@ function renderCapabilities(root, data) {
for (const c of caps) {
hrow.append(el('th', { class: 'cap-col', title: descriptions[c] || c }, c));
}
hrow.append(el('th', { class: 'cap-save-col' }, ''));
thead.append(hrow);
table.append(thead);
@ -90,14 +122,13 @@ function renderCapabilities(root, data) {
// Effective caps (explicit-or-default) drive the checkboxes so
// default-perms agents show their real grants, not blank.
const assigned = effective[name] || assignments[name] || [];
const tr = el('tr', { class: 'cap-row' });
const tr = el('tr', { class: 'cap-row', 'data-agent': name });
// Agent name cell.
tr.append(el('td', { class: 'cap-agent-col' },
el('span', { class: 'cap-agent-name' }, name)));
// One checkbox per capability.
const checkboxes = [];
for (const c of caps) {
const checked = assigned.includes(c);
const td = el('td', { class: 'cap-col' });
@ -105,52 +136,21 @@ function renderCapabilities(root, data) {
type: 'checkbox',
class: 'cap-cb',
'data-cap': c,
'data-baseline': checked ? '1' : '0',
'aria-label': c,
});
cb.checked = checked;
cb.addEventListener('change', onCellToggle);
td.append(cb);
tr.append(td);
checkboxes.push(cb);
}
// Save button cell.
const saveTd = el('td', { class: 'cap-save-col' });
const saveBtn = el('button', { type: 'button', class: 'btn cap-save-btn' }, 'save');
saveBtn.addEventListener('click', async () => {
const selectedCaps = checkboxes
.filter((cb) => cb.checked)
.map((cb) => cb.dataset.cap);
saveBtn.disabled = true;
saveBtn.textContent = '…';
try {
const r = await fetch('/api/capabilities/' + encodeURIComponent(name), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ caps: selectedCaps }),
});
if (!r.ok) {
const txt = await r.text();
saveBtn.textContent = 'err';
saveBtn.title = txt;
} else {
saveBtn.textContent = '✓';
setTimeout(fetchAndRenderCapabilities, 800);
}
} catch (err) {
saveBtn.textContent = 'err';
saveBtn.title = String(err);
} finally {
saveBtn.disabled = false;
}
});
saveTd.append(saveBtn);
tr.append(saveTd);
tbody.append(tr);
}
table.append(tbody);
wrap.append(table);
root.append(wrap);
updateSaveBar();
}
export async function fetchAndRenderToolGroups() {
@ -174,6 +174,7 @@ function renderToolGroups(root, data) {
const { groups, descriptions = {}, assignments, effective = {} } = data;
if (!groups || !groups.length) {
root.append(el('p', { class: 'meta' }, '(no tool groups defined)'));
updateSaveBar();
return;
}
@ -188,6 +189,7 @@ function renderToolGroups(root, data) {
if (!agentNames.length) {
root.append(el('p', { class: 'meta' }, '(no agents)'));
updateSaveBar();
return;
}
@ -201,7 +203,6 @@ function renderToolGroups(root, data) {
for (const g of groups) {
hrow.append(el('th', { class: 'tg-group-col', title: descriptions[g] || g }, g));
}
hrow.append(el('th', { class: 'tg-save-col' }, ''));
thead.append(hrow);
table.append(thead);
@ -213,7 +214,7 @@ function renderToolGroups(root, data) {
// badge still keys off explicit-assignment presence.
const assigned = effective[name] || assignments[name] || [];
const hasExplicit = Object.prototype.hasOwnProperty.call(assignments, name);
const tr = el('tr', { class: 'tg-row' });
const tr = el('tr', { class: 'tg-row', 'data-agent': name });
// Agent name cell.
const nameTd = el('td', { class: 'tg-agent-col' });
@ -224,7 +225,6 @@ function renderToolGroups(root, data) {
tr.append(nameTd);
// One checkbox per group.
const checkboxes = [];
for (const g of groups) {
const checked = assigned.includes(g);
const td = el('td', { class: 'tg-group-col' });
@ -232,50 +232,137 @@ function renderToolGroups(root, data) {
type: 'checkbox',
class: 'tg-cb',
'data-group': g,
'data-baseline': checked ? '1' : '0',
'aria-label': g,
});
cb.checked = checked;
cb.addEventListener('change', onCellToggle);
td.append(cb);
tr.append(td);
checkboxes.push(cb);
}
// Save button cell.
const saveTd = el('td', { class: 'tg-save-col' });
const saveBtn = el('button', { type: 'button', class: 'btn tg-save-btn' }, 'save');
saveBtn.addEventListener('click', async () => {
const selectedGroups = checkboxes
.filter((cb) => cb.checked)
.map((cb) => cb.dataset.group);
saveBtn.disabled = true;
saveBtn.textContent = '…';
try {
const r = await fetch('/api/tool-groups/' + encodeURIComponent(name), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ groups: selectedGroups }),
});
if (!r.ok) {
const txt = await r.text();
saveBtn.textContent = 'err';
saveBtn.title = txt;
} else {
saveBtn.textContent = '✓';
setTimeout(fetchAndRenderToolGroups, 800);
}
} catch (err) {
saveBtn.textContent = 'err';
saveBtn.title = String(err);
} finally {
saveBtn.disabled = false;
}
});
saveTd.append(saveBtn);
tr.append(saveTd);
tbody.append(tr);
}
table.append(tbody);
wrap.append(table);
root.append(wrap);
updateSaveBar();
}
// ── Save-all wiring ─────────────────────────────────────────────────
// Recompute the save bar on every cell toggle. Also clears any stale
// error/✓ status the bar may be showing from a prior save.
function onCellToggle() {
clearSaveStatus();
updateSaveBar();
}
// Collect the sparse change-set: one entry per agent that has at least
// one perm-type diverging from baseline. Only the changed perm-type(s)
// are included so untouched defaults stay defaults (an included array is
// a full replacement → omitting it leaves that file alone).
function collectChanges() {
const byAgent = new Map(); // agent -> { capabilities?, tool_groups? }
collectSection($('capabilities-section'), '.cap-row', '.cap-cb', 'cap', 'capabilities', byAgent);
collectSection($('tool-groups-section'), '.tg-row', '.tg-cb', 'group', 'tool_groups', byAgent);
const changes = [];
for (const [agent, obj] of byAgent) changes.push({ agent, ...obj });
return changes;
}
function collectSection(root, rowSel, cbSel, dataKey, field, byAgent) {
if (!root) return;
for (const tr of root.querySelectorAll(rowSel)) {
const agent = tr.dataset.agent;
if (!agent) continue;
let dirty = false;
const selected = [];
for (const cb of tr.querySelectorAll(cbSel)) {
if (cb.checked !== (cb.dataset.baseline === '1')) dirty = true;
if (cb.checked) selected.push(cb.dataset[dataKey]);
}
if (dirty) {
const obj = byAgent.get(agent) || {};
obj[field] = selected;
byAgent.set(agent, obj);
}
}
}
function updateSaveBar() {
const btn = $('perm-save-all');
if (!btn) return;
// Don't stomp a transient saving/rebuilding label.
if (btn.dataset.busy === '1') return;
const n = collectChanges().length;
btn.disabled = n === 0;
btn.textContent = n === 0 ? 'save all' : `save all (${n} agent${n === 1 ? '' : 's'})`;
}
function clearSaveStatus() {
const note = $('perm-save-note');
if (note) { note.textContent = ''; note.classList.remove('perm-save-err'); }
}
function setSaveNote(text, isErr) {
const note = $('perm-save-note');
if (!note) return;
note.textContent = text;
note.classList.toggle('perm-save-err', !!isErr);
}
async function saveAll() {
const btn = $('perm-save-all');
if (!btn) return;
const changes = collectChanges();
if (!changes.length) return;
btn.dataset.busy = '1';
btn.disabled = true;
btn.textContent = 'saving…';
clearSaveStatus();
try {
const r = await fetch('/api/permissions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ changes }),
});
if (!r.ok) {
const txt = await r.text();
btn.dataset.busy = '';
btn.disabled = false;
btn.textContent = 'save all';
setSaveNote('save failed: ' + (txt || ('http ' + r.status)), true);
updateSaveBar();
return;
}
// Atomic 200: the whole batch landed. Show a rebuilding hint and
// re-fetch both tables once the queue worker has committed — that
// resets baselines (dirty clears) and the bar disables itself.
const n = changes.length;
btn.textContent = 'queued ✓';
setSaveNote(`rebuilding ${n} agent${n === 1 ? '' : 's'}`, false);
setTimeout(() => {
btn.dataset.busy = '';
fetchAndRenderCapabilities();
fetchAndRenderToolGroups();
}, 900);
} catch (err) {
btn.dataset.busy = '';
btn.disabled = false;
btn.textContent = 'save all';
setSaveNote('save failed: ' + String(err), true);
updateSaveBar();
}
}
// Bind the page-level save button once. Called from the dashboard entry
// after the DOM is ready (the button lives in the static permissions
// pane markup, so it exists before any fetch).
export function initPermissions() {
const btn = $('perm-save-all');
if (btn && !btn.dataset.bound) {
btn.dataset.bound = '1';
btn.addEventListener('click', saveAll);
}
}