Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Make pending voice cancellation atomic (#1054)

Ali Khokhar795a83a826f6
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 041891bb..fce6dadb 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -841,12 +841,19 @@ message ID lists; platform IO decides whether to use native batch deletion
(Telegram) or internal per-message deletion (Discord).
Shared voice-note orchestration lives in
[messaging/platforms/voice_flow.py](src/free_claude_code/messaging/platforms/voice_flow.py), which owns
-pending voice registration, file-size validation, temp-file cleanup,
-transcription, cancellation, error replies, and the handoff to
-`IncomingMessage`. It depends only on the consumer-owned `Transcriber` protocol
-from [messaging/voice.py](src/free_claude_code/messaging/voice.py). Pending voice lookups use the
-same `(platform, chat_id)` `MessageScope` as tree references, so raw IDs from
-different transports cannot share cancellation ownership. Bootstrap selects either the
+file-size validation, temp-file cleanup, transcription, error replies, and the
+handoff to `IncomingMessage`. Before status delivery it reserves an opaque claim
+in the `PendingVoiceRegistry` owned by [messaging/voice.py](src/free_claude_code/messaging/voice.py).
+That registry atomically owns optional status binding, cancellation by either
+message ID, and the exclusive handoff claim; only a flow that wins the handoff
+transition may invoke the message workflow. Cancellation can therefore win while
+status delivery is still pending, and a stale flow cannot bind or remove a newer
+generation reusing the same ID. Once cancellation wins, late status or
+transcription completion is cleanup-only and cannot hand off work or emit a
+second error reply. Pending voice identities use the same
+`(platform, chat_id)` `MessageScope` as tree references, so raw IDs from different
+transports cannot share cancellation ownership. The flow depends only on the
+consumer-owned `Transcriber` protocol. Bootstrap selects either the
instance-owned local Whisper `TranscriptionService` or the provider-owned
`NvidiaNimTranscriber`. Messaging no longer imports a provider adapter, and the
local service retains only one lazy pipeline for its immutable runtime settings;
diff --git a/pyproject.toml b/pyproject.toml
index 79337ae0..7ee7bccb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "3.5.1"
+version = "3.5.2"
description = "Middleware between Claude Code CLI (Anthropic API) and NVIDIA NIM"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/smoke/lib/e2e.py b/smoke/lib/e2e.py
index beee97c8..03c08188 100644
--- a/smoke/lib/e2e.py
+++ b/smoke/lib/e2e.py
@@ -27,6 +27,7 @@ from free_claude_code.core.anthropic.stream_contracts import (
)
from free_claude_code.messaging.models import IncomingMessage, MessageScope
from free_claude_code.messaging.session import SessionStore
+from free_claude_code.messaging.voice import VoiceCancellationResult
from free_claude_code.messaging.workflow import MessagingWorkflow
from smoke.lib.child_process import run_captured_text
from smoke.lib.config import ProviderModel, SmokeConfig, auth_headers
@@ -429,7 +430,7 @@ class FakePlatform:
for message_id in message_ids:
await self.delete_message(chat_id, message_id)
- def register_pending_voice(
+ def seed_pending_voice(
self, chat_id: str, voice_message_id: str, status_message_id: str
) -> None:
scope = MessageScope(platform=self.name, chat_id=chat_id)
@@ -440,8 +441,15 @@ class FakePlatform:
async def cancel_pending_voice(
self, scope: MessageScope, reply_id: str
- ) -> tuple[str, str] | None:
- return self._pending_voice.pop((scope, reply_id), None)
+ ) -> VoiceCancellationResult | None:
+ pending = self._pending_voice.pop((scope, reply_id), None)
+ if pending is None:
+ return None
+ voice_message_id, status_message_id = pending
+ return VoiceCancellationResult(
+ voice_message_id=voice_message_id,
+ status_message_id=status_message_id,
+ )
class FakeCLISession:
diff --git a/smoke/product/test_messaging_product_live.py b/smoke/product/test_messaging_product_live.py
index 7122effa..91118f37 100644
--- a/smoke/product/test_messaging_product_live.py
+++ b/smoke/product/test_messaging_product_live.py
@@ -267,7 +267,7 @@ async def test_same_message_ids_are_isolated_by_chat_e2e(
@pytest.mark.parametrize("platform_name", ["discord", "telegram"])
async def test_voice_platform_fake_e2e(platform_name: str, tmp_path) -> None:
driver = FakePlatformDriver(platform_name, tmp_path)
- driver.platform.register_pending_voice("chat_1", "voice_msg_1", "voice_status_1")
+ driver.platform.seed_pending_voice("chat_1", "voice_msg_1", "voice_status_1")
await driver.send("/clear", message_id="clear_voice", reply_to="voice_msg_1")
diff --git a/src/free_claude_code/messaging/commands.py b/src/free_claude_code/messaging/commands.py
index 11f8fc79..98f9b1a3 100644
--- a/src/free_claude_code/messaging/commands.py
+++ b/src/free_claude_code/messaging/commands.py
@@ -163,8 +163,9 @@ async def handle_clear_command(
incoming.scope, reply_id
)
if cancelled is not None:
- voice_msg_id, status_msg_id = cancelled
- msg_ids_to_del: set[str] = {voice_msg_id, status_msg_id}
+ msg_ids_to_del = {cancelled.voice_message_id}
+ if cancelled.status_message_id is not None:
+ msg_ids_to_del.add(cancelled.status_message_id)
if incoming.message_id is not None:
msg_ids_to_del.add(str(incoming.message_id))
await _delete_message_ids(handler, incoming.chat_id, msg_ids_to_del)
diff --git a/src/free_claude_code/messaging/platforms/discord.py b/src/free_claude_code/messaging/platforms/discord.py
index ca005153..be798392 100644
--- a/src/free_claude_code/messaging/platforms/discord.py
+++ b/src/free_claude_code/messaging/platforms/discord.py
@@ -12,7 +12,7 @@ from free_claude_code.core.diagnostics import format_user_error_preview
from ..limiter import MessagingRateLimiter
from ..models import IncomingMessage, MessageScope
from ..rendering.discord_markdown import format_status_discord
-from ..voice import Transcriber
+from ..voice import Transcriber, VoiceCancellationResult
from .discord_inbound import (
discord_text_message_from_event,
discord_voice_request_from_event,
@@ -140,7 +140,7 @@ class DiscordRuntime:
async def cancel_pending_voice(
self, scope: MessageScope, reply_id: str
- ) -> tuple[str, str] | None:
+ ) -> VoiceCancellationResult | None:
"""Cancel a pending voice transcription."""
return await self._voice_flow.cancel_pending_voice(scope, reply_id)
diff --git a/src/free_claude_code/messaging/platforms/ports.py b/src/free_claude_code/messaging/platforms/ports.py
index be4edb04..2b13ebee 100644
--- a/src/free_claude_code/messaging/platforms/ports.py
+++ b/src/free_claude_code/messaging/platforms/ports.py
@@ -5,6 +5,7 @@ from dataclasses import dataclass
from typing import Any, Protocol, runtime_checkable
from ..models import IncomingMessage, MessageScope
+from ..voice import VoiceCancellationResult
InboundMessageHandler = Callable[[IncomingMessage], Awaitable[None]]
@@ -67,7 +68,7 @@ class VoiceCancellation(Protocol):
async def cancel_pending_voice(
self, scope: MessageScope, reply_id: str
- ) -> tuple[str, str] | None: ...
+ ) -> VoiceCancellationResult | None: ...
@dataclass(frozen=True, slots=True)
diff --git a/src/free_claude_code/messaging/platforms/telegram.py b/src/free_claude_code/messaging/platforms/telegram.py
index b1f910d4..e61a13fc 100644
--- a/src/free_claude_code/messaging/platforms/telegram.py
+++ b/src/free_claude_code/messaging/platforms/telegram.py
@@ -15,7 +15,7 @@ from free_claude_code.core.diagnostics import format_user_error_preview
from ..limiter import MessagingRateLimiter
from ..models import IncomingMessage, MessageScope
from ..rendering.telegram_markdown import escape_md_v2
-from ..voice import Transcriber
+from ..voice import Transcriber, VoiceCancellationResult
from .ports import InboundMessageHandler
from .telegram_inbound import (
telegram_text_message_from_update,
@@ -85,7 +85,7 @@ class TelegramRuntime:
async def cancel_pending_voice(
self, scope: MessageScope, reply_id: str
- ) -> tuple[str, str] | None:
+ ) -> VoiceCancellationResult | None:
"""Cancel a pending voice transcription."""
return await self._voice_flow.cancel_pending_voice(scope, reply_id)
diff --git a/src/free_claude_code/messaging/platforms/voice_flow.py b/src/free_claude_code/messaging/platforms/voice_flow.py
index 96fb3a7f..e2738971 100644
--- a/src/free_claude_code/messaging/platforms/voice_flow.py
+++ b/src/free_claude_code/messaging/platforms/voice_flow.py
@@ -13,7 +13,12 @@ from loguru import logger
from free_claude_code.core.diagnostics import format_user_error_preview
from ..models import IncomingMessage, MessageScope
-from ..voice import PendingVoiceRegistry, Transcriber
+from ..voice import (
+ PendingVoiceClaim,
+ PendingVoiceRegistry,
+ Transcriber,
+ VoiceCancellationResult,
+)
AUDIO_EXTENSIONS = (".ogg", ".mp4", ".mp3", ".wav", ".m4a")
MAX_AUDIO_SIZE_BYTES = 25 * 1024 * 1024
@@ -116,30 +121,12 @@ class VoiceNoteFlow:
await reply_text(VOICE_DISABLED_MESSAGE)
return True
- async def register_pending_voice(
- self, scope: MessageScope, voice_msg_id: str, status_msg_id: str
- ) -> None:
- """Register a voice note as pending transcription."""
- await self._pending_voice.register(scope, voice_msg_id, status_msg_id)
-
async def cancel_pending_voice(
self, scope: MessageScope, reply_id: str
- ) -> tuple[str, str] | None:
+ ) -> VoiceCancellationResult | None:
"""Cancel a pending voice transcription."""
return await self._pending_voice.cancel(scope, reply_id)
- async def is_voice_still_pending(
- self, scope: MessageScope, voice_msg_id: str
- ) -> bool:
- """Return whether a voice note is still pending."""
- return await self._pending_voice.is_pending(scope, voice_msg_id)
-
- async def complete_pending_voice(
- self, scope: MessageScope, voice_msg_id: str, status_msg_id: str
- ) -> None:
- """Mark a voice note as no longer pending."""
- await self._pending_voice.complete(scope, voice_msg_id, status_msg_id)
-
async def handle(
self,
request: VoiceNoteRequest,
@@ -155,28 +142,44 @@ class VoiceNoteFlow:
if message_handler is None:
return False
- status_msg_id = await queue_send_message(
- request.chat_id,
- request.status_text,
- reply_to=request.message_id,
- parse_mode=request.status_parse_mode,
- fire_and_forget=False,
- message_thread_id=request.message_thread_id,
- )
- status_msg_id_text = str(status_msg_id)
- await self.register_pending_voice(
+ claim = await self._pending_voice.reserve(
request.scope,
request.message_id,
- status_msg_id_text,
)
- handed_off = False
+ if claim is None:
+ return True
- with tempfile.NamedTemporaryFile(
- suffix=request.temp_suffix, delete=False
- ) as tmp:
- tmp_path = Path(tmp.name)
+ status_msg_id: str | None = None
+ tmp_path: Path | None = None
+ handed_off = False
try:
+ delivered_status_id = await queue_send_message(
+ request.chat_id,
+ request.status_text,
+ reply_to=request.message_id,
+ parse_mode=request.status_parse_mode,
+ fire_and_forget=False,
+ message_thread_id=request.message_thread_id,
+ )
+ if delivered_status_id is None:
+ raise RuntimeError("Voice status delivery returned no message ID.")
+ status_msg_id = str(delivered_status_id)
+ if not await self._pending_voice.bind_status(claim, status_msg_id):
+ await self._clear_failed_pending_voice(
+ request,
+ claim,
+ status_msg_id,
+ queue_delete_messages,
+ handed_off=False,
+ )
+ return True
+
+ with tempfile.NamedTemporaryFile(
+ suffix=request.temp_suffix, delete=False
+ ) as tmp:
+ tmp_path = Path(tmp.name)
+
await request.download_to(tmp_path)
_validate_audio_file(tmp_path)
@@ -185,20 +188,6 @@ class VoiceNoteFlow:
raise RuntimeError("Voice transcription is not configured.")
transcribed = await transcriber.transcribe(tmp_path)
- if not await self.is_voice_still_pending(
- request.scope,
- request.message_id,
- ):
- await queue_delete_messages(request.chat_id, [status_msg_id_text])
- return True
-
- await self.complete_pending_voice(
- request.scope,
- request.message_id,
- status_msg_id_text,
- )
- handed_off = True
-
incoming = IncomingMessage(
text=transcribed,
chat_id=request.chat_id,
@@ -211,43 +200,51 @@ class VoiceNoteFlow:
raw_event=request.raw_event,
status_message_id=status_msg_id,
)
-
self._log_transcription(request, transcribed)
+ if not await self._pending_voice.claim_for_handoff(claim):
+ await self._clear_failed_pending_voice(
+ request,
+ claim,
+ status_msg_id,
+ queue_delete_messages,
+ handed_off=False,
+ )
+ return True
+ handed_off = True
+
await message_handler(incoming)
return True
except asyncio.CancelledError:
await self._clear_failed_pending_voice(
request,
- status_msg_id_text,
+ claim,
+ status_msg_id,
queue_delete_messages,
handed_off=handed_off,
)
raise
- except ValueError as e:
- await self._clear_failed_pending_voice(
+ except (ValueError, ImportError) as e:
+ discarded = await self._clear_failed_pending_voice(
request,
- status_msg_id_text,
- queue_delete_messages,
- handed_off=handed_off,
- )
- await request.reply_text(format_user_error_preview(e))
- return True
- except ImportError as e:
- await self._clear_failed_pending_voice(
- request,
- status_msg_id_text,
+ claim,
+ status_msg_id,
queue_delete_messages,
handed_off=handed_off,
)
+ if not handed_off and not discarded:
+ return True
await request.reply_text(format_user_error_preview(e))
return True
except Exception as e:
- await self._clear_failed_pending_voice(
+ discarded = await self._clear_failed_pending_voice(
request,
- status_msg_id_text,
+ claim,
+ status_msg_id,
queue_delete_messages,
handed_off=handed_off,
)
+ if not handed_off and not discarded:
+ return True
if self._log_api_error_tracebacks:
logger.error("Voice transcription failed: {}", e)
else:
@@ -258,25 +255,24 @@ class VoiceNoteFlow:
await request.reply_text(VOICE_TRANSCRIPTION_ERROR_MESSAGE)
return True
finally:
- with contextlib.suppress(OSError):
- tmp_path.unlink(missing_ok=True)
+ if tmp_path is not None:
+ with contextlib.suppress(OSError):
+ tmp_path.unlink(missing_ok=True)
async def _clear_failed_pending_voice(
self,
request: VoiceNoteRequest,
- status_msg_id: str,
+ claim: PendingVoiceClaim,
+ status_msg_id: str | None,
queue_delete_messages: QueueDeleteMany,
*,
handed_off: bool,
- ) -> None:
- await self.complete_pending_voice(
- request.scope,
- request.message_id,
- status_msg_id,
- )
- if not handed_off:
+ ) -> bool:
+ discarded = await self._pending_voice.discard(claim)
+ if not handed_off and status_msg_id is not None:
with contextlib.suppress(Exception):
await queue_delete_messages(request.chat_id, [status_msg_id])
+ return discarded
def _log_transcription(self, request: VoiceNoteRequest, transcribed: str) -> None:
label = request.platform.upper()
diff --git a/src/free_claude_code/messaging/voice.py b/src/free_claude_code/messaging/voice.py
index d6eb72ba..4c5112cf 100644
--- a/src/free_claude_code/messaging/voice.py
+++ b/src/free_claude_code/messaging/voice.py
@@ -1,8 +1,10 @@
"""Platform-neutral voice note helpers."""
import asyncio
+from dataclasses import dataclass
from pathlib import Path
from typing import Protocol
+from uuid import uuid4
from .models import MessageScope
@@ -15,40 +17,113 @@ class Transcriber(Protocol):
async def close(self) -> None: ...
+@dataclass(frozen=True, slots=True)
+class PendingVoiceClaim:
+ """Opaque ownership token for one pending voice-note generation."""
+
+ scope: MessageScope
+ voice_message_id: str
+ claim_id: str
+
+
+@dataclass(frozen=True, slots=True)
+class VoiceCancellationResult:
+ """Message IDs released by one successful voice cancellation."""
+
+ voice_message_id: str
+ status_message_id: str | None
+
+
+@dataclass(slots=True)
+class _PendingVoice:
+ claim: PendingVoiceClaim
+ status_message_id: str | None = None
+
+
class PendingVoiceRegistry:
- """Track voice notes that are still waiting on transcription."""
+ """Own atomic reservation, cancellation, and handoff of voice notes."""
def __init__(self) -> None:
- self._pending: dict[tuple[MessageScope, str], tuple[str, str]] = {}
+ self._pending: dict[tuple[MessageScope, str], _PendingVoice] = {}
self._lock = asyncio.Lock()
- async def register(
- self, scope: MessageScope, voice_msg_id: str, status_msg_id: str
- ) -> None:
+ async def reserve(
+ self,
+ scope: MessageScope,
+ voice_message_id: str,
+ ) -> PendingVoiceClaim | None:
async with self._lock:
- entry = (voice_msg_id, status_msg_id)
- self._pending[(scope, voice_msg_id)] = entry
- self._pending[(scope, status_msg_id)] = entry
+ key = (scope, voice_message_id)
+ if key in self._pending:
+ return None
+ claim = PendingVoiceClaim(
+ scope=scope,
+ voice_message_id=voice_message_id,
+ claim_id=uuid4().hex,
+ )
+ self._pending[key] = _PendingVoice(claim=claim)
+ return claim
+
+ async def bind_status(
+ self,
+ claim: PendingVoiceClaim,
+ status_message_id: str,
+ ) -> bool:
+ async with self._lock:
+ entry = self._entry_for_claim(claim)
+ if entry is None:
+ return False
+ if entry.status_message_id is not None:
+ return entry.status_message_id == status_message_id
+ status_key = (claim.scope, status_message_id)
+ existing = self._pending.get(status_key)
+ if existing is not None and existing is not entry:
+ return False
+ entry.status_message_id = status_message_id
+ self._pending[status_key] = entry
+ return True
+
+ async def claim_for_handoff(self, claim: PendingVoiceClaim) -> bool:
+ async with self._lock:
+ entry = self._entry_for_claim(claim)
+ if entry is None or entry.status_message_id is None:
+ return False
+ self._remove(entry)
+ return True
+
+ async def discard(self, claim: PendingVoiceClaim) -> bool:
+ async with self._lock:
+ entry = self._entry_for_claim(claim)
+ if entry is None:
+ return False
+ self._remove(entry)
+ return True
async def cancel(
self, scope: MessageScope, reply_id: str
- ) -> tuple[str, str] | None:
+ ) -> VoiceCancellationResult | None:
async with self._lock:
- entry = self._pending.pop((scope, reply_id), None)
+ entry = self._pending.get((scope, reply_id))
if entry is None:
return None
- voice_msg_id, status_msg_id = entry
- self._pending.pop((scope, voice_msg_id), None)
- self._pending.pop((scope, status_msg_id), None)
- return entry
+ self._remove(entry)
+ return VoiceCancellationResult(
+ voice_message_id=entry.claim.voice_message_id,
+ status_message_id=entry.status_message_id,
+ )
- async def is_pending(self, scope: MessageScope, voice_msg_id: str) -> bool:
- async with self._lock:
- return (scope, voice_msg_id) in self._pending
+ def _entry_for_claim(self, claim: PendingVoiceClaim) -> _PendingVoice | None:
+ entry = self._pending.get((claim.scope, claim.voice_message_id))
+ if entry is None or entry.claim != claim:
+ return None
+ return entry
- async def complete(
- self, scope: MessageScope, voice_msg_id: str, status_msg_id: str
- ) -> None:
- async with self._lock:
- self._pending.pop((scope, voice_msg_id), None)
- self._pending.pop((scope, status_msg_id), None)
+ def _remove(self, entry: _PendingVoice) -> None:
+ voice_key = (entry.claim.scope, entry.claim.voice_message_id)
+ if self._pending.get(voice_key) is entry:
+ self._pending.pop(voice_key)
+ if entry.status_message_id is None:
+ return
+ status_key = (entry.claim.scope, entry.status_message_id)
+ if self._pending.get(status_key) is entry:
+ self._pending.pop(status_key)
diff --git a/tests/messaging/test_handler.py b/tests/messaging/test_handler.py
index 68fb2819..2b2890c9 100644
--- a/tests/messaging/test_handler.py
+++ b/tests/messaging/test_handler.py
@@ -19,6 +19,7 @@ from free_claude_code.messaging.trees import (
TreeSnapshot,
)
from free_claude_code.messaging.trees.transitions import CancellationEffect
+from free_claude_code.messaging.voice import VoiceCancellationResult
from free_claude_code.messaging.workflow import MessagingWorkflow
_SCOPE = MessageScope(platform="telegram", chat_id="chat_1")
@@ -1159,10 +1160,24 @@ async def test_global_clear_invalidates_inflight_prompt_without_waiting_for_stat
@pytest.mark.asyncio
+ ("status_message_id", "expected_deleted_ids"),
+ [
+ ("101", {"100", "101", "150"}),
+ (None, {"100", "150"}),
+ ],
+)
async def test_reply_clear_pending_voice_cancels_and_reports(
- handler, mock_platform, incoming_message_factory
-):
- mock_platform.cancel_pending_voice.return_value = ("100", "101")
+ handler,
+ mock_platform,
+ incoming_message_factory,
+ status_message_id,
+ expected_deleted_ids,
+) -> None:
+ mock_platform.cancel_pending_voice.return_value = VoiceCancellationResult(
+ voice_message_id="100",
+ status_message_id=status_message_id,
+ )
deleted_ids: list[str] = []
async def capture_delete(chat_id, message_ids, fire_and_forget=True):
@@ -1178,5 +1193,5 @@ async def test_reply_clear_pending_voice_cancels_and_reports(
await handler.handle_message(incoming)
mock_platform.cancel_pending_voice.assert_awaited_once_with(incoming.scope, "100")
- assert set(deleted_ids) == {"100", "101", "150"}
+ assert set(deleted_ids) == expected_deleted_ids
assert "Voice note cancelled" in mock_platform.queue_send_message.call_args.args[1]
diff --git a/tests/messaging/test_platform_voice_flow.py b/tests/messaging/test_platform_voice_flow.py
index db69b2ea..bfdf0c65 100644
--- a/tests/messaging/test_platform_voice_flow.py
+++ b/tests/messaging/test_platform_voice_flow.py
@@ -130,6 +130,28 @@ async def test_voice_flow_disabled_replies_without_transcribing() -> None:
transcriber.run.assert_not_awaited()
+async def test_voice_flow_missing_status_id_stops_before_transcription() -> None:
+ flow, transcriber = _flow()
+ reply_text = AsyncMock()
+ handler = AsyncMock()
+ queue_delete = AsyncMock()
+
+ handled = await flow.handle(
+ _request(reply_text=reply_text),
+ message_handler=handler,
+ queue_send_message=AsyncMock(return_value=None),
+ queue_delete_messages=queue_delete,
+ )
+
+ assert handled is True
+ transcriber.run.assert_not_awaited()
+ handler.assert_not_awaited()
+ queue_delete.assert_not_awaited()
+ reply_text.assert_awaited_once_with(VOICE_TRANSCRIPTION_ERROR_MESSAGE)
+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None
+
+
@pytest.mark.asyncio
async def test_voice_flow_cancelled_transcription_deletes_status() -> None:
flow, transcriber = _flow()
@@ -155,6 +177,182 @@ async def test_voice_flow_cancelled_transcription_deletes_status() -> None:
queue_delete.assert_awaited_once_with("chat", ["status"])
+async def test_voice_flow_cancel_during_status_delivery_prevents_transcription() -> (
+ None
+):
+ flow, transcriber = _flow()
+ status_send_started = asyncio.Event()
+ release_status_send = asyncio.Event()
+ handler = AsyncMock()
+ queue_delete = AsyncMock()
+
+ async def send_status(*_args, **_kwargs) -> str:
+ status_send_started.set()
+ await release_status_send.wait()
+ return "status"
+
+ handle_task = asyncio.create_task(
+ flow.handle(
+ _request(),
+ message_handler=handler,
+ queue_send_message=send_status,
+ queue_delete_messages=queue_delete,
+ )
+ )
+
+ try:
+ await asyncio.wait_for(status_send_started.wait(), timeout=1)
+ cancelled = await flow.cancel_pending_voice(VOICE_SCOPE, "voice")
+
+ assert cancelled is not None
+ assert cancelled.voice_message_id == "voice"
+ assert cancelled.status_message_id is None
+
+ release_status_send.set()
+ assert await asyncio.wait_for(handle_task, timeout=1) is True
+ finally:
+ release_status_send.set()
+ if not handle_task.done():
+ handle_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await handle_task
+
+ transcriber.run.assert_not_awaited()
+ handler.assert_not_awaited()
+ queue_delete.assert_awaited_once_with("chat", ["status"])
+
+
+async def test_voice_flow_cancel_during_status_delivery_suppresses_late_failure() -> (
+ None
+):
+ flow, transcriber = _flow()
+ status_send_started = asyncio.Event()
+ release_status_send = asyncio.Event()
+ reply_text = AsyncMock()
+ handler = AsyncMock()
+
+ async def fail_status_send(*_args, **_kwargs) -> str:
+ status_send_started.set()
+ await release_status_send.wait()
+ raise RuntimeError("late status failure")
+
+ handle_task = asyncio.create_task(
+ flow.handle(
+ _request(reply_text=reply_text),
+ message_handler=handler,
+ queue_send_message=fail_status_send,
+ queue_delete_messages=AsyncMock(),
+ )
+ )
+
+ try:
+ await asyncio.wait_for(status_send_started.wait(), timeout=1)
+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is not None
+
+ release_status_send.set()
+ assert await asyncio.wait_for(handle_task, timeout=1) is True
+ finally:
+ release_status_send.set()
+ if not handle_task.done():
+ handle_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await handle_task
+
+ transcriber.run.assert_not_awaited()
+ handler.assert_not_awaited()
+ reply_text.assert_not_awaited()
+
+
+async def test_voice_flow_cancel_during_transcription_suppresses_late_failure() -> None:
+ flow, transcriber = _flow()
+ transcription_started = asyncio.Event()
+ release_transcription = asyncio.Event()
+ reply_text = AsyncMock()
+ handler = AsyncMock()
+ queue_delete = AsyncMock()
+
+ async def fail_transcription(_path: Path) -> str:
+ transcription_started.set()
+ await release_transcription.wait()
+ raise RuntimeError("late transcription failure")
+
+ transcriber.run.side_effect = fail_transcription
+ handle_task = asyncio.create_task(
+ flow.handle(
+ _request(reply_text=reply_text),
+ message_handler=handler,
+ queue_send_message=AsyncMock(return_value="status"),
+ queue_delete_messages=queue_delete,
+ )
+ )
+
+ try:
+ await asyncio.wait_for(transcription_started.wait(), timeout=1)
+ cancelled = await flow.cancel_pending_voice(VOICE_SCOPE, "voice")
+ assert cancelled is not None
+ assert cancelled.status_message_id == "status"
+
+ release_transcription.set()
+ assert await asyncio.wait_for(handle_task, timeout=1) is True
+ finally:
+ release_transcription.set()
+ if not handle_task.done():
+ handle_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await handle_task
+
+ handler.assert_not_awaited()
+ reply_text.assert_not_awaited()
+ queue_delete.assert_awaited_once_with("chat", ["status"])
+
+
+async def test_voice_flow_cancel_at_handoff_boundary_prevents_handler(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ flow, _transcriber = _flow()
+ claim_started = asyncio.Event()
+ release_claim = asyncio.Event()
+ handler = AsyncMock()
+ registry = flow._pending_voice
+ claim_for_handoff = registry.claim_for_handoff
+
+ async def gated_claim(claim) -> bool:
+ claim_started.set()
+ await release_claim.wait()
+ return await claim_for_handoff(claim)
+
+ monkeypatch.setattr(registry, "claim_for_handoff", gated_claim)
+ handle_task = asyncio.create_task(
+ flow.handle(
+ _request(),
+ message_handler=handler,
+ queue_send_message=AsyncMock(return_value="status"),
+ queue_delete_messages=AsyncMock(),
+ )
+ )
+
+ try:
+ await asyncio.wait_for(claim_started.wait(), timeout=1)
+ cancelled = await flow.cancel_pending_voice(VOICE_SCOPE, "voice")
+ assert cancelled is not None
+ assert cancelled.status_message_id == "status"
+
+ release_claim.set()
+ assert await asyncio.wait_for(handle_task, timeout=1) is True
+ finally:
+ release_claim.set()
+ if not handle_task.done():
+ handle_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await handle_task
+
+ handler.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_voice_flow_task_cancellation_waits_then_cleans_pending_state() -> None:
flow, transcriber = _flow()
@@ -191,7 +389,6 @@ async def test_voice_flow_task_cancellation_waits_then_cleans_pending_state() ->
await cancellation_received.wait()
assert not handle_task.done()
- assert await flow.is_voice_still_pending(VOICE_SCOPE, "voice") is True
queue_delete.assert_not_awaited()
release.set()
diff --git a/tests/messaging/test_voice_services.py b/tests/messaging/test_voice_services.py
index d6d79bcb..9cee0e54 100644
--- a/tests/messaging/test_voice_services.py
+++ b/tests/messaging/test_voice_services.py
@@ -1,48 +1,107 @@
import pytest
from free_claude_code.messaging.models import MessageScope
-from free_claude_code.messaging.voice import PendingVoiceRegistry
+from free_claude_code.messaging.voice import (
+ PendingVoiceRegistry,
+ VoiceCancellationResult,
+)
TELEGRAM_CHAT = MessageScope(platform="telegram", chat_id="chat")
DISCORD_CHAT = MessageScope(platform="discord", chat_id="chat")
@pytest.mark.asyncio
-async def test_pending_voice_registry_tracks_voice_and_status_ids():
+async def test_cancel_before_status_binding_rejects_late_flow() -> None:
registry = PendingVoiceRegistry()
+ claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")
- await registry.register(TELEGRAM_CHAT, "voice-1", "status-1")
+ assert claim is not None
+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") == (
+ VoiceCancellationResult(
+ voice_message_id="voice-1",
+ status_message_id=None,
+ )
+ )
+ assert await registry.bind_status(claim, "status-1") is False
+ assert await registry.claim_for_handoff(claim) is False
- assert await registry.is_pending(TELEGRAM_CHAT, "voice-1") is True
+
+async def test_pending_voice_registry_cancel_and_handoff_are_exclusive() -> None:
+ registry = PendingVoiceRegistry()
+ cancelled_claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")
+
+ assert cancelled_claim is not None
+ assert await registry.bind_status(cancelled_claim, "status-1") is True
assert await registry.cancel(TELEGRAM_CHAT, "status-1") == (
- "voice-1",
- "status-1",
+ VoiceCancellationResult(
+ voice_message_id="voice-1",
+ status_message_id="status-1",
+ )
)
- assert await registry.is_pending(TELEGRAM_CHAT, "voice-1") is False
+ assert await registry.claim_for_handoff(cancelled_claim) is False
+
+ handed_off_claim = await registry.reserve(TELEGRAM_CHAT, "voice-2")
+ assert handed_off_claim is not None
+ assert await registry.bind_status(handed_off_claim, "status-2") is True
+ assert await registry.claim_for_handoff(handed_off_claim) is True
+ assert await registry.cancel(TELEGRAM_CHAT, "voice-2") is None
@pytest.mark.asyncio
-async def test_pending_voice_registry_isolates_platform_scopes():
+async def test_pending_voice_registry_isolates_platform_scopes() -> None:
registry = PendingVoiceRegistry()
- await registry.register(DISCORD_CHAT, "voice-1", "status-1")
- await registry.register(TELEGRAM_CHAT, "voice-1", "status-1")
+ discord_claim = await registry.reserve(DISCORD_CHAT, "voice-1")
+ telegram_claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")
+ assert discord_claim is not None
+ assert telegram_claim is not None
+ assert await registry.bind_status(discord_claim, "status-1") is True
+ assert await registry.bind_status(telegram_claim, "status-1") is True
assert await registry.cancel(TELEGRAM_CHAT, "voice-1") == (
- "voice-1",
- "status-1",
+ VoiceCancellationResult(
+ voice_message_id="voice-1",
+ status_message_id="status-1",
+ )
)
- assert await registry.is_pending(DISCORD_CHAT, "voice-1") is True
assert await registry.cancel(DISCORD_CHAT, "voice-1") == (
- "voice-1",
- "status-1",
+ VoiceCancellationResult(
+ voice_message_id="voice-1",
+ status_message_id="status-1",
+ )
)
@pytest.mark.asyncio
-async def test_pending_voice_registry_complete_removes_entries():
+async def test_stale_claim_cannot_mutate_reused_voice_id() -> None:
registry = PendingVoiceRegistry()
+ stale_claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")
- await registry.register(TELEGRAM_CHAT, "voice-1", "status-1")
- await registry.complete(TELEGRAM_CHAT, "voice-1", "status-1")
+ assert stale_claim is not None
+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is not None
+
+ current_claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")
+ assert current_claim is not None
+ assert current_claim != stale_claim
+ assert await registry.bind_status(current_claim, "status-current") is True
+
+ assert await registry.bind_status(stale_claim, "status-stale") is False
+ assert await registry.claim_for_handoff(stale_claim) is False
+ assert await registry.discard(stale_claim) is False
+ assert await registry.cancel(TELEGRAM_CHAT, "status-current") == (
+ VoiceCancellationResult(
+ voice_message_id="voice-1",
+ status_message_id="status-current",
+ )
+ )
+
+
+async def test_pending_voice_registry_rejects_duplicate_and_unbound_handoff() -> None:
+ registry = PendingVoiceRegistry()
+ claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")
- assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None
+ assert claim is not None
+ assert await registry.reserve(TELEGRAM_CHAT, "voice-1") is None
+ assert await registry.claim_for_handoff(claim) is False
+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is not None
diff --git a/uv.lock b/uv.lock
index d6d22317..8ded56af 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "3.5.1"
+version = "3.5.2"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },