mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
feat(voice-input): enable dictation with a configured STT service (#8286)
* feat(voice-input): enable dictation with a configured STT service * fix(voice-input): bound provider responses and warn on old configs * fix(voice-input): redact config errors and validate transcripts
This commit is contained in:
parent
ee72fe281c
commit
5eb78f6530
@ -64,6 +64,7 @@ from app.gateway.routers import (
|
||||
trash,
|
||||
uploads,
|
||||
user_preferences,
|
||||
voice_input,
|
||||
)
|
||||
from app.gateway.trace_middleware import TraceMiddleware
|
||||
from deerflow.config import app_config as deerflow_app_config
|
||||
@ -1416,6 +1417,7 @@ This gateway provides runtime endpoints for agent runs plus custom endpoints for
|
||||
|
||||
# Input polishing API is mounted at /api/input-polish
|
||||
app.include_router(input_polish.router)
|
||||
app.include_router(voice_input.router)
|
||||
|
||||
# User-facing IM channel connection API is mounted at /api/channels
|
||||
app.include_router(channel_connections.router)
|
||||
|
||||
@ -12,6 +12,7 @@ from . import (
|
||||
thread_runs,
|
||||
threads,
|
||||
uploads,
|
||||
voice_input,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@ -19,6 +20,7 @@ __all__ = [
|
||||
"assistants_compat",
|
||||
"browser",
|
||||
"input_polish",
|
||||
"voice_input",
|
||||
"mcp",
|
||||
"models",
|
||||
"scheduled_tasks",
|
||||
|
||||
@ -90,6 +90,12 @@ class ToolApprovalFeature(BaseModel):
|
||||
allowed_modes: list[Literal["ask", "auto", "full"]] = Field(default_factory=list)
|
||||
|
||||
|
||||
class VoiceInputFeature(BaseModel):
|
||||
enabled: bool = False
|
||||
max_audio_bytes: int = 0
|
||||
max_duration_seconds: int = 0
|
||||
|
||||
|
||||
class FeaturesResponse(BaseModel):
|
||||
"""Frontend-facing feature availability flags."""
|
||||
|
||||
@ -102,6 +108,7 @@ class FeaturesResponse(BaseModel):
|
||||
scheduled_tasks: ScheduledTasksFeature
|
||||
thread_activity: ThreadActivityFeature
|
||||
run_inputs: bool = False
|
||||
voice_input: VoiceInputFeature = Field(default_factory=VoiceInputFeature)
|
||||
tool_approval: ToolApprovalFeature = Field(default_factory=ToolApprovalFeature)
|
||||
|
||||
|
||||
@ -115,8 +122,10 @@ async def list_features(request: Request, config: AppConfig = Depends(get_config
|
||||
"""Return availability of optional frontend features."""
|
||||
browser = browser_capability(config)
|
||||
approval = getattr(config, "hitl_approval", None)
|
||||
voice = getattr(config, "voice_input", None)
|
||||
subagent_batch_worker_running = bool(getattr(request.app.state, "subagent_batches_available", False))
|
||||
return FeaturesResponse(
|
||||
voice_input=VoiceInputFeature(enabled=True, max_audio_bytes=voice.max_audio_bytes, max_duration_seconds=voice.max_duration_seconds) if voice is not None else VoiceInputFeature(),
|
||||
tool_approval=ToolApprovalFeature(enabled=approval.enabled, default_mode=approval.default_mode, allowed_modes=approval.allowed_modes) if approval is not None else ToolApprovalFeature(),
|
||||
run_inputs=getattr(getattr(request.app.state, "run_manager", None), "input_store", None) is not None,
|
||||
agents_api=AgentsApiFeature(enabled=config.agents_api.enabled),
|
||||
|
||||
113
backend/app/gateway/routers/voice_input.py
Normal file
113
backend/app/gateway/routers/voice_input.py
Normal file
@ -0,0 +1,113 @@
|
||||
"""Bounded, authenticated proxy to an operator-configured transcription service."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.gateway.authz import require_permission
|
||||
from app.gateway.deps import get_config
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.config.voice_input_config import VoiceInputConfig
|
||||
from deerflow.utils.file_io import await_drained
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/voice-input", tags=["voice-input"])
|
||||
_MAX_RESPONSE_BYTES = 1024 * 1024
|
||||
_AUDIO_TYPES = {"audio/webm": "webm", "audio/mp4": "mp4", "audio/ogg": "ogg", "audio/wav": "wav", "audio/x-wav": "wav", "audio/mpeg": "mp3"}
|
||||
|
||||
|
||||
class TranscriptionResponse(BaseModel):
|
||||
text: str
|
||||
|
||||
|
||||
async def _read_audio(request: Request, limit: int) -> bytes:
|
||||
declared = request.headers.get("content-length")
|
||||
if declared is not None:
|
||||
try:
|
||||
size = int(declared)
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Invalid audio length") from None
|
||||
if size < 0:
|
||||
raise HTTPException(400, "Invalid audio length")
|
||||
if size > limit:
|
||||
raise HTTPException(413, "Audio exceeds the size limit")
|
||||
audio = bytearray()
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
async for chunk in request.stream():
|
||||
if len(audio) + len(chunk) > limit:
|
||||
raise HTTPException(413, "Audio exceeds the size limit")
|
||||
audio.extend(chunk)
|
||||
except TimeoutError:
|
||||
raise HTTPException(408, "Audio upload timed out") from None
|
||||
if not audio:
|
||||
raise HTTPException(400, "Audio is required")
|
||||
return bytes(audio)
|
||||
|
||||
|
||||
async def _transcribe(audio: bytes, mime: str, config: VoiceInputConfig) -> str:
|
||||
headers = {"Accept-Encoding": "identity"}
|
||||
if config.api_key:
|
||||
headers["Authorization"] = f"Bearer {config.api_key.get_secret_value()}"
|
||||
data = {"model": config.model, "response_format": "json"}
|
||||
if config.language:
|
||||
data["language"] = config.language
|
||||
try:
|
||||
async with asyncio.timeout(config.timeout_seconds):
|
||||
# Load TLS trust before owning HTTP handles, so cancellation during
|
||||
# this filesystem work cannot leak a client built in a worker thread.
|
||||
verify = await asyncio.to_thread(httpx.create_ssl_context)
|
||||
client = httpx.AsyncClient(timeout=config.timeout_seconds, follow_redirects=False, verify=verify)
|
||||
try:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
f"{config.base_url}/audio/transcriptions",
|
||||
headers=headers,
|
||||
data=data,
|
||||
files={"file": (f"recording.{_AUDIO_TYPES[mime]}", audio, mime)},
|
||||
) as response:
|
||||
if not response.is_success:
|
||||
raise HTTPException(502, "Transcription service failed")
|
||||
# A decoder could allocate beyond the limit before yielding a chunk.
|
||||
if response.headers.get("content-encoding", "identity").strip().lower() != "identity":
|
||||
raise HTTPException(502, "Invalid transcription response")
|
||||
payload = bytearray()
|
||||
async for chunk in response.aiter_bytes(chunk_size=16384):
|
||||
if len(payload) + len(chunk) > _MAX_RESPONSE_BYTES:
|
||||
raise HTTPException(502, "Invalid transcription response")
|
||||
payload.extend(chunk)
|
||||
finally:
|
||||
await await_drained(client.aclose())
|
||||
result = json.loads(payload)
|
||||
if not isinstance(result, dict) or not isinstance(result.get("text"), str):
|
||||
raise HTTPException(502, "Invalid transcription response")
|
||||
text = result["text"].strip()
|
||||
if not text:
|
||||
raise HTTPException(422, "No speech was detected")
|
||||
# JSON escapes can decode to lone surrogates that the API cannot serialize.
|
||||
text.encode("utf-8")
|
||||
return text
|
||||
except (TimeoutError, httpx.TimeoutException):
|
||||
raise HTTPException(504, "Transcription service timed out") from None
|
||||
except (httpx.HTTPError, ValueError, UnicodeError):
|
||||
# Never surface or log provider URLs, credentials, audio or response bodies.
|
||||
logger.warning("Voice transcription request failed")
|
||||
raise HTTPException(502, "Transcription service failed") from None
|
||||
|
||||
|
||||
@router.post("/transcribe", response_model=TranscriptionResponse, summary="Transcribe Composer Audio")
|
||||
@require_permission("runs", "create")
|
||||
async def transcribe_audio(request: Request, config: AppConfig = Depends(get_config)) -> TranscriptionResponse:
|
||||
voice = config.voice_input
|
||||
if voice is None:
|
||||
raise HTTPException(404, "Voice input is disabled")
|
||||
mime = request.headers.get("content-type", "").partition(";")[0].strip().lower()
|
||||
if mime not in _AUDIO_TYPES:
|
||||
raise HTTPException(415, "Unsupported audio format")
|
||||
# Authentication/authorization runs before reading any audio or contacting STT.
|
||||
audio = await _read_audio(request, voice.max_audio_bytes)
|
||||
return TranscriptionResponse(text=await _transcribe(audio, mime, voice))
|
||||
@ -67,6 +67,7 @@ from deerflow.config.tool_progress_config import ToolProgressConfig
|
||||
from deerflow.config.tool_search_config import ToolSearchConfig, load_tool_search_config_from_dict
|
||||
from deerflow.config.typesafe_config import TypeSafeConfig, load_typesafe_config_from_dict
|
||||
from deerflow.config.verification_config import VerificationConfig
|
||||
from deerflow.config.voice_input_config import VoiceInputConfig
|
||||
from deerflow.env import load_selected_env_file
|
||||
from deerflow.extensions.loader import ExtensionSpec
|
||||
|
||||
@ -325,6 +326,7 @@ class AppConfig(BaseModel):
|
||||
)
|
||||
authorization: AuthorizationConfig = Field(default_factory=AuthorizationConfig, description="Fine-grained resource authorization configuration (RBAC and beyond)")
|
||||
input_polish: InputPolishConfig = Field(default_factory=InputPolishConfig, description="Pre-send input polishing configuration.")
|
||||
voice_input: VoiceInputConfig | None = Field(default=None, description="Optional composer transcription service. Omit to hide voice input.")
|
||||
suggestions: SuggestionsConfig = Field(default_factory=SuggestionsConfig, description="Follow-up suggestions configuration.")
|
||||
circuit_breaker: CircuitBreakerConfig = Field(default_factory=CircuitBreakerConfig, description="LLM circuit breaker configuration")
|
||||
llm_call: LlmCallConfig = Field(default_factory=LlmCallConfig, description="LLM call execution configuration (concurrency / rate shaping)")
|
||||
@ -345,7 +347,8 @@ class AppConfig(BaseModel):
|
||||
pii_redaction: PiiRedactionConfig = Field(default_factory=PiiRedactionConfig, description="PII redaction middleware configuration (issue #3190)")
|
||||
safety_finish_reason: SafetyFinishReasonConfig = Field(default_factory=SafetyFinishReasonConfig, description="Provider safety-filter finish_reason interception middleware configuration")
|
||||
auth: AuthAppConfig = Field(default_factory=AuthAppConfig, description="Authentication configuration (local + OIDC SSO)")
|
||||
model_config = ConfigDict(extra="allow")
|
||||
# Validation errors are logged at startup and on reload. Resolved inputs can contain secrets.
|
||||
model_config = ConfigDict(extra="allow", hide_input_in_errors=True)
|
||||
database: DatabaseConfig = Field(
|
||||
default_factory=DatabaseConfig,
|
||||
description=format_field_description(
|
||||
|
||||
@ -0,0 +1,49 @@
|
||||
"""Operator-configured, optional speech-to-text for the composer."""
|
||||
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, SecretStr, ValidationInfo, field_validator
|
||||
|
||||
from deerflow.config._boolean_guards import reject_boolean
|
||||
|
||||
|
||||
class VoiceInputConfig(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", hide_input_in_errors=True)
|
||||
|
||||
base_url: str = Field(description="OpenAI-compatible API base URL, including /v1 if required")
|
||||
model: str = Field(min_length=1, description="Transcription model served by this endpoint")
|
||||
api_key: SecretStr | None = Field(default=None, description="Optional bearer key; supports $ENV_VAR through AppConfig")
|
||||
language: str | None = Field(default=None, pattern=r"^[a-z]{2}$", description="Optional ISO-639-1 language hint; omit for automatic detection")
|
||||
max_audio_bytes: int = Field(default=10 * 1024 * 1024, ge=1024, le=25 * 1024 * 1024)
|
||||
max_duration_seconds: int = Field(default=120, ge=1, le=600, description="Browser recording time limit")
|
||||
timeout_seconds: int = Field(default=60, ge=1, le=120, description="Total provider request timeout")
|
||||
|
||||
@field_validator("max_audio_bytes", "max_duration_seconds", "timeout_seconds", mode="before")
|
||||
@classmethod
|
||||
def reject_boolean_limits(cls, value: object, info: ValidationInfo) -> object:
|
||||
return reject_boolean(value, info, kind="an integer")
|
||||
|
||||
@field_validator("base_url")
|
||||
@classmethod
|
||||
def validate_base_url(cls, value: str) -> str:
|
||||
value = value.strip().rstrip("/")
|
||||
parsed = urlsplit(value)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or any(c.isspace() for c in value):
|
||||
raise ValueError("base_url must be an HTTP(S) API base URL without credentials, query or fragment")
|
||||
# Validate the port even though the provider client builds the URL later.
|
||||
_ = parsed.port
|
||||
return value
|
||||
|
||||
@field_validator("model")
|
||||
@classmethod
|
||||
def validate_model(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("model must not be blank")
|
||||
return value.strip()
|
||||
|
||||
@field_validator("api_key")
|
||||
@classmethod
|
||||
def validate_api_key(cls, value: SecretStr | None) -> SecretStr | None:
|
||||
if value is not None and (not value.get_secret_value().strip() or any(c in value.get_secret_value() for c in "\r\n")):
|
||||
raise ValueError("api_key must not be blank or contain newlines")
|
||||
return value
|
||||
35
backend/tests/blocking_io/test_voice_input.py
Normal file
35
backend/tests/blocking_io/test_voice_input.py
Normal file
@ -0,0 +1,35 @@
|
||||
"""Transcription constructs TLS off-loop and uses async transport on-loop."""
|
||||
|
||||
import json
|
||||
import ssl
|
||||
import threading
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.gateway.routers.voice_input import _transcribe
|
||||
from deerflow.config.voice_input_config import VoiceInputConfig
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_transcription_does_not_block_on_tls_or_network(monkeypatch):
|
||||
loop_thread = threading.get_ident()
|
||||
original = ssl.create_default_context
|
||||
contexts = []
|
||||
requests = []
|
||||
|
||||
def create_context(*args, **kwargs):
|
||||
assert threading.get_ident() != loop_thread
|
||||
contexts.append(True)
|
||||
return original(*args, **kwargs)
|
||||
|
||||
async def send(_transport, request):
|
||||
assert threading.get_ident() == loop_thread
|
||||
requests.append(await request.aread())
|
||||
return httpx.Response(200, content=json.dumps({"text": "spoken task"}).encode())
|
||||
|
||||
monkeypatch.setattr(ssl, "create_default_context", create_context)
|
||||
monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", send)
|
||||
text = await _transcribe(b"audio", "audio/webm", VoiceInputConfig(base_url="https://speech.example/v1", model="stt-test"))
|
||||
assert text == "spoken task"
|
||||
assert contexts and len(requests) == 1
|
||||
@ -79,6 +79,7 @@ def test_features_reports_agents_api_enabled() -> None:
|
||||
"agents_api": {"enabled": True},
|
||||
"tool_approval": {"enabled": False, "default_mode": "ask", "allowed_modes": []},
|
||||
"run_inputs": False,
|
||||
"voice_input": {"enabled": False, "max_audio_bytes": 0, "max_duration_seconds": 0},
|
||||
"browser_control": {"enabled": False},
|
||||
"mcp_tasks": {"enabled": False},
|
||||
"subagent_batches": {
|
||||
@ -104,6 +105,7 @@ def test_features_reports_agents_api_disabled() -> None:
|
||||
"agents_api": {"enabled": False},
|
||||
"tool_approval": {"enabled": False, "default_mode": "ask", "allowed_modes": []},
|
||||
"run_inputs": False,
|
||||
"voice_input": {"enabled": False, "max_audio_bytes": 0, "max_duration_seconds": 0},
|
||||
"browser_control": {"enabled": False},
|
||||
"mcp_tasks": {"enabled": False},
|
||||
"subagent_batches": {
|
||||
|
||||
16
backend/tests/test_nginx_voice_input.py
Normal file
16
backend/tests/test_nginx_voice_input.py
Normal file
@ -0,0 +1,16 @@
|
||||
"""All shipped ingress routes must admit the maximum configurable STT body."""
|
||||
|
||||
import pytest
|
||||
from support.nginx_conf import NGINX_CONFIGS, extract_location_block, parse_body_size_bytes, parse_read_timeout_seconds, read_config
|
||||
|
||||
from deerflow.config.voice_input_config import VoiceInputConfig
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", NGINX_CONFIGS)
|
||||
def test_audio_route_preserves_recording_limits(path):
|
||||
block = extract_location_block(read_config(path), "= /api/voice-input/transcribe")
|
||||
config = VoiceInputConfig(base_url="https://speech.example/v1", model="stt", max_audio_bytes=25 * 1024 * 1024, timeout_seconds=120)
|
||||
assert parse_body_size_bytes(block) >= config.max_audio_bytes
|
||||
assert parse_read_timeout_seconds(block) >= config.timeout_seconds + 30
|
||||
assert "proxy_request_buffering off;" in block
|
||||
assert "proxy_http_version 1.1;" in block
|
||||
262
backend/tests/test_voice_input.py
Normal file
262
backend/tests/test_voice_input.py
Normal file
@ -0,0 +1,262 @@
|
||||
"""Exercise the authenticated route and real HTTPX multipart encoding offline."""
|
||||
|
||||
from pathlib import Path
|
||||
from shutil import copyfile
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import ValidationError
|
||||
from starlette.requests import Request
|
||||
|
||||
from app.gateway import deps
|
||||
from app.gateway.auth.models import User
|
||||
from app.gateway.authz import AuthContext
|
||||
from app.gateway.deps import get_config
|
||||
from app.gateway.routers import features, voice_input
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.config.voice_input_config import VoiceInputConfig
|
||||
|
||||
|
||||
def settings(**overrides):
|
||||
return VoiceInputConfig(base_url="https://speech.example/v1", model="stt-test", **overrides)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def upstream(monkeypatch):
|
||||
state = SimpleNamespace(requests=[], response=httpx.Response(200, json={"text": " Spoken task "}), error=None)
|
||||
|
||||
async def handle(_transport, request):
|
||||
await request.aread()
|
||||
state.requests.append(request)
|
||||
if state.error:
|
||||
raise state.error
|
||||
return state.response
|
||||
|
||||
monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", handle)
|
||||
return state
|
||||
|
||||
|
||||
def client_for(config, *, authenticated=True, permitted=True, use_config_loader=False):
|
||||
app = FastAPI()
|
||||
app.include_router(voice_input.router)
|
||||
if not use_config_loader:
|
||||
app.dependency_overrides[get_config] = lambda: SimpleNamespace(voice_input=config)
|
||||
|
||||
@app.middleware("http")
|
||||
async def auth(request, call_next):
|
||||
request.state.auth = AuthContext(user=User(email="tester@example.com") if authenticated else None, permissions=["runs:create"] if permitted else [])
|
||||
return await call_next(request)
|
||||
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_recording_is_forwarded_as_multipart_using_server_config(upstream):
|
||||
with client_for(settings(api_key="synthetic-key", language="zh")) as client:
|
||||
response = client.post("/api/voice-input/transcribe?model=untrusted&base_url=https://other.example", content=b"encoded audio", headers={"Content-Type": "audio/webm;codecs=opus"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"text": "Spoken task"}
|
||||
assert len(upstream.requests) == 1
|
||||
request = upstream.requests[0]
|
||||
assert str(request.url) == "https://speech.example/v1/audio/transcriptions"
|
||||
assert request.headers["authorization"] == "Bearer synthetic-key"
|
||||
assert request.headers["accept-encoding"] == "identity"
|
||||
assert request.headers["content-type"].startswith("multipart/form-data; boundary=")
|
||||
for value in (b'name="model"\r\n\r\nstt-test', b'name="language"\r\n\r\nzh', b'name="response_format"\r\n\r\njson', b'filename="recording.webm"', b"Content-Type: audio/webm", b"encoded audio"):
|
||||
assert value in request.content
|
||||
assert b"untrusted" not in request.content
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime,extension", [("audio/mp4", "mp4"), ("audio/ogg;codecs=opus", "ogg")])
|
||||
def test_other_browser_recording_formats_and_no_key(upstream, mime, extension):
|
||||
with client_for(settings()) as client:
|
||||
assert client.post("/api/voice-input/transcribe", content=b"audio", headers={"Content-Type": mime}).status_code == 200
|
||||
assert "authorization" not in upstream.requests[0].headers
|
||||
assert f'filename="recording.{extension}"'.encode() in upstream.requests[0].content
|
||||
assert b'name="language"' not in upstream.requests[0].content
|
||||
|
||||
|
||||
@pytest.mark.parametrize("authenticated,permitted,status", [(False, False, 401), (True, False, 403)])
|
||||
def test_permission_required(upstream, authenticated, permitted, status):
|
||||
with client_for(settings(), authenticated=authenticated, permitted=permitted) as client:
|
||||
response = client.post("/api/voice-input/transcribe", content=b"audio", headers={"Content-Type": "audio/webm"})
|
||||
assert response.status_code == status
|
||||
assert not upstream.requests
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config,content,mime,status", [(None, b"audio", "audio/webm", 404), (settings(), b"", "audio/webm", 400), (settings(), b"audio", "text/plain", 415), (settings(max_audio_bytes=1024), b"a" * 1025, "audio/webm", 413)])
|
||||
def test_disabled_invalid_and_oversized_requests_never_contact_provider(upstream, config, content, mime, status):
|
||||
with client_for(config) as client:
|
||||
response = client.post("/api/voice-input/transcribe", content=content, headers={"Content-Type": mime})
|
||||
assert response.status_code == status
|
||||
assert not upstream.requests
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"provider,status",
|
||||
[
|
||||
(httpx.Response(401, text="private provider error synthetic-key"), 502),
|
||||
(httpx.Response(302, headers={"Location": "https://other.example/secret"}), 502),
|
||||
(httpx.Response(200, text="not json synthetic-key"), 502),
|
||||
(httpx.Response(200, json=[]), 502),
|
||||
(httpx.Response(200, json={"text": 1}), 502),
|
||||
(httpx.Response(200, content=rb'{"text":"\ud800"}'), 502),
|
||||
(httpx.Response(200, json={"text": " "}), 422),
|
||||
(httpx.Response(200, text="x" * (1024 * 1024 + 1)), 502),
|
||||
],
|
||||
)
|
||||
def test_provider_failures_are_bounded_and_redacted(upstream, provider, status):
|
||||
upstream.response = provider
|
||||
with client_for(settings(api_key="synthetic-key")) as client:
|
||||
response = client.post("/api/voice-input/transcribe", content=b"audio", headers={"Content-Type": "audio/webm"})
|
||||
assert response.status_code == status
|
||||
assert len(upstream.requests) == 1
|
||||
assert "synthetic-key" not in response.text
|
||||
assert "speech.example" not in response.text
|
||||
|
||||
|
||||
def test_invalid_voice_key_is_hidden_in_config_errors(monkeypatch, caplog, upstream):
|
||||
secret_marker = "synthetic-invalid-voice-key"
|
||||
voice = {"base_url": "https://speech.example/v1", "model": "stt-test", "api_key": f"{secret_marker}\n"}
|
||||
|
||||
with pytest.raises(ValidationError) as direct_error:
|
||||
VoiceInputConfig.model_validate(voice)
|
||||
assert secret_marker not in str(direct_error.value)
|
||||
|
||||
def load_invalid_config():
|
||||
return AppConfig.model_validate({"config_version": 67, "sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}, "voice_input": voice})
|
||||
|
||||
monkeypatch.setattr(deps, "get_app_config", load_invalid_config)
|
||||
with client_for(None, use_config_loader=True) as client:
|
||||
response = client.post("/api/voice-input/transcribe", content=b"audio", headers={"Content-Type": "audio/webm"})
|
||||
|
||||
assert response.status_code == 503
|
||||
assert "voice_input.api_key" in caplog.text
|
||||
assert secret_marker not in caplog.text
|
||||
assert not upstream.requests
|
||||
|
||||
|
||||
def test_provider_timeout_is_sanitized(upstream):
|
||||
upstream.error = httpx.ReadTimeout("https://speech.example/secret")
|
||||
with client_for(settings()) as client:
|
||||
response = client.post("/api/voice-input/transcribe", content=b"audio", headers={"Content-Type": "audio/webm"})
|
||||
assert response.status_code == 504
|
||||
assert "speech.example" not in response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encoding", ["gzip", "br", "identity, gzip"])
|
||||
def test_encoded_provider_response_is_rejected_before_reading(upstream, encoding):
|
||||
class Body(httpx.AsyncByteStream):
|
||||
async def __aiter__(self):
|
||||
pytest.fail("encoded provider body was read")
|
||||
yield b""
|
||||
|
||||
async def aclose(self):
|
||||
self.closed = True
|
||||
|
||||
body = Body()
|
||||
upstream.response = httpx.Response(200, headers={"Content-Encoding": encoding}, stream=body)
|
||||
with client_for(settings()) as client:
|
||||
response = client.post("/api/voice-input/transcribe", content=b"audio", headers={"Content-Type": "audio/webm"})
|
||||
assert response.status_code == 502
|
||||
assert body.closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("declared", [None, "1"])
|
||||
async def test_stream_size_is_enforced_without_trusting_content_length(declared, upstream):
|
||||
chunks = iter([b"a" * 800, b"b" * 800])
|
||||
headers = [(b"content-type", b"audio/webm")]
|
||||
if declared:
|
||||
headers.append((b"content-length", declared.encode()))
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": next(chunks), "more_body": True}
|
||||
|
||||
request = Request({"type": "http", "method": "POST", "headers": headers}, receive)
|
||||
request.state.auth = AuthContext(user=User(email="tester@example.com"), permissions=["runs:create"])
|
||||
with pytest.raises(HTTPException) as error:
|
||||
await voice_input.transcribe_audio(request, config=SimpleNamespace(voice_input=settings(max_audio_bytes=1024)))
|
||||
assert error.value.status_code == 413
|
||||
assert not upstream.requests
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("authenticated", [False, True])
|
||||
async def test_auth_precedes_reading_the_audio(authenticated):
|
||||
async def receive():
|
||||
pytest.fail("unauthorized request body was consumed")
|
||||
|
||||
request = Request({"type": "http", "method": "POST", "headers": [(b"content-type", b"audio/webm")]}, receive)
|
||||
request.state.auth = AuthContext(user=User(email="tester@example.com") if authenticated else None)
|
||||
with pytest.raises(HTTPException) as error:
|
||||
await voice_input.transcribe_audio(request, config=SimpleNamespace(voice_input=settings()))
|
||||
assert error.value.status_code == (403 if authenticated else 401)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"override",
|
||||
[
|
||||
{"base_url": "file:///tmp/model"},
|
||||
{"base_url": "https://user:key@speech.example/v1"},
|
||||
{"base_url": "https://speech.example/v1?key=secret"},
|
||||
{"base_url": " "},
|
||||
{"model": " "},
|
||||
{"api_key": ""},
|
||||
{"max_audio_bytes": True},
|
||||
{"timeout_seconds": 121},
|
||||
],
|
||||
)
|
||||
def test_invalid_config_is_rejected(override):
|
||||
with pytest.raises(ValidationError):
|
||||
VoiceInputConfig.model_validate({"base_url": "https://speech.example/v1", "model": "stt-test", **override})
|
||||
|
||||
|
||||
def test_unconfigured_and_null_sections_disable_voice_input():
|
||||
base = {"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}}
|
||||
assert AppConfig.model_validate(base).voice_input is None
|
||||
assert AppConfig.model_validate({**base, "voice_input": None}).voice_input is None
|
||||
with pytest.raises(ValidationError):
|
||||
AppConfig.model_validate({**base, "voice_input": {}})
|
||||
|
||||
|
||||
def test_existing_config_warns_about_the_voice_input_schema(tmp_path, caplog):
|
||||
example = Path(__file__).resolve().parents[2] / "config.example.yaml"
|
||||
copyfile(example, tmp_path / example.name)
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text("config_version: 66\nsandbox:\n use: deerflow.sandbox.local:LocalSandboxProvider\n", encoding="utf-8")
|
||||
assert AppConfig.from_file(str(path)).voice_input is None
|
||||
assert "Your config.yaml (version 66) is outdated" in caplog.text
|
||||
|
||||
|
||||
def test_config_resolves_environment_once_and_does_not_expose_secrets(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("TEST_VOICE_KEY", "$literal-dollar-key")
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text("config_version: 66\nsandbox:\n use: deerflow.sandbox.local:LocalSandboxProvider\nvoice_input:\n base_url: http://localhost:9000/v1/\n model: stt-test\n api_key: $TEST_VOICE_KEY\n")
|
||||
config = AppConfig.from_file(str(path))
|
||||
assert config.voice_input.api_key.get_secret_value() == "$literal-dollar-key"
|
||||
assert config.voice_input.base_url == "http://localhost:9000/v1"
|
||||
assert "literal-dollar-key" not in repr(config.voice_input)
|
||||
app = FastAPI()
|
||||
app.include_router(features.router)
|
||||
app.dependency_overrides[get_config] = lambda: config
|
||||
with TestClient(app) as client:
|
||||
response = client.get("/api/features")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["voice_input"] == {"enabled": True, "max_audio_bytes": 10485760, "max_duration_seconds": 120}
|
||||
assert "literal-dollar-key" not in response.text
|
||||
assert "localhost:9000" not in response.text
|
||||
assert "stt-test" not in response.text
|
||||
config.voice_input = None
|
||||
assert client.get("/api/features").json()["voice_input"]["enabled"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field,value", [("max_audio_bytes", 4096), ("max_duration_seconds", 30), ("timeout_seconds", 15)])
|
||||
def test_numeric_settings_accept_resolved_environment_strings_and_reject_booleans(monkeypatch, field, value):
|
||||
monkeypatch.setenv("TEST_VOICE_LIMIT", str(value))
|
||||
raw = AppConfig.resolve_env_variables({"base_url": "https://speech.example/v1", "model": "stt", field: "$TEST_VOICE_LIMIT"})
|
||||
assert getattr(VoiceInputConfig.model_validate(raw), field) == value
|
||||
with pytest.raises(ValidationError):
|
||||
VoiceInputConfig.model_validate({**raw, field: True})
|
||||
@ -1527,6 +1527,23 @@ input_polish:
|
||||
model_name: null
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Optional Voice Input (Speech-to-Text)
|
||||
# ============================================================================
|
||||
# Omit this block (or set voice_input: null) to hide the microphone in the UI.
|
||||
# Requires an OpenAI-compatible POST /audio/transcriptions endpoint and a model
|
||||
# that accepts the browser's recording format (WebM/Opus, MP4 or Ogg/Opus).
|
||||
# The base URL and key stay on the Gateway; audio is sent only after recording.
|
||||
# voice_input:
|
||||
# base_url: https://speech.example.com/v1
|
||||
# model: your-transcription-model
|
||||
# api_key: $VOICE_INPUT_API_KEY # Optional for services without authentication.
|
||||
# language: zh # Optional; omit to detect the spoken language.
|
||||
# max_audio_bytes: 10485760 # 10 MiB; must not exceed the provider's limit.
|
||||
# max_duration_seconds: 120 # Browser recording limit.
|
||||
# timeout_seconds: 60 # Total provider request timeout (1–120 seconds).
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Loop Detection Configuration
|
||||
# ============================================================================
|
||||
|
||||
@ -285,6 +285,19 @@ data:
|
||||
}
|
||||
{{- end }}
|
||||
|
||||
# Audio recordings must reach the Gateway's bounded streaming reader.
|
||||
location = /api/voice-input/transcribe {
|
||||
proxy_pass http://gateway_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $forwarded_proto;
|
||||
client_max_body_size 25M;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 150s;
|
||||
}
|
||||
|
||||
# Catch-all for other /api/ routes (e.g. /api/v1/auth/*).
|
||||
location /api/ {
|
||||
proxy_pass http://gateway_upstream;
|
||||
|
||||
@ -341,6 +341,19 @@ http {
|
||||
|
||||
}
|
||||
|
||||
# Audio recordings must reach the Gateway's bounded streaming reader.
|
||||
location = /api/voice-input/transcribe {
|
||||
proxy_pass http://$gateway_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $forwarded_proto;
|
||||
client_max_body_size 25M;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 150s;
|
||||
}
|
||||
|
||||
# Catch-all for /api/ routes not covered above (e.g. /api/v1/auth/*).
|
||||
# More specific prefix and regex locations above still take precedence.
|
||||
location /api/ {
|
||||
|
||||
@ -358,6 +358,19 @@ http {
|
||||
proxy_cache off;
|
||||
}
|
||||
|
||||
# Audio recordings must reach the Gateway's bounded streaming reader.
|
||||
location = /api/voice-input/transcribe {
|
||||
proxy_pass http://gateway;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 25M;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 150s;
|
||||
}
|
||||
|
||||
# Catch-all for any /api/* prefix not matched by a more specific block above.
|
||||
# Covers the auth module (/api/v1/auth/login, /me, /change-password, ...),
|
||||
# plus feedback / runs / token-usage routes that 2.0-rc added without
|
||||
|
||||
BIN
docs/guide/assets/voice-input/entry.png
Normal file
BIN
docs/guide/assets/voice-input/entry.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
BIN
docs/guide/assets/voice-input/recording.png
Normal file
BIN
docs/guide/assets/voice-input/recording.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
@ -357,7 +357,30 @@ The Web UI composer supports `@` references at the cursor or through the `@` but
|
||||
|
||||
After picking an inline reference, typing continues immediately after it. Moving the cursor keeps the position you chose, including when editing text beside a reference.
|
||||
|
||||
The Web UI composer also supports browser-based voice dictation when the browser exposes the Web Speech API. The microphone button transcribes speech into the local draft only; DeerFlow receives only the transcribed text, while audio handling is delegated to the browser or operating system speech-recognition service according to that environment's policy. Users can review or edit the text before sending. Dictation keeps words separated when browsers trim transcript segments, preserves Chinese and Japanese joins, and attaches leading punctuation and percent signs without adding spaces.
|
||||
The Web UI composer supports optional voice input. The microphone appears beside Send only when the operator configures `voice_input` in `config.yaml`. Omitting the section or setting it to `null` hides the microphone and disables its shortcut. It is independent of chat models and does not need a built-in speech model or a browser speech-recognition service.
|
||||
|
||||
```yaml
|
||||
voice_input:
|
||||
base_url: https://speech.example.com/v1
|
||||
model: your-transcription-model
|
||||
api_key: $VOICE_INPUT_API_KEY # Omit for an endpoint without authentication.
|
||||
# language: zh # Optional ISO-639-1 hint; otherwise auto-detect.
|
||||
max_audio_bytes: 10485760
|
||||
max_duration_seconds: 120
|
||||
timeout_seconds: 60
|
||||
```
|
||||
|
||||
The service must support an OpenAI-compatible multipart `POST /audio/transcriptions` with `model`, `file`, and `response_format=json`, returning `{ "text": "..." }`. Choose a model that accepts the browser's format: WebM/Opus, MP4, or Ogg/Opus. `base_url` is the API prefix, not the full transcription URL. Credentials are resolved on the server using the same `$ENV_VAR` configuration mechanism as other model services. The feature response contains only availability and recording limits. The authenticated Gateway forwards audio to this service; it does not persist the recording or create a conversation message. Audio handling at the configured service follows that service's policy.
|
||||
|
||||
Use HTTPS (or localhost), allow microphone access, then click the microphone or press `Ctrl+M` while the composer has focus. Click again, press `Ctrl+M`, or press `Enter` in the editor to finish. Recording also ends at the configured duration. The audio is uploaded when recording finishes; the completed transcript is appended to the draft for review, editing, or **Polish input** before sending. Sending and polishing wait during recording and transcription. Cancel (`Esc` or the status bar's cancel button) keeps the existing draft. Typing or switching conversations cancels pending recording/transcription, releases the microphone, and ignores late results. Cancelling after upload cannot recall audio already received by the service. Errors preserve the draft and allow retry.
|
||||
|
||||
The configured microphone appears beside Send; recording adds a status bar with a cancel action:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
The Gateway requires `runs:create`, accepts only supported audio MIME types, enforces `max_audio_bytes` even without `Content-Length`, and bounds upload/provider request time. The transcription service must return uncompressed JSON of at most 1 MiB. `max_duration_seconds` limits browser recording; the server enforces bytes rather than decoding audio duration. Set limits to match the chosen service. Removing the configuration disables new transcription requests immediately; refreshed feature discovery hides the UI.
|
||||
|
||||
The Web UI displays a localized AI-generated-content disclaimer below the composer in both standard and custom-agent conversations, reminding users to verify important
|
||||
information.
|
||||
|
||||
@ -10,12 +10,10 @@ import {
|
||||
GraduationCapIcon,
|
||||
LightbulbIcon,
|
||||
Loader2Icon,
|
||||
MicIcon,
|
||||
PaperclipIcon,
|
||||
PlusIcon,
|
||||
RocketIcon,
|
||||
SparklesIcon,
|
||||
SquareIcon,
|
||||
TargetIcon,
|
||||
Undo2Icon,
|
||||
XIcon,
|
||||
@ -137,16 +135,9 @@ import {
|
||||
type UploadLimitViolation,
|
||||
} from "@/core/uploads";
|
||||
import { AttachmentUploadSession } from "@/core/uploads/attachment-upload-session";
|
||||
import {
|
||||
appendSpeechTranscript,
|
||||
getSpeechRecognitionConstructor,
|
||||
getSpeechRecognitionLanguage,
|
||||
mapSpeechRecognitionError,
|
||||
readSpeechRecognitionTranscript,
|
||||
shouldRestartSpeechRecognition,
|
||||
type BrowserSpeechRecognition,
|
||||
type SpeechRecognitionErrorKind,
|
||||
} from "@/core/voice-input/speech-recognition";
|
||||
import { appendVoiceTranscript } from "@/core/voice-input/api";
|
||||
import { useVoiceInputCapability } from "@/core/voice-input/capability";
|
||||
import { useVoiceInput } from "@/core/voice-input/use-voice-input";
|
||||
import { isCompositionConfirmEnter, isIMEComposing } from "@/lib/ime";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@ -213,6 +204,7 @@ import {
|
||||
normalizeGoalStatusRead,
|
||||
type GoalChangeKind,
|
||||
} from "./use-active-goal";
|
||||
import { VoiceInputButton, VoiceInputStatus } from "./voice-input-controls";
|
||||
|
||||
const COMPOSER_DRAFT_SAVE_DELAY_MS = 300;
|
||||
|
||||
@ -276,10 +268,6 @@ export type InputBoxSubmitOptions = {
|
||||
onSent?: () => void;
|
||||
};
|
||||
|
||||
type VoiceRecognitionStartOptions = {
|
||||
focusAfterStart?: boolean;
|
||||
};
|
||||
|
||||
function buildHiddenConversationQuoteMessage({
|
||||
contexts,
|
||||
}: {
|
||||
@ -582,17 +570,7 @@ export function InputBox({
|
||||
controller: null,
|
||||
sequence: 0,
|
||||
});
|
||||
const voiceRecognitionRef = useRef<BrowserSpeechRecognition | null>(null);
|
||||
const voiceBaseTextRef = useRef("");
|
||||
const voiceLatestTextRef = useRef("");
|
||||
const voiceLastErrorKindRef = useRef<SpeechRecognitionErrorKind | null>(null);
|
||||
const voiceStopRequestedRef = useRef(false);
|
||||
const voiceRestartTimerRef = useRef<ReturnType<typeof setTimeout> | null>(
|
||||
null,
|
||||
);
|
||||
const startVoiceRecognitionRef = useRef<
|
||||
((options?: VoiceRecognitionStartOptions) => boolean) | null
|
||||
>(null);
|
||||
const promptHistoryIndexRef = useRef<number | null>(null);
|
||||
const promptHistoryDraftRef = useRef("");
|
||||
const pendingDraftSubmissionRef = useRef<{
|
||||
@ -625,7 +603,6 @@ export function InputBox({
|
||||
const [followupsHidden, setFollowupsHidden] = useState(false);
|
||||
const [followupsLoading, setFollowupsLoading] = useState(false);
|
||||
const [polishingInput, setPolishingInput] = useState(false);
|
||||
const [voiceListening, setVoiceListening] = useState(false);
|
||||
const [inputPolishUndo, setInputPolishUndo] = useState<{
|
||||
originalText: string;
|
||||
rewrittenText: string;
|
||||
@ -642,57 +619,45 @@ export function InputBox({
|
||||
const stoppedByUserRef = useRef(false);
|
||||
const messagesRef = useRef(thread.messages);
|
||||
|
||||
const clearVoiceRestartTimer = useCallback(() => {
|
||||
if (voiceRestartTimerRef.current === null) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(voiceRestartTimerRef.current);
|
||||
voiceRestartTimerRef.current = null;
|
||||
}, []);
|
||||
|
||||
const cleanupVoiceRecognition = useCallback(
|
||||
(
|
||||
recognition: BrowserSpeechRecognition | null,
|
||||
options: { keepListening?: boolean } = {},
|
||||
) => {
|
||||
clearVoiceRestartTimer();
|
||||
if (!recognition) {
|
||||
if (!options.keepListening) {
|
||||
voiceLastErrorKindRef.current = null;
|
||||
voiceStopRequestedRef.current = false;
|
||||
setVoiceListening(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
recognition.onend = null;
|
||||
recognition.onerror = null;
|
||||
recognition.onresult = null;
|
||||
if (voiceRecognitionRef.current === recognition) {
|
||||
voiceRecognitionRef.current = null;
|
||||
}
|
||||
if (!options.keepListening) {
|
||||
voiceLastErrorKindRef.current = null;
|
||||
voiceStopRequestedRef.current = false;
|
||||
setVoiceListening(false);
|
||||
}
|
||||
},
|
||||
[clearVoiceRestartTimer],
|
||||
const voiceCapability = useVoiceInputCapability(
|
||||
user?.id,
|
||||
!isMock && canCreateRuns,
|
||||
);
|
||||
|
||||
const abortVoiceInput = useCallback(() => {
|
||||
const recognition = voiceRecognitionRef.current;
|
||||
voiceStopRequestedRef.current = true;
|
||||
if (!recognition) {
|
||||
cleanupVoiceRecognition(null);
|
||||
return;
|
||||
}
|
||||
cleanupVoiceRecognition(recognition);
|
||||
try {
|
||||
recognition.abort();
|
||||
} catch {
|
||||
// Browser implementations can throw when the recognizer already ended.
|
||||
}
|
||||
}, [cleanupVoiceRecognition]);
|
||||
const {
|
||||
phase: voicePhase,
|
||||
supported: voiceInputSupported,
|
||||
start: startVoiceInput,
|
||||
stop: stopVoiceInput,
|
||||
abort: abortVoiceInput,
|
||||
} = useVoiceInput({
|
||||
enabled: voiceCapability !== null,
|
||||
scope: `${user?.id ?? ""}:${threadId}:${projectId ?? ""}`,
|
||||
maxBytes: voiceCapability?.max_audio_bytes ?? 0,
|
||||
maxSeconds: voiceCapability?.max_duration_seconds ?? 0,
|
||||
onTranscript: (transcript) => {
|
||||
textInput.setInput(
|
||||
appendVoiceTranscript(voiceBaseTextRef.current, transcript),
|
||||
);
|
||||
},
|
||||
onError: (code) => {
|
||||
const messages = {
|
||||
permission_denied: t.inputBox.voiceInputPermissionDenied,
|
||||
microphone_unavailable: t.inputBox.voiceInputMicrophoneUnavailable,
|
||||
unsupported: t.inputBox.voiceInputUnsupported,
|
||||
too_large: t.inputBox.voiceInputTooLarge,
|
||||
unavailable: t.inputBox.voiceInputUnavailable,
|
||||
no_speech: t.inputBox.voiceInputNoSpeech,
|
||||
failed: t.inputBox.voiceInputFailed,
|
||||
};
|
||||
toast.error(messages[code]);
|
||||
},
|
||||
});
|
||||
const voiceListening = voicePhase !== "idle";
|
||||
useLayoutEffect(() => {
|
||||
// Reference pickers and history can edit the draft without a typing event.
|
||||
if (voiceListening && textInput.value !== voiceBaseTextRef.current)
|
||||
abortVoiceInput();
|
||||
}, [abortVoiceInput, textInput.value, voiceListening]);
|
||||
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [pendingSuggestion, setPendingSuggestion] = useState<string | null>(
|
||||
@ -1671,6 +1636,9 @@ export function InputBox({
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (message: PromptInputMessage) => {
|
||||
// Keep the draft until recording and transcription have completed.
|
||||
if (voiceListening)
|
||||
return Promise.reject(new Error("voice-input-active"));
|
||||
if (mentionInFlight.current)
|
||||
return Promise.reject(new Error("Reference is loading"));
|
||||
if (status === "streaming") {
|
||||
@ -1805,6 +1773,7 @@ export function InputBox({
|
||||
},
|
||||
[
|
||||
abortVoiceInput,
|
||||
voiceListening,
|
||||
canCreateRuns,
|
||||
canSendBusyInput,
|
||||
onBusySubmit,
|
||||
@ -2197,6 +2166,7 @@ export function InputBox({
|
||||
inputPolishUndo !== null &&
|
||||
(textInput.value ?? "") === inputPolishUndo.rewrittenText;
|
||||
const inputPolishDisabled =
|
||||
voiceListening ||
|
||||
isComposerDisabled ||
|
||||
isMockThread ||
|
||||
polishingInput ||
|
||||
@ -2204,192 +2174,93 @@ export function InputBox({
|
||||
(status === "streaming" ||
|
||||
slashCommandQuery !== null ||
|
||||
!canPolishInput(textInput.value ?? "")));
|
||||
const speechRecognitionConstructor = useMemo(
|
||||
() =>
|
||||
typeof window === "undefined"
|
||||
? null
|
||||
: getSpeechRecognitionConstructor(window),
|
||||
[],
|
||||
);
|
||||
const voiceInputSupported = speechRecognitionConstructor !== null;
|
||||
|
||||
const getVoiceInputErrorMessage = useCallback(
|
||||
(kind: SpeechRecognitionErrorKind) => {
|
||||
switch (kind) {
|
||||
case "permission_denied":
|
||||
return t.inputBox.voiceInputPermissionDenied;
|
||||
case "microphone_unavailable":
|
||||
return t.inputBox.voiceInputMicrophoneUnavailable;
|
||||
case "unsupported_language":
|
||||
return t.inputBox.voiceInputUnsupportedLanguage;
|
||||
case "network":
|
||||
return t.inputBox.voiceInputNetworkError;
|
||||
case "no_speech":
|
||||
return t.inputBox.voiceInputNoSpeech;
|
||||
case "cancelled":
|
||||
return null;
|
||||
default:
|
||||
return t.inputBox.voiceInputFailed;
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const startVoiceRecognition = useCallback(
|
||||
(options: VoiceRecognitionStartOptions = {}) => {
|
||||
if (composerLocked || !speechRecognitionConstructor) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const recognition = new speechRecognitionConstructor();
|
||||
recognition.continuous = true;
|
||||
recognition.interimResults = true;
|
||||
recognition.lang = getSpeechRecognitionLanguage(locale);
|
||||
recognition.maxAlternatives = 1;
|
||||
voiceLastErrorKindRef.current = null;
|
||||
voiceLatestTextRef.current = voiceBaseTextRef.current;
|
||||
voiceRecognitionRef.current = recognition;
|
||||
|
||||
recognition.onresult = (event) => {
|
||||
if (voiceRecognitionRef.current !== recognition) {
|
||||
return;
|
||||
}
|
||||
const transcript = readSpeechRecognitionTranscript(event.results).text;
|
||||
const nextValue = appendSpeechTranscript(
|
||||
voiceBaseTextRef.current,
|
||||
transcript,
|
||||
);
|
||||
voiceLatestTextRef.current = nextValue;
|
||||
textInput.setInput(nextValue);
|
||||
};
|
||||
recognition.onerror = (event) => {
|
||||
const errorKind = mapSpeechRecognitionError(event.error);
|
||||
voiceLastErrorKindRef.current = errorKind;
|
||||
if (
|
||||
!voiceStopRequestedRef.current &&
|
||||
shouldRestartSpeechRecognition(errorKind)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = getVoiceInputErrorMessage(errorKind);
|
||||
if (message) {
|
||||
toast.error(message);
|
||||
}
|
||||
};
|
||||
recognition.onend = () => {
|
||||
const shouldRestart =
|
||||
voiceRecognitionRef.current === recognition &&
|
||||
!voiceStopRequestedRef.current &&
|
||||
shouldRestartSpeechRecognition(voiceLastErrorKindRef.current);
|
||||
if (shouldRestart) {
|
||||
voiceBaseTextRef.current = voiceLatestTextRef.current;
|
||||
cleanupVoiceRecognition(recognition, { keepListening: true });
|
||||
voiceRestartTimerRef.current = setTimeout(() => {
|
||||
voiceRestartTimerRef.current = null;
|
||||
if (voiceStopRequestedRef.current) {
|
||||
cleanupVoiceRecognition(null);
|
||||
return;
|
||||
}
|
||||
const restarted = startVoiceRecognitionRef.current?.() ?? false;
|
||||
if (!restarted) {
|
||||
cleanupVoiceRecognition(null);
|
||||
}
|
||||
}, 150);
|
||||
return;
|
||||
}
|
||||
cleanupVoiceRecognition(recognition);
|
||||
};
|
||||
|
||||
setVoiceListening(true);
|
||||
try {
|
||||
recognition.start();
|
||||
if (options.focusAfterStart) {
|
||||
requestAnimationFrame(() => {
|
||||
if (inlineSkillTextRef.current) {
|
||||
focusContentEditableEnd(inlineSkillTextRef.current);
|
||||
} else {
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
cleanupVoiceRecognition(recognition);
|
||||
toast.error(t.inputBox.voiceInputFailed);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[
|
||||
cleanupVoiceRecognition,
|
||||
composerLocked,
|
||||
getVoiceInputErrorMessage,
|
||||
locale,
|
||||
speechRecognitionConstructor,
|
||||
t.inputBox.voiceInputFailed,
|
||||
textInput,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
startVoiceRecognitionRef.current = startVoiceRecognition;
|
||||
}, [startVoiceRecognition]);
|
||||
|
||||
const stopVoiceInput = useCallback(() => {
|
||||
const recognition = voiceRecognitionRef.current;
|
||||
voiceStopRequestedRef.current = true;
|
||||
if (!recognition) {
|
||||
cleanupVoiceRecognition(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
recognition.stop();
|
||||
} catch {
|
||||
cleanupVoiceRecognition(recognition);
|
||||
}
|
||||
}, [cleanupVoiceRecognition]);
|
||||
|
||||
const toggleVoiceInput = useCallback(() => {
|
||||
if (voiceListening) {
|
||||
stopVoiceInput();
|
||||
return;
|
||||
}
|
||||
if (composerLocked) {
|
||||
return;
|
||||
}
|
||||
if (!speechRecognitionConstructor) {
|
||||
toast.error(t.inputBox.voiceInputUnsupported);
|
||||
return;
|
||||
}
|
||||
|
||||
if (composerLocked || !voiceCapability || !voiceInputSupported) return;
|
||||
abortInputPolishRequest();
|
||||
setInputPolishUndo(null);
|
||||
promptHistoryIndexRef.current = null;
|
||||
promptHistoryDraftRef.current = "";
|
||||
voiceStopRequestedRef.current = false;
|
||||
voiceBaseTextRef.current = textInput.value ?? "";
|
||||
voiceLatestTextRef.current = voiceBaseTextRef.current;
|
||||
startVoiceRecognition({ focusAfterStart: true });
|
||||
setMentionQuery(null);
|
||||
setMentionButtonOpen(false);
|
||||
void startVoiceInput();
|
||||
if (inlineSkillTextRef.current)
|
||||
focusContentEditableEnd(inlineSkillTextRef.current);
|
||||
else textareaRef.current?.focus();
|
||||
}, [
|
||||
abortInputPolishRequest,
|
||||
composerLocked,
|
||||
speechRecognitionConstructor,
|
||||
startVoiceRecognition,
|
||||
voiceCapability,
|
||||
voiceInputSupported,
|
||||
startVoiceInput,
|
||||
stopVoiceInput,
|
||||
t.inputBox.voiceInputUnsupported,
|
||||
textInput,
|
||||
textInput.value,
|
||||
voiceListening,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (composerLocked && voiceListening) {
|
||||
stopVoiceInput();
|
||||
}
|
||||
}, [composerLocked, stopVoiceInput, voiceListening]);
|
||||
const cancelVoiceInput = useCallback(() => {
|
||||
abortVoiceInput();
|
||||
if (inlineSkillTextRef.current)
|
||||
focusContentEditableEnd(inlineSkillTextRef.current);
|
||||
else textareaRef.current?.focus();
|
||||
}, [abortVoiceInput]);
|
||||
|
||||
const handleVoiceKeyDown = useCallback(
|
||||
(event: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (
|
||||
!voiceCapability ||
|
||||
!voiceInputSupported ||
|
||||
!(event.target instanceof Node) ||
|
||||
!event.currentTarget.contains(event.target) ||
|
||||
isIMEComposing(event) ||
|
||||
event.repeat
|
||||
)
|
||||
return;
|
||||
if (
|
||||
event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.altKey &&
|
||||
!event.shiftKey &&
|
||||
event.key.toLowerCase() === "m"
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleVoiceInput();
|
||||
} else if (voiceListening && event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
cancelVoiceInput();
|
||||
} else if (
|
||||
voiceListening &&
|
||||
event.key === "Enter" &&
|
||||
!event.shiftKey &&
|
||||
(event.target === textareaRef.current ||
|
||||
inlineSkillTextRef.current?.contains(event.target))
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
stopVoiceInput();
|
||||
}
|
||||
},
|
||||
[
|
||||
cancelVoiceInput,
|
||||
stopVoiceInput,
|
||||
toggleVoiceInput,
|
||||
voiceListening,
|
||||
voiceCapability,
|
||||
voiceInputSupported,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return () => abortVoiceInput();
|
||||
}, [abortVoiceInput, threadId]);
|
||||
if (composerLocked && voiceListening) {
|
||||
abortVoiceInput();
|
||||
}
|
||||
}, [abortVoiceInput, composerLocked, voiceListening]);
|
||||
|
||||
useEffect(() => {
|
||||
setCommandSuggestionIndex(0);
|
||||
@ -2980,6 +2851,7 @@ export function InputBox({
|
||||
return (
|
||||
<div
|
||||
ref={promptRootRef}
|
||||
onKeyDownCapture={handleVoiceKeyDown}
|
||||
className={cn(
|
||||
"relative flex min-w-0 flex-col",
|
||||
isWelcomeMode ? "gap-4" : "gap-2",
|
||||
@ -3294,6 +3166,7 @@ export function InputBox({
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<VoiceInputStatus phase={voicePhase} onCancel={cancelVoiceInput} />
|
||||
<PromptInputFooter className="flex flex-col gap-2 sm:flex-row sm:flex-nowrap">
|
||||
<PromptInputTools className="w-full min-w-0 flex-wrap sm:w-auto sm:flex-1">
|
||||
<Tooltip content={t.inputBox.mentionPicker}>
|
||||
@ -3311,12 +3184,6 @@ export function InputBox({
|
||||
disabled={composerLocked}
|
||||
uploadLimits={uploadLimits}
|
||||
/>
|
||||
<VoiceInputButton
|
||||
disabled={composerLocked}
|
||||
listening={voiceListening}
|
||||
supported={voiceInputSupported}
|
||||
onToggle={toggleVoiceInput}
|
||||
/>
|
||||
<Tooltip
|
||||
content={
|
||||
polishingInput
|
||||
@ -3683,10 +3550,20 @@ export function InputBox({
|
||||
className="rounded-full"
|
||||
variant="outline"
|
||||
status={runInputSending ? "submitted" : "ready"}
|
||||
disabled={composerLocked || !textInput.value.trim()}
|
||||
disabled={
|
||||
composerLocked || voiceListening || !textInput.value.trim()
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{voiceCapability && (
|
||||
<VoiceInputButton
|
||||
disabled={composerLocked && !voiceListening}
|
||||
phase={voicePhase}
|
||||
supported={voiceInputSupported}
|
||||
onToggle={toggleVoiceInput}
|
||||
/>
|
||||
)}
|
||||
<PromptInputSubmit
|
||||
className="rounded-full"
|
||||
disabled={
|
||||
@ -3695,7 +3572,7 @@ export function InputBox({
|
||||
polishingInput ||
|
||||
mentionBusy ||
|
||||
runInputSending
|
||||
: composerLocked) ||
|
||||
: composerLocked || voiceListening) ||
|
||||
stopDenied ||
|
||||
sendDenied ||
|
||||
(status !== "streaming" && conversationReferencesUnavailable)
|
||||
@ -3782,50 +3659,6 @@ export function InputBox({
|
||||
);
|
||||
}
|
||||
|
||||
function VoiceInputButton({
|
||||
disabled,
|
||||
listening,
|
||||
supported,
|
||||
onToggle,
|
||||
}: {
|
||||
disabled?: boolean;
|
||||
listening: boolean;
|
||||
supported: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const tooltipContent = !supported
|
||||
? t.inputBox.voiceInputUnsupported
|
||||
: listening
|
||||
? t.inputBox.voiceInputListening
|
||||
: t.inputBox.voiceInputStart;
|
||||
const label = listening
|
||||
? t.inputBox.voiceInputStopLabel
|
||||
: t.inputBox.voiceInputStartLabel;
|
||||
|
||||
return (
|
||||
<Tooltip content={<span className="block max-w-72">{tooltipContent}</span>}>
|
||||
<PromptInputButton
|
||||
aria-label={label}
|
||||
aria-pressed={listening}
|
||||
className={cn(
|
||||
"px-2!",
|
||||
listening && "text-primary bg-primary/10 hover:bg-primary/15",
|
||||
)}
|
||||
data-testid="voice-input-button"
|
||||
disabled={(disabled ?? false) || !supported}
|
||||
onClick={onToggle}
|
||||
>
|
||||
{listening ? (
|
||||
<SquareIcon className="size-3 fill-current" />
|
||||
) : (
|
||||
<MicIcon className="size-3" />
|
||||
)}
|
||||
</PromptInputButton>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function SuggestionList({
|
||||
onSelectPlaceholder,
|
||||
}: {
|
||||
|
||||
104
frontend/src/components/workspace/voice-input-controls.tsx
Normal file
104
frontend/src/components/workspace/voice-input-controls.tsx
Normal file
@ -0,0 +1,104 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon, XIcon } from "lucide-react";
|
||||
|
||||
import { PromptInputButton } from "@/components/ai-elements/prompt-input";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import type { VoiceInputPhase } from "@/core/voice-input/use-voice-input";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { Tooltip } from "./tooltip";
|
||||
|
||||
export function VoiceInputButton({
|
||||
disabled,
|
||||
phase,
|
||||
supported,
|
||||
onToggle,
|
||||
}: {
|
||||
disabled: boolean;
|
||||
phase: VoiceInputPhase;
|
||||
supported: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const active = phase !== "idle";
|
||||
const label = active
|
||||
? t.inputBox.voiceInputStopLabel
|
||||
: t.inputBox.voiceInputStartLabel;
|
||||
const tooltip = !supported
|
||||
? t.inputBox.voiceInputUnsupported
|
||||
: phase === "stopping"
|
||||
? t.inputBox.voiceInputFinishing
|
||||
: active
|
||||
? t.inputBox.voiceInputStop
|
||||
: t.inputBox.voiceInputStart;
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
content={
|
||||
<span className="block max-w-72">
|
||||
{tooltip} {supported && "(Ctrl+M)"}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<span className="inline-flex">
|
||||
<PromptInputButton
|
||||
aria-label={label}
|
||||
aria-keyshortcuts="Control+M"
|
||||
aria-pressed={active}
|
||||
className={cn(
|
||||
"size-9 rounded-full p-0! max-sm:size-11",
|
||||
active && "text-primary bg-primary/10 hover:bg-primary/15",
|
||||
)}
|
||||
data-testid="voice-input-button"
|
||||
disabled={disabled || !supported || phase === "stopping"}
|
||||
onClick={onToggle}
|
||||
>
|
||||
{phase === "starting" || phase === "stopping" ? (
|
||||
<Loader2Icon className="size-4 motion-safe:animate-spin" />
|
||||
) : active ? (
|
||||
<SquareIcon className="size-4 fill-current" />
|
||||
) : (
|
||||
<MicIcon className="size-4" />
|
||||
)}
|
||||
</PromptInputButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function VoiceInputStatus({
|
||||
phase,
|
||||
onCancel,
|
||||
}: {
|
||||
phase: VoiceInputPhase;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
if (phase === "idle") return null;
|
||||
return (
|
||||
<div className="bg-secondary/60 flex items-center gap-2 rounded-lg px-3 py-1">
|
||||
<span
|
||||
className="bg-primary size-2 shrink-0 rounded-full motion-safe:animate-pulse"
|
||||
aria-hidden
|
||||
/>
|
||||
<span
|
||||
role="status"
|
||||
data-testid="voice-input-status"
|
||||
className="flex-1 text-sm"
|
||||
>
|
||||
{phase === "starting"
|
||||
? t.inputBox.voiceInputStarting
|
||||
: phase === "stopping"
|
||||
? t.inputBox.voiceInputFinishing
|
||||
: t.inputBox.voiceInputListening}
|
||||
</span>
|
||||
<PromptInputButton
|
||||
aria-label={t.inputBox.voiceInputCancel}
|
||||
title={`${t.inputBox.voiceInputCancel} (Esc)`}
|
||||
className="size-9 shrink-0 max-sm:size-11"
|
||||
onClick={onCancel}
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</PromptInputButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -2,6 +2,11 @@ import { fetch } from "@/core/api/fetcher";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
export interface FeaturesResponse {
|
||||
voice_input?: {
|
||||
enabled: boolean;
|
||||
max_audio_bytes: number;
|
||||
max_duration_seconds: number;
|
||||
};
|
||||
run_inputs?: boolean;
|
||||
tool_approval?: {
|
||||
enabled: boolean;
|
||||
@ -86,8 +91,10 @@ export interface SubagentBatchesCapability {
|
||||
maxRunning: number;
|
||||
}
|
||||
|
||||
export async function fetchFeatures(): Promise<FeaturesResponse> {
|
||||
const res = await fetch(`${getBackendBaseURL()}/api/features`);
|
||||
export async function fetchFeatures(
|
||||
signal?: AbortSignal,
|
||||
): Promise<FeaturesResponse> {
|
||||
const res = await fetch(`${getBackendBaseURL()}/api/features`, { signal });
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to load features: ${res.statusText}`);
|
||||
}
|
||||
|
||||
@ -625,19 +625,22 @@ export const enUS: Translations = {
|
||||
voiceInputStartLabel: "Dictate with voice",
|
||||
voiceInputStopLabel: "Stop voice input",
|
||||
voiceInputStart:
|
||||
"Dictate with voice. DeerFlow receives only transcribed text; audio is handled by your browser or system speech service.",
|
||||
"Record audio and send it to the configured transcription service.",
|
||||
voiceInputStop: "Stop voice input",
|
||||
voiceInputListening: "Listening... Click to stop voice input.",
|
||||
voiceInputListening: "Recording… Finish to review or polish your text.",
|
||||
voiceInputStarting: "Waiting for microphone…",
|
||||
voiceInputFinishing: "Transcribing audio…",
|
||||
voiceInputCancel: "Cancel voice input",
|
||||
voiceInputUnsupported:
|
||||
"Voice input is not supported in this browser. Try Chrome or Edge.",
|
||||
"Recording requires HTTPS (or localhost) and a browser that supports microphone recording.",
|
||||
voiceInputPermissionDenied:
|
||||
"Microphone access was denied. Allow microphone access and try again.",
|
||||
voiceInputMicrophoneUnavailable:
|
||||
"No microphone was detected. Check your device input and try again.",
|
||||
voiceInputUnsupportedLanguage:
|
||||
"Voice input does not support the current language in this browser.",
|
||||
voiceInputNetworkError:
|
||||
"Voice input could not reach the browser speech service.",
|
||||
voiceInputTooLarge:
|
||||
"Recording exceeds the size limit. Please try a shorter recording.",
|
||||
voiceInputUnavailable:
|
||||
"Voice input is no longer enabled. Your draft has been kept.",
|
||||
voiceInputNoSpeech: "No speech was detected. Please try again.",
|
||||
voiceInputFailed: "Voice input failed. Please try again.",
|
||||
mode: "Mode",
|
||||
|
||||
@ -540,11 +540,14 @@ export interface Translations {
|
||||
voiceInputStart: string;
|
||||
voiceInputStop: string;
|
||||
voiceInputListening: string;
|
||||
voiceInputStarting: string;
|
||||
voiceInputFinishing: string;
|
||||
voiceInputCancel: string;
|
||||
voiceInputUnsupported: string;
|
||||
voiceInputPermissionDenied: string;
|
||||
voiceInputMicrophoneUnavailable: string;
|
||||
voiceInputUnsupportedLanguage: string;
|
||||
voiceInputNetworkError: string;
|
||||
voiceInputTooLarge: string;
|
||||
voiceInputUnavailable: string;
|
||||
voiceInputNoSpeech: string;
|
||||
voiceInputFailed: string;
|
||||
mode: string;
|
||||
|
||||
@ -592,16 +592,18 @@ export const zhCN: Translations = {
|
||||
inputPolishCancel: "取消优化",
|
||||
voiceInputStartLabel: "语音输入",
|
||||
voiceInputStopLabel: "停止语音输入",
|
||||
voiceInputStart:
|
||||
"语音输入。DeerFlow 只接收转写文本,音频由浏览器或系统语音服务处理。",
|
||||
voiceInputStart: "录音结束后,将音频发送到已配置的转写服务。",
|
||||
voiceInputStop: "停止语音输入",
|
||||
voiceInputListening: "正在聆听... 点击停止语音输入。",
|
||||
voiceInputListening: "正在录音… 结束后可检查文字或润色。",
|
||||
voiceInputStarting: "正在等待麦克风…",
|
||||
voiceInputFinishing: "正在转写音频…",
|
||||
voiceInputCancel: "取消语音输入",
|
||||
voiceInputUnsupported:
|
||||
"当前浏览器不支持语音输入。建议使用 Chrome 或 Edge。",
|
||||
"录音需要通过 HTTPS(或 localhost)访问,并使用支持麦克风录音的浏览器。",
|
||||
voiceInputPermissionDenied: "麦克风权限被拒绝。请允许麦克风访问后重试。",
|
||||
voiceInputMicrophoneUnavailable: "未检测到麦克风。请检查设备输入后重试。",
|
||||
voiceInputUnsupportedLanguage: "当前浏览器不支持该语言的语音输入。",
|
||||
voiceInputNetworkError: "无法连接浏览器语音识别服务。",
|
||||
voiceInputTooLarge: "录音超过大小限制,请缩短录音后重试。",
|
||||
voiceInputUnavailable: "语音输入已停用,草稿已保留。",
|
||||
voiceInputNoSpeech: "没有检测到语音,请重试。",
|
||||
voiceInputFailed: "语音输入失败,请重试。",
|
||||
mode: "模式",
|
||||
|
||||
64
frontend/src/core/voice-input/api.ts
Normal file
64
frontend/src/core/voice-input/api.ts
Normal file
@ -0,0 +1,64 @@
|
||||
import { fetch } from "@/core/api/fetcher";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
export type VoiceInputErrorCode =
|
||||
| "permission_denied"
|
||||
| "microphone_unavailable"
|
||||
| "unsupported"
|
||||
| "too_large"
|
||||
| "unavailable"
|
||||
| "no_speech"
|
||||
| "failed";
|
||||
|
||||
export class VoiceInputError extends Error {
|
||||
constructor(public readonly code: VoiceInputErrorCode) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export async function transcribeAudio(
|
||||
audio: Blob,
|
||||
signal: AbortSignal,
|
||||
): Promise<string> {
|
||||
const response = await fetch(
|
||||
`${getBackendBaseURL()}/api/voice-input/transcribe`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": audio.type },
|
||||
body: audio,
|
||||
signal,
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const code =
|
||||
response.status === 404
|
||||
? "unavailable"
|
||||
: response.status === 413
|
||||
? "too_large"
|
||||
: response.status === 422
|
||||
? "no_speech"
|
||||
: "failed";
|
||||
throw new VoiceInputError(code);
|
||||
}
|
||||
const data: unknown = await response.json();
|
||||
if (
|
||||
!data ||
|
||||
typeof data !== "object" ||
|
||||
!("text" in data) ||
|
||||
typeof data.text !== "string"
|
||||
) {
|
||||
throw new VoiceInputError("failed");
|
||||
}
|
||||
const text = data.text.trim();
|
||||
if (!text) throw new VoiceInputError("no_speech");
|
||||
return text;
|
||||
}
|
||||
|
||||
export function appendVoiceTranscript(
|
||||
draft: string,
|
||||
transcript: string,
|
||||
): string {
|
||||
const text = transcript.trim();
|
||||
if (!text) return draft;
|
||||
return draft.trimEnd() ? `${draft.trimEnd()} ${text}` : text;
|
||||
}
|
||||
30
frontend/src/core/voice-input/capability.ts
Normal file
30
frontend/src/core/voice-input/capability.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { fetchFeatures } from "@/core/features/api";
|
||||
import { isStaticWebsiteOnly } from "@/core/static-mode";
|
||||
|
||||
export function useVoiceInputCapability(
|
||||
viewerId: string | undefined,
|
||||
enabled: boolean,
|
||||
) {
|
||||
const available = enabled && !isStaticWebsiteOnly();
|
||||
const query = useQuery({
|
||||
queryKey: ["features", "voice_input", viewerId],
|
||||
queryFn: ({ signal }) => fetchFeatures(signal),
|
||||
enabled: available,
|
||||
staleTime: 0,
|
||||
retry: false,
|
||||
refetchOnMount: true,
|
||||
});
|
||||
const feature =
|
||||
available && query.isSuccess ? query.data?.voice_input : undefined;
|
||||
if (
|
||||
feature?.enabled !== true ||
|
||||
!Number.isInteger(feature.max_audio_bytes) ||
|
||||
feature.max_audio_bytes <= 0 ||
|
||||
!Number.isInteger(feature.max_duration_seconds) ||
|
||||
feature.max_duration_seconds <= 0
|
||||
)
|
||||
return null;
|
||||
return feature;
|
||||
}
|
||||
@ -1,232 +0,0 @@
|
||||
export type SpeechRecognitionErrorCode =
|
||||
| "aborted"
|
||||
| "audio-capture"
|
||||
| "bad-grammar"
|
||||
| "language-not-supported"
|
||||
| "network"
|
||||
| "no-speech"
|
||||
| "not-allowed"
|
||||
| "phrases-not-supported"
|
||||
| "service-not-allowed";
|
||||
|
||||
export type SpeechRecognitionErrorKind =
|
||||
| "cancelled"
|
||||
| "microphone_unavailable"
|
||||
| "permission_denied"
|
||||
| "unsupported_language"
|
||||
| "network"
|
||||
| "no_speech"
|
||||
| "unknown";
|
||||
|
||||
export type SpeechRecognitionConstructor = new () => BrowserSpeechRecognition;
|
||||
|
||||
export type SpeechRecognitionEventLike = {
|
||||
results: SpeechRecognitionResultListLike;
|
||||
};
|
||||
|
||||
export type SpeechRecognitionErrorEventLike = {
|
||||
error?: SpeechRecognitionErrorCode | string;
|
||||
};
|
||||
|
||||
export type BrowserSpeechRecognition = {
|
||||
continuous: boolean;
|
||||
interimResults: boolean;
|
||||
lang: string;
|
||||
maxAlternatives: number;
|
||||
onend: (() => void) | null;
|
||||
onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
|
||||
onresult: ((event: SpeechRecognitionEventLike) => void) | null;
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
abort: () => void;
|
||||
};
|
||||
|
||||
type SpeechRecognitionWindow = Window &
|
||||
typeof globalThis & {
|
||||
SpeechRecognition?: SpeechRecognitionConstructor;
|
||||
webkitSpeechRecognition?: SpeechRecognitionConstructor;
|
||||
};
|
||||
|
||||
export type SpeechRecognitionAlternativeLike = {
|
||||
transcript?: string;
|
||||
};
|
||||
|
||||
export type SpeechRecognitionResultLike = {
|
||||
0?: SpeechRecognitionAlternativeLike;
|
||||
isFinal: boolean;
|
||||
length: number;
|
||||
};
|
||||
|
||||
export type SpeechRecognitionResultListLike = {
|
||||
[index: number]: SpeechRecognitionResultLike | undefined;
|
||||
length: number;
|
||||
};
|
||||
|
||||
const DEFAULT_SPEECH_RECOGNITION_LANGUAGE = "en-US";
|
||||
const SPEECH_RECOGNITION_LANGUAGE_ALLOWLIST = new Set([
|
||||
"de",
|
||||
"en",
|
||||
"es",
|
||||
"fr",
|
||||
"it",
|
||||
"ja",
|
||||
"ko",
|
||||
"pt",
|
||||
"zh",
|
||||
]);
|
||||
|
||||
export function getSpeechRecognitionConstructor(
|
||||
value: unknown = globalThis,
|
||||
): SpeechRecognitionConstructor | null {
|
||||
const maybeWindow = value as Partial<SpeechRecognitionWindow>;
|
||||
return (
|
||||
maybeWindow.SpeechRecognition ?? maybeWindow.webkitSpeechRecognition ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function getSpeechRecognitionLanguage(locale: string): string {
|
||||
const normalized = normalizeBCP47Locale(locale);
|
||||
const language = normalized.split("-")[0]?.toLowerCase();
|
||||
|
||||
if (language === "zh") {
|
||||
return "zh-CN";
|
||||
}
|
||||
if (language && SPEECH_RECOGNITION_LANGUAGE_ALLOWLIST.has(language)) {
|
||||
return normalized;
|
||||
}
|
||||
return DEFAULT_SPEECH_RECOGNITION_LANGUAGE;
|
||||
}
|
||||
|
||||
export function shouldRestartSpeechRecognition(
|
||||
lastError: SpeechRecognitionErrorKind | null,
|
||||
): boolean {
|
||||
return lastError === null || lastError === "no_speech";
|
||||
}
|
||||
|
||||
// Scripts written without spaces between words and the punctuation that
|
||||
// surrounds them: Han (Chinese), kana (Japanese), CJK symbols/punctuation,
|
||||
// and their full-width/half-width compatibility forms. Korean Hangul is
|
||||
// deliberately absent — Korean uses eojeol spaces, so it is joined like any
|
||||
// space-delimited script. Boundaries compare single UTF-16 code units, so
|
||||
// supplementary-plane Han (CJK Ext B+) never matches; fine for ASR output.
|
||||
const NO_SPACE_SCRIPT_BOUNDARY =
|
||||
/[\u3000-\u303f\u3040-\u30ff\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uff9f]/;
|
||||
|
||||
// These leading marks attach to the preceding text. Keep the rule directional:
|
||||
// a sentence-ending mark on the left still needs a space before the next word.
|
||||
const NO_SPACE_BEFORE_PUNCTUATION = /[,.;:!?%…)\]}]/;
|
||||
|
||||
function joinTranscriptSegments(left: string, right: string): string {
|
||||
if (!left) {
|
||||
return right;
|
||||
}
|
||||
if (!right) {
|
||||
return left;
|
||||
}
|
||||
const lastChar = left.trimEnd().slice(-1);
|
||||
const firstChar = right.trimStart().slice(0, 1);
|
||||
// Space-delimited scripts need an explicit separator when a provider does
|
||||
// not pad its results (WebKit trims final transcripts), otherwise the last
|
||||
// finalized word glues onto the next segment. No-space scripts (Chinese,
|
||||
// Japanese) keep the plain concatenation they always had.
|
||||
if (
|
||||
!lastChar ||
|
||||
!firstChar ||
|
||||
NO_SPACE_SCRIPT_BOUNDARY.test(lastChar) ||
|
||||
NO_SPACE_SCRIPT_BOUNDARY.test(firstChar) ||
|
||||
NO_SPACE_BEFORE_PUNCTUATION.test(firstChar)
|
||||
) {
|
||||
return `${left}${right}`;
|
||||
}
|
||||
return `${left} ${right}`;
|
||||
}
|
||||
|
||||
export function readSpeechRecognitionTranscript(
|
||||
results: SpeechRecognitionResultListLike,
|
||||
): { finalText: string; interimText: string; text: string } {
|
||||
const finalParts: string[] = [];
|
||||
const interimParts: string[] = [];
|
||||
|
||||
for (const result of Array.from(
|
||||
{ length: results.length },
|
||||
(_, index) => results[index],
|
||||
)) {
|
||||
const transcript = result?.[0]?.transcript ?? "";
|
||||
if (result?.isFinal) {
|
||||
finalParts.push(transcript);
|
||||
} else {
|
||||
interimParts.push(transcript);
|
||||
}
|
||||
}
|
||||
|
||||
let finalText = "";
|
||||
for (const part of finalParts) {
|
||||
finalText = joinTranscriptSegments(finalText, part);
|
||||
}
|
||||
let interimText = "";
|
||||
for (const part of interimParts) {
|
||||
interimText = joinTranscriptSegments(interimText, part);
|
||||
}
|
||||
let text = "";
|
||||
for (const part of [...finalParts, ...interimParts]) {
|
||||
text = joinTranscriptSegments(text, part);
|
||||
}
|
||||
|
||||
return {
|
||||
finalText: normalizeSpeechTranscript(finalText),
|
||||
interimText: normalizeSpeechTranscript(interimText),
|
||||
text: normalizeSpeechTranscript(text),
|
||||
};
|
||||
}
|
||||
|
||||
export function appendSpeechTranscript(baseText: string, transcript: string) {
|
||||
const cleanTranscript = normalizeSpeechTranscript(transcript);
|
||||
if (!cleanTranscript) {
|
||||
return baseText;
|
||||
}
|
||||
|
||||
const cleanBase = baseText.trimEnd();
|
||||
if (!cleanBase) {
|
||||
return cleanTranscript;
|
||||
}
|
||||
|
||||
return `${cleanBase} ${cleanTranscript}`;
|
||||
}
|
||||
|
||||
export function normalizeSpeechTranscript(value: string) {
|
||||
return value.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
export function mapSpeechRecognitionError(
|
||||
error: SpeechRecognitionErrorCode | string | undefined,
|
||||
): SpeechRecognitionErrorKind {
|
||||
switch (error) {
|
||||
case "aborted":
|
||||
return "cancelled";
|
||||
case "audio-capture":
|
||||
return "microphone_unavailable";
|
||||
case "not-allowed":
|
||||
case "service-not-allowed":
|
||||
return "permission_denied";
|
||||
case "language-not-supported":
|
||||
return "unsupported_language";
|
||||
case "network":
|
||||
return "network";
|
||||
case "no-speech":
|
||||
return "no_speech";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBCP47Locale(locale: string): string {
|
||||
const trimmed = locale.trim();
|
||||
if (!trimmed) {
|
||||
return DEFAULT_SPEECH_RECOGNITION_LANGUAGE;
|
||||
}
|
||||
try {
|
||||
return Intl.getCanonicalLocales(trimmed)[0] ?? trimmed;
|
||||
} catch {
|
||||
return DEFAULT_SPEECH_RECOGNITION_LANGUAGE;
|
||||
}
|
||||
}
|
||||
209
frontend/src/core/voice-input/use-voice-input.ts
Normal file
209
frontend/src/core/voice-input/use-voice-input.ts
Normal file
@ -0,0 +1,209 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import {
|
||||
transcribeAudio,
|
||||
VoiceInputError,
|
||||
type VoiceInputErrorCode,
|
||||
} from "./api";
|
||||
|
||||
export type VoiceInputPhase = "idle" | "starting" | "listening" | "stopping";
|
||||
type Session = {
|
||||
controller: AbortController;
|
||||
stream?: MediaStream;
|
||||
recorder?: MediaRecorder;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
chunks: Blob[];
|
||||
bytes: number;
|
||||
};
|
||||
|
||||
function recordingMimeType(): string | null {
|
||||
if (typeof MediaRecorder === "undefined") return null;
|
||||
return (
|
||||
["audio/webm;codecs=opus", "audio/mp4", "audio/ogg;codecs=opus"].find(
|
||||
(mime) => MediaRecorder.isTypeSupported(mime),
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function releaseMicrophone(session: Session) {
|
||||
session.stream?.getTracks().forEach((track) => track.stop());
|
||||
session.stream = undefined;
|
||||
clearTimeout(session.timer);
|
||||
}
|
||||
|
||||
/** One recording and one transcription, owned by the current composer scope. */
|
||||
export function useVoiceInput({
|
||||
enabled,
|
||||
scope,
|
||||
maxBytes,
|
||||
maxSeconds,
|
||||
onTranscript,
|
||||
onError,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
scope: string;
|
||||
maxBytes: number;
|
||||
maxSeconds: number;
|
||||
onTranscript: (text: string) => void;
|
||||
onError: (code: VoiceInputErrorCode) => void;
|
||||
}) {
|
||||
const [phase, setPhase] = useState<VoiceInputPhase>("idle");
|
||||
const [supported, setSupported] = useState(false);
|
||||
const sessionRef = useRef<Session | null>(null);
|
||||
const callbacks = useRef({ onTranscript, onError });
|
||||
useLayoutEffect(() => {
|
||||
callbacks.current = { onTranscript, onError };
|
||||
}, [onTranscript, onError]);
|
||||
useEffect(() => {
|
||||
setSupported(
|
||||
window.isSecureContext &&
|
||||
!!navigator.mediaDevices?.getUserMedia &&
|
||||
recordingMimeType() !== null,
|
||||
);
|
||||
}, []);
|
||||
|
||||
const abort = useCallback(() => {
|
||||
const session = sessionRef.current;
|
||||
sessionRef.current = null;
|
||||
if (session) {
|
||||
session.controller.abort();
|
||||
const recorder = session.recorder;
|
||||
if (recorder) {
|
||||
recorder.ondataavailable = null;
|
||||
recorder.onstop = null;
|
||||
recorder.onerror = null;
|
||||
if (recorder.state !== "inactive") {
|
||||
try {
|
||||
recorder.stop();
|
||||
} catch {
|
||||
/* Already stopped by the browser. */
|
||||
}
|
||||
}
|
||||
}
|
||||
releaseMicrophone(session);
|
||||
session.chunks = [];
|
||||
}
|
||||
setPhase("idle");
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!enabled) abort();
|
||||
return abort;
|
||||
}, [abort, enabled, scope]);
|
||||
|
||||
const fail = useCallback(
|
||||
(session: Session, code: VoiceInputErrorCode) => {
|
||||
if (sessionRef.current !== session) return;
|
||||
abort();
|
||||
callbacks.current.onError(code);
|
||||
},
|
||||
[abort],
|
||||
);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
const session = sessionRef.current;
|
||||
if (!session) return;
|
||||
if (!session.recorder) {
|
||||
abort();
|
||||
return;
|
||||
}
|
||||
if (session.recorder.state === "inactive") return;
|
||||
setPhase("stopping");
|
||||
clearTimeout(session.timer);
|
||||
// A recorder that never dispatches stop must still release the device.
|
||||
session.timer = setTimeout(() => fail(session, "failed"), 5000);
|
||||
try {
|
||||
session.recorder.stop();
|
||||
} catch {
|
||||
fail(session, "failed");
|
||||
}
|
||||
}, [abort, fail]);
|
||||
|
||||
const start = useCallback(async () => {
|
||||
if (!enabled || sessionRef.current) return;
|
||||
const mimeType = recordingMimeType();
|
||||
if (!supported || !mimeType) {
|
||||
callbacks.current.onError("unsupported");
|
||||
return;
|
||||
}
|
||||
const session: Session = {
|
||||
controller: new AbortController(),
|
||||
chunks: [],
|
||||
bytes: 0,
|
||||
};
|
||||
sessionRef.current = session;
|
||||
setPhase("starting");
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
// Permission can resolve after Cancel, navigation or account switching.
|
||||
if (sessionRef.current !== session) {
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
return;
|
||||
}
|
||||
session.stream = stream;
|
||||
const recorder = new MediaRecorder(stream, {
|
||||
mimeType,
|
||||
audioBitsPerSecond: 64000,
|
||||
});
|
||||
session.recorder = recorder;
|
||||
recorder.ondataavailable = (event) => {
|
||||
if (sessionRef.current !== session || !event.data.size) return;
|
||||
session.bytes += event.data.size;
|
||||
if (session.bytes > maxBytes) {
|
||||
fail(session, "too_large");
|
||||
return;
|
||||
}
|
||||
session.chunks.push(event.data);
|
||||
};
|
||||
recorder.onerror = () => fail(session, "failed");
|
||||
recorder.onstop = () => {
|
||||
if (sessionRef.current !== session) return;
|
||||
releaseMicrophone(session);
|
||||
setPhase("stopping");
|
||||
const audio = new Blob(session.chunks, {
|
||||
type: recorder.mimeType || mimeType,
|
||||
});
|
||||
session.chunks = [];
|
||||
if (!audio.size) {
|
||||
fail(session, "no_speech");
|
||||
return;
|
||||
}
|
||||
// Bound the whole HTTP exchange as well as the backend's provider call.
|
||||
session.timer = setTimeout(() => fail(session, "failed"), 155000);
|
||||
void transcribeAudio(audio, session.controller.signal)
|
||||
.then((text) => {
|
||||
if (sessionRef.current !== session) return;
|
||||
abort();
|
||||
callbacks.current.onTranscript(text);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
fail(
|
||||
session,
|
||||
error instanceof VoiceInputError ? error.code : "failed",
|
||||
);
|
||||
});
|
||||
};
|
||||
recorder.start(250);
|
||||
setPhase("listening");
|
||||
session.timer = setTimeout(stop, maxSeconds * 1000);
|
||||
} catch (error) {
|
||||
const name = error instanceof Error ? error.name : "";
|
||||
fail(
|
||||
session,
|
||||
name === "NotAllowedError"
|
||||
? "permission_denied"
|
||||
: name === "NotFoundError" || name === "NotReadableError"
|
||||
? "microphone_unavailable"
|
||||
: "failed",
|
||||
);
|
||||
}
|
||||
}, [abort, enabled, fail, maxBytes, maxSeconds, stop, supported]);
|
||||
|
||||
return { phase, supported, start, stop, abort };
|
||||
}
|
||||
270
frontend/tests/e2e/voice-input.spec.ts
Normal file
270
frontend/tests/e2e/voice-input.spec.ts
Normal file
@ -0,0 +1,270 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
|
||||
import { MOCK_THREAD_ID, mockLangGraphAPI } from "./utils/mock-api";
|
||||
|
||||
// Real Chromium MediaRecorder, with a synthetic microphone. Only the remote
|
||||
// feature/transcription endpoints are replaced; no speech service is required.
|
||||
test.use({
|
||||
launchOptions: {
|
||||
args: [
|
||||
"--use-fake-ui-for-media-stream",
|
||||
"--use-fake-device-for-media-stream",
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
async function configure(
|
||||
page: Page,
|
||||
voice: unknown = {
|
||||
enabled: true,
|
||||
max_audio_bytes: 10485760,
|
||||
max_duration_seconds: 120,
|
||||
},
|
||||
) {
|
||||
await page.route("**/api/features", (route) =>
|
||||
route.fulfill({
|
||||
json: {
|
||||
agents_api: { enabled: true },
|
||||
browser_control: { enabled: false },
|
||||
mcp_tasks: { enabled: false },
|
||||
knowledge_base: { scope_selection_enabled: false },
|
||||
voice_input: voice,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function startRecording(page: Page) {
|
||||
await page.getByTestId("voice-input-button").click();
|
||||
await expect(page.getByTestId("voice-input-status")).toContainText(
|
||||
"Recording",
|
||||
);
|
||||
// Wait for a real encoded chunk, not just an empty MediaRecorder header.
|
||||
await page.waitForTimeout(400);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
mockLangGraphAPI(page, {
|
||||
threads: [{ thread_id: MOCK_THREAD_ID, title: "Another conversation" }],
|
||||
});
|
||||
});
|
||||
|
||||
for (const [name, feature] of [
|
||||
["missing", undefined],
|
||||
["disabled", { enabled: false }],
|
||||
["invalid", { enabled: true }],
|
||||
] as const) {
|
||||
test(`${name} configuration hides the microphone and disables its shortcut`, async ({
|
||||
page,
|
||||
}) => {
|
||||
// Explicit undefined would select configure's default.
|
||||
await configure(page, feature ?? null);
|
||||
let uploads = 0;
|
||||
page.on("request", (r) => {
|
||||
if (r.url().endsWith("/voice-input/transcribe")) uploads++;
|
||||
});
|
||||
await page.goto("/workspace/chats/new");
|
||||
const input = page.getByPlaceholder(/how can i assist you/i);
|
||||
await input.fill("Draft");
|
||||
await input.press("Control+m");
|
||||
await expect(page.getByTestId("voice-input-button")).toHaveCount(0);
|
||||
await expect(page.getByTestId("voice-input-status")).toHaveCount(0);
|
||||
await expect(input).toHaveValue("Draft");
|
||||
expect(uploads).toBe(0);
|
||||
});
|
||||
}
|
||||
|
||||
test("feature request failure hides the microphone", async ({ page }) => {
|
||||
await page.route("**/api/features", (route) =>
|
||||
route.fulfill({ status: 503, json: {} }),
|
||||
);
|
||||
await page.goto("/workspace/chats/new");
|
||||
await expect(page.getByPlaceholder(/how can i assist you/i)).toBeVisible();
|
||||
await expect(page.getByTestId("voice-input-button")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("records beside Send, uploads real audio once, then polishes the transcript", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
await configure(page);
|
||||
let uploads = 0;
|
||||
let audioBytes = 0;
|
||||
let audioType = "";
|
||||
let polishedText: string | undefined;
|
||||
await page.route("**/api/voice-input/transcribe", (route) => {
|
||||
uploads++;
|
||||
audioBytes = route.request().postDataBuffer()?.length ?? 0;
|
||||
audioType = route.request().headers()["content-type"] ?? "";
|
||||
return route.fulfill({ json: { text: "research energy storage" } });
|
||||
});
|
||||
await page.route("**/api/input-polish", (route) => {
|
||||
polishedText = (route.request().postDataJSON() as { text: string }).text;
|
||||
return route.fulfill({
|
||||
json: {
|
||||
rewritten_text:
|
||||
"Please research energy storage and provide a structured report.",
|
||||
changed: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
await page.goto("/workspace/chats/new");
|
||||
const input = page.getByPlaceholder(/how can i assist you/i);
|
||||
await input.fill("Task:");
|
||||
await expect(page.getByTestId("voice-input-button")).toBeEnabled();
|
||||
await page.screenshot({ path: testInfo.outputPath("voice-input-entry.png") });
|
||||
await testInfo.attach("Configured voice input beside Send", {
|
||||
path: testInfo.outputPath("voice-input-entry.png"),
|
||||
contentType: "image/png",
|
||||
});
|
||||
await startRecording(page);
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath("voice-input-recording.png"),
|
||||
});
|
||||
await testInfo.attach("Recording status and cancel", {
|
||||
path: testInfo.outputPath("voice-input-recording.png"),
|
||||
contentType: "image/png",
|
||||
});
|
||||
await expect(input).toHaveValue("Task:");
|
||||
await expect(page.getByTestId("polish-input-button")).toBeDisabled();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Submit", exact: true }),
|
||||
).toBeDisabled();
|
||||
await input.press("Enter");
|
||||
await expect(input).toHaveValue("Task: research energy storage");
|
||||
expect(uploads).toBe(1);
|
||||
expect(audioBytes).toBeGreaterThan(100);
|
||||
expect(audioType).toContain("audio/webm");
|
||||
await page.getByTestId("polish-input-button").click();
|
||||
await expect.poll(() => polishedText).toBe("Task: research energy storage");
|
||||
await expect(input).toHaveValue(
|
||||
"Please research energy storage and provide a structured report.",
|
||||
);
|
||||
await page.getByTestId("polish-input-button").click();
|
||||
await expect(input).toHaveValue("Task: research energy storage");
|
||||
const micBox = (await page.getByTestId("voice-input-button").boundingBox())!;
|
||||
const sendBox = (await page
|
||||
.getByRole("button", { name: "Submit", exact: true })
|
||||
.boundingBox())!;
|
||||
expect(micBox.x + micBox.width).toBeLessThanOrEqual(sendBox.x);
|
||||
expect(sendBox.x - micBox.x).toBeLessThan(65);
|
||||
});
|
||||
|
||||
test("cancel releases the microphone and preserves the draft without upload", async ({
|
||||
page,
|
||||
}) => {
|
||||
await configure(page);
|
||||
let uploads = 0;
|
||||
page.on("request", (r) => {
|
||||
if (r.url().endsWith("/voice-input/transcribe")) uploads++;
|
||||
});
|
||||
await page.goto("/workspace/chats/new");
|
||||
const input = page.getByPlaceholder(/how can i assist you/i);
|
||||
await input.fill("Keep my draft");
|
||||
await startRecording(page);
|
||||
await input.press("Escape");
|
||||
await expect(page.getByTestId("voice-input-status")).toBeHidden();
|
||||
await expect(input).toHaveValue("Keep my draft");
|
||||
expect(uploads).toBe(0);
|
||||
await startRecording(page);
|
||||
await page.getByRole("button", { name: "Cancel voice input" }).click();
|
||||
await expect(page.getByTestId("voice-input-status")).toBeHidden();
|
||||
});
|
||||
|
||||
test("transcription failure preserves the draft and allows retry", async ({
|
||||
page,
|
||||
}) => {
|
||||
await configure(page);
|
||||
await page.route("**/api/voice-input/transcribe", (route) =>
|
||||
route.fulfill({ status: 502, json: { detail: "unavailable" } }),
|
||||
);
|
||||
await page.goto("/workspace/chats/new");
|
||||
const input = page.getByPlaceholder(/how can i assist you/i);
|
||||
await input.fill("Original");
|
||||
await startRecording(page);
|
||||
await input.press("Control+m");
|
||||
await expect(
|
||||
page.getByText("Voice input failed. Please try again."),
|
||||
).toBeVisible();
|
||||
await expect(input).toHaveValue("Original");
|
||||
await expect(page.getByTestId("voice-input-status")).toBeHidden();
|
||||
await startRecording(page);
|
||||
});
|
||||
|
||||
for (const action of ["edit", "navigate"] as const) {
|
||||
test(`${action} while transcribing ignores the late response`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await configure(page);
|
||||
let finish!: () => void;
|
||||
const pending = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
await page.route("**/api/voice-input/transcribe", async (route) => {
|
||||
await pending;
|
||||
await route
|
||||
.fulfill({ json: { text: "stale result" } })
|
||||
.catch(() => undefined);
|
||||
});
|
||||
await page.goto("/workspace/chats/new");
|
||||
const input = page.getByPlaceholder(/how can i assist you/i);
|
||||
await input.fill("Draft");
|
||||
await startRecording(page);
|
||||
await input.press("Enter");
|
||||
await expect(page.getByTestId("voice-input-status")).toContainText(
|
||||
"Transcribing",
|
||||
);
|
||||
if (action === "edit") await input.fill("My edited draft");
|
||||
else {
|
||||
await page
|
||||
.getByRole("link", { name: "Another conversation", exact: true })
|
||||
.click();
|
||||
await expect(page).toHaveURL(new RegExp(`/chats/${MOCK_THREAD_ID}$`));
|
||||
}
|
||||
finish();
|
||||
await expect(page.getByTestId("voice-input-status")).toBeHidden();
|
||||
await expect(input).toHaveValue(action === "edit" ? "My edited draft" : "");
|
||||
});
|
||||
}
|
||||
|
||||
test("recording stops automatically at the configured duration", async ({
|
||||
page,
|
||||
}) => {
|
||||
await configure(page, {
|
||||
enabled: true,
|
||||
max_audio_bytes: 10485760,
|
||||
max_duration_seconds: 1,
|
||||
});
|
||||
await page.route("**/api/voice-input/transcribe", (route) =>
|
||||
route.fulfill({ json: { text: "Automatic stop" } }),
|
||||
);
|
||||
await page.goto("/workspace/chats/new");
|
||||
await startRecording(page);
|
||||
await expect(page.getByPlaceholder(/how can i assist you/i)).toHaveValue(
|
||||
"Automatic stop",
|
||||
);
|
||||
});
|
||||
|
||||
test("mobile recording and cancel remain accessible in both themes", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
await configure(page);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto("/workspace/chats/new");
|
||||
expect(
|
||||
(await page.getByTestId("voice-input-button").boundingBox())!.height,
|
||||
).toBeGreaterThanOrEqual(44);
|
||||
await startRecording(page);
|
||||
for (const theme of ["light", "dark"] as const) {
|
||||
await page.emulateMedia({ colorScheme: theme });
|
||||
await expect(page.locator("html")).toHaveCSS("color-scheme", theme);
|
||||
const cancel = page.getByRole("button", { name: "Cancel voice input" });
|
||||
expect((await cancel.boundingBox())!.height).toBeGreaterThanOrEqual(44);
|
||||
expect(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth),
|
||||
).toBeLessThanOrEqual(390);
|
||||
await page.screenshot({ path: testInfo.outputPath(`voice-${theme}.png`) });
|
||||
}
|
||||
await page.getByRole("button", { name: "Cancel voice input" }).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByTestId("voice-input-status")).toBeHidden();
|
||||
});
|
||||
@ -35,7 +35,9 @@ describe("fetchAgentsApiEnabled", () => {
|
||||
jsonResponse(200, { agents_api: { enabled: true } }),
|
||||
);
|
||||
await expect(fetchAgentsApiEnabled()).resolves.toBe(true);
|
||||
expect(mockedFetch).toHaveBeenCalledWith("/api/features");
|
||||
expect(mockedFetch).toHaveBeenCalledWith("/api/features", {
|
||||
signal: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test("returns false when backend reports agents_api disabled", async () => {
|
||||
@ -60,7 +62,9 @@ describe("fetchBrowserControlEnabled", () => {
|
||||
}),
|
||||
);
|
||||
await expect(fetchBrowserControlEnabled()).resolves.toBe(true);
|
||||
expect(mockedFetch).toHaveBeenCalledWith("/api/features");
|
||||
expect(mockedFetch).toHaveBeenCalledWith("/api/features", {
|
||||
signal: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test("returns false when browser_control is disabled or omitted", async () => {
|
||||
@ -93,7 +97,9 @@ describe("fetchMcpTasksEnabled", () => {
|
||||
}),
|
||||
);
|
||||
await expect(fetchMcpTasksEnabled()).resolves.toBe(true);
|
||||
expect(mockedFetch).toHaveBeenCalledWith("/api/features");
|
||||
expect(mockedFetch).toHaveBeenCalledWith("/api/features", {
|
||||
signal: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test("returns false when mcp_tasks is disabled or omitted", async () => {
|
||||
|
||||
53
frontend/tests/unit/core/voice-input/api.test.ts
Normal file
53
frontend/tests/unit/core/voice-input/api.test.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import { afterEach, expect, rs, test } from "@rstest/core";
|
||||
|
||||
rs.mock("@/core/config", () => ({ getBackendBaseURL: () => "" }));
|
||||
rs.mock("@/core/static-mode", () => ({ isStaticWebsiteOnly: () => false }));
|
||||
import { appendVoiceTranscript, transcribeAudio } from "@/core/voice-input/api";
|
||||
|
||||
afterEach(() => {
|
||||
rs.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("keeps the draft when the transcript is empty and preserves transcript line breaks", () => {
|
||||
expect(appendVoiceTranscript("Draft ", " ")).toBe("Draft ");
|
||||
expect(appendVoiceTranscript("Task: ", " first\nsecond ")).toBe(
|
||||
"Task: first\nsecond",
|
||||
);
|
||||
expect(appendVoiceTranscript("", " 转写文本 ")).toBe("转写文本");
|
||||
});
|
||||
|
||||
test("sends the encoded blob with session credentials and caller cancellation", async () => {
|
||||
const fetcher = rs
|
||||
.fn()
|
||||
.mockResolvedValue(new Response(JSON.stringify({ text: " hello " })));
|
||||
rs.stubGlobal("fetch", fetcher);
|
||||
const blob = new Blob(["audio"], { type: "audio/webm" });
|
||||
const signal = new AbortController().signal;
|
||||
expect(await transcribeAudio(blob, signal)).toBe("hello");
|
||||
expect(fetcher).toHaveBeenCalledWith(
|
||||
"/api/voice-input/transcribe",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: blob,
|
||||
signal,
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
for (const [status, code] of [
|
||||
[404, "unavailable"],
|
||||
[413, "too_large"],
|
||||
[422, "no_speech"],
|
||||
[502, "failed"],
|
||||
] as const) {
|
||||
test(`maps HTTP ${status} to safe UI error`, async () => {
|
||||
rs.stubGlobal(
|
||||
"fetch",
|
||||
rs.fn().mockResolvedValue(new Response("provider details", { status })),
|
||||
);
|
||||
await expect(
|
||||
transcribeAudio(new Blob(), new AbortController().signal),
|
||||
).rejects.toMatchObject({ code });
|
||||
});
|
||||
}
|
||||
@ -1,311 +0,0 @@
|
||||
import { describe, expect, it } from "@rstest/core";
|
||||
|
||||
import {
|
||||
appendSpeechTranscript,
|
||||
getSpeechRecognitionConstructor,
|
||||
getSpeechRecognitionLanguage,
|
||||
mapSpeechRecognitionError,
|
||||
readSpeechRecognitionTranscript,
|
||||
shouldRestartSpeechRecognition,
|
||||
type SpeechRecognitionConstructor,
|
||||
} from "@/core/voice-input/speech-recognition";
|
||||
|
||||
describe("speech recognition helpers", () => {
|
||||
it("prefers the standard constructor and falls back to webkit", () => {
|
||||
const standard = makeSpeechRecognitionConstructor();
|
||||
const webkit = makeSpeechRecognitionConstructor();
|
||||
|
||||
expect(
|
||||
getSpeechRecognitionConstructor({
|
||||
SpeechRecognition: standard as unknown as SpeechRecognitionConstructor,
|
||||
webkitSpeechRecognition:
|
||||
webkit as unknown as SpeechRecognitionConstructor,
|
||||
}),
|
||||
).toBe(standard);
|
||||
expect(
|
||||
getSpeechRecognitionConstructor({
|
||||
webkitSpeechRecognition:
|
||||
webkit as unknown as SpeechRecognitionConstructor,
|
||||
}),
|
||||
).toBe(webkit);
|
||||
expect(getSpeechRecognitionConstructor({})).toBeNull();
|
||||
});
|
||||
|
||||
it("maps DeerFlow locales to browser recognition locales", () => {
|
||||
expect(getSpeechRecognitionLanguage("zh-CN")).toBe("zh-CN");
|
||||
expect(getSpeechRecognitionLanguage("zh-Hans")).toBe("zh-CN");
|
||||
expect(getSpeechRecognitionLanguage("en-US")).toBe("en-US");
|
||||
expect(getSpeechRecognitionLanguage("en-GB")).toBe("en-GB");
|
||||
expect(getSpeechRecognitionLanguage("fr-FR")).toBe("fr-FR");
|
||||
expect(getSpeechRecognitionLanguage("ja-JP")).toBe("ja-JP");
|
||||
expect(getSpeechRecognitionLanguage("xx-YY")).toBe("en-US");
|
||||
expect(getSpeechRecognitionLanguage("not a locale")).toBe("en-US");
|
||||
});
|
||||
|
||||
it("combines final and interim transcripts with whitespace cleanup", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 3,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: " hello " } },
|
||||
1: { isFinal: true, length: 1, 0: { transcript: " world" } },
|
||||
2: { isFinal: false, length: 1, 0: { transcript: " again " } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "hello world",
|
||||
interimText: "again",
|
||||
text: "hello world again",
|
||||
});
|
||||
});
|
||||
|
||||
it("separates unpadded final and interim segments", () => {
|
||||
// WebKit-style providers trim final transcripts; without an explicit
|
||||
// separator the finalized text glues onto the interim hypothesis.
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "hello world" } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "today is" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "hello world",
|
||||
interimText: "today is",
|
||||
text: "hello world today is",
|
||||
});
|
||||
});
|
||||
|
||||
it("separates consecutive unpadded final segments", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "hello" } },
|
||||
1: { isFinal: true, length: 1, 0: { transcript: "world" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "hello world",
|
||||
interimText: "",
|
||||
text: "hello world",
|
||||
});
|
||||
});
|
||||
|
||||
it("adds no separator when the provider already emitted boundary space", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "hello world " } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "today" } },
|
||||
}).text,
|
||||
).toBe("hello world today");
|
||||
});
|
||||
|
||||
it("keeps CJK segments glued when the provider emits no spaces", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "你好世界" } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "今天" } },
|
||||
}).text,
|
||||
).toBe("你好世界今天");
|
||||
});
|
||||
|
||||
it("separates consecutive trimmed finals accumulated over a session", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 3,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "hello" } },
|
||||
1: { isFinal: true, length: 1, 0: { transcript: "world" } },
|
||||
2: { isFinal: false, length: 1, 0: { transcript: "today" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "hello world",
|
||||
interimText: "today",
|
||||
text: "hello world today",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["cet été", "cafe\u0301"])(
|
||||
"separates accented Latin words after %s",
|
||||
(finalText) => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: finalText } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "demain" } },
|
||||
}).text,
|
||||
).toBe(`${finalText} demain`);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps digit and symbol boundaries glued", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "up to 50" } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "%" } },
|
||||
}).text,
|
||||
).toBe("up to 50%");
|
||||
});
|
||||
|
||||
it("attaches leading punctuation across final and interim segments", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 4,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "done" } },
|
||||
1: { isFinal: true, length: 1, 0: { transcript: ", maybe" } },
|
||||
2: { isFinal: false, length: 1, 0: { transcript: "next" } },
|
||||
3: { isFinal: false, length: 1, 0: { transcript: ", please" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "done, maybe",
|
||||
interimText: "next, please",
|
||||
text: "done, maybe next, please",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Done.", "Next", "Done. Next"],
|
||||
["Hello,", "world", "Hello, world"],
|
||||
["she said", '"hello"', 'she said "hello"'],
|
||||
['"hello"', "again", '"hello" again'],
|
||||
])("separates phrases at %s / %s", (left, right, text) => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: left } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: right } },
|
||||
}).text,
|
||||
).toBe(text);
|
||||
});
|
||||
|
||||
it("preserves separation across whitespace-only final segments", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 3,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "hello" } },
|
||||
1: { isFinal: true, length: 1, 0: { transcript: " " } },
|
||||
2: { isFinal: true, length: 1, 0: { transcript: "world" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "hello world",
|
||||
interimText: "",
|
||||
text: "hello world",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps no-space scripts concatenated without inserting separators", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 3,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "你好" } },
|
||||
1: { isFinal: true, length: 1, 0: { transcript: "世界" } },
|
||||
2: { isFinal: false, length: 1, 0: { transcript: "早上好" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "你好世界",
|
||||
interimText: "早上好",
|
||||
text: "你好世界早上好",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps mixed-script boundaries concatenated", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "你好" } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "hello" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "你好",
|
||||
interimText: "hello",
|
||||
text: "你好hello",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps CJK clause-final punctuation boundaries concatenated", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "こんにちは、" } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "iPhone" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "こんにちは、",
|
||||
interimText: "iPhone",
|
||||
text: "こんにちは、iPhone",
|
||||
});
|
||||
});
|
||||
|
||||
it("joins Korean segments with a space like other space-delimited scripts", () => {
|
||||
expect(
|
||||
readSpeechRecognitionTranscript({
|
||||
length: 2,
|
||||
0: { isFinal: true, length: 1, 0: { transcript: "안녕" } },
|
||||
1: { isFinal: false, length: 1, 0: { transcript: "하세요" } },
|
||||
}),
|
||||
).toEqual({
|
||||
finalText: "안녕",
|
||||
interimText: "하세요",
|
||||
text: "안녕 하세요",
|
||||
});
|
||||
});
|
||||
|
||||
it("appends transcript to an existing draft without duplicating whitespace", () => {
|
||||
expect(appendSpeechTranscript("", " hello world ")).toBe("hello world");
|
||||
expect(appendSpeechTranscript("Draft", "voice text")).toBe(
|
||||
"Draft voice text",
|
||||
);
|
||||
expect(appendSpeechTranscript("Draft\n", "voice text")).toBe(
|
||||
"Draft voice text",
|
||||
);
|
||||
expect(appendSpeechTranscript("Draft", " ")).toBe("Draft");
|
||||
});
|
||||
|
||||
it("normalizes browser speech recognition errors", () => {
|
||||
expect(mapSpeechRecognitionError("not-allowed")).toBe("permission_denied");
|
||||
expect(mapSpeechRecognitionError("service-not-allowed")).toBe(
|
||||
"permission_denied",
|
||||
);
|
||||
expect(mapSpeechRecognitionError("audio-capture")).toBe(
|
||||
"microphone_unavailable",
|
||||
);
|
||||
expect(mapSpeechRecognitionError("language-not-supported")).toBe(
|
||||
"unsupported_language",
|
||||
);
|
||||
expect(mapSpeechRecognitionError("network")).toBe("network");
|
||||
expect(mapSpeechRecognitionError("no-speech")).toBe("no_speech");
|
||||
expect(mapSpeechRecognitionError("aborted")).toBe("cancelled");
|
||||
expect(mapSpeechRecognitionError("bad-grammar")).toBe("unknown");
|
||||
});
|
||||
|
||||
it("restarts only after browser auto-end conditions", () => {
|
||||
expect(shouldRestartSpeechRecognition(null)).toBe(true);
|
||||
expect(shouldRestartSpeechRecognition("no_speech")).toBe(true);
|
||||
expect(shouldRestartSpeechRecognition("cancelled")).toBe(false);
|
||||
expect(shouldRestartSpeechRecognition("permission_denied")).toBe(false);
|
||||
expect(shouldRestartSpeechRecognition("network")).toBe(false);
|
||||
expect(shouldRestartSpeechRecognition("unknown")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function makeSpeechRecognitionConstructor(): SpeechRecognitionConstructor {
|
||||
return class {
|
||||
continuous = false;
|
||||
interimResults = false;
|
||||
lang = "";
|
||||
maxAlternatives = 1;
|
||||
onend = null;
|
||||
onerror = null;
|
||||
onresult = null;
|
||||
|
||||
start() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
stop() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
abort() {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
192
frontend/tests/unit/core/voice-input/use-voice-input.dom.test.ts
Normal file
192
frontend/tests/unit/core/voice-input/use-voice-input.dom.test.ts
Normal file
@ -0,0 +1,192 @@
|
||||
import { afterEach, beforeEach, expect, rs, test } from "@rstest/core";
|
||||
import { act, cleanup, renderHook } from "@testing-library/react";
|
||||
|
||||
const api = rs.hoisted(() => ({ transcribeAudio: rs.fn() }));
|
||||
rs.mock("@/core/voice-input/api", () => ({
|
||||
transcribeAudio: api.transcribeAudio,
|
||||
VoiceInputError: class extends Error {
|
||||
code = "failed";
|
||||
},
|
||||
}));
|
||||
import { useVoiceInput } from "@/core/voice-input/use-voice-input";
|
||||
|
||||
class Recorder {
|
||||
static current: Recorder;
|
||||
static isTypeSupported = () => true;
|
||||
state = "inactive";
|
||||
mimeType = "audio/webm";
|
||||
onstop: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
ondataavailable: ((event: { data: Blob }) => void) | null = null;
|
||||
constructor() {
|
||||
Recorder.current = this;
|
||||
}
|
||||
start() {
|
||||
this.state = "recording";
|
||||
}
|
||||
stop() {
|
||||
this.state = "inactive";
|
||||
this.ondataavailable?.({ data: new Blob(["audio"]) });
|
||||
this.onstop?.();
|
||||
}
|
||||
}
|
||||
const stopTrack = rs.fn();
|
||||
const stream = {
|
||||
getTracks: () => [{ stop: stopTrack }],
|
||||
} as unknown as MediaStream;
|
||||
const getUserMedia = rs.fn<() => Promise<MediaStream>>();
|
||||
const originalMedia = Object.getOwnPropertyDescriptor(
|
||||
navigator,
|
||||
"mediaDevices",
|
||||
);
|
||||
const originalSecure = Object.getOwnPropertyDescriptor(
|
||||
window,
|
||||
"isSecureContext",
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
stopTrack.mockClear();
|
||||
getUserMedia.mockReset().mockResolvedValue(stream);
|
||||
api.transcribeAudio.mockReset().mockResolvedValue("spoken text");
|
||||
Object.defineProperty(navigator, "mediaDevices", {
|
||||
configurable: true,
|
||||
value: { getUserMedia },
|
||||
});
|
||||
Object.defineProperty(window, "isSecureContext", {
|
||||
configurable: true,
|
||||
value: true,
|
||||
});
|
||||
rs.stubGlobal("MediaRecorder", Recorder);
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
rs.unstubAllGlobals();
|
||||
if (originalMedia)
|
||||
Object.defineProperty(navigator, "mediaDevices", originalMedia);
|
||||
else Reflect.deleteProperty(navigator, "mediaDevices");
|
||||
if (originalSecure)
|
||||
Object.defineProperty(window, "isSecureContext", originalSecure);
|
||||
else Reflect.deleteProperty(window, "isSecureContext");
|
||||
});
|
||||
function setup(enabled = true) {
|
||||
const onTranscript = rs.fn();
|
||||
const onError = rs.fn();
|
||||
const hook = renderHook(
|
||||
({ scope, available }) =>
|
||||
useVoiceInput({
|
||||
enabled: available,
|
||||
scope,
|
||||
maxBytes: 1024,
|
||||
maxSeconds: 120,
|
||||
onTranscript,
|
||||
onError,
|
||||
}),
|
||||
{ initialProps: { scope: "thread-a", available: enabled } },
|
||||
);
|
||||
return { ...hook, onTranscript, onError };
|
||||
}
|
||||
|
||||
test("unconfigured input never requests microphone access", async () => {
|
||||
const { result } = setup(false);
|
||||
await act(() => result.current.start());
|
||||
expect(getUserMedia).not.toHaveBeenCalled();
|
||||
expect(result.current.phase).toBe("idle");
|
||||
});
|
||||
|
||||
test("permission denied permits retry and does not upload", async () => {
|
||||
getUserMedia.mockRejectedValueOnce(
|
||||
new DOMException("denied", "NotAllowedError"),
|
||||
);
|
||||
const { result, onError } = setup();
|
||||
await act(() => result.current.start());
|
||||
expect(onError).toHaveBeenCalledWith("permission_denied");
|
||||
expect(result.current.phase).toBe("idle");
|
||||
expect(api.transcribeAudio).not.toHaveBeenCalled();
|
||||
await act(() => result.current.start());
|
||||
expect(result.current.phase).toBe("listening");
|
||||
});
|
||||
|
||||
test("cancel while permission is pending stops the late stream", async () => {
|
||||
let release!: (stream: MediaStream) => void;
|
||||
getUserMedia.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
release = resolve;
|
||||
}),
|
||||
);
|
||||
const { result, onTranscript } = setup();
|
||||
let started!: Promise<void>;
|
||||
act(() => {
|
||||
started = result.current.start();
|
||||
});
|
||||
expect(result.current.phase).toBe("starting");
|
||||
act(() => result.current.abort());
|
||||
await act(async () => {
|
||||
release(stream);
|
||||
await started;
|
||||
});
|
||||
expect(stopTrack).toHaveBeenCalledTimes(1);
|
||||
expect(api.transcribeAudio).not.toHaveBeenCalled();
|
||||
expect(onTranscript).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("finishing uploads once and releases the microphone before STT completes", async () => {
|
||||
let finish!: (text: string) => void;
|
||||
api.transcribeAudio.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const { result, onTranscript } = setup();
|
||||
await act(() => result.current.start());
|
||||
act(() => {
|
||||
result.current.stop();
|
||||
result.current.stop();
|
||||
});
|
||||
expect(stopTrack).toHaveBeenCalledTimes(1);
|
||||
expect(api.transcribeAudio).toHaveBeenCalledTimes(1);
|
||||
expect(result.current.phase).toBe("stopping");
|
||||
expect(onTranscript).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
finish("final text");
|
||||
});
|
||||
expect(onTranscript).toHaveBeenCalledWith("final text");
|
||||
expect(result.current.phase).toBe("idle");
|
||||
});
|
||||
|
||||
for (const boundary of ["cancel", "thread", "disable", "unmount"] as const) {
|
||||
test(`${boundary} aborts a pending upload and ignores its late response`, async () => {
|
||||
let finish!: (text: string) => void;
|
||||
api.transcribeAudio.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const { result, rerender, unmount, onTranscript, onError } = setup();
|
||||
await act(() => result.current.start());
|
||||
act(() => result.current.stop());
|
||||
const signal = api.transcribeAudio.mock.calls[0]![1] as AbortSignal;
|
||||
if (boundary === "cancel") act(() => result.current.abort());
|
||||
if (boundary === "thread") rerender({ scope: "thread-b", available: true });
|
||||
if (boundary === "disable")
|
||||
rerender({ scope: "thread-a", available: false });
|
||||
if (boundary === "unmount") unmount();
|
||||
expect(signal.aborted).toBe(true);
|
||||
await act(async () => {
|
||||
finish("stale text");
|
||||
});
|
||||
expect(onTranscript).not.toHaveBeenCalled();
|
||||
expect(onError).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
|
||||
test("oversized recording aborts without sending audio", async () => {
|
||||
const { result, onError } = setup();
|
||||
await act(() => result.current.start());
|
||||
act(() =>
|
||||
Recorder.current.ondataavailable?.({ data: new Blob(["a".repeat(1025)]) }),
|
||||
);
|
||||
expect(onError).toHaveBeenCalledWith("too_large");
|
||||
expect(stopTrack).toHaveBeenCalledTimes(1);
|
||||
expect(api.transcribeAudio).not.toHaveBeenCalled();
|
||||
expect(result.current.phase).toBe("idle");
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user