Skip to content
32 changes: 31 additions & 1 deletion gateway/relay/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ def __init__(
self._auto_thread_waiters: Dict[str, asyncio.Event] = {}
# Bounded FIFO seen-set for inbound replay dedupe (insertion-ordered dict).
self._seen_inbound: Dict[str, None] = {}
# Discord labels the text lane carries (connector-resolved) and a forwarded interaction does
# not: (scope, chat) -> (chat_name, chat_topic), (scope, user) -> display name.
self._discord_chat_labels: Dict[tuple, tuple] = {}
self._discord_user_labels: Dict[tuple, str] = {}
# Live cards: draft_key -> draft_id of the OPEN native stream. Armed by
# send_draft; consumed by send() to convert the turn-final into
# draft(final=true) instead of a duplicate post. Keyed by _draft_key (chat +
Expand Down Expand Up @@ -882,6 +886,7 @@ async def _on_inbound(self, event) -> None:
self._seen_inbound[dedupe_key] = None
self._evict_oldest(self._seen_inbound, self._SEEN_INBOUND_MAX)
self._capture_scope(event)
self._remember_discord_labels(event.source)
self._stamp_slack_session_thread(event)
# A structured prompt answer resolves its waiting primitive and is CONSUMED β€”
# never also dispatched as chat.
Expand All @@ -891,6 +896,21 @@ async def _on_inbound(self, event) -> None:
await self.handle_message(event)

_SEEN_INBOUND_MAX = 512
_DISCORD_LABELS_MAX = 2048

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: 2048 per map is generous but cheap (a tuple of two short strings). The only behavioral cost of a miss is one extra re-render on the first interaction after eviction/restart, which is the same as today. No change requested.


def _remember_discord_labels(self, source) -> None:
"""Keep the text lane's Discord chat/user labels for the interaction lane: the pinned
session-context prompt renders them, so a slash turn without them re-rendered the cached
prefix and the next message rendered it back."""
if getattr(source, "platform", None) != Platform.DISCORD or not source.chat_id:
return
scope = str(source.scope_id or "")
if source.chat_name or source.chat_topic:
self._discord_chat_labels[(scope, str(source.chat_id))] = (source.chat_name, source.chat_topic)
self._evict_oldest(self._discord_chat_labels, self._DISCORD_LABELS_MAX)
if source.user_id and source.user_name:
self._discord_user_labels[(scope, str(source.user_id))] = source.user_name
self._evict_oldest(self._discord_user_labels, self._DISCORD_LABELS_MAX)

def _inbound_dedupe_key(self, event) -> Optional[str]:
"""Stable replay identity: (platform, chat, platform message id). The platform
Expand Down Expand Up @@ -1170,6 +1190,14 @@ def _discord_interaction_to_event(self, forward):
if not isinstance(user, dict):
user = {}
guild_id = payload.get("guild_id")
scope, user_id = str(guild_id or ""), str(user.get("id") or "")
# The text lane's user_display_name is the native author.display_name (guild nick, else
# global name, else username); prefer what that lane last carried for this user.
user_name = self._discord_user_labels.get((scope, user_id)) or next(

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up status: Rechecked at fa9259fdc1346c8d2ba5c1bd052358b559777789: addressed by changing the policy to current interaction identity (nick β†’ global name β†’ username) and removing the user cache. The old fixture's differing names represent a nickname change; persisting its stale text name would contradict the new policy. This finding is closed under that policy.


[P2] Preserve text-lane user labels across restart and eviction

Only chat labels get a persisted fallback. Once this user map is empty, the same interaction switches back to its raw nickname even when a matching persisted text origin contains the label the warm path chose.

Reproduction on this head: use the existing warm-case inputs, text user_display_name="Ben D" and raw interaction member.nick="Benny", for the same guild/channel/user. Deliver the text through _on_inbound and persist its session. Warm conversion returns Ben D. Reload the store and create a fresh adapter without changing the interaction body: actual Benny; expected the previously chosen Ben D under this PR's warm parity policy. The real session-context renderer differs in its User field. Keeping the adapter alive and admitting 2048 distinct users through the text lane reproduces the same result through FIFO eviction.

The restart rows currently use nick="Ben D", so they hide the mismatch already permitted by the warm fixture. Repeated interactions retain the raw label until another text observation restores the cached label, recreating message/interaction prompt changes.

Recover the matching user's last authoritative text label on a miss, with an explicit freshness policy for genuine name changes and guild/user isolation. Add restart and user-map eviction cases that keep the warm fixture's differing names unchanged and assert one rendered prompt. Routing IDs remain equal in this probe; this finding concerns label parity.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced the dependence on cache lifetime. I resolved it in the other direction, because your /new nickname finding on #128796 pulls against persisting the text-lane name: a remembered name outlives a nickname change, whatever freshness policy sits on it.

fa9259fd drops the user-label map. The interaction names its user from its own member.nick β†’ user.global_name β†’ user.username, which is what the text lane's user_display_name (discord.py display_name) resolves to at the same moment. Warm, restarted and evicted processes now give the same answer by construction, and your nickname probe passes (New Nick on both turns, one prompt).

As you noted on the issue, the old warm fixture paired Ben D with a fresh Benny, which is a name change rather than a stationary name. The prompt cases now use compatible snapshots, and the second test pins the current-identity rule after an earlier message carried another name. The contract doc now says the connector's user_display_name must resolve the same way.

(str(v) for v in ((member.get("nick") if isinstance(member, dict) else None),
user.get("global_name"), user.get("username")) if v), None)
chat_name, chat_topic = self._discord_chat_labels.get(
(scope, str(payload.get("channel_id") or "")), (None, None))
source = SessionSource(
# The LOGICAL platform, not RELAY: session keys must match the connector's
# capability binding (platform="discord"), /sethome must file under the
Expand All @@ -1180,7 +1208,9 @@ def _discord_interaction_to_event(self, forward):
# native Discord adapter key guild channels as "group".
chat_type="group" if guild_id else "dm",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking residual, same family: the interaction lane still never sets thread_id / parent_chat_id, both of which are in the Discord tuple of _ephemeral_change_key (and thread_id is in the session-key _ALWAYS_FIELDS). So a slash command inside a thread still diverges from the text lane there. The interaction body does carry enough to close it: channel.type in (11, 12) marks a thread and channel.parent_id is the parent, so thread_id=channel_id, parent_chat_id=parent_id can be derived without any remembered state. Fine as a follow-up; noting it so the class is closed knowingly rather than by omission.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Closed in 6aad417 rather than left as a follow-up, since the divergence is a session split, not only a pin flip. On the previous head, with the text lane's thread message keyed per the contract (chat_id = thread_id = the thread channel, chat_type: thread):

text  key= agent:main:discord:thread:th1:th1
slash key= agent:main:discord:group:th1:u1

so a slash command inside a relayed thread ran in a per-user session beside the thread's shared one. The interaction lane now derives chat_type: thread, thread_id = channel_id and parent_chat_id = channel.parent_id when the partial channel.type is 10, 11 or 12 (announcement threads included, which is what discord.Thread covers natively). No remembered state, as you noted. A body without the channel object (or a DM) keys exactly as before.

One dependency, stated in the contract doc (Β§3.1): the session source mirrors the connector's interactionSessionSource, which binds the discord.interaction_token capability, so the connector's binding for a thread interaction has to derive the same fields before a follow_up caller lands. There is no in-tree caller of send_follow_up today (only tests), so nothing changes at runtime until then.

Test: the thread row of the parity test asserts the two session keys are equal and the pinned prompt stays one across message β†’ slash β†’ message. Red on cd581c70 with the key diff above, green now; the 46 tests/gateway/relay/ files stay green.

user_id=str(user["id"]) if user.get("id") else None,
user_name=str(user["username"]) if user.get("username") else None,
user_name=user_name,
chat_name=chat_name,
chat_topic=chat_topic,
scope_id=str(guild_id) if guild_id else None,
message_id=str(payload.get("id")) if payload.get("id") else None,
# Same upstream-trust marker the relay text lane stamps. Set locally, never

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep interaction identity separate from actual message identity

This source still uses payload.id as message_id. Discord's interaction schema distinguishes the interaction ID from the component's attached message.id. The resulting MessageEvent also leaves its own message_id empty. These existing boundary defects are relevant to the full prompt/input-parity class even though this assignment predates the diff.

Reproduction: forward a type-3 component with id=i1, message.id=actual-message-77, and a foreign custom_id that follows the normal text/agent path. The real converter returns source.message_id=i1, event.message_id=None. Passing its real SessionContext through GatewayRunner._set_session_env exposes HERMES_SESSION_MESSAGE_ID=i1, not the actual attached message. Thus source-based consumers receive an interaction identifier as a message target, while event-based reply/message-note consumers receive no message identifier.

A second real-wire probe provides a text frame's root message_id=platform-message-1 but omits the optional nested source.message_id. The text decoder leaves the source ID empty; the interaction source always has one. With actual Discord tool capability enabled and equal labels/user/session keys, the pinned renderer still changes its Triggering message guidance. Label parity alone therefore does not close the prefix class.

Normalize event/source message identity at the boundary and represent the interaction identifier separately. Use the attached actual message for components; slash invocations with no platform message must not invent one. Regress both component identity and root-only text frames with tools enabled. Both probes also fail on the merge base; they require repair but are not new regressions introduced by this PR.

Verified on fa9259fdc1346c8d2ba5c1bd052358b559777789 and its clean composition onto upstream 8d30c4eaabd85edb77a02fef6c5388d9344ef80c, using scripts/run_tests.sh, a temporary HERMES_HOME, real SQLite/SessionStore, and real boundary conversion. Only final message dispatch was mocked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and older than this PR (same on the merge base). Filed as #130306 with your probes, crediting you. It stays out of this PR on purpose. teknium1's review of #129032 measured what an identity split does to the slash prompt when source.message_id presence changes. This PR keeps today's identity, and the test now renders the prompt with Discord tools loaded, so a split that drops source.message_id fails 11 cases.

Expand Down
63 changes: 63 additions & 0 deletions tests/gateway/relay/test_relay_discord_interaction_labels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""A relayed Discord interaction carries the same chat/user labels as a relayed message in that chat.

The text lane gets ``chat_name``, ``chat_topic`` and ``user_display_name`` from the connector; a
forwarded interaction (slash command, component) is the raw Discord body. Both land in one session,
and the pinned session-context prompt renders those labels, so a slash turn built without them
re-rendered the cached prefix and the next message rendered it back.
"""

import json
from unittest.mock import AsyncMock

import pytest

import gateway.run as gateway_run
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.relay.ws_transport import _event_from_wire
from gateway.session import build_session_context
from tests.gateway.relay.test_relay_interactive import _adapter


def _forward(**payload):
body = {"type": 2, "id": "i1", "channel_id": "ch1", "guild_id": "g1", "data": {"name": "status"}}

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] F04 β€” Read-only status consumes first-agent-turn initialization through timestamp-based newness

