Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(audio): transcribe inbound audio attachments

cyh4e1501e598a1
diff --git a/config/v2_config.py b/config/v2_config.py
index e4775d7ea..42d9ea7e7 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -137,6 +137,16 @@ class GatewayConfig:
last_connected_at: Optional[str] = None
+@dataclass
+class AudioAsrConfig:
+ enabled: bool = False
+ echo_transcript: bool = True
+ timeout_seconds: float = 60.0
+ endpoint_path: str = "/v1/audio/transcriptions"
+ model: str = "qwen3-asr-flash"
+ max_file_bytes: Optional[int] = None
+
+
@dataclass
class RuntimeConfig:
default_cwd: str
@@ -295,6 +305,7 @@ class V2Config:
gateway: Optional[GatewayConfig] = None
ui: UiConfig = field(default_factory=UiConfig)
remote_access: RemoteAccessConfig = field(default_factory=RemoteAccessConfig)
+ audio_asr: AudioAsrConfig = field(default_factory=AudioAsrConfig)
update: UpdateConfig = field(default_factory=UpdateConfig)
ack_mode: str = "typing"
show_duration: bool = False # Show task duration in result messages
@@ -434,6 +445,24 @@ class V2Config:
),
)
+ audio_asr_payload = payload.get("audio_asr") or {}
+ if not isinstance(audio_asr_payload, dict):
+ raise ValueError("Config 'audio_asr' must be an object")
+ audio_asr = AudioAsrConfig(**_filter_dataclass_fields(AudioAsrConfig, audio_asr_payload))
+ try:
+ audio_asr.timeout_seconds = max(0.1, float(audio_asr.timeout_seconds))
+ except (TypeError, ValueError):
+ audio_asr.timeout_seconds = 60.0
+ if audio_asr.max_file_bytes is not None:
+ try:
+ audio_asr.max_file_bytes = max(1, int(audio_asr.max_file_bytes))
+ except (TypeError, ValueError):
+ audio_asr.max_file_bytes = None
+ if not isinstance(audio_asr.endpoint_path, str) or not audio_asr.endpoint_path.startswith("/"):
+ audio_asr.endpoint_path = "/v1/audio/transcriptions"
+ if not isinstance(audio_asr.model, str) or not audio_asr.model.strip():
+ audio_asr.model = "qwen3-asr-flash"
+
update_payload = payload.get("update") or {}
if not isinstance(update_payload, dict):
raise ValueError("Config 'update' must be an object")
@@ -480,6 +509,7 @@ class V2Config:
gateway=gateway,
ui=ui,
remote_access=remote_access,
+ audio_asr=audio_asr,
update=update,
ack_mode=ack_mode,
show_duration=show_duration,
@@ -528,6 +558,7 @@ class V2Config:
"provider": self.remote_access.provider,
"vibe_cloud": self.remote_access.vibe_cloud.__dict__,
},
+ "audio_asr": self.audio_asr.__dict__,
"update": self.update.__dict__,
"ack_mode": self.ack_mode,
"show_duration": self.show_duration,
diff --git a/core/audio_asr.py b/core/audio_asr.py
new file mode 100644
index 000000000..418cfc0a3
--- /dev/null
+++ b/core/audio_asr.py
@@ -0,0 +1,242 @@
+"""Audio transcription helpers for inbound file attachments."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import mimetypes
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Iterable
+from urllib.parse import urljoin
+
+import aiohttp
+
+from config.v2_config import AudioAsrConfig, V2Config
+from modules.im.base import FileAttachment
+
+logger = logging.getLogger(__name__)
+
+_SUPPORTED_AUDIO_EXTENSIONS = {
+ ".aac",
+ ".flac",
+ ".m4a",
+ ".mp3",
+ ".mp4",
+ ".ogg",
+ ".opus",
+ ".wav",
+ ".webm",
+}
+
+
+@dataclass
+class AudioTranscript:
+ attachment_name: str
+ local_path: str
+ text: str
+ duration_ms: int | None = None
+
+
+@dataclass
+class AudioAsrRuntimeConfig:
+ base_url: str
+ instance_id: str
+ device_secret: str
+
+
+class AudioAsrService:
+ """Transcribe downloaded audio attachments through AVIBE ASR."""
+
+ def __init__(self, config: V2Config):
+ self.config = config
+
+ def _get_audio_asr_config(self) -> AudioAsrConfig:
+ return getattr(self.config, "audio_asr", None) or AudioAsrConfig()
+
+ def _runtime_config(self) -> AudioAsrRuntimeConfig | None:
+ cloud = getattr(getattr(self.config, "remote_access", None), "vibe_cloud", None)
+ if not cloud:
+ return None
+ if not getattr(cloud, "enabled", False):
+ return None
+ base_url = (getattr(cloud, "backend_url", "") or "").strip().rstrip("/")
+ instance_id = (getattr(cloud, "instance_id", "") or "").strip()
+ device_secret = (getattr(cloud, "instance_secret", "") or "").strip()
+ if not base_url or not instance_id or not device_secret:
+ return None
+ return AudioAsrRuntimeConfig(base_url=base_url, instance_id=instance_id, device_secret=device_secret)
+
+ def _endpoint_url(self, runtime: AudioAsrRuntimeConfig) -> str:
+ asr_config = self._get_audio_asr_config()
+ endpoint_path = (asr_config.endpoint_path or "/v1/audio/transcriptions").strip()
+ if not endpoint_path.startswith("/"):
+ endpoint_path = f"/{endpoint_path}"
+ return urljoin(f"{runtime.base_url}/", endpoint_path.lstrip("/"))
+
+ def is_available(self) -> bool:
+ asr_config = self._get_audio_asr_config()
+ return bool(asr_config.enabled and self._runtime_config())
+
+ def is_audio_attachment(self, attachment: FileAttachment) -> bool:
+ mimetype = (attachment.mimetype or "").lower()
+ if mimetype.startswith("audio/"):
+ if mimetype == "audio/silk":
+ return False
+ return True
+ name = attachment.name or attachment.local_path or ""
+ suffix = Path(name).suffix.lower()
+ return suffix in _SUPPORTED_AUDIO_EXTENSIONS
+
+ def eligible_attachments(self, attachments: Iterable[FileAttachment]) -> list[FileAttachment]:
+ asr_config = self._get_audio_asr_config()
+ eligible: list[FileAttachment] = []
+ for attachment in attachments:
+ if not attachment.local_path or not self.is_audio_attachment(attachment):
+ continue
+ if asr_config.max_file_bytes is not None and attachment.size and attachment.size > asr_config.max_file_bytes:
+ logger.info(
+ "Skipping audio ASR for %s: file size %s exceeds configured max %s",
+ attachment.name,
+ attachment.size,
+ asr_config.max_file_bytes,
+ )
+ continue
+ eligible.append(attachment)
+ return eligible
+
+ async def transcribe_attachments(self, attachments: list[FileAttachment]) -> list[AudioTranscript]:
+ asr_config = self._get_audio_asr_config()
+ if not asr_config.enabled:
+ return []
+ runtime = self._runtime_config()
+ if not runtime:
+ logger.info("Skipping audio ASR: Vibe Cloud pairing credentials are unavailable")
+ return []
+ eligible = self.eligible_attachments(attachments)
+ if not eligible:
+ return []
+
+ timeout_seconds = max(0.1, float(asr_config.timeout_seconds or 60.0))
+ deadline = time.monotonic() + timeout_seconds
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ tasks = [self._transcribe_one(session, runtime, attachment, deadline) for attachment in eligible]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ transcripts: list[AudioTranscript] = []
+ for result in results:
+ if isinstance(result, AudioTranscript):
+ transcripts.append(result)
+ elif isinstance(result, Exception):
+ logger.warning("Audio ASR skipped after error: %s", result)
+ return transcripts
+
+ async def _transcribe_one(
+ self,
+ session: aiohttp.ClientSession,
+ runtime: AudioAsrRuntimeConfig,
+ attachment: FileAttachment,
+ deadline: float,
+ ) -> AudioTranscript | None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return None
+
+ path = Path(attachment.local_path or "")
+ if not path.is_file():
+ logger.warning("Skipping audio ASR for %s: local file is unavailable", attachment.name)
+ return None
+
+ asr_config = self._get_audio_asr_config()
+ mimetype = attachment.mimetype or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
+ start = time.monotonic()
+ form = aiohttp.FormData()
+ form.add_field("model", asr_config.model)
+ form.add_field("response_format", "json")
+
+ with path.open("rb") as handle:
+ form.add_field(
+ "file",
+ handle,
+ filename=attachment.name or path.name,
+ content_type=mimetype,
+ )
+ try:
+ async with session.post(
+ self._endpoint_url(runtime),
+ data=form,
+ headers={
+ "Accept": "application/json",
+ "User-Agent": "Vibe Remote/dev",
+ "X-Vibe-Instance-Id": runtime.instance_id,
+ "X-Vibe-Device-Secret": runtime.device_secret,
+ },
+ timeout=aiohttp.ClientTimeout(total=max(0.1, remaining)),
+ ) as response:
+ payload: dict[str, Any] = {}
+ try:
+ payload = await response.json(content_type=None)
+ except Exception:
+ text = await response.text()
+ payload = {"error": text[:200]}
+ duration_ms = int((time.monotonic() - start) * 1000)
+ if response.status < 200 or response.status >= 300:
+ logger.warning(
+ "Audio ASR failed for %s: status=%s mimetype=%s duration_ms=%s",
+ attachment.name,
+ response.status,
+ mimetype,
+ duration_ms,
+ )
+ return None
+ except asyncio.TimeoutError:
+ logger.warning("Audio ASR timed out for %s", attachment.name)
+ return None
+ except Exception as exc:
+ logger.warning("Audio ASR request failed for %s: %s", attachment.name, exc)
+ return None
+
+ text = str(payload.get("text") or "").strip()
+ if not text:
+ logger.warning("Audio ASR returned empty transcript for %s", attachment.name)
+ return None
+ return AudioTranscript(
+ attachment_name=attachment.name or path.name,
+ local_path=str(path),
+ text=text,
+ duration_ms=duration_ms,
+ )
+
+
+def format_audio_transcripts_block(transcripts: list[AudioTranscript]) -> str:
+ if not transcripts:
+ return ""
+ lines = ["[Audio Transcripts]"]
+ for transcript in transcripts:
+ name = transcript.attachment_name or Path(transcript.local_path).name
+ text = transcript.text.replace("\r", " ").strip()
+ lines.append(f"- {name}: {text}")
+ return "\n".join(lines)
+
+
+def append_audio_transcripts_to_message(message: str, transcripts: list[AudioTranscript]) -> str:
+ block = format_audio_transcripts_block(transcripts)
+ if not block:
+ return message
+ if not message or not message.strip():
+ return block
+ return f"{message}\n\n{block}"
+
+
+def format_audio_transcript_echo(transcripts: list[AudioTranscript]) -> str:
+ if not transcripts:
+ return ""
+ if len(transcripts) == 1:
+ return f"Voice transcript:\n{transcripts[0].text.strip()}"
+ lines = ["Voice transcripts:"]
+ for transcript in transcripts:
+ name = transcript.attachment_name or Path(transcript.local_path).name
+ lines.append(f"- {name}: {transcript.text.strip()}")
+ return "\n".join(lines)
diff --git a/core/controller.py b/core/controller.py
index 486217868..7a4095bfe 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -23,6 +23,7 @@ from core.handlers import (
MessageHandler,
)
from core.agent_auth_service import AgentAuthService
+from core.audio_asr import AudioAsrService
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.processing_indicator import ProcessingIndicatorService
from core.runtime_commands import RuntimeCommandWatcher
@@ -109,6 +110,7 @@ class Controller:
self.sessions = self.settings_manager.sessions
self.native_session_service = None
self.processing_indicator = ProcessingIndicatorService(self)
+ self.audio_asr_service = AudioAsrService(self.config)
self._migrate_discord_guild_scope_from_config()
# Migrate legacy per-channel language into global config
@@ -198,6 +200,10 @@ class Controller:
self.config.include_time_info = v2_config.include_time_info
self.config.include_user_info = v2_config.include_user_info
self.config.reply_enhancements = v2_config.reply_enhancements
+ self.config.audio_asr = v2_config.audio_asr
+ audio_asr_service = getattr(self, "audio_asr_service", None)
+ if audio_asr_service is not None:
+ audio_asr_service.config = self.config
mutable_platform_attrs = (
"require_mention",
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 1a667369f..e39462d2d 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -4,6 +4,11 @@ import logging
from datetime import datetime
from typing import List, Optional, Tuple
+from core.audio_asr import (
+ AudioTranscript,
+ append_audio_transcripts_to_message,
+ format_audio_transcript_echo,
+)
from modules.agents.base import AgentRequest
from modules.im import MessageContext
from modules.im.base import FileAttachment
@@ -251,6 +256,11 @@ class MessageHandler(BaseHandler):
if processed_files:
logger.info(f"Processed {len(processed_files)} file attachments for message")
+ audio_transcripts = await self._transcribe_audio_attachments(context, processed_files or [])
+ if audio_transcripts:
+ message = append_audio_transcripts_to_message(message, audio_transcripts)
+ await self._echo_audio_transcripts_if_enabled(context, audio_transcripts)
+
message = await self._prepend_message_metadata(context, message, include_user_info=is_human)
message = self._append_attachment_errors(message, attachment_errors)
@@ -302,6 +312,43 @@ class MessageHandler(BaseHandler):
)
return str(e)
+ async def _transcribe_audio_attachments(
+ self,
+ context: MessageContext,
+ files: List[FileAttachment],
+ ) -> List[AudioTranscript]:
+ asr_service = getattr(self.controller, "audio_asr_service", None)
+ if not files or asr_service is None:
+ return []
+ try:
+ return await asr_service.transcribe_attachments(files)
+ except Exception as err:
+ logger.warning(
+ "Audio ASR augmentation failed for channel=%s message=%s: %s",
+ context.channel_id,
+ context.message_id,
+ err,
+ )
+ return []
+
+ async def _echo_audio_transcripts_if_enabled(
+ self,
+ context: MessageContext,
+ transcripts: List[AudioTranscript],
+ ) -> None:
+ if not transcripts:
+ return
+ audio_asr_config = getattr(self.config, "audio_asr", None)
+ if not getattr(audio_asr_config, "echo_transcript", True):
+ return
+ echo = format_audio_transcript_echo(transcripts)
+ if not echo:
+ return
+ try:
+ await self._get_im_client(context).send_message(context, echo)
+ except Exception as err:
+ logger.debug("Failed to echo audio transcript: %s", err, exc_info=True)
+
@staticmethod
def _sanitize_identity(value: str) -> str:
"""Strip control chars and delimiters that could break the [name<id>] format."""
diff --git a/docs/plans/audio-attachment-asr.md b/docs/plans/audio-attachment-asr.md
new file mode 100644
index 000000000..9b7f525e3
--- /dev/null
+++ b/docs/plans/audio-attachment-asr.md
@@ -0,0 +1,410 @@
+# Audio Attachment ASR Plan
+
+## Background
+
+Incoming file attachments are already normalized into `FileAttachment` objects by
+each IM adapter, downloaded by the shared `MessageHandler._process_file_attachments`
+pipeline, and then attached to `AgentRequest.files`. The final `[User Attachments]`
+block is currently rendered inside each agent backend:
+
+- Claude/OpenCode append text file lines in `_prepare_message_with_files`.
+- Codex builds text input plus native `localImage` items for images.
+
+That means the correct insertion point for audio transcription is not a single
+IM adapter or a single agent backend. It should run after attachment download and
+before `AgentRequest` is created, so every platform and backend inherits the same
+behavior.
+
+## Goal
+
+When a user sends an audio file attachment:
+
+1. Download and store the attachment exactly as today.
+2. Start ASR for eligible audio files through the AVIBE backend's OpenAI
+ compatible ASR endpoint.
+3. Wait up to 60 seconds in the normal turn pipeline.
+4. If ASR finishes successfully within the deadline, append the transcription to
+ the user message while still passing the original attachment in
+ `AgentRequest.files`.
+5. If ASR times out or fails, preserve the current behavior: user text plus the
+ existing attachment block only.
+6. Expose the feature as a Web UI switch on the Messaging settings page.
+7. Add a neighboring switch that controls whether successful transcripts are
+ echoed back to the IM user; default echo should be enabled.
+8. Use this feature as the forcing function to reorganize Messaging settings
+ into clear groups instead of adding one more row to the current long panel.
+
+## Non-Goals
+
+- Do not implement speech recognition inside Vibe Remote.
+- Do not call DashScope/Qwen directly from the local client.
+- Do not change how agents read the downloaded attachment path.
+- Do not add platform-specific audio behavior unless a platform cannot provide
+ a usable file attachment.
+- Do not show ASR failure details to the user or agent by default; failures are
+ fallback conditions, not user-visible errors.
+- Do not add a user-managed Qwen/DashScope API key to Vibe Remote. The local
+ runtime should call AVIBE, and AVIBE owns the upstream model credential.
+
+## Current Flow
+
+```text
+IM adapter
+ -> MessageContext(files=[FileAttachment(...)] )
+ -> MessageHandler._handle_turn()
+ -> _process_file_attachments()
+ saves ~/.vibe_remote/attachments/<channel_id>/<timestamp>_<name>
+ -> _prepend_message_metadata()
+ -> _append_attachment_errors()
+ -> AgentRequest(message=..., files=processed_files)
+ -> agent backend renders [User Attachments]
+```
+
+The ASR step should sit here:
+
+```text
+_process_file_attachments()
+ -> _augment_message_with_audio_transcripts()
+ -> _prepend_message_metadata()
+ -> _append_attachment_errors()
+```
+
+This placement keeps ASR platform-agnostic and backend-agnostic.
+
+## Proposed Design
+
+### 1. Add a shared ASR service
+
+Create a small core service, for example `core/audio_asr.py`, with three pieces:
+
+- audio eligibility detection
+- AVIBE OpenAI-compatible transcription client
+- message augmentation formatting
+
+The service should accept downloaded `FileAttachment` objects and return a list
+of transcript results. It should not know about Slack, Telegram, Claude, Codex,
+or OpenCode.
+
+Suggested shape:
+
+```python
+@dataclass
+class AudioTranscript:
+ attachment_name: str
+ local_path: str
+ text: str
+ duration_ms: int | None = None
+
+
+class AudioAsrService:
+ async def transcribe_attachments(
+ self,
+ attachments: list[FileAttachment],
+ *,
+ timeout_seconds: float = 60.0,
+ ) -> list[AudioTranscript]:
+ ...
+```
+
+`MessageHandler` owns the per-turn deadline and catches all ASR exceptions. On
+timeout or error, it logs a concise warning and continues without transcripts.
+
+### 2. Audio eligibility
+
+Treat an attachment as audio if either:
+
+- `mimetype` starts with `audio/`
+- extension is one of the formats the AVIBE backend supports for the Qwen ASR
+ model: `aac`, `flac`, `m4a`, `mp3`, `mp4`, `ogg`, `opus`, `wav`, `webm`
+
+Important edge case: WeChat can include `voice_item.text` directly in extracted
+message text, and Vibe Remote already reuses that official platform transcript.
+Do not support WeChat `audio/silk` in the first ASR version. If a WeChat voice
+message arrives without platform-provided text, keep the current attachment-only
+fallback behavior instead of adding local or backend Silk transcoding.
+
+### 3. AVIBE backend API contract
+
+Use an OpenAI-compatible audio transcription contract. Preferred local client
+request:
+
+```http
+POST {backend_url}/v1/audio/transcriptions
+Content-Type: multipart/form-data
+
+model=qwen3-asr-flash
+response_format=json
+```
+
+Expected response:
+
+```json
+{
+ "text": "transcribed speech..."
+}
+```
+
+Do not put "openai" in the product route. The endpoint is OpenAI-compatible,
+but the public path should be AVIBE-owned.
+
+Authentication should reuse the existing remote-access device credential
+created by pairing:
+
+- Pairing returns a long-lived `instance_secret`.
+- Vibe Remote stores it in `remote_access.vibe_cloud.instance_secret`.
+- AVIBE stores only its hash as `remoteAccessDevices.deviceSecretHash`.
+- The existing `runtime-status` route validates it through
+ `getInstanceByDeviceSecret()`, which also requires the device to be unrevoked
+ and the instance to be active.
+
+Recommended ASR auth:
+
+```http
+X-Vibe-Instance-Id: <instance_id>
+X-Vibe-Device-Secret: <instance_secret>
+```
+
+The backend should hash `X-Vibe-Device-Secret`, call the same
+`getInstanceByDeviceSecret()` store method, update `lastSeenAt` on success, and
+require the latest runtime status to show `tunnel_running=true`. If no recent
+runtime status exists or the tunnel is not running, reject ASR with a clear 403
+or 409 error. This keeps ASR tied to an actively paired and running local Vibe
+Remote.
+
+Why this is the preferred long-term shape:
+
+- It reuses the one credential already issued during pairing.
+- It remains valid until the device is revoked, the instance is disabled, or the
+ user re-pairs.
+- It does not depend on browser OAuth sessions or expiring ID/access tokens.
+- It keeps ASR scoped to paired Vibe Cloud devices without adding user-managed
+ API keys.
+- It avoids overloading the Cloudflare tunnel token. The tunnel token is for
+ connectivity; the device secret is already the local-runtime API credential.
+
+For consistency, a small AVIBE helper such as `requireDeviceRuntime()` should be
+added and then both `runtime-status` and ASR can share the same credential
+validation path. `runtime-status` may keep accepting `instance_secret` in JSON
+for backward compatibility, while ASR should use headers because multipart
+requests should not mix auth fields into the form body.
+
+### 4. Configuration
+
+Add a local config block instead of burying constants in `MessageHandler`:
+
+```python
+@dataclass
+class AudioAsrConfig:
+ enabled: bool = False
+ echo_transcript: bool = True
+ timeout_seconds: float = 60.0
+ endpoint_path: str = "/v1/audio/transcriptions"
+ model: str = "qwen3-asr-flash"
+ max_file_bytes: int | None = None
+```
+
+Default endpoint base should come from
+`config.remote_access.vibe_cloud.backend_url`, defaulting to `https://avibe.bot`.
+If remote access is unpaired or `instance_secret` is unavailable, skip ASR and
+preserve current behavior.
+
+Default should be **off** until the AVIBE endpoint is available and verified.
+The switch belongs under Messaging because it changes how inbound messages are
+prepared for agents. It should not live under a specific backend because Claude,
+Codex, and OpenCode all consume the same enriched `AgentRequest`.
+
+Persist this block through V2 config load/save and include it in the UI config
+payload. Suggested JSON shape:
+
+```json
+{
+ "audio_asr": {
+ "enabled": false,
+ "echo_transcript": true,
+ "timeout_seconds": 60,
+ "endpoint_path": "/v1/audio/transcriptions",
+ "model": "qwen3-asr-flash",
+ "max_file_bytes": null
+ }
+}
+```
+
+### 5. Message formatting
+
+Append transcripts to the user-authored message before current-time/user-info
+metadata is prepended. Keep the original attachment list unchanged.
+
+Recommended block:
+
+```text
+[Audio Transcripts]
+- <filename>: <transcript text>
+```
+
+For a voice-only message, this block becomes the agent-visible content, and the
+existing backend-specific attachment renderer still adds:
+
+```text
+[User Attachments]
+- File: /.../voice.m4a (audio/mp4, 327763 bytes)
+```
+
+This satisfies the product requirement: transcript text plus the original file
+attachment reaches the agent together.
+
+If `audio_asr.echo_transcript` is enabled, send a concise IM reply immediately
+after successful ASR. This echo is independent user feedback and should not wait
+for the agent request to be accepted. Keep it factual and short:
+
+```text
+Voice transcript:
+<transcript text>
+```
+
+For multiple audio attachments, echo one combined message with file labels. Do
+not echo anything on timeout or failure.
+
+### 6. Timeout and failure behavior
+
+The 60-second timeout should wrap the whole ASR augmentation step. If there are
+multiple audio files, run requests concurrently under the same deadline. Partial
+success is useful: include transcripts that completed successfully before the
+deadline and silently skip failed/timed-out files.
+
+On failure:
+
+- log file name, MIME type, status code/error class, and duration
+- do not log audio contents or transcript text at warning/error level
+- do not append an `[Attachment Download Errors]` entry for ASR failure
+- still pass `processed_files` into `AgentRequest`
+
+### 7. Web UI settings
+
+The current Messaging page has one broad `Message Handling` panel. It mixes
+different concepts:
+
+- inbound processing: future audio transcription
+- agent context metadata: current time, user info
+- run feedback: ACK mode, duration display
+- reliability: OpenCode error retry limit
+- output formatting: quick-reply buttons, Slack link previews
+- scope/routing navigation: allowed groups link
+
+Adding ASR as just another row would make the page harder to scan. The page
+should become a small set of grouped panels, reusing existing settings
+primitives (`SettingsPanel`, `SettingsRow`, `ToggleSwitch`, `CompactField`,
+`CompactSelect`) rather than introducing a new visual system.
+
+Recommended grouping:
+
+1. **Input Enrichment**
+ - Audio transcription switch.
+ - Echo transcription switch, enabled only when audio transcription is on.
+ - Optional future status/meta row: only show "Requires Vibe Cloud pairing"
+ when remote access credentials are missing and the switch is disabled or
+ ineffective.
+ - This group owns features that transform inbound user content before it
+ reaches an agent.
+
+2. **Agent Context**
+ - Include current time.
+ - Include user info.
+ - These rows both prepend metadata to messages sent to agents, so they
+ belong together.
+
+3. **Work Feedback**
+ - ACK mode.
+ - Show duration.
+ - Error retry limit.
+ - These settings affect how Vibe Remote signals progress and handles a
+ running turn. Keep the retry row here because the product direction is a
+ shared backend retry setting, not an OpenCode-only setting.
+
+4. **Reply Experience**
+ - Quick-reply buttons.
+ - Slack link preview suppression, shown only when Slack is enabled.
+ - These settings affect outbound bot messages rather than agent input.
+
+5. **Groups and Routing**
+ - Existing "Manage channels/groups" link.
+ - Keep this as a navigation row or a compact panel at the bottom. It should
+ not be mixed with message transformation settings.
+
+The autosave chip can remain in the page header. Each row should still autosave
+immediately; no new Save button is needed.
+
+Audio transcription switch behavior:
+
+- Label: "Audio transcription" / "语音转文字"
+- Description: "Transcribe supported audio attachments before sending the turn
+ to the agent." / "在把消息交给 Agent 前,先转写支持的语音附件。"
+- If unpaired with Vibe Cloud, keep the switch clickable only if a manual ASR
+ backend is later introduced. For the first version, prefer disabling the
+ switch with a short hint that Vibe Cloud pairing is required.
+- Do not expose model id or endpoint path in the normal UI. Those are product
+ defaults, not day-to-day user controls.
+
+Echo transcription switch behavior:
+
+- Label: "Echo transcript" / "回显转写结果"
+- Description: "Send the recognized text back to the chat when transcription
+ succeeds." / "语音识别成功后,把转写文本也发回当前对话。"
+- Default: on.
+- Disabled when audio transcription is off.
+
+### 8. Tests
+
+Add focused unit tests around the shared handler/service boundary:
+
+- non-audio attachments do not invoke ASR
+- audio attachment success appends `[Audio Transcripts]` and preserves files
+- audio ASR timeout falls back to the original message and files
+- audio ASR error falls back to the original message and files
+- multiple audio attachments can include partial successful transcripts
+- unpaired/missing backend credentials skips ASR
+- WeChat voice with existing extracted text is not duplicated by ASR unless a
+ real audio attachment is also present
+- echo enabled sends a transcript reply on success
+- echo disabled does not send transcript replies
+
+Keep tests at the `MessageHandler` level where possible, with a fake ASR service
+injected through the controller. Add lower-level client tests for HTTP payload
+shape if the AVIBE endpoint contract is finalized.
+
+Add UI-focused tests only if the existing UI test setup already covers settings
+pages cheaply. Otherwise, rely on `npm run build` plus manual screenshot review
+for this narrow settings layout change.
+
+## Implementation Steps
+
+1. Add `AudioAsrConfig` to V2 config load/save.
+2. Add `core/audio_asr.py` with audio detection, HTTP client, and transcript
+ block rendering helpers.
+3. Wire `AudioAsrService` in `core/controller.py`.
+4. Call the service from `MessageHandler._handle_turn` after attachments are
+ downloaded and before message metadata is prepended.
+5. Add `audio_asr` to the Web UI config payload and `SettingsMessagingPage`
+ save patch.
+6. Reorganize `SettingsMessagingPage` into grouped panels and add the audio
+ transcription and echo switches under Input Enrichment.
+7. Add English and Chinese i18n strings for the new group labels, descriptions,
+ and Vibe Cloud pairing hint.
+8. Add focused tests in `tests/test_message_handler_attachments.py` or a new
+ `tests/test_audio_asr.py`.
+9. Run targeted Python tests, `ruff check` on changed Python files, and
+ `npm run build` for the UI.
+10. Once the AVIBE backend endpoint exists, add one integration/manual check
+ using an m4a/ogg fixture against staging or production.
+
+## Final Decisions
+
+- AVIBE route: `/v1/audio/transcriptions`.
+- Auth: reuse paired device identity with `X-Vibe-Instance-Id` and
+ `X-Vibe-Device-Secret`.
+- Availability: only paired Vibe Cloud users; backend also checks recent runtime
+ status and requires `tunnel_running=true`.
+- WeChat Silk: not supported in the first version; rely on WeChat's official
+ voice transcript when present.
+- Echo: enabled by default and sent immediately after ASR success.
+- Retry setting: keep in Messaging / Work Feedback as a shared backend setting.
diff --git a/docs/plans/audio-attachment-asr.zh.md b/docs/plans/audio-attachment-asr.zh.md
new file mode 100644
index 000000000..0dc2ba8eb
--- /dev/null
+++ b/docs/plans/audio-attachment-asr.zh.md
@@ -0,0 +1,340 @@
+# 语音附件 ASR 计划
+
+## 背景
+
+现在各 IM 平台收到文件后,会先把附件归一化成 `FileAttachment`,
+再由共享的 `MessageHandler._process_file_attachments` 下载到本地,
+最后放进 `AgentRequest.files`。最终给 Agent 看的 `[User Attachments]`
+区块目前是在各个 agent backend 内部渲染的:
+
+- Claude / OpenCode 在 `_prepare_message_with_files` 里追加附件文本。
+- Codex 会构造文本输入,同时把图片作为原生 `localImage` 输入传入。
+
+所以语音转文字不应该写在某一个 IM 平台适配器里,也不应该写在
+Claude、Codex 或 OpenCode 某一个 backend 里。正确位置是在附件下载完成之后、
+`AgentRequest` 创建之前。这样所有平台和所有 agent backend 都能继承同一套行为。
+
+## 目标
+
+当用户发送语音文件附件时:
+
+1. 继续按现有逻辑下载并保存附件。
+2. 对符合条件的语音文件,调用 AVIBE 后端的 OpenAI Compatible ASR 接口。
+3. 在正常 turn pipeline 里最多等待 60 秒。
+4. 如果 ASR 在 60 秒内成功完成,把转写文本追加到用户消息里,同时继续把原始附件放进 `AgentRequest.files`。
+5. 如果 ASR 超时或失败,保持现有行为:用户文本加原本的附件说明,不额外暴露错误。
+6. 在 Web UI 的 Messaging 设置页提供一个开关。
+7. 在 ASR 开关旁边加一个“是否回显转写结果”的开关;默认开启回显。
+8. 借这个功能顺手重组 Messaging 设置页,不再把新功能继续塞进当前越来越长的大面板里。
+
+## 非目标
+
+- 不在 Vibe Remote 本地实现语音识别。
+- 不让本地客户端直接调用 DashScope / Qwen。
+- 不改变 Agent 读取已下载附件路径的方式。
+- 除非平台无法提供可用附件,否则不做平台专属语音逻辑。
+- ASR 失败默认不展示给用户或 Agent;失败只是 fallback 条件。
+- 不在 Vibe Remote 里新增用户自管的 Qwen / DashScope API Key。local runtime 只调用 AVIBE,AVIBE 负责上游模型凭据。
+
+## 当前流程
+
+```text
+IM adapter
+ -> MessageContext(files=[FileAttachment(...)] )
+ -> MessageHandler._handle_turn()
+ -> _process_file_attachments()
+ 保存到 ~/.vibe_remote/attachments/<channel_id>/<timestamp>_<name>
+ -> _prepend_message_metadata()
+ -> _append_attachment_errors()
+ -> AgentRequest(message=..., files=processed_files)
+ -> agent backend 渲染 [User Attachments]
+```
+
+ASR 步骤应该插在这里:
+
+```text
+_process_file_attachments()
+ -> _augment_message_with_audio_transcripts()
+ -> _prepend_message_metadata()
+ -> _append_attachment_errors()
+```
+
+这样 ASR 保持平台无关、backend 无关。
+
+## 方案设计
+
+### 1. 新增共享 ASR 服务
+
+新增一个小的 core 服务,例如 `core/audio_asr.py`,包含三部分:
+
+- 判断附件是否是可转写音频
+- 调用 AVIBE OpenAI Compatible 转写接口
+- 把转写结果格式化并追加到消息里
+
+这个服务只接收下载后的 `FileAttachment`,返回转写结果列表。它不应该知道 Slack、Telegram、Claude、Codex 或 OpenCode。
+
+建议结构:
+
+```python
+@dataclass
+class AudioTranscript:
+ attachment_name: str
+ local_path: str
+ text: str
+ duration_ms: int | None = None
+
+
+class AudioAsrService:
+ async def transcribe_attachments(
+ self,
+ attachments: list[FileAttachment],
+ *,
+ timeout_seconds: float = 60.0,
+ ) -> list[AudioTranscript]:
+ ...
+```
+
+`MessageHandler` 负责每个 turn 的 60 秒 deadline,并捕获所有 ASR 异常。
+超时或失败时只记录简洁 warning,然后继续走没有转写结果的老路径。
+
+### 2. 音频判断规则
+
+满足以下任一条件就认为是音频附件:
+
+- `mimetype` 以 `audio/` 开头
+- 文件扩展名属于 AVIBE 后端 / Qwen ASR 支持的格式:`aac`、`flac`、`m4a`、`mp3`、`mp4`、`ogg`、`opus`、`wav`、`webm`
+
+重要边界:微信有时会直接在 `voice_item.text` 里给出平台自带转写文本,
+Vibe Remote 现在已经复用了这段官方转写。第一版不要支持微信 `audio/silk`。
+如果微信语音没有平台自带文本,就继续走当前“只有附件说明”的 fallback,
+不要为了它新增本地或后端 Silk 转码。
+
+### 3. AVIBE 后端 API 契约
+
+使用 OpenAI Compatible 的 audio transcription 契约。建议本地客户端请求:
+
+```http
+POST {backend_url}/v1/audio/transcriptions
+Content-Type: multipart/form-data
+
+model=qwen3-asr-flash
+response_format=json
+```
+
+期望响应:
+
+```json
+{
+ "text": "transcribed speech..."
+}
+```
+
+产品 route 不要带 `openai`。接口可以是 OpenAI-compatible,但路径应该是 AVIBE 自己的路径。
+
+鉴权应该复用 pairing 后已经存在的 remote-access device credential:
+
+- pairing 会返回长期有效的 `instance_secret`
+- Vibe Remote 把它保存在 `remote_access.vibe_cloud.instance_secret`
+- AVIBE 后端只保存它的 hash,也就是 `remoteAccessDevices.deviceSecretHash`
+- 现有 `runtime-status` route 已经通过 `getInstanceByDeviceSecret()` 验证它,同时要求 device 未撤销、instance 处于 active 状态
+
+推荐 ASR 鉴权方式:
+
+```http
+X-Vibe-Instance-Id: <instance_id>
+X-Vibe-Device-Secret: <instance_secret>
+```
+
+后端收到后 hash `X-Vibe-Device-Secret`,复用同一个 `getInstanceByDeviceSecret()` store 方法校验,成功后更新 `lastSeenAt`,并且要求最近一次 runtime status 显示 `tunnel_running=true`。如果没有最近 runtime status,或者 tunnel 不在运行中,ASR 返回明确的 403 或 409。这样 ASR 会绑定到“已经配对且本地 Vibe Remote 正在运行”的设备。
+
+这是更适合长期使用的方案:
+
+- 复用 pairing 时已经发放的一份凭据
+- 只要 device 没被撤销、instance 没被停用、用户没重新 pairing,就长期有效
+- 不依赖浏览器 OAuth session 或会过期的 ID / access token
+- ASR 只开放给已配对 Vibe Cloud 的本地 runtime,不引入用户自管 API key
+- 不滥用 Cloudflare tunnel token;tunnel token 负责连接,device secret 才是 local runtime 调后端 API 的凭据
+
+建议后端新增一个小 helper,例如 `requireDeviceRuntime()`,让 `runtime-status` 和 ASR 共用同一套 device credential 校验。`runtime-status` 可以为了兼容继续接受 JSON body 里的 `instance_secret`,但 ASR 是 multipart 请求,鉴权更适合放在 header 里。
+
+### 4. 配置
+
+新增本地配置块,不把常量埋在 `MessageHandler` 里:
+
+```python
+@dataclass
+class AudioAsrConfig:
+ enabled: bool = False
+ echo_transcript: bool = True
+ timeout_seconds: float = 60.0
+ endpoint_path: str = "/v1/audio/transcriptions"
+ model: str = "qwen3-asr-flash"
+ max_file_bytes: int | None = None
+```
+
+默认 endpoint base 来自 `config.remote_access.vibe_cloud.backend_url`,
+默认是 `https://avibe.bot`。如果还没有配对 Vibe Cloud,或者缺少 `instance_secret`,
+就跳过 ASR,保持当前行为。
+
+默认值建议先设为 **关闭**,等 AVIBE endpoint 上线并验证后再决定是否默认打开。
+开关属于 Messaging,因为它改变的是“用户消息进入 Agent 前怎么准备”。
+它不应该放在某个具体 backend 下,因为 Claude、Codex、OpenCode 都消费同一个增强后的 `AgentRequest`。
+
+配置需要进入 V2 config load/save,并包含在 UI config payload 里。建议 JSON 形状:
+
+```json
+{
+ "audio_asr": {
+ "enabled": false,
+ "echo_transcript": true,
+ "timeout_seconds": 60,
+ "endpoint_path": "/v1/audio/transcriptions",
+ "model": "qwen3-asr-flash",
+ "max_file_bytes": null
+ }
+}
+```
+
+### 5. 消息格式
+
+转写结果追加到用户原始消息之后,再 prepend 当前时间 / 用户信息等 metadata。
+原始附件列表保持不变。
+
+推荐区块:
+
+```text
+[Audio Transcripts]
+- <filename>: <transcript text>
+```
+
+如果用户只发语音,没有文字,那么这个区块就是 agent-visible 的主要内容。
+之后现有 backend 的附件渲染仍然会追加:
+
+```text
+[User Attachments]
+- File: /.../voice.m4a (audio/mp4, 327763 bytes)
+```
+
+这满足产品要求:转写文本和原始文件附件会一起提供给 Agent。
+
+如果 `audio_asr.echo_transcript` 开启,则 ASR 成功后立刻向 IM 对话里发一条简短回显。这个回显是独立的用户反馈,不需要等 agent request 成功提交。
+
+```text
+Voice transcript:
+<transcript text>
+```
+
+如果一条消息里有多个语音附件,就合并成一条带文件名标签的回显消息。
+ASR 超时或失败时不回显。
+
+### 6. 超时和失败行为
+
+60 秒超时应该包住整个 ASR 增强步骤。如果一条消息里有多个音频附件,
+可以在同一个 deadline 下并发请求。部分成功是有价值的:成功完成的转写可以追加,失败或超时的文件静默跳过。
+
+失败时:
+
+- 记录文件名、MIME 类型、状态码 / 错误类型、耗时
+- warning / error 级别不要记录音频内容或转写文本
+- 不追加 `[Attachment Download Errors]`,因为 ASR 失败不是附件下载失败
+- 仍然把 `processed_files` 传进 `AgentRequest`
+
+### 7. Web UI 设置页
+
+当前 Messaging 页只有一个大的 `Message Handling` 面板,里面混了很多概念:
+
+- 输入处理:未来的语音转文字
+- Agent 上下文:当前时间、用户信息
+- 工作反馈:ACK 模式、耗时展示
+- 可靠性:OpenCode 错误重试次数
+- 输出格式:快捷回复按钮、Slack 链接预览
+- 范围 / 路由入口:允许的群组
+
+如果把 ASR 继续当成一个 row 塞进去,页面会更难扫。建议把页面拆成几个分组面板,
+继续复用现有设置组件:`SettingsPanel`、`SettingsRow`、`ToggleSwitch`、`CompactField`、`CompactSelect`,不要重新发明一套视觉系统。
+
+推荐分组:
+
+1. **Input Enrichment / 输入增强**
+ - 语音转文字开关。
+ - 回显转写结果开关,只在语音转文字开启时可用。
+ - 未来可加状态提示:缺少 Vibe Cloud pairing 时展示“需要先配对 Vibe Cloud”。
+ - 这个组负责所有“用户内容进入 Agent 前的转换”。
+
+2. **Agent Context / Agent 上下文**
+ - 携带当前时间。
+ - 携带用户信息。
+ - 这两个都是给 Agent 消息 prepend metadata,应该放一起。
+
+3. **Work Feedback / 工作反馈**
+ - ACK 模式。
+ - 显示耗时。
+ - 错误重试次数。
+ - 这些设置影响 Vibe Remote 如何反馈运行中状态、如何处理一次 turn。错误重试保持在这里,因为产品方向是所有 backend 共享的重试设置,不是 OpenCode 独有设置。
+
+4. **Reply Experience / 回复体验**
+ - 快捷回复按钮。
+ - Slack 链接预览抑制,仅 Slack 启用时展示。
+ - 这些设置影响 bot 发出的消息,而不是 Agent 输入。
+
+5. **Groups and Routing / 群组与路由**
+ - 现有“管理群组 / channel”的入口。
+ - 保持为底部导航 row 或小面板,不要和消息转换设置混在一起。
+
+页面 header 里的 autosave 状态可以保留。每个 row 继续即时 autosave,不需要新增 Save 按钮。
+
+语音转文字开关行为:
+
+- Label: "Audio transcription" / "语音转文字"
+- Description: "Transcribe supported audio attachments before sending the turn to the agent." / "在把消息交给 Agent 前,先转写支持的语音附件。"
+- 如果还没有配对 Vibe Cloud,第一版建议禁用开关并展示短提示:需要先配对 Vibe Cloud。
+- 正常 UI 不暴露 model id 或 endpoint path。这些是产品默认值,不是日常用户控制项。
+
+回显转写结果开关行为:
+
+- Label: "Echo transcript" / "回显转写结果"
+- Description: "Send the recognized text back to the chat when transcription succeeds." / "语音识别成功后,把转写文本也发回当前对话。"
+- 默认开启。
+- 语音转文字关闭时禁用。
+
+### 8. 测试
+
+围绕 shared handler / service 边界加聚焦测试:
+
+- 非音频附件不会触发 ASR
+- 音频附件转写成功时,会追加 `[Audio Transcripts]`,并保留原文件附件
+- ASR 超时时,fallback 到原消息和原附件
+- ASR 报错时,fallback 到原消息和原附件
+- 多个音频附件允许部分成功
+- 未配对 / 缺少后端凭据时跳过 ASR
+- 微信已有 `voice_item.text` 时不重复转写,除非同时存在真实音频附件
+- 开启回显时,ASR 成功会发回转写结果
+- 关闭回显时,ASR 成功也不会发回转写结果
+
+尽量把测试放在 `MessageHandler` 层,用 fake ASR service 注入 controller。
+如果 AVIBE endpoint 契约已经定下来,再补 HTTP payload 形状的低层 client 测试。
+
+UI 测试只有在现有 setup 能低成本覆盖 settings page 时才加。否则这个设置页布局改动可以用 `npm run build` 加手动截图检查。
+
+## 实施步骤
+
+1. 在 V2 config load/save 里加入 `AudioAsrConfig`。
+2. 新增 `core/audio_asr.py`,包含音频判断、HTTP client、转写文本格式化 helper。
+3. 在 `core/controller.py` 里挂载 `AudioAsrService`。
+4. 在 `MessageHandler._handle_turn` 中,附件下载完成后、prepend metadata 前调用 ASR service。
+5. 把 `audio_asr` 加入 Web UI config payload 和 `SettingsMessagingPage` 的保存 patch。
+6. 重组 `SettingsMessagingPage` 为多个分组面板,并把语音转文字和回显开关放到 Input Enrichment。
+7. 添加英文和中文 i18n 文案,包括新分组标题、描述、Vibe Cloud pairing 提示。
+8. 在 `tests/test_message_handler_attachments.py` 或新的 `tests/test_audio_asr.py` 里加聚焦测试。
+9. 跑目标 Python 测试、对修改过的 Python 文件跑 `ruff check`,并对 UI 跑 `npm run build`。
+10. 等 AVIBE 后端 endpoint 可用后,用 m4a / ogg fixture 做一次 staging 或 production 的集成 / 手动验证。
+
+## 最终决策
+
+- AVIBE route:`/v1/audio/transcriptions`。
+- 鉴权:复用已配对设备身份,使用 `X-Vibe-Instance-Id` 和 `X-Vibe-Device-Secret`。
+- 可用性:只给已配对 Vibe Cloud 的用户使用;后端同时检查最近 runtime status,并要求 `tunnel_running=true`。
+- 微信 Silk:第一版不支持;有微信官方语音转写文本时继续复用。
+- 回显:默认开启,ASR 成功后立刻发。
+- 错误重试:继续放在 Messaging / Work Feedback 下,作为所有 backend 共享设置。
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index 1ff1c9558..f47454189 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -132,6 +132,23 @@ def test_save_config_accepts_typing_ack_mode(monkeypatch, tmp_path):
assert updated.ack_mode == "typing"
+def test_save_config_merges_audio_asr_settings(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+
+ created = api.save_config(_full_config_payload())
+ assert created.audio_asr.enabled is False
+ assert created.audio_asr.echo_transcript is True
+
+ updated = api.save_config({"audio_asr": {"enabled": True, "echo_transcript": False}})
+ payload = api.config_to_payload(updated)
+
+ assert updated.audio_asr.enabled is True
+ assert updated.audio_asr.echo_transcript is False
+ assert updated.audio_asr.endpoint_path == "/v1/audio/transcriptions"
+ assert payload["audio_asr"]["enabled"] is True
+ assert payload["audio_asr"]["echo_transcript"] is False
+
+
def test_config_to_payload_redacts_remote_access_secrets_and_save_preserves_them(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
payload = _full_config_payload()
diff --git a/tests/test_audio_asr.py b/tests/test_audio_asr.py
new file mode 100644
index 000000000..d52da14cb
--- /dev/null
+++ b/tests/test_audio_asr.py
@@ -0,0 +1,164 @@
+import asyncio
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from config.v2_config import AudioAsrConfig, RemoteAccessConfig, VibeCloudRemoteAccessConfig
+from core.audio_asr import (
+ AudioAsrService,
+ AudioTranscript,
+ append_audio_transcripts_to_message,
+ format_audio_transcript_echo,
+)
+from modules.im import MessageContext
+from modules.im.base import FileAttachment, FileDownloadResult
+
+from tests.test_message_handler_typing import MessageHandler, _StubController
+
+
+class AudioAsrServiceTests(unittest.TestCase):
+ def test_audio_detection_skips_wechat_silk(self):
+ service = AudioAsrService(SimpleNamespace(audio_asr=AudioAsrConfig()))
+
+ self.assertTrue(service.is_audio_attachment(FileAttachment(name="voice.m4a", mimetype="audio/mp4")))
+ self.assertTrue(service.is_audio_attachment(FileAttachment(name="voice.ogg", mimetype="application/octet-stream")))
+ self.assertFalse(service.is_audio_attachment(FileAttachment(name="wechat_voice.silk", mimetype="audio/silk")))
+ self.assertFalse(service.is_audio_attachment(FileAttachment(name="report.pdf", mimetype="application/pdf")))
+
+ def test_requires_enabled_vibe_cloud_pairing(self):
+ service = AudioAsrService(
+ SimpleNamespace(
+ audio_asr=AudioAsrConfig(enabled=True),
+ remote_access=RemoteAccessConfig(
+ vibe_cloud=VibeCloudRemoteAccessConfig(
+ enabled=False,
+ backend_url="https://avibe.bot",
+ instance_id="instance",
+ instance_secret="secret",
+ )
+ ),
+ )
+ )
+
+ self.assertFalse(service.is_available())
+
+ def test_transcript_blocks(self):
+ transcripts = [
+ AudioTranscript(
+ attachment_name="voice.m4a",
+ local_path="/tmp/voice.m4a",
+ text="hello world",
+ )
+ ]
+
+ self.assertEqual(
+ append_audio_transcripts_to_message("please handle", transcripts),
+ "please handle\n\n[Audio Transcripts]\n- voice.m4a: hello world",
+ )
+ self.assertEqual(format_audio_transcript_echo(transcripts), "Voice transcript:\nhello world")
+
+
+class _AttachmentIMClient:
+ def __init__(self, payload: bytes = b"audio"):
+ self.payload = payload
+ self.sent_messages = []
+ self.formatter = SimpleNamespace(format_error=lambda text: text)
+
+ def should_use_thread_for_reply(self):
+ return False
+
+ async def prepare_turn_context(self, context, source):
+ return context
+
+ async def get_user_info(self, user_id):
+ return {"display_name": user_id}
+
+ async def download_file_to_path(self, file_info, target_path):
+ Path(target_path).write_bytes(self.payload)
+ return FileDownloadResult(True)
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ self.sent_messages.append(text)
+ return "echo-1"
+
+
+class _FakeAudioAsrService:
+ def __init__(self, result=None, error=None):
+ self.result = result or []
+ self.error = error
+ self.calls = []
+
+ async def transcribe_attachments(self, files):
+ self.calls.append(files)
+ if self.error:
+ raise self.error
+ return self.result
+
+
+class MessageHandlerAudioAsrTests(unittest.IsolatedAsyncioTestCase):
+ async def _run_turn(self, *, asr_service, echo_transcript=True):
+ controller = _StubController(platform="slack", ack_mode="message", typing_result=True)
+ controller.config.audio_asr = AudioAsrConfig(enabled=True, echo_transcript=echo_transcript)
+ controller.im_client = _AttachmentIMClient()
+ controller.audio_asr_service = asr_service
+ handler = MessageHandler(controller)
+ handler.set_session_handler(controller.session_handler or SimpleNamespace())
+
+ class _SessionHandler:
+ @staticmethod
+ def get_session_info(context, source="human"):
+ return ("base", "/tmp", "base:/tmp")
+
+ @staticmethod
+ def should_allocate_scheduled_anchor(context, source="human"):
+ return False
+
+ handler.set_session_handler(_SessionHandler())
+ attachment = FileAttachment(name="voice.m4a", mimetype="audio/mp4", url="file-id", size=5)
+ context = MessageContext(user_id="U1", channel_id="C1", message_id="M1", files=[attachment])
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):
+ await handler.handle_user_message(context, "please transcribe")
+
+ return controller
+
+ async def test_audio_asr_success_appends_transcript_and_echoes(self):
+ transcript = AudioTranscript("voice.m4a", "/tmp/voice.m4a", "hello from audio")
+ asr_service = _FakeAudioAsrService(result=[transcript])
+
+ controller = await self._run_turn(asr_service=asr_service)
+
+ self.assertEqual(len(asr_service.calls), 1)
+ request = controller.agent_service.requests[0][1]
+ self.assertIn("[Audio Transcripts]", request.message)
+ self.assertIn("hello from audio", request.message)
+ self.assertEqual(len(request.files), 1)
+ self.assertIn("Voice transcript:\nhello from audio", controller.im_client.sent_messages)
+
+ async def test_audio_asr_error_falls_back_to_original_message_and_files(self):
+ asr_service = _FakeAudioAsrService(error=RuntimeError("asr down"))
+
+ controller = await self._run_turn(asr_service=asr_service)
+
+ request = controller.agent_service.requests[0][1]
+ self.assertNotIn("[Audio Transcripts]", request.message)
+ self.assertIn("please transcribe", request.message)
+ self.assertEqual(len(request.files), 1)
+ self.assertFalse(any("Voice transcript" in message for message in controller.im_client.sent_messages))
+
+ async def test_audio_asr_echo_can_be_disabled(self):
+ transcript = AudioTranscript("voice.m4a", "/tmp/voice.m4a", "hello from audio")
+ asr_service = _FakeAudioAsrService(result=[transcript])
+
+ controller = await self._run_turn(asr_service=asr_service, echo_transcript=False)
+
+ request = controller.agent_service.requests[0][1]
+ self.assertIn("hello from audio", request.message)
+ self.assertFalse(any("Voice transcript" in message for message in controller.im_client.sent_messages))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsx
index 97d265f22..40993bd6e 100644
--- a/ui/src/components/settings/SettingsMessagingPage.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useState } from 'react';
-import { ArrowRight, MessageSquare } from 'lucide-react';
+import { ArrowRight, Bot, MessageSquare, Radio, Send, Sparkles } from 'lucide-react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -26,6 +26,7 @@ const SAVE_KEYS = [
'include_time_info',
'include_user_info',
'reply_enhancements',
+ 'audio_asr',
'slack',
'discord',
'telegram',
@@ -106,6 +107,11 @@ export const SettingsMessagingPage: React.FC = () => {
{ value: 'message', label: t('dashboard.ackMessage'), disabled: false },
];
const includeTimeInfoEnabled = config.include_time_info !== false;
+ const audioAsr = config.audio_asr || {};
+ const audioAsrEnabled = Boolean(audioAsr.enabled);
+ const audioEchoEnabled = audioAsr.echo_transcript !== false;
+ const vibeCloud = config.remote_access?.vibe_cloud || {};
+ const vibeCloudPaired = Boolean(vibeCloud.enabled && vibeCloud.instance_id);
return (
<SettingsPageShell
@@ -133,11 +139,101 @@ export const SettingsMessagingPage: React.FC = () => {
<SettingsPanel
title={
<span className="inline-flex items-center gap-2">
- <MessageSquare className="size-3.5 text-cyan" />
- {t('dashboard.messageHandling')}
+ <Sparkles className="size-3.5 text-cyan" />
+ {t('settings.messagingInputEnrichmentTitle')}
</span>
}
- description={t('settings.messagingCardDescription')}
+ description={t('settings.messagingInputEnrichmentDescription')}
+ >
+ <SettingsRow
+ title={t('dashboard.audioTranscription')}
+ description={
+ vibeCloudPaired
+ ? t('dashboard.audioTranscriptionHint')
+ : t('dashboard.audioTranscriptionRequiresVibeCloud')
+ }
+ control={
+ <ToggleSwitch
+ enabled={audioAsrEnabled}
+ disabled={!vibeCloudPaired}
+ onClick={() =>
+ void persist({
+ ...config,
+ audio_asr: {
+ ...audioAsr,
+ enabled: !audioAsrEnabled,
+ },
+ })
+ }
+ />
+ }
+ />
+
+ <SettingsRow
+ title={t('dashboard.audioTranscriptEcho')}
+ description={t('dashboard.audioTranscriptEchoHint')}
+ control={
+ <ToggleSwitch
+ enabled={audioEchoEnabled}
+ disabled={!audioAsrEnabled}
+ onClick={() =>
+ void persist({
+ ...config,
+ audio_asr: {
+ ...audioAsr,
+ echo_transcript: !audioEchoEnabled,
+ },
+ })
+ }
+ />
+ }
+ />
+ </SettingsPanel>
+
+ <SettingsPanel
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Bot className="size-3.5 text-mint" />
+ {t('settings.messagingAgentContextTitle')}
+ </span>
+ }
+ description={t('settings.messagingAgentContextDescription')}
+ >
+ <SettingsRow
+ title={t('dashboard.includeTimeInfo')}
+ description={t('dashboard.includeTimeInfoHint')}
+ control={
+ <ToggleSwitch
+ enabled={includeTimeInfoEnabled}
+ onClick={() =>
+ void persist({ ...config, include_time_info: !includeTimeInfoEnabled })
+ }
+ />
+ }
+ />
+
+ <SettingsRow
+ title={t('dashboard.includeUserInfo')}
+ description={t('dashboard.includeUserInfoHint')}
+ control={
+ <ToggleSwitch
+ enabled={Boolean(config.include_user_info)}
+ onClick={() =>
+ void persist({ ...config, include_user_info: !config.include_user_info })
+ }
+ />
+ }
+ />
+ </SettingsPanel>
+
+ <SettingsPanel
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Radio className="size-3.5 text-gold" />
+ {t('settings.messagingWorkFeedbackTitle')}
+ </span>
+ }
+ description={t('settings.messagingWorkFeedbackDescription')}
>
<SettingsRow
title={t('dashboard.ackMode')}
@@ -196,33 +292,17 @@ export const SettingsMessagingPage: React.FC = () => {
/>
}
/>
+ </SettingsPanel>
- <SettingsRow
- title={t('dashboard.includeTimeInfo')}
- description={t('dashboard.includeTimeInfoHint')}
- control={
- <ToggleSwitch
- enabled={includeTimeInfoEnabled}
- onClick={() =>
- void persist({ ...config, include_time_info: !includeTimeInfoEnabled })
- }
- />
- }
- />
-
- <SettingsRow
- title={t('dashboard.includeUserInfo')}
- description={t('dashboard.includeUserInfoHint')}
- control={
- <ToggleSwitch
- enabled={Boolean(config.include_user_info)}
- onClick={() =>
- void persist({ ...config, include_user_info: !config.include_user_info })
- }
- />
- }
- />
-
+ <SettingsPanel
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Send className="size-3.5 text-cyan" />
+ {t('settings.messagingReplyExperienceTitle')}
+ </span>
+ }
+ description={t('settings.messagingReplyExperienceDescription')}
+ >
<SettingsRow
title={t('dashboard.replyEnhancements')}
description={t('dashboard.replyEnhancementsHint')}
@@ -235,7 +315,6 @@ export const SettingsMessagingPage: React.FC = () => {
/>
}
/>
-
{slackSupportsLinkUnfurl && (
<SettingsRow
title={t('dashboard.slackLinkPreviews')}
@@ -256,7 +335,17 @@ export const SettingsMessagingPage: React.FC = () => {
}
/>
)}
+ </SettingsPanel>
+ <SettingsPanel
+ title={
+ <span className="inline-flex items-center gap-2">
+ <MessageSquare className="size-3.5 text-mint" />
+ {t('settings.messagingGroupsTitle')}
+ </span>
+ }
+ description={t('settings.messagingGroupsDescription')}
+ >
<SettingsRow
title={t('dashboard.allowedChannels')}
description={t('settings.messagingGroupsHint')}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 88e2a44e0..05906feb6 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -301,6 +301,16 @@
"messagingStatusIdle": "No recent changes",
"messagingStatusJustNow": "Saved just now",
"messagingStatusAgo": "Saved {{seconds}}s ago",
+ "messagingInputEnrichmentTitle": "Input enrichment",
+ "messagingInputEnrichmentDescription": "Transform inbound user content before it reaches an agent.",
+ "messagingAgentContextTitle": "Agent context",
+ "messagingAgentContextDescription": "Metadata prepended to each user turn sent to an agent.",
+ "messagingWorkFeedbackTitle": "Work feedback",
+ "messagingWorkFeedbackDescription": "How Vibe Remote acknowledges, retries, and reports running work.",
+ "messagingReplyExperienceTitle": "Reply experience",
+ "messagingReplyExperienceDescription": "Controls for messages Vibe Remote sends back into chat.",
+ "messagingGroupsTitle": "Groups and routing",
+ "messagingGroupsDescription": "Jump to group allow-list and per-group backend routing.",
"messagingGroupsHint": "Manage which groups are allowed and how each one routes to an agent backend.",
"messagingSupportTitle": "Platform support",
"messagingSupportLine1": "Typing indicators and reaction-based acknowledgements depend on the capabilities of the platforms you enabled.",
@@ -924,6 +934,11 @@
"ackReaction": "👀 Reaction",
"ackTyping": "✏️ Typing...",
"ackMessage": "💬 Message",
+ "audioTranscription": "Audio Transcription",
+ "audioTranscriptionHint": "Transcribe supported audio attachments before sending the turn to the agent",
+ "audioTranscriptionRequiresVibeCloud": "Pair this Vibe Remote with Vibe Cloud before enabling audio transcription",
+ "audioTranscriptEcho": "Echo Transcript",
+ "audioTranscriptEchoHint": "Send recognized text back to the chat when transcription succeeds",
"errorRetryLimit": "Error Retry Limit",
"errorRetryLimitHint": "Auto-retry with 'continue' when LLM stream errors occur (0 = no retry)",
"showDuration": "Show Duration",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b884775f6..23f1e29a2 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -301,6 +301,16 @@
"messagingStatusIdle": "最近没有变更",
"messagingStatusJustNow": "刚刚保存",
"messagingStatusAgo": "{{seconds}} 秒前已保存",
+ "messagingInputEnrichmentTitle": "输入增强",
+ "messagingInputEnrichmentDescription": "在消息交给 Agent 前,对用户输入内容做预处理。",
+ "messagingAgentContextTitle": "Agent 上下文",
+ "messagingAgentContextDescription": "随每次用户消息一起发送给 Agent 的上下文信息。",
+ "messagingWorkFeedbackTitle": "工作反馈",
+ "messagingWorkFeedbackDescription": "配置 Vibe Remote 如何确认、重试和展示运行中的工作。",
+ "messagingReplyExperienceTitle": "回复体验",
+ "messagingReplyExperienceDescription": "控制 Vibe Remote 发回聊天里的消息体验。",
+ "messagingGroupsTitle": "群组与路由",
+ "messagingGroupsDescription": "进入群组允许列表和按群组 backend 路由配置。",
"messagingGroupsHint": "前往群组页,管理允许工作的群组以及每个群组分别路由到哪个 agent backend。",
"messagingSupportTitle": "平台能力说明",
"messagingSupportLine1": "Typing 指示器和 Reaction ACK 取决于你当前启用的平台是否支持这些能力。",
@@ -924,6 +934,11 @@
"ackReaction": "👀 表情回应",
"ackTyping": "✏️ 正在输入...",
"ackMessage": "💬 消息回复",
+ "audioTranscription": "语音转文字",
+ "audioTranscriptionHint": "在把消息交给 Agent 前,先转写支持的语音附件",
+ "audioTranscriptionRequiresVibeCloud": "请先将 Vibe Remote 配对到 Vibe Cloud,再启用语音转文字",
+ "audioTranscriptEcho": "回显转写结果",
+ "audioTranscriptEchoHint": "语音识别成功后,把转写文本也发回当前对话",
"errorRetryLimit": "错误重试次数",
"errorRetryLimitHint": "当 LLM 流式响应出错时,自动发送 'continue' 重试(0 = 不重试)",
"showDuration": "显示耗时",
diff --git a/vibe/api.py b/vibe/api.py
index 0a5c152c9..f20384109 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -621,6 +621,7 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dic
"provider": config.remote_access.provider,
"vibe_cloud": _vibe_cloud_payload(config, include_secrets),
},
+ "audio_asr": config.audio_asr.__dict__,
"update": config.update.__dict__,
"ack_mode": config.ack_mode,
"language": config.language,