Skip to content

The agent that grows with you

fix(stt): isolate CAF conversions from source recordings

Muhammed Furkan Akıncıc17dafee29d9
diff --git a/tests/tools/test_transcription_caf_cleanup.py b/tests/tools/test_transcription_caf_cleanup.py
new file mode 100644
index 00000000000..82b68b8b8ec
--- /dev/null
+++ b/tests/tools/test_transcription_caf_cleanup.py
@@ -0,0 +1,48 @@
+"""Cloud CAF conversion owns its output without modifying neighboring files."""
+
+from pathlib import Path
+import subprocess
+
+import pytest
+
+from tools import transcription_audio as audio
+from tools import transcription_tools as stt
+
+
[email protected]("outcome", ["success", "provider-error", "conversion-error"])
+def test_caf_conversion_preserves_source_neighbors_and_removes_owned_output(tmp_path, monkeypatch, outcome):
+ source = tmp_path / "voice.caf"
+ source.write_bytes(b"caff fixture")
+ neighbor = source.with_suffix(".wav")
+ neighbor.write_bytes(b"existing recording")
+ outputs = []
+ monkeypatch.setattr(stt, "_load_stt_config", lambda: {
+ "provider": "groq", "cloud_trim_silence": False,
+ })
+ monkeypatch.setattr(audio, "_find_ffmpeg_binary", lambda: "ffmpeg")
+ monkeypatch.setattr(audio.shutil, "which", lambda _name: None)
+
+ def encode(command, **_kwargs):
+ output = Path(command[-1])
+ outputs.append(output)
+ output.write_bytes(b"converted recording")
+ if outcome == "conversion-error":
+ raise subprocess.CalledProcessError(1, command)
+
+ def transcribe(file_path, *_args):
+ assert Path(file_path).read_bytes() == b"converted recording"
+ if outcome == "provider-error":
+ raise RuntimeError("transcription failed")
+ return {"success": True, "transcript": "hello"}
+
+ monkeypatch.setattr(audio, "_run_quiet", encode)
+ monkeypatch.setattr(stt, "_dispatch_stt_provider", transcribe)
+ if outcome == "provider-error":
+ with pytest.raises(RuntimeError, match="transcription failed"):
+ stt.transcribe_audio(str(source))
+ else:
+ result = stt.transcribe_audio(str(source))
+ assert result["success"] is (outcome == "success")
+ assert source.read_bytes() == b"caff fixture"
+ assert neighbor.read_bytes() == b"existing recording"
+ assert outputs and all(not path.exists() and not path.parent.exists() for path in outputs)
diff --git a/tests/tools/test_transcription_tools.py b/tests/tools/test_transcription_tools.py
index 6195f536215..514c020eabc 100644
--- a/tests/tools/test_transcription_tools.py
+++ b/tests/tools/test_transcription_tools.py
@@ -1300,7 +1300,9 @@ class TestCafConversion:
"""_convert_caf_to_wav uses ffmpeg when available."""
caf_path = tmp_path / "voice.caf"
caf_path.write_bytes(b"caff\x00" * 20)
- wav_path = str(tmp_path / "voice.wav")
+ work_dir = tmp_path / "converted"
+ work_dir.mkdir()
+ wav_path = str(work_dir / "voice.wav")
def fake_run(cmd, **kwargs):
Path(wav_path).write_bytes(b"RIFF\x00\x00\x00\x00")
@@ -1313,7 +1315,7 @@ class TestCafConversion:
monkeypatch.setattr(subprocess, "run", fake_run)
from tools.transcription_tools import _convert_caf_to_wav
- result = _convert_caf_to_wav(str(caf_path))
+ result = _convert_caf_to_wav(str(caf_path), str(work_dir))
assert result == wav_path
assert Path(result).exists()
@@ -1349,7 +1351,7 @@ class TestTranscribeCredentialReadGuard:
from agent.file_safety import get_read_block_error
env_file = tmp_path / ".env"
- env_file.write_text("OPENAI_API_KEY=sk-secret\n")
+ env_file.write_text("OPENAI_API_KEY=sk-secret\n", encoding="utf-8")
expected = get_read_block_error(str(env_file))
assert expected, "test setup: a .env file should be read-blocked"
diff --git a/tools/transcription_audio.py b/tools/transcription_audio.py
index 45658e01b4e..7660c0a1f00 100644
--- a/tools/transcription_audio.py
+++ b/tools/transcription_audio.py
@@ -161,10 +161,10 @@ def _prepare_local_audio(file_path: str, work_dir: str) -> tuple[Optional[str],
return None, f"Failed to convert audio for local STT: {details}"
-def _convert_caf_to_wav(file_path: str) -> Optional[str]:
- """Convert CAF to WAV using ffmpeg or afconvert (macOS)."""
+def _convert_caf_to_wav(file_path: str, work_dir: str) -> Optional[str]:
+ """Convert CAF to WAV in a caller-owned directory using ffmpeg or afconvert."""
audio_path = Path(file_path)
- wav_path = os.path.join(audio_path.parent, f"{audio_path.stem}.wav")
+ wav_path = os.path.join(work_dir, f"{audio_path.stem}.wav")
ffmpeg = _find_ffmpeg_binary()
afconvert = shutil.which("afconvert")
candidates = (
diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py
index 715ddbff564..9ec6836e5cc 100644
--- a/tools/transcription_tools.py
+++ b/tools/transcription_tools.py
@@ -15,7 +15,9 @@ import shutil
import threading
import time
import importlib.util as _ilu
+from contextlib import ExitStack
from pathlib import Path
+from tempfile import TemporaryDirectory
from typing import Optional, Dict, Any
from utils import is_truthy_value
@@ -408,27 +410,24 @@ def _transcribe_prepared_audio(
if not is_stt_enabled(stt_config):
return _error_result("STT is disabled in config.yaml (stt.enabled: false).")
provider = _get_provider(stt_config)
- if not _is_local_stt_provider(provider, stt_config):
- error = _validate_audio_file_size(Path(file_path))
- if error:
- return error
- # Convert CAF (iMessage voice notes) to WAV for cloud STT providers.
- if Path(file_path).suffix.lower() == ".caf":
- file_path = _convert_caf_to_wav(file_path)
- if not file_path:
- return _error_result("CAF audio could not be converted to WAV.")
- # Best-effort pre-upload silence trim for built-in cloud providers.
- trim_cleanup_dir: Optional[str] = None
- if provider in CLOUD_STT_PROVIDERS:
- trimmed = _trim_silence_for_cloud_stt(file_path, stt_config)
- if trimmed:
- file_path = trimmed
- trim_cleanup_dir = os.path.dirname(trimmed)
- try:
+ with ExitStack() as cleanup:
+ if not _is_local_stt_provider(provider, stt_config):
+ error = _validate_audio_file_size(Path(file_path))
+ if error:
+ return error
+ # Never overwrite a neighboring WAV or leave converted voice notes behind.
+ if Path(file_path).suffix.lower() == ".caf":
+ work_dir = cleanup.enter_context(TemporaryDirectory(prefix="hermes-caf-"))
+ file_path = _convert_caf_to_wav(file_path, work_dir)
+ if not file_path:
+ return _error_result("CAF audio could not be converted to WAV.")
+ # Best-effort pre-upload silence trim for built-in cloud providers.
+ if provider in CLOUD_STT_PROVIDERS:
+ trimmed = _trim_silence_for_cloud_stt(file_path, stt_config)
+ if trimmed:
+ file_path = trimmed
+ cleanup.callback(shutil.rmtree, os.path.dirname(trimmed), ignore_errors=True)
return _dispatch_stt_provider(file_path, provider, stt_config, model, source)
- finally:
- if trim_cleanup_dir:
- shutil.rmtree(trim_cleanup_dir, ignore_errors=True)
# Built-in provider -> (stt section, config key, default, treat-empty-as-missing). "local_command"