Attribution: inherited.

This /status fixture is converted and rendered, not run through its lifecycle. The real status handler gets or creates the row. The next existing-row lookup updates activity, before created_at == updated_at is used as newness.

Probe: real status handler and real SessionStore, with expensive model-route/status-display leaves substituted. After /status then first agent lookup, _hmwa_open_session returns (False, False) and emits zero session:start hooks. Direct-first control returns (False, True), emits once. Both head and base reproduce. Driving the real turn-preparation guard with manually supplied auto_skill calls the skill loader in the direct control but not after status; execution stops before the model.

Important narrowing: relay text reconstruction and interaction construction do not populate auto_skill. Thus the hook failure is demonstrated; unconditional relayed configured-skill loss is not established by that manually seeded fixture. The earlier issue wording needs that qualification.

Repair/closure: represent initialization for an agent/session incarnation separately from last activity. Regress real /status β†’ first text and /status β†’ first model-reaching command, with direct-first and later-turn controls. If relay skill parity is intended, exercise its actual producer separately rather than manufacturing auto_skill in every test.

Fresh receipt: lifecycle-parent and lifecycle-base-parent: status_first_turn, manual_skill_guard, auto_skill_wire. Head fa9259fdc1346c8d2ba5c1bd052358b559777789; native Windows; inert external I/O. Full reconciliation and test boundaries are in the review body.

