: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): relay Slack agent-design signals on sequenced-ingest path (#68131)
Vojta Bartošb5f37a64e6ba
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.pyindex 840be77687cb..50f2414cbdef 100644--- a/products/tasks/backend/temporal/__init__.py+++ b/products/tasks/backend/temporal/__init__.py@@ -34,6 +34,7 @@ from .process_task.activities import (prepare_sandbox_for_repository,read_sandbox_logs,refresh_sandbox_credentials,+ relay_agent_design_signals,relay_sandbox_events,run_wizard,send_followup_to_sandbox,@@ -76,6 +77,7 @@ ACTIVITIES = [execute_task_in_sandbox,run_wizard,forward_pending_user_message,+ relay_agent_design_signals,relay_sandbox_events,create_resume_snapshot,send_followup_to_sandbox,diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.pyindex 0b56aad03515..f5296d4617a5 100644--- a/products/tasks/backend/temporal/process_task/activities/__init__.py+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py@@ -37,6 +37,7 @@ from .refresh_sandbox_credentials import (from .relay_sandbox_events import RelaySandboxEventsInput, relay_sandbox_eventsfrom .run_wizard import RunWizardInput, run_wizardfrom .send_followup_to_sandbox import SendFollowupToSandboxInput, send_followup_to_sandbox+from .slack_agent_design_signals import RelayAgentDesignSignalsInput, relay_agent_design_signalsfrom .start_agent_server import (MarkRepoReadyInput,StartAgentServerInput,@@ -79,6 +80,7 @@ __all__ = ["TaskProcessingContext","TrackWorkflowEventInput","UpdateTaskRunStatusInput",+ "RelayAgentDesignSignalsInput","RelaySandboxEventsInput","SendFollowupToSandboxInput","cleanup_sandbox",@@ -87,6 +89,7 @@ __all__ = ["emit_progress_activity","execute_task_in_sandbox","forward_pending_user_message",+ "relay_agent_design_signals","relay_sandbox_events","send_followup_to_sandbox","get_sandbox_for_repository",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.pynew file mode 100644index 000000000000..e167f8491586--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py@@ -0,0 +1,121 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any++import structlog+from temporalio import activity++from posthog.temporal.common.utils import close_db_connections++from products.tasks.backend.logic.stream.redis_stream import (+ TaskRunRedisStream,+ TaskRunStreamError,+ get_task_run_stream_key,+)+from products.tasks.backend.models import TaskRun as TaskRunModel++from ee.hogai.sandbox import is_turn_complete++# Reuse the ACP event helpers and signal dispatcher from relay_sandbox_events so the SSE relay+# and this stream-tailing relay derive and emit signals from identical logic. Only the event+# source differs.+from .relay_sandbox_events import (+ _extract_agent_message_text,+ _extract_tool_call_step,+ _is_session_update,+ _signal_safely,+)++logger = structlog.get_logger(__name__)++HEARTBEAT_INTERVAL_SECONDS = 30+++class SlackAgentDesignSignalEmitter:+ """Converts a run's sandbox ACP event stream into the per-turn signals that drive+ ``SlackAgentDesignRelayWorkflow`` on the parent ``ProcessTaskWorkflow``.++ Stateful per run: a turn is bracketed from the first ``session/update`` until the+ turn-complete notification, and tool-call ids are de-duplicated for the lifetime of the+ run (the set is not cleared between turns). This mirrors the inline fan-out in+ ``relay_sandbox_events._relay_loop`` — keep the two in sync.+ """++ def __init__(self, slack_thread_context: dict[str, Any] | None) -> None:+ self._slack_thread_context = slack_thread_context or {}+ self._turn_active = False+ self._emitted_tool_call_ids: set[str] = set()++ def process(self, event_data: dict) -> list[tuple[str, Any]]:+ """Return the ordered ``(signal_name, arg)`` pairs to send for one event."""+ if is_turn_complete(event_data):+ if self._turn_active:+ self._turn_active = False+ return [("turn_completed", None)]+ return []++ signals: list[tuple[str, Any]] = []+ if not self._turn_active and _is_session_update(event_data):+ self._turn_active = True+ signals.append(("turn_started", {"slack_thread_context": self._slack_thread_context}))++ if self._turn_active:+ step_payload = _extract_tool_call_step(event_data, self._emitted_tool_call_ids)+ if step_payload is not None:+ signals.append(("agent_status_update", step_payload))+ if _is_session_update(event_data):+ text_delta = _extract_agent_message_text(event_data)+ if text_delta:+ signals.append(("agent_text_delta", text_delta))++ return signals+++@dataclass+class RelayAgentDesignSignalsInput:+ run_id: str+ task_id: str+ slack_thread_context: dict[str, Any] | None = None+++@close_db_connections+async def relay_agent_design_signals(input: RelayAgentDesignSignalsInput) -> None:+ """Tail the run's Redis event stream and emit the Slack agent-design per-turn signals.++ This is the sequenced-ingest counterpart to the agent-design fan-out in+ ``relay_sandbox_events``: when ``sandbox_event_ingest_enabled`` is on, the sandbox POSTs+ its events to the Django ingest endpoint (which writes them to this Redis stream) instead+ of holding an SSE connection open for the relay. Here we read that stream and drive the+ same signals, so the Slack thread streams turns on DEV/PROD just as it does locally.+ """+ try:+ from posthog.temporal.common.client import async_connect++ temporal_client = await async_connect()+ workflow_id = TaskRunModel.get_workflow_id(input.task_id, input.run_id)+ workflow_handle = temporal_client.get_workflow_handle(workflow_id)+ except Exception as e:+ logger.warning("relay_agent_design_signals_handle_init_failed", run_id=input.run_id, error=str(e))+ return++ emitter = SlackAgentDesignSignalEmitter(input.slack_thread_context)+ # Match the ingest endpoint's stream construction (default, non-dedicated client) so we+ # read from exactly the key the sandbox events are written to.+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(input.run_id))++ try:+ async for item in redis_stream.read_stream_entries(+ start_id="0",+ keepalive_interval_seconds=HEARTBEAT_INTERVAL_SECONDS,+ ):+ activity.heartbeat()+ if item is None:+ continue+ _, event_data = item+ for signal_name, arg in emitter.process(event_data):+ await _signal_safely(workflow_handle, signal_name, arg)+ except TaskRunStreamError as e:+ # The stream completed (complete/error sentinel) or timed out — nothing left to relay.+ logger.info("relay_agent_design_signals_stream_ended", run_id=input.run_id, reason=str(e))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.pynew file mode 100644index 000000000000..d6c74a5b4399--- /dev/null+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py@@ -0,0 +1,98 @@+from typing import Any++from products.tasks.backend.temporal.process_task.activities.slack_agent_design_signals import (+ SlackAgentDesignSignalEmitter,+)++from ee.hogai.sandbox import TURN_COMPLETE_METHOD++SLACK_CTX = {"channel": "C1", "integration_id": 7}+++def _text_chunk(text: str) -> dict[str, Any]:+ return {+ "type": "notification",+ "notification": {+ "method": "session/update",+ "params": {"update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}},+ },+ }+++def _tool_call(tool_call_id: str, tool_name: str, file_path: str) -> dict[str, Any]:+ return {+ "type": "notification",+ "notification": {+ "method": "session/update",+ "params": {+ "update": {+ "sessionUpdate": "tool_call",+ "toolCallId": tool_call_id,+ "_meta": {"claudeCode": {"toolName": tool_name}},+ "rawInput": {"file_path": file_path},+ }+ },+ },+ }+++def _turn_complete() -> dict[str, Any]:+ return {"type": "notification", "notification": {"method": TURN_COMPLETE_METHOD}}+++class TestSlackAgentDesignSignalEmitter:+ def test_first_session_update_opens_turn_and_streams_text(self) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)++ signals = emitter.process(_text_chunk("Hello"))++ assert signals == [+ ("turn_started", {"slack_thread_context": SLACK_CTX}),+ ("agent_text_delta", "Hello"),+ ]++ def test_turn_started_fires_once_per_turn(self) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)+ emitter.process(_text_chunk("first"))++ signals = emitter.process(_text_chunk("second"))++ assert signals == [("agent_text_delta", "second")]++ def test_tool_call_emits_status_update_and_dedupes(self) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)+ emitter.process(_text_chunk("thinking"))++ first = emitter.process(_tool_call("call-1", "Read", "/etc/hosts"))+ repeat = emitter.process(_tool_call("call-1", "Read", "/etc/hosts"))++ assert first == [("agent_status_update", {"title": "Read", "details": "/etc/hosts"})]+ assert repeat == []++ def test_turn_completed_emitted_only_when_turn_active(self) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)++ # No turn open yet — a stray completion is a no-op.+ assert emitter.process(_turn_complete()) == []++ emitter.process(_text_chunk("hi"))+ assert emitter.process(_turn_complete()) == [("turn_completed", None)]++ def test_second_turn_reopens_after_completion(self) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)+ emitter.process(_text_chunk("turn one"))+ emitter.process(_turn_complete())++ signals = emitter.process(_text_chunk("turn two"))++ assert signals == [+ ("turn_started", {"slack_thread_context": SLACK_CTX}),+ ("agent_text_delta", "turn two"),+ ]++ def test_events_before_any_turn_are_ignored(self) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)++ # A tool_call without a preceding session/update still opens the turn (it is a+ # session/update itself), but a non-session event must not leak signals.+ assert emitter.process({"type": "keepalive"}) == []diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 4d3d7906fd81..3a9acbe7b1ed 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -555,6 +555,58 @@ class TestProcessTaskWorkflowUnit:assert result.success is Truerelay_sandbox_events_mock.assert_not_awaited()+ async def test_run_relays_agent_design_signals_when_ingest_and_agent_design_enabled(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ context = _build_context(github_integration_id=123, sandbox_event_ingest_enabled=True)+ relay_sandbox_events_mock = AsyncMock()+ relay_agent_design_signals_mock = AsyncMock()++ monkeypatch.setattr(workflow, "_get_task_processing_context", AsyncMock(return_value=context))+ monkeypatch.setattr(workflow, "_update_task_run_status", AsyncMock())+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())+ monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())+ monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())+ monkeypatch.setattr(workflow, "_cleanup_sandbox", AsyncMock())+ monkeypatch.setattr(workflow, "_create_resume_snapshot", AsyncMock())+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())+ monkeypatch.setattr(workflow, "_forward_pending_user_message", AsyncMock())+ monkeypatch.setattr(workflow, "_resolve_agent_design_flag", AsyncMock(return_value=True))+ monkeypatch.setattr(+ workflow,+ "_get_sandbox_for_repository",+ AsyncMock(+ return_value=GetSandboxForRepositoryOutput(+ sandbox_id="sandbox-123",+ sandbox_url="https://sandbox.example",+ connect_token="connect-token",+ used_snapshot=False,+ should_create_snapshot=False,+ )+ ),+ )+ monkeypatch.setattr(+ workflow,+ "_start_agent_server",+ AsyncMock(+ return_value=StartAgentServerOutput(+ sandbox_url="https://sandbox.example",+ connect_token="connect-token",+ )+ ),+ )+ monkeypatch.setattr(+ workflow, "_wait_for_event", AsyncMock(return_value=process_task_workflow_module.TaskEvent.TIMEOUT_REACHED)+ )+ monkeypatch.setattr(workflow, "_relay_sandbox_events", relay_sandbox_events_mock)+ monkeypatch.setattr(workflow, "_relay_agent_design_signals", relay_agent_design_signals_mock)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))++ result = await workflow.run(ProcessTaskInput(run_id="run-id", slack_thread_context={"channel": "C1"}))++ assert result.success is True+ relay_sandbox_events_mock.assert_not_called()+ relay_agent_design_signals_mock.assert_called_once()+async def test_run_completes_when_credential_refresh_detects_sandbox_gone(self, monkeypatch):workflow = ProcessTaskWorkflow()context = _build_context(github_integration_id=123)diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 726dd7696768..f930abc169de 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -59,6 +59,7 @@ from .activities.send_followup_to_sandbox import (SendFollowupToSandboxInput,send_followup_to_sandbox,)+from .activities.slack_agent_design_signals import RelayAgentDesignSignalsInput, relay_agent_design_signalsfrom .activities.start_agent_server import (MarkRepoReadyInput,StartAgentServerInput,@@ -546,6 +547,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):relay_task = asyncio.ensure_future(self._relay_sandbox_events(agent_server_output, sandbox_id=sandbox_id))+ elif self._is_agent_design_enabled:+ # Sequenced ingest streams events straight to Redis, bypassing the SSE relay that+ # normally fans out the Slack agent-design signals. Tail that stream instead so+ # the per-turn Slack updates still fire.+ relay_task = asyncio.ensure_future(self._relay_agent_design_signals())if self.context.has_github_credentials:credential_refresh_task = asyncio.ensure_future(@@ -1217,6 +1223,42 @@ class ProcessTaskWorkflow(PostHogWorkflow):},)+ async def _relay_agent_design_signals(self) -> None:+ """Tail the ingest-populated Redis stream to fan out Slack agent-design signals.++ The flag-on counterpart to ``_relay_sandbox_events``: it reads events from Redis+ rather than the sandbox SSE stream, so it holds no sandbox connection."""+ try:+ relay_input = RelayAgentDesignSignalsInput(+ run_id=self.context.run_id,+ task_id=self.context.task_id,+ slack_thread_context=self._slack_thread_context,+ )+ await workflow.execute_activity(+ relay_agent_design_signals,+ relay_input,+ start_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,+ schedule_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,+ heartbeat_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_interval=timedelta(minutes=1),+ maximum_attempts=0,+ non_retryable_error_types=["ValueError"],+ ),+ cancellation_type=workflow.ActivityCancellationType.TRY_CANCEL,+ )+ except asyncio.CancelledError:+ raise+ except Exception as e:+ workflow.logger.warning(+ "relay_agent_design_signals_failed_non_fatal",+ extra={+ "run_id": self.context.run_id,+ "error": str(e),+ },+ )+@staticmethodasync def _cancel_relay(relay_task: "asyncio.Task[None]") -> None:"""Cancel the relay task if still running."""