The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): synthetic goal turns keep inherit_channel_pin across native admission
Tekniumdfc46828ef90
diff --git a/gateway/session_envelope.py b/gateway/session_envelope.pyindex d8568cabc3f..52ad7fc9342 100644--- a/gateway/session_envelope.py+++ b/gateway/session_envelope.py@@ -205,6 +205,8 @@ def _snapshot_native(runner, event, provenance, fresh_roles=False, encoded_sourc# its fingerprint. Explicit context (including an empty skill list) is exact.envelope['event'].update({name: deepcopy(getattr(event, name)) for name in _CONTEXT_FIELDSif getattr(event, name) is not None})+ if event.inherit_channel_pin is True: # synthetic goal/resume turn reuses the session's pins (#126109)+ envelope['event']['inherit_channel_pin'] = Trueif metadata := _native_metadata(event):envelope['event']['metadata'] = metadataif event.message_type != MessageType.TEXT:diff --git a/tests/gateway/test_internal_event_pin_wiring.py b/tests/gateway/test_internal_event_pin_wiring.pyindex d7869fb6fd1..323b3c07154 100644--- a/tests/gateway/test_internal_event_pin_wiring.py+++ b/tests/gateway/test_internal_event_pin_wiring.py@@ -427,7 +427,23 @@ async def test_synthetic_goal_turn_keeps_pins_and_effective_prompt(monkeypatch,await _drive(runner, ((False, human),), channel_prompt="Channel hint.")synthetic = _synthetic_turn(runner, human, kind)assert not synthetic.internal and synthetic.channel_prompt is None- await runner._handle_message_with_agent(synthetic, synthetic.source, KEY, 1)+ if kind == "goal-continuation":+ # A continuation queued behind the running turn drains through the in-band follow-up.+ runner._run_agent_deliver_first_response = AsyncMock()+ runner._refresh_agent_cache_message_count = AsyncMock()+ runner._session_key_for_source = lambda _source: KEY+ adapter = MagicMock(_active_sessions={}, _pending_messages={KEY: synthetic})+ adapter.get_pending_message = lambda key: adapter._pending_messages.pop(key, None)+ result = {"final_response": "done", "messages": []}+ pending_event, pending = await runner._run_agent_drain_pending(result, adapter, human, KEY)+ assert pending_event is synthetic+ first = calls[0]+ turn_ctx = TurnContext(source=first["source"], context_prompt=first["context_prompt"],+ channel_prompt=first["channel_prompt"], session_key=KEY,+ session_id=first["session_id"], run_generation=1, history=[])+ await runner._run_agent_queued_followup(turn_ctx, adapter, pending, pending_event, "done", result, None)+ else:+ await runner._handle_message_with_agent(synthetic, synthetic.source, KEY, 1)assert runner._peek_session_state(KEY).conversation.channel_pin[0] == "Channel hint."await _drive(runner, ((False, human),), channel_prompt="Channel hint.")@@ -437,6 +453,48 @@ async def test_synthetic_goal_turn_keeps_pins_and_effective_prompt(monkeypatch,assert eph[0] == eph[1] == eph[2], "synthetic turn toggled the effective ephemeral prompt"+async def test_goal_continuation_keeps_channel_pin_through_session_authority(tmp_path, monkeypatch):+ """The default runtime admits adapter turns through the native session envelope; a goal+ continuation must arrive at the handler still asking to reuse the pins (#126109)."""+ import gateway.run as gr+ from gateway.platforms.base import SendResult+ from gateway.session_authority import initialize_session_authority+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter+ from tests.waiting import async_wait_until++ chat = "[email protected]"+ monkeypatch.setenv("WHATSAPP_ALLOWED_USERS", "15551234567")+ monkeypatch.setattr(gr, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "fake"})+ runner = gr.GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ adapter = WhatsAppAdapter(PlatformConfig(enabled=True, extra={+ "text_batch_delay_seconds": 0, "session_path": str(tmp_path / "wa")}))+ adapter.gateway_runner, runner.adapters = runner, {Platform.WHATSAPP: adapter}+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="pins")+ runner._wire_adapter_handlers(adapter)+ calls: list[dict] = []+ _capture(runner, calls)+ monkeypatch.setattr(adapter, "send", AsyncMock(return_value=SendResult(success=True, message_id="s")))+ source = adapter.build_source(chat_id=chat, user_id=chat, chat_type="dm")+ turns = (+ MessageEvent(text="hi", source=source, message_id="h1", channel_prompt="Channel hint."),+ runner._synthetic_prompt_event(source, "[Continuing toward your standing goal]\nGoal: x"),+ MessageEvent(text="hi again", source=source, message_id="h2", channel_prompt="Channel hint."),+ )+ try:+ for index, event in enumerate(turns):+ await adapter.handle_message(event)+ await async_wait_until(+ lambda: len(calls) > index and not adapter._background_tasks and not adapter._session_tasks,+ timeout=60, what=f"turn {index}")+ finally:+ authority.db.close()++ assert [kw["channel_prompt"] for kw in calls] == ["Channel hint."] * 3+ pin = runner._peek_session_state(runner._session_key_for_source(source)).conversation.channel_pin+ assert pin[0] == "Channel hint."++@pytest.mark.asyncioasync def test_human_turn_without_channel_prompt_still_replaces_the_pin(monkeypatch):"""Negative control: only synthetic turns inherit. A human turn whose channel prompt wasdiff --git a/tests/gateway/test_queue_consumption.py b/tests/gateway/test_queue_consumption.pyindex 79d323262cc..3fd3619b08c 100644--- a/tests/gateway/test_queue_consumption.py+++ b/tests/gateway/test_queue_consumption.py@@ -265,3 +265,18 @@ class TestBusyInputModeQueueFifo:assert head.media_urls == ["/tmp/a.jpg", "/tmp/b.jpg"]assert "first" in head.text and "second" in head.textassert runner._queue_depth(session_key, adapter=adapter) == 1++ def test_photo_never_merges_into_a_queued_goal_continuation(self):+ """A human photo arriving behind a synthetic continuation keeps its own turn: merged, it+ would run under the continuation's inherited pins instead of its own channel inputs."""+ runner, adapter = self._make_runner_and_adapter()+ session_key = "telegram:user:goal-photo"+ continuation = self._text_event("[goal] continue")+ continuation.inherit_channel_pin = True+ runner._queue_or_replace_pending_event(session_key, continuation)+ runner._queue_or_replace_pending_event(+ session_key, self._media_event("/tmp/a.jpg", "image/jpeg", MessageType.PHOTO))++ assert adapter._pending_messages[session_key] is continuation+ assert continuation.media_urls == []+ assert runner._queue_depth(session_key, adapter=adapter) == 2