Privilege split 6/11: the app reads and drives the hardware through the service

- kurgan/hw/client.py: HardwareClient polls the service's state once a second
  on its own thread, reconnecting (and greeting again) whenever the pipe
  breaks, and sends the app's chase clock with each poll. Profile and RAM
  lighting changes are sent at once: bad values are ValueError before anything
  is sent; an unreachable or refusing service is HardwareUnavailable. A state
  that stops arriving (5 s) or a service loop that stops publishing (15 s)
  counts as unavailable. PipeTransport for the real pipe, LocalTransport (same
  encoding and checks, no pipe) for --demo and tests.
- Telemetry: the CPU package temperature and power (CpuSensors(package=...))
  and the Commander PRO RPMs for the power model (SystemPower(fans=...)) come
  from the service; the app opens neither PawnIO nor the Commander PRO.
  "hardware service" is its own health source, and while it's down the
  missing CPU temperature isn't reported a second time.
- The fan UI, profile buttons and fan history come from the service's state;
  the RAM lighting zone goes through it (LightingService(ram=...)), and the
  case fan and GPU zones stay local. The alert monitor balloons "Hardware
  service unavailable"; the header shows a hardware service pill instead of
  the admin-rights one (and warns if the app itself runs elevated); the tray
  lines read the service's fans. POSTs answer 503 while it's unavailable.
- Removed --gpu-fan-ports, --no-gpu-fan-control and --rgb-memory-*: the
  service owns those now.
- settings.json: cooling and lighting.memory are legacy. Old files keep them
  (still validated), nothing reads them, and defaults no longer add them.
- --demo runs the real HardwareService in-process on the demo fakes, with its
  settings in demo-hw-settings.json, through the same client.
- --preview reads the CPU temperature and fan power from the service too.
- Tests: 13 for the client (including a real pipe end to end); the alert,
  lighting, settings and web tests follow the new shapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
paulandClaude Opus 5.5 committed 2026-12-05 19:41:51 +13:00
1 parent 3e84ab1322
commit eb771656fb
15 files changed
+803 -179

No files matched your search

