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
fix(voice): synchronize transcript with device playback
rubenluetke10-beepfde51d549b66
diff --git a/jarvis/live/playback.py b/jarvis/live/playback.pynew file mode 100644index 0000000000..ea73f9a7ee--- /dev/null+++ b/jarvis/live/playback.py@@ -0,0 +1,73 @@+"""Ephemeral source-timed audio/captions for the device-owned playback clock.++These frames are not playback acknowledgements and are never persisted as such.+Transcript history keeps its existing session/segment schema.+"""++from __future__ import annotations++import logging+import math+from typing import Any, Literal++from pydantic import BaseModel, Field, ValidationError, model_validator+++def playback_frame(model: type[BaseModel], **fields: Any) -> dict | None:+ """Reject malformed metadata without logging provider text or raw audio."""+ try:+ return model(**fields).model_dump()+ except ValidationError:+ logging.getLogger(__name__).warning("Invalid voice playback metadata was discarded")+ return None+++class AudioTimedFrame(BaseModel):+ type: Literal["audio_timed"] = "audio_timed"+ epoch: int = Field(ge=0)+ audio: str = Field(max_length=1_400_000)+ sample_rate: int = Field(default=24_000, ge=8000, le=192000)+ start_ms: float = Field(ge=0, allow_inf_nan=False)+ end_ms: float = Field(ge=0, allow_inf_nan=False)++ @model_validator(mode="after")+ def ordered(self) -> AudioTimedFrame:+ if self.end_ms <= self.start_ms:+ raise ValueError("Audio interval must have positive duration")+ return self+++class SpeechTimingFrame(BaseModel):+ type: Literal["speech_timing"] = "speech_timing"+ epoch: int = Field(ge=0)+ line_id: str = Field(min_length=1, max_length=512)+ text: str = Field(max_length=128_000)+ char_start: int = Field(ge=0)+ char_end: int = Field(ge=0)+ start_ms: float = Field(ge=0, allow_inf_nan=False)+ end_ms: float = Field(ge=0, allow_inf_nan=False)++ @model_validator(mode="after")+ def ordered(self) -> SpeechTimingFrame:+ if self.end_ms <= self.start_ms or not 0 <= self.char_start < self.char_end <= utf16_length(+ self.text+ ):+ raise ValueError("Invalid speech interval")+ return self+++def utf16_length(text: str) -> int:+ """Browser offsets count UTF-16 code units, including astral characters."""+ return len(text.encode("utf-16-le")) // 2+++def source_interval(start: object, end: object) -> bool:+ return (+ isinstance(start, (int, float))+ and not isinstance(start, bool)+ and isinstance(end, (int, float))+ and not isinstance(end, bool)+ and math.isfinite(start)+ and math.isfinite(end)+ and 0 <= start < end+ )diff --git a/jarvis/live/session.py b/jarvis/live/session.pyindex 65b8882b23..d9f18ba6e6 100644--- a/jarvis/live/session.py+++ b/jarvis/live/session.py@@ -220,6 +220,10 @@ class LiveVoiceSession:self._resume_needs_input = Falseself._base_session_config: dict = {}self._using_webrtc = False+ self._playback_epoch = 0+ self._awaiting_output_clear = False+ self._last_output_audio_end = 0.0+ self._discard_audio_before = 0.0self._offer_request = ""self._offer_future: asyncio.Future | None = Noneself._past_voice_seconds = 0.0@@ -638,8 +642,11 @@ class LiveVoiceSession:self._speaking = Falseself._thinking = Falseself.playback_active = False- await self._send_json({"type": "audio_clear"})- await self._emit_indicator({"type": "tts_cancel"})+ epoch = await self._clear_playback(wait_for_provider=True)+ await self._emit_indicator({+ "type": "tts_cancel",+ **({"epoch": epoch} if self._output_transport() == "timed_pcm" else {}),+ })async def _start(self, message: dict) -> None:self._adopt_desktop_session()@@ -806,6 +813,8 @@ class LiveVoiceSession:"requires_webrtc_answer": bool(offer),"webrtc_answer_sdp": self._connection.answer_sdp,"continuous": True,+ "output_transport": self._output_transport(),+ "session_id": self.session_id,"input_muted": self._input_muted,})@@ -827,7 +836,47 @@ class LiveVoiceSession:raise asyncio.CancelledError("Voice start cancelled")if self._startup_timing is not None:self._startup_timing.mark("transport_answer")- await self._send_json({"type": "audio_transport", "webrtc_answer_sdp": answer_sdp})+ await self._send_json({+ "type": "audio_transport", "webrtc_answer_sdp": answer_sdp,+ "output_transport": self._output_transport(),+ "session_id": self.session_id,+ })++ def _output_transport(self) -> str:+ return "timed_pcm" if getattr(self._provider, "source_timed_audio", False) else "webrtc"++ async def _clear_playback(self, *, wait_for_provider: bool = False) -> int:+ self._playback_epoch += 1+ epoch = self._playback_epoch+ self._awaiting_output_clear = wait_for_provider+ self._discard_audio_before = self._last_output_audio_end+ await self._send_json({+ "type": "audio_clear",+ **({"epoch": epoch} if self._output_transport() == "timed_pcm" else {}),+ })+ return epoch++ async def _speech_timing(self, caption: Any, delta: str, start: object, end: object) -> None:+ from jarvis.live.playback import (+ SpeechTimingFrame,+ playback_frame,+ source_interval,+ utf16_length,+ )++ if (self._output_transport() != "timed_pcm" or self._awaiting_output_clear+ or not delta or not source_interval(start, end)+ or not caption.text.endswith(delta)):+ return+ frame = playback_frame(SpeechTimingFrame,+ epoch=self._playback_epoch,+ line_id=f"live:{self.session_id}:{caption.segment_id}", text=caption.text,+ char_start=utf16_length(caption.text[:-len(delta)]),+ char_end=utf16_length(caption.text),+ start_ms=self._timeline_offset + start, end_ms=self._timeline_offset + end,+ )+ if frame is not None:+ await self._send_json(frame)async def _announce_start_failure(self, exc: Exception) -> None:"""Say why the call ends instead of hanging up in silence.@@ -1080,13 +1129,57 @@ class LiveVoiceSession:})if role == "assistant" and current:+ await self._speech_timing(+ caption, delta, event.get("start_ms"), event.get("end_ms")+ )await self._note_thinking()elif kind == "session.output_audio.delta":# With WebRTC, only measured RTP playback owns the speaking# state. Sideband generation can lead playback or include silence.- if not self._connection.answer_sdp:+ from jarvis.live.playback import AudioTimedFrame, playback_frame, source_interval++ timed = source_interval(event.get("start_ms"), event.get("end_ms"))+ if timed:+ self._last_output_audio_end = max(+ self._last_output_audio_end, self._timeline_offset + event["end_ms"]+ )+ if self._awaiting_output_clear:+ return+ if self._output_transport() == "timed_pcm":+ if timed:+ start = self._timeline_offset + event["start_ms"]+ end = self._timeline_offset + event["end_ms"]+ if end <= self._discard_audio_before:+ return+ audio = event["delta"]+ if start < self._discard_audio_before:+ # A reflected packet can straddle an interruption.+ # Drop only its cancelled prefix, using source samples.+ import math++ pcm = base64.b64decode(audio)+ skip = math.ceil(+ len(pcm) // 2 * (self._discard_audio_before - start) / (end - start)+ )+ if skip * 2 >= len(pcm):+ return+ start += (end - start) * skip / (len(pcm) // 2)+ audio = base64.b64encode(pcm[skip * 2:]).decode("ascii")+ frame = playback_frame(AudioTimedFrame,+ epoch=self._playback_epoch, audio=audio,+ start_ms=start, end_ms=end,+ )+ if frame is not None:+ await self._send_json(frame)+ else:+ # Older wires can omit timing; audio must still be heard,+ # but reception must never be presented as a word position.+ await self._send_binary(base64.b64decode(event["delta"]))+ elif not self._connection.answer_sdp:await self._note_speaking()await self._send_binary(base64.b64decode(event["delta"]))+ elif kind == "output_audio_buffer.cleared":+ await self._clear_playback()elif kind in {"session.usage.updated", "session.closed"}:self._wire_seconds = max(self._wire_seconds, float(event.get("usage", {}).get("seconds", self._wire_seconds))@@ -1368,6 +1461,7 @@ class LiveVoiceSession:for task in tuple(self._control_tasks):task.cancel()await asyncio.gather(*self._control_tasks, return_exceptions=True)+ await self._clear_playback()await self._send_json({"type": "reconnecting", "attempt": self._reconnect_attempts})await self._connection.close()delay = random.uniform(0.1, min(4.0, 2**self._reconnect_attempts)) # noqa: S311@@ -1379,6 +1473,8 @@ class LiveVoiceSession:self._past_voice_seconds = self._voice_secondsself._wire_seconds = 0.0self._wire_epoch += 1+ self._last_output_audio_end = 0.0+ self._discard_audio_before = 0.0self._captions = {"user": "", "assistant": ""}self._resampler.reset()await self._open_replacement(history)@@ -1423,6 +1519,7 @@ class LiveVoiceSession:self._recovering = Trueattempt += 1await self._publish_phase("connecting")+ await self._clear_playback()await self._send_json({"type": "reconnecting", "attempt": attempt})delay = random.uniform(0.5, min(30.0, 2 ** min(attempt, 5))) # noqa: S311await asyncio.sleep(delay)@@ -1454,6 +1551,8 @@ class LiveVoiceSession:"model": self._active_model, "language": self._language,"output_sample_rate": 24000, "input_sample_rate": 24000,"continuous": True, "reconnected": True, "reuse_webrtc": True,+ "output_transport": self._output_transport(),+ "session_id": self.session_id,"input_muted": self._input_muted,})return True@@ -1505,6 +1604,8 @@ class LiveVoiceSession:"webrtc_answer_sdp": self._connection.answer_sdp,"continuous": True,"reconnected": True,+ "output_transport": self._output_transport(),+ "session_id": self.session_id,})diff --git a/jarvis/live/subscription.py b/jarvis/live/subscription.pyindex 28b50e604d..600b947b65 100644--- a/jarvis/live/subscription.py+++ b/jarvis/live/subscription.py@@ -178,6 +178,7 @@ class SubscriptionLiveVoiceSession(LiveVoiceSession):)returnif kind == "output_audio_buffer.cleared":+ await self._clear_playback()# Match native voice: a report the user interrupted was heard.self._report_finished(delivered=True)self._notify_pause()@@ -259,7 +260,17 @@ class SubscriptionLiveVoiceSession(LiveVoiceSession):"end_ms": end,})+ if role == "assistant" and event.get("timestamp_source") == "source_audio":+ await self._speech_timing(+ caption, str(event.get("delta") or ""),+ event.get("fragment_start_ms"), event.get("fragment_end_ms"),+ )if event.get("is_final"):+ if role == "assistant" and self._awaiting_output_clear:+ # Subscription transports also signal cancellation by ending+ # the old turn. Do not wait forever for an optional clear event.+ self._last_output_audio_end = max(self._last_output_audio_end, end)+ await self._clear_playback()self._transcript.finish(role)self._notify_pause()diff --git a/jarvis/plugins/realtime/openai_live.py b/jarvis/plugins/realtime/openai_live.pyindex d7ae4dffab..e2e95bc38c 100644--- a/jarvis/plugins/realtime/openai_live.py+++ b/jarvis/plugins/realtime/openai_live.py@@ -39,6 +39,7 @@ class OpenAILiveProvider:supports_realtime = Truecontinuous_conversation = Truebrowser_audio = True+ source_timed_audio = Truerequires_webrtc_offer = Truehandshake_budget_s = 60.0implicit_usage_fallback_allowed = Falsediff --git a/jarvis/plugins/realtime/openai_subscription_live.py b/jarvis/plugins/realtime/openai_subscription_live.pyindex cceb7eb257..e271cabe21 100644--- a/jarvis/plugins/realtime/openai_subscription_live.py+++ b/jarvis/plugins/realtime/openai_subscription_live.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import mathimport randomimport reimport time@@ -182,7 +183,7 @@ def _session_config(session: dict) -> dict:class OpenAISubscriptionLiveConnection:- """One private control socket; RTP audio belongs solely to the browser."""+ """One subscription sideband with timed audio and host-owned controls."""requires_close_ack = Falseusage_billed = False@@ -230,12 +231,18 @@ class OpenAISubscriptionLiveConnection:text = payload.get("transcript" if done else "text", "")if not isinstance(text, str):raise SubscriptionLiveError("invalid_response")+ timing = payload if done else event+ start, end = timing.get("start_ms"), timing.get("end_ms")+ timed = (+ type(start) in (int, float) and type(end) in (int, float)+ and math.isfinite(start) and math.isfinite(end) and 0 <= start < end+ )turn = self._turns.setdefault(role,{"id": str(uuid4()),"text": "",- "start_ms": now,+ "start_ms": start if timed else now,},)turn["text"] = text if done else turn["text"] + text@@ -253,8 +260,9 @@ class OpenAISubscriptionLiveConnection:"snapshot": True,"is_final": done,"start_ms": turn["start_ms"],- "end_ms": now,- "timestamp_source": "local_receive_clock",+ "end_ms": end if timed else now,+ "timestamp_source": "source_audio" if timed else "local_receive_clock",+ **({"fragment_start_ms": start, "fragment_end_ms": end} if timed else {}),}if done:del self._turns[role]@@ -264,6 +272,16 @@ class OpenAISubscriptionLiveConnection:if self._already_seen(event):return {"type": "subscription.ignored"}kind = event.get("type")+ if kind in {"session.output_audio.delta", "output_audio.delta"}:+ audio = event.get("delta" if kind.startswith("session.") else "audio")+ if not isinstance(audio, str) or len(audio) > _MAX_FRAME_BYTES:+ raise SubscriptionLiveError("invalid_response")+ # Playback is explicitly negotiated as PCM by the host. RTP is+ # still the input transport but must not also drive the speaker.+ return {+ "type": "session.output_audio.delta", "delta": audio,+ "start_ms": event.get("start_ms"), "end_ms": event.get("end_ms"),+ }if kind in {"input_transcript.added", "output_transcript.added"}:return self._transcript(event,@@ -341,7 +359,6 @@ class OpenAISubscriptionLiveConnection:"message": str(SubscriptionLiveError(code)),},}- # In particular, never mirror output_audio.delta onto browser playback.return {"type": "subscription.ignored"}async def receive(self) -> dict:@@ -434,6 +451,7 @@ class OpenAISubscriptionLiveProvider:"""Additive subscription adapter; never searches for or falls back to a key."""name = "openai-live-subscription"+ source_timed_audio = Truecredential_family = "openai-codex"credential_candidates: tuple = ()supports_realtime = Truediff --git a/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsxindex 94812761f2..468fc701f2 100644--- a/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx+++ b/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx@@ -19,42 +19,10 @@ import { TurnSteps, traceWorthShowing } from "@/components/home/TurnSteps";import { traceModel } from "@/lib/thinkingSteps";/**- * The voice stage — the front page's chat, spoken (2026-10-01, after the- * Claude app's voice mode).- *- * It looks like the chat it lives in, not like a separate page: the same- * column, your words in soft bubbles on the right (italic, because they were- * heard rather than typed), the answers as plain text on the left, and at- * the bottom a composer-shaped card (components/home/VoiceComposer) that- * says what is happening and carries Start / Stop. Behind it a soft light- * rises from the bottom edge and breathes with the voices- * (components/home/VoiceGlow) — and keeps moving while the assistant- * thinks, so a silent turn never looks dead; while it thinks or speaks, the- * user's pet thinks or talks under the last line. While the answer is being spoken, the- * words not yet said stay grey and light up as the voice reaches them- * (components/home/useSpokenCursor — an estimate from the playback level,- * since no voice path reports a per-word position). `onExit`, where the host page has a typed- * half, puts the way back to the keyboard into the composer.- *- * Empty, it is one centred column: the greeting and the voice composer.- * Once anything has been said the page becomes a document: the whole- * conversation scrolls in its own viewport and the composer docks to the- * bottom. WHOLE, not a window onto the- * last few turns — until 2026-08-24 the lane rendered only the last 8 lines,- * so anything that scrolled off was gone from the DOM and could not be- * scrolled back to. The lane reads the home store's transcript- * (lib/homeTranscript: heard words, the turn's reasoning steps, spoken- * answers and typed turns merged into one list) plus the live, not-yet-final- * transcription, so what you are saying appears while you say it. A turn's- * steps render between your words and the answer — live while the turn runs,- * folded afterwards (components/home/TurnSteps).- *- * Scrolling follows the Claude app, through the rule every conversation- * surface here shares (hooks/useStickToBottom): new output pulls the view- * along ONLY while the view is already at the end; scrolled up to read- * something, you keep your place while the conversation goes on below, and a- * button over the bar takes you back. Nothing yanks the page out from under- * someone mid-sentence.+ * The live voice conversation shares the chat column and scroll behavior.+ * Speaker captions and tool steps remain visible for the whole conversation.+ * Players that report word boundaries can highlight their current position;+ * unaligned streams render ordinary text without pretending to know it.*/export function VoiceStage({ onExit }: { onExit?: () => void } = {}) {const t = useT();@@ -90,16 +58,11 @@ export function VoiceStage({ onExit }: { onExit?: () => void } = {}) {const hasLines = lines.length > 0 || Boolean(liveLine) || Boolean(liveAnswer);// The answer the voice is saying right now: the growing snapshot, or —// once its final line has landed while the audio still plays — that line.- const speaking = active && voiceState === "speaking";const lastIsAnswer = !liveAnswer && lastLine?.who === "assistant";// A live work trace already shows the pet on its live line — also while// the answer streams in under it — so a second pet below would say the// same thing twice.const traceShowsPet = lines.some((m) => m.who === "steps" && m.live);- const spoken = useSpokenCursor(- liveAnswer || (lastIsAnswer ? lastLine.text : ""),- speaking,- );const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();useLayoutEffect(follow, [follow, lines, liveLine, liveAnswer]);@@ -152,14 +115,15 @@ export function VoiceStage({ onExit }: { onExit?: () => void } = {}) {key={m.id}who={m.who === "user" ? t("home.transcript_you") : assistantName}text={m.text}+ lineId={m.id}user={m.who === "user"}- spoken={lastIsAnswer && i === lines.length - 1 ? spoken : null}+ playbackEligible={active && lastIsAnswer && i === lines.length - 1}/>),)}{liveLine && <TranscriptLine who={t("home.transcript_you")} text={liveLine} user live />}{liveAnswer && (- <TranscriptLine who={assistantName} text={liveAnswer} user={false} live spoken={spoken} />+ <TranscriptLine who={assistantName} text={liveAnswer} user={false} live playbackEligible={active} />)}{active && (voiceState === "thinking" || voiceState === "speaking") && !traceShowsPet && (<div className="pl-0.5" data-testid="voice-turn-indicator" aria-hidden>@@ -188,19 +152,22 @@ export function VoiceStage({ onExit }: { onExit?: () => void } = {}) {* the rest grey. The speaker's name stays for screen readers only — the side* says who spoke.*/-function TranscriptLine({+export function TranscriptLine({who,text,user,live = false,- spoken = null,+ playbackEligible = false,+ lineId = "",}: {who: string;text: string;user: boolean;live?: boolean;- spoken?: number | null;+ playbackEligible?: boolean;+ lineId?: string;}) {+ const spoken = useSpokenCursor(text, !user && playbackEligible, lineId);const reading = !user && spoken !== null;return (<div@@ -219,7 +186,7 @@ function TranscriptLine({{reading ? (<><span data-testid="spoken-part">{text.slice(0, spoken)}</span>- <span className="text-muted-foreground transition-colors" data-testid="unspoken-part">+ <span className="text-muted-foreground" data-testid="unspoken-part">{text.slice(spoken)}</span></>diff --git a/jarvis/ui/web/frontend/src/components/home/speechPlayback.test.tsx b/jarvis/ui/web/frontend/src/components/home/speechPlayback.test.tsxnew file mode 100644index 0000000000..ab80bf5ac2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/home/speechPlayback.test.tsx@@ -0,0 +1,109 @@+import { act, cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { TranscriptLine } from "./VoiceStage";+import { BrowserSpeechFallback } from "@/lib/realtimeAudio";+import { clearSpeechPlayback, readSpeechPlayback } from "@/lib/speechPlayback";++afterEach(() => {+ cleanup();+ clearSpeechPlayback();+ vi.useRealTimers();+});++function player() {+ const utterances: SpeechSynthesisUtterance[] = [];+ const synthesis = {+ cancel: () => undefined,+ speak: (utterance: SpeechSynthesisUtterance) => { utterances.push(utterance); },+ };+ const create = (text: string) => ({ text, volume: 1 }) as SpeechSynthesisUtterance;+ return { controller: new BrowserSpeechFallback(synthesis, create), utterances };+}++function boundary(utterance: SpeechSynthesisUtterance, charIndex: number, name = "word") {+ utterance.onboundary?.({ charIndex, name } as SpeechSynthesisEvent);+}++const event = new Event("speech") as SpeechSynthesisEvent;+const text = "Ready when you are.";++describe("speech engine to visible transcript", () => {+ it("uses playback boundaries, independently of elapsed time and speech rate", () => {+ vi.useFakeTimers();+ const { controller, utterances } = player();+ controller.speak(text, "en", 1, { onFinish: () => undefined });+ render(<TranscriptLine who="Assistant" text={text} user={false} playbackEligible />);+ const utterance = utterances[0];+ expect(screen.getByTestId("spoken-part").textContent).toBe("");+ act(() => vi.advanceTimersByTime(20_000));+ expect(screen.getByTestId("spoken-part").textContent).toBe("");+ act(() => utterance.onstart?.(event));+ act(() => boundary(utterance, 0));+ expect(screen.getByTestId("spoken-part").textContent).toBe("Ready");+ act(() => boundary(utterance, 6));+ expect(screen.getByTestId("spoken-part").textContent).toBe("Ready when");+ act(() => utterance.onpause?.(event));+ act(() => vi.advanceTimersByTime(90_000));+ act(() => boundary(utterance, 11));+ expect(screen.getByTestId("spoken-part").textContent).toBe("Ready when");+ act(() => utterance.onresume?.(event));+ act(() => boundary(utterance, 11));+ expect(screen.getByTestId("spoken-part").textContent).toBe("Ready when you");+ act(() => utterance.onend?.(event));+ expect(screen.getByTestId("spoken-part").textContent).toBe(text);+ expect(screen.getByTestId("unspoken-part").textContent).toBe("");+ });++ it.each(["cancel", "error"])("keeps the unheard tail grey after %s, including stale callbacks", (reason) => {+ const { controller, utterances } = player();+ controller.speak(text, "en", 1, { onFinish: () => undefined });+ const view = render(<TranscriptLine who="Assistant" text={text} user={false} playbackEligible />);+ const utterance = utterances[0];+ act(() => utterance.onstart?.(event));+ act(() => boundary(utterance, 0));+ act(() => {+ if (reason === "cancel") controller.cancel();+ else utterance.onerror?.(event as SpeechSynthesisErrorEvent);+ });+ view.rerender(<TranscriptLine who="Assistant" text={text} user={false} />);+ act(() => {+ boundary(utterance, 15);+ utterance.onend?.(event);+ utterance.onstart?.(event);+ });+ expect(screen.getByTestId("spoken-part").textContent).toBe("Ready");+ expect(screen.getByTestId("unspoken-part").textContent).toBe(" when you are.");+ });++ it("never claims silent output was heard", () => {+ const { controller, utterances } = player();+ controller.speak(text, "en", 0, { onFinish: () => undefined });+ render(<TranscriptLine who="Assistant" text={text} user={false} playbackEligible />);+ act(() => {+ utterances[0].onstart?.(event);+ boundary(utterances[0], 15);+ utterances[0].onend?.(event);+ });+ expect(screen.getByTestId("spoken-part").textContent).toBe("");+ expect(readSpeechPlayback()?.state).toBe("cancelled");+ });++ it("ignores non-word, invalid and out-of-order boundaries", () => {+ const { controller, utterances } = player();+ controller.speak(text, "en", 1, { onFinish: () => undefined });+ render(<TranscriptLine who="Assistant" text={text} user={false} playbackEligible />);+ act(() => {+ boundary(utterances[0], 6); // Not playing yet.+ utterances[0].onstart?.(event);+ boundary(utterances[0], 11, "sentence");+ boundary(utterances[0], NaN);+ });+ expect(screen.getByTestId("spoken-part").textContent).toBe("");+ act(() => {+ boundary(utterances[0], 6);+ boundary(utterances[0], 0);+ });+ expect(screen.getByTestId("spoken-part").textContent).toBe("Ready when");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.test.ts b/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.test.tsindex 4460fd7b6a..77526db434 100644--- a/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.test.ts+++ b/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.test.ts@@ -1,57 +1,100 @@import { act, renderHook } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";-import { CHARS_PER_SECOND, useSpokenCursor, wordEnd } from "@/components/home/useSpokenCursor";+import { useSpokenCursor } from "@/components/home/useSpokenCursor";+import { beginSpeechPlayback, clearSpeechPlayback, publishTimedSpeechPlayback, setTimedSpeechSession, updateSpeechPlayback } from "@/lib/speechPlayback";import { voiceOutputLevelRef } from "@/lib/voiceOutputLevel";afterEach(() => {- vi.useRealTimers();+ clearSpeechPlayback();+ setTimedSpeechSession("");voiceOutputLevelRef.current = null;+ vi.useRealTimers();});-describe("wordEnd", () => {- it("lights a word up whole, never half-way", () => {- expect(wordEnd("Morgen ist Freitag", 0)).toBe(0);- expect(wordEnd("Morgen ist Freitag", 2)).toBe(6);- expect(wordEnd("Morgen ist Freitag", 7.4)).toBe(10);- expect(wordEnd("Morgen ist Freitag", 12)).toBe(18);- expect(wordEnd("Morgen ist Freitag", 99)).toBe(18);+describe("playback-confirmed spoken cursor", () => {+ it("keeps a new bus caption grey before the audio socket's metadata arrives", () => {+ setTimedSpeechSession("current");+ const { result } = renderHook(() => useSpokenCursor("New caption", true, "live:current:new"));+ const old = renderHook(() => useSpokenCursor("Old caption", true, "live:previous:old"));+ expect(result.current).toBe(0);+ expect(old.result.current).toBeNull();+ act(() => publishTimedSpeechPlayback("live:current:new", "New caption", 3));+ expect(result.current).toBe(3);});-});--describe("useSpokenCursor", () => {- it("draws the text plainly while nothing is being spoken", () => {- const { result } = renderHook(() => useSpokenCursor("Hallo Ruben", false));+ it("does not invent progress from time, levels or the speaking state", () => {+ vi.useFakeTimers();+ voiceOutputLevelRef.current = 1;+ const { result } = renderHook(() => useSpokenCursor("A generated answer", true));+ act(() => vi.advanceTimersByTime(60_000));expect(result.current).toBeNull();});- it("moves while audio plays and waits while it is silent", () => {- vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"] });- const text = "Morgen ist Freitag, der zweite Oktober. Hast du was Besonderes vor?";- voiceOutputLevelRef.current = 0.5;- const { result } = renderHook(() => useSpokenCursor(text, true));+ it("follows actual boundaries at any rate and remains still during pauses", () => {+ vi.useFakeTimers();+ const text = "One two three four";+ const id = beginSpeechPlayback(text);+ const { result, rerender } = renderHook(({ active }) => useSpokenCursor(text, active), {+ initialProps: { active: true },+ });expect(result.current).toBe(0);+ act(() => vi.advanceTimersByTime(20_000));+ expect(result.current).toBe(0);+ act(() => updateSpeechPlayback(id, "playing", 3));+ expect(result.current).toBe(3);+ act(() => updateSpeechPlayback(id, "playing", 7));+ expect(result.current).toBe(7);+ act(() => updateSpeechPlayback(id, "paused"));+ rerender({ active: false });+ act(() => vi.advanceTimersByTime(60_000));+ expect(result.current).toBe(7);+ act(() => updateSpeechPlayback(id, "playing", 13));+ expect(result.current).toBe(13);+ act(() => updateSpeechPlayback(id, "ended", text.length));+ expect(result.current).toBe(text.length);+ });- act(() => vi.advanceTimersByTime(1000));- const afterOneSecond = result.current ?? 0;- expect(afterOneSecond).toBeGreaterThan(CHARS_PER_SECOND / 2);- expect(afterOneSecond).toBeLessThan(text.length);+ it("does not mark an unheard tail as spoken on cancellation or a status change", () => {+ const text = "Heard then cancelled";+ const id = beginSpeechPlayback(text);+ const { result, rerender } = renderHook(({ active }) => useSpokenCursor(text, active), {+ initialProps: { active: true },+ });+ act(() => updateSpeechPlayback(id, "playing", 5));+ act(() => updateSpeechPlayback(id, "cancelled"));+ rerender({ active: false });+ act(() => updateSpeechPlayback(id, "ended", text.length));+ expect(result.current).toBe(5);+ act(() => beginSpeechPlayback("A new reply"));+ expect(result.current).toBe(5);+ });- voiceOutputLevelRef.current = 0;- act(() => vi.advanceTimersByTime(1000));- const paused = result.current ?? 0;- act(() => vi.advanceTimersByTime(1000));- expect(result.current).toBe(paused);+ it("does not give a repeated reply the previous reply's position", () => {+ const text = "The same answer";+ const first = beginSpeechPlayback(text);+ const oldLine = renderHook(({ eligible }) => useSpokenCursor(text, eligible), {+ initialProps: { eligible: true },+ });+ act(() => updateSpeechPlayback(first, "playing", 8));+ act(() => updateSpeechPlayback(first, "cancelled"));+ oldLine.rerender({ eligible: false });+ let second = 0;+ act(() => { second = beginSpeechPlayback(text); });+ const newLine = renderHook(() => useSpokenCursor(text, true));+ expect(newLine.result.current).toBe(0);+ act(() => updateSpeechPlayback(first, "ended", text.length));+ act(() => updateSpeechPlayback(second, "playing", 3));+ expect(newLine.result.current).toBe(3);+ expect(oldLine.result.current).toBe(8);});- it("starts a new answer from its beginning", () => {- vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"] });+ it("invalidates positions when the transcript is corrected", () => {+ const first = beginSpeechPlayback("Original text");const { result, rerender } = renderHook(({ text }) => useSpokenCursor(text, true), {- initialProps: { text: "Erste Antwort mit ein paar Worten" },+ initialProps: { text: "Original text" },});- act(() => vi.advanceTimersByTime(1000));- expect(result.current).toBeGreaterThan(0);- rerender({ text: "Ganz andere Antwort" });- expect(result.current).toBeLessThanOrEqual("Ganz".length);+ act(() => updateSpeechPlayback(first, "playing", 8));+ rerender({ text: "Corrected text" });+ expect(result.current).toBeNull();});});diff --git a/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.ts b/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.tsindex 6a95d09f6f..da009849ae 100644--- a/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.ts+++ b/jarvis/ui/web/frontend/src/components/home/useSpokenCursor.ts@@ -1,82 +1,30 @@-import { useEffect, useRef, useState } from "react";+import { useRef, useSyncExternalStore } from "react";-import { voiceOutputLevelRef } from "@/lib/voiceOutputLevel";+import { readSpeechPlayback, readTimedSpeechPlayback, readTimedSpeechSession, subscribeSpeechPlayback } from "@/lib/speechPlayback";/**- * How far into the current answer the voice has got — the Claude app's- * "words not yet spoken are grey" effect for voice mode.- *- * No voice path reports a playback position per word, so this is an- * estimate made where the sound is: while the assistant is speaking and the- * playback level says audio is actually coming out, the cursor moves at a- * steady speaking rate; in a pause between sentences it waits. A surface- * that cannot observe its playback level (`voiceOutputLevelRef` is null)- * counts the whole speaking state as audible. The cursor snaps to word ends- * so a word never lights up half-way, and the moment the assistant stops- * speaking the whole answer is shown as spoken — a guess is never left- * hanging greyed out.- *- * Returns the number of leading characters of `text` to draw as spoken, or- * null while nothing is being spoken (draw the text plainly).+ * Read positions confirmed by the player. A level is not a word position, and+ * neither elapsed wall time nor a transcript final proves audio was heard.+ * Unsupported players render ordinary text instead of a fabricated cursor.+ * Keep a bound line's position through pauses, cancellation and later replies.*/-export function useSpokenCursor(text: string, speaking: boolean): number | null {- // The count is kept with the text it was measured on, so a new answer- // never borrows the last one's position for a frame.- const [shown, setShown] = useState({ text: "", chars: 0 });- const charsRef = useRef(0);- const textRef = useRef("");- const lastAudibleRef = useRef(0);-- // A new answer starts from the beginning; the same answer growing (more- // snapshot words arriving) keeps its place.- if (text !== textRef.current) {- if (!text.startsWith(textRef.current) || !textRef.current) charsRef.current = 0;- textRef.current = text;+export function useSpokenCursor(text: string, eligible: boolean, lineId = ""): number | null {+ const playback = useSyncExternalStore(subscribeSpeechPlayback, readSpeechPlayback);+ const timed = useSyncExternalStore(subscribeSpeechPlayback, () => readTimedSpeechPlayback(lineId));+ const session = useSyncExternalStore(subscribeSpeechPlayback, readTimedSpeechSession);+ const bound = useRef<{ id: number; text: string; chars: number } | null>(null);+ if (bound.current && bound.current.text !== text) bound.current = null;+ if (timed?.text === text) bound.current = { id: -1, text, chars: timed.chars };+ else if (!bound.current && eligible && session && lineId.startsWith(`live:${session}:`)) {+ // The bus caption and audio-control socket can arrive in either order.+ // A fresh caption stays grey until its playback metadata catches up.+ bound.current = { id: -1, text, chars: 0 };}-- useEffect(() => {- if (!speaking || !text || typeof requestAnimationFrame === "undefined") return;- let frame = 0;- let last = performance.now();- const tick = (now: number) => {- const dt = Math.min(0.1, (now - last) / 1000);- last = now;- const level = voiceOutputLevelRef.current;- if (level === null || level > AUDIBLE_LEVEL) lastAudibleRef.current = now;- // A word's own dips are not a pause: keep moving for a beat after- // the last audible frame.- if (now - lastAudibleRef.current < AUDIBLE_HOLD_MS) {- charsRef.current = Math.min(textRef.current.length, charsRef.current + dt * CHARS_PER_SECOND);- }- const current = textRef.current;- const next = wordEnd(current, charsRef.current);- setShown((prev) =>- prev.text === current && prev.chars === next ? prev : { text: current, chars: next },- );- frame = requestAnimationFrame(tick);- };- frame = requestAnimationFrame(tick);- return () => cancelAnimationFrame(frame);- }, [speaking, text]);-- if (!speaking || !text) return null;- return shown.text === text ? shown.chars : wordEnd(text, charsRef.current);-}--/** A calm speaking voice: roughly 160 words a minute. */-export const CHARS_PER_SECOND = 15;-/** Playback level above which audio counts as audible. */-const AUDIBLE_LEVEL = 0.015;-const AUDIBLE_HOLD_MS = 300;--/**- * The end of the word the cursor is in, so a word lights up whole. A cursor- * at 0 stays at 0 — nothing has been said yet.- */-export function wordEnd(text: string, chars: number): number {- const at = Math.floor(chars);- if (at <= 0) return 0;- if (at >= text.length) return text.length;- const space = text.slice(at).search(/\s/);- return space === -1 ? text.length : at + space;+ if (playback?.text === text && (+ playback.id === bound.current?.id ||+ (eligible && playback.state !== "ended" && playback.state !== "cancelled")+ )) {+ bound.current = { id: playback.id, text, chars: playback.chars };+ }+ return timed?.text === text ? timed.chars : bound.current?.chars ?? null;}diff --git a/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts b/jarvis/ui/web/frontend/src/lib/pcm-worklet.tsindex 48276aadcd..b36f23f87b 100644--- a/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts+++ b/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts@@ -4,12 +4,14 @@// to it (isolatedModules requires every file to be a module or a script; as a// script these ambient declarations would otherwise leak into the rest of the// app's type-check).-import { JitterBufferedPcm16Queue, Pcm16Packetizer } from "./pcmWorkletBuffer";+import { Pcm16Packetizer } from "./pcmWorkletBuffer";+import { TimedPcmQueue, type RenderedAudioInterval } from "./playbackTimeline";import { StartupAudioQueue } from "./startupAudio";export {};declare const sampleRate: number;+declare const currentTime: number;declare function registerProcessor(name: string, ctor: unknown): void;declare class AudioWorkletProcessor {readonly port: MessagePort;@@ -84,7 +86,9 @@ class StartupCapture extends AudioWorkletProcessor {registerProcessor("pcm-startup", StartupCapture);class PcmPlayback extends AudioWorkletProcessor {- private readonly queue = new JitterBufferedPcm16Queue(sampleRate);+ private readonly queue = new TimedPcmQueue(sampleRate);+ private spans: RenderedAudioInterval[] = [];+ private generation = 0;private levelSum = 0;private levelCount = 0;private muted = true;@@ -93,18 +97,27 @@ class PcmPlayback extends AudioWorkletProcessor {constructor() {super();this.port.onmessage = (e: MessageEvent) => {- const msg = e.data as { type: string; data?: ArrayBuffer; muted?: boolean; volume?: number };+ const msg = e.data as {+ type: string; data?: ArrayBuffer; muted?: boolean; volume?: number;+ generation?: number; startMs?: number; endMs?: number;+ };if (msg.type === "output_state") {const muted = msg.muted === true;- if (muted !== this.muted) this.queue.clear();+ if (muted !== this.muted) { this.queue.clear(); this.spans = []; }+ if (msg.generation !== undefined) this.generation = msg.generation;this.muted = muted;this.volume = msg.volume ?? 1;- } else if (msg.type === "flush") this.queue.clear();+ } else if (msg.type === "flush") {+ this.queue.clear();+ this.spans = [];+ this.generation = msg.generation ?? this.generation + 1;+ }else if (msg.type === "pcm" && msg.data && !this.muted) {// The bounded ring keeps the newest audio if a provider outruns// playback for more than ten seconds. enqueue() drops the oldest// samples on overrun, preventing stale latency and unbounded memory.- this.queue.enqueue(new Int16Array(msg.data));+ this.queue.enqueue(new Int16Array(msg.data), msg.startMs !== undefined && msg.endMs !== undefined+ ? { startMs: msg.startMs, endMs: msg.endMs } : undefined);}};}@@ -115,7 +128,8 @@ class PcmPlayback extends AudioWorkletProcessor {// Banks a jitter reserve at a burst start and after an underrun, then// streams at wall clock. Zero-filling a starved quantum instead is what// chopped the voice on this surface.- this.queue.render(out);+ const rendered = this.queue.render(out, currentTime);+ if (!this.muted && this.volume > 0) this.spans.push(...rendered);for (let i = 0; i < out.length; i++) out[i] *= this.muted ? 0 : this.volume;// Throttled (~30 Hz) OUTPUT-level messages, the mirror of PcmCapture's.// Measured on the samples this processor just wrote, so the number is the@@ -130,6 +144,8 @@ class PcmPlayback extends AudioWorkletProcessor {if (this.levelCount >= sampleRate / 30) {const rms = Math.sqrt(this.levelSum / this.levelCount);this.port.postMessage({ type: "level", rms });+ this.port.postMessage({ type: "playback", generation: this.generation, spans: this.spans });+ this.spans = [];this.levelSum = 0;this.levelCount = 0;}diff --git a/jarvis/ui/web/frontend/src/lib/playbackTimeline.test.ts b/jarvis/ui/web/frontend/src/lib/playbackTimeline.test.tsnew file mode 100644index 0000000000..bf68011709--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/playbackTimeline.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from "vitest";+import { audibleContextTime, DevicePlaybackTimeline, TimedPcmQueue } from "./playbackTimeline";+import { TimedSpeechTracker, type TimedText } from "./timedSpeech";+import { TimedAudioFrame, TimedTextFrame } from "./timedSpeech";+import { readFileSync } from "node:fs";+import path from "node:path";+import { readTimedSpeechPlayback } from "./speechPlayback";++function cue(id: string, text: string, start: number, end: number, charStart = 0): TimedText {+ return { type: "speech_timing", epoch: 0, line_id: id, text,+ char_start: charStart, char_end: text.length, start_ms: start, end_ms: end };+}++describe("source audio to device to transcript", () => {+ it("accepts the Python wire fixture without changing values", () => {+ const [audio, text] = JSON.parse(readFileSync(path.resolve(+ process.cwd(), "../../../../tests/fixtures/voice_playback_contract.json",+ ), "utf8"));+ expect(TimedAudioFrame.parse(audio)).toEqual(audio);+ expect(TimedTextFrame.parse(text)).toEqual(text);+ });+ it.each([16_000, 24_000, 44_100, 48_000])("uses rendered frames at %i Hz and waits for hardware latency", rate => {+ const queue = new TimedPcmQueue(rate);+ const device = new DevicePlaybackTimeline();+ const text = new TimedSpeechTracker();+ const id = `rate-${rate}`;+ text.text(cue(id, "First second", 1000, 2000));+ queue.enqueue(new Int16Array(rate).fill(1000), { startMs: 1000, endMs: 2000 });+ expect(readTimedSpeechPlayback(id)?.chars).toBe(0); // All audio received, none played.+ device.rendered(queue.render(new Float32Array(rate / 2), 5));+ text.played(device.advance(4.99));+ expect(readTimedSpeechPlayback(id)?.chars).toBe(0); // Rendered ahead of the DAC.+ text.played(device.advance(5.05));+ expect(readTimedSpeechPlayback(id)?.chars).toBe(5);+ device.rendered(queue.render(new Float32Array(rate / 2), 5.5));+ text.played(device.advance(6));+ expect(readTimedSpeechPlayback(id)?.chars).toBe(12);+ });++ it.each([200, 600, 1800])("follows a %i ms spoken fragment without a fixed speech rate", duration => {+ const tracker = new TimedSpeechTracker();+ const id = `speed-${duration}`;+ tracker.text(cue(id, "One two", 0, duration));+ tracker.played([{ startMs: 0, endMs: duration / 4 }]);+ expect(readTimedSpeechPlayback(id)?.chars).toBe(3);+ tracker.played([{ startMs: duration / 4, endMs: duration }]);+ expect(readTimedSpeechPlayback(id)?.chars).toBe(7);+ });++ it("does not consume source time while priming, underrunning or waiting between sentences", () => {+ const queue = new TimedPcmQueue(1000);+ queue.enqueue(new Int16Array(50), { startMs: 1000, endMs: 1050 });+ expect(queue.render(new Float32Array(100), 0)).toEqual([]);+ expect(queue.render(new Float32Array(100), 0.1)).toEqual([]);+ expect(queue.render(new Float32Array(100), 0.2)).toEqual([]);+ const played = queue.render(new Float32Array(100), 0.3);+ expect(played[0]).toMatchObject({ startMs: 1000, endMs: 1050, contextEnd: 0.35 });+ expect(queue.render(new Float32Array(100), 30)).toEqual([]);+ queue.enqueue(new Int16Array(200), { startMs: 5000, endMs: 5200 });+ expect(queue.render(new Float32Array(100), 31)[0].startMs).toBe(5000);+ });++ it("freezes in an embedded pause and catches up when a caption arrives late", () => {+ const tracker = new TimedSpeechTracker();+ tracker.text(cue("pause", "One", 0, 200));+ tracker.text(cue("pause", "One two", 1200, 1400, 3));+ tracker.played([{ startMs: 0, endMs: 1000 }]);+ expect(readTimedSpeechPlayback("pause")?.chars).toBe(3);+ tracker.played([{ startMs: 1000, endMs: 1400 }]);+ expect(readTimedSpeechPlayback("pause")?.chars).toBe(7);+ tracker.text(cue("late", "Already heard", 100, 300));+ expect(readTimedSpeechPlayback("late")?.chars).toBe(13);+ });++ it("does not turn an interrupted or dropped tail white", () => {+ const tracker = new TimedSpeechTracker();+ const device = new DevicePlaybackTimeline();+ tracker.text(cue("cut", "First second", 0, 1000));+ device.rendered([{ startMs: 0, endMs: 1000, contextStart: 5, contextEnd: 6 }]);+ tracker.played(device.advance(5.1));+ tracker.clear();+ device.clear();+ tracker.played(device.advance(600));+ expect(readTimedSpeechPlayback("cut")?.chars).toBe(5);+ const queue = new TimedPcmQueue(1000);+ queue.enqueue(new Int16Array(12_000), { startMs: 0, endMs: 12_000 });+ expect(queue.render(new Float32Array(1000), 0)[0].startMs).toBe(2000);+ const dropped = new TimedSpeechTracker();+ dropped.text(cue("dropped", "Not heard", 0, 1000));+ dropped.played([{ startMs: 2000, endMs: 3000 }]);+ expect(readTimedSpeechPlayback("dropped")?.chars).toBe(0);+ });++ it("uses the device timestamp, and measured latency only on older engines", () => {+ const context = { currentTime: 5, baseLatency: 0.01, outputLatency: 0.2,+ getOutputTimestamp: () => ({ contextTime: 4.75, performanceTime: 100 }) };+ expect(audibleContextTime(context as AudioContext)).toBe(4.75);+ context.getOutputTimestamp = () => ({ contextTime: 0, performanceTime: 0 });+ expect(audibleContextTime(context as AudioContext)).toBe(0);+ expect(audibleContextTime({ ...context, getOutputTimestamp: undefined } as unknown as AudioContext)).toBe(4.79);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/playbackTimeline.ts b/jarvis/ui/web/frontend/src/lib/playbackTimeline.tsnew file mode 100644index 0000000000..31ea3fc324--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/playbackTimeline.ts@@ -0,0 +1,107 @@+import { JitterBufferedPcm16Queue } from "./pcmWorkletBuffer";++/** Source time is preserved across buffering, resampling and device playout. */+export type AudioInterval = { startMs: number; endMs: number };+export type RenderedAudioInterval = AudioInterval & { contextStart: number; contextEnd: number };+type QueuedInterval = { frames: number; consumed: number; timing?: AudioInterval };++export function validAudioInterval(start: unknown, end: unknown): boolean {+ return typeof start === "number" && typeof end === "number" &&+ Number.isFinite(start) && Number.isFinite(end) && start >= 0 && end > start;+}++/** Shares the audio ring's exact dequeue/drop decisions; silence is not progress. */+export class TimedPcmQueue {+ private readonly audio: JitterBufferedPcm16Queue;+ private spans: QueuedInterval[] = [];++ constructor(private readonly rate: number) { this.audio = new JitterBufferedPcm16Queue(rate); }++ clear(): void { this.audio.clear(); this.spans = []; }++ enqueue(samples: Int16Array, timing?: AudioInterval): void {+ if (!samples.length) return;+ this.spans.push({ frames: samples.length, consumed: 0,+ timing: timing && validAudioInterval(timing.startMs, timing.endMs) ? timing : undefined });+ this.consume(this.audio.enqueue(samples)); // Overrun discards audio, never counts it as heard.+ }++ render(output: Float32Array, contextStart: number): RenderedAudioInterval[] {+ const count = this.audio.render(output);+ return this.consume(count, contextStart);+ }++ private consume(count: number, contextStart?: number): RenderedAudioInterval[] {+ const result: RenderedAudioInterval[] = [];+ let offset = 0;+ while (count > 0 && this.spans.length) {+ const span = this.spans[0];+ const take = Math.min(count, span.frames - span.consumed);+ if (contextStart !== undefined && span.timing) {+ const duration = span.timing.endMs - span.timing.startMs;+ result.push({+ startMs: span.timing.startMs + duration * span.consumed / span.frames,+ endMs: span.timing.startMs + duration * (span.consumed + take) / span.frames,+ contextStart: contextStart + offset / this.rate,+ contextEnd: contextStart + (offset + take) / this.rate,+ });+ }+ span.consumed += take;+ offset += take;+ count -= take;+ if (span.consumed === span.frames) this.spans.shift();+ }+ return result;+ }+}++/** The hardware output clock, not AudioContext's ahead-of-device render clock. */+export function audibleContextTime(context: Pick<AudioContext,+ "state" | "currentTime" | "getOutputTimestamp" | "baseLatency" | "outputLatency"+>): number {+ const stamp = context.getOutputTimestamp?.();+ if (stamp && Number.isFinite(stamp.contextTime)) {+ return stamp.contextTime!;+ }+ // Older engines expose measured latency rather than getOutputTimestamp.+ const latency = (Number.isFinite(context.baseLatency) ? context.baseLatency : 0) ++ (Number.isFinite(context.outputLatency) ? context.outputLatency : 0);+ return Number.isFinite(context.currentTime) ? Math.max(0, context.currentTime - latency) : 0;+}++/** Retain rendered spans until the device clock reaches them, including the tail. */+export class DevicePlaybackTimeline {+ private pending: RenderedAudioInterval[] = [];++ clear(): void { this.pending = []; }++ rendered(spans: RenderedAudioInterval[]): void {+ for (const span of spans) {+ const last = this.pending.at(-1);+ if (last && Math.abs(last.endMs - span.startMs) < 0.00001 &&+ Math.abs(last.contextEnd - span.contextStart) < 0.0000001 &&+ Math.abs((last.endMs - last.startMs) / (last.contextEnd - last.contextStart) -+ (span.endMs - span.startMs) / (span.contextEnd - span.contextStart)) < 0.001) {+ last.endMs = span.endMs;+ last.contextEnd = span.contextEnd;+ } else this.pending.push({ ...span });+ }+ }++ advance(contextTime: number): AudioInterval[] {+ const heard: AudioInterval[] = [];+ while (this.pending.length) {+ const span = this.pending[0];+ if (contextTime <= span.contextStart) break;+ const fraction = Math.min(1, (contextTime - span.contextStart) / (span.contextEnd - span.contextStart));+ const endMs = span.startMs + fraction * (span.endMs - span.startMs);+ heard.push({ startMs: span.startMs, endMs });+ if (fraction === 1) this.pending.shift();+ else {+ this.pending[0] = { ...span, startMs: endMs, contextStart: contextTime };+ break;+ }+ }+ return heard;+ }+}diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsindex 740f1acc2e..693191f780 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -10,6 +10,8 @@ import {RealtimeWebRtcTransport,StreamingPcm16Resampler,} from "./realtimeAudio";+import { TimedPcmQueue } from "./playbackTimeline";+import { readTimedSpeechPlayback } from "./speechPlayback";class FakePort {onmessage: ((event: MessageEvent) => void) | null = null;@@ -31,6 +33,10 @@ class FakeAudioContext {static voices: Array<{ start: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> }> = [];state = "running";currentTime = 0;+ static instances: FakeAudioContext[] = [];+ outputTime = 0;+ getOutputTimestamp = () => ({ contextTime: this.outputTime, performanceTime: 1 });+ constructor() { FakeAudioContext.instances.push(this); }sampleRate = 48_000;destination = {} as AudioDestinationNode;audioWorklet = { addModule: vi.fn(async () => undefined) };@@ -174,6 +180,60 @@ describe("realtime audio client", () => {await client.disconnect();});+ it("plays timed source audio once and highlights only at the device clock", async () => {+ installVoiceBrowserFakes();+ const speakers: { muted: boolean }[] = [];+ vi.stubGlobal("Audio", class {+ muted = false;+ play = async () => undefined;+ pause = () => undefined;+ constructor() { speakers.push(this); }+ });+ const client = new RealtimeAudioClient({}, { browserAudio: true, requiresWebRtcOffer: true });+ const connecting = client.connect();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ socket.receive({ type: "audio_transport", webrtc_answer_sdp: "answer", output_transport: "timed_pcm" });+ socket.receive({ type: "audio_ready", webrtc_answer_sdp: "answer", output_transport: "timed_pcm", output_sample_rate: 24000 });+ await connecting;+ const context = FakeAudioContext.instances.at(-1)!;+ const playback = FakeAudioNode.instances.find(node => node.name === "pcm-playback")!;+ const state = playback.port.postMessage.mock.calls.map(([m]) => m).filter(m => m.type === "output_state").at(-1);+ expect(state.muted).toBe(false);+ expect(speakers[0].muted).toBe(true); // RTP can never double the PCM output.+ socket.receive({ type: "speech_timing", epoch: 0, line_id: "wire-test", text: "First second",+ char_start: 0, char_end: 12, start_ms: 1000, end_ms: 2000 });+ socket.receive({ type: "audio_timed", epoch: 0, start_ms: 1000, end_ms: 2000,+ sample_rate: 24000, audio: Buffer.from(new Int16Array(24000).fill(1000).buffer).toString("base64") });+ expect(readTimedSpeechPlayback("wire-test")?.chars).toBe(0);+ const packet = playback.port.postMessage.mock.calls.map(([m]) => m).find(m => m.type === "pcm");+ const queue = new TimedPcmQueue(48000);+ queue.enqueue(new Int16Array(packet.data), packet);+ const spans = queue.render(new Float32Array(48000), 5);+ const report = (intervals: typeof spans = []) => playback.port.onmessage?.({ data: {+ type: "playback", generation: state.generation, spans: intervals,+ } } as MessageEvent);+ report(spans);+ expect(readTimedSpeechPlayback("wire-test")?.chars).toBe(0);+ context.outputTime = 5.05;+ report();+ expect(readTimedSpeechPlayback("wire-test")?.chars).toBe(5);+ socket.receive({ type: "turn_complete" });+ expect(readTimedSpeechPlayback("wire-test")?.chars).toBe(5);+ socket.receive({ type: "audio_clear", epoch: 1 });+ const flushes = playback.port.postMessage.mock.calls.length;+ socket.receive({ type: "tts_cancel", epoch: 0 });+ expect(playback.port.postMessage.mock.calls).toHaveLength(flushes);+ context.outputTime = 20;+ report(spans); // A delayed worklet message from the cancelled generation.+ expect(readTimedSpeechPlayback("wire-test")?.chars).toBe(5);+ socket.receive({ type: "speech_timing", epoch: 0, line_id: "stale-wire", text: "Stale",+ char_start: 0, char_end: 5, start_ms: 1000, end_ms: 2000 });+ expect(readTimedSpeechPlayback("stale-wire")).toBeNull();+ socket.receive({ type: "audio_closed" });+ await client.disconnect();+ });it("does not consume the media deadline while microphone permission is pending", async () => {vi.useFakeTimers();vi.stubGlobal("RTCPeerConnection", FakePeerConnection);diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex 2a698bb34d..faf3e181e6 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -6,6 +6,9 @@ import { playListeningCue } from "./listeningCue";import { MediaActivity, type MediaLevels } from "./mediaLevels";import { requestConnect } from "./connectBudget";import { mintWsTicket } from "./ws";+import { beginSpeechPlayback, clearSpeechPlayback, setTimedSpeechSession, spokenWordEnd, updateSpeechPlayback } from "./speechPlayback";+import { audibleContextTime, DevicePlaybackTimeline, type AudioInterval, type RenderedAudioInterval } from "./playbackTimeline";+import { TimedAudioFrame, TimedTextFrame, TimedSpeechTracker } from "./timedSpeech";import pcmWorkletUrl from "./pcm-worklet.ts?worker&url";export function buildAudioSocketUrl(ticket?: string | null): string {@@ -279,6 +282,7 @@ export class BrowserSpeechFallback {private generation = 0;private active = false;private finishCancelled: (() => void) | null = null;+ private playbackId: number | null = null;constructor(private readonly synthesis: SpeechSynthesisSurface | null =@@ -312,19 +316,47 @@ export class BrowserSpeechFallback {const generation = ++this.generation;const utterance = this.createUtterance(text);+ const playbackId = beginSpeechPlayback(text);+ this.playbackId = playbackId;let settled = false;+ let playing = false;const finish = (outcome: BrowserSpeechOutcome) => {if (settled || generation !== this.generation) return;settled = true;this.active = false;this.finishCancelled = null;+ if (outcome === "ended" && utterance.volume > 0) {+ updateSpeechPlayback(playbackId, "ended", text.length);+ } else {+ updateSpeechPlayback(playbackId, "cancelled");+ }handlers.onFinish(outcome);};this.finishCancelled = () => finish("cancelled");if (language) utterance.lang = language;utterance.volume = Math.max(0, Math.min(1, Number.isFinite(volume) ? volume : 1));utterance.onstart = () => {- if (generation === this.generation) handlers.onStart?.();+ if (settled || generation !== this.generation) return;+ playing = true;+ updateSpeechPlayback(playbackId, "playing");+ handlers.onStart?.();+ };+ // These boundaries come from the speech engine's playback, so changing+ // rate, pausing or waiting in its queue needs no timer or tempo estimate.+ utterance.onboundary = (event) => {+ if (!playing || settled || generation !== this.generation || utterance.volume <= 0) return;+ if (event.name !== "word") return;+ updateSpeechPlayback(playbackId, "playing", spokenWordEnd(text, event.charIndex));+ };+ utterance.onpause = () => {+ if (settled || generation !== this.generation) return;+ playing = false;+ updateSpeechPlayback(playbackId, "paused");+ };+ utterance.onresume = () => {+ if (settled || generation !== this.generation) return;+ playing = true;+ updateSpeechPlayback(playbackId, "playing");};utterance.onend = () => finish("ended");utterance.onerror = () => finish("error");@@ -343,6 +375,8 @@ export class BrowserSpeechFallback {if (notify) this.finishCancelled?.();this.finishCancelled = null;this.generation += 1;+ if (this.playbackId !== null) updateSpeechPlayback(this.playbackId, "cancelled");+ this.playbackId = null;if (!wasActive) return;this.active = false;try {@@ -467,6 +501,43 @@ export class RealtimeAudioClient {private outputRevision = -1;private listeningCueConsumed = false;private stopListeningCue: (() => void) | null = null;+ private timedOutput = false;+ private timedEpoch = 0;+ private playbackGeneration = 0;+ private lastTimedAudioEnd = -1;+ private readonly deviceTimeline = new DevicePlaybackTimeline();+ private readonly speechTimeline = new TimedSpeechTracker();++ private flushPlayback(): void {+ this.playbackGeneration += 1;+ this.deviceTimeline.clear();+ this.speechTimeline.clear();+ this.playbackNode?.port.postMessage({ type: "flush", generation: this.playbackGeneration });+ }++ private selectOutputTransport(value: unknown, session: unknown): void {+ if (value !== "timed_pcm" && value !== "webrtc") return;+ this.timedOutput = value === "timed_pcm";+ if (typeof session === "string") setTimedSpeechSession(this.timedOutput ? session : "");+ // One speaker only. The peer still carries microphone input; timed PCM+ // owns output and its source-to-device clock instead of parallel RTP.+ this.webRtcTransport.setOutputState(this.outputMuted || this.timedOutput, this.outputVolume);+ if (this.timedOutput) {+ this.remoteMeter?.disconnect();+ if (this.remoteMeter) this.remoteMeter.port.onmessage = null;+ this.remoteSource?.disconnect();+ }+ }++ private acceptPlaybackEpoch(epoch: number): boolean {+ if (!Number.isSafeInteger(epoch) || epoch < 0) return false;+ if (epoch < this.timedEpoch) return false;+ if (epoch > this.timedEpoch) {+ this.flushPlayback();+ this.timedEpoch = epoch;+ }+ return true;+ }private applyOutputState(muted: unknown, volume: unknown, revision: unknown): void {if (typeof muted !== "boolean") return;@@ -479,8 +550,11 @@ export class RealtimeAudioClient {if (typeof volume === "number" && Number.isFinite(volume)) {this.outputVolume = Math.max(0, Math.min(1, volume));}- this.webRtcTransport.setOutputState(effectiveMuted, this.outputVolume);- this.playbackNode?.port.postMessage({ type: "output_state", muted: effectiveMuted, volume: this.outputVolume });+ this.webRtcTransport.setOutputState(effectiveMuted || this.timedOutput, this.outputVolume);+ if (changed) this.flushPlayback();+ this.playbackNode?.port.postMessage({+ type: "output_state", muted: effectiveMuted, volume: this.outputVolume, generation: this.playbackGeneration,+ });if (changed) {this.browserSpeech.cancel(true);this.playbackResampler?.reset();@@ -553,7 +627,8 @@ export class RealtimeAudioClient {}private observeRemoteAudio(stream: MediaStream): void {- if (!this.ctx) return;+ if (!this.ctx || this.timedOutput) return;+ clearSpeechPlayback();// A suspended context measures only zeros: the assistant would talk// while the bar keeps showing listening. The call started from a user// gesture, so resuming here is allowed and makes the tap truthful.@@ -683,7 +758,15 @@ export class RealtimeAudioClient {this.playbackNode.port.onmessage = (event: MessageEvent) => {// RTP is measured by pcm-level. The unused PCM queue produces zeros// and must not erase the real output meter thirty times per second.- if (this.options.browserAudio && this.options.requiresWebRtcOffer) return;+ if (this.options.browserAudio && this.options.requiresWebRtcOffer && !this.timedOutput) return;+ if (event.data?.type === "playback") {+ if (!this.ctx || this.outputMuted || event.data.generation !== this.playbackGeneration) return;+ this.deviceTimeline.rendered(event.data.spans as RenderedAudioInterval[]);+ if (this.ctx.state !== "suspended" && this.ctx.state !== "closed") {+ this.speechTimeline.played(this.deviceTimeline.advance(audibleContextTime(this.ctx)));+ }+ return;+ }const data = event.data as { type?: string; rms?: number } | null;if (data && data.type === "level" && typeof data.rms === "number") {const live = performance.now() - this.lastPcmAt <= OUTPUT_TAP_TTL_MS;@@ -818,6 +901,8 @@ export class RealtimeAudioClient {socket.onerror = () => fail(new Error("Realtime voice socket failed"));socket.onclose = (event) => {this.ready = false;+ this.flushPlayback();+ setTimedSpeechSession("");this.startupNode?.port.postMessage({ type: "suspend" });this.stopInput();this.webRtcTransport.close();@@ -839,13 +924,44 @@ export class RealtimeAudioClient {return;}const type = typeof message.type === "string" ? message.type : "unknown";- if (type === "transcript" && typeof message.text === "string") {+ if (type === "audio_timed") {+ const parsed = TimedAudioFrame.safeParse(message);+ if (!parsed.success || !this.timedOutput || !this.acceptPlaybackEpoch(parsed.data.epoch)) return;+ const frame = parsed.data;+ // A sideband reattach can repeat a reflected frame. Replaying it+ // would move audio backward even though the transcript is revisioned.+ if (frame.end_ms <= this.lastTimedAudioEnd) return;+ try {+ const raw = atob(frame.audio);+ if (raw.length % 2) throw new Error("Invalid PCM16 length");+ const bytes = Uint8Array.from(raw, char => char.charCodeAt(0));+ const overlap = Math.max(0, this.lastTimedAudioEnd - frame.start_ms);+ const skip = Math.min(bytes.length / 2, Math.ceil(+ bytes.length / 2 * overlap / (frame.end_ms - frame.start_ms),+ ));+ const startMs = frame.start_ms + (frame.end_ms - frame.start_ms) * skip / (bytes.length / 2);+ this.lastTimedAudioEnd = frame.end_ms;+ if (skip * 2 < bytes.length) {+ this.handleAudio(bytes.buffer.slice(skip * 2), { startMs, endMs: frame.end_ms });+ }+ } catch {+ console.warn("Invalid timed voice audio was discarded");+ }+ return;+ } else if (type === "speech_timing") {+ const parsed = TimedTextFrame.safeParse(message);+ if (parsed.success && this.timedOutput && this.acceptPlaybackEpoch(parsed.data.epoch)) {+ this.speechTimeline.text(parsed.data);+ }+ return;+ } else if (type === "transcript" && typeof message.text === "string") {this.cb.onTranscript?.(message.text,Boolean(message.is_final),typeof message.role === "string" ? message.role : "user",);} else if (type === "reconnecting") {+ this.lastTimedAudioEnd = -1;this.earlyAnswer = null;this.reconnecting = true;this.ready = false;@@ -856,7 +972,7 @@ export class RealtimeAudioClient {this.cb.onPlaybackState?.(false);this.startupPreroll = [];this.startupPrerollBytes = 0;- this.playbackNode?.port.postMessage({ type: "flush" });+ this.flushPlayback();} else if (type === "reconnect_offer") {void this.webRtcTransport.createOffer(this.rtcInput?.stream ?? this.stream ?? undefined, this.options.webRtcStartEventRequired, this.options.startBudgetMs).then(sdp => {if (sdp && socket.readyState === WebSocket.OPEN && !this.intentionalClose) {@@ -879,10 +995,11 @@ export class RealtimeAudioClient {this.serverClosed = true;this.finalized?.();} else if (type === "tts_cancel" || type === "audio_clear") {+ if (typeof message.epoch === "number" && !this.acceptPlaybackEpoch(message.epoch)) return;this.browserSpeech.cancel();this.playbackResampler?.reset();- this.playbackNode?.port.postMessage({ type: "flush" });- if (this.options.browserAudio && !this.options.requiresWebRtcOffer) {+ this.flushPlayback();+ if (this.options.browserAudio && (!this.options.requiresWebRtcOffer || this.timedOutput)) {this.outputActivity.reset();this.outputLevel = 0;this.cb.onPlaybackState?.(false);@@ -896,6 +1013,7 @@ export class RealtimeAudioClient {}return;} else if (type === "audio_transport") {+ this.selectOutputTransport(message.output_transport, message.session_id);this.applyOutputState(message.output_muted, message.output_volume, message.output_revision);// SDP alone is not readiness. ICE/DTLS may overlap the server's// sideband attach, while pcm-startup continues to output silence.@@ -914,6 +1032,7 @@ export class RealtimeAudioClient {});return;} else if (type === "audio_ready") {+ this.selectOutputTransport(message.output_transport, message.session_id);// The local control channel can already relay levels while RTP// finishes its handshake. Native and browser bars share this input.this.controlReady = true;@@ -1077,16 +1196,16 @@ export class RealtimeAudioClient {this.playbackResampler = new StreamingPcm16Resampler(providerRate, contextRate);}- private handleAudio(pcm: ArrayBuffer): void {+ private handleAudio(pcm: ArrayBuffer, timing?: AudioInterval): void {if (this.outputMuted) return;- // This is authoritative for both API and subscription providers. The- // subscription WebRTC peer intentionally does not play remote RTP; Codex's- // documented sideband PCM therefore keeps Jarvis's scrub gate in the path.+ // Timed sessions mute the peer's RTP element before negotiation. Only+ // this worklet owns their audible output and its source-time mapping.this.browserSpeech.cancel();+ clearSpeechPlayback();if (!this.playbackResampler) this.setOutputRate(24_000);const converted = this.playbackResampler?.process(pcm) ?? pcm;if (converted.byteLength === 0) return;- this.playbackNode?.port.postMessage({ type: "pcm", data: converted }, [converted]);+ this.playbackNode?.port.postMessage({ type: "pcm", data: converted, ...timing }, [converted]);this.lastPcmAt = performance.now();if (!this.options.browserAudio) this.cb.onAudio?.();}@@ -1101,7 +1220,7 @@ export class RealtimeAudioClient {}this.playbackResampler?.reset();- this.playbackNode?.port.postMessage({ type: "flush" });+ this.flushPlayback();// Passed through verbatim from the backend's single turn-language// resolver. No default is substituted here: inventing one would be a// second language decision in a layer that has no business making it.diff --git a/jarvis/ui/web/frontend/src/lib/speechPlayback.ts b/jarvis/ui/web/frontend/src/lib/speechPlayback.tsnew file mode 100644index 0000000000..2c20c4f4b8--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/speechPlayback.ts@@ -0,0 +1,78 @@+/** Playback-confirmed text positions. Generation/level events are not positions. */+export type SpeechPlayback = {+ id: number;+ text: string;+ chars: number;+ state: "queued" | "playing" | "paused" | "ended" | "cancelled";+};++let serial = 0;+let current: SpeechPlayback | null = null;+const listeners = new Set<() => void>();+const timedLines = new Map<string, { text: string; chars: number }>();+let timedSession = "";++export function readTimedSpeechSession(): string { return timedSession; }++export function setTimedSpeechSession(session: string): void {+ if (session === timedSession) return;+ timedSession = session;+ for (const listener of listeners) listener();+}++export function readTimedSpeechPlayback(id: string): { text: string; chars: number } | null {+ return timedLines.get(id) ?? null;+}++export function publishTimedSpeechPlayback(id: string, text: string, chars: number): void {+ const old = timedLines.get(id);+ if (old?.text === text && old.chars === chars) return;+ timedLines.set(id, { text, chars });+ while (timedLines.size > 128) timedLines.delete(timedLines.keys().next().value!);+ for (const listener of listeners) listener();+}++export function subscribeSpeechPlayback(listener: () => void): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+}++export function readSpeechPlayback(): SpeechPlayback | null { return current; }++function publish(value: SpeechPlayback | null): void {+ current = value;+ for (const listener of listeners) listener();+}++/** The player owns this id; late callbacks cannot advance a replacement. */+export function beginSpeechPlayback(text: string): number {+ const id = ++serial;+ publish({ id, text, chars: 0, state: "queued" });+ return id;+}++export function updateSpeechPlayback(+ id: number,+ state: SpeechPlayback["state"],+ chars = current?.chars ?? 0,+): void {+ if (!current || current.id !== id || !Number.isFinite(chars)) return;+ if (current.state === "ended" || current.state === "cancelled") return;+ const next = Math.max(current.chars, Math.min(current.text.length, Math.floor(chars)));+ if (current.state !== state || current.chars !== next) publish({ ...current, state, chars: next });+}++/** A different playback surface has no word positions; never inherit old ones. */+export function clearSpeechPlayback(): void {+ if (current) publish(null);+}++/** Highlight the current whole word only when its playback boundary fires. */+export function spokenWordEnd(text: string, index: number): number {+ if (!Number.isInteger(index) || index < 0 || index >= text.length) return 0;+ const nextWord = text.slice(index).search(/\S/);+ if (nextWord < 0) return text.length;+ index += nextWord;+ const end = text.slice(index).search(/\s/);+ return end < 0 ? text.length : index + end;+}diff --git a/jarvis/ui/web/frontend/src/lib/timedSpeech.ts b/jarvis/ui/web/frontend/src/lib/timedSpeech.tsnew file mode 100644index 0000000000..18d7611615--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/timedSpeech.ts@@ -0,0 +1,76 @@+import { z } from "zod";+import type { AudioInterval } from "./playbackTimeline";+import { publishTimedSpeechPlayback, spokenWordEnd } from "./speechPlayback";++const epoch = z.number().int().nonnegative();+const time = z.number().finite().nonnegative();+export const TimedAudioFrame = z.object({+ type: z.literal("audio_timed"), epoch,+ audio: z.string().max(1_400_000), sample_rate: z.number().int().min(8000).max(192000),+ start_ms: time, end_ms: time,+}).refine(v => v.end_ms > v.start_ms);+export const TimedTextFrame = z.object({+ type: z.literal("speech_timing"), epoch,+ line_id: z.string().min(1).max(512), text: z.string().max(128_000),+ char_start: z.number().int().nonnegative(), char_end: z.number().int().nonnegative(),+ start_ms: time, end_ms: time,+}).refine(v => v.end_ms > v.start_ms && v.char_end <= v.text.length && v.char_end > v.char_start);+export type TimedText = z.infer<typeof TimedTextFrame>;+type Line = { text: string; chars: number; cues: TimedText[] };++/** Match timestamped fragments against intervals the device actually played. */+export class TimedSpeechTracker {+ private lines = new Map<string, Line>();+ private heard: AudioInterval[] = [];++ clear(): void {+ // Published positions survive an interruption; pending cues never do.+ this.lines.clear();+ this.heard = [];+ }++ text(cue: TimedText): void {+ let line = this.lines.get(cue.line_id);+ if (!line || !cue.text.startsWith(line.text)) {+ line = { text: cue.text, chars: 0, cues: [] };+ this.lines.set(cue.line_id, line);+ }+ line.text = cue.text;+ if (!line.cues.some(old => old.char_start === cue.char_start && old.char_end === cue.char_end)) {+ line.cues.push(cue);+ line.cues.sort((a, b) => a.char_start - b.char_start);+ }+ while (this.lines.size > 128) this.lines.delete(this.lines.keys().next().value!);+ this.project(cue.line_id, line);+ }++ played(intervals: AudioInterval[]): void {+ for (const span of intervals) {+ const last = this.heard.at(-1);+ if (last && span.startMs <= last.endMs + 0.01 && span.startMs >= last.startMs) {+ last.endMs = Math.max(last.endMs, span.endMs);+ } else this.heard.push({ ...span });+ }+ // One minute covers late captions without retaining a call's audio history.+ const oldest = (this.heard.at(-1)?.endMs ?? 0) - 60_000;+ this.heard = this.heard.filter(span => span.endMs >= oldest).slice(-4096);+ for (const [id, line] of this.lines) this.project(id, line);+ }++ private project(id: string, line: Line): void {+ for (const cue of line.cues) {+ if (cue.char_start > line.chars) break;+ const span = this.heard.find(range => range.startMs <= cue.start_ms + 0.01 && range.endMs > cue.start_ms);+ if (!span) break;+ const fraction = Math.min(1, (span.endMs - cue.start_ms) / (cue.end_ms - cue.start_ms));+ // Provider intervals may span more than one word. Interpolate only+ // inside that measured fragment, never at a global characters/sec rate.+ const fragment = line.text.slice(cue.char_start, cue.char_end);+ const position = fraction === 1 ? fragment.length :+ spokenWordEnd(fragment, Math.min(fragment.length - 1, Math.floor(fraction * fragment.length)));+ line.chars = Math.max(line.chars, cue.char_start + position);+ if (fraction < 1) break;+ }+ publishTimedSpeechPlayback(id, line.text, line.chars);+ }+}diff --git a/tests/fixtures/voice_playback_contract.json b/tests/fixtures/voice_playback_contract.jsonnew file mode 100644index 0000000000..b6ab59bbc4--- /dev/null+++ b/tests/fixtures/voice_playback_contract.json@@ -0,0 +1,4 @@+[+ {"type":"audio_timed","epoch":2,"audio":"AAAA","sample_rate":24000,"start_ms":600,"end_ms":800},+ {"type":"speech_timing","epoch":2,"line_id":"live:test:segment","text":"One two","char_start":3,"char_end":7,"start_ms":1200,"end_ms":1400}+]diff --git a/tests/unit/live/test_playback_timing.py b/tests/unit/live/test_playback_timing.pynew file mode 100644index 0000000000..1fdcbff085--- /dev/null+++ b/tests/unit/live/test_playback_timing.py@@ -0,0 +1,222 @@+"""Provider source intervals survive through to the sole browser audio owner."""++import base64+import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.live.config import LiveConfig+from jarvis.live.playback import AudioTimedFrame, SpeechTimingFrame, source_interval, utf16_length+from jarvis.live.session import LiveVoiceSession+from jarvis.live.state import LiveLedger+from jarvis.live.subscription import SubscriptionLiveVoiceSession+from jarvis.plugins.realtime.openai_subscription_live import OpenAISubscriptionLiveConnection+from tests.fakes.fake_subscription_live_wire import SDP, FakeSubscriptionSocket+from tests.fakes.fake_subscription_session import subscription_provider+++async def test_real_subscription_envelope_keeps_source_times_instead_of_receive_times(tmp_path):+ raw = [+ {+ "type": "session.output_audio.delta",+ "delta": base64.b64encode(bytes(9600)).decode(),+ "start_ms": 600,+ "end_ms": 800,+ },+ {+ "type": "output_transcript.added",+ "start_ms": 600,+ "end_ms": 800,+ "item": {"id": "item-1", "type": "text", "text": "One"},+ },+ {+ "type": "output_transcript.added",+ "start_ms": 1200,+ "end_ms": 1400,+ "item": {"id": "item-2", "type": "text", "text": " two"},+ },+ {+ "type": "turn.done",+ "turn": {+ "id": "turn-1",+ "role": "assistant",+ "start_ms": 600,+ "end_ms": 1400,+ "transcript": "One two",+ },+ },+ ]+ conn = OpenAISubscriptionLiveConnection(+ FakeSubscriptionSocket(raw), session_id="rtc_test", answer_sdp=SDP+ )+ messages = []++ async def send(value):+ messages.append(value)++ provider = subscription_provider()+ provider.source_timed_audio = True+ session = SubscriptionLiveVoiceSession(+ session_id="voice-test",+ providers=[provider],+ config=SimpleNamespace(+ live=LiveConfig(configured=True), brain=SimpleNamespace(reply_language="en")+ ),+ send_json=send,+ send_binary=send,+ )+ session._connection = conn+ session._ledger = LiveLedger(tmp_path / "timing.sqlite3")+ session._tools = SimpleNamespace(user_text="")+ try:+ await session._transport_ready(SDP)+ assert messages[-1]["output_transport"] == "timed_pcm"+ for _ in raw:+ event = await conn.receive()+ if event["type"].startswith("session.output_transcript"):+ assert event["timestamp_source"] == "source_audio"+ assert event["start_ms"] == 600+ await session._event(event)+ audio = next(m for m in messages if m["type"] == "audio_timed")+ assert AudioTimedFrame.model_validate(audio).start_ms == 600+ cues = [+ SpeechTimingFrame.model_validate(m) for m in messages if m["type"] == "speech_timing"+ ]+ assert [(c.start_ms, c.end_ms, c.char_start, c.char_end) for c in cues] == [+ (600, 800, 0, 3),+ (1200, 1400, 3, 7),+ ]+ assert cues[0].line_id == cues[1].line_id+ assert cues[1].text == "One two"+ # A final transcript is not a playback acknowledgement.+ assert len(cues) == 2+ await session._clear_playback(wait_for_provider=True)+ before = len(messages)+ await session._event(+ {+ "type": "session.output_audio.delta",+ "delta": "AAAA",+ "start_ms": 1400,+ "end_ms": 1600,+ }+ )+ assert len(messages) == before+ await session._event({"type": "output_audio_buffer.cleared"})+ await session._event(+ {+ "type": "session.output_audio.delta",+ "delta": "AAAA",+ "start_ms": 1600,+ "end_ms": 1800,+ }+ )+ assert messages[-1]["epoch"] == 2+ await session._clear_playback(wait_for_provider=True)+ await session._caption(event) # A cancelled turn may end without a clear acknowledgement.+ assert not session._awaiting_output_clear+ await session._event(+ {+ "type": "session.output_audio.delta",+ "delta": "AAAAAA==",+ "start_ms": 1800,+ "end_ms": 2000,+ }+ )+ assert messages[-1]["epoch"] == 4+ finally:+ session._ledger.close()+++def test_intervals_and_offsets_are_browser_compatible():+ assert utf16_length("A\U0001f600 B") == 5+ assert source_interval(0, 200)+ for start, end in [(True, 200), (0, False), (100, 100), (-1, 20), (0, float("inf"))]:+ assert not source_interval(start, end)+ frame = SpeechTimingFrame(+ epoch=0,+ line_id="line",+ text="A\U0001f600 B",+ char_start=0,+ char_end=5,+ start_ms=0,+ end_ms=200,+ )+ assert frame.char_end == 5+++async def test_untimed_legacy_transcript_is_not_claimed_as_audio_timing():+ conn = OpenAISubscriptionLiveConnection(+ FakeSubscriptionSocket(+ [+ {"type": "output_transcript.added", "item": {"text": "Legacy"}},+ ]+ ),+ session_id="rtc_test",+ answer_sdp=SDP,+ )+ event = await conn.receive()+ assert event["timestamp_source"] == "local_receive_clock"+ assert "fragment_start_ms" not in event+++def test_shared_browser_wire_fixture_validates_without_changing_values():+ fixture = Path(__file__).parents[2] / "fixtures" / "voice_playback_contract.json"+ audio, text = json.loads(fixture.read_text(encoding="utf-8"))+ assert AudioTimedFrame.model_validate(audio).model_dump() == audio+ assert SpeechTimingFrame.model_validate(text).model_dump() == text+++async def test_public_live_uses_the_same_timed_output_contract():+ messages = []++ async def send(value):+ messages.append(value)++ session = LiveVoiceSession(+ session_id="public-test",+ providers=[SimpleNamespace(name="public-test", source_timed_audio=True)],+ config=SimpleNamespace(brain=SimpleNamespace(reply_language="en")),+ send_json=send,+ send_binary=send,+ )+ session._connection = SimpleNamespace(answer_sdp="answer")+ session._tools = SimpleNamespace(user_text="")+ session._ledger = SimpleNamespace(append=lambda _: True)+ await session._event(+ {+ "type": "session.output_transcript.delta",+ "delta": "Hello",+ "start_ms": 100,+ "end_ms": 300,+ }+ )+ await session._event(+ {"type": "session.output_audio.delta", "delta": "AAAA", "start_ms": 100, "end_ms": 300}+ )+ assert next(m for m in messages if m["type"] == "speech_timing")["char_end"] == 5+ assert messages[-1]["type"] == "audio_timed"+++def test_bad_metadata_does_not_log_provider_payload(caplog):+ from jarvis.live.playback import playback_frame++ assert (+ playback_frame(+ SpeechTimingFrame,+ epoch=0,+ line_id="",+ text="private-payload-sentinel",+ char_start=0,+ char_end=5,+ start_ms=0,+ end_ms=10,+ )+ is None+ )+ assert "private-payload-sentinel" not in caplog.text+ assert "metadata was discarded" in caplog.textdiff --git a/tests/unit/live/test_subscription_wire.py b/tests/unit/live/test_subscription_wire.pyindex 5a6b275d83..cb76a350f8 100644--- a/tests/unit/live/test_subscription_wire.py+++ b/tests/unit/live/test_subscription_wire.py@@ -274,7 +274,7 @@ async def test_unknown_delegation_and_api_commands_cannot_reach_provider():assert conn.socket.sent == []-async def test_audio_stays_on_webrtc_and_provider_error_is_fatal_but_safe():+async def test_reflected_audio_is_retained_and_provider_error_is_fatal_but_safe():conn = connection([{"type": "output_audio.delta", "audio": "AAAA"},@@ -284,7 +284,7 @@ async def test_audio_stays_on_webrtc_and_provider_error_is_fatal_but_safe():},])- assert (await conn.receive())["type"] == "subscription.ignored"+ assert (await conn.receive())["type"] == "session.output_audio.delta"event = await conn.receive()assert event["fatal"] is Trueassert event["error"]["code"] == "quota_exhausted"