fix: a delete question counts as asked only once the answer reached the person

A person's reply stopped counting as "unanswered" as soon as the worker sent
reply_text, so a delete question that could not be spoken (no TTS, a failed
or stopped speech) or that the app could not post still let the next
"응, 지워" confirm the delete.

- Worker: an answer reaches the person on a tts_done neither failed nor
  cancelled (spoken answers), on the app's reply_delivered ok (chat
  answers), or at reply_text (unspoken voice answers). tts_unavailable, a
  failed or cancelled tts_done, reply_delivered ok=false, no report within
  30 s and the session ending all mean it never did: a turn number is
  skipped, so the delete asked in it lapses. A reply sent before the
  previous answer reached them is still not their next turn.
- App: a chat answer reports reply_delivered with whether Discord took the
  post; a late, failed or empty answer reports it was not posted.
- Tests: no TTS, a failed speech, a chat post the app reports failed, and
  no report at all do not delete; a spoken and a posted question do.
  Conversation and worker client tests for the report.
- Specs: voice_worker.spec.md (reply_delivered, when an answer reaches the
  person), discord_core.spec.md, conversation.spec.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 01:39:48 +09:00
parent c328bda699
commit 9e75df266b
9 changed files with 209 additions and 32 deletions

View File

@@ -41,7 +41,8 @@ def is_loopback(host: str) -> bool:
class VoiceWorker:
def __init__(self, token: str, transcriber: Transcriber | None, vad_factory: Callable[[], VadStream],
tts_engine: TtsEngine | None = None, hello_timeout_s: float = 5.0, tick_s: float = 0.05,
history=None, brain: Brain | None = None, chat_timeout_s: float = 15.0):
history=None, brain: Brain | None = None, chat_timeout_s: float = 15.0,
delivery_timeout_s: float = 30.0):
if not token:
raise ValueError("a connection token is required")
self.token = token
@@ -59,14 +60,15 @@ class VoiceWorker:
self.brain_lanes = {"voice": asyncio.Lock(), "chat": asyncio.Lock()}
self.brain_people: dict[str, asyncio.Lock] = {}
self.chat_timeout_s = chat_timeout_s
self.delivery_timeout_s = delivery_timeout_s # a chat answer the app never reports: not posted
# chat_action ids are unique across connections and worker runs, so a late answer from an
# earlier connection (or an earlier worker) never completes a newer action.
self.chat_action_prefix = secrets.token_hex(4)
# Per person: how many replies they had (a delete is confirmed only in the very next one),
# the deletes they were asked to confirm (chat_channels.spec.md) and how many of their
# replies are not answered yet. A turn number is skipped for a request that arrived before
# the person's previous answer was given, and after an answer they never got, so a
# confirmation asked in that answer lapses.
# replies have not reached them yet (spoken, or posted by the app). A turn number is skipped
# for a request that arrived before the person's previous answer reached them, and after an
# answer that never did, so a confirmation asked in that answer lapses.
self.reply_turns: dict[str, int] = {}
self.pending_deletes: dict[str, dict] = {}
self.replies_unanswered: dict[str, int] = {}
@@ -174,6 +176,9 @@ class Session:
# Spoken replies whose speech was cancelled while the brain was still answering.
self.cancelled_replies: set[str] = set()
self.thinking_replies: set[str] = set()
# Answers sent but not yet known to have reached the person: id -> (user, turn, timer).
self.deliveries: dict[str, tuple[str, int, asyncio.TimerHandle | None]] = {}
self._handed_over: dict[str, bool] = {} # replies whose end is counted by _delivered
self.out: asyncio.Queue = asyncio.Queue()
self.closed = False
@@ -211,6 +216,8 @@ class Session:
for fut in self.chat_waiting.values():
if not fut.done():
fut.set_result({"ok": False, "error": "the app disconnected"})
for rid in list(self.deliveries):
self._delivered(rid, False)
ticker.cancel()
writer.cancel()
if w.scheduler:
@@ -309,7 +316,7 @@ class Session:
"chat_delete": self._on_chat_delete, "reply": self._on_reply,
"addressed": self._on_addressed, "rank": self._on_rank,
"chat_channels": self._on_chat_channels, "chat_action_result": self._on_chat_action_result,
"memory_config": self._on_memory_config}.get(kind)
"memory_config": self._on_memory_config, "reply_delivered": self._on_reply_delivered}.get(kind)
if handler is None:
self.error("bad_message", f"unknown type: {kind!r}")
return
@@ -350,6 +357,7 @@ class Session:
tts = self.worker.tts
if tts is None:
self.error("tts_unavailable", "no TTS engine is loaded", id=rid)
self._delivered(rid, False)
return
req = self.tts_requests.get(rid)
if req is None:
@@ -553,10 +561,38 @@ class Session:
finally:
self.thinking_replies.discard(rid)
self.cancelled_replies.discard(rid)
waiting = self.worker.replies_unanswered
waiting[user] -= 1
if not waiting[user]:
del waiting[user]
if not self._handed_over.pop(rid, False): # else _delivered counts it
self._reached(user)
def _reached(self, user: str) -> None:
waiting = self.worker.replies_unanswered
waiting[user] -= 1
if not waiting[user]:
del waiting[user]
def _delivered(self, rid: str, ok: bool) -> None:
"""The answer ``rid`` reached its asker (spoken, or posted by the app), or never will."""
got = self.deliveries.pop(rid, None)
if got is None:
return
user, turn, timer = got
if timer is not None:
timer.cancel()
if not ok:
# They never got this answer, so nothing it asked can be confirmed next.
w = self.worker
w.reply_turns[user] = max(w.reply_turns.get(user, 0), turn + 1)
debug_log(f"brain reply {rid} did not reach the asker", "voice_worker")
self._reached(user)
def _on_reply_delivered(self, msg: dict) -> None:
rid, ok = msg.get("id"), msg.get("ok")
if not isinstance(rid, str) or not isinstance(ok, bool):
self.error("bad_message", "reply_delivered needs a string id and a boolean ok")
return
got = self.deliveries.get(rid)
if got is not None and got[2] is not None: # only chat answers wait for the app's report
self._delivered(rid, ok)
async def _reply_inner(self, rid: str, user: str, text: str, via: str, speak: bool, early: bool) -> None:
w = self.worker
@@ -588,9 +624,17 @@ class Session:
answer = None
answer = (answer or "").strip()
self.send({"type": "reply_text", "id": rid, "text": answer, "failed": not answer})
if not answer or (speak and rid in self.cancelled_replies):
# They never got this answer, so nothing it asked can be confirmed next.
w.reply_turns[user] = max(w.reply_turns.get(user, 0), turn + 1)
# The answer reaches them when spoken (tts_done) or when the app reports the post
# (reply_delivered); an unspoken voice answer has nothing more to wait for.
posted = via == "chat" and not speak
timer = asyncio.get_running_loop().call_later(w.delivery_timeout_s, self._delivered, rid, False) \
if posted else None
self.deliveries[rid] = (user, turn, timer)
self._handed_over[rid] = True
if self.closed or not answer or (speak and rid in self.cancelled_replies):
self._delivered(rid, False)
elif not speak and not posted:
self._delivered(rid, True)
if not answer:
return
if via == "voice" and channel and w.history is not None:
@@ -613,6 +657,7 @@ class Session:
self.tts_requests.pop(req.id, None)
self.send({"type": "tts_done", "id": req.id, "chunks": req.chunks, "cancelled": req.cancelled,
"failed": req.failed})
self._delivered(req.id, not (req.cancelled or req.failed))
def _tts_error(self, req: TtsRequest, message: str) -> None:
self.error("tts_failed", message, id=req.id)

