aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--deckit/modules/assistant.py71
-rw-r--r--tests/test_assistant.py109
2 files changed, 142 insertions, 38 deletions
diff --git a/deckit/modules/assistant.py b/deckit/modules/assistant.py
index b608df2..d535eb7 100644
--- a/deckit/modules/assistant.py
+++ b/deckit/modules/assistant.py
@@ -25,6 +25,7 @@ desktop-assistant's docs/superpowers/specs/2026-10-16-text-daemon-design.md.
import json
import os
import socket
+import struct
import subprocess
import threading
from pathlib import Path
@@ -49,6 +50,12 @@ def _turn(t):
"think": t.get("think", ""), "tools": list(t.get("tools") or [])}
+def _daemon_op(st):
+ """Whether a write the daemon is doing for this tab is in flight."""
+ op = st["op"] or {}
+ return bool(op.get("running") and op.get("daemon"))
+
+
def fold(st, e):
"""Apply one daemon event to the state the tab polls."""
kind = e.get("type")
@@ -75,7 +82,7 @@ def fold(st, e):
st["pending"] = None
elif kind == "error":
msg = e.get("message", "")
- if e.get("turn") and (st["op"] or {}).get("running"):
+ if e.get("turn") and _daemon_op(st):
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})
@@ -91,7 +98,7 @@ def fold(st, e):
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"]:
+ if _daemon_op(st):
st["op"].update(running=False, ok=True, out=[e.get("path", "")])
@@ -122,6 +129,7 @@ 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
+ voice_lock = threading.Lock()
stop = threading.Event()
st = blank()
conn = {"sock": None, "qarma": None}
@@ -157,24 +165,33 @@ def make(cfg: dict) -> Module:
st.update(connected=False, error=str(e) or type(e).__name__)
stop.wait(5)
continue
+ # A stalled daemon must not hang the HTTP handlers that send.
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("ll", 2, 0))
conn["sock"] = s
with lock:
st.update(connected=True, error=None)
try:
send({"type": "models"})
- for line in s.makefile("r", encoding="utf-8"):
+ for line in s.makefile("r", encoding="utf-8", errors="replace"):
try:
e = json.loads(line)
except ValueError:
continue
+ if not isinstance(e, dict):
+ continue
with lock:
- fold(st, e)
+ try:
+ fold(st, e)
+ except (AttributeError, TypeError, KeyError, IndexError):
+ continue
except (OSError, ModuleError):
pass
conn["sock"] = None
s.close()
with lock:
st.update(connected=False, error="disconnected")
+ if _daemon_op(st):
+ st["op"].update(running=False, error="disconnected")
stop.wait(5)
def state():
@@ -205,22 +222,29 @@ def make(cfg: dict) -> Module:
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)}))
+ if conn["sock"] is None:
+ raise ModuleError("assistant not running")
+ with voice_lock: # one clip at a time: the file is shared
+ 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 load_catalog():
try:
out = subprocess.run(["qs", "-p", shell, "ipc", "call", "assistant", "catalog"],
capture_output=True, text=True, timeout=5, check=True).stdout
cat, err = json.loads(out), ""
+ if not isinstance(cat, dict):
+ cat, err = None, "keystone's catalog is not an object"
except (OSError, subprocess.SubprocessError, ValueError) as e:
cat, err = None, f"no presets from keystone: {e}"
with lock:
- st.update(catalog=cat, catalogError=err)
- return cat
+ if cat is not None:
+ st["catalog"] = cat
+ st["catalogError"] = err
+ return cat, err
def choose(cat, item):
"""Paths picked in qarma on the PC; [] when the dialog is cancelled."""
@@ -229,6 +253,8 @@ def make(cfg: dict) -> Module:
conn["qarma"] = p
out, _ = p.communicate()
conn["qarma"] = None
+ if p.returncode not in (0, 1): # 1 is a cancelled dialog
+ raise subprocess.SubprocessError(f"qarma exited {p.returncode}")
return [x for x in out.split("\n") if x.startswith("/")] if p.returncode == 0 else []
def set_op(**kw):
@@ -240,7 +266,7 @@ def make(cfg: dict) -> Module:
paths = choose(cat, item)
except (OSError, subprocess.SubprocessError) as e:
with lock:
- st.update(picking=None, notice=f"qarma: {e}")
+ st.update(picking=None, notice=str(e) if isinstance(e, subprocess.SubprocessError) else f"qarma: {e}")
return
with lock:
st["picking"] = None
@@ -251,7 +277,8 @@ def make(cfg: dict) -> Module:
send(with_model({"type": "ask", "text": item["prompt"], "files": paths}))
return
with lock:
- st["op"] = {"label": item["label"], "running": True, "ok": False, "out": [], "error": ""}
+ st["op"] = {"label": item["label"], "running": True, "ok": False, "out": [], "error": "",
+ "daemon": item["op"] == "md"}
if len(paths) < item.get("min", 1):
set_op(running=False, error=f"{item['label']} needs at least {item['min']} files")
elif item["op"] == "md":
@@ -261,22 +288,26 @@ def make(cfg: dict) -> Module:
else:
try:
out = subprocess.run([cat["fileops"], item["op"], cat["outDir"], *paths],
- capture_output=True, text=True).stdout
+ capture_output=True, text=True, timeout=600).stdout
r = json.loads(out.strip().splitlines()[-1])
+ if not isinstance(r, dict):
+ raise ValueError
+ except subprocess.TimeoutExpired:
+ r = {"ok": False, "error": "fileops timed out"}
except (OSError, ValueError, IndexError):
r = {"ok": False, "error": "fileops gave no answer"}
set_op(running=False, ok=bool(r.get("ok")), out=r.get("out") or [], error=r.get("error", ""))
- except ModuleError as e:
+ except Exception as e: # nothing may leave the op running
with lock:
if st["op"] and st["op"]["running"]:
- st["op"].update(running=False, error=str(e))
+ st["op"].update(running=False, error=str(e) or type(e).__name__)
else:
- st["notice"] = str(e)
+ st["notice"] = str(e) or type(e).__name__
def pick(body):
- cat = load_catalog()
+ cat, err = load_catalog()
if not cat:
- raise ModuleError(st["catalogError"])
+ raise ModuleError(err or "no presets from keystone")
if isinstance(body.get("preset"), str):
kind, items, label = "preset", cat.get("presets", []), body["preset"]
elif isinstance(body.get("op"), str):
@@ -298,6 +329,8 @@ def make(cfg: dict) -> Module:
p.terminate()
def close():
+ # ponytail: a close() between connect and conn["sock"] = s leaves the
+ # reader blocked until the daemon speaks; the thread is a daemon one.
stop.set()
s = conn["sock"]
if s is not None:
diff --git a/tests/test_assistant.py b/tests/test_assistant.py
index a3fb2b7..7ea782b 100644
--- a/tests/test_assistant.py
+++ b/tests/test_assistant.py
@@ -12,9 +12,11 @@
#
# 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
@@ -72,17 +74,32 @@ class Fold(unittest.TestCase):
def test_written_ends_the_op(self):
st = a.blank()
- st["op"] = {"label": "To .md", "running": True, "ok": False, "out": [], "error": ""}
+ 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": ""}
+ 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"]},
@@ -132,6 +149,10 @@ class FakeDaemon:
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()
@@ -145,22 +166,35 @@ def until(fn, secs=2):
return False
-class Client(unittest.TestCase):
+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))
- def tearDown(self):
- self.m.stop()
- self.d.close()
+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")
@@ -197,6 +231,13 @@ class Client(unittest.TestCase):
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"})
@@ -234,18 +275,10 @@ def stub(dirpath, name, body):
return p
-class Pick(Client):
- def setUp(self):
- self.bin = tempfile.mkdtemp(dir="/tmp")
+class Pick(Base):
+ def qs_body(self):
cat = dict(CATALOG, fileops=str(Path(self.bin) / "fileops"))
- stub(self.bin, "qs", "cat <<'EOF'\n" + json.dumps(cat) + "\nEOF")
- self.path = os.environ["PATH"]
- os.environ["PATH"] = self.bin + ":" + self.path
- super().setUp()
-
- def tearDown(self):
- os.environ["PATH"] = self.path
- super().tearDown()
+ 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'")
@@ -280,14 +313,52 @@ class Pick(Client):
"dir": "/tmp/out", "name": "scan.md"} in self.d.got))
def test_unknown_label_and_busy(self):
- stub(self.bin, "qarma", "sleep 2")
+ 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"]({})
- self.assertTrue(until(lambda: self.m.state()["picking"] is None, 3))
+
+ 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__":