Files
seismo-relay/tests/test_webapp_device_routing.py
T
serversdownandClaude Opus 5.5 5326e99ac2 fix(sfm): a monitoring MiniMate's call-home says 'stop monitoring first', not 'unknown(0x6E)'
Measured at the bench 2026-11-03 (BE9441): while monitoring, a MiniMate answers
the 0x2C call-home read with its DEVICE-INFO block ('Instantel', 'MiniMate Plus',
its serial) -- as it answers 1A -- and idle again, minutes later, the call-home
block.  SFM writes back only a block it just read, so a monitoring MiniMate's
call-home cannot be changed; the change core already refused (byte 5 read as
'unknown(0x6E)', nothing sent), but said so cryptically.

- minimateplus.protocol.is_call_home_block(raw): the block starts with its own
  length 0x7C and is N (or N + 2) bytes unescaped; the device-info block fails it.
- The Series-3 change raises UnitStateUnknown (409) with 'did not return its
  call-home settings -- a MiniMate answers the call-home read with its
  device-info block while monitoring; stop monitoring first ... nothing sent',
  for a dry run too.  call_home_state returns enabled = None with that reason.
- The page's callHomeRows shows the reason in place of 'Unknown (byte 5 = ...)'.

A blind write while monitoring stays untested on purpose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-03 14:19:19 -05:00

337 lines
19 KiB
Python

