fix(updater): keep auto-updater alive across watcher restarts (v0.4.1)

Saving the Settings dialog calls _restart_watcher, which set+replaced the
shared stop_event the updater loop also keyed off — so a settings save
silently killed the auto-updater thread (race: survived one save, died on
the next). Heartbeats kept flowing but the agent stopped checking for /
applying updates until relaunch.

Give the updater its own app-lifetime event (_app_stop), set only on
Exit / when applying an update and untouched by watcher restarts. Adds
test_thor_tray.py (4 lifecycle tests). Bump to v0.4.1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-25 18:01:58 +00:00
parent 302934ced6
commit a92afd64cd
7 changed files with 101 additions and 11 deletions
+6
View File
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.4.1] - 2026-06-25
### 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 normally, 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.
- Added `test_thor_tray.py` covering the tray thread lifecycle (updater survives a watcher restart; stops on app exit; `_exit`/`_do_update` signal the lifetime event).
## [0.4.0] - 2026-06-25
### Added — Mirror (dual-send)
+3 -3
View File
@@ -1,6 +1,6 @@
# Thor Watcher
**Version:** 0.4.0
**Version:** 0.4.1
Micromate (Series 4) watcher agent for Terra-View fleet management. Runs as a Windows system tray application, scans THORDATA for Micromate unit activity, sends heartbeat data to Terra-View, and (optionally) forwards `.IDFH`/`.IDFW` event files to a seismo-relay SFM server. Heartbeats and events can optionally be **mirrored** to a second server (e.g. a standby/NAS) in addition to the primary.
@@ -29,7 +29,7 @@ build.bat
```
Produces:
- `dist\thor-watcher-0.4.0.exe` — upload to Gitea release
- `dist\thor-watcher-0.4.1.exe` — upload to Gitea release
- `dist\thor-watcher.exe` — use with Inno Setup
Then run Inno Setup Compiler on `installer.iss` to produce `thor-watcher-setup.exe`.
@@ -139,7 +139,7 @@ Posted to `api_url` on each API interval:
{
"source_id": "THOR-PC",
"source_type": "series4_watcher",
"version": "0.4.0",
"version": "0.4.1",
"generated_at": "2026-03-20T14:30:00Z",
"log_tail": ["...last 25 log lines..."],
"units": [
+1 -1
View File
@@ -3,7 +3,7 @@
[Setup]
AppName=Thor Watcher
AppVersion=0.4.0
AppVersion=0.4.1
AppPublisher=Terra-Mechanics Inc.
DefaultDirName={pf}\ThorWatcher
DefaultGroupName=Thor Watcher
+2 -2
View File
@@ -1,5 +1,5 @@
"""
Thor Watcher — Series 4 Ingest Agent v0.4.0
Thor Watcher — Series 4 Ingest Agent v0.4.1
Micromate (Series 4) ingest agent for Terra-View.
@@ -29,7 +29,7 @@ import event_forwarder
# ── Version ───────────────────────────────────────────────────────────────────
VERSION = "0.4.0"
VERSION = "0.4.1"
# ── Config ────────────────────────────────────────────────────────────────────
+81
View File
@@ -0,0 +1,81 @@
"""
Tests for thor_tray's thread lifecycle.
Regression guard for the bug where saving settings — which restarts the
watcher thread via ``_restart_watcher`` — also killed the auto-updater
thread, because both shared a single ``stop_event``. The updater must key
off a separate lifetime event (``_app_stop``) that a watcher restart never
disturbs; it should only stop when the app actually exits.
"""
import sys
import time
import threading
import unittest
from unittest import mock
# Thor's tray pulls in Windows-only GUI deps at import time; stub them so the
# module imports on a headless dev/CI box.
for _name in ("pystray", "PIL", "PIL.Image", "PIL.ImageDraw"):
sys.modules.setdefault(_name, mock.MagicMock())
import thor_tray # noqa: E402
class TrayThreadLifecycle(unittest.TestCase):
def setUp(self):
# Keep _start_watcher cheap: a no-op watcher loop so restarting the
# watcher doesn't spin up the real THORDATA scanner / network heartbeat.
patcher = mock.patch.object(
thor_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 = thor_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 = thor_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 = thor_tray.WatcherTray()
app._restart_watcher()
self.assertFalse(app.stop_event.is_set())
def test_updater_survives_watcher_restart_then_stops_on_exit(self):
app = thor_tray.WatcherTray()
app._icon = None
with mock.patch.object(thor_tray, "check_for_update", return_value=(None, None)), \
mock.patch.object(thor_tray, "_update_log"), \
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()
+1 -1
View File
@@ -1,5 +1,5 @@
"""
Thor Watcher — Settings Dialog v0.4.0
Thor Watcher — Settings Dialog v0.4.1
Provides a Tkinter settings dialog that doubles as a first-run wizard.
+7 -4
View File
@@ -1,5 +1,5 @@
"""
Thor Watcher — System Tray Launcher v0.4.0
Thor Watcher — System Tray Launcher v0.4.1
Requires: pystray, Pillow, tkinter (stdlib)
Run with: pythonw thor_tray.py (no console window)
@@ -334,7 +334,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
self._menu_lock = threading.Lock()
@@ -390,6 +391,7 @@ class WatcherTray:
subprocess.Popen(["explorer", HERE])
def _exit(self, icon, item):
self._app_stop.set()
self.stop_event.set()
icon.stop()
@@ -478,7 +480,7 @@ class WatcherTray:
# line in the log soon after startup; subsequent checks every ~5 min.
update_check_counter = 27
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:
@@ -504,7 +506,7 @@ class WatcherTray:
self._do_update(url)
return
self.stop_event.wait(timeout=10)
self._app_stop.wait(timeout=10)
def _do_update(self, download_url=None):
"""Notify tray then apply update. If url is None, fetch it first."""
@@ -519,6 +521,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()