View File

@@ -200,6 +200,7 @@ which carry Discord's own time.
-> {"type": "chat_delete", "channel": "...", "message_id": "..."}
-> {"type": "reply", "id": "r1", "user": "<id>", "text": "...", "via": "voice", "speak": true}
<- {"type": "reply_text", "id": "r1", "text": "...", "failed": false}
-> {"type": "reply_delivered", "id": "c1", "ok": true} // a chat answer was posted (ok: false: it was not)
-> {"type": "addressed", "id": "q1", "user": "<id>", "text": "..."}
<- {"type": "addressed_result", "id": "q1", "addressed": true, "failed": false}
-> {"type": "rank", "id": "k1", "candidates": [{"id": "7", "user": "<id>", "text": "..."}]}
@@ -262,10 +263,14 @@ which carry Discord's own time.
newer action.
With no registered channels the tool is not offered. An action waits up to 15 s for its result
(then it fails), and a closed session fails every waiting action. Each reply counts as one turn
per person, so a delete is confirmed only in that person's next reply. A reply sent before the
person's previous answer was given cannot answer it, and an answer they never got (failed, or
stopped before it was spoken) asked them nothing: in both cases a turn number is skipped, so a
delete asked in that previous answer lapses.
per person, so a delete is confirmed only in that person's next reply. An answer reaches the
person when its speech ends with `tts_done` neither failed nor cancelled (`speak: true`), when the
app reports it posted with `reply_delivered` `ok: true` (`via: "chat"`), or at `reply_text` for an
unspoken voice answer. It never reaches them when the brain gave none, its speech was stopped,
failed or had no TTS (`tts_unavailable`), the app reports `ok: false`, no report comes within 30 s,
or the session ends first. A reply sent before the person's previous answer reached them cannot
answer it, and an answer that never reached them asked them nothing: in both cases a turn number is
skipped, so a delete asked in that previous answer lapses.
- Memory settings, optional in `hello` as `"memory": {...}` and changeable with
`{"type": "memory_config", ...}`: `chat` (true), `others` (true), `off` (false), `since_days`
(null: whole history), `recent_minutes` (30), `recent_records` (20), `matches` (5),