11 Commits

Author SHA1 Message Date
serversdown 9d4ea822fd Merge pull request 'fix: updater survives Settings saves + cache unsniffable MLGs (v1.6.1)' (#13) from dev into main
Reviewed-on: #13
2026-06-30 01:17:15 -04:00
serversdown aa341c7342 fix: updater survives Settings saves + cache unsniffable MLGs (v1.6.1)
Two reliability fixes for the Series 3 tray app:

1. Auto-updater no longer dies on a Settings save. _restart_watcher
   set+replaced the shared stop_event that the updater loop also keyed
   off, so saving settings could kill the updater thread (race). Give
   the updater its own app-lifetime event (_app_stop). Same fix as
   thor-watcher 0.4.1.

2. Unsniffable .MLG files are now cached, so each is sniffed + logged
   once per session instead of every 5-min scan. A long-lived autocall
   folder with a few hundred unidentifiable files was flooding the log
   (~600K lines in 10 days) and re-reading every header each scan.

Adds test_series3_tray.py (4 lifecycle tests) and test_scan_latest.py
(2 scan tests). Full suite 50 passing. Bump to v1.6.1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 20:08:03 +00:00
serversdown fb1edfbad4 Merge pull request 'v1.6.0 - Optional dual-send mirror so a standby server stays a live replica.' (#12) from dev into main
Reviewed-on: #12
2026-06-25 10:53:29 -04:00
serversdown e6e4c94f19 chore(release): bump to v1.6.0 — mirror (dual-send) docs
Version bump across series3_watcher.py / tray / settings dialog / installer.iss.
CHANGELOG + README document the optional best-effort mirror server
(MIRROR_API_URL / MIRROR_SFM_URL / MIRROR_SFM_STATE_FILE, default off).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 05:54:20 +00:00
serversdown a457619158 Merge pull request 'doc: update to 1.5.0' (#10) from dev into main
Reviewed-on: #10
2026-05-11 12:31:57 -04:00
serversdown 9b3ae6d548 Merge pull request 'feat(forward): SFM event forwarder (v1.5.0)' (#9) from dev into main
Reviewed-on: #9
2026-05-11 12:29:21 -04:00
serversdown 1abdc13645 Merge pull request 'bump to 1.4.4 (the nonupdate update)' (#6) from dev into main
Reviewed-on: #6
2026-03-17 21:54:59 -04:00
serversdown f790b21808 Merge pull request 'merge v1.4.3' (#5) from dev into main
Reviewed-on: #5
2026-03-17 21:11:41 -04:00
serversdown 0bea6ca4ea Merge pull request 'v1.4.2' (#3) from dev into main
Reviewed-on: #3
2026-03-17 16:15:22 -04:00
serversdown 2456fd0ee8 Merge pull request 'Merge v1.4.1 from dev' (#2) from dev into main
## [1.4.1] - 2026-03-17

### Fixed
- `config.ini` now saves to `AppData\Local\Series3Watcher\` instead of `Program Files` — fixes permission denied error on first-run wizard save.
- Config path resolution in both `series3_tray.py` and `series3_watcher.py` updated to use `sys.frozen` + `LOCALAPPDATA` when running as a PyInstaller `.exe`.
- Status menu item now uses a callable so it updates every time the menu opens — was showing stale "Starting..." while tooltip correctly showed current status.
- Settings dialog now opens in its own thread — fixes unresponsive tabs and text fields while the watcher loop is running.
- Tray icon reverted to plain colored dot — custom icon graphic was unreadable at 16px tray size. `.ico` file is still used for the `.exe` file icon.

### Changed
- Terra-View URL field in settings wizard now accepts base URL only (e.g. `http://192.168.x.x:8000`) — `/api/series3/heartbeat` endpoint appended automatically.
- Test Connection button now hits `/health` endpoint instead of posting a fake heartbeat — no database side effects.
- "terra-view URL" label capitalized to "Terra-View URL".
- Default log path updated to `AppData\Local\Series3Watcher\agent_logs\series3_watcher.log`.
- Installer now creates `agent_logs\` folder on install.
- `BUILDING.md` added — step-by-step guide for building, releasing, and updating.

## [1.4.0] - 2026-03-12

### Added
- `series3_tray.py` — system tray launcher using `pystray` + `Pillow`. Color-coded icon (green=OK, amber=Pending, red=Missing, purple=Error, grey=Starting). Right-click menu shows live status, unit count, last scan age, Open Log Folder, and Exit.
- `run_watcher(state, stop_event)` in `series3_watcher.py` for background thread use by the tray. Shared `state` dict updated on every scan cycle with status, unit list, last scan time, and last error.
- Interruptible sleep in watcher loop — tray exit is immediate, no waiting out the full scan interval.

### Changed
- `main()` now calls `run_watcher()` — standalone behavior unchanged.
- `requirements.txt` updated to document tray dependencies (`pystray`, `Pillow`); watcher itself remains stdlib-only.
2026-03-17 14:31:50 -04:00
serversdown c133932b29 Merge pull request 'Merge: dev to main, refactor rename' (#1) from dev into main
Reviewed-on: serversdown/series3-agent#1
2026-03-03 17:12:58 -05:00
8 changed files with 217 additions and 15 deletions
+35
View File
@@ -6,6 +6,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
## [6-25-26] — v1.6.1
Reliability fixes for the tray app's auto-updater and scan logging.
### Fixed
- **Auto-updater no longer dies when Settings are saved.** Saving the Settings dialog restarts the watcher thread via `_restart_watcher`, which sets and then replaces the shared `stop_event`. Because the updater loop keyed off that *same* event, saving settings would terminate the auto-updater thread (a race — it could survive one save and die on the next). The watcher kept running and reporting heartbeats, but the agent silently stopped checking for / applying updates until the tray app was relaunched. The updater now keys off its own app-lifetime event (`_app_stop`) that watcher restarts never touch; it stops only on Exit or when applying an update. (Same fix as thor-watcher 0.4.1.)
- **Unsniffable `.MLG` files are logged once, not every scan.** A `.MLG` file the watcher couldn't extract a unit ID from was never cached, so every scan (~every 5 min) re-sniffed *and* re-emitted its `[unsniffable-recent]` log line. With a few hundred such files in a long-lived Blastware autocall folder that meant tens of thousands of duplicate lines per day (a 10-day-old log had grown to ~600K lines). The scan now caches the unsniffable result, so each file is sniffed and logged once per session — and the redundant per-scan header reads are gone.
- Added `test_scan_latest.py` (unsniffable cached / logged-once + happy-path sniff) and `test_series3_tray.py` (updater survives a watcher restart; stops on exit).
## [6-25-26] — v1.6.0
Optional dual-send mirror so a standby server stays a live replica.
### Added — Mirror (dual-send)
- **Post every heartbeat and event to a second ("mirror") server in addition to the primary.** When `MIRROR_API_URL` and/or `MIRROR_SFM_URL` are set, each heartbeat POST and each forwarded Blastware event is *also* sent to the mirror destination — letting a standby box (e.g. the office NAS) stay a continuous replica of prod during a migration so the eventual cutover is a non-event. **Default off** — blank URLs mean existing 1.5.x installs don't change behaviour after an auto-update.
- **Heartbeat mirror (best-effort).** After the primary `send_api_payload`, the same payload is fired at `MIRROR_API_URL` when set. It is fully wrapped and bounded by the existing API timeout — the mirror can **never** delay or fail the primary heartbeat; its outcome is ignored except for a debug log line.
- **Event mirror (reliable, isolated).** Events are re-forwarded to `MIRROR_SFM_URL` through a *separate* sha256 state file (`MIRROR_SFM_STATE_FILE`, blank → `<log dir>/sfm_forwarded_mirror.json`) so the mirror tracks its own delivery independently of the primary forwarder. Before each mirror pass a quick reachability probe (~3 s) checks the mirror server; if it's down the pass is skipped and retried next tick rather than blocking the loop on per-event timeouts. Skipped events stay pending in the mirror state and deliver once the mirror returns — **no data loss**.
- **Isolation invariant.** Nothing on the mirror path can delay or fail the primary: its own state file, its own try/except, the reachability guard + bounded timeouts, and all exceptions swallowed-and-logged. The primary path stays exactly as reliable as before. The mirror rides along with the primary — there is no separate enable flag (heartbeat-mirror active iff the primary heartbeat is on *and* `MIRROR_API_URL` is set; event-mirror active iff primary forwarding is on *and* `MIRROR_SFM_URL` is set).
- **Mirror fields in the Settings dialog**: `Mirror API URL` + `Mirror SFM URL` (blank = off).
- New unit tests in `test_event_forwarder.py` covering mirror reachability, the down-mirror skip, separate-state idempotency, and the isolation invariant (a mirror failure leaves the primary's result + state untouched).
### Configuration
New `[agent]` keys (all default-off — existing 1.5.x deployments don't change behaviour on auto-update):
| Key | Default | Notes |
|---|---|---|
| `MIRROR_API_URL` | empty | Second heartbeat base URL, e.g. `http://10.0.0.x:8001` (blank = off) |
| `MIRROR_SFM_URL` | empty | Second SFM base URL, e.g. `http://10.0.0.x:8200` (blank = off) |
| `MIRROR_SFM_STATE_FILE` | `<log dir>/sfm_forwarded_mirror.json` | Override location of the mirror's forwarded-sha256 state file |
### Operational (migration seeding)
To make the mirror re-deliver only the gap since a one-time replica snapshot, copy the primary state file to the mirror state file and drop entries whose `forwarded_at` is after the snapshot. SFM-side dedup covers any overlap. See `docs/mirror-dual-send-design.md`.
## [5-11-26] — v1.5.0
First release of the SFM event forwarder.
+23 -2
View File
@@ -1,4 +1,4 @@
# Series 3 Watcher v1.5.0
# Series 3 Watcher v1.6.1
Monitors Instantel **Series 3 (Minimate)** call-in activity on a Blastware server. Runs as a **system tray app** that starts automatically on login, reports heartbeats to terra-view, and self-updates from Gitea.
@@ -124,6 +124,27 @@ Combine both for a fully controlled rollout: seed-state to skip the deep archive
---
## Mirror (Dual-Send) — v1.6.0+
The watcher can post every heartbeat and event to a **second ("mirror") server** in addition to the primary — useful for keeping a standby box (e.g. the office NAS) as a continuous replica during a server migration, so the eventual cutover is a non-event. **Default off.**
The mirror rides along with the primary — there is no separate enable flag:
- **Heartbeat mirror** is active when `API_ENABLED = true` **and** `MIRROR_API_URL` is set. After the primary heartbeat POST, the same payload is fired at the mirror.
- **Event mirror** is active when `SFM_FORWARD_ENABLED = true` **and** `MIRROR_SFM_URL` is set. Events are re-forwarded to the mirror using a **separate** sha256 state file (`MIRROR_SFM_STATE_FILE`, blank → `<log dir>/sfm_forwarded_mirror.json`).
**The mirror can never delay or fail the primary.** The heartbeat mirror is fully wrapped and bounded by the API timeout. The event mirror runs a quick reachability probe (~3 s) first and skips the pass if the mirror server is down — skipped events stay pending in the mirror state and deliver when it returns, so nothing is lost. All mirror exceptions are swallowed-and-logged; the primary path stays exactly as reliable as before.
| Key | Description |
|-----|-------------|
| `MIRROR_API_URL` | Second heartbeat base URL, e.g. `http://10.0.0.x:8001` (blank = off) |
| `MIRROR_SFM_URL` | Second SFM base URL, e.g. `http://10.0.0.x:8200` (blank = off) |
| `MIRROR_SFM_STATE_FILE` | Path to the mirror's sha256 state file. Blank → `<log dir>/sfm_forwarded_mirror.json` |
**Seeding for a migration.** To re-deliver only the gap since a one-time replica snapshot, copy the primary state file to the mirror state file and drop entries whose `forwarded_at` is after the snapshot. SFM-side dedup covers any overlap. See [`docs/mirror-dual-send-design.md`](docs/mirror-dual-send-design.md).
---
## Tray Icon
| Colour | Meaning |
@@ -167,7 +188,7 @@ where the corresponding server-side work lives.
## Versioning
Follows **Semantic Versioning**. Current release: **v1.5.0**.
Follows **Semantic Versioning**. Current release: **v1.6.1**.
See `CHANGELOG.md` for full history.
---
+1 -1
View File
@@ -3,7 +3,7 @@
[Setup]
AppName=Series 3 Watcher
AppVersion=1.5.0
AppVersion=1.6.1
AppPublisher=Terra-Mechanics Inc.
DefaultDirName={pf}\Series3Watcher
DefaultGroupName=Series 3 Watcher
+7 -4
View File
@@ -1,5 +1,5 @@
"""
Series 3 Watcher — System Tray Launcher v1.5.0
Series 3 Watcher — System Tray Launcher v1.6.1
Requires: pystray, Pillow, tkinter (stdlib)
Run with: pythonw series3_tray.py (no console window)
@@ -335,7 +335,8 @@ def _show_cancel_message():
class WatcherTray:
def __init__(self):
self.state = {}
self.stop_event = threading.Event()
self.stop_event = threading.Event() # watcher lifecycle; replaced on restart
self._app_stop = threading.Event() # app lifetime; only set on exit/update
self._watcher_thread = None
self._icon = None
# Lock guards _rebuild_menu calls from the updater thread
@@ -394,6 +395,7 @@ class WatcherTray:
subprocess.Popen(["explorer", HERE])
def _exit(self, icon, item):
self._app_stop.set()
self.stop_event.set()
icon.stop()
@@ -459,7 +461,7 @@ class WatcherTray:
last_status = None
update_check_counter = 0 # check for updates every ~5 min (30 * 10s ticks)
while not self.stop_event.is_set():
while not self._app_stop.is_set():
icon_status = self._tray_status()
if self._icon is not None:
@@ -487,7 +489,7 @@ class WatcherTray:
self._do_update(url)
return # exit loop; swap bat will relaunch
self.stop_event.wait(timeout=10)
self._app_stop.wait(timeout=10)
def _do_update(self, download_url=None):
"""Notify tray icon then apply update. If url is None, fetch it first."""
@@ -502,6 +504,7 @@ class WatcherTray:
success = apply_update(download_url)
if success:
self._app_stop.set()
self.stop_event.set()
if self._icon is not None:
self._icon.stop()
+9 -6
View File
@@ -237,13 +237,16 @@ def scan_latest(
uid = cached[1]
else:
uid = sniff_unit_from_mlg(fpath, header_bytes)
if not uid:
# If unsniffable but very recent, log for later inspection
if (recent_cutoff is not None) and (mtime >= recent_cutoff):
# Cache the result either way — including unsniffable (uid=None) —
# so the same file isn't re-sniffed and re-logged on every scan.
cache[fpath] = (mtime, uid)
if (not uid) and (recent_cutoff is not None) and (mtime >= recent_cutoff):
# Log once, on first sight, for later inspection.
if logger:
logger("[unsniffable-recent] {}".format(fpath))
continue # skip file if no unit ID found in header
cache[fpath] = (mtime, uid)
if not uid:
continue # no unit ID in header — skip (cached above, won't re-log)
if (uid not in latest) or (mtime > latest[uid]["mtime"]):
latest[uid] = {"mtime": mtime, "fname": e.name, "path": fpath}
@@ -253,7 +256,7 @@ def scan_latest(
# --- API heartbeat / SFM telemetry helpers ---
VERSION = "1.5.0"
VERSION = "1.6.1"
def _read_log_tail(log_file: str, n: int = 25) -> Optional[list]:
+1 -1
View File
@@ -1,5 +1,5 @@
"""
Series 3 Watcher — Settings Dialog v1.5.0
Series 3 Watcher — Settings Dialog v1.6.1
Provides a Tkinter settings dialog that doubles as a first-run wizard.
+62
View File
@@ -0,0 +1,62 @@
"""
Tests for scan_latest's handling of unsniffable .MLG files.
Regression guard: a .MLG file the watcher can't extract a unit ID from must
be cached (as "no id") so it isn't re-sniffed and re-logged on every scan.
Previously the unsniffable result was never cached, so the
`[unsniffable-recent]` warning was re-emitted every scan cycle — ~200 files
x 288 scans/day flooded the log with hundreds of thousands of duplicate lines.
"""
import os
import time
import tempfile
import unittest
import series3_watcher
class UnsniffableCaching(unittest.TestCase):
def test_unsniffable_recent_file_logged_once_across_scans(self):
with tempfile.TemporaryDirectory() as d:
# A .MLG file with no BE####/BA#### pattern → sniff returns None.
path = os.path.join(d, "junk001.MLG")
with open(path, "wb") as f:
f.write(b"\x00" * 512)
calls = []
cache = {}
recent_cutoff = time.time() - 86400.0 # file (mtime≈now) counts as recent
for _ in range(3):
series3_watcher.scan_latest(
watch=d,
header_bytes=2048,
cache=cache,
recent_cutoff=recent_cutoff,
max_age_days=365,
logger=calls.append,
)
unsniff = [c for c in calls if "[unsniffable-recent]" in c]
self.assertEqual(
len(unsniff), 1,
"unsniffable file should log once across scans, got {}: {}".format(
len(unsniff), unsniff),
)
def test_sniffable_file_still_returned(self):
# Sanity: a file WITH a unit id is still detected (happy path intact).
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "evt001.MLG")
with open(path, "wb") as f:
f.write(b"hdr\x00BE12599\x00hdr") # contains a sniffable unit id
cache = {}
result = series3_watcher.scan_latest(
watch=d, header_bytes=2048, cache=cache,
recent_cutoff=time.time() - 86400.0, max_age_days=365, logger=None,
)
self.assertIn("BE12599", result)
if __name__ == "__main__":
unittest.main()
+78
View File
@@ -0,0 +1,78 @@
"""
Tests for series3_tray's thread lifecycle.
Regression guard: saving the Settings dialog restarts the watcher thread via
``_restart_watcher``, which sets and replaces the shared ``stop_event``. The
auto-updater must key off its own lifetime event (``_app_stop``) so a watcher
restart never kills it; it should only stop when the app actually exits.
"""
import sys
import time
import threading
import unittest
from unittest import mock
# Series3's tray pulls in Windows-only GUI deps at import time; stub them.
for _name in ("pystray", "PIL", "PIL.Image", "PIL.ImageDraw"):
sys.modules.setdefault(_name, mock.MagicMock())
import series3_tray # noqa: E402
class TrayThreadLifecycle(unittest.TestCase):
def setUp(self):
# No-op watcher loop so restarting the watcher doesn't spin up the real
# Blastware scanner / network heartbeat.
patcher = mock.patch.object(
series3_tray.watcher, "run_watcher", lambda state, stop_event: None
)
patcher.start()
self.addCleanup(patcher.stop)
def test_app_stop_is_separate_lifetime_event(self):
app = series3_tray.WatcherTray()
self.assertIsInstance(app._app_stop, threading.Event)
self.assertIsNot(app._app_stop, app.stop_event)
self.assertFalse(app._app_stop.is_set())
def test_exit_signals_app_stop(self):
app = series3_tray.WatcherTray()
icon = mock.MagicMock()
app._exit(icon, None)
self.assertTrue(app._app_stop.is_set())
icon.stop.assert_called_once()
def test_restart_watcher_leaves_watcher_stop_unset(self):
app = series3_tray.WatcherTray()
app._restart_watcher()
self.assertFalse(app.stop_event.is_set())
def test_updater_survives_watcher_restart_then_stops_on_exit(self):
app = series3_tray.WatcherTray()
app._icon = None
with mock.patch.object(series3_tray, "check_for_update", return_value=(None, None)), \
mock.patch.object(app, "_tray_status", return_value="ok"):
t = threading.Thread(
target=app._icon_updater, daemon=True, name="test-updater"
)
t.start()
time.sleep(0.1)
self.assertTrue(t.is_alive(), "updater failed to start")
# A settings save restarts the watcher — it must NOT kill the updater.
app._restart_watcher()
time.sleep(0.2)
self.assertTrue(
t.is_alive(), "updater thread died on watcher restart (the bug)"
)
# Real app exit DOES stop the updater.
app._app_stop.set()
t.join(timeout=2)
self.assertFalse(
t.is_alive(), "updater thread did not stop on app exit"
)
if __name__ == "__main__":
unittest.main()