From eeb39c082be2ebb81a8205d26a3639ff000ebf23 Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Tue, 10 Nov 2026 12:17:03 +0100 Subject: feat(assistant): daemon client with chat, model and voice actions Co-Authored-By: Claude Opus 5.5 --- deckit/modules/assistant.py | 114 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_assistant.py | 109 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 223 insertions(+) diff --git a/deckit/modules/assistant.py b/deckit/modules/assistant.py index 088cac3..3069876 100644 --- a/deckit/modules/assistant.py +++ b/deckit/modules/assistant.py @@ -104,3 +104,117 @@ def hears(models, wanted): or next((m for m in local if m.get("status") != "unloaded"), None)) inputs = m.get("inputs") if m else None return inputs is None or "audio" in inputs + + +def make(cfg: dict) -> Module: + shell = os.path.expanduser(cfg.get("assistant", {}).get("shell", "")) + lock = threading.Lock() # guards st + send_lock = threading.Lock() # one writer on the socket at a time + stop = threading.Event() + st = blank() + conn = {"sock": None, "qarma": None} + + def send(cmd): + s = conn["sock"] + if s is None: + raise ModuleError("assistant not running") + try: + with send_lock: + s.sendall((json.dumps(cmd) + "\n").encode()) + except OSError as e: + raise ModuleError(f"assistant: {e}") from None + + def wanted(): + # Caller holds lock. As the canvas: the chat's pick, else the + # preferred model, else none (the daemon uses what is loaded). + return st["chatModel"] or (st["catalog"] or {}).get("preferred") or None + + def with_model(cmd): + with lock: + m = wanted() + return {**cmd, "model": m} if m else cmd + + def loop(): + while not stop.is_set(): + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + s.connect(str(SOCK)) + except OSError as e: + s.close() + with lock: + st.update(connected=False, error=str(e) or type(e).__name__) + stop.wait(5) + continue + conn["sock"] = s + with lock: + st.update(connected=True, error=None) + try: + send({"type": "models"}) + for line in s.makefile("r", encoding="utf-8"): + try: + e = json.loads(line) + except ValueError: + continue + with lock: + fold(st, e) + except (OSError, ModuleError): + pass + conn["sock"] = None + s.close() + with lock: + st.update(connected=False, error="disconnected") + stop.wait(5) + + def state(): + with lock: + out = json.loads(json.dumps(st)) # a copy: the reader keeps writing + out["wanted"] = wanted() + out["hears"] = hears(st["models"], out["wanted"]) + return out + + def ask(body): + text = body.get("text") + if not isinstance(text, str) or not text.strip(): + raise ModuleError("text required") + send(with_model({"type": "ask", "text": text})) + + def model(body): + mid = body.get("id") + with lock: + m = next((x for x in st["models"] if x.get("id") == mid), None) + if m is None: + raise ModuleError("unknown model") + was_cloud = any(x.get("cloud") and x.get("id") == wanted() for x in st["models"]) + # Moving a chat with turns to the cloud sends its history there. + if m.get("cloud") and not was_cloud and st["turns"]: + st["notice"] = f"History in this chat goes to {m.get('provider')}." + st["chatModel"] = mid + + def voice(data): + if data[:4] != b"RIFF" or data[8:12] != b"WAVE": + raise ModuleError("not a WAV") + VOICE.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + tmp = VOICE.with_suffix(".tmp") + tmp.write_bytes(data) + os.replace(tmp, VOICE) + send(with_model({"type": "ask", "text": "", "audio": str(VOICE)})) + + def close(): + stop.set() + s = conn["sock"] + if s is not None: + try: + s.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + return Module( + name="assistant", title="Assistant", state=state, + actions={"ask": ask, "stop": lambda b: send({"type": "stop"}), + "new": lambda b: send({"type": "new"}), + "models": lambda b: send({"type": "models"}), + "model": model, "voice": voice}, + uploads={"voice": ("audio/wav", MAX_VOICE)}, + start=lambda: threading.Thread(target=loop, daemon=True).start(), + stop=close, + ) diff --git a/tests/test_assistant.py b/tests/test_assistant.py index f91f3cd..b384a6c 100644 --- a/tests/test_assistant.py +++ b/tests/test_assistant.py @@ -13,7 +13,13 @@ # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., +import json +import os +import socket import sys +import tempfile +import threading +import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) @@ -94,5 +100,108 @@ class Hears(unittest.TestCase): self.assertTrue(a.hears([{"id": "x", "status": "loaded", "cloud": False, "inputs": None}], None)) + +class FakeDaemon: + """A desktop-assistant stand-in: says hello, records commands, can push events.""" + + def __init__(self, path): + self.got, self.conns = [], [] + self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.srv.bind(path) + self.srv.listen() + threading.Thread(target=self.serve, daemon=True).start() + + def serve(self): + while True: + try: + c, _ = self.srv.accept() + except OSError: + return + self.conns.append(c) + c.sendall(b'{"type":"hello","state":"idle","model":"m1","turns":[],"pending":null}\n') + threading.Thread(target=self.read, args=(c,), daemon=True).start() + + def read(self, c): + for line in c.makefile("r"): + self.got.append(json.loads(line)) + + def push(self, e): + for c in self.conns: + c.sendall((json.dumps(e) + "\n").encode()) + + def close(self): + for c in self.conns: + c.close() + self.srv.close() + + +def until(fn, secs=2): + end = time.monotonic() + secs + while time.monotonic() < end: + if fn(): + return True + time.sleep(0.02) + return False + + +class Client(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp(dir="/tmp") + a.SOCK = Path(self.dir) / "d.sock" + a.VOICE = Path(self.dir) / "deck-it" / "voice.wav" + self.d = FakeDaemon(str(a.SOCK)) + self.m = a.make({"assistant": {"shell": "/nonexistent"}}) + self.m.start() + self.assertTrue(until(lambda: self.m.state()["connected"])) + + def tearDown(self): + self.m.stop() + self.d.close() + + def test_connects_and_asks_for_models(self): + self.assertTrue(until(lambda: {"type": "models"} in self.d.got)) + self.assertEqual(self.m.state()["model"], "m1") + + def test_ask_carries_the_picked_model(self): + self.d.push({"type": "models", "items": [{"id": "ears", "status": "loaded", "cloud": False, + "inputs": ["audio"]}]}) + self.assertTrue(until(lambda: self.m.state()["models"])) + self.m.actions["model"]({"id": "ears"}) + self.m.actions["ask"]({"text": "hi"}) + self.assertTrue(until(lambda: {"type": "ask", "text": "hi", "model": "ears"} in self.d.got)) + self.assertTrue(self.m.state()["hears"]) + + def test_bad_input_is_refused(self): + for bad in ({}, {"text": ""}, {"text": 3}): + with self.assertRaises(a.ModuleError): + self.m.actions["ask"](bad) + with self.assertRaises(a.ModuleError): + self.m.actions["model"]({"id": "nope"}) + + def test_cloud_pick_with_turns_warns_once(self): + self.d.push({"type": "models", "items": [{"id": "p:big", "provider": "p", "cloud": True}]}) + self.d.push({"type": "user", "text": "q"}) + self.d.push({"type": "done", "id": 1}) + self.assertTrue(until(lambda: self.m.state()["models"] and self.m.state()["turns"])) + self.m.actions["model"]({"id": "p:big"}) + self.assertIn("goes to p", self.m.state()["notice"]) + + def test_voice_writes_the_clip_and_asks(self): + wav = b"RIFF\x24\x00\x00\x00WAVE" + b"\x00" * 32 + self.m.actions["voice"](wav) + self.assertEqual(a.VOICE.read_bytes(), wav) + self.assertTrue(until(lambda: {"type": "ask", "text": "", "audio": str(a.VOICE)} in self.d.got)) + with self.assertRaises(a.ModuleError): + self.m.actions["voice"](b"not a wav") + + def test_streamed_state_is_a_copy(self): + self.d.push({"type": "user", "text": "q"}) + self.d.push({"type": "token", "delta": "a"}) + self.assertTrue(until(lambda: (self.m.state()["pending"] or {}).get("reply") == "a")) + s = self.m.state() + s["pending"]["reply"] = "changed" + self.assertEqual(self.m.state()["pending"]["reply"], "a") + + if __name__ == "__main__": unittest.main() -- cgit v1.2.3