# 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., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import json import os import shutil import socket import stat import sys import tempfile import threading import time 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": "", "daemon": True} 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": "", "daemon": True} a.fold(st, {"type": "error", "message": "bad write", "turn": True}) self.assertEqual((st["op"]["running"], st["op"]["error"]), (False, "bad write")) def test_written_without_a_daemon_op_changes_nothing(self): st = a.blank() op = {"label": "To .md", "running": False, "ok": False, "out": [], "error": "x", "daemon": True} st["op"] = dict(op) a.fold(st, {"type": "written", "path": "/x/doc.md"}) self.assertEqual(st["op"], op) def test_turn_error_during_a_local_op_goes_to_the_transcript(self): st = folded({"type": "user", "text": "q"}) st["op"] = {"label": "Merge", "running": True, "ok": False, "out": [], "error": "", "daemon": False} a.fold(st, {"type": "error", "message": "boom", "turn": True}) self.assertTrue(st["op"]["running"]) self.assertEqual(st["turns"][-1]["error"], "boom") 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)) 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: try: c.shutdown(socket.SHUT_RDWR) # the reader's makefile keeps the fd open except OSError: pass 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 Base(unittest.TestCase): """A module on a fake daemon, with a stub `qs` first on PATH.""" def qs_body(self): return "exit 1" def setUp(self): self.dir = tempfile.mkdtemp(dir="/tmp") self.addCleanup(shutil.rmtree, self.dir, True) self.bin = tempfile.mkdtemp(dir="/tmp") self.addCleanup(shutil.rmtree, self.bin, True) stub(self.bin, "qs", self.qs_body()) self.addCleanup(os.environ.__setitem__, "PATH", os.environ["PATH"]) os.environ["PATH"] = self.bin + ":" + os.environ["PATH"] self.addCleanup(setattr, a, "SOCK", a.SOCK) self.addCleanup(setattr, a, "VOICE", a.VOICE) a.SOCK = Path(self.dir) / "d.sock" a.VOICE = Path(self.dir) / "deck-it" / "voice.wav" self.d = FakeDaemon(str(a.SOCK)) self.addCleanup(self.d.close) self.m = a.make({"assistant": {"shell": "/nonexistent"}}) self.m.start() self.addCleanup(self.m.stop) self.assertTrue(until(lambda: self.m.state()["connected"])) # The daemon has registered the connection (and said hello) once it hears us. self.assertTrue(until(lambda: {"type": "models"} in self.d.got)) class Client(Base): 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_reader_survives_bad_input(self): self.d.push({"type": "user", "text": "q"}) self.d.conns[0].sendall(b'[1]\n"str"\n{"type":"token","delta":null}\n\xff\xfe\n') self.d.push({"type": "token", "delta": "ok"}) self.assertTrue(until(lambda: (self.m.state()["pending"] or {}).get("reply") == "ok")) self.assertTrue(self.m.state()["connected"]) 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") CATALOG = {"presets": [{"label": "Translate", "icon": "", "kinds": ["pdf", "text"], "prompt": "Translate this into English."}], "ops": [{"label": "To .md", "icon": "", "op": "md", "kinds": ["pdf"], "max": 1}, {"label": "Merge", "icon": "", "op": "pdf-merge", "kinds": ["pdf"], "min": 2}, {"label": ".zip", "icon": "", "op": "zip", "kinds": ["any"]}], "kinds": {"pdf": [".pdf"], "text": [".md", ".txt"]}, "fileops": "", "outDir": "/tmp/out", "mdPrompt": "As Markdown.", "preferred": ""} class QarmaArgs(unittest.TestCase): def test_filter_and_multiple(self): args = a.qarma_args(CATALOG["presets"][0], CATALOG["kinds"]) self.assertIn("--multiple", args) self.assertIn("--file-filter=Translate | *.md *.pdf *.txt", args) def test_single_file_op_and_any_kind(self): self.assertNotIn("--multiple", a.qarma_args(CATALOG["ops"][0], CATALOG["kinds"])) self.assertFalse([x for x in a.qarma_args(CATALOG["ops"][2], CATALOG["kinds"]) if x.startswith("--file-filter")]) def stub(dirpath, name, body): p = Path(dirpath) / name p.write_text("#!/bin/sh\n" + body + "\n") p.chmod(p.stat().st_mode | stat.S_IXUSR) return p class Pick(Base): def qs_body(self): cat = dict(CATALOG, fileops=str(Path(self.bin) / "fileops")) return "cat <<'EOF'\n" + json.dumps(cat) + "\nEOF" def test_preset_asks_with_the_picked_files(self): stub(self.bin, "qarma", "printf '/docs/a.pdf'") self.m.actions["pick"]({"preset": "Translate"}) self.assertTrue(until(lambda: {"type": "ask", "text": "Translate this into English.", "files": ["/docs/a.pdf"]} in self.d.got)) self.assertIsNone(self.m.state()["picking"]) def test_cancelled_dialog_does_nothing(self): stub(self.bin, "qarma", "exit 1") self.m.actions["pick"]({"preset": "Translate"}) self.assertTrue(until(lambda: self.m.state()["picking"] is None)) self.assertFalse([c for c in self.d.got if c["type"] == "ask"]) def test_op_runs_fileops(self): stub(self.bin, "qarma", "printf '/v/a.pdf\\n/v/b.pdf'") stub(self.bin, "fileops", 'echo \'{"ok": true, "out": ["/tmp/out/a+b.pdf"]}\'') self.m.actions["pick"]({"op": "Merge"}) self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("ok"))) self.assertEqual(self.m.state()["op"]["out"], ["/tmp/out/a+b.pdf"]) def test_op_min_is_checked(self): stub(self.bin, "qarma", "printf '/v/a.pdf'") self.m.actions["pick"]({"op": "Merge"}) self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("error"))) self.assertIn("at least 2", self.m.state()["op"]["error"]) def test_md_goes_to_the_daemon(self): stub(self.bin, "qarma", "printf '/docs/scan.pdf'") self.m.actions["pick"]({"op": "To .md"}) self.assertTrue(until(lambda: {"type": "write", "files": ["/docs/scan.pdf"], "prompt": "As Markdown.", "dir": "/tmp/out", "name": "scan.md"} in self.d.got)) def test_unknown_label_and_busy(self): stub(self.bin, "qarma", "exec sleep 10") with self.assertRaises(a.ModuleError): self.m.actions["pick"]({"preset": "Nope"}) self.m.actions["pick"]({"preset": "Translate"}) with self.assertRaises(a.ModuleError): self.m.actions["pick"]({"preset": "Translate"}) self.m.actions["cancel"]({}) def test_cancel_closes_the_dialog(self): mark = Path(self.bin) / "up" stub(self.bin, "qarma", f"touch {mark}; exec sleep 10") self.m.actions["pick"]({"preset": "Translate"}) self.assertTrue(until(mark.exists)) self.assertEqual(self.m.state()["picking"], "Translate") time.sleep(0.1) # let the shell exec; terminate works either way self.m.actions["cancel"]({}) self.assertTrue(until(lambda: self.m.state()["picking"] is None, 1)) def test_fileops_silence_ends_the_op(self): stub(self.bin, "qarma", "printf '/v/a.pdf'") stub(self.bin, "fileops", "true") self.m.actions["pick"]({"op": ".zip"}) self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("error"))) self.assertEqual(self.m.state()["op"]["error"], "fileops gave no answer") self.assertFalse(self.m.state()["op"]["running"]) def test_daemon_op_ends_when_the_daemon_goes(self): stub(self.bin, "qarma", "printf '/docs/scan.pdf'") self.m.actions["pick"]({"op": "To .md"}) self.assertTrue(until(lambda: any(c["type"] == "write" for c in self.d.got))) self.d.close() self.assertTrue(until(lambda: (self.m.state()["op"] or {}).get("error") == "disconnected")) self.assertFalse(self.m.state()["op"]["running"]) def test_odd_qarma_exit_is_a_notice(self): stub(self.bin, "qarma", "exit 3") self.m.actions["pick"]({"preset": "Translate"}) self.assertTrue(until(lambda: self.m.state()["notice"])) self.assertEqual(self.m.state()["notice"], "qarma exited 3") class NoCatalog(Base): def test_pick_says_why(self): with self.assertRaises(a.ModuleError) as cm: self.m.actions["pick"]({"preset": "Translate"}) self.assertTrue(str(cm.exception)) if __name__ == "__main__": unittest.main()