Code under discussion β€” producer, state owner, and consumers:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed by trace: _hmwa_open_session decides newness by created_at == updated_at, /status creates the entry, and the first real message's lookup moves updated_at. Older than this PR, gateway-wide, different class. Filed as #130304, crediting you.

body.update(payload)

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] F09 β€” Context-menu commands are flattened to slash names without their selected target

Attribution: inherited.

Outer interaction type 2 is not synonymous with a slash/chat-input command. Discord's application-command data schema distinguishes the inner type and context-menu target_id. The current converter emits only /name and option values; event construction preserves neither target nor resolved message.

Probe: a type-2 message command with inner data.type=3, target_id=selected-message-99 and matching resolved content becomes '/summarize', metadata={}, raw_message=None. The target cannot be recovered from the event. The nested slash control becomes '/skill run deploy' with its expected arguments. The merge-base adapter gives the same projection.

Consequence/limit: a context-menu request reaching this generic boundary loses what it was invoked on; additionally unknown slash dispatch is not a general substitute for processing that selected message. This does not establish that the external connector currently registers or forwards this command type.

Repair/closure: branch by inner command subtype and preserve the resolved target in a defined consumer contract, or explicitly reject unsupported context-menu types. Tests need target-distinct cases, user/message command controls and existing slash/subcommand compatibility. Do not equate a parsed slash string with preserved command intent.

