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.

feat(voice): finalize segmented dictation on server (#1141)

Call Whited185dda8e59a
diff --git a/core/audio_asr.py b/core/audio_asr.py
index 1c5e4f8fb..d9ec6ccef 100644
--- a/core/audio_asr.py
+++ b/core/audio_asr.py
@@ -99,6 +99,10 @@ class AudioAsrProtocolError(ValueError):
"""Raised when upstream returns a success response with an invalid schema."""
+class AudioAsrInvalidDictationError(ValueError):
+ """Raised when upstream rejects composer dictation metadata or receipts."""
+
+
class AudioAsrUnavailableError(ConnectionError):
"""Raised when the configured upstream ASR service is unavailable."""
@@ -132,6 +136,10 @@ class AudioAsrService:
endpoint_path = f"/{endpoint_path}"
return urljoin(f"{runtime.base_url}/", endpoint_path.lstrip("/"))
+ @staticmethod
+ def _dictation_endpoint_url(runtime: AudioAsrRuntimeConfig) -> str:
+ return urljoin(f"{runtime.base_url}/", "v1/voice/dictations")
+
def is_available(self) -> bool:
asr_config = self._get_audio_asr_config()
return bool(asr_config.enabled and self._runtime_config())
@@ -217,6 +225,127 @@ class AudioAsrService:
logger.warning("Audio ASR skipped after error: %s", result)
return transcripts
+ async def transcribe_voice_segment(
+ self,
+ attachment: FileAttachment | None,
+ *,
+ dictation_id: str,
+ sequence: int,
+ overlap_ms: int,
+ final: bool,
+ finalize_only: bool,
+ receipts: list[str],
+ before: str,
+ after: str,
+ timeout_seconds: float = 120.0,
+ ) -> dict[str, Any]:
+ """Forward one composer segment using the server-owned dictation contract."""
+ runtime = self._runtime_config()
+ if not self._get_audio_asr_config().enabled or not runtime:
+ raise AudioAsrUnavailableError("audio ASR upstream unavailable")
+
+ form = aiohttp.FormData()
+ form.add_field("model", self._get_audio_asr_config().model)
+ form.add_field("response_format", "json")
+ form.add_field("dictation_id", dictation_id)
+ form.add_field("sequence", str(sequence))
+ form.add_field("overlap_ms", str(overlap_ms))
+ form.add_field("final", "true" if final else "false")
+ if finalize_only:
+ form.add_field("finalize_only", "true")
+ for receipt in receipts:
+ form.add_field("receipt", receipt)
+ if before:
+ form.add_field("before", before)
+ if after:
+ form.add_field("after", after)
+
+ path: Path | None = None
+ handle = None
+ if attachment is not None:
+ path = Path(attachment.local_path or "")
+ if not path.is_file():
+ raise AudioAsrProtocolError("composer audio file is unavailable")
+ mimetype = attachment.mimetype or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
+ detected_audio = detect_audio_mime_from_file(path)
+ if detected_audio and not mimetype.lower().startswith(("audio/", "video/")):
+ mimetype = detected_audio[0]
+ filename = attachment.name or path.name
+ if detected_audio and not Path(filename).suffix:
+ filename = f"{filename}{detected_audio[1]}"
+ handle = path.open("rb")
+ form.add_field("file", handle, filename=filename, content_type=mimetype)
+
+ timeout = aiohttp.ClientTimeout(total=max(0.1, timeout_seconds))
+ started_at = time.monotonic()
+ try:
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.post(
+ self._dictation_endpoint_url(runtime),
+ data=form,
+ headers={
+ "Accept": "application/json",
+ "User-Agent": "avibe/dev",
+ "X-Vibe-Instance-Id": runtime.instance_id,
+ "X-Vibe-Device-Secret": runtime.device_secret,
+ },
+ ) as response:
+ payload = None
+ try:
+ payload = await response.json(content_type=None)
+ except Exception as exc:
+ if 200 <= response.status < 300:
+ raise AudioAsrProtocolError("audio ASR returned invalid JSON") from exc
+ if response.status < 200 or response.status >= 300:
+ 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 == 422 and upstream_error == "transcription_empty":
+ raise AudioAsrEmptyTranscriptError("audio ASR returned an empty transcript")
+ if response.status == 422 and upstream_error == "invalid_dictation":
+ raise AudioAsrInvalidDictationError("audio ASR rejected dictation metadata")
+ if response.status == 503 or upstream_error in {
+ "asr_not_configured",
+ "asr_unavailable",
+ }:
+ raise AudioAsrUnavailableError("audio ASR upstream unavailable")
+ raise AudioAsrProtocolError("audio ASR rejected the composer segment")
+ except (
+ AudioAsrEmptyTranscriptError,
+ AudioAsrInvalidDictationError,
+ AudioAsrProtocolError,
+ AudioAsrTimeoutError,
+ AudioAsrUnavailableError,
+ ):
+ raise
+ except asyncio.TimeoutError:
+ raise AudioAsrTimeoutError("audio ASR request timed out") from None
+ except aiohttp.ClientError as exc:
+ raise AudioAsrUnavailableError("audio ASR request unavailable") from exc
+ finally:
+ if handle is not None:
+ handle.close()
+
+ if not isinstance(payload, dict):
+ raise AudioAsrProtocolError("audio ASR returned a malformed success response")
+ if isinstance(payload.get("text"), str):
+ cleanup = payload.get("cleanup")
+ if cleanup not in {"success", "fallback"}:
+ raise AudioAsrProtocolError("audio ASR omitted cleanup outcome")
+ elif not (
+ isinstance(payload.get("receipt"), str)
+ and isinstance(payload.get("sequence"), int)
+ and not isinstance(payload.get("sequence"), bool)
+ ):
+ raise AudioAsrProtocolError("audio ASR returned a malformed success response")
+ logger.info(
+ "Composer voice segment completed: sequence=%s final=%s duration_ms=%s",
+ sequence,
+ final,
+ int((time.monotonic() - started_at) * 1000),
+ )
+ return payload
+
async def _transcribe_one(
self,
session: aiohttp.ClientSession,
diff --git a/docs/plans/voice-input-reliability.md b/docs/plans/voice-input-reliability.md
index 7ba4380a8..1d55a2888 100644
--- a/docs/plans/voice-input-reliability.md
+++ b/docs/plans/voice-input-reliability.md
@@ -20,18 +20,27 @@ getUserMedia
-> 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 assemble once after the user stops
- -> best-effort transcript cleanup with bounded cursor context
+ -> receive an encrypted receipt for each completed segment
+ -> submit the final segment, prior receipts, and bounded cursor context
+ -> server validates order, joins overlap, and runs cleanup once
-> replace the selection captured when recording started
```
+The client never receives or joins intermediate transcript text. Encrypted
+receipts bind the transcript to the instance, dictation id, sequence, and
+overlap.
+They let the server remain stateless between segment uploads without exposing
+raw intermediate text to the client or requiring a transcript database. If the
+recording stops exactly at a segment boundary, the client sends a small
+finalize-only request containing the receipts and cursor context.
+
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
+ -> paired-device /v1/voice/dictations
+ -> the same receipt and finalization contract
```
The compatibility path is selected before a cloud upload starts. A response or
@@ -47,10 +56,12 @@ The first stabilization increment establishes these invariants:
- 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;
+ audio until finalization, and return encrypted receipts rather than raw
+ intermediate transcript text;
+- apply independent 120-second ASR and 30-second cleanup deadlines, plus a
+ 5-second server-finalization allowance; the browser grants 193 seconds for
+ token/CSRF acquisition, encoding/upload, and the complete server request,
+ not for 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;
@@ -120,11 +131,11 @@ the same capture/session library and insertion contract.
## Text cleanup and insertion
-Cleanup is a second, separately budgeted stage:
+Cleanup is a separately budgeted server-side stage within finalization:
```text
final raw transcript
- -> qwen3.6-flash-2026-04-16 by default, with thinking disabled
+ -> qwen3.7-plus-2026-05-26 by default, with thinking disabled
-> cleaned text
-> composer or active application
```
@@ -135,25 +146,33 @@ ASR corrections, punctuation, filler removal, repetitions, superseded
corrections, and useful formatting. Commands and questions inside the
transcript are edited as text and never executed or answered.
-The browser contract is:
+The browser sends each non-final segment as multipart form data:
```http
-POST /api/cloud/voice/cleanup
+POST /api/cloud/voice/dictations
Authorization: Bearer <cloud token with asr scope>
-Content-Type: application/json
+Content-Type: multipart/form-data
-{
- "transcript": "raw ASR text",
- "before": "up to 500 UTF-16 code units before the selection",
- "after": "up to 200 UTF-16 code units after the selection"
-}
+file=<audio>
+dictation_id=<opaque client id>
+sequence=0
+overlap_ms=0
+final=false
```
-A successful response is `{ "text": "cleaned transcript" }`. An empty string
-means the input contained no insertable content. Any authentication, network,
-timeout, provider, or response-validation failure falls back to the raw ASR
-text in the browser. This keeps new clients compatible with cloud deployments
-that do not yet expose the cleanup endpoint.
+The response is `{ "receipt": "<encrypted receipt>", "sequence": 0 }`.
+The final request uses the same endpoint and adds all prior `receipt` fields,
+`before` (up to 500 UTF-16 code units), and `after` (up to 200). A successful
+final response is `{ "text": "cleaned transcript", "cleanup": "success" }`.
+When cleanup fails, the server returns the assembled raw ASR text with
+`"cleanup": "fallback"`.
+
+A bare legacy request to `/api/cloud/audio/transcriptions` containing only
+`file` is transcribed and cleaned in the same request, with empty cursor
+context. This gives old clients cleanup without changing their request shape.
+The paired-device `/v1/audio/transcriptions` route keeps bare file requests raw
+for IM audio attachments; the local composer uses the independent
+`/v1/voice/dictations` route for the combined cleanup path.
The composer captures its serialized draft and selection on the microphone
button's `pointerdown`, before focus moves to the button. Keyboard activation
@@ -171,6 +190,7 @@ Cleanup requirements:
- regression corpus covering Chinese, English, mixed language, code, URLs,
names, and numeric dictation;
- no general Agent invocation and no tool access.
+- no standalone browser cleanup request after transcription finalization.
## Delivery sequence
diff --git a/tests/test_audio_asr.py b/tests/test_audio_asr.py
index 8eaa3c22d..94c8c682e 100644
--- a/tests/test_audio_asr.py
+++ b/tests/test_audio_asr.py
@@ -335,6 +335,72 @@ class AudioAsrServiceTests(unittest.TestCase):
[],
)
+ def test_dictation_classifies_non_json_proxy_errors_by_status(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 ErrorResponse:
+ def __init__(self, status):
+ self.status = status
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def json(self, **_kwargs):
+ raise ValueError("proxy returned HTML")
+
+ class ErrorSession:
+ def __init__(self, status):
+ self.status = status
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ def post(self, *_args, **_kwargs):
+ return ErrorResponse(self.status)
+
+ cases = [
+ (503, AudioAsrUnavailableError),
+ (504, AudioAsrTimeoutError),
+ ]
+ for status, expected_error in cases:
+ with self.subTest(status=status):
+ with patch(
+ "core.audio_asr.aiohttp.ClientSession",
+ return_value=ErrorSession(status),
+ ):
+ with self.assertRaises(expected_error):
+ asyncio.run(
+ service.transcribe_voice_segment(
+ None,
+ dictation_id="dictation-1",
+ sequence=1,
+ overlap_ms=0,
+ final=True,
+ finalize_only=True,
+ receipts=["receipt-0"],
+ before="",
+ after="",
+ )
+ )
+
def test_http_callers_can_override_the_request_deadline(self):
service = AudioAsrService(
SimpleNamespace(
diff --git a/tests/test_ui_server_voice_transcription.py b/tests/test_ui_server_voice_transcription.py
index a4983ed2c..d400bddb9 100644
--- a/tests/test_ui_server_voice_transcription.py
+++ b/tests/test_ui_server_voice_transcription.py
@@ -6,6 +6,8 @@ from types import SimpleNamespace
from config.v2_config import AudioAsrConfig, RemoteAccessConfig, VibeCloudRemoteAccessConfig
from core.audio_asr import (
AudioAsrEmptyTranscriptError,
+ AudioAsrInvalidDictationError,
+ AudioAsrProtocolError,
AudioAsrService,
AudioAsrTimeoutError,
AudioAsrUnavailableError,
@@ -43,17 +45,24 @@ def test_asr_status_exposes_the_configured_file_limit(monkeypatch):
def test_asr_transcribe_preserves_compatibility_timeout(monkeypatch):
async def timeout(
_self,
- _attachments,
+ _attachment,
*,
- raise_on_empty=False,
- raise_on_timeout=False,
- raise_on_unavailable=False,
- timeout_seconds=None,
+ sequence,
+ final,
+ finalize_only,
+ receipts,
+ before,
+ after,
+ timeout_seconds,
+ **_kwargs,
):
- assert raise_on_empty is True
- assert raise_on_timeout is True
- assert raise_on_unavailable is True
- assert timeout_seconds == 120.0
+ assert sequence == 0
+ assert final is True
+ assert finalize_only is False
+ assert receipts == []
+ assert before == ""
+ assert after == ""
+ assert timeout_seconds == 155.0
raise AudioAsrTimeoutError("timed out")
monkeypatch.setattr(
@@ -71,7 +80,7 @@ def test_asr_transcribe_preserves_compatibility_timeout(monkeypatch):
),
)
monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
- monkeypatch.setattr(AudioAsrService, "transcribe_attachments", timeout)
+ monkeypatch.setattr(AudioAsrService, "transcribe_voice_segment", timeout)
client = app.test_client()
response = client.post(
@@ -91,17 +100,9 @@ def test_asr_transcribe_preserves_compatibility_timeout(monkeypatch):
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,
+ _attachment,
+ **_kwargs,
):
- 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(
@@ -119,7 +120,7 @@ def test_asr_transcribe_preserves_empty_transcript_classification(monkeypatch):
),
)
monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
- monkeypatch.setattr(AudioAsrService, "transcribe_attachments", empty)
+ monkeypatch.setattr(AudioAsrService, "transcribe_voice_segment", empty)
client = app.test_client()
response = client.post(
@@ -141,12 +142,8 @@ def test_asr_transcribe_preserves_configured_size_rejection(monkeypatch):
async def transcribe(
_self,
- _attachments,
- *,
- raise_on_empty=False,
- raise_on_timeout=False,
- raise_on_unavailable=False,
- timeout_seconds=None,
+ _attachment,
+ **_kwargs,
):
nonlocal transcribe_called
transcribe_called = True
@@ -167,7 +164,7 @@ def test_asr_transcribe_preserves_configured_size_rejection(monkeypatch):
),
)
monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
- monkeypatch.setattr(AudioAsrService, "transcribe_attachments", transcribe)
+ monkeypatch.setattr(AudioAsrService, "transcribe_voice_segment", transcribe)
client = app.test_client()
response = client.post(
@@ -188,17 +185,9 @@ def test_asr_transcribe_preserves_configured_size_rejection(monkeypatch):
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,
+ _attachment,
+ **_kwargs,
):
- 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(
@@ -216,7 +205,7 @@ def test_asr_transcribe_preserves_provider_unavailable_classification(monkeypatc
),
)
monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
- monkeypatch.setattr(AudioAsrService, "transcribe_attachments", unavailable)
+ monkeypatch.setattr(AudioAsrService, "transcribe_voice_segment", unavailable)
client = app.test_client()
response = client.post(
@@ -231,3 +220,155 @@ def test_asr_transcribe_preserves_provider_unavailable_classification(monkeypatc
assert response.status_code == 503
assert response.get_json() == {"error": "asr_unavailable"}
+
+
+def test_asr_transcribe_forwards_segment_receipts_and_context(monkeypatch):
+ calls = []
+
+ async def transcribe(_self, attachment, **kwargs):
+ assert attachment is not None
+ assert attachment.name == "voice.webm"
+ calls.append(kwargs)
+ return {"receipt": "encrypted-receipt", "sequence": 0}
+
+ 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_voice_segment", transcribe)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/asr/transcribe",
+ json={
+ "name": "voice.webm",
+ "mime": "audio/webm",
+ "data": base64.b64encode(b"audio").decode(),
+ "dictation_id": "dictation-1",
+ "sequence": 0,
+ "overlap_ms": 250,
+ "final": False,
+ "receipts": [],
+ "before": "",
+ "after": "",
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {"receipt": "encrypted-receipt", "sequence": 0}
+ assert calls == [
+ {
+ "dictation_id": "dictation-1",
+ "sequence": 0,
+ "overlap_ms": 250,
+ "final": False,
+ "finalize_only": False,
+ "receipts": [],
+ "before": "",
+ "after": "",
+ "timeout_seconds": 155.0,
+ }
+ ]
+
+
+def test_asr_transcribe_supports_finalize_only_without_audio(monkeypatch):
+ async def transcribe(_self, attachment, **kwargs):
+ assert attachment is None
+ assert kwargs == {
+ "dictation_id": "dictation-1",
+ "sequence": 1,
+ "overlap_ms": 0,
+ "final": True,
+ "finalize_only": True,
+ "receipts": ["receipt-0"],
+ "before": "前文",
+ "after": "后文",
+ "timeout_seconds": 155.0,
+ }
+ return {"text": "整理结果", "cleanup": "success"}
+
+ 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_voice_segment", transcribe)
+ client = app.test_client()
+
+ response = client.post(
+ "/api/asr/transcribe",
+ json={
+ "dictation_id": "dictation-1",
+ "sequence": 1,
+ "overlap_ms": 0,
+ "final": True,
+ "finalize_only": True,
+ "receipts": ["receipt-0"],
+ "before": "前文",
+ "after": "后文",
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {"text": "整理结果", "cleanup": "success"}
+
+
+def test_asr_transcribe_preserves_dictation_and_protocol_errors(monkeypatch):
+ config = 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("core.services.settings.load_config", lambda: config)
+ monkeypatch.setattr(AudioAsrService, "is_available", lambda _self: True)
+ client = app.test_client()
+ payload = {
+ "name": "voice.webm",
+ "mime": "audio/webm",
+ "data": base64.b64encode(b"audio").decode(),
+ }
+
+ async def invalid(_self, _attachment, **_kwargs):
+ raise AudioAsrInvalidDictationError("invalid")
+
+ monkeypatch.setattr(AudioAsrService, "transcribe_voice_segment", invalid)
+ response = client.post("/api/asr/transcribe", json=payload, headers=csrf_headers(client))
+ assert response.status_code == 422
+ assert response.get_json() == {"error": "invalid_dictation"}
+
+ async def malformed(_self, _attachment, **_kwargs):
+ raise AudioAsrProtocolError("malformed")
+
+ monkeypatch.setattr(AudioAsrService, "transcribe_voice_segment", malformed)
+ response = client.post("/api/asr/transcribe", json=payload, headers=csrf_headers(client))
+ assert response.status_code == 502
+ assert response.get_json() == {"error": "transcription_failed"}
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 2585cb6c0..5f1c92576 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -18,18 +18,17 @@ import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard
import { cn, copyTextToClipboard } from '../../lib/utils';
import {
applyVoiceInsertion,
- cleanupVoiceTranscript,
voiceInsertionSnapshot,
voiceInsertionText,
- type VoiceCleanupResult,
type VoiceInsertionSnapshot,
} from '../../lib/voiceCleanup';
import {
+ finalizeVoiceDictation,
transcribeVoiceSegments,
VOICE_SEGMENT_MS,
VOICE_TRANSCRIPTION_CONCURRENCY,
VoiceTranscriptionQueue,
- voiceTranscriptFromSegments,
+ type VoiceCleanupOutcome,
type VoiceTranscriptionSegment,
VoiceTranscriptionError,
} from '../../lib/voiceTranscription';
@@ -117,7 +116,7 @@ type VoiceRecordingSession = {
finalization?: Promise<void>;
transcriptionQueue: VoiceTranscriptionQueue;
insertion: VoiceInsertionSnapshot;
- cleanupOutcome?: VoiceCleanupResult['outcome'];
+ cleanupOutcome?: VoiceCleanupOutcome;
cleanupElapsedMs?: number;
};
@@ -135,24 +134,33 @@ const newVoiceDictationId = (): string => (
);
const settleVoiceSession = async (session: VoiceRecordingSession): Promise<void> => {
+ const startedAt = Date.now();
try {
- const rawTranscript = voiceTranscriptFromSegments(session.segments);
- session.finalizedSegmentCount = session.segments.length;
- session.finalizedFailedSegmentCount = session.segments.filter(
- (segment) => segment.error,
- ).length;
- const cleanup = await cleanupVoiceTranscript(rawTranscript, session.insertion, {
- signal: session.abortController.signal,
- });
+ session.finalizedSegmentCount = session.segments.filter((segment) => segment.blob).length;
+ const result = await (async () => {
+ try {
+ return await finalizeVoiceDictation(session.segments, {
+ dictationId: session.dictationId,
+ before: session.insertion.before,
+ after: session.insertion.after,
+ }, {
+ signal: session.abortController.signal,
+ });
+ } finally {
+ session.finalizedFailedSegmentCount = session.segments.filter(
+ (segment) => segment.error,
+ ).length;
+ }
+ })();
if (session.abortController.signal.aborted) return;
- session.cleanupOutcome = cleanup.outcome;
- session.cleanupElapsedMs = cleanup.elapsedMs;
- if (!cleanup.text.trim()) throw new VoiceTranscriptionError('empty');
- session.transcript = cleanup.text;
+ session.cleanupOutcome = result.cleanup;
+ session.cleanupElapsedMs = Date.now() - startedAt;
+ session.transcript = result.text;
session.segments = [];
session.error = undefined;
session.status = 'ready';
} catch (error) {
+ session.cleanupElapsedMs = Date.now() - startedAt;
session.transcript = undefined;
session.error = error;
session.status = 'failed';
@@ -643,9 +651,12 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
blob: Blob,
durationMs: number,
overlapMs?: number,
+ final = false,
) => {
const segment: VoiceSegment = {
blob,
+ sequence: session.segments.length,
+ final,
durationMs,
overlapMs,
task: Promise.resolve(),
@@ -818,12 +829,13 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
blob,
metadata.durationMs,
metadata.overlapMs,
+ metadata.final,
),
onStopRequested: (reason, metadata) => {
if (reason === 'abort') return;
session.stoppedAt = metadata.requestedAt;
session.backlogAtStop = session.segments.filter(
- (segment) => !segment.text && !segment.error,
+ (segment) => !segment.final && !segment.receipt && !segment.error,
).length;
},
onError: (error) => {
@@ -852,6 +864,15 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
deleteMapValueIfCurrent(voiceSessionsById, session.sessionId, session);
return;
}
+ if (session.segments.length && !session.segments.at(-1)?.final) {
+ session.segments.push({
+ blob: null,
+ sequence: session.segments.length,
+ final: true,
+ durationMs: 0,
+ task: Promise.resolve(),
+ });
+ }
void finishVoiceSession(session);
},
});
diff --git a/ui/src/lib/voiceCleanup.test.ts b/ui/src/lib/voiceCleanup.test.ts
index 83f70e711..8f7aea482 100644
--- a/ui/src/lib/voiceCleanup.test.ts
+++ b/ui/src/lib/voiceCleanup.test.ts
@@ -1,8 +1,7 @@
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import {
applyVoiceInsertion,
- cleanupVoiceTranscript,
voiceInsertionSnapshot,
voiceInsertionText,
} from './voiceCleanup';
@@ -148,61 +147,4 @@ describe('voice cleanup', () => {
expect(applyVoiceInsertion('changed', snapshot, 'voice')).toBeNull();
});
- it('sends only bounded context and returns the cleaned text', async () => {
- const cloudFetch = vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ text: '后天发布。' }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- }),
- );
- const snapshot = voiceInsertionSnapshot('计划:。', 3, 3);
-
- await expect(cleanupVoiceTranscript('呃后天发布', snapshot, { cloudFetch })).resolves.toMatchObject({
- text: '后天发布。',
- outcome: 'success',
- });
- const [, init] = cloudFetch.mock.calls[0];
- expect(JSON.parse(String(init?.body))).toEqual({
- transcript: '呃后天发布',
- before: '计划:',
- after: '。',
- });
- });
-
- it('keeps raw ASR text when cleanup is unavailable or malformed', async () => {
- const snapshot = voiceInsertionSnapshot('', 0, 0);
- const unavailable = vi.fn().mockResolvedValue(new Response('{}', { status: 404 }));
- const malformed = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }));
- const networkError = vi.fn().mockRejectedValue(new TypeError('network unavailable'));
-
- await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: unavailable })).resolves.toMatchObject({
- text: 'raw',
- outcome: 'fallback',
- });
- await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: malformed })).resolves.toMatchObject({
- text: 'raw',
- outcome: 'fallback',
- });
- await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: networkError })).resolves.toMatchObject({
- text: 'raw',
- outcome: 'fallback',
- });
- });
-
- it('preserves intentional empty output but falls back from whitespace-only output', async () => {
- const snapshot = voiceInsertionSnapshot('', 0, 0);
- const empty = vi.fn().mockResolvedValue(new Response(JSON.stringify({ text: '' }), { status: 200 }));
- const whitespace = vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ text: ' ' }), { status: 200 }),
- );
-
- await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: empty })).resolves.toMatchObject({
- text: '',
- outcome: 'success',
- });
- await expect(cleanupVoiceTranscript('raw', snapshot, { cloudFetch: whitespace })).resolves.toMatchObject({
- text: 'raw',
- outcome: 'fallback',
- });
- });
});
diff --git a/ui/src/lib/voiceCleanup.ts b/ui/src/lib/voiceCleanup.ts
index f7a1c6e1b..87ab80d58 100644
--- a/ui/src/lib/voiceCleanup.ts
+++ b/ui/src/lib/voiceCleanup.ts
@@ -1,8 +1,5 @@
-import { avibeFetch } from './avibeFetch';
-
export const VOICE_CONTEXT_BEFORE_CHARS = 500;
export const VOICE_CONTEXT_AFTER_CHARS = 200;
-export const VOICE_CLEANUP_TIMEOUT_MS = 35_000;
export type VoiceInsertionSnapshot = {
text: string;
@@ -19,23 +16,6 @@ type VoiceInsertionBoundaries = {
right?: string;
};
-type VoiceCleanupFetch = (
- path: string,
- init?: RequestInit,
-) => Promise<Response>;
-
-type VoiceCleanupDependencies = {
- cloudFetch?: VoiceCleanupFetch;
- timeoutMs?: number;
- signal?: AbortSignal;
-};
-
-export type VoiceCleanupResult = {
- text: string;
- outcome: 'success' | 'fallback';
- elapsedMs: number;
-};
-
const boundedSelection = (text: string, start: number, end: number): [number, number] => {
const safeStart = Math.max(0, Math.min(text.length, Math.floor(start)));
const safeEnd = Math.max(safeStart, Math.min(text.length, Math.floor(end)));
@@ -160,67 +140,3 @@ export const applyVoiceInsertion = (
if (insertion === null) return null;
return `${currentText.slice(0, snapshot.start)}${insertion}${currentText.slice(snapshot.end)}`;
};
-
-const timeoutSignal = (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('voice cleanup timed out', 'TimeoutError')),
- durationMs,
- );
- return {
- signal: controller.signal,
- cancel: () => {
- globalThis.clearTimeout(timer);
- externalSignal?.removeEventListener('abort', abortFromExternal);
- },
- };
-};
-
-// Cleanup is deliberately best-effort. Raw ASR text remains usable when an old
-// cloud deployment lacks the endpoint or the small editing model is unavailable.
-export const cleanupVoiceTranscript = async (
- transcript: string,
- snapshot: VoiceInsertionSnapshot,
- dependencies: VoiceCleanupDependencies = {},
-): Promise<VoiceCleanupResult> => {
- const startedAt = Date.now();
- const result = (text: string, outcome: VoiceCleanupResult['outcome']): VoiceCleanupResult => ({
- text,
- outcome,
- elapsedMs: Date.now() - startedAt,
- });
- const request = timeoutSignal(
- dependencies.timeoutMs ?? VOICE_CLEANUP_TIMEOUT_MS,
- dependencies.signal,
- );
- try {
- const response = await (dependencies.cloudFetch ?? avibeFetch)(
- '/api/cloud/voice/cleanup',
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- transcript,
- before: snapshot.before,
- after: snapshot.after,
- }),
- signal: request.signal,
- },
- );
- if (!response.ok) return result(transcript, 'fallback');
- const payload = await response.json().catch(() => null) as { text?: unknown } | null;
- if (typeof payload?.text !== 'string') return result(transcript, 'fallback');
- if (payload.text !== '' && !payload.text.trim()) return result(transcript, 'fallback');
- return result(payload.text, 'success');
- } catch {
- return result(transcript, 'fallback');
- } finally {
- request.cancel();
- }
-};
diff --git a/ui/src/lib/voiceRecording.test.ts b/ui/src/lib/voiceRecording.test.ts
index 3bdfe396e..c2b6ad414 100644
--- a/ui/src/lib/voiceRecording.test.ts
+++ b/ui/src/lib/voiceRecording.test.ts
@@ -180,8 +180,8 @@ describe('VoiceRecordingPipeline', () => {
[3, 4, 5, 6],
]);
expect(onSegment.mock.calls.map(([, metadata]) => metadata)).toEqual([
- { durationMs: 1000 },
- { durationMs: 1000, overlapMs: 500 },
+ { durationMs: 1000, final: false },
+ { durationMs: 1000, overlapMs: 500, final: false },
]);
});
@@ -210,7 +210,7 @@ describe('VoiceRecordingPipeline', () => {
capture().settle();
expect(onSegment).toHaveBeenCalledTimes(1);
- expect(onSegment.mock.calls[0]?.[1]).toEqual({ durationMs: 500 });
+ expect(onSegment.mock.calls[0]?.[1]).toEqual({ durationMs: 500, final: true });
expect(await wavDataBytes(onSegment.mock.calls[0]![0])).toBe(4);
expect(onStopped).toHaveBeenCalledWith('finish', { pendingSegmentCount: 1 });
expect(track.stop).toHaveBeenCalledTimes(1);
diff --git a/ui/src/lib/voiceRecording.ts b/ui/src/lib/voiceRecording.ts
index 4ce08fe8a..c62112cf6 100644
--- a/ui/src/lib/voiceRecording.ts
+++ b/ui/src/lib/voiceRecording.ts
@@ -334,6 +334,7 @@ export type VoiceRecordingStopReason = 'finish' | 'abort' | 'error';
export type VoiceRecordingSegmentMetadata = {
durationMs: number;
overlapMs?: number;
+ final: boolean;
};
export type VoiceRecordingStopMetadata = {
@@ -538,7 +539,7 @@ export class VoiceRecordingPipeline {
}
}
- private emitSegment(retainOverlap = false): void {
+ private emitSegment(retainOverlap = false, final = false): void {
if (!this.segmentSampleCount) return;
const sampleCount = this.segmentSampleCount;
const chunks = this.segmentChunks;
@@ -555,6 +556,7 @@ export class VoiceRecordingPipeline {
{
durationMs: Math.round(sampleCount * 1000 / this.sampleRate),
...(overlapMs > 0 ? { overlapMs } : {}),
+ final,
},
);
}
@@ -570,7 +572,7 @@ export class VoiceRecordingPipeline {
if (this.stopped) return;
this.requestStop('finish');
if (this.stopping !== 'abort' && this.segmentFreshSampleCount > 0) {
- this.emitSegment();
+ this.emitSegment(false, true);
}
else {
this.segmentChunks = [];
diff --git a/ui/src/lib/voiceTranscription.test.ts b/ui/src/lib/voiceTranscription.test.ts
index 7801704c2..31da8082e 100644
--- a/ui/src/lib/voiceTranscription.test.ts
+++ b/ui/src/lib/voiceTranscription.test.ts
@@ -6,12 +6,12 @@ import {
type AvibeFetchRequestInit,
} from './avibeFetch';
import {
+ finalizeVoiceDictation,
transcribeVoiceBlob,
VoiceTranscriptionQueue,
- VoiceTranscriptionError,
+ type VoiceTranscriptionSegment,
transcribeVoiceSegments,
VOICE_TRANSCRIPTION_TIMEOUT_MS,
- voiceTranscriptFromSegments,
voiceRecordingFileName,
} from './voiceTranscription';
@@ -29,7 +29,8 @@ describe('voice transcription', () => {
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 cloudFetch = vi.fn().mockImplementation(async (path: string, init?: RequestInit) => {
+ expect(path).toBe('/api/cloud/audio/transcriptions');
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');
@@ -370,18 +371,24 @@ describe('voice transcription', () => {
);
});
- 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']) },
+ it('retains accepted receipts and uploads only missing intermediate segments', async () => {
+ const segments: VoiceTranscriptionSegment[] = [
+ { blob: new Blob(['one']), sequence: 0, final: false, receipt: 'accepted' },
+ { blob: new Blob(['two']), sequence: 1, final: false },
+ { blob: new Blob(['three']), sequence: 2, final: false },
+ { blob: new Blob(['final']), sequence: 3, final: true },
];
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');
+ expect(segments.map((segment) => segment.receipt)).toEqual([
+ 'accepted',
+ 'two',
+ 'three',
+ undefined,
+ ]);
});
it('bounds incrementally queued initial transcriptions', async () => {
@@ -396,9 +403,13 @@ describe('voice transcription', () => {
return blob.text();
});
const queue = new VoiceTranscriptionQueue({ concurrency: 2, transcribe });
- const segments = Array.from(
+ const segments: VoiceTranscriptionSegment[] = Array.from(
{ length: 5 },
- (_value, index) => ({ blob: new Blob([String(index)]) }),
+ (_value, index) => ({
+ blob: new Blob([String(index)]),
+ sequence: index,
+ final: false,
+ }),
);
const tasks = segments.map((segment) => queue.enqueue(segment));
@@ -412,7 +423,7 @@ describe('voice transcription', () => {
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.receipt)).toEqual(['0', '1', '2', '3', '4']);
expect(segments.map((segment) => segment.attemptCount)).toEqual([1, 1, 1, 1, 1]);
});
@@ -425,14 +436,15 @@ describe('voice transcription', () => {
}, { once: true });
}),
);
- const segments = Array.from(
+ const segments: VoiceTranscriptionSegment[] = Array.from(
{ length: 5 },
- () => ({ blob: audioBlob() }),
+ (_value, index) => ({ blob: audioBlob(), sequence: index, final: false }),
);
const transcription = transcribeVoiceSegments(segments, {
cloudFetch,
concurrency: 2,
+ dictationId: 'dictation-cancelled',
signal: controller.signal,
});
await vi.waitFor(() => expect(cloudFetch).toHaveBeenCalledTimes(2));
@@ -469,11 +481,12 @@ describe('voice transcription', () => {
const queue = new VoiceTranscriptionQueue({
cloudFetch,
concurrency: 2,
+ dictationId: 'dictation-discarded',
signal: controller.signal,
});
- const segments = Array.from(
+ const segments: VoiceTranscriptionSegment[] = Array.from(
{ length: 5 },
- () => ({ blob: audioBlob() }),
+ (_value, index) => ({ blob: audioBlob(), sequence: index, final: false }),
);
const tasks = segments.map((segment) => queue.enqueue(segment));
@@ -499,110 +512,127 @@ describe('voice transcription', () => {
]);
});
- 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('submits ordered receipts and cursor context with the final audio segment', async () => {
+ const cloudFetch = vi.fn(async (path: string, init?: RequestInit) => {
+ expect(path).toBe('/api/cloud/voice/dictations');
+ const form = init?.body as FormData;
+ if (form.get('final') === 'false') {
+ expect(form.get('sequence')).toBe('0');
+ expect(form.getAll('receipt')).toEqual([]);
+ return Response.json({ receipt: 'receipt-0', sequence: 0 });
+ }
+ expect(form.get('sequence')).toBe('1');
+ expect(form.get('finalize_only')).toBeNull();
+ expect(form.getAll('receipt')).toEqual(['receipt-0']);
+ expect(form.get('before')).toBe('prefix ');
+ expect(form.get('after')).toBe(' suffix');
+ expect(form.get('file')).toBeInstanceOf(Blob);
+ return Response.json({ text: 'cleaned result', cleanup: 'success' });
+ });
+ const segments: VoiceTranscriptionSegment[] = [
+ { blob: audioBlob(), sequence: 0, final: false },
+ { blob: audioBlob(), sequence: 1, final: true, overlapMs: 250 },
+ ];
- 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');
+ await transcribeVoiceSegments(segments, {
+ cloudFetch,
+ dictationId: 'dictation-final',
+ });
+ await expect(finalizeVoiceDictation(segments, {
+ dictationId: 'dictation-final',
+ before: 'prefix ',
+ after: ' suffix',
+ }, { cloudFetch })).resolves.toEqual({ text: 'cleaned result', cleanup: 'success' });
+
+ expect(cloudFetch).toHaveBeenCalledTimes(2);
+ expect(segments[0]?.receipt).toBe('receipt-0');
});
- 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('uses a finalize-only request when capture stops exactly at a segment boundary', async () => {
+ const cloudFetch = vi.fn(async (_path: string, init?: RequestInit) => {
+ const form = init?.body as FormData;
+ expect(form.get('file')).toBeNull();
+ expect(form.get('finalize_only')).toBe('true');
+ expect(form.getAll('receipt')).toEqual(['receipt-0']);
+ return Response.json({ text: 'boundary result', cleanup: 'fallback' });
+ });
+ const segments: VoiceTranscriptionSegment[] = [
+ { blob: audioBlob(), sequence: 0, final: false, receipt: 'receipt-0' },
+ { blob: null, sequence: 1, final: true },
+ ];
+
+ await expect(finalizeVoiceDictation(segments, {
+ dictationId: 'dictation-boundary',
+ before: '',
+ after: '',
+ }, { cloudFetch })).resolves.toEqual({ text: 'boundary result', cleanup: 'fallback' });
});
- 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');
+ it('reuploads retained segments after the server rejects their receipts', async () => {
+ const cloudFetch = vi.fn().mockResolvedValue(
+ Response.json({ error: 'invalid_dictation' }, { status: 422 }),
+ );
+ const segments: VoiceTranscriptionSegment[] = [
+ { blob: audioBlob(), sequence: 0, final: false, receipt: 'stale-receipt' },
+ { blob: null, sequence: 1, final: true },
+ ];
- await transcribeVoiceSegments([silent, failed], { transcribe });
+ await expect(finalizeVoiceDictation(segments, {
+ dictationId: 'dictation-stale',
+ before: '',
+ after: '',
+ }, { cloudFetch })).rejects.toMatchObject({ code: 'failed', status: 422 });
+ expect(segments[0]?.receipt).toBeUndefined();
+ const transcribe = vi.fn().mockResolvedValue('replacement-receipt');
+ await transcribeVoiceSegments(segments, { transcribe });
expect(transcribe).toHaveBeenCalledOnce();
- expect(transcribe).toHaveBeenCalledWith(failed.blob);
- expect(silent.error).toMatchObject({ code: 'empty' });
- expect(failed).toMatchObject({ text: 'recovered', error: undefined });
+ expect(segments[0]?.receipt).toBe('replacement-receipt');
+ });
+
+ it('forwards the same finalization contract through the local compatibility route', async () => {
+ const cloudFetch = vi.fn().mockRejectedValue(new CloudUnavailableError());
+ const localFetch = vi.fn(async (_path: string, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body));
+ if (body.final === false) return Response.json({ receipt: 'local-receipt', sequence: 0 });
+ expect(body).toMatchObject({
+ dictation_id: 'dictation-local',
+ sequence: 1,
+ final: true,
+ finalize_only: true,
+ receipts: ['local-receipt'],
+ before: '前文',
+ after: '后文',
+ });
+ expect(body.data).toBeUndefined();
+ return Response.json({ text: '本地代理结果', cleanup: 'success' });
+ });
+ const segments: VoiceTranscriptionSegment[] = [
+ { blob: audioBlob(), sequence: 0, final: false },
+ { blob: null, sequence: 1, final: true },
+ ];
+
+ await transcribeVoiceSegments(segments, {
+ cloudFetch,
+ localFetch,
+ dictationId: 'dictation-local',
+ });
+ await expect(finalizeVoiceDictation(segments, {
+ dictationId: 'dictation-local',
+ before: '前文',
+ after: '后文',
+ }, { cloudFetch, localFetch })).resolves.toEqual({
+ text: '本地代理结果',
+ cleanup: 'success',
+ });
});
- it('retries only failed segments without discarding completed text', async () => {
+ it('retries only failed intermediate segments without discarding receipts', async () => {
const failed = new Error('provider failed');
- const segments = [
- { blob: new Blob(['one']) },
- { blob: new Blob(['two']) },
+ const segments: VoiceTranscriptionSegment[] = [
+ { blob: new Blob(['one']), sequence: 0, final: false },
+ { blob: new Blob(['two']), sequence: 1, final: false },
+ { blob: new Blob(['final']), sequence: 2, final: true },
];
const firstAttempt = vi
.fn<(blob: Blob) => Promise<string>>()
@@ -610,13 +640,26 @@ describe('voice transcription', () => {
.mockRejectedValueOnce(failed);
await transcribeVoiceSegments(segments, { transcribe: firstAttempt });
- expect(() => voiceTranscriptFromSegments(segments)).toThrow(failed);
+ expect(segments[0]).toMatchObject({ receipt: 'first', error: undefined });
+ expect(segments[1]?.error).toBe(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');
+ expect(segments.slice(0, 2).map((segment) => segment.receipt)).toEqual(['first', 'two']);
+
+ const finalize = vi.fn().mockResolvedValue({ text: 'final', cleanup: 'success' as const });
+ await finalizeVoiceDictation(segments, {
+ dictationId: 'dictation-retry',
+ before: '',
+ after: '',
+ }, { finalize });
+ expect(finalize).toHaveBeenCalledWith({
+ blob: segments[2]?.blob,
+ sequence: 2,
+ receipts: ['first', 'two'],
+ });
});
});
diff --git a/ui/src/lib/voiceTranscription.ts b/ui/src/lib/voiceTranscription.ts
index 032082aa9..bb971a464 100644
--- a/ui/src/lib/voiceTranscription.ts
+++ b/ui/src/lib/voiceTranscription.ts
@@ -15,7 +15,14 @@ import {
export const VOICE_SEGMENT_MS = 60_000;
export const VOICE_TRANSCRIPTION_CONCURRENCY = 2;
-const COMPATIBILITY_UPSTREAM_TIMEOUT_MS = 120_000;
+const ASR_UPSTREAM_TIMEOUT_MS = 120_000;
+const CLEANUP_UPSTREAM_TIMEOUT_MS = 30_000;
+const SERVER_FINALIZATION_ALLOWANCE_MS = 5_000;
+const COMPATIBILITY_UPSTREAM_TIMEOUT_MS = (
+ ASR_UPSTREAM_TIMEOUT_MS
+ + CLEANUP_UPSTREAM_TIMEOUT_MS
+ + SERVER_FINALIZATION_ALLOWANCE_MS
+);
const COMPATIBILITY_UPLOAD_BUDGET_MS = 30_000;
const COMPATIBILITY_CSRF_ALLOWANCE_MS = 4_000;
export const VOICE_TRANSCRIPTION_TIMEOUT_MS = (
@@ -70,25 +77,51 @@ export type VoiceTranscriptionDependencies = {
telemetry?: (event: VoiceTelemetryEvent) => void;
};
+export type VoiceCleanupOutcome = 'success' | 'fallback';
+
+export type VoiceDictationResult = {
+ text: string;
+ cleanup: VoiceCleanupOutcome;
+};
+
export type VoiceTranscriptionSegment = {
- blob: Blob;
+ blob: Blob | null;
+ sequence: number;
+ final: boolean;
durationMs?: number;
overlapMs?: number;
attemptCount?: number;
- text?: string;
+ receipt?: 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>;
};
+type VoiceFinalizationDependencies = VoiceTranscriptionDependencies & {
+ finalize?: (input: {
+ blob: Blob | null;
+ sequence: number;
+ receipts: string[];
+ }) => Promise<VoiceDictationResult>;
+};
+
+type VoiceRequestMetadata = {
+ dictationId: string;
+ sequence: number;
+ overlapMs: number;
+ final: boolean;
+ finalizeOnly: boolean;
+ receipts: string[];
+ before: string;
+ after: string;
+};
+
+type VoiceServerResponse =
+ | { kind: 'receipt'; receipt: string; sequence: number }
+ | { kind: 'text'; text: string; cleanup?: VoiceCleanupOutcome };
+
const normalizedMimeType = (blob: Blob): string =>
blob.type.split(';', 1)[0]?.trim().toLowerCase() || 'audio/webm';
@@ -160,20 +193,35 @@ const responseError = async (response: Response): Promise<VoiceTranscriptionErro
return new VoiceTranscriptionError('failed', { status: response.status });
};
-const responseText = async (response: Response): Promise<string> => {
+const responsePayload = async (response: Response): Promise<VoiceServerResponse> => {
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 body = payload as { text?: unknown; cleanup?: unknown; receipt?: unknown; sequence?: unknown };
+ if (
+ typeof body.receipt === 'string'
+ && body.receipt.length > 0
+ && Number.isInteger(body.sequence)
+ && (body.sequence as number) >= 0
+ ) {
+ return { kind: 'receipt', receipt: body.receipt, sequence: body.sequence as number };
+ }
+ if (typeof body.text === 'string') {
+ if (!body.text.trim()) {
+ throw new VoiceTranscriptionError('empty', { status: response.status });
+ }
+ const cleanup = body.cleanup === 'success' || body.cleanup === 'fallback'
+ ? body.cleanup
+ : undefined;
+ return { kind: 'text', text: body.text, cleanup };
+ }
+ throw new VoiceTranscriptionError('failed', { status: response.status });
};
const readBlobAsBase64 = async (blob: Blob): Promise<string> => {
@@ -196,32 +244,50 @@ const readBlobAsBase64 = async (blob: Blob): Promise<string> => {
};
const transcribeLocally = async (
- blob: Blob,
+ blob: Blob | null,
localFetch: VoiceFetch,
signal: AbortSignal,
-): Promise<string> => {
+ metadata?: VoiceRequestMetadata,
+): Promise<VoiceServerResponse> => {
try {
- const data = await readBlobAsBase64(blob);
+ const data = blob ? await readBlobAsBase64(blob) : undefined;
const response = await localFetch('/api/asr/transcribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
- name: voiceRecordingFileName(blob),
- mime: normalizedMimeType(blob),
+ ...(blob
+ ? {
+ name: voiceRecordingFileName(blob),
+ mime: normalizedMimeType(blob),
+ }
+ : {}),
data,
+ ...(metadata
+ ? {
+ dictation_id: metadata.dictationId,
+ sequence: metadata.sequence,
+ overlap_ms: metadata.overlapMs,
+ final: metadata.final,
+ finalize_only: metadata.finalizeOnly,
+ receipts: metadata.receipts,
+ before: metadata.before,
+ after: metadata.after,
+ }
+ : {}),
}),
signal,
});
- return await responseText(response);
+ return await responsePayload(response);
} catch (error) {
throw normalizeTranscriptionError(error, signal);
}
};
-export const transcribeVoiceBlob = async (
- blob: Blob,
+const requestVoiceServer = async (
+ blob: Blob | null,
dependencies: VoiceTranscriptionDependencies = {},
-): Promise<string> => {
+ metadata?: VoiceRequestMetadata,
+): Promise<VoiceServerResponse> => {
const cloudFetch = dependencies.cloudFetch ?? avibeFetch;
const localFetch = dependencies.localFetch ?? apiFetch;
const timeoutMs = dependencies.timeoutMs ?? VOICE_TRANSCRIPTION_TIMEOUT_MS;
@@ -250,8 +316,8 @@ export const transcribeVoiceBlob = async (
providerStage,
outcome,
dictationId: dependencies.dictationId,
- sizeBytes: blob.size,
- mimeType: normalizedMimeType(blob),
+ sizeBytes: blob?.size ?? 0,
+ mimeType: blob ? normalizedMimeType(blob) : undefined,
durationMs: dependencies.durationMs,
elapsedMs: overrides.elapsedMs ?? Date.now() - startedAt,
httpStatus: overrides.httpStatus ?? error?.status,
@@ -289,14 +355,27 @@ export const transcribeVoiceBlob = async (
};
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);
+ if (blob) form.set('file', blob, voiceRecordingFileName(blob));
+ if (metadata) {
+ form.set('dictation_id', metadata.dictationId);
+ form.set('sequence', String(metadata.sequence));
+ form.set('overlap_ms', String(metadata.overlapMs));
+ form.set('final', String(metadata.final));
+ if (metadata.finalizeOnly) form.set('finalize_only', 'true');
+ for (const receipt of metadata.receipts) form.append('receipt', receipt);
+ if (metadata.before) form.set('before', metadata.before);
+ if (metadata.after) form.set('after', metadata.after);
+ }
+ const response = await cloudFetch(
+ metadata ? '/api/cloud/voice/dictations' : '/api/cloud/audio/transcriptions',
+ {
+ method: 'POST',
+ body: form,
+ signal: timeout.signal,
+ onAttempt: handleCloudAttempt,
+ },
+ );
+ const payload = await responsePayload(response);
report(
'cloud',
'response',
@@ -305,15 +384,15 @@ export const transcribeVoiceBlob = async (
undefined,
{ attemptCount: cloudAttemptCount },
);
- return text;
+ return payload;
} 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);
+ const payload = await transcribeLocally(blob, localFetch, timeout.signal, metadata);
report('local', 'response', 'success', localStartedAt);
- return text;
+ return payload;
} catch (localError) {
const normalized = normalizeTranscriptionError(localError, timeout.signal);
report(
@@ -349,21 +428,53 @@ export const transcribeVoiceBlob = async (
}
};
+export const transcribeVoiceBlob = async (
+ blob: Blob,
+ dependencies: VoiceTranscriptionDependencies = {},
+): Promise<string> => {
+ const response = await requestVoiceServer(blob, dependencies);
+ if (response.kind !== 'text') throw new VoiceTranscriptionError('failed');
+ if (!response.text.trim()) throw new VoiceTranscriptionError('empty');
+ return response.text;
+};
+
const transcribeVoiceSegment = async (
segment: VoiceTranscriptionSegment,
dependencies: VoiceSegmentTranscriptionDependencies,
): Promise<void> => {
+ if (segment.final || !segment.blob) return;
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,
- });
+ if (transcribe) {
+ segment.receipt = await transcribe(segment.blob);
+ return;
+ }
+ const dictationId = transcriptionDependencies.dictationId;
+ if (!dictationId) throw new VoiceTranscriptionError('failed');
+ const response = await requestVoiceServer(
+ segment.blob,
+ {
+ ...transcriptionDependencies,
+ durationMs: segment.durationMs,
+ attemptCount: segment.attemptCount,
+ },
+ {
+ dictationId,
+ sequence: segment.sequence,
+ overlapMs: segment.overlapMs ?? 0,
+ final: false,
+ finalizeOnly: false,
+ receipts: [],
+ before: '',
+ after: '',
+ },
+ );
+ if (response.kind !== 'receipt' || response.sequence !== segment.sequence) {
+ throw new VoiceTranscriptionError('failed');
+ }
+ segment.receipt = response.receipt;
} catch (error) {
segment.error = error;
}
@@ -397,6 +508,7 @@ export class VoiceTranscriptionQueue {
}
enqueue(segment: VoiceTranscriptionSegment): Promise<void> {
+ if (segment.final) return Promise.resolve();
const task = new Promise<void>((resolve) => {
this.pending.push({ segment, resolve });
});
@@ -449,7 +561,7 @@ export const transcribeVoiceSegments = async (
...transcriptionDependencies
} = dependencies;
const queue = segments.filter((segment) => (
- !segment.text && !isEmptyVoiceSegment(segment)
+ !segment.final && !segment.receipt
));
const concurrency = Math.max(1, Math.floor(requestedConcurrency));
const worker = async () => {
@@ -468,103 +580,68 @@ export const transcribeVoiceSegments = async (
);
};
-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 = (
+export const finalizeVoiceDictation = async (
segments: VoiceTranscriptionSegment[],
-): string => {
- const failed = segments.find((segment) => (
- !isEmptyVoiceSegment(segment)
- && (segment.error || !segment.text)
- ));
+ input: {
+ dictationId: string;
+ before: string;
+ after: string;
+ },
+ dependencies: VoiceFinalizationDependencies = {},
+): Promise<VoiceDictationResult> => {
+ const ordered = [...segments].sort((left, right) => left.sequence - right.sequence);
+ const finalSegment = ordered.find((segment) => segment.final);
+ if (!finalSegment || ordered.at(-1) !== finalSegment) {
+ throw new VoiceTranscriptionError('failed');
+ }
+ const prior = ordered.filter((segment) => !segment.final);
+ const failed = prior.find((segment) => segment.error || !segment.receipt);
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 receipts = prior.map((segment) => segment.receipt as string);
+ finalSegment.error = undefined;
+ finalSegment.attemptCount = (finalSegment.attemptCount ?? 0) + 1;
+ try {
+ const result = dependencies.finalize
+ ? await dependencies.finalize({
+ blob: finalSegment.blob,
+ sequence: finalSegment.sequence,
+ receipts,
+ })
+ : await (async () => {
+ const response = await requestVoiceServer(
+ finalSegment.blob,
+ {
+ ...dependencies,
+ durationMs: finalSegment.durationMs,
+ attemptCount: finalSegment.attemptCount,
+ dictationId: input.dictationId,
+ },
+ {
+ dictationId: input.dictationId,
+ sequence: finalSegment.sequence,
+ overlapMs: finalSegment.overlapMs ?? 0,
+ final: true,
+ finalizeOnly: finalSegment.blob === null,
+ receipts,
+ before: input.before,
+ after: input.after,
+ },
+ );
+ if (response.kind !== 'text' || !response.cleanup) {
+ throw new VoiceTranscriptionError('failed');
+ }
+ return { text: response.text, cleanup: response.cleanup };
+ })();
+ if (!result.text.trim()) throw new VoiceTranscriptionError('empty');
+ return result;
+ } catch (error) {
+ if (error instanceof VoiceTranscriptionError && error.status === 422) {
+ for (const segment of prior) segment.receipt = undefined;
+ }
+ finalSegment.error = error;
+ throw error;
}
- 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 db417ee28..10a3992cf 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -7828,6 +7828,8 @@ async def asr_transcribe():
from core.audio_asr import (
AudioAsrEmptyTranscriptError,
+ AudioAsrInvalidDictationError,
+ AudioAsrProtocolError,
AudioAsrService,
AudioAsrTimeoutError,
AudioAsrUnavailableError,
@@ -7836,19 +7838,22 @@ async def asr_transcribe():
from modules.im.base import FileAttachment
payload = request.json or {}
+ finalize_only = payload.get("finalize_only") is True
data_b64 = payload.get("data") or ""
- if not isinstance(data_b64, str) or not data_b64:
- return jsonify({"error": "data is required"}), 400
- if data_b64.startswith("data:") and "," in data_b64:
- data_b64 = data_b64.split(",", 1)[1]
- try:
- raw = base64.b64decode(data_b64)
- except Exception:
- return jsonify({"error": "invalid base64"}), 400
- if not raw:
- return jsonify({"error": "empty audio"}), 400
- if len(raw) > 25 * 1024 * 1024:
- return jsonify({"error": "file_too_large"}), 413
+ raw = b""
+ if not finalize_only:
+ if not isinstance(data_b64, str) or not data_b64:
+ return jsonify({"error": "data is required"}), 400
+ if data_b64.startswith("data:") and "," in data_b64:
+ data_b64 = data_b64.split(",", 1)[1]
+ try:
+ raw = base64.b64decode(data_b64)
+ except Exception:
+ return jsonify({"error": "invalid base64"}), 400
+ if not raw:
+ return jsonify({"error": "empty audio"}), 400
+ if len(raw) > 25 * 1024 * 1024:
+ 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()
@@ -7863,36 +7868,69 @@ async def asr_transcribe():
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:
+ if max_file_bytes is not None and raw 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:
+ dictation_id = payload.get("dictation_id")
+ if not isinstance(dictation_id, str) or not dictation_id:
+ dictation_id = f"legacy-{uuid.uuid4().hex}"
+ sequence = payload.get("sequence", 0)
+ overlap_ms = payload.get("overlap_ms", 0)
+ final = payload.get("final", True)
+ receipts = payload.get("receipts", [])
+ before = payload.get("before", "")
+ after = payload.get("after", "")
+ if (
+ not isinstance(sequence, int)
+ or isinstance(sequence, bool)
+ or not isinstance(overlap_ms, int)
+ or isinstance(overlap_ms, bool)
+ or not isinstance(final, bool)
+ or not isinstance(receipts, list)
+ or not all(isinstance(receipt, str) for receipt in receipts)
+ or not isinstance(before, str)
+ or not isinstance(after, str)
+ ):
+ return jsonify({"error": "invalid_dictation"}), 422
+
+ tmp_path = None
+ attachment = None
+ if raw:
+ suffix = Path(name).suffix or ".webm"
+ tmp_path = Path(tempfile.gettempdir()) / f"vibe_asr_{uuid.uuid4().hex[:8]}{suffix}"
+ tmp_path.write_bytes(raw)
attachment = FileAttachment(name=name, mimetype=mime, local_path=str(tmp_path), size=len(raw))
+ try:
try:
- transcripts = await service.transcribe_attachments(
- [attachment],
- raise_on_empty=True,
- raise_on_timeout=True,
- raise_on_unavailable=True,
- timeout_seconds=120.0,
+ result = await service.transcribe_voice_segment(
+ attachment,
+ dictation_id=dictation_id,
+ sequence=sequence,
+ overlap_ms=overlap_ms,
+ final=final,
+ finalize_only=finalize_only,
+ receipts=receipts,
+ before=before,
+ after=after,
+ timeout_seconds=155.0,
)
except AudioAsrEmptyTranscriptError:
return jsonify({"error": "transcription_empty"}), 422
+ except AudioAsrInvalidDictationError:
+ return jsonify({"error": "invalid_dictation"}), 422
except AudioAsrTimeoutError:
return jsonify({"error": "transcription_timeout"}), 504
except AudioAsrUnavailableError:
return jsonify({"error": "asr_unavailable"}), 503
+ except AudioAsrProtocolError:
+ return jsonify({"error": "transcription_failed"}), 502
finally:
- try:
- tmp_path.unlink()
- except OSError:
- pass
- if not transcripts:
- return jsonify({"error": "transcription_failed"}), 502
- return jsonify({"text": transcripts[0].text})
+ if tmp_path is not None:
+ try:
+ tmp_path.unlink()
+ except OSError:
+ pass
+ return jsonify(result)
@app.route("/api/asr/telemetry", methods=["POST"])