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

+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`);
}