The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tts): a failed synthesis no longer deletes an existing file
Teknium7085fbf77532
diff --git a/tests/tools/test_tts_failure_preserves_existing.py b/tests/tools/test_tts_failure_preserves_existing.pynew file mode 100644index 00000000000..08faf580540--- /dev/null+++ b/tests/tools/test_tts_failure_preserves_existing.py@@ -0,0 +1,76 @@+"""A failed text_to_speech call must never destroy a file that already lived at output_path.++The model picks ``output_path``; before this fix a provider failure swept that path as a+"partial artifact" even when it was the user's pre-existing file.+"""++import json+from pathlib import Path++import pytest++from gateway.session_context import _UNSET, _VAR_MAP+from tools import tts_tool++[email protected](autouse=True)+def _edge_without_session_platform(monkeypatch):+ for var in _VAR_MAP.values():+ var.set(_UNSET)+ monkeypatch.delenv("HERMES_SESSION_PLATFORM", raising=False)+ monkeypatch.setattr(tts_tool, "_load_tts_config", lambda: {"provider": "edge"})+ monkeypatch.setattr(tts_tool, "_import_edge_tts", lambda: object())+ yield+ for var in _VAR_MAP.values():+ var.set(_UNSET)+++def audio_dir(tmp_path):+ path = tmp_path / "audio" # tmp_path also holds the conftest's isolated HERMES_HOME+ path.mkdir()+ return path+++async def _partial_write_then_fail(_text: str, output_path: str, _cfg: dict) -> str:+ Path(output_path).write_bytes(b"partial")+ raise RuntimeError("provider unreachable")+++async def _write_audio(_text: str, output_path: str, _cfg: dict) -> str:+ Path(output_path).write_bytes(b"new-audio")+ return output_path+++def test_failed_synthesis_keeps_existing_file_and_cleans_partial(audio_dir, monkeypatch):+ existing = audio_dir / "notes.mp3"+ existing.write_bytes(b"user data")+ monkeypatch.setattr(tts_tool, "_generate_edge_tts", _partial_write_then_fail)++ result = json.loads(tts_tool.text_to_speech_tool("hello", output_path=str(existing)))++ assert result["success"] is False+ assert existing.read_bytes() == b"user data"+ assert sorted(p.name for p in audio_dir.iterdir()) == ["notes.mp3"]+++def test_failed_synthesis_to_new_path_leaves_nothing_behind(audio_dir, monkeypatch):+ monkeypatch.setattr(tts_tool, "_generate_edge_tts", _partial_write_then_fail)++ result = json.loads(tts_tool.text_to_speech_tool("hello", output_path=str(audio_dir / "new.mp3")))++ assert result["success"] is False+ assert list(audio_dir.iterdir()) == []+++def test_successful_synthesis_still_overwrites_existing_file(audio_dir, monkeypatch):+ existing = audio_dir / "notes.mp3"+ existing.write_bytes(b"user data")+ monkeypatch.setattr(tts_tool, "_generate_edge_tts", _write_audio)++ result = json.loads(tts_tool.text_to_speech_tool("hello", output_path=str(existing)))++ assert result["success"] is True+ assert result["file_path"] == str(existing)+ assert existing.read_bytes() == b"new-audio"+ assert sorted(p.name for p in audio_dir.iterdir()) == ["notes.mp3"]diff --git a/tools/tts_tool.py b/tools/tts_tool.pyindex c5172e7c254..b60cdf372f3 100644--- a/tools/tts_tool.py+++ b/tools/tts_tool.py@@ -18,6 +18,7 @@ import loggingimport osimport reimport tempfile+import uuidfrom pathlib import Pathfrom typing import Callable, Dict, Any, List, Optional@@ -431,6 +432,10 @@ def _synthesize_chunks(chunks: list[str], base_path: Path, generated_artifacts:chunk_path = base_pathif len(chunks) > 1:chunk_path = base_path.with_name(f"{base_path.stem}.chunk{index:03d}{base_path.suffix}")+ if os.path.lexists(chunk_path):+ # A file we didn't create: synthesize beside it so a failed attempt can neither truncate+ # nor sweep it; on success the delivery step os.replace()s the audio over it (overwrite).+ chunk_path = chunk_path.with_name(f".{chunk_path.stem}.{uuid.uuid4().hex}{chunk_path.suffix}")generated_artifacts.add(str(chunk_path))raw_result = _text_to_speech_single(chunk, str(chunk_path), **single_kwargs)try: