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
Keep voice ownership continuous through admission (#1063)
Ali Khokhar78377253d6db
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 906c3161..9d9589c9 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -854,8 +854,8 @@ The platform factory returns a `MessagingPlatformComponents` bundle from[messaging/platforms/ports.py](src/free_claude_code/messaging/platforms/ports.py): a`MessagingRuntime` with separate `quiesce()` and `close()` phases, an `OutboundMessenger`for queued sends/edits/deletes, and an optional `VoiceCancellation` port for-reply-scoped `/clear` during voice transcription. Workflow code depends on-these ports, not on Telegram or Discord SDK objects.+scoped and bulk voice cancellation during `/stop` and `/clear`. Workflow code+depends on these ports, not on Telegram or Discord SDK objects.Runtime adapters in[messaging/platforms/telegram.py](src/free_claude_code/messaging/platforms/telegram.py) and@@ -889,12 +889,20 @@ file-size validation, temp-file cleanup, transcription, error replies, and thehandoff to `IncomingMessage`. Before status delivery it reserves an opaque claimin 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+message ID, and one child task that retains the exclusive handoff lease through+the complete workflow callback. An explicit stop or clear atomically removes+the exact claim and assumes ownership under the registry lock, then cancels and+joins its published child without holding that lock. Caller cancellation instead+keeps both aliases published while it cancels and drains the child, then removes+only that exact generation. Repeated cancellation cannot abandon either join or+pre-handoff cleanup, and fatal callback failures release the aliases before they+propagate. A cancellation that wins turns late status, transcription, callback+completion, or ordinary callback failure into cleanup-only work. Bulk+cancellation deduplicates the voice/status aliases and excludes the exact+current handoff child plus claims participating in a nested cancellation, so a+voice-transcribed `/stop` or `/clear` cannot cancel itself or form a recursive+join cycle. A stale flow cannot bind or remove a newer generation reusing the+same ID. Pending voice identities use the same`(platform, chat_id)` `MessageScope` as tree references, so raw IDs from differenttransports cannot share cancellation ownership. The flow depends only on theconsumer-owned `Transcriber` protocol. Bootstrap selects either the@@ -914,10 +922,17 @@ state-transaction lock, admission epoch, stop/clear side effects, andshutdown-visible state. Each inbound turn snapshots the epoch before externalstatus I/O and rechecks it while committing admission; global `/stop` and`/clear` advance the epoch so an older provisional turn is discarded instead of-crossing that boundary. The workflow persists the detached snapshot returned by-the same transition instead of taking a later mutable-node read. Once a stop or-clear transition commits, its persistence effects are applied before the later-interruptible global CLI cleanup. At startup it restores and normalizes+crossing that boundary. Before taking the workflow lock, those global commands+cancel and join every older voice handoff; they then cancel any tree that won+admission during the join. Reply-scoped commands first join the matching voice+claim and then resolve its authoritative tree, so either the voice cancellation+or the admitted-tree transition wins and the same scoped request is never+double-counted. Epoch validation, tree admission, processor publication, and+persistence of the detached snapshot complete as one workflow-owned operation;+caller cancellation is restored only after that transaction finishes. Stop and+clear use the same completion-driven boundary, so caller cancellation cannot+leave a committed state transition without its remaining persistence or CLI+cleanup. At startup it restores and normalizespersisted state before ingress begins, then repairs interrupted platformstatuses after outbound delivery starts. Diagnostic detail policy is capturedat construction and passed into the processor; messaging does not read globaldiff --git a/pyproject.toml b/pyproject.tomlindex 20d142c3..9621a22c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "3.5.6"+version = "3.5.7"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.pyindex 03c08188..95d4af24 100644--- a/smoke/lib/e2e.py+++ b/smoke/lib/e2e.py@@ -319,7 +319,9 @@ class FakePlatform:self.deletes: list[dict[str, Any]] = []self._counter = 0self._tasks: list[asyncio.Future[Any]] = []- self._pending_voice: dict[tuple[MessageScope, str], tuple[str, str]] = {}+ self._pending_voice: dict[+ tuple[MessageScope, str], VoiceCancellationResult+ ] = {}async def start(self) -> None:return None@@ -434,21 +436,43 @@ class FakePlatform:self, chat_id: str, voice_message_id: str, status_message_id: str) -> None:scope = MessageScope(platform=self.name, chat_id=chat_id)- self._pending_voice[(scope, voice_message_id)] = (- voice_message_id,- status_message_id,+ result = VoiceCancellationResult(+ scope=scope,+ voice_message_id=voice_message_id,+ status_message_id=status_message_id,)+ self._pending_voice[(scope, voice_message_id)] = result+ self._pending_voice[(scope, status_message_id)] = resultasync def cancel_pending_voice(self, scope: MessageScope, reply_id: str) -> VoiceCancellationResult | None:- pending = self._pending_voice.pop((scope, reply_id), None)- if pending is None:+ result = self._pending_voice.get((scope, reply_id))+ if result 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,+ for message_id in result.message_ids:+ self._pending_voice.pop((scope, message_id), None)+ return result++ async def cancel_all_pending_voices(+ self,+ ) -> tuple[VoiceCancellationResult, ...]:+ results = tuple(+ {+ (result.scope, result.voice_message_id): result+ for result in self._pending_voice.values()+ }.values()+ )+ self._pending_voice.clear()+ return results++ @property+ def pending_voice_count(self) -> int:+ return len(+ {+ (result.scope, result.voice_message_id)+ for result in self._pending_voice.values()+ })diff --git a/smoke/product/test_messaging_product_live.py b/smoke/product/test_messaging_product_live.pyindex 91118f37..93f0a8b2 100644--- a/smoke/product/test_messaging_product_live.py+++ b/smoke/product/test_messaging_product_live.py@@ -271,7 +271,12 @@ async def test_voice_platform_fake_e2e(platform_name: str, tmp_path) -> None:await driver.send("/clear", message_id="clear_voice", reply_to="voice_msg_1")+ driver.platform.seed_pending_voice("chat_1", "voice_msg_2", "voice_status_2")+ await driver.send("/stop", message_id="stop_voice")+deleted = {entry["message_id"] for entry in driver.platform.deletes}assert {"voice_msg_1", "voice_status_1", "clear_voice"} <= deleted+ assert driver.platform.pending_voice_count == 0sent_text = "\n".join(sent["text"] for sent in driver.platform.sent)assert "Voice note cancelled" in sent_text+ assert "Cancelled 1 pending or active requests" in sent_textdiff --git a/src/free_claude_code/messaging/command_context.py b/src/free_claude_code/messaging/command_context.pyindex 01d0bbca..95c75d35 100644--- a/src/free_claude_code/messaging/command_context.py+++ b/src/free_claude_code/messaging/command_context.py@@ -1,19 +1,26 @@"""Typed dependency surface for messaging slash commands."""+from dataclasses import dataclassfrom typing import Protocolfrom .managed_protocols import ManagedClaudeSessionManagerProtocolfrom .models import MessageScope-from .platforms.ports import OutboundMessenger, VoiceCancellation+from .platforms.ports import OutboundMessengerfrom .transcript import RenderCtx-from .trees import BranchRemovalResult+++@dataclass(frozen=True, slots=True)+class ReplyClearResult:+ """Customer-facing result of clearing one replied-to owner."""++ message_ids: frozenset[str]+ tree_cleared: boolclass MessagingCommandContext(Protocol):"""Operations commands need from the messaging workflow."""outbound: OutboundMessenger- voice_cancellation: VoiceCancellation | Nonecli_manager: ManagedClaudeSessionManagerProtocoldef format_status(self, emoji: str, label: str, suffix: str | None = None) -> str:@@ -28,32 +35,28 @@ class MessagingCommandContext(Protocol):"""Stop every pending or active messaging task."""...- async def stop_task(self, scope: MessageScope, node_id: str) -> int:- """Stop one pending or active node."""- ...-- async def resolve_node_id(+ async def stop_reply(self,scope: MessageScope,- reference_id: str,- ) -> str | None:- """Resolve a node or status-message reference."""+ reply_id: str,+ ) -> int | None:+ """Stop the exact voice/tree owner of a replied-to message."""...def get_tree_count(self) -> int:"""Return the number of conversation trees."""...- async def clear_branch(+ async def clear_reply(self,scope: MessageScope,- node_id: str,- ) -> BranchRemovalResult:- """Atomically cancel, remove, and persist a conversation branch."""+ reply_id: str,+ ) -> ReplyClearResult | None:+ """Clear the exact voice/tree owner of a replied-to message."""...async def clear_all_state(self, platform: str, chat_id: str) -> frozenset[str]:- """Clear all FCC messaging state and return platform message IDs."""+ """Globally clear FCC state and return invoking-chat platform IDs."""...def forget_message_ids(@@ -76,4 +79,4 @@ class MessagingCommandContext(Protocol):...-__all__ = ["MessagingCommandContext"]+__all__ = ["MessagingCommandContext", "ReplyClearResult"]diff --git a/src/free_claude_code/messaging/commands.py b/src/free_claude_code/messaging/commands.pyindex 98f9b1a3..1df1c088 100644--- a/src/free_claude_code/messaging/commands.py+++ b/src/free_claude_code/messaging/commands.py@@ -15,10 +15,12 @@ async def handle_stop_command("""Handle /stop command from messaging platform."""# Reply-scoped stop: reply "/stop" to stop only that task.if incoming.is_reply() and incoming.reply_to_message_id:- reply_id = incoming.reply_to_message_id- node_id = await handler.resolve_node_id(incoming.scope, reply_id)+ count = await handler.stop_reply(+ incoming.scope,+ incoming.reply_to_message_id,+ )- if not node_id:+ if count is None:msg_id = await handler.outbound.queue_send_message(incoming.chat_id,handler.format_status(@@ -32,7 +34,6 @@ async def handle_stop_command()return- count = await handler.stop_task(incoming.scope, node_id)noun = "request" if count == 1 else "requests"msg_id = await handler.outbound.queue_send_message(incoming.chat_id,@@ -126,25 +127,6 @@ async def _delete_message_ids()-async def _handle_clear_branch(- handler: MessagingCommandContext,- incoming: IncomingMessage,- branch_root_id: str,-) -> None:- """- Clear a branch (replied-to node + all descendants).-- FCC state is removed and persisted before platform deletion begins.- """- result = await handler.clear_branch(incoming.scope, branch_root_id)- msg_ids = set(result.message_ids)- if incoming.message_id:- msg_ids.add(str(incoming.message_id))-- await _delete_message_ids(handler, incoming.chat_id, msg_ids)- handler.forget_message_ids(incoming.platform, incoming.chat_id, msg_ids)--async def handle_clear_command(handler: MessagingCommandContext, incoming: IncomingMessage) -> None:@@ -152,33 +134,14 @@ async def handle_clear_command(Handle /clear command.Reply-scoped: reply to a message to clear that branch (node + descendants).- Standalone: global clear (stop all, delete all chat messages, reset store).+ Standalone: global clear (stop all, reset state, delete invoking-chat history)."""if incoming.is_reply() and incoming.reply_to_message_id:- reply_id = incoming.reply_to_message_id- branch_root_id = await handler.resolve_node_id(incoming.scope, reply_id)- if not branch_root_id:- if handler.voice_cancellation is not None:- cancelled = await handler.voice_cancellation.cancel_pending_voice(- incoming.scope, reply_id- )- if cancelled is not None:- 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)- msg_id = await handler.outbound.queue_send_message(- incoming.chat_id,- handler.format_status("🗑", "Cleared.", "Voice note cancelled."),- fire_and_forget=False,- message_thread_id=incoming.message_thread_id,- )- handler.record_outgoing_message(- incoming.platform, incoming.chat_id, msg_id, "command"- )- return+ result = await handler.clear_reply(+ incoming.scope,+ incoming.reply_to_message_id,+ )+ if result is None:msg_id = await handler.outbound.queue_send_message(incoming.chat_id,handler.format_status(@@ -191,7 +154,29 @@ async def handle_clear_command(incoming.platform, incoming.chat_id, msg_id, "command")return- await _handle_clear_branch(handler, incoming, branch_root_id)++ message_ids = set(result.message_ids)+ if incoming.message_id is not None:+ message_ids.add(str(incoming.message_id))+ await _delete_message_ids(handler, incoming.chat_id, message_ids)+ handler.forget_message_ids(+ incoming.platform,+ incoming.chat_id,+ message_ids,+ )+ if not result.tree_cleared:+ msg_id = await handler.outbound.queue_send_message(+ incoming.chat_id,+ handler.format_status("🗑", "Cleared.", "Voice note cancelled."),+ fire_and_forget=False,+ message_thread_id=incoming.message_thread_id,+ )+ handler.record_outgoing_message(+ incoming.platform,+ incoming.chat_id,+ msg_id,+ "command",+ )returnmsg_ids = set(await handler.clear_all_state(incoming.platform, incoming.chat_id))diff --git a/src/free_claude_code/messaging/platforms/discord.py b/src/free_claude_code/messaging/platforms/discord.pyindex be798392..eba53331 100644--- a/src/free_claude_code/messaging/platforms/discord.py+++ b/src/free_claude_code/messaging/platforms/discord.py@@ -144,6 +144,12 @@ class DiscordRuntime:"""Cancel a pending voice transcription."""return await self._voice_flow.cancel_pending_voice(scope, reply_id)+ async def cancel_all_pending_voices(+ self,+ ) -> tuple[VoiceCancellationResult, ...]:+ """Cancel every pending voice transcription and handoff."""+ return await self._voice_flow.cancel_all_pending_voices()+async def _handle_voice_note(self, message: Any, attachment: Any, channel_id: str) -> bool:diff --git a/src/free_claude_code/messaging/platforms/ports.py b/src/free_claude_code/messaging/platforms/ports.pyindex 2b13ebee..fe398d69 100644--- a/src/free_claude_code/messaging/platforms/ports.py+++ b/src/free_claude_code/messaging/platforms/ports.py@@ -64,12 +64,16 @@ class OutboundMessenger(Protocol):@runtime_checkableclass VoiceCancellation(Protocol):- """Optional voice-note cancellation port used by /clear replies."""+ """Optional voice-note cancellation boundary used by stop/clear flows."""async def cancel_pending_voice(self, scope: MessageScope, reply_id: str) -> VoiceCancellationResult | None: ...+ async def cancel_all_pending_voices(+ self,+ ) -> tuple[VoiceCancellationResult, ...]: ...+@dataclass(frozen=True, slots=True)class MessagingPlatformComponents:diff --git a/src/free_claude_code/messaging/platforms/telegram.py b/src/free_claude_code/messaging/platforms/telegram.pyindex e61a13fc..083a6078 100644--- a/src/free_claude_code/messaging/platforms/telegram.py+++ b/src/free_claude_code/messaging/platforms/telegram.py@@ -89,6 +89,12 @@ class TelegramRuntime:"""Cancel a pending voice transcription."""return await self._voice_flow.cancel_pending_voice(scope, reply_id)+ async def cancel_all_pending_voices(+ self,+ ) -> tuple[VoiceCancellationResult, ...]:+ """Cancel every pending voice transcription and handoff."""+ return await self._voice_flow.cancel_all_pending_voices()+async def start(self) -> None:"""Initialize and connect to Telegram."""if not self.bot_token:diff --git a/src/free_claude_code/messaging/platforms/voice_flow.py b/src/free_claude_code/messaging/platforms/voice_flow.pyindex e2738971..e8053a2e 100644--- a/src/free_claude_code/messaging/platforms/voice_flow.py+++ b/src/free_claude_code/messaging/platforms/voice_flow.py@@ -18,6 +18,7 @@ from ..voice import (PendingVoiceRegistry,Transcriber,VoiceCancellationResult,+ VoiceHandoffOutcome,)AUDIO_EXTENSIONS = (".ogg", ".mp4", ".mp3", ".wav", ".m4a")@@ -127,6 +128,12 @@ class VoiceNoteFlow:"""Cancel a pending voice transcription."""return await self._pending_voice.cancel(scope, reply_id)+ async def cancel_all_pending_voices(+ self,+ ) -> tuple[VoiceCancellationResult, ...]:+ """Cancel every pending voice transcription and published handoff."""+ return await self._pending_voice.cancel_all()+async def handle(self,request: VoiceNoteRequest,@@ -150,6 +157,7 @@ class VoiceNoteFlow:return Truestatus_msg_id: str | None = None+ status_bound = Falsetmp_path: Path | None = Nonehanded_off = False@@ -165,14 +173,18 @@ class VoiceNoteFlow: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(+ status_bound = await self._pending_voice.bind_status(claim, status_msg_id)+ if not status_bound:+ _, cancellation = await self._finish_failed_pending_voice(request,claim,status_msg_id,queue_delete_messages,+ status_bound=False,handed_off=False,)+ if cancellation is not None:+ raise cancellation from Nonereturn Truewith tempfile.NamedTemporaryFile(@@ -201,48 +213,65 @@ class VoiceNoteFlow: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(++ async def handle_incoming() -> None:+ nonlocal handed_off+ handed_off = True+ await message_handler(incoming)++ handoff_outcome = await self._pending_voice.handoff(+ claim,+ handle_incoming,+ )+ if handoff_outcome is VoiceHandoffOutcome.REJECTED:+ _, cancellation = await self._finish_failed_pending_voice(request,claim,status_msg_id,queue_delete_messages,+ status_bound=status_bound,handed_off=False,)+ if cancellation is not None:+ raise cancellation from Nonereturn True- handed_off = True-- await message_handler(incoming)return Trueexcept asyncio.CancelledError:- await self._clear_failed_pending_voice(+ await self._finish_failed_pending_voice(request,claim,status_msg_id,queue_delete_messages,+ status_bound=status_bound,handed_off=handed_off,)raiseexcept (ValueError, ImportError) as e:- discarded = await self._clear_failed_pending_voice(+ discarded, cancellation = await self._finish_failed_pending_voice(request,claim,status_msg_id,queue_delete_messages,+ status_bound=status_bound,handed_off=handed_off,)+ if cancellation is not None:+ raise cancellation from Noneif not handed_off and not discarded:return Trueawait request.reply_text(format_user_error_preview(e))return Trueexcept Exception as e:- discarded = await self._clear_failed_pending_voice(+ discarded, cancellation = await self._finish_failed_pending_voice(request,claim,status_msg_id,queue_delete_messages,+ status_bound=status_bound,handed_off=handed_off,)+ if cancellation is not None:+ raise cancellation from Noneif not handed_off and not discarded:return Trueif self._log_api_error_tracebacks:@@ -254,11 +283,54 @@ class VoiceNoteFlow:)await request.reply_text(VOICE_TRANSCRIPTION_ERROR_MESSAGE)return True+ except BaseException:+ await self._finish_failed_pending_voice(+ request,+ claim,+ status_msg_id,+ queue_delete_messages,+ status_bound=status_bound,+ handed_off=handed_off,+ )+ raisefinally:if tmp_path is not None:with contextlib.suppress(OSError):tmp_path.unlink(missing_ok=True)+ async def _finish_failed_pending_voice(+ self,+ request: VoiceNoteRequest,+ claim: PendingVoiceClaim,+ status_msg_id: str | None,+ queue_delete_messages: QueueDeleteMany,+ *,+ status_bound: bool,+ handed_off: bool,+ ) -> tuple[bool, asyncio.CancelledError | None]:+ """Finish owned cleanup before propagating any caller cancellation."""+ cleanup_task = asyncio.create_task(+ self._clear_failed_pending_voice(+ request,+ claim,+ status_msg_id,+ queue_delete_messages,+ status_bound=status_bound,+ handed_off=handed_off,+ ),+ name=f"voice-cleanup-{claim.claim_id}",+ )+ cancellation: asyncio.CancelledError | None = None+ current = asyncio.current_task()+ while True:+ cancelling_before = current.cancelling() if current is not None else 0+ try:+ return await asyncio.shield(cleanup_task), cancellation+ except asyncio.CancelledError as error:+ if current is None or current.cancelling() <= cancelling_before:+ raise+ cancellation = cancellation or error+async def _clear_failed_pending_voice(self,request: VoiceNoteRequest,@@ -266,10 +338,15 @@ class VoiceNoteFlow:status_msg_id: str | None,queue_delete_messages: QueueDeleteMany,*,+ status_bound: bool,handed_off: bool,) -> bool:discarded = await self._pending_voice.discard(claim)- if not handed_off and status_msg_id is not None:+ if (+ not handed_off+ and status_msg_id is not None+ and (discarded or not status_bound)+ ):with contextlib.suppress(Exception):await queue_delete_messages(request.chat_id, [status_msg_id])return discardeddiff --git a/src/free_claude_code/messaging/voice.py b/src/free_claude_code/messaging/voice.pyindex 4c5112cf..b2e993da 100644--- a/src/free_claude_code/messaging/voice.py+++ b/src/free_claude_code/messaging/voice.py@@ -1,7 +1,10 @@"""Platform-neutral voice note helpers."""import asyncio+from collections.abc import Awaitable, Callable+from contextvars import ContextVarfrom dataclasses import dataclass+from enum import Enumfrom pathlib import Pathfrom typing import Protocolfrom uuid import uuid4@@ -9,6 +12,24 @@ from uuid import uuid4from .models import MessageScope+async def _await_owned_task[T](+ task: asyncio.Task[T],+) -> tuple[T, asyncio.CancelledError | None]:+ """Finish an owned task before returning any caller cancellation."""+ cancellation: asyncio.CancelledError | None = None+ current = asyncio.current_task()+ while True:+ cancelling_before = current.cancelling() if current is not None else 0+ try:+ return await asyncio.shield(task), cancellation+ except asyncio.CancelledError as exc:+ if current is None or (+ current.cancelling() <= cancelling_before and task.done()+ ):+ raise+ cancellation = cancellation or exc++class Transcriber(Protocol):"""Consumer-owned voice transcription boundary."""@@ -26,18 +47,42 @@ class PendingVoiceClaim:claim_id: str+_current_voice_claim: ContextVar[PendingVoiceClaim | None] = ContextVar(+ "current_voice_claim",+ default=None,+)+++class VoiceHandoffOutcome(Enum):+ """Exclusive outcome of publishing one transcribed voice message."""++ REJECTED = "rejected"+ COMPLETED = "completed"+ CANCELLED = "cancelled"++@dataclass(frozen=True, slots=True)class VoiceCancellationResult:"""Message IDs released by one successful voice cancellation."""+ scope: MessageScopevoice_message_id: strstatus_message_id: str | None+ @property+ def message_ids(self) -> frozenset[str]:+ """Return each platform message ID owned by the cancelled voice note."""+ ids = {self.voice_message_id}+ if self.status_message_id is not None:+ ids.add(self.status_message_id)+ return frozenset(ids)+@dataclass(slots=True)class _PendingVoice:claim: PendingVoiceClaimstatus_message_id: str | None = None+ handoff_task: asyncio.Task[None] | None = Noneclass PendingVoiceRegistry:@@ -46,6 +91,7 @@ class PendingVoiceRegistry:def __init__(self) -> None:self._pending: dict[tuple[MessageScope, str], _PendingVoice] = {}self._lock = asyncio.Lock()+ self._active_cancellations: dict[PendingVoiceClaim, int] = {}async def reserve(self,@@ -83,13 +129,61 @@ class PendingVoiceRegistry:self._pending[status_key] = entryreturn True- async def claim_for_handoff(self, claim: PendingVoiceClaim) -> bool:+ async def handoff(+ self,+ claim: PendingVoiceClaim,+ callback: Callable[[], Awaitable[None]],+ ) -> VoiceHandoffOutcome:+ """Run a published handoff while retaining its cancellable ownership."""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+ if (+ entry is None+ or entry.status_message_id is None+ or entry.handoff_task is not None+ ):+ return VoiceHandoffOutcome.REJECTED+ task = asyncio.create_task(+ self._run_callback(claim, callback),+ name=f"voice-handoff-{claim.claim_id}",+ )+ entry.handoff_task = task++ current = asyncio.current_task()+ cancelling_before = current.cancelling() if current is not None else 0+ try:+ await asyncio.shield(task)+ except BaseException as error:+ caller_cancelled = (+ isinstance(error, asyncio.CancelledError)+ and current is not None+ and (current.cancelling() > cancelling_before or not task.done())+ )+ if caller_cancelled:+ task.cancel()+ child_error: BaseException | None = None+ try:+ await self._drain((task,))+ except BaseException as drained_error:+ child_error = drained_error+ await self._finish_ownership(entry)+ if child_error is not None:+ raise child_error from None+ raise error from None++ completed, cancellation = await self._finish_ownership(entry)+ if cancellation is not None and not self._is_fatal(error):+ raise cancellation from None+ if completed or self._is_fatal(error):+ raise error+ return VoiceHandoffOutcome.CANCELLED++ completed, cancellation = await self._finish_ownership(entry)+ if cancellation is not None:+ raise cancellation+ if completed:+ return VoiceHandoffOutcome.COMPLETED+ return VoiceHandoffOutcome.CANCELLEDasync def discard(self, claim: PendingVoiceClaim) -> bool:async with self._lock:@@ -97,20 +191,134 @@ class PendingVoiceRegistry:if entry is None:return Falseself._remove(entry)- return True+ task = entry.handoff_task+ cancellation = await self._cancel_and_drain(task)+ if cancellation is not None:+ raise cancellation+ return Trueasync def cancel(self, scope: MessageScope, reply_id: str) -> VoiceCancellationResult | None:+ current_claim = _current_voice_claim.get()+ self._protect_claim(current_claim)+ try:+ async with self._lock:+ entry = self._pending.get((scope, reply_id))+ if entry is None or self._is_excluded(entry, current_claim):+ return None+ self._remove(entry)+ task = entry.handoff_task+ result = self._cancellation_result(entry)+ cancellation = await self._cancel_and_drain(task)+ if cancellation is not None:+ raise cancellation+ return result+ finally:+ self._unprotect_claim(current_claim)++ async def cancel_all(self) -> tuple[VoiceCancellationResult, ...]:+ """Cancel every unique pending voice note and drain published handoffs."""+ current_claim = _current_voice_claim.get()+ self._protect_claim(current_claim)+ try:+ async with self._lock:+ entries = tuple(+ {+ entry.claim: entry+ for entry in self._pending.values()+ if not self._is_excluded(entry, current_claim)+ }.values()+ )+ for entry in entries:+ self._remove(entry)++ tasks = tuple(+ task for entry in entries if (task := entry.handoff_task) is not None+ )+ for task in tasks:+ task.cancel()+ cancellation = await self._drain(tasks)+ if cancellation is not None:+ raise cancellation+ return tuple(self._cancellation_result(entry) for entry in entries)+ finally:+ self._unprotect_claim(current_claim)++ async def _finish_ownership(+ self,+ entry: _PendingVoice,+ ) -> tuple[bool, asyncio.CancelledError | None]:+ finish_task = asyncio.create_task(+ self._complete_if_owned(entry),+ name=f"voice-handoff-finish-{entry.claim.claim_id}",+ )+ return await _await_owned_task(finish_task)++ async def _complete_if_owned(self, entry: _PendingVoice) -> bool:async with self._lock:- entry = self._pending.get((scope, reply_id))- if entry is None:- return None+ if self._entry_for_claim(entry.claim) is not entry:+ return Falseself._remove(entry)- return VoiceCancellationResult(- voice_message_id=entry.claim.voice_message_id,- status_message_id=entry.status_message_id,- )+ return True++ @staticmethod+ async def _run_callback(+ claim: PendingVoiceClaim,+ callback: Callable[[], Awaitable[None]],+ ) -> None:+ token = _current_voice_claim.set(claim)+ try:+ await callback()+ finally:+ _current_voice_claim.reset(token)++ @staticmethod+ async def _cancel_and_drain(+ task: asyncio.Task[None] | None,+ ) -> asyncio.CancelledError | None:+ if task is None or task is asyncio.current_task():+ return None+ task.cancel()+ return await PendingVoiceRegistry._drain((task,))++ @staticmethod+ async def _drain(+ tasks: tuple[asyncio.Task[None], ...],+ ) -> asyncio.CancelledError | None:+ if not tasks:+ return None+ drain_task = asyncio.create_task(+ PendingVoiceRegistry._consume_results(tasks),+ name="voice-handoff-drain",+ )+ _, cancellation = await _await_owned_task(drain_task)+ return cancellation++ @staticmethod+ async def _consume_results(tasks: tuple[asyncio.Task[None], ...]) -> None:+ fatal_error: BaseException | None = None+ for task in tasks:+ try:+ await task+ except asyncio.CancelledError, Exception:+ continue+ except BaseException as error:+ fatal_error = fatal_error or error+ if fatal_error is not None:+ raise fatal_error++ @staticmethod+ def _is_fatal(error: BaseException) -> bool:+ return not isinstance(error, (asyncio.CancelledError, Exception))++ @staticmethod+ def _cancellation_result(entry: _PendingVoice) -> VoiceCancellationResult:+ return VoiceCancellationResult(+ scope=entry.claim.scope,+ voice_message_id=entry.claim.voice_message_id,+ status_message_id=entry.status_message_id,+ )def _entry_for_claim(self, claim: PendingVoiceClaim) -> _PendingVoice | None:entry = self._pending.get((claim.scope, claim.voice_message_id))@@ -118,6 +326,30 @@ class PendingVoiceRegistry:return Nonereturn entry+ def _is_excluded(+ self,+ entry: _PendingVoice,+ current_claim: PendingVoiceClaim | None,+ ) -> bool:+ return (+ entry.claim == current_claim+ or self._active_cancellations.get(entry.claim, 0) > 0+ )++ def _protect_claim(self, claim: PendingVoiceClaim | None) -> None:+ if claim is None:+ return+ self._active_cancellations[claim] = self._active_cancellations.get(claim, 0) + 1++ def _unprotect_claim(self, claim: PendingVoiceClaim | None) -> None:+ if claim is None:+ return+ remaining = self._active_cancellations[claim] - 1+ if remaining:+ self._active_cancellations[claim] = remaining+ else:+ self._active_cancellations.pop(claim)+def _remove(self, entry: _PendingVoice) -> None:voice_key = (entry.claim.scope, entry.claim.voice_message_id)if self._pending.get(voice_key) is entry:diff --git a/src/free_claude_code/messaging/workflow.py b/src/free_claude_code/messaging/workflow.pyindex d48e0b5a..9bc4c62b 100644--- a/src/free_claude_code/messaging/workflow.py+++ b/src/free_claude_code/messaging/workflow.py@@ -1,11 +1,14 @@"""Messaging workflow coordinator for Discord and Telegram prompts."""import asyncio+from collections.abc import Coroutine+from typing import Anyfrom loguru import loggerfrom free_claude_code.core.trace import trace_event+from .command_context import ReplyClearResultfrom .managed_protocols import ManagedClaudeSessionManagerProtocolfrom .models import IncomingMessage, MessageScopefrom .node_runner import MessagingNodeRunner@@ -15,7 +18,6 @@ from .safe_diagnostics import format_exception_for_logfrom .session import SessionStorefrom .transcript import RenderCtxfrom .trees import (- BranchRemovalResult,CancellationReason,CancellationResult,CancellationUiOwner,@@ -27,6 +29,33 @@ from .trees import (TreeQueueManager,)from .turn_intake import MessagingTurnIntake+from .voice import VoiceCancellationResult+++async def _finish_owned_operation[T](+ operation: Coroutine[Any, Any, T],+ *,+ name: str,+) -> T:+ """Finish owned work, preserving its failures before caller cancellation."""+ task = asyncio.create_task(operation, name=name)+ current = asyncio.current_task()+ cancellation: asyncio.CancelledError | None = None+ while not task.done():+ try:+ await asyncio.shield(task)+ except asyncio.CancelledError as exc:+ if current is not None and current.cancelling():+ cancellation = cancellation or exc+ except Exception:+ break++ # Task.result() raises the owned operation's failure. Caller cancellation+ # is restored only after successful completion.+ result = task.result()+ if cancellation is not None:+ raise cancellation+ return resultclass MessagingWorkflow:@@ -202,81 +231,167 @@ class MessagingWorkflow:parent_node_id: str | None,admission_epoch: int,) -> QueueDecision | None:- async with self._state_lock:- if admission_epoch != self._admission_epoch:- return None- return await self._admit_locked(+ return await _finish_owned_operation(+ self._admit_if_current(incoming,status_message_id,parent_node_id,- )+ admission_epoch,+ ),+ name=f"messaging-admit-{incoming.message_id}",+ )- async def _admit_locked(+ async def _admit_if_current(self,incoming: IncomingMessage,status_message_id: str,parent_node_id: str | None,- ) -> QueueDecision:- """Admit while the workflow caller owns the state transaction lock."""- decision = await self._tree_queue.admit(- incoming,- status_message_id,- parent_node_id=parent_node_id,- )- if decision.snapshot is not None:- self.session_store.save_tree_snapshot(decision.snapshot)- return decision-- async def resolve_node_id(- self,- scope: MessageScope,- reference_id: str,- ) -> str | None:- return await self._tree_queue.resolve_node_id(scope, reference_id)+ admission_epoch: int,+ ) -> QueueDecision | None:+ """Commit admission and its exact snapshot as one owned transaction."""+ async with self._state_lock:+ if admission_epoch != self._admission_epoch:+ return None+ decision = await self._tree_queue.admit(+ incoming,+ status_message_id,+ parent_node_id=parent_node_id,+ )+ if decision.snapshot is not None:+ self.session_store.save_tree_snapshot(decision.snapshot)+ return decisiondef get_tree_count(self) -> int:return self._tree_queue.get_tree_count()- async def stop_all_tasks(self) -> int:- """Stop every pending and active messaging task."""- async with self._state_lock:- self._admission_epoch += 1- logger.info("Cancelling tree queue tasks...")- result = await self._tree_queue.cancel_all(reason=CancellationReason.STOP)- logger.info("Cancelled {} nodes", len(result.effects))- self._apply_cancellation_result(result)- logger.info("Stopping all CLI sessions...")- await self.cli_manager.stop_all()- return len(result.effects)+ async def stop_reply(+ self,+ scope: MessageScope,+ reply_id: str,+ ) -> int | None:+ """Stop the exact voice/tree owner of one replied-to message."""+ return await _finish_owned_operation(+ self._stop_reply(scope, reply_id),+ name=f"messaging-stop-reply-{reply_id}",+ )++ async def _stop_reply(+ self,+ scope: MessageScope,+ reply_id: str,+ ) -> int | None:+ voice_result = await self._cancel_pending_voice(scope, reply_id)+ if voice_result is not None:+ self.render_voice_stopped(voice_result)- async def stop_task(self, scope: MessageScope, node_id: str) -> int:- """Stop one queued or active task."""async with self._state_lock:+ node_id = await self._tree_queue.resolve_node_id(scope, reply_id)+ if node_id is None:+ return 1 if voice_result is not None else Noneresult = await self._tree_queue.cancel_node(scope,node_id,reason=CancellationReason.STOP,)self._apply_cancellation_result(result)- return len(result.effects)- async def clear_branch(+ owners = {(effect.node.scope, effect.node.node_id) for effect in result.effects}+ if voice_result is not None:+ owners.add((voice_result.scope, voice_result.voice_message_id))+ return len(owners)++ async def clear_reply(+ self,+ scope: MessageScope,+ reply_id: str,+ ) -> ReplyClearResult | None:+ """Clear the exact voice/tree owner of one replied-to message."""+ return await _finish_owned_operation(+ self._clear_reply(scope, reply_id),+ name=f"messaging-clear-reply-{reply_id}",+ )++ async def _clear_reply(self,scope: MessageScope,- node_id: str,- ) -> BranchRemovalResult:- """Cancel, detach, and persist a branch before platform deletion."""+ reply_id: str,+ ) -> ReplyClearResult | None:+ voice_result = await self._cancel_pending_voice(scope, reply_id)+ if voice_result is not None:+ self.render_voice_stopped(voice_result)+async with self._state_lock:- result = await self._tree_queue.remove_branch(scope, node_id)- self._apply_cancellation_result(result.cancellation)- if result.removed_tree_identity is not None:- self.session_store.remove_tree_snapshot(result.removed_tree_identity)- return result+ node_id = await self._tree_queue.resolve_node_id(scope, reply_id)+ if node_id is None:+ if voice_result is None:+ return None+ return ReplyClearResult(+ message_ids=voice_result.message_ids,+ tree_cleared=False,+ )++ branch = await self._tree_queue.remove_branch(scope, node_id)+ self._apply_cancellation_result(branch.cancellation)+ if branch.removed_tree_identity is not None:+ self.session_store.remove_tree_snapshot(branch.removed_tree_identity)++ message_ids = set(branch.message_ids)+ if voice_result is not None:+ message_ids.update(voice_result.message_ids)+ return ReplyClearResult(+ message_ids=frozenset(message_ids),+ tree_cleared=True,+ )++ async def stop_all_tasks(self) -> int:+ """Stop every pending and active messaging task."""+ return await _finish_owned_operation(+ self._stop_all_tasks(),+ name="messaging-stop-all",+ )++ async def _stop_all_tasks(self) -> int:+ voice_results = await self._cancel_all_pending_voices()+ for voice in voice_results:+ self.render_voice_stopped(voice)+ async with self._state_lock:+ self._admission_epoch += 1+ logger.info("Cancelling tree queue tasks...")+ result = await self._tree_queue.cancel_all(reason=CancellationReason.STOP)+ logger.info("Cancelled {} nodes", len(result.effects))+ self._apply_cancellation_result(result)+ logger.info("Stopping all CLI sessions...")+ await self.cli_manager.stop_all()+ tree_keys = {+ (effect.node.scope, effect.node.node_id) for effect in result.effects+ }+ voice_keys = {+ (voice.scope, voice.voice_message_id) for voice in voice_results+ }+ return len(tree_keys | voice_keys)async def clear_all_state(self, platform: str, chat_id: str) -> frozenset[str]:"""Clear FCC state atomically with respect to later turn admission."""+ return await _finish_owned_operation(+ self._clear_all_state(platform, chat_id),+ name="messaging-clear-all",+ )++ async def _clear_all_state(+ self,+ platform: str,+ chat_id: str,+ ) -> frozenset[str]:+ """Globally reset FCC state; return deletion IDs for the invoking chat."""+ voice_results = await self._cancel_all_pending_voices()+ for voice in voice_results:+ self.render_voice_stopped(voice)async with self._state_lock:message_ids: set[str] = set()+ clear_scope = MessageScope(platform=platform, chat_id=chat_id)+ for voice in voice_results:+ if voice.scope == clear_scope:+ message_ids.update(voice.message_ids)try:message_ids.update(str(message_id)@@ -336,6 +451,37 @@ class MessagingWorkflow:raise ExceptionGroup("Global clear failed", failures)return frozenset(message_ids)+ async def _cancel_all_pending_voices(+ self,+ ) -> tuple[VoiceCancellationResult, ...]:+ cancellation = self.voice_cancellation+ if cancellation is None:+ return ()+ return await cancellation.cancel_all_pending_voices()++ async def _cancel_pending_voice(+ self,+ scope: MessageScope,+ reply_id: str,+ ) -> VoiceCancellationResult | None:+ cancellation = self.voice_cancellation+ if cancellation is None:+ return None+ return await cancellation.cancel_pending_voice(scope, reply_id)++ def render_voice_stopped(self, result: VoiceCancellationResult) -> None:+ """Publish terminal UI for a voice cancelled before tree ownership."""+ if result.status_message_id is None:+ return+ self.outbound.fire_and_forget(+ self.outbound.queue_edit_message(+ result.scope.chat_id,+ result.status_message_id,+ self.format_status("⏹", "Stopped."),+ parse_mode=self._parse_mode(),+ )+ )+def forget_message_ids(self,platform: str,diff --git a/tests/conftest.py b/tests/conftest.pyindex a0736870..9f799cbe 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -127,6 +127,7 @@ def mock_platform():platform.queue_edit_message = AsyncMock()platform.queue_delete_messages = AsyncMock()platform.cancel_pending_voice = AsyncMock(return_value=None)+ platform.cancel_all_pending_voices = AsyncMock(return_value=())def _fire_and_forget(task):if asyncio.iscoroutine(task):diff --git a/tests/messaging/test_handler.py b/tests/messaging/test_handler.pyindex 66b5ee6d..7e17b7e4 100644--- a/tests/messaging/test_handler.py+++ b/tests/messaging/test_handler.py@@ -3,9 +3,11 @@ from unittest.mock import AsyncMock, MagicMock, call, patchimport pytest+from free_claude_code.messaging.command_context import ReplyClearResultfrom free_claude_code.messaging.models import MessageScopefrom free_claude_code.messaging.session import SessionStorefrom free_claude_code.messaging.trees import (+ BranchRemovalResult,CancellationReason,CancellationResult,CancellationUiOwner,@@ -160,8 +162,7 @@ async def test_failed_global_stop_never_reports_success(async def test_reply_stop_resolves_and_stops_only_target(handler, mock_platform, mock_cli_manager, incoming_message_factory):- handler.resolve_node_id = AsyncMock(return_value="root_msg")- handler.stop_task = AsyncMock(return_value=1)+ handler.stop_reply = AsyncMock(return_value=1)handler.stop_all_tasks = AsyncMock(return_value=999)incoming = incoming_message_factory(text="/stop",@@ -171,8 +172,7 @@ async def test_reply_stop_resolves_and_stops_only_target(await handler.handle_message(incoming)- handler.resolve_node_id.assert_awaited_once_with(incoming.scope, "status_root")- handler.stop_task.assert_awaited_once_with(incoming.scope, "root_msg")+ handler.stop_reply.assert_awaited_once_with(incoming.scope, "status_root")handler.stop_all_tasks.assert_not_awaited()mock_cli_manager.stop_all.assert_not_awaited()assert "Cancelled 1 request" in mock_platform.queue_send_message.call_args.args[1]@@ -182,7 +182,7 @@ async def test_reply_stop_resolves_and_stops_only_target(async def test_reply_stop_unknown_does_not_stop_all(handler, mock_platform, mock_cli_manager, incoming_message_factory):- handler.resolve_node_id = AsyncMock(return_value=None)+ handler.stop_reply = AsyncMock(return_value=None)handler.stop_all_tasks = AsyncMock(return_value=5)incoming = incoming_message_factory(text="/stop",@@ -192,6 +192,7 @@ async def test_reply_stop_unknown_does_not_stop_all(await handler.handle_message(incoming)+ handler.stop_reply.assert_awaited_once_with(incoming.scope, "unknown_msg")handler.stop_all_tasks.assert_not_awaited()mock_cli_manager.stop_all.assert_not_awaited()assert (@@ -200,6 +201,217 @@ async def test_reply_stop_unknown_does_not_stop_all()+async def test_reply_stop_cancels_voice_when_no_tree_was_admitted(+ handler,+ mock_platform,+ incoming_message_factory,+) -> None:+ mock_platform.cancel_pending_voice.return_value = VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )+ incoming = incoming_message_factory(+ text="/stop",+ message_id="stop_msg",+ reply_to_message_id="voice",+ )++ await handler.handle_message(incoming)+ await asyncio.sleep(0)++ assert "Cancelled 1 request" in mock_platform.queue_send_message.call_args.args[1]+ assert mock_platform.queue_edit_message.call_args.args[1] == "voice_status"+ assert "Stopped" in mock_platform.queue_edit_message.call_args.args[2]+++async def test_reply_stop_resolves_tree_after_joining_voice_handoff(+ handler,+ mock_platform,+ incoming_message_factory,+) -> None:+ events: list[str] = []++ async def cancel_voice(*_args) -> VoiceCancellationResult:+ events.append("voice")+ return VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )++ async def resolve_tree(*_args) -> str:+ events.append("tree")+ return "voice"++ mock_platform.cancel_pending_voice.side_effect = cancel_voice+ cancellation = CancellationResult(+ effects=(+ CancellationEffect(+ node=NodeUiTarget(+ scope=_SCOPE,+ node_id="voice",+ status_message_id="voice_status",+ ),+ ui_owner=CancellationUiOwner.WORKFLOW,+ ),+ )+ )+ incoming = incoming_message_factory(+ text="/stop",+ message_id="stop_msg",+ reply_to_message_id="voice",+ )++ with (+ patch.object(+ handler.tree_queue,+ "resolve_node_id",+ side_effect=resolve_tree,+ ),+ patch.object(+ handler.tree_queue,+ "cancel_node",+ new_callable=AsyncMock,+ return_value=cancellation,+ ) as cancel_node,+ ):+ await handler.handle_message(incoming)++ cancel_node.assert_awaited_once_with(+ incoming.scope,+ "voice",+ reason=CancellationReason.STOP,+ )+ assert events == ["voice", "tree"]+ assert "Nothing to stop" not in mock_platform.queue_send_message.call_args.args[1]+ assert "Cancelled 1 request" in mock_platform.queue_send_message.call_args.args[1]+++async def test_reply_stop_port_failure_prevents_tree_transition(+ handler,+ mock_platform,+) -> None:+ mock_platform.cancel_pending_voice.side_effect = RuntimeError("voice port failed")+ with (+ patch.object(+ handler.tree_queue,+ "resolve_node_id",+ new_callable=AsyncMock,+ ) as resolve,+ pytest.raises(RuntimeError, match="voice port failed"),+ ):+ await handler.stop_reply(_SCOPE, "voice")++ resolve.assert_not_awaited()+ mock_platform.queue_edit_message.assert_not_awaited()+++async def test_reply_stop_renders_voice_before_resolve_failure(+ handler,+ mock_platform,+) -> None:+ mock_platform.cancel_pending_voice.return_value = VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )+ with (+ patch.object(+ handler.tree_queue,+ "resolve_node_id",+ AsyncMock(side_effect=RuntimeError("resolve failed")),+ ),+ pytest.raises(RuntimeError, match="resolve failed"),+ ):+ await handler.stop_reply(_SCOPE, "voice")+ await asyncio.sleep(0)++ mock_platform.queue_edit_message.assert_awaited_once()+ assert mock_platform.queue_edit_message.call_args.args[1] == "voice_status"+++async def test_cancelled_reply_stop_finishes_after_voice_join_and_lock_wait(+ handler,+ mock_platform,+) -> None:+ voice_returned = asyncio.Event()++ async def cancel_voice(*_args) -> VoiceCancellationResult:+ voice_returned.set()+ return VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )++ mock_platform.cancel_pending_voice.side_effect = cancel_voice+ resolve = AsyncMock(return_value=None)+ await handler._state_lock.acquire()+ try:+ with patch.object(handler.tree_queue, "resolve_node_id", resolve):+ stop_task = asyncio.create_task(handler.stop_reply(_SCOPE, "voice"))+ await voice_returned.wait()+ await asyncio.sleep(0)+ stop_task.cancel()+ stop_task.cancel()+ await asyncio.sleep(0)++ assert not stop_task.done()+ handler._state_lock.release()+ with pytest.raises(asyncio.CancelledError):+ await stop_task+ finally:+ if handler._state_lock.locked():+ handler._state_lock.release()+ await asyncio.sleep(0)++ assert stop_task.cancelling() == 2+ resolve.assert_awaited_once_with(_SCOPE, "voice")+ mock_platform.queue_edit_message.assert_awaited_once()+ assert mock_platform.queue_edit_message.call_args.args[1] == "voice_status"+++async def test_cancelled_reply_stop_preserves_later_operation_failure(+ handler,+ mock_platform,+) -> None:+ voice_returned = asyncio.Event()+ failure = RuntimeError("resolve failed after cancellation")++ async def cancel_voice(*_args) -> None:+ voice_returned.set()++ mock_platform.cancel_pending_voice.side_effect = cancel_voice+ resolve = AsyncMock(side_effect=failure)+ await handler._state_lock.acquire()+ try:+ with patch.object(handler.tree_queue, "resolve_node_id", resolve):+ stop_task = asyncio.create_task(handler.stop_reply(_SCOPE, "voice"))+ await voice_returned.wait()+ await asyncio.sleep(0)+ stop_task.cancel()+ await asyncio.sleep(0)++ assert not stop_task.done()+ handler._state_lock.release()+ with pytest.raises(RuntimeError) as raised:+ await stop_task+ finally:+ if handler._state_lock.locked():+ handler._state_lock.release()++ assert raised.value is failure+ assert stop_task.cancelling() == 1+ resolve.assert_awaited_once_with(_SCOPE, "voice")++@pytest.mark.asyncioasync def test_stats_command_reports_cli_and_tree_counts(handler, mock_platform, mock_cli_manager, incoming_message_factory@@ -414,6 +626,76 @@ async def test_stop_all_applies_immutable_ui_ownership_and_snapshots(mock_session_store.save_tree_snapshot.assert_called_once_with(snapshot)+async def test_stop_all_joins_voices_before_tree_transaction_and_deduplicates(+ handler,+ mock_cli_manager,+ mock_platform,+) -> None:+ events: list[str] = []+ voice = VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )+ tree_result = CancellationResult(+ effects=(+ CancellationEffect(+ node=NodeUiTarget(+ scope=_SCOPE,+ node_id="voice",+ status_message_id="voice_status",+ ),+ ui_owner=CancellationUiOwner.RUNNER,+ ),+ )+ )++ async def cancel_voices() -> tuple[VoiceCancellationResult, ...]:+ assert not handler._state_lock.locked()+ events.append("voices")+ return (voice,)++ async def cancel_trees(*, reason: CancellationReason) -> CancellationResult:+ assert reason is CancellationReason.STOP+ assert handler._state_lock.locked()+ events.append("trees")+ return tree_result++ mock_platform.cancel_all_pending_voices.side_effect = cancel_voices+ with patch.object(handler.tree_queue, "cancel_all", side_effect=cancel_trees):+ count = await handler.stop_all_tasks()+ await asyncio.sleep(0)++ assert count == 1+ assert events == ["voices", "trees"]+ mock_cli_manager.stop_all.assert_awaited_once()+ mock_platform.queue_edit_message.assert_awaited_once()+ assert mock_platform.queue_edit_message.call_args.args[1] == "voice_status"+++async def test_stop_all_voice_join_failure_prevents_false_transition(+ handler,+ mock_cli_manager,+ mock_platform,+) -> None:+ mock_platform.cancel_all_pending_voices.side_effect = RuntimeError(+ "voice handoff cleanup failed"+ )++ with (+ patch.object(+ handler.tree_queue, "cancel_all", new_callable=AsyncMock+ ) as cancel,+ pytest.raises(RuntimeError, match="voice handoff cleanup failed"),+ ):+ await handler.stop_all_tasks()++ cancel.assert_not_awaited()+ mock_cli_manager.stop_all.assert_not_awaited()++@pytest.mark.asyncioasync def test_stop_all_persists_committed_transition_before_cli_shutdown(handler,@@ -421,12 +703,13 @@ async def test_stop_all_persists_committed_transition_before_cli_shutdown(mock_session_store,):shutdown_started = asyncio.Event()+ release_shutdown = asyncio.Event()snapshot = _snapshot()result = CancellationResult(snapshots=(snapshot,))async def block_shutdown() -> None:shutdown_started.set()- await asyncio.Event().wait()+ await release_shutdown.wait()mock_cli_manager.stop_all.side_effect = block_shutdownwith patch.object(@@ -439,8 +722,13 @@ async def test_stop_all_persists_committed_transition_before_cli_shutdown(mock_session_store.save_tree_snapshot.assert_called_once_with(snapshot)stop_task.cancel()+ stop_task.cancel()+ await asyncio.sleep(0)+ assert not stop_task.done()+ release_shutdown.set()with pytest.raises(asyncio.CancelledError):await stop_task+ assert stop_task.cancelling() == 2@pytest.mark.asyncio@@ -948,6 +1236,53 @@ async def test_clear_all_state_is_chat_scoped_for_deletes_and_global_for_fcc_stamock_session_store.clear_all.assert_called_once()+async def test_clear_all_joins_voices_before_lock_and_returns_only_current_chat_ids(+ handler,+ mock_platform,+ mock_session_store,+) -> None:+ events: list[str] = []+ current = VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )+ other = VoiceCancellationResult(+ scope=MessageScope(platform="telegram", chat_id="other"),+ voice_message_id="other_voice",+ status_message_id="other_status",+ )++ async def cancel_voices() -> tuple[VoiceCancellationResult, ...]:+ assert not handler._state_lock.locked()+ events.append("voices")+ return (current, other)++ async def clear_trees(*, reason: CancellationReason) -> CancellationResult:+ assert reason is CancellationReason.STOP+ assert handler._state_lock.locked()+ events.append("trees")+ return CancellationResult()++ mock_platform.cancel_all_pending_voices.side_effect = cancel_voices+ mock_session_store.get_message_ids_for_chat.return_value = ["stored"]+ with patch.object(handler.tree_queue, "clear_all", side_effect=clear_trees):+ message_ids = await handler.clear_all_state("telegram", "chat_1")+ await asyncio.sleep(0)++ assert events == ["voices", "trees"]+ assert message_ids == frozenset({"stored", "voice", "voice_status"})+ assert "other_voice" not in message_ids+ assert "other_status" not in message_ids+ assert {+ call.args[1] for call in mock_platform.queue_edit_message.call_args_list+ } == {+ "voice_status",+ "other_status",+ }++@pytest.mark.asyncioasync def test_global_clear_retries_transient_early_persistence_failure_at_final_write(handler,@@ -1120,7 +1455,7 @@ async def test_committed_global_clear_attempts_remaining_steps_after_tree_failur@pytest.mark.asyncio-async def test_cancelled_global_clear_before_commit_preserves_tree_and_store(+async def test_cancelled_global_clear_finishes_owned_transaction_before_propagating(handler,mock_cli_manager,mock_session_store,@@ -1129,13 +1464,13 @@ async def test_cancelled_global_clear_before_commit_preserves_tree_and_store(root = incoming_message_factory(text="work", message_id="100")await handler.tree_queue.admit(root, "101")await _wait_for_idle(handler)- initial_epoch = handler._admission_epochid_read_started = asyncio.Event()+ release_id_read = asyncio.Event()async def block_id_read(platform: str, chat_id: str) -> set[str]:id_read_started.set()- await asyncio.Future()- raise AssertionError("unreachable")+ await release_id_read.wait()+ return {"100", "101"}mock_session_store.reset_mock()with patch.object(@@ -1148,14 +1483,17 @@ async def test_cancelled_global_clear_before_commit_preserves_tree_and_store()await id_read_started.wait()clear_task.cancel()+ await asyncio.sleep(0)+ assert not clear_task.done()+ release_id_read.set()with pytest.raises(asyncio.CancelledError):await clear_task- assert handler._admission_epoch == initial_epoch- assert handler.get_tree_count() == 1- mock_session_store.clear_all.assert_not_called()- mock_session_store.clear_conversation_snapshot.assert_not_called()- mock_cli_manager.stop_all.assert_not_awaited()+ assert handler._admission_epoch == 1+ assert handler.get_tree_count() == 0+ mock_session_store.clear_all.assert_called_once()+ mock_session_store.clear_conversation_snapshot.assert_called_once()+ mock_cli_manager.stop_all.assert_awaited_once()@pytest.mark.asyncio@@ -1456,9 +1794,14 @@ async def test_reply_clear_pending_voice_cancels_and_reports(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,+ message_ids = {"100"}+ if status_message_id is not None:+ message_ids.add(status_message_id)+ handler.clear_reply = AsyncMock(+ return_value=ReplyClearResult(+ message_ids=frozenset(message_ids),+ tree_cleared=False,+ ))deleted_ids: list[str] = []@@ -1474,6 +1817,132 @@ 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")+ handler.clear_reply.assert_awaited_once_with(incoming.scope, "100")assert set(deleted_ids) == expected_deleted_idsassert "Voice note cancelled" in mock_platform.queue_send_message.call_args.args[1]+++async def test_reply_clear_deletes_owned_result_ids(+ handler,+ mock_platform,+ incoming_message_factory,+) -> None:+ handler.clear_reply = AsyncMock(+ return_value=ReplyClearResult(+ message_ids=frozenset({"voice", "tree_status"}),+ tree_cleared=True,+ )+ )+ deleted_ids: list[str] = []++ async def capture_delete(_chat_id, message_ids, fire_and_forget=True):+ deleted_ids.extend(message_ids)++ mock_platform.queue_delete_messages.side_effect = capture_delete+ incoming = incoming_message_factory(+ text="/clear",+ message_id="clear",+ reply_to_message_id="voice",+ )++ await handler.handle_message(incoming)++ handler.clear_reply.assert_awaited_once_with(incoming.scope, "voice")+ assert set(deleted_ids) == {+ "voice",+ "tree_status",+ "clear",+ }+ mock_platform.queue_send_message.assert_not_awaited()+++async def test_reply_clear_joins_voice_then_unions_authoritative_branch_ids(+ handler,+ mock_platform,+) -> None:+ events: list[str] = []++ async def cancel_voice(*_args) -> VoiceCancellationResult:+ events.append("voice")+ return VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )++ async def resolve_tree(*_args) -> str:+ events.append("resolve")+ return "voice"++ branch = BranchRemovalResult(+ cancellation=CancellationResult(),+ removed_tree_identity=None,+ message_ids=frozenset({"voice", "tree_status"}),+ )+ mock_platform.cancel_pending_voice.side_effect = cancel_voice+ with (+ patch.object(+ handler.tree_queue,+ "resolve_node_id",+ side_effect=resolve_tree,+ ) as resolve,+ patch.object(+ handler.tree_queue,+ "remove_branch",+ new_callable=AsyncMock,+ return_value=branch,+ ) as remove_branch,+ ):+ result = await handler.clear_reply(_SCOPE, "voice")+ await asyncio.sleep(0)++ assert result == ReplyClearResult(+ message_ids=frozenset({"voice", "voice_status", "tree_status"}),+ tree_cleared=True,+ )+ assert events == ["voice", "resolve"]+ resolve.assert_awaited_once_with(_SCOPE, "voice")+ remove_branch.assert_awaited_once_with(_SCOPE, "voice")+ mock_platform.queue_edit_message.assert_awaited_once()+++async def test_cancelled_reply_clear_finishes_voice_only_owner_after_lock_wait(+ handler,+ mock_platform,+) -> None:+ voice_returned = asyncio.Event()++ async def cancel_voice(*_args) -> VoiceCancellationResult:+ voice_returned.set()+ return VoiceCancellationResult(+ scope=_SCOPE,+ voice_message_id="voice",+ status_message_id="voice_status",+ )++ mock_platform.cancel_pending_voice.side_effect = cancel_voice+ resolve = AsyncMock(return_value=None)+ await handler._state_lock.acquire()+ try:+ with patch.object(handler.tree_queue, "resolve_node_id", resolve):+ clear_task = asyncio.create_task(handler.clear_reply(_SCOPE, "voice"))+ await voice_returned.wait()+ await asyncio.sleep(0)+ clear_task.cancel()+ await asyncio.sleep(0)++ assert not clear_task.done()+ handler._state_lock.release()+ with pytest.raises(asyncio.CancelledError):+ await clear_task+ finally:+ if handler._state_lock.locked():+ handler._state_lock.release()+ await asyncio.sleep(0)++ resolve.assert_awaited_once_with(_SCOPE, "voice")+ mock_platform.queue_edit_message.assert_awaited_once()+ assert mock_platform.queue_edit_message.call_args.args[1] == "voice_status"diff --git a/tests/messaging/test_platform_voice_flow.py b/tests/messaging/test_platform_voice_flow.pyindex bfdf0c65..113fe072 100644--- a/tests/messaging/test_platform_voice_flow.py+++ b/tests/messaging/test_platform_voice_flow.py@@ -13,11 +13,17 @@ from free_claude_code.messaging.platforms.voice_flow import (audio_suffix_from_metadata,is_audio_metadata,)+from free_claude_code.messaging.trees.runtime import MessageTreefrom free_claude_code.messaging.voice import Transcriber+from free_claude_code.messaging.workflow import MessagingWorkflowVOICE_SCOPE = MessageScope(platform="telegram", chat_id="chat")+class FatalVoiceError(BaseException):+ """Fatal sentinel used to verify ownership finalization."""++class MockTranscriber:def __init__(self, result: str = "hello from voice") -> None:self.run = AsyncMock(return_value=result)@@ -153,7 +159,7 @@ async def test_voice_flow_missing_status_id_stops_before_transcription() -> None@pytest.mark.asyncio-async def test_voice_flow_cancelled_transcription_deletes_status() -> None:+async def test_voice_flow_cancelled_transcription_preserves_owned_status() -> None:flow, transcriber = _flow()async def canceling_transcribe(_path: Path) -> str:@@ -174,7 +180,7 @@ async def test_voice_flow_cancelled_transcription_deletes_status() -> None:assert handled is Truehandler.assert_not_awaited()- queue_delete.assert_awaited_once_with("chat", ["status"])+ queue_delete.assert_not_awaited()@pytest.mark.asyncio@@ -306,51 +312,336 @@ async def test_voice_flow_cancel_during_transcription_suppresses_late_failure()handler.assert_not_awaited()reply_text.assert_not_awaited()- queue_delete.assert_awaited_once_with("chat", ["status"])+ queue_delete.assert_not_awaited()@pytest.mark.asyncio-async def test_voice_flow_cancel_at_handoff_boundary_prevents_handler(- monkeypatch: pytest.MonkeyPatch,+async def test_reply_stop_status_survives_late_transcription_success(+ mock_platform,+ mock_cli_manager,+ mock_session_store,+ incoming_message_factory,) -> None:+ flow, transcriber = _flow()+ workflow = MessagingWorkflow(+ mock_platform,+ mock_cli_manager,+ mock_session_store,+ platform_name="telegram",+ voice_cancellation=flow,+ )+ transcription_started = asyncio.Event()+ release_transcription = asyncio.Event()++ async def delayed_transcription(_path: Path) -> str:+ transcription_started.set()+ await release_transcription.wait()+ return "late voice prompt"++ transcriber.run.side_effect = delayed_transcription+ mock_platform.queue_send_message.return_value = "voice_status"+ voice_task = asyncio.create_task(+ flow.handle(+ _request(),+ message_handler=workflow.handle_message,+ queue_send_message=mock_platform.queue_send_message,+ queue_delete_messages=mock_platform.queue_delete_messages,+ )+ )+ await asyncio.wait_for(transcription_started.wait(), timeout=1)++ try:+ await workflow.handle_message(+ incoming_message_factory(+ text="/stop",+ chat_id="chat",+ message_id="stop_command",+ reply_to_message_id="voice",+ )+ )+ finally:+ release_transcription.set()+ assert await asyncio.wait_for(voice_task, timeout=1) is True+ await asyncio.sleep(0)++ stopped = workflow.format_status("⏹", "Stopped.")+ assert any(+ call.args[:3] == ("chat", "voice_status", stopped)+ for call in mock_platform.queue_edit_message.await_args_list+ )+ mock_platform.queue_delete_messages.assert_not_awaited()+ assert await workflow.tree_queue.resolve_node_id(VOICE_SCOPE, "voice") is None+++async def test_voice_flow_cancel_during_handoff_stops_and_drains_handler() -> 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+ handler_started = asyncio.Event()+ handler_cancelled = asyncio.Event()+ release_handler = asyncio.Event()+ queue_delete = AsyncMock()- async def gated_claim(claim) -> bool:- claim_started.set()- await release_claim.wait()- return await claim_for_handoff(claim)+ async def handler(_incoming) -> None:+ handler_started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ handler_cancelled.set()+ await release_handler.wait()+ raise- 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(),+ queue_delete_messages=queue_delete,))try:- await asyncio.wait_for(claim_started.wait(), timeout=1)- cancelled = await flow.cancel_pending_voice(VOICE_SCOPE, "voice")+ await asyncio.wait_for(handler_started.wait(), timeout=1)+ cancel_task = asyncio.create_task(+ flow.cancel_pending_voice(VOICE_SCOPE, "voice")+ )+ await asyncio.wait_for(handler_cancelled.wait(), timeout=1)++ assert not cancel_task.done()+ release_handler.set()+ cancelled = await asyncio.wait_for(cancel_task, timeout=1)assert cancelled is not Noneassert cancelled.status_message_id == "status"-- release_claim.set()assert await asyncio.wait_for(handle_task, timeout=1) is Truefinally:- release_claim.set()+ release_handler.set()if not handle_task.done():handle_task.cancel()with pytest.raises(asyncio.CancelledError):await handle_task- handler.assert_not_awaited()+ queue_delete.assert_not_awaited()+++async def test_voice_flow_cancel_during_handoff_suppresses_late_handler_error() -> None:+ flow, _transcriber = _flow()+ handler_started = asyncio.Event()+ reply_text = AsyncMock()++ async def handler(_incoming) -> None:+ handler_started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ raise RuntimeError("late handler failure") from None++ 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=AsyncMock(),+ )+ )++ await asyncio.wait_for(handler_started.wait(), timeout=1)+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "status") is not None+ assert await asyncio.wait_for(handle_task, timeout=1) is True+ reply_text.assert_not_awaited()++[email protected]("command", ["/stop", "/clear"])+async def test_reply_command_cancels_voice_at_tree_admission_commit(+ command: str,+ monkeypatch: pytest.MonkeyPatch,+ mock_platform,+ mock_cli_manager,+ mock_session_store,+ incoming_message_factory,+) -> None:+ flow, _transcriber = _flow()+ workflow = MessagingWorkflow(+ mock_platform,+ mock_cli_manager,+ mock_session_store,+ platform_name="telegram",+ voice_cancellation=flow,+ )+ admission_mutated = asyncio.Event()+ release_admission = asyncio.Event()+ original_enqueue_or_claim = MessageTree.enqueue_or_claim++ async def mutate_then_block(tree: MessageTree, node_id: str):+ decision = await original_enqueue_or_claim(tree, node_id)+ if node_id == "voice":+ admission_mutated.set()+ await release_admission.wait()+ return decision++ monkeypatch.setattr(MessageTree, "enqueue_or_claim", mutate_then_block)+ mock_platform.queue_send_message.return_value = "voice_status"+ voice_task = asyncio.create_task(+ flow.handle(+ _request(),+ message_handler=workflow.handle_message,+ queue_send_message=mock_platform.queue_send_message,+ queue_delete_messages=mock_platform.queue_delete_messages,+ )+ )+ await asyncio.wait_for(admission_mutated.wait(), timeout=1)++ command_task = asyncio.create_task(+ workflow.handle_message(+ incoming_message_factory(+ text=command,+ chat_id="chat",+ message_id="command",+ reply_to_message_id="voice",+ )+ )+ )+ try:+ await asyncio.sleep(0)+ assert not command_task.done()+ finally:+ release_admission.set()+ await asyncio.wait_for(command_task, timeout=1)+ voice_result = await asyncio.wait_for(voice_task, timeout=1)+ assert voice_result is True+ await asyncio.sleep(0)++ mock_session_store.save_tree_snapshot.assert_called()+ if command == "/clear":+ assert workflow.get_tree_count() == 0+ assert await workflow.tree_queue.resolve_node_id(VOICE_SCOPE, "voice") is None+ else:+ assert workflow.get_tree_count() == 1+ assert (+ await workflow.tree_queue.resolve_node_id(VOICE_SCOPE, "voice") == "voice"+ )++[email protected]("command", ["/stop", "/clear"])+async def test_global_command_rejects_transcription_that_finishes_late(+ command: str,+ mock_platform,+ mock_cli_manager,+ mock_session_store,+ incoming_message_factory,+) -> None:+ flow, transcriber = _flow()+ workflow = MessagingWorkflow(+ mock_platform,+ mock_cli_manager,+ mock_session_store,+ platform_name="telegram",+ voice_cancellation=flow,+ )+ transcription_started = asyncio.Event()+ release_transcription = asyncio.Event()++ async def delayed_transcription(_path: Path) -> str:+ transcription_started.set()+ await release_transcription.wait()+ return "late voice prompt"++ transcriber.run.side_effect = delayed_transcription+ mock_platform.queue_send_message.return_value = "voice_status"+ voice_task = asyncio.create_task(+ flow.handle(+ _request(),+ message_handler=workflow.handle_message,+ queue_send_message=mock_platform.queue_send_message,+ queue_delete_messages=mock_platform.queue_delete_messages,+ )+ )+ await asyncio.wait_for(transcription_started.wait(), timeout=1)++ await asyncio.wait_for(+ workflow.handle_message(+ incoming_message_factory(text=command, message_id="command")+ ),+ timeout=1,+ )+ release_transcription.set()+ assert await asyncio.wait_for(voice_task, timeout=1) is True++ assert workflow.get_tree_count() == 0+ assert await workflow.tree_queue.resolve_node_id(VOICE_SCOPE, "voice") is None++[email protected]("command", ["/stop", "/clear"])+async def test_transcribed_global_command_does_not_cancel_its_own_handoff(+ command: str,+ mock_platform,+ mock_cli_manager,+ mock_session_store,+) -> None:+ flow, transcriber = _flow()+ transcriber.run.return_value = command+ workflow = MessagingWorkflow(+ mock_platform,+ mock_cli_manager,+ mock_session_store,+ platform_name="telegram",+ voice_cancellation=flow,+ )+ mock_platform.queue_send_message.return_value = "voice_status"++ assert (+ await asyncio.wait_for(+ flow.handle(+ _request(),+ message_handler=workflow.handle_message,+ queue_send_message=mock_platform.queue_send_message,+ queue_delete_messages=mock_platform.queue_delete_messages,+ ),+ timeout=1,+ )+ is True+ )++ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None+++async def test_voice_flow_caller_cancellation_drains_handoff_child() -> None:+ flow, _transcriber = _flow()+ handler_started = asyncio.Event()+ handler_cancelled = asyncio.Event()+ release_handler = asyncio.Event()+ queue_delete = AsyncMock()++ async def handler(_incoming) -> None:+ handler_started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ handler_cancelled.set()+ await release_handler.wait()+ raise++ handle_task = asyncio.create_task(+ flow.handle(+ _request(),+ message_handler=handler,+ queue_send_message=AsyncMock(return_value="status"),+ queue_delete_messages=queue_delete,+ )+ )+ await asyncio.wait_for(handler_started.wait(), timeout=1)+ handle_task.cancel()+ await asyncio.wait_for(handler_cancelled.wait(), timeout=1)++ assert not handle_task.done()+ release_handler.set()+ with pytest.raises(asyncio.CancelledError):+ await handle_task+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None+ queue_delete.assert_not_awaited()@pytest.mark.asyncio@@ -401,6 +692,119 @@ async def test_voice_flow_task_cancellation_waits_then_cleans_pending_state() ->assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None+async def test_voice_flow_repeated_cancellation_cannot_interrupt_cleanup(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ flow, transcriber = _flow()+ transcription_started = asyncio.Event()+ cleanup_started = asyncio.Event()+ release_cleanup = asyncio.Event()++ async def blocked_transcription(_path: Path) -> str:+ transcription_started.set()+ await asyncio.Event().wait()+ return "unreachable"++ original_discard = flow._pending_voice.discard++ async def delayed_discard(claim) -> bool:+ cleanup_started.set()+ await release_cleanup.wait()+ return await original_discard(claim)++ transcriber.run.side_effect = blocked_transcription+ monkeypatch.setattr(flow._pending_voice, "discard", delayed_discard)+ queue_delete = AsyncMock()+ handle_task = asyncio.create_task(+ flow.handle(+ _request(),+ message_handler=AsyncMock(),+ queue_send_message=AsyncMock(return_value="status"),+ queue_delete_messages=queue_delete,+ )+ )++ await asyncio.wait_for(transcription_started.wait(), timeout=1)+ handle_task.cancel("first cancellation")+ await asyncio.wait_for(cleanup_started.wait(), timeout=1)+ handle_task.cancel("second cancellation")+ await asyncio.sleep(0)++ assert not handle_task.done()+ release_cleanup.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(handle_task, timeout=1)++ queue_delete.assert_awaited_once_with("chat", ["status"])+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "status") is None+++async def test_voice_flow_fatal_status_failure_releases_claim() -> None:+ flow, transcriber = _flow()+ queue_delete = AsyncMock()++ async def fatal_status(*_args, **_kwargs) -> str:+ raise FatalVoiceError++ with pytest.raises(FatalVoiceError):+ await flow.handle(+ _request(),+ message_handler=AsyncMock(),+ queue_send_message=fatal_status,+ queue_delete_messages=queue_delete,+ )++ transcriber.run.assert_not_awaited()+ queue_delete.assert_not_awaited()+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None+++async def test_voice_flow_fatal_download_failure_releases_status_ownership() -> None:+ flow, transcriber = _flow()+ queue_delete = AsyncMock()++ async def fatal_download(_path: Path) -> None:+ raise FatalVoiceError++ with pytest.raises(FatalVoiceError):+ await flow.handle(+ _request(download_to=fatal_download),+ message_handler=AsyncMock(),+ queue_send_message=AsyncMock(return_value="status"),+ queue_delete_messages=queue_delete,+ )++ transcriber.run.assert_not_awaited()+ queue_delete.assert_awaited_once_with("chat", ["status"])+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "status") is None+++async def test_voice_flow_fatal_transcription_releases_status_ownership() -> None:+ flow, transcriber = _flow()+ transcriber.run.side_effect = FatalVoiceError()+ handler = AsyncMock()+ queue_delete = AsyncMock()++ with pytest.raises(FatalVoiceError):+ await flow.handle(+ _request(),+ message_handler=handler,+ queue_send_message=AsyncMock(return_value="status"),+ queue_delete_messages=queue_delete,+ )++ handler.assert_not_awaited()+ queue_delete.assert_awaited_once_with("chat", ["status"])+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "voice") is None+ assert await flow.cancel_pending_voice(VOICE_SCOPE, "status") is None++@pytest.mark.asyncioasync def test_voice_flow_download_failure_cleans_pending_state() -> None:flow, transcriber = _flow()diff --git a/tests/messaging/test_restart_reply_restore.py b/tests/messaging/test_restart_reply_restore.pyindex d0aa6c75..d42d0165 100644--- a/tests/messaging/test_restart_reply_restore.py+++ b/tests/messaging/test_restart_reply_restore.py@@ -187,7 +187,7 @@ async def test_save_tree_snapshot_restores_status_lookup_without_manual_index()workflow.restore()- assert await workflow.resolve_node_id(TELEGRAM_CHAT_1, "status_A") == "A"+ assert await workflow.tree_queue.resolve_node_id(TELEGRAM_CHAT_1, "status_A") == "A"@pytest.mark.asynciodiff --git a/tests/messaging/test_voice_handlers.py b/tests/messaging/test_voice_handlers.pyindex 9584f582..5275a7d1 100644--- a/tests/messaging/test_voice_handlers.py+++ b/tests/messaging/test_voice_handlers.py@@ -117,6 +117,16 @@ async def test_telegram_voice_success_invokes_handler(telegram_platform):assert incoming.status_message_id == "999"+async def test_telegram_bulk_voice_cancellation_delegates(telegram_platform) -> None:+ platform, _transcriber = telegram_platform+ platform._voice_flow.cancel_all_pending_voices = AsyncMock(return_value=())++ assert await platform.cancel_all_pending_voices() == ()++ platform._voice_flow.cancel_all_pending_voices.assert_awaited_once()++@pytest.mark.skipif(not DISCORD_AVAILABLE, reason="discord.py not installed")class TestDiscordGetAudioAttachment:"""Tests for _get_audio_attachment helper."""@@ -177,3 +187,19 @@ async def test_discord_voice_disabled_sends_reply():await platform._on_discord_message(mock_message)mock_message.reply.assert_called_once_with("Voice notes are disabled.")++[email protected](not DISCORD_AVAILABLE, reason="discord.py not installed")+async def test_discord_bulk_voice_cancellation_delegates() -> None:+ platform = DiscordRuntime(+ bot_token="token",+ allowed_channel_ids="123",+ limiter=MagicMock(),+ transcriber=None,+ )+ platform._voice_flow.cancel_all_pending_voices = AsyncMock(return_value=())++ assert await platform.cancel_all_pending_voices() == ()++ platform._voice_flow.cancel_all_pending_voices.assert_awaited_once()diff --git a/tests/messaging/test_voice_services.py b/tests/messaging/test_voice_services.pyindex 9cee0e54..c2d18e6a 100644--- a/tests/messaging/test_voice_services.py+++ b/tests/messaging/test_voice_services.py@@ -1,75 +1,592 @@+import asyncio+import pytestfrom free_claude_code.messaging.models import MessageScopefrom free_claude_code.messaging.voice import (+ PendingVoiceClaim,PendingVoiceRegistry,VoiceCancellationResult,+ VoiceHandoffOutcome,)TELEGRAM_CHAT = MessageScope(platform="telegram", chat_id="chat")DISCORD_CHAT = MessageScope(platform="discord", chat_id="chat")+class AsyncNoop:+ async def __call__(self) -> None:+ return None+++class FatalVoiceFailure(BaseException):+ pass+++async def _reserve_bound(+ registry: PendingVoiceRegistry,+ *,+ scope: MessageScope = TELEGRAM_CHAT,+ voice_id: str = "voice-1",+ status_id: str = "status-1",+) -> PendingVoiceClaim:+ claim = await registry.reserve(scope, voice_id)+ assert claim is not None+ assert await registry.bind_status(claim, status_id) is True+ return claim++@pytest.mark.asyncioasync def test_cancel_before_status_binding_rejects_late_flow() -> None:registry = PendingVoiceRegistry()claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")+ callback_called = False++ async def callback() -> None:+ nonlocal callback_called+ callback_called = Trueassert claim is not None- assert await registry.cancel(TELEGRAM_CHAT, "voice-1") == (- VoiceCancellationResult(- voice_message_id="voice-1",- status_message_id=None,- )+ cancellation = await registry.cancel(TELEGRAM_CHAT, "voice-1")+ assert cancellation is not None+ assert cancellation == VoiceCancellationResult(+ scope=TELEGRAM_CHAT,+ voice_message_id="voice-1",+ status_message_id=None,)+ assert cancellation.message_ids == frozenset({"voice-1"})assert await registry.bind_status(claim, "status-1") is False- assert await registry.claim_for_handoff(claim) is False+ assert await registry.handoff(claim, callback) is VoiceHandoffOutcome.REJECTED+ assert callback_called is False+++async def test_handoff_remains_addressable_until_callback_completes() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ await release.wait()++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)++ assert await registry.reserve(TELEGRAM_CHAT, "voice-1") is None+ release.set()+ assert await asyncio.wait_for(handoff_task, timeout=1) is (+ VoiceHandoffOutcome.COMPLETED+ )+ assert await registry.cancel(TELEGRAM_CHAT, "status-1") is None+++async def test_cancel_removes_then_drains_handoff_without_holding_lock() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ cancellation_received = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancellation_received.set()+ await release.wait()+ raise++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)+ cancel_task = asyncio.create_task(registry.cancel(TELEGRAM_CHAT, "status-1"))+ await asyncio.wait_for(cancellation_received.wait(), timeout=1)++ assert not cancel_task.done()+ replacement = await asyncio.wait_for(+ registry.reserve(TELEGRAM_CHAT, "voice-1"), timeout=1+ )+ assert replacement is not None+ assert await registry.bind_status(replacement, "status-new") is True++ release.set()+ cancellation = await asyncio.wait_for(cancel_task, timeout=1)+ assert cancellation is not None+ assert cancellation == VoiceCancellationResult(+ scope=TELEGRAM_CHAT,+ voice_message_id="voice-1",+ status_message_id="status-1",+ )+ assert cancellation.message_ids == frozenset({"voice-1", "status-1"})+ assert await asyncio.wait_for(handoff_task, timeout=1) is (+ VoiceHandoffOutcome.CANCELLED+ )+ assert await registry.cancel(TELEGRAM_CHAT, "status-new") is not None@pytest.mark.asyncio-async def test_pending_voice_registry_cancel_and_handoff_are_exclusive() -> None:+async def test_handoff_propagates_callback_error_when_completion_wins() -> None:registry = PendingVoiceRegistry()- cancelled_claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")+ claim = await _reserve_bound(registry)++ async def callback() -> None:+ raise RuntimeError("handler failed")++ with pytest.raises(RuntimeError, match="handler failed"):+ await registry.handoff(claim, callback)++ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+++async def test_handoff_suppresses_late_callback_error_when_cancellation_wins() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ raise RuntimeError("late handler failure") from None++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=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") == (- VoiceCancellationResult(- voice_message_id="voice-1",- status_message_id="status-1",- )+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is not None+ assert await asyncio.wait_for(handoff_task, timeout=1) is (+ VoiceHandoffOutcome.CANCELLED)- 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++async def test_handoff_caller_cancellation_drains_child_and_propagates() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ cancellation_received = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancellation_received.set()+ await release.wait()+ raise++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)+ handoff_task.cancel()+ await asyncio.wait_for(cancellation_received.wait(), timeout=1)+ assert handoff_task.cancelling() == 1+ assert await registry.reserve(TELEGRAM_CHAT, "voice-1") is None+ assert await registry.reserve(TELEGRAM_CHAT, "status-1") is None++ handoff_task.cancel()+ await asyncio.sleep(0)+ assert handoff_task.cancelling() == 2+ handoff_task.cancel()+ await asyncio.sleep(0)+ assert handoff_task.cancelling() == 3+ assert not handoff_task.done()+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await handoff_task+ assert handoff_task.cancelling() == 3+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None@pytest.mark.asyncio-async def test_pending_voice_registry_isolates_platform_scopes() -> None:+async def test_handoff_drains_child_when_cancellation_is_already_pending() -> None:registry = PendingVoiceRegistry()- discord_claim = await registry.reserve(DISCORD_CHAT, "voice-1")- telegram_claim = await registry.reserve(TELEGRAM_CHAT, "voice-1")+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ finished = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await release.wait()+ finally:+ finished.set()++ async def cancelled_caller() -> VoiceHandoffOutcome:+ current = asyncio.current_task()+ assert current is not None+ current.cancel()+ return await registry.handoff(claim, callback)++ handoff_task = asyncio.create_task(cancelled_caller())+ try:+ with pytest.raises(asyncio.CancelledError):+ await handoff_task+ assert started.is_set()+ assert finished.is_set()+ assert handoff_task.cancelling() == 1+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+ finally:+ release.set()+ await asyncio.sleep(0)+++async def test_external_cancel_owns_aliases_during_caller_cancelled_drain() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ caller_cancellation_received = asyncio.Event()+ external_cancellation_received = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ caller_cancellation_received.set()+ try:+ await release.wait()+ except asyncio.CancelledError:+ external_cancellation_received.set()+ await release.wait()+ raise++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)++ handoff_task.cancel()+ await asyncio.wait_for(caller_cancellation_received.wait(), timeout=1)+ cancel_task = asyncio.create_task(registry.cancel(TELEGRAM_CHAT, "status-1"))+ await asyncio.wait_for(external_cancellation_received.wait(), timeout=1)++ replacement = await registry.reserve(TELEGRAM_CHAT, "voice-1")+ assert replacement is not None+ assert await registry.bind_status(replacement, "status-new") is True+ release.set()- 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") == (- VoiceCancellationResult(- voice_message_id="voice-1",- status_message_id="status-1",- )+ cancellation = await asyncio.wait_for(cancel_task, timeout=1)+ assert cancellation == VoiceCancellationResult(+ scope=TELEGRAM_CHAT,+ voice_message_id="voice-1",+ status_message_id="status-1",)- assert await registry.cancel(DISCORD_CHAT, "voice-1") == (- VoiceCancellationResult(- voice_message_id="voice-1",- status_message_id="status-1",- )+ with pytest.raises(asyncio.CancelledError):+ await handoff_task+ assert await registry.cancel(TELEGRAM_CHAT, "status-new") is not None+++async def test_handoff_finalization_survives_repeated_caller_cancellation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ finalization_started = asyncio.Event()+ release_finalization = asyncio.Event()+ complete_if_owned = registry._complete_if_owned++ async def gated_completion(entry) -> bool:+ finalization_started.set()+ await release_finalization.wait()+ return await complete_if_owned(entry)++ monkeypatch.setattr(registry, "_complete_if_owned", gated_completion)+ handoff_task = asyncio.create_task(registry.handoff(claim, AsyncNoop()))+ await asyncio.wait_for(finalization_started.wait(), timeout=1)++ handoff_task.cancel()+ await asyncio.sleep(0)+ handoff_task.cancel()+ await asyncio.sleep(0)+ assert not handoff_task.done()++ release_finalization.set()+ with pytest.raises(asyncio.CancelledError):+ await handoff_task+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+++async def test_cancel_drain_survives_repeated_caller_cancellation() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ child_cancelled = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ child_cancelled.set()+ await release.wait()+ raise++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)+ cancel_task = asyncio.create_task(registry.cancel(TELEGRAM_CHAT, "voice-1"))+ await asyncio.wait_for(child_cancelled.wait(), timeout=1)++ cancel_task.cancel()+ await asyncio.sleep(0)+ cancel_task.cancel()+ await asyncio.sleep(0)+ assert not cancel_task.done()++ release.set()+ with pytest.raises(asyncio.CancelledError):+ await cancel_task+ assert await asyncio.wait_for(handoff_task, timeout=1) is (+ VoiceHandoffOutcome.CANCELLED)+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+++async def test_timeout_and_independent_cancellation_remain_distinct() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ child_cancelled = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ child_cancelled.set()+ await release.wait()+ raise++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)++ async def timed_cancel() -> VoiceCancellationResult | None:+ async with asyncio.timeout(0.01):+ return await registry.cancel(TELEGRAM_CHAT, "voice-1")++ cancel_task = asyncio.create_task(timed_cancel())+ await asyncio.wait_for(child_cancelled.wait(), timeout=1)+ await asyncio.sleep(0.05)+ assert cancel_task.cancelling() == 1+ cancel_task.cancel()+ await asyncio.sleep(0)+ assert cancel_task.cancelling() == 2+ release.set()++ with pytest.raises(asyncio.CancelledError):+ await cancel_task+ assert await asyncio.wait_for(handoff_task, timeout=1) is (+ VoiceHandoffOutcome.CANCELLED+ )+++async def test_reentrant_callback_cancellation_does_not_join_a_cycle() -> None:+ registry = PendingVoiceRegistry()+ first = await _reserve_bound(+ registry,+ voice_id="voice-1",+ status_id="status-1",+ )+ second = await _reserve_bound(+ registry,+ voice_id="voice-2",+ status_id="status-2",+ )+ second_started = asyncio.Event()+ first_cancellation: VoiceCancellationResult | None = None+ second_cancellation: VoiceCancellationResult | None = None++ async def first_callback() -> None:+ nonlocal second_cancellation+ await second_started.wait()+ second_cancellation = await registry.cancel(TELEGRAM_CHAT, "voice-2")++ async def second_callback() -> None:+ nonlocal first_cancellation+ second_started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ first_cancellation = await registry.cancel(TELEGRAM_CHAT, "voice-1")+ raise++ first_handoff = asyncio.create_task(registry.handoff(first, first_callback))+ second_handoff = asyncio.create_task(registry.handoff(second, second_callback))++ assert await asyncio.wait_for(first_handoff, timeout=1) is (+ VoiceHandoffOutcome.COMPLETED+ )+ assert await asyncio.wait_for(second_handoff, timeout=1) is (+ VoiceHandoffOutcome.CANCELLED+ )+ assert first_cancellation is None+ assert second_cancellation is not None+ assert second_cancellation.voice_message_id == "voice-2"+++async def test_nested_callback_task_cannot_cancel_its_own_claim() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ cancellation: VoiceCancellationResult | None = None++ async def nested_cancel() -> None:+ nonlocal cancellation+ cancellation = await registry.cancel(TELEGRAM_CHAT, "status-1")++ async def callback() -> None:+ await asyncio.create_task(nested_cancel())++ assert await asyncio.wait_for(registry.handoff(claim, callback), timeout=1) is (+ VoiceHandoffOutcome.COMPLETED+ )+ assert cancellation is None+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+++async def test_nested_callback_task_is_excluded_from_bulk_cancellation() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ cancellations: tuple[VoiceCancellationResult, ...] | None = None++ async def nested_cancel_all() -> None:+ nonlocal cancellations+ cancellations = await registry.cancel_all()++ async def callback() -> None:+ await asyncio.create_task(nested_cancel_all())++ assert await asyncio.wait_for(registry.handoff(claim, callback), timeout=1) is (+ VoiceHandoffOutcome.COMPLETED+ )+ assert cancellations == ()+ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+++async def test_fatal_callback_failure_releases_aliases_and_propagates() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)++ async def callback() -> None:+ raise FatalVoiceFailure++ with pytest.raises(FatalVoiceFailure):+ await registry.handoff(claim, callback)++ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+ assert await registry.cancel(TELEGRAM_CHAT, "status-1") is None+++async def test_fatal_failure_after_caller_cancellation_releases_aliases() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()+ cancellation_received = asyncio.Event()+ release = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancellation_received.set()+ await release.wait()+ raise FatalVoiceFailure from None++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)+ handoff_task.cancel()+ await asyncio.wait_for(cancellation_received.wait(), timeout=1)++ assert await registry.reserve(TELEGRAM_CHAT, "voice-1") is None+ release.set()+ with pytest.raises(FatalVoiceFailure):+ await handoff_task++ assert await registry.cancel(TELEGRAM_CHAT, "voice-1") is None+ assert await registry.cancel(TELEGRAM_CHAT, "status-1") is None+++async def test_fatal_loser_failure_is_retrieved_and_propagated() -> None:+ registry = PendingVoiceRegistry()+ claim = await _reserve_bound(registry)+ started = asyncio.Event()++ async def callback() -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ raise FatalVoiceFailure from None++ handoff_task = asyncio.create_task(registry.handoff(claim, callback))+ await asyncio.wait_for(started.wait(), timeout=1)++ with pytest.raises(FatalVoiceFailure):+ await registry.cancel(TELEGRAM_CHAT, "voice-1")+ with pytest.raises(FatalVoiceFailure):+ await handoff_task++ assert await registry.cancel(TELEGRAM_CHAT, "status-1") is None+++async def test_cancel_all_deduplicates_aliases_and_excludes_current_child() -> None:+ registry = PendingVoiceRegistry()+ first = await _reserve_bound(registry, voice_id="voice-1", status_id="status-1")+ second = await _reserve_bound(+ registry,+ scope=DISCORD_CHAT,+ voice_id="voice-2",+ status_id="status-2",+ )+ first_started = asyncio.Event()+ first_cancelled = asyncio.Event()+ cancellations: tuple[VoiceCancellationResult, ...] | None = None++ async def first_callback() -> None:+ first_started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ first_cancelled.set()+ raise++ async def second_callback() -> None:+ nonlocal cancellations+ await first_started.wait()+ cancellations = await registry.cancel_all()++ first_handoff = asyncio.create_task(registry.handoff(first, first_callback))+ second_handoff = asyncio.create_task(registry.handoff(second, second_callback))++ assert await asyncio.wait_for(first_handoff, timeout=1) is (+ VoiceHandoffOutcome.CANCELLED+ )+ assert await asyncio.wait_for(second_handoff, timeout=1) is (+ VoiceHandoffOutcome.COMPLETED+ )+ assert first_cancelled.is_set()+ assert cancellations is not None+ assert len(cancellations) == 1+ assert {result.scope for result in cancellations} == {TELEGRAM_CHAT}+ assert {result.message_ids for result in cancellations} == {+ frozenset({"voice-1", "status-1"}),+ }@pytest.mark.asyncio@@ -80,20 +597,17 @@ async def test_stale_claim_cannot_mutate_reused_voice_id() -> None:assert stale_claim is not Noneassert 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+ current_claim = await _reserve_bound(+ registry, voice_id="voice-1", status_id="status-current"+ )+ assert current_claim != stale_claimassert 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",- )+ assert (+ await registry.handoff(stale_claim, AsyncNoop()) is VoiceHandoffOutcome.REJECTED)+ assert await registry.discard(stale_claim) is False+ assert await registry.cancel(TELEGRAM_CHAT, "status-current") is not None@pytest.mark.asyncio@@ -103,5 +617,5 @@ async def test_pending_voice_registry_rejects_duplicate_and_unbound_handoff() ->assert claim is not Noneassert await registry.reserve(TELEGRAM_CHAT, "voice-1") is None- assert await registry.claim_for_handoff(claim) is False+ assert await registry.handoff(claim, AsyncNoop()) is VoiceHandoffOutcome.REJECTEDassert await registry.cancel(TELEGRAM_CHAT, "voice-1") is not Nonediff --git a/uv.lock b/uv.lockindex b6ae57c6..3fd51615 100644--- a/uv.lock+++ b/uv.lock@@ -561,7 +561,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "3.5.6"+version = "3.5.7"source = { editable = "." }dependencies = [{ name = "aiohttp" },