Files
seismo-relay/docs/superpowers/plans/2026-10-28-sfm-phase1c-webapp.md
T

19 KiB
Raw Blame History

SFM phase 1c — the webapp on the serial-based endpoints, plus wrong-series safeguards

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: The SFM standalone page (sfm/sfm_webapp.html) drives both series through the serial-based device endpoints. In addition, no MiniMate-only write or erase can reach a unit that has not identified itself as Series 3.

Architecture:

  • Server: one helper refuses the legacy Series-3 write/erase routes unless the unit's own serial (read on the same connection) says Series 3.
  • Page: the series routing and button rules live in a marked block of pure functions, tested through Node. The DOM wiring calls those functions and nothing else to build a /device/ URL or decide a button's state.

Tech Stack: Python 3.10 / FastAPI (sfm/server.py), vanilla JS in one HTML file, pytest. Node 20 (~/.local/bin/node) runs the page-logic tests.

Spec: docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md covers "The webapp", "Scope: the parity table" rows 1–5 and 7, and "Build phases" 1c. The design agreed with Brian on 2026-10-28 is recorded in the Global Constraints below.

Global Constraints

  • Work in worktree ~/seismo-relay-parity, on branch feat/series4-sfm-parity. Never commit to main. Check with git branch --show-current before every commit.
  • Run tests with /home/serversdown/seismo-relay/.venv/bin/python -m pytest -q -p no:cacheprovider. The baseline is 16 known failures (15 in test_bw_ascii_report.py, 1 in test_event_file_io.py). Read the failure list before committing. A pytest | tail exits 0.
  • Serial optional: with a serial, the Live tabs use the serial-based endpoints: /device/info, /device/monitor/status, /device/settings, /device/events, POST /device/events/download, and POST /device/monitor/start|stop (all with serial=), plus POST /device/hangup?host=&tcp_port=. With the serial blank, every read behaves exactly as today.
  • Series comes from the unit's reply. The badge and every series-specific control follow the series field of the last /device/info reply, and only if its serial equals the typed one. A typed serial alone never enables a series-specific control.
  • Write buttons:
    • Start/stop use the audited serial path for both series.
    • Config write and Call-Home write are disabled for both series. Their tooltips read exactly "Coming in phase 5 (#46)" and "Coming in phase 4".
    • Diagnostics (erase, rescue, slow drip, blind stop) is enabled only when the confirmed series is 3.
    • Hang up is shown only when the confirmed series is 4.
  • Start feedback: while a start is in flight, show "Starting — the unit runs its sensor check first (about 35 s)". The legacy 60-second _pollMonitorConfirm loop is not used in serial mode.
  • Results are reported as SFM returned them: outcome, verified, state before → after, and the first 8 characters of the audit id. HTTP error detail strings are shown verbatim.
  • Speed (Brian): no new request may be added to a path unless the plan says why. The server identity check reuses the serial that connect() already reads. On rescue and POST /device/call_home it adds exactly one SUB 0x15 read.
  • No codec, store or DB change. The legacy /device/* routes keep their URLs and parameters (a new optional serial is added).

Review Focus

  1. A typed BE… serial at an address that holds a Micromate. The server must refuse every guarded route with 409 and send no write. In the page, Diagnostics stays disabled until /device/info answers Series 3. Pinned by Task 1 (test_guarded_route_refuses_a_unit_that_answers_as_series4) and Task 2 (controls: typed serial is not confirmation).
  2. The serial is edited after a successful identify. The confirmation must stop counting the moment the typed serial no longer matches. Pinned by Task 2 (controls: confirmation drops when the serial changes).
  3. Lower-case or space-padded serials (" be9441 ") are normalised the same way the server normalises them. Pinned by Task 2 (seriesFromSerial and unitQuery cases).
  4. A start that times out (504) or reads back a mismatch (409). The page must show the server's detail and the audit id, never "started". Pinned by Task 2 (changeSummary cases for failed/mismatch) and Task 5 (an error-path render).
  5. A download that is already stored (inserted: false) is reported as "already stored" and still opens the stored event. Pinned by Task 2 (downloadSummary).

Task 1: Server — legacy Series-3 writes refuse a unit that isn't Series 3

Files:

  • Modify: sfm/server.py:
    • device_config (~1107), device_events_erase (~1427), device_rescue (~1763), the device_call_home POST (~2066);
    • device_config_project passes serial through.
  • Modify: minimateplus/client.py: add MiniMateClient.read_serial().
  • Test: create tests/test_server_series3_guard.py.

Interfaces:

  • Produces: MiniMateClient.read_serial(self) -> str. Requires an open, polled session. It runs the SUB 0x15 read (self._require_proto().read(SUB_SERIAL_NUMBER)) and returns _decode_serial_number(...).serial.

  • Produces: sfm.server._require_series3(unit_serial: Optional[str], expected: Optional[str]) -> None. It raises HTTPException(409, detail) when either:

    • series_for_serial(unit_serial) is not 3 (an unknown serial counts as not 3), with detail f"the unit at this address answers as {unit_serial!r}, not a Series-3 unit -- nothing sent"; or
    • expected is given and normalise_serial(expected) != normalise_serial(unit_serial), with detail f"the unit at this address is {unit_serial}, not {expected} -- nothing sent".
  • Each guarded route gains serial: Optional[str] = Query(None, description=_SERIAL_DOC). It calls the guard right after it knows the unit's serial, and before its first write:

    • device_config and device_events_erase: info = client.connect() → _require_series3(info.serial, serial);
    • device_rescue and device_call_home (POST): after client.poll() → _require_series3(client.read_serial(), serial).
  • Not guarded, and each gets a one-line comment saying why: legacy monitor/start|stop, stop_monitoring_blind, stop_monitoring_slow_drip, stop_monitoring_spam. They send only 0x96/0x97, which mean the same on both series (measured 2026-10-25/27), and the rescue tools must work on a unit too wedged to answer.

  • Step 1: Write the failing tests in tests/test_server_series3_guard.py. Use monkeypatch.setattr(srv, "_build_client", factory) as tests/test_server_device_access.py:398 does. The fake client records every call:

    • test_guarded_route_refuses_a_unit_that_answers_as_series4[route]: parametrise over the four routes. The fake's connect() returns a DeviceInfo(serial="UM20147"), or its read_serial() returns "UM20147". Assert HTTPException.status_code == 409, and that the recorded calls contain no write method (delete_all_events, apply_config, set_call_home_config, stop_monitoring).
    • test_guarded_route_refuses_a_different_series3_unit: the unit answers "BE9441", the request names serial="BE12599", so the response is 409 with "not BE12599" in the detail.
    • test_guarded_route_proceeds_for_the_named_series3_unit: the unit answers "BE9441" with serial="be9441 " (normalised), and the write method is called once.
    • test_unguarded_stop_routes_send_without_an_identity_read: stop_monitoring_blind (it writes through a bare TcpTransport; stub srv.TcpTransport) sends its stop frames, and nothing builds a client or reads a serial.
  • Step 2: Run them. …pytest tests/test_server_series3_guard.py -q → FAIL (_require_series3 / read_serial don't exist).

  • Step 3: Implement read_serial, _require_series3, the serial query parameter, and the four guard calls as specified.

  • Step 4: Run the new tests plus tests/test_server_device_access.py → PASS. Then the full suite → only the 16 known failures.

  • Step 5: Commit fix(sfm): legacy Series-3 writes and erase refuse a unit that does not answer as Series 3.

Task 2: Page — the device-routing block (pure functions) and its Node-run tests

Files:

  • Modify: sfm/sfm_webapp.html. Add one <script> block, delimited by the lines /* <device-routing> */ and /* </device-routing> */. It must not touch document or fetch.
  • Test: create tests/test_webapp_device_routing.py. It extracts the block, appends module.exports = {…}, and runs cases through node -e (via subprocess, reading JSON on stdout). Skip with a clear reason if shutil.which("node") is None.

Interfaces (Produces, used by Tasks 3–6):

  • seriesFromSerial(serial) -> 3 | 4 | null: trims and upper-cases; UM… → 4, BE…/BA… → 3 (prefix plus at least one more character), anything else → null. Mirrors sfm/device_access/series.py.

  • unitQuery(unit) -> string, where unit = {serial, host, tcpPort}:

    • serial mode: serial=<NORMALISED>&host=<h>&tcp_port=<p>;
    • blank serial: host=<h>&tcp_port=<p>;
    • every value goes through encodeURIComponent.
  • deviceUrl(action, unit, params = {}) -> {method, path}: path is relative, e.g. /device/info?serial=…. Actions:

    • info, status, settings, events → GET;
    • download (needs params.event_id), start, stop → POST;
    • hangup → POST, with no serial (host/port only);
    • legacy actions: storage_range, index, erase, rescue, blind_stop, slow_drip, call_home_read (GET /device/call_home), call_home_write, config_write (POST /device/config).

    settings, download and hangup with a blank serial return null, since there is no legacy equivalent. Unknown actions throw.

  • confirmedSeries(unit) -> 3 | 4 | null, where unit.confirmed = {serial, series} comes from the last /device/info reply:

    • returns unit.confirmed.series only when the normalised typed serial equals unit.confirmed.serial;
    • with a blank typed serial, returns unit.confirmed.series from a legacy identify;
    • otherwise null.
  • controlsFor(unit) -> {startStop, hangup, diagnostics, callHomeRead, configWrite, callHomeWrite, reasons}, all booleans except reasons:

    • startStop = serial mode and confirmedSeries ∈ {3, 4};
    • hangup = confirmedSeries === 4;
    • diagnostics = confirmedSeries === 3;
    • callHomeRead = confirmedSeries === 3;
    • configWrite = callHomeWrite = false;
    • reasons = {configWrite: "Coming in phase 5 (#46)", callHomeWrite: "Coming in phase 4"}.
  • changeSummary(body) -> string, for a ChangeResult JSON (action, outcome, verified, state_before, state_after, audit_id, plan):

    • dry_run → "<action>: dry run — would send <subs comma-joined>";
    • skipped → "<action>: already <state_before> — nothing sent";
    • sent + ok → "<action>: confirmed — <state_before> → <state_after> (audit <id8>)";
    • anything else → "<action>: <outcome>, <verified> (audit <id8>)".
  • downloadSummary(body) -> string, for an EventDownload JSON:

    • inserted: false → "already stored — <stored_filename>";
    • otherwise "stored <stored_filename>, <filesize> bytes, check: <detail.check>".
  • Step 1: Write the failing test file. Each case is (function, args, expected) and runs as node evaluating JSON.stringify(fn(...args)). Cases that must be present:

    • seriesFromSerial: "UM20147"→4, " be9441 "→3, "BA123"→3, "BE"→null, "XX1"→null.
    • unitQuery: serial mode upper-cases and trims; blank serial omits serial=; a host with & is encoded.
    • deviceUrl: info with a serial → {method:"GET", path:"/device/info?serial=BE9441&host=h&tcp_port=9034"}; hangup → no serial; settings with a blank serial → null; download carries event_id.
    • controls (named for Review Focus 1 and 2):
      • typed serial is not confirmation: typed BE9441 with confirmed:null → diagnostics:false, startStop:false;
      • confirmed S3: diagnostics true, hangup false;
      • confirmed S4: hangup true, diagnostics false, callHomeRead false;
      • confirmation drops when the serial changes: confirmed {serial:"BE9441",series:3} with typed BE9442 → all false;
      • config/call-home write always false, with the exact reason strings.
    • changeSummary: one case per outcome, including failed with verified:"not_checked" and sent with verified:"mismatch".
    • downloadSummary: inserted and already-stored.
  • Step 2: Run → FAIL (no block in the page).

  • Step 3: Implement the block in the page, just before the existing main <script>'s first function. Exactly the functions above, no DOM.

  • Step 4: Run → PASS. Full suite → only the 16 known failures.

  • Step 5: Commit feat(webapp): the device-routing rules as pure functions, tested through Node.