Fresh receipt: consumers-isolated: context-menu target assertion fails; exact-base equivalence passes. Head fa9259fdc1346c8d2ba5c1bd052358b559777789; native Windows; inert external I/O. Full reconciliation and test boundaries are in the review body.

Code under discussion β€” producer, state owner, and consumers:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: a context-menu command arrives as a bare /summarize, with no target_id and no resolved object. Filed in #130305.


class Forward:
platform, method, path = "discord", "POST", "/interactions/bot1"

Forward.body = json.dumps(body).encode()

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] F10 β€” Interaction action IDs are advertised and used as provider message targets

Attribution: inherited.

Discord defines payload.id as interaction ID and message.id as the attached message when present. The converter conflates the former with source.message_id, while only hp1 prompt responses retain attached message identity. The new fixture's interaction ID therefore needs consumer assertions, not merely a label assertion.

Observed: component id=interaction-1 attached to message=attached-message-77 β†’ real session context exposes HERMES_SESSION_MESSAGE_ID=interaction-1, event.message_id=None. Cached guidance says the triggering message is supplied per-turn, but the event-ID note supplies none. Actual processing lifecycle emits local stub react operations targeting the interaction ID; normal text targets its message ID. Slash without any attached message has the same misleading source target. These behaviors predate the PR. No external reaction API or message disclosure was tested.

Repair/closure: represent interaction action identity separately from an actual message target and any reply anchor. Components may have a real attached target; slash interactions may have none. Preserve action identity for F01 without treating it as a reply/react ID. Multiple clicks on one attached message must remain distinct actions. Tests should cover tool context, rendered promise, per-turn note, reactions and persistence owner, not only constructor fields.

