feat(webapp): edit a unit's settings by serial: preview, send, read back

The Config tab by serial is now the unit's edit form, headed 'On the
unit <serial> -- read HH:MM' and built from the server's editable
fields.  Preview runs a dry run and shows old -> new, notes and anything
that blocks the change; Send (confirm) sends exactly what was previewed,
with its revision, then shows what the unit now holds and re-reads it.
An edit after a preview disables Send until the next preview.  The
by-host form loses its write button; the read stays.  Logic in
device_routing.js (Node-tested), glue in sfm_webapp.js, no inline JS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-03 21:57:17 -05:00
1 parent e8eabee4a2
commit 385716d8e1
7 files changed
+351 -77

No files matched your search

+178 -65
View File
@@ -90,8 +90,7 @@ function applyControls() {
badge.textContent = series ? `Series ${series}` : '';
document.getElementById('hangup-btn').hidden = !c.hangup;
setDiagButtonsEnabled(c.diagnostics);
const cw = document.getElementById('cfg-write-btn');
cw.disabled = !c.configWrite; cw.title = c.reasons.configWrite;
updateSettingsButtons();
const hw = document.getElementById('ch-write-btn');
hw.disabled = !c.callHomeWrite; hw.title = c.reasons.callHomeWrite;
const chr = document.getElementById('ch-read-btn');
@@ -163,18 +162,24 @@ async function changeCallHome(on) {
await readCallHomeBySerial({ quiet: true });
}
// The Config tab by serial (#6): settings are read-only until phase 5, so the
// empty legacy edit form stays hidden and the settings box shows from the start.
// A different unit's settings are never left on screen.
// The Config tab by serial (#6; phase 5): the settings box shows from the start
// and the empty legacy form stays hidden. A different unit's settings, form,
// preview or result are never left on screen.
let settingsShownFor = null;
let settingsShown = null; // the UnitSettings the edit form was built from
let settingsPreview = null; // {serial, changes (JSON), revision, blocked}: what a Send would send
function applyConfigPanes() {
const serial = normSerial(currentUnit().serial);
const p = serialPanes(Boolean(serial), Boolean(serial) && settingsShownFor === serial);
document.getElementById('cfg-form').style.display = p.configForm ? '' : 'none';
document.getElementById('cfg-settings').style.display = p.settingsBox ? 'block' : 'none';
if (p.settingsPlaceholder) {
settingsShownFor = null;
settingsShownFor = null; settingsShown = null; settingsPreview = null;
renderTextTable('cfg-settings-table', [['Settings', 'Not read yet — press Read from Device']]);
document.getElementById('cfg-settings-title').textContent = 'On the unit (read by serial)';
for (const id of ['cfg-edit-title', 'cfg-edit', 'cfg-edit-actions']) document.getElementById(id).hidden = true;
renderTextTable('cfg-preview', []);
renderTextTable('cfg-result', []);
}
}
@@ -783,25 +788,185 @@ function clearConfigForm() {
setCfgStatus('');
}
// Serial mode: the shared UnitSettings, read-only (writes wait for phase 5).
async function readSettingsBySerial() {
// Serial mode: the shared UnitSettings, and the form to change them (phase 5).
// `quiet`: the re-read after a send -- the send's own result stays on screen.
async function readSettingsBySerial({ quiet = false } = {}) {
const btn = document.getElementById('cfg-read-btn');
btn.disabled = true;
setCfgStatus('Reading settings from the unit…');
if (!quiet) setCfgStatus('Reading settings from the unit…');
try {
const st = await deviceFetch('settings');
renderTextTable('cfg-settings-table', settingsRows(st));
settingsShownFor = normSerial(st.serial);
settingsShown = st;
settingsPreview = null;
document.getElementById('cfg-settings-title').textContent =
`On the unit ${st.serial} — read ${new Date().toTimeString().slice(0, 5)}`;
renderSettingsForm(st);
renderTextTable('cfg-preview', []);
if (!quiet) renderTextTable('cfg-result', []);
document.getElementById('cfg-settings').style.display = 'block';
document.getElementById('cfg-form').style.display = 'none';
setCfgStatus(`Settings read from ${st.serial}.`, 'ok');
if (!quiet) setCfgStatus(`Settings read from ${st.serial}.`, 'ok');
} catch (e) {
setCfgStatus(`Read failed: ${e.message}`, 'error');
if (!quiet) setCfgStatus(`Read failed: ${e.message}`, 'error');
else renderTextTable('cfg-preview', [['Re-read', `failed: ${e.message}`]]);
} finally {
btn.disabled = false;
updateSettingsButtons();
}
}
// ── Changing settings by serial (phase 5) ─────────────────────────────────────
function settingsInput(f) {
let el;
if (f.kind === 'choice') {
el = document.createElement('select');
for (const c of f.choices || []) {
const o = document.createElement('option');
o.value = String(c.value); o.textContent = c.label;
el.appendChild(o);
}
el.value = String(f.value);
} else if (f.kind === 'bool') {
el = document.createElement('input');
el.type = 'checkbox'; el.checked = Boolean(f.value);
} else {
el = document.createElement('input');
el.type = f.kind === 'number' ? 'number' : 'text';
if (f.kind === 'number') {
el.step = f.step != null ? String(f.step) : 'any';
if (f.min != null) el.min = String(f.min);
if (f.max != null) el.max = String(f.max);
}
if (f.maxlength) el.maxLength = f.maxlength;
el.value = f.value == null ? '' : String(f.value);
}
el.id = `cfg-f-${f.field}`;
el.dataset.field = f.field;
el.disabled = Boolean(f.readonly);
if (f.readonly) el.title = 'Shown, not changed yet';
el.addEventListener(f.kind === 'text' || f.kind === 'number' ? 'input' : 'change', settingsEdited);
return el;
}
function renderSettingsForm(st) {
const box = document.getElementById('cfg-edit');
box.innerHTML = '';
for (const f of settingsFormFields(st)) {
const wrap = document.createElement('div');
wrap.className = 'cfg-field';
const label = document.createElement('label');
label.textContent = f.unit ? `${f.label} (${f.unit})` : f.label;
label.htmlFor = `cfg-f-${f.field}`;
wrap.append(label, settingsInput(f));
box.appendChild(wrap);
}
for (const id of ['cfg-edit-title', 'cfg-edit', 'cfg-edit-actions']) document.getElementById(id).hidden = false;
}
function editedSettings() {
const out = {};
for (const el of document.querySelectorAll('#cfg-edit [data-field]')) {
out[el.dataset.field] = el.type === 'checkbox' ? el.checked : el.value;
}
return out;
}
function currentSettingsChanges() {
return settingsShown ? settingsChanges(settingsFormFields(settingsShown), editedSettings()) : {};
}
// Any edit after a preview: the preview no longer covers what Send would send.
function settingsEdited() {
settingsPreview = null;
renderTextTable('cfg-preview', []);
updateSettingsButtons();
}
function updateSettingsButtons() {
const c = controlsFor(currentUnit());
const serial = normSerial(currentUnit().serial);
const shown = Boolean(settingsShown) && normSerial(settingsShown.serial) === serial;
const changes = shown ? currentSettingsChanges() : {};
const preview = document.getElementById('cfg-preview-btn');
preview.disabled = !(c.configWrite && shown && Object.keys(changes).length) || changeInFlight;
preview.title = c.reasons.configWrite;
const ready = Boolean(settingsPreview) && settingsPreview.serial === serial && !settingsPreview.blocked
&& settingsPreview.changes === JSON.stringify(changes);
document.getElementById('cfg-send-btn').disabled = !(c.configWrite && ready) || changeInFlight;
}
function postSettingsChange(changes, { dryRun, revision }) {
return deviceRequest('settings_change', dryRun ? { dry_run: 'true' } : {}, {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(revision ? { changes, revision } : { changes }),
});
}
// A dry run: SFM re-reads the unit and says what would change. Nothing is sent.
async function previewSettings() {
const changes = currentSettingsChanges();
const serial = normSerial(currentUnit().serial);
renderTextTable('cfg-result', []);
setCfgStatus('Previewing — reading the unit…');
try {
const r = await postSettingsChange(changes, { dryRun: true });
const body = await r.json().catch(() => ({}));
if (!r.ok) {
setCfgStatus(changeErrorText('Preview', r.status, body, currentUnit(), r.statusText), 'error');
return;
}
const blocked = settingsBlockedText(body);
renderTextTable('cfg-preview', [
...settingsPreviewRows(body).map(([label, old, now]) => [label, `${old} → ${now}`]),
...((body.plan || {}).warnings || []).map(w => ['Note', w]),
...(blocked ? [['Will not send', blocked]] : []),
]);
settingsPreview = { serial, changes: JSON.stringify(changes), revision: (body.plan || {}).revision,
blocked: Boolean(blocked) };
setCfgStatus(blocked ? 'Preview: this change cannot be sent (see above). Nothing was sent.'
: 'Preview ready — nothing sent yet. Check it, then Send to Unit.',
blocked ? 'error' : 'ok');
} catch (e) {
setCfgStatus(`Preview failed: ${e.message}`, 'error');
} finally {
updateSettingsButtons();
}
}
// One audited send, never retried; the body says what the unit now holds.
async function sendSettings() {
const p = settingsPreview;
if (!p) return;
const changes = JSON.parse(p.changes);
const names = settingsFormFields(settingsShown).filter(f => f.field in changes).map(f => f.label);
if (!confirm(`Send these changes to ${p.serial}?\n\n${names.join('\n')}`)) return;
changeInFlight = true; applyControls();
setCfgStatus(`Sending to ${p.serial}…`);
let body = {};
try {
const r = await postSettingsChange(changes, { dryRun: false, revision: p.revision });
body = await r.json().catch(() => ({}));
if (body.outcome) {
renderTextTable('cfg-result', settingsResultRows(body).map(
([label, old, sent, now]) => [label, `${old} → ${sent} · the unit now holds ${now}`]));
setCfgStatus(changeSummary(body), r.ok ? 'ok' : 'error');
} else {
setCfgStatus(changeErrorText('Change settings', r.status, body, currentUnit(), r.statusText), 'error');
}
} catch (e) {
// No reply is not "nothing sent": the request may have reached the unit.
setCfgStatus(`Change settings: no reply from SFM (${e.message}) — it may have been sent; `
+ 'read the unit\'s settings and GET /db/device_commands', 'error');
}
settingsPreview = null;
renderTextTable('cfg-preview', []);
changeInFlight = false; applyControls();
if (body.outcome) await readSettingsBySerial({ quiet: true });
}
async function readConfig() {
if (!devHost()) { setCfgStatus('Not connected.', 'error'); return; }
if (serialMode()) { await readSettingsBySerial(); return; }
@@ -822,60 +987,6 @@ async function readConfig() {
}
}
async function writeConfig() {
if (!devHost()) { setCfgStatus('Not connected.', 'error'); return; }
// Build body — only include fields that have values
const body = {};
const rm = qs('cfg-recording-mode').value;
if (rm !== '') body.recording_mode = parseInt(rm, 10);
const sr = qs('cfg-sample-rate').value;
if (sr) body.sample_rate = parseInt(sr, 10);
const hi = qs('cfg-histogram-interval').value;
if (hi !== '') body.histogram_interval_sec = parseInt(hi, 10);
const rt = qs('cfg-record-time').value;
if (rt) body.record_time = parseFloat(rt);
const trig = qs('cfg-trigger').value;
if (trig) body.trigger_level_geo = parseFloat(trig);
const alarm = qs('cfg-alarm').value;
if (alarm) body.alarm_level_geo = parseFloat(alarm);
const gr = qs('cfg-geo-range').value;
if (gr !== '') body.geo_range = parseInt(gr, 10);
const proj = qs('cfg-project').value.trim();
if (proj) body.project = proj;
const cli = qs('cfg-client').value.trim();
if (cli) body.client_name = cli;
const op = qs('cfg-operator').value.trim();
if (op) body.operator = op;
const sl = qs('cfg-seis-loc').value.trim();
if (sl) body.seis_loc = sl;
const notes = qs('cfg-notes').value.trim();
if (notes) body.notes = notes;
if (Object.keys(body).length === 0) {
setCfgStatus('No fields to write — fill in at least one field.', 'error');
return;
}
const fieldsStr = Object.keys(body).join(', ');
setCfgStatus(`Writing ${Object.keys(body).length} field(s)…`);
document.getElementById('cfg-write-btn').disabled = true;
try {
await deviceFetch('config_write', {}, {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
setCfgStatus(`Written: ${fieldsStr}`, 'ok');
// Re-read device info so Device tab and bar refresh
await readConfig();
} catch(e) {
setCfgStatus(`Write failed: ${e.message}`, 'error');
} finally {
document.getElementById('cfg-write-btn').disabled = false;
}
}
// ── Call Home form ─────────────────────────────────────────────────────────────
function setChStatus(msg, type) {
const el = document.getElementById('ch-status');
@@ -2339,6 +2450,8 @@ for (const id of ['dev-serial', 'dev-host', 'dev-port']) {
// New controls are wired here, not with onclick= in the HTML (no inline JS).
document.getElementById('ch-on-btn').addEventListener('click', () => changeCallHome(true));
document.getElementById('ch-off-btn').addEventListener('click', () => changeCallHome(false));
document.getElementById('cfg-preview-btn').addEventListener('click', previewSettings);
document.getElementById('cfg-send-btn').addEventListener('click', sendSettings);
applyControls();
// Reflect any persisted mic-unit preference in the header pill on load