Repository navigation
fix(relay): a relayed Discord interaction carries the text lane's chat and user labels #128797
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
40322be
cd581c7
6aad417
0f3aa86
fa9259f
10b955a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 + | ||
|
|
@@ -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. | ||
|
|
@@ -891,6 +896,21 @@ async def _on_inbound(self, event) -> None: | |
| await self.handle_message(event) | ||
|
|
||
| _SEEN_INBOUND_MAX = 512 | ||
| _DISCORD_LABELS_MAX = 2048 | ||
|
|
||
| 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 | ||
|
|
@@ -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( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Follow-up status: Rechecked at [P2] Preserve text-lane user labels across restart and evictionOnly 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 The restart rows currently use 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.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
As you noted on the issue, the old |
||
| (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 | ||
|
|
@@ -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", | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Non-blocking residual, same family: the interaction lane still never sets
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 ( 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 One dependency, stated in the contract doc (Β§3.1): the session source mirrors the connector's Test: the |
||
| 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 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Keep interaction identity separate from actual message identityThis source still uses Reproduction: forward a type-3 component with A second real-wire probe provides a text frame's root 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
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
|
||
| 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"}} | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 newnessAttribution: 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 Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed by trace: |
||
| body.update(payload) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 targetAttribution: 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 Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed: a context-menu command arrives as a bare |
||
|
|
||
| class Forward: | ||
| platform, method, path = "discord", "POST", "/interactions/bot1" | ||
|
|
||
| Forward.body = json.dumps(body).encode() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F10 β Interaction action IDs are advertised and used as provider message targetsAttribution: 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 Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)} | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] F06 β Select component identity survives while the actual selected values disappearAttribution: 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 Code under discussion β producer, state owner, and consumers:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed: |
||
| 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 | ||
There was a problem hiding this comment.
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.