Fresh receipt: consumers-isolated: component/slash identity assertions fail; lifecycle both pins: reaction_id_kind, delivery_accounting, turn_owner. Head fa9259fdc1346c8d2ba5c1bd052358b559777789; native Windows; inert external I/O. Full reconciliation and test boundaries are in the review body.

Code under discussion β€” producer, state owner, and consumers:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and older than this PR. Filed as #130306 with F11 and the earlier inline. See the reply on line 1260 for why it stays out of this PR.

return Forward()


def _pinned_prompt(source):
runner = object.__new__(gateway_run.GatewayRunner)
config = GatewayConfig(platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="x")})
return runner._pinned_session_context_prompt(build_session_context(source, config), False, "k")


@pytest.mark.asyncio
async def test_slash_between_messages_keeps_one_pinned_prompt():
adapter, _stub = _adapter(platform="discord")
adapter.handle_message = AsyncMock()
message = _event_from_wire({"text": "hi", "message_type": "text", "source": {
"platform": "discord", "chat_id": "ch1", "chat_type": "group", "scope_id": "g1",
"user_id": "u1", "user_name": "ben", "user_display_name": "Ben D",
"chat_name": "Hermes Server / #ops", "chat_topic": "Incident triage", "message_id": "m1"}})
await adapter._on_inbound(message)
slash = adapter._discord_interaction_to_event(
_forward(member={"nick": "Benny", "user": {"id": "u1", "username": "ben"}}))

prompts = {_pinned_prompt(event.source) for event in (message, slash, message)}

@andrexibiza andrexibiza Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] F06 β€” Select component identity survives while the actual selected values disappear

Attribution: inherited.

Type-3 conversion projects only custom_id. Discord's component-data schema makes values present for select components. The hp1 prompt-token path is a separate recognized control and is not evidence that generic selects preserve their values.

Probe: the registered callback receives a type-3 select with custom_id=choose, component_type=3 and values=[item-b]. The dispatched event is text='choose', metadata={}, prompt_response=None; the selected value appears nowhere. An ordinary button produces its intended custom_id. The exact merge-base adapter produces the same output tuple. No real select was registered or invoked in Discord.

Consequence: if such a select reaches this generic forwarder, the consumer cannot distinguish selections. That conditional boundary is demonstrated; deployment frequency and supported connector menus are not. This is separate from modal flattening because it uses an otherwise implemented branch and needs value-aware component handling.

Repair/closure: distinguish component type and carry selected values/resolved entities without confusing them with developer-defined custom_id. Alternatively reject unsupported select types explicitly. A regression should compare two different choices with the same custom_id and require different preserved user input, plus a button and recognized hp1 control.

Fresh receipt: consumers-isolated: test_select_component_preserves_user_choices fails; exact-base adapter equivalence passes. Head fa9259fdc1346c8d2ba5c1bd052358b559777789; native Windows; inert external I/O. Full reconciliation and test boundaries are in the review body.

Code under discussion β€” producer, state owner, and consumers:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: values are dropped and only custom_id survives. Filed in #130305.

assert len(prompts) == 1


@pytest.mark.parametrize("member, expected", [
({"nick": "Benny", "user": {"id": "u1", "username": "ben", "global_name": "Ben D"}}, "Benny"),
({"user": {"id": "u1", "username": "ben", "global_name": "Ben D"}}, "Ben D"),
({"user": {"id": "u1", "username": "ben"}}, "ben"),
])
def test_first_interaction_names_the_user_like_the_text_lane(member, expected):
"""With no relayed message seen yet, the name follows the text lane's contract:
user_display_name is the native author.display_name (guild nick, else global name, else username)."""
adapter, _stub = _adapter(platform="discord")
assert adapter._discord_interaction_to_event(_forward(member=member)).source.user_name == expected
Loading