Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(stt): REST API for the dictionary (CRUD, headless-safe)

Ruben Lütkeac7628460f52
diff --git a/jarvis/ui/web/dictionary_routes.py b/jarvis/ui/web/dictionary_routes.py
new file mode 100644
index 0000000000..b32f46e0a8
--- /dev/null
+++ b/jarvis/ui/web/dictionary_routes.py
@@ -0,0 +1,107 @@
+"""REST API for the STT dictionary — custom vocabulary + misrecognition fixes.
+
+Endpoints (mounted by the WebServer in ``_build_app()``):
+
+ GET /api/dictionary → {"entries": [entry, ...]} in insertion order.
+ POST /api/dictionary → create one entry; 201 (400 on duplicate).
+ PATCH /api/dictionary/{id} → partial edit; returns the entry; 404.
+ DELETE /api/dictionary/{id} → remove (idempotent → 200, {"removed": bool}).
+
+An entry is one canonical ``word`` plus optional ``misheard`` variants — see
+``jarvis/speech/stt_dictionary.py``. Storage is the atomic JSON sidecar under
+``user_data_dir()/data/``; corrections apply on the NEXT utterance (the
+corrector live-reloads on file change), so no restart is required.
+
+Like the Contacts/Socials endpoints this router has **no Brain dependency**,
+so it works headless / with MockBrain (open-source universality, CLAUDE.md §3).
+"""
+from __future__ import annotations
+
+import logging
+import threading
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+
+from jarvis.speech.stt_dictionary import DictionaryStore
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/dictionary", tags=["dictionary"])
+
+# Serializes read-modify-write across the per-request DictionaryStore
+# instances. Endpoints are sync ``def`` (FastAPI threadpool), so a
+# threading.Lock fits (same pattern as contacts_routes).
+_LOCK = threading.Lock()
+
+
+def _store() -> DictionaryStore:
+ # Constructed per request; resolves user_data_dir() at call time so the
+ # LOCALAPPDATA-based test sandbox works (mirrors contacts_routes).
+ return DictionaryStore()
+
+
+# ----------------------------------------------------------------------
+# Request models
+# ----------------------------------------------------------------------
+
+
+class EntryCreate(BaseModel):
+ word: str
+ misheard: list[str] = []
+
+
+class EntryUpdate(BaseModel):
+ word: str | None = None
+ misheard: list[str] | None = None
+
+
+# ----------------------------------------------------------------------
+# Endpoints
+# ----------------------------------------------------------------------
+
+
+def list_entries() -> dict[str, Any]:
+ with _LOCK:
+ entries = _store().list_all()
+ return {"entries": [e.to_dict() for e in entries]}
+
+
[email protected]("", status_code=201)
+def create_entry(body: EntryCreate) -> dict[str, Any]:
+ try:
+ with _LOCK:
+ entry = _store().add(body.word, body.misheard)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ log.info("STT dictionary: added %r (%d misheard).", entry.word, len(entry.misheard))
+ return entry.to_dict()
+
+
[email protected]("/{entry_id}")
+def update_entry(entry_id: str, body: EntryUpdate) -> dict[str, Any]:
+ fields = body.model_dump(exclude_unset=True)
+ try:
+ with _LOCK:
+ entry = _store().update(
+ entry_id,
+ word=fields.get("word"),
+ misheard=fields.get("misheard"),
+ misheard_set="misheard" in fields,
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if entry is None:
+ raise HTTPException(
+ status_code=404, detail=f"No dictionary entry with id {entry_id!r}."
+ )
+ return entry.to_dict()
+
+
[email protected]("/{entry_id}")
+def delete_entry(entry_id: str) -> dict[str, Any]:
+ with _LOCK:
+ removed = _store().delete(entry_id)
+ return {"ok": True, "removed": removed}
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 4f1d35b92c..3d24f461fa 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -230,6 +230,7 @@ class WebServer:
from .drop_routes import router as drop_router
from .contacts_routes import router as contacts_router
from .control_routes import router as control_router
+ from .dictionary_routes import router as dictionary_router
from .docs_routes import router as docs_router
from .federation_proxy_routes import router as federation_proxy_router
from .friends_routes import router as friends_router
@@ -325,6 +326,7 @@ class WebServer:
app.include_router(workspace_router)
# Contacts section — user-curated address book (pure file store, no Brain dep).
app.include_router(contacts_router)
+ app.include_router(dictionary_router)
app.include_router(workflows_router)
if conductor_router is not None:
app.include_router(conductor_router)
diff --git a/tests/unit/ui/web/test_dictionary_routes.py b/tests/unit/ui/web/test_dictionary_routes.py
new file mode 100644
index 0000000000..355e55d370
--- /dev/null
+++ b/tests/unit/ui/web/test_dictionary_routes.py
@@ -0,0 +1,97 @@
+"""REST route tests for the STT dictionary API (custom vocabulary CRUD)."""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.dictionary_routes import router as dictionary_router
+
+
+def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ # DictionaryStore resolves user_data_dir() per request; sandbox it so the
+ # tests never touch the real user profile.
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
+ app = FastAPI()
+ app.include_router(dictionary_router)
+ return TestClient(app)
+
+
+def test_list_empty(client: TestClient) -> None:
+ r = client.get("/api/dictionary")
+ assert r.status_code == 200
+ assert r.json() == {"entries": []}
+
+
+def test_create_and_list(client: TestClient) -> None:
+ r = client.post(
+ "/api/dictionary", json={"word": "GitHub", "misheard": ["Gitter"]}
+ )
+ assert r.status_code == 201
+ created = r.json()
+ assert created["word"] == "GitHub"
+ assert created["misheard"] == ["Gitter"]
+ assert created["id"]
+
+ r2 = client.get("/api/dictionary")
+ assert r2.status_code == 200
+ entries = r2.json()["entries"]
+ assert len(entries) == 1
+ assert entries[0]["word"] == "GitHub"
+
+
+def test_create_plain_word_without_misheard(client: TestClient) -> None:
+ r = client.post("/api/dictionary", json={"word": "Anthropic"})
+ assert r.status_code == 201
+ assert r.json()["misheard"] == []
+
+
+def test_create_rejects_empty_and_duplicate(client: TestClient) -> None:
+ assert client.post("/api/dictionary", json={"word": " "}).status_code == 400
+ assert client.post("/api/dictionary", json={"word": "Fable"}).status_code == 201
+ r = client.post("/api/dictionary", json={"word": "fable"})
+ assert r.status_code == 400
+ assert "already" in r.json()["detail"]
+
+
+def test_patch_updates_word_and_misheard(client: TestClient) -> None:
+ created = client.post(
+ "/api/dictionary", json={"word": "Ultrathink", "misheard": ["UltraSync"]}
+ ).json()
+ r = client.patch(
+ f"/api/dictionary/{created['id']}",
+ json={"misheard": ["UltraSync", "Ultra-think"]},
+ )
+ assert r.status_code == 200
+ assert r.json()["misheard"] == ["UltraSync", "Ultra-think"]
+
+ r2 = client.patch(f"/api/dictionary/{created['id']}", json={"word": "Ultra"})
+ assert r2.status_code == 200
+ assert r2.json()["word"] == "Ultra"
+ # Misheard list survives a word-only patch.
+ assert r2.json()["misheard"] == ["UltraSync", "Ultra-think"]
+
+
+def test_patch_unknown_id_404(client: TestClient) -> None:
+ r = client.patch("/api/dictionary/nope", json={"word": "X"})
+ assert r.status_code == 404
+
+
+def test_patch_duplicate_word_400(client: TestClient) -> None:
+ client.post("/api/dictionary", json={"word": "Fable"})
+ other = client.post("/api/dictionary", json={"word": "Opus"}).json()
+ r = client.patch(f"/api/dictionary/{other['id']}", json={"word": "fable"})
+ assert r.status_code == 400
+
+
+def test_delete_idempotent(client: TestClient) -> None:
+ created = client.post("/api/dictionary", json={"word": "Claude.md"}).json()
+ r1 = client.delete(f"/api/dictionary/{created['id']}")
+ assert r1.status_code == 200
+ assert r1.json() == {"ok": True, "removed": True}
+ r2 = client.delete(f"/api/dictionary/{created['id']}")
+ assert r2.status_code == 200
+ assert r2.json() == {"ok": True, "removed": False}