:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): queue cloud task follow-up messages (#57836)
Alessandro Pogliaghi2869fb954fb3
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.pyindex 351e2ae0f59c..2ee8aafb6342 100644--- a/products/tasks/backend/api.py+++ b/products/tasks/backend/api.py@@ -117,6 +117,7 @@ from .temporal.client import (execute_posthog_code_agent_relay_workflow,execute_task_processing_workflow,resume_task_in_cloud_workflow,+ signal_task_followup_message,)from .temporal.process_task.utils import (PrAuthorshipMode,@@ -1911,9 +1912,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):404: OpenApiResponse(description="Task run not found"),502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),},- summary="Send command to agent server",- description="Forward a JSON-RPC command to the agent server running in the sandbox. "- "Supports user_message, cancel, close, permission_response, and set_config_option commands.",+ summary="Send command to task run",+ description="Queue user_message JSON-RPC commands through the task workflow and forward sandbox control "+ "commands to the agent server. Supports user_message, cancel, close, permission_response, "+ "and set_config_option commands.",strict_request_validation=True,)@action(@@ -1924,6 +1926,45 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)def command(self, request, pk=None, **kwargs):task_run = cast(TaskRun, self.get_object())+ method = request.validated_data["method"]+ request_id = request.validated_data.get("id")+ params = request.validated_data.get("params")++ if method == "user_message":+ command_params = dict(params or {})+ artifact_ids = command_params.pop("artifact_ids", [])+ if artifact_ids:+ _, missing_artifact_ids = get_task_run_artifacts_by_id(task_run, artifact_ids)+ if missing_artifact_ids:+ return Response(+ {+ "error": "Some artifact_ids are invalid for this run",+ "missing_artifact_ids": missing_artifact_ids,+ },+ status=status.HTTP_400_BAD_REQUEST,+ )++ try:+ signal_task_followup_message(+ task_run.workflow_id,+ command_params.get("content"),+ artifact_ids,+ )+ except Exception:+ logger.exception("Failed to signal follow-up message for task run %s", task_run.id)+ return Response(+ TaskRunErrorResponseSerializer({"error": "Failed to queue user message for task run"}).data,+ status=status.HTTP_502_BAD_GATEWAY,+ )++ response_payload: dict[str, Any] = {+ "jsonrpc": request.validated_data["jsonrpc"],+ "result": {"queued": True},+ }+ if request_id is not None:+ response_payload["id"] = request_id+ return Response(TaskRunCommandResponseSerializer(response_payload).data)+run_state = parse_run_state(task_run.state)if not run_state.sandbox_url:@@ -1947,28 +1988,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):command_payload: dict = {"jsonrpc": request.validated_data["jsonrpc"],- "method": request.validated_data["method"],+ "method": method,}- params = request.validated_data.get("params")if params:command_params = dict(params)- if request.validated_data["method"] == "user_message":- artifact_ids = command_params.pop("artifact_ids", [])- if artifact_ids:- resolved_artifacts, missing_artifact_ids = get_task_run_artifacts_by_id(task_run, artifact_ids)- if missing_artifact_ids:- return Response(- {- "error": "Some artifact_ids are invalid for this run",- "missing_artifact_ids": missing_artifact_ids,- },- status=status.HTTP_400_BAD_REQUEST,- )- command_params["artifacts"] = resolved_artifactsif command_params:command_payload["params"] = command_params- if "id" in request.validated_data and request.validated_data["id"] is not None:- command_payload["id"] = request.validated_data["id"]+ if request_id is not None:+ command_payload["id"] = request_idtry:agent_response = self._proxy_command_to_agent_server(diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex ef32b98dca93..1f78f67d6c69 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -260,6 +260,12 @@ def resume_task_in_cloud_workflow(run_id: str, workflow_id: str) -> None:)+def signal_task_followup_message(workflow_id: str, message: str | None, artifact_ids: list[str]) -> None:+ client = sync_connect()+ handle = client.get_workflow_handle(workflow_id)+ asyncio.run(handle.signal("send_followup_message", args=[message, artifact_ids]))++def execute_posthog_code_agent_relay_workflow(run_id: str,text: str,diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 727498af263b..23ee9ac70048 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -6,7 +6,7 @@ from concurrent.futures import ThreadPoolExecutorfrom datetime import timedeltaimport pytest-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, Mockfrom django.conf import settings@@ -39,6 +39,7 @@ from products.tasks.backend.temporal.process_task.activities import (update_task_run_status,)from products.tasks.backend.temporal.process_task.workflow import (+ PendingFollowup,ProcessTaskInput,ProcessTaskOutput,ProcessTaskWorkflow,@@ -274,6 +275,46 @@ class TestProcessTaskWorkflow:@pytest.mark.django_dbclass TestProcessTaskWorkflowUnit:+ async def test_send_followup_message_can_arrive_before_context_is_loaded(self, monkeypatch):+ logger = Mock()+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", logger)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ workflow = ProcessTaskWorkflow()++ await workflow.send_followup_message("first", ["artifact-1"])+ await workflow.send_followup_message("second", ["artifact-2"])++ assert workflow._pending_followups == [+ PendingFollowup(message="first", artifact_ids=["artifact-1"]),+ PendingFollowup(message="second", artifact_ids=["artifact-2"]),+ ]+ logger.info.assert_any_call(+ "send_followup_signal_received",+ run_id=None,+ message_length=5,+ artifact_count=1,+ )+ logger.info.assert_any_call(+ "send_followup_signal_received",+ run_id=None,+ message_length=6,+ artifact_count=1,+ )+ assert logger.info.call_count == 2++ async def test_send_followup_message_preserves_legacy_single_slot_before_patch(self, monkeypatch):+ logger = Mock()+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", logger)+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=False))+ workflow = ProcessTaskWorkflow()++ await workflow.send_followup_message("first", ["artifact-1"])+ await workflow.send_followup_message("second", ["artifact-2"])++ assert workflow._pending_followup == PendingFollowup(message="second", artifact_ids=["artifact-2"])+ assert workflow._pending_followups == []+ assert logger.info.call_count == 2+@pytest.mark.parametrize("state, expected",[diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex b4f7c3088d3d..c7d432b5aa2b 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -59,6 +59,12 @@ class ProcessTaskInput:posthog_mcp_scopes: PosthogMcpScopes = "read_only"+@dataclass+class PendingFollowup:+ message: str | None+ artifact_ids: list[str]++@dataclassclass ProcessTaskOutput:success: bool@@ -125,6 +131,7 @@ After fixing, commit and push so CI can re-run.# 2. Second cleanup PR (after another full drain): delete this helper and# `_PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT`._PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT = "tasks-ci-follow-up-pr-context"+_PATCH_ID_FOLLOWUP_QUEUE = "tasks-follow-up-message-queue"def _deprecate_ci_follow_up_pr_context_patch() -> None:@@ -142,7 +149,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._completion_status: str = "completed"self._completion_error: Optional[str] = Noneself._heartbeat_received: bool = False- self._pending_followup: Optional[dict[str, Any]] = None+ self._pending_followup: PendingFollowup | None = None+ self._pending_followups: list[PendingFollowup] = []self._ci_repetitions: int = 0self._last_active_time: Optional[datetime] = None# Tracks which progress step is currently in-progress (step, label,@@ -198,7 +206,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):async def _wait_for_task_external_event(self):await workflow.wait_condition(- lambda: self._task_completed or self._heartbeat_received or self._pending_followup is not None+ lambda: self._task_completed+ or self._heartbeat_received+ or self._pending_followup is not None+ or len(self._pending_followups) > 0)return TaskEvent.SIGNAL_RECEIVED@@ -427,15 +438,23 @@ class ProcessTaskWorkflow(PostHogWorkflow):case _:raise ValueError(f"Unknown CIFollowUpDecision: {follow_up_result}")case TaskEvent.SIGNAL_RECEIVED:- if self._pending_followup is not None:+ 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", run_id=self.context.run_id+ "Pending follow-up message received, sending to sandbox",+ run_id=self.context.run_id,+ pending_followup_count=pending_followup_count,)- pending_followup = self._pending_followup- self._pending_followup = None+ if self._pending_followup is not None:+ pending_followup = self._pending_followup+ self._pending_followup = None+ else:+ pending_followup = self._pending_followups.pop(0)self._last_active_time = workflow.now()- message = pending_followup.get("message")- artifact_ids = pending_followup.get("artifact_ids") or []+ message = pending_followup.message+ artifact_ids = pending_followup.artifact_idsif self._should_skip_followup(message, artifact_ids):workflow.logger.warning("empty_followup_skipped",@@ -903,16 +922,18 @@ class ProcessTaskWorkflow(PostHogWorkflow):async def send_followup_message(self, message: str | None = None, artifact_ids: Optional[list[str]] = None) -> 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._contextworkflow.logger.info("send_followup_signal_received",- run_id=self.context.run_id,+ run_id=context.run_id if context is not None else None,message_length=len(message or ""),artifact_count=len(artifact_ids or []),)- self._pending_followup = {- "message": message,- "artifact_ids": artifact_ids or [],- }+ pending_followup = PendingFollowup(message=message, artifact_ids=artifact_ids or [])+ if workflow.patched(_PATCH_ID_FOLLOWUP_QUEUE):+ self._pending_followups.append(pending_followup)+ else:+ self._pending_followup = pending_followupasync def _send_followup_to_sandbox(self, message: str | None, artifact_ids: list[str]) -> None:workflow.logger.info(diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 30e0657c7af7..7f2c84755f95 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -4923,6 +4923,9 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):"id": request_id,}+ def _make_cancel(self, request_id="req-cancel"):+ return {"jsonrpc": "2.0", "method": "cancel", "id": request_id}+def _create_run_with_sandbox(self, task, sandbox_url="http://localhost:9999", connect_token=None):state = {"sandbox_url": sandbox_url, "mode": "interactive"}if connect_token:@@ -4942,19 +4945,8 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):mock_resp.text = json.dumps(body) if isinstance(body, dict) else str(body)mock_post.return_value = mock_resp- @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)- @patch("products.tasks.backend.api.http_requests.post")- def test_command_proxies_user_message(self, mock_post):- get_sandbox_jwt_public_key.cache_clear()- self._mock_agent_response(- mock_post,- {- "jsonrpc": "2.0",- "id": "req-1",- "result": {"stopReason": "end_turn"},- },- )-+ @patch("products.tasks.backend.api.signal_task_followup_message")+ def test_command_signals_user_message(self, mock_signal_followup):task = self.create_task()run = self._create_run_with_sandbox(task)@@ -4967,27 +4959,32 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()self.assertEqual(data["jsonrpc"], "2.0")- self.assertEqual(data["result"]["stopReason"], "end_turn")+ self.assertTrue(data["result"]["queued"])- mock_post.assert_called_once()- call_kwargs = mock_post.call_args- self.assertEqual(call_kwargs[1]["json"]["method"], "user_message")- self.assertEqual(call_kwargs[1]["json"]["params"]["content"], "Hello agent")- self.assertIn("Bearer ", call_kwargs[1]["headers"]["Authorization"])+ mock_signal_followup.assert_called_once_with(run.workflow_id, "Hello agent", [])- @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)- @patch("products.tasks.backend.api.http_requests.post")- def test_command_resolves_artifact_ids(self, mock_post):- get_sandbox_jwt_public_key.cache_clear()- self._mock_agent_response(- mock_post,- {- "jsonrpc": "2.0",- "id": "req-attachments",- "result": {"stopReason": "end_turn"},- },+ @patch("products.tasks.backend.api.signal_task_followup_message")+ def test_command_signals_user_message_without_active_sandbox(self, mock_signal_followup):+ task = self.create_task()+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.QUEUED,+ state={},+ )++ response = self.client.post(+ self._command_url(task, run),+ self._make_user_message(),+ format="json",)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json()["result"]["queued"])+ mock_signal_followup.assert_called_once_with(run.workflow_id, "Hello agent", [])++ @patch("products.tasks.backend.api.signal_task_followup_message")+ def test_command_signals_user_message_artifact_ids(self, mock_signal_followup):task = self.create_task()run = self._create_run_with_sandbox(task)artifact = {@@ -5015,10 +5012,23 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- sent_params = mock_post.call_args[1]["json"]["params"]- self.assertEqual(sent_params["content"], "See attached")- self.assertEqual(sent_params["artifacts"], [artifact])- self.assertNotIn("artifact_ids", sent_params)+ self.assertTrue(response.json()["result"]["queued"])+ mock_signal_followup.assert_called_once_with(run.workflow_id, "See attached", ["artifact-123"])++ @patch("products.tasks.backend.api.signal_task_followup_message")+ def test_command_returns_502_when_user_message_signal_fails(self, mock_signal_followup):+ mock_signal_followup.side_effect = RuntimeError("temporal unavailable")+ task = self.create_task()+ run = self._create_run_with_sandbox(task)++ response = self.client.post(+ self._command_url(task, run),+ self._make_user_message(),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)+ self.assertEqual(response.json()["error"], "Failed to queue user message for task run")@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)@patch("products.tasks.backend.api.http_requests.post")@@ -5162,7 +5172,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5229,7 +5239,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5249,7 +5259,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5268,7 +5278,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5286,7 +5296,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5308,7 +5318,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5330,7 +5340,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5348,7 +5358,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5380,7 +5390,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5438,7 +5448,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5475,7 +5485,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5518,7 +5528,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5549,7 +5559,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5565,7 +5575,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)@@ -5602,7 +5612,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):response = self.client.post(self._command_url(task, run),- self._make_user_message(),+ self._make_cancel(),format="json",)diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 183032add74c..6f07c0b14fa2 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -635,8 +635,8 @@ export const tasksRunsArtifactsPresignCreate = async (}/**- * Forward a JSON-RPC command to the agent server running in the sandbox. Supports user_message, cancel, close, permission_response, and set_config_option commands.- * @summary Send command to agent server+ * Queue user_message JSON-RPC commands through the task workflow and forward sandbox control commands to the agent server. Supports user_message, cancel, close, permission_response, and set_config_option commands.+ * @summary Send command to task run*/export const getTasksRunsCommandCreateUrl = (projectId: string, taskId: string, id: string) => {return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/command/`diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex fd1cc21a892f..eb586f1bb26a 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -843,8 +843,8 @@ export const TasksRunsArtifactsPresignCreateBody = /* @__PURE__ */ zod.object({})/**- * Forward a JSON-RPC command to the agent server running in the sandbox. Supports user_message, cancel, close, permission_response, and set_config_option commands.- * @summary Send command to agent server+ * Queue user_message JSON-RPC commands through the task workflow and forward sandbox control commands to the agent server. Supports user_message, cancel, close, permission_response, and set_config_option commands.+ * @summary Send command to task run*/export const TasksRunsCommandCreateBody = /* @__PURE__ */ zod.object({