:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): close slack agent-design replies when a background turn ends (#110850)
Vojta Bartošd3d37ae7d0a3
diff --git a/ee/hogai/sandbox/__init__.py b/ee/hogai/sandbox/__init__.pyindex a46515b5f01b..c2a4bbb2f0b4 100644--- a/ee/hogai/sandbox/__init__.py+++ b/ee/hogai/sandbox/__init__.py@@ -1,8 +1,10 @@from ee.hogai.sandbox.types import (+ BACKGROUND_TURN_COMPLETE_METHOD,IDLE_RESUME_STOP_REASON,PI_RUNTIME_ERROR_MESSAGE,STOP_REASON_END_TURN,TURN_COMPLETE_METHOD,+ is_background_turn_complete,is_idle_resume_turn_complete,is_turn_complete,pi_turn_error,@@ -11,10 +13,12 @@ from ee.hogai.sandbox.types import ()__all__ = [+ "BACKGROUND_TURN_COMPLETE_METHOD","IDLE_RESUME_STOP_REASON","PI_RUNTIME_ERROR_MESSAGE","STOP_REASON_END_TURN","TURN_COMPLETE_METHOD",+ "is_background_turn_complete","is_idle_resume_turn_complete","is_turn_complete","pi_turn_error",diff --git a/ee/hogai/sandbox/types.py b/ee/hogai/sandbox/types.pyindex 5a28f1491382..ab254c960ae6 100644--- a/ee/hogai/sandbox/types.py+++ b/ee/hogai/sandbox/types.py@@ -11,6 +11,7 @@ ACP_METHOD_SESSION_UPDATE = "session/update"# Sandbox-specific notification methodsTURN_COMPLETE_METHOD = "_posthog/turn_complete"+BACKGROUND_TURN_COMPLETE_METHOD = "_posthog/background_turn_complete"# Stop reasonsSTOP_REASON_END_TURN = "end_turn"@@ -48,6 +49,19 @@ def is_turn_complete(event: Mapping[str, object]) -> bool:return isinstance(result, dict) and result.get("stopReason") == STOP_REASON_END_TURN+def is_background_turn_complete(event: Mapping[str, object]) -> bool:+ """Check if a sandbox event ends a turn that the agent started without a user prompt.++ The agent starts such a turn when a background task that it launched finishes. That turn+ has no prompt response, so the agent server reports its end with this notification and not+ with ``_posthog/turn_complete``. ``is_turn_complete`` does not match it.+ """+ if event.get("type") != ACP_NOTIFICATION_TYPE:+ return False+ notification = event.get("notification")+ return isinstance(notification, dict) and notification.get("method") == BACKGROUND_TURN_COMPLETE_METHOD++def is_idle_resume_turn_complete(event: Mapping[str, object]) -> bool:if event.get("type") != ACP_NOTIFICATION_TYPE:return Falsediff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex 8e9e5d3de6da..f9bc36ddf009 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -60,6 +60,7 @@ from products.tasks.backend.turn_completed import dispatch_turn_completedfrom ee.hogai.sandbox import (PI_RUNTIME_ERROR_MESSAGE,+ is_background_turn_complete,is_idle_resume_turn_complete,is_turn_complete,pi_turn_error,@@ -588,18 +589,22 @@ async def _relay_loop(and workflow_handle is not None):slack_turn_active[0] = False- # Awaited in order: the final prose must be recorded before- # turn_completed, which clears the parent's relay id and would- # otherwise drop a delta that arrived after it.- await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)- await _signal_safely(+ await _complete_slack_turn(workflow_handle,- "turn_completed",- arg=turn_complete_trace_id(event_data),+ pending_text_parts,+ last_text_flush,+ turn_complete_trace_id(event_data),)final_text = final_message_tracker.end_turn()if final_text is not None and task_run is not None:await asyncio.to_thread(_persist_final_message, run_id, final_text)+ elif is_background_turn_complete(event_data):+ if is_agent_design_enabled and slack_turn_active[0] and workflow_handle is not None:+ slack_turn_active[0] = False+ # The agent server reports no trace id for a background turn.+ await _complete_slack_turn(+ workflow_handle, pending_text_parts, last_text_flush, None+ )elif not agent_active[0] and _is_active_agent_update(event_data):agent_active[0] = Trueif workflow_handle is not None:@@ -934,6 +939,18 @@ async def _flush_pending_text(pending_text_parts.clear()+async def _complete_slack_turn(+ workflow_handle: temporalio.client.WorkflowHandle,+ pending_text_parts: list[str],+ last_text_flush: list[float],+ trace_id: str | None,+) -> None:+ # Awaited in order: the final prose must be recorded before turn_completed, which clears+ # the parent's relay id and would otherwise drop a delta that arrived after it.+ await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)+ await _signal_safely(workflow_handle, "turn_completed", arg=trace_id)++async def _signal_safely(workflow_handle: temporalio.client.WorkflowHandle,signal_name: str,diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.pyindex 63d854098104..288e37a35340 100644--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py@@ -26,7 +26,7 @@ from products.tasks.backend.logic.stream.redis_stream import ()from products.tasks.backend.models import TaskRun as TaskRunModel-from ee.hogai.sandbox import is_turn_complete, turn_complete_trace_id+from ee.hogai.sandbox import is_background_turn_complete, is_turn_complete, turn_complete_trace_id# Reuse the ACP event helpers, signal dispatcher, and SSE reconnect tuning from relay_sandbox_events# so the two relays derive/emit signals and drive their SSE transport from identical logic.@@ -48,6 +48,7 @@ logger = structlog.get_logger(__name__)HEARTBEAT_INTERVAL_SECONDS = 30# Terminal SSE frame name emitted when the run's stream is complete (matches the stream endpoints).STREAM_END_EVENT_NAME = "stream-end"+BACKGROUND_TURN_OPENERS = frozenset({"_posthog/task_notification", "_posthog/background_turn_started"})class SlackAgentDesignSignalEmitter:@@ -55,7 +56,8 @@ class SlackAgentDesignSignalEmitter:``SlackAgentDesignRelayWorkflow`` on the parent ``ProcessTaskWorkflow``.Stateful per run: a turn is bracketed from the first ``session/update`` after a user- ``session/prompt`` until the turn-complete notification, and tool-call ids are de-duplicated+ ``session/prompt`` or a background task notification until the turn-complete or+ background-turn-complete notification, and tool-call ids are de-duplicatedfor the lifetime of the run (the set is not cleared between turns). The inline fan-out in``relay_sandbox_events._relay_loop`` shares this bracketing but still opens on any``session/update`` — it needs the same prompt gate to stop trailing updates opening phantom turns.@@ -93,7 +95,15 @@ class SlackAgentDesignSignalEmitter:self._turn_message_id = _prompt_message_id(event_data)return []- if is_turn_complete(event_data):+ # A finished background task makes the agent start a turn without a user prompt. The Claude+ # adapter reports the task notification, and the Codex adapter reports the turn start.+ if _event_method(event_data) in BACKGROUND_TURN_OPENERS:+ if not self._turn_active:+ self._awaiting_turn = True+ self._turn_message_id = None+ return []++ if is_turn_complete(event_data) or is_background_turn_complete(event_data):if self._turn_active:self._turn_active = False# The trace id rides the signal because this event is the only place itdiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex 2c87edbbe095..3b74ba2c08a6 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -50,7 +50,13 @@ from products.tasks.backend.temporal.process_task.workflow import (ProcessTaskWorkflow,)-from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, TURN_COMPLETE_METHOD, is_turn_complete, pi_turn_error+from ee.hogai.sandbox import (+ BACKGROUND_TURN_COMPLETE_METHOD,+ PI_RUNTIME_ERROR_MESSAGE,+ TURN_COMPLETE_METHOD,+ is_turn_complete,+ pi_turn_error,+)relay_sandbox_events_module = importlib.import_module("products.tasks.backend.temporal.process_task.activities.relay_sandbox_events"@@ -1723,6 +1729,72 @@ class TestPersistFinalMessage:_persist_final_message("00000000-0000-0000-0000-000000000000", "The report.")+class TestRelaySlackAgentDesignFanOut:+ async def test_background_turn_end_closes_the_slack_turn_with_the_whole_answer(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ redis_stream = SimpleNamespace(+ write_event=AsyncMock(),+ mark_complete=AsyncMock(),+ mark_error=AsyncMock(),+ claim_first_agent_command=AsyncMock(return_value=False),+ claim_first_agent_activity=AsyncMock(return_value=False),+ )+ events = [+ _acp("agent_message_chunk", {"content": {"type": "text", "text": "No, it is not safe to"}}),+ _acp("agent_message_chunk", {"content": {"type": "text", "text": " merge yet."}}),+ {+ "type": "notification",+ "notification": {"method": BACKGROUND_TURN_COMPLETE_METHOD, "params": {"stopReason": "end_turn"}},+ },+ {"type": "notification", "notification": {"method": "_posthog/task_complete"}},+ ]++ class EventSource:+ response = SimpleNamespace(raise_for_status=lambda: None)++ async def __aenter__(self) -> "EventSource":+ return self++ async def __aexit__(self, *_args: object) -> None:+ return None++ async def aiter_sse(self):+ for event in events:+ yield SimpleNamespace(data=json.dumps(event))++ handle = SimpleNamespace(signal=AsyncMock())+ client = SimpleNamespace(get_workflow_handle=MagicMock(return_value=handle))+ monkeypatch.setattr(relay_sandbox_events_module.httpx_sse, "aconnect_sse", lambda *_a, **_kw: EventSource())+ monkeypatch.setattr(relay_sandbox_events_module, "_background_heartbeat", AsyncMock())+ monkeypatch.setattr(+ relay_sandbox_events_module.activity, "info", lambda: SimpleNamespace(workflow_id="workflow-1")+ )+ monkeypatch.setattr("posthog.temporal.common.client.async_connect", AsyncMock(return_value=client))++ await _relay_loop(+ events_url="https://sandbox.example/events",+ headers={"Authorization": "Bearer token"},+ params={},+ redis_stream=cast(TaskRunRedisStream, redis_stream),+ run_id="run-id",+ task_id="task-id",+ slack_thread_context={"channel": "C1"},+ is_agent_design_enabled=True,+ )++ slack_signals = [+ (c.args[0], c.kwargs.get("arg"))+ for c in handle.signal.await_args_list+ if c.args[0] in ("turn_started", "agent_text_delta", "turn_completed")+ ]+ assert slack_signals[0][0] == "turn_started"+ assert slack_signals[-1] == ("turn_completed", None)+ assert "".join(arg for name, arg in slack_signals if name == "agent_text_delta") == (+ "No, it is not safe to merge yet."+ )++class TestFlushPendingText:"""Coalescing many chunks into one agent_text_delta signal keeps the parent workflow'shistory small enough to replay under the 2s deadlock budget."""diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.pyindex b4ef3e9da996..e4e90e7ba266 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py@@ -10,7 +10,7 @@ from products.tasks.backend.temporal.process_task.activities.slack_agent_design__resume_position,)-from ee.hogai.sandbox import TURN_COMPLETE_METHOD+from ee.hogai.sandbox import BACKGROUND_TURN_COMPLETE_METHOD, TURN_COMPLETE_METHODSLACK_CTX = {"channel": "C1", "integration_id": 7}@@ -49,6 +49,24 @@ def _turn_complete(trace_id: str | None = None) -> dict[str, Any]:return {"type": "notification", "notification": notification}+def _background_turn_complete() -> dict[str, Any]:+ return {+ "type": "notification",+ "notification": {"method": BACKGROUND_TURN_COMPLETE_METHOD, "params": {"stopReason": "end_turn"}},+ }+++def _notification(method: str) -> dict[str, Any]:+ return {"type": "notification", "notification": {"method": method, "params": {}}}+++def _task_notification() -> dict[str, Any]:+ return {+ "type": "notification",+ "notification": {"method": "_posthog/task_notification", "params": {"status": "completed"}},+ }++def _session_prompt(message_id: str | None = None) -> dict[str, Any]:notification: dict[str, Any] = {"method": "session/prompt"}if message_id:@@ -137,14 +155,20 @@ class TestSlackAgentDesignSignalEmitter:("agent_status_update", {"plan": [{"title": "Count weekly signups", "status": "in_progress"}]})]- def test_turn_completed_emitted_only_when_turn_active(self) -> None:+ @parameterized.expand(+ [+ ("turn_complete", _turn_complete()),+ ("background_turn_complete", _background_turn_complete()),+ ]+ )+ def test_turn_completed_emitted_only_when_turn_active(self, _name: str, completion: dict[str, Any]) -> None:emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)# No turn open yet — a stray completion is a no-op.- assert emitter.process(_turn_complete()) == []+ assert emitter.process(completion) == []emitter.process(_text_chunk("hi"))- assert emitter.process(_turn_complete()) == [("turn_completed", None)]+ assert emitter.process(completion) == [("turn_completed", None)]def test_turn_completed_carries_the_turns_trace_id(self) -> None:# The closing reply carries the thumbs, and this event is the only place the id@@ -156,16 +180,25 @@ class TestSlackAgentDesignSignalEmitter:assert signals == [("turn_completed", "f960aead-b2af-4ee0-b0eb-630109a1b2a0")]- def test_second_turn_reopens_after_idle_prompt(self) -> None:+ @parameterized.expand(+ [+ ("user_prompt", _session_prompt("msg-2"), "msg-2"),+ ("finished_background_task", _task_notification(), None),+ ("background_turn_started", _notification("_posthog/background_turn_started"), None),+ ]+ )+ def test_second_turn_reopens_after_idle_prompt(+ self, _name: str, opener: dict[str, Any], message_id: str | None+ ) -> None:emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)emitter.process(_text_chunk("turn one"))emitter.process(_turn_complete())- emitter.process(_session_prompt("msg-2")) # a new user message arms the next turn+ emitter.process(opener)signals = emitter.process(_text_chunk("turn two"))assert signals == [- ("turn_started", {"slack_thread_context": SLACK_CTX, "message_id": "msg-2"}),+ ("turn_started", {"slack_thread_context": SLACK_CTX, "message_id": message_id}),("agent_text_delta", "turn two"),]diff --git a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.pyindex b571e7072d2e..e21f5675c2e3 100644--- a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py+++ b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py@@ -319,8 +319,10 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):def _final_answer(self) -> str:# A trace id that differs from this turn's means the text is a late answer of an earlier turn.+ # A turn that the agent starts after a background task ends with no trace id, and the agent+ # server sends no final text for it, so a final text with a trace id is an earlier answer too.final_trace, turn_trace = _trace_key(self._final_text_trace_id), _trace_key(self._trace_id)- stale = bool(final_trace and turn_trace and final_trace != turn_trace)+ stale = bool(final_trace and final_trace != turn_trace)if self._final_text and not stale:return self._final_textreturn (self._narrative if self._narrative.strip() else self._last_burst).strip()diff --git a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.pyindex b309ac4dfcc8..d7338a1cc153 100644--- a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py+++ b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py@@ -88,6 +88,7 @@ async def _run_relay(setup_title: str | None = None,cancel: bool = False,stream_closed: bool = False,+ turn_trace_id: str | None = TRACE_ID,) -> _SlackCalls:calls = _SlackCalls(stream_closed=stream_closed)async with await WorkflowEnvironment.start_time_skipping() as env:@@ -116,7 +117,7 @@ async def _run_relay(with pytest.raises(WorkflowFailureError):await handle.result()else:- await handle.signal("complete_turn", TRACE_ID)+ await handle.signal("complete_turn", turn_trace_id)await handle.result()return calls@@ -195,6 +196,21 @@ class TestSlackAgentDesignRelay:assert calls.answer() == expected_answer+ @pytest.mark.timeout(60, func_only=True)+ async def test_a_background_turn_keeps_its_streamed_answer_over_a_late_final_text(self) -> None:+ # The agent server sends the previous turn's final text after that turn ends, so it can land+ # in the relay of a background turn, which completes with no trace id.+ calls = await _run_relay(+ [+ *CHECKING,+ ("agent_final_text", {"text": "The previous turn's answer.", "trace_id": str(uuid.UUID(TRACE_ID))}),+ ("agent_text_delta", "Answer."),+ ],+ turn_trace_id=None,+ )++ assert calls.answer() == "Answer."+@pytest.mark.parametrize("work, work_lines",[