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(sessions): polish conversation transcripts beside the turn, never in it

rubenluetke10-beep6a65f13b9f4f
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 1c83a93662..b271755a19 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -3003,6 +3003,40 @@ class DictationConfig(BaseModel):
#: one switch means one thing whichever pass runs.
polish_precision: bool = False
+ #: Also re-read the transcripts of ordinary VOICE TURNS — the ones produced
+ #: by talking to the assistant, not by dictating into a document.
+ #:
+ #: It lives in ``[dictation]`` despite not being about dictation, because it
+ #: switches on the SAME pass with the same provider, ceiling, style and
+ #: precision setting. A block of its own would mean configuring the wording
+ #: model twice and letting the two answers drift; one switch reading one
+ #: block is the smaller surprise (AP-4).
+ #:
+ #: **It never delays a turn.** The brain is handed the raw transcript and is
+ #: already answering before this runs; the polished text arrives afterwards
+ #: as ``TranscriptPolished``, for the surfaces that display and store the
+ #: turn. Spending the latency ceiling between a finished sentence and the
+ #: start of the answer would trade the responsiveness that makes a voice
+ #: assistant usable for a comma in a log nobody was reading yet.
+ #:
+ #: Ships OFF, and the reason is cost rather than safety: a dictation is a
+ #: deliberate act a few times an hour, while a conversation produces a turn
+ #: every few seconds, and each one would spend a model call. Someone who
+ #: wants readable transcripts should say so.
+ #:
+ #: Requires ``polish`` above — it extends that pass rather than being a
+ #: second one, so with the formatter off there is nothing for it to extend.
+ #: The UI reflects that by showing it inside the formatter's own block, so
+ #: the dependency is visible instead of being a switch that reads as on and
+ #: does nothing (AP-31).
+ #:
+ #: Never translates, even with ``translate`` on. That switch is about text
+ #: on its way into a document; a conversation transcript is a RECORD of what
+ #: was said, and rewriting the record into another language than the one the
+ #: brain answered in would make the session history unreadable as a
+ #: conversation.
+ polish_conversation: bool = False
+
# ------------------------------------------------------------------
# The translate pass — speak one language, deliver another
# ------------------------------------------------------------------
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 78edb93701..eefc7e397b 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -116,6 +116,48 @@ class TranscriptionUpdate(Event):
is_final: bool = False
+@dataclass(frozen=True, slots=True)
+class TranscriptPolished(Event):
+ """A finished voice turn, re-read and written out as prose.
+
+ The AFTERMATH of a turn, never part of it. The brain has already been given
+ ``text`` verbatim and is already answering by the time this fires — that is
+ the entire design. The polish pass costs up to its latency ceiling, and
+ spending that between the user finishing a sentence and Jarvis starting to
+ answer would trade the thing that makes a voice assistant feel alive for a
+ comma. So the turn runs unpolished at full speed and this arrives a moment
+ later, for the surfaces that DISPLAY and STORE the turn rather than act on
+ it: the transcription view, the session record.
+
+ Separate from ``DictationTranscript`` (a dictation is text on its way into a
+ document, and it is polished BEFORE delivery because nothing is waiting on
+ it) and from ``TranscriptFinal`` (which is the turn itself, and must never
+ be delayed). Three events because there are three different deadlines.
+
+ Fail-open like every other part of the pass: when it does not arrive — no
+ key, a timeout, a guard that fired — the raw transcript simply stands, which
+ is what every consumer already has.
+ """
+
+ #: The polished text. Never empty: this event is not published at all when
+ #: the pass returned anything other than a usable rewrite.
+ text: str = ""
+ #: The exact string this replaces, so a consumer can match it to the turn it
+ #: belongs to without depending on event ordering, and can keep the original
+ #: alongside rather than over-writing it.
+ raw_text: str = ""
+ #: The pass's own status vocabulary (``jarvis.dictation.polish``), carried
+ #: so a recorder can store WHY a turn is unpolished instead of leaving the
+ #: absence of an event as the only evidence.
+ status: str = ""
+ #: The model family that answered, "" when none did.
+ provider: str = ""
+ #: What the pass cost in wall-clock time. Off the critical path by
+ #: construction, and worth measuring precisely because that claim has to
+ #: stay true.
+ latency_ms: int = 0
+
+
@dataclass(frozen=True, slots=True)
class DictationTranscript(Event):
"""Live transcript of a dictation, as it is recognized.
diff --git a/jarvis/sessions/models.py b/jarvis/sessions/models.py
index 7f50c9cb44..bad4b03af3 100644
--- a/jarvis/sessions/models.py
+++ b/jarvis/sessions/models.py
@@ -111,6 +111,11 @@ class VoiceTurnRow(BaseModel):
started_ms: int
ended_ms: int | None = None
user_text: str = ""
+ #: The wording pass's reading of ``user_text``; "" when it never ran, was
+ #: switched off, or was refused by a guard. Never replaces ``user_text`` —
+ #: what was said is the record, this is a convenience laid beside it, and a
+ #: consumer that wants the original can always still have it.
+ user_text_polished: str = ""
user_lang: str = "de"
jarvis_text: str = ""
jarvis_lang: str = "de"
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index e990379fcc..9dbaa30281 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -58,6 +58,7 @@ from jarvis.core.events import (
ToolCallStarted,
TranscriptFinal,
TranscriptionUpdate,
+ TranscriptPolished,
VoiceSessionEnded,
VoiceSessionStarted,
VoiceTurnCompleted,
@@ -337,6 +338,8 @@ class SessionRecorder:
self._on_transcript_final(event)
elif isinstance(event, TranscriptionUpdate):
self._on_transcription_update(event)
+ elif isinstance(event, TranscriptPolished):
+ self._on_transcript_polished(event)
elif isinstance(event, BrainTurnStarted):
self._on_brain_started(event)
elif isinstance(event, BrainTurnCompleted):
@@ -777,6 +780,53 @@ class SessionRecorder:
recovered.turn_id,
)
+ def _on_transcript_polished(self, event: TranscriptPolished) -> None:
+ """Attach a polished reading to the turn whose words it re-reads.
+
+ The event arrives on its OWN clock — the pass runs beside the brain, so
+ it lands while the turn is still open, or after it was finalized, or
+ after the next turn has already opened. Which is why the turn is found
+ by MATCHING the text rather than by assuming "the current one": stamping
+ a late arrival onto whatever turn happens to be open is how one user's
+ sentence ends up attributed to the next (the BUG-090 shape, which
+ ``last_final_turn`` exists for).
+
+ Two candidates are considered and no more: the open turn and the last
+ finalized one. Anything older has scrolled out of the window this pass
+ can possibly still be answering for — its ceiling is a second or two —
+ and searching further would trade a correct miss for a possible
+ mis-attribution.
+
+ Written straight through to the store rather than held on the in-memory
+ turn, because for the already-finalized candidate there is no finalize
+ left to carry it. ``user_text`` is never touched.
+ """
+ if self._state is None:
+ return
+ polished = str(event.text or "").strip()
+ raw = str(event.raw_text or "").strip()
+ if not polished or not raw or polished == raw:
+ return
+
+ for candidate in (self._state.current_turn, self._state.last_final_turn):
+ if candidate is None:
+ continue
+ if str(candidate.user_text or "").strip() != raw:
+ continue
+ try:
+ self._store.set_turn_polished(
+ turn_id=candidate.turn_id, text=polished
+ )
+ except Exception as exc: # noqa: BLE001 — never break the recorder
+ log.debug("SessionRecorder: polished text not stored: %s", exc)
+ return
+
+ log.debug(
+ "SessionRecorder: a polished transcript matched no recent turn "
+ "(session=%s) — the raw transcript stands.",
+ self._state.session_id,
+ )
+
def _on_system_state(self, event: SystemStateChanged) -> None:
"""Track THINKING/SPEAKING boundaries for think_ms + speak_ms.
diff --git a/jarvis/sessions/schema.sql b/jarvis/sessions/schema.sql
index ccc950b1ef..4c6e42c98e 100644
--- a/jarvis/sessions/schema.sql
+++ b/jarvis/sessions/schema.sql
@@ -35,6 +35,10 @@ CREATE TABLE IF NOT EXISTS voice_turns (
started_ms INTEGER NOT NULL, -- turn start (user starts speaking)
ended_ms INTEGER, -- AudioOutFirst (Jarvis finished)
user_text TEXT NOT NULL DEFAULT '',
+ -- The wording pass's reading of user_text, '' when it never ran or was
+ -- refused. A SEPARATE column on purpose: what was said is the record, and a
+ -- model's reading of it is a convenience laid beside it, never over it.
+ user_text_polished TEXT NOT NULL DEFAULT '',
user_lang TEXT NOT NULL DEFAULT 'de',
jarvis_text TEXT NOT NULL DEFAULT '',
jarvis_lang TEXT NOT NULL DEFAULT 'de',
diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.py
index 09d0b856a0..35c5a6eb2d 100644
--- a/jarvis/sessions/store.py
+++ b/jarvis/sessions/store.py
@@ -162,6 +162,18 @@ class SessionStore:
"ADD COLUMN voice_provider TEXT NOT NULL DEFAULT ''"
)
log.info("SessionStore migration: added voice_turns.voice_provider")
+ if "user_text_polished" not in existing:
+ # A NEW column rather than a rewrite of ``user_text``, and that is
+ # the whole point: the transcript of what was actually said is the
+ # record, and a model's reading of it is a convenience laid beside
+ # it. Overwriting would leave no way to check the polish afterwards
+ # — the same rule the dictation history already follows by keeping
+ # the raw text next to the polished one.
+ self._conn.execute(
+ "ALTER TABLE voice_turns "
+ "ADD COLUMN user_text_polished TEXT NOT NULL DEFAULT ''"
+ )
+ log.info("SessionStore migration: added voice_turns.user_text_polished")
def close(self) -> None:
with self._lock:
@@ -354,6 +366,26 @@ class SessionStore:
),
)
+ def set_turn_polished(self, *, turn_id: str, text: str) -> None:
+ """Attach the polished reading of a turn's user text.
+
+ Its own statement rather than a parameter on :meth:`finalize_turn`
+ because it does not share that method's timing. The polish pass runs
+ beside the brain and lands whenever it lands — usually while the turn is
+ still open, sometimes after it has been finalized, and occasionally not
+ at all. A single UPDATE keyed on the row id is correct in all three
+ cases; threading it through finalize would only be correct in the middle
+ one, and would silently drop the polish in the others.
+
+ ``user_text`` is never touched. What was said is the record; this is a
+ reading of it laid alongside.
+ """
+ with self._lock:
+ self._c.execute(
+ "UPDATE voice_turns SET user_text_polished = ? WHERE id = ?",
+ (text, turn_id),
+ )
+
def update_turn_voice(
self,
*,
@@ -790,6 +822,12 @@ def _row_to_turn(r: sqlite3.Row) -> VoiceTurnRow:
started_ms=r["started_ms"],
ended_ms=r["ended_ms"],
user_text=r["user_text"],
+ # Read through the row's own keys rather than indexed, so a database
+ # that predates the migration (or a SELECT that does not list it) yields
+ # "" instead of raising on a missing column.
+ user_text_polished=(
+ r["user_text_polished"] if "user_text_polished" in r.keys() else ""
+ ),
user_lang=r["user_lang"],
jarvis_text=r["jarvis_text"],
jarvis_lang=r["jarvis_lang"],
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 865ca64ae0..6c02920065 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -3935,6 +3935,100 @@ class SpeechPipeline:
except RuntimeError as exc:
log.debug("%s publish scheduling failed: %s", type(event).__name__, exc)
+ def _spawn_turn_polish(self, raw: str, *, language: str) -> None:
+ """Re-read a finished voice turn as prose, AFTER the turn has moved on.
+
+ Returns immediately, always. The brain already has ``raw`` verbatim and
+ is already answering; this schedules the polish pass beside that work and
+ publishes ``TranscriptPolished`` if a usable rewrite comes back. Nothing
+ in the turn waits for it, and nothing in the turn changes because of it —
+ the polished text is for the surfaces that DISPLAY and STORE the turn.
+
+ Putting the pass in front of the brain instead would be the obvious
+ implementation and the wrong one: it spends the whole latency ceiling
+ between the user finishing a sentence and Jarvis starting to answer,
+ every single turn, to improve a transcript nobody is reading yet.
+
+ Deliberately does NOT translate, even with ``[dictation].translate`` on.
+ That switch is about dictated text on its way into a document. A
+ conversation transcript is a record of what was said, and a record in a
+ different language from the one the assistant answered in is not a
+ readable conversation.
+
+ Fail-open twice, like the dictation call site: ``polish_transcript``
+ never raises and returns the raw text on every non-``applied`` status,
+ and the task additionally swallows anything the import or the publish
+ surfaces. A wording pass may never cost a turn.
+ """
+ text = str(raw or "").strip()
+ if not text:
+ return
+ cfg = getattr(self._config, "dictation", None)
+ # Both switches, because this EXTENDS the formatter rather than being a
+ # second one. Checked here rather than inside the task so the common
+ # case — the feature is off — costs one attribute read and no task.
+ if not getattr(cfg, "polish", False):
+ return
+ if not getattr(cfg, "polish_conversation", False):
+ return
+
+ async def _run() -> None:
+ try:
+ from jarvis.core.events import TranscriptPolished
+ from jarvis.dictation.polish import polish_transcript
+
+ result = await polish_transcript(
+ text,
+ language=language,
+ cfg=cfg,
+ protected_terms=self._dictation_protected_terms(),
+ style=str(getattr(cfg, "polish_style", "neutral") or "neutral"),
+ )
+ log.debug(
+ "turn polish: %s (%s, %d ms%s).",
+ result.status,
+ result.provider or "no provider",
+ result.latency_ms,
+ f", {result.reason}" if result.reason else "",
+ )
+ # ``applied`` is the only status that carries a DIFFERENT string;
+ # every other one hands back exactly what went in, and publishing
+ # that would make every consumer re-render the text it already
+ # has and log a change that never happened.
+ if result.status != "applied":
+ return
+ await self._publish_event(
+ TranscriptPolished(
+ source_layer="speech.stt",
+ text=result.text,
+ raw_text=text,
+ status=result.status,
+ provider=result.provider,
+ latency_ms=result.latency_ms,
+ )
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — a wording pass never costs a turn
+ log.debug("turn polish failed; the raw transcript stands.",
+ exc_info=True)
+
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # No loop means no turn in flight either; nothing to polish.
+ return
+ # Same strong-reference discipline as ``_publish_detached``: the loop
+ # holds only a weak one, so a fire-and-forget task can be collected
+ # mid-flight and the polish would simply never happen.
+ pending = getattr(self, "_turn_polish_tasks", None)
+ if pending is None:
+ pending = set()
+ self._turn_polish_tasks = pending
+ task = loop.create_task(_run(), name="turn-polish")
+ pending.add(task)
+ task.add_done_callback(pending.discard)
+
async def _publish_utterance_captured(self, pcm: bytes) -> None:
duration_ms = int((len(pcm) / 2) / 16_000 * 1000)
audio_ref = hashlib.sha256(pcm).hexdigest()[:16]
@@ -12219,6 +12313,18 @@ class SpeechPipeline:
)
)
+ # Re-read this turn as prose, beside the brain rather than in front of
+ # it. Deliberately HERE and not next to the ``TranscriptFinal`` publish
+ # above: everything between the two is a gate that decides this
+ # utterance is not worth answering — a bare wake word, a hangup, a
+ # Whisper hallucination, our own speaker echo — and polishing text we
+ # just decided to throw away spends a model call on nothing.
+ #
+ # ``transcript.text`` rather than the recombined ``text``, so the string
+ # published for matching is the one the session recorder stored as this
+ # turn's ``user_text``.
+ self._spawn_turn_polish(transcript.text, language=lang)
+
# Continuation-Buffer (Spec: incomplete-prompt completion). If this
# utterance ends open (trailing comma / conjunction / determiner /
# preposition), hold it and wait up to 8s for the continuation. On
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index f50cb683a1..6e1b000789 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -511,6 +511,16 @@ class SettingsBody(BaseModel):
"is off unless you turn it on. Applies to translated dictations too."
),
)
+ polish_conversation: bool | None = Field(
+ default=None,
+ description=(
+ "Also tidy up the transcripts of ordinary conversations, not just "
+ "dictation. It never slows a reply down: the assistant answers your "
+ "raw words and the tidied version arrives afterwards, for the "
+ "transcript view and the session record. What was actually said is "
+ "always kept alongside. Needs the wording clean-up above."
+ ),
+ )
# The translate pass. Same FastAPI trap as the polish keys above: an
# undeclared body key is dropped before the handler ever sees it.
translate: bool | None = Field(
diff --git a/tests/unit/sessions/test_turn_polish.py b/tests/unit/sessions/test_turn_polish.py
new file mode 100644
index 0000000000..c8cfe14559
--- /dev/null
+++ b/tests/unit/sessions/test_turn_polish.py
@@ -0,0 +1,344 @@
+"""Polishing an ordinary voice turn — the pass that must never cost a turn.
+
+Three separate promises are pinned here, because breaking any one of them turns
+a readability feature into a regression the user feels:
+
+1. **It stays off the critical path.** The brain is handed the raw transcript
+ and is already answering; the polish runs beside it. A change that moves the
+ pass in front of the brain would still pass every functional test and would
+ add the whole latency ceiling to every single turn.
+2. **It never publishes a no-op.** Only ``applied`` carries a different string.
+ Publishing ``unchanged`` would make every consumer re-render text it already
+ has and record a change that never happened.
+3. **It attaches to the right turn.** The event arrives on its own clock, so
+ the recorder matches it by TEXT. Stamping a late arrival onto whichever turn
+ happens to be open is the BUG-090 shape — one person's sentence attributed
+ to the next.
+
+No network and no real pipeline: ``_spawn_turn_polish`` reads three attributes
+off ``self``, so it is exercised bound to a stand-in.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass, field
+from typing import Any
+
+import pytest
+
+from jarvis.core.events import TranscriptPolished
+from jarvis.dictation.polish import PolishOutcome
+from jarvis.sessions.recorder import _SessionState, _TurnState
+from jarvis.sessions.store import SessionStore
+from jarvis.speech.pipeline import SpeechPipeline
+
+RAW = "so we should probably move the meeting to the morning and tell the team"
+POLISHED = "So we should probably move the meeting to the morning and tell the team."
+
+
+@dataclass
+class _Dictation:
+ polish: bool = True
+ polish_conversation: bool = True
+ polish_style: str = "neutral"
+ # Deliberately ON, to prove the turn pass ignores it: translating a
+ # conversation RECORD into another language than the one the assistant
+ # answered in makes the session history unreadable as a conversation.
+ translate: bool = True
+ translate_target: str = "en"
+
+
+@dataclass
+class _Config:
+ dictation: _Dictation = field(default_factory=_Dictation)
+
+
+@dataclass
+class _FakePipeline:
+ """Everything ``_spawn_turn_polish`` touches on ``self`` — and no more."""
+
+ _config: _Config = field(default_factory=_Config)
+ published: list[Any] = field(default_factory=list)
+
+ def _dictation_protected_terms(self) -> tuple[str, ...]:
+ return ("Jarvis",)
+
+ async def _publish_event(self, event: Any) -> None:
+ self.published.append(event)
+
+ def spawn(self, raw: str, *, language: str = "en") -> None:
+ SpeechPipeline._spawn_turn_polish(self, raw, language=language) # type: ignore[arg-type]
+
+
+async def _settle() -> None:
+ """Let the detached task run to completion."""
+ for _ in range(6):
+ await asyncio.sleep(0)
+
+
+def calls(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
+ """Record every call into the polish pass, and answer with ``applied``."""
+ seen: list[dict[str, Any]] = []
+
+ async def _fake(text: str, **kwargs: Any) -> PolishOutcome:
+ seen.append({"text": text, **kwargs})
+ return PolishOutcome(text=POLISHED, status="applied", provider="groq")
+
+ monkeypatch.setattr("jarvis.dictation.polish.polish_transcript", _fake)
+ return seen
+
+
+# --------------------------------------------------------------------------- #
+# The switch
+# --------------------------------------------------------------------------- #
+
+
+async def test_nothing_happens_when_the_feature_is_off(
+ calls: list[dict[str, Any]],
+) -> None:
+ pipeline = _FakePipeline(_Config(_Dictation(polish_conversation=False)))
+
+ pipeline.spawn(RAW)
+ await _settle()
+
+ assert calls == []
+ assert pipeline.published == []
+
+
+async def test_nothing_happens_when_the_formatter_itself_is_off(
+ calls: list[dict[str, Any]],
+) -> None:
+ """It EXTENDS the formatter; with that off there is nothing to extend."""
+ pipeline = _FakePipeline(_Config(_Dictation(polish=False)))
+
+ pipeline.spawn(RAW)
+ await _settle()
+
+ assert calls == []
+
+
+async def test_an_empty_transcript_is_not_sent_anywhere(
+ calls: list[dict[str, Any]],
+) -> None:
+ pipeline = _FakePipeline()
+
+ pipeline.spawn(" ")
+ await _settle()
+
+ assert calls == []
+
+
+# --------------------------------------------------------------------------- #
+# What it publishes
+# --------------------------------------------------------------------------- #
+
+
+async def test_a_polished_turn_is_published(calls: list[dict[str, Any]]) -> None:
+ pipeline = _FakePipeline()
+
+ pipeline.spawn(RAW)
+ await _settle()
+
+ assert len(pipeline.published) == 1
+ event = pipeline.published[0]
+ assert isinstance(event, TranscriptPolished)
+ assert event.text == POLISHED
+ # The raw text rides along so a consumer can match the turn it belongs to
+ # without depending on event ordering.
+ assert event.raw_text == RAW
+ assert event.status == "applied"
+ assert event.provider == "groq"
+
+
+async def test_the_call_returns_before_the_pass_does() -> None:
+ """The whole point: the turn does not wait.
+
+ The fake blocks until released, so a synchronous implementation would
+ deadlock here rather than fail an assertion.
+ """
+ released = asyncio.Event()
+
+ async def _slow(text: str, **kwargs: Any) -> PolishOutcome:
+ await released.wait()
+ return PolishOutcome(text=POLISHED, status="applied")
+
+ pipeline = _FakePipeline()
+ import jarvis.dictation.polish as polish_mod
+
+ original = polish_mod.polish_transcript
+ polish_mod.polish_transcript = _slow # type: ignore[assignment]
+ try:
+ pipeline.spawn(RAW) # must return immediately
+ await _settle()
+ assert pipeline.published == [], "published before the pass finished"
+ released.set()
+ await _settle()
+ assert len(pipeline.published) == 1
+ finally:
+ polish_mod.polish_transcript = original # type: ignore[assignment]
+
+
[email protected]("status", ["unchanged", "rejected_drift", "timeout", "unavailable", "off"])
+async def test_only_a_real_rewrite_is_published(
+ monkeypatch: pytest.MonkeyPatch, status: str
+) -> None:
+ """Every other status hands back exactly what went in."""
+
+ async def _fake(text: str, **kwargs: Any) -> PolishOutcome:
+ return PolishOutcome(text=text, status=status)
+
+ monkeypatch.setattr("jarvis.dictation.polish.polish_transcript", _fake)
+ pipeline = _FakePipeline()
+
+ pipeline.spawn(RAW)
+ await _settle()
+
+ assert pipeline.published == []
+
+
+async def test_a_failing_pass_never_reaches_the_turn(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def _boom(text: str, **kwargs: Any) -> PolishOutcome:
+ raise RuntimeError("provider exploded")
+
+ monkeypatch.setattr("jarvis.dictation.polish.polish_transcript", _boom)
+ pipeline = _FakePipeline()
+
+ pipeline.spawn(RAW)
+ await _settle()
+
+ assert pipeline.published == []
+
+
+async def test_a_conversation_turn_is_never_translated(
+ calls: list[dict[str, Any]],
+) -> None:
+ """With ``translate`` ON, the turn pass still asks for no translation."""
+ pipeline = _FakePipeline()
+
+ pipeline.spawn(RAW)
+ await _settle()
+
+ assert calls[0].get("translate_to", "") == ""
+
+
+async def test_the_users_own_terms_are_protected(
+ calls: list[dict[str, Any]],
+) -> None:
+ pipeline = _FakePipeline()
+
+ pipeline.spawn(RAW)
+ await _settle()
+
+ assert "Jarvis" in calls[0]["protected_terms"]
+
+
+# --------------------------------------------------------------------------- #
+# Where it lands
+# --------------------------------------------------------------------------- #
+
+
+def _store(tmp_path: Any) -> SessionStore:
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ return store
+
+
+def test_the_polished_column_survives_an_older_database(tmp_path: Any) -> None:
+ """The migration runs on open, and the default is the honest "" ."""
+ store = _store(tmp_path)
+ try:
+ store.upsert_session(
+ session_id="s1", started_ms=1_000, language="en", voice_mode="pipeline"
+ )
+ store.upsert_turn(turn_id="t1", session_id="s1", idx=0, started_ms=1_000)
+
+ store.set_turn_polished(turn_id="t1", text=POLISHED)
+ turns = store.get_turns("s1")
+
+ assert turns[0].user_text_polished == POLISHED
+ # The record of what was said is untouched.
+ assert turns[0].user_text == ""
+ finally:
+ store.close()
+
+
+@dataclass
+class _RecordingStore:
+ written: list[tuple[str, str]] = field(default_factory=list)
+
+ def set_turn_polished(self, *, turn_id: str, text: str) -> None:
+ self.written.append((turn_id, text))
+
+
+def _recorder(store: Any, *, current: Any = None, last: Any = None) -> Any:
+ from jarvis.sessions.recorder import SessionRecorder
+
+ recorder = SessionRecorder(store)
+ state = _SessionState(session_id="s1", started_ms=0, language="en")
+ state.current_turn = current
+ state.last_final_turn = last
+ recorder._state = state
+ return recorder
+
+
+def _turn(turn_id: str, user_text: str) -> _TurnState:
+ return _TurnState(turn_id=turn_id, idx=0, started_ms=0, user_text=user_text)
+
+
+def _event() -> TranscriptPolished:
+ return TranscriptPolished(
+ source_layer="speech.stt", text=POLISHED, raw_text=RAW, status="applied"
+ )
+
+
+def test_it_attaches_to_the_open_turn() -> None:
+ store = _RecordingStore()
+ recorder = _recorder(store, current=_turn("open", RAW))
+
+ recorder._on_transcript_polished(_event())
+
+ assert store.written == [("open", POLISHED)]
+
+
+def test_it_attaches_to_a_turn_that_was_already_finalized() -> None:
+ """The pass lands on its own clock; the turn may already be closed."""
+ store = _RecordingStore()
+ recorder = _recorder(
+ store, current=_turn("next", "something else entirely"), last=_turn("done", RAW)
+ )
+
+ recorder._on_transcript_polished(_event())
+
+ assert store.written == [("done", POLISHED)]
+
+
+def test_it_never_stamps_a_late_arrival_onto_the_wrong_turn() -> None:
+ """The BUG-090 shape: one person's sentence attributed to the next.
+
+ A miss is the correct outcome — the raw transcript simply stands, which is
+ what every consumer already has.
+ """
+ store = _RecordingStore()
+ recorder = _recorder(
+ store,
+ current=_turn("next", "a completely different sentence"),
+ last=_turn("older", "another unrelated sentence"),
+ )
+
+ recorder._on_transcript_polished(_event())
+
+ assert store.written == []
+
+
+def test_a_store_failure_never_breaks_the_recorder() -> None:
+ class _Broken:
+ def set_turn_polished(self, **kwargs: Any) -> None:
+ raise RuntimeError("disk is gone")
+
+ recorder = _recorder(_Broken(), current=_turn("open", RAW))
+
+ recorder._on_transcript_polished(_event()) # must not raise