From a9a737c7fd0efd8f82db78ce19e7858803e0f6b2 Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Tue, 10 Nov 2026 12:16:40 +0100 Subject: feat(assistant): fold daemon events into the tab's state Co-Authored-By: Claude Opus 5.5 --- deckit/modules/assistant.py | 106 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_assistant.py | 98 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+) create mode 100644 deckit/modules/assistant.py create mode 100644 tests/test_assistant.py diff --git a/deckit/modules/assistant.py b/deckit/modules/assistant.py new file mode 100644 index 0000000..088cac3 --- /dev/null +++ b/deckit/modules/assistant.py @@ -0,0 +1,106 @@ +# deck-it - assistant module +# Copyright (C) 2026 Danilo M. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# 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., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +"""desktop-assistant on the tablet: chat, voice, model choice, and the +canvas's Ask presets and Do ops applied to a file picked on the PC. + +One client of the daemon's socket (JSON lines both ways; every client sees +every event), folded into one state the tab polls. The protocol is +desktop-assistant's docs/superpowers/specs/2026-10-16-text-daemon-design.md. +""" + +import json +import os +import socket +import subprocess +import threading +from pathlib import Path + +from ..module import Module, ModuleError + +RUN = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) +SOCK = RUN / "desktop-assistant.sock" +VOICE = RUN / "deck-it" / "voice.wav" +MAX_VOICE = 2_000_000 # 60 s of 16 kHz mono 16-bit is 1.92 MB + + +def blank(): + return {"connected": False, "error": None, "state": "idle", "tool": None, + "model": None, "chatModel": None, "turns": [], "pending": None, + "notice": "", "models": [], "picking": None, "op": None, + "catalog": None, "catalogError": "", "epoch": 0} + + +def _turn(t): + return {"user": t.get("user", ""), "reply": t.get("reply", ""), + "think": t.get("think", ""), "tools": list(t.get("tools") or [])} + + +def fold(st, e): + """Apply one daemon event to the state the tab polls.""" + kind = e.get("type") + if kind == "hello": + st.update(state=e.get("state", "idle"), tool=e.get("tool"), model=e.get("model"), + chatModel=e.get("chat_model"), + turns=[_turn(t) for t in e.get("turns") or []], + pending=_turn(e["pending"]) if e.get("pending") else None, + epoch=st["epoch"] + 1) + elif kind == "state": + st.update(state=e.get("state", "idle"), tool=e.get("tool")) + elif kind == "user": + st.update(pending=_turn({"user": e.get("text", "")}), notice="") + elif kind in ("think", "token"): + p = st["pending"] or _turn({}) + p["think" if kind == "think" else "reply"] += e.get("delta", "") + st["pending"] = p + elif kind == "tool": + if st["pending"] and not e.get("done"): + st["pending"]["tools"].append(e.get("name", "")) + elif kind == "done": + if st["pending"]: + st["turns"].append({**st["pending"], "stopped": bool(e.get("stopped"))}) + st["pending"] = None + elif kind == "error": + msg = e.get("message", "") + if e.get("turn") and (st["op"] or {}).get("running"): + st["op"].update(running=False, error=msg) # a refused or failed write + elif e.get("turn") and st["pending"]: + st["turns"].append({**st["pending"], "error": msg}) + st["pending"] = None + else: + st["notice"] = msg + elif kind == "ctx": + if e.get("model"): + st["model"] = e["model"] + elif kind == "models": + st["models"] = e.get("items") or [] + elif kind == "conversation": + st.update(turns=[_turn(t) for t in e.get("turns") or []], pending=None, + chatModel=e.get("model"), epoch=st["epoch"] + 1) + elif kind == "written": + if st["op"]: + st["op"].update(running=False, ok=True, out=[e.get("path", "")]) + + +def hears(models, wanted): + """Whether the model that will hear a voice question takes audio: the + chat's pick if it is local, else the loaded local model (a cloud chat's + voice is transcribed locally). Unknown counts as yes.""" + local = [m for m in models if not m.get("cloud")] + m = (next((m for m in local if m.get("id") == wanted), None) + 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 diff --git a/tests/test_assistant.py b/tests/test_assistant.py new file mode 100644 index 0000000..f91f3cd --- /dev/null +++ b/tests/test_assistant.py @@ -0,0 +1,98 @@ +# deck-it - tests for assistant +# Copyright (C) 2026 Danilo M. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# 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 sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import unittest + +from deckit.modules import assistant as a + + +def folded(*events): + st = a.blank() + for e in events: + a.fold(st, e) + return st + + +class Fold(unittest.TestCase): + def test_hello_with_a_reply_in_flight(self): + st = folded({"type": "hello", "state": "thinking", "model": "m1", "chat_model": "c1", + "turns": [{"user": "hi", "reply": "yo", "tools": ["now"], "files": []}], + "pending": {"user": "and?", "reply": "par", "think": "", "tools": [], "files": []}}) + self.assertEqual((st["state"], st["model"], st["chatModel"]), ("thinking", "m1", "c1")) + self.assertEqual(st["turns"][0]["tools"], ["now"]) + self.assertEqual(st["pending"]["reply"], "par") + + def test_a_turn_streams_and_settles(self): + st = folded({"type": "user", "text": "q"}, {"type": "think", "delta": "h"}, + {"type": "tool", "name": "web", "done": False}, {"type": "tool", "name": "web", "done": True}, + {"type": "token", "delta": "a"}, {"type": "token", "delta": "b"}, + {"type": "done", "id": 3}) + self.assertIsNone(st["pending"]) + self.assertEqual(st["turns"], [{"user": "q", "reply": "ab", "think": "h", "tools": ["web"], + "stopped": False}]) + + def test_stop_keeps_the_partial_reply_marked(self): + st = folded({"type": "user", "text": "q"}, {"type": "token", "delta": "a"}, + {"type": "error", "message": "stopped", "turn": True}, + {"type": "done", "id": None, "stopped": True}) + self.assertEqual(st["turns"][-1]["error"], "stopped") + self.assertIsNone(st["pending"]) + + def test_command_error_is_a_notice(self): + self.assertEqual(folded({"type": "error", "message": "bad id"})["notice"], "bad id") + + def test_conversation_replaces_the_transcript(self): + st = folded({"type": "user", "text": "q"}, + {"type": "conversation", "id": None, "turns": [], "model": None}) + self.assertEqual((st["turns"], st["pending"], st["epoch"]), ([], None, 1)) + + def test_written_ends_the_op(self): + st = a.blank() + st["op"] = {"label": "To .md", "running": True, "ok": False, "out": [], "error": ""} + a.fold(st, {"type": "written", "path": "/x/doc.md"}) + self.assertEqual((st["op"]["running"], st["op"]["ok"], st["op"]["out"]), (False, True, ["/x/doc.md"])) + + def test_refused_write_ends_the_op(self): + st = a.blank() + st["op"] = {"label": "To .md", "running": True, "ok": False, "out": [], "error": ""} + a.fold(st, {"type": "error", "message": "bad write", "turn": True}) + self.assertEqual((st["op"]["running"], st["op"]["error"]), (False, "bad write")) + + +class Hears(unittest.TestCase): + MODELS = [{"id": "deaf", "status": "loaded", "cloud": False, "inputs": ["text"]}, + {"id": "ears", "status": "unloaded", "cloud": False, "inputs": ["text", "audio"]}, + {"id": "p:big", "provider": "p", "cloud": True}] + + def test_local_pick_decides(self): + self.assertTrue(a.hears(self.MODELS, "ears")) + self.assertFalse(a.hears(self.MODELS, "deaf")) + + def test_cloud_or_no_pick_uses_the_loaded_model(self): + self.assertFalse(a.hears(self.MODELS, "p:big")) + self.assertFalse(a.hears(self.MODELS, None)) + + def test_unknown_is_yes(self): + self.assertTrue(a.hears([], None)) + self.assertTrue(a.hears([{"id": "x", "status": "loaded", "cloud": False, "inputs": None}], None)) + + +if __name__ == "__main__": + unittest.main() -- cgit v1.2.3