Files
the_kurgan/kurgan/tray.py
T
paul ba39016d52 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.
2026-12-05 17:51:00 +13:00

437 lines
18 KiB
Python

"""Notification-area icon for The Kurgan.
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. 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,
with admin rights and no UAC prompt: Start-ScheduledTask "The Kurgan"
The Kurgan usually runs elevated while Explorer doesn't, so Windows would drop Explorer's
clicks on the icon; the window explicitly accepts those messages (ChangeWindowMessageFilterEx).
"""
from __future__ import annotations
import ctypes
import ctypes.wintypes as wt
import logging
import subprocess
import threading
log = logging.getLogger(__name__)
TASK_NAME = "The Kurgan"
LEGACY_TASK_NAME = "TT LCD Dashboard" # until setup.ps1 re-registers the task
# ----------------------------------------------------------------------------- startup task
def _powershell(script: str) -> str:
r = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script],
capture_output=True, text=True, timeout=60, creationflags=subprocess.CREATE_NO_WINDOW)
if r.returncode != 0:
lines = [ln.strip() for ln in (r.stderr or r.stdout).splitlines() if ln.strip()]
raise RuntimeError(lines[0] if lines else f"PowerShell exited with code {r.returncode}")
return r.stdout.strip()
_QUERY = """
$t = Get-ScheduledTask -TaskName '%TASK%' -ErrorAction SilentlyContinue
if (-not $t) { 'missing' }
elseif ($t.State -ne 'Disabled' -and @($t.Triggers | Where-Object {
$_.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger' -and $_.Enabled }).Count) { 'on' }
else { 'off' }
"""
_SET = """
$ErrorActionPreference = 'Stop'
$t = Get-ScheduledTask -TaskName '%TASK%'
$n = 0
foreach ($tr in $t.Triggers) {
if ($tr.CimClass.CimClassName -eq 'MSFT_TaskLogonTrigger') { $tr.Enabled = %ON%; $n++ }
}
if (-not $n) { throw 'The startup task has no logon trigger; run setup.ps1 again.' }
Set-ScheduledTask -InputObject $t | Out-Null
if (%ON% -and $t.State -eq 'Disabled') { Enable-ScheduledTask -TaskName '%TASK%' | Out-Null }
"""
def _task_state(name: str) -> str:
return _powershell(_QUERY.replace("%TASK%", name))
def startup_task() -> str | None:
"""The installed startup task's name, preferring The Kurgan's own."""
for name in (TASK_NAME, LEGACY_TASK_NAME):
if _task_state(name) != "missing":
return name
return None
def autostart_enabled() -> bool | None:
"""True/False: the startup task does/doesn't run at logon. None: it isn't installed."""
name = startup_task()
return None if name is None else _task_state(name) == "on"
def set_autostart(on: bool) -> None:
name = startup_task()
if name is None:
raise RuntimeError("The startup task isn't installed; run setup.ps1.")
_powershell(_SET.replace("%TASK%", name).replace("%ON%", "$true" if on else "$false"))
# ----------------------------------------------------------------------------- icon image
def make_icon(path: str, layers: list[tuple[int, int, int]]) -> str:
"""Draw a small version of the dashboard's power tank and save it as a .ico file.
layers: colours from the bottom up (other, CPU, GPU).
"""
from PIL import Image, ImageDraw
s = 256
img = Image.new("RGBA", (s, s), (0, 0, 0, 0))
d = ImageDraw.Draw(img)
chrome, dark = (206, 206, 212, 255), (20, 20, 24, 255)
x0, x1 = 52, 204 # glass
d.rectangle([x0, 30, x1, 226], fill=dark)
y = 226
for h, c in zip((50, 42, 56), layers): # bottom up
d.rectangle([x0, y - h, x1, y], fill=c + (255,))
y -= h
d.rectangle([x0, y - 3, x1, y + 3], fill=dark)
hl = Image.new("RGBA", (s, s), (0, 0, 0, 0))
ImageDraw.Draw(hl).rectangle([x0 + 22, 36, x0 + 40, 222], fill=(255, 255, 255, 70))
img.alpha_composite(hl)
d = ImageDraw.Draw(img)
for y0, y1 in ((4, 40), (216, 252)): # end caps
d.rounded_rectangle([28, y0, 228, y1], radius=12, fill=chrome)
d.rectangle([28, (y0 + y1) // 2 - 2, 228, (y0 + y1) // 2 + 2], fill=(120, 120, 128, 255))
img.save(path, sizes=[(16, 16), (20, 20), (24, 24), (32, 32), (40, 40), (48, 48), (64, 64)])
return path
# ----------------------------------------------------------------------------- Win32
_u32 = ctypes.WinDLL("user32", use_last_error=True)
_shell32 = ctypes.WinDLL("shell32", use_last_error=True)
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
LRESULT = ctypes.c_ssize_t
WNDPROC = ctypes.WINFUNCTYPE(LRESULT, wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM)
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, 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
MSGFLT_ALLOW = 1
RETRY_TIMER = 1
class WNDCLASSEXW(ctypes.Structure):
_fields_ = [("cbSize", wt.UINT), ("style", wt.UINT), ("lpfnWndProc", WNDPROC), ("cbClsExtra", ctypes.c_int),
("cbWndExtra", ctypes.c_int), ("hInstance", wt.HINSTANCE), ("hIcon", wt.HICON),
("hCursor", wt.HANDLE), ("hbrBackground", wt.HBRUSH), ("lpszMenuName", wt.LPCWSTR),
("lpszClassName", wt.LPCWSTR), ("hIconSm", wt.HICON)]
class NOTIFYICONDATAW(ctypes.Structure):
_fields_ = [("cbSize", wt.DWORD), ("hWnd", wt.HWND), ("uID", wt.UINT), ("uFlags", wt.UINT),
("uCallbackMessage", wt.UINT), ("hIcon", wt.HICON), ("szTip", wt.WCHAR * 128),
("dwState", wt.DWORD), ("dwStateMask", wt.DWORD), ("szInfo", wt.WCHAR * 256),
("uVersion", wt.UINT), ("szInfoTitle", wt.WCHAR * 64), ("dwInfoFlags", wt.DWORD),
("guidItem", ctypes.c_byte * 16), ("hBalloonIcon", wt.HICON)]
_u32.RegisterClassExW.argtypes = [ctypes.POINTER(WNDCLASSEXW)]
_u32.RegisterClassExW.restype = wt.ATOM
_u32.CreateWindowExW.argtypes = [wt.DWORD, wt.LPCWSTR, wt.LPCWSTR, wt.DWORD, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int, wt.HWND, wt.HMENU, wt.HINSTANCE, wt.LPVOID]
_u32.CreateWindowExW.restype = wt.HWND
_u32.DefWindowProcW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM]
_u32.DefWindowProcW.restype = LRESULT
_u32.GetMessageW.argtypes = [ctypes.POINTER(wt.MSG), wt.HWND, wt.UINT, wt.UINT]
_u32.GetMessageW.restype = wt.BOOL
_u32.TranslateMessage.argtypes = [ctypes.POINTER(wt.MSG)]
_u32.DispatchMessageW.argtypes = [ctypes.POINTER(wt.MSG)]
_u32.DispatchMessageW.restype = LRESULT
_u32.PostMessageW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM]
_u32.PostMessageW.restype = wt.BOOL
_u32.PostQuitMessage.argtypes = [ctypes.c_int]
_u32.DestroyWindow.argtypes = [wt.HWND]
_u32.RegisterWindowMessageW.argtypes = [wt.LPCWSTR]
_u32.RegisterWindowMessageW.restype = wt.UINT
_u32.ChangeWindowMessageFilterEx.argtypes = [wt.HWND, wt.UINT, wt.DWORD, wt.LPVOID]
_u32.ChangeWindowMessageFilterEx.restype = wt.BOOL
_u32.LoadImageW.argtypes = [wt.HINSTANCE, wt.LPCWSTR, wt.UINT, ctypes.c_int, ctypes.c_int, wt.UINT]
_u32.LoadImageW.restype = wt.HANDLE
_u32.DestroyIcon.argtypes = [wt.HICON]
_u32.CreatePopupMenu.restype = wt.HMENU
_u32.AppendMenuW.argtypes = [wt.HMENU, wt.UINT, ctypes.c_size_t, wt.LPCWSTR]
_u32.TrackPopupMenu.argtypes = [wt.HMENU, wt.UINT, ctypes.c_int, ctypes.c_int, ctypes.c_int, wt.HWND, wt.LPVOID]
_u32.TrackPopupMenu.restype = ctypes.c_int
_u32.DestroyMenu.argtypes = [wt.HMENU]
_u32.GetCursorPos.argtypes = [ctypes.POINTER(wt.POINT)]
_u32.SetForegroundWindow.argtypes = [wt.HWND]
_u32.SetTimer.argtypes = [wt.HWND, ctypes.c_size_t, wt.UINT, wt.LPVOID]
_u32.SetTimer.restype = ctypes.c_size_t
_u32.KillTimer.argtypes = [wt.HWND, ctypes.c_size_t]
_u32.MessageBoxW.argtypes = [wt.HWND, wt.LPCWSTR, wt.LPCWSTR, wt.UINT]
_shell32.Shell_NotifyIconW.argtypes = [wt.DWORD, ctypes.POINTER(NOTIFYICONDATAW)]
_shell32.Shell_NotifyIconW.restype = wt.BOOL
_k32.GetModuleHandleW.argtypes = [wt.LPCWSTR]
_k32.GetModuleHandleW.restype = wt.HMODULE
def _is_admin() -> bool:
try:
return bool(_shell32.IsUserAnAdmin())
except Exception:
return False
class TrayIcon:
"""Notification-area icon on its own thread.
status_lines() is called when the menu opens; on_open/on_exit are called from the tray thread."""
CLASS_NAME = "KurganTray"
ID_OPEN, ID_AUTOSTART, ID_EXIT = 1, 2, 3
def __init__(self, title: str, icon_path: str, on_exit, on_open=None, status_lines=None):
self.title = title
self.icon_path = icon_path
self.on_exit = on_exit
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
self._autostart: bool | None = None
self._autostart_known = False
self._msg_taskbar = _u32.RegisterWindowMessageW("TaskbarCreated")
self._wndproc = WNDPROC(self._proc) # keep a reference: Windows calls it
self._thread = threading.Thread(target=self._run, name="tray", daemon=True)
# -- called from other threads
def start(self) -> None:
self._thread.start()
threading.Thread(target=self._refresh_autostart, name="tray-autostart", daemon=True).start()
def set_tooltip(self, text: str) -> None:
text = text[:127]
if text != self._tip:
self._tip = text
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)
self._thread.join(timeout=3)
# -- tray thread
def _run(self) -> None:
try:
try:
_u32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # per-monitor v2: crisp menu and icon
except Exception:
pass
hinst = _k32.GetModuleHandleW(None)
wc = WNDCLASSEXW()
wc.cbSize = ctypes.sizeof(wc)
wc.lpfnWndProc = self._wndproc
wc.hInstance = hinst
wc.lpszClassName = self.CLASS_NAME
_u32.RegisterClassExW(ctypes.byref(wc)) # fails harmlessly if already registered
# A hidden top-level window: message-only windows miss the TaskbarCreated broadcast.
hwnd = _u32.CreateWindowExW(0, self.CLASS_NAME, self.title, 0, 0, 0, 0, 0, None, None, hinst, None)
if not hwnd:
raise OSError(f"CreateWindowEx failed: {ctypes.FormatError(ctypes.get_last_error()).strip()}")
for msg in (WM_TRAY, self._msg_taskbar):
_u32.ChangeWindowMessageFilterEx(hwnd, msg, MSGFLT_ALLOW, None)
size = _u32.GetSystemMetrics(49) # SM_CXSMICON
self._hicon = _u32.LoadImageW(None, self.icon_path, 1, size, size, 0x10) # IMAGE_ICON, LR_LOADFROMFILE
self._hwnd = hwnd
self._add()
msg = wt.MSG()
while _u32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
_u32.TranslateMessage(ctypes.byref(msg))
_u32.DispatchMessageW(ctypes.byref(msg))
except Exception:
log.exception("Tray icon failed")
finally:
if self._hicon:
_u32.DestroyIcon(self._hicon)
self._hwnd = None
def _notify(self, op: int) -> bool:
nid = NOTIFYICONDATAW()
nid.cbSize = ctypes.sizeof(nid)
nid.hWnd = self._hwnd
nid.uID = 1
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP
nid.uCallbackMessage = WM_TRAY
nid.hIcon = self._hicon
nid.szTip = self._tip
return bool(_shell32.Shell_NotifyIconW(op, ctypes.byref(nid)))
def _add(self) -> None:
"""Add the icon; at logon the taskbar may not exist yet, so keep retrying."""
self._shown = self._notify(NIM_ADD) or self._notify(NIM_MODIFY)
if self._shown:
_u32.KillTimer(self._hwnd, RETRY_TIMER)
log.info("Tray icon shown")
else:
_u32.SetTimer(self._hwnd, RETRY_TIMER, 5000, None)
def _proc(self, hwnd, msg, wparam, lparam):
try:
if msg == WM_TRAY:
event = lparam & 0xFFFF
if event == WM_LBUTTONUP and self.on_open is not None:
self.on_open()
elif event in (WM_LBUTTONUP, WM_RBUTTONUP):
self._menu()
return 0
if msg == WM_TRAY_TIP:
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
if msg == WM_CLOSE:
self._notify(NIM_DELETE)
_u32.DestroyWindow(hwnd)
return 0
if msg == WM_DESTROY:
_u32.PostQuitMessage(0)
return 0
except Exception:
log.exception("Tray icon message %#x failed", msg)
return _u32.DefWindowProcW(hwnd, msg, wparam, lparam)
def _menu(self) -> None:
cmd = 0
m = _u32.CreatePopupMenu()
try:
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, self.title)
try:
lines = list(self.status_lines())
except Exception:
log.exception("Tray status failed")
lines = []
for line in lines:
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, 0, line[:120])
_u32.AppendMenuW(m, MF_SEPARATOR, 0, None)
if self.on_open is not None:
_u32.AppendMenuW(m, MF_STRING, self.ID_OPEN, f"Open {self.title}")
if not self._autostart_known:
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART, "Start with Windows (checking...)")
elif self._autostart is None:
_u32.AppendMenuW(m, MF_STRING | MF_GRAYED, self.ID_AUTOSTART,
"Start with Windows (run setup.ps1 first)")
else:
_u32.AppendMenuW(m, MF_STRING | (MF_CHECKED if self._autostart else 0), self.ID_AUTOSTART,
"Start with Windows")
_u32.AppendMenuW(m, MF_SEPARATOR, 0, None)
_u32.AppendMenuW(m, MF_STRING, self.ID_EXIT, "Exit")
pt = wt.POINT()
_u32.GetCursorPos(ctypes.byref(pt))
_u32.SetForegroundWindow(self._hwnd) # otherwise the menu doesn't close when clicking elsewhere
cmd = _u32.TrackPopupMenu(m, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, pt.x, pt.y, 0,
self._hwnd, None)
_u32.PostMessageW(self._hwnd, WM_NULL, 0, 0)
finally:
_u32.DestroyMenu(m)
if cmd == self.ID_EXIT:
log.info("Exit chosen from the tray menu")
self.on_exit()
elif cmd == self.ID_OPEN:
self.on_open()
elif cmd == self.ID_AUTOSTART:
self._toggle_autostart()
def _refresh_autostart(self) -> None:
try:
self._autostart = autostart_enabled()
except Exception as e:
log.warning("Couldn't read the startup task: %s", e)
self._autostart = None
self._autostart_known = True
def _toggle_autostart(self) -> None:
want = not self._autostart
try:
set_autostart(want)
log.info("Start with Windows turned %s", "on" if want else "off")
except Exception as e:
log.warning("Couldn't change Start with Windows: %s", e)
hint = "" if _is_admin() else (
"\n\nChanging this needs admin rights. The Kurgan has them when its startup task "
"starts it (Start-ScheduledTask \"The Kurgan\").")
_u32.MessageBoxW(self._hwnd, f"Couldn't turn Start with Windows {'on' if want else 'off'}.\n\n{e}{hint}",
self.title, MB_ICONWARNING | MB_SETFOREGROUND)
self._refresh_autostart() # show what the task really says now
if __name__ == "__main__":
# Quick check: show the icon for 20 s with a test tooltip.
import os
import tempfile
import time
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
print("Start with Windows:", autostart_enabled())
path = make_icon(os.path.join(tempfile.gettempdir(), "kurgan_tray_test.ico"),
[(217, 89, 38), (57, 135, 229), (25, 158, 112)])
done = threading.Event()
tray = TrayIcon("The Kurgan (test)", path, on_exit=done.set, status_lines=lambda: ["Test run"])
tray.start()
for i in range(20):
tray.set_tooltip(f"The Kurgan (test)\n{i} s")
if done.wait(1):
break
tray.close()