Sensor health in the API and UI; balloon tips when something starts going wrong

- telemetry: _source() now remembers each failing source's error message, not
  just the log timestamp; health() reports them and every snapshot carries a
  "health" key, so /api/state shows which sensor source is failing and since
  when. A source that reads again clears its entry.
- Web UI: a header pill counts the failing sources; hovering lists the errors.
- tray: notify() shows a balloon tip from any thread (queued on the tray
  window, NIF_INFO). app.py grows an alert monitor: every 5 s it diffs the
  current bad states (fan failsafes/control errors, AI backend errors, failing
  sensor sources) against the last look and balloons only what is new. The
  first look is the baseline: problems that predate the tray icon stay quiet.
- Tests: test_telemetry.py (5) and test_alerts.py (7); README updated.
This commit is contained in:
paul committed 2026-12-05 17:51:00 +13:00
1 parent b2da2213b7
commit ba39016d52
7 files changed
+292 -10

No files matched your search

+6 -3
View File
@@ -50,9 +50,12 @@ is elevated (see `kurgan/ai/launcher.py`). The web UI shows each server's integr
Open it from the tray icon (left-click, or **Open The Kurgan** in its menu) or browse to
<http://127.0.0.1:8080/>. It only listens on 127.0.0.1. The page refreshes once a second while it
is visible. Every chart has a **Table** button that shows the same numbers as a table.
is visible. Every chart has a **Table** button that shows the same numbers as a table. The tray
icon also pops a balloon tip when something starts to go wrong — a fan group entering failsafe,
an AI server reporting an error, or a sensor source starting to fail. What is already wrong when
The Kurgan starts is not ballooned; it sits in the tray menu and the UI.
- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes.
- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes. When a sensor source's last read failed — a disconnected Commander PRO, a busy NVML — a pill in the header names it and hover shows the error.
- **Cooling**: the fan profile selector; each fan group's duty, temperature and RPMs; fan speeds over time; and the selected profile's curves, with a dot for each group's current operating point. Hover over a profile to preview its curves.
- **Lighting**: a mode selector per zone (case fans, RAM, GPU), the zone's status, and the shared chase speed.
- **AI**: pick Strata (and its model), llama.cpp or None; requests to either address also pick it. Then see the server's process, model, context size, live request progress and token speeds, and when it will stop if unused; load or unload the model; GPU memory over time; and recent requests.
@@ -64,7 +67,7 @@ next start.
| Request | Body / result |
| --- | --- |
| `GET /api/state` | Everything live (what the UI polls) |
| `GET /api/state` | Everything live (what the UI polls), including `telemetry.health`: the sensor sources whose latest read failed, each with its error and age |
| `GET /api/history` | The last 10 minutes of telemetry and fan duty |
| `GET /api/config` | Fan profiles and LCD theme thresholds |
| `POST /api/lighting` | `{"zone": "case_fans"\|"memory"\|"gpu", "mode": "off"\|"temperature"\|"chase"}` |
+47
View File
@@ -67,6 +67,32 @@ def _parse_color(text: str) -> tuple[int, int, int]:
return tuple(int(text[i:i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
ALERT_SECONDS = 5.0 # how often the alert monitor looks for things starting to go wrong
def alert_states(fans, ai, telemetry) -> dict[str, str]:
"""What is wrong right now: key -> message, for the things worth one balloon each."""
states = {}
if fans is not None:
for group in fans.groups:
if group.status.startswith(("FAILSAFE", "CONTROL ERROR")):
states[f"fans/{group.name}"] = f"{group.name} case fans: {group.status}"
if fans.top is not None and fans.top.status.startswith(("FAILSAFE", "UNAVAILABLE")):
states["fans/top"] = f"Top fans: {fans.top.status}"
if ai is not None:
for backend in ai.snapshot()["backends"]:
if backend["error"]:
states[f"ai/{backend['key']}"] = f"{backend['label']}: {backend['error']}"
for name, info in telemetry.health().items():
states[f"telemetry/{name}"] = f"{name} read failed ({info['error']}); continuing without it"
return states
def new_alerts(known: dict[str, str], states: dict[str, str]) -> list[tuple[str, str]]:
"""(key, message) for alerts that are new since the last look; recovered ones stay quiet."""
return [(key, states[key]) for key in sorted(states.keys() - known.keys())]
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
from kurgan.cooling.control import parse_ports
@@ -246,6 +272,27 @@ class Kurgan:
log.error("Web UI unavailable on port %s: %s", port, e)
if tray:
self._start_tray()
self._thread("alerts", self._alert_monitor, self.stop)
def _alert_monitor(self, stop: threading.Event) -> None:
"""Balloon tips for things starting to go wrong. The first look is the baseline: what
is already wrong at startup sits in the tray menu and the UI, it doesn't need a balloon."""
known: dict[str, str] | None = None
while not stop.wait(ALERT_SECONDS):
if self.tray is None:
continue # no icon, no balloons -- and no baseline burnt before the icon exists
try:
states = alert_states(self.fans, self.ai, self.telemetry)
except Exception:
log.exception("Alert check failed")
continue
if known is None:
known = states
continue
for _, message in new_alerts(known, states):
log.warning("Alert: %s", message)
self.tray.notify(APP_NAME, message, warning=True)
known = states
def _start_tray(self) -> None:
from kurgan.tray import TrayIcon, make_icon
+16 -5
View File
@@ -50,7 +50,7 @@ class Telemetry:
self._history: collections.deque[tuple] = collections.deque(maxlen=int(HISTORY_SECONDS / interval))
self._listeners: list[Callable[[Sample], None]] = []
self._seq = 0
self._last_failure: dict[str, float] = {}
self._failures: dict[str, tuple[float, str]] = {} # source -> (monotonic, message) of its latest failed read
def subscribe(self, listener: Callable[[Sample], None]) -> None:
self._listeners.append(listener)
@@ -66,13 +66,23 @@ class Telemetry:
def _source(self, name: str, read: Callable, fallback, *args):
try:
return read(*args)
result = read(*args)
except Exception as e:
# The loop retries every second, so log each failing source at most once a minute.
if time.monotonic() - self._last_failure.get(name, -1e9) >= 60:
self._last_failure[name] = time.monotonic()
now = time.monotonic()
last = self._failures.get(name)
if last is None or now - last[0] >= 60:
log.warning("%s read failed; continuing without it: %s", name, e, exc_info=True)
self._failures[name] = (now, f"{type(e).__name__}: {e}")
return fallback
self._failures.pop(name, None) # reading again: healthy
return result
def health(self) -> dict[str, dict]:
"""Sources whose latest read failed: name -> {"error", "age_s"}. Empty while every source reads."""
now = time.monotonic()
return {name: {"error": message, "age_s": round(now - when, 1)}
for name, (when, message) in self._failures.items()}
def run(self, stop: threading.Event) -> None:
while not stop.is_set():
@@ -115,9 +125,10 @@ class Telemetry:
def snapshot(self) -> dict:
s = self.latest
if s is None:
return {"seq": 0}
return {"seq": 0, "health": self.health()}
return {
"seq": s.seq, "t": s.t,
"health": self.health(),
"cpu": {"temp": _r(s.cpu.temp), "load": _r(s.cpu.load), "clock": _r(s.cpu.clock, 0), "power": _r(s.cpu.power)},
"gpu": {"temp": _r(s.gpu.temp), "load": _r(s.gpu.load), "clock": _r(s.gpu.clock, 0), "power": _r(s.gpu.power),
"vram_used": None if s.vram is None else s.vram[0],
+31 -2
View File
@@ -2,7 +2,8 @@
The tooltip shows the power draw; the menu shows each capability's status and has
"Open The Kurgan" (the web UI), "Start with Windows" and "Exit". Clicking the icon with the
left button opens the web UI directly.
left button opens the web UI directly. notify() shows a balloon tip when something starts
going wrong (fan failsafes, AI server errors, failing sensors).
"Start with Windows" switches the logon trigger of "The Kurgan" scheduled task (installed by
setup.ps1) on or off. The task itself stays enabled, so it can still be started by hand,
@@ -127,8 +128,10 @@ WM_NULL, WM_DESTROY, WM_CLOSE, WM_TIMER = 0x0000, 0x0002, 0x0010, 0x0113
WM_LBUTTONUP, WM_RBUTTONUP = 0x0202, 0x0205
WM_TRAY = 0x8000 + 1 # WM_APP + 1: Explorer -> us, mouse events on the icon
WM_TRAY_TIP = 0x8000 + 2 # WM_APP + 2: main thread -> us, tooltip changed
WM_TRAY_INFO = 0x8000 + 3 # WM_APP + 3: any thread -> us, balloon tip to show
NIM_ADD, NIM_MODIFY, NIM_DELETE = 0, 1, 2
NIF_MESSAGE, NIF_ICON, NIF_TIP = 0x1, 0x2, 0x4
NIF_MESSAGE, NIF_ICON, NIF_TIP, NIF_INFO = 0x1, 0x2, 0x4, 0x10
NIIF_NONE, NIIF_WARNING, NIIF_ERROR = 0x0, 0x2, 0x3
MF_STRING, MF_GRAYED, MF_CHECKED, MF_SEPARATOR = 0x0, 0x1, 0x8, 0x800
TPM_RIGHTBUTTON, TPM_NONOTIFY, TPM_RETURNCMD = 0x2, 0x80, 0x100
MB_ICONWARNING, MB_SETFOREGROUND = 0x30, 0x10000
@@ -213,6 +216,7 @@ class TrayIcon:
self.on_open = on_open
self.status_lines = status_lines or (lambda: [])
self._tip = title
self._info: tuple[str, str, int] | None = None
self._hwnd = None
self._hicon = None
self._shown = False
@@ -235,6 +239,27 @@ class TrayIcon:
if self._hwnd:
_u32.PostMessageW(self._hwnd, WM_TRAY_TIP, 0, 0)
def notify(self, title: str, message: str, warning: bool = False) -> None:
"""Show a balloon tip; safe from any thread (it queues on the tray window)."""
self._info = (title[:63], message[:255], NIIF_WARNING if warning else NIIF_NONE)
if self._hwnd:
_u32.PostMessageW(self._hwnd, WM_TRAY_INFO, 0, 0)
def _info_nid(self) -> NOTIFYICONDATAW:
title, message, flags = self._info
nid = NOTIFYICONDATAW()
nid.cbSize = ctypes.sizeof(nid)
nid.hWnd = self._hwnd
nid.uID = 1
nid.uFlags = NIF_INFO
nid.szInfo = message
nid.szInfoTitle = title
nid.dwInfoFlags = flags
return nid
def _show_info(self) -> None:
_shell32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(self._info_nid()))
def close(self) -> None:
if self._hwnd:
_u32.PostMessageW(self._hwnd, WM_CLOSE, 0, 0)
@@ -309,6 +334,10 @@ class TrayIcon:
if self._shown:
self._notify(NIM_MODIFY)
return 0
if msg == WM_TRAY_INFO:
if self._shown and self._info is not None:
self._show_info()
return 0
if msg == self._msg_taskbar or (msg == WM_TIMER and wparam == RETRY_TIMER):
self._add() # Explorer restarted (or the taskbar wasn't up yet)
return 0
+6
View File
@@ -445,11 +445,17 @@ function renderHeader(s) {
setText("hero-total", (power?.partial ? "≈" : "") + fmt.n0(power?.total));
const meta = $("meta");
const elevated = s.app.token?.elevated;
const health = Object.entries(s.telemetry.health ?? {});
meta.replaceChildren(
el("span", { class: "pill" }, el("span", { class: "dot good" }), "Live"),
el("span", { text: `Up ${fmt.dur(s.app.uptime)}` }),
el("span", { class: "pill", title: "PawnIO sensors, top fans and RAM lighting need admin rights" },
el("span", { class: `dot ${elevated ? "good" : "warning"}` }), elevated ? "Admin rights" : "No admin rights"),
...(health.length
? [el("span", { class: "pill", title: health.map(([name, h]) => `${name}: ${h.error}`).join("\n") },
el("span", { class: "dot warning" }),
`${health.length} sensor source${health.length > 1 ? "s are" : " is"} failing`)]
: []),
);
setText("footer", `${s.app.name} ${s.app.version} · pid ${s.app.pid} · log: %LOCALAPPDATA%\\Kurgan\\kurgan.log · JSON: /api/state`);
}
+97
View File
@@ -0,0 +1,97 @@
import unittest
from unittest.mock import Mock, patch
from kurgan import tray
from kurgan.app import alert_states, new_alerts
def fake_fans(gpu_status="GPU 50 C, 40% PWM", top_status="55 C, 45%"):
group = Mock()
group.name = "GPU"
group.status = gpu_status
top = Mock()
top.status = top_status
fans = Mock()
fans.groups = [group]
fans.top = top
return fans
def fake_ai(*errors):
ai = Mock()
ai.snapshot.return_value = {"backends": [{"key": key, "label": key.capitalize(), "error": error}
for key, error in errors]}
return ai
def fake_health(entries=None):
telemetry = Mock()
telemetry.health.return_value = entries or {}
return telemetry
class AlertStatesTest(unittest.TestCase):
def test_healthy_everything_is_quiet(self):
self.assertEqual(alert_states(fake_fans(), fake_ai(("strata", None), ("llama", None)),
fake_health()), {})
def test_failsafes_errors_and_failing_sources_are_collected(self):
states = alert_states(
fake_fans(gpu_status="FAILSAFE 100%: GPU temperature unavailable",
top_status="UNAVAILABLE (lost); BIOS curve keeps control"),
fake_ai(("strata", "exited (code 3); restarting."), ("llama", None)),
fake_health({"GPU sensors": {"error": "NVMLError: uninitialised", "age_s": 3.0}}))
self.assertEqual(states, {
"fans/GPU": "GPU case fans: FAILSAFE 100%: GPU temperature unavailable",
"fans/top": "Top fans: UNAVAILABLE (lost); BIOS curve keeps control",
"ai/strata": "Strata: exited (code 3); restarting.",
"telemetry/GPU sensors": "GPU sensors read failed (NVMLError: uninitialised); continuing without it",
})
def test_fans_or_ai_being_off_is_not_an_error(self):
self.assertEqual(alert_states(None, None, fake_health()), {})
class NewAlertsTest(unittest.TestCase):
def test_only_new_keys_alert_and_recovery_is_quiet(self):
known = {"fans/GPU": "an earlier message"}
states = {"fans/GPU": "still failing", "ai/strata": "exited"}
self.assertEqual(new_alerts(known, states), [("ai/strata", "exited")])
self.assertEqual(new_alerts(states, {}), []) # everything recovered: nothing new
self.assertEqual(new_alerts({}, states), [("ai/strata", "exited"), ("fans/GPU", "still failing")])
class TrayNotifyTest(unittest.TestCase):
def make_icon(self):
return tray.TrayIcon("The Kurgan", "unused.ico", on_exit=lambda: None)
def test_notify_queues_a_balloon_and_pings_the_tray_thread(self):
icon = self.make_icon()
icon.notify("The Kurgan", "Top fans: FAILSAFE 100%", warning=True) # no window yet: just stored
self.assertEqual(icon._info, ("The Kurgan", "Top fans: FAILSAFE 100%", tray.NIIF_WARNING))
icon._hwnd = 123
with patch.object(tray, "_u32") as u32:
icon.notify("The Kurgan", "hello")
u32.PostMessageW.assert_called_once_with(123, tray.WM_TRAY_INFO, 0, 0)
self.assertEqual(icon._info[2], tray.NIIF_NONE)
def test_messages_are_cut_to_what_the_structure_holds(self):
icon = self.make_icon()
icon.notify("t" * 100, "m" * 300)
title, message, _ = icon._info
self.assertEqual((len(title), len(message)), (63, 255))
def test_the_balloon_fields_are_filled_and_shown(self):
icon = self.make_icon()
icon._hwnd = 1
icon._info = ("The Kurgan", "GPU case fans: FAILSAFE 100%", tray.NIIF_WARNING)
nid = icon._info_nid()
self.assertEqual((nid.uFlags, nid.szInfoTitle, nid.szInfo, nid.dwInfoFlags),
(tray.NIF_INFO, "The Kurgan", "GPU case fans: FAILSAFE 100%", tray.NIIF_WARNING))
with patch.object(tray, "_shell32") as shell:
icon._show_info()
self.assertEqual(shell.Shell_NotifyIconW.call_args.args[0], tray.NIM_MODIFY)
if __name__ == "__main__":
unittest.main()
+89
View File
@@ -0,0 +1,89 @@
import threading
import unittest
from kurgan.telemetry.readings import PowerReadings, Readings
from kurgan.telemetry.service import Telemetry
class FakeSource:
"""A cpu/gpu-shaped source: readings, plus the memory query the GPU one provides."""
def __init__(self):
self.fail = False
self.memory_fails = False
def read(self, *args):
if self.fail:
raise OSError("device gone")
return Readings(temp=50, load=10, clock=4000, power=30)
def memory(self):
if self.memory_fails:
raise OSError("nvml busy")
return (8 * 1024 ** 3, 24 * 1024 ** 3)
class FakeSystem:
def __init__(self):
self.fail = False
def read(self, cpu, gpu):
if self.fail:
raise OSError("commander gone")
return PowerReadings(cpu=cpu.power, gpu=gpu.power, other=40, parts={"fans": 2.0})
class TelemetryHealthTest(unittest.TestCase):
def setUp(self):
self.cpu, self.gpu, self.system = FakeSource(), FakeSource(), FakeSystem()
self.telemetry = Telemetry(self.cpu, self.gpu, self.system)
def test_before_the_first_read_there_is_nothing_to_report(self):
self.assertEqual(self.telemetry.snapshot(), {"seq": 0, "health": {}})
def test_a_healthy_run_has_no_health_entries(self):
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {})
self.assertEqual(self.telemetry.snapshot()["health"], {})
def test_a_failing_source_costs_only_itself_and_is_reported(self):
self.cpu.fail = True
with self.assertLogs("kurgan.telemetry.service", level="WARNING"):
sample = self.telemetry.read()
health = self.telemetry.health()
self.assertEqual(list(health), ["CPU sensors"])
self.assertIn("device gone", health["CPU sensors"]["error"])
self.assertIsNone(sample.cpu.temp) # the fallback stands in ...
self.assertEqual(sample.gpu.temp, 50) # ... while every other source still reads
self.assertEqual(sample.power.total, 70) # GPU 30 W + other 40 W; the CPU part is missing
def test_recovery_clears_the_entry(self):
self.gpu.fail = True
with self.assertLogs("kurgan.telemetry.service", level="WARNING"):
self.telemetry.read()
self.assertEqual(list(self.telemetry.health()), ["GPU sensors"])
self.gpu.fail = False
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {})
def test_the_snapshot_carries_health(self):
self.system.fail = True
self.gpu.memory_fails = True
first, stop = threading.Event(), threading.Event()
self.telemetry.subscribe(lambda sample: first.set())
with self.assertLogs("kurgan.telemetry.service", level="WARNING") as logs:
thread = threading.Thread(target=self.telemetry.run, args=(stop,), daemon=True)
thread.start()
self.assertTrue(first.wait(5)) # the listener fires after read(): both warnings are out
stop.set()
thread.join(5)
self.assertEqual(len(logs.output), 2) # each failing source is reported once
health = self.telemetry.snapshot()["health"]
self.assertEqual(set(health), {"system power", "GPU memory"})
snapshot = self.telemetry.snapshot()
self.assertIsNone(snapshot["gpu"]["vram_used"])
self.assertEqual(snapshot["gpu"]["temp"], 50)
if __name__ == "__main__":
unittest.main()