Skip to content

The agent that grows with you

fix(discord): a spoken turn reads its thread's parent bindings and the channel's current labels

John Paul Soliva04a6eb4835c9
diff --git a/gateway/run_voice.py b/gateway/run_voice.py
index f5e6537fa40..44b759e11e8 100644
--- a/gateway/run_voice.py
+++ b/gateway/run_voice.py
@@ -235,18 +235,29 @@ class GatewayVoiceMixin:
session), else a synthetic one."""
# The speaker's display name, as their typed messages carry it: the pinned session-context
# prompt renders it, so a bare id here re-rendered it on every spoken/typed switch.
- guild = getattr(adapter, "_client", None) and adapter._client.get_guild(guild_id)
+ client = getattr(adapter, "_client", None)
+ guild = client.get_guild(guild_id) if client else None
member = guild.get_member(int(user_id)) if guild else None
display_name = getattr(member, "display_name", None)
- user_name = display_name if isinstance(display_name, str) and display_name else str(user_id)
+ user_name = display_name if isinstance(display_name, str) and display_name else None
if source_data := getattr(adapter, "_voice_sources", {}).get(guild_id):
source = SessionSource.from_dict(source_data)
- source.user_id, source.user_name = str(user_id), user_name
+ # get_member() is cache-only: on a miss the /voice join invoker keeps the name bound at
+ # join, never another participant's.
+ if user_name is None and source.user_id == str(user_id):
+ user_name = source.user_name
+ source.user_id, source.user_name = str(user_id), user_name or str(user_id)
else:
source = SessionSource(
platform=Platform.DISCORD, chat_id=str(text_ch_id), user_id=str(user_id),
- user_name=user_name, chat_type="channel",
+ user_name=user_name or str(user_id), chat_type="channel",
profile=getattr(adapter, "_owner_profile", None))
+ # The stored source is a join-time copy; a typed message reads the channel's current name and
+ # topic, so a rename or topic edit would otherwise flip the pinned prompt on every switch.
+ channel = client.get_channel(int(text_ch_id)) if client else None
+ if channel is not None and callable(labels := getattr(adapter, "_guild_channel_labels", None)):
+ if isinstance(current := labels(channel), tuple):
+ source.chat_name, source.chat_topic = current
# Serialization drops transport provenance; auth must still follow the receiving bot.
source._transport_adapter_ref = weakref.ref(adapter)
return source
@@ -289,13 +300,15 @@ class GatewayVoiceMixin:
await channel.send(t("gateway.voice.transcript_echo", user=user_id, text=safe_text))
# Bound text channel's channel_prompt and skills: voice input gets the same per-channel
# context, and a first spoken turn opens the session, the only point skills load.
+ # A thread inherits its parent's bindings, as its typed messages do.
channel_prompt = auto_skill = None
+ parent_id = source.parent_chat_id or None
if callable(resolver := getattr(adapter, "_resolve_channel_prompt", None)):
with suppress(Exception):
- resolved = resolver(str(text_ch_id))
+ resolved = resolver(str(text_ch_id), parent_id)
channel_prompt = resolved if isinstance(resolved, str) else None
if callable(skills := getattr(adapter, "_resolve_channel_skills", None)):
- bound = skills(str(text_ch_id))
+ bound = skills(str(text_ch_id), parent_id)
auto_skill = bound if isinstance(bound, list) else None
# Synthetic MessageEvent for the normal pipeline; the SimpleNamespace raw_message lets
# _get_guild_id() extract guild_id so _send_voice_reply() plays audio in the voice channel.
diff --git a/plugins/platforms/discord/adapter_thread_titles.py b/plugins/platforms/discord/adapter_thread_titles.py
index 8f4580209f1..c1557f7234e 100644
--- a/plugins/platforms/discord/adapter_thread_titles.py
+++ b/plugins/platforms/discord/adapter_thread_titles.py
@@ -13,6 +13,11 @@ from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any
+try:
+ import discord
+except ImportError: # the adapter does not start without discord.py
+ discord = None
+
_MAX_RECORDS = 2000
@@ -73,6 +78,7 @@ class SemanticThreadRenames:
class DiscordThreadTitlesMixin:
_semantic_thread_renames: SemanticThreadRenames
_is_forum_parent: Callable[[Any], bool]
+ _get_effective_topic: Callable[..., str | None]
async def _on_platform_raw_thread_update(self, payload: Any) -> None:
# discord.py updates the cached thread before cached callbacks run, so batched updates
@@ -96,3 +102,10 @@ class DiscordThreadTitlesMixin:
if parent_name:
return f"{parent_name} / {thread_name}"
return thread_name
+
+ def _guild_channel_labels(self, channel: Any) -> tuple[str, str | None]:
+ """``(chat_name, chat_topic)`` for a guild channel or thread, as a message posted there gets them."""
+ if isinstance(channel, discord.Thread):
+ return self._format_thread_chat_name(channel), self._get_effective_topic(channel, is_thread=True)
+ name, guild = getattr(channel, "name", str(channel.id)), getattr(channel, "guild", None)
+ return (f"{guild.name} / #{name}" if guild else name), self._get_effective_topic(channel)
diff --git a/tests/gateway/test_discord_turn_prompt_parity.py b/tests/gateway/test_discord_turn_prompt_parity.py
index 3312d31680a..1c61ff913b4 100644
--- a/tests/gateway/test_discord_turn_prompt_parity.py
+++ b/tests/gateway/test_discord_turn_prompt_parity.py
@@ -5,6 +5,8 @@ input are human turns: each re-pins the session-context prompt and the channel p
another chat label (DM: none; thread: without its parent channel), another topic or a bare user id,
they re-rendered the pinned prompt, and the next typed message rendered it back: a prompt-cache miss
each way. Built without ``auto_skill``, a session they opened never loaded the channel's bound skill.
+Voice rebuilds its source from a ``/voice join`` copy, so it must also see the parent's bindings from a
+thread and the channel's current name and topic.
"""
from datetime import datetime, timezone
@@ -109,15 +111,22 @@ async def test_slash_and_thread_starter_turns_match_a_message_turn(monkeypatch,
@pytest.mark.asyncio
-async def test_voice_channel_turn_matches_a_typed_turn(monkeypatch):
[email protected]("case", ["channel", "thread-under-bound-parent", "renamed-after-join", "speaker-uncached"])
+async def test_voice_channel_turn_matches_a_typed_turn(monkeypatch, case):
parent = _parent()
+ channel = _Thread(800, parent) if case == "thread-under-bound-parent" else parent
adapter = _adapter(monkeypatch, parent.id)
- typed = await _typed(adapter, parent)
join = adapter._build_slash_event(
- SimpleNamespace(channel=parent, channel_id=parent.id, guild=parent.guild, guild_id=1, user=_USER),
+ SimpleNamespace(channel=channel, channel_id=channel.id, guild=parent.guild, guild_id=1, user=_USER),
"/voice join")
- adapter._voice_text_channels = {1: parent.id}
+ adapter._voice_text_channels = {1: channel.id}
adapter._voice_sources = {1: join.source.to_dict()}
+ adapter._client.get_channel = {channel.id: channel}.get
+ if case == "renamed-after-join":
+ channel.name, channel.topic = "renamed", "New topic"
+ if case == "speaker-uncached":
+ adapter._client.get_guild = lambda _id: SimpleNamespace(get_member=lambda _uid: None)
+ typed = await _typed(adapter, channel)
runner = object.__new__(gateway_run.GatewayRunner)
runner.adapters = {Platform.DISCORD: adapter}
runner._voice_mode = {}
@@ -130,3 +139,6 @@ async def test_voice_channel_turn_matches_a_typed_turn(monkeypatch):
spoken = adapter.handle_message.await_args.args[0]
assert spoken is not typed
_assert_same_prompt_inputs(typed, spoken)
+ # The join-time name belongs to the joiner only; another uncached speaker never borrows it.
+ other = runner._voice_input_source(adapter, 1, 43, channel.id).user_name
+ assert other == ("43" if case == "speaker-uncached" else "Alice")
diff --git a/tests/gateway/test_voice_command.py b/tests/gateway/test_voice_command.py
index b26521e36df..8950e43d9af 100644
--- a/tests/gateway/test_voice_command.py
+++ b/tests/gateway/test_voice_command.py
@@ -592,7 +592,7 @@ class TestVoiceChannelCommands:
mock_adapter._resolve_channel_prompt = MagicMock(return_value="Be terse in #dev.")
runner.adapters[Platform.DISCORD] = mock_adapter
await runner._handle_voice_channel_input(111, 42, "Hello from VC")
- mock_adapter._resolve_channel_prompt.assert_called_once_with("123")
+ mock_adapter._resolve_channel_prompt.assert_called_once_with("123", None)
event = mock_adapter.handle_message.call_args[0][0]
assert event.channel_prompt == "Be terse in #dev."