: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): remove run environment handoff API (#90015)
Jonathan Mielooe61ba0d457cc
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex eaabe56033af..0ccdf4f5ca7e 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -203,7 +203,7 @@ def kill_stale_queued_task_runs() -> None:status=QUEUED handles the race where a worker picks up the run between selectionand update.- Staleness is keyed primarily on `updated_at`, not `created_at`. `prepare_for_cloud_handoff`+ Staleness is keyed primarily on `updated_at`, not `created_at`. `prepare_for_cloud_resume`re-queues an existing run (status=QUEUED, completed_at=None) without resetting`created_at`; using `created_at` would cause the cleanup to kill freshlyre-queued long-lived runs. `updated_at` (auto_now=True) advances on every save,diff --git a/posthog/tasks/test/test_kill_stale_queued_task_runs.py b/posthog/tasks/test/test_kill_stale_queued_task_runs.pyindex cd6b327eaaf6..69792f113ed5 100644--- a/posthog/tasks/test/test_kill_stale_queued_task_runs.py+++ b/posthog/tasks/test/test_kill_stale_queued_task_runs.py@@ -117,11 +117,11 @@ class TestKillStaleQueuedTaskRuns(TestCase):def test_leaves_re_queued_run_with_old_created_at_alone(self) -> None:TaskRun = apps.get_model("tasks", "TaskRun")- # prepare_for_cloud_handoff re-queues an existing run without resetting+ # prepare_for_cloud_resume re-queues an existing run without resetting# created_at. A staleness check keyed on created_at would mistakenly mark# the freshly re-queued run as FAILED; updated_at (auto_now) protects it.run = self._make_run(TaskRun.Status.COMPLETED, datetime.timedelta(hours=48))- run.prepare_for_cloud_handoff()+ run.prepare_for_cloud_resume()kill_stale_queued_task_runs()diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.tsindex 08532467a085..2a671dfaffdd 100644--- a/products/logs/frontend/generated/api.ts+++ b/products/logs/frontend/generated/api.ts@@ -1148,7 +1148,7 @@ export const getTasksRunsLogsRetrieveUrl = (projectId: string, taskId: string, i}/**- * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history and can find the most recent git_checkpoint event regardless of which run emitted it.+ * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history.* @summary Get task run logs*/export const tasksRunsLogsRetrieve = async (diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 0e9433948dec..867e998fe5b2 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -3239,7 +3239,7 @@ export const runStreamLogic = kea<runStreamLogicType>([if (method?.startsWith('_posthog/')) {// _posthog/error, _posthog/status, _posthog/compact_boundary, _posthog/task_notification// → rendered by the projection. _posthog/console, _posthog/sandbox_output,- // _posthog/git_checkpoint, … → no UI. No side effect either way.+ // other internal events → no UI. No side effect either way.return}// The session/new request carries the run's starting permission mode in its meta. Seed thediff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex da2081c94ffc..ea2fe7b72120 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -1,6 +1,7 @@import jsonimport hashlib-from typing import Literal, get_args+from collections.abc import Mapping+from typing import Any, Literal, get_argsimport posthoganalytics@@ -39,6 +40,33 @@ TASK_ANALYSIS_INSIGHTS_STATE_KEY = "task_analysis_insights"# Consumers read the stamp, so the decision stays stable for the run's whole lifetime.AGENT_OTEL_TELEMETRY_STATE_KEY = "agent_otel_telemetry_enabled"PR_LOOP_ENABLED_STATE_KEY = "pr_loop_enabled"+SAME_RUN_RESUME_STATE_KEY = "same_run_resume"+SAME_RUN_RESUME_IDLE_STATE_KEY = "same_run_resume_idle"+_LEGACY_SAME_RUN_RESUME_STATE_KEY = "handoff_resumed"+_LEGACY_SAME_RUN_RESUME_IDLE_STATE_KEY = "handoff_resume_idle"+SERVER_OWNED_RESUME_STATE_KEYS = frozenset(+ {+ SAME_RUN_RESUME_STATE_KEY,+ SAME_RUN_RESUME_IDLE_STATE_KEY,+ _LEGACY_SAME_RUN_RESUME_STATE_KEY,+ _LEGACY_SAME_RUN_RESUME_IDLE_STATE_KEY,+ }+)+++def is_same_run_resume_state(state: Mapping[str, Any] | None) -> bool:+ if not state:+ return False+ return state.get(SAME_RUN_RESUME_STATE_KEY) is True or state.get(_LEGACY_SAME_RUN_RESUME_STATE_KEY) is True+++def is_same_run_resume_idle_state(state: Mapping[str, Any] | None) -> bool:+ if not state:+ return False+ return (+ state.get(SAME_RUN_RESUME_IDLE_STATE_KEY) is True or state.get(_LEGACY_SAME_RUN_RESUME_IDLE_STATE_KEY) is True+ )+# Models a caller may only select while the paired flag is enabled for them. The Desktop# pickers already hide these client-side (`products/desktop/packages/shared/src/flags.ts`),diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 7a01bc6a1d93..47126aaa1c16 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -77,11 +77,13 @@ from products.tasks.backend.constants import (PR_LOOP_ENABLED_STATE_KEY,PR_STATES as PR_STATES, # re-exported for presentationRESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS,+ SERVER_OWNED_RESUME_STATE_KEYS,TASK_ANALYSIS_FEATURE_FLAG,TASK_ANALYSIS_INSIGHTS_STATE_KEY,TASK_SESSION_MAX_SIZE_BYTES,get_required_model_flag,is_blocked_sandbox_env_key,+ is_same_run_resume_state,)from products.tasks.backend.error_telemetry import truncate_error_messagefrom products.tasks.backend.feature_flags import get_model_access_error, is_workflow_dispatch_shadow_enabled@@ -1101,7 +1103,7 @@ def filter_uncovered_workflow_dispatch_run_ids(candidate_ids: list[UUID]) -> lisrun = runs.get(run_id)state = run.state if run and isinstance(run.state, dict) else {}has_legacy_intent = bool(state.get("pending_dispatch"))- awaiting_restart_rollout = bool(state.get("handoff_resumed"))+ awaiting_restart_rollout = is_same_run_resume_state(state)if run_id not in dispatch_run_ids and not has_legacy_intent and not awaiting_restart_rollout:WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL.inc()logger.warning(@@ -1221,9 +1223,9 @@ def collect_task_run_state_metrics(parent origin_product) so no ORM leaks across the boundary.A QUEUED run's age counts from ``queued_at``, not from row creation:- ``prepare_for_cloud_handoff`` re-queues an existing run without resetting ``created_at``,- so a desktop-to-cloud handoff would otherwise report the whole prior run's lifetime as- queue wait. Rows queued before ``queued_at`` existed fall back to ``created_at``, which is+ ``prepare_for_cloud_resume`` re-queues an existing run without resetting ``created_at``,+ so a cloud restart would otherwise report the whole prior run's lifetime as queue wait.+ Rows queued before ``queued_at`` existed fall back to ``created_at``, which isexact for a run that was only ever queued once. Every other non-terminal status countsfrom creation, where elapsed lifetime is the useful age."""@@ -1393,9 +1395,8 @@ def recent_wizard_cloud_run_times(user_id: int, since: datetime) -> list[datetimThe filter trusts only PATCH-immutable markers: ``created_by`` (set at creation) and theprotected ``wizard_config`` state key that only ``create_wizard_cloud_run`` stamps (see- ``_PROTECTED_RUN_STATE_KEYS``). Mutable fields like the run's ``environment`` are- deliberately NOT filtered — a run PATCHed from cloud to local must keep consuming quota,- or flipping it would launder sandbox boots out of the limits.+ ``_PROTECTED_RUN_STATE_KEYS``). The environment is not part of the quota identity because+ these immutable markers already identify every wizard cloud run.Deliberately user-scoped across teams: the throttle is per user, and a user can run thewizard on projects in different teams. Returns only timestamps, no run data.@@ -1557,9 +1558,8 @@ def complete_idle_local_task_run(run_id: str | UUID) -> bool:noise, not signal.Compare-and-set claim (like ``claim_and_fail_stale_run``): the conditional update flips the- run only while it is still QUEUED *and* local, so a run that left the queue — or was handed- off to cloud (handoff keeps status QUEUED) — between the candidate scan and this call is- skipped rather than terminalized under its just-dispatched workflow. The winner finalizes+ run only while it is still QUEUED *and* local, so a run that left the queue between the+ candidate scan and this call is skipped. The winner finalizesvia ``mark_completed`` (``completed_at``, stream + analytics). Intentionally cross-team(janitor sweep)."""@@ -2043,6 +2043,8 @@ def delete_sandbox_custom_image(image_id: str | UUID, team_id: int, user_id: int# a caller could otherwise force the VM runtime while the feature flag or custom-image gate is off.# - snapshot_external_id / snapshot_kind / snapshot_mount_path control which Modal image is# restored on resume and where directory snapshots are mounted.+# - same-run resume markers control whether provisioning reloads the current run's logs and+# starts the sandbox idle. Legacy marker names remain protected during rollout.# - workflow_id is the run's Temporal workflow address (``TaskRun.workflow_id`` prefers it over# the derived id); a caller could otherwise repoint their run at another team's workflow and# signal or terminate-and-restart it.@@ -2086,6 +2088,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("snapshot_external_id","snapshot_kind","snapshot_mount_path",+ *SERVER_OWNED_RESUME_STATE_KEYS,"workflow_id","pending_dispatch",# Written once at loop fire time; seeding copies these storage paths into the@@ -2580,7 +2583,6 @@ def update_task_run(if only_if_non_terminal and run.is_terminal:return _task_run_detail_to_dto(run)old_status = run.status- old_environment = run.environmentold_pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else Noneold_commit_head = _commit_push_head_sha(run.output)@@ -2675,10 +2677,6 @@ def update_task_run()notify_task_run_cancelled(run)- new_environment = validated_data.get("environment")- if new_environment == "local" and old_environment == TaskRun.Environment.CLOUD:- signal_workflow_completion(run.id, "cancelled", "handoff")-new_pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else Noneif new_pr_url and new_pr_url != old_pr_url:_refresh_self_driving_quota_for_pr(run, old_pr_url)@@ -4676,7 +4674,8 @@ def resume_task_run_in_cloud("""Resume a run in a cloud sandbox, terminating any prior workflow.Returns ``(outcome, run_dto, debug_use_modal)``. ``outcome`` is one of: ``"not_found"``,- ``"already_active"`` (400), ``"ownership_changed"`` (400), ``"invalid_origin"`` (400), ``"auth_error:<detail>"``+ ``"already_active"`` (400), ``"not_cloud"`` (400), ``"ownership_changed"`` (400), ``"invalid_origin"`` (400),+ ``"auth_error:<detail>"``(400, GitHub auth), ``"workflow_failed"`` (502), or ``"resumed"`` (run_dto set).Mirrors ``TaskRunViewSet.resume_in_cloud``."""@@ -4729,11 +4728,13 @@ def resume_task_run_in_cloud()if not run.matches_task_ownership(task):return "ownership_changed", None, None+ if run.environment != TaskRun.Environment.CLOUD:+ return "not_cloud", None, Noneif task.origin_product not in Task.OriginProduct.values:return "invalid_origin", None, None- is_cloud_active = run.environment == TaskRun.Environment.CLOUD and run.status in (+ is_cloud_active = run.status in (TaskRun.Status.QUEUED,TaskRun.Status.IN_PROGRESS,)@@ -4762,7 +4763,7 @@ def resume_task_run_in_cloud(prior_completed_at = run.completed_atprior_queued_at = run.queued_atprior_state = dict(run.state or {})- run.prepare_for_cloud_handoff()+ run.prepare_for_cloud_resume()if restart_dispatch_enabled:snapshot = RestartSnapshot(@@ -4792,7 +4793,7 @@ def resume_task_run_in_cloud(raise RuntimeError("Failed to reset task run event stream")resume_task_in_cloud_workflow(str(run.id), run.workflow_id)except Exception as e:- logger.exception("Failed to trigger handoff workflow", extra={"task_run_id": str(run.id), "error": str(e)})+ logger.exception("Failed to trigger resume workflow", extra={"task_run_id": str(run.id), "error": str(e)})with transaction.atomic():run = TaskRun.objects.select_for_update().get(pk=run.pk)run.status = prior_status@@ -8606,8 +8607,8 @@ def post_comment_thread_update(*, team_id: int, comment_id: UUID) -> None:def _announce_agent_artifact_uploads(run: TaskRun, new_entries: list[dict], manifest: list[dict]) -> None:"""Announce files the agent delivered as task outputs.- The manifest also holds internal state such as git handoff checkpoints and skill- bundles. Those files support the run but are not deliverables for the timeline.+ The manifest also holds internal state such as skill bundles. Those files support the+ run but are not deliverables for the timeline.Manifest entries carry no version, so same-named output entries determine whetheran upload created or revised a file. The artifact id deduplicates retried uploads."""diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 4304e2848864..81a99d08a963 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -1995,7 +1995,7 @@ class TaskRun(models.Model):updated_at = models.DateTimeField(auto_now=True)completed_at = models.DateTimeField(null=True, blank=True)# When the run last entered QUEUED. `created_at` can't stand in for it because- # `prepare_for_cloud_handoff` re-queues an existing run without resetting it, and+ # `prepare_for_cloud_resume` re-queues an existing run without resetting it, and# `updated_at` can't either because any unrelated write to a still-queued run would# move it. Null on rows queued before this field existed; readers fall back to# `created_at`, which is exact for a run that was only ever queued once.@@ -2078,11 +2078,11 @@ class TaskRun(models.Model):task_created_by_id=self.task.created_by_id,)- def prepare_for_cloud_handoff(self) -> None:+ def prepare_for_cloud_resume(self) -> None:"""- Restart this run in the cloud, resuming from its existing log/checkpoints.+ Restart this cloud run from its existing log and sandbox snapshot.- The `handoff_resumed` flag tells the workflow and sandbox provisioning+ The `same_run_resume` flag tells the workflow and sandbox provisioningto treat this as a resume of the same run (skip initial prompt, hydratefrom the existing log) without overloading `resume_from_run_id`, whichmeans "continue from a different run".@@ -2097,7 +2097,7 @@ class TaskRun(models.Model):prior_snapshot_external_id = state.get("snapshot_external_id")prior_snapshot_kind = state.get("snapshot_kind")prior_snapshot_mount_path = state.get("snapshot_mount_path")- state["handoff_resumed"] = True+ state["same_run_resume"] = Truestate["mode"] = "interactive"state.pop("pending_user_message", None)state.pop("pending_user_artifact_ids", None)@@ -2107,14 +2107,14 @@ class TaskRun(models.Model):state.pop("sandbox_url", None)state.pop("sandbox_jwt_kid", None)state.pop("sandbox_connect_token", None)- # Drop the provider stamp too: the handed-off run re-resolves its backend from+ # Drop the provider stamp because the resumed run re-resolves its backend from# scratch, so a stale `hogland` must not survive to outrank the EU guard, the# Modal-only fallbacks, or the flag kill switch on the next context resolution.state.pop("sandbox_backend", None)self.state = statelogger.info(- "prepare_for_cloud_handoff",+ "prepare_for_cloud_resume",run_id=str(self.id),task_id=str(self.task_id),prior_snapshot_external_id=prior_snapshot_external_id,@@ -2628,7 +2628,7 @@ class TaskRun(models.Model):clear it would cost a whole run, so the marker is written straight to the log.Resume reads a chain's logs concatenated and rebuilds only the turns after themarker, so the next run continues the task with an empty conversation while its- checkpoints, artifacts, and visible history stay intact.+ artifacts and visible history stay intact.The `/clear` message is recorded ahead of the marker, matching the agent, so thetranscript shows what the user typed and rehydration drops it with everythingdiff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 3eae5989064b..cdbc80afb39f 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -260,11 +260,6 @@ class TaskRunUpdateSerializer(serializers.Serializer):error_message = serializers.CharField(required=False, allow_null=True, allow_blank=True, help_text="Error message if execution failed")- environment = serializers.ChoiceField(- choices=["local"],- required=False,- help_text="Transition a cloud run to local. Use the resume_in_cloud action to move a run into cloud.",- )class TaskRunSkillBundleMetadataSerializer(serializers.Serializer):diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 34029e9af81d..36486de70815 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -1761,7 +1761,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):summary="Clear conversation history",description=("Record a `/clear` boundary in a finished run's log so the next run in the chain "- "starts with an empty conversation. Its checkpoints, artifacts, and visible history "+ "starts with an empty conversation. Its artifacts and visible history ""are unaffected. Only for a finished run: an active one has an agent that owns the ""clear, so send `/clear` to it as an ordinary message instead."),@@ -2181,8 +2181,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):task_id = self._ensure_task_accessible()storage_path = request.validated_data["storage_path"]- # Walk the resume chain so cloud→cloud resume runs can fetch the git checkpoint- # pack/index that lives on the prior run they were forked from.+ # Walk the resume chain because a resumed run can reference artifacts from an ancestor.content, artifact, error = tasks_facade.read_task_run_artifact(pk, task_id, self.team_id, storage_path=storage_path)@@ -2484,8 +2483,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"Fetch the logs for a task run as JSONL. If the run resumes from ""another (state.resume_from_run_id), each ancestor's log is ""concatenated first (oldest ancestor → ... → this run) so resume "- "consumers see a single continuous history and can find the most "- "recent git_checkpoint event regardless of which run emitted it."+ "consumers see a single continuous history."),)@action(detail=True, methods=["get"], url_path="logs", required_scopes=["task:read"])@@ -3057,7 +3055,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):) == tasks_facade.TaskRuntime.PI and not tasks_facade.pi_cloud_runtime_enabled(self.team, request.user):return _pi_cloud_runtime_disabled_response()- # Resume also runs in cloud: gate before handoff.+ # A resumed run also consumes cloud capacity, so apply the cloud access gates.if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (access_response := code_access_required_response(request, self.organization, task_id=task_id)):@@ -3075,6 +3073,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):TaskRunErrorResponseSerializer({"error": "Run is already active in cloud"}).data,status=status.HTTP_400_BAD_REQUEST,)+ if outcome == "not_cloud":+ return Response(+ TaskRunErrorResponseSerializer({"error": "Only cloud runs can be resumed in cloud"}).data,+ status=status.HTTP_400_BAD_REQUEST,+ )if outcome == "ownership_changed":return Response(TaskRunErrorResponseSerializer(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 bc72b3562d40..86e48abefdab 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@@ -127,7 +127,7 @@ class TestShouldForwardPendingUserMessage:# Resume runs already replay the original prompt — forwarding would# double up. Both resume markers must short-circuit.({"mode": "background", "resume_from_run_id": "prev"}, False),- ({"mode": "background", "handoff_resumed": True}, False),+ ({"mode": "background", "same_run_resume": True}, False),],)def test_forwards_only_in_background_and_not_on_resume(self, state: dict, expected: bool):diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex cfd657850210..e3f39b6939e5 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -23,7 +23,7 @@ from temporalio.common import RetryPolicyfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.oauth import PosthogMcpScopes-from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME+from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME, is_same_run_resume_statefrom 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 (@@ -1182,7 +1182,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):await self._emit_progress("clone", "completed", clone_label, "setup")state = self.context.state or {}- is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))+ is_resume = bool(state.get("resume_from_run_id") or is_same_run_resume_state(state))if will_checkout and not is_resume:assert checkout_repository is not Noneassert prepared.branch is not None@@ -1308,7 +1308,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):if not self._context:return Falsestate = self.context.state or {}- is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))+ is_resume = bool(state.get("resume_from_run_id") or is_same_run_resume_state(state))return self.context.mode != "interactive" and not is_resumeasync def _track_workflow_event(self, event_name: str, properties: dict, capture_analytics: bool = True) -> None:diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.pyindex c0479d0bd5ad..9fc9ba5081a8 100644--- a/products/tasks/backend/temporal/metrics.py+++ b/products/tasks/backend/temporal/metrics.py@@ -110,9 +110,9 @@ def _runtime_adapter_label(value: str | None) -> str:return value if value in _ALLOWED_RUNTIME_ADAPTERS else "other"-def resume_mode_label(*, handoff_resumed: bool, using_modal_snapshot: bool) -> str:- if handoff_resumed:- return "handoff_and_snapshot" if using_modal_snapshot else "handoff"+def resume_mode_label(*, same_run_resume: bool, using_modal_snapshot: bool) -> str:+ if same_run_resume:+ return "same_run_and_snapshot" if using_modal_snapshot else "same_run"return "snapshot_only" if using_modal_snapshot else "neither"@@ -121,9 +121,8 @@ def increment_resume_mode(mode: str, *, origin_product: str | None) -> None:_metric_meter({"mode": mode, "origin_product": origin_product or "unknown"}).create_counter("tasks_process_resume_mode","Resuming process-task runs by the resume state available at provision time. "- "handoff labels record that a handoff was requested, not that its git checkpoint "- "was captured. neither means no snapshot and no handoff state accompanied the "- "resume, so the agent's prior working tree could not be restored.",+ "same_run labels identify a restart of the current run. neither means no snapshot "+ "or same-run state accompanied the resume, so the prior working tree could not be restored.",).add(1)except Exception:passdiff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.pyindex 1eca8443c4d8..44ff66da72d8 100644--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py@@ -274,7 +274,7 @@ def get_sandbox_for_repository(input: GetSandboxForRepositoryInput) -> GetSandbo# can be rebuilt from logs even when the filesystem snapshot has expired.if run_state.resume_from_run_id:environment_variables["POSTHOG_RESUME_RUN_ID"] = run_state.resume_from_run_id- elif run_state.handoff_resumed:+ elif run_state.same_run_resume:environment_variables["POSTHOG_RESUME_RUN_ID"] = str(ctx.run_id)# Check for resume snapshot (takes priority over integration-level snapshots)diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 7b99cd4cebc4..d990d6872ef4 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -26,6 +26,7 @@ from products.tasks.backend.constants import (SANDBOX_EVENT_INGEST_FEATURE_FLAG,SANDBOX_ROTATION_FEATURE_FLAG,get_vm_sandbox_flag_payload,+ is_same_run_resume_state,vm_sandbox_allowed_origin_products,vm_sandbox_default_base_origin_products,vm_sandbox_default_custom_image,@@ -182,7 +183,7 @@ class TaskProcessingContext:@propertydef is_snapshot_resume(self) -> bool:state = self.state or {}- has_resume_source = isinstance(state.get("resume_from_run_id"), str) or state.get("handoff_resumed") is True+ has_resume_source = isinstance(state.get("resume_from_run_id"), str) or is_same_run_resume_state(state)return has_resume_source and isinstance(state.get("snapshot_external_id"), str)@property@@ -769,7 +770,7 @@ def _resolve_sandbox_backend(# Hard gates: a "hogland" result (override OR flag) is only allowed when hogland can# actually run this run. These sit ahead of the override so a stale or forged `hogland`- # (e.g. carried across a cloud handoff) can't defeat the EU guard or the Modal-only+ # carried across a cloud resume can't defeat the EU guard or the Modal-only# fallbacks and leave the run with unenforced egress.if not settings.HOGLAND_API_URL or not (settings.HOGLAND_API_TOKEN_FILE or settings.HOGLAND_API_TOKEN):return "modal"diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 6c64044edaa5..a50a3db60483 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -533,9 +533,9 @@ def _build_environment_variables(run_state = parse_run_state(ctx.state)if run_state.resume_from_run_id:environment_variables["POSTHOG_RESUME_RUN_ID"] = run_state.resume_from_run_id- elif run_state.handoff_resumed:+ elif run_state.same_run_resume:environment_variables["POSTHOG_RESUME_RUN_ID"] = str(ctx.run_id)- if run_state.handoff_resume_idle:+ if run_state.same_run_resume_idle:environment_variables["POSTHOG_RESUME_IDLE"] = "1"# Cloud wizard runs get a SEPARATE token, minted under the wizard's own OAuth app with the@@ -668,9 +668,9 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Psnapshot_kind = run_state.resume_snapshot_kind()snapshot_mount_path = run_state.resume_snapshot_mount_path()- is_resume = bool(run_state.handoff_resumed or run_state.resume_from_run_id)+ is_resume = bool(run_state.same_run_resume or run_state.resume_from_run_id)resume_mode = resume_mode_label(- handoff_resumed=run_state.handoff_resumed,+ same_run_resume=run_state.same_run_resume,using_modal_snapshot=resume_snapshot_external_id is not None,)resume_decision_log = (@@ -686,8 +686,8 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P"effective_snapshot_external_id": resume_snapshot_external_id,"effective_snapshot_kind": snapshot_kind,"effective_snapshot_mount_path": snapshot_mount_path,- "handoff_resumed": run_state.handoff_resumed,- "handoff_resume_idle": run_state.handoff_resume_idle,+ "same_run_resume": run_state.same_run_resume,+ "same_run_resume_idle": run_state.same_run_resume_idle,"resume_from_run_id": run_state.resume_from_run_id,"posthog_resume_run_id_set": "POSTHOG_RESUME_RUN_ID" in environment_variables,"used_snapshot": used_snapshot,@@ -697,8 +697,8 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Pemit_agent_log(ctx.run_id,"debug",- f"Resume mode: handoff_resumed={run_state.handoff_resumed}, "- f"resume_idle={run_state.handoff_resume_idle}, "+ f"Resume mode: same_run_resume={run_state.same_run_resume}, "+ f"resume_idle={run_state.same_run_resume_idle}, "f"resume_from_run_id={run_state.resume_from_run_id}, "f"using_modal_snapshot={resume_snapshot_external_id is not None}",)@@ -1006,8 +1006,8 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneReemit_agent_log(ctx.run_id, "debug", f"Cloning {input.repository} into sandbox")sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)- state = ctx.state or {}- is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))+ state = parse_run_state(ctx.state)+ is_resume = bool(state.resume_from_run_id or state.same_run_resume)with StepTimer("repository_clone",@@ -1027,7 +1027,7 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneReemit_agent_log(ctx.run_id,"debug",- f"Resume branch {ctx.branch} is unavailable; cloning the repository default branch so the agent can restore its git checkpoint",+ f"Resume branch {ctx.branch} is unavailable; cloning the repository default branch so the agent can continue from its preserved conversation",)clone_result = sandbox.clone_repository(input.repository,diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.pyindex d680c4e774ec..daa2bb66bf32 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py@@ -53,7 +53,7 @@ VM_FLAG_PAYLOAD_TARGET = "products.tasks.backend.constants.posthoganalytics.get_[({}, False),({"resume_from_run_id": "previous-run"}, False),- ({"handoff_resumed": True}, False),+ ({"same_run_resume": True}, False),({"snapshot_external_id": "snapshot-id"}, False),({@@ -64,7 +64,7 @@ VM_FLAG_PAYLOAD_TARGET = "products.tasks.backend.constants.posthoganalytics.get_),({- "handoff_resumed": True,+ "same_run_resume": True,"snapshot_external_id": "snapshot-id",},True,@@ -1421,7 +1421,7 @@ class TestResolveSandboxBackend:@override_settings(**_HOGLAND_SETTINGS, CLOUD_DEPLOYMENT="EU")def test_hogland_override_cannot_defeat_the_eu_guard(self):- # A stale/forged hogland override (e.g. surviving a cloud handoff) must not run an+ # A stale or forged hogland override surviving a cloud resume must not run an# EU run on hogland — the capability gates sit ahead of the override.assert self._resolve_with_flag(True, state={"sandbox_backend": "hogland"}) == "modal"diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.pyindex 5518ebf4a8ea..cffcd5892eeb 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py@@ -12,7 +12,7 @@ from asgiref.sync import async_to_syncfrom products.tasks.backend.constants import SNAPSHOT_KIND_DIRECTORY, SNAPSHOT_KIND_FILESYSTEMfrom products.tasks.backend.exceptions import RepositoryCloneErrorfrom products.tasks.backend.logic.services.docker_sandbox import DockerSandbox-from products.tasks.backend.logic.services.sandbox import ExecutionResult, Sandbox+from products.tasks.backend.logic.services.sandbox import ExecutionResultfrom products.tasks.backend.models import Taskfrom products.tasks.backend.temporal.metrics import modal_sandbox_backend_label, resume_mode_labelfrom products.tasks.backend.temporal.process_task.activities import provision_sandbox as provision_sandbox_module@@ -195,16 +195,16 @@ def test_modal_sandbox_backend_label(monkeypatch: pytest.MonkeyPatch, value: str@pytest.mark.parametrize(- ("handoff_resumed", "using_modal_snapshot", "expected"),+ ("same_run_resume", "using_modal_snapshot", "expected"),[- (True, False, "handoff"),- (True, True, "handoff_and_snapshot"),+ (True, False, "same_run"),+ (True, True, "same_run_and_snapshot"),(False, True, "snapshot_only"),(False, False, "neither"),],)-def test_resume_mode_label(handoff_resumed: bool, using_modal_snapshot: bool, expected: str) -> None:- assert resume_mode_label(handoff_resumed=handoff_resumed, using_modal_snapshot=using_modal_snapshot) == expected+def test_resume_mode_label(same_run_resume: bool, using_modal_snapshot: bool, expected: str) -> None:+ assert resume_mode_label(same_run_resume=same_run_resume, using_modal_snapshot=using_modal_snapshot) == expected@pytest.mark.asyncio@@ -277,7 +277,7 @@ async def test_create_sandbox_cancellation_stops_docker_subprocess(monkeypatch:"state, expected_branch",[({"resume_from_run_id": "previous-run-id"}, "feature-branch"),- ({"handoff_resumed": True}, "feature-branch"),+ ({"same_run_resume": True}, "feature-branch"),({}, None),],)@@ -297,7 +297,10 @@ def test_clone_repository_uses_saved_branch_only_for_resumes(mocker, activity_en)sandbox = mocker.Mock()sandbox.clone_repository.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)- mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)+ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_class_for_sandbox_id",+ return_value=mocker.Mock(get_by_id=mocker.Mock(return_value=sandbox)),+ )mocker.patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.posthoganalytics.feature_enabled",return_value=True,@@ -348,7 +351,10 @@ def test_resume_clone_falls_back_to_default_branch_when_saved_branch_is_missing(),ExecutionResult(stdout="", stderr="", exit_code=0),]- mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)+ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_class_for_sandbox_id",+ return_value=mocker.Mock(get_by_id=mocker.Mock(return_value=sandbox)),+ )async_to_sync(activity_environment.run)(clone_repository_in_sandbox,@@ -398,7 +404,10 @@ def test_clone_failure_records_failed_latency_and_captures_command_result(mockerexit_code=124,error="execution stopped",)- mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)+ mocker.patch(+ "products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_class_for_sandbox_id",+ return_value=mocker.Mock(get_by_id=mocker.Mock(return_value=sandbox)),+ )metric_meter = mocker.patch("products.tasks.backend.temporal.metrics._metric_meter")capture_exception = mocker.patch("products.tasks.backend.exceptions.capture_exception")diff --git a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.pyindex 91919cc572f2..219286e6d99a 100644--- a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py@@ -318,12 +318,12 @@ def test_build_environment_variables_injects_ai_gateway_pair(_api, _jwt, _git):"state, expected_resume_run_id, expected_idle",[({}, None, None),- ({"handoff_resumed": True}, "run-456", None),- ({"handoff_resumed": True, "handoff_resume_idle": True}, "run-456", "1"),- ({"resume_from_run_id": "run-000", "handoff_resume_idle": True}, "run-000", None),+ ({"same_run_resume": True}, "run-456", None),+ ({"same_run_resume": True, "same_run_resume_idle": True}, "run-456", "1"),+ ({"resume_from_run_id": "run-000", "same_run_resume_idle": True}, "run-000", None),],)-def test_build_environment_variables_marks_only_an_idle_handoff_as_idle(+def test_build_environment_variables_marks_only_an_idle_same_run_resume_as_idle(_api, _jwt, _git, state, expected_resume_run_id, expected_idle):env = _build_environment_variables(_context(state=state), MagicMock(), "", "access-token")diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex dc10bc66eb9b..781175bde137 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -31,6 +31,7 @@ from products.tasks.backend.temporal.process_task.utils import (is_bot_authorship_fallback,is_caller_token_run,loop_mcp_installation_allowlist,+ parse_run_state,upgrade_run_to_user_authorship,)@@ -48,6 +49,22 @@ class TestRuntimeModelCapabilities(SimpleTestCase):assert get_supported_reasoning_efforts("claude", "moonshotai/kimi-k3") == ()+class TestRunStateResumeCompatibility(SimpleTestCase):+ @parameterized.expand(+ [+ ("resume", {"handoff_resumed": True}, True, False),+ ("idle", {"handoff_resumed": True, "handoff_resume_idle": True}, True, True),+ ]+ )+ def test_parse_run_state_accepts_legacy_resume_keys(+ self, _name: str, state: dict[str, bool], expected_resume: bool, expected_idle: bool+ ) -> None:+ parsed = parse_run_state(state)++ self.assertEqual(parsed.same_run_resume, expected_resume)+ self.assertEqual(parsed.same_run_resume_idle, expected_idle)++class TestRunStateSnapshotPaths(TestCase):@parameterized.expand([diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 154c35f6ecc0..af69d0a88643 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -527,7 +527,7 @@ class TestSandboxRotation:async def provision_replacement():state = wf.context.state or {}- resume_flags_at_provision["value"] = (state.get("handoff_resumed"), state.get("handoff_resume_idle"))+ resume_flags_at_provision["value"] = (state.get("same_run_resume"), state.get("same_run_resume_idle"))return self._replacement()monkeypatch.setattr(wf, "_get_sandbox_for_repository", provision_replacement)diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex f25dcf8a90ef..d4db558293ae 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -26,6 +26,8 @@ from products.tasks.backend.constants import (InitialPermissionMode,SnapshotKind,filter_user_sandbox_env_vars,+ is_same_run_resume_idle_state,+ is_same_run_resume_state,)from products.tasks.backend.exceptions import CredentialUnavailableErrorfrom products.tasks.backend.logic.services.mcp_url import resolve_mcp_url as _resolve_mcp_url@@ -389,8 +391,8 @@ class RunState(BaseModel, extra="allow"):context_window: str | None = Nonefast_mode: bool | None = Noneresume_from_run_id: str | None = None- handoff_resumed: bool = False- handoff_resume_idle: bool = False+ same_run_resume: bool = False+ same_run_resume_idle: bool = Falsesnapshot_external_id: str | None = Nonesnapshot_kind: str | None = Nonesnapshot_mount_path: str | None = None@@ -436,7 +438,10 @@ class RunState(BaseModel, extra="allow"):def parse_run_state(state: dict[str, Any] | None) -> RunState:- return RunState.model_validate(state or {})+ normalized_state = dict(state or {})+ normalized_state["same_run_resume"] = is_same_run_resume_state(state)+ normalized_state["same_run_resume_idle"] = is_same_run_resume_idle_state(state)+ return RunState.model_validate(normalized_state)@dataclass(frozen=True)diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 4bf31de5c5e0..099636a35b93 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -17,7 +17,7 @@ from posthog.dataclasses import frozenfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.oauth import PosthogMcpScopes-from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME, SNAPSHOT_KIND_FILESYSTEM+from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME, SNAPSHOT_KIND_FILESYSTEM, is_same_run_resume_statefrom products.tasks.backend.error_telemetry import truncate_error_messagefrom products.tasks.backend.logic.services.sandbox import is_public_sandbox_repofrom products.tasks.backend.temporal.babysit_pr.prompts import (@@ -1966,7 +1966,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):await self._emit_progress("clone", "completed", clone_label, "setup")state = self.context.state or {}- is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))+ is_resume = bool(state.get("resume_from_run_id") or is_same_run_resume_state(state))checkout_ms: int | None = Noneif will_checkout and checkout_repository not in failed_repositories and not is_resume:assert checkout_repository is not None@@ -2342,7 +2342,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):return Falsestate = self.context.state or {}- is_resume = bool(state.get("resume_from_run_id") or state.get("handoff_resumed"))+ is_resume = bool(state.get("resume_from_run_id") or is_same_run_resume_state(state))return self.context.mode != "interactive" and not is_resumeasync def _track_workflow_event(self, event_name: str, properties: dict, capture_analytics: bool = True) -> None:@@ -2552,8 +2552,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):"snapshot_external_id": snapshot.external_id,"snapshot_kind": snapshot.snapshot_kind,"snapshot_mount_path": snapshot.snapshot_mount_path,- "handoff_resumed": True,- "handoff_resume_idle": True,+ "same_run_resume": True,+ "same_run_resume_idle": True,}live_sandbox = PreRotationSandbox(sandbox_id=old_sandbox_id,diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex 8442a5b11d28..0ff55a001908 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py@@ -232,7 +232,7 @@ class TestRelaySlackMessage(TestCase):_mock_update,_mock_flag,):- # Run-manifest artifacts are internal (checkpoints, inputs, raw agent outputs).+ # Run-manifest artifacts are internal (inputs, context, raw agent outputs).# Even with living artifacts enabled they must not leak into the posted text,# and their presence must not suppress the unconfirmed-attachment notice.self.task_run.artifacts = [diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 41138bb6aab4..829d5d826905 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -5360,6 +5360,10 @@ class TestTaskRunAPI(BaseTaskAPITest):"snapshot_external_id": "im-real","snapshot_kind": "directory","snapshot_mount_path": "/tmp",+ "same_run_resume": True,+ "same_run_resume_idle": False,+ "handoff_resumed": True,+ "handoff_resume_idle": False,"workflow_id": "wf-real","pending_dispatch": {"workflow_id_prefix": "review-real", "create_pr": True},"pending_external_followups": pending_external_followups,@@ -5382,7 +5386,7 @@ class TestTaskRunAPI(BaseTaskAPITest):# credential-propagation target at a sandbox they control, inflate the run's compute /# lifetime to provision an oversized, long-lived sandbox, turn the run into a wizard run# (which would mint a write-scoped wizard token into the sandbox), change rollout- # decisions, change Modal resume snapshot metadata, repoint the run at another+ # decisions, change resume state or snapshot metadata, repoint the run at another# team's Temporal workflow, or steer an orphan re-dispatch (workflow ID prefix / MCP# scopes) via pending_dispatch, or repoint the run at a costlier model (which for a run# routed to an unbilled gateway product is free spend). Nor can a caller stamp a@@ -5407,6 +5411,10 @@ class TestTaskRunAPI(BaseTaskAPITest):"snapshot_external_id": "im-attacker","snapshot_kind": "directory","snapshot_mount_path": "/tmp/workspace",+ "same_run_resume": False,+ "same_run_resume_idle": True,+ "handoff_resumed": False,+ "handoff_resume_idle": True,"workflow_id": "wf-another-teams-workflow","pending_dispatch": {"workflow_id_prefix": "attacker", "posthog_mcp_scopes": ["*"]},"pending_external_followups": [@@ -5456,6 +5464,10 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["snapshot_external_id"] == "im-real"assert run.state["snapshot_kind"] == "directory"assert run.state["snapshot_mount_path"] == "/tmp"+ assert run.state["same_run_resume"] is True+ assert run.state["same_run_resume_idle"] is False+ assert run.state["handoff_resumed"] is True+ assert run.state["handoff_resume_idle"] is Falseassert run.state["workflow_id"] == "wf-real"assert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}assert run.state["pending_external_followups"] == pending_external_followups@@ -5489,6 +5501,10 @@ class TestTaskRunAPI(BaseTaskAPITest):"snapshot_external_id","snapshot_kind","snapshot_mount_path",+ "same_run_resume",+ "same_run_resume_idle",+ "handoff_resumed",+ "handoff_resume_idle","workflow_id","pending_dispatch","pending_external_followups",@@ -5517,6 +5533,10 @@ class TestTaskRunAPI(BaseTaskAPITest):assert run.state["snapshot_external_id"] == "im-real" # protected key survives removalassert run.state["snapshot_kind"] == "directory" # protected key survives removalassert run.state["snapshot_mount_path"] == "/tmp" # protected key survives removal+ assert run.state["same_run_resume"] is True+ assert run.state["same_run_resume_idle"] is False+ assert run.state["handoff_resumed"] is True+ assert run.state["handoff_resume_idle"] is Falseassert run.state["workflow_id"] == "wf-real" # protected key survives removalassert run.state["pending_dispatch"] == {"workflow_id_prefix": "review-real", "create_pr": True}assert run.state["pending_external_followups"] == pending_external_followups@@ -5564,7 +5584,7 @@ class TestTaskRunAPI(BaseTaskAPITest):run = TaskRun.objects.create(task=task,team=self.team,- environment=TaskRun.Environment.LOCAL,+ environment=TaskRun.Environment.CLOUD,status=TaskRun.Status.COMPLETED,state={"pr_authorship_mode": "bot"},)@@ -5578,13 +5598,33 @@ class TestTaskRunAPI(BaseTaskAPITest):mock_reset_stream.assert_called_once_with(str(run.id), use_dedicated=False)mock_resume.assert_called_once_with(str(run.id), run.workflow_id)+ @patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow")+ def test_resume_in_cloud_rejects_local_run(self, mock_resume):+ task = self.create_task(runtime=Task.Runtime.PI)+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ environment=TaskRun.Environment.LOCAL,+ status=TaskRun.Status.COMPLETED,+ state={"pr_authorship_mode": "bot"},+ )++ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/resume_in_cloud/")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "Only cloud runs can be resumed in cloud")+ run.refresh_from_db()+ self.assertEqual(run.environment, TaskRun.Environment.LOCAL)+ self.assertEqual(run.status, TaskRun.Status.COMPLETED)+ mock_resume.assert_not_called()+@patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow")def test_resume_in_cloud_rejects_user_authorship_without_github_identity_when_no_repo(self, mock_resume):task = self.create_task(created_by=self.user)run = TaskRun.objects.create(task=task,team=self.team,- environment=TaskRun.Environment.LOCAL,+ environment=TaskRun.Environment.CLOUD,status=TaskRun.Status.COMPLETED,state={"pr_authorship_mode": "user"},)@@ -5594,7 +5634,7 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["code"], "github_authorization_required")run.refresh_from_db()- self.assertEqual(run.environment, TaskRun.Environment.LOCAL)+ self.assertEqual(run.environment, TaskRun.Environment.CLOUD)self.assertEqual(run.status, TaskRun.Status.COMPLETED)mock_resume.assert_not_called()@@ -5605,7 +5645,7 @@ class TestTaskRunAPI(BaseTaskAPITest):run = TaskRun.objects.create(task=task,team=self.team,- environment=TaskRun.Environment.LOCAL,+ environment=TaskRun.Environment.CLOUD,status=TaskRun.Status.COMPLETED,state={"pr_authorship_mode": "user"},)@@ -5627,7 +5667,7 @@ class TestTaskRunAPI(BaseTaskAPITest):run = TaskRun.objects.create(task=task,team=self.team,- environment=TaskRun.Environment.LOCAL,+ environment=TaskRun.Environment.CLOUD,status=TaskRun.Status.COMPLETED,state={"pr_authorship_mode": "user"},)@@ -7568,12 +7608,12 @@ class TestTaskRunAPI(BaseTaskAPITest):def test_download_artifact_walks_resume_chain(self, mock_read_bytes):"""A resumed run can download an artifact owned by the run it was forked from.- Cloud→cloud resume creates a new TaskRun with state.resume_from_run_id pointing- to the prior run; the prior run owns the git checkpoint pack/index artifacts.+ Cloud-to-cloud resume creates a new TaskRun with state.resume_from_run_id pointing+ to the prior run, which can own artifacts referenced by the resumed conversation."""- mock_read_bytes.return_value = b"prior run pack bytes"+ mock_read_bytes.return_value = b"prior run context"task = self.create_task()- prior_storage_path = "tasks/artifacts/team_1/task_x/run_prior/abc_pack.pack"+ prior_storage_path = "tasks/artifacts/team_1/task_x/run_prior/context.json"prior_run = TaskRun.objects.create(task=task,@@ -7582,9 +7622,9 @@ class TestTaskRunAPI(BaseTaskAPITest):artifacts=[{"id": uuid.uuid4().hex,- "name": "checkpoint.pack",+ "name": "context.json","type": "artifact",- "content_type": "application/x-git-packed-objects",+ "content_type": "application/json","storage_path": prior_storage_path,}],@@ -7604,7 +7644,7 @@ class TestTaskRunAPI(BaseTaskAPITest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.content, b"prior run pack bytes")+ self.assertEqual(response.content, b"prior run context")mock_read_bytes.assert_called_once_with(prior_storage_path, missing_ok=True)def test_find_artifact_in_resume_chain_direct_hit(self):@@ -7779,10 +7819,10 @@ class TestTaskRunAPI(BaseTaskAPITest):("chained_returns_ancestors_first",True, # has_ancestor- {"a": '{"notification":{"method":"_posthog/git_checkpoint","params":{"checkpointId":"ckpt-A"}}}\n'},+ {"a": '{"notification":{"method":"_posthog/legacy_event","params":{"source":"ancestor"}}}\n'},'{"notification":{"method":"session/update","params":{"update":{"sessionUpdate":"agent_message"}}}}\n',[- '{"notification":{"method":"_posthog/git_checkpoint","params":{"checkpointId":"ckpt-A"}}}',+ '{"notification":{"method":"_posthog/legacy_event","params":{"source":"ancestor"}}}','{"notification":{"method":"session/update","params":{"update":{"sessionUpdate":"agent_message"}}}}',],),@@ -12388,7 +12428,7 @@ class TestCloudUsageGate(BaseTaskAPITest):run = TaskRun.objects.create(task=task,team=self.team,- environment=TaskRun.Environment.LOCAL,+ environment=TaskRun.Environment.CLOUD,status=TaskRun.Status.COMPLETED,state={"pr_authorship_mode": "bot"},)@@ -12522,7 +12562,7 @@ class TestCloudUsageGate(BaseTaskAPITest):run = TaskRun.objects.create(task=task,team=self.team,- environment=TaskRun.Environment.LOCAL,+ environment=TaskRun.Environment.CLOUD,status=TaskRun.Status.COMPLETED,)@@ -12575,7 +12615,7 @@ class TestCloudUsageGate(BaseTaskAPITest):run = TaskRun.objects.create(task=task,team=self.team,- environment=TaskRun.Environment.LOCAL,+ environment=TaskRun.Environment.CLOUD,status=TaskRun.Status.COMPLETED,)diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex f45cc08734af..18205623110d 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -328,7 +328,12 @@ class TestFacadeReadsAndMappers(TestCase):def test_resume_in_cloud_rejects_invalid_origin(self):task = self._make_task(origin_product="automation")- run = task.create_run(environment=TaskRun.Environment.LOCAL)+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ environment=TaskRun.Environment.CLOUD,+ status=TaskRun.Status.COMPLETED,+ )outcome, resumed_run, _ = facade.resume_task_run_in_cloud(run.id,@@ -340,7 +345,7 @@ class TestFacadeReadsAndMappers(TestCase):self.assertEqual(outcome, "invalid_origin")self.assertIsNone(resumed_run)run.refresh_from_db()- self.assertEqual(run.environment, TaskRun.Environment.LOCAL)+ self.assertEqual(run.environment, TaskRun.Environment.CLOUD)def test_task_exists_and_visibility(self):task = self._make_task()diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 7069904b2625..415242d14318 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -875,7 +875,7 @@ class TestTaskRun(TestCase):self.assertEqual(state["pending_user_message_id"] == existing_id, keeps_id)@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")- def test_prepare_for_cloud_handoff_clears_stale_sandbox_routing(self, _publish):+ def test_prepare_for_cloud_resume_clears_stale_sandbox_routing(self, _publish):run = TaskRun.objects.create(task=self.task,team=self.team,@@ -892,19 +892,19 @@ class TestTaskRun(TestCase):},)- run.prepare_for_cloud_handoff()+ run.prepare_for_cloud_resume()self.assertNotIn("sandbox_id", run.state)self.assertNotIn("sandbox_url", run.state)self.assertNotIn("sandbox_jwt_kid", run.state)self.assertNotIn("sandbox_connect_token", run.state)- # The provider stamp must not survive; a stale `hogland` would otherwise outrank- # the EU guard and Modal-only fallbacks when the handed-off run re-resolves.+ # The provider stamp must not survive because a stale `hogland` would outrank+ # the EU guard and Modal-only fallbacks when the resumed run re-resolves.self.assertNotIn("sandbox_backend", run.state)self.assertNotIn("pending_user_message", run.state)self.assertNotIn("pending_user_artifact_ids", run.state)self.assertEqual(run.state["snapshot_external_id"], "snapshot-1")- self.assertTrue(run.state["handoff_resumed"])+ self.assertTrue(run.state["same_run_resume"])def test_s3_prefixes_keep_existing_logs_and_artifact_paths(self):run = TaskRun.objects.create(diff --git a/products/tasks/backend/tests/test_thread_updates.py b/products/tasks/backend/tests/test_thread_updates.pyindex bbd9ae9a7fb0..2d599f61ffc6 100644--- a/products/tasks/backend/tests/test_thread_updates.py+++ b/products/tasks/backend/tests/test_thread_updates.py@@ -228,8 +228,8 @@ class TestAgentThreadUpdates(TestCase):from products.tasks.backend.facade.api import upload_task_run_artifactsoutput = {"name": "summary.md", "type": "output", "content_bytes": b"v1", "content_type": "text/markdown"}- checkpoint = {- "name": "checkpoint.index",+ internal_artifact = {+ "name": "context.json","type": "artifact","content_bytes": b"internal state","content_type": "application/octet-stream",@@ -239,7 +239,7 @@ class TestAgentThreadUpdates(TestCase):self.task_run.id,self.task.id,self.team.id,- artifacts=[output, checkpoint],+ artifacts=[output, internal_artifact],uploaded_by="agent",)upload_task_run_artifacts(diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.pyindex 16dba0e6a4da..19b27fb05a77 100644--- a/products/tasks/backend/tests/test_workflow_dispatch.py+++ b/products/tasks/backend/tests/test_workflow_dispatch.py@@ -267,7 +267,7 @@ class TestWorkflowDispatchPersistence(TestCase):self, _shadow_enabled: Mock, increment_missing_intent: Mock) -> None:resumed_run = TaskRun.objects.create(- task=self.task_run.task, team=self.team, status=TaskRun.Status.QUEUED, state={"handoff_resumed": True}+ task=self.task_run.task, team=self.team, status=TaskRun.Status.QUEUED, state={"same_run_resume": True})uncovered = filter_uncovered_workflow_dispatch_run_ids([self.task_run.id, resumed_run.id])diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 7e8a30af58a1..47a656b59ac1 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3132,16 +3132,6 @@ export const RunStatusEnumApi = {Cancelled: 'cancelled',} as const-/**- * * `local` - local- */-export type TaskRunUpdateEnvironmentEnumApi =- (typeof TaskRunUpdateEnvironmentEnumApi)[keyof typeof TaskRunUpdateEnvironmentEnumApi]--export const TaskRunUpdateEnvironmentEnumApi = {- Local: 'local',-} as const-export interface PatchedTaskRunUpdateApi {/** Current execution status*@@ -3175,10 +3165,6 @@ export interface PatchedTaskRunUpdateApi {* @nullable*/error_message?: string | null- /** Transition a cloud run to local. Use the resume_in_cloud action to move a run into cloud.- *- * * `local` - local */- environment?: TaskRunUpdateEnvironmentEnumApi}/**diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex ee2ea58b92a5..ab7e54accd90 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -2022,7 +2022,7 @@ export const getTasksRunsClearConversationCreateUrl = (projectId: string, taskId}/**- * Record a `/clear` boundary in a finished run's log so the next run in the chain starts with an empty conversation. Its checkpoints, artifacts, and visible history are unaffected. Only for a finished run: an active one has an agent that owns the clear, so send `/clear` to it as an ordinary message instead.+ * Record a `/clear` boundary in a finished run's log so the next run in the chain starts with an empty conversation. Its artifacts and visible history are unaffected. Only for a finished run: an active one has an agent that owns the clear, so send `/clear` to it as an ordinary message instead.* @summary Clear conversation history*/export const tasksRunsClearConversationCreate = async (diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 5ce0681e83d5..fa8e46daf377 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -2454,13 +2454,6 @@ export const TasksRunsPartialUpdateBody = /* @__PURE__ */ zod.object({'State keys whose value to append to the list stored at that key, atomically under the row lock. Use instead of sending the whole list back through `state`, which loses concurrent appends to a read-modify-write race.'),error_message: zod.string().nullish().describe('Error message if execution failed'),- environment: zod- .enum(['local'])- .describe('\* `local` - local')- .optional()- .describe(- 'Transition a cloud run to local. Use the resume_in_cloud action to move a run into cloud.\n\n\* `local` - local'- ),})/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex eeb1d294b9e8..605d20c07cf2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -65776,16 +65776,6 @@ export namespace Schemas {*/export type PatchedTaskRunUpdateStateAppend = { [key: string]: unknown };- /**- * * `local` - local- */- export type TaskRunUpdateEnvironmentEnum = typeof TaskRunUpdateEnvironmentEnum[keyof typeof TaskRunUpdateEnvironmentEnum];--- export const TaskRunUpdateEnvironmentEnum = {- Local: 'local',- } as const;-export interface PatchedTaskRunUpdate {/** Current execution status*@@ -65819,10 +65809,6 @@ export namespace Schemas {* @nullable*/error_message?: string | null;- /** Transition a cloud run to local. Use the resume_in_cloud action to move a run into cloud.- *- * * `local` - local */- environment?: TaskRunUpdateEnvironmentEnum;}/**