aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_assistant.py
blob: b384a6c07987ae596ab3c1856cc79a7b231527db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# deck-it - tests for assistant
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# 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 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))

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))



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()