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

+13
View File
@@ -285,6 +285,19 @@ Read this first when picking the project back up.
menu. ⚠ **Neither series takes a call-home change while monitoring:** a MiniMate
returns its device-info block, and a Micromate acks the write and ignores it.
SFM refuses both up front.
**Phase 5 built 2026-11-03, bench pending:** change a unit's settings by serial,
both series (`POST /device/settings/change`; the Config tab's Preview, then Send).
Spec `docs/superpowers/specs/2026-11-03-sfm-phase5-settings-design.md`.
- 🔑 **A MiniMate's settings block IS Series IV's `0x1A` layout** (measured):
the 1A read assembles to 2,090 bytes headed by N = 2090, and all 11
Blastware compliance writes reproduce from the block before them. One codec
serves both series: `micromate/setup_fields.py`.
- Limits are the units' own, from Instantel's manuals (Brian). A live send
needs its preview's revision; refused up front: monitoring, a Micromate on
its factory setup or whose schedule would load another setup.
- Retired: `/device/config` (410), `apply_config`, `_encode_compliance_config`.
- ⚠ Not yet sent to a unit. The MiniMate alarm level is read-only until a
bench write is checked (`S3_ALARM_WRITE_MEASURED`).
**Ring path measured the same night:** with THOR's watchdog off, a call-home
reaches THOR when nobody holds the line, and **is lost when SFM holds it** --
the unit takes SFM's connection for the call, times out and does not retry.
@@ -1,6 +1,7 @@
# Phase 5: changing a unit's settings by serial (design)
**Date:** 2026-11-03. **Status:** draft for Brian. Phase 5 of
**Date:** 2026-11-03. **Status:** approved by Brian 2026-11-03; built 2026-11-03
(plan `docs/superpowers/plans/2026-11-03-sfm-phase5-settings.md`); bench pending. Phase 5 of
`docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md` (row 10, "change
recording settings"; build phase 5, "setup push: one field first, then several").
**Branch:** `feat/series4-sfm-parity`.
+11 -2
View File
@@ -1020,8 +1020,18 @@
<div id="tab-config" class="tab-pane">
<div id="cfg-settings" style="display:none; margin-bottom:12px">
<div class="cfg-section-title">On the unit (read by serial)</div>
<div class="cfg-section-title" id="cfg-settings-title">On the unit (read by serial)</div>
<div class="dev-table" id="cfg-settings-table"></div>
<!-- Phase 5: change the unit's settings by serial -- Preview, then Send (audited, read back). -->
<div class="cfg-section-title" id="cfg-edit-title" hidden>Change settings on this unit</div>
<div class="cfg-grid" id="cfg-edit" hidden></div>
<div class="cfg-actions" id="cfg-edit-actions" hidden>
<button class="btn btn-ghost" id="cfg-preview-btn" disabled>Preview</button>
<button class="btn btn-success" id="cfg-send-btn" disabled>Send to Unit</button>
<span id="cfg-edit-note"></span>
</div>
<div class="dev-table" id="cfg-preview"></div>
<div class="dev-table" id="cfg-result"></div>
</div>
<div class="cfg-grid" id="cfg-form">
@@ -1129,7 +1139,6 @@
<div class="cfg-actions">
<button class="btn btn-ghost" id="cfg-read-btn" onclick="readConfig()" disabled>Read from Device</button>
<button class="btn btn-success" id="cfg-write-btn" onclick="writeConfig()" disabled>Write to Device</button>
<button class="btn btn-ghost" onclick="clearConfigForm()">Clear Form</button>
<span id="cfg-status"></span>
</div>
+62 -3
View File
@@ -47,7 +47,7 @@ const DEVICE_ROUTES = {
call_home_state: ['GET', '/device/call_home/state', true],
call_home_on: ['POST', '/device/call_home/enable', true],
call_home_off: ['POST', '/device/call_home/disable', true],
config_write: ['POST', '/device/config', false],
settings_change: ['POST', '/device/settings/change', true],
event_waveform: ['GET', '/device/event/{index}/waveform', false],
event_file: ['GET', '/device/event/{index}/blastware_file', false],
};
@@ -88,9 +88,9 @@ function controlsFor(unit) {
// by host, the legacy read is Series 3's; by serial, both series (phase 4)
callHomeRead: series === 3 || (serialMode && series === 4),
callHomeChange: serialMode && (series === 3 || series === 4),
configWrite: false,
configWrite: serialMode && (series === 3 || series === 4),
callHomeWrite: false,
reasons: { configWrite: 'Coming in phase 5 (#46)',
reasons: { configWrite: 'By serial only: Preview, then Send (audited).',
callHomeWrite: 'By serial: use Call-home On / Off (audited). Other call-home fields wait for the THOR round.' },
};
}
@@ -101,6 +101,15 @@ function changeSummary(body) {
const subs = ((body.plan || {}).steps || []).map(s => s.sub).join(', ');
return `${body.action}: dry run — would send ${subs}`;
}
if (body.action === 'change settings') { // phase 5: the state is a read-back verdict
if (body.outcome === 'skipped') return 'change settings: the unit already holds these — nothing sent';
if (body.outcome === 'sent' && body.verified === 'ok') {
return `change settings: confirmed — the unit holds what was sent (audit ${id8})`;
}
if (body.verified === 'mismatch') {
return `change settings: sent, but the unit reads ${body.state_after} — see what it holds (audit ${id8})`;
}
}
if (body.outcome === 'skipped') return `${body.action}: already ${body.state_before} — nothing sent`;
if (body.outcome === 'sent' && body.verified === 'ok') {
return `${body.action}: confirmed — ${body.state_before} → ${body.state_after} (audit ${id8})`;
@@ -209,4 +218,54 @@ function callHomeRows(state) {
: d.reason || `Unknown (byte 5 = ${d.byte5 ?? '?'})`;
return [['Call-home', sw], ['Dial string', s.dial_string || '—'], ['Series', s.series]];
}
// ── The Config tab's edit form, by serial (phase 5) ──────────────────────────
// The fields the server says this unit can change, in its order, with their
// limits (UnitSettings.detail.editable).
function settingsFormFields(st) {
return (((st || {}).detail || {}).editable || []).map(f => ({ ...f }));
}
// Only what the operator changed, typed as the server expects. Numbers compare
// as numbers (0.30 is 0.3); a number that does not parse is left out (the
// preview shows exactly what would change); read-only fields never count.
function settingsChanges(fields, edited) {
const out = {};
const e = edited || {};
for (const f of fields || []) {
if (f.readonly || !(f.field in e)) continue;
let v = e[f.field];
if (f.kind === 'number' || (f.kind === 'choice' && typeof f.value === 'number')) {
if (v === '' || v == null) continue;
v = Number(v);
if (!Number.isFinite(v) || v === Number(f.value)) continue;
} else if (f.kind === 'bool') {
v = Boolean(v);
if (v === Boolean(f.value)) continue;
} else {
v = String(v);
if (v === String(f.value == null ? '' : f.value)) continue;
}
out[f.field] = v;
}
return out;
}
const _dash = v => (v == null || v === '' ? '—' : v);
// A preview (dry run): one row per field, [label, the unit holds, it would get].
function settingsPreviewRows(body) {
return Object.values(((body || {}).plan || {}).fields || {}).map(r => [r.label, _dash(r.old), _dash(r.new)]);
}
// Why a preview would not be sent ('' when nothing blocks it).
function settingsBlockedText(body) {
return (((body || {}).plan || {}).blocked || []).join('; ');
}
// After a send: [label, the unit held, SFM sent, the unit now holds].
function settingsResultRows(body) {
const fields = ((((body || {}).detail || {}).snapshot || {}).fields) || {};
return Object.values(fields).map(r => [r.label, _dash(r.old), _dash(r.new), _dash(r.now)]);
}
/* </device-routing> */
+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
+71 -6
View File
@@ -29,7 +29,8 @@ pytestmark = pytest.mark.skipif(NODE is None, reason="node is not installed; the
EXPORTS = ["seriesFromSerial", "unitQuery", "deviceUrl", "confirmedSeries", "controlsFor", "eventView", "settingsRows", "perIndexLive", "escapeHtml",
"changeSummary", "downloadSummary", "firmwareLabel", "deviceErrorText", "changeErrorText", "serialPanes",
"callHomeRows"]
"callHomeRows", "settingsFormFields", "settingsChanges",
"settingsPreviewRows", "settingsBlockedText", "settingsResultRows"]
def _block() -> str:
@@ -77,7 +78,8 @@ def test_device_url():
["deviceUrl", ["start", S4]], ["deviceUrl", ["stop", S3]],
["deviceUrl", ["erase", S3]], ["deviceUrl", ["call_home_read", BLANK]],
["deviceUrl", ["config_write", S3]], ["deviceUrl", ["nonsense", S3]],
["deviceUrl", ["download", BLANK, {"event_id": "x"}]], ["deviceUrl", ["hangup", BLANK]])
["deviceUrl", ["download", BLANK, {"event_id": "x"}]], ["deviceUrl", ["hangup", BLANK]],
["deviceUrl", ["settings_change", S4, {"dry_run": "true"}]], ["deviceUrl", ["settings_change", BLANK]])
assert r[0] == {"method": "GET", "path": "/device/info?serial=BE9441&host=h&tcp_port=9034"}
assert r[1] == {"method": "GET", "path": "/device/monitor/status?serial=UM20147&host=h&tcp_port=9034"}
assert r[2] == {"method": "POST", "path": "/device/hangup?host=h&tcp_port=9034"}
@@ -88,9 +90,12 @@ def test_device_url():
assert r[6] == {"method": "POST", "path": "/device/monitor/stop?serial=BE9441&host=h&tcp_port=9034"}
assert r[7] == {"method": "POST", "path": "/device/events/erase?serial=BE9441&host=h&tcp_port=9034"}
assert r[8] == {"method": "GET", "path": "/device/call_home?host=h&tcp_port=9034"}
assert r[9] == {"method": "POST", "path": "/device/config?serial=BE9441&host=h&tcp_port=9034"}
assert "throws" in r[9] # /device/config is retired (phase 5)
assert "throws" in r[10]
assert r[11] is None and r[12] is None
assert r[13] == {"method": "POST", "path": "/device/settings/change?serial=UM20147&host=h&tcp_port=9034"
"&dry_run=true"}
assert r[14] is None # by serial only
def _with(unit, confirmed):
@@ -126,13 +131,62 @@ def test_controls_a_legacy_identify_confirms_without_a_typed_serial():
assert s == 3 and c["diagnostics"] is True and c["startStop"] is False # start/stop needs a serial
def test_controls_config_waits_for_phase_5_and_the_legacy_call_home_form_stays_off():
def test_controls_config_write_is_by_serial_for_both_series():
for unit in (_with(S3, {"serial": "BE9441", "series": 3}), _with(S4, {"serial": "UM20147", "series": 4})):
c = run(["controlsFor", [unit]])[0]
assert c["configWrite"] is False and c["callHomeWrite"] is False
assert c["reasons"] == {"configWrite": "Coming in phase 5 (#46)",
assert c["configWrite"] is True and c["callHomeWrite"] is False
assert c["reasons"] == {"configWrite": "By serial only: Preview, then Send (audited).",
"callHomeWrite": "By serial: use Call-home On / Off (audited). Other call-home "
"fields wait for the THOR round."}
c = run(["controlsFor", [_with(BLANK, {"serial": "BE9441", "series": 3})]])[0]
assert c["configWrite"] is False # by host: the legacy form is read-only
EDITABLE = [
{"field": "record_mode", "label": "Record mode", "kind": "choice", "value": "histogram",
"choices": [{"value": "histogram", "label": "Histogram"}, {"value": "waveform", "label": "Waveform"}]},
{"field": "sample_rate", "label": "Sample rate", "kind": "choice", "value": 1024, "unit": "sps",
"choices": [{"value": 1024, "label": "1024 sps"}, {"value": 4096, "label": "4096 sps"}]},
{"field": "geo_trigger_ips", "label": "Geophone trigger", "kind": "number", "value": 0.3,
"unit": "in/s", "min": 0.005, "max": 10.0, "step": 0.001},
{"field": "geo_alarm_ips", "label": "Geophone alarm", "kind": "number", "value": 1.0, "readonly": True},
{"field": "job_number_shown", "label": "Job number on report", "kind": "bool", "value": False},
{"field": "note_1", "label": "Project", "kind": "text", "value": "Bridge", "maxlength": 41},
]
def test_settings_form_fields_come_from_the_servers_list_in_order():
(f,) = run(["settingsFormFields", [{"detail": {"editable": EDITABLE}}]])
assert [x["field"] for x in f] == [e["field"] for e in EDITABLE]
assert f[2] == EDITABLE[2] and f[3]["readonly"] is True
assert run(["settingsFormFields", [{"detail": {}}]]) == [[]]
def test_settings_changes_are_only_what_differs():
same = {"record_mode": "histogram", "sample_rate": "1024", "geo_trigger_ips": "0.30",
"geo_alarm_ips": "2.0", "job_number_shown": False, "note_1": "Bridge"}
edited = {**same, "sample_rate": "4096", "geo_trigger_ips": "0.25", "job_number_shown": True,
"note_1": "Bridge 2"}
a, b = run(["settingsChanges", [EDITABLE, same]], ["settingsChanges", [EDITABLE, edited]])
assert a == {} # 0.30 == 0.3; the read-only alarm is ignored
assert b == {"sample_rate": 4096, "geo_trigger_ips": 0.25, "job_number_shown": True, "note_1": "Bridge 2"}
PREVIEW = {"outcome": "dry_run", "plan": {
"fields": {"geo_trigger_ips": {"label": "Geophone trigger", "old": 0.5, "new": 0.3},
"note_1": {"label": "Project", "old": "", "new": "Bridge"}},
"blocked": ["this unit's schedule loads other.mmb at 07:00, which would replace this change"],
"revision": "0123456789abcdef"}}
RESULT = {"outcome": "sent", "verified": "ok", "detail": {"snapshot": {"fields": {
"geo_trigger_ips": {"label": "Geophone trigger", "old": 0.5, "new": 0.3, "now": 0.3}}}}}
def test_settings_preview_result_and_blocked_text():
rows, blocked, none, result = run(["settingsPreviewRows", [PREVIEW]], ["settingsBlockedText", [PREVIEW]],
["settingsBlockedText", [RESULT]], ["settingsResultRows", [RESULT]])
assert rows == [["Geophone trigger", 0.5, 0.3], ["Project", "—", "Bridge"]]
assert "other.mmb" in blocked and none == ""
assert result == [["Geophone trigger", 0.5, 0.3, 0.3]]
def test_change_summary():
@@ -334,3 +388,14 @@ def test_call_home_rows_say_why_a_switch_did_not_read():
r = run(["callHomeRows", [{"enabled": None, "dial_string": None, "series": 3,
"detail": {"byte5": "0x6E", "reason": "not readable while monitoring -- stop it first"}}]])
assert r[0][0] == ["Call-home", "not readable while monitoring -- stop it first"]
def test_change_summary_for_settings_says_it_plainly():
base = {"action": "change settings", "audit_id": "cb540970-5e17", "state_before": "unchanged"}
ok, skip, mism = run(
["changeSummary", [{**base, "outcome": "sent", "verified": "ok", "state_after": "as asked"}]],
["changeSummary", [{**base, "outcome": "skipped", "verified": "not_checked", "state_before": "as asked"}]],
["changeSummary", [{**base, "outcome": "failed", "verified": "mismatch", "state_after": "differs"}]])
assert ok == "change settings: confirmed — the unit holds what was sent (audit cb540970)"
assert skip == "change settings: the unit already holds these — nothing sent"
assert "unit reads differs" in mism and "cb540970" in mism
+14
View File
@@ -57,3 +57,17 @@ def test_the_page_scripts_are_served_from_static(name):
def test_a_missing_static_file_is_a_404():
assert _get("/static/nope.js")[0] == 404
def test_the_config_write_is_the_audited_preview_and_send():
# Phase 5: the legacy by-host "Write to Device" is gone; the serial-mode edit
# form's Preview and Send are wired from sfm_webapp.js, not inline handlers.
html = PAGE.read_text()
assert 'id="cfg-write-btn"' not in html
for el in ("cfg-edit", "cfg-preview-btn", "cfg-send-btn", "cfg-preview", "cfg-result"):
tag = re.search(r'<[^>]*id="%s"[^>]*>' % el, html)
assert tag is not None and "onclick" not in tag.group(0), el
js = (PAGE.parent / "static" / "sfm_webapp.js").read_text()
assert "config_write" not in js and "function writeConfig" not in js
assert "getElementById('cfg-preview-btn').addEventListener" in js
assert "getElementById('cfg-send-btn').addEventListener" in js