: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)!: expose the created run on POST /run/ and return sandbox_not_ready as a retryable 503 (#107856)
Tom Owers883d3b668f6e
diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.tsindex 76d66f2a535d..f5c63125d41c 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts@@ -369,64 +369,67 @@ describe("CloudPiSessionClient", () => {expect(cloud.client.sendCommand).toHaveBeenCalledOnce();});- it("retries a sandbox command after a resumed sandbox starts", async () => {- const cloud = createCloudTaskClient();- let liveRuntimeStarted = false;- vi.mocked(cloud.client.sendCommand)- .mockResolvedValueOnce({- success: false,- status: 400,- code: "sandbox_not_ready",- error: "No active sandbox for this task run",- })- .mockImplementationOnce(async () => {- if (!liveRuntimeStarted) {- throw new Error("Sandbox command retried before Pi started");- }- return {- success: true,- result: {- type: "response",- command: "get_state",+ it.each([400, 503])(+ "retries a sandbox command after a resumed sandbox starts (%i)",+ async (status) => {+ const cloud = createCloudTaskClient();+ let liveRuntimeStarted = false;+ vi.mocked(cloud.client.sendCommand)+ .mockResolvedValueOnce({+ success: false,+ status,+ code: "sandbox_not_ready",+ error: "No active sandbox for this task run",+ })+ .mockImplementationOnce(async () => {+ if (!liveRuntimeStarted) {+ throw new Error("Sandbox command retried before Pi started");+ }+ return {success: true,- data: { isStreaming: false },- },- };- });- const session = new CloudPiSessionClient(- cloud.client,- context("in_progress"),- );- session.onConversationEvent(vi.fn(), vi.fn());+ result: {+ type: "response",+ command: "get_state",+ success: true,+ data: { isStreaming: false },+ },+ };+ });+ const session = new CloudPiSessionClient(+ cloud.client,+ context("in_progress"),+ );+ session.onConversationEvent(vi.fn(), vi.fn());- const state = session.client.getState();- cloud.sendUpdate({- taskId: "task-1",- runId: "run-1",- kind: "snapshot",- status: "in_progress",- newEntries: [{ type: "pi_run_started" }],- totalEntryCount: 1,- });+ const state = session.client.getState();+ cloud.sendUpdate({+ taskId: "task-1",+ runId: "run-1",+ kind: "snapshot",+ status: "in_progress",+ newEntries: [{ type: "pi_run_started" }],+ totalEntryCount: 1,+ });- await vi.waitFor(() =>- expect(cloud.client.sendCommand).toHaveBeenCalledOnce(),- );+ await vi.waitFor(() =>+ expect(cloud.client.sendCommand).toHaveBeenCalledOnce(),+ );- liveRuntimeStarted = true;- cloud.sendUpdate({- taskId: "task-1",- runId: "run-1",- kind: "logs",- newEntries: [{ type: "pi_run_started" }],- totalEntryCount: 2,- });+ liveRuntimeStarted = true;+ cloud.sendUpdate({+ taskId: "task-1",+ runId: "run-1",+ kind: "logs",+ newEntries: [{ type: "pi_run_started" }],+ totalEntryCount: 2,+ });- await expect(state).resolves.toMatchObject({ isStreaming: false });- expect(cloud.client.sendCommand).toHaveBeenCalledTimes(2);- const commandCalls = vi.mocked(cloud.client.sendCommand).mock.calls;- expect(commandCalls[1][0].id).toBe(commandCalls[0][0].id);- });+ await expect(state).resolves.toMatchObject({ isStreaming: false });+ expect(cloud.client.sendCommand).toHaveBeenCalledTimes(2);+ const commandCalls = vi.mocked(cloud.client.sendCommand).mock.calls;+ expect(commandCalls[1][0].id).toBe(commandCalls[0][0].id);+ },+ );it("does not fail while a sandbox takes longer than 30 seconds to boot", async () => {vi.useFakeTimers();diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.tsindex 6ee4f68fad23..8ff528eccaaa 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts@@ -129,9 +129,11 @@ function isCompletedCompaction(event: AgentConversationEvent): boolean {}function isNoActiveSandboxError(result: SendCommandOutput): boolean {+ // The server used to word this as a 400; it is a 503 now that the condition+ // is documented as transient. Accept both so either side can deploy first.return (result.success === false &&- result.status === 400 &&+ (result.status === 400 || result.status === 503) &&(result.code === "sandbox_not_ready" ||result.error === "No active sandbox for this task run"));diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 600a0eef046b..9d08e9e7452a 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -207,7 +207,7 @@ describe('runInteractionLogic', () => {jest.clearAllMocks()localStorage.clear();(tasksRunsCommandCreate as jest.Mock).mockResolvedValue({ jsonrpc: '2.0', result: { queued: true } })- ;(tasksRunCreate as jest.Mock).mockResolvedValue({ latest_run: { id: 'run-2' } })+ ;(tasksRunCreate as jest.Mock).mockResolvedValue({ run: { id: 'run-2' }, latest_run: { id: 'run-2' } });(tasksRunsClearConversationCreate as jest.Mock).mockResolvedValue({});(tasksWarmResumeCreate as jest.Mock).mockResolvedValue({ task_id: TASK_ID, run_id: 'warm-run' })initKeaTests()diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 4f96345542d8..79382aca0cc9 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -1534,7 +1534,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// Same endpoint as the "Run again" button, but seeded with the user's message and chained// from the finished run so the new run continues the thread, and carrying the picked model /// reasoning effort (the resume schema can't, so we send the Claude create shape). The response- // carries the new run id as `latest_run`; the consumer-provided `onRunStarted` re-points to it.+ // carries the new run as `run`; the consumer-provided `onRunStarted` re-points to it.const createRequest = buildRunCreateRequest(values.catalogue,values.selectedModel,@@ -1582,8 +1582,9 @@ export const runInteractionLogic = kea<runInteractionLogicType>([if (!isCurrent()) {return}- getWarmLogic()?.actions.consumeWarm(warmSubmission, result.latest_run?.id ?? null)- const run = result.latest_run+ // `?? latest_run` covers the deploy skew window where this bundle outruns the backend.+ const run = result.run ?? result.latest_run+ getWarmLogic()?.actions.consumeWarm(warmSubmission, run?.id ?? null)if (!run?.id) {throw new Error('The run response did not include a run')}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex fee648e75246..f46c8932fe21 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -869,7 +869,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([),disposables)- createdRun = runResponse.latest_run+ // `?? latest_run` covers the deploy skew window where this bundle outruns the backend.+ createdRun = runResponse.run ?? runResponse.latest_runrunId = createdRun?.id}diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex 58a47b848404..ff3d8b320ad0 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -307,7 +307,8 @@ async function createReportTask((options) => tasksRunCreate(projectId, task.id, runOptions, options),disposables)- run = running.latest_run ?? null+ // `?? latest_run` covers the deploy skew window where this bundle outruns the backend.+ run = running.run ?? running.latest_run ?? null}if (!run) {throw new Error('The task has no run. Open the task list to check its status.')diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 5d0601509a78..98626f226a54 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -5308,7 +5308,9 @@ def get_task_run_sandbox_connection(run_state = parse_run_state(run.state)if not run_state.sandbox_url:- return contracts.TaskRunSandboxConnectionDTO(sandbox_url=None, sandbox_connect_token=None)+ return contracts.TaskRunSandboxConnectionDTO(+ sandbox_url=None, sandbox_connect_token=None, run_is_terminal=run.is_terminal+ )from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415 — keep sandbox deps off the api import pathsandbox_transport_token,@@ -5321,6 +5323,7 @@ def get_task_run_sandbox_connection(sandbox_connect_token=transport_token,connection_token=connection_token,sandbox_token_param=token_param,+ run_is_terminal=run.is_terminal,)@@ -8753,7 +8756,7 @@ def run_task(reasoning_effort=validated_data.get("reasoning_effort"),retry_token=warm_retry_token,)- return contracts.TaskRunResult(task=get_task_detail(task.id, team_id, user_id))+ return contracts.TaskRunResult(task=get_task_detail(task.id, team_id, user_id), run_id=warm_run.id)if warm_retry_token is not None:raise WarmRunActivationUnavailable("target_unavailable")sandbox_environment_id = validated_data.get("sandbox_environment_id")@@ -9064,7 +9067,8 @@ def run_task(if scheduled_at is not None:return contracts.TaskRunResult(- task=_task_detail_to_dto(task, latest_run=task_run, include_latest_run_log_url=False)+ task=_task_detail_to_dto(task, latest_run=task_run, include_latest_run_log_url=False),+ run_id=task_run.id,)logger.info("Triggering workflow for task %s, run %s", task.id, task_run.id)@@ -9092,7 +9096,7 @@ def run_task(except Exception:logger.exception("Failed to hydrate task %s after starting run %s", task.id, task_run.id)task_detail = _task_detail_to_dto(task, latest_run=task_run, include_latest_run_log_url=False)- return contracts.TaskRunResult(task=task_detail, run_error=run_error)+ return contracts.TaskRunResult(task=task_detail, run_error=run_error, run_id=task_run.id)# --- Task presence beacons ---diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 780aa9f9ebad..5562e7ebccab 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -240,6 +240,19 @@ class TaskCreateResponseDTO(TaskDetailDTO):run_error: str | None = None+@dataclass(frozen=True)+class TaskRunResponseDTO(TaskCreateResponseDTO):+ """The task ``run`` action's response: the refreshed task detail plus the run this call made.++ ``run`` is the run the call created or activated — the payload a caller reads run-scoped ids+ from, instead of inferring them from ``latest_run`` (or, worse, the top-level task ``id``).+ Set on every 200; when ``run_error`` is also set, the run exists but its workflow did not+ start.+ """++ run: "TaskRunDetailDTO | None" = None++@dataclass(frozen=True)class ChannelDTO:"""The HTTP representation of a task channel."""@@ -467,11 +480,14 @@ class TaskRunResult:Exactly one of ``task`` / ``error`` is set. ``task`` is the refreshed task detail DTO withits new latest run; ``error`` carries the structured error the original view returned inline.+ ``run_id`` names the run this call created or activated, so the view does not have to infer+ it from ``task.latest_run`` (which a concurrent run creation can race past)."""task: "TaskDetailDTO | None" = Noneerror: TaskValidationError | None = Nonerun_error: str | None = None+ run_id: UUID | None = None@dataclass(frozen=True)@@ -682,6 +698,8 @@ class TaskRunSandboxConnectionDTO:Carries the sandbox URL and connect token parsed off the run state plus a freshly-mintedconnection token. ``sandbox_url`` is ``None`` when the run has no active sandbox.+ ``run_is_terminal`` disambiguates that case: a terminal run's sandbox is cleaned up and+ never comes back, while a non-terminal run's sandbox may simply not be reachable yet."""sandbox_url: str | None@@ -689,6 +707,7 @@ class TaskRunSandboxConnectionDTO:connection_token: str | None = None# Query-param name the transport token travels under (provider-specific).sandbox_token_param: str = "_modal_connect_token"+ run_is_terminal: bool = FalseSPACE_SETUP_SCOPES = (diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex b1550a09ea68..afca412e23df 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -47,6 +47,7 @@ from products.tasks.backend.facade.contracts import (TaskDetailDTO,TaskMentionDTO,TaskRunDetailDTO,+ TaskRunResponseDTO,TaskSummaryDTO,TaskThreadMessageDTO,TaskUserBasicInfo,@@ -664,7 +665,27 @@ class TaskCreateResponseSerializer(TaskSerializer):@extend_schema_serializer(component_name="TaskRunResponse")class TaskRunResponseSerializer(TaskCreateResponseSerializer):+ """The task ``run`` action's response: the refreshed task detail plus the run this call made.++ ``run`` is the run the call created or activated — the payload a caller reads run-scoped ids+ from, instead of inferring them from ``latest_run`` (or, worse, the top-level task ``id``).+ """+run_error = serializers.CharField(required=False, help_text="Error returned when the run could not start.")+ run = TaskRunDetailSerializer(+ allow_null=True,+ required=False,+ help_text=(+ "The run this call created or activated. Read run-scoped ids from here — `run.id` is "+ "the id the run's stream and command endpoints take, while the top-level `id` is the "+ "task's. Set on every 200; when `run_error` is also set, the run exists but its "+ "workflow did not start."+ ),+ )++ class Meta(TaskCreateResponseSerializer.Meta):+ dataclass = TaskRunResponseDTO+ fields = [*TaskCreateResponseSerializer.Meta.fields, "run"]TASK_DESCRIPTION_PREVIEW_LENGTH = 1000diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 0dbc43830c5e..0a8e45c298cb 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -1280,7 +1280,10 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@validated_request(request_serializer=TaskRunCreateRequestSerializer,responses={- 200: OpenApiResponse(response=TaskRunResponseSerializer, description="Task with updated latest run"),+ 200: OpenApiResponse(+ response=TaskRunResponseSerializer,+ description="The refreshed task, plus the created run under the top-level `run` key",+ ),400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),402: OpenApiResponse(response=TaskRunErrorResponseSerializer,@@ -1312,10 +1315,11 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):},summary="Run task",description=(- "Create a new task run and kick off the workflow. **Responds with the task, not the "- "run**: the new run is nested under `latest_run`, and the top-level `id` is still the "- "task's. Read `latest_run.id` for anything run-scoped, such as the run's stream and "- "command endpoints."+ "Create a new task run and kick off the workflow. The response is the refreshed task "+ "with the created run under the top-level `run` key: read `run.id` for anything "+ "run-scoped, such as the run's stream and command endpoints. The top-level `id` is "+ "the task's, and `latest_run` mirrors `run` only as long as nothing newer starts — "+ "reading either of those as the created run is deprecated."),include_serializer_context=True,)@@ -1383,8 +1387,24 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):response_data = TaskSerializer(result.task).dataif result.run_error:response_data["run_error"] = result.run_error+ response_data["run"] = self._created_run_payload(result, response_data, task_id=pk)return Response(response_data)+ def _created_run_payload(self, result, response_data: dict, *, task_id) -> dict | None:+ """The run the ``run`` action created or activated, as a serialized run detail.++ Usually this is exactly the refreshed task's ``latest_run``, so reuse that payload+ (including its inherited-PR backfill). A concurrent run creation can race past it, in+ which case the run named by the facade is fetched directly.+ """+ if result.run_id is None:+ return None+ latest_run = response_data.get("latest_run")+ if latest_run and str(latest_run.get("id")) == str(result.run_id):+ return latest_run+ run = tasks_facade.get_task_run_detail(result.run_id, task_id, self.team_id, user_id=self._user_id())+ return TaskRunDetailSerializer(run).data if run is not None else None+def _agent_run_enabled(self, request) -> bool:return _agent_run_enabled(request, self.team)@@ -3127,12 +3147,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):),400: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description=(- "Invalid command, or no active sandbox. Code `sandbox_not_ready` is transient "- "rather than a refusal — the run exists but its agent server is still starting, "- "which is the usual answer to a command sent as soon as the run asks for one. "- "Retry it until the request you are answering expires. Every other 400 is fatal."- ),+ description="Invalid command — fatal, do not retry. (Legacy exception: interactive PostHog "+ "Desktop grants still receive the transient `sandbox_not_ready` condition as a 400 for every "+ "method except `credential_response`, because shipped Desktop builds branch on that status; "+ "API callers always get it as a 503.)",),403: OpenApiResponse(response=TaskRunErrorResponseSerializer,@@ -3141,7 +3159,9 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):404: OpenApiResponse(description="Task run not found"),409: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description="Task run workflow has ended; permission_target_ended for an ended approval target",+ description="Final, do not retry. Task run workflow has ended; `permission_target_ended` for an "+ "ended approval target; `run_ended` when the run is completed, failed, or cancelled and its "+ "sandbox is cleaned up — unlike `sandbox_not_ready`, nothing will ever come up",),429: OpenApiResponse(response=TaskRunErrorResponseSerializer,@@ -3150,17 +3170,24 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),503: OpenApiResponse(response=TaskRunErrorResponseSerializer,- description="agent_session_not_ready: approval rejected before execution while the agent starts; "- "or PostHog Desktop access could not be verified",+ description="Transient, retry after `Retry-After` until the request you are answering expires. "+ "Code `sandbox_not_ready`: the run is still live but its sandbox's command channel is not "+ "reachable yet — the usual answer to a command sent as soon as the run asks for one, such as a "+ "credential_response (a 409 `run_ended` ends that loop). Code `agent_session_not_ready`: approval "+ "rejected before execution while the agent starts. Or PostHog Desktop access could not be verified.",),},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, ""set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. "- "Permission responses return 503 agent_session_not_ready only when rejected before execution; "- "clients may retry that code within a bounded startup wait. HTTP 200 preserves JSON-RPC errors; "- "permission acceptance requires result.resolved=true.",+ "Retry loop: a 503 is transient (sandbox_not_ready means the command arrived before the live "+ "run's command channel came up; agent_session_not_ready means an approval was rejected before "+ "execution while the agent starts) — retry it until the request you are answering expires. "+ "A 502 (agent server unreachable) or 504 (agent server timed out) means delivery is unknown; "+ "retry only when the command method is safe to retry. A 409 run_ended is final: the run is over "+ "and its sandbox is gone. "+ "HTTP 200 preserves JSON-RPC errors; permission acceptance requires result.resolved=true.",strict_request_validation=True,)@action(@@ -3355,15 +3382,45 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)if not connection.sandbox_url:+ if connection.run_is_terminal:+ # A completed, failed, or cancelled run's sandbox is cleaned up and never comes+ # back, so this refusal must be final — a retryable status here would tell a+ # client to poll a dead run until its own deadline. 409 matches this endpoint's+ # other "the run is over" refusals; the distinct code lets a client tell "stop"+ # from the transient `sandbox_not_ready` below.+ return Response(+ TaskRunErrorResponseSerializer(+ {"code": "run_ended", "error": "This task run has ended and its sandbox is gone"}+ ).data,+ status=status.HTTP_409_CONFLICT,+ )+ not_ready_body = TaskRunErrorResponseSerializer(+ {+ "type": "runtime_unavailable",+ "code": "sandbox_not_ready",+ "error": "No active sandbox for this task run",+ }+ ).data+ # Shipped PostHog Desktop builds recognise this condition only as a 400+ # (isNoActiveSandboxError gates its startup wait-and-retry on that status), so an+ # interactive Desktop grant keeps the legacy status. Current Desktop accepts either;+ # drop this carve-out once pre-503 builds age out.+ # Desktop's credential relay retries a 503 and gives up on a 400, so it gets the 503.+ if (+ method != "credential_response"+ and get_task_client_provenance(request) is tasks_facade.TaskClientProvenance.POSTHOG_DESKTOP+ ):+ return Response(not_ready_body, status=status.HTTP_400_BAD_REQUEST)+ # 503, not 400, for everyone else: the sandbox registers its command channel a+ # moment after it starts emitting events, so a command sent promptly — a+ # credential_response answering the sandbox's own credential_request being the+ # canonical case — reliably arrives here first. That is a transient server-side+ # condition, and returning it as a 400 made correctly-behaving clients (which treat+ # 4xx as fatal) give up with most of the request's expiry window still left.return Response(- TaskRunErrorResponseSerializer(- {- "type": "runtime_unavailable",- "code": "sandbox_not_ready",- "error": "No active sandbox for this task run",- }- ).data,- status=status.HTTP_400_BAD_REQUEST,+ not_ready_body,+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ headers={"Retry-After": "2"},)if not self._is_valid_sandbox_url(connection.sandbox_url):diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 50d1ced21370..03587f376f6a 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -229,6 +229,35 @@ class BaseTaskAPITest(TestCase):self.desktop_access_patcher.stop()super().tearDown()+ def _oauth_client(self, client_id: str, *, scope: str = "task:read task:write") -> APIClient:+ application = OAuthApplication.objects.create(+ name="Task API client",+ client_id=client_id,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=f"pha_task_{uuid.uuid4().hex}",+ expires=django_timezone.now() + timedelta(hours=1),+ scope=scope,+ scoped_teams=[self.team.id],+ )+ OAuthRefreshToken.objects.create(+ user=self.user,+ application=application,+ token=f"phr_task_{uuid.uuid4().hex}",+ access_token=access_token,+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ return client+def set_tasks_feature_flag(self, enabled=True):self._desktop_access_enabled = enabledif hasattr(self, "feature_flag_patcher"):@@ -1034,35 +1063,6 @@ class TestTaskVisibilityInternalDebugRegionGate(BaseTaskAPITest):class TestTaskAPI(BaseTaskAPITest):- def _oauth_client(self, client_id: str, *, scope: str = "task:read task:write") -> APIClient:- application = OAuthApplication.objects.create(- name="Task API client",- client_id=client_id,- client_type=OAuthApplication.CLIENT_PUBLIC,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- algorithm="RS256",- redirect_uris="https://example.com/callback",- organization=self.organization,- user=self.user,- )- access_token = OAuthAccessToken.objects.create(- user=self.user,- application=application,- token=f"pha_task_{uuid.uuid4().hex}",- expires=django_timezone.now() + timedelta(hours=1),- scope=scope,- scoped_teams=[self.team.id],- )- OAuthRefreshToken.objects.create(- user=self.user,- application=application,- token=f"phr_task_{uuid.uuid4().hex}",- access_token=access_token,- )- client = APIClient()- client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")- return client-@patch("products.tasks.backend.presentation.views.api.get_task_usage")def test_usage_returns_task_cost_breakdown(self, mock_get_task_usage: MagicMock) -> None:task = self.create_task()@@ -1606,6 +1606,8 @@ class TestTaskAPI(BaseTaskAPITest):assert response.status_code == (201 if combined_create else 200), response.json()assert "run_error" not in response.json()+ if not combined_create:+ assert response.json()["run"]["id"] == response.json()["latest_run"]["id"]run = TaskRun.objects.get(id=response.json()["latest_run"]["id"])assert run.status == TaskRun.Status.NOT_STARTEDassert run.queued_at is None@@ -1873,6 +1875,8 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_201_CREATED if combined_create else status.HTTP_200_OK)run = Task.objects.get(id=response.json()["id"]).runs.get()self.assertEqual(response.json()["latest_run"]["id"], str(run.id))+ if not combined_create:+ self.assertEqual(response.json()["run"]["id"], str(run.id))self.assertNotIn("run_error", response.json())mock_workflow.assert_called_once()@@ -3236,6 +3240,7 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(data["id"], str(task.id))self.assertIn("latest_run", data)self.assertIsNotNone(data["latest_run"])+ self.assertEqual(data["run"], data["latest_run"])latest_run = data["latest_run"]run_id = latest_run["id"]@@ -13800,7 +13805,65 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):format="json",)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)+ self.assertEqual(response.headers.get("Retry-After"), "2")+ self.assertEqual(+ response.json(),+ {+ "type": "runtime_unavailable",+ "code": "sandbox_not_ready",+ "error": "No active sandbox for this task run",+ },+ )++ @parameterized.expand(+ [+ ("completed", TaskRun.Status.COMPLETED),+ ("failed", TaskRun.Status.FAILED),+ ("cancelled", TaskRun.Status.CANCELLED),+ ]+ )+ def test_command_on_ended_run_without_sandbox_is_final(self, _name, run_status):+ task = self.create_task()+ run = TaskRun.objects.create(task=task, team=self.team, status=run_status, state={})++ response = self.client.post(self._command_url(task, run), self._make_cancel(), format="json")++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertIsNone(response.headers.get("Retry-After"))+ self.assertEqual(+ response.json(),+ {"code": "run_ended", "error": "This task run has ended and its sandbox is gone"},+ )++ @parameterized.expand(+ [+ ("cancel", {"jsonrpc": "2.0", "method": "cancel", "id": "req-1"}, status.HTTP_400_BAD_REQUEST),+ (+ "credential_response",+ {+ "jsonrpc": "2.0",+ "method": "credential_response",+ "params": {"requestId": "cred-1", "credential": "claude_subscription_token", "error": "no_token"},+ "id": "req-1",+ },+ status.HTTP_503_SERVICE_UNAVAILABLE,+ ),+ ]+ )+ def test_command_without_sandbox_for_desktop_grant(self, _name, body, expected_status):+ task = self.create_task()+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"claude_subscription_user_id": self.user.id},+ )++ client = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV)+ response = client.post(self._command_url(task, run), body, format="json")++ self.assertEqual(response.status_code, expected_status)self.assertEqual(response.json(),{@@ -14474,7 +14537,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):format="json",)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)self.assertIn("No active sandbox", response.json()["error"])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.pyindex b7398cecae81..86a83402a02a 100644--- a/products/tasks/backend/tests/test_warm_facade.py+++ b/products/tasks/backend/tests/test_warm_facade.py@@ -1151,6 +1151,8 @@ class TestCreateTaskWarmReuse(APIBaseTest):retry = self.client.post(url, payload, format="json", HTTP_X_POSTHOG_WARM_RETRY=retry_token)assert retry.status_code == (201 if endpoint == "create" else 200), retry.contentassert retry.json()["latest_run"]["id"] == str(run.id)+ if endpoint != "create":+ assert retry.json()["run"]["id"] == str(run.id)assert handle.signal.await_count == 3assert all(call.kwargs["args"] == first_message for call in handle.signal.await_args_list)run.refresh_from_db()@@ -1721,6 +1723,7 @@ class TestWarmTaskResumeSandbox(APIBaseTest):)assert result is not None and result.error is None+ assert result.run_id == warm_run.idassert task.runs.count() == 2signal.assert_called_once()warm_run.refresh_from_db()diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex c4ae628e18c2..6eec084c91dd 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3230,11 +3230,10 @@ export type TaskRunCreateRequestSchemaApi =export type TaskRunResponseApiJsonSchema = { [key: string]: unknown } | null/**- * Detail response for a task.+ * The task ``run`` action's response: the refreshed task detail plus the run this call made.*- * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /- * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and- * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.+ * ``run`` is the run the call created or activated — the payload a caller reads run-scoped ids+ * from, instead of inferring them from ``latest_run`` (or, worse, the top-level task ``id``).*/export interface TaskRunResponseApi {id: string@@ -3286,6 +3285,8 @@ export interface TaskRunResponseApi {origin_key?: string | null/** Error returned when the run could not start. */run_error?: string+ /** The run this call created or activated. Read run-scoped ids from here — `run.id` is the id the run's stream and command endpoints take, while the top-level `id` is the task's. Set on every 200; when `run_error` is also set, the run exists but its workflow did not start. */+ run?: TaskRunDetailDTOApi | null}/**diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 2cab03133447..fb6b5843268b 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -1622,7 +1622,7 @@ export const getTasksRunCreateUrl = (projectId: string, id: string) => {}/**- * Create a new task run and kick off the workflow. **Responds with the task, not the run**: the new run is nested under `latest_run`, and the top-level `id` is still the task's. Read `latest_run.id` for anything run-scoped, such as the run's stream and command endpoints.+ * Create a new task run and kick off the workflow. The response is the refreshed task with the created run under the top-level `run` key: read `run.id` for anything run-scoped, such as the run's stream and command endpoints. The top-level `id` is the task's, and `latest_run` mirrors `run` only as long as nothing newer starts — reading either of those as the created run is deprecated.* @summary Run task*/export const tasksRunCreate = async (@@ -2143,7 +2143,7 @@ export const getTasksRunsCommandCreateUrl = (projectId: string, taskId: string,}/**- * 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, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. Permission responses return 503 agent_session_not_ready only when rejected before execution; clients may retry that code within a bounded startup wait. HTTP 200 preserves JSON-RPC errors; permission acceptance requires result.resolved=true.+ * 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, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. Retry loop: a 503 is transient (sandbox_not_ready means the command arrived before the live run's command channel came up; agent_session_not_ready means an approval was rejected before execution while the agent starts) — retry it until the request you are answering expires. A 502 (agent server unreachable) or 504 (agent server timed out) means delivery is unknown; retry only when the command method is safe to retry. A 409 run_ended is final: the run is over and its sandbox is gone. HTTP 200 preserves JSON-RPC errors; permission acceptance requires result.resolved=true.* @summary Send command to task run*/export const tasksRunsCommandCreate = async (diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 9d38520d84de..618d826db2e6 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1840,7 +1840,7 @@ export const TasksPresenceCreateBody = /* @__PURE__ */ zod)/**- * Create a new task run and kick off the workflow. **Responds with the task, not the run**: the new run is nested under `latest_run`, and the top-level `id` is still the task's. Read `latest_run.id` for anything run-scoped, such as the run's stream and command endpoints.+ * Create a new task run and kick off the workflow. The response is the refreshed task with the created run under the top-level `run` key: read `run.id` for anything run-scoped, such as the run's stream and command endpoints. The top-level `id` is the task's, and `latest_run` mirrors `run` only as long as nothing newer starts — reading either of those as the created run is deprecated.* @summary Run task*/export const tasksRunCreateBodyOneImportedMcpServersItemNameMax = 64@@ -3315,7 +3315,7 @@ export const TasksRunsCancelCreateBody = /* @__PURE__ */ zod.object({})/**- * 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, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. Permission responses return 503 agent_session_not_ready only when rejected before execution; clients may retry that code within a bounded startup wait. HTTP 200 preserves JSON-RPC errors; permission acceptance requires result.resolved=true.+ * 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, set_config_option, mcp_response, side_question, native Pi RPC commands, and Pi queue operations. Retry loop: a 503 is transient (sandbox_not_ready means the command arrived before the live run's command channel came up; agent_session_not_ready means an approval was rejected before execution while the agent starts) — retry it until the request you are answering expires. A 502 (agent server unreachable) or 504 (agent server timed out) means delivery is unknown; retry only when the command method is safe to retry. A 409 run_ended is final: the run is over and its sandbox is gone. HTTP 200 preserves JSON-RPC errors; permission acceptance requires result.resolved=true.* @summary Send command to task run*/export const TasksRunsCommandCreateBody = /* @__PURE__ */ zoddiff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 93ec23bec5fa..31e5d94f3cfb 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -733,7 +733,8 @@ tools:without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit modelfields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before anexplicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a- prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start+ prior run. The created run is the top-level `run`; read `run.id` for run-scoped calls — the top-level `id`+ is the task's. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a startfailure. If the response is lost, check the runs before you retry. A repeated call can start another run.feature_flag: tasks-mcp-agent-run-startresponse:@@ -744,6 +745,12 @@ tools:- title- description- repository+ - run.id+ - run.stage+ - run.status+ - run.scheduled_at+ - run.model+ - run.reasoning_effort- latest_run.id- latest_run.stage- latest_run.statusdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 620da0e5e0cc..89aae591d297 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -12301,7 +12301,7 @@"feature_flag": "tasks"},"tasks-run-create": {- "description": "Start a cloud run for an existing task, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before an explicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",+ "description": "Start a cloud run for an existing task, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before an explicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. The created run is the top-level `run`; read `run.id` for run-scoped calls — the top-level `id` is the task's. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.","category": "Tasks","feature": "tasks","summary": "Start or schedule task run",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex b7100deba316..74a362397c9d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -12979,7 +12979,7 @@"feature_flag": "tasks"},"tasks-run-create": {- "description": "Start a cloud run for an existing task, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before an explicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",+ "description": "Start a cloud run for an existing task, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before an explicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. The created run is the top-level `run`; read `run.id` for run-scoped calls — the top-level `id` is the task's. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.","category": "Tasks","feature": "tasks","summary": "Start or schedule task run",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2f740b2a44b3..a3cf07cb9e5d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -101330,11 +101330,10 @@ export namespace Schemas {export type TaskRunResponseJsonSchema = { [key: string]: unknown } | null;/**- * Detail response for a task.+ * The task ``run`` action's response: the refreshed task detail plus the run this call made.*- * Reads from a frozen ``TaskDetailDTO`` produced by the facade. ``github_integration`` /- * ``github_user_integration`` are integration ids, ``signal_report`` is the report id, and- * ``latest_run`` nests the run-detail shape. ``created_by`` mirrors core ``UserBasicSerializer``.+ * ``run`` is the run the call created or activated — the payload a caller reads run-scoped ids+ * from, instead of inferring them from ``latest_run`` (or, worse, the top-level task ``id``).*/export interface TaskRunResponse {id: string;@@ -101386,6 +101385,8 @@ export namespace Schemas {origin_key?: string | null;/** Error returned when the run could not start. */run_error?: string;+ /** The run this call created or activated. Read run-scoped ids from here — `run.id` is the id the run's stream and command endpoints take, while the top-level `id` is the task's. Set on every 200; when `run_error` is also set, the run exists but its workflow did not start. */+ run?: TaskRunDetailDTO | null;}export interface TaskRunStartRequest {diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex c9bc353ba963..e64d308a58bc 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -1273,7 +1273,7 @@ export const TasksRetrieveParams = () => zod.object({})/**- * Create a new task run and kick off the workflow. **Responds with the task, not the run**: the new run is nested under `latest_run`, and the top-level `id` is still the task's. Read `latest_run.id` for anything run-scoped, such as the run's stream and command endpoints.+ * Create a new task run and kick off the workflow. The response is the refreshed task with the created run under the top-level `run` key: read `run.id` for anything run-scoped, such as the run's stream and command endpoints. The top-level `id` is the task's, and `latest_run` mirrors `run` only as long as nothing newer starts — reading either of those as the created run is deprecated.* @summary Run task*/export const tasksRunCreatePathIdRegExp = new RegExp(diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 93cf9d0035a4..ee340ed08b80 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -902,6 +902,12 @@ const tasksRunCreate = (): ToolBase<ReturnType<typeof TasksRunCreateSchema>, Sch'title','description','repository',+ 'run.id',+ 'run.stage',+ 'run.status',+ 'run.scheduled_at',+ 'run.model',+ 'run.reasoning_effort','latest_run.id','latest_run.stage','latest_run.status',