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.

@ fix(dictation): heal the word count and store one spelling per language

Ruben Lütkeda956c77d63b
diff --git a/jarvis/dictation/history.py b/jarvis/dictation/history.py
index 004e17a150..01e80e86a1 100644
--- a/jarvis/dictation/history.py
+++ b/jarvis/dictation/history.py
@@ -68,7 +68,11 @@ class DictationEntry:
raw_text: str
#: What was actually inserted (equals ``raw_text`` when no cleanup applied).
text: str
- #: BCP-47-ish language the STT reported, or "" when unknown.
+ #: The language of the dictation as ONE code, or "" when none was
+ #: established. Normalised at the store boundary by
+ #: :func:`_normalize_language` — never stored the way a provider happened to
+ #: spell it, because four spellings of two languages is what the live
+ #: history actually grew (AP-4).
language: str = ""
#: Seconds of audio.
duration_s: float = 0.0
@@ -222,7 +226,12 @@ class DictationHistory:
created_at=str(item.get("created_at") or ""),
raw_text=str(item.get("raw_text") or ""),
text=str(item.get("text") or ""),
- language=str(item.get("language") or ""),
+ # Normalised on the way OUT as well as on the way in:
+ # every row already on disk was written before this
+ # store had a boundary, so the four live spellings are
+ # collapsed here and the next _write persists the
+ # collapsed value (F10).
+ language=_normalize_language(item.get("language")),
duration_s=float(item.get("duration_s") or 0.0),
outcome=str(item.get("outcome") or ""),
method=str(item.get("method") or ""),
@@ -233,7 +242,11 @@ class DictationHistory:
# written by an older install reads as these defaults
# instead of failing — verified, not assumed
# (test_history_written_before_the_new_fields_reads_as_defaults).
- word_count=int(item.get("word_count") or 0),
+ # word_count is the exception: its default is a
+ # measurable value, so a legacy row is repaired rather
+ # than left at a zero that would then be written back
+ # forever (F9, see _healed_word_count).
+ word_count=_healed_word_count(item),
discarded=bool(item.get("discarded") or False),
audio_path=(str(item["audio_path"]) if item.get("audio_path") else None),
error=(str(item["error"]) if item.get("error") else None),
@@ -289,7 +302,7 @@ class DictationHistory:
created_at=datetime.now(UTC).isoformat(),
raw_text=_clip(raw_text),
text=_clip(text),
- language=str(language or ""),
+ language=_normalize_language(language),
duration_s=max(0.0, float(duration_s or 0.0)),
outcome=str(outcome or ""),
method=str(method or ""),
@@ -336,6 +349,13 @@ class DictationHistory:
changes["raw_text"] = _clip(str(changes["raw_text"] or ""))
if "text" in changes:
changes["text"] = _clip(str(changes["text"] or ""))
+ if "language" in changes:
+ # The Restore route re-transcribes and writes the language its
+ # provider reported, so this is the fourth writer into the same
+ # field. Normalising HERE rather than there is what makes the
+ # boundary a boundary: a caller cannot re-introduce a fifth
+ # spelling by forgetting to collapse its own value first.
+ changes["language"] = _normalize_language(changes["language"])
if "audio_path" in changes and changes["audio_path"] is not None:
changes["audio_path"] = str(changes["audio_path"])
try:
@@ -449,6 +469,101 @@ def _clip(text: str) -> str:
return value[:MAX_TEXT_LEN] + " […truncated]"
+def _healed_word_count(item: dict[str, Any]) -> int:
+ """The stored word count, recomputed when the row never carried one.
+
+ ``word_count`` was added after the first release, so every row written
+ before it defaults to zero — and a zero is indistinguishable from a
+ measured "this dictation had no words". That matters because the lifetime
+ counters skip anything at or below zero
+ (:meth:`jarvis.dictation.stats.DictationStats.record`), so a history full of
+ obvious text reported a fraction of its own words: 26 counted for 41 rows on
+ the maintainer's machine. Worse, the zero was durable — every write rewrites
+ the whole file from what was read, so a default that is never repaired on
+ read is a default that gets persisted forever.
+
+ So a missing or zero count on a row that HAS text is treated as "never
+ measured" rather than "measured as none", and recomputed with the same
+ :func:`jarvis.dictation.cleanup.count_words` the writer would have used. The
+ next :meth:`DictationHistory._write` persists it, so the repair happens once
+ per row rather than on every read.
+
+ A row with no text at all keeps its zero: a failed or empty dictation really
+ did produce no words, and inventing one would break the counters in the
+ other direction. A stored count that is not a number is treated the same way
+ as a missing one — a broken field is worth healing, never worth dropping the
+ whole row over.
+ """
+ try:
+ stored = int(item.get("word_count") or 0)
+ except (TypeError, ValueError):
+ stored = 0
+ if stored > 0:
+ return stored
+ text = str(item.get("text") or "") or str(item.get("raw_text") or "")
+ if not text.strip():
+ return 0
+ from jarvis.dictation.cleanup import count_words
+
+ return count_words(text)
+
+
+#: Tags that are an answer of "we could not tell", not a language. ``auto`` is
+#: the REQUEST ("detect it") echoed back by a provider that had no opinion;
+#: ``unknown`` / ``und`` are what a recogniser says when detection failed. All
+#: three store as "" so "not detected" stays distinguishable from a real result.
+_NON_LANGUAGE_TAGS: frozenset[str] = frozenset({"auto", "unknown", "und"})
+
+
+def _normalize_language(tag: object) -> str:
+ """Collapse a provider's language tag to ONE spelling per row (AP-4).
+
+ The live history grew four spellings for two languages — ``"English"`` 27
+ rows, ``"German"`` 9, ``"de"`` 3, ``"en"`` 1, ``""`` 1 — because every
+ writer stored whatever its provider happened to say: a Whisper cloud
+ endpoint returns the English NAME, local faster-whisper returns an ISO code,
+ a BCP-47 pin returns ``"de-DE"``. Any consumer doing
+ ``{"de": ...}.get(entry.language)`` then misses on three rows out of four,
+ which is exactly the BUG-008 / AP-4 shape. The collapse therefore happens
+ HERE, at the store boundary, on the way in AND on the way out — not in each
+ of the four writers, where the fifth one to be added would forget.
+
+ Resolution, in order:
+
+ * an empty tag, or one of :data:`_NON_LANGUAGE_TAGS`, stores as ``""``;
+ * anything :func:`jarvis.core.turn_language.normalize_language_tag` resolves
+ stores as that code — ``de`` / ``en`` / ``es``;
+ * **anything else keeps what the recogniser said**, lower-cased and reduced
+ to its primary subtag (``"ja-JP"`` -> ``"ja"``). Never coerced, never
+ dropped.
+
+ That last rule is the load-bearing one. The canonical resolver knows only
+ the three product locales and answers ``"unknown"`` for the other ~96
+ languages dictation accepts (:data:`jarvis.core.config.RECOGNITION_LANGUAGES`),
+ so folding an unresolved tag into the default locale would relabel a
+ Japanese dictation as English — a worse lie than the drift this function
+ exists to remove. Storing ``""`` is the other bad answer: it erases the only
+ record of what was actually heard and makes a detected language look like a
+ failed detection. Keeping the tag costs nothing and stays honest.
+
+ The consequence is a bounded, deliberate residue: one code per row is EXACT
+ for de/en/es and best-effort canonicalisation elsewhere, so ``"Japanese"``
+ and ``"ja"`` can still coexist as two rows. Closing that needs a language
+ NAME -> code table covering all of ``RECOGNITION_LANGUAGES``, and it belongs
+ next to the canonical resolver in :mod:`jarvis.core.turn_language` — a
+ second private copy here would be the drift it is meant to prevent.
+ """
+ value = str(tag or "").strip().lower().replace("_", "-")
+ if not value or value in _NON_LANGUAGE_TAGS:
+ return ""
+ from jarvis.core.turn_language import normalize_language_tag
+
+ code = normalize_language_tag(value)
+ if code != "unknown":
+ return code
+ return value.split("-", 1)[0]
+
+
def _holds_pending_recovery(entry: DictationEntry) -> bool:
"""``True`` when dropping this entry would strand a Restore.
diff --git a/tests/unit/dictation/test_history_selfheal.py b/tests/unit/dictation/test_history_selfheal.py
new file mode 100644
index 0000000000..cc2dcfda07
--- /dev/null
+++ b/tests/unit/dictation/test_history_selfheal.py
@@ -0,0 +1,324 @@
+"""The dictation store repairs what older writers left behind.
+
+Two defects share one shape: a value that was written wrong ONCE stays wrong
+forever, because every write rewrites the whole file from whatever the reader
+just produced. So a default that is not repaired on read is a default that gets
+persisted again on the next dictation.
+
+* ``word_count`` was added after the first release. Rows written before it read
+ as zero, the lifetime counters skip anything at or below zero, and the
+ maintainer's 41-row history therefore reported 26 words dictated.
+* ``language`` was stored the way each provider happened to spell it — the same
+ live history holds ``"English"``, ``"German"``, ``"de"``, ``"en"`` and ``""``
+ for two languages, so any consumer indexing by code misses three rows in four
+ (the AP-4 / BUG-008 shape).
+
+Both are fixed at the store boundary rather than in the four writers, and both
+are asserted here to heal on read AND to stay healed on disk.
+"""
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.dictation.history import DictationHistory
+
+
+def _row(row_id: str, **fields: Any) -> dict[str, Any]:
+ """One on-disk row, spelled the way an older install would have written it."""
+ row: dict[str, Any] = {
+ "id": row_id,
+ "created_at": datetime.now(UTC).isoformat(),
+ "raw_text": "",
+ "text": "",
+ }
+ row.update(fields)
+ return row
+
+
+def _legacy_history(path: Path, *rows: dict[str, Any]) -> DictationHistory:
+ """A history file placed on disk directly, bypassing every writer."""
+ path.write_text(
+ json.dumps({"version": 1, "entries": list(rows)}, ensure_ascii=False),
+ encoding="utf-8",
+ )
+ return DictationHistory(path)
+
+
+def _stored(store: DictationHistory) -> list[dict[str, Any]]:
+ """What is actually in the file, not what the reader made of it."""
+ payload = json.loads(store.path.read_text(encoding="utf-8"))
+ return list(payload["entries"])
+
+
+def _by_id(store: DictationHistory, row_id: str) -> dict[str, Any]:
+ return next(row for row in _stored(store) if row["id"] == row_id)
+
+
+def history(tmp_path: Path) -> DictationHistory:
+ return DictationHistory(tmp_path / "dictation_history.json")
+
+
+# --------------------------------------------------------------------------
+# F9 — word_count self-heals on read
+# --------------------------------------------------------------------------
+
+
+def test_a_row_written_before_word_count_existed_heals_on_read(
+ tmp_path: Path,
+) -> None:
+ store = _legacy_history(
+ tmp_path / "old.json",
+ _row("a", raw_text="send the report today", text="send the report today"),
+ )
+ assert store.list_all()[0].word_count == 4
+
+
+def test_a_stored_zero_on_a_row_with_text_is_treated_as_never_measured(
+ tmp_path: Path,
+) -> None:
+ """The live shape: the key is present, and its value is a durable lie."""
+ store = _legacy_history(
+ tmp_path / "zeroed.json",
+ _row("a", raw_text="one two three", text="one two three", word_count=0),
+ )
+ assert store.list_all()[0].word_count == 3
+
+
+def test_the_healed_count_is_written_back_and_stays_healed(tmp_path: Path) -> None:
+ """Healing only on read would recompute the same repair on every load."""
+ store = _legacy_history(
+ tmp_path / "old.json",
+ _row("a", raw_text="one two three four", text="one two three four"),
+ )
+ # Any write rewrites the whole file from what the reader produced.
+ assert store.add(raw_text="later", text="later") is not None
+ assert _by_id(store, "a")["word_count"] == 4
+ # And a second reader sees the persisted value, not a fresh recomputation.
+ assert DictationHistory(store.path).get("a").word_count == 4 # type: ignore[union-attr]
+
+
+def test_a_row_with_no_text_keeps_its_zero(tmp_path: Path) -> None:
+ """A failed dictation really did produce no words — inventing one is worse."""
+ store = _legacy_history(
+ tmp_path / "failed.json",
+ _row("a", outcome="failed", error="provider 401"),
+ )
+ entry = store.list_all()[0]
+ assert entry.word_count == 0
+ assert entry.outcome == "failed"
+
+
+def test_whitespace_only_text_is_not_words(tmp_path: Path) -> None:
+ store = _legacy_history(tmp_path / "blank.json", _row("a", text=" \n "))
+ assert store.list_all()[0].word_count == 0
+
+
+def test_a_measured_count_is_never_recomputed(tmp_path: Path) -> None:
+ """An explicit count is the caller's answer and outranks the transcript."""
+ store = _legacy_history(
+ tmp_path / "explicit.json",
+ _row("a", raw_text="a b c", text="a b c", word_count=99),
+ )
+ assert store.list_all()[0].word_count == 99
+
+
+def test_the_raw_text_carries_the_heal_when_the_cleaned_text_is_gone(
+ tmp_path: Path,
+) -> None:
+ """Same fallback order the writer uses: ``text or raw_text``."""
+ store = _legacy_history(
+ tmp_path / "rawonly.json",
+ _row("a", raw_text="uh send the report", text=""),
+ )
+ assert store.list_all()[0].word_count == 4
+
+
+def test_a_broken_word_count_heals_instead_of_dropping_the_row(
+ tmp_path: Path,
+) -> None:
+ """One unusable field must never cost the user the whole entry."""
+ store = _legacy_history(
+ tmp_path / "broken.json",
+ _row("a", raw_text="one two", text="one two", word_count="not-a-number"),
+ )
+ entries = store.list_all()
+ assert [e.id for e in entries] == ["a"]
+ assert entries[0].word_count == 2
+
+
+def test_the_healed_count_reaches_the_api_shape(tmp_path: Path) -> None:
+ store = _legacy_history(
+ tmp_path / "old.json", _row("a", raw_text="one two three", text="one two three")
+ )
+ assert store.list_all()[0].to_dict()["word_count"] == 3
+
+
+# --------------------------------------------------------------------------
+# F10 — one row, one language code
+# --------------------------------------------------------------------------
+
+
+ ("written", "stored"),
+ [
+ ("de", "de"),
+ ("DE", "de"),
+ ("de-DE", "de"),
+ ("de_DE", "de"),
+ ("German", "de"),
+ ("deutsch", "de"), # i18n-allow: provider language NAME under test (§1 list #4)
+ ("en", "en"),
+ ("English", "en"),
+ ("en-US", "en"),
+ ("es", "es"),
+ ("Spanish", "es"),
+ ("español", "es"), # i18n-allow: provider language NAME under test (§1 list #4)
+ ],
+)
+def test_add_collapses_every_spelling_of_a_known_language(
+ history: DictationHistory, written: str, stored: str
+) -> None:
+ entry = history.add(raw_text="x", text="x", language=written)
+ assert entry is not None
+ assert entry.language == stored
+ assert history.list_all()[0].language == stored
+
+
[email protected]("written", ["", "auto", "AUTO", "unknown", "und", " "])
+def test_a_tag_that_is_not_a_language_stores_as_empty(
+ history: DictationHistory, written: str
+) -> None:
+ """"detect it" and "I could not tell" are answers, not languages."""
+ entry = history.add(raw_text="x", text="x", language=written)
+ assert entry is not None
+ assert entry.language == ""
+
+
+ ("written", "stored"),
+ [
+ ("ja", "ja"),
+ ("ja-JP", "ja"),
+ ("JA", "ja"),
+ ("Japanese", "japanese"),
+ ("Polish", "polish"),
+ ("zh", "zh"),
+ ("yue", "yue"),
+ ],
+)
+def test_a_language_outside_the_product_locales_is_kept_never_coerced(
+ history: DictationHistory, written: str, stored: str
+) -> None:
+ """The canonical resolver answers "unknown" for ~96 of the 99 recognition
+ languages, so folding an unresolved tag into the default locale would
+ relabel a Japanese dictation as English. The tag survives instead.
+ """
+ entry = history.add(raw_text="x", text="x", language=written)
+ assert entry is not None
+ assert entry.language == stored
+ assert entry.language != "en"
+
+
+def test_the_four_live_spellings_collapse_on_read_and_are_written_back(
+ tmp_path: Path,
+) -> None:
+ """The exact shape of the maintainer's history: four spellings, two languages."""
+ store = _legacy_history(
+ tmp_path / "drifted.json",
+ _row("english-name", text="hello there", language="English"),
+ _row("german-name", text="the second row", language="German"),
+ _row("iso-de", text="the third row", language="de"),
+ _row("iso-en", text="good morning", language="en"),
+ _row("nothing", text="ok", language=""),
+ )
+ assert {e.id: e.language for e in store.list_all()} == {
+ "english-name": "en",
+ "german-name": "de",
+ "iso-de": "de",
+ "iso-en": "en",
+ "nothing": "",
+ }
+ # ...and the collapse is durable, so the drift cannot come back on the next read.
+ fresh = store.add(raw_text="later", text="later", language="German")
+ assert fresh is not None
+ on_disk = {row["id"]: row["language"] for row in _stored(store)}
+ assert on_disk == {
+ "english-name": "en",
+ "german-name": "de",
+ "iso-de": "de",
+ "iso-en": "en",
+ "nothing": "",
+ fresh.id: "de",
+ }
+
+
+def test_a_legacy_non_product_language_survives_the_read_heal(tmp_path: Path) -> None:
+ store = _legacy_history(
+ tmp_path / "jp.json", _row("a", text="konnichiwa", language="Japanese")
+ )
+ assert store.list_all()[0].language == "japanese"
+
+
+def test_update_normalizes_the_language_the_restore_route_writes(
+ history: DictationHistory,
+) -> None:
+ """Re-transcribing writes a provider tag straight back into the row."""
+ entry = history.add(raw_text="", text="", outcome="failed")
+ assert entry is not None
+ updated = history.update(entry.id, text="recovered text", language="German")
+ assert updated is not None
+ assert updated.language == "de"
+ assert history.get(entry.id).language == "de" # type: ignore[union-attr]
+
+
+def test_update_can_clear_the_language_without_inventing_one(
+ history: DictationHistory,
+) -> None:
+ entry = history.add(raw_text="x", text="x", language="German")
+ assert entry is not None
+ updated = history.update(entry.id, language="unknown")
+ assert updated is not None
+ assert updated.language == ""
+
+
+def test_the_normalized_language_reaches_the_api_shape(
+ history: DictationHistory,
+) -> None:
+ entry = history.add(raw_text="x", text="x", language="English")
+ assert entry is not None
+ assert entry.to_dict()["language"] == "en"
+
+
+def test_normalizing_the_language_leaves_every_other_field_alone(
+ tmp_path: Path,
+) -> None:
+ """A read-time repair must not become a read-time rewrite."""
+ store = _legacy_history(
+ tmp_path / "intact.json",
+ _row(
+ "a",
+ raw_text="uh one two three",
+ text="one two three",
+ language="English",
+ duration_s=4.25,
+ outcome="inserted",
+ method="clipboard+ctrl_v",
+ removed_words=1,
+ cleanup_reason="",
+ discarded=False,
+ ),
+ )
+ entry = store.list_all()[0]
+ assert entry.raw_text == "uh one two three"
+ assert entry.text == "one two three"
+ assert entry.duration_s == 4.25
+ assert entry.outcome == "inserted"
+ assert entry.method == "clipboard+ctrl_v"
+ assert entry.removed_words == 1
+ assert entry.discarded is False
diff --git a/tests/unit/dictation/test_segment_and_history.py b/tests/unit/dictation/test_segment_and_history.py
index 192abcddf0..039a1b067b 100644
--- a/tests/unit/dictation/test_segment_and_history.py
+++ b/tests/unit/dictation/test_segment_and_history.py
@@ -228,7 +228,15 @@ def test_update_never_rewrites_the_id_or_timestamp(history: DictationHistory) ->
def test_history_written_before_the_new_fields_reads_as_defaults(
tmp_path: Path,
) -> None:
- """An install that predates word_count/discarded/audio/error still loads."""
+ """An install that predates word_count/discarded/audio/error still loads.
+
+ ``word_count`` is deliberately the one field that does NOT read back as its
+ default (F9): a zero on a row that plainly has text is indistinguishable
+ from a measured "this dictation had no words", and the lifetime counters
+ skip anything at or below zero — so the legacy row is repaired on read
+ instead of persisting its zero forever. The other three stay defaults,
+ because for them the default IS the honest answer for an old row.
+ """
path = tmp_path / "old.json"
path.write_text(
'{"version": 1, "entries": ['
@@ -238,12 +246,29 @@ def test_history_written_before_the_new_fields_reads_as_defaults(
encoding="utf-8",
)
entry = DictationHistory(path).list_all()[0]
- assert entry.word_count == 0
+ assert entry.word_count == 1
assert entry.discarded is False
assert entry.audio_path is None
assert entry.error is None
+def test_a_legacy_row_with_no_text_keeps_its_zero_word_count(
+ tmp_path: Path,
+) -> None:
+ """The other half of the F9 self-heal: a failed dictation really did produce
+ no words, so inventing one would break the counters in the other direction.
+ """
+ path = tmp_path / "old-empty.json"
+ path.write_text(
+ '{"version": 1, "entries": ['
+ '{"id": "a", "created_at": "2026-07-28T00:00:00+00:00",'
+ ' "raw_text": "", "text": "", "outcome": "failed"}'
+ "]}",
+ encoding="utf-8",
+ )
+ assert DictationHistory(path).list_all()[0].word_count == 0
+
+
def test_public_dict_never_leaks_the_audio_path(history: DictationHistory) -> None:
entry = history.add(raw_text="a", text="a")
assert entry is not None