: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): stop slack agent-design replies from repeating the answer (#109894)
Vojta Bartošef651ca434bb
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex fa700e909dbd..583a0fa1be0a 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -5578,7 +5578,7 @@ def relay_task_run_message(trace_id: str | None = None,) -> tuple[str, str | None]:"""Queue a Slack relay workflow for a run message, or under the agent-design- flag signal the running task workflow to stream the text inline.+ flag give the running task workflow the text as the turn's final answer.Returns ``(status, relay_id)`` where status is ``"accepted"`` (relay_id set), ``"skipped"``(run not found / terminal / no Slack mapping / empty text / streamed inline under the@@ -5598,7 +5598,7 @@ def relay_task_run_message()from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import pathexecute_posthog_code_agent_relay_workflow,- signal_agent_text_delta,+ signal_agent_final_text,)from products.tasks.backend.temporal.process_task.activities.feature_flags import ( # noqa: PLC0415 — keep temporal off the api import pathAGENT_DESIGN_STATE_KEY,@@ -5617,7 +5617,7 @@ def relay_task_run_message(if bool((run.state or {}).get(AGENT_DESIGN_STATE_KEY)):try:- signal_agent_text_delta(run.workflow_id, trimmed)+ signal_agent_final_text(run.workflow_id, trimmed, trace_id)except Exception:logger.exception("task_run_relay_text_signal_failed", extra={"run_id": str(run.id)})return "skipped", Nonediff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex 85b8b1acb17a..9029f67f19ce 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -655,11 +655,14 @@ def signal_task_followup_message(asyncio.run(signal())-def signal_agent_text_delta(workflow_id: str, text: str) -> None:- """Push text into the live agent-design plan-block stream for a running task."""+def signal_agent_final_text(workflow_id: str, text: str, trace_id: str | None = None) -> None:+ """Give the live agent-design reply of a running task the turn's whole answer.++ The relay replaces its streamed text deltas with this text, so the answer shows one time+ even when this signal lands between two deltas."""client = sync_connect()handle = client.get_workflow_handle(workflow_id)- asyncio.run(handle.signal("agent_text_delta", text))+ asyncio.run(handle.signal("agent_final_text", {"text": text, "trace_id": trace_id}))def execute_posthog_code_agent_relay_workflow(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 4af3593f2b1d..b571e7072d2e 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@@ -2,9 +2,9 @@The reply is a plan block and the final answer. The plan shows one line per kind of work (see``products.slack_app.backend.logic.progress_phases``), or the agent's todo list when it keeps one. Each line lists the-descriptions of its calls. The agent's prose does not stream: the last burst before the turn-ends is the answer. While the turn runs, one line always spins and the plan title says what-happens now.+descriptions of its calls. The agent's prose does not stream: the answer is the final text the+agent server reports for the turn, or the last burst before the turn ends when that text does not+arrive in time. While the turn runs, one line always spins and the plan title says what happens now.The first turn's relay starts before the sandbox exists, so the plan shows the setup steps theparent sends through ``setup_step``. Slack ends a stream that gets no update for a few minutes,@@ -62,6 +62,12 @@ _SANDBOX_SETUP_STEP = "sandbox"_PATCH_ID_STREAM_ENDED = "tasks-slack-relay-stream-ended"+def _trace_key(trace_id: Optional[str]) -> Optional[str]:+ """The trace id in one form. The relay endpoint sends it as a hyphenated UUID, and the turn-complete+ event sends the W3C form, which is the same 32 hex digits without hyphens."""+ return trace_id.replace("-", "").lower() if trace_id else None++@frozenclass SlackAgentDesignRelayInput:slack_thread_context: dict[str, Any]@@ -98,6 +104,12 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):# Prose since the last tool call, and the last non-empty burst before it.self._narrative: str = ""self._last_burst: str = ""+ # The whole answer as the agent server reports it. It can arrive between two text deltas,+ # so it is kept apart from the deltas and replaces them at close.+ self._final_text: str = ""+ self._final_text_trace_id: Optional[str] = None+ # Whether this turn's agent sent a tool call or prose yet.+ self._turn_has_activity: bool = Falseself._stream: Optional[SlackAgentDesignStream] = None# Slack closed the stream early. Later appends to it can only fail.self._stream_ended: bool = False@@ -114,6 +126,7 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):async def agent_status_update(self, payload: dict[str, Any] | str) -> None:"""A tool call or a new agent todo list. Either ends the prose burst before it."""self._last_signal_at = workflow.now()+ self._turn_has_activity = Truenarrative, self._narrative = self._narrative, ""if narrative.strip():self._last_burst = narrative@@ -206,6 +219,19 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):self._last_signal_at = workflow.now()if isinstance(text, str) and text:self._narrative += text+ self._turn_has_activity = True++ @workflow.signal+ async def agent_final_text(self, payload: dict[str, Any]) -> None:+ # The agent server sends a turn's final text after the turn ends. A late one can reach the+ # relay of the next turn, which has no activity yet, and must not become its answer.+ if not self._turn_has_activity:+ return+ text = payload.get("text")+ if isinstance(text, str) and text.strip():+ self._final_text = text.strip()+ trace_id = payload.get("trace_id")+ self._final_text_trace_id = trace_id if isinstance(trace_id, str) else None@workflow.signalasync def complete_turn(self, trace_id: str | None = None) -> None:@@ -292,6 +318,11 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):return done_plan_title(workflow.now() - self._started_at)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.+ 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)+ if self._final_text and not stale:+ return self._final_textreturn (self._narrative if self._narrative.strip() else self._last_burst).strip()def _idle_for(self) -> timedelta: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 a30c1364b8ec..b309ac4dfcc8 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@@ -26,8 +26,13 @@ pytestmark = [pytest.mark.asyncio]# A pseudo signal for ``_run_relay``: skip this many seconds, so the relay flushes what it has.WAIT = "__wait__"+# A turn's gateway trace id in the W3C form that the turn-complete event carries.+TRACE_ID = "4bf92f3577b34da6a3ce929d0e0e4736"+SLACK_CTX = {"integration_id": 1, "channel": "C1", "thread_ts": "1.0", "mentioning_slack_user_id": "U1"}+CHECKING = [("agent_text_delta", "Checking."), ("agent_status_update", {"phase": "posthog:Execute SQL query"})]+class _SlackCalls:def __init__(self, stream_closed: bool = False) -> None:@@ -111,7 +116,7 @@ async def _run_relay(with pytest.raises(WorkflowFailureError):await handle.result()else:- await handle.signal("complete_turn", "trace-1")+ await handle.signal("complete_turn", TRACE_ID)await handle.result()return calls@@ -143,21 +148,52 @@ class TestSlackAgentDesignRelay:assert [(s.plan_title or "").startswith("Done in ") for s in calls.stops] == [True]@pytest.mark.parametrize(- "tail",+ "signals, expected_answer",[- [("agent_text_delta", "Answer.")],+ ([*CHECKING, ("agent_text_delta", "Answer.")], "Answer."),# A trailing hidden tool, such as a summary update, must not cost the answer.- [("agent_text_delta", "Answer."), ("agent_status_update", {"phase": None})],+ ([*CHECKING, ("agent_text_delta", "Answer."), ("agent_status_update", {"phase": None})], "Answer."),+ # The agent server's final text can land while the last deltas of the same answer are still buffered.+ (+ [+ *CHECKING,+ ("agent_text_delta", "The answer is "),+ # The relay endpoint sends the trace id as a hyphenated UUID.+ ("agent_final_text", {"text": "The answer is 42.", "trace_id": str(uuid.UUID(TRACE_ID))}),+ ],+ "The answer is 42.",+ ),+ (+ [+ *CHECKING,+ ("agent_final_text", {"text": "An earlier turn's answer.", "trace_id": str(uuid.uuid4())}),+ ("agent_text_delta", "Answer."),+ ],+ "Answer.",+ ),+ # The previous turn's final text, without a trace id, reaches the relay before this turn starts.+ (+ [+ ("agent_final_text", {"text": "The previous turn's answer.", "trace_id": None}),+ *CHECKING,+ ("agent_text_delta", "Answer."),+ ],+ "Answer.",+ ),+ ],+ ids=[+ "answer_after_last_tool",+ "answer_before_hidden_tool",+ "final_text_before_the_last_delta",+ "final_text_of_another_turn",+ "final_text_before_the_turn_starts",],- ids=["answer_after_last_tool", "answer_before_hidden_tool"],)@pytest.mark.timeout(60, func_only=True)- async def test_last_prose_burst_is_the_answer(self, tail: list[tuple[str, Any]]) -> None:- calls = await _run_relay(- [("agent_text_delta", "Checking."), ("agent_status_update", {"phase": "posthog:Execute SQL query"}), *tail]- )+ async def test_last_prose_burst_is_the_answer(self, signals: list[tuple[str, Any]], expected_answer: str) -> None:+ calls = await _run_relay(signals)- assert calls.answer() == "Answer."+ assert calls.answer() == expected_answer@pytest.mark.parametrize("work, work_lines",diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 7f94cae31cb7..cefc9e6710c1 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -1,6 +1,6 @@import jsonimport asyncio-from collections.abc import Iterable+from collections.abc import Callable, Iterablefrom dataclasses import dataclass, field, replacefrom datetime import datetime, timedeltafrom enum import StrEnum@@ -405,6 +405,11 @@ _ORIGIN_PRODUCT_SIGNAL_REPORT = "signal_report"# Two-step deprecate-then-delete cleanup lifecycle as above._PATCH_ID_SLACK_AGENT_DESIGN_STATUS = "tasks-slack-agent-design-status"+# Gates the forward of the agent_final_text signal to the Slack relay. A worker without the+# handler records that signal in history and sends nothing, so a replay that forwards it emits a+# command the history does not have (TMPRL1100). Same two-step cleanup lifecycle as above.+_PATCH_ID_SLACK_AGENT_FINAL_TEXT = "tasks-slack-agent-final-text"+# Progress steps of sandbox setup. The Slack plan shows them until the first turn starts._SLACK_SETUP_PROGRESS_STEPS = frozenset({"sandbox", "clone", "checkout", "wizard", "agent"})@@ -595,6 +600,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._sandbox_ttl_snapshot_taken: bool = False# Decided once at workflow start; gates the placeholder skip + relay spawn.self._is_agent_design_enabled: bool = False+ # See _PATCH_ID_SLACK_AGENT_FINAL_TEXT.+ self._forwards_agent_final_text: bool = Falseself._dev_stack_preview_enabled: bool = False# Deadline-based so heartbeats waking the event loop don't keep resetting the timer.self._self_driving_quota_next_check_at: Optional[datetime] = None@@ -1340,6 +1347,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):)self._sandbox_url = sandbox_urlself._sandbox_connect_token = sandbox_connect_token+ if self._is_agent_design_enabled:+ self._forwards_agent_final_text = workflow.patched(_PATCH_ID_SLACK_AGENT_FINAL_TEXT)relay_task: asyncio.Task[None] | None = self._spawn_event_relay(sandbox_url, sandbox_connect_token, sandbox_id@@ -3568,33 +3577,39 @@ class ProcessTaskWorkflow(PostHogWorkflow):execution_timeout=timedelta(hours=6),)- @temporalio.workflow.signal- async def agent_status_update(self, payload: dict[str, Any]) -> None:- """Forward a {phase} tool-call update to the current per-turn child."""+ async def _forward_to_slack_relay(self, signal: Callable[..., Any], arg: Any, failure_event: str) -> None:if not self._is_agent_design_enabled or not self._current_slack_relay_workflow_id:returntry:handle = workflow.get_external_workflow_handle(self._current_slack_relay_workflow_id)- await handle.signal(SlackAgentDesignRelayWorkflow.agent_status_update, payload)+ await handle.signal(signal, arg)except Exception as e:# Child already gone — drop the update.workflow.logger.debug(- "slack_status_forward_failed",+ failure_event,extra={"run_id": self.context.run_id, "error": str(e)},)+ @temporalio.workflow.signal+ async def agent_status_update(self, payload: dict[str, Any]) -> None:+ """Forward a {phase} tool-call update to the current per-turn child."""+ await self._forward_to_slack_relay(+ SlackAgentDesignRelayWorkflow.agent_status_update, payload, "slack_status_forward_failed"+ )+@temporalio.workflow.signalasync def agent_text_delta(self, text: str) -> None:- if not self._is_agent_design_enabled or not self._current_slack_relay_workflow_id:+ await self._forward_to_slack_relay(+ SlackAgentDesignRelayWorkflow.agent_text_delta, text, "slack_text_forward_failed"+ )++ @temporalio.workflow.signal+ async def agent_final_text(self, payload: dict[str, Any]) -> None:+ if not self._forwards_agent_final_text:return- try:- handle = workflow.get_external_workflow_handle(self._current_slack_relay_workflow_id)- await handle.signal(SlackAgentDesignRelayWorkflow.agent_text_delta, text)- except Exception as e:- workflow.logger.debug(- "slack_text_forward_failed",- extra={"run_id": self.context.run_id, "error": str(e)},- )+ await self._forward_to_slack_relay(+ SlackAgentDesignRelayWorkflow.agent_final_text, payload, "slack_final_text_forward_failed"+ )@temporalio.workflow.signalasync def turn_completed(self, trace_id: str | None = None) -> None: