Skip to content

: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.

fix(tasks): stop reconciler from cloud-dispatching local desktop runs (#67702)

Alessandro Pogliaghi099b8024e2b0
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 367d78ad9308..212194a8ebf4 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -245,7 +245,9 @@ def redispatch_orphaned_queued_task_runs() -> None:
RECONCILE_AFTER = datetime.timedelta(minutes=5)
# Janitor sweep is intentionally cross-team — it runs without a team context.
- candidate_ids = tasks_facade.get_stale_queued_task_run_ids(RECONCILE_AFTER, BATCH_SIZE)
+ # cloud_only: local (desktop) runs idle in QUEUED by design while the desktop agent drives
+ # them; cloud-dispatching one hijacks the live session and eventually marks it failed.
+ candidate_ids = tasks_facade.get_stale_queued_task_run_ids(RECONCILE_AFTER, BATCH_SIZE, cloud_only=True)
outcomes: dict[str, int] = {}
for run_id in candidate_ids:
try:
@@ -264,6 +266,7 @@ def redispatch_orphaned_queued_task_runs() -> None:
recovered=outcomes.get("recovered", 0),
already_running=outcomes.get("already_running", 0),
left_queue=outcomes.get("left_queue", 0),
+ skipped_local=outcomes.get("skipped_local", 0),
errors=outcomes.get("error", 0),
batch_size=BATCH_SIZE,
saturated=saturated,
diff --git a/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py b/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py
index 6f917ce10fd4..59c032c1797b 100644
--- a/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py
+++ b/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py
@@ -31,9 +31,14 @@ class TestRedispatchOrphanedQueuedTaskRuns(TestCase):
origin_product=Task.OriginProduct.USER_CREATED,
)
- def _queued_run(self, updated_age: datetime.timedelta) -> "TaskRun":
+ def _queued_run(self, updated_age: datetime.timedelta, environment: str | None = None) -> "TaskRun":
TaskRun = apps.get_model("tasks", "TaskRun")
- run = TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.QUEUED)
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.QUEUED,
+ environment=environment or TaskRun.Environment.CLOUD,
+ )
now = timezone.now()
TaskRun.objects.filter(pk=run.pk).update(created_at=now - updated_age, updated_at=now - updated_age)
return run
@@ -60,6 +65,20 @@ class TestRedispatchOrphanedQueuedTaskRuns(TestCase):
mock_redispatch.assert_not_called()
+ def test_never_redispatches_local_environment_runs(self) -> None:
+ # Local (desktop-driven) runs sit in QUEUED by design while the desktop agent works;
+ # the reconciler once cloud-dispatched them, hijacking and failing live local sessions.
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ self._queued_run(datetime.timedelta(minutes=10), environment=TaskRun.Environment.LOCAL)
+ cloud_run = self._queued_run(datetime.timedelta(minutes=10))
+
+ with patch(
+ "products.tasks.backend.facade.api.redispatch_task_run", return_value="recovered"
+ ) as mock_redispatch:
+ redispatch_orphaned_queued_task_runs()
+
+ mock_redispatch.assert_called_once_with(cloud_run.id)
+
def test_one_failure_does_not_block_the_sweep(self) -> None:
self._queued_run(datetime.timedelta(minutes=10))
self._queued_run(datetime.timedelta(minutes=11))
diff --git a/products/tasks/backend/exceptions.py b/products/tasks/backend/exceptions.py
index 7f3671934505..056735c8550c 100644
--- a/products/tasks/backend/exceptions.py
+++ b/products/tasks/backend/exceptions.py
@@ -77,6 +77,18 @@ class SandboxExecutionError(ProcessTaskTransientError):
pass
+class SandboxMissingRepositoryError(ProcessTaskFatalError):
+ """The repository directory the agent-server needs as its cwd is absent from the sandbox.
+
+ Happens when a run reaches agent-server start without a clone — no snapshot restored and no
+ usable GitHub credentials. Retrying cannot make the directory appear, so fail immediately
+ with the real reason instead of burning health-check timeouts on a server that can never
+ open a session.
+ """
+
+ pass
+
+
class SandboxNotRunningError(SandboxExecutionError):
"""Sandbox is not in a running state."""
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 677dce20b8d3..b1430078b12f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -537,21 +537,24 @@ def get_stale_queued_task_run_ids(
*,
created_hard_cap: timedelta | None = None,
hard_cap_min_queued: timedelta = timedelta(hours=1),
+ cloud_only: bool = False,
) -> list[UUID]:
"""Ids of runs stuck in QUEUED, by ``updated_at`` age or an optional ``created_at`` backstop.
+ ``cloud_only`` restricts the sweep to cloud-environment runs. Local (desktop) runs sit in
+ QUEUED by design while the desktop agent drives them, so dispatch-recovery callers must
+ exclude them — cloud-dispatching one hijacks the user's live local session.
+
Intentionally cross-team — the janitor sweep runs without a team context.
"""
now = django_timezone.now()
stale = Q(updated_at__lt=now - older_than)
if created_hard_cap is not None:
stale |= Q(created_at__lt=now - created_hard_cap, updated_at__lt=now - hard_cap_min_queued)
- return list(
- TaskRun.objects.filter(status=TaskRun.Status.QUEUED) # nosemgrep: celery-task-team-scope-audit
- .filter(stale)
- .order_by("updated_at")
- .values_list("id", flat=True)[:limit]
- )
+ queryset = TaskRun.objects.filter(status=TaskRun.Status.QUEUED) # nosemgrep: celery-task-team-scope-audit
+ if cloud_only:
+ queryset = queryset.filter(environment=TaskRun.Environment.CLOUD)
+ return list(queryset.filter(stale).order_by("updated_at").values_list("id", flat=True)[:limit])
def get_stale_prewarmed_queued_task_run_ids(older_than: timedelta, limit: int) -> list[UUID]:
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index ae8b33e0f074..268a90147db9 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -133,6 +133,12 @@ def is_public_sandbox_repo(repository: str | None) -> bool:
return repository is not None and repository.lower() in PUBLIC_SANDBOX_REPOS
+def sandbox_repo_path(repository: str) -> str:
+ """Absolute path an ``org/repo`` is cloned to inside the sandbox (the agent-server's cwd)."""
+ org, repo = repository.lower().split("/")
+ return f"{WORKING_DIR}/repos/{org}/{repo}"
+
+
def redact_sandbox_command(command: str) -> str:
return SENSITIVE_AGENT_RUNTIME_ENV_PATTERN.sub(r"\g<name>=<redacted>", command)
@@ -209,7 +215,7 @@ class SandboxBase(ABC):
else f"https://github.com/{org}/{repo}.git"
)
- target_path = f"{WORKING_DIR}/repos/{org}/{repo}"
+ target_path = sandbox_repo_path(repository)
org_path = f"{WORKING_DIR}/repos/{org}"
depth_flag = f" --depth {shlex.quote('1')}" if shallow else ""
@@ -460,6 +466,7 @@ __all__ = [
"SandboxBase",
"WORKING_DIR",
"parse_sandbox_repo_mount_map",
+ "sandbox_repo_path",
"get_sandbox_class",
"get_sandbox_class_for_backend",
"wait_for_health_check",
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 0e2f73ecc49a..c8aa71442904 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -326,7 +326,8 @@ def redispatch_orphaned_task_run(run_id: str) -> str:
Returns an outcome for metrics/logs: ``recovered`` (workflow started), ``already_running``
(a workflow already exists), ``left_queue`` (row is no longer QUEUED), ``skipped_prewarmed``
- (owned by the prewarmed reaper), ``error`` (transient).
+ (owned by the prewarmed reaper), ``skipped_local`` (desktop-driven run, nothing to recover),
+ ``error`` (transient).
"""
from temporalio.exceptions import WorkflowAlreadyStartedError # noqa: PLC0415 — keep temporalio off the import path
@@ -338,6 +339,13 @@ def redispatch_orphaned_task_run(run_id: str) -> str:
if task_run is None:
return "left_queue"
+ # Local (desktop) runs idle in QUEUED while the user's local agent drives them — there is no
+ # lost dispatch to recover. Starting a cloud workflow here would hijack the live session: the
+ # sandbox boots without the repo ever being cloned, burns its retries, and marks the user's
+ # run FAILED. The sweep already filters these out (cloud_only); this guards direct callers.
+ if task_run.environment == TaskRun.Environment.LOCAL:
+ return "skipped_local"
+
# Prewarmed runs idle in QUEUED awaiting the user's first message; the dedicated prewarmed
# reaper *kills* them if never activated. Recovering one would boot an agent with no prompt
# (and re-dispatching without the prewarmed flag would change its boot behaviour), so skip.
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 28212f745f03..997219ef66cb 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -1,3 +1,4 @@
+import shlex
import threading
from dataclasses import dataclass
@@ -13,9 +14,9 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify
from posthog.temporal.oauth import PosthogMcpScopes
-from products.tasks.backend.exceptions import OAuthTokenError, SandboxExecutionError
+from products.tasks.backend.exceptions import OAuthTokenError, SandboxExecutionError, SandboxMissingRepositoryError
from products.tasks.backend.logic.services.connection_token import create_sandbox_event_ingest_token
-from products.tasks.backend.logic.services.sandbox import REPO_READY_FILE, Sandbox, SandboxBase
+from products.tasks.backend.logic.services.sandbox import REPO_READY_FILE, Sandbox, SandboxBase, sandbox_repo_path
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.metrics import StepTimer, record_agent_server_session_init_ms
from products.tasks.backend.temporal.oauth import create_oauth_access_token
@@ -94,6 +95,37 @@ def _resolve_protected_base_branch(ctx: TaskProcessingContext) -> str | None:
return branch
+def _ensure_repository_on_disk(ctx: TaskProcessingContext, sandbox: SandboxBase) -> None:
+ """Fail fast when the repository the agent-server will use as its cwd was never materialized.
+
+ A run can reach this point without a clone: no snapshot restored and no usable GitHub
+ credentials (``will_clone`` is false in the workflow). The agent-server then boots against a
+ missing working directory, every ACP ``session/new`` fails, and the health wait times out —
+ repeated 5-minute attempts surfacing as a misleading "Failed to start agent server". Check
+ the directory upfront and fail non-retryably with the actual reason instead.
+ """
+ if not ctx.repository:
+ return
+ repo_path = sandbox_repo_path(ctx.repository)
+ result = sandbox.execute(f"test -d {shlex.quote(repo_path)}", timeout_seconds=10)
+ if result.exit_code == 0:
+ return
+ raise SandboxMissingRepositoryError(
+ f"Repository {ctx.repository} is not present in the sandbox at {repo_path} — it was never "
+ "cloned (no snapshot restored and no usable GitHub credentials for this task)",
+ {
+ "task_id": ctx.task_id,
+ "run_id": ctx.run_id,
+ "sandbox_id": sandbox.id,
+ "repository": ctx.repository,
+ "repo_path": repo_path,
+ "github_integration_id": ctx.github_integration_id,
+ "github_user_integration_id": ctx.github_user_integration_id,
+ },
+ cause=RuntimeError(f"missing repository directory {repo_path}"),
+ )
+
+
@dataclass
class StartAgentServerInput:
context: TaskProcessingContext
@@ -314,6 +346,10 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
emit_agent_log(ctx.run_id, "debug", "Starting agent server")
sandbox = Sandbox.get_by_id(input.sandbox_id)
+ # Classic (non-deferred) path only: any clone has already happened by now, so a missing
+ # repo directory can never appear later. The deferred/overlap path clones in parallel
+ # and gates the session on the repo-ready barrier instead.
+ _ensure_repository_on_disk(ctx, sandbox)
params = _prepare_launch(ctx, input.posthog_mcp_scopes)
with StepTimer("agent_server_ready"):
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 839303b79318..4330b14ddf7e 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -1,8 +1,11 @@
import pytest
+from products.tasks.backend.exceptions import SandboxMissingRepositoryError
+from products.tasks.backend.logic.services.sandbox import ExecutionResult, sandbox_repo_path
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.start_agent_server import (
StartAgentServerInput,
+ _ensure_repository_on_disk,
_resolve_protected_base_branch,
start_agent_server,
)
@@ -80,6 +83,40 @@ def test_resolve_protected_base_falls_back_to_branch_on_error(mocker) -> None:
assert _resolve_protected_base_branch(context) == "posthog-code/fix"
+def test_ensure_repository_on_disk_passes_when_repo_present(mocker) -> None:
+ sandbox = mocker.Mock()
+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
+
+ _ensure_repository_on_disk(_context(repository="PostHog/posthog"), sandbox)
+
+ # The precheck must probe the same path the clone writes to.
+ assert sandbox_repo_path("PostHog/posthog") in sandbox.execute.call_args.args[0]
+
+
+def test_ensure_repository_on_disk_fails_non_retryably_when_repo_missing(mocker) -> None:
+ # Without this, a run whose repo was never cloned (no snapshot, no GitHub credentials) burns
+ # repeated 5-minute health-check timeouts and fails with a misleading "Failed to start agent
+ # server" instead of the actual reason.
+ sandbox = mocker.Mock()
+ sandbox.id = "sandbox-id"
+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=1)
+ mocker.patch("products.tasks.backend.exceptions.capture_exception")
+
+ with pytest.raises(SandboxMissingRepositoryError) as exc_info:
+ _ensure_repository_on_disk(_context(repository="PostHog/posthog"), sandbox)
+
+ assert exc_info.value.non_retryable is True
+ assert "never" in str(exc_info.value)
+
+
+def test_ensure_repository_on_disk_skips_repo_less_runs(mocker) -> None:
+ sandbox = mocker.Mock()
+
+ _ensure_repository_on_disk(_context(repository=None), sandbox)
+
+ sandbox.execute.assert_not_called()
+
+
async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker) -> None:
context = _context(sandbox_event_ingest_enabled=True)
sandbox = mocker.Mock()
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index 1326582952da..d483de707df1 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -60,6 +60,7 @@ def _build_context(
state: dict | None = None,
use_modal_resume_snapshots: bool = True,
sandbox_event_ingest_enabled: bool = False,
+ environment: str | None = None,
) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-id",
@@ -70,6 +71,7 @@ def _build_context(
github_integration_id=github_integration_id,
repository=repository,
distinct_id="distinct-id",
+ environment=environment,
create_pr=True,
state=state or {},
_branch="feature-branch",
@@ -408,6 +410,34 @@ class TestProcessTaskWorkflowUnit:
read_sandbox_logs_mock.assert_awaited_once_with("sandbox-123")
cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123")
+ async def test_run_refuses_local_environment_run_without_touching_it(self, monkeypatch):
+ # If a local (desktop-driven) run is ever cloud-dispatched again (e.g. the reconciler's
+ # environment filter regresses), the workflow must bail out without provisioning anything
+ # and — critically — without flipping the live local session's status.
+ workflow = ProcessTaskWorkflow()
+ update_task_run_status_mock = AsyncMock()
+ get_sandbox_mock = AsyncMock()
+
+ monkeypatch.setattr(
+ workflow,
+ "_get_task_processing_context",
+ AsyncMock(return_value=_build_context(github_integration_id=None, environment="local")),
+ )
+ monkeypatch.setattr(workflow, "_update_task_run_status", update_task_run_status_mock)
+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())
+ monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())
+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())
+ monkeypatch.setattr(workflow, "_get_sandbox_for_repository", get_sandbox_mock)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+
+ result = await workflow.run(ProcessTaskInput(run_id="run-id"))
+
+ assert result.success is False
+ assert "local" in (result.error or "")
+ update_task_run_status_mock.assert_not_awaited()
+ get_sandbox_mock.assert_not_awaited()
+
async def test_run_marks_failed_when_context_load_fails(self, monkeypatch):
workflow = ProcessTaskWorkflow()
get_task_processing_context_mock = AsyncMock(side_effect=RuntimeError("database connection closed"))
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 4172a93cb0dd..5199ba70b3aa 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -152,6 +152,11 @@ _PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING = "tasks-drop-slack-post-after-prov
# Two-step deprecate-then-delete cleanup lifecycle as above.
_PATCH_ID_SLACK_AGENT_DESIGN_STATUS = "tasks-slack-agent-design-status"
+# Gates the refusal to execute local-environment (desktop-driven) runs. Pre-guard
+# histories of such runs proceeded into provisioning; the marker keeps their replays
+# deterministic. Same two-step cleanup lifecycle as above.
+_PATCH_ID_SKIP_LOCAL_ENVIRONMENT_RUNS = "tasks-skip-local-environment-runs"
+
def _deprecate_ci_follow_up_pr_context_patch() -> None:
workflow.deprecate_patch(_PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT)
@@ -428,6 +433,21 @@ class ProcessTaskWorkflow(PostHogWorkflow):
try:
self._context = await self._get_task_processing_context(input)
self._posthog_mcp_scopes = input.posthog_mcp_scopes
+ # A local-environment run is driven by the user's desktop agent — QUEUED does not
+ # mean "awaiting a cloud workflow". Executing it here would boot a sandbox the repo
+ # was never cloned into and, once the attempts burn out, stomp the live local
+ # session's status. Refuse without touching the run. The environment check comes
+ # first so cloud runs (and unit tests exercising them outside a workflow event
+ # loop) never call ``workflow.patched``.
+ if self.context.environment == "local" and workflow.patched(_PATCH_ID_SKIP_LOCAL_ENVIRONMENT_RUNS):
+ workflow.logger.warning(
+ "Refusing to process local-environment run in cloud workflow",
+ extra={"run_id": run_id, "task_id": self.context.task_id},
+ )
+ return ProcessTaskOutput(
+ success=False,
+ error="Run environment is 'local' (desktop-driven); refusing to execute it as a cloud workflow",
+ )
# See _PATCH_ID_SLACK_AGENT_DESIGN_STATUS. Short-circuit on
# ``_slack_thread_context`` so non-Slack runs never call the
# workflow-scoped ``workflow.patched`` API (unit tests that
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index d474df166d14..43c6376a145b 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -195,13 +195,24 @@ class TestFacadeReadsAndMappers(TestCase):
task = self._make_task()
fresh = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
stale = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
+ stale_local = TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.QUEUED, environment=TaskRun.Environment.LOCAL
+ )
past = django_timezone.now() - timedelta(hours=48)
- TaskRun.objects.filter(pk=stale.pk).update(updated_at=past)
+ TaskRun.objects.filter(pk__in=[stale.pk, stale_local.pk]).update(updated_at=past)
stale_ids = facade.get_stale_queued_task_run_ids(older_than=timedelta(hours=24), limit=100)
self.assertIn(stale.id, stale_ids)
+ # The unrestricted sweep (24h killer) still reaps abandoned local runs.
+ self.assertIn(stale_local.id, stale_ids)
self.assertNotIn(fresh.id, stale_ids)
+ # The dispatch reconciler must never see local (desktop-driven) runs — re-dispatching
+ # one starts a cloud workflow that hijacks and eventually fails the live local session.
+ cloud_ids = facade.get_stale_queued_task_run_ids(older_than=timedelta(hours=24), limit=100, cloud_only=True)
+ self.assertIn(stale.id, cloud_ids)
+ self.assertNotIn(stale_local.id, cloud_ids)
+
with patch("products.tasks.backend.push_dispatcher.notify_task_run_failed"):
self.assertTrue(facade.fail_task_run(stale.id, "boom"))
# already-failed run is no longer QUEUED -> no-op
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index 6c5000a4dcdd..72d55bf43f36 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -193,7 +193,11 @@ class TestRedispatchOrphanedTaskRun(TestCase):
)
def _orphaned_run(
- self, pending_dispatch: dict | None = None, run_source: str | None = None, prewarmed: bool = False
+ self,
+ pending_dispatch: dict | None = None,
+ run_source: str | None = None,
+ prewarmed: bool = False,
+ environment: str = TaskRun.Environment.CLOUD,
) -> TaskRun:
state: dict = {}
if pending_dispatch is not None:
@@ -202,7 +206,9 @@ class TestRedispatchOrphanedTaskRun(TestCase):
state["run_source"] = run_source
if prewarmed:
state["prewarmed"] = True
- return TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.QUEUED, state=state)
+ return TaskRun.objects.create(
+ task=self.task, team=self.team, status=TaskRun.Status.QUEUED, state=state, environment=environment
+ )
def _run_reconcile(self, run: TaskRun, start_workflow: Mock) -> str:
client = Mock()
@@ -282,6 +288,19 @@ class TestRedispatchOrphanedTaskRun(TestCase):
self.assertEqual(outcome, "left_queue")
start_workflow.assert_not_called()
+ def test_skips_local_environment_run(self) -> None:
+ # A local run sits in QUEUED while the user's desktop agent drives it; cloud-dispatching
+ # it would hijack the live session (no repo in the sandbox) and later mark the run failed.
+ run = self._orphaned_run(environment=TaskRun.Environment.LOCAL)
+ start_workflow = AsyncMock()
+
+ outcome = self._run_reconcile(run, start_workflow)
+
+ self.assertEqual(outcome, "skipped_local")
+ start_workflow.assert_not_called()
+ run.refresh_from_db()
+ self.assertEqual(run.status, TaskRun.Status.QUEUED)
+
def test_skips_prewarmed_run(self) -> None:
# Prewarmed runs are owned by the prewarmed reaper (it kills them); re-dispatching one would
# boot an agent with no user prompt and drop the prewarmed flag, changing boot behaviour.