: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
feat(tasks): coordinate task-managed steering (#71944)
Alessandro Pogliaghibbc2b08e6d53
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex e825b5825b8f..6c3087bcd723 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1654,6 +1654,8 @@ def _sync_automation_schedule(automation: TaskAutomation) -> None:# - workflow_id is the run's Temporal workflow address (``TaskRun.workflow_id`` prefers it over# the derived id); a caller could otherwise repoint their run at another team's workflow and# signal or terminate-and-restart it.+# - pending_external_followups / pending_external_followups_generation are the workflow-owned+# durable queue; a caller could otherwise inject actor identity into a restored follow-up.# These keys are reserved for server-owned run state, never PATCH input._PROTECTED_RUN_STATE_KEYS = frozenset({@@ -1677,6 +1679,8 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("cancel_requested_by_user_id","cancel_source","cancel_fallback_cleanup_complete",+ "pending_external_followups",+ "pending_external_followups_generation",})diff --git a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.pyindex 2bd4d52ab105..28eca6ae5d49 100644--- a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py@@ -198,11 +198,28 @@ class TestSignalHandlers:workflow = ExecuteSandboxWorkflow()workflow._context = _build_context()- await workflow.send_steer_message("ack-3", "hello", ["art-1"], source="user")+ await workflow.send_steer_message(+ "ack-3",+ "hello",+ ["art-1"],+ source="user",+ message_id="message-1",+ actor_user_id=42,+ message_context={"actor_slack_user_id": "U123"},+ )await workflow.send_followup_message("ack-legacy", "legacy", ["art-2"], "user", True)assert workflow._pending_followups == [- PendingFollowup(message="hello", artifact_ids=["art-1"], ack_id="ack-3", source="user", steer=True),+ PendingFollowup(+ message="hello",+ artifact_ids=["art-1"],+ ack_id="ack-3",+ source="user",+ actor_user_id=42,+ message_id="message-1",+ context={"actor_slack_user_id": "U123"},+ steer=True,+ ),PendingFollowup(message="legacy",artifact_ids=["art-2"],@@ -545,10 +562,25 @@ class TestHandleFollowup:monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())await workflow._handle_followup(- PendingFollowup(message="msg", artifact_ids=["art-1"], ack_id="ack-ok", source="user")+ PendingFollowup(+ message="msg",+ artifact_ids=["art-1"],+ ack_id="ack-ok",+ source="user",+ actor_user_id=42,+ message_id="message-1",+ context={"actor_slack_user_id": "U123"},+ ))- send_mock.assert_awaited_once_with(message="msg", artifact_ids=["art-1"], steer=False)+ send_mock.assert_awaited_once_with(+ message="msg",+ artifact_ids=["art-1"],+ actor_user_id=42,+ message_id="message-1",+ message_context={"actor_slack_user_id": "U123"},+ steer=False,+ )assert workflow._pending_outbound == [OutboundSignal(target_signal=PARENT_ACK_SIGNAL,@@ -935,7 +967,14 @@ class TestHandleFollowupInFlightTracking:snapshot: dict[str, bool] = {}- async def fake_send(message=None, artifact_ids=None, steer=False):+ async def fake_send(+ message=None,+ artifact_ids=None,+ actor_user_id=None,+ message_id=None,+ message_context=None,+ steer=False,+ ):snapshot["in_flight_at_await"] = "ack-track" in workflow._in_flight_followup_ack_idsmonkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send)@@ -970,7 +1009,9 @@ class TestHandleFollowupInFlightTracking:release_initial = asyncio.Event()deliveries: list[tuple[str | None, bool]] = []- async def fake_send_followup(*, message, artifact_ids, steer=False):+ async def fake_send_followup(+ *, message, artifact_ids, actor_user_id=None, message_id=None, message_context=None, steer=False+ ):deliveries.append((message, steer))if message == "keep working":await release_initial.wait()@@ -1016,7 +1057,9 @@ class TestHandleFollowupInFlightTracking:release_steer = asyncio.Event()deliveries: list[tuple[str | None, bool]] = []- async def fake_send_followup(*, message, artifact_ids, steer=False):+ async def fake_send_followup(+ *, message, artifact_ids, actor_user_id=None, message_id=None, message_context=None, steer=False+ ):deliveries.append((message, steer))if steer:await release_steer.wait()diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex 61eab1dba3d5..3bf1c650f406 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -11,7 +11,7 @@ is deleted in a later PR.import jsonimport asyncio-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom datetime import timedeltafrom enum import StrEnumfrom typing import Any, Optional@@ -175,6 +175,9 @@ class PendingFollowup:artifact_ids: list[str]ack_id: strsource: str = FOLLOWUP_SOURCE_USER # FOLLOWUP_SOURCE_USER | FOLLOWUP_SOURCE_CI+ actor_user_id: int | None = None+ message_id: str | None = None+ context: dict[str, Any] = field(default_factory=dict)steer: bool = Falsesequence: int = 0@@ -730,14 +733,21 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):message: str | None = None,artifact_ids: Optional[list[str]] = None,source: str = FOLLOWUP_SOURCE_USER,- steer: bool = False,+ message_id: str | bool | None = None,+ actor_user_id: int | None = None,+ message_context: dict[str, Any] | None = None,) -> None:+ legacy_steer = message_id if isinstance(message_id, bool) else False+ stable_message_id = message_id if isinstance(message_id, str) else Noneself._queue_followup_message(ack_id,message,artifact_ids,source,- steer=steer,+ actor_user_id=actor_user_id,+ message_id=stable_message_id,+ message_context=message_context,+ steer=legacy_steer,signal_name=SEND_FOLLOWUP_SIGNAL,)@@ -748,12 +758,18 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):message: str | None = None,artifact_ids: Optional[list[str]] = None,source: str = FOLLOWUP_SOURCE_USER,+ message_id: str | None = None,+ actor_user_id: int | None = None,+ message_context: dict[str, Any] | None = None,) -> None:self._queue_followup_message(ack_id,message,artifact_ids,source,+ actor_user_id=actor_user_id,+ message_id=message_id,+ message_context=message_context,steer=True,signal_name=SEND_STEER_SIGNAL,)@@ -768,6 +784,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):message: str | None,artifact_ids: Optional[list[str]],source: str,+ actor_user_id: int | None = None,+ message_id: str | None = None,+ message_context: dict[str, Any] | None = None,*,steer: bool,signal_name: str,@@ -812,6 +831,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):artifact_ids=artifact_ids or [],ack_id=ack_id,source=source,+ actor_user_id=actor_user_id,+ message_id=message_id,+ context=message_context if isinstance(message_context, dict) else {},steer=steer,sequence=self._next_followup_sequence,)@@ -860,6 +882,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):outcome = await self._send_followup_to_sandbox(message=followup.message,artifact_ids=followup.artifact_ids,+ actor_user_id=followup.actor_user_id,+ message_id=followup.message_id,+ message_context=followup.context,steer=followup.steer,)if followup.steer and outcome == STEER_DECLINED_OUTCOME:@@ -869,6 +894,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):artifact_ids=followup.artifact_ids,ack_id=followup.ack_id,source=followup.source,+ actor_user_id=followup.actor_user_id,+ message_id=followup.message_id,+ context=followup.context,sequence=followup.sequence,),)@@ -1376,7 +1404,14 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):workflow.logger.warning(f"Resume snapshot skipped: {result.error}")async def _send_followup_to_sandbox(- self, message: str | None, artifact_ids: list[str], *, steer: bool = False+ self,+ message: str | None,+ artifact_ids: list[str],+ actor_user_id: int | None = None,+ message_id: str | None = None,+ message_context: dict[str, Any] | None = None,+ *,+ steer: bool = False,) -> str | None:workflow.logger.info("execute_sandbox_send_followup_begin",@@ -1391,7 +1426,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):message=message,posthog_mcp_scopes=self._posthog_mcp_scopes,artifact_ids=artifact_ids,- message_id=str(workflow.uuid4()),+ message_id=message_id or str(workflow.uuid4()),+ actor_user_id=actor_user_id,+ context=message_context if isinstance(message_context, dict) else {},steer=steer,),start_to_close_timeout=timedelta(minutes=35),diff --git a/products/tasks/backend/temporal/task_management/activities/ensure_execute_sandbox_started.py b/products/tasks/backend/temporal/task_management/activities/ensure_execute_sandbox_started.pyindex 471546f98a9c..bf2891398f2d 100644--- a/products/tasks/backend/temporal/task_management/activities/ensure_execute_sandbox_started.py+++ b/products/tasks/backend/temporal/task_management/activities/ensure_execute_sandbox_started.py@@ -15,11 +15,14 @@ from dataclasses import dataclassfrom django.conf import settings+from asgiref.sync import sync_to_asyncfrom temporalio import activityfrom temporalio.common import WorkflowIDReusePolicyfrom posthog.temporal.common.client import async_connect+from products.tasks.backend.feature_flags import is_native_steering_signals_enabled+from products.tasks.backend.temporal.constants import STEERING_PROTOCOL_QUERY, STEERING_PROTOCOL_QUERY_TIMEOUTfrom products.tasks.backend.temporal.execute_sandbox.workflow import PARENT_ATTACHED_SIGNAL, ExecuteSandboxInputfrom products.tasks.backend.temporal.observability import log_activity_execution@@ -32,7 +35,7 @@ class EnsureExecuteSandboxStartedInput:@activity.defn-async def ensure_execute_sandbox_started(input: EnsureExecuteSandboxStartedInput) -> None:+async def ensure_execute_sandbox_started(input: EnsureExecuteSandboxStartedInput) -> int:with log_activity_execution("ensure_execute_sandbox_started",run_id=input.workflow_input.run_id,@@ -40,7 +43,7 @@ async def ensure_execute_sandbox_started(input: EnsureExecuteSandboxStartedInputbootstrap_ack_id=input.bootstrap_ack_id,):client = await async_connect()- await client.start_workflow(+ handle = await client.start_workflow("execute-sandbox",input.workflow_input,id=input.workflow_id,@@ -59,3 +62,16 @@ async def ensure_execute_sandbox_started(input: EnsureExecuteSandboxStartedInput# restart. Recovery from those failures lives at the orchestrator# level via the ACK-retry / re-bootstrap path.)+ native_steering_signals_enabled = await sync_to_async(+ is_native_steering_signals_enabled, thread_sensitive=False+ )()+ if not native_steering_signals_enabled:+ return 0+ try:+ protocol_version = await handle.query(+ STEERING_PROTOCOL_QUERY,+ rpc_timeout=STEERING_PROTOCOL_QUERY_TIMEOUT,+ )+ except Exception:+ return 0+ return protocol_version if isinstance(protocol_version, int) else 0diff --git a/products/tasks/backend/temporal/task_management/activities/pending_followups.py b/products/tasks/backend/temporal/task_management/activities/pending_followups.pyindex bee0b04cb761..5a3e704d0994 100644--- a/products/tasks/backend/temporal/task_management/activities/pending_followups.py+++ b/products/tasks/backend/temporal/task_management/activities/pending_followups.py@@ -30,7 +30,7 @@ PENDING_FOLLOWUPS_STATE_KEY = "pending_external_followups"@dataclassclass PersistPendingFollowupsInput:run_id: str- # Pre-serialized list of {message, artifact_ids, source}. The workflow+ # Pre-serialized list of {message, artifact_ids, source, steer, sequence}. The workflow# serializes its `PendingExternalFollowup` dataclasses here so the# activity doesn't need to import workflow-side types.followups: list[dict[str, Any]]diff --git a/products/tasks/backend/temporal/task_management/activities/tests/test_ensure_execute_sandbox_started.py b/products/tasks/backend/temporal/task_management/activities/tests/test_ensure_execute_sandbox_started.pyindex 57bf1e59c0ee..f1c467c63afd 100644--- a/products/tasks/backend/temporal/task_management/activities/tests/test_ensure_execute_sandbox_started.py+++ b/products/tasks/backend/temporal/task_management/activities/tests/test_ensure_execute_sandbox_started.py@@ -1,10 +1,15 @@import pytest-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, Mock, patchfrom django.conf import settingsfrom temporalio.common import WorkflowIDReusePolicy+from products.tasks.backend.temporal.constants import (+ STEERING_PROTOCOL_QUERY,+ STEERING_PROTOCOL_QUERY_TIMEOUT,+ STEERING_PROTOCOL_VERSION,+)from products.tasks.backend.temporal.execute_sandbox.workflow import PARENT_ATTACHED_SIGNAL, ExecuteSandboxInputfrom products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started import (EnsureExecuteSandboxStartedInput,@@ -22,6 +27,9 @@ class TestEnsureExecuteSandboxStarted:# re-use the deterministic workflow id once the prior execution closed.client = AsyncMock()client.start_workflow = AsyncMock()+ handle = AsyncMock()+ handle.query.return_value = STEERING_PROTOCOL_VERSION+ client.start_workflow.return_value = handleinput_data = EnsureExecuteSandboxStartedInput(workflow_id="sandbox-wf-id",@@ -35,11 +43,17 @@ class TestEnsureExecuteSandboxStarted:bootstrap_ack_id="ack-bootstrap",)- with patch(- "products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started.async_connect",- AsyncMock(return_value=client),+ with (+ patch(+ "products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started.is_native_steering_signals_enabled",+ Mock(return_value=True),+ ),+ patch(+ "products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started.async_connect",+ AsyncMock(return_value=client),+ ),):- await activity_environment.run(ensure_execute_sandbox_started, input_data)+ protocol_version = await activity_environment.run(ensure_execute_sandbox_started, input_data)client.start_workflow.assert_awaited_once()args, kwargs = client.start_workflow.call_args@@ -52,3 +66,66 @@ class TestEnsureExecuteSandboxStarted:# The bootstrap signal is what the orchestrator ACKs on to confirm the# child is alive — args are (ack_id, parent_workflow_id) in that order.assert kwargs["start_signal_args"] == ["ack-bootstrap", "parent-wf-id"]+ handle.query.assert_awaited_once_with(+ STEERING_PROTOCOL_QUERY,+ rpc_timeout=STEERING_PROTOCOL_QUERY_TIMEOUT,+ )+ assert protocol_version == STEERING_PROTOCOL_VERSION++ @pytest.mark.parametrize(+ "query_error",+ [RuntimeError("query not registered"), TimeoutError("query timed out")],+ )+ async def test_returns_legacy_protocol_when_query_is_unavailable(self, activity_environment, query_error):+ client = AsyncMock()+ handle = AsyncMock()+ handle.query.side_effect = query_error+ client.start_workflow.return_value = handle+ input_data = EnsureExecuteSandboxStartedInput(+ workflow_id="sandbox-wf-id",+ workflow_input=ExecuteSandboxInput(run_id="run-1", parent_workflow_id="parent-wf-id"),+ bootstrap_ack_id="ack-bootstrap",+ )++ with (+ patch(+ "products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started.is_native_steering_signals_enabled",+ Mock(return_value=True),+ ),+ patch(+ "products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started.async_connect",+ AsyncMock(return_value=client),+ ),+ ):+ protocol_version = await activity_environment.run(ensure_execute_sandbox_started, input_data)++ assert protocol_version == 0+ handle.query.assert_awaited_once_with(+ STEERING_PROTOCOL_QUERY,+ rpc_timeout=STEERING_PROTOCOL_QUERY_TIMEOUT,+ )++ async def test_disabled_feature_flag_skips_capability_query(self, activity_environment):+ client = AsyncMock()+ handle = AsyncMock()+ client.start_workflow.return_value = handle+ input_data = EnsureExecuteSandboxStartedInput(+ workflow_id="sandbox-wf-id",+ workflow_input=ExecuteSandboxInput(run_id="run-1", parent_workflow_id="parent-wf-id"),+ bootstrap_ack_id="ack-bootstrap",+ )++ with (+ patch(+ "products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started.is_native_steering_signals_enabled",+ Mock(return_value=False),+ ),+ patch(+ "products.tasks.backend.temporal.task_management.activities.ensure_execute_sandbox_started.async_connect",+ AsyncMock(return_value=client),+ ),+ ):+ protocol_version = await activity_environment.run(ensure_execute_sandbox_started, input_data)++ assert protocol_version == 0+ handle.query.assert_not_awaited()diff --git a/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py b/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.pyindex 3f7e04acf274..8c4982db76ce 100644--- a/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py+++ b/products/tasks/backend/temporal/task_management/tests/test_task_management_workflow.py@@ -9,6 +9,8 @@ from products.tasks.backend.temporal.constants import (HEARTBEAT_DEBOUNCE,MAX_ACK_RETRIES,MAX_CI_REPETITIONS,+ SEND_STEER_SIGNAL,+ STEERING_PROTOCOL_VERSION,)from products.tasks.backend.temporal.execute_sandbox.workflow import PARENT_ATTACHED_SIGNAL, ChildCompletionPayloadfrom products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextOutput, get_pr_context@@ -20,6 +22,7 @@ from products.tasks.backend.temporal.task_management.workflow import (CIFollowUpDecision,PendingAckSlot,PendingExternalFollowup,+ TaskEvent,TaskManagementWorkflow,TaskRunManagementInput,)@@ -112,6 +115,31 @@ class TestExternalSignalHandlers:PendingExternalFollowup(message="hello", artifact_ids=[], source="user")]+ async def test_send_steer_message_preserves_steer_intent(self):+ workflow = TaskManagementWorkflow()++ await workflow.send_steer_message(+ "hello",+ ["a1"],+ message_id="message-1",+ actor_user_id=42,+ message_context={"actor_slack_user_id": "U123"},+ )+ await workflow.send_followup_message("legacy", ["a2"], True)++ assert workflow._pending_external_followups == [+ PendingExternalFollowup(+ message="hello",+ artifact_ids=["a1"],+ source="user",+ actor_user_id=42,+ message_id="message-1",+ context={"actor_slack_user_id": "U123"},+ steer=True,+ ),+ PendingExternalFollowup(message="legacy", artifact_ids=["a2"], source="user", steer=True, sequence=1),+ ]+async def test_external_heartbeat_records_activity(self, fixed_now):# Heartbeats only flow child -> parent, so the external handler is a# local-state-only update — it never forwards down to the sandbox.@@ -598,13 +626,70 @@ class TestSignalChildFollowup:handle.signal.assert_awaited_once_with("send_followup_message",- args=["ack-generated", "m", ["a"], "ci"],+ args=["ack-generated", "m", ["a"], "ci", None, None, {}],)slot = workflow._pending_ack_slots["ack-generated"]assert slot.signal_name == "send_followup_message"# signal_args must mirror the exact bytes we sent so the retry loop# can replay them — the child dedupes on ack_id so a replay is safe.- assert slot.signal_args == ["ack-generated", "m", ["a"], "ci"]+ assert slot.signal_args == ["ack-generated", "m", ["a"], "ci", None, None, {}]++ @pytest.mark.parametrize(+ ("patch_enabled", "protocol_version", "expected_signal"),+ [+ (True, STEERING_PROTOCOL_VERSION, SEND_STEER_SIGNAL),+ (True, 0, "send_followup_message"),+ (False, 0, SEND_STEER_SIGNAL),+ ],+ )+ async def test_steer_signal_is_capability_gated_without_breaking_replay(+ self,+ monkeypatch,+ fixed_now,+ patch_enabled: bool,+ protocol_version: int,+ expected_signal: str,+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_workflow_id = "sandbox-wf"+ workflow._child_steering_protocol_version = protocol_version++ handle = Mock()+ handle.signal = AsyncMock()+ monkeypatch.setattr(+ task_management_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle),+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "uuid4", lambda: "ack-steer")+ monkeypatch.setattr(task_management_workflow_module.workflow, "patched", lambda _patch_id: patch_enabled)++ await workflow._signal_child_followup(+ message="m",+ artifact_ids=["a"],+ source="user",+ actor_user_id=42,+ message_id="message-1",+ message_context={"actor_slack_user_id": "U123"},+ steer=True,+ )++ handle.signal.assert_awaited_once_with(+ expected_signal,+ args=["ack-steer", "m", ["a"], "user", "message-1", 42, {"actor_slack_user_id": "U123"}],+ )+ slot = workflow._pending_ack_slots["ack-steer"]+ assert slot.signal_name == expected_signal+ assert slot.signal_args == [+ "ack-steer",+ "m",+ ["a"],+ "user",+ "message-1",+ 42,+ {"actor_slack_user_id": "U123"},+ ]async def test_skips_when_no_sandbox_id(self, monkeypatch, silent_workflow_logger):# If the sandbox workflow id was never set we have nowhere to deliver@@ -643,7 +728,7 @@ class TestSignalChildFollowup:assert "ack-x" in workflow._pending_ack_slotsslot = workflow._pending_ack_slots["ack-x"]assert slot.signal_name == "send_followup_message"- assert slot.signal_args == ["ack-x", "m", [], "user"]+ assert slot.signal_args == ["ack-x", "m", [], "user", None, None, {}]assert slot.retry_count == 0@@ -927,6 +1012,52 @@ class TestShutdownRejectionHandling:]silent_workflow_logger.warning.assert_called()+ async def test_steer_rejections_preserve_arrival_order_as_normal_followups(self, fixed_now, silent_workflow_logger):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._pending_ack_slots["ack-steer-1"] = PendingAckSlot(+ signal_name=SEND_STEER_SIGNAL,+ sent_at=fixed_now.now,+ signal_args=["ack-steer-1", "first instruction", [], "user"],+ sequence=0,+ )+ workflow._pending_ack_slots["ack-steer-2"] = PendingAckSlot(+ signal_name=SEND_STEER_SIGNAL,+ sent_at=fixed_now.now,+ signal_args=["ack-steer-2", "second instruction", [], "user"],+ sequence=1,+ )+ workflow._child_acks.append(+ ChildAck(+ signal_name=SEND_STEER_SIGNAL,+ ack_id="ack-steer-1",+ accepted=False,+ detail="child_shutting_down",+ received_at=fixed_now.now,+ )+ )++ await workflow._drain_child_signals()+ workflow._child_acks.append(+ ChildAck(+ signal_name=SEND_STEER_SIGNAL,+ ack_id="ack-steer-2",+ accepted=False,+ detail="child_shutting_down",+ received_at=fixed_now.now,+ )+ )+ await workflow._drain_child_signals()++ assert workflow._pending_external_followups == [+ PendingExternalFollowup(+ message="first instruction", artifact_ids=[], source="user", steer=False, sequence=0+ ),+ PendingExternalFollowup(+ message="second instruction", artifact_ids=[], source="user", steer=False, sequence=1+ ),+ ]+async def test_complete_task_rejection_is_dropped_silently(self, fixed_now, silent_workflow_logger):# If the child rejects a `complete_task` because it's shutting down,# that means it's already completing — no need to re-queue anything.@@ -957,6 +1088,39 @@ class TestSandboxSessionCompletionReset:"""The orchestrator is persistent across sandbox sessions: when one endswe reset per-session state but stay alive for the next external signal."""+ async def test_ack_is_processed_before_queued_session_completion(+ self, monkeypatch, fixed_now, silent_workflow_logger+ ):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_alive = True+ workflow._child_completion = ChildCompletion(success=True, error=None, sandbox_id="sb-1", timed_out=False)+ workflow._pending_ack_slots["ack-delivered"] = PendingAckSlot(+ signal_name="send_followup_message",+ sent_at=fixed_now.now,+ signal_args=["ack-delivered", "already delivered", [], "user"],+ )+ workflow._child_acks.append(+ ChildAck(+ signal_name="send_followup_message",+ ack_id="ack-delivered",+ accepted=True,+ detail=None,+ received_at=fixed_now.now,+ )+ )+ monkeypatch.setattr(task_management_workflow_module.workflow, "wait_condition", AsyncMock())+ monkeypatch.setattr(workflow, "_persist_pending_followups", AsyncMock())++ assert await workflow._wait_for_signal() is TaskEvent.CHILD_FORWARDED+ await workflow._drain_child_signals()+ assert workflow._pending_ack_slots == {}++ assert await workflow._wait_for_signal() is TaskEvent.CHILD_COMPLETED+ await workflow._on_sandbox_session_completed()++ assert workflow._pending_external_followups == []+async def test_session_completion_does_not_close_orchestrator(self, monkeypatch, fixed_now, silent_workflow_logger):# Hardest assertion to lose: after `_on_sandbox_session_completed`,# the workflow has *not* returned and is ready for more work.@@ -1013,6 +1177,40 @@ class TestSandboxSessionCompletionReset:assert workflow._pending_ack_slots == {}persist_mock.assert_awaited()+ async def test_unacked_steer_is_requeued_without_stale_intent(self, monkeypatch, silent_workflow_logger, fixed_now):+ workflow = TaskManagementWorkflow()+ workflow._run_id = "run-id"+ workflow._sandbox_alive = True+ workflow._child_completion = ChildCompletion(success=True, error=None, sandbox_id="sb-1", timed_out=False)+ workflow._pending_ack_slots["ack-steer"] = PendingAckSlot(+ signal_name=SEND_STEER_SIGNAL,+ sent_at=fixed_now.now,+ signal_args=[+ "ack-steer",+ "survive replacement",+ [],+ "user",+ "message-1",+ 42,+ {"actor_slack_user_id": "U123"},+ ],+ )+ monkeypatch.setattr(workflow, "_persist_pending_followups", AsyncMock())++ await workflow._on_sandbox_session_completed()++ assert workflow._pending_external_followups == [+ PendingExternalFollowup(+ message="survive replacement",+ artifact_ids=[],+ source="user",+ actor_user_id=42,+ message_id="message-1",+ context={"actor_slack_user_id": "U123"},+ steer=False,+ )+ ]+class TestPendingFollowupPersistence:async def test_restore_pending_seeds_in_memory_queue(self, monkeypatch, silent_workflow_logger):@@ -1042,7 +1240,7 @@ class TestPendingFollowupPersistence:assert workflow._pending_external_followups == [PendingExternalFollowup(message="queued-1", artifact_ids=[], source="user"),- PendingExternalFollowup(message="queued-2", artifact_ids=["a1"], source="user"),+ PendingExternalFollowup(message="queued-2", artifact_ids=["a1"], source="user", sequence=1),]async def test_restore_swallows_read_error(self, monkeypatch, silent_workflow_logger):@@ -1082,4 +1280,15 @@ class TestPendingFollowupPersistence:await workflow._persist_pending_followups()assert captured["input"].run_id == "run-id"- assert captured["input"].followups == [{"message": "persist-me", "artifact_ids": ["a1"], "source": "user"}]+ assert captured["input"].followups == [+ {+ "message": "persist-me",+ "artifact_ids": ["a1"],+ "source": "user",+ "actor_user_id": None,+ "message_id": None,+ "context": {},+ "steer": False,+ "sequence": 0,+ }+ ]diff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.pyindex 45ea37d8c70e..e7c8d4d1e6b5 100644--- a/products/tasks/backend/temporal/task_management/workflow.py+++ b/products/tasks/backend/temporal/task_management/workflow.py@@ -1,6 +1,6 @@import jsonimport asyncio-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timedeltafrom enum import StrEnumfrom typing import Any, Optional@@ -20,6 +20,9 @@ from products.tasks.backend.temporal.constants import (HEARTBEAT_DEBOUNCE,MAX_ACK_RETRIES,MAX_CI_REPETITIONS,+ SEND_STEER_SIGNAL,+ STEERING_PROTOCOL_QUERY,+ STEERING_PROTOCOL_VERSION,)from products.tasks.backend.temporal.execute_sandbox.workflow import (COMPLETE_TASK_SIGNAL,@@ -68,6 +71,15 @@ from products.tasks.backend.temporal.task_management.activities.pending_followupread_pending_followups,)+_PATCH_ID_CAPABILITY_GATED_STEERING = "tasks-capability-gated-steering-signal"+_PATCH_ID_ACK_BEFORE_COMPLETION = "tasks-task-management-ack-before-completion"+++def _ack_before_completion() -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(_PATCH_ID_ACK_BEFORE_COMPLETION)+@dataclassclass TaskRunManagementInput:@@ -93,6 +105,11 @@ class PendingExternalFollowup:message: str | Noneartifact_ids: list[str]source: str = FOLLOWUP_SOURCE_USER # FOLLOWUP_SOURCE_USER | FOLLOWUP_SOURCE_CI+ actor_user_id: int | None = None+ message_id: str | None = None+ context: dict[str, Any] = field(default_factory=dict)+ steer: bool = False+ sequence: int = 0@dataclass@@ -133,6 +150,7 @@ class PendingAckSlot:detail: Optional[str] = Nonesignal_args: Optional[list[Any]] = Noneretry_count: int = 0+ sequence: int = 0class TaskEvent(StrEnum):@@ -180,6 +198,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# External signals (from API, Slack, runner) queued for delivery to# the sandbox workflow. We assign ack_ids when we forward.self._pending_external_followups: list[PendingExternalFollowup] = []+ self._next_followup_sequence: int = 0self._pending_external_complete: Optional[tuple[str, Optional[str]]] = None# Last payload we wrote to TaskRun.state, so `_persist_pending_followups`# can skip the DB roundtrip when nothing changed (e.g., draining an@@ -191,11 +210,13 @@ class TaskManagementWorkflow(PostHogWorkflow):self._child_acks: list[ChildAck] = []self._pending_ack_slots: dict[str, PendingAckSlot] = {}self._child_completion: Optional[ChildCompletion] = None+ self._ack_before_completion: bool = True# True between a successful `_ensure_sandbox_workflow_started` and# the next `PARENT_COMPLETED_SIGNAL`. The orchestrator lives for the# whole task run and spawns sandboxes lazily: when a follow-up arrives# while `_sandbox_alive=False`, we re-bootstrap before forwarding.self._sandbox_alive: bool = False+ self._child_steering_protocol_version: int = 0# Activity tracking for CI follow-up timing. `_last_active_time` is# set when the sandbox workflow forwards a heartbeat with@@ -243,10 +264,70 @@ class TaskManagementWorkflow(PostHogWorkflow):self._pending_external_complete = (status, error_message)@workflow.signal- async def send_followup_message(self, message: str | None = None, artifact_ids: Optional[list[str]] = None) -> None:+ async def send_followup_message(+ self,+ message: str | None = None,+ artifact_ids: Optional[list[str]] = None,+ message_id: str | bool | None = None,+ actor_user_id: int | None = None,+ message_context: dict[str, Any] | None = None,+ ) -> None:+ legacy_steer = message_id if isinstance(message_id, bool) else False+ stable_message_id = message_id if isinstance(message_id, str) else None+ self._queue_external_followup(+ message,+ artifact_ids,+ actor_user_id=actor_user_id,+ message_id=stable_message_id,+ message_context=message_context,+ steer=legacy_steer,+ )++ @workflow.signal(name=SEND_STEER_SIGNAL)+ async def send_steer_message(+ self,+ message: str | None = None,+ artifact_ids: Optional[list[str]] = None,+ message_id: str | None = None,+ actor_user_id: int | None = None,+ message_context: dict[str, Any] | None = None,+ ) -> None:+ self._queue_external_followup(+ message,+ artifact_ids,+ actor_user_id=actor_user_id,+ message_id=message_id,+ message_context=message_context,+ steer=True,+ )++ @workflow.query(name=STEERING_PROTOCOL_QUERY)+ def steering_protocol_version(self) -> int:+ return STEERING_PROTOCOL_VERSION++ def _queue_external_followup(+ self,+ message: str | None,+ artifact_ids: Optional[list[str]],+ actor_user_id: int | None = None,+ message_id: str | None = None,+ message_context: dict[str, Any] | None = None,+ *,+ steer: bool,+ ) -> None:self._pending_external_followups.append(- PendingExternalFollowup(message=message, artifact_ids=artifact_ids or [], source=FOLLOWUP_SOURCE_USER)+ PendingExternalFollowup(+ message=message,+ artifact_ids=artifact_ids or [],+ source=FOLLOWUP_SOURCE_USER,+ actor_user_id=actor_user_id,+ message_id=message_id,+ context=message_context if isinstance(message_context, dict) else {},+ steer=steer,+ sequence=self._next_followup_sequence,+ ))+ self._next_followup_sequence += 1@workflow.signalasync def heartbeat(self, agent_active: bool = False) -> None:@@ -330,6 +411,7 @@ class TaskManagementWorkflow(PostHogWorkflow):self._slack_thread_context = input.slack_thread_contextself._posthog_mcp_scopes = input.posthog_mcp_scopesself._sandbox_workflow_id = f"{workflow.info().workflow_id}-sandbox"+ self._ack_before_completion = _ack_before_completion()try:self._context = await self._get_task_processing_context()@@ -425,11 +507,10 @@ class TaskManagementWorkflow(PostHogWorkflow):or self._child_completion is not None))- # Session-completion wins outright — short-circuits any pending work- # because the current sandbox session is ending. The orchestrator- # itself keeps running; the next follow-up will re-bootstrap a- # fresh sandbox.- if self._child_completion is not None:+ # Older histories processed completion first. New executions drain+ # ACKs before resetting the sandbox session so an already-delivered+ # follow-up is not re-queued onto the replacement sandbox.+ if self._child_completion is not None and (not self._ack_before_completion or not self._child_acks):return TaskEvent.CHILD_COMPLETED# Prefer external signals when both classes are pending — the child# signal drain is cheap and rarely time-critical.@@ -525,6 +606,11 @@ class TaskManagementWorkflow(PostHogWorkflow):message=followup.message,artifact_ids=followup.artifact_ids,source=followup.source,+ actor_user_id=followup.actor_user_id,+ message_id=followup.message_id,+ message_context=followup.context,+ steer=followup.steer,+ sequence=followup.sequence,)# The persisted queue is the orchestrator's recovery buffer — keep# it in sync after every drain so a restart sees an accurate picture@@ -540,7 +626,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# ACKs match pending signal slots by ack_id. We log unmatched ACKs at# debug — they happen if a slot was already cleared by a timeout, but# the work was still done by the child.- any_requeued = False+ requeued_followups: list[PendingExternalFollowup] = []while self._child_acks:ack = self._child_acks.pop(0)slot = self._pending_ack_slots.pop(ack.ack_id, None)@@ -557,8 +643,9 @@ class TaskManagementWorkflow(PostHogWorkflow):# Re-queue follow-ups so the next sandbox session picks them# up. complete_task rejections are fine to drop — the child# is shutting down precisely because it's already completing.- if self._handle_shutdown_rejection(slot):- any_requeued = True+ followup = self._followup_from_shutdown_rejection(slot)+ if followup is not None:+ requeued_followups.append(followup)continueworkflow.logger.info("task_management_ack_received",@@ -570,32 +657,55 @@ class TaskManagementWorkflow(PostHogWorkflow):detail=ack.detail,)self._heartbeat_received = False- if any_requeued:+ for followup in requeued_followups:+ self._insert_external_followup_in_arrival_order(followup)+ if requeued_followups:# Sync the recovery buffer to reflect the re-queue; otherwise an# orchestrator restart would forget about the rejected follow-up.await self._persist_pending_followups()- def _handle_shutdown_rejection(self, slot: PendingAckSlot) -> bool:- """Re-queue rejected follow-up work. Returns True if anything was re-queued."""- if slot.signal_name == SEND_FOLLOWUP_SIGNAL and slot.signal_args is not None:- # signal_args = [ack_id, message, artifact_ids, source]- _ack_id, message, artifact_ids, source = slot.signal_args- self._pending_external_followups.insert(- 0,- PendingExternalFollowup(message=message, artifact_ids=artifact_ids, source=source),- )+ def _followup_from_shutdown_rejection(self, slot: PendingAckSlot) -> PendingExternalFollowup | None:+ if slot.signal_name in {SEND_FOLLOWUP_SIGNAL, SEND_STEER_SIGNAL} and slot.signal_args is not None:workflow.logger.warning("task_management_followup_requeued_after_shutdown",run_id=self._run_id,- source=source,+ source=slot.signal_args[3],)- return True+ return self._external_followup_from_slot(slot)workflow.logger.info("task_management_shutdown_rejection_ignored",run_id=self._run_id,signal_name=slot.signal_name,)- return False+ return None++ @staticmethod+ def _external_followup_from_slot(slot: PendingAckSlot) -> PendingExternalFollowup:+ assert slot.signal_args is not None+ _ack_id, message, artifact_ids, source, *metadata = slot.signal_args+ message_id = metadata[0] if metadata and isinstance(metadata[0], str) else None+ actor_user_id = (+ metadata[1]+ if len(metadata) > 1 and isinstance(metadata[1], int) and not isinstance(metadata[1], bool)+ else None+ )+ context = metadata[2] if len(metadata) > 2 and isinstance(metadata[2], dict) else {}+ return PendingExternalFollowup(+ message=message,+ artifact_ids=artifact_ids,+ source=source,+ actor_user_id=actor_user_id,+ message_id=message_id,+ context=context,+ sequence=slot.sequence,+ )++ def _insert_external_followup_in_arrival_order(self, followup: PendingExternalFollowup) -> None:+ for index, pending in enumerate(self._pending_external_followups):+ if pending.sequence > followup.sequence:+ self._pending_external_followups.insert(index, followup)+ return+ self._pending_external_followups.append(followup)# ------------------------------------------------------------------# Sandbox session lifecycle (multiple sessions per orchestrator)@@ -627,11 +737,8 @@ class TaskManagementWorkflow(PostHogWorkflow):# than silently dropping user input.requeued = 0for slot in list(self._pending_ack_slots.values()):- if slot.signal_name == SEND_FOLLOWUP_SIGNAL and slot.signal_args is not None:- _ack_id, message, artifact_ids, source = slot.signal_args- self._pending_external_followups.append(- PendingExternalFollowup(message=message, artifact_ids=artifact_ids, source=source)- )+ if slot.signal_name in {SEND_FOLLOWUP_SIGNAL, SEND_STEER_SIGNAL} and slot.signal_args is not None:+ self._insert_external_followup_in_arrival_order(self._external_followup_from_slot(slot))requeued += 1if requeued:workflow.logger.warning(@@ -646,6 +753,7 @@ class TaskManagementWorkflow(PostHogWorkflow):self._pending_ack_slots.clear()self._child_completion = Noneself._sandbox_alive = False+ self._child_steering_protocol_version = 0self._ci_repetitions = 0self._pr_fingerprint = Noneself._pr_unresolved_threads = 0@@ -675,11 +783,25 @@ class TaskManagementWorkflow(PostHogWorkflow):if not result.followups:returnfor item in result.followups:+ sequence = item.get("sequence")+ if not isinstance(sequence, int):+ sequence = self._next_followup_sequence+ self._next_followup_sequence = max(self._next_followup_sequence, sequence + 1)self._pending_external_followups.append(PendingExternalFollowup(message=item.get("message"),artifact_ids=list(item.get("artifact_ids") or []),source=item.get("source", FOLLOWUP_SOURCE_USER),+ actor_user_id=(+ item.get("actor_user_id")+ if isinstance(item.get("actor_user_id"), int)+ and not isinstance(item.get("actor_user_id"), bool)+ else None+ ),+ message_id=item.get("message_id") if isinstance(item.get("message_id"), str) else None,+ context=item.get("context") if isinstance(item.get("context"), dict) else {},+ steer=item.get("steer") is True,+ sequence=sequence,))# Seed the persistence snapshot so the next `_persist_pending_followups`@@ -740,7 +862,7 @@ class TaskManagementWorkflow(PostHogWorkflow):signal_name=PARENT_ATTACHED_SIGNAL,sent_at=workflow.now(),)- await workflow.execute_activity(+ protocol_version = await workflow.execute_activity(ensure_execute_sandbox_started,EnsureExecuteSandboxStartedInput(workflow_id=self._sandbox_workflow_id,@@ -756,6 +878,7 @@ class TaskManagementWorkflow(PostHogWorkflow):start_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=3),)+ self._child_steering_protocol_version = protocol_version if isinstance(protocol_version, int) else 0# Activity success means Signal-With-Start landed — either delivered# to an already-running execution or kicked off a fresh one. Either# way, a sandbox session is now in-flight.@@ -770,6 +893,11 @@ class TaskManagementWorkflow(PostHogWorkflow):message: str | None,artifact_ids: list[str],source: str = FOLLOWUP_SOURCE_USER,+ actor_user_id: int | None = None,+ message_id: str | None = None,+ message_context: dict[str, Any] | None = None,+ steer: bool = False,+ sequence: int | None = None,) -> None:if self._sandbox_workflow_id is None:workflow.logger.warning(@@ -779,18 +907,35 @@ class TaskManagementWorkflow(PostHogWorkflow):)returnack_id = self._new_ack_id()- signal_args: list[Any] = [ack_id, message, artifact_ids, source]+ if sequence is None:+ sequence = self._next_followup_sequence+ self._next_followup_sequence += 1+ signal_args: list[Any] = [+ ack_id,+ message,+ artifact_ids,+ source,+ message_id,+ actor_user_id,+ message_context if isinstance(message_context, dict) else {},+ ]+ supports_steering = self._child_steering_protocol_version >= STEERING_PROTOCOL_VERSION+ if steer and workflow.patched(_PATCH_ID_CAPABILITY_GATED_STEERING):+ signal_name = SEND_STEER_SIGNAL if supports_steering else SEND_FOLLOWUP_SIGNAL+ else:+ signal_name = SEND_STEER_SIGNAL if steer else SEND_FOLLOWUP_SIGNAL# Register the slot *before* sending so an in-flight send-failure# leaves the slot intact for the retry loop to re-attempt. The child# dedupes by ack_id so re-sending is safe.self._pending_ack_slots[ack_id] = PendingAckSlot(- signal_name=SEND_FOLLOWUP_SIGNAL,+ signal_name=signal_name,sent_at=workflow.now(),detail=f"source={source}",signal_args=signal_args,+ sequence=sequence,)try:- await self._sandbox_handle().signal(SEND_FOLLOWUP_SIGNAL, args=signal_args)+ await self._sandbox_handle().signal(signal_name, args=signal_args)except Exception as e:# Keep the slot — `_retry_stale_acks` will try again after# ACK_TIMEOUT. This is the "child is dead, parent retries"diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex f887523bcb81..af6feeefe41f 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -4233,7 +4233,20 @@ class TestTaskRunAPI(BaseTaskAPITest):@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")def test_patch_cannot_mutate_protected_credential_state_keys(self, _mock_publish):+ credential_target = self.create_organization_user("credential-target")task = self.create_task()+ pending_external_followups = [+ {+ "message": "server queued message",+ "artifact_ids": [],+ "source": "user",+ "actor_user_id": self.user.id,+ "message_id": "server-message",+ "context": {},+ "steer": False,+ "sequence": 0,+ }+ ]run = TaskRun.objects.create(task=task,team=self.team,@@ -4253,6 +4266,8 @@ class TestTaskRunAPI(BaseTaskAPITest):"snapshot_mount_path": "/tmp","workflow_id": "wf-real","pending_dispatch": {"workflow_id_prefix": "review-real", "create_pr": True},+ "pending_external_followups": pending_external_followups,+ "pending_external_followups_generation": 7,},)@@ -4282,6 +4297,14 @@ class TestTaskRunAPI(BaseTaskAPITest):"snapshot_mount_path": "/tmp/workspace","workflow_id": "wf-another-teams-workflow","pending_dispatch": {"workflow_id_prefix": "attacker", "posthog_mcp_scopes": ["*"]},+ "pending_external_followups": [+ {+ "message": "attacker message",+ "actor_user_id": credential_target.id,+ "context": {"interaction_origin": "slack"},+ }+ ],+ "pending_external_followups_generation": 999,"scratch": "ok",}},@@ -4304,6 +4327,8 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["snapshot_mount_path"] == "/tmp"assert run.state["workflow_id"] == "wf-real"assert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}+ assert run.state["pending_external_followups"] == pending_external_followups+ assert run.state["pending_external_followups_generation"] == 7assert run.state["scratch"] == "ok" # non-protected keys still merge# Nor can a caller remove a protected key to force a fallback or unguarded path.@@ -4321,6 +4346,8 @@ class TestTaskRunAPI(BaseTaskAPITest):"snapshot_mount_path","workflow_id","pending_dispatch",+ "pending_external_followups",+ "pending_external_followups_generation","scratch",],},@@ -4337,6 +4364,8 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["snapshot_mount_path"] == "/tmp" # protected key survives removalassert run.state["workflow_id"] == "wf-real" # protected key survives removalassert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}+ assert run.state["pending_external_followups"] == pending_external_followups+ assert run.state["pending_external_followups_generation"] == 7assert "scratch" not in run.state # non-protected key removed@patch("products.tasks.backend.facade.api.signal_workflow_completion")