Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(workbench): support reliable long-form voice input (#1097)

Call White53cae428eb50
diff --git a/core/audio_asr.py b/core/audio_asr.py
index 3ac6109e2..1c5e4f8fb 100644
--- a/core/audio_asr.py
+++ b/core/audio_asr.py
@@ -87,6 +87,22 @@ class AudioAsrRuntimeConfig:
device_secret: str
+class AudioAsrTimeoutError(TimeoutError):
+ """Raised when the upstream ASR request exhausts its total deadline."""
+
+
+class AudioAsrEmptyTranscriptError(ValueError):
+ """Raised when upstream accepts the audio but returns no transcript text."""
+
+
+class AudioAsrProtocolError(ValueError):
+ """Raised when upstream returns a success response with an invalid schema."""
+
+
+class AudioAsrUnavailableError(ConnectionError):
+ """Raised when the configured upstream ASR service is unavailable."""
+
+
class AudioAsrService:
"""Transcribe downloaded audio attachments through AVIBE ASR."""
@@ -152,7 +168,15 @@ class AudioAsrService:
eligible.append(attachment)
return eligible
- async def transcribe_attachments(self, attachments: list[FileAttachment]) -> list[AudioTranscript]:
+ async def transcribe_attachments(
+ self,
+ attachments: list[FileAttachment],
+ *,
+ raise_on_empty: bool = False,
+ raise_on_timeout: bool = False,
+ raise_on_unavailable: bool = False,
+ timeout_seconds: float | None = None,
+ ) -> list[AudioTranscript]:
asr_config = self._get_audio_asr_config()
if not asr_config.enabled:
return []
@@ -164,9 +188,16 @@ class AudioAsrService:
if not eligible:
return []
- timeout_seconds = max(0.1, float(asr_config.timeout_seconds or 60.0))
- deadline = time.monotonic() + timeout_seconds
- timeout = aiohttp.ClientTimeout(total=timeout_seconds)
+ request_timeout_seconds = max(
+ 0.1,
+ float(
+ timeout_seconds
+ if timeout_seconds is not None
+ else asr_config.timeout_seconds or 60.0
+ ),
+ )
+ deadline = time.monotonic() + request_timeout_seconds
+ timeout = aiohttp.ClientTimeout(total=request_timeout_seconds)
async with aiohttp.ClientSession(timeout=timeout) as session:
tasks = [self._transcribe_one(session, runtime, attachment, deadline) for attachment in eligible]
results = await asyncio.gather(*tasks, return_exceptions=True)
@@ -175,6 +206,13 @@ class AudioAsrService:
for result in results:
if isinstance(result, AudioTranscript):
transcripts.append(result)
+ elif isinstance(result, AudioAsrEmptyTranscriptError):
+ if raise_on_empty:
+ raise result
+ elif isinstance(result, AudioAsrTimeoutError) and raise_on_timeout:
+ raise result
+ elif isinstance(result, AudioAsrUnavailableError) and raise_on_unavailable:
+ raise result
elif isinstance(result, Exception):
logger.warning("Audio ASR skipped after error: %s", result)
return transcripts
@@ -188,7 +226,7 @@ class AudioAsrService:
) -> AudioTranscript | None:
remaining = deadline - time.monotonic()
if remaining <= 0:
- return None
+ raise AudioAsrTimeoutError("audio ASR deadline exhausted")
path = Path(attachment.local_path or "")
if not path.is_file():
@@ -232,12 +270,13 @@ class AudioAsrService:
},
timeout=aiohttp.ClientTimeout(total=max(0.1, remaining)),
) as response:
- payload: dict[str, Any] = {}
+ payload: Any = None
try:
payload = await response.json(content_type=None)
except Exception:
text = await response.text()
- payload = {"error": text[:200]}
+ if response.status < 200 or response.status >= 300:
+ payload = {"error": text[:200]}
duration_ms = int((time.monotonic() - start) * 1000)
if response.status < 200 or response.status >= 300:
logger.warning(
@@ -247,18 +286,38 @@ class AudioAsrService:
mimetype,
duration_ms,
)
+ upstream_error = (
+ payload.get("error")
+ if isinstance(payload, dict)
+ else None
+ )
+ if response.status == 504 or upstream_error == "transcription_timeout":
+ raise AudioAsrTimeoutError("audio ASR upstream timed out")
+ if response.status == 503 or upstream_error in {
+ "asr_not_configured",
+ "asr_unavailable",
+ }:
+ raise AudioAsrUnavailableError("audio ASR upstream unavailable")
return None
+ except (AudioAsrTimeoutError, AudioAsrUnavailableError):
+ raise
except asyncio.TimeoutError:
logger.warning("Audio ASR timed out for %s", attachment.name)
- return None
+ raise AudioAsrTimeoutError("audio ASR request timed out") from None
+ except aiohttp.ClientError as exc:
+ logger.warning("Audio ASR request unavailable for %s: %s", attachment.name, exc)
+ raise AudioAsrUnavailableError("audio ASR request unavailable") from exc
except Exception as exc:
logger.warning("Audio ASR request failed for %s: %s", attachment.name, exc)
return None
- text = str(payload.get("text") or "").strip()
- if not text:
+ if not isinstance(payload, dict) or not isinstance(payload.get("text"), str):
+ logger.warning("Audio ASR returned a malformed success response for %s", attachment.name)
+ raise AudioAsrProtocolError("audio ASR returned a malformed success response")
+ text = payload["text"]
+ if not text.strip():
logger.warning("Audio ASR returned empty transcript for %s", attachment.name)
- return None
+ raise AudioAsrEmptyTranscriptError("audio ASR returned an empty transcript")
return AudioTranscript(
attachment_name=attachment.name or path.name,
local_path=str(path),
diff --git a/docs/plans/voice-input-reliability.md b/docs/plans/voice-input-reliability.md
new file mode 100644
index 000000000..7814c4679
--- /dev/null
+++ b/docs/plans/voice-input-reliability.md
@@ -0,0 +1,158 @@
+# Voice Input Reliability and Typeless Direction
+
+## Product contract
+
+Voice input is an input method, not an agent turn. It must:
+
+1. preserve the recording until text is produced or the user discards it;
+2. never submit the same recording to two transcription paths automatically;
+3. never auto-send the resulting text;
+4. return raw ASR text even when optional text cleanup is unavailable;
+5. support continuous dictation without an arbitrary total recording limit;
+6. collect timing and failure-stage metadata without logging audio or transcript
+ contents.
+
+## Current request path
+
+```text
+getUserMedia
+ -> AudioWorklet mono PCM capture on the audio rendering thread
+ -> independently decodable 16 kHz WAV segments framed by sample count
+ -> upload completed segments directly to avibe.bot while capture continues
+ -> qwen3-asr-flash per segment
+ -> preserve segment order and append once after the user stops
+```
+
+When the browser cannot obtain a cloud token, the compatibility path remains:
+
+```text
+getUserMedia / AudioWorklet
+ -> local /api/asr/transcribe
+ -> paired-device /v1/audio/transcriptions
+ -> qwen3-asr-flash
+```
+
+The compatibility path is selected before a cloud upload starts. A response or
+timeout from the direct cloud request is final for that attempt; the user may
+retry only the failed retained segments explicitly.
+
+## Reliability baseline
+
+The first stabilization increment establishes these invariants:
+
+- capture mono 16 kHz PCM on the audio rendering thread and frame WAV files by
+ sample count so a blocked UI thread cannot create an oversized recording;
+- emit a segment every minute because `qwen3-asr-flash` has a five-minute
+ per-file limit, while imposing no total dictation limit;
+- transcribe completed segments while capture continues, retain all segment
+ audio until finalization, and join results in capture order;
+- apply a 120-second upstream deadline and a 158-second browser deadline to each
+ one-minute segment, including token/CSRF acquisition and a 30-second
+ encoding/upload allowance, not to the complete dictation;
+- distinguish timeout, size, availability, empty-audio, and generic failures;
+- retain the complete recording and expose an explicit retry action that
+ resubmits only failed segments;
+- keep pending and retryable batches keyed by chat session so ordinary
+ navigation cannot discard audio;
+- log request size, MIME type, duration, provider stage, and attempt count, but
+ never audio bytes, credentials, or transcript text.
+
+### Initial service indicators
+
+Measure these by request path, browser family, MIME type, total dictation
+duration, segment duration, and release:
+
+- transcription success rate;
+- p50, p95, and p99 time from recording stop to text insertion;
+- segment backlog at recording stop;
+- upstream fetch, timeout, HTTP, and empty-result failure rates;
+- explicit retry success rate;
+- recording-size and duration distributions.
+
+Set production SLOs only after one week of representative measurements. The
+first target should be at least 99.5% successful finalization for accepted
+recordings, excluding user cancellation and permission denial.
+
+## Streaming path
+
+Segmented batch upload removes the long-dictation limit and overlaps inference
+with capture, but it cannot deliver Typeless-class partial-result latency. The
+next capability should use the provider's realtime ASR model:
+
+```text
+capture client
+ -> ephemeral ASR session token
+ -> authenticated WebSocket
+ -> 20-40 ms mono PCM or Opus frames
+ -> partial transcript events
+ -> final raw transcript
+```
+
+The composer should render partial text separately from the persisted draft.
+Only a final transcript is appended to the draft. A dropped WebSocket may resume
+from the last acknowledged audio sequence while the client still holds its
+bounded local audio buffer.
+
+Acceptance targets for the streaming path:
+
+- p95 first partial transcript under 800 ms on a healthy connection;
+- p95 final transcript under 1.5 seconds after the user stops speaking;
+- no lost final audio when the stop action races the last frame;
+- raw transcript remains usable when cleanup fails.
+
+## System-wide input
+
+System-wide dictation should reuse the streaming protocol through a native
+capture client, not automate the Web composer:
+
+- global hotkey or press-and-hold capture;
+- active-application text insertion through the operating system accessibility
+ API, with clipboard insertion as an explicit fallback;
+- local recording indicator and cancel action;
+- the same ephemeral cloud credential and privacy-safe telemetry as Web;
+- raw audio kept only in a bounded in-memory retry buffer unless the user opts
+ into history.
+
+Browser extension support may follow for browser-only users, but it should use
+the same capture/session library and insertion contract.
+
+## Optional text cleanup
+
+Cleanup is a second, separately budgeted stage:
+
+```text
+final raw transcript
+ -> small text model
+ -> cleaned text
+ -> composer or active application
+```
+
+The cleanup model receives text only. Its prompt must preserve facts, names,
+numbers, links, commands, and language while limiting edits to punctuation,
+filler removal, obvious repetitions, and paragraph breaks. The raw transcript
+is retained for undo and comparison.
+
+Cleanup requirements:
+
+- disabled, literal, and clean modes;
+- hard deadline independent of ASR;
+- raw-text fallback on timeout or any model error;
+- deterministic settings and a versioned prompt;
+- regression corpus covering Chinese, English, mixed language, code, URLs,
+ names, and numeric dictation;
+- no general Agent invocation and no tool access.
+
+## Delivery sequence
+
+1. Ship and observe the continuous segmented-batch reliability baseline.
+2. Add dashboards and alerts for success rate and latency by failure stage.
+3. Prototype realtime ASR in the Web composer behind a feature flag.
+4. Add the cleanup stage only after raw streaming ASR meets its latency and
+ reliability targets.
+5. Extract the shared capture/session client for the native system-wide input
+ surface.
+
+The segmented batch route remains the fallback and long-tail compatibility path.
+Imported audio files that are already long recordings should use the provider's
+asynchronous file-transcription model rather than being decoded and split in the
+browser.
diff --git a/docs/plans/workbench-chat-media-io.md b/docs/plans/workbench-chat-media-io.md
index 0b28b997b..78e0e65ab 100644
--- a/docs/plans/workbench-chat-media-io.md
+++ b/docs/plans/workbench-chat-media-io.md
@@ -122,6 +122,11 @@ the right-side send/stop button.
IM "download" step and build `FileAttachment(local_path=...)` directly.
### Voice (ASR)
+> **Superseded:** Browser voice capture and transcription now follow
+> [`voice-input-reliability.md`](voice-input-reliability.md): AudioWorklet
+> capture produces independently transcribed WAV segments and no longer uses
+> the single-file MediaRecorder flow described below.
+
- Record with `MediaRecorder` (webm/opus, which `core/audio_asr.py` supports).
- `POST /api/asr/transcribe` (multipart) → save temp file → wrap as
`FileAttachment(local_path=...)` → `AudioAsrService.transcribe_attachments()`
diff --git a/tests/test_audio_asr.py b/tests/test_audio_asr.py
index 1e6f81fbc..8eaa3c22d 100644
--- a/tests/test_audio_asr.py
+++ b/tests/test_audio_asr.py
@@ -3,11 +3,15 @@ import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
from config.v2_config import AudioAsrConfig, RemoteAccessConfig, VibeCloudRemoteAccessConfig
from core.audio_asr import (
+ AudioAsrEmptyTranscriptError,
+ AudioAsrProtocolError,
AudioAsrService,
+ AudioAsrTimeoutError,
+ AudioAsrUnavailableError,
AudioTranscript,
append_audio_transcripts_to_message,
format_audio_transcript_echo,
@@ -82,6 +86,292 @@ class AudioAsrServiceTests(unittest.TestCase):
"Voice transcript:\nhello world",
)
+ def test_http_callers_can_preserve_timeout_classification(self):
+ service = AudioAsrService(
+ SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ )
+ )
+ with tempfile.TemporaryDirectory() as tmpdir:
+ audio_path = Path(tmpdir) / "voice.webm"
+ audio_path.write_bytes(b"audio")
+ attachment = FileAttachment(
+ name="voice.webm",
+ mimetype="audio/webm",
+ local_path=str(audio_path),
+ size=5,
+ )
+ timeout = AsyncMock(side_effect=AudioAsrTimeoutError("timed out"))
+ with patch.object(service, "_transcribe_one", timeout):
+ with self.assertRaises(AudioAsrTimeoutError):
+ asyncio.run(
+ service.transcribe_attachments(
+ [attachment],
+ raise_on_timeout=True,
+ )
+ )
+ self.assertEqual(
+ asyncio.run(service.transcribe_attachments([attachment])),
+ [],
+ )
+
+ def test_empty_upstream_transcript_has_a_distinct_classification(self):
+ service = AudioAsrService(
+ SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ )
+ )
+
+ class EmptyResponse:
+ status = 200
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def json(self, **_kwargs):
+ return {"text": " "}
+
+ class EmptySession:
+ def post(self, *_args, **_kwargs):
+ return EmptyResponse()
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ audio_path = Path(tmpdir) / "voice.wav"
+ audio_path.write_bytes(b"RIFF\x00\x00\x00\x00WAVE")
+ attachment = FileAttachment(
+ name="voice.wav",
+ mimetype="audio/wav",
+ local_path=str(audio_path),
+ size=12,
+ )
+
+ with self.assertRaises(AudioAsrEmptyTranscriptError):
+ asyncio.run(
+ service._transcribe_one(
+ EmptySession(),
+ service._runtime_config(),
+ attachment,
+ 10**12,
+ )
+ )
+
+ empty = AsyncMock(side_effect=AudioAsrEmptyTranscriptError("empty"))
+ with patch.object(service, "_transcribe_one", empty):
+ with self.assertRaises(AudioAsrEmptyTranscriptError):
+ asyncio.run(
+ service.transcribe_attachments(
+ [attachment],
+ raise_on_empty=True,
+ )
+ )
+ self.assertEqual(
+ asyncio.run(service.transcribe_attachments([attachment])),
+ [],
+ )
+
+ def test_success_payload_requires_string_and_preserves_whitespace(self):
+ service = AudioAsrService(
+ SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ )
+ )
+
+ class MalformedResponse:
+ status = 200
+
+ def __init__(self, payload=None, *, invalid_json=False):
+ self.payload = payload
+ self.invalid_json = invalid_json
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def json(self, **_kwargs):
+ if self.invalid_json:
+ raise ValueError("invalid JSON")
+ return self.payload
+
+ async def text(self):
+ return "{"
+
+ class MalformedSession:
+ def __init__(self, response):
+ self.response = response
+
+ def post(self, *_args, **_kwargs):
+ return self.response
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ audio_path = Path(tmpdir) / "voice.wav"
+ audio_path.write_bytes(b"RIFF\x00\x00\x00\x00WAVE")
+ attachment = FileAttachment(
+ name="voice.wav",
+ mimetype="audio/wav",
+ local_path=str(audio_path),
+ size=12,
+ )
+
+ malformed_responses = [
+ MalformedResponse(invalid_json=True),
+ MalformedResponse({}),
+ MalformedResponse({"text": 123}),
+ ]
+ for response in malformed_responses:
+ with self.subTest(response=response):
+ with self.assertRaises(AudioAsrProtocolError):
+ asyncio.run(
+ service._transcribe_one(
+ MalformedSession(response),
+ service._runtime_config(),
+ attachment,
+ 10**12,
+ )
+ )
+
+ transcript = asyncio.run(
+ service._transcribe_one(
+ MalformedSession(MalformedResponse({"text": "first paragraph\n\n"})),
+ service._runtime_config(),
+ attachment,
+ 10**12,
+ )
+ )
+ self.assertEqual(transcript.text, "first paragraph\n\n")
+
+ def test_provider_outage_has_an_opt_in_availability_classification(self):
+ service = AudioAsrService(
+ SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ )
+ )
+
+ class UnavailableResponse:
+ status = 503
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def json(self, **_kwargs):
+ return {"error": "asr_unavailable"}
+
+ class UnavailableSession:
+ def post(self, *_args, **_kwargs):
+ return UnavailableResponse()
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ audio_path = Path(tmpdir) / "voice.wav"
+ audio_path.write_bytes(b"RIFF\x00\x00\x00\x00WAVE")
+ attachment = FileAttachment(
+ name="voice.wav",
+ mimetype="audio/wav",
+ local_path=str(audio_path),
+ size=12,
+ )
+
+ with self.assertRaises(AudioAsrUnavailableError):
+ asyncio.run(
+ service._transcribe_one(
+ UnavailableSession(),
+ service._runtime_config(),
+ attachment,
+ 10**12,
+ )
+ )
+
+ unavailable = AsyncMock(
+ side_effect=AudioAsrUnavailableError("unavailable"),
+ )
+ with patch.object(service, "_transcribe_one", unavailable):
+ with self.assertRaises(AudioAsrUnavailableError):
+ asyncio.run(
+ service.transcribe_attachments(
+ [attachment],
+ raise_on_unavailable=True,
+ )
+ )
+ self.assertEqual(
+ asyncio.run(service.transcribe_attachments([attachment])),
+ [],
+ )
+
+ def test_http_callers_can_override_the_request_deadline(self):
+ service = AudioAsrService(
+ SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True, timeout_seconds=60.0),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ )
+ )
+ with tempfile.TemporaryDirectory() as tmpdir:
+ audio_path = Path(tmpdir) / "voice.wav"
+ audio_path.write_bytes(b"audio")
+ attachment = FileAttachment(
+ name="voice.wav",
+ mimetype="audio/wav",
+ local_path=str(audio_path),
+ size=5,
+ )
+ transcribe = AsyncMock(return_value=None)
+ with (
+ patch("core.audio_asr.time.monotonic", return_value=100.0),
+ patch.object(service, "_transcribe_one", transcribe),
+ ):
+ asyncio.run(
+ service.transcribe_attachments(
+ [attachment],
+ timeout_seconds=120.0,
+ )
+ )
+
+ self.assertEqual(transcribe.await_args.args[3], 220.0)
+
class _AttachmentIMClient:
def __init__(self, payload: bytes = b"audio"):
diff --git a/tests/test_ui_server_voice_telemetry.py b/tests/test_ui_server_voice_telemetry.py
new file mode 100644
index 000000000..058f7f3d3
--- /dev/null
+++ b/tests/test_ui_server_voice_telemetry.py
@@ -0,0 +1,158 @@
+from __future__ import annotations
+
+import json
+import logging
+
+from tests.ui_server_test_helpers import csrf_headers
+from vibe.ui_server import app
+
+
+def test_voice_telemetry_logs_only_allowlisted_metadata(caplog):
+ client = app.test_client()
+ with caplog.at_level(logging.INFO, logger="vibe.ui_server"):
+ response = client.post(
+ "/api/asr/telemetry",
+ json={
+ "event": "segment_transcription",
+ "outcome": "success",
+ "dictationId": "dictation-123",
+ "path": "cloud",
+ "providerStage": "response",
+ "sizeBytes": 240_000,
+ "mimeType": "audio/webm",
+ "durationMs": 60_000,
+ "elapsedMs": 820,
+ "httpStatus": 200,
+ "attemptCount": 1,
+ "browserFamily": "chrome",
+ "transcript": "private words",
+ "audio": "private bytes",
+ "token": "secret credential",
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ record = next(record for record in caplog.records if record.message.startswith("voice_reliability "))
+ metric = json.loads(record.message.removeprefix("voice_reliability "))
+ assert metric["event"] == "segment_transcription"
+ assert metric["dictationId"] == "dictation-123"
+ assert metric["sizeBytes"] == 240_000
+ assert metric["httpStatus"] == 200
+ assert metric["release"]
+ assert "transcript" not in metric
+ assert "audio" not in metric
+ assert "token" not in metric
+ assert "private" not in record.message
+ assert "secret" not in record.message
+
+
+def test_voice_telemetry_rejects_unknown_events():
+ client = app.test_client()
+ response = client.post(
+ "/api/asr/telemetry",
+ json={"event": "audio_contents", "outcome": "success"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {"error": "invalid_event"}
+
+
+def test_voice_telemetry_accepts_insertion_timing(caplog):
+ client = app.test_client()
+ with caplog.at_level(logging.INFO, logger="vibe.ui_server"):
+ response = client.post(
+ "/api/asr/telemetry",
+ json={
+ "event": "dictation_inserted",
+ "outcome": "success",
+ "providerStage": "finalization",
+ "attemptCount": 1,
+ "stopToInsertionMs": 820,
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ record = next(record for record in caplog.records if record.message.startswith("voice_reliability "))
+ metric = json.loads(record.message.removeprefix("voice_reliability "))
+ assert metric["event"] == "dictation_inserted"
+ assert metric["stopToInsertionMs"] == 820
+
+
+def test_voice_telemetry_rejects_unknown_outcomes():
+ client = app.test_client()
+ for outcome in ("sort-of-worked", ["success"]):
+ response = client.post(
+ "/api/asr/telemetry",
+ json={"event": "segment_transcription", "outcome": outcome},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {"error": "invalid_outcome"}
+
+
+def test_voice_telemetry_rejects_fractional_counts():
+ client = app.test_client()
+ response = client.post(
+ "/api/asr/telemetry",
+ json={
+ "event": "dictation_finalized",
+ "outcome": "success",
+ "segmentCount": 1.5,
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {"error": "invalid_field", "field": "segmentCount"}
+
+
+def test_voice_telemetry_rejects_content_disguised_as_mime_type(caplog):
+ client = app.test_client()
+ with caplog.at_level(logging.INFO, logger="vibe.ui_server"):
+ response = client.post(
+ "/api/asr/telemetry",
+ json={
+ "event": "segment_transcription",
+ "outcome": "failed",
+ "mimeType": "private transcript words",
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {"error": "invalid_field", "field": "mimeType"}
+ assert not any(record.message.startswith("voice_reliability ") for record in caplog.records)
+
+
+def test_voice_telemetry_rejects_content_disguised_as_dictation_id(caplog):
+ client = app.test_client()
+ with caplog.at_level(logging.INFO, logger="vibe.ui_server"):
+ response = client.post(
+ "/api/asr/telemetry",
+ json={
+ "event": "dictation_finalized",
+ "outcome": "failed",
+ "dictationId": "private transcript words",
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {"error": "invalid_field", "field": "dictationId"}
+ assert not any(record.message.startswith("voice_reliability ") for record in caplog.records)
+
+
+def test_voice_telemetry_rejects_non_object_payload():
+ client = app.test_client()
+ response = client.post(
+ "/api/asr/telemetry",
+ json=["segment_transcription"],
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {"error": "invalid_payload"}
diff --git a/tests/test_ui_server_voice_transcription.py b/tests/test_ui_server_voice_transcription.py
new file mode 100644
index 000000000..a4983ed2c
--- /dev/null
+++ b/tests/test_ui_server_voice_transcription.py
@@ -0,0 +1,233 @@
+from __future__ import annotations
+
+import base64
+from types import SimpleNamespace
+
+from config.v2_config import AudioAsrConfig, RemoteAccessConfig, VibeCloudRemoteAccessConfig
+from core.audio_asr import (
+ AudioAsrEmptyTranscriptError,
+ AudioAsrService,
+ AudioAsrTimeoutError,
+ AudioAsrUnavailableError,
+)
+from tests.ui_server_test_helpers import csrf_headers
+from vibe.ui_server import app
+
+
+def test_asr_status_exposes_the_configured_file_limit(monkeypatch):
+ config = SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True, max_file_bytes=160_044),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ )
+ monkeypatch.setattr("core.services.settings.load_config", lambda: config)
+ monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
+ client = app.test_client()
+
+ response = client.get("/api/asr/status")
+
+ assert response.status_code == 200
+ assert response.get_json() == {"available": True, "max_file_bytes": 160_044}
+
+ config.audio_asr.max_file_bytes = 160_043
+ response = client.get("/api/asr/status")
+ assert response.get_json() == {"available": False, "max_file_bytes": 160_043}
+
+
+def test_asr_transcribe_preserves_compatibility_timeout(monkeypatch):
+ async def timeout(
+ _self,
+ _attachments,
+ *,
+ raise_on_empty=False,
+ raise_on_timeout=False,
+ raise_on_unavailable=False,
+ timeout_seconds=None,
+ ):
+ assert raise_on_empty is True
+ assert raise_on_timeout is True
+ assert raise_on_unavailable is True
+ assert timeout_seconds == 120.0
+ raise AudioAsrTimeoutError("timed out")
+
+ monkeypatch.setattr(
+ "core.services.settings.load_config",
+ lambda: SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ ),
+ )
+ monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
+ monkeypatch.setattr(AudioAsrService, "transcribe_attachments", timeout)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/asr/transcribe",
+ json={
+ "name": "voice.webm",
+ "mime": "audio/webm",
+ "data": base64.b64encode(b"audio").decode(),
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 504
+ assert response.get_json() == {"error": "transcription_timeout"}
+
+
+def test_asr_transcribe_preserves_empty_transcript_classification(monkeypatch):
+ async def empty(
+ _self,
+ _attachments,
+ *,
+ raise_on_empty=False,
+ raise_on_timeout=False,
+ raise_on_unavailable=False,
+ timeout_seconds=None,
+ ):
+ assert raise_on_empty is True
+ assert raise_on_timeout is True
+ assert raise_on_unavailable is True
+ assert timeout_seconds == 120.0
+ raise AudioAsrEmptyTranscriptError("empty")
+
+ monkeypatch.setattr(
+ "core.services.settings.load_config",
+ lambda: SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ ),
+ )
+ monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
+ monkeypatch.setattr(AudioAsrService, "transcribe_attachments", empty)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/asr/transcribe",
+ json={
+ "name": "voice.webm",
+ "mime": "audio/webm",
+ "data": base64.b64encode(b"audio").decode(),
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 422
+ assert response.get_json() == {"error": "transcription_empty"}
+
+
+def test_asr_transcribe_preserves_configured_size_rejection(monkeypatch):
+ transcribe_called = False
+
+ async def transcribe(
+ _self,
+ _attachments,
+ *,
+ raise_on_empty=False,
+ raise_on_timeout=False,
+ raise_on_unavailable=False,
+ timeout_seconds=None,
+ ):
+ nonlocal transcribe_called
+ transcribe_called = True
+ return []
+
+ monkeypatch.setattr(
+ "core.services.settings.load_config",
+ lambda: SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True, max_file_bytes=4),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ ),
+ )
+ monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
+ monkeypatch.setattr(AudioAsrService, "transcribe_attachments", transcribe)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/asr/transcribe",
+ json={
+ "name": "voice.webm",
+ "mime": "audio/webm",
+ "data": base64.b64encode(b"audio").decode(),
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 413
+ assert response.get_json() == {"error": "file_too_large"}
+ assert transcribe_called is False
+
+
+def test_asr_transcribe_preserves_provider_unavailable_classification(monkeypatch):
+ async def unavailable(
+ _self,
+ _attachments,
+ *,
+ raise_on_empty=False,
+ raise_on_timeout=False,
+ raise_on_unavailable=False,
+ timeout_seconds=None,
+ ):
+ assert raise_on_empty is True
+ assert raise_on_timeout is True
+ assert raise_on_unavailable is True
+ assert timeout_seconds == 120.0
+ raise AudioAsrUnavailableError("unavailable")
+
+ monkeypatch.setattr(
+ "core.services.settings.load_config",
+ lambda: SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=True,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ ),
+ )
+ monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
+ monkeypatch.setattr(AudioAsrService, "transcribe_attachments", unavailable)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/asr/transcribe",
+ json={
+ "name": "voice.webm",
+ "mime": "audio/webm",
+ "data": base64.b64encode(b"audio").decode(),
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 503
+ assert response.get_json() == {"error": "asr_unavailable"}
diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
index f8065949b..4d3d416ff 100644
--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
@@ -7,6 +7,8 @@ import { describe, expect, it } from 'vitest';
import en from '../../i18n/en.json';
import type { WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import { ToastProvider } from '../../context/ToastContext';
+import { isVoiceControlDisabled } from '../../lib/voiceRecording';
import { ChatHeaderBar, MessageRow } from './ChatPage';
import { Composer } from './Composer';
import { QuickReplies } from './QuickReplies';
@@ -32,7 +34,9 @@ void i18n.use(initReactI18next).init({
const render = (ui: ReactElement) =>
renderToStaticMarkup(
<I18nextProvider i18n={i18n}>
- <MemoryRouter>{ui}</MemoryRouter>
+ <ToastProvider>
+ <MemoryRouter>{ui}</MemoryRouter>
+ </ToastProvider>
</I18nextProvider>,
);
@@ -341,6 +345,12 @@ describe('a disabled composer has no live-turn controls', () => {
expect(markup).toContain('disabled=""');
});
+ it('keeps only an active recording Stop control available after archiving', () => {
+ expect(isVoiceControlDisabled(true, true, false)).toBe(false);
+ expect(isVoiceControlDisabled(true, false, false)).toBe(true);
+ expect(isVoiceControlDisabled(true, true, true)).toBe(true);
+ });
+
// The busy branch's sibling "send to queue" button needs no case of its own: it
// is gated on ``canSubmit``, which ``disabled`` already clears, so it never
// rendered here even before this fix.
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 1ffd53374..0ca40fd16 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -1,12 +1,39 @@
-import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
import { useTranslation } from 'react-i18next';
-import { Clock, Loader2, Mic, Paperclip, Plus, Send, Square, Trash2, X } from 'lucide-react';
+import { Clock, Copy, Loader2, Mic, Paperclip, Plus, RotateCcw, Send, Square, Trash2, X } from 'lucide-react';
import clsx from 'clsx';
+import { useToast } from '../../context/ToastContext';
import { apiFetch } from '../../lib/apiFetch';
-import { avibeFetch, primeCloudToken } from '../../lib/avibeFetch';
+import { primeCloudToken } from '../../lib/avibeFetch';
import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';
-import { cn } from '../../lib/utils';
+import { cn, copyTextToClipboard } from '../../lib/utils';
+import {
+ transcribeVoiceSegments,
+ VOICE_SEGMENT_MS,
+ VOICE_TRANSCRIPTION_CONCURRENCY,
+ VoiceTranscriptionQueue,
+ voiceTranscriptFromSegments,
+ type VoiceTranscriptionSegment,
+ VoiceTranscriptionError,
+} from '../../lib/voiceTranscription';
+import {
+ emitVoiceTelemetry,
+ type VoiceTelemetryOutcome,
+} from '../../lib/voiceTelemetry';
+import {
+ deleteMapValueIfCurrent,
+ isVoiceControlDisabled,
+ VoiceRecordingPipeline,
+} from '../../lib/voiceRecording';
import { Button } from '../ui/button';
import {
MentionEditor,
@@ -58,32 +85,168 @@ const UPLOAD_CONCURRENCY = 4;
// files staged in the same tick.
const newLocalId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
-// Transcribe a recorded clip. Prefer a direct upload to avibe.bot (no tunnel
-// relay — the audio doesn't detour through the user's machine); fall back to the
-// local relay endpoint when the cloud token is unavailable (local access / not
-// paired / signed out) or the direct call fails for any reason.
-async function transcribeVoiceBlob(blob: Blob): Promise<string> {
+type VoiceSegment = VoiceTranscriptionSegment & {
+ task: Promise<void>;
+};
+
+type VoiceRecordingSession = {
+ sessionId: string;
+ dictationId: string;
+ abortController: AbortController;
+ segments: VoiceSegment[];
+ status: 'recording' | 'transcribing' | 'failed' | 'ready';
+ startedAt?: number;
+ stoppedAt?: number;
+ backlogAtStop?: number;
+ finalizedSegmentCount?: number;
+ finalizedFailedSegmentCount?: number;
+ retryCount: number;
+ reportedAttemptCount?: number;
+ reportedInsertionAttemptCount?: number;
+ transcript?: string;
+ error?: unknown;
+ captureError?: unknown;
+ finalization?: Promise<void>;
+ transcriptionQueue: VoiceTranscriptionQueue;
+};
+
+// Composer remounts when the user switches chats. Keep pending or retryable
+// audio outside the component; successful finalization retains transcript only.
+const voiceSessionsById = new Map<string, VoiceRecordingSession>();
+
+const newVoiceDictationId = (): string => (
+ globalThis.crypto?.randomUUID?.()
+ ?? `voice-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`
+);
+
+const settleVoiceSession = (session: VoiceRecordingSession) => {
try {
- const form = new FormData();
- form.set('file', blob, 'voice.webm');
- const res = await avibeFetch('/api/cloud/audio/transcriptions', { method: 'POST', body: form });
- if (res.ok) {
- const json = await res.json().catch(() => null);
- if (json?.text) return String(json.text);
- }
- // Non-OK from the cloud → fall through to the local relay below.
- } catch {
- // No cloud token / network error → fall back to the local relay.
+ session.transcript = voiceTranscriptFromSegments(session.segments);
+ session.finalizedSegmentCount = session.segments.length;
+ session.finalizedFailedSegmentCount = session.segments.filter(
+ (segment) => segment.error,
+ ).length;
+ session.segments = [];
+ session.error = undefined;
+ session.status = 'ready';
+ } catch (error) {
+ session.transcript = undefined;
+ session.error = error;
+ session.status = 'failed';
}
- const data = await readFileAsBase64(blob);
- const res = await apiFetch('/api/asr/transcribe', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name: 'voice.webm', mime: blob.type || 'audio/webm', data }),
+};
+
+const finalizeVoiceSession = (session: VoiceRecordingSession): Promise<void> => {
+ if (session.finalization) return session.finalization;
+ session.status = 'transcribing';
+ session.finalization = (async () => {
+ await Promise.all(session.segments.map((segment) => segment.task));
+ if (session.abortController.signal.aborted) {
+ deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);
+ return;
+ }
+ if (session.captureError !== undefined) {
+ session.transcript = undefined;
+ session.error = session.captureError;
+ session.status = 'failed';
+ return;
+ }
+ settleVoiceSession(session);
+ })();
+ return session.finalization;
+};
+
+const retryStoredVoiceSession = (session: VoiceRecordingSession): Promise<void> => {
+ if (session.captureError !== undefined) return Promise.resolve();
+ session.retryCount += 1;
+ session.status = 'transcribing';
+ session.error = undefined;
+ session.finalization = (async () => {
+ await transcribeVoiceSegments(session.segments, {
+ concurrency: VOICE_TRANSCRIPTION_CONCURRENCY,
+ signal: session.abortController.signal,
+ dictationId: session.dictationId,
+ });
+ if (session.abortController.signal.aborted) {
+ deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);
+ return;
+ }
+ settleVoiceSession(session);
+ })();
+ return session.finalization;
+};
+
+const voiceErrorTranslationKey = (error: unknown): string => {
+ if (!(error instanceof VoiceTranscriptionError)) return 'chat.compose.voiceFailed';
+ if (error.code === 'too_large') return 'chat.compose.voiceTooLarge';
+ if (error.code === 'timeout') return 'chat.compose.voiceTimedOut';
+ if (error.code === 'unavailable') return 'chat.compose.voiceUnavailable';
+ if (error.code === 'empty') return 'chat.compose.voiceEmpty';
+ return 'chat.compose.voiceFailed';
+};
+
+const voiceTelemetryOutcome = (error: unknown): VoiceTelemetryOutcome =>
+ error instanceof VoiceTranscriptionError ? error.code : 'failed';
+
+const canRetryVoiceSession = (session: VoiceRecordingSession): boolean =>
+ session.captureError === undefined
+ && !(
+ session.error instanceof VoiceTranscriptionError
+ && session.error.code === 'empty'
+ );
+
+const reportVoiceFinalization = (
+ session: VoiceRecordingSession,
+ outcome: VoiceTelemetryOutcome,
+): void => {
+ const attemptCount = session.retryCount + 1;
+ if (session.reportedAttemptCount === attemptCount) return;
+ emitVoiceTelemetry({
+ event: 'dictation_finalized',
+ outcome,
+ dictationId: session.dictationId,
+ providerStage: 'finalization',
+ attemptCount,
+ segmentCount: session.finalizedSegmentCount ?? session.segments.length,
+ failedSegmentCount: (
+ session.finalizedFailedSegmentCount
+ ?? session.segments.filter((segment) => segment.error).length
+ ),
+ backlogAtStop: session.backlogAtStop,
+ totalDurationMs: session.stoppedAt == null || session.startedAt == null
+ ? undefined
+ : session.stoppedAt - session.startedAt,
+ retry: session.retryCount > 0,
});
- const json = await res.json().catch(() => null);
- return res.ok && json?.text ? String(json.text) : '';
-}
+ session.reportedAttemptCount = attemptCount;
+};
+
+const reportVoiceInsertion = (session: VoiceRecordingSession): void => {
+ const attemptCount = session.retryCount + 1;
+ if (session.reportedInsertionAttemptCount === attemptCount) return;
+ emitVoiceTelemetry({
+ event: 'dictation_inserted',
+ outcome: 'success',
+ dictationId: session.dictationId,
+ providerStage: 'finalization',
+ attemptCount,
+ segmentCount: session.finalizedSegmentCount ?? session.segments.length,
+ backlogAtStop: session.backlogAtStop,
+ totalDurationMs: session.stoppedAt == null || session.startedAt == null
+ ? undefined
+ : session.stoppedAt - session.startedAt,
+ stopToInsertionMs: session.stoppedAt == null
+ ? undefined
+ : Date.now() - session.stoppedAt,
+ retry: session.retryCount > 0,
+ });
+ session.reportedInsertionAttemptCount = attemptCount;
+};
+
+const formatRecordingDuration = (seconds: number): string => {
+ const minutes = Math.floor(seconds / 60);
+ return `${minutes}:${String(seconds % 60).padStart(2, '0')}`;
+};
export interface ComposerProps {
/** Fired with the trimmed text (+ ready attachments) when the user sends.
@@ -160,6 +323,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
onSearchSessions,
}, ref) {
const { t } = useTranslation();
+ const { showToast } = useToast();
const [value, setValue] = useState('');
// The mention editor (Lexical) OWNS its text, so we don't mirror every
// keystroke into ``value`` there — a fast third-party IME (e.g. a voice
@@ -179,19 +343,32 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);
const [asrAvailable, setAsrAvailable] = useState(false);
+ const [asrMaxFileBytes, setAsrMaxFileBytes] = useState<number | null>(null);
const [recording, setRecording] = useState(false);
+ const [recordingSeconds, setRecordingSeconds] = useState(0);
const [transcribing, setTranscribing] = useState(false);
- const recorderRef = useRef<MediaRecorder | null>(null);
- const chunksRef = useRef<Blob[]>([]);
- const streamRef = useRef<MediaStream | null>(null);
+ const [voiceRetainedSession, setVoiceRetainedSession] = useState<VoiceRecordingSession | null>(null);
+ const transcribingRef = useRef(false);
+ const recorderRef = useRef<VoiceRecordingPipeline | null>(null);
+ const recordingSessionRef = useRef<VoiceRecordingSession | null>(null);
+ const recordingStartRef = useRef(false);
+ const recordingTickerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const unmountedRef = useRef(false);
- // Set just before stopping to mean "discard, don't transcribe" (ESC / unmount).
- const abortedRef = useRef(false);
+ const disabledRef = useRef(disabled);
// Upload + voice are scoped to a session (the upload endpoint needs one); the
// home composer leaves them off.
const mediaEnabled = Boolean(sessionId);
+ useLayoutEffect(() => {
+ disabledRef.current = disabled;
+ }, [disabled]);
+
+ const clearRecordingTimers = useCallback(() => {
+ if (recordingTickerRef.current != null) clearInterval(recordingTickerRef.current);
+ recordingTickerRef.current = null;
+ }, []);
+
// Mentions upgrade the plain textarea to a Lexical editor (chat composer only,
// gated on the caller wiring both search sources). The editor owns the rich
// content; ``valueRef`` holds its live serialized marker text for the
@@ -246,6 +423,13 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (!alive) return;
const available = Boolean(data?.available);
setAsrAvailable(available);
+ setAsrMaxFileBytes(
+ typeof data?.max_file_bytes === 'number'
+ && Number.isFinite(data.max_file_bytes)
+ && data.max_file_bytes > 0
+ ? Math.floor(data.max_file_bytes)
+ : null,
+ );
// Prewarm the cloud token so the first recording uploads straight to
// avibe.bot with no mint latency (no-op when the cloud is unavailable).
if (available) primeCloudToken();
@@ -256,8 +440,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
};
}, [mediaEnabled]);
- // Release the mic + suppress post-unmount setState if the composer unmounts
- // mid-recording (it remounts on every session switch).
+ // Finish capture + suppress post-unmount setState if the composer unmounts.
+ // Chat navigation is not a discard action: the session-keyed batch continues
+ // finalizing and is restored when the user returns.
useEffect(() => {
// Reset on setup (StrictMode runs cleanup→setup twice on mount, so a stale
// ``true`` from the first cleanup would otherwise wedge voice input).
@@ -265,19 +450,25 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
return () => {
unmountedRef.current = true;
try {
- recorderRef.current?.stop();
+ if (recordingStartRef.current) {
+ recordingSessionRef.current?.abortController.abort();
+ recorderRef.current?.abort();
+ } else {
+ recorderRef.current?.finish();
+ }
} catch {
/* already stopped */
}
- streamRef.current?.getTracks().forEach((track) => track.stop());
+ clearRecordingTimers();
};
- }, []);
+ }, [clearRecordingTimers]);
// Clear staged attachments when the session changes so a chip uploaded in one
// chat can't ride into another — defense in depth on top of ChatPage keying
// the composer by session.
useEffect(() => {
setAttachments([]);
+ setVoiceRetainedSession(null);
}, [sessionId]);
const removeAttachment = (localId: string) => {
@@ -365,61 +556,277 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
appendText: (text: string) => mentionRef.current?.append(text),
}));
+ const appendVoiceTranscript = useCallback((text: string) => {
+ // Voice input fills the draft and never sends it. Keeping the whole recording
+ // as one append also prevents an intermediate segment from being sent before
+ // the user has finished speaking.
+ if (useMentions) {
+ mentionRef.current?.append(text);
+ } else {
+ const next = valueRef.current ? `${valueRef.current} ${text}` : text;
+ setValue(next);
+ onDraftChange?.(next);
+ }
+ }, [onDraftChange, useMentions]);
+
+ const queueVoiceSegment = (
+ session: VoiceRecordingSession,
+ blob: Blob,
+ durationMs: number,
+ overlapMs?: number,
+ ) => {
+ const segment: VoiceSegment = {
+ blob,
+ durationMs,
+ overlapMs,
+ task: Promise.resolve(),
+ };
+ session.segments.push(segment);
+ segment.task = session.transcriptionQueue.enqueue(segment);
+ };
+
+ const presentVoiceSession = useCallback((session: VoiceRecordingSession) => {
+ const activeHere = (
+ !unmountedRef.current
+ && sessionId === session.sessionId
+ && voiceSessionsById.get(session.sessionId) === session
+ );
+ if (session.status === 'ready' && session.transcript) {
+ reportVoiceFinalization(session, 'success');
+ } else if (session.status === 'failed') {
+ reportVoiceFinalization(session, voiceTelemetryOutcome(session.error));
+ }
+ if (!activeHere) return;
+
+ if (session.status === 'ready' && session.transcript) {
+ if (disabledRef.current) {
+ setVoiceRetainedSession(session);
+ return;
+ }
+ voiceSessionsById.delete(session.sessionId);
+ setVoiceRetainedSession(null);
+ appendVoiceTranscript(session.transcript);
+ reportVoiceInsertion(session);
+ return;
+ }
+ if (session.status === 'failed') {
+ setVoiceRetainedSession(session);
+ showToast(t(voiceErrorTranslationKey(session.error)), 'error');
+ }
+ }, [appendVoiceTranscript, sessionId, showToast, t]);
+
+ const finishVoiceSession = async (session: VoiceRecordingSession) => {
+ const activeHere = !unmountedRef.current && sessionId === session.sessionId;
+ if (activeHere) {
+ transcribingRef.current = true;
+ setTranscribing(true);
+ setVoiceRetainedSession(session);
+ }
+ try {
+ await finalizeVoiceSession(session);
+ presentVoiceSession(session);
+ } finally {
+ if (recordingSessionRef.current === session) recordingSessionRef.current = null;
+ if (activeHere) {
+ transcribingRef.current = false;
+ if (!unmountedRef.current) setTranscribing(false);
+ }
+ }
+ };
+
+ const retryVoiceSession = async (session: VoiceRecordingSession) => {
+ if (unmountedRef.current || transcribingRef.current) return;
+ transcribingRef.current = true;
+ setTranscribing(true);
+ try {
+ await retryStoredVoiceSession(session);
+ presentVoiceSession(session);
+ } finally {
+ transcribingRef.current = false;
+ if (!unmountedRef.current) setTranscribing(false);
+ }
+ };
+
+ const discardVoiceSession = useCallback((session: VoiceRecordingSession) => {
+ session.abortController.abort();
+ deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);
+ setVoiceRetainedSession((current) => (current === session ? null : current));
+ }, []);
+
+ const copyReadyVoiceTranscript = useCallback(async (session: VoiceRecordingSession) => {
+ if (!session.transcript) return;
+ if (await copyTextToClipboard(session.transcript)) {
+ showToast(t('chat.compose.voiceTranscriptCopied'), 'success');
+ }
+ }, [showToast, t]);
+
+ useEffect(() => {
+ if (!sessionId) return;
+ let alive = true;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const restore = () => {
+ if (!alive) return;
+ const session = voiceSessionsById.get(sessionId);
+ if (!session) return;
+ if (session.status === 'recording') {
+ timer = setTimeout(restore, 50);
+ return;
+ }
+ if (session.status === 'transcribing' && session.finalization) {
+ transcribingRef.current = true;
+ setTranscribing(true);
+ setVoiceRetainedSession(session);
+ void session.finalization.finally(() => {
+ if (!alive) return;
+ transcribingRef.current = false;
+ setTranscribing(false);
+ presentVoiceSession(session);
+ });
+ return;
+ }
+ presentVoiceSession(session);
+ };
+ restore();
+ return () => {
+ alive = false;
+ if (timer != null) clearTimeout(timer);
+ };
+ }, [presentVoiceSession, sessionId]);
+
const startRecording = async () => {
+ if (
+ !sessionId
+ || recordingStartRef.current
+ || voiceSessionsById.has(sessionId)
+ ) {
+ return;
+ }
+ recordingStartRef.current = true;
+ let stream: MediaStream | null = null;
+ let startingPipeline: VoiceRecordingPipeline | null = null;
+ let startingSession: VoiceRecordingSession | null = null;
try {
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- streamRef.current = stream;
- const recorder = new MediaRecorder(stream);
- chunksRef.current = [];
- recorder.ondataavailable = (e) => {
- if (e.data.size) chunksRef.current.push(e.data);
- };
- recorder.onstop = async () => {
+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ if (unmountedRef.current || disabledRef.current) {
stream.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
- const aborted = abortedRef.current;
- abortedRef.current = false;
- if (unmountedRef.current) return;
- setRecording(false);
- // ESC (or unmount) aborted the recording → mic released above, discard it.
- if (aborted) return;
- const blob = new Blob(chunksRef.current, { type: recorder.mimeType || 'audio/webm' });
- if (!blob.size) return;
- setTranscribing(true);
- try {
- const text = await transcribeVoiceBlob(blob);
- if (!unmountedRef.current && text) {
- // Append the transcript into the box (never auto-send) via the draft
- // path so it persists if the user switches away before sending.
- if (useMentions) {
- mentionRef.current?.append(text);
- } else {
- const next = valueRef.current ? `${valueRef.current} ${text}` : text;
- update(next);
+ return;
+ }
+
+ const abortController = new AbortController();
+ const dictationId = newVoiceDictationId();
+ const session: VoiceRecordingSession = {
+ sessionId,
+ dictationId,
+ abortController,
+ segments: [],
+ status: 'recording',
+ retryCount: 0,
+ transcriptionQueue: new VoiceTranscriptionQueue({
+ concurrency: VOICE_TRANSCRIPTION_CONCURRENCY,
+ signal: abortController.signal,
+ dictationId,
+ }),
+ };
+ startingSession = session;
+ const pipeline = new VoiceRecordingPipeline({
+ stream,
+ segmentMs: VOICE_SEGMENT_MS,
+ maxFileBytes: asrMaxFileBytes,
+ onSegment: (blob, metadata) => queueVoiceSegment(
+ session,
+ blob,
+ metadata.durationMs,
+ metadata.overlapMs,
+ ),
+ onStopRequested: (reason, metadata) => {
+ if (reason === 'abort') return;
+ session.stoppedAt = metadata.requestedAt;
+ session.backlogAtStop = session.segments.filter(
+ (segment) => !segment.text && !segment.error,
+ ).length;
+ },
+ onError: (error) => {
+ session.captureError = error;
+ if (!voiceSessionsById.has(session.sessionId)) {
+ voiceSessionsById.set(session.sessionId, session);
+ }
+ },
+ onStopped: (reason, metadata) => {
+ if (recorderRef.current === pipeline) recorderRef.current = null;
+ if (recordingSessionRef.current === session) recordingSessionRef.current = null;
+ clearRecordingTimers();
+ if (!unmountedRef.current) setRecording(false);
+
+ if (reason === 'abort') {
+ session.abortController.abort();
+ deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);
+ return;
+ }
+ session.backlogAtStop = (session.backlogAtStop ?? 0) + metadata.pendingSegmentCount;
+ if (!session.segments.length && session.captureError === undefined) {
+ reportVoiceFinalization(session, 'empty');
+ if (!unmountedRef.current && sessionId === session.sessionId) {
+ showToast(t('chat.compose.voiceEmpty'), 'error');
}
+ deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);
+ return;
}
- } finally {
- if (!unmountedRef.current) setTranscribing(false);
- }
- };
- abortedRef.current = false;
- recorderRef.current = recorder;
- recorder.start();
+ void finishVoiceSession(session);
+ },
+ });
+ startingPipeline = pipeline;
+ recordingSessionRef.current = session;
+ recorderRef.current = pipeline;
+ const captureActive = await pipeline.start();
+ if (!captureActive) return;
+ if (unmountedRef.current || disabledRef.current) {
+ pipeline.abort();
+ return;
+ }
+ const startedAt = Date.now();
+ session.startedAt = startedAt;
+
+ const previous = voiceSessionsById.get(sessionId);
+ if (previous) {
+ // A retained batch may have settled while microphone setup was pending.
+ // Preserve it until the user explicitly retries or discards it.
+ pipeline.abort();
+ return;
+ }
+ voiceSessionsById.set(sessionId, session);
+ setVoiceRetainedSession(null);
+ setRecordingSeconds(0);
+ recordingTickerRef.current = setInterval(() => {
+ setRecordingSeconds(Math.floor((Date.now() - startedAt) / 1000));
+ }, 1000);
setRecording(true);
} catch {
- // getUserMedia may have handed us a live stream before MediaRecorder
- // construction / start() threw — release it so the mic doesn't stay on.
- streamRef.current?.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
- setRecording(false);
+ // getUserMedia may have handed us a live stream before capture setup
+ // threw. Release it so the mic does not stay on.
+ if (recorderRef.current === startingPipeline) recorderRef.current = null;
+ if (recordingSessionRef.current === startingSession) recordingSessionRef.current = null;
+ clearRecordingTimers();
+ stream?.getTracks().forEach((track) => track.stop());
+ if (!unmountedRef.current) {
+ setRecording(false);
+ showToast(t(
+ stream
+ ? 'chat.compose.voiceStartFailed'
+ : 'chat.compose.voicePermissionFailed',
+ ), 'error');
+ }
+ } finally {
+ recordingStartRef.current = false;
}
};
- const stopRecording = () => recorderRef.current?.stop(); // stop → transcribe
- const abortRecording = () => {
- abortedRef.current = true;
- recorderRef.current?.stop(); // stop → discard (onstop honors the abort flag)
- };
+ const stopRecording = useCallback(() => {
+ recorderRef.current?.finish();
+ }, []);
+ const abortRecording = useCallback(() => {
+ recordingSessionRef.current?.abortController.abort();
+ recorderRef.current?.abort();
+ }, []);
const toggleRecording = () => {
if (recording) stopRecording();
else void startRecording();
@@ -436,7 +843,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
- }, [recording]);
+ }, [abortRecording, recording]);
const trimmed = value.trim();
const readyAttachments = attachments.filter((a) => a.status === 'ready');
@@ -449,7 +856,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// reads the files); blocked while an upload is still in flight, and while
// recording so neither the Send button nor the Enter key can fire mid-record.
const canSubmit =
- (hasComposerText || readyAttachments.length > 0) && !uploading && !disabled && !recording;
+ (hasComposerText || readyAttachments.length > 0)
+ && !uploading
+ && !disabled
+ && !recording
+ && !transcribing;
// ``busy && disabled`` is an incoherent pair for ANY caller: ``disabled`` means
// this composer may not act on the session, yet the busy branch renders an
// ENABLED Stop button (it never consulted ``disabled``) and its "working"
@@ -560,6 +971,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
ref={fileInputRef}
type="file"
multiple
+ disabled={disabled || recording}
className="hidden"
onChange={(e) => {
if (e.target.files?.length) void uploadFiles(Array.from(e.target.files));
@@ -573,34 +985,93 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
variant="ghost"
size="icon"
onClick={() => fileInputRef.current?.click()}
- // A disabled composer cannot send, so staging attachments (or
- // recording) is a dead end — gate both media affordances too.
- disabled={disabled}
+ // A disabled composer cannot send, so staging attachments is a
+ // dead end. Opening a native picker can also hide the page, so
+ // keep it unavailable until an active recording has stopped.
+ disabled={disabled || recording}
aria-label={t('chat.compose.attach')}
className="h-9 w-7 shrink-0"
>
<Plus className="size-4" />
</Button>
{asrAvailable && (
- // While recording this is the Stop control: tap to finish +
- // transcribe (the discard path is the trash button by Send, or ESC).
- <Button
- type="button"
- variant={recording ? 'secondary' : 'ghost'}
- size="icon"
- onClick={toggleRecording}
- disabled={transcribing || disabled}
- aria-label={t(recording ? 'chat.compose.stopRecording' : 'chat.compose.voice')}
- className={clsx('h-9 w-7 shrink-0', recording && 'animate-pulse')}
- >
- {transcribing ? (
- <Loader2 className="size-4 animate-spin" />
- ) : recording ? (
- <Square className="size-4" />
- ) : (
- <Mic className="size-4" />
+ <>
+ {/* While recording this is the Stop control: tap to finish +
+ transcribe (the discard path is the trash button by Send, or ESC). */}
+ <Button
+ type="button"
+ variant={recording ? 'secondary' : 'ghost'}
+ size="icon"
+ onClick={toggleRecording}
+ disabled={isVoiceControlDisabled(
+ disabled,
+ recording,
+ transcribing,
+ Boolean(voiceRetainedSession),
+ )}
+ aria-label={t(recording ? 'chat.compose.stopRecording' : 'chat.compose.voice')}
+ className={clsx('h-9 w-7 shrink-0', recording && 'animate-pulse')}
+ >
+ {transcribing ? (
+ <Loader2 className="size-4 animate-spin" />
+ ) : recording ? (
+ <Square className="size-4" />
+ ) : (
+ <Mic className="size-4" />
+ )}
+ </Button>
+ {recording && (
+ <span
+ className="flex h-9 w-10 items-center justify-center text-xs tabular-nums text-muted"
+ aria-live="off"
+ >
+ {formatRecordingDuration(recordingSeconds)}
+ </span>
)}
- </Button>
+ </>
+ )}
+ {/* Recovery remains available even when the ASR status request fails:
+ Copy and Discard are local, and Retry can explain unavailability. */}
+ {voiceRetainedSession && !recording && (
+ <>
+ {voiceRetainedSession.status === 'ready' ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => void copyReadyVoiceTranscript(voiceRetainedSession)}
+ aria-label={t('chat.compose.voiceCopyTranscript')}
+ title={t('chat.compose.voiceCopyTranscript')}
+ className="h-9 w-7 shrink-0"
+ >
+ <Copy className="size-4" />
+ </Button>
+ ) : canRetryVoiceSession(voiceRetainedSession) ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => void retryVoiceSession(voiceRetainedSession)}
+ disabled={transcribing}
+ aria-label={t('chat.compose.voiceRetry')}
+ title={t('chat.compose.voiceRetry')}
+ className="h-9 w-7 shrink-0"
+ >
+ <RotateCcw className="size-4" />
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ variant="destructive-soft"
+ size="icon"
+ onClick={() => discardVoiceSession(voiceRetainedSession)}
+ aria-label={t('chat.compose.voiceDiscard')}
+ title={t('chat.compose.voiceDiscard')}
+ className="h-9 w-7 shrink-0"
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ </>
)}
</div>
)}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 958f3e5ac..d61c464b4 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2958,6 +2958,17 @@
"voice": "Voice input",
"stopRecording": "Stop recording",
"cancelRecording": "Cancel recording",
+ "voiceRetry": "Retry transcription",
+ "voiceCopyTranscript": "Copy recovered transcript",
+ "voiceTranscriptCopied": "Recovered transcript copied",
+ "voiceDiscard": "Discard recording",
+ "voiceFailed": "Voice transcription failed. Your recording is available to retry.",
+ "voiceTimedOut": "Voice transcription timed out. Your recording is available to retry.",
+ "voiceUnavailable": "Voice transcription is temporarily unavailable.",
+ "voiceTooLarge": "This recording is too large to transcribe.",
+ "voiceEmpty": "No speech was detected in this recording.",
+ "voicePermissionFailed": "Microphone access failed. Check your browser permission and try again.",
+ "voiceStartFailed": "Voice recording could not start in this browser. Reload the page or try a supported browser.",
"removeAttachment": "Remove",
"dropOverlay": "Drop files to attach"
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4e4a28655..b860b6f43 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2958,6 +2958,17 @@
"voice": "语音输入",
"stopRecording": "停止录音",
"cancelRecording": "取消录音",
+ "voiceRetry": "重试转写",
+ "voiceCopyTranscript": "复制已恢复的文字",
+ "voiceTranscriptCopied": "已复制恢复的文字",
+ "voiceDiscard": "丢弃录音",
+ "voiceFailed": "语音转写失败,录音已保留,可以重试。",
+ "voiceTimedOut": "语音转写超时,录音已保留,可以重试。",
+ "voiceUnavailable": "语音转写暂时不可用。",
+ "voiceTooLarge": "这段录音太大,无法转写。",
+ "voiceEmpty": "这段录音中没有检测到语音。",
+ "voicePermissionFailed": "无法使用麦克风,请检查浏览器权限后重试。",
+ "voiceStartFailed": "当前浏览器无法启动语音录制,请刷新页面或更换支持的浏览器。",
"removeAttachment": "移除",
"dropOverlay": "拖放文件以添加"
},
diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.ts
index be044baee..6b342d642 100644
--- a/ui/src/lib/apiFetch.test.ts
+++ b/ui/src/lib/apiFetch.test.ts
@@ -4,7 +4,9 @@ const deferRemoteAuthRedirect = vi.hoisted(() => vi.fn());
vi.mock('./remoteAuth', () => ({ deferRemoteAuthRedirect }));
-import { apiFetch } from './apiFetch';
+import {
+ apiFetch,
+} from './apiFetch';
describe('apiFetch remote auth recovery', () => {
beforeEach(() => {
@@ -15,6 +17,7 @@ describe('apiFetch remote auth recovery', () => {
});
afterEach(() => {
+ vi.useRealTimers();
vi.unstubAllGlobals();
vi.clearAllMocks();
});
@@ -45,4 +48,73 @@ describe('apiFetch remote auth recovery', () => {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(deferRemoteAuthRedirect).not.toHaveBeenCalled();
});
+
+ it('honors the request signal while a shared CSRF request is pending', async () => {
+ let resolveCsrf!: (response: Response) => void;
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL) =>
+ new Promise<Response>((resolve) => {
+ expect(input).toBe('/api/csrf-token');
+ resolveCsrf = resolve;
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const controller = new AbortController();
+ const request = apiFetch('/api/asr/transcribe', {
+ method: 'POST',
+ signal: controller.signal,
+ });
+
+ controller.abort(new DOMException('transcription timed out', 'TimeoutError'));
+
+ await expect(request).rejects.toMatchObject({ name: 'TimeoutError' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ // Let the shared mint settle so it cannot leak into later tests.
+ resolveCsrf(Response.json({ csrf_token: 'token' }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+ it('does not impose the voice deadline on callers without a signal', async () => {
+ vi.useFakeTimers();
+ let resolveCsrf!: (response: Response) => void;
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(
+ () => new Promise<Response>((resolve) => {
+ resolveCsrf = resolve;
+ }),
+ )
+ .mockResolvedValueOnce(Response.json({ ok: true }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const request = apiFetch('/api/settings', { method: 'POST' });
+ await vi.advanceTimersByTimeAsync(4_001);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ resolveCsrf(Response.json({ csrf_token: 'token' }));
+ await expect(request).resolves.toMatchObject({ status: 200 });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('evicts a stalled shared CSRF fetch after a deadline-bound caller aborts', async () => {
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => new Promise<Response>(() => undefined))
+ .mockResolvedValueOnce(Response.json({ csrf_token: 'fresh-token' }))
+ .mockResolvedValueOnce(Response.json({ text: 'ok' }));
+ vi.stubGlobal('fetch', fetchMock);
+ const controller = new AbortController();
+
+ const stalled = apiFetch('/api/asr/transcribe', {
+ method: 'POST',
+ signal: controller.signal,
+ });
+ const stalledResult = expect(stalled).rejects.toMatchObject({ name: 'TimeoutError' });
+ controller.abort(new DOMException('transcription timed out', 'TimeoutError'));
+
+ await stalledResult;
+ await expect(apiFetch('/api/asr/transcribe', { method: 'POST' })).resolves.toMatchObject({
+ status: 200,
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
});
diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.ts
index 6936dba98..bf2380693 100644
--- a/ui/src/lib/apiFetch.ts
+++ b/ui/src/lib/apiFetch.ts
@@ -36,18 +36,63 @@ async function fetchCsrfToken(): Promise<string> {
return token;
}
-export async function ensureCsrfToken(): Promise<string> {
+const startCsrfTokenFetch = (): Promise<string> => {
+ const pending = fetchCsrfToken();
+ csrfTokenPromise = pending;
+ void pending.then(
+ () => {
+ if (csrfTokenPromise === pending) csrfTokenPromise = null;
+ },
+ () => {
+ if (csrfTokenPromise === pending) csrfTokenPromise = null;
+ },
+ );
+ return pending;
+};
+
+const waitForSignal = <Value>(promise: Promise<Value>, signal?: AbortSignal): Promise<Value> => {
+ if (!signal) return promise;
+ if (signal.aborted) {
+ return Promise.reject(signal.reason ?? new DOMException('request aborted', 'AbortError'));
+ }
+ return new Promise<Value>((resolve, reject) => {
+ const onAbort = () => {
+ reject(signal.reason ?? new DOMException('request aborted', 'AbortError'));
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ promise.then(
+ (value) => {
+ signal.removeEventListener('abort', onAbort);
+ resolve(value);
+ },
+ (error) => {
+ signal.removeEventListener('abort', onAbort);
+ reject(error);
+ },
+ );
+ });
+};
+
+export async function ensureCsrfToken(signal?: AbortSignal): Promise<string> {
const existing = readCookie(CSRF_COOKIE_NAME);
if (existing) {
return existing;
}
if (!csrfTokenPromise) {
- csrfTokenPromise = fetchCsrfToken().finally(() => {
+ startCsrfTokenFetch();
+ }
+ const pending = csrfTokenPromise!;
+ try {
+ return await waitForSignal(pending, signal);
+ } catch (error) {
+ // A deadline-bound caller must be able to retry even if the shared fetch
+ // ignores cancellation. Other callers already waiting on it remain intact.
+ if (signal?.aborted && csrfTokenPromise === pending) {
csrfTokenPromise = null;
- });
+ }
+ throw error;
}
- return csrfTokenPromise;
}
export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
@@ -63,7 +108,7 @@ export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {})
}
if (MUTATING_METHODS.has(method)) {
- const token = await ensureCsrfToken();
+ const token = await ensureCsrfToken(init.signal ?? undefined);
headers.set(CSRF_HEADER_NAME, token);
}
diff --git a/ui/src/lib/avibeFetch.test.ts b/ui/src/lib/avibeFetch.test.ts
new file mode 100644
index 000000000..627f21d10
--- /dev/null
+++ b/ui/src/lib/avibeFetch.test.ts
@@ -0,0 +1,156 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./apiFetch', () => ({
+ apiFetch: vi.fn(),
+}));
+
+const loadModules = async () => {
+ const { apiFetch } = await import('./apiFetch');
+ const avibe = await import('./avibeFetch');
+ return { ...avibe, apiFetch: vi.mocked(apiFetch) };
+};
+
+beforeEach(() => {
+ vi.resetModules();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('avibeFetch', () => {
+ it('honors the caller deadline while a shared token request is pending', async () => {
+ const { apiFetch, avibeFetch } = await loadModules();
+ apiFetch.mockReset();
+ apiFetch.mockImplementation(() => new Promise<Response>(() => undefined));
+ const controller = new AbortController();
+ const request = avibeFetch('/api/cloud/audio/transcriptions', {
+ signal: controller.signal,
+ });
+
+ controller.abort(new DOMException('timed out', 'TimeoutError'));
+
+ await expect(request).rejects.toMatchObject({ name: 'TimeoutError' });
+ expect(apiFetch).toHaveBeenCalledWith('/api/cloud/token', {
+ signal: expect.any(AbortSignal),
+ });
+ });
+
+ it('evicts a stalled shared mint after its caller-independent deadline', async () => {
+ vi.useFakeTimers();
+ const {
+ apiFetch,
+ avibeFetch,
+ CLOUD_TOKEN_MINT_TIMEOUT_MS,
+ CloudUnavailableError,
+ } = await loadModules();
+ expect(CLOUD_TOKEN_MINT_TIMEOUT_MS).toBeLessThanOrEqual(10_000);
+ apiFetch.mockReset();
+ apiFetch
+ // Intentionally ignore abort to prove the shared promise itself expires.
+ .mockImplementationOnce(() => new Promise<Response>(() => undefined))
+ .mockResolvedValueOnce(Response.json({
+ token: 'recovered',
+ base_url: 'https://example.test',
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ }));
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ text: 'ok' })));
+
+ const stalled = avibeFetch('/api/cloud/audio/transcriptions');
+ const stalledResult = expect(stalled).rejects.toBeInstanceOf(CloudUnavailableError);
+ await vi.advanceTimersByTimeAsync(CLOUD_TOKEN_MINT_TIMEOUT_MS);
+
+ await stalledResult;
+ await expect(avibeFetch('/api/cloud/audio/transcriptions')).resolves.toMatchObject({
+ status: 200,
+ });
+ expect(apiFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not let one waiter abort the shared token request', async () => {
+ const { apiFetch, avibeFetch } = await loadModules();
+ let resolveToken!: (response: Response) => void;
+ apiFetch.mockReset();
+ apiFetch.mockImplementation(
+ () => new Promise<Response>((resolve) => {
+ resolveToken = resolve;
+ }),
+ );
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ text: 'ok' })));
+ const firstController = new AbortController();
+ const secondController = new AbortController();
+
+ const first = avibeFetch('/api/cloud/audio/transcriptions', {
+ signal: firstController.signal,
+ });
+ const second = avibeFetch('/api/cloud/audio/transcriptions', {
+ signal: secondController.signal,
+ });
+ firstController.abort(new DOMException('first timed out', 'TimeoutError'));
+ await expect(first).rejects.toMatchObject({ name: 'TimeoutError' });
+
+ resolveToken(Response.json({
+ token: 'shared',
+ base_url: 'https://example.test',
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ }));
+
+ await expect(second).resolves.toMatchObject({ status: 200 });
+ expect(apiFetch).toHaveBeenCalledTimes(1);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks token refresh failure as post-upload unavailability', async () => {
+ const { apiFetch, avibeFetch, CloudUnavailableError } = await loadModules();
+ apiFetch.mockReset();
+ apiFetch
+ .mockResolvedValueOnce(Response.json({
+ token: 'initial',
+ base_url: 'https://example.test',
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ }))
+ .mockResolvedValueOnce(new Response(null, { status: 503 }));
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(
+ new Response(null, { status: 401 }),
+ ));
+
+ const error = await avibeFetch('/api/cloud/audio/transcriptions').catch((cause) => cause);
+
+ expect(error).toBeInstanceOf(CloudUnavailableError);
+ expect(error).toMatchObject({ uploadStarted: true });
+ expect(apiFetch).toHaveBeenCalledTimes(2);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('exposes both HTTP attempts around an internal 401 refresh', async () => {
+ const { apiFetch, avibeFetch } = await loadModules();
+ const onAttempt = vi.fn();
+ apiFetch.mockReset();
+ apiFetch
+ .mockResolvedValueOnce(Response.json({
+ token: 'initial',
+ base_url: 'https://example.test',
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ }))
+ .mockResolvedValueOnce(Response.json({
+ token: 'refreshed',
+ base_url: 'https://example.test',
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ }));
+ vi.stubGlobal('fetch', vi.fn()
+ .mockResolvedValueOnce(new Response(null, { status: 401 }))
+ .mockResolvedValueOnce(Response.json({ text: 'ok' })));
+
+ await expect(avibeFetch('/api/cloud/audio/transcriptions', {
+ onAttempt,
+ })).resolves.toMatchObject({ status: 200 });
+
+ expect(onAttempt.mock.calls.map(([event]) => event)).toEqual([
+ { phase: 'started', attempt: 1 },
+ { phase: 'response', attempt: 1, status: 401, elapsedMs: expect.any(Number) },
+ { phase: 'started', attempt: 2 },
+ { phase: 'response', attempt: 2, status: 200, elapsedMs: expect.any(Number) },
+ ]);
+ });
+});
diff --git a/ui/src/lib/avibeFetch.ts b/ui/src/lib/avibeFetch.ts
index 544b18b59..641ba6475 100644
--- a/ui/src/lib/avibeFetch.ts
+++ b/ui/src/lib/avibeFetch.ts
@@ -8,17 +8,32 @@
// - refresh-ahead: re-mint at ~half the remaining lifetime, and on focus/online,
// so the token is always warm when the user acts (never a mint on the hot path)
// - single-flight: concurrent callers share one /api/cloud/token request
-// - 401 safety net: re-mint once + retry (rare; covers revoke / clock skew)
-// - fallback: throws CloudUnavailableError when no token can be obtained (local
-// access / not paired / not signed in) so callers use the local relay instead
+// - 401 safety net: re-mint once + retry (rare; covers revoke / clock skew);
+// refresh failure is final because the request body was already submitted
+// - fallback: before any cloud request, throws CloudUnavailableError when no
+// token can be obtained so callers may use the local relay instead
import { apiFetch } from './apiFetch';
export type CloudToken = { token: string; baseUrl: string; expiresAt: number };
+export type AvibeFetchAttemptEvent =
+ | { phase: 'started'; attempt: number }
+ | { phase: 'response'; attempt: number; status: number; elapsedMs: number };
+
+export type AvibeFetchRequestInit = RequestInit & {
+ onAttempt?: (event: AvibeFetchAttemptEvent) => void;
+};
+
export class CloudUnavailableError extends Error {
- constructor(message = 'cloud_unavailable') {
+ readonly uploadStarted: boolean;
+
+ constructor(
+ message = 'cloud_unavailable',
+ options: { uploadStarted?: boolean } = {},
+ ) {
super(message);
this.name = 'CloudUnavailableError';
+ this.uploadStarted = options.uploadStarted ?? false;
}
}
@@ -27,6 +42,9 @@ export class CloudUnavailableError extends Error {
const EXPIRY_SKEW_MS = 30_000;
// Floor for the background refresh delay so a near-expired token doesn't busy-loop.
const MIN_REFRESH_DELAY_MS = 30_000;
+// Token minting is a local control-plane request. Bound the shared request
+// independently so one hung prewarm cannot poison every later caller.
+export const CLOUD_TOKEN_MINT_TIMEOUT_MS = 4_000;
let current: CloudToken | null = null;
let inflight: Promise<CloudToken | null> | null = null;
@@ -65,8 +83,20 @@ const bindActivityListeners = (): void => {
const mint = (): Promise<CloudToken | null> => {
if (inflight) return inflight;
inflight = (async () => {
+ const controller = new AbortController();
+ const timeoutError = new DOMException('cloud token mint timed out', 'TimeoutError');
+ let timeout: ReturnType<typeof setTimeout> | null = null;
+ const deadline = new Promise<never>((_resolve, reject) => {
+ timeout = globalThis.setTimeout(() => {
+ controller.abort(timeoutError);
+ reject(timeoutError);
+ }, CLOUD_TOKEN_MINT_TIMEOUT_MS);
+ });
try {
- const res = await apiFetch('/api/cloud/token');
+ const res = await Promise.race([
+ apiFetch('/api/cloud/token', { signal: controller.signal }),
+ deadline,
+ ]);
if (!res.ok) {
current = null;
return null;
@@ -88,6 +118,7 @@ const mint = (): Promise<CloudToken | null> => {
bindActivityListeners();
return current;
} finally {
+ if (timeout != null) globalThis.clearTimeout(timeout);
inflight = null;
}
})();
@@ -97,6 +128,29 @@ const mint = (): Promise<CloudToken | null> => {
const ensureToken = (): Promise<CloudToken | null> =>
isFresh(current) ? Promise.resolve(current) : mint();
+const waitForSignal = <Value>(promise: Promise<Value>, signal?: AbortSignal): Promise<Value> => {
+ if (!signal) return promise;
+ if (signal.aborted) {
+ return Promise.reject(signal.reason ?? new DOMException('request aborted', 'AbortError'));
+ }
+ return new Promise<Value>((resolve, reject) => {
+ const onAbort = () => {
+ reject(signal.reason ?? new DOMException('request aborted', 'AbortError'));
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ promise.then(
+ (value) => {
+ signal.removeEventListener('abort', onAbort);
+ resolve(value);
+ },
+ (error) => {
+ signal.removeEventListener('abort', onAbort);
+ reject(error);
+ },
+ );
+ });
+};
+
// Prewarm at app load (fire-and-forget): get a token before the first real use
// so recording never waits on a mint.
export const primeCloudToken = (): void => {
@@ -105,23 +159,62 @@ export const primeCloudToken = (): void => {
// Fetch a path on the avibe.bot cloud surface with the short-lived user token.
// Throws CloudUnavailableError when no token can be obtained; on a 401 it
-// re-mints once and retries.
-export const avibeFetch = async (path: string, init: RequestInit = {}): Promise<Response> => {
- let token = await ensureToken();
+// re-mints once and retries without making post-upload fallback look safe.
+export const avibeFetch = async (
+ path: string,
+ init: AvibeFetchRequestInit = {},
+): Promise<Response> => {
+ const { onAttempt, ...requestInit } = init;
+ let token: CloudToken | null;
+ try {
+ token = await waitForSignal(
+ ensureToken(),
+ requestInit.signal ?? undefined,
+ );
+ } catch (error) {
+ if (requestInit.signal?.aborted) throw requestInit.signal.reason ?? error;
+ throw new CloudUnavailableError();
+ }
if (!token) throw new CloudUnavailableError();
- const send = (active: CloudToken): Promise<Response> => {
- const headers = new Headers(init.headers ?? {});
+ const notifyAttempt = (event: AvibeFetchAttemptEvent): void => {
+ try {
+ onAttempt?.(event);
+ } catch {
+ // Request instrumentation cannot change the cloud request behavior.
+ }
+ };
+ const send = async (active: CloudToken, attempt: number): Promise<Response> => {
+ const headers = new Headers(requestInit.headers ?? {});
headers.set('Authorization', `Bearer ${active.token}`);
- return fetch(`${active.baseUrl}${path}`, { ...init, headers });
+ notifyAttempt({ phase: 'started', attempt });
+ const startedAt = Date.now();
+ const response = await fetch(
+ `${active.baseUrl}${path}`,
+ { ...requestInit, headers },
+ );
+ notifyAttempt({
+ phase: 'response',
+ attempt,
+ status: response.status,
+ elapsedMs: Date.now() - startedAt,
+ });
+ return response;
};
- const res = await send(token);
+ const res = await send(token, 1);
if (res.status !== 401) return res;
// Token rejected (revoked / clock skew / server restart) — re-mint once.
current = null;
- token = await mint();
- if (!token) throw new CloudUnavailableError();
- return send(token);
+ try {
+ token = await waitForSignal(mint(), requestInit.signal ?? undefined);
+ } catch (error) {
+ if (requestInit.signal?.aborted) throw requestInit.signal.reason ?? error;
+ throw new CloudUnavailableError('cloud_refresh_unavailable', { uploadStarted: true });
+ }
+ if (!token) {
+ throw new CloudUnavailableError('cloud_refresh_unavailable', { uploadStarted: true });
+ }
+ return send(token, 2);
};
diff --git a/ui/src/lib/voiceRecording.test.ts b/ui/src/lib/voiceRecording.test.ts
new file mode 100644
index 000000000..3bdfe396e
--- /dev/null
+++ b/ui/src/lib/voiceRecording.test.ts
@@ -0,0 +1,643 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ deleteMapValueIfCurrent,
+ isVoiceControlDisabled,
+ VOICE_CAPTURE_STOP_TIMEOUT_MS,
+ VOICE_MIN_SEGMENT_MS,
+ voicePcmDeliverySamples,
+ voicePcmWorkletSource,
+ voiceWavMaxSamples,
+ VoiceRecordingPipeline,
+} from './voiceRecording';
+
+type CaptureHandlers = {
+ onSamples: (samples: Int16Array) => void;
+ onStopped: () => void;
+ onError: (error: unknown) => void;
+};
+
+class FakeCapture {
+ private readonly handlers: CaptureHandlers;
+ readonly start = vi.fn(async () => undefined);
+ readonly stop = vi.fn();
+
+ constructor(handlers: CaptureHandlers) {
+ this.handlers = handlers;
+ }
+
+ emit(...samples: number[]): void {
+ this.handlers.onSamples(Int16Array.from(samples));
+ }
+
+ settle(): void {
+ this.handlers.onStopped();
+ }
+
+ fail(error: unknown): void {
+ this.handlers.onError(error);
+ this.handlers.onStopped();
+ }
+}
+
+const setup = (options: {
+ maxFileBytes?: number;
+ overlapMs?: number;
+ segmentMs?: number;
+} = {}) => {
+ const track = {
+ stop: vi.fn(),
+ };
+ const stream = {
+ getTracks: () => [track],
+ } as unknown as MediaStream;
+ const onSegment = vi.fn<(blob: Blob, metadata: { durationMs: number }) => void>();
+ const onError = vi.fn();
+ const onStopRequested = vi.fn();
+ const onStopped = vi.fn();
+ let capture: FakeCapture | null = null;
+ const pipeline = new VoiceRecordingPipeline({
+ stream,
+ sampleRate: 4,
+ segmentMs: options.segmentMs ?? 1000,
+ maxFileBytes: options.maxFileBytes,
+ overlapMs: options.overlapMs ?? 0,
+ onSegment,
+ onError,
+ onStopRequested,
+ onStopped,
+ createCapture: (_stream, sampleRate, segmentSamples, handlers) => {
+ expect(sampleRate).toBe(4);
+ expect(segmentSamples).toBe(
+ Math.min(
+ Math.round(4 * (options.segmentMs ?? 1000) / 1000),
+ voiceWavMaxSamples(options.maxFileBytes) ?? Number.POSITIVE_INFINITY,
+ ),
+ );
+ capture = new FakeCapture(handlers);
+ return capture;
+ },
+ });
+ return {
+ capture: () => capture!,
+ onError,
+ onSegment,
+ onStopRequested,
+ onStopped,
+ pipeline,
+ track,
+ };
+};
+
+const wavDataBytes = async (blob: Blob): Promise<number> => {
+ const buffer = await blob.arrayBuffer();
+ return new DataView(buffer).getUint32(40, true);
+};
+
+const wavSamples = async (blob: Blob): Promise<number[]> => {
+ const buffer = await blob.arrayBuffer();
+ const view = new DataView(buffer);
+ const samples: number[] = [];
+ for (let offset = 44; offset < buffer.byteLength; offset += 2) {
+ samples.push(view.getInt16(offset, true));
+ }
+ return samples;
+};
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('VoiceRecordingPipeline', () => {
+ it('frames delayed PCM delivery into provider-safe segments by sample count', async () => {
+ const { capture, onSegment, pipeline } = setup();
+ await pipeline.start();
+
+ // This represents audio-render-thread messages delivered after a long main
+ // thread stall. No emitted file may grow with the delayed wall time.
+ capture().emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ expect(onSegment).toHaveBeenCalledTimes(2);
+ expect(onSegment.mock.calls.map(([, metadata]) => metadata.durationMs)).toEqual([
+ 1000,
+ 1000,
+ ]);
+ expect(await Promise.all(onSegment.mock.calls.map(([blob]) => wavDataBytes(blob)))).toEqual([
+ 8,
+ 8,
+ ]);
+ expect(await Promise.all(onSegment.mock.calls.map(([blob]) => wavSamples(blob)))).toEqual([
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ ]);
+ expect(onSegment.mock.calls.every(([blob]) => blob.type === 'audio/wav')).toBe(true);
+ });
+
+ it('keeps every WAV within the configured ASR byte limit', async () => {
+ const { capture, onSegment, pipeline } = setup({
+ maxFileBytes: 52,
+ overlapMs: 250,
+ });
+ await pipeline.start();
+
+ capture().emit(1, 2, 3, 4, 5, 6, 7, 8);
+ pipeline.finish();
+ capture().settle();
+
+ expect(onSegment).toHaveBeenCalledTimes(3);
+ expect(onSegment.mock.calls.map(([blob]) => blob.size)).toEqual([52, 52, 48]);
+ expect(await Promise.all(onSegment.mock.calls.map(([blob]) => wavSamples(blob)))).toEqual([
+ [1, 2, 3, 4],
+ [4, 5, 6, 7],
+ [7, 8],
+ ]);
+ });
+
+ it('rejects a file limit below one practical segment', () => {
+ const minimumSamples = Math.round(4 * VOICE_MIN_SEGMENT_MS / 1000);
+ const belowMinimumBytes = 44 + ((minimumSamples - 1) * 2);
+ expect(() => setup({
+ maxFileBytes: belowMinimumBytes,
+ segmentMs: VOICE_MIN_SEGMENT_MS + 1000,
+ })).toThrow(
+ 'configured ASR file limit is too small for a practical WAV segment',
+ );
+ });
+
+ it('overlaps adjacent segments without emitting an overlap-only tail', async () => {
+ const { capture, onSegment, pipeline } = setup({ overlapMs: 500 });
+ await pipeline.start();
+
+ capture().emit(1, 2, 3, 4, 5, 6);
+ pipeline.finish();
+ capture().settle();
+
+ expect(onSegment).toHaveBeenCalledTimes(2);
+ expect(await Promise.all(onSegment.mock.calls.map(([blob]) => wavSamples(blob)))).toEqual([
+ [1, 2, 3, 4],
+ [3, 4, 5, 6],
+ ]);
+ expect(onSegment.mock.calls.map(([, metadata]) => metadata)).toEqual([
+ { durationMs: 1000 },
+ { durationMs: 1000, overlapMs: 500 },
+ ]);
+ });
+
+ it('flushes the final partial segment after the user stops', async () => {
+ vi.setSystemTime(new Date('2026-07-29T17:00:00Z'));
+ const {
+ capture,
+ onSegment,
+ onStopRequested,
+ onStopped,
+ pipeline,
+ track,
+ } = setup();
+ await pipeline.start();
+ capture().emit(1, 2);
+
+ pipeline.finish();
+
+ expect(capture().stop).toHaveBeenCalledTimes(1);
+ expect(track.stop).toHaveBeenCalledTimes(1);
+ expect(onStopRequested).toHaveBeenCalledWith('finish', {
+ requestedAt: Date.now(),
+ });
+ expect(onStopped).not.toHaveBeenCalled();
+
+ capture().settle();
+
+ expect(onSegment).toHaveBeenCalledTimes(1);
+ expect(onSegment.mock.calls[0]?.[1]).toEqual({ durationMs: 500 });
+ expect(await wavDataBytes(onSegment.mock.calls[0]![0])).toBe(4);
+ expect(onStopped).toHaveBeenCalledWith('finish', { pendingSegmentCount: 1 });
+ expect(track.stop).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards buffered PCM when aborted', async () => {
+ const { capture, onSegment, onStopped, pipeline } = setup();
+ await pipeline.start();
+ capture().emit(1, 2);
+
+ pipeline.abort();
+ capture().settle();
+
+ expect(onSegment).not.toHaveBeenCalled();
+ expect(onStopped).toHaveBeenCalledWith('abort', { pendingSegmentCount: 0 });
+ });
+
+ it('finishes before a hidden page can suspend audio processing', async () => {
+ const visibilityDocument = new EventTarget() as EventTarget & {
+ visibilityState: DocumentVisibilityState;
+ };
+ visibilityDocument.visibilityState = 'visible';
+ vi.stubGlobal('document', visibilityDocument);
+ const { capture, pipeline } = setup();
+ await pipeline.start();
+
+ visibilityDocument.visibilityState = 'hidden';
+ visibilityDocument.dispatchEvent(new Event('visibilitychange'));
+
+ expect(capture().stop).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not become active when the page hides during capture startup', async () => {
+ const visibilityDocument = new EventTarget() as EventTarget & {
+ visibilityState: DocumentVisibilityState;
+ };
+ visibilityDocument.visibilityState = 'visible';
+ vi.stubGlobal('document', visibilityDocument);
+ const { capture, onStopped, pipeline, track } = setup();
+ let resolveStart!: () => void;
+ capture().start.mockImplementationOnce(() => new Promise<void>((resolve) => {
+ resolveStart = resolve;
+ }));
+
+ const starting = pipeline.start();
+ await vi.waitFor(() => expect(capture().start).toHaveBeenCalledOnce());
+ visibilityDocument.visibilityState = 'hidden';
+ visibilityDocument.dispatchEvent(new Event('visibilitychange'));
+ expect(track.stop).toHaveBeenCalledTimes(1);
+ resolveStart();
+
+ await expect(starting).resolves.toBe(false);
+ expect(capture().stop).toHaveBeenCalledTimes(1);
+ capture().settle();
+ expect(onStopped).toHaveBeenCalledWith('finish', { pendingSegmentCount: 0 });
+ });
+
+ it('retains captured audio as failed after the processor stops unexpectedly', async () => {
+ const {
+ capture,
+ onError,
+ onSegment,
+ onStopRequested,
+ onStopped,
+ pipeline,
+ } = setup();
+ await pipeline.start();
+ capture().emit(1, 2);
+ const error = new Error('processor stopped');
+
+ capture().fail(error);
+
+ expect(onStopRequested).toHaveBeenCalledWith('error', {
+ requestedAt: expect.any(Number),
+ });
+ expect(onError).toHaveBeenCalledWith(error);
+ expect(onSegment).toHaveBeenCalledTimes(1);
+ expect(onStopped).toHaveBeenCalledWith('error', { pendingSegmentCount: 1 });
+ });
+
+ it('upgrades a user stop to failure when the processor crashes while flushing', async () => {
+ const {
+ capture,
+ onError,
+ onStopRequested,
+ onStopped,
+ pipeline,
+ } = setup();
+ await pipeline.start();
+ capture().emit(1, 2);
+ pipeline.finish();
+ const error = new Error('processor stopped while flushing');
+
+ capture().fail(error);
+
+ expect(onStopRequested).toHaveBeenCalledOnce();
+ expect(onStopRequested).toHaveBeenCalledWith('finish', {
+ requestedAt: expect.any(Number),
+ });
+ expect(onError).toHaveBeenCalledWith(error);
+ expect(onStopped).toHaveBeenCalledWith('error', { pendingSegmentCount: 1 });
+ });
+
+ it('reports inactive when capture stops before asynchronous startup completes', async () => {
+ const { capture, onStopped, pipeline } = setup();
+ let resolveStart!: () => void;
+ capture().start.mockImplementationOnce(() => new Promise<void>((resolve) => {
+ resolveStart = resolve;
+ }));
+
+ const starting = pipeline.start();
+ await vi.waitFor(() => expect(capture().start).toHaveBeenCalledOnce());
+ capture().settle();
+ resolveStart();
+
+ await expect(starting).resolves.toBe(false);
+ expect(onStopped).toHaveBeenCalledWith('finish', { pendingSegmentCount: 0 });
+ });
+
+ it('observes a microphone track ending while the worklet module loads', async () => {
+ let resolveModule!: () => void;
+ const addModule = vi.fn(() => new Promise<void>((resolve) => {
+ resolveModule = resolve;
+ }));
+ class FakeAudioContext {
+ state = 'running';
+ readonly audioWorklet = { addModule };
+ readonly destination = {};
+ readonly close = vi.fn(async () => {
+ this.state = 'closed';
+ });
+ readonly resume = vi.fn(async () => undefined);
+ readonly createMediaStreamSource = vi.fn(() => ({
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ }));
+ }
+ class FakeAudioWorkletNode {
+ readonly port = {
+ onmessage: null,
+ postMessage: vi.fn(),
+ close: vi.fn(),
+ };
+ onprocessorerror: (() => void) | null = null;
+ readonly connect = vi.fn();
+ readonly disconnect = vi.fn();
+ }
+ class FakeTrack extends EventTarget {
+ readyState: MediaStreamTrackState = 'live';
+ readonly stop = vi.fn();
+
+ end(): void {
+ this.readyState = 'ended';
+ this.dispatchEvent(new Event('ended'));
+ }
+ }
+ const track = new FakeTrack();
+ const stream = {
+ getTracks: () => [track],
+ } as unknown as MediaStream;
+ const onError = vi.fn();
+ const onStopRequested = vi.fn();
+ const onStopped = vi.fn();
+ vi.stubGlobal('AudioContext', FakeAudioContext);
+ vi.stubGlobal('AudioWorkletNode', FakeAudioWorkletNode);
+ vi.stubGlobal('URL', {
+ createObjectURL: vi.fn(() => 'blob:voice-worklet'),
+ revokeObjectURL: vi.fn(),
+ });
+ const pipeline = new VoiceRecordingPipeline({
+ stream,
+ segmentMs: 1000,
+ onSegment: vi.fn(),
+ onError,
+ onStopRequested,
+ onStopped,
+ });
+
+ const starting = pipeline.start();
+ await vi.waitFor(() => expect(addModule).toHaveBeenCalledOnce());
+ track.end();
+ resolveModule();
+
+ await expect(starting).resolves.toBe(false);
+ expect(onError).toHaveBeenCalledWith(expect.any(Error));
+ expect(onStopRequested).toHaveBeenCalledWith('error', {
+ requestedAt: expect.any(Number),
+ });
+ expect(onStopped).toHaveBeenCalledWith('error', { pendingSegmentCount: 0 });
+ });
+
+ it('retains delivered PCM when the worklet does not acknowledge stop', async () => {
+ vi.useFakeTimers();
+ class FakeAudioContext {
+ state = 'running';
+ readonly audioWorklet = { addModule: vi.fn(async () => undefined) };
+ readonly destination = {};
+ readonly close = vi.fn(async () => {
+ this.state = 'closed';
+ });
+ readonly resume = vi.fn(async () => undefined);
+ readonly createMediaStreamSource = vi.fn(() => ({
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ }));
+ }
+ class FakeAudioWorkletNode {
+ static instance: FakeAudioWorkletNode | null = null;
+ readonly port = {
+ onmessage: null as ((event: {
+ data: { type?: string; samples?: ArrayBuffer };
+ }) => void) | null,
+ postMessage: vi.fn(),
+ close: vi.fn(),
+ };
+ onprocessorerror: (() => void) | null = null;
+ readonly connect = vi.fn();
+ readonly disconnect = vi.fn();
+
+ constructor() {
+ FakeAudioWorkletNode.instance = this;
+ }
+ }
+ const track = new EventTarget() as EventTarget & {
+ readyState: MediaStreamTrackState;
+ stop: ReturnType<typeof vi.fn>;
+ };
+ track.readyState = 'live';
+ track.stop = vi.fn();
+ const stream = {
+ getTracks: () => [track],
+ } as unknown as MediaStream;
+ const onError = vi.fn();
+ const onSegment = vi.fn();
+ const onStopped = vi.fn();
+ vi.stubGlobal('AudioContext', FakeAudioContext);
+ vi.stubGlobal('AudioWorkletNode', FakeAudioWorkletNode);
+ vi.stubGlobal('URL', {
+ createObjectURL: vi.fn(() => 'blob:voice-worklet'),
+ revokeObjectURL: vi.fn(),
+ });
+ const pipeline = new VoiceRecordingPipeline({
+ stream,
+ sampleRate: 4,
+ segmentMs: 1000,
+ overlapMs: 0,
+ stopTimeoutMs: VOICE_CAPTURE_STOP_TIMEOUT_MS,
+ onSegment,
+ onError,
+ onStopped,
+ });
+ await pipeline.start();
+ const workletNode = FakeAudioWorkletNode.instance;
+ expect(workletNode).not.toBeNull();
+ workletNode.port.onmessage?.({
+ data: { type: 'samples', samples: Int16Array.from([1, 2]).buffer },
+ });
+
+ pipeline.finish();
+ await vi.advanceTimersByTimeAsync(VOICE_CAPTURE_STOP_TIMEOUT_MS);
+
+ expect(onError).toHaveBeenCalledWith(expect.any(Error));
+ expect(onSegment).toHaveBeenCalledOnce();
+ expect(await wavSamples(onSegment.mock.calls[0]![0])).toEqual([1, 2]);
+ expect(onStopped).toHaveBeenCalledWith('error', { pendingSegmentCount: 1 });
+ });
+
+ it('reports no queued segment when stopping exactly at a segment boundary', async () => {
+ const { capture, onStopped, pipeline } = setup();
+ await pipeline.start();
+ capture().emit(1, 2, 3, 4);
+
+ pipeline.finish();
+ capture().settle();
+
+ expect(onStopped).toHaveBeenCalledWith('finish', { pendingSegmentCount: 0 });
+ });
+
+ it('counts every file segment delivered after the stop request', async () => {
+ const { capture, onSegment, onStopped, pipeline } = setup();
+ await pipeline.start();
+
+ pipeline.finish();
+ capture().emit(1, 2, 3, 4, 5, 6, 7, 8);
+ capture().settle();
+
+ expect(onSegment).toHaveBeenCalledTimes(2);
+ expect(onStopped).toHaveBeenCalledWith('finish', { pendingSegmentCount: 2 });
+ });
+});
+
+describe('voice PCM worklet', () => {
+ it('delivers PCM before a full file segment has accumulated', () => {
+ const oneMinute = 60 * 16_000;
+
+ expect(voicePcmDeliverySamples(16_000, oneMinute)).toBe(4_000);
+ expect(voicePcmDeliverySamples(16_000, 2_000)).toBe(2_000);
+ });
+
+ it('loads and emits bounded downsampled buffers on the rendering thread', () => {
+ const postMessage = vi.fn();
+ class FakeAudioWorkletProcessor {
+ readonly port = {
+ onmessage: null as ((event: { data: { type?: string } }) => void) | null,
+ postMessage,
+ };
+ }
+ let Processor: (new (options: {
+ processorOptions: {
+ targetSampleRate: number;
+ chunkSamples: number;
+ };
+ }) => {
+ port: FakeAudioWorkletProcessor['port'];
+ process: (inputs: Float32Array[][]) => boolean;
+ }) | null = null;
+ const loadModule = new Function(
+ 'AudioWorkletProcessor',
+ 'registerProcessor',
+ 'sampleRate',
+ voicePcmWorkletSource,
+ );
+ loadModule(
+ FakeAudioWorkletProcessor,
+ (_name: string, constructor: typeof Processor) => {
+ Processor = constructor;
+ },
+ 8,
+ );
+
+ const processor = new Processor!({
+ processorOptions: {
+ targetSampleRate: 4,
+ chunkSamples: 4,
+ },
+ });
+ expect(processor.process([[
+ Float32Array.from([0, 0.25, 0.5, 0.75, 1, 0.75, 0.5, 0.25]),
+ ]])).toBe(true);
+
+ const sampleMessage = postMessage.mock.calls[0]?.[0] as {
+ type: string;
+ samples: ArrayBuffer;
+ };
+ expect(sampleMessage.type).toBe('samples');
+ expect(new Int16Array(sampleMessage.samples)).toHaveLength(4);
+
+ processor.port.onmessage?.({ data: { type: 'stop' } });
+ expect(postMessage.mock.calls.at(-1)?.[0]).toEqual({ type: 'stopped' });
+ });
+
+ it('upsamples low-rate input before emitting target-rate PCM', () => {
+ const postMessage = vi.fn();
+ class FakeAudioWorkletProcessor {
+ readonly port = {
+ onmessage: null as ((event: { data: { type?: string } }) => void) | null,
+ postMessage,
+ };
+ }
+ let Processor: (new (options: {
+ processorOptions: {
+ targetSampleRate: number;
+ chunkSamples: number;
+ };
+ }) => {
+ port: FakeAudioWorkletProcessor['port'];
+ process: (inputs: Float32Array[][]) => boolean;
+ }) | null = null;
+ const loadModule = new Function(
+ 'AudioWorkletProcessor',
+ 'registerProcessor',
+ 'sampleRate',
+ voicePcmWorkletSource,
+ );
+ loadModule(
+ FakeAudioWorkletProcessor,
+ (_name: string, constructor: typeof Processor) => {
+ Processor = constructor;
+ },
+ 4,
+ );
+
+ const processor = new Processor!({
+ processorOptions: {
+ targetSampleRate: 8,
+ chunkSamples: 8,
+ },
+ });
+ expect(processor.process([[
+ Float32Array.from([0, 1, 0, -1]),
+ ]])).toBe(true);
+ processor.port.onmessage?.({ data: { type: 'stop' } });
+
+ const sampleMessage = postMessage.mock.calls[0]?.[0] as {
+ type: string;
+ samples: ArrayBuffer;
+ };
+ expect(sampleMessage.type).toBe('samples');
+ expect(Array.from(new Int16Array(sampleMessage.samples))).toEqual([
+ 0,
+ 16384,
+ 32767,
+ 16384,
+ 0,
+ -16384,
+ -32768,
+ -32768,
+ ]);
+ expect(postMessage.mock.calls.at(-1)?.[0]).toEqual({ type: 'stopped' });
+ });
+});
+
+describe('deleteMapValueIfCurrent', () => {
+ it('cannot let an old finalizer delete a replacement session', () => {
+ const oldSession = {};
+ const replacement = {};
+ const sessions = new Map([['session', replacement]]);
+
+ expect(deleteMapValueIfCurrent(sessions, 'session', oldSession)).toBe(false);
+ expect(sessions.get('session')).toBe(replacement);
+ expect(deleteMapValueIfCurrent(sessions, 'session', replacement)).toBe(true);
+ });
+});
+
+describe('isVoiceControlDisabled', () => {
+ it('requires explicit discard before a retained recording can be replaced', () => {
+ expect(isVoiceControlDisabled(false, false, false, true)).toBe(true);
+ expect(isVoiceControlDisabled(false, true, false, true)).toBe(false);
+ });
+});
diff --git a/ui/src/lib/voiceRecording.ts b/ui/src/lib/voiceRecording.ts
new file mode 100644
index 000000000..4ce08fe8a
--- /dev/null
+++ b/ui/src/lib/voiceRecording.ts
@@ -0,0 +1,621 @@
+const PCM_SAMPLE_RATE = 16_000;
+const PCM_WORKLET_NAME = 'avibe-voice-pcm-capture';
+const PCM_DELIVERY_MS = 250;
+const PCM_BYTES_PER_SAMPLE = 2;
+const WAV_HEADER_BYTES = 44;
+const DEFAULT_SEGMENT_OVERLAP_MS = 500;
+export const VOICE_MIN_SEGMENT_MS = 5_000;
+export const VOICE_CAPTURE_STOP_TIMEOUT_MS = 5_000;
+
+export const voiceWavMaxSamples = (maxFileBytes?: number | null): number | null => {
+ if (maxFileBytes == null || !Number.isFinite(maxFileBytes)) return null;
+ return Math.max(
+ 0,
+ Math.floor((Math.floor(maxFileBytes) - WAV_HEADER_BYTES) / PCM_BYTES_PER_SAMPLE),
+ );
+};
+
+export const voicePcmDeliverySamples = (
+ sampleRate: number,
+ segmentSamples: number,
+): number => Math.max(
+ 1,
+ Math.min(segmentSamples, Math.round(sampleRate * PCM_DELIVERY_MS / 1000)),
+);
+
+const PCM_WORKLET_SOURCE = `
+class AvibeVoicePcmCapture extends AudioWorkletProcessor {
+ constructor(options) {
+ super();
+ const processorOptions = options.processorOptions || {};
+ this.targetSampleRate = processorOptions.targetSampleRate || 16000;
+ this.chunkSamples = processorOptions.chunkSamples || this.targetSampleRate;
+ this.output = new Int16Array(this.chunkSamples);
+ this.outputOffset = 0;
+ this.phase = 0;
+ this.sum = 0;
+ this.sumCount = 0;
+ this.previousSample = 0;
+ this.hasPreviousSample = false;
+ this.nextOutputPosition = 0;
+ this.totalInputSamples = 0;
+ this.totalOutputSamples = 0;
+ this.stopped = false;
+ this.port.onmessage = (event) => {
+ if (event.data && event.data.type === 'stop') this.finish();
+ };
+ }
+
+ emitSample(sample) {
+ const normalized = Math.max(-1, Math.min(1, sample));
+ this.output[this.outputOffset++] = normalized < 0
+ ? Math.round(normalized * 32768)
+ : Math.round(normalized * 32767);
+ this.totalOutputSamples += 1;
+ if (this.outputOffset === this.output.length) this.flush();
+ }
+
+ flush() {
+ if (!this.outputOffset) return;
+ const samples = this.outputOffset === this.output.length
+ ? this.output
+ : this.output.slice(0, this.outputOffset);
+ this.port.postMessage({ type: 'samples', samples: samples.buffer }, [samples.buffer]);
+ this.output = new Int16Array(this.chunkSamples);
+ this.outputOffset = 0;
+ }
+
+ finish() {
+ if (this.stopped) return;
+ if (this.targetSampleRate <= sampleRate && this.sumCount) {
+ this.emitSample(this.sum / this.sumCount);
+ this.sum = 0;
+ this.sumCount = 0;
+ } else if (this.targetSampleRate > sampleRate && this.hasPreviousSample) {
+ const expectedOutputSamples = Math.round(
+ this.totalInputSamples * this.targetSampleRate / sampleRate,
+ );
+ while (this.totalOutputSamples < expectedOutputSamples) {
+ this.emitSample(this.previousSample);
+ }
+ }
+ this.flush();
+ this.stopped = true;
+ this.port.postMessage({ type: 'stopped' });
+ }
+
+ processDownsample(sample) {
+ this.sum += sample;
+ this.sumCount += 1;
+ this.phase += this.targetSampleRate;
+ if (this.phase >= sampleRate) {
+ this.phase -= sampleRate;
+ this.emitSample(this.sum / this.sumCount);
+ this.sum = 0;
+ this.sumCount = 0;
+ }
+ }
+
+ processUpsample(sample) {
+ const currentPosition = this.totalInputSamples;
+ if (!this.hasPreviousSample) {
+ this.previousSample = sample;
+ this.hasPreviousSample = true;
+ this.emitSample(sample);
+ this.nextOutputPosition = sampleRate / this.targetSampleRate;
+ } else {
+ const previousPosition = currentPosition - 1;
+ while (this.nextOutputPosition <= currentPosition) {
+ const fraction = Math.max(
+ 0,
+ Math.min(1, this.nextOutputPosition - previousPosition),
+ );
+ this.emitSample(
+ this.previousSample + (sample - this.previousSample) * fraction,
+ );
+ this.nextOutputPosition += sampleRate / this.targetSampleRate;
+ }
+ this.previousSample = sample;
+ }
+ this.totalInputSamples += 1;
+ }
+
+ process(inputs) {
+ if (this.stopped) return false;
+ const channels = inputs[0];
+ if (!channels || !channels.length) return true;
+ const frameCount = channels[0].length;
+ for (let frame = 0; frame < frameCount; frame += 1) {
+ let sample = 0;
+ for (let channel = 0; channel < channels.length; channel += 1) {
+ sample += channels[channel][frame] || 0;
+ }
+ const monoSample = sample / channels.length;
+ if (this.targetSampleRate <= sampleRate) this.processDownsample(monoSample);
+ else this.processUpsample(monoSample);
+ }
+ return true;
+ }
+}
+
+registerProcessor('${PCM_WORKLET_NAME}', AvibeVoicePcmCapture);
+`;
+
+export const voicePcmWorkletSource = PCM_WORKLET_SOURCE;
+
+type VoicePcmCaptureHandlers = {
+ onSamples: (samples: Int16Array<ArrayBuffer>) => void;
+ onStopped: () => void;
+ onError: (error: unknown) => void;
+};
+
+type VoicePcmCapture = {
+ start: () => Promise<void>;
+ stop: () => void;
+};
+
+type VoicePcmCaptureFactory = (
+ stream: MediaStream,
+ sampleRate: number,
+ segmentSamples: number,
+ handlers: VoicePcmCaptureHandlers,
+ stopTimeoutMs?: number,
+) => VoicePcmCapture;
+
+class AudioWorkletPcmCapture implements VoicePcmCapture {
+ private readonly stream: MediaStream;
+ private readonly sampleRate: number;
+ private readonly segmentSamples: number;
+ private readonly handlers: VoicePcmCaptureHandlers;
+ private readonly stopTimeoutMs: number;
+ private context: AudioContext | null = null;
+ private source: MediaStreamAudioSourceNode | null = null;
+ private node: AudioWorkletNode | null = null;
+ private stopTimer: ReturnType<typeof setTimeout> | null = null;
+ private stopping = false;
+ private stopped = false;
+ private failureReported = false;
+
+ constructor(
+ stream: MediaStream,
+ sampleRate: number,
+ segmentSamples: number,
+ handlers: VoicePcmCaptureHandlers,
+ stopTimeoutMs = VOICE_CAPTURE_STOP_TIMEOUT_MS,
+ ) {
+ this.stream = stream;
+ this.sampleRate = sampleRate;
+ this.segmentSamples = segmentSamples;
+ this.handlers = handlers;
+ this.stopTimeoutMs = Math.max(0, stopTimeoutMs);
+ }
+
+ async start(): Promise<void> {
+ const context = new AudioContext();
+ this.context = context;
+ this.stream.getTracks().forEach((track) => {
+ track.addEventListener('ended', this.handleTrackEnded, { once: true });
+ });
+ if (this.stream.getTracks().some((track) => track.readyState === 'ended')) {
+ this.stop();
+ }
+ let moduleUrl: string | null = null;
+ try {
+ moduleUrl = URL.createObjectURL(
+ new Blob([PCM_WORKLET_SOURCE], { type: 'text/javascript' }),
+ );
+ await context.audioWorklet.addModule(moduleUrl);
+ if (this.stopping) {
+ await context.close();
+ this.finish();
+ return;
+ }
+
+ const node = new AudioWorkletNode(context, PCM_WORKLET_NAME, {
+ numberOfInputs: 1,
+ numberOfOutputs: 1,
+ outputChannelCount: [1],
+ processorOptions: {
+ targetSampleRate: this.sampleRate,
+ // File-sized segments are assembled on the main thread. Deliver
+ // smaller chunks so a processor failure cannot erase a whole segment.
+ chunkSamples: voicePcmDeliverySamples(this.sampleRate, this.segmentSamples),
+ },
+ });
+ node.port.onmessage = (event: MessageEvent<{
+ type?: string;
+ samples?: ArrayBuffer;
+ }>) => {
+ if (event.data.type === 'samples' && event.data.samples) {
+ this.handlers.onSamples(new Int16Array(event.data.samples));
+ } else if (event.data.type === 'stopped') {
+ this.finish();
+ }
+ };
+ node.onprocessorerror = () => {
+ this.reportFailure(new Error('voice PCM processor stopped unexpectedly'));
+ this.finish();
+ };
+ this.node = node;
+ this.source = context.createMediaStreamSource(this.stream);
+ this.source.connect(node);
+ node.connect(context.destination);
+ await context.resume();
+ } catch (error) {
+ this.detachNodes();
+ this.context = null;
+ if (context.state !== 'closed') await context.close().catch(() => undefined);
+ throw error;
+ } finally {
+ if (moduleUrl) URL.revokeObjectURL(moduleUrl);
+ }
+ }
+
+ stop(): void {
+ if (this.stopping || this.stopped) return;
+ this.stopping = true;
+ this.stopTimer = setTimeout(() => {
+ this.reportFailure(new Error('voice PCM processor did not stop in time'));
+ this.finish();
+ }, this.stopTimeoutMs);
+ if (!this.node) return;
+ this.node.port.postMessage({ type: 'stop' });
+ }
+
+ private readonly handleTrackEnded = (): void => {
+ if (!this.stopping && !this.stopped) {
+ this.reportFailure(new Error('voice microphone track ended unexpectedly'));
+ }
+ this.stop();
+ };
+
+ private reportFailure(error: Error): void {
+ if (this.failureReported) return;
+ this.failureReported = true;
+ this.handlers.onError(error);
+ }
+
+ private finish(): void {
+ if (this.stopped) return;
+ this.stopped = true;
+ if (this.stopTimer !== null) clearTimeout(this.stopTimer);
+ this.stopTimer = null;
+ this.detachNodes();
+ const context = this.context;
+ this.context = null;
+ if (context && context.state !== 'closed') void context.close().catch(() => undefined);
+ this.handlers.onStopped();
+ }
+
+ private detachNodes(): void {
+ this.stream.getTracks().forEach((track) => {
+ track.removeEventListener('ended', this.handleTrackEnded);
+ });
+ this.source?.disconnect();
+ this.node?.disconnect();
+ this.node?.port.close();
+ this.source = null;
+ this.node = null;
+ }
+}
+
+const defaultCaptureFactory: VoicePcmCaptureFactory = (
+ stream,
+ sampleRate,
+ segmentSamples,
+ handlers,
+ stopTimeoutMs,
+) => new AudioWorkletPcmCapture(
+ stream,
+ sampleRate,
+ segmentSamples,
+ handlers,
+ stopTimeoutMs,
+);
+
+export const deleteMapValueIfCurrent = <Key, Value>(
+ map: Map<Key, Value>,
+ key: Key,
+ value: Value,
+): boolean => {
+ if (map.get(key) !== value) return false;
+ return map.delete(key);
+};
+
+export const isVoiceControlDisabled = (
+ disabled: boolean,
+ recording: boolean,
+ transcribing: boolean,
+ retained = false,
+): boolean => transcribing || (!recording && (disabled || retained));
+
+export type VoiceRecordingStopReason = 'finish' | 'abort' | 'error';
+
+export type VoiceRecordingSegmentMetadata = {
+ durationMs: number;
+ overlapMs?: number;
+};
+
+export type VoiceRecordingStopMetadata = {
+ requestedAt: number;
+};
+
+export type VoiceRecordingStoppedMetadata = {
+ pendingSegmentCount: number;
+};
+
+export type VoiceRecordingPipelineOptions = {
+ stream: MediaStream;
+ segmentMs: number;
+ onSegment: (blob: Blob, metadata: VoiceRecordingSegmentMetadata) => void;
+ onStopRequested?: (
+ reason: VoiceRecordingStopReason,
+ metadata: VoiceRecordingStopMetadata,
+ ) => void;
+ onStopped: (
+ reason: VoiceRecordingStopReason,
+ metadata: VoiceRecordingStoppedMetadata,
+ ) => void;
+ onError?: (error: unknown) => void;
+ sampleRate?: number;
+ maxFileBytes?: number | null;
+ overlapMs?: number;
+ stopTimeoutMs?: number;
+ createCapture?: VoicePcmCaptureFactory;
+};
+
+const wavHeader = (
+ sampleRate: number,
+ sampleCount: number,
+): Uint8Array<ArrayBuffer> => {
+ const header = new Uint8Array(44);
+ const view = new DataView(header.buffer);
+ const writeAscii = (offset: number, value: string) => {
+ for (let index = 0; index < value.length; index += 1) {
+ view.setUint8(offset + index, value.charCodeAt(index));
+ }
+ };
+ const dataBytes = sampleCount * 2;
+ writeAscii(0, 'RIFF');
+ view.setUint32(4, 36 + dataBytes, true);
+ writeAscii(8, 'WAVE');
+ writeAscii(12, 'fmt ');
+ view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true);
+ view.setUint16(22, 1, true);
+ view.setUint32(24, sampleRate, true);
+ view.setUint32(28, sampleRate * 2, true);
+ view.setUint16(32, 2, true);
+ view.setUint16(34, 16, true);
+ writeAscii(36, 'data');
+ view.setUint32(40, dataBytes, true);
+ return header;
+};
+
+const wavBlob = (
+ sampleRate: number,
+ sampleCount: number,
+ chunks: Int16Array<ArrayBuffer>[],
+): Blob => new Blob(
+ [wavHeader(sampleRate, sampleCount), ...chunks],
+ { type: 'audio/wav' },
+);
+
+const tailPcmChunks = (
+ chunks: Int16Array<ArrayBuffer>[],
+ tailSamples: number,
+): Int16Array<ArrayBuffer>[] => {
+ const tail: Int16Array<ArrayBuffer>[] = [];
+ let remaining = tailSamples;
+ for (let index = chunks.length - 1; index >= 0 && remaining > 0; index -= 1) {
+ const chunk = chunks[index];
+ if (!chunk) continue;
+ const take = Math.min(remaining, chunk.length);
+ tail.unshift(chunk.subarray(chunk.length - take));
+ remaining -= take;
+ }
+ return tail;
+};
+
+/**
+ * Captures mono PCM on the audio rendering thread, then frames it by sample
+ * count. Even if the main thread is blocked, queued PCM chunks are converted
+ * into provider-safe files instead of one oversized MediaRecorder blob.
+ */
+export class VoiceRecordingPipeline {
+ private readonly options: VoiceRecordingPipelineOptions;
+ private readonly sampleRate: number;
+ private readonly segmentSamples: number;
+ private readonly overlapSamples: number;
+ private readonly capture: VoicePcmCapture;
+ private segmentChunks: Int16Array<ArrayBuffer>[] = [];
+ private segmentSampleCount = 0;
+ private segmentFreshSampleCount = 0;
+ private segmentLeadingOverlapSamples = 0;
+ private visibilityDocument: Document | null = null;
+ private started = false;
+ private stopping: VoiceRecordingStopReason | null = null;
+ private stopped = false;
+ private streamStopped = false;
+ private emittedSegmentCount = 0;
+ private segmentCountAtStop: number | null = null;
+
+ constructor(options: VoiceRecordingPipelineOptions) {
+ this.options = options;
+ this.sampleRate = options.sampleRate ?? PCM_SAMPLE_RATE;
+ const durationSamples = Math.max(
+ 1,
+ Math.round(this.sampleRate * options.segmentMs / 1000),
+ );
+ const maxFileSamples = voiceWavMaxSamples(options.maxFileBytes);
+ const minimumFileSamples = Math.min(
+ durationSamples,
+ Math.max(1, Math.round(this.sampleRate * VOICE_MIN_SEGMENT_MS / 1000)),
+ );
+ if (maxFileSamples != null && maxFileSamples < minimumFileSamples) {
+ throw new Error('configured ASR file limit is too small for a practical WAV segment');
+ }
+ this.segmentSamples = maxFileSamples == null
+ ? durationSamples
+ : Math.min(durationSamples, maxFileSamples);
+ this.overlapSamples = Math.min(
+ Math.max(
+ 0,
+ Math.round(this.sampleRate * (options.overlapMs ?? DEFAULT_SEGMENT_OVERLAP_MS) / 1000),
+ ),
+ Math.floor(this.segmentSamples / 2),
+ );
+ const createCapture = options.createCapture ?? defaultCaptureFactory;
+ this.capture = createCapture(options.stream, this.sampleRate, this.segmentSamples, {
+ onSamples: (samples) => this.handleSamples(samples),
+ onStopped: () => this.handleCaptureStopped(),
+ onError: (error) => this.handleCaptureError(error),
+ }, options.stopTimeoutMs);
+ }
+
+ async start(): Promise<boolean> {
+ if (this.started || this.stopped) {
+ throw new Error('voice recording pipeline already started');
+ }
+ this.started = true;
+ // Bind before asynchronous capture setup so a tab switch during addModule
+ // or resume cannot be missed. A hidden document immediately enters finish.
+ this.bindVisibilityStop();
+ try {
+ await this.capture.start();
+ } catch (error) {
+ if (this.stopped) return false;
+ if (this.stopping) {
+ this.complete(this.pendingSegmentCount());
+ return false;
+ }
+ this.unbindVisibilityStop();
+ this.stopStream();
+ this.stopped = true;
+ throw error;
+ }
+ return !this.stopped && !this.stopping;
+ }
+
+ finish(): void {
+ this.stop('finish');
+ }
+
+ abort(): void {
+ this.stop('abort');
+ }
+
+ private stop(reason: VoiceRecordingStopReason): void {
+ if (!this.requestStop(reason)) return;
+ // Mark the capture as stopping before releasing tracks so an implementation
+ // that synchronously emits "ended" does not turn an intentional stop into
+ // a device-loss failure. Buffered PCM still flushes before completion.
+ this.capture.stop();
+ this.stopStream();
+ }
+
+ private requestStop(reason: VoiceRecordingStopReason): boolean {
+ if (this.stopping || this.stopped) return false;
+ this.stopping = reason;
+ this.segmentCountAtStop = this.emittedSegmentCount;
+ this.options.onStopRequested?.(reason, { requestedAt: Date.now() });
+ return true;
+ }
+
+ private handleSamples(samples: Int16Array<ArrayBuffer>): void {
+ if (this.stopped || this.stopping === 'abort') return;
+ let offset = 0;
+ while (offset < samples.length) {
+ const available = this.segmentSamples - this.segmentSampleCount;
+ const take = Math.min(available, samples.length - offset);
+ this.segmentChunks.push(samples.subarray(offset, offset + take));
+ this.segmentSampleCount += take;
+ this.segmentFreshSampleCount += take;
+ offset += take;
+ if (this.segmentSampleCount === this.segmentSamples) {
+ this.emitSegment(true);
+ }
+ }
+ }
+
+ private emitSegment(retainOverlap = false): void {
+ if (!this.segmentSampleCount) return;
+ const sampleCount = this.segmentSampleCount;
+ const chunks = this.segmentChunks;
+ const leadingOverlapSamples = this.segmentLeadingOverlapSamples;
+ const retainedSamples = retainOverlap ? this.overlapSamples : 0;
+ this.segmentChunks = tailPcmChunks(chunks, retainedSamples);
+ this.segmentSampleCount = retainedSamples;
+ this.segmentFreshSampleCount = 0;
+ this.segmentLeadingOverlapSamples = retainedSamples;
+ this.emittedSegmentCount += 1;
+ const overlapMs = Math.round(leadingOverlapSamples * 1000 / this.sampleRate);
+ this.options.onSegment(
+ wavBlob(this.sampleRate, sampleCount, chunks),
+ {
+ durationMs: Math.round(sampleCount * 1000 / this.sampleRate),
+ ...(overlapMs > 0 ? { overlapMs } : {}),
+ },
+ );
+ }
+
+ private handleCaptureError(error: unknown): void {
+ if (this.stopped || this.stopping === 'abort') return;
+ if (!this.stopping) this.requestStop('error');
+ else this.stopping = 'error';
+ this.options.onError?.(error);
+ }
+
+ private handleCaptureStopped(): void {
+ if (this.stopped) return;
+ this.requestStop('finish');
+ if (this.stopping !== 'abort' && this.segmentFreshSampleCount > 0) {
+ this.emitSegment();
+ }
+ else {
+ this.segmentChunks = [];
+ this.segmentSampleCount = 0;
+ this.segmentFreshSampleCount = 0;
+ this.segmentLeadingOverlapSamples = 0;
+ }
+ this.complete(this.pendingSegmentCount());
+ }
+
+ private pendingSegmentCount(): number {
+ if (this.stopping === 'abort') return 0;
+ return this.emittedSegmentCount - (this.segmentCountAtStop ?? this.emittedSegmentCount);
+ }
+
+ private complete(pendingSegmentCount: number): void {
+ if (this.stopped) return;
+ this.stopped = true;
+ this.unbindVisibilityStop();
+ this.stopStream();
+ this.options.onStopped(
+ this.stopping ?? 'finish',
+ { pendingSegmentCount },
+ );
+ }
+
+ private bindVisibilityStop(): void {
+ if (typeof document === 'undefined') return;
+ this.visibilityDocument = document;
+ document.addEventListener('visibilitychange', this.handleVisibilityChange);
+ if (document.visibilityState === 'hidden') this.finish();
+ }
+
+ private unbindVisibilityStop(): void {
+ this.visibilityDocument?.removeEventListener('visibilitychange', this.handleVisibilityChange);
+ this.visibilityDocument = null;
+ }
+
+ private readonly handleVisibilityChange = (): void => {
+ if (this.visibilityDocument?.visibilityState === 'hidden') this.finish();
+ };
+
+ private stopStream(): void {
+ if (this.streamStopped) return;
+ this.streamStopped = true;
+ this.options.stream.getTracks().forEach((track) => track.stop());
+ }
+}
diff --git a/ui/src/lib/voiceTelemetry.test.ts b/ui/src/lib/voiceTelemetry.test.ts
new file mode 100644
index 000000000..835b290eb
--- /dev/null
+++ b/ui/src/lib/voiceTelemetry.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ browserFamilyFromUserAgent,
+ emitVoiceTelemetry,
+} from './voiceTelemetry';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('voice telemetry', () => {
+ it.each([
+ ['CriOS/126.0 Mobile/15E148 Safari/604.1', 'chrome'],
+ ['FxiOS/127.0 Mobile/15E148 Safari/605.1.15', 'firefox'],
+ ['EdgiOS/126.0 Mobile/15E148 Safari/605.1.15', 'edge'],
+ ])('classifies iOS browser token %s as %s', (userAgent, expected) => {
+ expect(browserFamilyFromUserAgent(userAgent)).toBe(expected);
+ });
+
+ it('emits privacy-safe structured metadata without voice contents', async () => {
+ vi.stubGlobal('window', {});
+ vi.stubGlobal('navigator', { userAgent: 'Mozilla/5.0 Chrome/126.0 Safari/537.36' });
+ const telemetryFetch = vi.fn().mockResolvedValue(Response.json({ ok: true }));
+
+ emitVoiceTelemetry({
+ event: 'segment_transcription',
+ outcome: 'success',
+ dictationId: 'dictation-123',
+ path: 'cloud',
+ providerStage: 'response',
+ sizeBytes: 240_000,
+ mimeType: 'audio/webm',
+ durationMs: 60_000,
+ elapsedMs: 820,
+ attemptCount: 1,
+ }, telemetryFetch);
+
+ await vi.waitFor(() => expect(telemetryFetch).toHaveBeenCalledOnce());
+ const [path, init] = telemetryFetch.mock.calls[0]!;
+ const payload = JSON.parse(String(init?.body));
+ expect(path).toBe('/api/asr/telemetry');
+ expect(init).toMatchObject({ method: 'POST', keepalive: true });
+ expect(payload).toEqual({
+ event: 'segment_transcription',
+ outcome: 'success',
+ dictationId: 'dictation-123',
+ path: 'cloud',
+ providerStage: 'response',
+ sizeBytes: 240_000,
+ mimeType: 'audio/webm',
+ durationMs: 60_000,
+ elapsedMs: 820,
+ attemptCount: 1,
+ browserFamily: 'chrome',
+ });
+ expect(payload).not.toHaveProperty('audio');
+ expect(payload).not.toHaveProperty('transcript');
+ expect(payload).not.toHaveProperty('credential');
+ });
+});
diff --git a/ui/src/lib/voiceTelemetry.ts b/ui/src/lib/voiceTelemetry.ts
new file mode 100644
index 000000000..64a455915
--- /dev/null
+++ b/ui/src/lib/voiceTelemetry.ts
@@ -0,0 +1,62 @@
+import { apiFetch } from './apiFetch';
+
+export type VoiceTelemetryOutcome =
+ | 'success'
+ | 'fallback'
+ | 'cancelled'
+ | 'empty'
+ | 'failed'
+ | 'timeout'
+ | 'too_large'
+ | 'unavailable';
+
+export type VoiceTelemetryEvent = {
+ event: 'segment_transcription' | 'dictation_finalized' | 'dictation_inserted';
+ outcome: VoiceTelemetryOutcome;
+ dictationId?: string;
+ path?: 'cloud' | 'local';
+ providerStage?: 'token' | 'upload' | 'refresh' | 'response' | 'finalization';
+ sizeBytes?: number;
+ mimeType?: string;
+ durationMs?: number;
+ elapsedMs?: number;
+ httpStatus?: number;
+ attemptCount?: number;
+ segmentCount?: number;
+ failedSegmentCount?: number;
+ backlogAtStop?: number;
+ totalDurationMs?: number;
+ stopToInsertionMs?: number;
+ retry?: boolean;
+};
+
+type TelemetryFetch = (path: string, init?: RequestInit) => Promise<Response>;
+
+export const browserFamilyFromUserAgent = (userAgent: string): string => {
+ if (/Edg(?:iOS|A)?\//.test(userAgent)) return 'edge';
+ if (/Firefox\/|FxiOS\//.test(userAgent)) return 'firefox';
+ if (/Chrome\/|CriOS\//.test(userAgent)) return 'chrome';
+ if (/Safari\//.test(userAgent)) return 'safari';
+ return 'other';
+};
+
+const browserFamily = (): string => (
+ typeof navigator === 'undefined'
+ ? 'unknown'
+ : browserFamilyFromUserAgent(navigator.userAgent)
+);
+
+export const emitVoiceTelemetry = (
+ event: VoiceTelemetryEvent,
+ telemetryFetch: TelemetryFetch = apiFetch,
+): void => {
+ if (typeof window === 'undefined') return;
+ void telemetryFetch('/api/asr/telemetry', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...event, browserFamily: browserFamily() }),
+ keepalive: true,
+ }).catch(() => {
+ // Metrics must never delay or fail voice input.
+ });
+};
diff --git a/ui/src/lib/voiceTranscription.test.ts b/ui/src/lib/voiceTranscription.test.ts
new file mode 100644
index 000000000..7801704c2
--- /dev/null
+++ b/ui/src/lib/voiceTranscription.test.ts
@@ -0,0 +1,622 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ CloudUnavailableError,
+ CLOUD_TOKEN_MINT_TIMEOUT_MS,
+ type AvibeFetchRequestInit,
+} from './avibeFetch';
+import {
+ transcribeVoiceBlob,
+ VoiceTranscriptionQueue,
+ VoiceTranscriptionError,
+ transcribeVoiceSegments,
+ VOICE_TRANSCRIPTION_TIMEOUT_MS,
+ voiceTranscriptFromSegments,
+ voiceRecordingFileName,
+} from './voiceTranscription';
+
+const audioBlob = () => new Blob(['audio'], { type: 'audio/mp4; codecs=mp4a.40.2' });
+
+describe('voice transcription', () => {
+ it('reserves the complete upstream budget on the compatibility path', () => {
+ const compatibilityRequestBudget = (
+ VOICE_TRANSCRIPTION_TIMEOUT_MS
+ - CLOUD_TOKEN_MINT_TIMEOUT_MS
+ );
+
+ expect(compatibilityRequestBudget).toBeGreaterThanOrEqual(150_000);
+ });
+
+ it('uses the real container extension and normalized MIME type', async () => {
+ const telemetry = vi.fn();
+ const cloudFetch = vi.fn().mockImplementation(async (_path: string, init?: RequestInit) => {
+ const file = (init?.body as FormData).get('file') as File;
+ expect(file.name).toBe('voice.mp4');
+ expect(file.type).toBe('audio/mp4; codecs=mp4a.40.2');
+ return Response.json({ text: 'hello' });
+ });
+
+ await expect(transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ durationMs: 58_000,
+ attemptCount: 2,
+ dictationId: 'dictation-123',
+ telemetry,
+ })).resolves.toBe('hello');
+ expect(voiceRecordingFileName(audioBlob())).toBe('voice.mp4');
+ expect(telemetry).toHaveBeenCalledWith(expect.objectContaining({
+ event: 'segment_transcription',
+ outcome: 'success',
+ path: 'cloud',
+ providerStage: 'response',
+ dictationId: 'dictation-123',
+ sizeBytes: 5,
+ mimeType: 'audio/mp4',
+ durationMs: 58_000,
+ attemptCount: 2,
+ }));
+ });
+
+ it('uses the local compatibility route only when cloud credentials are unavailable', async () => {
+ const cloudFetch = vi.fn().mockRejectedValue(new CloudUnavailableError());
+ const localFetch = vi.fn().mockResolvedValue(Response.json({ text: 'local transcript' }));
+ const telemetry = vi.fn();
+
+ await expect(transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ localFetch,
+ telemetry,
+ })).resolves.toBe('local transcript');
+ expect(localFetch).toHaveBeenCalledTimes(1);
+ const payload = JSON.parse(String(localFetch.mock.calls[0]?.[1]?.body));
+ expect(payload).toMatchObject({ name: 'voice.mp4', mime: 'audio/mp4' });
+ expect(telemetry.mock.calls.map(([event]) => event)).toEqual([
+ expect.objectContaining({
+ path: 'cloud',
+ providerStage: 'token',
+ outcome: 'fallback',
+ }),
+ expect.objectContaining({
+ path: 'local',
+ providerStage: 'response',
+ outcome: 'success',
+ }),
+ ]);
+ });
+
+ it('reports the hidden 401 and the refreshed cloud upload as separate attempts', async () => {
+ const telemetry = vi.fn();
+ const cloudFetch = vi.fn().mockImplementation(
+ async (_path: string, init?: AvibeFetchRequestInit) => {
+ init?.onAttempt?.({ phase: 'started', attempt: 1 });
+ init?.onAttempt?.({
+ phase: 'response',
+ attempt: 1,
+ status: 401,
+ elapsedMs: 37,
+ });
+ init?.onAttempt?.({ phase: 'started', attempt: 2 });
+ return Response.json({ text: 'after refresh' });
+ },
+ );
+
+ await expect(transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ telemetry,
+ })).resolves.toBe('after refresh');
+
+ expect(telemetry.mock.calls.map(([event]) => event)).toEqual([
+ expect.objectContaining({
+ path: 'cloud',
+ providerStage: 'response',
+ outcome: 'failed',
+ httpStatus: 401,
+ elapsedMs: 37,
+ attemptCount: 1,
+ retry: false,
+ }),
+ expect.objectContaining({
+ path: 'cloud',
+ providerStage: 'response',
+ outcome: 'success',
+ attemptCount: 2,
+ retry: true,
+ }),
+ ]);
+ });
+
+ it('does not double-report a terminal 401 after refresh', async () => {
+ const telemetry = vi.fn();
+ const cloudFetch = vi.fn().mockImplementation(
+ async (_path: string, init?: AvibeFetchRequestInit) => {
+ init?.onAttempt?.({ phase: 'started', attempt: 1 });
+ init?.onAttempt?.({
+ phase: 'response',
+ attempt: 1,
+ status: 401,
+ elapsedMs: 12,
+ });
+ init?.onAttempt?.({ phase: 'started', attempt: 2 });
+ init?.onAttempt?.({
+ phase: 'response',
+ attempt: 2,
+ status: 401,
+ elapsedMs: 9,
+ });
+ return Response.json({ error: 'unauthorized' }, { status: 401 });
+ },
+ );
+
+ await expect(transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ telemetry,
+ })).rejects.toMatchObject({ code: 'failed', status: 401 });
+
+ expect(telemetry.mock.calls.map(([event]) => event)).toEqual([
+ expect.objectContaining({
+ outcome: 'failed',
+ httpStatus: 401,
+ attemptCount: 1,
+ }),
+ expect.objectContaining({
+ outcome: 'failed',
+ httpStatus: 401,
+ attemptCount: 2,
+ }),
+ ]);
+ });
+
+ it('keeps the original deadline when the compatibility route starts late', async () => {
+ vi.useFakeTimers();
+ try {
+ const cloudFetch = vi.fn(
+ async () =>
+ new Promise<Response>((_resolve, reject) => {
+ setTimeout(() => reject(new CloudUnavailableError()), 80);
+ }),
+ );
+ const localFetch = vi.fn(
+ async (_path: string, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener(
+ 'abort',
+ () => reject(init.signal?.reason),
+ { once: true },
+ );
+ }),
+ );
+
+ const transcription = transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ localFetch,
+ timeoutMs: 100,
+ });
+ const result = expect(transcription).rejects.toMatchObject({ code: 'timeout' });
+
+ await vi.advanceTimersByTimeAsync(80);
+ expect(localFetch).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(20);
+ await result;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('preserves timeout classification from the compatibility route', async () => {
+ const cloudFetch = vi.fn().mockRejectedValue(new CloudUnavailableError());
+ const localFetch = vi.fn().mockResolvedValue(
+ Response.json({ error: 'transcription_timeout' }, { status: 504 }),
+ );
+ const telemetry = vi.fn();
+
+ await expect(transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ localFetch,
+ telemetry,
+ })).rejects.toMatchObject({ code: 'timeout', status: 504 });
+ expect(telemetry).toHaveBeenCalledWith(expect.objectContaining({
+ path: 'local',
+ providerStage: 'response',
+ outcome: 'timeout',
+ httpStatus: 504,
+ }));
+ });
+
+ it('preserves empty-audio classification from the compatibility route', async () => {
+ const cloudFetch = vi.fn().mockRejectedValue(new CloudUnavailableError());
+ const localFetch = vi.fn().mockResolvedValue(
+ Response.json({ error: 'transcription_empty' }, { status: 422 }),
+ );
+ const telemetry = vi.fn();
+
+ await expect(transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ localFetch,
+ telemetry,
+ })).rejects.toMatchObject({ code: 'empty', status: 422 });
+ expect(telemetry).toHaveBeenCalledWith(expect.objectContaining({
+ path: 'local',
+ providerStage: 'response',
+ outcome: 'empty',
+ httpStatus: 422,
+ }));
+ });
+
+ it('does not duplicate an audio upload after the cloud has returned an error', async () => {
+ const cloudFetch = vi.fn().mockResolvedValue(
+ Response.json({ error: 'transcription_failed' }, { status: 502 }),
+ );
+ const localFetch = vi.fn();
+
+ await expect(transcribeVoiceBlob(audioBlob(), { cloudFetch, localFetch })).rejects.toMatchObject({
+ code: 'failed',
+ status: 502,
+ });
+ expect(localFetch).not.toHaveBeenCalled();
+ });
+
+ it('does not use the compatibility route after a cloud upload started', async () => {
+ const telemetry = vi.fn();
+ const cloudFetch = vi.fn().mockRejectedValue(
+ new CloudUnavailableError('cloud_refresh_unavailable', { uploadStarted: true }),
+ );
+ const localFetch = vi.fn();
+
+ await expect(
+ transcribeVoiceBlob(audioBlob(), { cloudFetch, localFetch, telemetry }),
+ ).rejects.toMatchObject({ code: 'unavailable' });
+ expect(localFetch).not.toHaveBeenCalled();
+ expect(telemetry).toHaveBeenCalledWith(expect.objectContaining({
+ outcome: 'unavailable',
+ path: 'cloud',
+ providerStage: 'refresh',
+ }));
+ });
+
+ it('classifies direct cloud transport failures as unavailable without fallback', async () => {
+ const telemetry = vi.fn();
+ const cloudFetch = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'));
+ const localFetch = vi.fn();
+
+ await expect(
+ transcribeVoiceBlob(audioBlob(), { cloudFetch, localFetch, telemetry }),
+ ).rejects.toMatchObject({ code: 'unavailable' });
+ expect(localFetch).not.toHaveBeenCalled();
+ expect(telemetry).toHaveBeenCalledWith(expect.objectContaining({
+ outcome: 'unavailable',
+ path: 'cloud',
+ providerStage: 'upload',
+ }));
+ });
+
+ it.each([
+ ['malformed JSON', () => new Response('{', {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }), 'failed'],
+ ['missing text', () => Response.json({ result: 'hello' }), 'failed'],
+ ['empty text', () => Response.json({ text: ' ' }), 'empty'],
+ ])('classifies a 2xx %s payload as %s', async (_case, response, expectedCode) => {
+ const cloudFetch = vi.fn().mockImplementation(response);
+ const telemetry = vi.fn();
+
+ await expect(
+ transcribeVoiceBlob(audioBlob(), { cloudFetch, telemetry }),
+ ).rejects.toMatchObject({ code: expectedCode, status: 200 });
+ expect(telemetry).toHaveBeenCalledWith(expect.objectContaining({
+ outcome: expectedCode,
+ path: 'cloud',
+ providerStage: 'response',
+ httpStatus: 200,
+ }));
+ });
+
+ it('stops a hung cloud request without starting the compatibility route', async () => {
+ const cloudFetch = vi.fn().mockImplementation(
+ async (_path: string, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true });
+ }),
+ );
+ const localFetch = vi.fn();
+
+ await expect(
+ transcribeVoiceBlob(audioBlob(), { cloudFetch, localFetch, timeoutMs: 5 }),
+ ).rejects.toMatchObject({ code: 'timeout' });
+ expect(cloudFetch).toHaveBeenCalledTimes(1);
+ expect(localFetch).not.toHaveBeenCalled();
+ });
+
+ it('reports deliberate cancellation separately from a deadline timeout', async () => {
+ const controller = new AbortController();
+ const telemetry = vi.fn();
+ const cloudFetch = vi.fn().mockImplementation(
+ async (_path: string, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true });
+ }),
+ );
+
+ const transcription = transcribeVoiceBlob(audioBlob(), {
+ cloudFetch,
+ signal: controller.signal,
+ telemetry,
+ });
+ controller.abort();
+
+ await expect(transcription).rejects.toMatchObject({ code: 'cancelled' });
+ expect(telemetry).toHaveBeenCalledWith(expect.objectContaining({
+ event: 'segment_transcription',
+ outcome: 'cancelled',
+ path: 'cloud',
+ }));
+ expect(telemetry).not.toHaveBeenCalledWith(expect.objectContaining({
+ outcome: 'timeout',
+ }));
+ });
+
+ it.each([
+ [413, 'file_too_large', 'too_large'],
+ [504, 'transcription_timeout', 'timeout'],
+ [503, 'asr_not_configured', 'unavailable'],
+ [400, 'asr_unavailable', 'unavailable'],
+ ] as const)('maps status %s to %s', async (status, upstreamCode, expectedCode) => {
+ const cloudFetch = vi.fn().mockResolvedValue(
+ Response.json({ error: upstreamCode }, { status }),
+ );
+
+ await expect(transcribeVoiceBlob(audioBlob(), { cloudFetch })).rejects.toEqual(
+ expect.objectContaining({ code: expectedCode, status }),
+ );
+ });
+
+ it('joins independently transcribed segments in capture order', async () => {
+ const segments = [
+ { blob: new Blob(['one']), text: 'first' },
+ { blob: new Blob(['two']) },
+ { blob: new Blob(['three']) },
+ ];
+ const transcribe = vi.fn(async (blob: Blob) => blob.text());
+
+ await transcribeVoiceSegments(segments, { concurrency: 2, transcribe });
+
+ expect(transcribe).toHaveBeenCalledTimes(2);
+ expect(voiceTranscriptFromSegments(segments)).toBe('first two three');
+ });
+
+ it('bounds incrementally queued initial transcriptions', async () => {
+ const releases: Array<() => void> = [];
+ let active = 0;
+ let maxActive = 0;
+ const transcribe = vi.fn(async (blob: Blob) => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ await new Promise<void>((resolve) => releases.push(resolve));
+ active -= 1;
+ return blob.text();
+ });
+ const queue = new VoiceTranscriptionQueue({ concurrency: 2, transcribe });
+ const segments = Array.from(
+ { length: 5 },
+ (_value, index) => ({ blob: new Blob([String(index)]) }),
+ );
+
+ const tasks = segments.map((segment) => queue.enqueue(segment));
+ expect(transcribe).toHaveBeenCalledTimes(2);
+
+ releases.splice(0, 2).forEach((release) => release());
+ await vi.waitFor(() => expect(transcribe).toHaveBeenCalledTimes(4));
+ releases.splice(0, 2).forEach((release) => release());
+ await vi.waitFor(() => expect(transcribe).toHaveBeenCalledTimes(5));
+ releases.splice(0).forEach((release) => release());
+ await Promise.all(tasks);
+
+ expect(maxActive).toBe(2);
+ expect(segments.map((segment) => segment.text)).toEqual(['0', '1', '2', '3', '4']);
+ expect(segments.map((segment) => segment.attemptCount)).toEqual([1, 1, 1, 1, 1]);
+ });
+
+ it('cancels active retries without starting queued segments', async () => {
+ const controller = new AbortController();
+ const cloudFetch = vi.fn(
+ (_path: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => {
+ reject(new DOMException('Aborted', 'AbortError'));
+ }, { once: true });
+ }),
+ );
+ const segments = Array.from(
+ { length: 5 },
+ () => ({ blob: audioBlob() }),
+ );
+
+ const transcription = transcribeVoiceSegments(segments, {
+ cloudFetch,
+ concurrency: 2,
+ signal: controller.signal,
+ });
+ await vi.waitFor(() => expect(cloudFetch).toHaveBeenCalledTimes(2));
+ controller.abort();
+ await transcription;
+
+ expect(cloudFetch).toHaveBeenCalledTimes(2);
+ expect(segments.slice(0, 2)).toEqual([
+ expect.objectContaining({
+ attemptCount: 1,
+ error: expect.objectContaining({ code: 'cancelled' }),
+ }),
+ expect.objectContaining({
+ attemptCount: 1,
+ error: expect.objectContaining({ code: 'cancelled' }),
+ }),
+ ]);
+ expect(segments.slice(2)).toEqual([
+ expect.not.objectContaining({ attemptCount: expect.anything() }),
+ expect.not.objectContaining({ attemptCount: expect.anything() }),
+ expect.not.objectContaining({ attemptCount: expect.anything() }),
+ ]);
+ });
+
+ it('discards pending initial transcriptions when capture is discarded', async () => {
+ const controller = new AbortController();
+ const cloudFetch = vi.fn(
+ (_path: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => {
+ reject(new DOMException('Aborted', 'AbortError'));
+ }, { once: true });
+ }),
+ );
+ const queue = new VoiceTranscriptionQueue({
+ cloudFetch,
+ concurrency: 2,
+ signal: controller.signal,
+ });
+ const segments = Array.from(
+ { length: 5 },
+ () => ({ blob: audioBlob() }),
+ );
+
+ const tasks = segments.map((segment) => queue.enqueue(segment));
+ await vi.waitFor(() => expect(cloudFetch).toHaveBeenCalledTimes(2));
+ controller.abort();
+ await Promise.all(tasks);
+
+ expect(cloudFetch).toHaveBeenCalledTimes(2);
+ expect(segments.slice(0, 2)).toEqual([
+ expect.objectContaining({
+ attemptCount: 1,
+ error: expect.objectContaining({ code: 'cancelled' }),
+ }),
+ expect.objectContaining({
+ attemptCount: 1,
+ error: expect.objectContaining({ code: 'cancelled' }),
+ }),
+ ]);
+ expect(segments.slice(2)).toEqual([
+ expect.not.objectContaining({ attemptCount: expect.anything() }),
+ expect.not.objectContaining({ attemptCount: expect.anything() }),
+ expect.not.objectContaining({ attemptCount: expect.anything() }),
+ ]);
+ });
+
+ it.each([
+ [['你好', '世界'], '你好世界'],
+ [['hello', 'world'], 'hello world'],
+ [['hello ', 'world'], 'hello world'],
+ [['123', '456'], '123456'],
+ [['https://example.', 'com/path'], 'https://example.com/path'],
+ [['https://example.', 'technology'], 'https://example.technology'],
+ [['example.', 'cn/path'], 'example.cn/path'],
+ [['example.', 'co.uk/path'], 'example.co.uk/path'],
+ [['sentence.', 'cn'], 'sentence. cn'],
+ [['voice_input-', 'reliability'], 'voice_input-reliability'],
+ [['hello,', 'world'], 'hello, world'],
+ [['use camelCase', 'notation matters'], 'use camelCase notation matters'],
+ [['camel', 'Case'], 'camel Case'],
+ [['we met', 'Alice yesterday'], 'we met Alice yesterday'],
+ [['first paragraph\n\n', 'second paragraph'], 'first paragraph\n\nsecond paragraph'],
+ [['hello.', 'world'], 'hello. world'],
+ ])('joins segment boundaries without corrupting language or tokens', (parts, expected) => {
+ expect(voiceTranscriptFromSegments(
+ parts.map((text) => ({ blob: new Blob(), text })),
+ )).toBe(expected);
+ });
+
+ it('removes transcript duplicated by acoustic segment overlap', () => {
+ expect(voiceTranscriptFromSegments([
+ { blob: new Blob(), text: 'Please ship reliable voice input' },
+ {
+ blob: new Blob(),
+ text: 'reliable voice input today',
+ overlapMs: 500,
+ },
+ ])).toBe('Please ship reliable voice input today');
+ expect(voiceTranscriptFromSegments([
+ { blob: new Blob(), text: '今天讨论语音输入稳定性' },
+ {
+ blob: new Blob(),
+ text: '语音输入稳定性和延迟',
+ overlapMs: 500,
+ },
+ ])).toBe('今天讨论语音输入稳定性和延迟');
+ expect(voiceTranscriptFromSegments([
+ { blob: new Blob(), text: 'use cat' },
+ {
+ blob: new Blob(),
+ text: 'category labels',
+ overlapMs: 500,
+ },
+ ])).toBe('use cat category labels');
+ expect(voiceTranscriptFromSegments([
+ { blob: new Blob(), text: 'first paragraph' },
+ {
+ blob: new Blob(),
+ text: '\n\nsecond paragraph',
+ overlapMs: 500,
+ },
+ ])).toBe('first paragraph\n\nsecond paragraph');
+ expect(voiceTranscriptFromSegments([
+ { blob: new Blob(), text: 'first paragraph' },
+ {
+ blob: new Blob(),
+ text: 'paragraph\n\nsecond paragraph',
+ overlapMs: 500,
+ },
+ ])).toBe('first paragraph\n\nsecond paragraph');
+ });
+
+ it('skips silent segments unless the whole dictation is silent', () => {
+ const empty = new VoiceTranscriptionError('empty');
+ expect(voiceTranscriptFromSegments([
+ { blob: new Blob(), text: 'first' },
+ { blob: new Blob(), error: empty },
+ { blob: new Blob(), text: 'second' },
+ ])).toBe('first second');
+
+ expect(() => voiceTranscriptFromSegments([
+ { blob: new Blob(), error: empty },
+ { blob: new Blob(), error: new VoiceTranscriptionError('empty') },
+ ])).toThrowError(empty);
+ });
+
+ it('does not resubmit accepted silent segments during explicit retry', async () => {
+ const silent = {
+ blob: new Blob(['silent']),
+ error: new VoiceTranscriptionError('empty'),
+ };
+ const failed = {
+ blob: new Blob(['failed']),
+ error: new VoiceTranscriptionError('failed'),
+ };
+ const transcribe = vi.fn(async () => 'recovered');
+
+ await transcribeVoiceSegments([silent, failed], { transcribe });
+
+ expect(transcribe).toHaveBeenCalledOnce();
+ expect(transcribe).toHaveBeenCalledWith(failed.blob);
+ expect(silent.error).toMatchObject({ code: 'empty' });
+ expect(failed).toMatchObject({ text: 'recovered', error: undefined });
+ });
+
+ it('retries only failed segments without discarding completed text', async () => {
+ const failed = new Error('provider failed');
+ const segments = [
+ { blob: new Blob(['one']) },
+ { blob: new Blob(['two']) },
+ ];
+ const firstAttempt = vi
+ .fn<(blob: Blob) => Promise<string>>()
+ .mockResolvedValueOnce('first')
+ .mockRejectedValueOnce(failed);
+
+ await transcribeVoiceSegments(segments, { transcribe: firstAttempt });
+ expect(() => voiceTranscriptFromSegments(segments)).toThrow(failed);
+
+ const retry = vi.fn(async (blob: Blob) => blob.text());
+ await transcribeVoiceSegments(segments, { transcribe: retry });
+
+ expect(retry).toHaveBeenCalledTimes(1);
+ expect(await retry.mock.calls[0]?.[0].text()).toBe('two');
+ expect(voiceTranscriptFromSegments(segments)).toBe('first two');
+ });
+});
diff --git a/ui/src/lib/voiceTranscription.ts b/ui/src/lib/voiceTranscription.ts
new file mode 100644
index 000000000..032082aa9
--- /dev/null
+++ b/ui/src/lib/voiceTranscription.ts
@@ -0,0 +1,570 @@
+import { apiFetch } from './apiFetch';
+import {
+ avibeFetch,
+ CLOUD_TOKEN_MINT_TIMEOUT_MS,
+ CloudUnavailableError,
+ type AvibeFetchAttemptEvent,
+ type AvibeFetchRequestInit,
+} from './avibeFetch';
+import {
+ emitVoiceTelemetry,
+ type VoiceTelemetryEvent,
+ type VoiceTelemetryOutcome,
+} from './voiceTelemetry';
+
+export const VOICE_SEGMENT_MS = 60_000;
+export const VOICE_TRANSCRIPTION_CONCURRENCY = 2;
+
+const COMPATIBILITY_UPSTREAM_TIMEOUT_MS = 120_000;
+const COMPATIBILITY_UPLOAD_BUDGET_MS = 30_000;
+const COMPATIBILITY_CSRF_ALLOWANCE_MS = 4_000;
+export const VOICE_TRANSCRIPTION_TIMEOUT_MS = (
+ CLOUD_TOKEN_MINT_TIMEOUT_MS
+ + COMPATIBILITY_CSRF_ALLOWANCE_MS
+ + COMPATIBILITY_UPLOAD_BUDGET_MS
+ + COMPATIBILITY_UPSTREAM_TIMEOUT_MS
+);
+
+const EXTENSION_BY_MIME: Record<string, string> = {
+ 'audio/aac': 'aac',
+ 'audio/mp4': 'mp4',
+ 'audio/mpeg': 'mp3',
+ 'audio/ogg': 'ogg',
+ 'audio/opus': 'opus',
+ 'audio/wav': 'wav',
+ 'audio/webm': 'webm',
+ 'audio/x-m4a': 'm4a',
+};
+
+export type VoiceTranscriptionErrorCode =
+ | 'cancelled'
+ | 'empty'
+ | 'failed'
+ | 'timeout'
+ | 'too_large'
+ | 'unavailable';
+
+export class VoiceTranscriptionError extends Error {
+ readonly code: VoiceTranscriptionErrorCode;
+ readonly status?: number;
+
+ constructor(code: VoiceTranscriptionErrorCode, options: { cause?: unknown; status?: number } = {}) {
+ super(code, { cause: options.cause });
+ this.name = 'VoiceTranscriptionError';
+ this.code = code;
+ this.status = options.status;
+ }
+}
+
+type VoiceFetch = (path: string, init?: RequestInit) => Promise<Response>;
+type VoiceCloudFetch = (path: string, init?: AvibeFetchRequestInit) => Promise<Response>;
+
+export type VoiceTranscriptionDependencies = {
+ cloudFetch?: VoiceCloudFetch;
+ localFetch?: VoiceFetch;
+ signal?: AbortSignal;
+ timeoutMs?: number;
+ durationMs?: number;
+ attemptCount?: number;
+ dictationId?: string;
+ telemetry?: (event: VoiceTelemetryEvent) => void;
+};
+
+export type VoiceTranscriptionSegment = {
+ blob: Blob;
+ durationMs?: number;
+ overlapMs?: number;
+ attemptCount?: number;
+ text?: string;
+ error?: unknown;
+};
+
+const isEmptyVoiceSegment = (segment: VoiceTranscriptionSegment): boolean => (
+ segment.error instanceof VoiceTranscriptionError
+ && segment.error.code === 'empty'
+ && !segment.text
+);
+
+type VoiceSegmentTranscriptionDependencies = VoiceTranscriptionDependencies & {
+ transcribe?: (blob: Blob) => Promise<string>;
+};
+
+const normalizedMimeType = (blob: Blob): string =>
+ blob.type.split(';', 1)[0]?.trim().toLowerCase() || 'audio/webm';
+
+export const voiceRecordingFileName = (blob: Blob): string =>
+ `voice.${EXTENSION_BY_MIME[normalizedMimeType(blob)] ?? 'webm'}`;
+
+const requestTimeout = (durationMs: number, externalSignal?: AbortSignal) => {
+ const controller = new AbortController();
+ const abortFromExternal = () => controller.abort(externalSignal?.reason);
+ if (externalSignal?.aborted) {
+ abortFromExternal();
+ } else {
+ externalSignal?.addEventListener('abort', abortFromExternal, { once: true });
+ }
+ const timer = globalThis.setTimeout(
+ () => controller.abort(new DOMException('transcription timed out', 'TimeoutError')),
+ durationMs,
+ );
+ return {
+ signal: controller.signal,
+ cancel: () => {
+ globalThis.clearTimeout(timer);
+ externalSignal?.removeEventListener('abort', abortFromExternal);
+ },
+ };
+};
+
+const isAbortError = (error: unknown): boolean =>
+ error instanceof DOMException && error.name === 'AbortError';
+
+const isTimeoutError = (error: unknown): boolean =>
+ error instanceof DOMException && error.name === 'TimeoutError';
+
+const normalizeTranscriptionError = (
+ error: unknown,
+ signal: AbortSignal,
+): VoiceTranscriptionError => {
+ if (error instanceof VoiceTranscriptionError) return error;
+ if (isTimeoutError(error) || isTimeoutError(signal.reason)) {
+ return new VoiceTranscriptionError('timeout', { cause: error });
+ }
+ if (isAbortError(error) || signal.aborted) {
+ return new VoiceTranscriptionError('cancelled', { cause: error });
+ }
+ return new VoiceTranscriptionError('failed', { cause: error });
+};
+
+const telemetryOutcome = (error: VoiceTranscriptionError): VoiceTelemetryOutcome => error.code;
+
+const responseError = async (response: Response): Promise<VoiceTranscriptionError> => {
+ const payload = (await response.json().catch(() => null)) as { error?: unknown } | null;
+ const upstreamCode = typeof payload?.error === 'string' ? payload.error : '';
+ if (response.status === 413 || upstreamCode === 'file_too_large') {
+ return new VoiceTranscriptionError('too_large', { status: response.status });
+ }
+ if (response.status === 504 || upstreamCode === 'transcription_timeout') {
+ return new VoiceTranscriptionError('timeout', { status: response.status });
+ }
+ if (upstreamCode === 'transcription_empty') {
+ return new VoiceTranscriptionError('empty', { status: response.status });
+ }
+ if (
+ response.status === 503
+ || upstreamCode === 'asr_not_configured'
+ || upstreamCode === 'asr_unavailable'
+ ) {
+ return new VoiceTranscriptionError('unavailable', { status: response.status });
+ }
+ return new VoiceTranscriptionError('failed', { status: response.status });
+};
+
+const responseText = async (response: Response): Promise<string> => {
+ if (!response.ok) throw await responseError(response);
+ const payload = await response.json().catch(() => null) as unknown;
+ if (
+ payload == null
+ || typeof payload !== 'object'
+ || Array.isArray(payload)
+ || typeof (payload as { text?: unknown }).text !== 'string'
+ ) {
+ throw new VoiceTranscriptionError('failed', { status: response.status });
+ }
+ const { text } = payload as { text: string };
+ if (!text.trim()) throw new VoiceTranscriptionError('empty', { status: response.status });
+ return text;
+};
+
+const readBlobAsBase64 = async (blob: Blob): Promise<string> => {
+ if (typeof FileReader === 'undefined') {
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ let binary = '';
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary);
+ }
+ return new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onerror = () => reject(reader.error);
+ reader.onload = () => {
+ const dataUrl = String(reader.result || '');
+ const comma = dataUrl.indexOf(',');
+ resolve(comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl);
+ };
+ reader.readAsDataURL(blob);
+ });
+};
+
+const transcribeLocally = async (
+ blob: Blob,
+ localFetch: VoiceFetch,
+ signal: AbortSignal,
+): Promise<string> => {
+ try {
+ const data = await readBlobAsBase64(blob);
+ const response = await localFetch('/api/asr/transcribe', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: voiceRecordingFileName(blob),
+ mime: normalizedMimeType(blob),
+ data,
+ }),
+ signal,
+ });
+ return await responseText(response);
+ } catch (error) {
+ throw normalizeTranscriptionError(error, signal);
+ }
+};
+
+export const transcribeVoiceBlob = async (
+ blob: Blob,
+ dependencies: VoiceTranscriptionDependencies = {},
+): Promise<string> => {
+ const cloudFetch = dependencies.cloudFetch ?? avibeFetch;
+ const localFetch = dependencies.localFetch ?? apiFetch;
+ const timeoutMs = dependencies.timeoutMs ?? VOICE_TRANSCRIPTION_TIMEOUT_MS;
+ const telemetry = dependencies.telemetry ?? emitVoiceTelemetry;
+ const attemptCount = dependencies.attemptCount ?? 1;
+ const timeout = requestTimeout(timeoutMs, dependencies.signal);
+ let cloudAttemptCount = attemptCount;
+ let cloudStageStartedAt = Date.now();
+ const report = (
+ path: 'cloud' | 'local',
+ providerStage: NonNullable<VoiceTelemetryEvent['providerStage']>,
+ outcome: VoiceTelemetryOutcome,
+ startedAt: number,
+ error?: VoiceTranscriptionError,
+ overrides: {
+ attemptCount?: number;
+ elapsedMs?: number;
+ httpStatus?: number;
+ } = {},
+ ) => {
+ const reportedAttemptCount = overrides.attemptCount ?? attemptCount;
+ try {
+ telemetry({
+ event: 'segment_transcription',
+ path,
+ providerStage,
+ outcome,
+ dictationId: dependencies.dictationId,
+ sizeBytes: blob.size,
+ mimeType: normalizedMimeType(blob),
+ durationMs: dependencies.durationMs,
+ elapsedMs: overrides.elapsedMs ?? Date.now() - startedAt,
+ httpStatus: overrides.httpStatus ?? error?.status,
+ attemptCount: reportedAttemptCount,
+ retry: reportedAttemptCount > 1,
+ });
+ } catch {
+ // Instrumentation cannot change transcription behavior.
+ }
+ };
+ const handleCloudAttempt = (event: AvibeFetchAttemptEvent): void => {
+ if (event.phase === 'started') {
+ cloudAttemptCount = attemptCount + event.attempt - 1;
+ cloudStageStartedAt = Date.now();
+ return;
+ }
+ // Only the first 401 is hidden inside avibeFetch. The caller receives and
+ // reports every terminal response, including a second 401 after refresh.
+ if (event.attempt !== 1 || event.status !== 401) return;
+ report(
+ 'cloud',
+ 'response',
+ 'failed',
+ cloudStageStartedAt,
+ undefined,
+ {
+ attemptCount: attemptCount + event.attempt - 1,
+ elapsedMs: event.elapsedMs,
+ httpStatus: event.status,
+ },
+ );
+ // A refresh failure is a distinct stage, and a successful refresh will
+ // replace this timestamp when the second HTTP attempt starts.
+ cloudStageStartedAt = Date.now();
+ };
+ try {
+ const form = new FormData();
+ form.set('file', blob, voiceRecordingFileName(blob));
+ const response = await cloudFetch('/api/cloud/audio/transcriptions', {
+ method: 'POST',
+ body: form,
+ signal: timeout.signal,
+ onAttempt: handleCloudAttempt,
+ });
+ const text = await responseText(response);
+ report(
+ 'cloud',
+ 'response',
+ 'success',
+ cloudStageStartedAt,
+ undefined,
+ { attemptCount: cloudAttemptCount },
+ );
+ return text;
+ } catch (error) {
+ if (error instanceof CloudUnavailableError && !error.uploadStarted) {
+ report('cloud', 'token', 'fallback', cloudStageStartedAt);
+ const localStartedAt = Date.now();
+ try {
+ const text = await transcribeLocally(blob, localFetch, timeout.signal);
+ report('local', 'response', 'success', localStartedAt);
+ return text;
+ } catch (localError) {
+ const normalized = normalizeTranscriptionError(localError, timeout.signal);
+ report(
+ 'local',
+ normalized.status == null ? 'upload' : 'response',
+ telemetryOutcome(normalized),
+ localStartedAt,
+ normalized,
+ );
+ throw normalized;
+ }
+ }
+ const normalized = error instanceof CloudUnavailableError
+ || (error instanceof TypeError && !timeout.signal.aborted)
+ ? new VoiceTranscriptionError('unavailable', { cause: error })
+ : normalizeTranscriptionError(error, timeout.signal);
+ const providerStage = error instanceof CloudUnavailableError
+ ? 'refresh'
+ : normalized.status == null
+ ? 'upload'
+ : 'response';
+ report(
+ 'cloud',
+ providerStage,
+ telemetryOutcome(normalized),
+ cloudStageStartedAt,
+ normalized,
+ { attemptCount: cloudAttemptCount },
+ );
+ throw normalized;
+ } finally {
+ timeout.cancel();
+ }
+};
+
+const transcribeVoiceSegment = async (
+ segment: VoiceTranscriptionSegment,
+ dependencies: VoiceSegmentTranscriptionDependencies,
+): Promise<void> => {
+ const { transcribe, ...transcriptionDependencies } = dependencies;
+ segment.error = undefined;
+ segment.attemptCount = (segment.attemptCount ?? 0) + 1;
+ try {
+ segment.text = transcribe
+ ? await transcribe(segment.blob)
+ : await transcribeVoiceBlob(segment.blob, {
+ ...transcriptionDependencies,
+ durationMs: segment.durationMs,
+ attemptCount: segment.attemptCount,
+ });
+ } catch (error) {
+ segment.error = error;
+ }
+};
+
+type VoiceTranscriptionQueueEntry = {
+ segment: VoiceTranscriptionSegment;
+ resolve: () => void;
+};
+
+export class VoiceTranscriptionQueue {
+ private readonly concurrency: number;
+ private readonly dependencies: VoiceSegmentTranscriptionDependencies;
+ private readonly signal?: AbortSignal;
+ private readonly pending: VoiceTranscriptionQueueEntry[] = [];
+ private active = 0;
+
+ constructor(
+ dependencies: VoiceSegmentTranscriptionDependencies & {
+ concurrency?: number;
+ } = {},
+ ) {
+ const {
+ concurrency: requestedConcurrency = VOICE_TRANSCRIPTION_CONCURRENCY,
+ ...transcriptionDependencies
+ } = dependencies;
+ this.concurrency = Math.max(1, Math.floor(requestedConcurrency));
+ this.dependencies = transcriptionDependencies;
+ this.signal = transcriptionDependencies.signal;
+ this.signal?.addEventListener('abort', this.discardPending, { once: true });
+ }
+
+ enqueue(segment: VoiceTranscriptionSegment): Promise<void> {
+ const task = new Promise<void>((resolve) => {
+ this.pending.push({ segment, resolve });
+ });
+ this.pump();
+ return task;
+ }
+
+ private pump(): void {
+ if (this.signal?.aborted) {
+ this.discardPending();
+ return;
+ }
+ while (this.active < this.concurrency) {
+ const entry = this.pending.shift();
+ if (!entry) return;
+ this.active += 1;
+ void this.run(entry);
+ }
+ }
+
+ private readonly discardPending = (): void => {
+ let entry = this.pending.shift();
+ while (entry) {
+ entry.resolve();
+ entry = this.pending.shift();
+ }
+ };
+
+ private async run(entry: VoiceTranscriptionQueueEntry): Promise<void> {
+ try {
+ await transcribeVoiceSegment(entry.segment, this.dependencies);
+ } finally {
+ this.active -= 1;
+ entry.resolve();
+ this.pump();
+ }
+ }
+}
+
+export const transcribeVoiceSegments = async (
+ segments: VoiceTranscriptionSegment[],
+ dependencies: VoiceTranscriptionDependencies & {
+ concurrency?: number;
+ transcribe?: (blob: Blob) => Promise<string>;
+ } = {},
+): Promise<void> => {
+ const {
+ concurrency: requestedConcurrency = 2,
+ transcribe: customTranscribe,
+ ...transcriptionDependencies
+ } = dependencies;
+ const queue = segments.filter((segment) => (
+ !segment.text && !isEmptyVoiceSegment(segment)
+ ));
+ const concurrency = Math.max(1, Math.floor(requestedConcurrency));
+ const worker = async () => {
+ let segment = queue.shift();
+ while (segment) {
+ if (transcriptionDependencies.signal?.aborted) return;
+ await transcribeVoiceSegment(segment, {
+ ...transcriptionDependencies,
+ transcribe: customTranscribe,
+ });
+ segment = queue.shift();
+ }
+ };
+ await Promise.all(
+ Array.from({ length: Math.min(concurrency, queue.length) }, () => worker()),
+ );
+};
+
+const NO_SPACE_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;
+const WORD_CHARACTER = /[\p{L}\p{N}]/u;
+const CLOSING_PUNCTUATION = /^[,.;:!?%)\]},。;:!?)》】」』]/u;
+const OPENING_PUNCTUATION = /[([{(《【「『]$/u;
+const DOMAIN_SUFFIX = /^(?:\p{L}{2,63}|xn--[a-z0-9-]{1,59})(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*(?:[/:?#]|$)/iu;
+const EXPLICIT_URL_OR_EMAIL = /^(?:[a-z][a-z\d+.-]*:\/\/|www\.|[^@\s]+@)/iu;
+
+const continuesDomain = (leftToken: string, rightToken: string): boolean => {
+ if (!leftToken.endsWith('.')) return false;
+ const suffix = rightToken.match(DOMAIN_SUFFIX)?.[0];
+ if (!suffix) return false;
+ return EXPLICIT_URL_OR_EMAIL.test(leftToken) || /[/:?#]$/u.test(suffix);
+};
+
+const voiceSegmentSeparator = (left: string, right: string): string => {
+ const leftCharacter = left.at(-1) ?? '';
+ const rightCharacter = right.at(0) ?? '';
+ if (!leftCharacter || !rightCharacter || /\s/u.test(leftCharacter + rightCharacter)) return '';
+ if (NO_SPACE_SCRIPT.test(leftCharacter) || NO_SPACE_SCRIPT.test(rightCharacter)) return '';
+ if (CLOSING_PUNCTUATION.test(rightCharacter) || OPENING_PUNCTUATION.test(leftCharacter)) return '';
+
+ const leftToken = left.match(/\S+$/u)?.[0] ?? '';
+ const rightToken = right.match(/^\S+/u)?.[0] ?? '';
+ if (
+ /[-'@/_#=+%&?]$/u.test(leftToken)
+ || /^[-'@/_#=+%&?]/u.test(rightToken)
+ || (/^\p{N}+$/u.test(leftToken) && /^\p{N}+$/u.test(rightToken))
+ || (
+ /[\p{N}][.,:]$/u.test(leftToken)
+ && /^\p{N}/u.test(rightToken)
+ )
+ || continuesDomain(leftToken, rightToken)
+ ) {
+ return '';
+ }
+
+ if (WORD_CHARACTER.test(rightCharacter)) return ' ';
+ return '';
+};
+
+const trimTranscribedOverlap = (left: string, right: string): string => {
+ const candidate = right.trimStart();
+ const leftFolded = left.toLocaleLowerCase();
+ const candidateFolded = candidate.toLocaleLowerCase();
+ for (
+ let length = Math.min(leftFolded.length, candidateFolded.length);
+ length > 0;
+ length -= 1
+ ) {
+ const overlap = candidateFolded.slice(0, length);
+ if (!leftFolded.endsWith(overlap)) continue;
+
+ const leftStart = left.length - length;
+ const leftBefore = left.at(leftStart - 1) ?? '';
+ const overlapFirst = candidate.at(0) ?? '';
+ const overlapLast = candidate.at(length - 1) ?? '';
+ const rightAfter = candidate.at(length) ?? '';
+ const containsNoSpaceScript = NO_SPACE_SCRIPT.test(overlap);
+ if (
+ !containsNoSpaceScript
+ && (
+ (WORD_CHARACTER.test(leftBefore) && WORD_CHARACTER.test(overlapFirst))
+ || (WORD_CHARACTER.test(overlapLast) && WORD_CHARACTER.test(rightAfter))
+ )
+ ) {
+ continue;
+ }
+ return candidate.slice(length);
+ }
+ return right;
+};
+
+export const voiceTranscriptFromSegments = (
+ segments: VoiceTranscriptionSegment[],
+): string => {
+ const failed = segments.find((segment) => (
+ !isEmptyVoiceSegment(segment)
+ && (segment.error || !segment.text)
+ ));
+ if (failed) {
+ if (failed.error instanceof Error) throw failed.error;
+ throw new VoiceTranscriptionError('failed', { cause: failed.error });
+ }
+ const transcribed = segments.filter((segment) => Boolean(segment.text));
+ if (!transcribed.length) {
+ const emptyError = segments.find(isEmptyVoiceSegment)?.error;
+ if (emptyError instanceof Error) throw emptyError;
+ throw new VoiceTranscriptionError('empty');
+ }
+ const text = transcribed.reduce((joined, segment) => {
+ const rawPart = segment.text ?? '';
+ const part = joined && (segment.overlapMs ?? 0) > 0
+ ? trimTranscribedOverlap(joined, rawPart)
+ : rawPart;
+ if (!part) return joined;
+ return joined ? `${joined}${voiceSegmentSeparator(joined, part)}${part}` : part;
+ }, '').trim();
+ if (!text) throw new VoiceTranscriptionError('empty');
+ return text;
+};
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 59605ffc9..279b4229b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -7672,7 +7672,12 @@ async def asr_transcribe():
import tempfile
import uuid
- from core.audio_asr import AudioAsrService
+ from core.audio_asr import (
+ AudioAsrEmptyTranscriptError,
+ AudioAsrService,
+ AudioAsrTimeoutError,
+ AudioAsrUnavailableError,
+ )
from core.services import settings as settings_service
from modules.im.base import FileAttachment
@@ -7689,7 +7694,7 @@ async def asr_transcribe():
if not raw:
return jsonify({"error": "empty audio"}), 400
if len(raw) > 25 * 1024 * 1024:
- return jsonify({"error": "file too large"}), 413
+ return jsonify({"error": "file_too_large"}), 413
name = (payload.get("name") or "voice.webm").strip() or "voice.webm"
mime = (payload.get("mime") or "audio/webm").strip()
@@ -7702,13 +7707,30 @@ async def asr_transcribe():
service = AudioAsrService(config)
if not service.is_available():
return jsonify({"error": "asr_unavailable"}), 400
+ audio_asr_config = getattr(config, "audio_asr", None)
+ max_file_bytes = getattr(audio_asr_config, "max_file_bytes", None)
+ if max_file_bytes is not None and len(raw) > max_file_bytes:
+ return jsonify({"error": "file_too_large"}), 413
suffix = Path(name).suffix or ".webm"
tmp_path = Path(tempfile.gettempdir()) / f"vibe_asr_{uuid.uuid4().hex[:8]}{suffix}"
tmp_path.write_bytes(raw)
try:
attachment = FileAttachment(name=name, mimetype=mime, local_path=str(tmp_path), size=len(raw))
- transcripts = await service.transcribe_attachments([attachment])
+ try:
+ transcripts = await service.transcribe_attachments(
+ [attachment],
+ raise_on_empty=True,
+ raise_on_timeout=True,
+ raise_on_unavailable=True,
+ timeout_seconds=120.0,
+ )
+ except AudioAsrEmptyTranscriptError:
+ return jsonify({"error": "transcription_empty"}), 422
+ except AudioAsrTimeoutError:
+ return jsonify({"error": "transcription_timeout"}), 504
+ except AudioAsrUnavailableError:
+ return jsonify({"error": "asr_unavailable"}), 503
finally:
try:
tmp_path.unlink()
@@ -7719,6 +7741,116 @@ async def asr_transcribe():
return jsonify({"text": transcripts[0].text})
[email protected]("/api/asr/telemetry", methods=["POST"])
+def asr_telemetry():
+ """Persist privacy-safe browser voice metrics in the normal service log."""
+ from vibe import __version__
+
+ payload = request.json or {}
+ if not isinstance(payload, dict):
+ return jsonify({"error": "invalid_payload"}), 400
+
+ event = payload.get("event")
+ if not isinstance(event, str) or event not in {
+ "segment_transcription",
+ "dictation_finalized",
+ "dictation_inserted",
+ }:
+ return jsonify({"error": "invalid_event"}), 400
+
+ enum_fields = {
+ "outcome": {
+ "success",
+ "fallback",
+ "cancelled",
+ "empty",
+ "failed",
+ "timeout",
+ "too_large",
+ "unavailable",
+ },
+ "path": {"cloud", "local"},
+ "providerStage": {"token", "upload", "refresh", "response", "finalization"},
+ "browserFamily": {"chrome", "firefox", "edge", "safari", "other", "unknown"},
+ }
+ outcome = payload.get("outcome")
+ if not isinstance(outcome, str) or outcome not in enum_fields["outcome"]:
+ return jsonify({"error": "invalid_outcome"}), 400
+
+ sanitized: dict[str, Any] = {
+ "release": __version__,
+ "event": event,
+ "outcome": outcome,
+ }
+ dictation_id = payload.get("dictationId")
+ if dictation_id is not None:
+ if not isinstance(dictation_id, str) or not re.fullmatch(
+ r"[a-z0-9_-]{1,80}",
+ dictation_id,
+ flags=re.IGNORECASE,
+ ):
+ return jsonify({"error": "invalid_field", "field": "dictationId"}), 400
+ sanitized["dictationId"] = dictation_id
+
+ for key, allowed_values in enum_fields.items():
+ if key == "outcome" or key not in payload:
+ continue
+ value = payload[key]
+ if not isinstance(value, str) or value not in allowed_values:
+ return jsonify({"error": "invalid_field", "field": key}), 400
+ sanitized[key] = value
+
+ mime_type = payload.get("mimeType")
+ if mime_type is not None:
+ if not isinstance(mime_type, str) or not re.fullmatch(
+ r"(?:audio|video)/[a-z0-9][a-z0-9.+_-]{0,63}",
+ mime_type,
+ flags=re.IGNORECASE,
+ ):
+ return jsonify({"error": "invalid_field", "field": "mimeType"}), 400
+ sanitized["mimeType"] = mime_type.lower()
+
+ integer_fields = {
+ "sizeBytes",
+ "durationMs",
+ "elapsedMs",
+ "attemptCount",
+ "segmentCount",
+ "failedSegmentCount",
+ "backlogAtStop",
+ "totalDurationMs",
+ "stopToInsertionMs",
+ }
+ for key in integer_fields:
+ if key not in payload:
+ continue
+ value = payload[key]
+ if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= 10**12:
+ return jsonify({"error": "invalid_field", "field": key}), 400
+ sanitized[key] = value
+
+ if "httpStatus" in payload:
+ http_status = payload["httpStatus"]
+ if (
+ not isinstance(http_status, int)
+ or isinstance(http_status, bool)
+ or not 100 <= http_status <= 599
+ ):
+ return jsonify({"error": "invalid_field", "field": "httpStatus"}), 400
+ sanitized["httpStatus"] = http_status
+
+ if "retry" in payload:
+ if not isinstance(payload["retry"], bool):
+ return jsonify({"error": "invalid_field", "field": "retry"}), 400
+ sanitized["retry"] = payload["retry"]
+
+ logger.info(
+ "voice_reliability %s",
+ json.dumps(sanitized, sort_keys=True, separators=(",", ":")),
+ )
+ return jsonify({"ok": True})
+
+
@app.route("/api/asr/status", methods=["GET"])
def asr_status():
"""Whether voice transcription is available (Vibe Cloud paired + enabled) so
@@ -7728,9 +7860,24 @@ def asr_status():
try:
config = settings_service.load_config()
- return jsonify({"available": bool(AudioAsrService(config).is_available())})
+ audio_asr_config = getattr(config, "audio_asr", None)
+ max_file_bytes = getattr(audio_asr_config, "max_file_bytes", None)
+ if not isinstance(max_file_bytes, int) or max_file_bytes <= 0:
+ max_file_bytes = None
+ available = bool(AudioAsrService(config).is_available())
+ # Browser capture uses 16 kHz mono 16-bit PCM. Smaller limits would
+ # create sub-five-second segments and an impractical ASR request rate.
+ min_browser_wav_bytes = 44 + (16_000 * 2 * 5)
+ if max_file_bytes is not None and max_file_bytes < min_browser_wav_bytes:
+ available = False
+ return jsonify(
+ {
+ "available": available,
+ "max_file_bytes": max_file_bytes,
+ }
+ )
except Exception:
- return jsonify({"available": False})
+ return jsonify({"available": False, "max_file_bytes": None})
def _publish_visible_input_message(