Task 3: Page — unit bar, series badge, Device tab and status panel, Hang up

Files: Modify sfm/sfm_webapp.html. Test: extend tests/test_webapp_device_routing.py with the static check below.

Interfaces:

  • Consumes: unitQuery, deviceUrl, confirmedSeries, controlsFor (Task 2).

  • Produces: a page-level currentUnit() returning {serial, host, tcpPort, confirmed}. confirmed is held in a module variable set only by connectUnit() from the /device/info reply ({serial: body.serial, series: body.series}), and cleared whenever the serial or host field changes. Also applyControls(), which sets every series-specific control's disabled/hidden state and tooltip from controlsFor(currentUnit()). Tasks 4–6 call applyControls() after any state change.

  • Step 1: Write the failing static test. test_every_device_url_is_built_by_deviceUrl: outside the device-routing block, the page source contains no `${api()}/device/ and no '/device/ string literal. The deviceUrl call sites are the only way to build one.

  • Step 2: Run → FAIL (today's page builds them by hand).

  • Step 3: Implement.

    • A Serial input beside host/port, id="dev-serial", with placeholder "BE…/BA… or UM… (optional)".
    • A badge id="series-badge" showing Series 3 / Series 4 from confirmedSeries, or hidden.
    • connectUnit() and refreshMonitorStatus() go through deviceUrl('info'|'status', …). The Device tab and status panel render UnitInfo/UnitStatus fields with "—" for null (device_time and event_count are null on Series 3).
    • A Hang up button id="hangup-btn", visible only when controlsFor().hangup, which POSTs deviceUrl('hangup').
    • Convert every remaining hand-built /device/ URL to deviceUrl (legacy actions included), so the static test passes. With a blank serial, behaviour is unchanged.
  • Step 4: Run the page tests and the full suite → PASS, only the 16 known failures.

  • Step 5: Commit feat(webapp): name a unit by serial; series badge from the unit's own answer; Hang up for Series 4.

Task 4: Page — Events tab by serial

Files: Modify sfm/sfm_webapp.html.

Interfaces:

  • Consumes: deviceUrl('events'|'download'), downloadSummary (Task 2), currentUnit() (Task 3), and the existing openSidecarModal(dbEventId) (~line 2780).

  • Step 1: Implement. In serial mode, the Events tab lists EventList.events: index, timestamp, record_type, PVS and peaks, or "—". Each row has a Download button that POSTs deviceUrl('download', unit, {event_id}), shows downloadSummary(body) in the status bar, and then calls openSidecarModal(body.db_event_id) when it isn't null. HTTP errors show detail verbatim. With a blank serial, the existing legacy list and waveform behaviour is unchanged.

  • Step 2: Verify the page tests and the full suite → only the 16 known failures. The bench check covers the live behaviour.

  • Step 3: Commit feat(webapp): list and download events by serial, for both series.

Task 5: Page — Start/Stop through the audited path

Files: Modify sfm/sfm_webapp.html.

Interfaces:

  • Consumes: deviceUrl('start'|'stop'), changeSummary, controlsFor().startStop (Task 2).

  • Step 1: Implement.

    • In serial mode, startMonitoring()/stopMonitoring() confirm() with "Start monitoring on <serial>?" / "Stop monitoring on <serial>?".
    • Then POST once (never retried). While a start is in flight, show "Starting — the unit runs its sensor check first (about 35 s)".
    • Show changeSummary(body) for any JSON body, including a 409/502 ChangeResult; show detail verbatim for an error without one (e.g. 504).
    • Then call refreshMonitorStatus().
    • Buttons are enabled only by controlsFor().startStop.
    • In serial mode the legacy _pollMonitorConfirm isn't called. With a blank serial, the legacy behaviour is unchanged.
  • Step 2: Verify the page tests and the full suite → only the 16 known failures. Task 2's changeSummary cases cover the 409/mismatch and failed bodies; the bench check covers the live behaviour.

  • Step 3: Commit feat(webapp): start/stop through the audited serial path, with the honest result.

Task 6: Page — Config, Call Home and Diagnostics gating

Files: Modify sfm/sfm_webapp.html.

Interfaces:

  • Consumes: deviceUrl('settings'|'call_home_read'|…), controlsFor() (Task 2), applyControls() (Task 3).

  • Step 1: Implement.

    • Config tab: in serial mode, Read shows UnitSettings (setup name, record mode, sample rate, record time, histogram interval, geo trigger, notes, with "—" for null). Write is disabled for both series, with the tooltip from reasons.configWrite.
    • Call Home tab: read enabled only by callHomeRead; for Series 4 it says "Not yet available for Series 4". Write is disabled, with reasons.callHomeWrite.
    • Diagnostics: every button is enabled only by controlsFor().diagnostics; the erase confirmation stays as is. Diagnostics requests pass serial when one is typed, so the server guard (Task 1) checks it as well.
    • With a blank serial, the legacy reads are unchanged, while writes and erase follow controlsFor. A legacy identify (blank serial) that answers as BE… confirms Series 3.
  • Step 2: Verify the page tests and the full suite → only the 16 known failures.

  • Step 3: Commit feat(webapp): config and call-home writes wait for phases 4-5; Diagnostics only for a confirmed Series-3 unit.

Task 7: Docs

Files: CLAUDE.md (the SFM REST API section, and "Where things stand"), docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md (the 1c entry in Build phases).

  • Step 1: Document:

    • the legacy-route Series-3 guard (which routes, why the stop tools are exempt);
    • the page's serial mode;
    • the node requirement for tests/test_webapp_device_routing.py.

    No CHANGELOG (feature branch).

  • Step 2: Commit docs: phase 1c -- the webapp by serial, and the Series-3 guard on legacy writes.

After Task 7 (controller, with Brian, not an implementer task): a bench pass on BE9441 and UM20147, through the bridge or cellular:

  • identify;
  • status;
  • settings read;
  • events list and one download each;
  • one audited start/stop each (Brian's go per send);
  • for the Micromate, Hang up;
  • Diagnostics disabled on UM20147, and enabled only after BE9441 identifies.