"""The SFM page's device-routing rules, run through Node (phase 1c).
sfm/sfm_webapp.html keeps every rule that decides where a request goes, or
whether a series-specific control is live, in one block of pure functions
between `/* <device-routing> */` and `/* </device-routing> */`. This file
extracts that block and runs it in Node -- no browser, no DOM.
The safety rules it pins (agreed with Brian, 2026-10-28):
* a series-specific control follows the unit's own /device/info answer, never
a typed serial alone, and stops counting the moment the serial is edited;
* config and call-home writes stay off for both series until phases 4-5.
"""
from __future__ import annotations
import json
import re
import shutil
import subprocess
from pathlib import Path
import pytest
PAGE = Path(__file__).resolve().parent.parent / "sfm" / "sfm_webapp.html"
STATIC = PAGE.parent / "static"
ROUTING_JS = STATIC / "device_routing.js" # the page's routing rules, loaded by <script src>
PAGE_JS = STATIC / "sfm_webapp.js" # the rest of the page's script
NODE = shutil.which("node")
pytestmark = pytest.mark.skipif(NODE is None, reason="node is not installed; the page-logic tests need it")
EXPORTS = ["seriesFromSerial", "unitQuery", "deviceUrl", "confirmedSeries", "controlsFor", "eventView", "settingsRows", "perIndexLive", "escapeHtml",
"changeSummary", "downloadSummary", "firmwareLabel", "deviceErrorText", "changeErrorText", "serialPanes",
"callHomeRows"]
def _block() -> str:
return ROUTING_JS.read_text()
def run(*cases):
"""Each case is (function name, [args]); returns each result, or {'throws': msg}."""
driver = _block() + """
const __fns = {%s};
const __cases = JSON.parse(require('fs').readFileSync(0, 'utf8'));
process.stdout.write(JSON.stringify(__cases.map(([fn, args]) => {
try { const r = __fns[fn](...args); return r === undefined ? null : r; }
catch (e) { return {throws: String(e.message || e)}; }
})));
""" % ", ".join(EXPORTS)
out = subprocess.run([NODE, "-e", driver], input=json.dumps(cases), capture_output=True,
text=True, timeout=30)
assert out.returncode == 0, out.stderr
return json.loads(out.stdout)
S3 = {"serial": "BE9441", "host": "h", "tcpPort": 9034}
S4 = {"serial": "UM20147", "host": "h", "tcpPort": 9034}
BLANK = {"serial": "", "host": "h", "tcpPort": 9034}
def test_series_from_serial():
assert run(["seriesFromSerial", ["UM20147"]], ["seriesFromSerial", [" be9441 "]],
["seriesFromSerial", ["BA123"]], ["seriesFromSerial", ["BE"]],
["seriesFromSerial", ["XX1"]], ["seriesFromSerial", [""]]) == [4, 3, 3, None, None, None]
def test_unit_query():
assert run(["unitQuery", [{"serial": " be9441 ", "host": "h", "tcpPort": 9034}]],
["unitQuery", [BLANK]],
["unitQuery", [{"serial": "", "host": "a&b", "tcpPort": 1}]]) == [
"serial=BE9441&host=h&tcp_port=9034", "host=h&tcp_port=9034", "host=a%26b&tcp_port=1"]
def test_device_url():
r = run(["deviceUrl", ["info", S3]], ["deviceUrl", ["status", S4]],
["deviceUrl", ["hangup", S4]], ["deviceUrl", ["settings", BLANK]],
["deviceUrl", ["download", S3, {"event_id": "BE9441:01110000:20261026"}]],
["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]])
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"}
assert r[3] is None
assert r[4] == {"method": "POST", "path": "/device/events/download?serial=BE9441&host=h&tcp_port=9034"
"&event_id=BE9441%3A01110000%3A20261026"}
assert r[5] == {"method": "POST", "path": "/device/monitor/start?serial=UM20147&host=h&tcp_port=9034"}
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[10]
assert r[11] is None and r[12] is None
def _with(unit, confirmed):
return {**unit, "confirmed": confirmed}
def test_controls_typed_serial_is_not_confirmation():
c = run(["controlsFor", [_with(S3, None)]])[0]
assert c["diagnostics"] is False and c["startStop"] is False and c["hangup"] is False
def test_controls_confirmed_series3():
c = run(["controlsFor", [_with(S3, {"serial": "BE9441", "series": 3})]])[0]
assert (c["diagnostics"], c["callHomeRead"], c["startStop"], c["hangup"]) == (True, True, True, False)
def test_controls_confirmed_series4():
c = run(["controlsFor", [_with(S4, {"serial": "UM20147", "series": 4})]])[0]
# phase 4: by serial a Micromate's call-home reads through /device/call_home/state
assert (c["hangup"], c["startStop"], c["diagnostics"], c["callHomeRead"]) == (True, True, False, True)
def test_controls_confirmation_drops_when_the_serial_changes():
unit = {**S3, "serial": "BE9442", "confirmed": {"serial": "BE9441", "series": 3}}
c = run(["controlsFor", [unit]], ["confirmedSeries", [unit]])
assert c[1] is None
assert not any(c[0][k] for k in ("startStop", "hangup", "diagnostics", "callHomeRead"))
def test_controls_a_legacy_identify_confirms_without_a_typed_serial():
unit = _with(BLANK, {"serial": "BE9441", "series": 3})
c, s = run(["controlsFor", [unit]], ["confirmedSeries", [unit]])
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():
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)",
"callHomeWrite": "By serial: use Call-home On / Off (audited). Other call-home "
"fields wait for the THOR round."}
def test_change_summary():
base = {"action": "start monitoring", "state_before": "idle", "state_after": "monitoring",
"audit_id": "cb540970-5e17-415d-b902-4b8343186494",
"plan": {"steps": [{"sub": "0x96"}]}}
r = run(["changeSummary", [{**base, "outcome": "dry_run", "verified": "not_checked"}]],
["changeSummary", [{**base, "outcome": "skipped", "verified": "not_checked",
"state_before": "monitoring"}]],
["changeSummary", [{**base, "outcome": "sent", "verified": "ok"}]],
["changeSummary", [{**base, "outcome": "sent", "verified": "mismatch", "state_after": "idle"}]],
["changeSummary", [{**base, "outcome": "failed", "verified": "not_checked"}]])
assert r == ["start monitoring: dry run — would send 0x96",
"start monitoring: already monitoring — nothing sent",
"start monitoring: confirmed — idle → monitoring (audit cb540970)",
"start monitoring: sent, mismatch (audit cb540970)",
"start monitoring: failed, not_checked (audit cb540970)"]
def test_download_summary():
r = run(["downloadSummary", [{"inserted": True, "stored_filename": "K441LTON.900", "filesize": 71106,
"detail": {"check": "a histogram: stored unverified"}}]],
["downloadSummary", [{"inserted": False, "stored_filename": "K441LTOK.R10", "filesize": 60290,
"detail": {"already_stored": True}}]])
assert r == ["stored K441LTON.900, 71106 bytes, check: a histogram: stored unverified",
"already stored — K441LTOK.R10"]
def test_the_block_touches_no_dom():
b = _block()
assert "document" not in b and "fetch(" not in b and "window" not in b
def test_the_page_scripts_parse_together(tmp_path):
"""The page's scripts share one global scope: a syntax slip, or a name declared
in both, breaks the whole page. Joined in load order, they must pass node --check."""
srcs = re.findall(r'<script src="(static/[^"]+)"></script>', PAGE.read_text())
assert srcs == ["static/device_routing.js", "static/sfm_webapp.js"]
js = tmp_path / "page.js"
js.write_text("\n;\n".join((PAGE.parent / s).read_text() for s in srcs))
r = subprocess.run([NODE, "--check", str(js)], capture_output=True, text=True, timeout=30)
assert r.returncode == 0, r.stderr
def test_every_device_url_is_built_by_deviceUrl():
"""One place builds /device/ URLs, so the series rules cannot be bypassed:
outside the device-routing block the page holds no hand-built device path."""
outside = PAGE.read_text() + PAGE_JS.read_text()
hand_built = [m.group(0) for m in re.finditer(r"(`\$\{api\(\)\}/device/[^`]*`|'/device/[^']*'|\"/device/[^\"]*\")", outside)]
assert hand_built == [], hand_built
def test_device_url_puts_an_event_index_in_the_path():
# the legacy per-event routes carry the index in the path, not the query
r = run(["deviceUrl", ["event_waveform", BLANK, {"index": 3}]],
["deviceUrl", ["event_file", S3, {"index": 0}]],
["deviceUrl", ["event_file", S3]])
assert r[0] == {"method": "GET", "path": "/device/event/3/waveform?host=h&tcp_port=9034"}
assert r[1] == {"method": "GET", "path": "/device/event/0/blastware_file?serial=BE9441&host=h&tcp_port=9034"}
assert "throws" in r[2]
def test_event_view_reads_both_event_shapes():
shared = {"event_id": "BE9441:0111f210:20261026170036", "index": 2, "timestamp": "2026-10-26T17:00:36",
"record_type": "histogram", "peak_vector_sum_ips": 1.083,
"peaks_ips": {"tran": 0.25, "vert": 1.08, "long": 0.195}}
legacy = {"index": 0, "timestamp": {"display": "2026-10-26 16:06:37"}, "record_type": "Waveform",
"peak_values": {"tran_in_s": 0.03, "vert_in_s": 0.095, "long_in_s": 0.02,
"peak_vector_sum": 0.1, "micl_psi": 0.0001}}
bare = {"index": 5}
a, b, c = run(["eventView", [shared]], ["eventView", [legacy]], ["eventView", [bare]])
assert a == {"label": "2026-10-26 17:00:36", "title": "histogram",
"peaks": {"tran": 0.25, "vert": 1.08, "long": 0.195, "pvs": 1.083, "micPsi": None}}
assert b == {"label": "2026-10-26 16:06:37", "title": "Waveform",
"peaks": {"tran": 0.03, "vert": 0.095, "long": 0.02, "pvs": 0.1, "micPsi": 0.0001}}
assert c == {"label": "Event 5", "title": "", "peaks": None}
def test_settings_rows_show_unit_settings_with_a_dash_for_null():
full = {"serial": "UM20147", "series": 4, "setup_name": "TMI default", "record_mode": "Waveform",
"sample_rate": 1024, "record_time_s": 2.0, "histogram_interval_s": 900, "geo_trigger_ips": 0.02,
"notes": {"project": "Bench", "client": ""}}
empty = {"serial": "BE9441", "series": 3, "setup_name": None, "record_mode": None, "sample_rate": None,
"record_time_s": None, "histogram_interval_s": None, "geo_trigger_ips": None, "notes": {}}
a, b, c = run(["settingsRows", [full]], ["settingsRows", [empty]],
["settingsRows", [{**empty, "histogram_interval_s": 15}]])
assert a == [["Setup Name", "TMI default"], ["Record Mode", "Waveform"], ["Sample Rate", "1024 sps"],
["Record Time", "2.00 s"], ["Histogram Interval", "15 min"], ["Geo Trigger", "0.0200 in/s"],
["Note: project", "Bench"], ["Note: client", "—"]]
assert b == [["Setup Name", "—"], ["Record Mode", "—"], ["Sample Rate", "—"], ["Record Time", "—"],
["Histogram Interval", "—"], ["Geo Trigger", "—"], ["Notes", "—"]]
assert c[4] == ["Histogram Interval", "15 s"]
def test_the_per_index_routes_follow_the_list_not_the_keyboard():
# the legacy per-index routes (Load / Save / Download / arrow keys) are live
# only for a list loaded without a serial that has events
r = run(["perIndexLive", [{"bySerial": False, "count": 2}]], ["perIndexLive", [{"bySerial": True, "count": 2}]],
["perIndexLive", [{"bySerial": False, "count": 0}]], ["perIndexLive", [{"bySerial": True, "count": 0}]])
assert r == [True, False, False, False]
def test_escape_html_makes_a_unit_string_inert():
r = run(["escapeHtml", ['Bench <b id="x">&\'']], ["escapeHtml", [None]], ["escapeHtml", [42]])
assert r == ["Bench &lt;b id=&quot;x&quot;&gt;&amp;&#39;", "", "42"]
# ── Batch 2 (1c bench polish, 2026-11-02) ─────────────────────────────────────
def test_firmware_label_says_which_line_a_micromate_runs():
# #12: a Micromate's version string is in 0x01, undecoded; its firmware line is known.
r = run(["firmwareLabel", [{"firmware": "S338.17"}]], ["firmwareLabel", [{"firmware_version": "S338.17"}]],
["firmwareLabel", [{"firmware": None, "detail": {"firmware_line": "thor"}}]],
["firmwareLabel", [{"firmware": None, "detail": {"firmware_line": "blastware"}}]],
["firmwareLabel", [{"firmware": None, "detail": {"firmware_line": "unknown"}}]],
["firmwareLabel", [{}]], ["firmwareLabel", [None]])
assert r == ["S338.17", "S338.17", "Thor line (version not read)", "Blastware line (version not read)",
"—", "—", "—"]
HINT = ("the connection opened, so the modem is reachable — another program (THOR or Blastware) may be "
"holding this unit's line, or the unit is busy (e.g. its sensor check)")
def test_a_504_says_another_program_may_hold_the_line():
# #16: measured 2026-10-29 -- while THOR polls a Micromate, SFM's connection is
# accepted and gets 0 bytes, a 504. The hint is not added once a change was sent.
silent = {"detail": "the unit did not answer: no reply"}
sent = {"detail": "start monitoring was sent and acknowledged, but reading the state back failed: x "
"-- audit record c7", "sent": "acknowledged", "audit_id": "c7"}
r = run(["deviceErrorText", [504, silent, S4, "HTTP 504"]], ["deviceErrorText", [504, sent, S4, "HTTP 504"]],
["deviceErrorText", [503, {"detail": "could not connect: refused"}, S4, "HTTP 503"]],
["deviceErrorText", [504, silent, {"serial": "UM20147", "host": "", "tcpPort": 9034}, "HTTP 504"]],
["deviceErrorText", [502, {}, S4, "HTTP 502"]])
assert r == [f"the unit did not answer: no reply — {HINT}", sent["detail"], "could not connect: refused",
"the unit did not answer: no reply", "HTTP 502"]
def test_a_change_that_was_sent_is_not_called_failed():
# #10: a ChangeUnconfirmed body carries `sent`; anything else is a real failure.
sent = {"detail": "start monitoring was sent and acknowledged, but reading the state back failed: x "
"-- audit record c7", "sent": "acknowledged", "audit_id": "c7"}
r = run(["changeErrorText", ["Start monitoring", 504, sent, S3, "HTTP 504"]],
["changeErrorText", ["Stop monitoring", 503, {**sent, "sent": "unknown"}, S3, "HTTP 503"]],
["changeErrorText", ["Start monitoring", 504, {"detail": "the unit did not answer: no reply"}, S3,
"HTTP 504"]],
["changeErrorText", ["Stop monitoring", 409, {"detail": "not BE9441: BE12599 answered"}, S3,
"HTTP 409"]])
assert r[0] == f"Start monitoring not confirmed: {sent['detail']}"
assert r[1] == f"Stop monitoring not confirmed: {sent['detail']}"
assert r[2] == f"Start monitoring failed: the unit did not answer: no reply — {HINT}"
assert r[3] == "Stop monitoring failed: not BE9441: BE12599 answered"
assert not any(x.startswith(("Start monitoring failed", "Stop monitoring failed")) for x in r[:2])
def test_serial_mode_hides_the_legacy_forms():
# #6 / #12: by serial, settings are read-only until phase 5 -- no empty edit
# form, no empty legacy tables; the settings box shows from the start.
r = run(["serialPanes", [True, False]], ["serialPanes", [True, True]], ["serialPanes", [False, False]])
serial = {"configForm": False, "settingsBox": True, "legacyDeviceTables": False,
"callHomeForm": False, "callHomeBox": True}
legacy = {"configForm": True, "settingsBox": False, "settingsPlaceholder": False, "legacyDeviceTables": True,
"callHomeForm": True, "callHomeBox": False}
assert r == [{**serial, "settingsPlaceholder": True}, {**serial, "settingsPlaceholder": False}, legacy]
# ── Call home by serial (phase 4) ─────────────────────────────────────────────
def test_call_home_routes_need_a_serial():
r = run(["deviceUrl", ["call_home_on", BLANK]], ["deviceUrl", ["call_home_on", S4]],
["deviceUrl", ["call_home_off", S3]], ["deviceUrl", ["call_home_state", S4]])
assert r[0] is None
assert r[1] == {"method": "POST", "path": "/device/call_home/enable?serial=UM20147&host=h&tcp_port=9034"}
assert r[2] == {"method": "POST", "path": "/device/call_home/disable?serial=BE9441&host=h&tcp_port=9034"}
assert r[3] == {"method": "GET", "path": "/device/call_home/state?serial=UM20147&host=h&tcp_port=9034"}
def test_call_home_change_needs_a_confirmed_series():
r = run(["controlsFor", [S3]], ["controlsFor", [_with(S3, {"serial": "BE9441", "series": 3})]],
["controlsFor", [_with(S4, {"serial": "UM20147", "series": 4})]],
["controlsFor", [_with(BLANK, {"serial": "BE9441", "series": 3})]])
assert [c["callHomeChange"] for c in r] == [False, True, True, False]
def test_call_home_rows():
r = run(["callHomeRows", [{"enabled": True, "dial_string": "RADIO RING", "series": 4}]],
["callHomeRows", [{"enabled": False, "dial_string": None, "series": 3}]],
["callHomeRows", [{"enabled": None, "dial_string": "RADIO RING", "series": 3,
"detail": {"byte5": "0x07"}}]])
assert r[0] == [["Call-home", "On"], ["Dial string", "RADIO RING"], ["Series", 4]]
assert r[1] == [["Call-home", "Off"], ["Dial string", "—"], ["Series", 3]]
assert r[2][0] == ["Call-home", "Unknown (byte 5 = 0x07)"]
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"]