+14 -12
View File
@@ -5,16 +5,10 @@ from kurgan import tray
from kurgan.app import ALERT_REPEAT_SECONDS, alert_states, balloon, due_alerts, 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_cooling(gpu_status="GPU 50 C, 40% PWM", top_status="55 C, 45%"):
"""The hardware service's fan state, as HardwareClient.cooling() returns it."""
return {"profile": "balanced", "groups": [{"name": "GPU", "duty": 40, "status": gpu_status}],
"top": {"duty": 45, "status": top_status}, "note": None, "row": None}
def fake_ai(*errors):
@@ -32,12 +26,12 @@ def fake_health(entries=None):
class AlertStatesTest(unittest.TestCase):
def test_healthy_everything_is_quiet(self):
self.assertEqual(alert_states(fake_fans(), fake_ai(("strata", None), ("llama", None)),
self.assertEqual(alert_states(fake_cooling(), 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",
fake_cooling(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}}))
@@ -50,6 +44,14 @@ class AlertStatesTest(unittest.TestCase):
def test_fans_or_ai_being_off_is_not_an_error(self):
self.assertEqual(alert_states(None, None, fake_health()), {})
not_set_up = {"profile": "balanced", "groups": [], "top": None, "note": "Fan control isn't set up", "row": None}
self.assertEqual(alert_states(not_set_up, None, fake_health()), {})
def test_the_hardware_service_being_unavailable_is_one_alert_of_its_own(self):
states = alert_states({"profile": None, "groups": [], "top": None, "note": "unavailable", "row": None}, None,
fake_health({"hardware service": {"error": "the hardware service isn't running (no pipe)",
"age_s": 0.0}}))
self.assertEqual(states, {"hw": "Hardware service unavailable: the hardware service isn't running (no pipe)"})
class NewAlertsTest(unittest.TestCase):
+212
View File
@@ -0,0 +1,212 @@
import json
import os
import tempfile
import threading
import time
import unittest
from kurgan import demo
from kurgan.hw import client as hw_client
from kurgan.hw.client import (CommanderReadings, CpuPackage, HardwareClient, HardwareUnavailable, LocalTransport,
PipeTransport, RamLighting)
from kurgan.hw.pipe import PipeError, PipeServer, current_user_sid, pipe_sddl
from kurgan.hw.protocol import VERSION, RemoteError, Session
from kurgan.telemetry.sensors import CpuSensors, SystemPower
from kurgan.telemetry.service import SERVICE_SOURCE, Telemetry
class Service:
"""The demo's hardware service (the real HardwareService on fakes) and a client to it."""
def __init__(self, test: unittest.TestCase):
directory = tempfile.TemporaryDirectory()
test.addCleanup(directory.cleanup)
self.path = os.path.join(directory.name, "hw-settings.json")
self.service = demo.hardware_service(self.path)
self.service.tick(time.monotonic())
self.connects = 0
self.down = False # the next connects fail, as with no pipe
self.transport: LocalTransport | None = None
def connect(self):
self.connects += 1
if self.down:
raise PipeError("the hardware service isn't running (no pipe)", 2)
self.transport = LocalTransport(self.service.dispatch)
return self.transport
def saved(self) -> dict:
with open(self.path, encoding="utf-8") as stream:
return json.load(stream)
class ClientTest(unittest.TestCase):
def setUp(self):
self.hw = Service(self)
self.client = HardwareClient(self.hw.connect)
def test_reads_the_services_state(self):
self.client.poll()
self.assertIsNone(self.client.error)
cooling = self.client.cooling()
self.assertEqual([g["name"] for g in cooling["groups"]], ["GPU", "CPU"])
self.assertEqual(cooling["profile"], "balanced")
self.assertEqual(len(cooling["row"]), 4)
self.assertIsNotNone(self.client.cpu()["temp"])
self.assertEqual(len(self.client.fan_rpms()), 6)
self.assertEqual(self.client.ram_lighting()["mode"], "off")
snapshot = self.client.snapshot()
self.assertTrue(snapshot["available"])
self.assertEqual(snapshot["pid"], os.getpid())
def test_changes_go_to_the_service_and_are_saved_there(self):
self.client.poll()
self.client.set_profile("quiet")
self.assertEqual(self.client.cooling()["profile"], "quiet") # the reply's state, no poll needed
self.client.set_ram_lighting("chase")
self.assertEqual(RamLighting(self.client).mode, "chase")
self.assertEqual(self.hw.saved()["cooling"]["profile"], "quiet")
self.assertEqual(self.hw.saved()["lighting"]["memory"], "chase")
def test_bad_values_are_value_errors_and_nothing_is_sent(self):
self.client.poll()
for call, value in ((self.client.set_profile, "turbo"), (self.client.set_ram_lighting, "rainbow")):
with self.subTest(value=value), self.assertRaises(ValueError):
call(value)
self.assertEqual(self.hw.saved()["cooling"]["profile"], "balanced")
def test_without_a_service_everything_reads_empty_and_changes_raise(self):
self.hw.down = True
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIn("isn't running", self.client.error)
self.assertIsNone(self.client.state)
cooling = self.client.cooling()
self.assertEqual((cooling["groups"], cooling["top"], cooling["row"]), ([], None, None))
self.assertIn("Hardware service unavailable", cooling["note"])
self.assertEqual(self.client.fan_rpms(), [])
self.assertEqual(CpuPackage(self.client).read(), (None, None))
self.assertIn("unavailable", CpuPackage(self.client).status)
self.assertIn("unavailable", RamLighting(self.client).status)
self.assertFalse(self.client.snapshot()["available"])
with self.assertRaises(HardwareUnavailable):
self.client.set_profile("quiet")
def test_reconnects_and_greets_again_after_the_service_restarts(self):
self.client.poll()
self.client.set_profile("quiet")
self.hw.transport.close() # the service went away mid-connection
self.hw.down = True
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIsNotNone(self.client.error)
self.assertEqual(self.client.cooling()["profile"], "quiet") # the last one known, for the buttons
self.hw.down = False
with self.assertLogs("kurgan.hw.client", level="INFO"):
self.client.poll()
self.assertIsNone(self.client.error)
self.assertEqual(self.hw.connects, 2) # the failed poll found the old connection broken
self.assertTrue(self.hw.transport._session.greeted)
def test_a_different_protocol_drops_the_connection_and_says_what_to_do(self):
class Old:
closed = False
def call(self, op, args=None, timeout=None):
raise RemoteError(VERSION, "the service speaks protocol 2, the client 1")
def close(self):
self.closed = True
old = Old()
client = HardwareClient(lambda: old)
with self.assertLogs("kurgan.hw.client", level="WARNING"):
client.poll()
self.assertIn("re-run setup.ps1", client.error)
self.assertTrue(old.closed)
def test_a_refusal_by_a_service_that_is_up_keeps_the_connection(self):
self.client.poll()
self.hw.service.settings = None # hw-settings.json turned out invalid
self.hw.service.settings_error = "cooling.profile must be one of ..."
with self.assertRaises(HardwareUnavailable) as raised:
self.client.set_profile("quiet")
self.assertIn("hw-settings.json is invalid", str(raised.exception))
self.client.poll()
self.assertIsNone(self.client.error)
self.assertEqual(self.hw.connects, 1)
def test_a_stuck_service_loop_counts_as_unavailable(self):
self.client.poll()
self.hw.service._snapshot["t"] = time.time() - 60 # the loop stopped publishing a minute ago
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIn("stalled", self.client.error)
self.assertIsNone(self.client.state)
def test_an_old_state_is_no_state(self):
self.client.poll()
self.client._state_at -= hw_client.STALE_SECONDS + 1 # no poll got through since
self.assertEqual(self.client.error, "no state from the hardware service")
self.assertEqual(self.client.fan_rpms(), [])
def test_each_poll_sends_the_chase_clock(self):
self.client.chase = lambda: {"phase": 123.0, "rate": 9.0, "power": 400.0}
self.client.poll()
chase = self.hw.service.chase
self.assertEqual((chase.phase, chase.rate), (123.0, 9.0))
def test_the_app_side_readers_take_the_services_values(self):
self.client.poll()
state = self.client.state
self.assertEqual(CommanderReadings(self.client).read(), state["commander"]["rpms"])
cpu = CpuSensors(package=CpuPackage(self.client))
self.assertEqual(cpu.read().temp, state["cpu"]["temp"])
self.assertEqual(cpu.status, "ok")
def test_telemetry_lists_the_service_once_not_also_the_cpu_temperature(self):
self.hw.down = True
cpu = CpuSensors(package=CpuPackage(self.client))
fake = demo.FakeGpu()
telemetry = Telemetry(cpu, fake, SystemPower(fans=CommanderReadings(self.client)), hw=self.client)
with self.assertLogs("kurgan", level="WARNING"):
for _ in range(3):
self.client.poll()
sample = telemetry.read()
self.assertIsNone(sample.cpu.temp)
self.assertEqual(list(telemetry.health()), [SERVICE_SOURCE])
self.hw.down = False
with self.assertLogs("kurgan", level="INFO"):
self.client.poll()
telemetry.read()
self.assertEqual(telemetry.health(), {})
class PipeEndToEndTest(unittest.TestCase):
def test_the_client_over_a_real_pipe(self):
me = current_user_sid()
hw = Service(self)
name = rf"\\.\pipe\kurgan-hw-client-test-{os.getpid()}"
server = PipeServer(name, pipe_sddl(me, server_sid=me), lambda: Session(hw.service.dispatch, "test"))
server.start()
self.addCleanup(server.close)
client = HardwareClient(lambda: PipeTransport(name, trusted_owners=None))
deadline = time.monotonic() + 2
while True: # the listener may not have created the pipe yet
with self.assertLogs("kurgan.hw.client", level="INFO"):
client.poll()
if client.error is None or time.monotonic() > deadline:
break
self.assertIsNone(client.error)
client.set_profile("performance")
self.assertEqual(hw.saved()["cooling"]["profile"], "performance")
stop = threading.Event()
thread = threading.Thread(target=client.run, args=(stop,))
thread.start()
stop.set()
thread.join(5)
self.assertFalse(thread.is_alive())
if __name__ == "__main__":
unittest.main()
+49 -8
View File
@@ -18,6 +18,19 @@ class FakeWorker:
pass
class FakeRam:
"""The RAM zone in the hardware service (kurgan.hw.client.RamLighting)."""
def __init__(self):
self.mode, self.status, self.error = "off", "off", None
def set_mode(self, mode):
if self.error is not None:
raise self.error
self.mode = mode
self.status = f"{mode} (service)"
class LightingServiceTest(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
@@ -25,22 +38,50 @@ class LightingServiceTest(unittest.TestCase):
self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None)
def service(self, overrides=None):
self.ram = FakeRam()
return LightingService(self.settings, Theme(), (0.15, 0.025, 150.0, 550.0), overrides,
rgb=FakeWorker(), memory=FakeWorker(), gpu=FakeWorker())
ram=self.ram, rgb=FakeWorker(), gpu=FakeWorker())
def active(self, service, zone):
return sorted(mode for mode, event in service._events[zone].items() if event.is_set())
def test_saved_modes_start_and_switch_exclusively(self):
self.settings.update("lighting", memory="temperature")
self.settings.update("lighting", case_fans="temperature")
service = self.service()
self.assertEqual(self.active(service, "memory"), ["temperature"])
service.set_mode("memory", "chase")
self.assertEqual(self.active(service, "memory"), ["chase"])
self.assertEqual(self.active(service, "case_fans"), ["temperature"])
service.set_mode("case_fans", "chase")
self.assertEqual(self.active(service, "case_fans"), ["chase"])
self.assertEqual(self.active(service, "gpu"), [])
service.set_mode("case_fans", "off")
self.assertEqual(self.active(service, "case_fans"), [])
service.set_mode("memory", "off")
self.assertEqual(self.active(service, "memory"), [])
self.assertEqual(Settings(self.settings.path, None).get("lighting", "memory"), "off")
self.assertEqual(Settings(self.settings.path, None).get("lighting", "case_fans"), "off")
def test_the_ram_is_the_hardware_services_and_not_saved_here(self):
self.settings.update("lighting", memory="temperature") # an old settings.json: ignored
service = self.service()
self.assertNotIn("memory", service._events)
self.assertEqual(service.mode("memory"), "off")
service.set_mode("memory", "chase")
self.assertEqual(self.ram.mode, "chase")
zone = service.snapshot()["zones"][1]
self.assertEqual((zone["key"], zone["mode"], zone["status"]), ("memory", "chase", "chase (service)"))
self.assertEqual(self.settings.get("lighting", "memory"), "temperature") # left alone
self.assertEqual(service.snapshot()["chase_ms_per_led"], 150) # a RAM chase counts
self.ram.error = OSError("the hardware service isn't running (no pipe)")
with self.assertRaises(OSError):
service.set_mode("memory", "off")
self.assertEqual(service.mode("memory"), "chase")
def test_the_chase_clock_is_what_the_hardware_service_takes(self):
from kurgan.hw.protocol import check_args
service = self.service()
service.on_telemetry(50, 50, 350.0)
clock = service.chase_clock()
self.assertEqual(check_args("ram_chase", clock), clock)
self.assertEqual(clock["power"], 350.0)
later = service.chase_clock()
self.assertGreaterEqual(later["phase"], clock["phase"])
def test_failed_save_leaves_the_lights_as_they_were(self):
service = self.service()
+14 -4
View File
@@ -24,11 +24,21 @@ class ValidateTest(unittest.TestCase):
validate({"cooling": cooling})
def test_lighting_modes_follow_each_zone(self):
self.assertEqual(validate({"lighting": {"memory": "chase"}})["lighting"]["memory"], "chase")
for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}):
self.assertEqual(validate({"lighting": {"case_fans": "chase"}})["lighting"]["case_fans"], "chase")
for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}, {"memory": "rainbow"}):
with self.subTest(lighting=lighting), self.assertRaises(SettingsError):
validate({"lighting": lighting})
def test_the_hardware_services_old_sections_are_checked_kept_and_never_added(self):
self.assertNotIn("cooling", validate({}))
self.assertNotIn("memory", validate({})["lighting"])
old = validate({"cooling": {"profile": "quiet", "gpu_ports": [4, 5, 6]}, "lighting": {"memory": "chase"}})
self.assertEqual(old["cooling"], {"profile": "quiet", "gpu_ports": [4, 5, 6]})
self.assertEqual(old["lighting"]["memory"], "chase")
self.assertEqual(validate({"cooling": {"gpu_ports": [4, 5, 6]}})["cooling"]["profile"], "balanced")
with self.assertRaises(SettingsError):
validate({"cooling": {"profile": "quiet", "fans": 3}})
def test_ai_choices_and_ports(self):
self.assertEqual(validate({"ai": {"active": "llama"}})["ai"]["active"], "llama")
for ai in ({"active": "ollama"}, {"strata_model": "q8"}, {"strata_port": 80},
@@ -95,8 +105,8 @@ class SettingsFileTest(unittest.TestCase):
def test_returned_sections_are_copies(self):
settings = Settings(self.path, None)
settings.section("lighting")["memory"] = "chase"
self.assertEqual(settings.get("lighting", "memory"), "off")
settings.section("lighting")["case_fans"] = "chase"
self.assertEqual(settings.get("lighting", "case_fans"), "off")
if __name__ == "__main__":
+4
View File
@@ -3,6 +3,7 @@ import json
import socket
import unittest
from kurgan.hw.client import HardwareUnavailable
from kurgan.web.server import WebServer
@@ -28,6 +29,8 @@ class FakeApp:
self.calls.append(("profile", profile))
if profile == "full-disk":
raise OSError("disk full")
if profile == "no-service":
raise HardwareUnavailable("the hardware service isn't running (no pipe)")
def set_ai(self, backend, variant):
self.calls.append(("ai", backend, variant))
@@ -119,6 +122,7 @@ class WebServerTest(unittest.TestCase):
("/api/lighting", b"x" * 20000, 400, "oversized"),
("/api/ai/active", {"backend": 3}, 400, "string or null"),
("/api/cooling/profile", {"profile": "full-disk"}, 500, "disk full"),
("/api/cooling/profile", {"profile": "no-service"}, 503, "isn't running"),
("/api/fans", {"x": 1}, 404, None))
for path, body, expected, message in cases:
with self.subTest(path=path, body=body):