Skip to content

: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.

fix(tasks): stop phantom agent-design turns from duplicating Slack messages (part 2) (#69719)

Vojta Bartošf7292bd7598d
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.py
index 5e7306a88cce..ad680d814c04 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
@@ -51,16 +51,27 @@ 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.
+ 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
+ for 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.
"""
- def __init__(self, slack_thread_context: dict[str, Any] | None, turn_active: bool = False) -> None:
+ def __init__(
+ self,
+ slack_thread_context: dict[str, Any] | None,
+ turn_active: bool = False,
+ awaiting_turn: bool = True,
+ ) -> None:
self._slack_thread_context = slack_thread_context or {}
# Seeded on a resumed activity attempt so a retry landing mid-turn doesn't re-open the turn.
self._turn_active = turn_active
+ # A turn opens only once a user prompt has been seen while idle. Armed for the run's first
+ # turn, then re-armed by each ``session/prompt`` observed between turns, so a trailing
+ # ``session/update`` emitted after turn-complete can't open a phantom turn. A resumed attempt
+ # starts disarmed and waits for the next prompt.
+ self._awaiting_turn = awaiting_turn
self._emitted_tool_call_ids: set[str] = set()
@property
@@ -69,6 +80,13 @@ class SlackAgentDesignSignalEmitter:
def process(self, event_data: dict) -> list[tuple[str, Any]]:
"""Return the ordered ``(signal_name, arg)`` pairs to send for one event."""
+ # A prompt received between turns arms the next turn; one received mid-turn belongs to the
+ # turn already open (the stream can interleave it just after the first response event).
+ if _is_session_prompt(event_data):
+ if not self._turn_active:
+ self._awaiting_turn = True
+ return []
+
if is_turn_complete(event_data):
if self._turn_active:
self._turn_active = False
@@ -76,8 +94,9 @@ class SlackAgentDesignSignalEmitter:
return []
signals: list[tuple[str, Any]] = []
- if not self._turn_active and _is_session_update(event_data):
+ if not self._turn_active and self._awaiting_turn and _is_session_update(event_data):
self._turn_active = True
+ self._awaiting_turn = False
signals.append(("turn_started", {"slack_thread_context": self._slack_thread_context}))
if self._turn_active:
@@ -123,6 +142,11 @@ def _event_method(event_data: dict) -> str | None:
return None
+def _is_session_prompt(event_data: dict) -> bool:
+ """Whether the event is a user ``session/prompt`` — the start of a new conversational turn."""
+ return _event_method(event_data) == "session/prompt"
+
+
def _resume_position() -> tuple[str | None, bool]:
"""Recover ``(last-processed SSE id, turn-active)`` from a prior attempt's heartbeat details.
@@ -224,9 +248,13 @@ async def _relay_from_agent_proxy(
async with Heartbeater() as heartbeater:
# Resume past what a prior attempt already relayed rather than replaying the stream from 0,
- # seeding the emitter's turn state so a retry mid-turn doesn't re-open the turn.
+ # seeding the emitter's turn state so a retry mid-turn doesn't re-open the turn. A resume
+ # starts disarmed (awaiting_turn=False) and waits for the next prompt, since any turn already
+ # under way was open before the crash.
last_event_id, turn_active = _resume_position()
- emitter = SlackAgentDesignSignalEmitter(input.slack_thread_context, turn_active=turn_active)
+ emitter = SlackAgentDesignSignalEmitter(
+ input.slack_thread_context, turn_active=turn_active, awaiting_turn=last_event_id is None
+ )
if last_event_id:
heartbeater.details = (last_event_id, turn_active)
logger.info(
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.py
index 7b5fb8b85874..7725ecb03881 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
@@ -44,6 +44,10 @@ def _turn_complete() -> dict[str, Any]:
return {"type": "notification", "notification": {"method": TURN_COMPLETE_METHOD}}
+def _session_prompt() -> dict[str, Any]:
+ return {"type": "notification", "notification": {"method": "session/prompt"}}
+
+
class TestSlackAgentDesignSignalEmitter:
def test_first_session_update_opens_turn_and_streams_text(self) -> None:
emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)
@@ -82,10 +86,11 @@ class TestSlackAgentDesignSignalEmitter:
emitter.process(_text_chunk("hi"))
assert emitter.process(_turn_complete()) == [("turn_completed", None)]
- def test_second_turn_reopens_after_completion(self) -> None:
+ def test_second_turn_reopens_after_idle_prompt(self) -> None:
emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)
emitter.process(_text_chunk("turn one"))
emitter.process(_turn_complete())
+ emitter.process(_session_prompt()) # a new user message arms the next turn
signals = emitter.process(_text_chunk("turn two"))
@@ -94,6 +99,39 @@ class TestSlackAgentDesignSignalEmitter:
("agent_text_delta", "turn two"),
]
+ def test_trailing_session_update_after_completion_does_not_reopen(self) -> None:
+ # The agent emits a session/update after turn-complete (mode/command updates, final
+ # consolidations). Without an intervening user prompt it must not open a phantom turn.
+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)
+ emitter.process(_text_chunk("joke"))
+ emitter.process(_session_prompt()) # this turn's prompt, interleaved mid-turn — must not re-arm
+ emitter.process(_turn_complete())
+
+ assert emitter.process(_text_chunk("trailing")) == []
+
+ def test_prompt_during_active_turn_does_not_arm_next(self) -> None:
+ # A prompt that lands mid-turn belongs to the open turn; the following trailing update after
+ # completion still must not reopen.
+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)
+ emitter.process(_text_chunk("answer"))
+ emitter.process(_session_prompt())
+ emitter.process(_text_chunk("more answer"))
+ emitter.process(_turn_complete())
+
+ assert emitter.process(_text_chunk("trailing")) == []
+
+ def test_resumed_emitter_waits_for_prompt_before_opening(self) -> None:
+ # A resumed attempt starts disarmed: a bare session/update must not open a turn until the
+ # next user prompt arrives.
+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX, awaiting_turn=False)
+
+ assert emitter.process(_text_chunk("stray")) == []
+ emitter.process(_session_prompt())
+ assert emitter.process(_text_chunk("real")) == [
+ ("turn_started", {"slack_thread_context": SLACK_CTX}),
+ ("agent_text_delta", "real"),
+ ]
+
def test_seeded_turn_active_does_not_reopen_mid_turn_resume(self) -> None:
# A retry that resumes mid-turn seeds turn_active=True, so the first resumed session/update
# streams text without emitting a duplicate turn_started.