aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_assistant.py
blob: 0280e0c3ebb584d7c627d3748a6378b0ae92cbd4 (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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# 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.,
# 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_voice_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["voice"](b"RIFF\x24\x00\x00\x00WAVE" + b"\x00" * 32)
        self.assertTrue(until(lambda: {"type": "ask", "text": "", "audio": str(a.VOICE),
                                       "model": "ears"} in self.d.got))
        self.assertTrue(self.m.state()["hears"])

    def test_bad_input_is_refused(self):
        self.assertNotIn("ask", self.m.actions)   # no keyboard on the tablet
        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()