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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(realtime,sessions): session detail/turn-card rework + realtime session updates
Ruben Lütke776074773672
diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 3f2d40926d..8e63abaa83 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -271,23 +271,22 @@ class ResponseGenerated(Event):@dataclass(frozen=True, slots=True)class SpeechSpoken(Event):- """A phrase was VOICED through TTS that is not the brain's normal reply.+ """Text committed to the user-audible output path.- The normal brain reply is already captured in the voice-session transcript- via ``ResponseGenerated`` -> ``VoiceTurnRow.jarvis_text``. But every OTHER- thing Jarvis speaks aloud — timeout / unavailable apologies, clarifying- questions, privacy acks, skill / mission announcements, the "still working"- progress nudge, flash-brain preambles, error readbacks — went through a- different speak path that never emitted ``ResponseGenerated``, so it left- NO trace in the Transcription view even though the user heard it.+ ``ResponseGenerated`` describes model output and can precede TTS, filtering,+ staleness checks, or interruption. ``SpeechSpoken`` is the authoritative+ transcript track. Producers emit it only after the corresponding audio was+ accepted by the active playback surface. This includes normal replies,+ timeout and unavailable notices, clarifying questions, privacy acknowledgments,+ mission announcements, progress nudges, preambles, and error readbacks.- The pipeline publishes this event at every such speak site so the passive+ The pipeline publishes this event at every audible-output site so the passive``SessionRecorder`` can persist it into ``voice_events`` and theTranscription view can show the full spoken track. ``spoken_kind`` is asoft tag from ``jarvis.sessions.constants.SPOKEN_KINDS`` (timeout /announcement / clarify / …) used for the UI label.- Latency-neutral: published fire-and-forget; the recorder is a read-only+ Published fire-and-forget; the recorder is a read-onlywildcard subscriber and never touches the voice hot path (AP-9 / AD-OE2)."""text: str = ""diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 455f9492a9..7ffb119e6c 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -31,6 +31,7 @@ from jarvis.sessions.constants import (HANGUP_CLIENT_STOP,HANGUP_VOICE_PATTERN,SPOKEN_KIND_PROGRESS,+ SPOKEN_KIND_REPLY,SPOKEN_KIND_WITHHELD,)from jarvis.speech.hangup import HANGUP_RE@@ -70,12 +71,12 @@ _END_CALL_DECLARATION: dict[str, Any] = {_DELEGATE_TIMEOUT_S = 90.0_DELEGATE_INPUT_BOUNDARY_WAIT_S = 3.0_DELEGATE_NATIVE_BOUNDARY_WAIT_S = 1.0-# BUG-051: a delegated router turn regularly needs 10-20 s before its first-# grounded token, and the pending-action honesty guard rightly mutes the live-# model for the whole wait — without a bridge the user hears pure dead air and-# hangs up. The bridge fires only when the action is still pending after this-# delay (necessity gate: fast actions stay chatter-free).-_DELEGATE_BRIDGE_DELAY_S = 2.0+# A realtime bridge is useful only for a genuinely long delegated turn. Starting+# a second provider response after two seconds made ordinary 5-7 second searches+# slower: the trusted result had to wait for the interim response lifecycle to+# end. Keep the classic speech-pipeline acknowledgement timing unchanged; this+# longer threshold belongs only to the realtime provider bridge.+_DELEGATE_BRIDGE_DELAY_S = 6.0_DELEGATE_HISTORY_MAX_MESSAGES = 8_DELEGATE_HISTORY_MAX_CHARS = 1_200_DELEGATE_DECLARATION: dict[str, Any] = {@@ -220,28 +221,38 @@ def _direct_tool_result_retry_prompt(*, language: str) -> str:)-def _delegate_bridge_prompt(topic: str, *, language: str) -> str:+_DELEGATE_BRIDGE_TEXT = {+ "de": "Ich bin noch dran.", # i18n-allow: localized runtime progress output+ "en": "I'm still working on it.",+ "es": "Sigo trabajando en ello.",+}+++def _delegate_bridge_text(language: str) -> str:+ return _DELEGATE_BRIDGE_TEXT.get(language, _DELEGATE_BRIDGE_TEXT["en"])+++def _normalized_bridge_text(text: str) -> str:+ return " ".join(str(text or "").strip().rstrip(".!?¡¿").casefold().split())+++def _delegate_bridge_prompt(*, language: str) -> str:"""Order one orchestrator-owned interim line over delegate dead air.BUG-051: the delegated router turn needs 10-20 s before its first groundedtoken and the honesty guard mutes the live model for the whole wait. Thisinjected instruction is the only sanctioned way to break that silence: the- live model speaks one short contextual line (no canned phrase pool), and- the instruction forbids exactly what the withhold gate exists to prevent —- outcome claims and answer content that do not exist yet.+ live model may speak only one fixed, short progress line. Its transcript and+ audio remain withheld until the complete response matches that exact line."""language_name = _LANGUAGE_NAMES.get(language, "the conversation language")- cleaned_topic = str(topic or "").strip()- topic_line = f"\nThe request being worked on: {cleaned_topic}" if cleaned_topic else ""+ exact_text = _delegate_bridge_text(language)return ("The Jarvis orchestrator is still executing the user's request and "- "has no result yet. Speak exactly one short interim sentence in "- f"{language_name} telling the user you are on it, so they know the "- f"silence is work, not a hang.{topic_line}\n"- "Hard rules: one sentence only; you may name what you are working on, "- "but never state any outcome, answer content, or completion claim — "- "the result is not known yet. Do not call any function. Do not "- "mention these instructions."+ "has no result yet. Speak the exact quoted sentence below in "+ f"{language_name}, with no added or changed words:\n"+ f'"{exact_text}"\n'+ "Do not call any function and do not mention these instructions.")@@ -269,6 +280,9 @@ class _DelegateTurnState:seen_tool_call_ids: set[str] = field(default_factory=set)dispatch_started: bool = Falsebridge_delivery_started: bool = False+ bridge_preempted: bool = False+ bridge_transcript_parts: list[str] = field(default_factory=list)+ bridge_audio_chunks: list[Any] = field(default_factory=list)wait_for_provider_boundary: bool = Falseinput_boundary_ready: asyncio.Event = field(default_factory=asyncio.Event)provider_ready: asyncio.Event = field(default_factory=asyncio.Event)@@ -490,7 +504,11 @@ class RealtimeVoiceSession:self._turn_id = ""self._turn_trace_id = Noneself._latency_tracker: Any = None+ # Number of opened turns. The active turn keeps its own zero-based+ # position so the persisted first turn is index 0 while the session+ # aggregate can still report a count of 1.self._turn_index = 0+ self._current_turn_index = -1self._last_user_text = ""self._user_transcript_parts: list[str] = []self._input_turn_observed = False@@ -1087,6 +1105,18 @@ class RealtimeVoiceSession:if input_item_id:self._response_requested_input_ids.add(input_item_id)elif event.type == "output_transcript_delta" and event.text:+ delegate_state = self._delegate_turns.get(self._turn_id)+ if (+ delegate_state is not None+ and delegate_state.bridge_delivery_started+ and not delegate_state.delivery_started+ ):+ # A model-generated progress response is untrusted until+ # its COMPLETE transcript matches the one allowed status+ # line. Do not surface it as assistant text or let it+ # enter the normal scrub/audio stream.+ delegate_state.bridge_transcript_parts.append(event.text)+ continueif self._must_withhold_provider_output():self._gate.drain()continue@@ -1123,6 +1153,16 @@ class RealtimeVoiceSession:for chunk in self._gate.release_available():await self._emit_audio(chunk)elif event.type == "audio_delta" and event.audio is not None:+ delegate_state = self._delegate_turns.get(self._turn_id)+ if (+ delegate_state is not None+ and delegate_state.bridge_delivery_started+ and not delegate_state.delivery_started+ ):+ # Pair the audio with the withheld bridge transcript. It+ # is released only after exact deterministic validation.+ delegate_state.bridge_audio_chunks.append(event.audio)+ continueif self._must_withhold_provider_output():self._gate.drain()continue@@ -1220,19 +1260,38 @@ class RealtimeVoiceSession:delegate_state.bridge_delivery_startedand not delegate_state.delivery_started)- if bridge_completed:- # The bridge response was audible — flush its tail- # instead of discarding it with the withheld-output- # bookkeeping below. A scrub hard-leak still drops- # the tail rather than leaking unscrubbed audio.- final_chunks = self._gate.finalize()- if not self._gate.hard_leak_pending():- for chunk in final_chunks:- await self._emit_audio(chunk)- bridge_text = "".join(self._output_transcript).strip()- bridge_was_audible = bool(+ bridge_text = "".join(+ delegate_state.bridge_transcript_parts+ ).strip()+ expected_bridge = _delegate_bridge_text(self._language)+ bridge_valid = bool(bridge_completed- and bridge_text+ and _normalized_bridge_text(bridge_text)+ == _normalized_bridge_text(expected_bridge)+ )+ bridge_may_speak = bool(+ bridge_valid+ and not delegate_state.bridge_preempted+ and not delegate_state.result_ready.is_set()+ )+ if bridge_may_speak:+ for chunk in delegate_state.bridge_audio_chunks:+ # The result can become ready between buffered+ # chunks. Stop immediately rather than queueing+ # progress audio ahead of the trusted answer.+ if delegate_state.result_ready.is_set():+ delegate_state.bridge_preempted = True+ break+ await self._emit_audio(chunk)+ elif bridge_completed and bridge_text and not bridge_valid:+ log.warning(+ "realtime[%s] dropped non-conforming delegate "+ "bridge output",+ self.session_id,+ )+ bridge_was_audible = bool(+ bridge_may_speak+ and not delegate_state.bridge_preemptedand self._output_samples_sent > 0)self._gate.drain()@@ -1240,16 +1299,18 @@ class RealtimeVoiceSession:delegate_state.input_boundary_ready.set()delegate_state.provider_ready.set()self._output_transcript.clear()+ delegate_state.bridge_transcript_parts.clear()+ delegate_state.bridge_audio_chunks.clear()self._output_active = False- self._output_samples_sent = 0- if bridge_completed:+ if bridge_was_audible:# The interim sentence is a complete local playback# segment, but the delegated action is still running.# Surfaces drain that segment and return to THINKING;# the final answer will open a new SPEAKING segment.await self._send_json({"type": "thinking"})if bridge_was_audible:- await self._publish_delegate_bridge_spoken(bridge_text)+ await self._publish_delegate_bridge_spoken(expected_bridge)+ self._output_samples_sent = 0log.debug("realtime[%s] held provider turn_complete for ""delegate turn %s",@@ -1570,6 +1631,7 @@ class RealtimeVoiceSession:trace_id = uuid4()self._turn_trace_id = trace_idself._turn_id = str(trace_id)+ self._current_turn_index = self._turn_indexself._turn_index += 1self._latency_tracker = self._create_latency_tracker(trace_id)if self._external_update is None:@@ -1828,7 +1890,7 @@ class RealtimeVoiceSession:source_layer=f"realtime.{self.active_provider}",session_id=self.session_id,turn_id=self._turn_id,- turn_index=self._turn_index,+ turn_index=self._current_turn_index,))except Exception: # noqa: BLE001, S110@@ -1899,6 +1961,16 @@ class RealtimeVoiceSession:language=self._language,))+ if answer and self._output_samples_sent > 0:+ await self._bus.publish(+ SpeechSpoken(+ **self._event_trace_kwargs(),+ source_layer=f"realtime.{self.active_provider}",+ text=answer,+ language=self._language,+ spoken_kind=SPOKEN_KIND_REPLY,+ )+ )await self._bus.publish(VoiceTurnCompleted(**self._event_trace_kwargs(),@@ -1960,6 +2032,7 @@ class RealtimeVoiceSession:self._turn_id = ""self._turn_trace_id = Noneself._latency_tracker = None+ self._current_turn_index = -1self._last_user_text = ""self._user_transcript_parts.clear()self._input_turn_observed = False@@ -2449,11 +2522,11 @@ class RealtimeVoiceSession:) -> None:"""Speak one interim line when a delegated action outlasts patience.- BUG-051: the ack used to arrive only AFTER the full first router model- round (~16 s), so the user heard pure dead air and hung up. This bridge- is delay-gated (fast actions stay chatter-free), spoken by the live- model itself (one voice per call, BUG-049), and content-bounded by the- injected instruction — never by a canned phrase pool.+ The bridge is realtime-only and deliberately later than the classic+ pipeline acknowledgement: normal delegated turns should finish before+ it. Its provider output is buffered and accepted only when the complete+ transcript matches the fixed localized progress line. A ready trusted+ result preempts the bridge lifecycle."""try:try:@@ -2474,14 +2547,19 @@ class RealtimeVoiceSession:if not callable(send_text):returnturn_state.bridge_delivery_started = True+ turn_state.bridge_preempted = False+ turn_state.bridge_transcript_parts.clear()+ turn_state.bridge_audio_chunks.clear()+ # ``send_text`` starts a distinct provider response. The trusted+ # result must wait for THIS boundary, not a boundary observed before+ # the bridge began.+ turn_state.provider_boundary_seen = False+ turn_state.provider_ready.clear()drop_before_bridge = self._drop_provider_output_until_new_responseself._drop_provider_output_until_new_response = Falsetry:await send_text(- _delegate_bridge_prompt(- turn_state.user_text,- language=self._language,- )+ _delegate_bridge_prompt(language=self._language))except Exception: # noqa: BLE001 — a broken bridge must not hurt the actionturn_state.bridge_delivery_started = False@@ -2506,6 +2584,30 @@ class RealtimeVoiceSession:exc_info=True,)+ async def _preempt_delegate_bridge(+ self,+ turn_id: str,+ turn_state: _DelegateTurnState,+ ) -> None:+ """Cancel a realtime-only interim response once the real result exists."""+ if (+ not turn_state.bridge_delivery_started+ or turn_state.delivery_started+ or turn_state.provider_boundary_seen+ or not self._delegate_turn_is_active(turn_id, turn_state)+ ):+ return+ turn_state.bridge_preempted = True+ turn_state.bridge_audio_chunks.clear()+ log.info(+ "realtime[%s] preempting delegate bridge for ready trusted result",+ self.session_id,+ )+ try:+ await self._session.interrupt()+ except Exception: # noqa: BLE001, S110 — boundary wait retains its fallback+ pass+async def _run_deterministic_delegate(self,turn_id: str,@@ -2615,6 +2717,7 @@ class RealtimeVoiceSession:self._queue_late_delegate_result(turn_state)return+ await self._preempt_delegate_bridge(turn_id, turn_state)await self._await_provider_response_boundary(turn_state)if not self._delegate_turn_is_active(turn_id, turn_state):@@ -2780,6 +2883,11 @@ class RealtimeVoiceSession:desired_kwargs: dict[str, Any] = {"allow_voice_confirm": True,"prefer_tool_model": True,+ # The classic pipeline owns its grounded tool acknowledgement.+ # A live realtime turn has its own late, preemptible bridge; a+ # second manager-level ack only creates duplicate UI/status+ # events and is dropped by the realtime voice owner anyway.+ "emit_tool_ack": False,"publish_response": False,"use_history": False,"history_override": tuple(self._delegate_history),diff --git a/jarvis/sessions/constants.py b/jarvis/sessions/constants.pyindex 37750fef45..2235933edb 100644--- a/jarvis/sessions/constants.py+++ b/jarvis/sessions/constants.py@@ -85,18 +85,16 @@ is intentionally stable for tests that assert against# Spoken-track kinds (SpeechSpoken.spoken_kind)# ----------------------------------------------------------------------#-# Same anti-drift contract as HANGUP_REASONS: every phrase Jarvis VOICES that-# is not the brain's normal reply is published as a ``SpeechSpoken`` event and+# Same anti-drift contract as HANGUP_REASONS: every phrase Jarvis commits to+# the audible output path is published as a ``SpeechSpoken`` event and# tagged with one of these kinds. The Transcription view renders a per-kind# label, so the set has to agree across Python (this module), the Pydantic# mirror (``models.py``), the TS const (``types.ts``) and the UI label map# (``TurnCard.tsx``). The parity test in# ``tests/unit/sessions/test_spoken_kind_parity.py`` fails on any drift.#-# Deliberately NOT a member: ``"reply"``. That is the sentinel default of-# ``SpeechPipeline._speak`` for the ordinary brain reply, which is already-# documented via ``ResponseGenerated`` -> ``jarvis_text``; ``_emit_spoken``-# suppresses it so it never reaches the spoken track.+SPOKEN_KIND_REPLY: Final[str] = "reply"+"""A normal assistant reply confirmed by the audible output path."""SPOKEN_KIND_CLARIFY: Final[str] = "clarify""""A clarifying question ('Wie meinst du das genau?') for an empty/incomplete turn."""@@ -147,6 +145,7 @@ SPOKEN_KIND_OTHER: Final[str] = "other""""Catch-all for any voiced phrase without a more specific tag."""SPOKEN_KINDS: Final[tuple[str, ...]] = (+ SPOKEN_KIND_REPLY,SPOKEN_KIND_CLARIFY,SPOKEN_KIND_TIMEOUT,SPOKEN_KIND_UNAVAILABLE,@@ -185,6 +184,7 @@ __all__ = ["SPOKEN_KIND_PREAMBLE","SPOKEN_KIND_PRIVACY","SPOKEN_KIND_PROGRESS",+ "SPOKEN_KIND_REPLY","SPOKEN_KIND_STT_UNAVAILABLE","SPOKEN_KIND_SUBAGENT","SPOKEN_KIND_TIMEOUT",diff --git a/jarvis/sessions/formatter.py b/jarvis/sessions/formatter.pyindex cdacc66f5b..eb49b2d576 100644--- a/jarvis/sessions/formatter.py+++ b/jarvis/sessions/formatter.py@@ -51,13 +51,14 @@ def _jarvis_outputs_for_turn() -> list[_JarvisOutput]:"""Return every Jarvis output for a turn in the order it was produced.- ``SpeechSpoken`` covers preambles, timeouts, readbacks and other voiced- non-reply phrases. ``ResponseGenerated`` covers the normal reply persisted- as ``VoiceTurnRow.jarvis_text``. Rendering both by timestamp prevents the- plain transcript from showing a preamble *after* the final answer.+ ``SpeechSpoken`` is authoritative for output accepted by the audible path.+ ``ResponseGenerated`` remains a compatibility fallback for sessions recorded+ before reply playback confirmation existed. Rendering by timestamp prevents+ the plain transcript from showing a preamble after the final answer."""items: list[_JarvisOutput] = []- saw_reply_event = False+ generated_replies: list[_JarvisOutput] = []+ saw_confirmed_reply = Falsefallback_seq = 1_000_000_000for e in events or []:if e.kind == "SpeechSpoken":@@ -66,13 +67,17 @@ def _jarvis_outputs_for_turn(continueraw_detail = e.payload.get("detail")detail = str(raw_detail).strip() if raw_detail else None+ spoken_kind = str(e.payload.get("spoken_kind", "other"))+ is_reply = spoken_kind == "reply"+ saw_confirmed_reply = saw_confirmed_reply or is_replyitems.append(_JarvisOutput(ts_ms=e.ts_ms,seq=e.seq or 0,text=text,- kind=str(e.payload.get("spoken_kind", "other")),+ kind=spoken_kind,detail=detail,+ is_reply=is_reply,))continue@@ -80,8 +85,7 @@ def _jarvis_outputs_for_turn(text = str(e.payload.get("text", "")).strip()if not text:continue- saw_reply_event = True- items.append(+ generated_replies.append(_JarvisOutput(ts_ms=e.ts_ms,seq=e.seq or 0,@@ -91,7 +95,10 @@ def _jarvis_outputs_for_turn())- if turn.jarvis_text and not saw_reply_event:+ if not saw_confirmed_reply:+ items.extend(generated_replies)++ if turn.jarvis_text and not generated_replies and not saw_confirmed_reply:items.append(_JarvisOutput(ts_ms=turn.ended_ms or turn.started_ms,@@ -144,8 +151,8 @@ def format_session_markdown(lines.append("_(keine Turns aufgezeichnet)_")return "\n".join(lines)- for t in turns_list:- lines.append(f"## Turn {t.idx + 1} · {_fmt_dt(t.started_ms, time_only=True)}")+ for display_index, t in enumerate(turns_list, start=1):+ lines.append(f"## Turn {display_index} · {_fmt_dt(t.started_ms, time_only=True)}")lines.append("")if t.user_text:diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsxindex 819e73267d..f3c6a7fbe8 100644--- a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx@@ -71,7 +71,8 @@ export function SessionDetail({ detail, loading, error }: Props) {const [editorFormat, setEditorFormat] = useState<ExportFormat | null>(null);// Group the SpeechSpoken raw events under their turn so each TurnCard can- // render the "Spoken output" track (every voiced non-reply phrase). Hook+ // render the playback-confirmed track. Reply entries replace generated model+ // text; all other kinds appear in the separate Spoken-output section. Hook// runs unconditionally (before the early returns) per the rules of hooks.const spokenByTurn = useMemo(() => {const map = new Map<string, VoiceSpokenLine[]>();@@ -333,10 +334,11 @@ export function SessionDetail({ detail, loading, error }: Props) {{t("session_detail.no_turns_suffix")}</div>) : (- turns.map((t) => (+ turns.map((t, index) => (<TurnCardkey={t.id}turn={t}+ displayNumber={index + 1}spoken={spokenByTurn.get(t.id) ?? []}/>))diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsxindex fa1a64c760..37921fd94b 100644--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.test.tsx@@ -1,8 +1,6 @@/**- * The Transcription turn card must show the "Spoken output" track — every- * phrase Jarvis VOICED that is not the normal reply (timeout / clarify /- * announcement / …). User report 2026-06-15: those special phrases were- * spoken but never appeared in the transcript.+ * The Transcription turn card uses playback-confirmed replies as its primary+ * assistant text and keeps status phrases/readbacks on a supplemental track.*/import { afterEach, describe, expect, it } from "vitest";import { cleanup, render, screen } from "@testing-library/react";@@ -49,6 +47,13 @@ function spokenLine(over: Partial<VoiceSpokenLine> = {}): VoiceSpokenLine {}describe("TurnCard spoken track", () => {+ it("uses the contiguous display number instead of a stale stored index", () => {+ render(<TurnCard turn={turn({ idx: 1 })} displayNumber={1} />);++ expect(screen.getByText("Turn 1")).toBeTruthy();+ expect(screen.queryByText("Turn 2")).toBeNull();+ });+it("renders each voiced phrase with a human-readable kind label", () => {render(<TurnCard turn={turn()} spoken={[spokenLine()]} />);expect(screen.getByText("Spoken output")).toBeTruthy();@@ -72,6 +77,24 @@ describe("TurnCard spoken track", () => {expect(screen.queryByText("Spoken output")).toBeNull();});+ it("uses the playback-confirmed reply instead of unplayed model text", () => {+ render(+ <TurnCard+ turn={turn({ jarvis_text: "Generated text that never reached audio." })}+ spoken={[+ spokenLine({+ spoken_kind: "reply",+ text: "This sentence reached playback.",+ }),+ ]}+ />,+ );++ expect(screen.getByText("This sentence reached playback.")).toBeTruthy();+ expect(screen.queryByText("Generated text that never reached audio.")).toBeNull();+ expect(screen.queryByText("Spoken output")).toBeNull();+ });+it("wraps very long transcript content without widening the turn card", () => {const longUserText = `user-${"x".repeat(400)}`;const longJarvisText = `assistant-${"y".repeat(400)}`;diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsxindex 379cd87f3a..65c3000e15 100644--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx@@ -32,6 +32,7 @@ import type { VoiceSpokenLine, VoiceTurnRow } from "./types";// (parity: tests/unit/sessions/test_spoken_kind_parity.py). An unknown kind// falls back to the kind string itself so it still renders.export const SPOKEN_KIND_LABEL: Record<string, string> = {+ reply: "Reply",clarify: "Clarifying question",timeout: "Timeout notice",unavailable: "Brain unavailable",@@ -50,16 +51,23 @@ export const SPOKEN_KIND_LABEL: Record<string, string> = {interface Props {turn: VoiceTurnRow;+ displayNumber?: number;spoken?: VoiceSpokenLine[];}-export function TurnCard({ turn, spoken = [] }: Props) {+export function TurnCard({ turn, displayNumber, spoken = [] }: Props) {const t = useT();const pushToast = useEventStore((s) => s.pushToast);const assistantName = useEventStore((s) => s.assistantName);// Desktop shell → save to ~/Downloads via the backend; browser → blob download.const caps = useCapabilities();const native = caps.data?.native_file_actions ?? false;+ const visibleTurnNumber = displayNumber ?? turn.idx + 1;+ const confirmedReplies = spoken.filter((line) => line.spoken_kind === "reply");+ const auxiliarySpoken = spoken.filter((line) => line.spoken_kind !== "reply");+ const audibleReply = confirmedReplies.length+ ? confirmedReplies.map((line) => line.text).join(" ")+ : turn.jarvis_text;// The Jarvis-Agents brand label is fixed: it names the system, not the// configured assistant, so it does not follow the assistant name.const kindLabel: Record<string, string> = {@@ -68,13 +76,13 @@ export function TurnCard({ turn, spoken = [] }: Props) {};const copyTurn = useCallback(async () => {- const text = formatTurnPlain(turn, spoken);+ const text = formatTurnPlain(turn, spoken, visibleTurnNumber);const ok = await robustCopy(text);pushToast(ok ? "success" : "error",- ok ? `${t("turn_card.turn")} ${turn.idx + 1} ${t("turn_card.copied")}` : t("turn_card.copy_failed"),+ ok ? `${t("turn_card.turn")} ${visibleTurnNumber} ${t("turn_card.copied")}` : t("turn_card.copy_failed"),);- }, [turn, spoken, pushToast, t]);+ }, [turn, spoken, visibleTurnNumber, pushToast, t]);const downloadTurn = useCallback(async () => {const text = formatTurnPlain(turn, spoken);@@ -110,7 +118,7 @@ export function TurnCard({ turn, spoken = [] }: Props) {{/* Header */}<div className="flex items-center justify-between gap-2"><div className="flex items-center gap-2 text-xs text-muted-foreground">- <span className="font-mono">Turn {turn.idx + 1}</span>+ <span className="font-mono">Turn {visibleTurnNumber}</span><span>·</span><span>{startedAt}</span>{turn.latency_total_ms > 0 && (@@ -217,7 +225,7 @@ export function TurnCard({ turn, spoken = [] }: Props) {)}{/* Jarvis */}- {turn.jarvis_text && (+ {audibleReply && (<div className="space-y-1"><div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-primary"><Volume2 className="h-3 w-3" />@@ -235,23 +243,22 @@ export function TurnCard({ turn, spoken = [] }: Props) {)}</div><div className="min-w-0 whitespace-pre-wrap break-words rounded-md border border-primary/20 bg-primary/5 p-2 text-sm [overflow-wrap:anywhere]">- {turn.jarvis_text}+ {audibleReply}</div></div>)}- {/* Spoken output — every phrase Jarvis VOICED that is not the normal- reply (timeout/clarify/announcement/…). Without this the log only- shows the conversational reply and hides what the user actually- heard (user report 2026-06-15). */}- {spoken.length > 0 && (+ {/* Supplemental spoken output. Playback-confirmed normal replies render+ in the main assistant block above; status phrases and readbacks stay+ distinct here while preserving their audible order. */}+ {auxiliarySpoken.length > 0 && (<div className="space-y-1.5 border-t border-border/50 pt-2"><div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-sky-300"><MessageSquareWarning className="h-3 w-3" />Spoken output</div><div className="space-y-1">- {spoken.map((s, i) => {+ {auxiliarySpoken.map((s, i) => {// A spawned sub-agent / mission result gets its own colour so it// reads distinctly from a generic background completion and from// a normal reply: violet ("agent") vs. the sky tint of the rest.@@ -327,9 +334,10 @@ function formatMs(ms: number): string {export function formatTurnPlain(turn: VoiceTurnRow,spoken: VoiceSpokenLine[] = [],+ displayNumber: number = turn.idx + 1,): string {const lines: string[] = [];- lines.push(`--- Turn ${turn.idx + 1} ---`);+ lines.push(`--- Turn ${displayNumber} ---`);if (turn.user_text) lines.push(`[USER] ${turn.user_text}`);const meta: string[] = [];if (turn.tier) meta.push(`tier=${turn.tier}`);@@ -349,7 +357,8 @@ export function formatTurnPlain(lines.push(`[TOOLS] ${turn.tool_calls.join(", ")}`);}const jarvisLines: Array<{ ts_ms: number; lines: string[] }> = [];- if (turn.jarvis_text) {+ const hasConfirmedReply = spoken.some((line) => line.spoken_kind === "reply");+ if (turn.jarvis_text && !hasConfirmedReply) {const prefix = turn.awaiting_confirmation ? "(awaiting confirmation) " : "";jarvisLines.push({ts_ms: turn.ended_ms ?? Number.MAX_SAFE_INTEGER,@@ -357,6 +366,10 @@ export function formatTurnPlain(});}for (const s of spoken) {+ if (s.spoken_kind === "reply") {+ jarvisLines.push({ ts_ms: s.ts_ms, lines: [`[JARVIS] ${s.text}`] });+ continue;+ }const label = (SPOKEN_KIND_LABEL[s.spoken_kind] ?? s.spoken_kind).toUpperCase();// The technical detail is deliberately excluded from the transcript copy —// it lives in the Run Inspector, not in what was said (user request 2026-06-22).diff --git a/jarvis/ui/web/frontend/src/components/sessions/types.ts b/jarvis/ui/web/frontend/src/components/sessions/types.tsindex cef0e9fa50..3fddb1c6a4 100644--- a/jarvis/ui/web/frontend/src/components/sessions/types.ts+++ b/jarvis/ui/web/frontend/src/components/sessions/types.ts@@ -40,6 +40,7 @@ export type VoiceTier = string;// test_spoken_kind_parity.py. Kept ``string`` (not a union) for the same// BUG-008 reason as the others — an unknown kind must degrade, not crash.export const KNOWN_SPOKEN_KINDS = [+ "reply","clarify","timeout","unavailable",@@ -58,8 +59,8 @@ export const KNOWN_SPOKEN_KINDS = [export type SpokenKind = string;-// One voiced phrase, extracted from the SpeechSpoken raw events of a session-// and grouped under its turn for rendering the "Spoken output" track.+// One playback-confirmed phrase extracted from a session's SpeechSpoken events.+// Reply entries are authoritative; other kinds render as supplemental output.export interface VoiceSpokenLine {turn_id: string | null;ts_ms: number;diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 1c9329cd35..0b05cccd72 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -1046,6 +1046,7 @@ async def test_latency_and_voice_events_share_one_fresh_trace_per_turn():spans = [event for event in bus.events if isinstance(event, LatencySpan)]assert len(started) == len(completed) == 2+ assert [item.turn_index for item in started] == [0, 1]assert started[0].trace_id != started[1].trace_idassert [item.trace_id for item in completed] == [item.trace_id for item in started@@ -1823,6 +1824,13 @@ async def test_local_evidence_turns_run_deterministic_jarvis_action(utterance):"What is the capital of France?","What is SAP?","How do I open a file in Python?",+ (+ "Ach, ich versuche gerade Suggestionen zu studieren. " # i18n-allow+ "Wie würdest du mir am besten dabei helfen, " # i18n-allow+ "Suggestionen anzuwenden und konkreter zu benutzen, " # i18n-allow+ "um meine Mitmenschen dazu zu bringen, " # i18n-allow+ "meine Interessen zu verfolgen?" # i18n-allow+ ),"I sent you an email yesterday.",],)@@ -2328,7 +2336,7 @@ class _SlowDelegateBridgeSession(FakeSession):await self._bridge_sent.wait()yield RealtimeEvent(type="output_transcript_delta",- text="I'm checking that now.",+ text="I'm still working on it.",)yield RealtimeEvent(type="audio_delta",@@ -2342,6 +2350,18 @@ class _SlowDelegateBridgeSession(FakeSession):# delegated result exists; the turn must survive this completion.yield RealtimeEvent(type="turn_complete")await self._result_delivered.wait()+ yield RealtimeEvent(+ type="output_transcript_delta",+ text="Stored on your page: note.",+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x03\x04" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ )yield RealtimeEvent(type="turn_complete")async def send_text(self, text):@@ -2403,8 +2423,8 @@ async def test_slow_deterministic_delegate_speaks_a_bridge_line(monkeypatch):bridge = provider.session.text_inputs[0]assert "<trusted_action_result>" not in bridge- assert "interim" in bridge- assert "Write this to my wiki." in bridge # the line may name the topic+ assert '"I\'m still working on it."' in bridge+ assert "Write this to my wiki." not in bridge# While the bridge response is live, provider output must flow.assert sess._must_withhold_provider_output() is False@@ -2421,9 +2441,10 @@ async def test_slow_deterministic_delegate_speaks_a_bridge_line(monkeypatch):assert "finished only now" not in resultawait sess.wait_finished()assert binaries- progress = [event for event in bus.events if isinstance(event, SpeechSpoken)]- assert [(event.text, event.spoken_kind) for event in progress] == [- ("I'm checking that now.", "progress")+ spoken = [event for event in bus.events if isinstance(event, SpeechSpoken)]+ assert [(event.text, event.spoken_kind) for event in spoken] == [+ ("I'm still working on it.", "progress"),+ ("Stored on your page: note.", "reply"),]await sess.end(reason="test")@@ -2468,6 +2489,188 @@ async def test_fast_deterministic_delegate_needs_no_bridge_line(monkeypatch):await sess.end(reason="test")+class _PreemptedDelegateBridgeSession(FakeSession):+ """Hold the bridge response open until the trusted result preempts it."""++ def __init__(self, *, bridge_sent, interrupted, result_delivered):+ super().__init__([])+ self._bridge_sent = bridge_sent+ self._interrupted = interrupted+ self._result_delivered = result_delivered++ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="Check the current figure.",+ is_final=True,+ )+ await self._bridge_sent.wait()+ yield RealtimeEvent(+ type="output_transcript_delta",+ text="I'm still working on it.",+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ )+ await self._interrupted.wait()+ yield RealtimeEvent(type="turn_complete")+ await self._result_delivered.wait()+ yield RealtimeEvent(type="turn_complete")++ async def send_text(self, text):+ await super().send_text(text)+ if "<trusted_action_result>" in text:+ self._result_delivered.set()+ else:+ self._bridge_sent.set()++ async def interrupt(self):+ await super().interrupt()+ self._interrupted.set()+++class _PreemptedDelegateBridgeProvider(FakeProvider):+ def __init__(self, *, bridge_sent, interrupted, result_delivered):+ super().__init__([])+ self._bridge_sent = bridge_sent+ self._interrupted = interrupted+ self._result_delivered = result_delivered++ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _PreemptedDelegateBridgeSession(+ bridge_sent=self._bridge_sent,+ interrupted=self._interrupted,+ result_delivered=self._result_delivered,+ )+ return self.session+++async def test_ready_result_preempts_active_realtime_bridge(monkeypatch):+ """A finished result must not queue behind an in-flight interim response."""+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 0.01)+ gate = asyncio.Event()+ bridge_sent = asyncio.Event()+ interrupted = asyncio.Event()+ result_delivered = asyncio.Event()+ bus = FakeBus()+ binaries: list[bytes] = []+ provider = _PreemptedDelegateBridgeProvider(+ bridge_sent=bridge_sent,+ interrupted=interrupted,+ result_delivered=result_delivered,+ )+ brain = FakeBrain(replies=("The grounded figure is 42.",), gate=gate)+ sess = _session(+ provider,+ brain=brain,+ binaries=binaries,+ bus=bus,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(bridge_sent.wait(), timeout=2)+ gate.set()+ await asyncio.wait_for(interrupted.wait(), timeout=2)+ await asyncio.wait_for(result_delivered.wait(), timeout=2)++ assert provider.session.interrupts >= 1+ assert binaries == []+ assert not any(isinstance(event, SpeechSpoken) for event in bus.events)+ assert "<trusted_action_result>" in provider.session.text_inputs[-1]+ await sess.wait_finished()+ await sess.end(reason="test")+++async def test_nonconforming_realtime_bridge_audio_is_never_released(monkeypatch):+ """A hostile bridge cannot turn an ungrounded claim into spoken output."""+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 0.01)+ gate = asyncio.Event()+ bridge_sent = asyncio.Event()+ bridge_finished = asyncio.Event()+ result_delivered = asyncio.Event()++ class _HostileBridgeSession(FakeSession):+ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="List my private notebooks.",+ is_final=True,+ )+ await bridge_sent.wait()+ yield RealtimeEvent(+ type="output_transcript_delta",+ text="Your notebooks are Alpha, Beta, and Gamma.",+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ )+ yield RealtimeEvent(type="turn_complete")+ bridge_finished.set()+ await result_delivered.wait()+ yield RealtimeEvent(type="turn_complete")++ async def send_text(self, text):+ await super().send_text(text)+ if "<trusted_action_result>" in text:+ result_delivered.set()+ else:+ bridge_sent.set()++ class _HostileBridgeProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _HostileBridgeSession([])+ return self.session++ bus = FakeBus()+ binaries: list[bytes] = []+ provider = _HostileBridgeProvider([])+ brain = FakeBrain(replies=("Notebook access is unavailable.",), gate=gate)+ sess = _session(+ provider,+ brain=brain,+ binaries=binaries,+ bus=bus,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(bridge_finished.wait(), timeout=2)+ assert binaries == []+ assert not any(isinstance(event, SpeechSpoken) for event in bus.events)++ gate.set()+ await asyncio.wait_for(result_delivered.wait(), timeout=2)+ await sess.wait_finished()+ assert all(+ "Alpha, Beta, and Gamma" not in getattr(event, "text", "")+ for event in bus.events+ )+ await sess.end(reason="test")+++async def test_realtime_delegate_disables_classic_tool_ack() -> None:+ """Classic pipeline acks stay enabled by default; realtime opts out per turn."""+ brain = FakeBrain(replies=("done",))+ sess = _session(FakeProvider([]), brain=brain)++ assert await sess._dispatch_brain_turn("Check it.") == "done"+ assert brain.calls[0][1]["emit_tool_ack"] is False++@pytest.mark.asyncioasync def test_direct_mode_builds_bridge_from_brain(wire_supervisor_gateway):brain = FakeBrain()@@ -2980,6 +3183,7 @@ async def test_delegate_call_dispatches_raw_transcript_with_voice_confirm():{"allow_voice_confirm": True,"prefer_tool_model": True,+ "emit_tool_ack": False,"publish_response": False,"use_history": False,"history_override": (),diff --git a/tests/unit/sessions/test_formatter.py b/tests/unit/sessions/test_formatter.pyindex 21bf764b8d..ce33603140 100644--- a/tests/unit/sessions/test_formatter.py+++ b/tests/unit/sessions/test_formatter.py@@ -115,6 +115,19 @@ def test_plain_has_no_emoji_anchors() -> None:assert emoji not in out, f"emoji {emoji!r} leaked into clean transcript"+def test_markdown_renumbers_legacy_one_based_turn_indices() -> None:+ turns = [+ _turn(1, "First visible request.", "First answer."),+ _turn(2, "Second visible request.", "Second answer."),+ ]++ out = format_session_markdown(_session(), turns)++ assert "## Turn 1" in out+ assert "## Turn 2" in out+ assert "## Turn 3" not in out++def test_plain_has_no_markdown_markers() -> None:out = format_session_plain(_session(), _example_turns())assert "# " not in out # no headings@@ -301,6 +314,19 @@ def test_plain_orders_preamble_before_final_response_by_timestamp() -> None:assert preamble_pos < final_pos+def test_plain_prefers_confirmed_reply_over_generated_model_text() -> None:+ turns = [_turn(0, "Give me the result", "Generated text that was not played.")]+ events = [+ _response("turn-0", "Generated text that was not played.", ts_ms=1000),+ _spoken("turn-0", "This sentence reached playback.", "reply", ts_ms=2000),+ ]++ out = format_session_plain(_session(), turns, events)++ assert "Jarvis: This sentence reached playback." in out+ assert "Generated text that was not played." not in out++def test_plain_orders_late_readback_after_final_response() -> None:turns = [_turn(0, "Starte die Recherche", "Ich kuemmere mich darum.")]events = [diff --git a/tests/unit/sessions/test_recorder_realtime.py b/tests/unit/sessions/test_recorder_realtime.pyindex 5991fc9cfd..8a487b8bcc 100644--- a/tests/unit/sessions/test_recorder_realtime.py+++ b/tests/unit/sessions/test_recorder_realtime.py@@ -8,6 +8,7 @@ from jarvis.core.bus import EventBusfrom jarvis.core.events import (RealtimeSessionReady,ResponseGenerated,+ SpeechSpoken,SystemStateChanged,TranscriptionUpdate,VoiceSessionEnded,@@ -15,6 +16,7 @@ from jarvis.core.events import (VoiceTurnCompleted,VoiceTurnStarted,)+from jarvis.sessions.formatter import format_session_plainfrom jarvis.sessions.recorder import SessionRecorderfrom jarvis.sessions.store import SessionStore@@ -272,3 +274,109 @@ async def test_realtime_bridge_accumulates_thinking_and_speaking_segments(assert turns[0].speak_ms == 3_000finally:store.close()+++async def test_realtime_progress_bridge_survives_into_plain_export(tmp_path) -> None:+ """Every audible bridge line must precede the final reply in the export."""+ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ try:+ bus = EventBus()+ SessionRecorder(store).attach(bus)+ await bus.publish(+ VoiceSessionStarted(+ timestamp_ns=1_000_000_000,+ source_layer="speech.pipeline",+ session_id="audible-bridge",+ wake_keyword="hotkey",+ language="en",+ )+ )+ await bus.publish(+ VoiceTurnStarted(+ timestamp_ns=1_100_000_000,+ source_layer="realtime.fake-live",+ session_id="audible-bridge",+ turn_id="bridge-turn",+ turn_index=1,+ )+ )+ await bus.publish(+ TranscriptionUpdate(+ timestamp_ns=1_200_000_000,+ source_layer="realtime.fake-live",+ text="Check the current figure.",+ is_final=True,+ )+ )+ await bus.publish(+ SpeechSpoken(+ timestamp_ns=2_000_000_000,+ source_layer="realtime.fake-live",+ text="I'm still working on it.",+ language="en",+ spoken_kind="progress",+ )+ )+ await bus.publish(+ ResponseGenerated(+ timestamp_ns=3_000_000_000,+ source_layer="realtime.fake-live",+ text="The current figure is 42.",+ language="en",+ )+ )+ await bus.publish(+ SpeechSpoken(+ timestamp_ns=3_050_000_000,+ source_layer="realtime.fake-live",+ text="The current figure is 42.",+ language="en",+ spoken_kind="reply",+ )+ )+ await bus.publish(+ VoiceTurnCompleted(+ timestamp_ns=3_100_000_000,+ source_layer="realtime.fake-live",+ session_id="audible-bridge",+ turn_id="bridge-turn",+ user_text="Check the current figure.",+ user_lang="en",+ jarvis_text="The current figure is 42.",+ jarvis_lang="en",+ tier="realtime",+ provider="fake-live",+ model="live-model",+ )+ )+ await bus.publish(+ VoiceSessionEnded(+ timestamp_ns=3_200_000_000,+ source_layer="speech.pipeline",+ session_id="audible-bridge",+ hangup_reason="turn_complete",+ turn_count=1,+ )+ )++ session = store.get_session("audible-bridge")+ assert session is not None+ events = store.get_events("audible-bridge")+ spoken = [event for event in events if event.kind == "SpeechSpoken"]+ assert [event.payload["text"] for event in spoken] == [+ "I'm still working on it.",+ "The current figure is 42.",+ ]++ exported = format_session_plain(+ session,+ store.get_turns("audible-bridge"),+ events,+ )+ progress_at = exported.index("Jarvis: I'm still working on it.")+ reply_at = exported.index("Jarvis: The current figure is 42.")+ assert progress_at < reply_at+ finally:+ store.close()