: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): steer active process workflows (#71943)
Alessandro Pogliaghi709be888a372
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 b6391d910295..2bd4d52ab105 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@@ -3,8 +3,9 @@ import asyncioimport pytestfrom unittest.mock import AsyncMock, Mock-from temporalio.exceptions import ActivityError, RetryState+from temporalio.exceptions import ActivityError, ApplicationError, RetryState+from products.tasks.backend.temporal.constants import MAX_FINAL_OUTBOUND_FLUSH_ATTEMPTSfrom products.tasks.backend.temporal.execute_sandbox import workflow as execute_sandbox_workflow_modulefrom products.tasks.backend.temporal.execute_sandbox.activities.reap_orphaned_sandbox import (ReapOrphanedSandboxInput,@@ -16,6 +17,7 @@ from products.tasks.backend.temporal.execute_sandbox.workflow import (PARENT_ATTACHED_SIGNAL,PARENT_COMPLETED_SIGNAL,PARENT_HEARTBEAT_SIGNAL,+ SEND_STEER_SIGNAL,ChildCompletionPayload,ExecuteSandboxInput,ExecuteSandboxWorkflow,@@ -27,6 +29,7 @@ from products.tasks.backend.temporal.process_task.activities.get_sandbox_for_repGetSandboxForRepositoryOutput,)from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext+from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import STEER_DECLINED_OUTCOMEfrom products.tasks.backend.temporal.process_task.activities.start_agent_server import StartAgentServerOutputfrom products.tasks.backend.temporal.process_task.credential_refresh import CredentialRefreshExitReason@@ -189,16 +192,25 @@ class TestSignalHandlers:)]- async def test_send_followup_message_queues_pending_followup_without_ack(self, silent_workflow_logger):+ async def test_send_steer_message_queues_pending_followup_without_ack(self, silent_workflow_logger):# ACK is deferred until the main loop actually dispatches — the# handler only enqueues. Logging is the only visible side-effect here.workflow = ExecuteSandboxWorkflow()workflow._context = _build_context()- await workflow.send_followup_message("ack-3", "hello", ["art-1"], source="user")+ await workflow.send_steer_message("ack-3", "hello", ["art-1"], source="user")+ 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")+ PendingFollowup(message="hello", artifact_ids=["art-1"], ack_id="ack-3", source="user", steer=True),+ PendingFollowup(+ message="legacy",+ artifact_ids=["art-2"],+ ack_id="ack-legacy",+ source="user",+ steer=True,+ sequence=1,+ ),]assert workflow._pending_outbound == []silent_workflow_logger.info.assert_called()@@ -338,6 +350,143 @@ class TestFlushPendingOutbound:# immediately and tight-loop against the unreachable parent.sleep_mock.assert_awaited_once()+ async def test_final_flush_retries_ack_before_sending_completion(self, monkeypatch, silent_workflow_logger):+ workflow = ExecuteSandboxWorkflow()+ workflow._context = _build_context()+ workflow._parent_workflow_id = "parent-wf"+ payload = ChildCompletionPayload(success=True, error=None, sandbox_id="sb-1", timed_out=False)+ workflow._pending_outbound.extend(+ [+ OutboundSignal(+ target_signal=PARENT_ACK_SIGNAL,+ args=["send_followup_message", "ack-delivered", True, None],+ correlation_id="ack-delivered",+ ),+ OutboundSignal(target_signal=PARENT_COMPLETED_SIGNAL, args=[payload]),+ ]+ )++ signal_mock = AsyncMock(side_effect=[RuntimeError("transient failure"), None, None])+ handle_mock = Mock()+ handle_mock.signal = signal_mock+ monkeypatch.setattr(+ execute_sandbox_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle_mock),+ )+ sleep_mock = AsyncMock()+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "sleep", sleep_mock)++ await workflow._flush_all_pending_outbound()++ assert [call.args[0] for call in signal_mock.await_args_list] == [+ PARENT_ACK_SIGNAL,+ PARENT_ACK_SIGNAL,+ PARENT_COMPLETED_SIGNAL,+ ]+ assert workflow._pending_outbound == []+ sleep_mock.assert_awaited_once()++ async def test_final_flush_stops_when_parent_workflow_is_closed(self, monkeypatch, silent_workflow_logger):+ workflow = ExecuteSandboxWorkflow()+ workflow._context = _build_context()+ workflow._parent_workflow_id = "parent-wf"+ workflow._pending_outbound.append(+ OutboundSignal(+ target_signal=PARENT_ACK_SIGNAL,+ args=["send_followup_message", "ack-delivered", True, None],+ )+ )++ signal_mock = AsyncMock(+ side_effect=ApplicationError(+ "Unable to signal external workflow because it was not found",+ type="ExternalWorkflowExecutionNotFound",+ )+ )+ handle_mock = Mock()+ handle_mock.signal = signal_mock+ monkeypatch.setattr(+ execute_sandbox_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle_mock),+ )+ sleep_mock = AsyncMock()+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "sleep", sleep_mock)++ await workflow._flush_all_pending_outbound()++ signal_mock.assert_awaited_once()+ sleep_mock.assert_not_awaited()+ assert workflow._pending_outbound == []++ async def test_final_flush_bounds_transient_parent_signal_retries(self, monkeypatch, silent_workflow_logger):+ workflow = ExecuteSandboxWorkflow()+ workflow._context = _build_context()+ workflow._parent_workflow_id = "parent-wf"+ workflow._pending_outbound.append(+ OutboundSignal(+ target_signal=PARENT_ACK_SIGNAL,+ args=["send_followup_message", "ack-delivered", True, None],+ )+ )++ signal_mock = AsyncMock(side_effect=RuntimeError("parent temporarily unavailable"))+ handle_mock = Mock()+ handle_mock.signal = signal_mock+ monkeypatch.setattr(+ execute_sandbox_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle_mock),+ )+ sleep_mock = AsyncMock()+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "sleep", sleep_mock)++ await workflow._flush_all_pending_outbound()++ assert signal_mock.await_count == MAX_FINAL_OUTBOUND_FLUSH_ATTEMPTS+ assert sleep_mock.await_count == MAX_FINAL_OUTBOUND_FLUSH_ATTEMPTS+ assert workflow._pending_outbound == []+ silent_workflow_logger.warning.assert_called()++ async def test_existing_history_keeps_retrying_past_new_final_flush_bound(+ self, monkeypatch, silent_workflow_logger+ ):+ workflow = ExecuteSandboxWorkflow()+ workflow._context = _build_context()+ workflow._parent_workflow_id = "parent-wf"+ workflow._pending_outbound.append(+ OutboundSignal(+ target_signal=PARENT_COMPLETED_SIGNAL,+ args=[ChildCompletionPayload(success=True)],+ )+ )++ signal_mock = AsyncMock(+ side_effect=[+ *[RuntimeError("parent temporarily unavailable")] * MAX_FINAL_OUTBOUND_FLUSH_ATTEMPTS,+ None,+ ]+ )+ handle_mock = Mock()+ handle_mock.signal = signal_mock+ monkeypatch.setattr(+ execute_sandbox_workflow_module.workflow,+ "get_external_workflow_handle",+ Mock(return_value=handle_mock),+ )+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "sleep", AsyncMock())+ monkeypatch.setattr(+ execute_sandbox_workflow_module,+ "_bounded_final_outbound_delivery",+ lambda: False,+ )++ await workflow._flush_all_pending_outbound()++ assert signal_mock.await_count == MAX_FINAL_OUTBOUND_FLUSH_ATTEMPTS + 1+ assert workflow._pending_outbound == []+async def test_no_backoff_when_flush_succeeds(self, monkeypatch):workflow = ExecuteSandboxWorkflow()workflow._context = _build_context()@@ -399,7 +548,7 @@ class TestHandleFollowup:PendingFollowup(message="msg", artifact_ids=["art-1"], ack_id="ack-ok", source="user"))- send_mock.assert_awaited_once_with(message="msg", artifact_ids=["art-1"])+ send_mock.assert_awaited_once_with(message="msg", artifact_ids=["art-1"], steer=False)assert workflow._pending_outbound == [OutboundSignal(target_signal=PARENT_ACK_SIGNAL,@@ -618,7 +767,7 @@ class TestRun:monkeypatch.setattr(workflow, "_cleanup_sandbox", cleanup_sandbox_mock)monkeypatch.setattr(workflow, "_create_resume_snapshot", create_resume_snapshot_mock)monkeypatch.setattr(workflow, "_clear_persisted_sandbox_id", AsyncMock())- monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())+ monkeypatch.setattr(workflow, "_flush_all_pending_outbound", AsyncMock())monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())monkeypatch.setattr(workflow, "_run_credential_refresh_until_sandbox_gone", AsyncMock())monkeypatch.setattr(@@ -678,7 +827,7 @@ class TestRun:monkeypatch.setattr(workflow, "_update_task_run_status", update_status_mock)monkeypatch.setattr(workflow, "_track_workflow_event", track_event_mock)monkeypatch.setattr(workflow, "_reap_orphaned_sandbox", reap_mock)- monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())+ monkeypatch.setattr(workflow, "_flush_all_pending_outbound", AsyncMock())result = await workflow.run(ExecuteSandboxInput(run_id="run-id", parent_workflow_id="parent-wf-id"))@@ -786,7 +935,7 @@ class TestHandleFollowupInFlightTracking:snapshot: dict[str, bool] = {}- async def fake_send(message=None, artifact_ids=None):+ async def fake_send(message=None, artifact_ids=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)@@ -815,6 +964,81 @@ class TestHandleFollowupInFlightTracking:assert "ack-fail" not in workflow._in_flight_followup_ack_idsassert "ack-fail" in workflow._acked_ids+ async def test_declined_steers_requeue_in_arrival_order(self, monkeypatch, silent_workflow_logger):+ workflow = ExecuteSandboxWorkflow()+ workflow._context = _build_context()+ release_initial = asyncio.Event()+ deliveries: list[tuple[str | None, bool]] = []++ async def fake_send_followup(*, message, artifact_ids, steer=False):+ deliveries.append((message, steer))+ if message == "keep working":+ await release_initial.wait()+ elif steer:+ return STEER_DECLINED_OUTCOME+ return None++ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)+ monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "patched", Mock(return_value=True))++ await workflow.send_followup_message("ack-normal", "keep working")+ assert await workflow._dispatch_next_followup() is True+ await asyncio.sleep(0)++ await workflow.send_steer_message("ack-steer", "use green instead")+ assert await workflow._dispatch_next_followup() is True+ await workflow.send_steer_message("ack-steer-2", "use blue instead")+ assert await workflow._dispatch_next_followup() is True++ assert deliveries == [+ ("keep working", False),+ ("use green instead", True),+ ("use blue instead", True),+ ]+ assert [(followup.message, followup.steer) for followup in workflow._pending_followups] == [+ ("use green instead", False),+ ("use blue instead", False),+ ]+ release_initial.set()+ await workflow._finish_active_followup()+ assert deliveries == [+ ("keep working", False),+ ("use green instead", True),+ ("use blue instead", True),+ ("use green instead", False),+ ("use blue instead", False),+ ]++ async def test_completion_waits_for_declined_steer_fallback(self, monkeypatch, silent_workflow_logger):+ workflow = ExecuteSandboxWorkflow()+ workflow._context = _build_context()+ release_steer = asyncio.Event()+ deliveries: list[tuple[str | None, bool]] = []++ async def fake_send_followup(*, message, artifact_ids, steer=False):+ deliveries.append((message, steer))+ if steer:+ await release_steer.wait()+ return STEER_DECLINED_OUTCOME+ return None++ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)+ monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())+ monkeypatch.setattr(execute_sandbox_workflow_module.workflow, "patched", Mock(return_value=True))++ await workflow.send_steer_message("ack-steer", "finish in green")+ assert await workflow._dispatch_next_followup() is True+ await asyncio.sleep(0)++ await workflow.complete_task("ack-complete")+ release_steer.set()+ await workflow._finish_active_followup()++ assert deliveries == [("finish in green", True), ("finish in green", False)]+ assert workflow._pending_followups == []+ assert "ack-steer" in workflow._acked_ids+async def test_parent_attached_replay_only_re_acks(self, silent_workflow_logger):workflow = ExecuteSandboxWorkflow()workflow._parent_workflow_id = "original-parent"@@ -846,13 +1070,13 @@ class TestShutdownRejection:normally queue new work are rejected so the orchestrator's retry pathcan route them to a fresh sandbox instead of silently losing them."""- async def test_send_followup_rejected_with_known_detail(self, silent_workflow_logger):+ async def test_terminal_drain_rejects_late_steer_with_known_detail(self, silent_workflow_logger):workflow = ExecuteSandboxWorkflow()workflow._context = _build_context()- workflow._shutting_down = Trueworkflow._pending_outbound.clear()- await workflow.send_followup_message("ack-late", "post-shutdown msg")+ await workflow._finish_active_followup()+ await workflow.send_steer_message("ack-late", "post-shutdown msg")# No queueing — the message goes nowhere on the sandbox side.assert workflow._pending_followups == []@@ -861,7 +1085,7 @@ class TestShutdownRejection:assert workflow._pending_outbound == [OutboundSignal(target_signal=PARENT_ACK_SIGNAL,- args=["send_followup_message", "ack-late", False, "child_shutting_down"],+ args=[SEND_STEER_SIGNAL, "ack-late", False, "child_shutting_down"],correlation_id="ack-late",)]@@ -953,7 +1177,7 @@ class TestCompletionStatusOnExceptionPaths:monkeypatch.setattr(workflow, "_update_task_run_status", AsyncMock())monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())monkeypatch.setattr(workflow, "_reap_orphaned_sandbox", AsyncMock())- monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())+ monkeypatch.setattr(workflow, "_flush_all_pending_outbound", AsyncMock())with pytest.raises(asyncio.CancelledError):await workflow.run(ExecuteSandboxInput(run_id="run-id", parent_workflow_id="parent-wf-id"))@@ -978,7 +1202,7 @@ class TestCompletionStatusOnExceptionPaths:monkeypatch.setattr(workflow, "_update_task_run_status", AsyncMock())monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())monkeypatch.setattr(workflow, "_reap_orphaned_sandbox", AsyncMock())- monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())+ monkeypatch.setattr(workflow, "_flush_all_pending_outbound", AsyncMock())result = await workflow.run(ExecuteSandboxInput(run_id="run-id", parent_workflow_id="parent-wf-id"))diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex 0e2ebaff7907..61eab1dba3d5 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -26,9 +26,13 @@ from posthog.temporal.oauth import PosthogMcpScopesfrom products.tasks.backend.error_telemetry import truncate_error_messagefrom products.tasks.backend.logic.services.sandbox import is_public_sandbox_repofrom products.tasks.backend.temporal.constants import (+ MAX_FINAL_OUTBOUND_FLUSH_ATTEMPTS,OUTBOUND_RETRY_BACKOFF,PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,+ SEND_STEER_SIGNAL,+ STEERING_PROTOCOL_QUERY,+ STEERING_PROTOCOL_VERSION,)from products.tasks.backend.temporal.execute_sandbox.activities.reap_orphaned_sandbox import (ReapOrphanedSandboxInput,@@ -80,6 +84,7 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_event)from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (SEND_FOLLOWUP_MAX_ATTEMPTS,+ STEER_DECLINED_OUTCOME,SendFollowupToSandboxInput,send_followup_to_sandbox,)@@ -170,6 +175,8 @@ class PendingFollowup:artifact_ids: list[str]ack_id: strsource: str = FOLLOWUP_SOURCE_USER # FOLLOWUP_SOURCE_USER | FOLLOWUP_SOURCE_CI+ steer: bool = False+ sequence: int = 0@dataclass@@ -209,6 +216,33 @@ class SandboxEvent(StrEnum):SANDBOX_GONE = "sandbox_gone"+_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING = "tasks-execute-sandbox-concurrent-followup-steering"+_PATCH_ID_ORDERED_OUTBOUND_DELIVERY = "tasks-execute-sandbox-ordered-outbound-delivery"+_PATCH_ID_BOUNDED_FINAL_OUTBOUND_DELIVERY = "tasks-execute-sandbox-bounded-final-outbound-delivery"+_PARENT_SIGNAL_TERMINAL_ERROR_TYPES = {+ "ExternalWorkflowExecutionNotFound",+ "NamespaceNotFound",+}+++def _ordered_outbound_delivery() -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(_PATCH_ID_ORDERED_OUTBOUND_DELIVERY)+++def _bounded_final_outbound_delivery() -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(_PATCH_ID_BOUNDED_FINAL_OUTBOUND_DELIVERY)+++def _parent_cannot_receive_signals(error: Exception) -> bool:+ return (+ isinstance(error, temporalio.exceptions.ApplicationError) and error.type in _PARENT_SIGNAL_TERMINAL_ERROR_TYPES+ )++@temporalio.workflow.defn(name="execute-sandbox")class ExecuteSandboxWorkflow(PostHogWorkflow):"""Run a single sandbox session for a task run.@@ -250,7 +284,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):self._heartbeat_received: bool = Falseself._pending_followups: list[PendingFollowup] = []+ self._next_followup_sequence: int = 0self._pending_outbound: list[OutboundSignal] = []+ self._ordered_outbound_delivery: bool = True+ self._parent_signal_delivery_closed: bool = False+ self._active_followup_task: asyncio.Task[None] | None = None# Set in the `finally` block before we start emitting the terminal# completion signal. While true, signal handlers that would otherwise@@ -305,7 +343,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):self._task_completedor self._sandbox_goneor self._heartbeat_received- or len(self._pending_followups) > 0+ or self._has_dispatchable_followup()or len(self._pending_outbound) > 0))@@ -313,6 +351,62 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):return SandboxEvent.SANDBOX_GONEreturn SandboxEvent.SIGNAL_RECEIVED+ def _has_dispatchable_followup(self) -> bool:+ if self._active_followup_task is None:+ return bool(self._pending_followups)+ if self._active_followup_task.done():+ return True+ return any(followup.steer for followup in self._pending_followups)++ def _pop_next_followup(self, *, steer_only: bool = False) -> PendingFollowup | None:+ for index, followup in enumerate(self._pending_followups):+ if not steer_only or followup.steer:+ return self._pending_followups.pop(index)+ return None++ def _insert_followup_in_arrival_order(self, followup: PendingFollowup) -> None:+ for index, pending in enumerate(self._pending_followups):+ if pending.sequence > followup.sequence:+ self._pending_followups.insert(index, followup)+ return+ self._pending_followups.append(followup)++ async def _dispatch_next_followup(self) -> bool:+ if self._active_followup_task is not None:+ if self._active_followup_task.done():+ task = self._active_followup_task+ self._active_followup_task = None+ await task+ return True+ followup = self._pop_next_followup(steer_only=True)+ if followup is None:+ return False+ await self._handle_followup(followup)+ return True++ followup = self._pop_next_followup()+ if followup is None:+ return False+ self._active_followup_task = asyncio.create_task(self._handle_followup(followup))+ return True++ async def _finish_active_followup(self) -> None:+ self._shutting_down = True+ while True:+ if self._active_followup_task is not None:+ task = self._active_followup_task+ self._active_followup_task = None+ await task++ if not self._pending_followups:+ return+ if not workflow.patched(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING):+ return++ followup = self._pop_next_followup()+ if followup is not None:+ await self._handle_followup(followup)+async def _wait_for_inactivity(self) -> SandboxEvent:await workflow.sleep(self.context.inactivity_timeout().total_seconds())return SandboxEvent.TIMEOUT_REACHED@@ -347,6 +441,8 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):timed_out = Falserun_id = input.run_id+ self._ordered_outbound_delivery = _ordered_outbound_delivery()+ self._parent_signal_delivery_closed = Falseself._parent_workflow_id = input.parent_workflow_idself._slack_thread_context = input.slack_thread_contextself._sandbox_id_for_cleanup = None@@ -424,7 +520,10 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):# check at the top of the loop exits us on the next pass.await self._flush_pending_outbound()- if self._pending_followups:+ if workflow.patched(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING):+ if await self._dispatch_next_followup():+ continue+ elif self._pending_followups:followup = self._pending_followups.pop(0)await self._handle_followup(followup)continue@@ -439,6 +538,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):case _:raise ValueError(f"Unknown sandbox event: {event}")+ await self._finish_active_followup()await self._cancel_relay(relay_task)# Drain any outbound signals that landed during shutdown so the# parent never waits on a signal we silently dropped.@@ -537,6 +637,10 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):# route them to a fresh sandbox instead of waiting on us.self._shutting_down = True+ if self._active_followup_task is not None:+ await self._cancel_relay(self._active_followup_task)+ self._active_followup_task = None+if credential_refresh_task is not None:await self._cancel_relay(credential_refresh_task)@@ -566,7 +670,10 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):)# Final outbound flush — the parent should never be left waiting# on a signal we accepted but never acknowledged.- await self._flush_pending_outbound()+ if self._ordered_outbound_delivery:+ await self._flush_all_pending_outbound()+ else:+ await self._flush_pending_outbound()# ------------------------------------------------------------------# Signal handlers — keep these short. They only mutate state; the main@@ -623,6 +730,47 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):message: str | None = None,artifact_ids: Optional[list[str]] = None,source: str = FOLLOWUP_SOURCE_USER,+ steer: bool = False,+ ) -> None:+ self._queue_followup_message(+ ack_id,+ message,+ artifact_ids,+ source,+ steer=steer,+ signal_name=SEND_FOLLOWUP_SIGNAL,+ )++ @workflow.signal(name=SEND_STEER_SIGNAL)+ async def send_steer_message(+ self,+ ack_id: str,+ message: str | None = None,+ artifact_ids: Optional[list[str]] = None,+ source: str = FOLLOWUP_SOURCE_USER,+ ) -> None:+ self._queue_followup_message(+ ack_id,+ message,+ artifact_ids,+ source,+ steer=True,+ signal_name=SEND_STEER_SIGNAL,+ )++ @workflow.query(name=STEERING_PROTOCOL_QUERY)+ def steering_protocol_version(self) -> int:+ return STEERING_PROTOCOL_VERSION++ def _queue_followup_message(+ self,+ ack_id: str,+ message: str | None,+ artifact_ids: Optional[list[str]],+ source: str,+ *,+ steer: bool,+ signal_name: str,) -> None:"""Accept a follow-up message from the parent and queue it.@@ -640,7 +788,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):ack_id=ack_id,)# Already dispatched (or rejected) — re-ack and skip.- if self._is_duplicate_signal(SEND_FOLLOWUP_SIGNAL, ack_id):+ if self._is_duplicate_signal(signal_name, ack_id):returnif any(p.ack_id == ack_id for p in self._pending_followups) or ack_id in self._in_flight_followup_ack_ids:# Still in flight from the first delivery (queued, or popped and@@ -652,7 +800,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):# route it to a fresh sandbox instead of waiting indefinitely# on a child that has already torn down its session.self._enqueue_ack(- signal_name=SEND_FOLLOWUP_SIGNAL,+ signal_name=signal_name,ack_id=ack_id,accepted=False,detail=SHUTDOWN_REJECTION_DETAIL,@@ -664,8 +812,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):artifact_ids=artifact_ids or [],ack_id=ack_id,source=source,+ steer=steer,+ sequence=self._next_followup_sequence,))+ self._next_followup_sequence += 1@workflow.signal(name=HEARTBEAT_SIGNAL)async def heartbeat(self, agent_active: bool = False) -> None:@@ -689,6 +840,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):# arrives mid-dispatch sees it via the dedupe check in# `send_followup_message` and is dropped quietly.self._in_flight_followup_ack_ids.add(followup.ack_id)+ signal_name = SEND_STEER_SIGNAL if followup.steer else SEND_FOLLOWUP_SIGNALtry:if self._should_skip_followup(followup.message, followup.artifact_ids):workflow.logger.warning(@@ -697,7 +849,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):ack_id=followup.ack_id,)self._enqueue_ack(- signal_name=SEND_FOLLOWUP_SIGNAL,+ signal_name=signal_name,ack_id=followup.ack_id,accepted=False,detail="empty follow-up skipped",@@ -705,11 +857,23 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):returntry:- await self._send_followup_to_sandbox(+ outcome = await self._send_followup_to_sandbox(message=followup.message,artifact_ids=followup.artifact_ids,+ steer=followup.steer,)- self._enqueue_ack(signal_name=SEND_FOLLOWUP_SIGNAL, ack_id=followup.ack_id)+ if followup.steer and outcome == STEER_DECLINED_OUTCOME:+ self._insert_followup_in_arrival_order(+ PendingFollowup(+ message=followup.message,+ artifact_ids=followup.artifact_ids,+ ack_id=followup.ack_id,+ source=followup.source,+ sequence=followup.sequence,+ ),+ )+ return+ self._enqueue_ack(signal_name=signal_name, ack_id=followup.ack_id)except Exception as e:# Mirror process_task: a failed follow-up dispatch is terminal.# Surface the failure to the parent via both the ACK and the@@ -727,7 +891,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):self._completion_error_type = "followup_delivery_failed"self._task_completed = Trueself._enqueue_ack(- signal_name=SEND_FOLLOWUP_SIGNAL,+ signal_name=signal_name,ack_id=followup.ack_id,accepted=False,detail=(cause_message or str(e))[:200],@@ -784,29 +948,28 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):)async def _flush_pending_outbound(self) -> None:- if not self._pending_outbound or not self._parent_workflow_id:+ if not self._pending_outbound or not self._parent_workflow_id or self._parent_signal_delivery_closed:return# Snapshot + clear before awaiting so a signal landing mid-flush# doesn't lose its delivery on the next iteration.- #- # Ordering note: we keep iterating after a failure, so a later- # signal that succeeds is delivered before an earlier one that- # failed and was re-queued. The protocol tolerates this — ACKs- # match by `ack_id` and PARENT_COMPLETED_SIGNAL is always enqueued- # last (from the finally block), so it trails any failed signals- # in the snapshot. Don't "fix" this by breaking after the first- # failure: that would drop the rest of the snapshot on the floor.to_send = self._pending_outboundself._pending_outbound = []parent = workflow.get_external_workflow_handle(self._parent_workflow_id)- for outbound in to_send:+ for index, outbound in enumerate(to_send):try:await parent.signal(outbound.target_signal, args=outbound.args)except Exception as e:- # Don't lose the signal — re-queue and let the next flush- # retry. If the parent is gone, future flushes will keep- # failing but the child run is independent and can complete- # on its own.+ if _parent_cannot_receive_signals(e):+ self._parent_signal_delivery_closed = True+ self._pending_outbound.clear()+ workflow.logger.info(+ "execute_sandbox_parent_signal_delivery_closed",+ run_id=self.context.run_id if self._context else None,+ target_signal=outbound.target_signal,+ correlation_id=outbound.correlation_id,+ error=str(e),+ )+ returnworkflow.logger.warning("execute_sandbox_outbound_signal_failed",run_id=self.context.run_id if self._context else None,@@ -814,6 +977,12 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):correlation_id=outbound.correlation_id,error=str(e),)+ if self._ordered_outbound_delivery:+ # Keep the failed ACK and every later signal ahead of+ # anything that arrived during the await. Completion must+ # never overtake an ACK for already-delivered work.+ self._pending_outbound = to_send[index:] + self._pending_outbound+ breakself._pending_outbound.append(outbound)if self._pending_outbound:# Re-queued items would otherwise wake the main loop immediately@@ -822,6 +991,24 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):# inactivity timer. Sleep to rate-limit retries.await workflow.sleep(OUTBOUND_RETRY_BACKOFF.total_seconds())+ async def _flush_all_pending_outbound(self) -> None:+ attempts = 0+ while self._pending_outbound and not self._parent_signal_delivery_closed:+ attempts += 1+ await self._flush_pending_outbound()+ if (+ self._pending_outbound+ and attempts >= MAX_FINAL_OUTBOUND_FLUSH_ATTEMPTS+ and _bounded_final_outbound_delivery()+ ):+ workflow.logger.warning(+ "execute_sandbox_final_outbound_retries_exhausted",+ run_id=self.context.run_id if self._context else None,+ attempts=attempts,+ undelivered=len(self._pending_outbound),+ )+ self._pending_outbound.clear()+# ------------------------------------------------------------------# Activities — these mirror process_task's implementations directly so# the sandbox lifecycle stays identical. Anything that was about CI@@ -1188,14 +1375,16 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):elif result.error:workflow.logger.warning(f"Resume snapshot skipped: {result.error}")- async def _send_followup_to_sandbox(self, message: str | None, artifact_ids: list[str]) -> None:+ async def _send_followup_to_sandbox(+ self, message: str | None, artifact_ids: list[str], *, steer: bool = False+ ) -> str | None:workflow.logger.info("execute_sandbox_send_followup_begin",run_id=self.context.run_id,message_length=len(message or ""),artifact_count=len(artifact_ids),)- await workflow.execute_activity(+ return await workflow.execute_activity(send_followup_to_sandbox,SendFollowupToSandboxInput(run_id=self.context.run_id,@@ -1203,6 +1392,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):posthog_mcp_scopes=self._posthog_mcp_scopes,artifact_ids=artifact_ids,message_id=str(workflow.uuid4()),+ steer=steer,),start_to_close_timeout=timedelta(minutes=35),# See process_task: heartbeat detects worker restarts, message_iddiff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.pyindex 801666500dc3..5ff8f1fcd6ce 100644--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py@@ -152,25 +152,42 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:state = task_run.stateif input.actor_user_id is not None:state = {**(state or {}), "slack_actor_user_id": input.actor_user_id}- if is_slack_interaction_state(state):- # Deliveries are serialized by the workflow, so stamping here- # moves the durable actor at turn boundaries — between-turn- # consumers (reply tagging, permission broker) see the executing- # turn's actor. Skipped when already current.- updates = slack_actor_state_updates(user_id=input.actor_user_id, slack_user_id=actor_slack_user_id)- current = task_run.state or {}- if any(current.get(key) != value for key, value in updates.items()):- try:- TaskRun.update_state_atomic(task_run.id, updates=updates)- except Exception:- logger.warning("send_followup_actor_stamp_failed", run_id=input.run_id, exc_info=True)- auth_token = Noneactor_user = get_task_run_credential_user(task_run.task, state)if is_slack_interaction_state(state) and actor_user is None:error_msg = "Slack actor unavailable for this run"_write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))raise RuntimeError(f"send_followup failed: {error_msg}")++ if input.steer:+ bound_user_id = get_sandbox_mcp_session_user(sandbox_identity_scope(str(task_run.id), task_run.state))+ if (+ input.actor_user_id is None+ or actor_user is None+ or actor_user.id != input.actor_user_id+ or bound_user_id != input.actor_user_id+ ):+ logger.info(+ "send_followup_steer_actor_mismatch",+ run_id=input.run_id,+ actor_user_id=input.actor_user_id,+ resolved_user_id=actor_user.id if actor_user is not None else None,+ bound_user_id=bound_user_id,+ )+ return STEER_DECLINED_OUTCOME++ if input.actor_user_id is not None and is_slack_interaction_state(state):+ # Deliveries are serialized by the workflow, so stamping here moves+ # the durable actor only after an active steer passes its identity gate.+ updates = slack_actor_state_updates(user_id=input.actor_user_id, slack_user_id=actor_slack_user_id)+ current = task_run.state or {}+ if any(current.get(key) != value for key, value in updates.items()):+ try:+ TaskRun.update_state_atomic(task_run.id, updates=updates)+ except Exception:+ logger.warning("send_followup_actor_stamp_failed", run_id=input.run_id, exc_info=True)++ auth_token = Noneif actor_user and actor_user.id:auth_token = create_sandbox_connection_token(task_run, user_id=actor_user.id, distinct_id=get_actor_distinct_id(actor_user)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.pyindex 763e4dc02237..4af87b8abc6e 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py@@ -80,14 +80,34 @@ class TestSendFollowupToSandbox(BaseTest):mock_refresh_sandbox_mcp,):task_run = MagicMock()- task_run.task.created_by = None+ task_run.id = "run-123"+ task_run.state = {"sandbox_id": "sandbox-123"}+ task_run.task.created_by_id = 42+ task_run.task.created_by = MagicMock(id=42)mock_task_run_objects.select_related.return_value.get.return_value = task_runmock_send_user_message.return_value = MagicMock(success=True,data={"result": {"stopReason": "steered", "steered": True}},)- send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-123", message="change direction", steer=True))+ with (+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_sandbox_mcp_session_user",+ return_value=42,+ ),+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.create_sandbox_connection_token",+ return_value=None,+ ),+ ):+ send_followup_to_sandbox(+ SendFollowupToSandboxInput(+ run_id="run-123",+ message="change direction",+ actor_user_id=42,+ steer=True,+ )+ )mock_refresh_sandbox_mcp.assert_not_called()mock_send_user_message.assert_called_once_with(diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.pyindex 6a75bac03f95..a3a5be67c43a 100644--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py@@ -469,6 +469,19 @@ class TestSendFollowupActivityRefreshOrdering:args, _kwargs = _patches["refresh"].call_argsassert args[1] == "read_only"+ def test_steer_from_different_actor_declines_before_using_credentials(self, _patches):+ _patches["task_run"].state = {"sandbox_id": "sandbox-1"}+ _patches["task_run"].task.created_by_id = 42++ outcome = send_followup_to_sandbox(+ SendFollowupToSandboxInput(run_id="run-1", message="hi", actor_user_id=99, steer=True)+ )++ assert outcome == STEER_DECLINED_OUTCOME+ _patches["conn_token"].assert_not_called()+ _patches["refresh"].assert_not_called()+ _patches["user_msg"].assert_not_called()+class TestSendFollowupTurnTimeout:"""A read timeout (turn_in_flight) means the message was delivered and the@@ -504,6 +517,7 @@ class TestSendFollowupTurnTimeout:mock_conn_token.return_value = "jwt"yield {+ "task_run": task_run,"user_msg": mock_user_msg,"turn_complete": mock_turn_complete,"error": mock_error,@@ -607,17 +621,29 @@ class TestSendFollowupTurnTimeout:_patches["turn_complete"].assert_not_called()def test_declined_steer_returns_for_normal_requeue_without_markers(self, _patches):+ _patches["task_run"].state = {"sandbox_id": "sandbox-1"}_patches["user_msg"].return_value = CommandResult(success=True,status_code=200,data={"result": {"steered": False, "stopReason": STEER_DECLINED_OUTCOME}},)- outcome = send_followup_to_sandbox(- SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1", steer=True)- )+ with patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_sandbox_mcp_session_user",+ return_value=42,+ ):+ outcome = send_followup_to_sandbox(+ SendFollowupToSandboxInput(+ run_id="run-1",+ message="hi",+ message_id="m-1",+ actor_user_id=42,+ steer=True,+ )+ )assert outcome == STEER_DECLINED_OUTCOME+ _patches["user_msg"].assert_called_once()_patches["error"].assert_not_called()_patches["turn_complete"].assert_not_called()diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex e2cc92a4ac0c..4f55b04688ea 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -23,6 +23,7 @@ from products.tasks.backend.models import SandboxSnapshotfrom products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_USER_SECONDS, WARM_IDLE_TIMEOUTfrom products.tasks.backend.temporal.process_task import workflow as process_task_workflow_modulefrom products.tasks.backend.temporal.process_task.activities import (+ STEER_DECLINED_OUTCOME,CleanupSandboxInput,CompleteRunStreamInput,CreateSandboxForRepositoryInput,@@ -303,6 +304,187 @@ class TestProcessTaskWorkflow:assert result.error is not None+class TestProcessTaskFollowupDispatch:+ async def test_declined_steers_requeue_in_arrival_order(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ release_initial = asyncio.Event()+ deliveries: list[tuple[str | None, bool]] = []++ async def fake_send_followup(+ *, message, artifact_ids, actor_user_id=None, message_id=None, context=None, steer=False+ ):+ deliveries.append((message, steer))+ if message == "keep working":+ await release_initial.wait()+ elif steer:+ return STEER_DECLINED_OUTCOME+ return None++ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ await workflow.send_followup_message("keep working")+ assert await workflow._dispatch_next_followup() is True+ await asyncio.sleep(0)++ await workflow.send_steer_message("use green instead")+ assert await workflow._dispatch_next_followup() is True+ await workflow.send_steer_message("use blue instead")+ assert await workflow._dispatch_next_followup() is True++ assert deliveries == [+ ("keep working", False),+ ("use green instead", True),+ ("use blue instead", True),+ ]+ assert [(followup.message, followup.steer) for followup in workflow._pending_followups] == [+ ("use green instead", False),+ ("use blue instead", False),+ ]+ release_initial.set()+ await workflow._finish_active_followup()+ assert deliveries == [+ ("keep working", False),+ ("use green instead", True),+ ("use blue instead", True),+ ("use green instead", False),+ ("use blue instead", False),+ ]++ async def test_sender_message_id_survives_concurrent_dispatch(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ deliveries: list[tuple[str | None, str | None, bool]] = []++ async def fake_send_followup(+ *, message, artifact_ids, actor_user_id=None, message_id=None, context=None, steer=False+ ):+ deliveries.append((message, message_id, steer))+ return None++ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ await workflow.send_followup_message("from Slack", [], "message-123")+ assert await workflow._dispatch_next_followup() is True+ await workflow._finish_active_followup()++ assert deliveries == [("from Slack", "message-123", False)]++ async def test_native_steer_preserves_sender_identity(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ deliveries: list[tuple[int | None, str | None, dict[str, object] | None, bool]] = []++ async def fake_send_followup(+ *, message, artifact_ids, actor_user_id=None, message_id=None, context=None, steer=False+ ):+ deliveries.append((actor_user_id, message_id, context, steer))+ return None++ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ await workflow.send_steer_message(+ "from Slack",+ [],+ "message-123",+ 42,+ {"actor_slack_user_id": "U1"},+ )+ assert await workflow._dispatch_next_followup() is True+ await workflow._finish_active_followup()++ assert deliveries == [(42, "message-123", {"actor_slack_user_id": "U1"}, True)]++ async def test_terminal_drain_closes_followup_admission(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ await workflow._finish_active_followup()+ await workflow.send_steer_message("too late")++ assert workflow._pending_followup is None+ assert workflow._pending_followups == []++ async def test_final_drain_rejects_followup_while_active_dispatch_finishes(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ release_initial = asyncio.Event()+ deliveries: list[str | None] = []++ async def fake_send_followup(+ *, message, artifact_ids, actor_user_id=None, message_id=None, context=None, steer=False+ ):+ deliveries.append(message)+ if message == "keep working":+ await release_initial.wait()+ return None++ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ await workflow.send_followup_message("keep working")+ assert await workflow._dispatch_next_followup() is True+ await asyncio.sleep(0)++ finish_task = asyncio.create_task(workflow._finish_active_followup())+ await asyncio.sleep(0)+ assert workflow._shutting_down is True++ await workflow.send_followup_message("arrived during drain")+ release_initial.set()+ await finish_task++ assert deliveries == ["keep working"]+ assert workflow._pending_followups == []++ async def test_completion_waits_for_declined_steer_fallback(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ release_steer = asyncio.Event()+ deliveries: list[tuple[str | None, bool]] = []++ async def fake_send_followup(+ *, message, artifact_ids, actor_user_id=None, message_id=None, context=None, steer=False+ ):+ deliveries.append((message, steer))+ if steer:+ await release_steer.wait()+ return STEER_DECLINED_OUTCOME+ return None++ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", fake_send_followup)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=Mock()))+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "deprecate_patch", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())++ await workflow.send_steer_message("finish in green")+ assert await workflow._dispatch_next_followup() is True+ await asyncio.sleep(0)++ await workflow.complete_task()+ release_steer.set()+ await workflow._finish_active_followup()++ assert deliveries == [("finish in green", True), ("finish in green", False)]+ assert workflow._pending_followup is None+ assert workflow._pending_followups == []++@pytest.mark.django_dbclass TestProcessTaskWorkflowUnit:async def test_final_sandbox_cleanup_completes_the_run_stream(self, monkeypatch):@@ -367,11 +549,13 @@ class TestProcessTaskWorkflowUnit:workflow = ProcessTaskWorkflow()await workflow.send_followup_message("first", ["artifact-1"])- await workflow.send_followup_message("second", ["artifact-2"])+ await workflow.send_steer_message("second", ["artifact-2"])+ await workflow.send_followup_message("legacy-steer", ["artifact-3"], True)assert workflow._pending_followups == [PendingFollowup(message="first", artifact_ids=["artifact-1"]),- PendingFollowup(message="second", artifact_ids=["artifact-2"]),+ PendingFollowup(message="second", artifact_ids=["artifact-2"], steer=True, sequence=1),+ PendingFollowup(message="legacy-steer", artifact_ids=["artifact-3"], steer=True, sequence=2),]assert workflow._pending_followup is Nonedeprecate_patch.assert_called_with(process_task_workflow_module._PATCH_ID_FOLLOWUP_QUEUE)@@ -391,7 +575,7 @@ class TestProcessTaskWorkflowUnit:"artifact_count": 1,},)- assert logger.info.call_count == 2+ assert logger.info.call_count == 3async def test_send_permission_response_can_arrive_before_context_is_loaded(self, monkeypatch):logger = Mock()diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 8d4d80754fac..471b82fcef09 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -72,6 +72,7 @@ from .activities.relay_sandbox_events import (from .activities.run_wizard import RunWizardInput, run_wizardfrom .activities.send_followup_to_sandbox import (SEND_FOLLOWUP_MAX_ATTEMPTS,+ STEER_DECLINED_OUTCOME,SendFollowupToSandboxInput,send_followup_to_sandbox,)@@ -145,6 +146,8 @@ class PendingFollowup:# Signal context carried verbatim (e.g. actor_slack_user_id for reply# tagging); consumers validate the keys they read.context: dict[str, Any] = field(default_factory=dict)+ steer: bool = False+ sequence: int = 0@dataclass@@ -188,6 +191,9 @@ from products.tasks.backend.temporal.constants import ( # noqa: E402MAX_CI_REPETITIONS,PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,+ SEND_STEER_SIGNAL,+ STEERING_PROTOCOL_QUERY,+ STEERING_PROTOCOL_VERSION,WARM_IDLE_TIMEOUT,)@@ -215,6 +221,11 @@ _PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT = "tasks-ci-follow-up-pr-context"# which workflow task records it. Same two-step lifecycle as above._PATCH_ID_FOLLOWUP_QUEUE = "tasks-follow-up-message-queue"+# Follow-up delivery waits synchronously for the sandbox turn to finish. Keep+# that delivery in the background so a later steer signal can reach the active+# turn, while ordinary follow-ups remain queued behind it.+_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING = "tasks-concurrent-followup-steering"+# #60923 dropped the redundant slack post that ran immediately after sandbox# provisioning — between `_get_sandbox_for_repository` and the agent-start# progress emit. Pre-rollout histories scheduled a `post_slack_update` activity@@ -275,6 +286,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._sandbox_gone: bool = Falseself._pending_followup: PendingFollowup | None = Noneself._pending_followups: list[PendingFollowup] = []+ self._next_followup_sequence: int = 0+ self._active_followup_task: asyncio.Task[None] | None = None+ self._shutting_down: bool = Falseself._pending_permission_responses: list[PendingPermissionResponse] = []self._ci_repetitions: int = 0self._last_active_time: Optional[datetime] = None@@ -324,8 +338,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._task_completedor self._sandbox_goneor self._heartbeat_received- or self._pending_followup is not None- or len(self._pending_followups) > 0+ or self._has_dispatchable_followup()or len(self._pending_permission_responses) > 0))@@ -333,6 +346,95 @@ class ProcessTaskWorkflow(PostHogWorkflow):return TaskEvent.SANDBOX_GONEreturn TaskEvent.SIGNAL_RECEIVED+ def _has_dispatchable_followup(self) -> bool:+ if self._active_followup_task is None:+ return self._pending_followup is not None or bool(self._pending_followups)+ if self._active_followup_task.done():+ return True+ return any(followup.steer for followup in self._pending_followups)++ def _pop_next_followup(self, *, steer_only: bool = False) -> PendingFollowup | None:+ if not steer_only and self._pending_followup is not None:+ followup = self._pending_followup+ self._pending_followup = None+ return followup+ for index, followup in enumerate(self._pending_followups):+ if not steer_only or followup.steer:+ return self._pending_followups.pop(index)+ return None++ def _insert_followup_in_arrival_order(self, followup: PendingFollowup) -> None:+ for index, pending in enumerate(self._pending_followups):+ if pending.sequence > followup.sequence:+ self._pending_followups.insert(index, followup)+ return+ self._pending_followups.append(followup)++ async def _dispatch_next_followup(self) -> bool:+ if self._active_followup_task is not None:+ if self._active_followup_task.done():+ task = self._active_followup_task+ self._active_followup_task = None+ await task+ return True+ followup = self._pop_next_followup(steer_only=True)+ if followup is None:+ return False+ await self._dispatch_followup(followup)+ return True++ followup = self._pop_next_followup()+ if followup is None:+ return False+ self._active_followup_task = asyncio.create_task(self._dispatch_followup(followup))+ return True++ async def _dispatch_followup(self, followup: PendingFollowup) -> None:+ self._last_active_time = workflow.now()+ self._first_user_message_received = True+ if self._should_skip_followup(followup.message, followup.artifact_ids):+ workflow.logger.warning(+ "empty_followup_skipped",+ extra={"run_id": self.context.run_id},+ )+ return+ 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,+ context=followup.context,+ steer=followup.steer,+ )+ if followup.steer and outcome == STEER_DECLINED_OUTCOME:+ self._insert_followup_in_arrival_order(+ PendingFollowup(+ message=followup.message,+ artifact_ids=followup.artifact_ids,+ actor_user_id=followup.actor_user_id,+ message_id=followup.message_id,+ context=followup.context,+ sequence=followup.sequence,+ ),+ )++ async def _finish_active_followup(self) -> None:+ self._shutting_down = True+ while True:+ if self._active_followup_task is not None:+ task = self._active_followup_task+ self._active_followup_task = None+ await task++ if self._pending_followup is None and not self._pending_followups:+ return+ if not workflow.patched(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING):+ return++ followup = self._pop_next_followup()+ if followup is not None:+ await self._dispatch_followup(followup)+async def _wait_for_inactivity(self, timeout: timedelta = INACTIVITY_TIMEOUT):await workflow.sleep(timeout.total_seconds())return TaskEvent.TIMEOUT_REACHED@@ -667,42 +769,42 @@ class ProcessTaskWorkflow(PostHogWorkflow):case TaskEvent.SANDBOX_GONE:self._mark_sandbox_gone()case TaskEvent.SIGNAL_RECEIVED:- pending_followup_count = len(self._pending_followups) + (- 1 if self._pending_followup is not None else 0- )- if pending_followup_count > 0:- workflow.logger.info(- "Pending follow-up message received, sending to sandbox",- extra={- "run_id": self.context.run_id,- "pending_followup_count": pending_followup_count,- },+ if workflow.patched(_PATCH_ID_CONCURRENT_FOLLOWUP_STEERING):+ if self._has_dispatchable_followup():+ pending_followup_count = len(self._pending_followups) + (+ 1 if self._pending_followup is not None else 0+ )+ workflow.logger.info(+ "Pending follow-up message received, sending to sandbox",+ extra={+ "run_id": self.context.run_id,+ "pending_followup_count": pending_followup_count,+ },+ )+ if await self._dispatch_next_followup():+ continue+ else:+ pending_followup_count = len(self._pending_followups) + (+ 1 if self._pending_followup is not None else 0)- if self._pending_followup is not None:+ if pending_followup_count == 0:+ pending_followup = None+ elif self._pending_followup is not None:pending_followup = self._pending_followupself._pending_followup = Noneelse:pending_followup = self._pending_followups.pop(0)- self._last_active_time = workflow.now()- self._first_user_message_received = True- message = pending_followup.message- artifact_ids = pending_followup.artifact_ids- if self._should_skip_followup(message, artifact_ids):- workflow.logger.warning(- "empty_followup_skipped",- extra={"run_id": self.context.run_id},+ if pending_followup is not None:+ workflow.logger.info(+ "Pending follow-up message received, sending to sandbox",+ extra={+ "run_id": self.context.run_id,+ "pending_followup_count": pending_followup_count,+ },)+ await self._dispatch_followup(pending_followup)continue- await self._send_followup_to_sandbox(- message=message,- artifact_ids=artifact_ids,- actor_user_id=pending_followup.actor_user_id,- message_id=pending_followup.message_id,- context=pending_followup.context,- )- continue-if self._heartbeat_received and not self._task_completed:workflow.logger.info("Heartbeat received, resetting inactivity timer",@@ -715,6 +817,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):# Cancel background loops as soon as the run ends, not just in `finally` —# a hang in the cleanup path below must not leave credential refresh running.+ await self._finish_active_followup()if relay_task is not None:await self._cancel_relay(relay_task)if credential_refresh_task is not None:@@ -842,6 +945,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):# Skip teardown on a continue_as_new hand-off (a `return` here would swallow the# ContinueAsNewError); the loops are already stopped and the sandbox lives on.if not continuing_as_new:+ if self._active_followup_task is not None:+ await self._cancel_relay(self._active_followup_task)+ self._active_followup_task = Noneif credential_refresh_task is not None:await self._cancel_relay(credential_refresh_task)if permission_response_task is not None:@@ -1820,17 +1926,55 @@ class ProcessTaskWorkflow(PostHogWorkflow):self,message: str | None = None,artifact_ids: Optional[list[str]] = None,- message_id: Optional[str] = None,+ message_id: str | bool | None = None,actor_user_id: Optional[int] = None,message_context: Optional[dict[str, Any]] = None,) -> None:- # The handler declares the full positional arg list even though only- # ``message`` and ``artifact_ids`` are read here. Temporal passes every- # positional arg a caller sends to the handler, and a handler that- # declares fewer params than were sent raises and fails the workflow- # task — so the arity must stay a superset of every caller's. Widening it- # here, ahead of any caller that populates the extra fields, lets this- # handler roll out to all workers before those callers ship.+ # The third positional field is a message ID for current senders, but+ # replayed steering histories may contain a boolean in that slot.+ 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_followup_message(+ message,+ artifact_ids,+ actor_user_id=actor_user_id,+ message_id=stable_message_id,+ message_context=message_context,+ steer=legacy_steer,+ )++ @temporalio.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_followup_message(+ message,+ artifact_ids,+ actor_user_id=actor_user_id,+ message_id=message_id,+ message_context=message_context,+ steer=True,+ )++ @temporalio.workflow.query(name=STEERING_PROTOCOL_QUERY)+ def steering_protocol_version(self) -> int:+ return STEERING_PROTOCOL_VERSION++ def _queue_followup_message(+ 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:# Log signal arrival so we can correlate it with the adapter's "begin dispatch"# log below — gaps between the two point at workflow-loop backpressure.context = self._context@@ -1842,13 +1986,22 @@ class ProcessTaskWorkflow(PostHogWorkflow):"artifact_count": len(artifact_ids or []),},)+ if self._shutting_down:+ workflow.logger.warning(+ "send_followup_signal_rejected_closing",+ extra={"run_id": context.run_id if context is not None else None},+ )+ returnpending_followup = PendingFollowup(message=message,artifact_ids=artifact_ids or [],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# Always queue. `deprecate_patch` accepts existing non-deprecated# markers from workflows that ran the prior `workflow.patched(...)`# gate, so this is safe to deploy alongside in-flight workflows. The@@ -1910,7 +2063,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):actor_user_id: int | None = None,message_id: str | None = None,context: dict[str, Any] | None = None,- ) -> None:+ *,+ steer: bool = False,+ ) -> str | None:workflow.logger.info("send_followup_dispatch_begin",extra={@@ -1920,7 +2075,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):},)try:- await workflow.execute_activity(+ return await workflow.execute_activity(send_followup_to_sandbox,SendFollowupToSandboxInput(run_id=self.context.run_id,@@ -1930,6 +2085,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):message_id=message_id or str(workflow.uuid4()),actor_user_id=actor_user_id,context=context,+ steer=steer,),start_to_close_timeout=timedelta(minutes=35),# The activity heartbeats while blocked on the sync delivery@@ -1960,3 +2116,4 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._completion_error = f"Follow-up delivery failed: {cause_message or e}"self._completion_error_type = "followup_delivery_failed"self._task_completed = True+ return None