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.

feat(tasks): isolate behind a facade with contracts (#64627)

Peter Kirkhamadc5cbe79b60
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 4bf999c4211b..d9902d89edfb 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -176,8 +176,8 @@ for example, a discovery pass followed by per-item research, then assessment and
### Example
```python
-from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
-from products.tasks.backend.services.custom_prompt_runner import CustomPromptSandboxContext
+from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import MultiTurnSession
+from products.tasks.backend.logic.services.custom_prompt_internals import CustomPromptSandboxContext
# 1. Start: discovery turn
session, candidates = await MultiTurnSession.start(
@@ -209,7 +209,7 @@ await session.end()
### Reference implementation
-See `products/tasks/backend/services/mts_example/` for a complete working example.
+See `products/tasks/backend/logic/services/mts_example/` for a complete working example.
It runs a multi-turn agent that discovers "cursed" identifiers in a repo,
researches each one, and produces output in the shape Signals consumes:
@@ -223,7 +223,7 @@ Run it locally (DEBUG only):
DEBUG=1 python manage.py demo_mts_example --team-id <id> --user-id <id>
```
-See the [example README](https://github.com/PostHog/posthog/blob/master/products/tasks/backend/services/mts_example/README.md) for details on adapting it to your own use case.
+See the [example README](https://github.com/PostHog/posthog/blob/master/products/tasks/backend/logic/services/mts_example/README.md) for details on adapting it to your own use case.
## Code execution
diff --git a/ee/hogai/chat_agent/toolkit.py b/ee/hogai/chat_agent/toolkit.py
index 563336c7eb59..d19efd974a55 100644
--- a/ee/hogai/chat_agent/toolkit.py
+++ b/ee/hogai/chat_agent/toolkit.py
@@ -7,7 +7,7 @@ from django.conf import settings
from langchain_core.runnables import RunnableConfig
from products.skills.backend.tools.skills import GetLLMSkillFileTool, GetLLMSkillTool, ListLLMSkillsTool
-from products.tasks.backend.max_tools import (
+from products.tasks.backend.facade.max_tools import (
CreateTaskTool,
GetTaskRunLogsTool,
GetTaskRunTool,
diff --git a/ee/hogai/eval/sandboxed/config.py b/ee/hogai/eval/sandboxed/config.py
index cf9bc1ff4646..73807a6b7660 100644
--- a/ee/hogai/eval/sandboxed/config.py
+++ b/ee/hogai/eval/sandboxed/config.py
@@ -5,7 +5,7 @@ from typing import Any
from pydantic import BaseModel, ConfigDict, Field
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
class SandboxedEvalCase(BaseModel):
diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.py
index 2bf92e998bc0..403cb3a94679 100644
--- a/ee/hogai/eval/sandboxed/conftest.py
+++ b/ee/hogai/eval/sandboxed/conftest.py
@@ -19,9 +19,12 @@ from temporalio.testing import WorkflowEnvironment
from posthog.temporal.common.worker import create_worker
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
-from products.tasks.backend.services.local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache
-from products.tasks.backend.temporal import (
+from products.tasks.backend.facade.agents import (
+ ENV_LOCAL_SKILLS_HOST_PATH,
+ CustomPromptSandboxContext,
+ LocalSkillsCache,
+)
+from products.tasks.backend.facade.temporal import (
ACTIVITIES as TASKS_ACTIVITIES,
WORKFLOWS as TASKS_WORKFLOWS,
)
@@ -575,7 +578,10 @@ class SandboxedDemoData:
self.agent_model = agent_model
def make_context(self, case_label: str) -> CustomPromptSandboxContext:
- from products.tasks.backend.models import CodeInvite, CodeInviteRedemption
+ from django.apps import apps
+
+ CodeInvite = apps.get_model("tasks", "CodeInvite")
+ CodeInviteRedemption = apps.get_model("tasks", "CodeInviteRedemption")
org, team, user = copy_demo_data_to_new_team(self.master_team_id, self._django_db_blocker, label=case_label)
create_core_memory(team, self._django_db_blocker)
diff --git a/ee/hogai/eval/sandboxed/experiments/seeders.py b/ee/hogai/eval/sandboxed/experiments/seeders.py
index 59b3ebce0463..177f0ddecded 100644
--- a/ee/hogai/eval/sandboxed/experiments/seeders.py
+++ b/ee/hogai/eval/sandboxed/experiments/seeders.py
@@ -14,7 +14,7 @@ import logging
from datetime import UTC, datetime, timedelta
from typing import Any
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
logger = logging.getLogger(__name__)
diff --git a/ee/hogai/eval/sandboxed/runner.py b/ee/hogai/eval/sandboxed/runner.py
index 705c9c99b751..0b7dcbdbaf29 100644
--- a/ee/hogai/eval/sandboxed/runner.py
+++ b/ee/hogai/eval/sandboxed/runner.py
@@ -8,11 +8,7 @@ import logging
import subprocess
from dataclasses import dataclass
-from products.tasks.backend.services.custom_prompt_internals import (
- CustomPromptSandboxContext,
- create_task_and_trigger,
- poll_for_turn,
-)
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext, create_task_and_trigger, poll_for_turn
from .config import AgentArtifacts, SandboxedEvalCase
diff --git a/ee/hogai/eval/sandboxed/seeders/insight.py b/ee/hogai/eval/sandboxed/seeders/insight.py
index 85351718014a..84ea09d0f917 100644
--- a/ee/hogai/eval/sandboxed/seeders/insight.py
+++ b/ee/hogai/eval/sandboxed/seeders/insight.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import logging
from typing import Any
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
from ee.hogai.eval.sandboxed.seeders.common import LOOKUP_PREFIX, NameProviders, make_name_providers
diff --git a/ee/hogai/eval/sandboxed/seeders/survey.py b/ee/hogai/eval/sandboxed/seeders/survey.py
index e098bc308989..ea4e5db6250c 100644
--- a/ee/hogai/eval/sandboxed/seeders/survey.py
+++ b/ee/hogai/eval/sandboxed/seeders/survey.py
@@ -6,7 +6,7 @@ import logging
from typing import Any
from products.feature_flags.backend.models.feature_flag import FeatureFlag
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
logger = logging.getLogger(__name__)
diff --git a/ee/hogai/eval/sandboxed/surveys/eval_surveys.py b/ee/hogai/eval/sandboxed/surveys/eval_surveys.py
index c41159c89236..7c5b07e0df61 100644
--- a/ee/hogai/eval/sandboxed/surveys/eval_surveys.py
+++ b/ee/hogai/eval/sandboxed/surveys/eval_surveys.py
@@ -16,7 +16,7 @@ from typing import Any
import pytest
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
from ee.hogai.eval.sandboxed.base import SandboxedPublicEval
from ee.hogai.eval.sandboxed.config import SandboxedEvalCase
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.py
index ee6b5d1ecf31..675457156e41 100644
--- a/ee/hogai/sandbox/executor.py
+++ b/ee/hogai/sandbox/executor.py
@@ -21,10 +21,9 @@ from posthog.models.user import User
from posthog.temporal.common.client import sync_connect
from products.posthog_ai.backend.models.assistant import Conversation
-from products.tasks.backend.models import Task, TaskRun
-from products.tasks.backend.stream.redis_stream import TaskRunRedisStream, TaskRunStreamError, get_task_run_stream_key
-from products.tasks.backend.temporal.client import execute_task_processing_workflow
-from products.tasks.backend.temporal.process_task.workflow import ProcessTaskWorkflow
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.streams import TaskRunRedisStream, TaskRunStreamError, get_task_run_stream_key
+from products.tasks.backend.facade.temporal import ProcessTaskWorkflow, execute_task_processing_workflow
from ee.hogai.api.serializers import ConversationMinimalSerializer
from ee.hogai.sandbox.mapping import get_sandbox_mapping, set_sandbox_mapping
@@ -77,9 +76,8 @@ def handle_sandbox_message(
run_id = mapping["run_id"]
start_id = _get_latest_stream_id(run_id)
- try:
- task_run = TaskRun.objects.select_related("task").get(id=run_id, team=team)
- except TaskRun.DoesNotExist:
+ task_run = tasks_facade.get_task_run(run_id, team_id=team.id)
+ if task_run is None:
raise exceptions.ValidationError("Sandbox session no longer exists.")
if task_run.is_terminal:
@@ -87,8 +85,8 @@ def handle_sandbox_message(
if not snapshot_ext_id:
raise exceptions.ValidationError("Sandbox session has ended and no snapshot is available.")
- task = task_run.task
- new_run = task.create_run(
+ new_run = tasks_facade.create_run(
+ task_run.task_id,
mode="interactive",
extra_state={
"snapshot_external_id": snapshot_ext_id,
@@ -101,12 +99,12 @@ def handle_sandbox_message(
conversation.sandbox_run_id = new_run.id
conversation.save(update_fields=["sandbox_run_id"])
- set_sandbox_mapping(conversation_id, str(task.id), run_id)
+ set_sandbox_mapping(conversation_id, str(task_run.task_id), run_id)
execute_task_processing_workflow(
- task_id=str(task.id),
+ task_id=str(task_run.task_id),
run_id=run_id,
- team_id=task.team_id,
+ team_id=task_run.team_id,
user_id=user.pk,
create_pr=False,
)
@@ -143,11 +141,11 @@ def handle_sandbox_message(
# First message: create task + run
# TODO(@tatoalo): hardcoding repo for now, already built repo selection wiring
try:
- task = Task.create_and_run(
+ created = tasks_facade.create_and_run_task(
team=team,
title=content[:80],
description=content,
- origin_product=Task.OriginProduct.USER_CREATED,
+ origin_product=tasks_facade.TaskOriginProduct.USER_CREATED,
user_id=user.pk,
repository="posthog/posthog",
create_pr=False,
@@ -157,15 +155,14 @@ def handle_sandbox_message(
except ValueError:
raise exceptions.ValidationError("Failed to create sandbox task.")
- task_run_or_none = task.latest_run
- if not task_run_or_none:
+ if created.latest_run is None:
raise exceptions.ValidationError("Failed to create sandbox task run.")
- task_run = task_run_or_none
+ task_run = created.latest_run
run_id = str(task_run.id)
- set_sandbox_mapping(conversation_id, str(task.id), run_id)
+ set_sandbox_mapping(conversation_id, str(created.task_id), run_id)
- conversation.sandbox_task_id = task.id
+ conversation.sandbox_task_id = created.task_id
conversation.sandbox_run_id = task_run.id
conversation.save(update_fields=["sandbox_task_id", "sandbox_run_id"])
diff --git a/posthog/api/file_system/folder_context_generation.py b/posthog/api/file_system/folder_context_generation.py
index 4dae9dfca0ab..3c7a1ec7cd23 100644
--- a/posthog/api/file_system/folder_context_generation.py
+++ b/posthog/api/file_system/folder_context_generation.py
@@ -2,7 +2,7 @@ from uuid import UUID
from rest_framework import serializers
-from products.tasks.backend.models import Task
+from products.tasks.backend.facade import api as tasks_facade
class ContextGenerationSerializer(serializers.Serializer):
@@ -25,6 +25,6 @@ class ContextGenerationSetSerializer(serializers.Serializer):
if value is None:
return None
team = self.context["folder_team"]
- if not Task.objects.filter(id=value, team=team).exists():
+ if not tasks_facade.task_exists(value, team.id):
raise serializers.ValidationError("No task with this id exists in this team.", code="invalid")
return value
diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.py
index 9155c04bed20..b38bf0b5800d 100644
--- a/posthog/api/file_system/registrations.py
+++ b/posthog/api/file_system/registrations.py
@@ -19,8 +19,7 @@ from posthog.models.activity_logging.model_activity import is_impersonated_sessi
from posthog.models.user import User
from products.cdp.backend.models.hog_functions.utils import humanize_hog_function_type
-from products.tasks.backend.models import Task as _Task
-from products.tasks.backend.visibility import task_visibility_q
+from products.tasks.backend.facade import api as tasks_facade
def _first_non_blank(*values: str | None) -> str | None:
@@ -292,7 +291,7 @@ def _ensure_task_visible_to_user(task: Any, user: Any | None) -> None:
# signal-pipeline tasks and legacy unowned tasks). Without this, anyone with file system
# write access could delete or restore another user's filed task via the generic flow.
user_id = getattr(user, "id", None)
- if not _Task.objects.filter(task_visibility_q(user_id), pk=task.id).exists():
+ if not tasks_facade.is_task_visible_to_user(task.id, user_id):
raise PermissionDenied("You do not have permission to modify this task.")
diff --git a/posthog/api/file_system/test/test_folder_context_generation.py b/posthog/api/file_system/test/test_folder_context_generation.py
index b553c6079750..efb3cd64afa8 100644
--- a/posthog/api/file_system/test/test_folder_context_generation.py
+++ b/posthog/api/file_system/test/test_folder_context_generation.py
@@ -1,14 +1,17 @@
-from typing import cast
+from typing import TYPE_CHECKING, cast
from posthog.test.base import APIBaseTest
+from django.apps import apps
+
from parameterized import parameterized
from rest_framework import status
from posthog.models import Organization, Team
from posthog.models.file_system.file_system import FileSystem
-from products.tasks.backend.models import Task
+if TYPE_CHECKING:
+ from products.tasks.backend.models import Task
class TestDesktopFolderContextGenerationAPI(APIBaseTest):
@@ -32,7 +35,8 @@ class TestDesktopFolderContextGenerationAPI(APIBaseTest):
def _instructions_url(self, folder_id: str) -> str:
return f"/api/projects/{self.team.id}/desktop_file_system/{folder_id}/instructions/"
- def _create_task(self, team: Team | None = None) -> Task:
+ def _create_task(self, team: Team | None = None) -> "Task":
+ Task = apps.get_model("tasks", "Task")
return Task.objects.create(
team=team or self.team,
title="Generate CONTEXT.md",
diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.py
index 30214ea5abdb..9ac506e4a7af 100644
--- a/posthog/api/test/test_github_installation_webhook.py
+++ b/posthog/api/test/test_github_installation_webhook.py
@@ -138,7 +138,7 @@ class TestGitHubInstallationWebhook(TestCase):
user=self.user, kind="github", integration_id=installation_id, config={}, sensitive_config={}
)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
def test_deleted_removes_all_rows_and_does_not_call_github(self, mock_client_request, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -153,7 +153,7 @@ class TestGitHubInstallationWebhook(TestCase):
# Inbound side must never call out to GitHub (loop prevention).
mock_client_request.assert_not_called()
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_deleted_with_no_matching_rows_is_idempotent(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -162,7 +162,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(response.status_code, 200)
@parameterized.expand([("suspend",), ("unsuspend",)])
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_reversible_action_does_not_delete_rows(self, action, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
self._team_integration("12345")
@@ -172,7 +172,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(response.status_code, 200)
self.assertTrue(Integration.objects.filter(kind="github", integration_id="12345").exists())
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_missing_installation_id_returns_200(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -180,7 +180,7 @@ class TestGitHubInstallationWebhook(TestCase):
self.assertEqual(response.status_code, 200)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_invalid_signature_returns_403_and_keeps_rows(self, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
self._team_integration("12345")
diff --git a/posthog/asgi.py b/posthog/asgi.py
index c75b13ca75d9..d3a2f5fcda7f 100644
--- a/posthog/asgi.py
+++ b/posthog/asgi.py
@@ -91,7 +91,7 @@ def self_capture_wrapper(func):
def task_run_event_ingest_wrapper(func):
async def inner(scope, receive, send):
- from products.tasks.backend.stream.event_ingest import handle_task_run_event_ingest
+ from products.tasks.backend.facade.streams import handle_task_run_event_ingest
if await handle_task_run_event_ingest(scope, receive, send):
return
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 6ea3c04b51bf..791ac5b9a43e 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -495,7 +495,7 @@ def _create_survey(team: Team, label: str) -> Survey:
def _create_task(team: Team, label: str):
- from products.tasks.backend.models import Task
+ Task = apps.get_model("tasks", "Task")
return Task.objects.create(
team=team,
@@ -506,7 +506,8 @@ def _create_task(team: Team, label: str):
def _create_task_run(team: Team, label: str):
- from products.tasks.backend.models import Task, TaskRun
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=team,
@@ -518,7 +519,7 @@ def _create_task_run(team: Team, label: str):
def _create_sandbox_environment(team: Team, label: str):
- from products.tasks.backend.models import SandboxEnvironment
+ SandboxEnvironment = apps.get_model("tasks", "SandboxEnvironment")
# private=False so the row is queryable via HogQL — the privacy predicate
# excludes private environments. Privacy filtering itself is covered by
@@ -688,7 +689,7 @@ class TestSystemTablesSandboxEnvironmentPrivacyIsolation(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
def test_private_environments_excluded(self):
- from products.tasks.backend.models import SandboxEnvironment
+ SandboxEnvironment = apps.get_model("tasks", "SandboxEnvironment")
public_env = SandboxEnvironment.objects.create(team=self.team, name="public_env", private=False)
private_env = SandboxEnvironment.objects.create(team=self.team, name="private_env", private=True)
@@ -700,7 +701,7 @@ class TestSystemTablesSandboxEnvironmentPrivacyIsolation(NonAtomicBaseTest):
assert str(private_env.pk) not in ids
def test_internal_environments_excluded(self):
- from products.tasks.backend.models import SandboxEnvironment
+ SandboxEnvironment = apps.get_model("tasks", "SandboxEnvironment")
regular_env = SandboxEnvironment.objects.create(
team=self.team, name="regular_env", private=False, internal=False
@@ -734,7 +735,7 @@ class TestSystemTablesTaskInternalExclusionIsolation(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
def test_internal_tasks_excluded(self):
- from products.tasks.backend.models import Task
+ Task = apps.get_model("tasks", "Task")
regular_task = Task.objects.create(
team=self.team,
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 7a45265b9d69..73b29cb126b5 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -211,7 +211,7 @@ from products.signals.backend.temporal import (
ACTIVITIES as SIGNALS_PRODUCT_ACTIVITIES,
WORKFLOWS as SIGNALS_PRODUCT_WORKFLOWS,
)
-from products.tasks.backend.temporal import (
+from products.tasks.backend.facade.temporal import (
ACTIVITIES as TASKS_ACTIVITIES,
WORKFLOWS as TASKS_WORKFLOWS,
)
diff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.py
index 6f1c0173182f..cd3dc9b89abf 100644
--- a/posthog/models/file_system/unfiled_file_saver.py
+++ b/posthog/models/file_system/unfiled_file_saver.py
@@ -22,7 +22,7 @@ from products.links.backend.models import Link
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import Survey
-from products.tasks.backend.models import Task
+from products.tasks.backend.facade.file_system import Task
MIXIN_MODELS: dict[str, type[FileSystemSyncMixin]] = {
"action": Action,
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 3772ccddcada..7d203ddabd43 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -142,34 +142,23 @@ def kill_stale_queued_task_runs() -> None:
so a re-queued run won't appear in this candidate set until it has actually
been QUEUED for the full STALE_AFTER window.
"""
- from products.tasks.backend.models import TaskRun
+ from products.tasks.backend.facade import api as tasks_facade
BATCH_SIZE = 500
STALE_AFTER = datetime.timedelta(hours=24)
REASON = "Run was stuck in QUEUED state for over 24h and was killed by the cleanup job."
- cutoff = timezone.now() - STALE_AFTER
# Janitor sweep is intentionally cross-team — it runs without a team context.
- stale_ids = list(
- TaskRun.objects.filter( # nosemgrep: celery-task-team-scope-audit
- status=TaskRun.Status.QUEUED, updated_at__lt=cutoff
- )
- .order_by("updated_at")
- .values_list("id", flat=True)[:BATCH_SIZE]
- )
+ stale_ids = tasks_facade.get_stale_queued_task_run_ids(STALE_AFTER, BATCH_SIZE)
swept = 0
errors = 0
for run_id in stale_ids:
- # Refetching by pk from the candidate set above; cross-team is intentional.
- run = TaskRun.objects.filter( # nosemgrep: celery-task-team-scope-audit
- pk=run_id, status=TaskRun.Status.QUEUED
- ).first()
- if run is None:
- continue
try:
- run.mark_failed(REASON)
- swept += 1
- STALE_QUEUED_TASK_RUN_SWEPT_COUNTER.inc()
+ # fail_task_run refetches with status=QUEUED, handling the race where a worker
+ # picked up the run between selection and update (returns False -> skip).
+ if tasks_facade.fail_task_run(run_id, REASON):
+ swept += 1
+ STALE_QUEUED_TASK_RUN_SWEPT_COUNTER.inc()
except Exception as exc: # noqa: BLE001 - one run must not block the sweep
errors += 1
STALE_QUEUED_TASK_RUN_ERRORS_COUNTER.inc()
@@ -593,9 +582,7 @@ _TASKS_RUN_TERMINAL_STATUSES = ("completed", "failed", "cancelled")
@skip_team_scope_audit
def capture_task_run_state_metrics() -> None:
"""Emit gauges describing the current state of the Tasks product's TaskRun table"""
- from django.db.models import Count, Min
-
- from products.tasks.backend.models import TaskRun
+ from products.tasks.backend.facade import api as tasks_facade
try:
with pushed_metrics_registry("tasks_run_state") as registry:
@@ -627,59 +614,40 @@ def capture_task_run_state_metrics() -> None:
labelnames=["status", "origin_product", "run_environment"],
)
- counts = (
- TaskRun.objects.filter(status__in=_TASKS_RUN_OPEN_STATUSES)
- .values("status", "environment", "task__origin_product")
- .annotate(count=Count("id"))
+ # Terminal runs are approximated by updated_at since completed_at can be null for
+ # FAILED/CANCELLED paths that didn't take the happy-path write.
+ metrics = tasks_facade.collect_task_run_state_metrics(
+ open_statuses=_TASKS_RUN_OPEN_STATUSES,
+ age_statuses=_TASKS_RUN_AGE_STATUSES,
+ terminal_statuses=_TASKS_RUN_TERMINAL_STATUSES,
+ window_seconds=int(datetime.timedelta(hours=1).total_seconds()),
)
- for row in counts:
+ for row in metrics.runs_in_status:
runs_in_status_gauge.labels(
- status=row["status"],
- origin_product=row["task__origin_product"] or "unknown",
- run_environment=row["environment"],
- ).set(row["count"])
-
- oldest = (
- TaskRun.objects.filter(status__in=_TASKS_RUN_AGE_STATUSES)
- .values("status", "environment", "task__origin_product")
- .annotate(oldest_created_at=Min("created_at"))
- )
- now = timezone.now()
- for row in oldest:
- age_seconds = (now - row["oldest_created_at"]).total_seconds()
+ status=row.status,
+ origin_product=row.origin_product,
+ run_environment=row.environment,
+ ).set(row.value)
+
+ for row in metrics.oldest_open_age_seconds:
oldest_age_gauge.labels(
- status=row["status"],
- origin_product=row["task__origin_product"] or "unknown",
- run_environment=row["environment"],
- ).set(age_seconds)
-
- created_1h = (
- TaskRun.objects.filter(created_at__gte=now - datetime.timedelta(hours=1))
- .values("environment", "task__origin_product")
- .annotate(count=Count("id"))
- )
- for row in created_1h:
+ status=row.status,
+ origin_product=row.origin_product,
+ run_environment=row.environment,
+ ).set(row.value)
+
+ for row in metrics.created_recently:
runs_created_1h_gauge.labels(
- origin_product=row["task__origin_product"] or "unknown",
- run_environment=row["environment"],
- ).set(row["count"])
-
- # Terminal runs: approximated by updated_at since completed_at can be null for FAILED/CANCELLED
- # paths that didn't take the happy-path write.
- terminal_1h = (
- TaskRun.objects.filter(
- status__in=_TASKS_RUN_TERMINAL_STATUSES,
- updated_at__gte=now - datetime.timedelta(hours=1),
- )
- .values("status", "environment", "task__origin_product")
- .annotate(count=Count("id"))
- )
- for row in terminal_1h:
+ origin_product=row.origin_product,
+ run_environment=row.environment,
+ ).set(row.value)
+
+ for row in metrics.terminal_recently:
runs_terminal_1h_gauge.labels(
- status=row["status"],
- origin_product=row["task__origin_product"] or "unknown",
- run_environment=row["environment"],
- ).set(row["count"])
+ status=row.status,
+ origin_product=row.origin_product,
+ run_environment=row.environment,
+ ).set(row.value)
except Exception as err:
logger.exception("capture_task_run_state_metrics", exception=err)
diff --git a/posthog/tasks/test/test_kill_stale_queued_task_runs.py b/posthog/tasks/test/test_kill_stale_queued_task_runs.py
index 0522db075931..845430df9c60 100644
--- a/posthog/tasks/test/test_kill_stale_queued_task_runs.py
+++ b/posthog/tasks/test/test_kill_stale_queued_task_runs.py
@@ -1,8 +1,9 @@
import datetime
-from typing import ClassVar
+from typing import TYPE_CHECKING, Any, ClassVar
from unittest.mock import patch
+from django.apps import apps
from django.test import TestCase
from django.utils import timezone
@@ -11,16 +12,18 @@ from parameterized import parameterized
from posthog.models import Organization, Team
from posthog.tasks.tasks import kill_stale_queued_task_runs
-from products.tasks.backend.models import Task, TaskRun
+if TYPE_CHECKING:
+ from products.tasks.backend.models import Task, TaskRun
class TestKillStaleQueuedTaskRuns(TestCase):
organization: ClassVar[Organization]
team: ClassVar[Team]
- task: ClassVar[Task]
+ task: ClassVar["Task"]
@classmethod
def setUpTestData(cls) -> None:
+ Task = apps.get_model("tasks", "Task")
cls.organization = Organization.objects.create(name="Test Org")
cls.team = Team.objects.create(organization=cls.organization, name="Test Team")
cls.task = Task.objects.create(
@@ -30,7 +33,8 @@ class TestKillStaleQueuedTaskRuns(TestCase):
origin_product=Task.OriginProduct.USER_CREATED,
)
- def _make_run(self, status: str, age: datetime.timedelta) -> TaskRun:
+ def _make_run(self, status: str, age: datetime.timedelta) -> "TaskRun":
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = TaskRun.objects.create(task=self.task, team=self.team, status=status)
past = timezone.now() - age
TaskRun.objects.filter(pk=run.pk).update(created_at=past, updated_at=past)
@@ -38,6 +42,7 @@ class TestKillStaleQueuedTaskRuns(TestCase):
return run
def test_marks_stale_queued_run_as_failed(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(hours=25))
kill_stale_queued_task_runs()
@@ -48,6 +53,7 @@ class TestKillStaleQueuedTaskRuns(TestCase):
self.assertIsNotNone(run.completed_at)
def test_leaves_recently_queued_run_alone(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(hours=23, minutes=59))
kill_stale_queued_task_runs()
@@ -58,6 +64,7 @@ class TestKillStaleQueuedTaskRuns(TestCase):
self.assertIsNone(run.error_message)
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
# 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.
@@ -73,11 +80,11 @@ class TestKillStaleQueuedTaskRuns(TestCase):
@parameterized.expand(
[
- (TaskRun.Status.NOT_STARTED,),
- (TaskRun.Status.IN_PROGRESS,),
- (TaskRun.Status.COMPLETED,),
- (TaskRun.Status.FAILED,),
- (TaskRun.Status.CANCELLED,),
+ (apps.get_model("tasks", "TaskRun").Status.NOT_STARTED,),
+ (apps.get_model("tasks", "TaskRun").Status.IN_PROGRESS,),
+ (apps.get_model("tasks", "TaskRun").Status.COMPLETED,),
+ (apps.get_model("tasks", "TaskRun").Status.FAILED,),
+ (apps.get_model("tasks", "TaskRun").Status.CANCELLED,),
]
)
def test_leaves_non_queued_runs_alone(self, status: str) -> None:
@@ -89,6 +96,7 @@ class TestKillStaleQueuedTaskRuns(TestCase):
self.assertEqual(run.status, status)
def test_caps_work_at_batch_size(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
for _ in range(550):
self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(hours=25))
@@ -100,13 +108,14 @@ class TestKillStaleQueuedTaskRuns(TestCase):
self.assertEqual(remaining_queued, 50)
def test_one_failure_does_not_block_the_sweep(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run_a = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(hours=25))
run_b = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(hours=26))
original_mark_failed = TaskRun.mark_failed
call_count = {"n": 0}
- def flaky_mark_failed(self: TaskRun, error: str) -> None:
+ def flaky_mark_failed(self: Any, error: str) -> None:
call_count["n"] += 1
if call_count["n"] == 1:
raise RuntimeError("synthetic failure")
@@ -125,6 +134,7 @@ class TestKillStaleQueuedTaskRuns(TestCase):
self.assertEqual(statuses, sorted([TaskRun.Status.QUEUED, TaskRun.Status.FAILED]))
def test_skips_run_whose_status_changed_between_select_and_update(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(hours=25))
original_filter = TaskRun.objects.filter
diff --git a/posthog/tasks/test/test_task_run_state_metrics.py b/posthog/tasks/test/test_task_run_state_metrics.py
index 6439e87f28e1..821ef4896b09 100644
--- a/posthog/tasks/test/test_task_run_state_metrics.py
+++ b/posthog/tasks/test/test_task_run_state_metrics.py
@@ -1,8 +1,9 @@
from datetime import datetime, timedelta
-from typing import ClassVar, Optional
+from typing import TYPE_CHECKING, ClassVar, Optional
from unittest.mock import MagicMock, patch
+from django.apps import apps
from django.test import TestCase
from django.utils import timezone
@@ -12,7 +13,8 @@ from prometheus_client import CollectorRegistry
from posthog.models import Organization, Team
from posthog.tasks.tasks import capture_task_run_state_metrics
-from products.tasks.backend.models import Task, TaskRun
+if TYPE_CHECKING:
+ from products.tasks.backend.models import Task, TaskRun
class TestCaptureTaskRunStateMetrics(TestCase):
@@ -27,11 +29,15 @@ class TestCaptureTaskRunStateMetrics(TestCase):
def _make_task_run(
self,
*,
- origin: Task.OriginProduct,
- status: TaskRun.Status,
- environment: TaskRun.Environment = TaskRun.Environment.CLOUD,
+ origin: "Task.OriginProduct",
+ status: "TaskRun.Status",
+ environment: "Optional[TaskRun.Environment]" = None,
created_at: Optional[datetime] = None,
- ) -> TaskRun:
+ ) -> "TaskRun":
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ if environment is None:
+ environment = TaskRun.Environment.CLOUD
task = Task.objects.create(
team=self.team,
title="t",
@@ -59,6 +65,8 @@ class TestCaptureTaskRunStateMetrics(TestCase):
return registry
def test_emits_counts_grouped_by_status_origin_and_environment(self) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
self._make_task_run(origin=Task.OriginProduct.SLACK, status=TaskRun.Status.QUEUED)
self._make_task_run(origin=Task.OriginProduct.SLACK, status=TaskRun.Status.QUEUED)
self._make_task_run(origin=Task.OriginProduct.USER_CREATED, status=TaskRun.Status.IN_PROGRESS)
@@ -94,12 +102,13 @@ class TestCaptureTaskRunStateMetrics(TestCase):
@parameterized.expand(
[
- (TaskRun.Status.COMPLETED,),
- (TaskRun.Status.FAILED,),
- (TaskRun.Status.CANCELLED,),
+ (apps.get_model("tasks", "TaskRun").Status.COMPLETED,),
+ (apps.get_model("tasks", "TaskRun").Status.FAILED,),
+ (apps.get_model("tasks", "TaskRun").Status.CANCELLED,),
]
)
- def test_ignores_terminal_statuses(self, status: TaskRun.Status) -> None:
+ def test_ignores_terminal_statuses(self, status: "TaskRun.Status") -> None:
+ Task = apps.get_model("tasks", "Task")
self._make_task_run(origin=Task.OriginProduct.SLACK, status=status)
registry = self._run_with_registry()
@@ -113,6 +122,8 @@ class TestCaptureTaskRunStateMetrics(TestCase):
)
def test_emits_oldest_open_run_age(self) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
long_ago = timezone.now() - timedelta(minutes=30)
self._make_task_run(
origin=Task.OriginProduct.SLACK,
@@ -132,6 +143,8 @@ class TestCaptureTaskRunStateMetrics(TestCase):
assert 1500 < age < 2400
def test_emits_runs_created_1h_by_origin_and_environment(self) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
# Two Slack runs created just now, one old run (outside the 1h window), one PostHog-code run.
self._make_task_run(origin=Task.OriginProduct.SLACK, status=TaskRun.Status.QUEUED)
self._make_task_run(origin=Task.OriginProduct.SLACK, status=TaskRun.Status.COMPLETED)
@@ -160,6 +173,8 @@ class TestCaptureTaskRunStateMetrics(TestCase):
)
def test_emits_runs_terminal_1h_grouped_by_status_and_origin(self) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
# 2 completed Slack runs + 1 failed User run in the last hour, plus 1 old completed run (outside 1h).
self._make_task_run(origin=Task.OriginProduct.SLACK, status=TaskRun.Status.COMPLETED)
self._make_task_run(origin=Task.OriginProduct.SLACK, status=TaskRun.Status.COMPLETED)
@@ -185,6 +200,8 @@ class TestCaptureTaskRunStateMetrics(TestCase):
)
def test_age_gauge_only_covers_queued_and_in_progress(self) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
self._make_task_run(
origin=Task.OriginProduct.SLACK,
status=TaskRun.Status.NOT_STARTED,
diff --git a/posthog/temporal/ai/slack_app/activities/repo_selection.py b/posthog/temporal/ai/slack_app/activities/repo_selection.py
index 428cfa1f605a..668fc53d45d3 100644
--- a/posthog/temporal/ai/slack_app/activities/repo_selection.py
+++ b/posthog/temporal/ai/slack_app/activities/repo_selection.py
@@ -95,8 +95,8 @@ async def discover_posthog_code_repository_via_agent_activity(
"""
from posthog.models.integration import Integration, SlackIntegration
- from products.tasks.backend.models import Task
- from products.tasks.backend.repo_selection import (
+ from products.tasks.backend.facade import api as tasks_facade
+ from products.tasks.backend.facade.repo_selection import (
RepoSelectionRejectedError,
RepoSelectionUnavailableError,
select_repository,
@@ -137,7 +137,7 @@ async def discover_posthog_code_repository_via_agent_activity(
team_id=integration.team_id,
user_id=user_id,
context=context_block,
- origin_product=Task.OriginProduct.SLACK,
+ origin_product=tasks_facade.TaskOriginProduct.SLACK,
on_research_session=_capture_research_session,
)
except RepoSelectionRejectedError as exc:
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 54b41b70db5f..1ef6e73b172e 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -101,8 +101,8 @@ def create_posthog_code_task_for_repo_activity(
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.slack_app.backend.slack_thread import SlackThreadContext
- from products.tasks.backend.models import Task, TaskRun
- from products.tasks.backend.temporal.client import execute_task_processing_workflow
+ from products.tasks.backend.facade import api as tasks_facade
+ from products.tasks.backend.facade.temporal import execute_task_processing_workflow
integration = Integration.objects.select_related("team", "team__organization").get(
id=inputs.integration_id,
@@ -162,11 +162,11 @@ def create_posthog_code_task_for_repo_activity(
# 1. Create task + run WITHOUT starting the workflow
try:
- task = Task.create_and_run(
+ created = tasks_facade.create_and_run_task(
team=integration.team,
title=title,
description=description,
- origin_product=Task.OriginProduct.SLACK,
+ origin_product=tasks_facade.TaskOriginProduct.SLACK,
user_id=user_id,
repository=repository,
create_pr=allow_pr_creation,
@@ -205,43 +205,41 @@ def create_posthog_code_task_for_repo_activity(
# 2. Create mapping BEFORE starting the workflow to avoid race condition
# where the agent finishes and tries to relay before the mapping exists
- task_run = None
- if task:
- task_run = task.latest_run
- if task_run:
- SlackThreadTaskMapping.objects.update_or_create(
- integration=integration,
+ task_run = created.latest_run
+ if task_run:
+ SlackThreadTaskMapping.objects.update_or_create(
+ integration=integration,
+ channel=channel,
+ thread_ts=thread_ts,
+ defaults={
+ "team": integration.team,
+ "slack_workspace_id": inputs.slack_team_id,
+ "task_id": created.task_id,
+ "task_run_id": task_run.id,
+ "mentioning_slack_user_id": slack_user_id,
+ },
+ )
+ # Track the workflow to link Temporal jobs to Slack threads
+ state_updates: dict[str, str] = {"slack_mention_workflow_id": derive_mention_workflow_id(inputs)}
+ if repo_research_task_id and repo_research_run_id:
+ state_updates["repo_research_task_id"] = repo_research_task_id
+ state_updates["repo_research_run_id"] = repo_research_run_id
+ try:
+ tasks_facade.update_task_run_state(task_run.id, updates=state_updates)
+ except Exception:
+ logger.exception(
+ "posthog_code_persist_mention_workflow_id_failed",
+ task_run_id=str(task_run.id),
channel=channel,
thread_ts=thread_ts,
- defaults={
- "team": integration.team,
- "slack_workspace_id": inputs.slack_team_id,
- "task": task,
- "task_run": task_run,
- "mentioning_slack_user_id": slack_user_id,
- },
)
- # Track the workflow to link Temporal jobs to Slack threads
- state_updates: dict[str, str] = {"slack_mention_workflow_id": derive_mention_workflow_id(inputs)}
- if repo_research_task_id and repo_research_run_id:
- state_updates["repo_research_task_id"] = repo_research_task_id
- state_updates["repo_research_run_id"] = repo_research_run_id
- try:
- TaskRun.update_state_atomic(task_run.id, updates=state_updates)
- except Exception:
- logger.exception(
- "posthog_code_persist_mention_workflow_id_failed",
- task_run_id=str(task_run.id),
- channel=channel,
- thread_ts=thread_ts,
- )
# 3. Now start the workflow
- if task and task_run:
+ if task_run:
execute_task_processing_workflow(
- task_id=str(task.id),
+ task_id=str(created.task_id),
run_id=str(task_run.id),
- team_id=task.team.id,
+ team_id=created.team_id,
user_id=user_id,
create_pr=allow_pr_creation,
slack_thread_context=slack_thread_context,
@@ -268,8 +266,7 @@ def forward_posthog_code_followup_activity(
from products.slack_app.backend.api import _parse_rules_command, resolve_slack_user
from products.slack_app.backend.models import SlackThreadTaskMapping
- from products.tasks.backend.services.agent_command import send_user_message
- from products.tasks.backend.services.connection_token import create_sandbox_connection_token
+ from products.tasks.backend.facade import api as tasks_facade
if _parse_rules_command(event_text):
return False
@@ -376,11 +373,13 @@ def forward_posthog_code_followup_activity(
created_by = mapping.task.created_by
if created_by and created_by.id:
distinct_id = created_by.distinct_id or f"user_{created_by.id}"
- auth_token = create_sandbox_connection_token(task_run, user_id=created_by.id, distinct_id=distinct_id)
+ auth_token = tasks_facade.create_sandbox_connection_token(
+ task_run.id, user_id=created_by.id, distinct_id=distinct_id
+ )
- result = send_user_message(task_run, user_text, auth_token=auth_token, timeout=90)
+ result = tasks_facade.send_user_message(task_run.id, user_text, auth_token=auth_token, timeout=90)
if not result.success and result.retryable and result.status_code != 504:
- result = send_user_message(task_run, user_text, auth_token=auth_token, timeout=90)
+ result = tasks_facade.send_user_message(task_run.id, user_text, auth_token=auth_token, timeout=90)
if not result.success:
logger.warning(
@@ -440,7 +439,8 @@ def _resume_task_with_new_run(
"""Create a new run on the same task when a follow-up arrives after the previous run completed."""
from products.slack_app.backend.services.slack_messages import decode_slack_event_text # noqa: PLC0415
from products.slack_app.backend.slack_thread import SlackThreadContext
- from products.tasks.backend.temporal.client import execute_task_processing_workflow
+ from products.tasks.backend.facade import api as tasks_facade
+ from products.tasks.backend.facade.temporal import execute_task_processing_workflow
integration = slack.integration
user_text = decode_slack_event_text(slack, integration, event_text)
@@ -494,13 +494,13 @@ def _resume_task_with_new_run(
extra_state["slack_mention_workflow_id"] = derive_mention_workflow_id(inputs)
try:
- new_run = mapping.task.create_run(mode="interactive", extra_state=extra_state)
+ new_run = tasks_facade.create_run(mapping.task_id, mode="interactive", extra_state=extra_state)
except Exception:
logger.exception(
"posthog_code_resume_create_run_failed",
channel=channel,
thread_ts=thread_ts,
- task_id=str(mapping.task.id),
+ task_id=str(mapping.task_id),
)
slack.client.chat_postMessage(
channel=channel,
@@ -519,9 +519,9 @@ def _resume_task_with_new_run(
try:
execute_task_processing_workflow(
- task_id=str(mapping.task.id),
+ task_id=str(mapping.task_id),
run_id=str(new_run.id),
- team_id=mapping.task.team_id,
+ team_id=new_run.team_id,
user_id=created_by.id,
create_pr=True,
slack_thread_context=slack_thread_context,
@@ -532,7 +532,7 @@ def _resume_task_with_new_run(
"posthog_code_resume_workflow_start_failed",
channel=channel,
thread_ts=thread_ts,
- task_id=str(mapping.task.id),
+ task_id=str(mapping.task_id),
run_id=str(new_run.id),
)
slack.client.chat_postMessage(
@@ -542,7 +542,7 @@ def _resume_task_with_new_run(
)
return True
- mapping.task_run = new_run
+ mapping.task_run_id = new_run.id
mapping.save(update_fields=["task_run", "updated_at"])
if user_message_ts:
diff --git a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py
index 3f7dea91b33a..74f204f41f76 100644
--- a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py
+++ b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py
@@ -84,8 +84,8 @@ from posthog.temporal.ai.slack_app import POSTHOG_CODE_SLACK_MENTION_PICKER_GUID
from posthog.temporal.ai.slack_app.activities.classifiers import classify_task_needs_repo
from products.slack_app.backend.api import _extract_explicit_repo
-from products.tasks.backend.models import Task
-from products.tasks.backend.repo_selection import (
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.repo_selection import (
RepoSelectionRejectedError,
RepoSelectionResult,
RepoSelectionUnavailableError,
@@ -456,7 +456,7 @@ class Command:
team_id=ctx.team_id,
user_id=ctx.user_id,
context=context,
- origin_product=Task.OriginProduct.SLACK,
+ origin_product=tasks_facade.TaskOriginProduct.SLACK,
)
)
if result.repository is None:
diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py b/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py
index 86b5594b02bc..1eaf2df9dea9 100644
--- a/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py
+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_interactivity.py
@@ -44,10 +44,8 @@ def process_posthog_code_task_termination_payload(payload: dict[str, Any]) -> No
from posthog.models.integration import Integration, SlackIntegration
from posthog.temporal.common.client import sync_connect
- from products.tasks.backend.models import TaskRun
- from products.tasks.backend.services.agent_command import send_cancel
- from products.tasks.backend.services.connection_token import create_sandbox_connection_token
- from products.tasks.backend.temporal.process_task.workflow import ProcessTaskWorkflow
+ from products.tasks.backend.facade import api as tasks_facade
+ from products.tasks.backend.facade.temporal import ProcessTaskWorkflow
actions = payload.get("actions", [])
action = next((a for a in actions if a.get("action_id") == "posthog_code_terminate_task"), None)
@@ -104,9 +102,8 @@ def process_posthog_code_task_termination_payload(payload: dict[str, Any]) -> No
message_ts = payload.get("message", {}).get("ts")
thread_ts = thread_ts_from_value or payload.get("message", {}).get("thread_ts") or message_ts
- try:
- task_run = TaskRun.objects.select_related("task").get(id=run_id, team_id=integration.team_id)
- except TaskRun.DoesNotExist:
+ task_run = tasks_facade.get_task_run(run_id, team_id=integration.team_id)
+ if task_run is None:
logger.warning("posthog_code_terminate_run_not_found", run_id=run_id)
return
@@ -125,15 +122,16 @@ def process_posthog_code_task_termination_payload(payload: dict[str, Any]) -> No
return
auth_token = None
- created_by = task_run.task.created_by
- if created_by and isinstance(created_by.id, int):
- distinct_id = created_by.distinct_id or f"user_{created_by.id}"
+ if task_run.created_by_id is not None:
+ distinct_id = task_run.created_by_distinct_id or f"user_{task_run.created_by_id}"
try:
- auth_token = create_sandbox_connection_token(task_run, user_id=created_by.id, distinct_id=distinct_id)
+ auth_token = tasks_facade.create_sandbox_connection_token(
+ run_id, user_id=task_run.created_by_id, distinct_id=distinct_id
+ )
except Exception as e:
logger.warning("posthog_code_terminate_auth_token_failed", run_id=run_id, error=str(e))
- cancel_result = send_cancel(task_run, auth_token=auth_token)
+ cancel_result = tasks_facade.send_cancel(run_id, auth_token=auth_token)
if cancel_result.success:
logger.info("posthog_code_terminate_command_dispatched", run_id=run_id)
else:
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index 07265ab6ca59..fbb18bc26b42 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -72,7 +72,7 @@ from products.logs.backend.facade.temporal import (
LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS,
LogsAlertingMetricsInterceptor,
)
-from products.tasks.backend.temporal.metrics import TASKS_LATENCY_HISTOGRAM_BUCKETS, TASKS_LATENCY_HISTOGRAM_METRICS
+from products.tasks.backend.facade.temporal import TASKS_LATENCY_HISTOGRAM_BUCKETS, TASKS_LATENCY_HISTOGRAM_METRICS
logger = get_write_only_logger()
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index d91d11485ea8..6910329e8d0d 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -89,7 +89,7 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (
)
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
from products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedule
-from products.tasks.backend.temporal.code_workstreams.schedule import create_evaluate_code_workstreams_schedule
+from products.tasks.backend.facade.temporal import create_evaluate_code_workstreams_schedule
from products.web_analytics.backend.temporal.digest_notification.types import WADigestNotificationInput
from products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInput
diff --git a/posthog/urls.py b/posthog/urls.py
index 6237b01044ed..4824a4a21804 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -105,7 +105,7 @@ def github_webhook(request: HttpRequest) -> HttpResponse:
"""
import json
- from products.tasks.backend.webhooks import get_github_webhook_secret, verify_github_signature
+ from products.tasks.backend.facade.webhooks import get_github_webhook_secret, verify_github_signature
if request.method != "POST":
return HttpResponse(status=405)
@@ -131,7 +131,7 @@ def github_webhook(request: HttpRequest) -> HttpResponse:
return dispatch_github_event(request, event_type, payload)
if event_type == "pull_request":
- from products.tasks.backend.webhooks import handle_pull_request_event
+ from products.tasks.backend.facade.webhooks import handle_pull_request_event
return handle_pull_request_event(payload)
diff --git a/products/conversations/backend/temporal/helpers.py b/products/conversations/backend/temporal/helpers.py
index 11d12c7bfe07..3922ffdf3ff3 100644
--- a/products/conversations/backend/temporal/helpers.py
+++ b/products/conversations/backend/temporal/helpers.py
@@ -1,59 +1,32 @@
from __future__ import annotations
-from django.db import transaction
-
import structlog
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
-from products.tasks.backend.models import SandboxEnvironment
+from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
CONVERSATIONS_SUPPORT_REPLY_ENV_NAME = "CONVERSATIONS_SUPPORT_REPLY"
-_SANDBOX_DEFAULTS = {
- "network_access_level": SandboxEnvironment.NetworkAccessLevel.TRUSTED,
- "private": False,
- "internal": True,
-}
-
def get_or_create_support_sandbox_env(team_id: int) -> str:
"""Get or create the sandbox environment for conversations support reply drafting.
- Returns the env ID as a string. Uses update_or_create to reassert policy on every call.
-
- SandboxEnvironment has no unique constraint on (team_id, name), so concurrent calls
- can race past the SELECT and both INSERT. We catch MultipleObjectsReturned, keep the
- oldest row, delete the rest, and retry.
+ Returns the env ID as a string. Reasserts policy on every call; the facade dedupes if a
+ concurrent call raced past the SELECT and produced multiple rows.
"""
- try:
- env, _ = SandboxEnvironment.objects.update_or_create(
- team_id=team_id,
- name=CONVERSATIONS_SUPPORT_REPLY_ENV_NAME,
- defaults=_SANDBOX_DEFAULTS,
+ return str(
+ tasks_facade.upsert_internal_sandbox_env(
+ team_id,
+ CONVERSATIONS_SUPPORT_REPLY_ENV_NAME,
+ tasks_facade.SandboxNetworkAccessLevel.TRUSTED,
+ private=False,
+ internal=True,
)
- return str(env.id)
- except SandboxEnvironment.MultipleObjectsReturned:
- logger.warning(
- "support_sandbox_env_duplicate_detected",
- team_id=team_id,
- name=CONVERSATIONS_SUPPORT_REPLY_ENV_NAME,
- )
- with transaction.atomic():
- dupes = list(
- SandboxEnvironment.objects.filter(team_id=team_id, name=CONVERSATIONS_SUPPORT_REPLY_ENV_NAME).order_by(
- "created_at"
- )
- )
- keeper = dupes[0]
- SandboxEnvironment.objects.filter(id__in=[d.id for d in dupes[1:]]).delete()
- for key, value in _SANDBOX_DEFAULTS.items():
- setattr(keeper, key, value)
- keeper.save(update_fields=list(_SANDBOX_DEFAULTS.keys()))
- return str(keeper.id)
+ )
def resolve_user_id_for_support(team_id: int) -> int:
diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.py
index 34356d1e8c79..90c391b4cdfe 100644
--- a/products/conversations/backend/temporal/pipeline.py
+++ b/products/conversations/backend/temporal/pipeline.py
@@ -37,9 +37,8 @@ with workflow.unsafe.imports_passed_through():
get_or_create_support_sandbox_env,
resolve_user_id_for_support,
)
- from products.tasks.backend.models import Task
- from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
- from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
+ from products.tasks.backend.facade import api as tasks_facade
+ from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession
logger = structlog.get_logger(__name__)
@@ -394,7 +393,7 @@ Return your response as a JSON object with keys: reply, citations, confidence, s
context,
model=SupportReplyDraft,
step_name="support_reply",
- origin_product=Task.OriginProduct.SUPPORT_REPLY,
+ origin_product=tasks_facade.TaskOriginProduct.SUPPORT_REPLY,
internal=True,
max_poll_seconds=DRAFT_POLL_SECONDS,
)
diff --git a/products/notebooks/backend/api/notebook.py b/products/notebooks/backend/api/notebook.py
index 477bcca8bc36..9aeb9445ff9a 100644
--- a/products/notebooks/backend/api/notebook.py
+++ b/products/notebooks/backend/api/notebook.py
@@ -48,8 +48,8 @@ from products.notebooks.backend.kernel_runtime import build_notebook_sandbox_con
from products.notebooks.backend.models import KernelRuntime, Notebook
from products.notebooks.backend.python_analysis import analyze_python_globals, annotate_python_nodes
from products.notebooks.backend.query_validation import InvalidNotebookQueryError, normalize_notebook_query_nodes
-from products.tasks.backend.exceptions import SandboxProvisionError
-from products.tasks.backend.services.sandbox import SandboxStatus
+from products.tasks.backend.facade.exceptions import SandboxProvisionError
+from products.tasks.backend.facade.sandbox import SandboxStatus
from ee.hogai.utils.aio import async_to_sync
from ee.hogai.utils.asgi import SyncIterableToAsync
diff --git a/products/notebooks/backend/kernel_runtime.py b/products/notebooks/backend/kernel_runtime.py
index 4824bea80f4e..1009f27f0658 100644
--- a/products/notebooks/backend/kernel_runtime.py
+++ b/products/notebooks/backend/kernel_runtime.py
@@ -23,7 +23,7 @@ from posthog.models import Team, User
from posthog.redis import get_client
from products.notebooks.backend.models import KernelRuntime, Notebook
-from products.tasks.backend.services.sandbox import (
+from products.tasks.backend.facade.sandbox import (
SandboxBase,
SandboxClass,
SandboxConfig,
@@ -708,7 +708,7 @@ class KernelRuntimeService:
if handle.backend in (KernelRuntime.Backend.MODAL, KernelRuntime.Backend.DOCKER):
if not handle.sandbox_id:
return False
- from products.tasks.backend.services.sandbox import SandboxStatus
+ from products.tasks.backend.facade.sandbox import SandboxStatus
try:
sandbox_class = self._get_sandbox_class(handle.backend)
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index f77fb4c69091..a532b9bc6f88 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -16,7 +16,7 @@ from products.signals.backend.report_generation.research import (
)
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
from products.signals.backend.slack_inbox_notifications import POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME
-from products.tasks.backend.models import Task
+from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
@@ -185,13 +185,13 @@ async def maybe_autostart_implementation_task(
if repository and team_config:
base_branch = (team_config.autostart_base_branches or {}).get(repository.lower())
- task = await database_sync_to_async(Task.create_and_run, thread_sensitive=False)(
+ created = await database_sync_to_async(tasks_facade.create_and_run_task, thread_sensitive=False)(
team=team,
title=title,
description=_build_autostart_task_description(
report_id=report_id, summary=summary, repository=repository, priority=priority
),
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,
user_id=task_user.id,
repository=repository,
branch=base_branch,
@@ -199,13 +199,12 @@ async def maybe_autostart_implementation_task(
posthog_mcp_scopes="read_only",
interaction_origin="signal_report", # Makes the agent auto-push and open a draft PR
)
- task_run = await task.runs.order_by("-created_at").afirst()
- if task_run is None:
- raise RuntimeError(f"Task {task.id} auto-started without producing a TaskRun")
+ if created.latest_run is None:
+ raise RuntimeError(f"Task {created.task_id} auto-started without producing a TaskRun")
await SignalReportTask.objects.acreate(
team_id=team_id,
report_id=report_id,
- task=task,
+ task_id=created.task_id,
relationship=SignalReportTask.Relationship.IMPLEMENTATION,
)
diff --git a/products/signals/backend/custom_agent/PLAN.md b/products/signals/backend/custom_agent/PLAN.md
index b93222165403..1d92dd964ffd 100644
--- a/products/signals/backend/custom_agent/PLAN.md
+++ b/products/signals/backend/custom_agent/PLAN.md
@@ -181,7 +181,7 @@ Free-form selection (`select_repository_for_prompt`) reuses the existing repo ca
## Send / multi-turn details
-- Session backing: `products/tasks/backend/services/custom_prompt_multi_turn_runner.MultiTurnSession`.
+- Session backing: `products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.MultiTurnSession`.
- Always uses `posthog_mcp_scopes="read_only"`.
- Sandbox env is `SIGNALS_REPORT_RESEARCH` (TRUSTED network access). Repo-selection runs in `SIGNALS_REPO_DISCOVERY` (CUSTOM, GitHub-only domains).
- `Heartbeater()` keeps the Temporal activity alive while the agent thinks.
diff --git a/products/signals/backend/custom_agent/base.py b/products/signals/backend/custom_agent/base.py
index aca61bba277a..9a6596d7af05 100644
--- a/products/signals/backend/custom_agent/base.py
+++ b/products/signals/backend/custom_agent/base.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import json
-from typing import TypeVar
+from typing import TYPE_CHECKING, TypeVar
import structlog
import posthoganalytics
@@ -29,9 +29,11 @@ from products.signals.backend.temporal.agentic import (
resolve_user_id_for_team,
)
from products.signals.backend.temporal.agentic.select_repository import GITHUB_ONLY_DOMAINS
-from products.tasks.backend.models import SandboxEnvironment, Task
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext, extract_json_from_text
-from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession, extract_json_from_text
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import Task
logger = structlog.get_logger(__name__)
@@ -405,7 +407,7 @@ Rules:
sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
self.team_id,
SIGNALS_REPO_DISCOVERY_ENV_NAME,
- SandboxEnvironment.NetworkAccessLevel.CUSTOM,
+ tasks_facade.SandboxNetworkAccessLevel.CUSTOM,
allowed_domains=GITHUB_ONLY_DOMAINS,
)
selected = await select_repository_for_team(
@@ -600,7 +602,7 @@ Return only a JSON object matching this schema. Do not include markdown fences o
)(
self.team_id,
SIGNALS_REPORT_RESEARCH_ENV_NAME,
- SandboxEnvironment.NetworkAccessLevel.TRUSTED,
+ tasks_facade.SandboxNetworkAccessLevel.TRUSTED,
)
context = CustomPromptSandboxContext(
team_id=self.team_id,
@@ -614,7 +616,7 @@ Return only a JSON object matching this schema. Do not include markdown fences o
prompt=prompt,
context=context,
step_name=label,
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,
internal=True,
)
self._session = session
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index 62bf70831e98..d58ed29658ab 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -1,31 +1,35 @@
"""Resolve implementation PR URLs linked to signal reports."""
-from django.db.models.fields.json import KeyTextTransform
-
from products.signals.backend.models import SignalReportTask
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.facade import api as tasks_facade
def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
- """PR URL from the latest implementation task run for each report, when available."""
+ """PR URL from the latest implementation task run for each report, when available.
+
+ A report has a single implementation task in practice; the facade resolves the latest
+ PR-bearing run for each task, so multiple runs of that task collapse to the newest PR.
+ """
if not report_ids:
return {}
- latest_runs = (
- TaskRun.objects.filter(
- task__signal_report_tasks__report_id__in=report_ids,
- task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
- output__pr_url__isnull=False,
+ # report_id -> task_id for the report's implementation task(s); signals owns this mapping.
+ pairs = list(
+ SignalReportTask.objects.filter(
+ report_id__in=report_ids,
+ relationship=SignalReportTask.Relationship.IMPLEMENTATION,
)
- .exclude(output__pr_url="")
- .order_by("task__signal_report_tasks__report_id", "-created_at", "-id")
- .annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
- .values("task__signal_report_tasks__report_id", "output_pr_url_text")
- .distinct("task__signal_report_tasks__report_id")
+ .order_by("report_id")
+ .values_list("report_id", "task_id")
)
+ if not pairs:
+ return {}
+
+ pr_url_by_task = tasks_facade.get_latest_pr_url_by_task([task_id for _, task_id in pairs])
- return {
- str(row["task__signal_report_tasks__report_id"]): row["output_pr_url_text"]
- for row in latest_runs
- if row["task__signal_report_tasks__report_id"] and row["output_pr_url_text"]
- }
+ result: dict[str, str] = {}
+ for report_id, task_id in pairs:
+ pr_url = pr_url_by_task.get(str(task_id))
+ if pr_url and str(report_id) not in result:
+ result[str(report_id)] = pr_url
+ return result
diff --git a/products/signals/backend/management/commands/analyze_report.py b/products/signals/backend/management/commands/analyze_report.py
index b69aff3500a9..4efba015d580 100644
--- a/products/signals/backend/management/commands/analyze_report.py
+++ b/products/signals/backend/management/commands/analyze_report.py
@@ -16,7 +16,7 @@ from django.core.management.base import BaseCommand, CommandError
from products.signals.backend.report_generation.research import ReportResearchOutput, run_multi_turn_research
from products.signals.backend.temporal.types import SignalData
-from products.tasks.backend.services.dev_sandbox_context import resolve_sandbox_context_for_local_dev
+from products.tasks.backend.facade.agents import resolve_sandbox_context_for_local_dev
logger = logging.getLogger(__name__)
diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.py
index 2b3baa392343..3a7540b3e812 100644
--- a/products/signals/backend/report_generation/research.py
+++ b/products/signals/backend/report_generation/research.py
@@ -31,7 +31,7 @@ class Priority(str, Enum):
if TYPE_CHECKING:
- from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext, OutputFn
+ from products.tasks.backend.facade.agents import CustomPromptSandboxContext, OutputFn
logger = logging.getLogger(__name__)
@@ -552,8 +552,8 @@ async def run_multi_turn_research(
has_business_knowledge: bool = False,
) -> ReportResearchOutput:
"""Orchestrate a multi-turn sandbox session that investigates each signal individually."""
- from products.tasks.backend.models import Task
- from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
+ from products.tasks.backend.facade import api as tasks_facade
+ from products.tasks.backend.facade.agents import MultiTurnSession
total = len(signals)
if total == 0:
@@ -589,7 +589,7 @@ async def run_multi_turn_research(
step_name="report_research",
verbose=verbose,
output_fn=output_fn,
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,
signal_report_id=signal_report_id,
ai_stage="research",
internal=True,
diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.py
index 9efe90249c64..fa94a8a50142 100644
--- a/products/signals/backend/report_generation/select_repo.py
+++ b/products/signals/backend/report_generation/select_repo.py
@@ -1,6 +1,6 @@
"""Repository selection for Signals reports.
-Thin wrapper around `products.tasks.backend.repo_selection.select_repository`.
+Thin wrapper around `products.tasks.backend.logic.repo_selection.select_repository`.
Renders `SignalData` to text and collapses both `RepoSelectionRejectedError`
(LLM hallucination) and `RepoSelectionUnavailableError` (no eligible repos)
into `RepoSelectionResult(repository=None, ...)` — Signals has no picker
@@ -14,8 +14,8 @@ from __future__ import annotations
import logging
from typing import TYPE_CHECKING
-from products.tasks.backend.models import Task
-from products.tasks.backend.repo_selection import (
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.repo_selection import (
REPO_SELECTION_DUMMY_REPOSITORY,
RepoSelectionRejectedError,
RepoSelectionResult,
@@ -29,7 +29,7 @@ if TYPE_CHECKING:
# __init__ (agentic -> back into report_generation), a circular import. SignalData is
# annotation-only here (module uses `from __future__ import annotations`).
from products.signals.backend.temporal.types import SignalData
- from products.tasks.backend.services.custom_prompt_internals import OutputFn
+ from products.tasks.backend.facade.agents import OutputFn
logger = logging.getLogger(__name__)
@@ -67,7 +67,7 @@ async def select_repository_for_team(
team_id=team_id,
user_id=user_id,
context=request_section,
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNAL_REPORT,
step_name=step_name,
signal_report_id=signal_report_id,
sandbox_environment_id=sandbox_environment_id,
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 3c69eb3f8c06..ad59671c206e 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -5,7 +5,7 @@ import asyncio
import logging
from dataclasses import dataclass
from datetime import timedelta
-from typing import Any
+from typing import TYPE_CHECKING, Any
from django.utils import timezone
@@ -26,9 +26,11 @@ from products.signals.backend.temporal.agentic import (
get_or_create_signals_sandbox_env,
resolve_user_id_for_team,
)
-from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
-from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
logger = logging.getLogger(__name__)
@@ -167,14 +169,14 @@ async def arun_signals_scout(
skill=skill,
run_id=run_id,
task_run_id=task_run_id,
- status=TaskRun.Status.COMPLETED.value,
+ status=tasks_facade.TaskRunStatus.COMPLETED.value,
runtime_s=runtime_s,
emitted_count=emitted_count,
)
return RunResult(
run_id=str(run_id),
task_run_id=task_run_id,
- status=TaskRun.Status.COMPLETED.value,
+ status=tasks_facade.TaskRunStatus.COMPLETED.value,
last_message=last_message,
runtime_s=runtime_s,
skill_name=skill.name,
@@ -215,14 +217,14 @@ async def arun_signals_scout(
skill=skill,
run_id=run_id,
task_run_id=failed_task_run_id,
- status=TaskRun.Status.FAILED.value,
+ status=tasks_facade.TaskRunStatus.FAILED.value,
runtime_s=runtime_s,
emitted_count=emitted_count,
)
return RunResult(
run_id=str(run_id) if row_persisted else None,
task_run_id=None,
- status=TaskRun.Status.FAILED.value,
+ status=tasks_facade.TaskRunStatus.FAILED.value,
last_message=None,
runtime_s=runtime_s,
skill_name=skill.name,
@@ -255,7 +257,7 @@ async def arun_signals_scout(
skill=skill,
run_id=run_id,
task_run_id=None,
- status=TaskRun.Status.CANCELLED.value,
+ status=tasks_facade.TaskRunStatus.CANCELLED.value,
runtime_s=runtime_s,
emitted_count=None,
)
@@ -280,7 +282,7 @@ async def _spawn_and_run(
sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
team.id,
SIGNALS_SCOUT_SANDBOX_ENV_NAME,
- SandboxEnvironment.NetworkAccessLevel.TRUSTED,
+ tasks_facade.SandboxNetworkAccessLevel.TRUSTED,
)
# `repository` is None on the cadence path — v1 doesn't clone a repo into the
# sandbox. The kwarg stays wired so the management command can still pass
@@ -347,7 +349,7 @@ async def _spawn_and_run(
model=SignalScoutRunSummary,
step_name=_step_name(skill),
verbose=verbose,
- origin_product=Task.OriginProduct.SIGNALS_SCOUT,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,
# Tag every scout $ai_generation with a coarse pipeline stage so scout spend is
# splittable out of the ai_product='signals' bucket (scouts carry no signal_report_id).
# Constant 'scout' keeps ai_stage a low-cardinality stage enum (peer of research /
@@ -411,7 +413,7 @@ def _has_running_run(*, team_id: int, skill_name: str) -> bool:
.filter(
team_id=team_id,
skill_name=skill_name,
- task_run__status__in=(TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS),
+ task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),
)
.exists()
)
@@ -441,7 +443,7 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
.filter(
team_id=team_id,
skill_name=skill_name,
- task_run__status__in=(TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS),
+ task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),
task_run__created_at__lt=cutoff,
)
.select_related("task_run")
@@ -455,23 +457,22 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
for run in stale_runs:
try:
task_run = run.task_run
+ # Read the pre-reap status / age off the loaded bridge instance before the claim:
+ # the conditional update below doesn't refresh it, so these stay the original values.
+ status_before = task_run.status
+ age_seconds = (now - task_run.created_at).total_seconds()
# Compare-and-set claim on the status transition. Two triggers for the same
# `(team, skill)` can reach this self-heal concurrently and load the same stale
# row; the conditional UPDATE lets exactly one win — the other matches zero rows
# once the first commits `FAILED`. Only the winner falls through to emit, so a
# single stranded run can't double-count in the worker-death / mass-stall signal.
- claimed = TaskRun.objects.filter(
- id=task_run.id,
- status__in=(TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS),
- ).update(status=TaskRun.Status.FAILED)
- if not claimed:
- continue
- status_before = task_run.status
- age_seconds = (now - task_run.created_at).total_seconds()
- task_run.mark_failed(
+ claimed = tasks_facade.claim_and_fail_stale_run(
+ task_run.id,
"Scout run abandoned: no terminal status past the runtime ceiling "
- "(worker/sandbox lost before finalize)."
+ "(worker/sandbox lost before finalize).",
)
+ if not claimed:
+ continue
logger.warning(
"signals_scout: reaped stale in-progress run before dispatch",
extra={
diff --git a/products/signals/backend/scout_harness/tools/emit.py b/products/signals/backend/scout_harness/tools/emit.py
index 4d8fbfc0a962..fb74b626e591 100644
--- a/products/signals/backend/scout_harness/tools/emit.py
+++ b/products/signals/backend/scout_harness/tools/emit.py
@@ -37,7 +37,7 @@ from posthog.models import Team
from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission, SignalScoutRun, SignalSourceConfig
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.facade import api as tasks_facade
logger = logging.getLogger(__name__)
@@ -364,7 +364,7 @@ def _resolve_task_id(run: SignalScoutRun) -> str | None:
return None
# Team-scope the lookup: the bridge run is already team-owned, but scoping the TaskRun query keeps
# the resolution fail-closed against cross-team ids.
- task_id = TaskRun.objects.filter(id=run.task_run_id, team_id=run.team_id).values_list("task_id", flat=True).first()
+ task_id = tasks_facade.get_task_id_for_run(run.task_run_id, run.team_id)
return str(task_id) if task_id else None
diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.py
index c78538066e6f..11684353bbcd 100644
--- a/products/signals/backend/scout_harness/tools/runs.py
+++ b/products/signals/backend/scout_harness/tools/runs.py
@@ -18,10 +18,13 @@ from __future__ import annotations
from dataclasses import asdict, dataclass, field
from datetime import datetime
-from typing import Any
+from typing import TYPE_CHECKING, Any
from products.signals.backend.models import SignalScoutRun
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.facade import api as tasks_facade
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
# Defensive caps so a runaway agent loop can't pull thousands of rows in one call.
DEFAULT_RUN_SEARCH_LIMIT = 20
@@ -188,13 +191,18 @@ def _derive_failure(task_run: TaskRun | None) -> tuple[str | None, str | None]:
`failure_reason` is what a bulk run scan reads to see *why* a run emitted nothing without
pulling every stack trace.
"""
- if task_run is None or task_run.status not in (TaskRun.Status.FAILED, TaskRun.Status.CANCELLED):
+ if task_run is None or task_run.status not in (
+ tasks_facade.TaskRunStatus.FAILED,
+ tasks_facade.TaskRunStatus.CANCELLED,
+ ):
return None, None
error = task_run.error_message or None
message = (task_run.error_message or "").strip()
if message:
return error, message.splitlines()[0][:MAX_FAILURE_REASON_LENGTH]
- fallback = "cancelled" if task_run.status == TaskRun.Status.CANCELLED else "failed (no error message recorded)"
+ fallback = (
+ "cancelled" if task_run.status == tasks_facade.TaskRunStatus.CANCELLED else "failed (no error message recorded)"
+ )
return error, fallback
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index a5106c20bf31..59784e939c11 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -393,7 +393,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def emit_signal(self, request: Request, **kwargs) -> Response:
run_id = _parse_run_id_or_404(kwargs)
- from products.tasks.backend.models import TaskRun
+ from products.tasks.backend.facade import api as tasks_facade
run = (
SignalScoutRun.objects.select_related("scout_config", "task_run")
@@ -402,7 +402,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
if run is None:
raise exceptions.NotFound()
- if run.task_run.status != TaskRun.Status.IN_PROGRESS:
+ if run.task_run.status != tasks_facade.TaskRunStatus.IN_PROGRESS:
raise exceptions.ValidationError(
{"status": f"Findings can only be emitted on in-progress runs (current: {run.task_run.status})."}
)
diff --git a/products/signals/backend/temporal/agentic/__init__.py b/products/signals/backend/temporal/agentic/__init__.py
index 1129d34e2cbe..1019b2c71512 100644
--- a/products/signals/backend/temporal/agentic/__init__.py
+++ b/products/signals/backend/temporal/agentic/__init__.py
@@ -6,7 +6,7 @@ from posthog.models.team.team import Team
from posthog.models.user_integration import UserGitHubIntegration
from products.signals.backend.report_generation.select_repo import resolve_team_github_integration
-from products.tasks.backend.models import SandboxEnvironment
+from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
@@ -17,30 +17,25 @@ SIGNALS_REPORT_RESEARCH_ENV_NAME = "SIGNALS_REPORT_RESEARCH"
def get_or_create_signals_sandbox_env(
team_id: int,
name: str,
- network_access_level: SandboxEnvironment.NetworkAccessLevel,
+ network_access_level: "tasks_facade.SandboxNetworkAccessLevel",
*,
allowed_domains: list[str] | None = None,
include_default_domains: bool = False,
) -> str:
"""Get or create a SandboxEnvironment for a Signals agent. Returns the env ID as a string.
- Uses update_or_create to reassert the expected policy on every call,
- so manual edits via the API are corrected on next run.
+ Reasserts the expected policy on every call, so manual edits via the API are corrected on
+ next run.
"""
- defaults: dict = {
- "network_access_level": network_access_level,
- "private": False,
- "internal": True,
- }
- if allowed_domains is not None:
- defaults["allowed_domains"] = allowed_domains
- defaults["include_default_domains"] = include_default_domains
- env, _ = SandboxEnvironment.objects.update_or_create(
- team_id=team_id,
- name=name,
- defaults=defaults,
+ return str(
+ tasks_facade.upsert_internal_sandbox_env(
+ team_id,
+ name,
+ network_access_level,
+ allowed_domains=allowed_domains,
+ include_default_domains=include_default_domains,
+ )
)
- return str(env.id)
def resolve_user_id_for_team(team_id: int, github: GitHubIntegrationBase | None = None) -> int:
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index bc99f8612232..2e207de5c711 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -34,8 +34,8 @@ from products.signals.backend.temporal.agentic import (
resolve_user_id_for_team,
)
from products.signals.backend.temporal.types import SignalData
-from products.tasks.backend.models import SandboxEnvironment
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.agents import CustomPromptSandboxContext
logger = structlog.get_logger(__name__)
@@ -296,7 +296,7 @@ async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenti
# 1. Get context for the sandbox
user_id = await database_sync_to_async(resolve_user_id_for_team, thread_sensitive=False)(input.team_id)
sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
- input.team_id, SIGNALS_REPORT_RESEARCH_ENV_NAME, SandboxEnvironment.NetworkAccessLevel.TRUSTED
+ input.team_id, SIGNALS_REPORT_RESEARCH_ENV_NAME, tasks_facade.SandboxNetworkAccessLevel.TRUSTED
)
context = CustomPromptSandboxContext(
team_id=input.team_id,
diff --git a/products/signals/backend/temporal/agentic/select_repository.py b/products/signals/backend/temporal/agentic/select_repository.py
index e131a868474c..872f8a4e2d1d 100644
--- a/products/signals/backend/temporal/agentic/select_repository.py
+++ b/products/signals/backend/temporal/agentic/select_repository.py
@@ -25,7 +25,7 @@ from products.signals.backend.temporal.agentic import (
resolve_user_id_for_team,
)
from products.signals.backend.temporal.types import SignalData
-from products.tasks.backend.models import SandboxEnvironment
+from products.tasks.backend.facade import api as tasks_facade
# Repo discovery only runs `gh` CLI commands — limit egress to GitHub hosts.
GITHUB_ONLY_DOMAINS = [
@@ -155,7 +155,7 @@ async def select_repository_activity(input: SelectRepositoryInput) -> RepoSelect
sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
input.team_id,
SIGNALS_REPO_DISCOVERY_ENV_NAME,
- SandboxEnvironment.NetworkAccessLevel.CUSTOM,
+ tasks_facade.SandboxNetworkAccessLevel.CUSTOM,
allowed_domains=GITHUB_ONLY_DOMAINS,
)
result = await select_repository_for_report(
diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.py
index e4f515b0a061..4429d0306f94 100644
--- a/products/signals/backend/temporal/inbox_notification.py
+++ b/products/signals/backend/temporal/inbox_notification.py
@@ -25,7 +25,7 @@ from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
from products.signals.backend.models import SignalReport, SignalReportTask
from products.signals.backend.temporal.signal_queries import fetch_signals_for_report_sync
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
@@ -44,23 +44,22 @@ class InboxNotificationState:
def _compute_inbox_notification_state(team_id: int, report_id: str) -> InboxNotificationState:
- has_task = SignalReportTask.objects.filter(
- team_id=team_id,
- report_id=report_id,
- relationship=SignalReportTask.Relationship.IMPLEMENTATION,
- ).exists()
- if not has_task:
+ impl_task_ids = list(
+ SignalReportTask.objects.filter(
+ team_id=team_id,
+ report_id=report_id,
+ relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ ).values_list("task_id", flat=True)
+ )
+ if not impl_task_ids:
return InboxNotificationState(has_implementation_task=False, pr_available=False, task_terminal=False)
pr_available = bool(fetch_implementation_pr_urls_for_reports([report_id]))
- latest_run = (
- TaskRun.objects.filter(
- task__signal_report_tasks__team_id=team_id,
- task__signal_report_tasks__report_id=report_id,
- task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
- )
- .order_by("-created_at", "-id")
- .first()
+ # Most recent run across the report's implementation task(s).
+ latest_run = max(
+ tasks_facade.get_latest_run_by_task(impl_task_ids).values(),
+ key=lambda run: (run.created_at, run.id),
+ default=None,
)
task_terminal = bool(latest_run and latest_run.is_terminal) and not pr_available
return InboxNotificationState(has_implementation_task=True, pr_available=pr_available, task_terminal=task_terminal)
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index b9be8204a7be..bf8d5269353d 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -367,7 +367,7 @@ async def test_run_multi_turn_research_ends_session_when_followup_fails():
first_finding = SignalFinding(signal_id="sig-1", relevant_code_paths=[], data_queried="", verified=True)
with patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.MultiTurnSession.start",
+ "products.tasks.backend.facade.agents.MultiTurnSession.start",
AsyncMock(return_value=(session, first_finding)),
):
with pytest.raises(RuntimeError, match="poll_for_turn"):
diff --git a/products/signals/backend/test/test_inbox_notification_workflow.py b/products/signals/backend/test/test_inbox_notification_workflow.py
index 457c283932c7..1669f44d956c 100644
--- a/products/signals/backend/test/test_inbox_notification_workflow.py
+++ b/products/signals/backend/test/test_inbox_notification_workflow.py
@@ -3,6 +3,7 @@ import uuid
import pytest
from unittest.mock import patch
+from django.apps import apps
from django.test import override_settings
from temporalio import activity
@@ -19,7 +20,6 @@ from products.signals.backend.temporal.inbox_notification import (
_compute_inbox_notification_state,
_send_report_inbox_notifications,
)
-from products.tasks.backend.models import Task, TaskRun
TASK_QUEUE = "test-inbox-notification-queue"
@@ -31,6 +31,8 @@ def _make_report(team: Team, status: str = SignalReport.Status.READY) -> SignalR
def _link_implementation_task(team: Team, report: SignalReport, *, pr_url: str | None, run_status: str) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
)
@@ -58,6 +60,7 @@ def test_state_no_implementation_task(team):
@pytest.mark.django_db
def test_state_task_with_pr(team):
+ TaskRun = apps.get_model("tasks", "TaskRun")
report = _make_report(team)
_link_implementation_task(team, report, pr_url="https://github.com/o/r/pull/1", run_status=TaskRun.Status.COMPLETED)
state = _compute_inbox_notification_state(team.id, str(report.id))
@@ -66,6 +69,7 @@ def test_state_task_with_pr(team):
@pytest.mark.django_db
def test_state_task_running_no_pr(team):
+ TaskRun = apps.get_model("tasks", "TaskRun")
report = _make_report(team)
_link_implementation_task(team, report, pr_url=None, run_status=TaskRun.Status.IN_PROGRESS)
state = _compute_inbox_notification_state(team.id, str(report.id))
@@ -74,6 +78,7 @@ def test_state_task_running_no_pr(team):
@pytest.mark.django_db
def test_state_task_failed_no_pr_is_terminal(team):
+ TaskRun = apps.get_model("tasks", "TaskRun")
report = _make_report(team)
_link_implementation_task(team, report, pr_url=None, run_status=TaskRun.Status.FAILED)
state = _compute_inbox_notification_state(team.id, str(report.id))
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 55e2fd91da70..54baaa087c49 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -3,11 +3,14 @@ from __future__ import annotations
import random
import asyncio
from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING
import pytest
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.apps import apps
+
import pytest_asyncio
from asgiref.sync import sync_to_async
from temporalio.testing import ActivityEnvironment
@@ -28,7 +31,9 @@ from products.signals.backend.scout_harness.skill_loader import (
from products.signals.backend.scout_harness.tools.runs import _build_task_url, _to_detail, _to_summary
from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, run_signals_scout_activity
from products.skills.backend.models.skills import LLMSkill, LLMSkillFile
-from products.tasks.backend.models import Task, TaskRun
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
@pytest_asyncio.fixture
@@ -68,6 +73,8 @@ async def aerrors_skill(ateam):
def _make_task_run(team: Team) -> TaskRun:
"""Minimal Task + TaskRun pair scoped to the given team."""
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=team,
title="scout run",
@@ -217,6 +224,7 @@ def _fake_start_invoking_hook(session: MagicMock, result: object):
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_successful_run_creates_bridge_row_pointing_at_task_run(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(
ateam, "I would investigate /checkout 500s next."
)
@@ -292,6 +300,7 @@ async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_failed_run_returns_failed_outcome_and_skips_bridge_insert(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
# Failure inside MultiTurnSession.start means we never get a session.task_run
# to bridge to — the runner's except path returns FAILED without persisting.
with (
@@ -321,6 +330,7 @@ async def test_failed_run_returns_failed_outcome_and_skips_bridge_insert(ateam,
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_successful_run_captures_run_finished_event(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)
with (
@@ -395,6 +405,7 @@ async def test_successful_run_captures_run_started_event(ateam, aerrors_skill):
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
with (
patch(
"products.signals.backend.scout_harness.runner.MultiTurnSession.start",
@@ -425,6 +436,8 @@ async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_cancelled_run_captures_run_finished_event(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
+
async def fake_spawn(**_kwargs):
raise asyncio.CancelledError("worker is shutting down")
@@ -455,6 +468,7 @@ async def test_missing_skill_does_not_create_run_row(ateam):
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_skip_if_running_prevents_concurrent_runs(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
# Seed an in-progress run for the same (team, skill) so the skip-if-running guard fires.
config = await database_sync_to_async(SignalScoutConfig.objects.create)(
team=ateam, skill_name="signals-scout-errors"
@@ -491,6 +505,7 @@ async def test_skip_if_running_lock_keys_on_team_and_skill_not_just_team(ateam,
coordinator can dispatch several due scouts for one team in a single tick. The
skip-if-running guard locks on `(team, skill_name)` rather than `(team, config_id)`
so this works."""
+ TaskRun = apps.get_model("tasks", "TaskRun")
config = await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam)
# A different skill for the same team is in flight — should NOT block. Run status lives
# on the linked TaskRun now, so stand up a real IN_PROGRESS TaskRun + bridge row.
@@ -522,6 +537,7 @@ async def test_skip_if_running_lock_keys_on_team_and_skill_not_just_team(ateam,
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_stale_in_progress_run_is_reaped_and_unblocks_dispatch(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
# An IN_PROGRESS run orphaned by a crashed worker must not block the lane forever. The
# stale-run self-heal fails any run older than STALE_RUN_CUTOFF_S before the skip-if-running
# guard, so a fresh dispatch proceeds and the orphan is marked FAILED.
@@ -563,6 +579,7 @@ async def test_stale_in_progress_run_is_reaped_and_unblocks_dispatch(ateam, aerr
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_recent_in_progress_run_is_not_reaped_and_still_blocks(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
# A genuinely in-flight run (younger than the cutoff) must still single-flight — the
# self-heal must not reap a live run out from under itself.
config = await database_sync_to_async(SignalScoutConfig.objects.create)(
@@ -596,6 +613,7 @@ async def test_recent_in_progress_run_is_not_reaped_and_still_blocks(ateam, aerr
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_stale_run_reap_captures_run_reaped_event(ateam, aerrors_skill):
+ TaskRun = apps.get_model("tasks", "TaskRun")
# Reaping an orphan emits `signals_scout_run_reaped` — the strand's only event (a reaped
# run never reaches the finalize path, so it emits no `signals_scout_run_finished`). This
# is what makes the worker-death / mass-stall shape alertable with no warehouse lag.
@@ -660,6 +678,8 @@ async def test_cancelled_run_re_raises(ateam, aerrors_skill):
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_activity_returns_completed_outcome(ateam):
+ TaskRun = apps.get_model("tasks", "TaskRun")
+
async def fake_arun(**_kwargs):
return RunResult(
run_id="abc",
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 29402254cf2b..b8fe1c17b73c 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -1,8 +1,12 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
+from django.apps import apps
+
from parameterized import parameterized
from rest_framework import status
@@ -27,7 +31,9 @@ from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY
from products.signals.backend.scout_harness.tools.profile import compute_project_profile
from products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_ids
from products.skills.backend.models.skills import LLMSkill
-from products.tasks.backend.models import Task, TaskRun
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
def _authenticate_as_scout(test: APIBaseTest) -> None:
@@ -60,6 +66,8 @@ def _authenticate_as_scout(test: APIBaseTest) -> None:
def _make_task_run(team: Team, *, status: str | None = None) -> TaskRun:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=team,
title="scout run",
@@ -73,8 +81,11 @@ def _make_task_run(team: Team, *, status: str | None = None) -> TaskRun:
return task_run
-def _make_run(team: Team, *, task_run_status: str = TaskRun.Status.IN_PROGRESS, **overrides) -> SignalScoutRun:
+def _make_run(team: Team, *, task_run_status: str | None = None, **overrides) -> SignalScoutRun:
"""Build a SignalScoutRun bridge row whose TaskRun is in the given status."""
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ if task_run_status is None:
+ task_run_status = TaskRun.Status.IN_PROGRESS
config, _ = SignalScoutConfig.objects.get_or_create(
team=team, skill_name="signals-scout-general", defaults={"emit": True}
)
@@ -156,6 +167,7 @@ class TestScoutHarnessRunsAPI(APIBaseTest):
assert ids == [str(errors.id)]
def test_list_surfaces_error_and_failure_reason_for_failed_run(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = _make_run(self.team, task_run_status=TaskRun.Status.FAILED)
TaskRun.objects.filter(id=run.task_run_id).update(error_message="boom: sandbox died\nstack line 2")
response = self.client.get(self._list_url())
@@ -165,6 +177,7 @@ class TestScoutHarnessRunsAPI(APIBaseTest):
assert row["failure_reason"] == "boom: sandbox died"
def test_retrieve_returns_bridge_projection(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = _make_run(self.team, summary="looked at /checkout, nothing actionable")
response = self.client.get(self._detail_url(str(run.id)))
assert response.status_code == status.HTTP_200_OK
@@ -435,6 +448,7 @@ class TestScoutHarnessEmitFindingAPI(APIBaseTest):
mock_emit.assert_not_called()
def test_emit_finding_rejects_non_in_progress_run(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = _make_run(self.team, task_run_status=TaskRun.Status.COMPLETED)
response = self.client.post(self._emit_signal_url(str(run.id)), data=self._payload(), format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.py
index 9bce6bb99526..b13297282173 100644
--- a/products/signals/backend/test/test_scout_harness_tools.py
+++ b/products/signals/backend/test/test_scout_harness_tools.py
@@ -1,11 +1,13 @@
from __future__ import annotations
from datetime import timedelta
+from typing import TYPE_CHECKING
import pytest
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, patch
+from django.apps import apps
from django.utils import timezone
import pytest_asyncio
@@ -44,10 +46,14 @@ from products.signals.backend.scout_harness.tools.scratchpad import (
MAX_SCRATCHPAD_CONTENT_LENGTH,
MAX_SCRATCHPAD_SEARCH_LIMIT,
)
-from products.tasks.backend.models import Task, TaskRun
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
def _make_task_run(team, *, status: str | None = None) -> TaskRun:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=team,
title="scout run",
@@ -67,6 +73,7 @@ def _create_run(team, **overrides) -> SignalScoutRun:
Default TaskRun status is COMPLETED so summary/detail surface a terminal
state — tests that need IN_PROGRESS pass `task_run_status` explicitly.
"""
+ TaskRun = apps.get_model("tasks", "TaskRun")
task_run_status = overrides.pop("task_run_status", TaskRun.Status.COMPLETED)
task_run = _make_task_run(team, status=task_run_status)
defaults: dict = {
@@ -139,6 +146,7 @@ class TestSearchRecentRuns(BaseTest):
assert len(hits) == MAX_RUN_SEARCH_LIMIT
def test_summary_surfaces_status_from_linked_task_run(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = _create_run(self.team, task_run_status=TaskRun.Status.COMPLETED)
hits = search_recent_runs(team_id=self.team.id, limit=1)
@@ -220,6 +228,7 @@ class TestSearchRecentRuns(BaseTest):
assert [h.run_id for h in hits] == [str(v1.id)]
def test_failure_reason_and_error_surface_for_failed_run(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = _create_run(self.team, task_run_status=TaskRun.Status.FAILED)
TaskRun.objects.filter(id=run.task_run_id).update(error_message="boom: sandbox died\nstack line 2")
@@ -233,6 +242,7 @@ class TestSearchRecentRuns(BaseTest):
assert detail.failure_reason == "boom: sandbox died"
def test_failure_reason_falls_back_when_no_error_message(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = _create_run(self.team, task_run_status=TaskRun.Status.CANCELLED)
hit = search_recent_runs(team_id=self.team.id, limit=1)[0]
@@ -242,6 +252,7 @@ class TestSearchRecentRuns(BaseTest):
assert hit.run_id == str(run.id)
def test_no_failure_reason_for_completed_run(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
_create_run(self.team, task_run_status=TaskRun.Status.COMPLETED)
hit = search_recent_runs(team_id=self.team.id, limit=1)[0]
@@ -250,6 +261,7 @@ class TestSearchRecentRuns(BaseTest):
assert hit.failure_reason is None
def test_completed_run_with_error_message_does_not_surface_error(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
# A stray error_message on a run that still reached COMPLETED must not surface as a
# failure signal — `error` and `failure_reason` are gated on terminal-failure status.
run = _create_run(self.team, task_run_status=TaskRun.Status.COMPLETED)
@@ -261,6 +273,7 @@ class TestSearchRecentRuns(BaseTest):
assert hit.failure_reason is None
def test_failure_reason_truncated_to_max_length(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
run = _create_run(self.team, task_run_status=TaskRun.Status.FAILED)
long_message = "x" * (MAX_FAILURE_REASON_LENGTH + 50)
TaskRun.objects.filter(id=run.task_run_id).update(error_message=long_message)
@@ -650,6 +663,7 @@ async def ateam_emit(aorganization_emit):
@pytest_asyncio.fixture
async def arun_emit(ateam_emit):
+ TaskRun = apps.get_model("tasks", "TaskRun")
config = await database_sync_to_async(SignalScoutConfig.objects.get)(team=ateam_emit)
task_run = await database_sync_to_async(_make_task_run)(ateam_emit, status=TaskRun.Status.IN_PROGRESS)
run = await database_sync_to_async(SignalScoutRun.objects.create)(
@@ -1055,6 +1069,7 @@ def test_emit_finding_sync_rejects_team_run_mismatch(db) -> None:
"""Same guard as the async path, exercised against `emit_finding_sync`."""
from posthog.models import Organization, Team
+ TaskRun = apps.get_model("tasks", "TaskRun")
org = Organization.objects.create(name="sync-mismatch-org", is_ai_data_processing_approved=True)
owning_team = Team.objects.create(organization=org, name="owner")
other_team = Team.objects.create(organization=org, name="other")
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index f7d0363484b5..b81ac759db35 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -2,11 +2,13 @@ import json
import uuid
from datetime import timedelta
from types import SimpleNamespace
+from typing import TYPE_CHECKING
from urllib.parse import urlencode
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.apps import apps
from django.core.cache import cache
from django.utils import timezone
@@ -18,7 +20,9 @@ from posthog.models.team.team import Team
from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportTask
-from products.tasks.backend.models import Task, TaskRun
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import Task, TaskRun
class TestSignalReportDeleteAPI(APIBaseTest):
@@ -506,7 +510,9 @@ class TestSignalReportListAPI(APIBaseTest):
def _create_implementation_task_with_run(
self, report: SignalReport, *, pr_url: str | None = None, output: dict | None = None
- ) -> tuple[Task, TaskRun]:
+ ) -> "tuple[Task, TaskRun]":
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=self.team,
title="Implementation task",
@@ -573,6 +579,8 @@ class TestSignalReportListAPI(APIBaseTest):
assert row["implementation_pr_url"] is None
def test_implementation_pr_url_uses_latest_task_run(self):
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
report = self._create_report()
task = Task.objects.create(
team=self.team,
diff --git a/products/signals/backend/test/test_signal_scout_models.py b/products/signals/backend/test/test_signal_scout_models.py
index 6801e22f2f6b..4fe73c7d5b60 100644
--- a/products/signals/backend/test/test_signal_scout_models.py
+++ b/products/signals/backend/test/test_signal_scout_models.py
@@ -1,8 +1,10 @@
from contextlib import AbstractContextManager
+from typing import TYPE_CHECKING
import pytest
from posthog.test.base import BaseTest
+from django.apps import apps
from django.db import IntegrityError
from django.utils import timezone
@@ -11,7 +13,9 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.scoping import team_scope
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun, SignalScratchpad
-from products.tasks.backend.models import Task, TaskRun
+
+if TYPE_CHECKING:
+ from products.tasks.backend.models import TaskRun
class _ScoutTeamScopedTestMixin:
@@ -91,8 +95,10 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
SignalScoutConfig.all_teams.filter(pk=config.pk).update(last_run_at=timezone.now())
assert not ActivityLog.objects.filter(scope="SignalScoutConfig", item_id=str(config.id)).exists()
- def _make_task_run(self) -> TaskRun:
+ def _make_task_run(self) -> "TaskRun":
"""Minimal Task + TaskRun pair scoped to this test's team."""
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=self.team,
title="scout run",
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index d3a2a8d71333..50ccabd8bfaf 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -3,6 +3,7 @@ import json
import pytest
from unittest.mock import MagicMock, patch
+from django.apps import apps
from django.conf import settings
from social_django.models import UserSocialAuth
@@ -30,7 +31,6 @@ from products.signals.backend.slack_inbox_notifications import (
_summary_excerpt,
dispatch_inbox_item_notifications,
)
-from products.tasks.backend.models import Task, TaskRun
@pytest.mark.parametrize(
@@ -353,6 +353,8 @@ def _create_implementation_task_with_run(
*,
pr_url: str | None = None,
) -> None:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(
team=team,
title="Implementation task",
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 41b4ef2bd0e3..4d95a77354cc 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -23,7 +23,6 @@ from django.db.models import (
Value,
When,
)
-from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions import Cast, Coalesce
import structlog
@@ -99,7 +98,7 @@ from products.signals.backend.temporal.types import (
SignalReportDeletionWorkflowInputs,
SignalReportReingestionWorkflowInputs,
)
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.facade import api as tasks_facade
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
logger = structlog.get_logger(__name__)
@@ -629,12 +628,9 @@ class SignalReportViewSet(
# `pr_url`. Mirrors `_annotate_implementation_pr_url`, but as a boolean
# EXISTS so it can be used as a filter (and counted) without the
# per-row PR-url annotation, which the list action skips for performance.
- return Exists(
- TaskRun.objects.filter(
- task__signal_report_tasks__report_id=OuterRef("id"),
- task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
- output__pr_url__isnull=False,
- ).exclude(output__pr_url="")
+ return tasks_facade.task_run_pr_url_exists_subquery(
+ task__signal_report_tasks__report_id=OuterRef("id"),
+ task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
)
def _apply_signal_report_implementation_pr_filter(self, queryset):
@@ -869,17 +865,9 @@ class SignalReportViewSet(
def _annotate_implementation_pr_url(self, queryset):
# Find the latest TaskRun output->pr_url for the implementation task linked to each report.
# Path: SignalReportTask(relationship=implementation) -> Task -> TaskRun(latest) -> output->'pr_url'
- latest_impl_pr_url = Subquery(
- TaskRun.objects.filter(
- task__signal_report_tasks__report_id=OuterRef("id"),
- task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
- output__pr_url__isnull=False,
- )
- .exclude(output__pr_url="")
- .order_by("-created_at")
- .annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
- .values("output_pr_url_text")[:1],
- output_field=CharField(),
+ latest_impl_pr_url = tasks_facade.latest_task_run_pr_url_subquery(
+ task__signal_report_tasks__report_id=OuterRef("id"),
+ task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
)
return queryset.annotate(implementation_pr_url=latest_impl_pr_url)
diff --git a/products/signals/skills/debugging-signals-pipeline/SKILL.md b/products/signals/skills/debugging-signals-pipeline/SKILL.md
index c33eddd1b7c4..97b6fd33c1a1 100644
--- a/products/signals/skills/debugging-signals-pipeline/SKILL.md
+++ b/products/signals/skills/debugging-signals-pipeline/SKILL.md
@@ -223,8 +223,8 @@ grep CLICKHOUSE_DATABASE .env
- Buffer workflow: `products/signals/backend/temporal/buffer.py`
- Grouping workflow: `products/signals/backend/temporal/grouping_v2.py`
- Report summary workflow: `products/signals/backend/temporal/summary.py`
-- Docker sandbox implementation: `products/tasks/backend/services/docker_sandbox.py`
+- Docker sandbox implementation: `products/tasks/backend/logic/services/docker_sandbox.py`
- Sandbox Dockerfiles: `products/tasks/backend/sandbox/images/`
-- Agent log polling: `products/tasks/backend/services/custom_prompt_internals.py`
+- Agent log polling: `products/tasks/backend/logic/services/custom_prompt_internals.py`
- Cleanup command: `products/signals/backend/management/commands/cleanup_signals.py`
- Management command docs: `products/signals/backend/management/CLAUDE.md`
diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.py
index c5fb909577f0..9997083da10e 100644
--- a/products/slack_app/backend/tests/test_followup_forwarding.py
+++ b/products/slack_app/backend/tests/test_followup_forwarding.py
@@ -165,7 +165,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
bot_id_patcher.start()
self.addCleanup(bot_id_patcher.stop)
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_no_repo_task_starts_with_pr_creation_enabled(self, mock_slack_cls, mock_execute_workflow):
mock_slack_instance = MagicMock()
@@ -210,7 +210,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert mapping.task_id == task.id
assert mapping.task_run_id == task.latest_run.id
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_persists_explicit_event_id_in_workflow_id(self, mock_slack_cls, mock_execute_workflow):
mock_slack_instance = MagicMock()
@@ -240,7 +240,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
task = self.Task.objects.get(team=self.team)
assert task.latest_run.state["slack_mention_workflow_id"] == "posthog-code-mention-T_SLACK:Ev01234567"
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_persists_repo_research_ids_when_provided(self, mock_slack_cls, mock_execute_workflow):
mock_slack_instance = MagicMock()
@@ -269,7 +269,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert state["repo_research_task_id"] == "11111111-1111-1111-1111-111111111111"
assert state["repo_research_run_id"] == "22222222-2222-2222-2222-222222222222"
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_no_repo_research_ids_when_not_provided(self, mock_slack_cls, mock_execute_workflow):
# The unambiguous path (explicit mention / cascade auto) never runs the
@@ -297,7 +297,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert "repo_research_task_id" not in task.latest_run.state
assert "repo_research_run_id" not in task.latest_run.state
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_no_repo_task_falls_back_to_team_github_integration(self, mock_slack_cls, mock_execute_workflow):
Integration.objects.create(team=self.team, kind="github", integration_id="12345", config={})
@@ -327,7 +327,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert task.latest_run.state["pr_authorship_mode"] == "bot"
mock_execute_workflow.assert_called_once()
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_no_repo_task_falls_back_to_team_github_integration_when_user_token_unusable(
self, mock_slack_cls, mock_execute_workflow
@@ -366,7 +366,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert task.latest_run.state["pr_authorship_mode"] == "bot"
mock_execute_workflow.assert_called_once()
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_no_repo_task_prefers_user_github_integration(self, mock_slack_cls, mock_execute_workflow):
UserIntegration.objects.create(
@@ -401,7 +401,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert task.latest_run.state["pr_authorship_mode"] == "user"
mock_execute_workflow.assert_called_once()
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_description_uses_initiator_as_prompt_with_thread_as_context(self, mock_slack_cls, mock_execute_workflow):
mock_slack_instance = MagicMock()
@@ -448,7 +448,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
last_context_pos = task.description.index("we just need to inject those better")
assert placeholder_pos < last_context_pos
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_description_with_no_thread_context_is_just_the_prompt(self, mock_slack_cls, mock_execute_workflow):
mock_slack_instance = MagicMock()
@@ -473,7 +473,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
task = self.Task.objects.get(team=self.team)
assert task.description == "do something"
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_description_encloses_thread_context_in_a_tag(self, mock_slack_cls, mock_execute_workflow):
# A Slack participant shouldn't be able to forge the context delimiter to
@@ -515,7 +515,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
)
assert task.description.endswith("do something")
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
@patch("ee.billing.quota_limiting.is_team_limited", return_value=True)
def test_quota_exceeded_blocks_task_creation_with_thread_message(
@@ -618,7 +618,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
assert result is True
_assert_quota_denial_posted(mock_slack_instance, "C123", "1234.5678")
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_terminal_run_resumes_same_task(self, mock_slack_cls, mock_execute_workflow):
self.task_run.status = self.TaskRun.Status.COMPLETED
@@ -662,7 +662,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
)
mock_slack_instance.client.chat_postMessage.assert_not_called()
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_terminal_no_repo_run_resumes_with_pr_creation_enabled(self, mock_slack_cls, mock_execute_workflow):
self.task.repository = None
@@ -681,7 +681,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
mock_execute_workflow.assert_called_once()
assert mock_execute_workflow.call_args.kwargs["create_pr"] is True
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_terminal_run_seeds_pr_url_into_new_run_state(self, mock_slack_cls, mock_execute_workflow):
self.task_run.status = self.TaskRun.Status.COMPLETED
@@ -739,7 +739,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
call_kwargs = mock_slack_instance.client.chat_postMessage.call_args.kwargs
assert "original task creator" in call_kwargs["text"]
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow", side_effect=Exception("boom"))
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow", side_effect=Exception("boom"))
@patch("posthog.models.integration.SlackIntegration")
def test_terminal_run_workflow_start_failure_returns_true_with_error(self, mock_slack_cls, mock_execute_workflow):
self.task_run.status = self.TaskRun.Status.COMPLETED
@@ -777,8 +777,11 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
mock_resolve.assert_called_once_with(mock_slack_instance, self.integration, "U_BOB", "C123", "1234.5678")
mock_slack_instance.client.chat_postMessage.assert_not_called()
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
@patch("products.slack_app.backend.api.resolve_slack_user")
@patch("posthog.models.integration.SlackIntegration")
def test_cross_user_followup_authorized_prefixes_actor_name(
@@ -811,8 +814,11 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
]
assert not post_calls
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
@patch("products.slack_app.backend.api.resolve_slack_user")
@patch("posthog.models.integration.SlackIntegration")
def test_cross_user_followup_falls_back_to_email_when_no_full_name(
@@ -848,7 +854,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
mock_resolve.assert_called_once_with(mock_slack_instance, self.integration, "U_BOB", "C123", "1234.5678")
mock_slack_instance.client.chat_postMessage.assert_not_called()
- @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("products.slack_app.backend.api.resolve_slack_user")
@patch("posthog.models.integration.SlackIntegration")
def test_cross_user_terminal_run_resume_prefixes_actor_name(
@@ -891,8 +897,11 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
call_kwargs = mock_slack_instance.client.chat_postMessage.call_args.kwargs
assert "still starting up" in call_kwargs["text"]
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
@patch("posthog.models.integration.SlackIntegration")
def test_successful_forwarding(self, mock_slack_cls, mock_send, mock_token):
mapping = self._create_mapping()
@@ -929,8 +938,11 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
assert mapping.latest_actor_slack_user_id == "U_ALICE"
assert mapping.mentioning_slack_user_id == "U_ALICE"
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
@patch("posthog.models.integration.SlackIntegration")
def test_forwarding_failure_posts_error(self, mock_slack_cls, mock_send, mock_token):
self._create_mapping()
@@ -946,8 +958,11 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
call_kwargs = mock_slack_instance.client.chat_postMessage.call_args.kwargs
assert "couldn't deliver" in call_kwargs["text"]
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
@patch("posthog.models.integration.SlackIntegration")
def test_timeout_delegates_to_relay_without_posting(self, mock_slack_cls, mock_send, mock_token):
self._create_mapping()
@@ -972,8 +987,11 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
)
mock_slack_instance.client.reactions_remove.assert_not_called()
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
@patch("posthog.models.integration.SlackIntegration")
def test_connection_error_retries_and_succeeds(self, mock_slack_cls, mock_send, mock_token):
self._create_mapping()
diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.py
index c6b3edf8990f..932c17e2eb9a 100644
--- a/products/slack_app/backend/tests/test_integration_resolver.py
+++ b/products/slack_app/backend/tests/test_integration_resolver.py
@@ -1,5 +1,7 @@
import pytest
+from django.apps import apps
+
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
@@ -7,7 +9,6 @@ from posthog.models.user import User
from products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping
from products.slack_app.backend.services.integration_resolver import load_integrations
-from products.tasks.backend.models import Task, TaskRun
WORKSPACE = "T_WS"
SLACK_USER = "U001"
@@ -60,6 +61,8 @@ class TestResolveIntegration:
channel: str = "C1",
thread_ts: str = "123.456",
) -> SlackThreadTaskMapping:
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(team=team, title="t")
task_run = TaskRun.objects.create(team=team, task=task)
return SlackThreadTaskMapping.objects.create(
@@ -350,7 +353,8 @@ class TestResolveIntegration:
assert result.integration == self.integration_a
def test_unresolved_user_still_honors_thread_mapping(self):
- from products.tasks.backend.models import Task, TaskRun
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(team=self.team_b, title="t")
task_run = TaskRun.objects.create(team=self.team_b, task=task)
diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
index 16a0f81c33fe..ade48a77aca6 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -329,13 +329,13 @@ class TestRepoPickerOptions(TestCase):
mock_sync_connect.return_value.start_workflow.assert_called_once()
mock_asyncio_run.assert_called_once()
- @patch("products.tasks.backend.services.agent_command.send_cancel")
- @patch("products.tasks.backend.models.TaskRun")
+ @patch("products.tasks.backend.facade.api.send_cancel")
+ @patch("products.tasks.backend.facade.api.get_task_run")
@patch("posthog.models.integration.Integration")
@patch("posthog.models.integration.SlackIntegration")
@patch("posthog.temporal.common.client.sync_connect")
def test_terminate_action_signals_workflow(
- self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_task_run_model, mock_send_cancel
+ self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_get_task_run, mock_send_cancel
):
from products.slack_app.backend.tasks import process_posthog_code_task_termination
@@ -343,18 +343,17 @@ class TestRepoPickerOptions(TestCase):
success=False, status_code=502, error="Connection refused", retryable=True
)
- mock_run = MagicMock()
- mock_run.id = "run-1"
- mock_run.task_id = "task-1"
- mock_run.team_id = self.team.id
- mock_run.status = "in_progress"
- mock_run.is_terminal = False
- mock_run.workflow_id = "task-processing-task-1-run-1"
- mock_run.state = {"sandbox_url": "https://sandbox.example.com/rpc"}
- mock_task_run_model.Status.COMPLETED = "completed"
- mock_task_run_model.Status.FAILED = "failed"
- mock_task_run_model.Status.CANCELLED = "cancelled"
- mock_task_run_model.objects.select_related.return_value.get.return_value = mock_run
+ mock_get_task_run.return_value = SimpleNamespace(
+ id="run-1",
+ task_id="task-1",
+ team_id=self.team.id,
+ status="in_progress",
+ is_terminal=False,
+ workflow_id="task-processing-task-1-run-1",
+ created_by_id=None,
+ created_by_distinct_id=None,
+ state={"sandbox_url": "https://sandbox.example.com/rpc"},
+ )
mock_integration = MagicMock()
mock_integration.team_id = self.team.id
@@ -396,12 +395,12 @@ class TestRepoPickerOptions(TestCase):
mock_handle.signal.assert_called_once()
mock_slack_client.chat_update.assert_called_once()
- @patch("products.tasks.backend.models.TaskRun")
+ @patch("products.tasks.backend.facade.api.get_task_run")
@patch("posthog.models.integration.Integration")
@patch("posthog.models.integration.SlackIntegration")
@patch("posthog.temporal.common.client.sync_connect")
def test_terminate_action_without_expected_user_is_denied(
- self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_task_run_model
+ self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_get_task_run
):
from products.slack_app.backend.tasks import process_posthog_code_task_termination
@@ -427,28 +426,28 @@ class TestRepoPickerOptions(TestCase):
process_posthog_code_task_termination(payload)
mock_integration_model.objects.get.assert_not_called()
- mock_task_run_model.objects.select_related.assert_not_called()
+ mock_get_task_run.assert_not_called()
mock_sync_connect.assert_not_called()
mock_slack_integration.assert_not_called()
- @patch("products.tasks.backend.models.TaskRun")
+ @patch("products.tasks.backend.facade.api.get_task_run")
@patch("posthog.models.integration.Integration")
@patch("posthog.models.integration.SlackIntegration")
@patch("posthog.temporal.common.client.sync_connect")
def test_terminate_action_on_terminal_run_posts_feedback(
- self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_task_run_model
+ self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_get_task_run
):
from products.slack_app.backend.tasks import process_posthog_code_task_termination
- mock_run = MagicMock()
- mock_run.id = "run-1"
- mock_run.task_id = "task-1"
- mock_run.team_id = self.team.id
- mock_run.status = "completed"
- mock_task_run_model.Status.COMPLETED = "completed"
- mock_task_run_model.Status.FAILED = "failed"
- mock_task_run_model.Status.CANCELLED = "cancelled"
- mock_task_run_model.objects.select_related.return_value.get.return_value = mock_run
+ mock_get_task_run.return_value = SimpleNamespace(
+ id="run-1",
+ task_id="task-1",
+ team_id=self.team.id,
+ status="completed",
+ is_terminal=True,
+ created_by_id=None,
+ created_by_distinct_id=None,
+ )
mock_integration = MagicMock()
mock_integration.team_id = self.team.id
@@ -482,20 +481,17 @@ class TestRepoPickerOptions(TestCase):
mock_sync_connect.assert_not_called()
mock_slack_client.chat_postMessage.assert_called_once()
- @patch("products.tasks.backend.models.TaskRun")
+ @patch("products.tasks.backend.facade.api.get_task_run")
@patch("posthog.models.integration.Integration")
@patch("posthog.models.integration.SlackIntegration")
@patch("posthog.temporal.common.client.sync_connect")
def test_terminate_action_with_mismatched_team_run_is_noop(
- self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_task_run_model
+ self, mock_sync_connect, mock_slack_integration, mock_integration_model, mock_get_task_run
):
from products.slack_app.backend.tasks import process_posthog_code_task_termination
- mock_task_run_model.DoesNotExist = Exception
- mock_task_run_model.Status.COMPLETED = "completed"
- mock_task_run_model.Status.FAILED = "failed"
- mock_task_run_model.Status.CANCELLED = "cancelled"
- mock_task_run_model.objects.select_related.return_value.get.side_effect = mock_task_run_model.DoesNotExist
+ # Team-scoped lookup returns nothing when the run belongs to another team.
+ mock_get_task_run.return_value = None
mock_integration = MagicMock()
mock_integration.team_id = self.team.id
diff --git a/products/slack_app/backend/tests/test_terminate.py b/products/slack_app/backend/tests/test_terminate.py
index 80075894c5fa..43187e9c8b5a 100644
--- a/products/slack_app/backend/tests/test_terminate.py
+++ b/products/slack_app/backend/tests/test_terminate.py
@@ -61,8 +61,11 @@ class TestProcessPostHogCodeTaskTermination(TestCase):
"message": {"ts": "1234.5678", "thread_ts": "1234.5678"},
}
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_cancel")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_cancel")
@patch("posthog.temporal.common.client.sync_connect")
def test_command_dispatched_on_success(self, mock_sync_connect, mock_send_cancel, mock_token):
mock_send_cancel.return_value = _command_result(success=True, status_code=200)
@@ -79,9 +82,12 @@ class TestProcessPostHogCodeTaskTermination(TestCase):
mock_send_cancel.assert_called_once_with(self.task_run, auth_token="jwt-token")
mock_handle.signal.assert_called_once()
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
@patch("posthog.temporal.common.client.sync_connect")
- @patch("products.tasks.backend.services.agent_command.send_cancel")
+ @patch("products.tasks.backend.logic.services.agent_command.send_cancel")
def test_fallback_signal_on_connection_error(self, mock_send_cancel, mock_sync_connect, mock_token):
mock_send_cancel.return_value = _command_result(
success=False, status_code=502, error="Connection refused", retryable=True
@@ -98,8 +104,11 @@ class TestProcessPostHogCodeTaskTermination(TestCase):
mock_send_cancel.assert_called_once_with(self.task_run, auth_token="jwt-token")
mock_handle.signal.assert_called_once()
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt-token")
- @patch("products.tasks.backend.services.agent_command.send_cancel")
+ @patch(
+ "products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token",
+ return_value="jwt-token",
+ )
+ @patch("products.tasks.backend.logic.services.agent_command.send_cancel")
def test_still_signals_on_4xx(self, mock_send_cancel, mock_token):
mock_send_cancel.return_value = _command_result(
success=False, status_code=401, error="Unauthorized", retryable=False
@@ -120,7 +129,7 @@ class TestProcessPostHogCodeTaskTermination(TestCase):
payload = self._make_payload(user_id="U_ALICE")
payload["user"]["id"] = "U_BOB"
# Should return early without any command or signal
- with patch("products.tasks.backend.services.agent_command.send_cancel") as mock_send:
+ with patch("products.tasks.backend.logic.services.agent_command.send_cancel") as mock_send:
process_posthog_code_task_termination(payload)
mock_send.assert_not_called()
diff --git a/products/streamlit_apps/backend/logic/app_runtime.py b/products/streamlit_apps/backend/logic/app_runtime.py
index b750a655410b..a6d8f95053ab 100644
--- a/products/streamlit_apps/backend/logic/app_runtime.py
+++ b/products/streamlit_apps/backend/logic/app_runtime.py
@@ -29,8 +29,8 @@ from products.streamlit_apps.backend.models import (
StreamlitAppVersion,
)
from products.streamlit_apps.backend.tasks import reset_streamlit_app_restart_count_if_stable
-from products.tasks.backend.models import SandboxSnapshot
-from products.tasks.backend.services.sandbox import SandboxBase, SandboxConfig, SandboxTemplate, get_sandbox_class
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.sandbox import SandboxBase, SandboxConfig, SandboxTemplate, get_sandbox_class
logger = structlog.get_logger(__name__)
@@ -393,11 +393,8 @@ class AppRuntimeService:
modal_image_id = sandbox.create_snapshot()
- snapshot = SandboxSnapshot.objects.create(
- external_id=modal_image_id,
- status=SandboxSnapshot.Status.COMPLETE,
- )
- version.snapshot_id = str(snapshot.id)
+ snapshot_id = tasks_facade.create_completed_sandbox_snapshot(external_id=modal_image_id)
+ version.snapshot_id = str(snapshot_id)
version.snapshot_created_at = timezone.now()
version.save(update_fields=["snapshot_id", "snapshot_created_at"])
diff --git a/products/streamlit_apps/backend/tests/test_app_runtime.py b/products/streamlit_apps/backend/tests/test_app_runtime.py
index dc654087b4e3..39b9cb27ec6e 100644
--- a/products/streamlit_apps/backend/tests/test_app_runtime.py
+++ b/products/streamlit_apps/backend/tests/test_app_runtime.py
@@ -82,11 +82,12 @@ class TestAppRuntimeStartApp(BaseTest):
assert version.snapshot_id is not None
assert version.snapshot_created_at is not None
- from products.tasks.backend.models import SandboxSnapshot
+ from products.tasks.backend.facade import api as tasks_facade
- snapshot = SandboxSnapshot.objects.get(id=version.snapshot_id)
+ snapshot = tasks_facade.get_sandbox_snapshot(version.snapshot_id)
+ assert snapshot is not None
assert snapshot.external_id == "snapshot-abc"
- assert snapshot.status == SandboxSnapshot.Status.COMPLETE
+ assert snapshot.status == tasks_facade.SandboxSnapshotStatus.COMPLETE
def test_cold_start_ignores_requirements_txt_in_zip(self, mock_get_sandbox_class, _mock_wait):
"""requirements.txt support was deleted: a zip with one is accepted but
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
deleted file mode 100644
index 23d9dbfc2d36..000000000000
--- a/products/tasks/backend/api.py
+++ /dev/null
@@ -1,3003 +0,0 @@
-import os
-import re
-import json
-import uuid
-import asyncio
-import logging
-import builtins
-from collections.abc import AsyncGenerator
-from datetime import datetime, timedelta
-from typing import Any, cast
-from urllib.parse import parse_qs, urlparse
-
-from django.conf import settings
-from django.db import models, transaction
-from django.db.models import F, OuterRef, Q, Subquery
-from django.db.models.functions import JSONObject
-from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
-from django.utils import timezone
-
-import requests as http_requests
-import jsonschema
-import posthoganalytics
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
-from rest_framework import status, viewsets
-from rest_framework.authentication import SessionAuthentication
-from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound
-from rest_framework.pagination import LimitOffsetPagination
-from rest_framework.permissions import IsAuthenticated
-from rest_framework.response import Response
-
-from posthog.api.mixins import validated_request
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.utils import ServerTimingsGathered
-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
-from posthog.event_usage import groups
-from posthog.models.integration import Integration
-from posthog.models.user_push_token import UserPushToken
-from posthog.permissions import APIScopePermission
-from posthog.rate_limit import CodeInviteThrottle
-from posthog.renderers import ServerSentEventRenderer
-from posthog.storage import object_storage
-from posthog.temporal.oauth import PosthogMcpScopes
-
-from products.slack_app.backend.models import SlackThreadTaskMapping
-
-from ee.hogai.utils.aio import async_to_sync
-
-from .access import has_tasks_access
-from .automation_service import (
- delete_automation_schedule,
- run_task_automation,
- sync_automation_schedule,
- update_automation_run_result,
-)
-from .metrics import (
- StreamConnectionOutcome,
- observe_stream_connection_closed,
- observe_stream_connection_opened,
- observe_stream_length_on_connect,
- observe_stream_resume_gap,
- origin_product_label,
-)
-from .models import (
- TASK_PRESENCE_TTL_SECONDS,
- CodeInvite,
- CodeInviteRedemption,
- SandboxEnvironment,
- Task,
- TaskAutomation,
- TaskPresence,
- TaskRun,
-)
-from .redis import get_tasks_cache, run_uses_dedicated_stream
-from .repository_readiness import compute_repository_readiness
-from .serializers import (
- CodeInviteRedeemRequestSerializer,
- ConnectionTokenResponseSerializer,
- RepositoryReadinessQuerySerializer,
- RepositoryReadinessResponseSerializer,
- SandboxEnvironmentListSerializer,
- SandboxEnvironmentSerializer,
- SlackThreadContextQuerySerializer,
- SlackThreadContextResponseSerializer,
- TaskAutomationSerializer,
- TaskListQuerySerializer,
- TaskPresenceBeaconRequestSerializer,
- TaskRepositoriesResponseSerializer,
- TaskRunAppendLogRequestSerializer,
- TaskRunArtifactPresignRequestSerializer,
- TaskRunArtifactPresignResponseSerializer,
- TaskRunArtifactsFinalizeUploadRequestSerializer,
- TaskRunArtifactsFinalizeUploadResponseSerializer,
- TaskRunArtifactsPrepareUploadRequestSerializer,
- TaskRunArtifactsPrepareUploadResponseSerializer,
- TaskRunArtifactsUploadRequestSerializer,
- TaskRunArtifactsUploadResponseSerializer,
- TaskRunBootstrapCreateRequestSerializer,
- TaskRunCommandRequestSerializer,
- TaskRunCommandResponseSerializer,
- TaskRunCreateRequestSchemaSerializer,
- TaskRunCreateRequestSerializer,
- TaskRunDetailSerializer,
- TaskRunErrorResponseSerializer,
- TaskRunRelayMessageRequestSerializer,
- TaskRunRelayMessageResponseSerializer,
- TaskRunSessionLogsQuerySerializer,
- TaskRunSetOutputRequestSerializer,
- TaskRunStartRequestSerializer,
- TaskRunUpdateSerializer,
- TaskSerializer,
- TaskStagedArtifactsFinalizeUploadRequestSerializer,
- TaskStagedArtifactsFinalizeUploadResponseSerializer,
- TaskStagedArtifactsPrepareUploadRequestSerializer,
- TaskStagedArtifactsPrepareUploadResponseSerializer,
- TaskSummariesRequestSerializer,
- TaskSummarySerializer,
- build_task_run_artifact_size_error,
- get_task_run_artifact_max_size_bytes,
-)
-from .services.code_usage_gate import cloud_usage_limit_response
-from .services.connection_token import create_sandbox_connection_token
-from .services.staged_artifacts import (
- RUN_ARTIFACT_TTL_DAYS,
- STAGED_ARTIFACT_TTL_DAYS,
- build_task_artifact_entry,
- build_task_staged_artifact_cache_key,
- build_task_staged_artifact_storage_path,
- cache_task_staged_artifact,
- get_safe_artifact_name,
- get_task_run_artifacts_by_id,
- get_task_staged_artifacts,
- tag_task_artifact,
-)
-from .stream.redis_stream import (
- TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
- TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,
- TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
- TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS,
- TaskRunRedisStream,
- TaskRunStreamError,
- get_task_run_stream_key,
-)
-from .temporal.client import (
- execute_posthog_code_agent_relay_workflow,
- execute_task_processing_workflow,
- resume_task_in_cloud_workflow,
- signal_task_followup_message,
-)
-from .temporal.process_task.utils import (
- GitHubCredentialSource,
- PrAuthorshipMode,
- RunSource,
- cache_github_user_token,
- get_pr_authorship_mode,
- get_provider_for_runtime_adapter,
- get_reasoning_effort_error,
- parse_run_state,
- resolve_user_github_integration_for_task,
- user_github_integration_is_usable,
-)
-from .visibility import task_run_visibility_q, task_visibility_q
-
-logger = logging.getLogger(__name__)
-TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS = 20.0
-TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME = "keepalive"
-TASK_RUN_STREAM_KEEPALIVE_PAYLOAD = {"type": "keepalive"}
-TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS = 60 * 60
-
-
-def _ensure_task_team_github_integration(task: Task) -> bool:
- if task.github_integration_id is not None:
- return True
-
- github_integration = Integration.objects.filter(team_id=task.team_id, kind="github").first()
- if github_integration is None:
- return False
-
- task.github_integration = github_integration
- task.save(update_fields=["github_integration", "updated_at"])
- return True
-
-
-def _resolve_cloud_pr_authorship_mode(
- task: Task,
- *,
- pr_authorship_mode: PrAuthorshipMode | str | None,
- request_user_id: int | None,
- github_user_token: str | None,
-) -> tuple[PrAuthorshipMode | str | None, Response | None]:
- if pr_authorship_mode != PrAuthorshipMode.USER or github_user_token:
- return pr_authorship_mode, None
-
- if task.created_by_id != request_user_id:
- return None, Response(
- {
- "type": "validation_error",
- "code": "github_authorization_required",
- "detail": "User-authored runs must be started by the task creator, or provide github_user_token.",
- "attr": "pr_authorship_mode",
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- user_github_integration = resolve_user_github_integration_for_task(task, allow_refresh=False)
- if user_github_integration is not None and user_github_integration_is_usable(user_github_integration):
- if task.github_user_integration_id != user_github_integration.integration.id:
- task.github_user_integration = user_github_integration.integration
- task.save(update_fields=["github_user_integration", "updated_at"])
- return PrAuthorshipMode.USER, None
-
- if _ensure_task_team_github_integration(task):
- return PrAuthorshipMode.BOT, None
-
- return None, Response(
- {
- "type": "validation_error",
- "code": "github_authorization_required",
- "detail": ("Link a GitHub account with repo access before running user-authored cloud tasks."),
- "attr": "pr_authorship_mode",
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
-
-def _github_credential_source_extra_state(
- pr_authorship_mode: PrAuthorshipMode | str | None, github_user_token: str | None
-) -> dict[str, str]:
- """Durable marker of which GitHub identity a run is pinned to, decided once at creation.
-
- A caller-supplied token is owned by the caller and un-refreshable by us, so the refresh
- loop must never swap it for the task creator's server integration. Persisting the source
- in run state keeps that decision durable (the per-run token cache only lives ~6h).
- """
- if pr_authorship_mode != PrAuthorshipMode.USER:
- return {}
- source = GitHubCredentialSource.CALLER_TOKEN if github_user_token else GitHubCredentialSource.SERVER_INTEGRATION
- return {"github_credential_source": source.value}
-
-
-# Run-state keys that are server-owned and must never be mutable through the PATCH endpoint:
-# - github_credential_source / pr_authorship_mode fix the run's GitHub identity at creation;
-# a caller could otherwise flip a caller-token run to ``server_integration`` and have the
-# task creator's server-side token injected into their sandbox.
-# - sandbox_id is the credential-propagation target; a caller could otherwise repoint a visible
-# run at a sandbox they control and capture the run owner's token on the next rotation.
-# - sandbox_cpu_cores / sandbox_memory_gb / sandbox_ttl_seconds / inactivity_timeout_seconds set
-# the run's compute and lifetime at creation; a caller could otherwise PATCH a queued run to
-# provision an oversized or long-lived sandbox beyond what they're entitled to.
-# All are written only server-side (run creation + the temporal workflow), never via PATCH.
-_PROTECTED_RUN_STATE_KEYS = frozenset(
- {
- "github_credential_source",
- "pr_authorship_mode",
- "sandbox_id",
- "sandbox_cpu_cores",
- "sandbox_memory_gb",
- "sandbox_ttl_seconds",
- "inactivity_timeout_seconds",
- }
-)
-
-
-TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024
-
-
-def _is_internal_debug_team(team_id: int | None) -> bool:
- if settings.DEBUG and not settings.TEST:
- return team_id == 1
- return team_id == 2 and settings.CLOUD_DEPLOYMENT == "US"
-
-
-class _SchemaAwareLimitOffsetPagination(LimitOffsetPagination):
- """LimitOffsetPagination subclass that surfaces `default_limit`/`max_limit` in the OpenAPI schema."""
-
- def get_schema_operation_parameters(self, view):
- parameters = super().get_schema_operation_parameters(view)
- for parameter in parameters:
- if parameter.get("name") == self.limit_query_param:
- parameter["schema"]["default"] = self.default_limit
- if self.max_limit is not None:
- parameter["schema"]["maximum"] = self.max_limit
- parameter["schema"]["minimum"] = 1
- elif parameter.get("name") == self.offset_query_param:
- parameter["schema"]["default"] = 0
- parameter["schema"]["minimum"] = 0
- return parameters
-
-
-class TasksPagination(_SchemaAwareLimitOffsetPagination):
- default_limit = 50
- max_limit = 100
-
-
-def _parse_slack_thread_url(url: str) -> tuple[str, str] | None:
- """Parse a Slack permalink into `(channel, thread_ts)`"""
- try:
- parsed = urlparse(url)
- except ValueError:
- return None
- match = re.search(r"/archives/(?P<channel>[A-Z0-9]+)/p(?P<ts>\d+)", parsed.path)
- if not match:
- return None
- channel = match.group("channel")
- # Reply permalinks put the parent thread_ts in the query string; that wins over the in-path ts.
- thread_ts_from_query = parse_qs(parsed.query).get("thread_ts", [None])[0]
- if thread_ts_from_query:
- return channel, thread_ts_from_query
- raw_ts = match.group("ts")
- if len(raw_ts) < 7:
- return None
- return channel, f"{raw_ts[:-6]}.{raw_ts[-6:]}"
-
-
-def _temporal_workflow_url(workflow_id: str | None) -> str | None:
- if not workflow_id:
- return None
- base = getattr(settings, "TEMPORAL_UI_HOST", None)
- namespace = getattr(settings, "TEMPORAL_NAMESPACE", None)
- if not base or not namespace:
- return None
- return f"{base.rstrip('/')}/namespaces/{namespace}/workflows/{workflow_id}"
-
-
-def _slack_repo_research_payload(
- request, team_id: int, state: dict[str, Any], repo_research_runs_by_id: dict[str, TaskRun]
-) -> dict[str, Any] | None:
- """Build the repo-research block for a run, or None when the mention wasn't ambiguous."""
- research_task_id = state.get("repo_research_task_id")
- research_run_id = state.get("repo_research_run_id")
- if not research_task_id or not research_run_id:
- return None
- research_run = repo_research_runs_by_id.get(research_run_id)
- sandbox_url = None
- log_url = None
- run_status = None
- if research_run is not None:
- sandbox_url = (research_run.state if isinstance(research_run.state, dict) else {}).get("sandbox_url")
- run_status = research_run.status
- try:
- log_url = object_storage.get_presigned_url(research_run.log_url, expiration=3600)
- except Exception:
- logger.exception("slack_thread_context_research_log_presign_failed", extra={"run_id": research_run_id})
- log_url = None
- workflow_id = TaskRun.get_workflow_id(research_task_id, research_run_id)
- return {
- "task_id": research_task_id,
- "run_id": research_run_id,
- "status": run_status,
- "task_processing_workflow_id": workflow_id,
- "task_processing_workflow_url": _temporal_workflow_url(workflow_id),
- "sandbox_url": sandbox_url,
- "task_view_url": request.build_absolute_uri(
- f"/project/{team_id}/tasks/{research_task_id}?runId={research_run_id}&ph_debug=true"
- ),
- "log_url": log_url,
- }
-
-
-_FULL_MCP_RUN_SOURCES: frozenset[RunSource | None] = frozenset({None, RunSource.MANUAL})
-
-
-def _resolve_posthog_mcp_scopes(task_run: TaskRun) -> PosthogMcpScopes:
- run_source = parse_run_state(task_run.state).run_source
- return "full" if run_source in _FULL_MCP_RUN_SOURCES else "read_only"
-
-
-class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- """
- API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
- """
-
- serializer_class = TaskSerializer
- authentication_classes = [
- SessionAuthentication,
- PersonalAPIKeyAuthentication,
- OAuthAccessTokenAuthentication,
- ]
- permission_classes = [IsAuthenticated, APIScopePermission]
- scope_object = "task"
- queryset = Task.objects.all()
- pagination_class = TasksPagination
-
- @validated_request(
- query_serializer=TaskListQuerySerializer,
- responses={
- 200: OpenApiResponse(response=TaskSerializer, description="List of tasks"),
- },
- summary="List tasks",
- description="Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, and created_by.",
- )
- def list(self, request, *args, **kwargs):
- return super().list(request, *args, **kwargs)
-
- @extend_schema(
- responses={
- 200: OpenApiResponse(
- response=TaskRepositoriesResponseSerializer,
- description="Distinct repositories used by tasks in the current project.",
- ),
- },
- summary="List distinct task repositories",
- description="Return the set of repositories referenced by non-deleted, non-internal tasks in the current project. Used to populate repository filter pickers without being constrained by task list pagination.",
- )
- @action(
- detail=False,
- methods=["get"],
- url_path="repositories",
- required_scopes=["task:read"],
- pagination_class=None,
- filter_backends=[],
- )
- def repositories(self, request, **kwargs):
- repositories = (
- Task.objects.filter(team=self.team, deleted=False, internal=False)
- .filter(task_visibility_q(getattr(self.request.user, "id", None)))
- .exclude(repository__isnull=True)
- .exclude(repository__exact="")
- .values_list("repository", flat=True)
- .distinct()
- .order_by("repository")
- )
- serializer = TaskRepositoriesResponseSerializer({"repositories": list(repositories)})
- return Response(serializer.data)
-
- @validated_request(
- request_serializer=TaskSummariesRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskSummarySerializer(many=True),
- description="Summary fields for the requested tasks",
- ),
- },
- summary="Fetch task summaries by ID",
- description=(
- "Returns summary for the requested tasks: `id`, `title`, `repository`, `created_at`, "
- "`updated_at`, and the latest run's `status` and `environment`."
- ),
- parameters=[
- OpenApiParameter(
- name="limit",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Page size for the paginated response.",
- ),
- OpenApiParameter(
- name="offset",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Offset into the result set for pagination.",
- ),
- ],
- )
- @action(
- detail=False,
- methods=["post"],
- url_path="summaries",
- required_scopes=["task:read"],
- filter_backends=[],
- )
- def summaries(self, request, **kwargs):
- ids = request.validated_data["ids"]
- latest_run = (
- TaskRun.objects.filter(task=OuterRef("pk"))
- .order_by("-created_at", "-id")
- .annotate(_data=JSONObject(status="status", environment="environment"))
- )
- tasks = (
- Task.objects.filter(team=self.team, deleted=False, id__in=ids)
- .filter(task_visibility_q(getattr(self.request.user, "id", None)))
- .annotate(_latest_run=Subquery(latest_run.values("_data")[:1]))
- .order_by("-created_at", "id")
- )
- page = self.paginate_queryset(tasks)
- if page is not None:
- serializer = TaskSummarySerializer(page, many=True)
- return self.get_paginated_response(serializer.data)
- serializer = TaskSummarySerializer(tasks, many=True)
- return Response(serializer.data)
-
- @validated_request(
- query_serializer=RepositoryReadinessQuerySerializer,
- responses={
- 200: OpenApiResponse(
- response=RepositoryReadinessResponseSerializer,
- description="Repository readiness status",
- ),
- },
- summary="Get repository readiness",
- description="Get autonomy readiness details for a specific repository in the current project.",
- )
- @action(
- detail=False,
- methods=["get"],
- url_path="repository_readiness",
- required_scopes=["task:read"],
- )
- def repository_readiness(self, request, **kwargs):
- repository = request.validated_query_data["repository"]
- window_days = request.validated_query_data["window_days"]
- refresh = request.validated_query_data["refresh"]
-
- result = compute_repository_readiness(
- team=self.team,
- repository=repository,
- window_days=window_days,
- refresh=refresh,
- )
- return Response(result)
-
- @validated_request(
- query_serializer=SlackThreadContextQuerySerializer,
- responses={
- 200: OpenApiResponse(
- response=SlackThreadContextResponseSerializer,
- description="Task, runs, and Temporal workflow handles for the Slack thread.",
- ),
- 400: OpenApiResponse(description="Malformed Slack URL or unparseable thread identifiers."),
- 403: OpenApiResponse(description="Endpoint is gated to PostHog-internal debugging."),
- 404: OpenApiResponse(description="No SlackThreadTaskMapping exists for the parsed (channel, thread_ts)."),
- },
- summary="Resolve a Slack thread to its task, runs, and Temporal workflows",
- description=(
- "PostHog-internal debug tool. Resolves a Slack permalink to the linked task, its runs, "
- "the task-processing and mention-dispatch Temporal workflow ids/URLs, and presigned log URLs."
- ),
- )
- @action(
- detail=False,
- methods=["get"],
- url_path="slack_thread_context",
- required_scopes=["task:read"],
- pagination_class=None,
- filter_backends=[],
- )
- def slack_thread_context(self, request, **kwargs):
- if not _is_internal_debug_team(self.team_id):
- return Response(
- {"detail": "slack-thread-context is restricted to PostHog-internal debugging."},
- status=status.HTTP_403_FORBIDDEN,
- )
- # 1. Get Slack URL from the request URL
- url = request.validated_query_data["url"]
- parsed = _parse_slack_thread_url(url)
- if parsed is None:
- return Response(
- {"detail": "Could not parse channel/thread_ts from the provided Slack URL.", "url": url},
- status=status.HTTP_400_BAD_REQUEST,
- )
- channel, thread_ts = parsed
- # 2. Find related tasks
- mapping = (
- SlackThreadTaskMapping.objects.select_related("task", "task__created_by")
- .filter(channel=channel, thread_ts=thread_ts)
- .first()
- )
- if mapping is None:
- return Response(
- {
- "detail": "no_mapping",
- "thread": {
- "url": url,
- "channel": channel,
- "thread_ts": thread_ts,
- "slack_workspace_id": None,
- "mentioning_slack_user_id": None,
- },
- },
- status=status.HTTP_404_NOT_FOUND,
- )
- task = mapping.task
- # 3. Find runs for the task
- runs = list(TaskRun.objects.filter(task=task).order_by("created_at", "id"))
- # Include repo discovery runs, if present
- repo_research_run_ids = [
- rid
- for run in runs
- if (rid := (run.state if isinstance(run.state, dict) else {}).get("repo_research_run_id"))
- ]
- repo_research_runs_by_id: dict[str, TaskRun] = (
- {str(r.id): r for r in TaskRun.objects.filter(team=task.team, id__in=repo_research_run_ids)}
- if repo_research_run_ids
- else {}
- )
- # `?ph_debug=true` allows to check tasks of all team members through /tasks/<id>
- task_url = request.build_absolute_uri(f"/project/{task.team_id}/tasks/{task.id}?ph_debug=true")
- run_payloads: list[dict[str, Any]] = []
- # 4. Find workflows for the runs
- for run in runs:
- state = run.state if isinstance(run.state, dict) else {}
- output = run.output if isinstance(run.output, dict) else {}
- task_processing_workflow_id = TaskRun.get_workflow_id(task.id, run.id)
- mention_workflow_id = state.get("slack_mention_workflow_id")
- try:
- presigned_log_url = object_storage.get_presigned_url(run.log_url, expiration=3600)
- except Exception:
- logger.exception("slack_thread_context_log_presign_failed", extra={"run_id": str(run.id)})
- presigned_log_url = None
- run_payloads.append(
- {
- "id": str(run.id),
- "status": run.status,
- "created_at": run.created_at,
- "completed_at": run.completed_at,
- "sandbox_url": state.get("sandbox_url"),
- "pr_url": output.get("pr_url"),
- "error_message": run.error_message,
- "task_processing_workflow_id": task_processing_workflow_id,
- "task_processing_workflow_url": _temporal_workflow_url(task_processing_workflow_id),
- "mention_workflow_id": mention_workflow_id,
- "mention_workflow_url": _temporal_workflow_url(mention_workflow_id),
- "task_view_url": request.build_absolute_uri(
- f"/project/{task.team_id}/tasks/{task.id}?runId={run.id}&ph_debug=true"
- ),
- "log_url": presigned_log_url,
- "repo_research": _slack_repo_research_payload(
- request, task.team_id, state, repo_research_runs_by_id
- ),
- }
- )
- payload = {
- "thread": {
- "url": url,
- "channel": channel,
- "thread_ts": thread_ts,
- "slack_workspace_id": mapping.slack_workspace_id,
- "mentioning_slack_user_id": mapping.mentioning_slack_user_id,
- },
- "task": {
- "id": str(task.id),
- "team_id": task.team_id,
- "title": task.title,
- "repository": task.repository,
- "origin_product": task.origin_product,
- "created_at": task.created_at,
- "url": task_url,
- },
- "runs": run_payloads,
- }
- serializer = SlackThreadContextResponseSerializer(payload)
- return Response(serializer.data)
-
- def safely_get_queryset(self, queryset):
- qs = queryset.filter(team=self.team, deleted=False)
- # `?ph_debug=true` allows to check tasks of all team members through /tasks/<id>
- if not (
- _is_internal_debug_team(self.team_id)
- and self.action == "retrieve"
- and self.request.query_params.get("ph_debug") == "true"
- ):
- qs = qs.filter(task_visibility_q(getattr(self.request.user, "id", None)))
- qs = qs.order_by("-created_at")
-
- params = self.request.query_params if hasattr(self, "request") else {}
-
- # Filter by origin product
- origin_product = params.get("origin_product")
- if origin_product:
- qs = qs.filter(origin_product=origin_product)
-
- stage = params.get("stage")
- if stage:
- qs = qs.filter(runs__stage=stage)
-
- # Filter by repository or organization using the repository field
- organization = params.get("organization")
- repository = params.get("repository")
- created_by = params.get("created_by")
- search = params.get("search")
- status_filter = params.get("status")
-
- if repository:
- repo_str = repository.strip().lower()
- if "/" in repo_str:
- qs = qs.filter(repository__iexact=repo_str)
- else:
- qs = qs.filter(repository__iendswith=f"/{repo_str}")
-
- if organization:
- org_str = organization.strip().lower()
- qs = qs.filter(repository__istartswith=f"{org_str}/")
-
- if created_by:
- qs = qs.filter(created_by_id=created_by)
-
- # Only apply list-oriented filters on list — retrieve/update should always work if
- # you have the ID. Without this guard, a client passing a query param while fetching
- # a single task by ID would see an unexpected 404 when the task does not match.
- if self.action == "list":
- if search:
- search_term = search.strip()
- if search_term:
- search_q = Q(title__icontains=search_term) | Q(description__icontains=search_term)
- # Slugs look like "<team-prefix>-<task_number>". If the search term is a bare
- # number, or looks like "<prefix>-<number>", also match by task_number so users
- # can find tasks by slug.
- number_part = search_term.split("-")[-1].strip()
- if number_part.isdigit():
- search_q |= Q(task_number=int(number_part))
- qs = qs.filter(search_q)
-
- if status_filter:
- # `-id` is a deterministic tiebreaker when two runs share a `created_at`
- # timestamp (e.g. both seeded with `timezone.now()` in the same tick).
- latest_run_status = (
- TaskRun.objects.filter(task=OuterRef("pk")).order_by("-created_at", "-id").values("status")[:1]
- )
- qs = qs.annotate(_latest_run_status=Subquery(latest_run_status)).filter(
- _latest_run_status=status_filter
- )
-
- internal_param = getattr(self.request, "validated_query_data", {}).get("internal")
- if internal_param is True and (settings.DEBUG or self.request.user.is_staff):
- qs = qs.filter(internal=True)
- else:
- qs = qs.filter(internal=False)
-
- archived_param = getattr(self.request, "validated_query_data", {}).get("archived")
- if archived_param == "true":
- qs = qs.filter(archived=True)
- elif archived_param == "all":
- pass
- else:
- qs = qs.filter(archived=False)
-
- # select_related to avoid N+1 on created_by (UserBasicSerializer), team (slug property),
- # and GitHub integrations returned on task rows.
- qs = qs.select_related("created_by", "team", "github_integration", "github_user_integration").prefetch_related(
- "runs"
- )
-
- # `stage` joins through `runs` and can produce duplicate task rows. If any other
- # JOIN-producing filter is added above, broaden this guard (or move `.distinct()`
- # to run unconditionally).
- if stage:
- qs = qs.distinct()
-
- return qs
-
- def get_serializer_context(self):
- return {**super().get_serializer_context(), "team": self.team, "team_id": self.team.id}
-
- def perform_create(self, serializer):
- logger.info(f"Creating task with data: {serializer.validated_data}")
- serializer.save(team=self.team)
-
- def perform_destroy(self, instance):
- task = cast(Task, instance)
- logger.info(f"Soft deleting task {task.id}")
- task.soft_delete()
-
- def _trigger_workflow(self, task: Task, task_run: TaskRun) -> None:
- try:
- logger.info(f"Attempting to trigger task processing workflow for task {task.id}, run {task_run.id}")
- execute_task_processing_workflow(
- task_id=str(task.id),
- run_id=str(task_run.id),
- team_id=task.team.id,
- user_id=getattr(self.request.user, "id", None),
- posthog_mcp_scopes=_resolve_posthog_mcp_scopes(task_run),
- )
- logger.info(f"Workflow trigger completed for task {task.id}, run {task_run.id}")
- except Exception as e:
- logger.exception(f"Failed to trigger task processing workflow for task {task.id}, run {task_run.id}: {e}")
-
- @validated_request(
- request_serializer=TaskStagedArtifactsPrepareUploadRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskStagedArtifactsPrepareUploadResponseSerializer,
- description="Prepared staged uploads for the requested artifacts",
- ),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
- 404: OpenApiResponse(description="Task not found"),
- },
- summary="Prepare staged direct uploads for task attachments",
- description="Reserve S3 object keys for task attachments before creating a new run and return presigned POST forms for direct uploads.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="staged_artifacts/prepare_upload",
- required_scopes=["task:write"],
- )
- def staged_artifacts_prepare_upload(self, request, pk=None, **kwargs):
- task = cast(Task, self.get_object())
- artifacts = request.validated_data["artifacts"]
-
- prepared_artifacts: list[dict] = []
- for artifact in artifacts:
- artifact_id = uuid.uuid4().hex
- safe_name = get_safe_artifact_name(artifact["name"])
- storage_path = build_task_staged_artifact_storage_path(task, artifact_id, safe_name)
- presigned_post = object_storage.get_presigned_post(
- storage_path,
- conditions=[
- ["content-length-range", 0, artifact["size"] + TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES]
- ],
- expiration=TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS,
- )
- if not presigned_post:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Unable to generate upload URL"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- prepared_artifacts.append(
- {
- "id": artifact_id,
- "name": safe_name,
- "type": artifact["type"],
- "source": artifact.get("source") or "",
- "size": artifact["size"],
- "content_type": artifact.get("content_type") or "",
- "storage_path": storage_path,
- "expires_in": TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS,
- "presigned_post": presigned_post,
- }
- )
-
- serializer = TaskStagedArtifactsPrepareUploadResponseSerializer(
- {"artifacts": prepared_artifacts},
- context=self.get_serializer_context(),
- )
- return Response(serializer.data)
-
- @validated_request(
- request_serializer=TaskStagedArtifactsFinalizeUploadRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskStagedArtifactsFinalizeUploadResponseSerializer,
- description="Finalized staged artifacts available for the next task run",
- ),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
- 404: OpenApiResponse(description="Task not found"),
- },
- summary="Finalize staged direct uploads for task attachments",
- description="Verify staged S3 uploads and cache their metadata so they can be attached to the next run created for this task.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="staged_artifacts/finalize_upload",
- required_scopes=["task:write"],
- )
- def staged_artifacts_finalize_upload(self, request, pk=None, **kwargs):
- task = cast(Task, self.get_object())
- artifacts = request.validated_data["artifacts"]
- artifact_prefix = f"{settings.OBJECT_STORAGE_TASKS_FOLDER}/artifacts/team_{task.team_id}/task_{task.id}/staged/"
- finalized_artifacts: list[dict] = []
-
- for artifact in artifacts:
- artifact_id = artifact["id"]
- storage_path = artifact["storage_path"]
- if not storage_path.startswith(artifact_prefix) or f"/{artifact_id}/" not in storage_path:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact storage path is invalid for this task"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- s3_object = object_storage.head_object(storage_path)
- if not s3_object:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact upload not found in object storage"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- content_length = s3_object.get("ContentLength")
- if not isinstance(content_length, int):
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact upload metadata is unavailable"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- safe_name = get_safe_artifact_name(artifact["name"])
- content_type = artifact.get("content_type") or s3_object.get("ContentType") or ""
- max_size_bytes = get_task_run_artifact_max_size_bytes(
- safe_name,
- content_type,
- artifact.get("type"),
- )
- if content_length > max_size_bytes:
- return Response(
- TaskRunErrorResponseSerializer(
- {"error": build_task_run_artifact_size_error(safe_name, max_size_bytes)}
- ).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
- finalized_artifact = build_task_artifact_entry(
- artifact_id=artifact_id,
- name=safe_name,
- artifact_type=artifact["type"],
- source=artifact.get("source") or "",
- size=content_length,
- content_type=content_type,
- storage_path=storage_path,
- )
- finalized_artifacts.append(finalized_artifact)
-
- for finalized_artifact in finalized_artifacts:
- cache_task_staged_artifact(task, finalized_artifact)
- tag_task_artifact(
- finalized_artifact["storage_path"],
- ttl_days=STAGED_ARTIFACT_TTL_DAYS,
- team_id=task.team_id,
- )
-
- serializer = TaskStagedArtifactsFinalizeUploadResponseSerializer(
- {"artifacts": finalized_artifacts},
- context=self.get_serializer_context(),
- )
- return Response(serializer.data)
-
- def perform_update(self, serializer):
- task = cast(Task, serializer.instance)
- logger.info(f"perform_update called for task {task.id} with validated_data: {serializer.validated_data}")
- serializer.save()
- logger.info(f"Task {task.id} updated successfully")
-
- return Response(TaskSerializer(task).data)
-
- @extend_schema(request=TaskRunCreateRequestSchemaSerializer)
- @validated_request(
- request_serializer=TaskRunCreateRequestSerializer,
- responses={
- 200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),
- 404: OpenApiResponse(description="Task not found"),
- 429: OpenApiResponse(
- response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
- ),
- },
- summary="Run task",
- description="Create a new task run and kick off the workflow.",
- )
- @action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])
- def run(self, request, pk=None, **kwargs):
- task = cast(Task, self.get_object())
-
- # Always cloud: gate before creating the run.
- if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
- return limit_response
-
- mode = request.validated_data.get("mode", "background")
- branch = request.validated_data.get("branch")
- resume_from_run_id = request.validated_data.get("resume_from_run_id")
- pending_user_message = request.validated_data.get("pending_user_message")
- pending_user_artifact_ids = request.validated_data.get("pending_user_artifact_ids") or []
- sandbox_environment_id = request.validated_data.get("sandbox_environment_id")
- sandbox_environment_id_supplied_by_user = sandbox_environment_id is not None
- pr_authorship_mode = request.validated_data.get("pr_authorship_mode")
- run_source = request.validated_data.get("run_source")
- signal_report_id = request.validated_data.get("signal_report_id")
- runtime_adapter = request.validated_data.get("runtime_adapter")
- model = request.validated_data.get("model")
- reasoning_effort = request.validated_data.get("reasoning_effort")
- github_user_token = request.validated_data.get("github_user_token")
- initial_permission_mode = request.validated_data.get("initial_permission_mode")
- if run_source == RunSource.SIGNAL_REPORT:
- pr_authorship_mode = PrAuthorshipMode.BOT
-
- runtime_state_fields = {
- "pr_authorship_mode": pr_authorship_mode,
- "run_source": run_source,
- "signal_report_id": signal_report_id,
- "runtime_adapter": runtime_adapter,
- "model": model,
- "reasoning_effort": reasoning_effort,
- }
-
- extra_state = None
- if pending_user_message is not None:
- extra_state = {"pending_user_message": pending_user_message}
- if pending_user_artifact_ids:
- extra_state = extra_state or {}
- extra_state["pending_user_artifact_ids"] = pending_user_artifact_ids
- if initial_permission_mode is not None:
- extra_state = extra_state or {}
- extra_state["initial_permission_mode"] = initial_permission_mode
-
- if resume_from_run_id:
- # prevent cross-task resume
- previous_run = task.runs.filter(id=resume_from_run_id).first()
- if not previous_run:
- return Response({"detail": "Invalid resume_from_run_id"}, status=400)
-
- # Derive snapshot_external_id from the validated previous run
- prev_state = parse_run_state(previous_run.state)
- extra_state = extra_state or {}
- extra_state["resume_from_run_id"] = str(resume_from_run_id)
- if prev_state.snapshot_external_id:
- extra_state["snapshot_external_id"] = prev_state.snapshot_external_id
-
- if prev_state.sandbox_environment_id and sandbox_environment_id is None:
- sandbox_environment_id = prev_state.sandbox_environment_id
-
- for field_name in runtime_state_fields:
- if runtime_state_fields[field_name] is None:
- runtime_state_fields[field_name] = getattr(prev_state, field_name)
-
- pr_authorship_mode = runtime_state_fields["pr_authorship_mode"]
- run_source = runtime_state_fields["run_source"]
- signal_report_id = runtime_state_fields["signal_report_id"]
- runtime_adapter = runtime_state_fields["runtime_adapter"]
- model = runtime_state_fields["model"]
- reasoning_effort = runtime_state_fields["reasoning_effort"]
- if branch is None and prev_state.pr_base_branch is not None:
- branch = prev_state.pr_base_branch
-
- provider = get_provider_for_runtime_adapter(runtime_adapter)
-
- for key, value in {
- "pr_base_branch": branch,
- "pr_authorship_mode": pr_authorship_mode,
- "run_source": run_source,
- "signal_report_id": signal_report_id,
- "runtime_adapter": runtime_adapter,
- "provider": provider,
- "model": model,
- "reasoning_effort": reasoning_effort,
- }.items():
- if value is not None:
- extra_state = extra_state or {}
- extra_state[key] = value.value if hasattr(value, "value") else value
-
- reasoning_effort_error = get_reasoning_effort_error(
- runtime_adapter=runtime_adapter,
- model=model,
- reasoning_effort=reasoning_effort,
- )
- if reasoning_effort_error is not None:
- return Response(
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": reasoning_effort_error,
- "attr": "reasoning_effort",
- },
- status=400,
- )
-
- pr_authorship_mode, validation_response = _resolve_cloud_pr_authorship_mode(
- task,
- pr_authorship_mode=pr_authorship_mode,
- request_user_id=getattr(request.user, "id", None),
- github_user_token=github_user_token,
- )
- if validation_response is not None:
- return validation_response
- if pr_authorship_mode is not None:
- extra_state = extra_state or {}
- extra_state["pr_authorship_mode"] = (
- pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
- )
-
- if credential_source := _github_credential_source_extra_state(pr_authorship_mode, github_user_token):
- extra_state = extra_state or {}
- extra_state.update(credential_source)
-
- if sandbox_environment_id is not None:
- sandbox_environment = SandboxEnvironment.get_accessible_for_task(
- environment_id=sandbox_environment_id,
- team_id=task.team_id,
- task_created_by_id=task.created_by_id,
- )
- if sandbox_environment is None:
- if sandbox_environment_id_supplied_by_user:
- return Response({"detail": "Invalid sandbox_environment_id"}, status=400)
- else:
- extra_state = extra_state or {}
- extra_state["sandbox_environment_id"] = str(sandbox_environment.id)
-
- logger.info(
- "Applying sandbox environment to task run",
- extra={
- "task_id": str(task.id),
- "sandbox_environment_id": str(sandbox_environment.id),
- "sandbox_environment_name": sandbox_environment.name,
- "network_access_level": sandbox_environment.network_access_level,
- },
- )
-
- staged_artifacts: list[dict[str, Any]] = []
- if pending_user_artifact_ids:
- staged_artifacts, missing_artifact_ids = get_task_staged_artifacts(task, pending_user_artifact_ids)
- if missing_artifact_ids:
- return Response(
- {
- "detail": "Some pending_user_artifact_ids are invalid or expired",
- "missing_artifact_ids": missing_artifact_ids,
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- logger.info(f"Creating task run for task {task.id} with mode={mode}, branch={branch}")
-
- task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state)
-
- if pending_user_artifact_ids:
- run_artifacts: list[dict] = []
- for staged_artifact in staged_artifacts:
- storage_path = str(staged_artifact["storage_path"])
- tag_task_artifact(storage_path, ttl_days=RUN_ARTIFACT_TTL_DAYS, team_id=task.team_id)
- run_artifacts.append(dict(staged_artifact))
-
- task_run.artifacts = run_artifacts
- task_run.save(update_fields=["artifacts", "updated_at"])
-
- for artifact_id in pending_user_artifact_ids:
- get_tasks_cache().delete(build_task_staged_artifact_cache_key(str(task.id), artifact_id))
-
- if github_user_token and pr_authorship_mode == PrAuthorshipMode.USER:
- cache_github_user_token(str(task_run.id), github_user_token)
-
- logger.info(f"Triggering workflow for task {task.id}, run {task_run.id}")
-
- self._trigger_workflow(task, task_run)
-
- task.refresh_from_db()
-
- return Response(TaskSerializer(task, context=self.get_serializer_context()).data)
-
- @validated_request(
- request_serializer=TaskPresenceBeaconRequestSerializer,
- responses={
- 204: OpenApiResponse(description="Presence recorded for this device."),
- 404: OpenApiResponse(description="`device_id` does not match a push token registered by the caller."),
- },
- summary="Beacon presence for a device watching this task",
- description=(
- "Idempotent upsert: marks the calling user + `device_id` as actively watching this task "
- "for the next ~60 seconds. While at least one device for the user has a non-expired "
- "presence row for this task, the push fanout will skip ALL of that user's other "
- "registered devices for task notifications — the contract is 'if any device is "
- "demonstrably watching, suppress the others'. Clients call this every ~30s while the "
- "task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row."
- ),
- )
- @action(
- detail=True,
- methods=["post", "delete"],
- url_path="presence",
- required_scopes=["task:write"],
- )
- def presence(self, request, **kwargs):
- if request.method == "DELETE":
- return self._presence_leave(request)
- return self._presence_beacon(request)
-
- def _presence_beacon(self, request) -> Response:
- task = cast(Task, self.get_object())
- device_id = request.validated_data["device_id"]
- push_token = UserPushToken.objects.filter(user=request.user, id=device_id).first()
- if push_token is None:
- raise NotFound("device_id does not match a push token registered by the caller")
-
- # Lookup mirrors the unique constraint exactly so a stray row with a
- # mismatched team/user (e.g. from a bug elsewhere) gets corrected on
- # upsert instead of crashing into the constraint a second time.
- # nosemgrep: idor-lookup-without-team — team scope is enforced by
- # TaskScopedManager (DRF view sets the ContextVar) and via `task` FK
- # whose row is fetched through self.get_object() above.
- now = timezone.now()
- TaskPresence.objects.update_or_create(
- task=task,
- push_token=push_token,
- defaults={
- "team": task.team,
- "user": request.user,
- "expires_at": now + timedelta(seconds=TASK_PRESENCE_TTL_SECONDS),
- },
- )
- return Response(status=status.HTTP_204_NO_CONTENT)
-
- def _presence_leave(self, request) -> Response:
- task = cast(Task, self.get_object())
- device_id = request.validated_data["device_id"]
- # No 404 on missing rows — the beacon-leave path runs from blur/background
- # handlers that should be safe to call unconditionally without the client
- # having to track whether a beacon was ever sent.
- TaskPresence.objects.filter(task=task, push_token_id=device_id, user=request.user).delete()
- return Response(status=status.HTTP_204_NO_CONTENT)
-
-
-@extend_schema(tags=["task-automations"])
-class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- serializer_class = TaskAutomationSerializer
- authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
- permission_classes = [IsAuthenticated, APIScopePermission]
- scope_object = "task"
- queryset = TaskAutomation.objects.all()
- filter_rewrite_rules = {"team_id": "task__team_id"}
-
- def safely_get_queryset(self, queryset):
- return (
- queryset.filter(task__team=self.team)
- .filter(task_run_visibility_q(getattr(self.request.user, "id", None)))
- .order_by("task__title", "-created_at")
- )
-
- def get_serializer_context(self):
- return {**super().get_serializer_context(), "team": self.team, "team_id": self.team.id}
-
- def perform_create(self, serializer):
- automation = serializer.save()
- sync_automation_schedule(automation)
-
- def perform_update(self, serializer):
- automation = serializer.save()
- sync_automation_schedule(automation)
-
- def perform_destroy(self, instance):
- automation = cast(TaskAutomation, instance)
- delete_automation_schedule(automation)
- automation.delete()
-
- @action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])
- def run(self, request, pk=None, **kwargs):
- automation = cast(TaskAutomation, self.get_object())
- run_task_automation(str(automation.id))
- automation.refresh_from_db()
- return Response(TaskAutomationSerializer(automation, context=self.get_serializer_context()).data)
-
-
-@extend_schema(tags=["task-runs", "tasks"])
-class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- """
- API for managing task runs. Each run represents an execution of a task.
- """
-
- serializer_class = TaskRunDetailSerializer
- authentication_classes = [
- SessionAuthentication,
- PersonalAPIKeyAuthentication,
- OAuthAccessTokenAuthentication,
- ]
- permission_classes = [IsAuthenticated, APIScopePermission]
- scope_object = "task"
- queryset = TaskRun.objects.select_related(
- "task", "task__created_by", "task__github_integration", "task__github_user_integration"
- ).all()
- http_method_names = ["get", "post", "patch", "head", "options"]
- filter_rewrite_rules = {"team_id": "team_id"}
- pagination_class = TasksPagination
-
- @validated_request(
- responses={
- 200: OpenApiResponse(response=TaskRunDetailSerializer, description="List of task runs"),
- },
- summary="List task runs",
- description="Get a list of runs for a specific task.",
- )
- def list(self, request, *args, **kwargs):
- return super().list(request, *args, **kwargs)
-
- @validated_request(
- request_serializer=TaskRunBootstrapCreateRequestSerializer,
- responses={
- 201: OpenApiResponse(response=TaskRunDetailSerializer, description="Created task run"),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),
- 429: OpenApiResponse(
- response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
- ),
- },
- summary="Create task run",
- description="Create a new run for a specific task without starting execution.",
- )
- def create(self, request, *args, **kwargs):
- task_id = self.kwargs.get("parent_lookup_task_id")
- if not task_id:
- raise NotFound("Task ID is required")
-
- task = (
- Task.objects.filter(id=task_id, team=self.team)
- .filter(task_visibility_q(getattr(request.user, "id", None)))
- .first()
- )
- if task is None:
- raise NotFound("Task not found")
- environment = request.validated_data.get("environment", TaskRun.Environment.LOCAL)
-
- # Gate cloud runs before the run row is created; local runs aren't limited.
- if environment == TaskRun.Environment.CLOUD:
- if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
- return limit_response
-
- mode = request.validated_data.get("mode", "background")
- branch = request.validated_data.get("branch")
- sandbox_environment_id = request.validated_data.get("sandbox_environment_id")
- pr_authorship_mode = request.validated_data.get("pr_authorship_mode")
- run_source = request.validated_data.get("run_source")
- signal_report_id = request.validated_data.get("signal_report_id")
- runtime_adapter = request.validated_data.get("runtime_adapter")
- model = request.validated_data.get("model")
- reasoning_effort = request.validated_data.get("reasoning_effort")
- github_user_token = request.validated_data.get("github_user_token")
- initial_permission_mode = request.validated_data.get("initial_permission_mode")
- home_quick_action = request.validated_data.get("home_quick_action")
- if run_source == RunSource.SIGNAL_REPORT:
- pr_authorship_mode = PrAuthorshipMode.BOT
-
- extra_state: dict[str, Any] | None = None
- if initial_permission_mode is not None:
- extra_state = {"initial_permission_mode": initial_permission_mode}
-
- provider = get_provider_for_runtime_adapter(runtime_adapter)
- for key, value in {
- "pr_base_branch": branch,
- "pr_authorship_mode": pr_authorship_mode,
- "run_source": run_source,
- "signal_report_id": signal_report_id,
- "runtime_adapter": runtime_adapter,
- "provider": provider,
- "model": model,
- "reasoning_effort": reasoning_effort,
- "home_quick_action": home_quick_action,
- }.items():
- if value is not None:
- extra_state = extra_state or {}
- extra_state[key] = value.value if hasattr(value, "value") else value
-
- reasoning_effort_error = get_reasoning_effort_error(
- runtime_adapter=runtime_adapter,
- model=model,
- reasoning_effort=reasoning_effort,
- )
- if reasoning_effort_error is not None:
- return Response(
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": reasoning_effort_error,
- "attr": "reasoning_effort",
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- pr_authorship_mode, validation_response = _resolve_cloud_pr_authorship_mode(
- task,
- pr_authorship_mode=pr_authorship_mode,
- request_user_id=getattr(request.user, "id", None),
- github_user_token=github_user_token,
- )
- if validation_response is not None:
- return validation_response
- if pr_authorship_mode is not None:
- extra_state = extra_state or {}
- extra_state["pr_authorship_mode"] = (
- pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
- )
-
- if credential_source := _github_credential_source_extra_state(pr_authorship_mode, github_user_token):
- extra_state = extra_state or {}
- extra_state.update(credential_source)
-
- if sandbox_environment_id is not None:
- sandbox_environment = SandboxEnvironment.get_accessible_for_task(
- environment_id=sandbox_environment_id,
- team_id=task.team_id,
- task_created_by_id=task.created_by_id,
- )
- if sandbox_environment is None:
- return Response({"detail": "Invalid sandbox_environment_id"}, status=status.HTTP_400_BAD_REQUEST)
-
- extra_state = extra_state or {}
- extra_state["sandbox_environment_id"] = str(sandbox_environment.id)
-
- logger.info(
- "Applying sandbox environment to task run",
- extra={
- "task_id": str(task.id),
- "sandbox_environment_id": str(sandbox_environment.id),
- "sandbox_environment_name": sandbox_environment.name,
- "network_access_level": sandbox_environment.network_access_level,
- },
- )
-
- logger.info(
- "Creating task run for task %s with mode=%s, branch=%s, environment=%s",
- task.id,
- mode,
- branch,
- environment,
- )
- task_run = task.create_run(
- environment=environment,
- mode=mode,
- branch=branch,
- extra_state=extra_state,
- )
-
- if github_user_token and pr_authorship_mode == PrAuthorshipMode.USER:
- cache_github_user_token(str(task_run.id), github_user_token)
-
- serializer = TaskRunDetailSerializer(task_run, context=self.get_serializer_context())
- return Response(serializer.data, status=status.HTTP_201_CREATED)
-
- @validated_request(
- request_serializer=TaskRunStartRequestSerializer,
- responses={
- 200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid start payload"),
- 404: OpenApiResponse(description="Task run not found"),
- 429: OpenApiResponse(
- response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
- ),
- },
- summary="Start task run",
- description="Start an existing cloud run after any initial run-scoped attachments have been uploaded.",
- )
- @action(detail=True, methods=["post"], url_path="start", required_scopes=["task:write"])
- def start(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- task = task_run.task
- pending_user_message = request.validated_data.get("pending_user_message")
- pending_user_artifact_ids = request.validated_data.get("pending_user_artifact_ids") or []
- startable_statuses = {TaskRun.Status.NOT_STARTED, TaskRun.Status.QUEUED}
-
- if task_run.environment != TaskRun.Environment.CLOUD:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Only cloud runs can be started via this endpoint"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
- if task_run.status not in startable_statuses:
- return Response(
- TaskRunErrorResponseSerializer(
- {
- "error": f"Only queued or not_started cloud runs can be started (current status: {task_run.status})"
- }
- ).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- # Backstop: don't launch the cloud workflow for an over-limit team.
- if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
- return limit_response
-
- if pending_user_artifact_ids:
- _, missing_artifact_ids = get_task_run_artifacts_by_id(task_run, pending_user_artifact_ids)
- if missing_artifact_ids:
- return Response(
- {
- "detail": "Some pending_user_artifact_ids are invalid for this run",
- "missing_artifact_ids": missing_artifact_ids,
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- state_updates: dict[str, Any] = {}
- if pending_user_message is not None:
- state_updates["pending_user_message"] = pending_user_message
- if pending_user_artifact_ids:
- state_updates["pending_user_artifact_ids"] = pending_user_artifact_ids
-
- previous_state = dict(task_run.state or {})
- try:
- if state_updates:
- TaskRun.update_state_atomic(task_run.id, updates=state_updates)
- task_run.refresh_from_db()
-
- logger.info("Triggering workflow for task %s, existing run %s", task.id, task_run.id)
- self._trigger_workflow(task, task_run, raise_on_error=True)
- except Exception:
- if state_updates:
- rollback_updates = {
- key: previous_state[key] for key in state_updates.keys() if key in previous_state
- } or None
- rollback_remove_keys = [key for key in state_updates.keys() if key not in previous_state] or None
- TaskRun.update_state_atomic(
- task_run.id,
- updates=rollback_updates,
- remove_keys=rollback_remove_keys,
- )
- raise
-
- task.refresh_from_db()
- return Response(TaskSerializer(task, context=self.get_serializer_context()).data)
-
- @validated_request(
- request_serializer=TaskRunUpdateSerializer,
- responses={
- 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Updated task run"),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid update data"),
- 404: OpenApiResponse(description="Task run not found"),
- },
- summary="Update task run",
- description="Update a task run with status, stage, branch, output, and state information.",
- strict_request_validation=True,
- )
- def update(self, request, *args, **kwargs):
- return self.partial_update(request, *args, **kwargs)
-
- @validated_request(
- request_serializer=TaskRunUpdateSerializer,
- responses={
- 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Updated task run"),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid update data"),
- 404: OpenApiResponse(description="Task run not found"),
- },
- summary="Update task run",
- strict_request_validation=True,
- )
- def partial_update(self, request, *args, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- has_output_merge = "output" in request.validated_data and isinstance(request.validated_data["output"], dict)
- has_state_merge = "state" in request.validated_data and isinstance(request.validated_data["state"], dict)
- # Protected keys fix the run's GitHub identity at creation — callers cannot change or remove them.
- if has_state_merge:
- request.validated_data["state"] = {
- k: v for k, v in request.validated_data["state"].items() if k not in _PROTECTED_RUN_STATE_KEYS
- }
- state_remove_keys = [
- k for k in (request.validated_data.get("state_remove_keys") or []) if k not in _PROTECTED_RUN_STATE_KEYS
- ]
- has_state_mutation = has_state_merge or bool(state_remove_keys)
- update_fields: set[str] = set()
-
- with transaction.atomic():
- # Re-fetch with row lock when merging output to prevent concurrent
- # PATCHes (e.g. branch sync + PR URL) from clobbering each other.
- if has_output_merge or has_state_mutation:
- task_run = TaskRun.objects.select_for_update().get(pk=task_run.pk)
-
- old_status = task_run.status
- old_environment = task_run.environment
- old_pr_url = (task_run.output or {}).get("pr_url") if isinstance(task_run.output, dict) else None
-
- # Update fields from validated data
- for key, value in request.validated_data.items():
- if key == "output" and isinstance(value, dict):
- existing_output = task_run.output if isinstance(task_run.output, dict) else {}
- setattr(task_run, key, {**existing_output, **value})
- update_fields.add(key)
- continue
- if key == "state_remove_keys":
- continue
- if key == "state" and has_state_merge:
- existing_state = task_run.state if isinstance(task_run.state, dict) else {}
- next_state = dict(existing_state)
- for remove_key in state_remove_keys:
- next_state.pop(remove_key, None)
- next_state.update(value)
- setattr(task_run, key, next_state)
- update_fields.add(key)
- continue
- setattr(task_run, key, value)
- update_fields.add(key)
-
- if state_remove_keys and not has_state_merge:
- existing_state = task_run.state if isinstance(task_run.state, dict) else {}
- next_state = dict(existing_state)
- for remove_key in state_remove_keys:
- next_state.pop(remove_key, None)
- task_run.state = next_state
- update_fields.add("state")
-
- new_status = request.validated_data.get("status")
- terminal_statuses = [
- TaskRun.Status.COMPLETED,
- TaskRun.Status.FAILED,
- TaskRun.Status.CANCELLED,
- ]
-
- # Auto-set completed_at if status is completed or failed
- if new_status in terminal_statuses:
- if not task_run.completed_at:
- task_run.completed_at = timezone.now()
- update_fields.add("completed_at")
-
- update_fields.add("updated_at")
- task_run.save(update_fields=list(update_fields))
- task_run.publish_stream_state_event()
-
- update_automation_run_result(task_run)
-
- # Signal Temporal and post Slack updates after commit to avoid
- # holding the row lock during external calls.
- if new_status in terminal_statuses and old_status != new_status:
- self._signal_workflow_completion(
- task_run,
- new_status,
- request.validated_data.get("error_message"),
- )
- # mark_completed / mark_failed fire pushes from the model. Cancellation
- # transitions only flow through this PATCH path, so dispatch here.
- if new_status == TaskRun.Status.CANCELLED:
- from products.tasks.backend.push_dispatcher import notify_task_run_cancelled
-
- notify_task_run_cancelled(task_run)
- new_environment = request.validated_data.get("environment")
- if new_environment == "local" and old_environment == TaskRun.Environment.CLOUD:
- self._signal_workflow_completion(task_run, "cancelled", "handoff")
-
- new_pr_url = (task_run.output or {}).get("pr_url") if isinstance(task_run.output, dict) else None
- if new_pr_url and new_pr_url != old_pr_url:
- self._post_slack_update_for_pr(task_run)
-
- return Response(TaskRunDetailSerializer(task_run, context=self.get_serializer_context()).data)
-
- def _post_slack_update_for_pr(self, task_run: TaskRun) -> None:
- pr_url = (task_run.output or {}).get("pr_url") if isinstance(task_run.output, dict) else None
- if not pr_url:
- return
-
- try:
- from products.slack_app.backend.models import SlackThreadTaskMapping
- from products.tasks.backend.temporal.process_task.activities.post_slack_update import (
- PostSlackUpdateInput,
- post_slack_update,
- )
-
- mapping = (
- SlackThreadTaskMapping.objects.filter(task_run=task_run)
- .order_by("-updated_at")
- .values(
- "integration_id",
- "channel",
- "thread_ts",
- "mentioning_slack_user_id",
- )
- .first()
- )
-
- if not mapping:
- return
-
- post_slack_update(
- PostSlackUpdateInput(
- run_id=str(task_run.id),
- slack_thread_context={
- "integration_id": mapping["integration_id"],
- "channel": mapping["channel"],
- "thread_ts": mapping["thread_ts"],
- "mentioning_slack_user_id": mapping["mentioning_slack_user_id"],
- },
- )
- )
- except Exception:
- logger.exception("task_run_slack_update_for_pr_failed for run %s", task_run.id)
-
- def _signal_workflow_completion(self, task_run: TaskRun, status: str, error_message: str | None) -> None:
- """Send completion signal to Temporal workflow."""
- from posthog.temporal.common.client import sync_connect
-
- from products.tasks.backend.temporal.process_task.workflow import ProcessTaskWorkflow
-
- try:
- client = sync_connect()
- handle = client.get_workflow_handle(task_run.workflow_id)
-
- import asyncio
-
- asyncio.run(handle.signal(ProcessTaskWorkflow.complete_task, args=[status, error_message]))
- logger.info(f"Signaled workflow completion for task run {task_run.id} with status {status}")
- except Exception as e:
- logger.warning(f"Failed to signal workflow completion for task run {task_run.id}: {e}")
-
- def safely_get_queryset(self, queryset):
- # Task runs are always scoped to a specific task
- task_id = self.kwargs.get("parent_lookup_task_id")
- if not task_id:
- raise NotFound("Task ID is required")
-
- task_filter = Task.objects.filter(id=task_id, team=self.team)
- # `?ph_debug=true` allows to check tasks of all team members through /tasks/<id>.
- # Allowlist read-only actions only — connection_token is a GET but mints a write-capable token.
- is_internal_debug_read = (
- _is_internal_debug_team(self.team_id)
- and self.action in ("list", "retrieve", "logs", "session_logs", "stream")
- and self.request.query_params.get("ph_debug") == "true"
- )
- if not is_internal_debug_read:
- task_filter = task_filter.filter(task_visibility_q(getattr(self.request.user, "id", None)))
- if not task_filter.exists():
- raise NotFound("Task not found")
-
- return queryset.filter(team=self.team, task_id=task_id)
-
- def get_serializer_context(self):
- return {**super().get_serializer_context(), "team": self.team, "team_id": self.team.id}
-
- def perform_create(self, serializer):
- task_id = self.kwargs.get("parent_lookup_task_id")
- if not task_id:
- raise NotFound("Task ID is required")
- task = (
- Task.objects.filter(id=task_id, team=self.team)
- .filter(task_visibility_q(getattr(self.request.user, "id", None)))
- .first()
- )
- if task is None:
- raise NotFound("Task not found")
- serializer.save(team=self.team, task=task)
-
- def _trigger_workflow(self, task: Task, task_run: TaskRun, *, raise_on_error: bool = False) -> None:
- try:
- logger.info("Attempting to trigger task processing workflow for task %s, run %s", task.id, task_run.id)
- execute_task_processing_workflow(
- task_id=str(task.id),
- run_id=str(task_run.id),
- team_id=task.team.id,
- user_id=getattr(self.request.user, "id", None),
- posthog_mcp_scopes=_resolve_posthog_mcp_scopes(task_run),
- )
- logger.info("Workflow trigger completed for task %s, run %s", task.id, task_run.id)
- except Exception as e:
- logger.exception(
- "Failed to trigger task processing workflow for task %s, run %s: %s", task.id, task_run.id, e
- )
- if raise_on_error:
- raise
-
- def _build_artifact_storage_path(self, task_run: TaskRun, artifact_id: str, name: str) -> tuple[str, str]:
- safe_name = get_safe_artifact_name(name)
- prefix = task_run.get_artifact_s3_prefix()
- return safe_name, f"{prefix}/{artifact_id[:8]}_{safe_name}"
-
- @staticmethod
- def _tag_artifact_object(task_run: TaskRun, storage_path: str) -> None:
- try:
- object_storage.tag(
- storage_path,
- {
- "ttl_days": "30",
- "team_id": str(task_run.team_id),
- },
- )
- except Exception as exc:
- logger.warning(
- "task_run.artifact_tag_failed",
- extra={
- "task_run_id": str(task_run.id),
- "storage_path": storage_path,
- "error": str(exc),
- },
- )
-
- @staticmethod
- def _build_artifact_manifest_entry(
- *,
- artifact_id: str,
- name: str,
- artifact_type: str,
- source: str,
- size: int,
- content_type: str,
- storage_path: str,
- uploaded_at: str,
- ) -> dict[str, str | int]:
- return {
- "id": artifact_id,
- "name": name,
- "type": artifact_type,
- "source": source,
- "size": size,
- "content_type": content_type,
- "storage_path": storage_path,
- "uploaded_at": uploaded_at,
- }
-
- @staticmethod
- def _find_artifact_manifest_entry(
- manifest: builtins.list[dict[str, Any]], artifact_id: str, storage_path: str
- ) -> dict[str, Any] | None:
- return next(
- (
- entry
- for entry in manifest
- if entry.get("id") == artifact_id or entry.get("storage_path") == storage_path
- ),
- None,
- )
-
- @staticmethod
- def _save_artifact_manifest(task_run: TaskRun, manifest: builtins.list[dict[str, Any]]) -> None:
- task_run.artifacts = manifest
- task_run.save(update_fields=["artifacts", "updated_at"])
-
- @validated_request(
- request_serializer=TaskRunSetOutputRequestSerializer,
- responses={
- 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run with updated output"),
- 404: OpenApiResponse(description="Run not found"),
- },
- summary="Set run output",
- description="Update the output field for a task run (e.g., PR URL, commit SHA, etc.)",
- )
- @action(
- detail=True,
- methods=["patch"],
- url_path="set_output",
- required_scopes=["task:write"],
- )
- def set_output(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- task = cast(Task, task_run.task)
- output_data = request.validated_data["output"]
-
- if task.json_schema:
- try:
- jsonschema.validate(instance=output_data, schema=task.json_schema)
- except jsonschema.ValidationError as e:
- return Response(
- TaskRunErrorResponseSerializer({"error": f"Output validation error: {e.message}"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
- task_run.output = output_data
- task_run.save(update_fields=["output", "updated_at"])
- # We only really want to complete the task run if it's a structured output task.
- if task.json_schema:
- self._signal_workflow_completion(task_run, TaskRun.Status.COMPLETED, None)
- task_run.publish_stream_state_event()
- self._post_slack_update_for_pr(task_run)
-
- return Response(TaskRunDetailSerializer(task_run, context=self.get_serializer_context()).data)
-
- @validated_request(
- request_serializer=TaskRunAppendLogRequestSerializer,
- responses={
- 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run with updated log"),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid log entries"),
- 404: OpenApiResponse(description="Run not found"),
- },
- summary="Append log entries",
- description="Append one or more log entries to the task run log array",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="append_log",
- required_scopes=["task:write"],
- )
- def append_log(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- timer = ServerTimingsGathered()
-
- entries = request.validated_data["entries"]
- with timer("s3_append"):
- task_run.append_log(entries)
-
- task_run.heartbeat_workflow(agent_active=True)
-
- response = Response(TaskRunDetailSerializer(task_run, context=self.get_serializer_context()).data)
- response["Server-Timing"] = timer.to_header_string()
- return response
-
- @validated_request(
- request_serializer=TaskRunRelayMessageRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskRunRelayMessageResponseSerializer,
- description="Relay accepted",
- ),
- 404: OpenApiResponse(description="Run not found"),
- },
- summary="Relay run message to Slack",
- description="Queue a Slack relay workflow to post a run message into the mapped Slack thread.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="relay_message",
- required_scopes=["task:write"],
- )
- def relay_message(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- if task_run.is_terminal:
- return Response({"status": "skipped"})
-
- # Skip relay for non-Slack tasks — no thread to post to
- from products.slack_app.backend.models import SlackThreadTaskMapping
-
- if not SlackThreadTaskMapping.objects.filter(task_run=task_run).exists():
- return Response({"status": "skipped"})
-
- text = request.validated_data["text"].strip()
- if not text:
- return Response({"status": "skipped"})
-
- try:
- relay_id = execute_posthog_code_agent_relay_workflow(
- run_id=str(task_run.id),
- text=text,
- delete_progress=True,
- )
- except Exception:
- logger.exception(
- "task_run_relay_message_enqueue_failed",
- extra={"run_id": str(task_run.id)},
- )
- return Response(
- TaskRunErrorResponseSerializer({"error": "Failed to queue Slack relay"}).data,
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
- return Response({"status": "accepted", "relay_id": relay_id})
-
- @validated_request(
- request_serializer=TaskRunArtifactsUploadRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskRunArtifactsUploadResponseSerializer,
- description="Run with updated artifact manifest",
- ),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
- 404: OpenApiResponse(description="Run not found"),
- },
- summary="Upload artifacts for a task run",
- description="Persist task artifacts to S3 and attach them to the run manifest.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="artifacts",
- required_scopes=["task:write"],
- )
- def artifacts(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- artifacts = request.validated_data["artifacts"]
- uploaded: list[dict] = []
-
- for artifact in artifacts:
- artifact_id = uuid.uuid4().hex
- safe_name, storage_path = self._build_artifact_storage_path(task_run, artifact_id, artifact["name"])
-
- content_bytes = artifact["content_bytes"]
- extras: dict[str, str] = {}
- content_type = artifact.get("content_type")
- if content_type:
- extras["ContentType"] = content_type
-
- object_storage.write(storage_path, content_bytes, extras or None)
- self._tag_artifact_object(task_run, storage_path)
-
- uploaded_at = timezone.now().isoformat()
- uploaded.append(
- self._build_artifact_manifest_entry(
- artifact_id=artifact_id,
- name=safe_name,
- artifact_type=artifact["type"],
- source=artifact.get("source") or "",
- size=len(content_bytes),
- content_type=content_type or "",
- storage_path=storage_path,
- uploaded_at=uploaded_at,
- )
- )
-
- logger.info(
- "task_run.artifact_uploaded",
- extra={
- "task_run_id": str(task_run.id),
- "storage_path": storage_path,
- "artifact_type": artifact["type"],
- "size": len(content_bytes),
- },
- )
-
- with transaction.atomic():
- task_run = TaskRun.objects.select_for_update().get(pk=task_run.pk)
- manifest = list(task_run.artifacts or [])
- manifest.extend(uploaded)
- self._save_artifact_manifest(task_run, manifest)
-
- serializer = TaskRunArtifactsUploadResponseSerializer(
- {"artifacts": manifest},
- context=self.get_serializer_context(),
- )
- return Response(serializer.data)
-
- @validated_request(
- request_serializer=TaskRunArtifactsPrepareUploadRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskRunArtifactsPrepareUploadResponseSerializer,
- description="Prepared uploads for the requested artifacts",
- ),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
- 404: OpenApiResponse(description="Run not found"),
- },
- summary="Prepare direct uploads for task run artifacts",
- description="Reserve S3 object keys for task artifacts and return presigned POST forms for direct uploads.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="artifacts/prepare_upload",
- required_scopes=["task:write"],
- )
- def artifacts_prepare_upload(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- artifacts = request.validated_data["artifacts"]
-
- prepared_artifacts: list[dict] = []
-
- for artifact in artifacts:
- artifact_id = uuid.uuid4().hex
- safe_name, storage_path = self._build_artifact_storage_path(task_run, artifact_id, artifact["name"])
- content_type = artifact.get("content_type") or ""
- conditions: list[list[str | int]] = [
- ["content-length-range", 0, artifact["size"] + TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES]
- ]
-
- presigned_post = object_storage.get_presigned_post(
- storage_path,
- conditions=conditions,
- expiration=TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS,
- )
- if not presigned_post:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Unable to generate upload URL"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- prepared_artifacts.append(
- {
- "id": artifact_id,
- "name": safe_name,
- "type": artifact["type"],
- "source": artifact.get("source") or "",
- "size": artifact["size"],
- "content_type": content_type,
- "storage_path": storage_path,
- "expires_in": TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS,
- "presigned_post": presigned_post,
- }
- )
-
- serializer = TaskRunArtifactsPrepareUploadResponseSerializer(
- {"artifacts": prepared_artifacts},
- context=self.get_serializer_context(),
- )
- return Response(serializer.data)
-
- @validated_request(
- request_serializer=TaskRunArtifactsFinalizeUploadRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskRunArtifactsFinalizeUploadResponseSerializer,
- description="Run with updated artifact manifest",
- ),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
- 404: OpenApiResponse(description="Run not found"),
- },
- summary="Finalize direct uploads for task run artifacts",
- description="Verify directly uploaded S3 objects and attach them to the run artifact manifest.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="artifacts/finalize_upload",
- required_scopes=["task:write"],
- )
- def artifacts_finalize_upload(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- artifacts = request.validated_data["artifacts"]
- manifest = list(task_run.artifacts or [])
- artifact_prefix = f"{task_run.get_artifact_s3_prefix()}/"
- finalized_entries: list[dict] = []
- new_storage_paths: list[str] = []
-
- for artifact in artifacts:
- artifact_id = artifact["id"]
- storage_path = artifact["storage_path"]
-
- if not storage_path.startswith(artifact_prefix) or f"/{artifact_id[:8]}_" not in storage_path:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact storage path is invalid for this run"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- existing_entry = self._find_artifact_manifest_entry(manifest, artifact_id, storage_path)
- if existing_entry is not None:
- # Callers rely on the response to return artifacts uploaded in
- # this request so they can pass those IDs back with subsequent
- # user_message commands. Echo the already-finalized entry
- # instead of the entire cumulative manifest — otherwise prior
- # turns' artifacts would be re-sent alongside the current ones.
- finalized_entries.append(existing_entry)
- continue
-
- s3_object = object_storage.head_object(storage_path)
- if not s3_object:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact upload not found in object storage"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- safe_name = get_safe_artifact_name(artifact["name"])
- content_type = artifact.get("content_type") or s3_object.get("ContentType") or ""
- content_length = s3_object.get("ContentLength")
- if not isinstance(content_length, int):
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact upload metadata is unavailable"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- max_size_bytes = get_task_run_artifact_max_size_bytes(
- safe_name,
- content_type,
- artifact.get("type"),
- )
- if content_length > max_size_bytes:
- return Response(
- TaskRunErrorResponseSerializer(
- {"error": build_task_run_artifact_size_error(safe_name, max_size_bytes)}
- ).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- entry = self._build_artifact_manifest_entry(
- artifact_id=artifact_id,
- name=safe_name,
- artifact_type=artifact["type"],
- source=artifact.get("source") or "",
- size=content_length,
- content_type=content_type,
- storage_path=storage_path,
- uploaded_at=timezone.now().isoformat(),
- )
- manifest.append(entry)
- finalized_entries.append(entry)
- new_storage_paths.append(storage_path)
-
- self._save_artifact_manifest(task_run, manifest)
-
- for storage_path in new_storage_paths:
- self._tag_artifact_object(task_run, storage_path)
-
- serializer = TaskRunArtifactsFinalizeUploadResponseSerializer(
- {"artifacts": finalized_entries},
- context=self.get_serializer_context(),
- )
- return Response(serializer.data)
-
- @validated_request(
- request_serializer=TaskRunArtifactPresignRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskRunArtifactPresignResponseSerializer,
- description="Presigned URL for the requested artifact",
- ),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request"),
- 404: OpenApiResponse(description="Artifact not found"),
- },
- summary="Generate presigned URL for an artifact",
- description="Returns a temporary, signed URL that can be used to download a specific artifact.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="artifacts/presign",
- required_scopes=["task:read"],
- )
- def artifacts_presign(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- storage_path = request.validated_data["storage_path"]
- artifacts = task_run.artifacts or []
-
- if not any(artifact.get("storage_path") == storage_path for artifact in artifacts):
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
- status=status.HTTP_404_NOT_FOUND,
- )
-
- url = object_storage.get_presigned_url(storage_path)
- if not url:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Unable to generate download URL"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- expires_in = 3600
- serializer = TaskRunArtifactPresignResponseSerializer({"url": url, "expires_in": expires_in})
- return Response(serializer.data)
-
- @validated_request(
- request_serializer=TaskRunArtifactPresignRequestSerializer,
- responses={
- 200: OpenApiResponse(
- description="Artifact content",
- ),
- 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request"),
- 404: OpenApiResponse(description="Artifact not found"),
- },
- summary="Download an artifact through the backend",
- description="Streams artifact content for a task run artifact after validating that it belongs to the run.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="artifacts/download",
- required_scopes=["task:read"],
- )
- def artifacts_download(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- 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.
- artifact = task_run.find_artifact_in_resume_chain(storage_path)
-
- if artifact is None:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
- status=status.HTTP_404_NOT_FOUND,
- )
-
- try:
- content = object_storage.read_bytes(storage_path, missing_ok=True)
- except Exception:
- logger.exception(
- "task_run.artifact_download_failed",
- extra={
- "task_run_id": str(task_run.id),
- "storage_path": storage_path,
- },
- )
- return Response(
- TaskRunErrorResponseSerializer({"error": "Unable to read artifact"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- if content is None:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Artifact content not found"}).data,
- status=status.HTTP_404_NOT_FOUND,
- )
-
- response = HttpResponse(
- content,
- content_type=str(artifact.get("content_type") or "application/octet-stream"),
- )
- response["Cache-Control"] = "no-cache"
- response["Content-Disposition"] = (
- f'attachment; filename="{os.path.basename(str(artifact.get("name") or "artifact"))}"'
- )
- return response
-
- @extend_schema(
- extensions={"x-product": "logs"},
- responses={
- 200: OpenApiResponse(description="Log content in JSONL format"),
- 404: OpenApiResponse(description="Task run not found"),
- },
- summary="Get task run logs",
- description=(
- "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."
- ),
- )
- @action(detail=True, methods=["get"], url_path="logs", required_scopes=["task:read"])
- def logs(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- timer = ServerTimingsGathered()
-
- chain = task_run.get_resume_chain()
- with timer("s3_read"):
- parts: list[str] = []
- for run in chain:
- chunk = object_storage.read(run.log_url, missing_ok=True) or ""
- if chunk:
- if not chunk.endswith("\n"):
- chunk = chunk + "\n"
- parts.append(chunk)
- log_content = "".join(parts)
-
- response = HttpResponse(log_content, content_type="application/jsonl")
- response["Cache-Control"] = "no-cache"
- response["Server-Timing"] = timer.to_header_string()
- return response
-
- @validated_request(
- responses={
- 200: OpenApiResponse(
- response=ConnectionTokenResponseSerializer,
- description="Connection token for direct sandbox connection",
- ),
- 404: OpenApiResponse(description="Task run not found"),
- },
- summary="Get sandbox connection token",
- description="Generate a JWT token for direct connection to the sandbox. Valid for 24 hours.",
- )
- @action(
- detail=True,
- methods=["get"],
- url_path="connection_token",
- required_scopes=["task:write"],
- )
- def connection_token(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- user = request.user
-
- token = create_sandbox_connection_token(
- task_run=task_run,
- user_id=user.id,
- distinct_id=user.distinct_id,
- )
-
- return Response(ConnectionTokenResponseSerializer({"token": token}).data)
-
- @validated_request(
- request_serializer=TaskRunCommandRequestSerializer,
- responses={
- 200: OpenApiResponse(
- response=TaskRunCommandResponseSerializer,
- description="Agent server response",
- ),
- 400: OpenApiResponse(
- response=TaskRunErrorResponseSerializer,
- description="Invalid command or no active sandbox",
- ),
- 404: OpenApiResponse(description="Task run not found"),
- 502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),
- },
- summary="Send command to task run",
- description="Queue user_message JSON-RPC commands through the task workflow and forward sandbox control "
- "commands to the agent server. Supports user_message, cancel, close, permission_response, "
- "and set_config_option commands.",
- strict_request_validation=True,
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="command",
- required_scopes=["task:write"],
- )
- def command(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- method = request.validated_data["method"]
- request_id = request.validated_data.get("id")
- params = request.validated_data.get("params")
-
- if method == "user_message":
- command_params = dict(params or {})
- artifact_ids = command_params.pop("artifact_ids", [])
- if artifact_ids:
- _, missing_artifact_ids = get_task_run_artifacts_by_id(task_run, artifact_ids)
- if missing_artifact_ids:
- return Response(
- {
- "error": "Some artifact_ids are invalid for this run",
- "missing_artifact_ids": missing_artifact_ids,
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- try:
- signal_task_followup_message(
- task_run.workflow_id,
- command_params.get("content"),
- artifact_ids,
- )
- except Exception:
- logger.exception("Failed to signal follow-up message for task run %s", task_run.id)
- return Response(
- TaskRunErrorResponseSerializer({"error": "Failed to queue user message for task run"}).data,
- status=status.HTTP_502_BAD_GATEWAY,
- )
-
- response_payload: dict[str, Any] = {
- "jsonrpc": request.validated_data["jsonrpc"],
- "result": {"queued": True},
- }
- if request_id is not None:
- response_payload["id"] = request_id
- return Response(TaskRunCommandResponseSerializer(response_payload).data)
-
- run_state = parse_run_state(task_run.state)
-
- if not run_state.sandbox_url:
- return Response(
- TaskRunErrorResponseSerializer({"error": "No active sandbox for this task run"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- if not self._is_valid_sandbox_url(run_state.sandbox_url):
- logger.warning(f"Blocked request to disallowed sandbox URL for task run {task_run.id}")
- return Response(
- TaskRunErrorResponseSerializer({"error": "Invalid sandbox URL"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- connection_token = create_sandbox_connection_token(
- task_run=task_run,
- user_id=request.user.id,
- distinct_id=request.user.distinct_id,
- )
-
- command_payload: dict = {
- "jsonrpc": request.validated_data["jsonrpc"],
- "method": method,
- }
- if params:
- command_params = dict(params)
- if command_params:
- command_payload["params"] = command_params
- if request_id is not None:
- command_payload["id"] = request_id
-
- try:
- agent_response = self._proxy_command_to_agent_server(
- sandbox_url=run_state.sandbox_url,
- connection_token=connection_token,
- sandbox_connect_token=run_state.sandbox_connect_token,
- payload=command_payload,
- )
-
- if agent_response.ok:
- return Response(agent_response.json())
-
- try:
- error_body = agent_response.json()
- except Exception:
- error_body = {}
-
- if agent_response.status_code == 401:
- error_msg = error_body.get("error", "Agent server authentication failed")
- logger.warning(f"Agent server auth failed for task run {task_run.id}: {error_msg}")
- elif agent_response.status_code == 400:
- error_msg = error_body.get("error", "Agent server rejected the command")
- logger.warning(f"Agent server rejected command for task run {task_run.id}: {error_msg}")
- else:
- error_msg = error_body.get("error", f"Agent server returned {agent_response.status_code}")
-
- return Response(
- TaskRunErrorResponseSerializer({"error": error_msg}).data,
- status=status.HTTP_502_BAD_GATEWAY,
- )
-
- except http_requests.ConnectionError:
- logger.warning(f"Agent server unreachable for task run {task_run.id}")
- return Response(
- TaskRunErrorResponseSerializer({"error": "Agent server is not reachable"}).data,
- status=status.HTTP_502_BAD_GATEWAY,
- )
- except http_requests.Timeout:
- logger.warning(f"Agent server request timed out for task run {task_run.id}")
- return Response(
- TaskRunErrorResponseSerializer({"error": "Agent server request timed out"}).data,
- status=status.HTTP_504_GATEWAY_TIMEOUT,
- )
- except Exception:
- logger.exception(f"Failed to proxy command to agent server for task run {task_run.id}")
- return Response(
- TaskRunErrorResponseSerializer({"error": "Failed to send command to agent server"}).data,
- status=status.HTTP_502_BAD_GATEWAY,
- )
-
- @staticmethod
- def _is_valid_sandbox_url(url: str) -> bool:
- """Validate sandbox URL against allowlist to prevent SSRF.
-
- Only allows:
- - http://localhost:{port} (Docker sandboxes)
- - http://127.0.0.1:{port} (Docker sandboxes)
- - https://*.modal.run (Modal sandboxes)
- - https://*.modal.host (Modal connect token sandboxes)
- """
- from urllib.parse import urlparse
-
- try:
- parsed = urlparse(url)
- except Exception:
- return False
-
- if parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1"):
- return True
-
- if (
- parsed.scheme == "https"
- and parsed.hostname
- and (parsed.hostname.endswith(".modal.run") or parsed.hostname.endswith(".modal.host"))
- ):
- return True
-
- return False
-
- @staticmethod
- def _proxy_command_to_agent_server(
- sandbox_url: str,
- connection_token: str,
- sandbox_connect_token: str | None,
- payload: dict,
- ) -> http_requests.Response:
- headers = {
- "Content-Type": "application/json",
- "Authorization": f"Bearer {connection_token}",
- }
-
- command_url = f"{sandbox_url.rstrip('/')}/command"
-
- # Modal connect tokens use Authorization: Bearer for tunnel auth,
- # which conflicts with the JWT auth the agent server expects.
- # Pass the Modal token as a query parameter instead so both
- # auth mechanisms can coexist.
- params = {}
- if sandbox_connect_token:
- params["_modal_connect_token"] = sandbox_connect_token
-
- return http_requests.post(
- command_url,
- json=payload,
- headers=headers,
- params=params,
- timeout=600,
- )
-
- @validated_request(
- query_serializer=TaskRunSessionLogsQuerySerializer,
- responses={
- 200: OpenApiResponse(description="Filtered log events as JSON array"),
- 404: OpenApiResponse(description="Task run not found"),
- },
- summary="Get filtered task run session logs",
- description="Fetch session log entries for a task run with optional filtering by timestamp, event type, and limit.",
- )
- @action(
- detail=True,
- methods=["get"],
- url_path="session_logs",
- required_scopes=["task:read"],
- )
- def session_logs(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- timer = ServerTimingsGathered()
-
- with timer("s3_read"):
- log_content = object_storage.read(task_run.log_url, missing_ok=True) or ""
-
- if not log_content.strip():
- response = JsonResponse([], safe=False)
- response["X-Total-Count"] = "0"
- response["X-Filtered-Count"] = "0"
- response["X-Matching-Count"] = "0"
- response["X-Has-More"] = "false"
- response["Cache-Control"] = "no-cache"
- response["Server-Timing"] = timer.to_header_string()
- return response
-
- # Parse all JSONL entries
- all_entries = []
- for line in log_content.strip().split("\n"):
- line = line.strip()
- if not line:
- continue
- try:
- all_entries.append(json.loads(line))
- except json.JSONDecodeError:
- continue
-
- total_count = len(all_entries)
-
- # Apply filters from validated query params
- params = request.validated_query_data
- after = params.get("after")
- event_types_str = params.get("event_types")
- exclude_types_str = params.get("exclude_types")
- limit = params.get("limit", 1000)
- offset = params.get("offset", 0)
-
- event_types = {t.strip() for t in event_types_str.split(",") if t.strip()} if event_types_str else None
- exclude_types = {t.strip() for t in exclude_types_str.split(",") if t.strip()} if exclude_types_str else None
-
- with timer("filter"):
- filtered = []
- for entry in all_entries:
- # Filter by timestamp (parse to avoid Z vs +00:00 and fractional second mismatches)
- if after:
- entry_ts = entry.get("timestamp", "")
- if not entry_ts:
- continue # Skip entries without timestamps
- try:
- entry_dt = datetime.fromisoformat(entry_ts.replace("Z", "+00:00"))
- if entry_dt <= after:
- continue
- except (ValueError, TypeError):
- continue # Skip entries with unparseable timestamps
-
- # Determine the event type for filtering
- event_type = self._get_event_type(entry)
-
- if event_types and event_type not in event_types:
- continue
- if exclude_types and event_type in exclude_types:
- continue
-
- filtered.append(entry)
-
- matching_count = len(filtered)
- page = filtered[offset : offset + limit]
- has_more = offset + len(page) < matching_count
-
- response = JsonResponse(page, safe=False)
- response["X-Total-Count"] = str(total_count)
- response["X-Filtered-Count"] = str(matching_count)
- response["X-Matching-Count"] = str(matching_count)
- response["X-Has-More"] = "true" if has_more else "false"
- response["Cache-Control"] = "no-cache"
- response["Server-Timing"] = timer.to_header_string()
- return response
-
- @validated_request(
- responses={
- 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run resumed in cloud"),
- 400: OpenApiResponse(
- response=TaskRunErrorResponseSerializer, description="Run already active or workflow failed"
- ),
- 429: OpenApiResponse(
- response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
- ),
- },
- summary="Resume task run in cloud",
- description="Resume an existing task run in a cloud sandbox. Terminates any existing workflow and starts a new one.",
- )
- @action(
- detail=True,
- methods=["post"],
- url_path="resume_in_cloud",
- required_scopes=["task:write"],
- )
- def resume_in_cloud(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
-
- # Resume also runs in cloud: gate before handoff.
- if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
- return limit_response
-
- logger.info(
- "resume_in_cloud_called",
- extra={
- "task_run_id": str(task_run.id),
- "task_id": str(task_run.task_id),
- "prior_status": task_run.status,
- "prior_environment": task_run.environment,
- "prior_state_keys": sorted((task_run.state or {}).keys()),
- "prior_snapshot_external_id": (task_run.state or {}).get("snapshot_external_id"),
- "use_modal_resume_snapshots": settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS,
- },
- )
-
- with transaction.atomic():
- task_run = (
- TaskRun.objects.select_for_update(of=("self",))
- .select_related("task", "task__created_by", "task__github_integration", "task__github_user_integration")
- .get(pk=task_run.pk)
- )
-
- is_cloud_active = task_run.environment == TaskRun.Environment.CLOUD and task_run.status in (
- TaskRun.Status.QUEUED,
- TaskRun.Status.IN_PROGRESS,
- )
- if is_cloud_active:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Run is already active in cloud"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- if get_pr_authorship_mode(task_run.task, task_run.state) == PrAuthorshipMode.USER:
- pr_authorship_mode, validation_response = _resolve_cloud_pr_authorship_mode(
- task_run.task,
- pr_authorship_mode=PrAuthorshipMode.USER,
- request_user_id=getattr(request.user, "id", None),
- github_user_token=None,
- )
- if validation_response is not None:
- return validation_response
- if pr_authorship_mode is not None:
- task_run.state = {
- **(task_run.state or {}),
- "pr_authorship_mode": (
- pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
- ),
- }
-
- prior_status = task_run.status
- prior_environment = task_run.environment
- prior_completed_at = task_run.completed_at
- prior_state = dict(task_run.state or {})
- task_run.prepare_for_cloud_handoff()
-
- # Any prior workflow under this ID gets terminated atomically by
- # TERMINATE_IF_RUNNING inside resume_task_in_cloud_workflow. We
- # intentionally don't send a separate cancel signal here: it races
- # with start, and signals are routed by workflow_id so a late signal
- # could land on the new execution.
-
- logger.info(
- "Resuming task run in cloud",
- extra={
- "task_run_id": str(task_run.id),
- "task_id": str(task_run.task_id),
- },
- )
-
- try:
- resume_task_in_cloud_workflow(str(task_run.id), task_run.workflow_id)
- except Exception as e:
- logger.exception(
- "Failed to trigger handoff workflow",
- extra={"task_run_id": str(task_run.id), "error": str(e)},
- )
- with transaction.atomic():
- task_run = TaskRun.objects.select_for_update().get(pk=task_run.pk)
- task_run.status = prior_status
- task_run.environment = prior_environment
- task_run.completed_at = prior_completed_at
- task_run.state = prior_state
- task_run.error_message = "Failed to start cloud workflow"
- task_run.save(
- update_fields=[
- "status",
- "environment",
- "completed_at",
- "state",
- "error_message",
- "updated_at",
- ]
- )
- task_run.publish_stream_state_event()
- return Response(
- TaskRunErrorResponseSerializer({"error": "Failed to start cloud workflow"}).data,
- status=status.HTTP_502_BAD_GATEWAY,
- )
-
- return Response(TaskRunDetailSerializer(task_run, context=self.get_serializer_context()).data)
-
- @staticmethod
- def _format_sse_event(data: dict, *, event_id: str | None = None, event_name: str | None = None) -> bytes:
- parts: list[str] = []
- if event_name:
- parts.append(f"event: {event_name}")
- if event_id:
- parts.append(f"id: {event_id}")
- parts.append(f"data: {json.dumps(data)}")
- return ("\n".join(parts) + "\n\n").encode()
-
- @action(
- detail=True,
- methods=["get"],
- url_path="stream",
- required_scopes=["task:read"],
- renderer_classes=[ServerSentEventRenderer],
- )
- def stream(self, request, pk=None, **kwargs):
- task_run = cast(TaskRun, self.get_object())
- stream_key = get_task_run_stream_key(str(task_run.id))
- use_dedicated_stream = run_uses_dedicated_stream(task_run.state)
- last_event_id = request.headers.get("Last-Event-ID")
- start_latest = request.GET.get("start") == "latest"
- format_sse_event = self._format_sse_event
- origin_product = origin_product_label(task_run)
-
- async def async_stream() -> AsyncGenerator[bytes]:
- redis_stream = TaskRunRedisStream(stream_key, use_dedicated_stream)
- connection_started_at = asyncio.get_running_loop().time()
- # Default to client_disconnect: any exit that isn't an explicit
- # completion/error/unavailable is the client (or proxy) going away.
- outcome: StreamConnectionOutcome = "client_disconnect"
- # Record opened inside the try so the closed counter only fires when
- # the open succeeded — keeps opened/closed balanced for the
- # active-connections gauge regardless of which increment fails.
- opened = False
- try:
- observe_stream_connection_opened(origin_product)
- opened = True
- delay = TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS
- wait_started_at = asyncio.get_running_loop().time()
- last_keepalive_at = wait_started_at
-
- while not await redis_stream.exists():
- now = asyncio.get_running_loop().time()
- if now - wait_started_at >= TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS:
- outcome = "unavailable"
- yield format_sse_event({"error": "Stream not available"}, event_name="error")
- return
-
- if now - last_keepalive_at >= TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS:
- last_keepalive_at = now
- yield format_sse_event(
- TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,
- event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,
- )
-
- await asyncio.sleep(delay)
- delay = min(
- delay + TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
- TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
- )
-
- # Only reconnects (Last-Event-ID set) can suffer a trimmed resume
- # point, and that's the only case where stream depth vs the trim
- # cap is interesting — so skip the extra Redis reads on fresh
- # connects. Best-effort: never break the stream.
- if last_event_id:
- try:
- observe_stream_length_on_connect(await redis_stream.get_length())
- if await redis_stream.resume_point_trimmed(last_event_id):
- observe_stream_resume_gap(origin_product)
- logger.warning(
- "task_run_stream_resume_gap",
- extra={"stream_key": stream_key, "last_event_id": last_event_id},
- )
- except Exception:
- logger.warning(
- "task_run_stream_attach_observe_failed",
- extra={"stream_key": stream_key},
- exc_info=True,
- )
-
- start_id = last_event_id or "0"
- if not last_event_id and start_latest:
- start_id = await redis_stream.get_latest_stream_id() or "0"
- try:
- async for stream_item in redis_stream.read_stream_entries(
- start_id=start_id,
- keepalive_interval_seconds=TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS,
- ):
- if stream_item is None:
- yield format_sse_event(
- TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,
- event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,
- )
- continue
- event_id, event = stream_item
- yield format_sse_event(event, event_id=event_id)
- outcome = "completed"
- except TaskRunStreamError as e:
- outcome = "stream_error"
- logger.error("TaskRunRedisStream error for stream %s: %s", stream_key, e, exc_info=True)
- yield format_sse_event({"error": str(e)}, event_name="error")
- finally:
- if opened:
- duration = asyncio.get_running_loop().time() - connection_started_at
- observe_stream_connection_closed(origin_product, outcome, duration)
-
- return StreamingHttpResponse(
- async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream()),
- content_type="text/event-stream",
- headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
- )
-
- @staticmethod
- def _get_event_type(entry: dict) -> str:
- """Extract the event type from a log entry for filtering purposes.
-
- For _posthog/* events, returns the notification method (e.g., '_posthog/console').
- For session/update events, returns the sessionUpdate value (e.g., 'agent_message_chunk').
- """
- notification = entry.get("notification", {})
- if not isinstance(notification, dict):
- return ""
- method = notification.get("method", "")
-
- if method == "session/update":
- params = notification.get("params", {})
- update = params.get("update", {}) if isinstance(params, dict) else {}
- return str(update.get("sessionUpdate", method)) if isinstance(update, dict) else method
-
- return method
-
-
-def _activate_code_for_user(user, organization=None) -> None:
- """Capture an analytics event when a user redeems a Code invite."""
- posthoganalytics.capture(
- distinct_id=str(user.distinct_id),
- event="code_invite_redeemed",
- groups=groups(organization=organization),
- )
-
-
-@extend_schema(tags=["code-invites"])
-class CodeInviteViewSet(viewsets.ViewSet):
- """API for redeeming PostHog Code invite codes."""
-
- authentication_classes = [
- SessionAuthentication,
- PersonalAPIKeyAuthentication,
- OAuthAccessTokenAuthentication,
- ]
- permission_classes = [IsAuthenticated, APIScopePermission]
-
- scope_object = "task"
-
- http_method_names = ["get", "post", "head", "options"]
- throttle_classes = [CodeInviteThrottle]
-
- def get_permissions(self):
- # Both endpoints are user-account-level operations (not project data).
- if self.action in ("check_access", "redeem"):
- return [IsAuthenticated()]
- return super().get_permissions()
-
- @validated_request(
- request_serializer=CodeInviteRedeemRequestSerializer,
- responses={
- 200: OpenApiResponse(description="Invite code redeemed successfully"),
- 400: OpenApiResponse(
- response=TaskRunErrorResponseSerializer,
- description="Invalid or expired invite code",
- ),
- },
- summary="Redeem invite code",
- description="Redeem a PostHog Code invite code to enable access.",
- )
- @action(detail=False, methods=["post"], url_path="redeem")
- def redeem(self, request, **kwargs):
- code_str = request.validated_data["code"].strip()
-
- try:
- invite_code = CodeInvite.objects.get(code__iexact=code_str)
- except CodeInvite.DoesNotExist:
- return Response(
- TaskRunErrorResponseSerializer({"error": "Invalid invite code"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- if CodeInviteRedemption.objects.filter(invite_code=invite_code, user=request.user).exists():
- return Response({"success": True})
-
- with transaction.atomic():
- invite_code = CodeInvite.objects.select_for_update().get(id=invite_code.id)
-
- if not invite_code.is_redeemable:
- return Response(
- TaskRunErrorResponseSerializer({"error": "This invite code is no longer valid"}).data,
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- organization = request.user.organization if hasattr(request.user, "organization") else None
-
- CodeInviteRedemption.objects.create(
- invite_code=invite_code,
- user=request.user,
- organization=organization,
- )
-
- CodeInvite.objects.filter(id=invite_code.id).update(redemption_count=F("redemption_count") + 1)
-
- _activate_code_for_user(request.user, organization=organization)
-
- return Response({"success": True})
-
- @extend_schema(
- responses={
- 200: OpenApiResponse(description="Access check result"),
- },
- summary="Check access",
- description="Check whether the authenticated user has access to PostHog Code.",
- )
- @action(detail=False, methods=["get"], url_path="check-access")
- def check_access(self, request, **kwargs):
- return Response({"has_access": has_tasks_access(request.user)})
-
-
-@extend_schema(tags=["sandbox-environments"])
-class SandboxEnvironmentViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
- """API for managing sandbox environments that control network access for task runs."""
-
- serializer_class = SandboxEnvironmentSerializer
- authentication_classes = [
- SessionAuthentication,
- PersonalAPIKeyAuthentication,
- OAuthAccessTokenAuthentication,
- ]
- permission_classes = [IsAuthenticated, APIScopePermission]
- scope_object = "task"
- queryset = SandboxEnvironment.objects.all()
- http_method_names = ["get", "post", "patch", "delete", "head", "options"]
- filter_rewrite_rules = {"team_id": "team_id"}
-
- def get_serializer_class(self):
- if self.action == "list":
- return SandboxEnvironmentListSerializer
- return SandboxEnvironmentSerializer
-
- def safely_get_queryset(self, queryset):
- user = self.request.user
- qs = queryset.filter(models.Q(private=False) | models.Q(created_by=user))
- # Exclude internal environments from list views by default
- if self.action == "list":
- qs = qs.filter(internal=False)
- return qs
-
- def get_serializer_context(self):
- context = super().get_serializer_context()
- context["team"] = self.team
- return context
diff --git a/products/tasks/backend/code_home_api.py b/products/tasks/backend/code_home_api.py
deleted file mode 100644
index 5edb815b3e51..000000000000
--- a/products/tasks/backend/code_home_api.py
+++ /dev/null
@@ -1,209 +0,0 @@
-from datetime import datetime, timedelta
-from typing import cast
-
-from django.db import transaction
-from django.utils import timezone
-
-from rest_framework import status, viewsets
-from rest_framework.authentication import SessionAuthentication
-from rest_framework.decorators import action
-from rest_framework.permissions import IsAuthenticated
-from rest_framework.response import Response
-
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
-from posthog.models.user import User
-from posthog.permissions import APIScopePermission
-
-from .code_workstreams.default_workflow import build_default_bindings
-from .code_workstreams.validation import ValidationDiagnostic, validate_bindings
-from .models import CodeWorkflowConfig, CodeWorkstream, TaskRun
-
-ACTIVE_AGENT_WINDOW = timedelta(minutes=30)
-RUNNING_STATUSES = (TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS)
-
-_AUTH_CLASSES = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
-
-
-def _epoch_ms(dt: datetime) -> int:
- return int(dt.timestamp() * 1000)
-
-
-def _serialize_diagnostic(d: ValidationDiagnostic) -> dict:
- out = {"severity": d.severity, "code": d.code, "message": d.message}
- if d.situation_id is not None:
- out["situationId"] = d.situation_id
- if d.action_id is not None:
- out["actionId"] = d.action_id
- return out
-
-
-def _serialize_config(config: CodeWorkflowConfig) -> dict:
- return {
- "id": str(config.id),
- "version": config.version,
- "updatedAt": config.updated_at.isoformat(),
- "bindings": config.bindings,
- }
-
-
-class CodeWorkflowViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
- scope_object = "task"
- authentication_classes = _AUTH_CLASSES
- permission_classes = [IsAuthenticated, APIScopePermission]
- hide_api_docs = True
-
- def _get_or_seed(self) -> CodeWorkflowConfig:
- config, _ = CodeWorkflowConfig.objects.get_or_create(
- team=self.team,
- user=self.request.user,
- defaults={"bindings": build_default_bindings(), "version": 1},
- )
- return config
-
- def list(self, request, *args, **kwargs):
- return Response(_serialize_config(self._get_or_seed()))
-
- @action(detail=False, methods=["post"], url_path="save", required_scopes=["task:write"])
- def save(self, request, **kwargs):
- config_in = request.data.get("config") or {}
- expected_version = request.data.get("expectedVersion")
- bindings = config_in.get("bindings") or {}
-
- with transaction.atomic():
- current, _ = CodeWorkflowConfig.objects.select_for_update().get_or_create(
- team=self.team,
- user=self.request.user,
- defaults={"bindings": build_default_bindings(), "version": 1},
- )
- if not isinstance(expected_version, int) or current.version != expected_version:
- return Response(
- {"status": "conflict", "config": _serialize_config(current)},
- status=status.HTTP_409_CONFLICT,
- )
-
- result = validate_bindings(bindings)
- if not result.can_save:
- return Response(
- {
- "status": "invalid",
- "config": _serialize_config(current),
- "diagnostics": [_serialize_diagnostic(d) for d in result.diagnostics],
- },
- status=status.HTTP_422_UNPROCESSABLE_ENTITY,
- )
-
- current.bindings = bindings
- current.version = current.version + 1
- current.save(update_fields=["bindings", "version", "updated_at"])
- return Response({"status": "saved", "config": _serialize_config(current)})
-
- @action(detail=False, methods=["post"], url_path="reset", required_scopes=["task:write"])
- def reset(self, request, **kwargs):
- with transaction.atomic():
- config, _ = CodeWorkflowConfig.objects.select_for_update().get_or_create(
- team=self.team,
- user=self.request.user,
- defaults={"bindings": build_default_bindings(), "version": 1},
- )
- config.bindings = build_default_bindings()
- config.version = config.version + 1
- config.save(update_fields=["bindings", "version", "updated_at"])
- return Response(_serialize_config(config))
-
-
-class CodeHomeViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
- scope_object = "task"
- authentication_classes = _AUTH_CLASSES
- permission_classes = [IsAuthenticated, APIScopePermission]
- hide_api_docs = True
-
- def _serialize_workstream(self, ws: CodeWorkstream) -> dict:
- return {
- "id": ws.key,
- "repoName": ws.repo_name,
- "repoFullPath": ws.repo_full_path,
- "branch": ws.branch,
- "prUrl": ws.pr_url,
- "pr": ws.pr,
- "tasks": [
- {
- "id": t.get("id"),
- "title": t.get("title"),
- "status": t.get("status"),
- "isGenerating": False,
- "needsPermission": False,
- "quickAction": t.get("quick_action"),
- }
- for t in (ws.tasks or [])
- ],
- "situations": ws.situations or [],
- "primarySituation": ws.primary_situation,
- "lastActivityAt": _epoch_ms(ws.last_activity_at),
- }
-
- def _active_agents(self) -> list[dict]:
- # Active agents are computed live; workstreams are persisted by the worker.
- cutoff = timezone.now() - ACTIVE_AGENT_WINDOW
- runs = (
- TaskRun.objects.filter(
- team=self.team,
- task__created_by=cast(User, self.request.user),
- task__archived=False,
- task__deleted=False,
- status__in=RUNNING_STATUSES,
- updated_at__gte=cutoff,
- )
- .select_related("task")
- .order_by("-updated_at")
- )
-
- seen_tasks: set[str] = set()
- agents: list[dict] = []
- for run in runs.iterator():
- task = run.task
- if str(task.id) in seen_tasks:
- continue
- if (run.output or {}).get("pr_url"):
- continue
- seen_tasks.add(str(task.id))
- agents.append(
- {
- "taskId": str(task.id),
- "title": task.title,
- "repoName": task.repository.split("/")[-1] if task.repository else None,
- "branch": run.branch,
- "status": run.status,
- "lastActivityAt": _epoch_ms(run.updated_at),
- "needsPermission": False,
- "cloudPrUrl": None,
- }
- )
- return agents
-
- def list(self, request, *args, **kwargs):
- workstreams = CodeWorkstream.objects.filter(team=self.team, user=cast(User, self.request.user))
- needs_attention = []
- in_progress = []
- for ws in workstreams.iterator():
- serialized = self._serialize_workstream(ws)
- if ws.state == CodeWorkstream.WorkstreamState.ATTENTION:
- needs_attention.append(serialized)
- else:
- in_progress.append(serialized)
-
- return Response(
- {
- "activeAgents": self._active_agents(),
- "needsAttention": needs_attention,
- "inProgress": in_progress,
- }
- )
-
- @action(detail=False, methods=["post"], url_path="refresh", required_scopes=["task:write"])
- def refresh(self, request, **kwargs):
- # Deferred import keeps the heavy temporalio dependency off the module import path.
- from .temporal.code_workstreams.client import trigger_team_code_workstreams_evaluation
-
- started = trigger_team_code_workstreams_evaluation(self.team.id)
- return Response({"started": started}, status=status.HTTP_202_ACCEPTED)
diff --git a/products/tasks/backend/code_workstreams/__init__.py b/products/tasks/backend/facade/__init__.py
similarity index 100%
rename from products/tasks/backend/code_workstreams/__init__.py
rename to products/tasks/backend/facade/__init__.py
diff --git a/products/tasks/backend/facade/access.py b/products/tasks/backend/facade/access.py
new file mode 100644
index 000000000000..8cc984ba4e62
--- /dev/null
+++ b/products/tasks/backend/facade/access.py
@@ -0,0 +1,14 @@
+"""
+Facade re-exports for tasks access / usage gating.
+
+``has_tasks_access`` gates whether a user may use the tasks/code product.
+``cloud_usage_limit_response`` returns a structured 429 ``Response`` when the team is over
+its posthog_code usage limit (or ``None`` to proceed) — it is HTTP-layer Response wiring the
+``run``/``start`` endpoints call directly. Presentation imports both from here rather than
+reaching the internal ``access`` / ``logic.services.code_usage_gate`` modules directly.
+"""
+
+from products.tasks.backend.access import has_tasks_access
+from products.tasks.backend.logic.services.code_usage_gate import cloud_usage_limit_response
+
+__all__ = ["cloud_usage_limit_response", "has_tasks_access"]
diff --git a/products/tasks/backend/facade/agents.py b/products/tasks/backend/facade/agents.py
new file mode 100644
index 000000000000..c08c7de0dfeb
--- /dev/null
+++ b/products/tasks/backend/facade/agents.py
@@ -0,0 +1,34 @@
+"""
+Facade re-exports for the multi-turn agent machinery.
+
+The custom-prompt agent surface (sandbox context, the multi-turn session driver, the
+create/poll primitives, local-dev helpers) is shared behavioral infrastructure that other
+products (signals, conversations, evals) build agentic flows on. It crosses the boundary as
+objects, not data, per the wiring pattern. Heavy by import, so it lives here rather than in
+``facade/api.py``.
+"""
+
+from products.tasks.backend.logic.services.custom_prompt_internals import (
+ CustomPromptSandboxContext,
+ EmptyAgentTurnError,
+ OutputFn,
+ create_task_and_trigger,
+ extract_json_from_text,
+ poll_for_turn,
+)
+from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import MultiTurnSession
+from products.tasks.backend.logic.services.dev_sandbox_context import resolve_sandbox_context_for_local_dev
+from products.tasks.backend.logic.services.local_skills import ENV_LOCAL_SKILLS_HOST_PATH, LocalSkillsCache
+
+__all__ = [
+ "ENV_LOCAL_SKILLS_HOST_PATH",
+ "CustomPromptSandboxContext",
+ "EmptyAgentTurnError",
+ "LocalSkillsCache",
+ "MultiTurnSession",
+ "OutputFn",
+ "create_task_and_trigger",
+ "extract_json_from_text",
+ "poll_for_turn",
+ "resolve_sandbox_context_for_local_dev",
+]
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
new file mode 100644
index 000000000000..55ffc066674d
--- /dev/null
+++ b/products/tasks/backend/facade/api.py
@@ -0,0 +1,3255 @@
+"""
+Facade API for the tasks product — the data surface other apps may import.
+
+Responsibilities:
+- Accept ids / DTOs as input.
+- Call into the product's models and logic.
+- Convert Django models to DTOs before returning — never return ORM instances.
+- Stay thin and stable.
+
+This module is deliberately light: it imports the models and small helpers only. The
+heavy behavioral surfaces (sandbox provisioning, the multi-turn agent machinery, temporal
+workflows, max tools) live in sibling facade submodules (``sandbox``, ``agents``,
+``temporal``, ``max_tools``, ``webhooks``, ``streams``, ``repo_selection``) so a
+config-only importer never drags docker/temporalio onto the ``django.setup()`` path.
+Functions that bridge to those heavy surfaces import them lazily inside the function body.
+"""
+
+import logging
+from collections.abc import Iterable, Sequence
+from datetime import datetime, timedelta
+from typing import Literal
+from uuid import UUID, uuid4
+
+from django.db import transaction
+from django.db.models import CharField, Count, Exists, F, Min, OuterRef, Q, Subquery
+from django.db.models.fields.json import KeyTextTransform
+from django.utils import timezone as django_timezone
+
+import posthoganalytics
+
+from posthog.event_usage import groups
+from posthog.models import User
+from posthog.models.integration import Integration
+
+from products.tasks.backend.logic.code_workstreams.default_workflow import build_default_bindings
+from products.tasks.backend.logic.code_workstreams.validation import validate_bindings
+from products.tasks.backend.models import (
+ CodeInvite,
+ CodeInviteRedemption,
+ CodeWorkflowConfig,
+ CodeWorkstream,
+ SandboxEnvironment,
+ SandboxSnapshot,
+ Task,
+ TaskAutomation,
+ TaskRun,
+)
+from products.tasks.backend.visibility import task_run_visibility_q, task_visibility_q
+
+from . import contracts
+
+logger = logging.getLogger(__name__)
+
+# --- Enum re-exports ---
+# Value types (not ORM models), safe to expose. External callers compare against the
+# string-valued ``.status`` / ``.environment`` / ``.origin_product`` fields on the DTOs.
+TaskRunStatus = TaskRun.Status
+TaskRunEnvironment = TaskRun.Environment
+TaskOriginProduct = Task.OriginProduct
+SandboxNetworkAccessLevel = SandboxEnvironment.NetworkAccessLevel
+SandboxSnapshotStatus = SandboxSnapshot.Status
+
+# --- Code-invite redeem outcomes ---
+# Returned on ``CodeInviteRedeemResult.outcome``; the presentation layer maps each to an
+# HTTP response. ``REDEEMED`` covers both a fresh redemption and the idempotent no-op when
+# the user already redeemed this code (both surface as success).
+CODE_INVITE_REDEEMED = "redeemed"
+CODE_INVITE_INVALID_CODE = "invalid_code"
+CODE_INVITE_NOT_REDEEMABLE = "not_redeemable"
+
+# --- Code-workflow save outcomes ---
+# Returned on ``CodeWorkflowSaveResult.outcome``; the presentation layer maps each to an
+# HTTP status (saved -> 200, conflict -> 409, invalid -> 422).
+CODE_WORKFLOW_SAVED = "saved"
+CODE_WORKFLOW_CONFLICT = "conflict"
+CODE_WORKFLOW_INVALID = "invalid"
+
+# --- Code-home tuning ---
+# An agent run counts as "active" only if it updated within this window.
+CODE_HOME_ACTIVE_AGENT_WINDOW = timedelta(minutes=30)
+_CODE_HOME_RUNNING_STATUSES = (TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS)
+
+__all__ = [
+ "CODE_INVITE_INVALID_CODE",
+ "CODE_INVITE_NOT_REDEEMABLE",
+ "CODE_INVITE_REDEEMED",
+ "CODE_WORKFLOW_CONFLICT",
+ "CODE_WORKFLOW_INVALID",
+ "CODE_WORKFLOW_SAVED",
+ "SandboxNetworkAccessLevel",
+ "SandboxSnapshotStatus",
+ "TaskOriginProduct",
+ "TaskRunEnvironment",
+ "TaskRunStatus",
+ "append_task_run_log",
+ "beacon_task_presence",
+ "bootstrap_task_run",
+ "check_task_run_startable",
+ "collect_task_run_state_metrics",
+ "compute_repository_readiness",
+ "create_and_run_task",
+ "create_completed_sandbox_snapshot",
+ "create_run",
+ "create_sandbox_connection_token",
+ "create_sandbox_environment",
+ "create_task",
+ "create_task_automation",
+ "create_task_run_connection_token",
+ "claim_and_fail_stale_run",
+ "delete_sandbox_environment",
+ "delete_task_automation",
+ "fail_task_run",
+ "finalize_task_run_artifact_uploads",
+ "finalize_task_staged_artifacts",
+ "get_code_home",
+ "get_code_workflow_config",
+ "get_latest_pr_url_by_task",
+ "get_latest_run_by_task",
+ "get_sandbox_environment",
+ "get_sandbox_snapshot",
+ "get_stale_queued_task_run_ids",
+ "get_task_automation",
+ "get_task_detail",
+ "get_task_id_for_run",
+ "get_task_run",
+ "get_task_run_detail",
+ "get_task_run_sandbox_connection",
+ "get_task_run_stream_info",
+ "get_task_summaries",
+ "is_internal_debug_team",
+ "is_task_visible_to_user",
+ "is_valid_sandbox_env_var_key",
+ "latest_task_run_pr_url_subquery",
+ "leave_task_presence",
+ "list_sandbox_environments",
+ "list_task_automations",
+ "list_task_repositories",
+ "list_task_runs",
+ "list_tasks",
+ "prepare_task_run_artifact_uploads",
+ "prepare_task_staged_artifacts",
+ "presign_task_run_artifact",
+ "read_task_run_artifact",
+ "read_task_run_logs",
+ "read_task_run_session_log_content",
+ "redeem_code_invite",
+ "refresh_team_code_workstreams",
+ "relay_task_run_message",
+ "reset_code_workflow_bindings",
+ "resolve_slack_thread_context",
+ "resume_task_run_in_cloud",
+ "run_task",
+ "run_task_automation_now",
+ "save_code_workflow_bindings",
+ "send_cancel",
+ "send_user_message",
+ "set_task_run_output",
+ "signal_report_queryset",
+ "signal_task_run_user_message",
+ "signal_workflow_completion",
+ "soft_delete_task",
+ "start_task_run",
+ "task_accessible_for_run_view",
+ "task_exists",
+ "task_run_has_slack_mapping",
+ "task_run_is_terminal",
+ "task_run_pr_url_exists_subquery",
+ "task_visible",
+ "update_sandbox_environment",
+ "update_task",
+ "update_task_automation",
+ "update_task_run",
+ "update_task_run_state",
+ "upsert_internal_sandbox_env",
+ "validate_set_output",
+ "validate_task_run_artifact_ids",
+]
+
+
+# --- Mappers ---
+
+
+def _task_to_dto(task: Task) -> contracts.TaskDTO:
+ return contracts.TaskDTO(
+ id=task.id,
+ team_id=task.team_id,
+ title=task.title,
+ description=task.description,
+ origin_product=task.origin_product,
+ repository=task.repository,
+ internal=task.internal,
+ archived=task.archived,
+ created_at=task.created_at,
+ updated_at=task.updated_at,
+ created_by_id=task.created_by_id,
+ task_number=task.task_number,
+ slug=task.slug,
+ )
+
+
+def _task_run_to_dto(run: TaskRun, *, task: Task | None = None) -> contracts.TaskRunDTO:
+ """Map a TaskRun to its DTO.
+
+ Pass ``task`` (or rely on a ``select_related("task", "task__created_by")`` queryset)
+ so the denormalised parent-task fields can be populated without an extra query.
+ """
+ parent = task if task is not None else getattr(run, "task", None)
+ created_by = getattr(parent, "created_by", None) if parent is not None else None
+ return contracts.TaskRunDTO(
+ id=run.id,
+ task_id=run.task_id,
+ team_id=run.team_id,
+ status=run.status,
+ environment=run.environment,
+ stage=run.stage,
+ branch=run.branch,
+ error_message=run.error_message,
+ output=run.output,
+ state=run.state or {},
+ artifacts=run.artifacts or [],
+ created_at=run.created_at,
+ updated_at=run.updated_at,
+ completed_at=run.completed_at,
+ is_terminal=run.is_terminal,
+ workflow_id=run.workflow_id,
+ mode=run.mode,
+ task_origin_product=parent.origin_product if parent is not None else None,
+ created_by_id=parent.created_by_id if parent is not None else None,
+ created_by_distinct_id=str(created_by.distinct_id) if created_by is not None else None,
+ pr_url=(run.output or {}).get("pr_url"),
+ )
+
+
+def _hedgehog_config(user: "User") -> dict | None:
+ """Mirror core ``UserBasicSerializer.get_hedgehog_config`` so ``created_by`` output is identical."""
+ config = user.hedgehog_config
+ if not config:
+ return None
+ if config.get("version") == 2:
+ actor_options = config.get("actor_options", {})
+ return {
+ "use_as_profile": config.get("use_as_profile"),
+ "color": actor_options.get("color"),
+ "accessories": actor_options.get("accessories"),
+ "skin": actor_options.get("skin"),
+ }
+ return {
+ "use_as_profile": config.get("use_as_profile"),
+ "color": config.get("color"),
+ "accessories": config.get("accessories"),
+ "skin": config.get("skin"),
+ }
+
+
+def _user_basic_info(user: "User | None") -> contracts.TaskUserBasicInfo | None:
+ """Map a core ``User`` to the display DTO (matches ``UserBasicSerializer`` fields)."""
+ if user is None:
+ return None
+ return contracts.TaskUserBasicInfo(
+ id=user.id,
+ uuid=user.uuid,
+ distinct_id=str(user.distinct_id),
+ first_name=user.first_name,
+ last_name=user.last_name,
+ email=user.email,
+ is_email_verified=user.is_email_verified,
+ hedgehog_config=_hedgehog_config(user),
+ role_at_organization=user.role_at_organization,
+ )
+
+
+# Presigned log URLs are cached just under their 1-hour S3 expiry to avoid regeneration.
+_TASK_RUN_LOG_URL_CACHE_TTL = 55 * 60
+
+
+def _task_run_log_url(run: TaskRun) -> str | None:
+ """Presigned S3 URL for a run's log, cached. Mirrors ``TaskRunDetailSerializer.get_log_url``."""
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ from products.tasks.backend.redis import get_tasks_cache # noqa: PLC0415 — keep redis off the api import path
+
+ cache_key = f"task_run_log_url:{run.id}"
+ cached_url = get_tasks_cache().get(cache_key)
+ if cached_url:
+ return cached_url
+
+ presigned_url = object_storage.get_presigned_url(run.log_url, expiration=3600)
+ if presigned_url:
+ get_tasks_cache().set(cache_key, presigned_url, timeout=_TASK_RUN_LOG_URL_CACHE_TTL)
+ return presigned_url
+
+
+def _task_run_detail_to_dto(run: TaskRun) -> contracts.TaskRunDetailDTO:
+ """Map a ``TaskRun`` to its HTTP detail DTO.
+
+ Reproduces the SMF-derived fields ``TaskRunDetailSerializer`` computed: ``log_url`` does
+ presigned-URL I/O (with caching), and ``runtime_adapter`` / ``provider`` / ``model`` /
+ ``reasoning_effort`` are parsed off the run ``state``.
+ """
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ parse_run_state,
+ )
+
+ state = parse_run_state(run.state)
+ return contracts.TaskRunDetailDTO(
+ id=run.id,
+ task=run.task_id,
+ stage=run.stage,
+ branch=run.branch,
+ status=run.status,
+ environment=run.environment,
+ runtime_adapter=state.runtime_adapter.value if state.runtime_adapter is not None else None,
+ provider=state.provider.value if state.provider is not None else None,
+ model=state.model,
+ reasoning_effort=state.reasoning_effort.value if state.reasoning_effort is not None else None,
+ log_url=_task_run_log_url(run),
+ error_message=run.error_message,
+ output=run.output,
+ state=run.state or {},
+ artifacts=run.artifacts or [],
+ created_at=run.created_at,
+ updated_at=run.updated_at,
+ completed_at=run.completed_at,
+ )
+
+
+def _task_detail_to_dto(task: Task) -> contracts.TaskDetailDTO:
+ """Map a ``Task`` to its HTTP detail DTO.
+
+ Mirrors ``TaskSerializer`` output exactly. ``latest_run`` is the task's most-recent run
+ (by ``created_at``) mapped to a ``TaskRunDetailDTO``; pass a queryset that has
+ ``prefetch_related("runs")`` and ``select_related("created_by")`` to avoid N+1s.
+ """
+ latest_run = task.latest_run
+ return contracts.TaskDetailDTO(
+ id=task.id,
+ task_number=task.task_number,
+ slug=task.slug,
+ title=task.title,
+ title_manually_set=task.title_manually_set,
+ description=task.description,
+ origin_product=task.origin_product,
+ repository=task.repository,
+ github_integration=task.github_integration_id,
+ github_user_integration=task.github_user_integration_id,
+ signal_report=task.signal_report_id,
+ json_schema=task.json_schema,
+ internal=task.internal,
+ archived=task.archived,
+ archived_at=task.archived_at,
+ ci_prompt=task.ci_prompt,
+ latest_run=_task_run_detail_to_dto(latest_run) if latest_run is not None else None,
+ created_at=task.created_at,
+ updated_at=task.updated_at,
+ created_by=_user_basic_info(task.created_by if task.created_by_id else None),
+ )
+
+
+def _sandbox_env_to_dto(env: SandboxEnvironment) -> contracts.SandboxEnvironmentDTO:
+ return contracts.SandboxEnvironmentDTO(
+ id=env.id,
+ team_id=env.team_id,
+ name=env.name,
+ network_access_level=env.network_access_level,
+ private=env.private,
+ internal=env.internal,
+ include_default_domains=env.include_default_domains,
+ allowed_domains=list(env.allowed_domains or []),
+ repositories=list(env.repositories or []),
+ effective_domains=env.get_effective_domains(),
+ has_environment_variables=bool(env.environment_variables),
+ created_by=_user_basic_info(env.created_by if env.created_by_id else None),
+ created_at=env.created_at,
+ updated_at=env.updated_at,
+ )
+
+
+def _sandbox_snapshot_to_dto(snapshot: SandboxSnapshot) -> contracts.SandboxSnapshotDTO:
+ return contracts.SandboxSnapshotDTO(
+ id=snapshot.id,
+ external_id=snapshot.external_id,
+ status=snapshot.status,
+ repos=list(snapshot.repos or []),
+ )
+
+
+# --- Reads ---
+
+
+def get_task_run(run_id: str | UUID, team_id: int | None = None) -> contracts.TaskRunDTO | None:
+ """Fetch a single task run as a DTO, optionally scoped to a team."""
+ qs = TaskRun.objects.select_related("task", "task__created_by")
+ if team_id is not None:
+ qs = qs.filter(team_id=team_id)
+ run = qs.filter(id=run_id).first()
+ if run is None:
+ return None
+ return _task_run_to_dto(run)
+
+
+def get_task_id_for_run(run_id: str | UUID, team_id: int) -> UUID | None:
+ """The parent task id for a run, team-scoped. ``None`` if the run isn't found for the team.
+
+ A lightweight ``task_run_id -> task_id`` resolution (no DTO build) for callers that only
+ need to deep-link a run to its task.
+ """
+ return TaskRun.objects.filter(id=run_id, team_id=team_id).values_list("task_id", flat=True).first()
+
+
+def task_exists(task_id: str | UUID, team_id: int) -> bool:
+ """Whether a (non-deleted) task exists for the team."""
+ return Task.objects.filter(id=task_id, team_id=team_id).exists()
+
+
+def is_task_visible_to_user(task_id: str | UUID, user_id: int | None) -> bool:
+ """Whether the task is visible to the user under the task visibility rules.
+
+ Tasks belong to their creator, plus team-wide signal-pipeline tasks and legacy unowned
+ tasks. Used by core's file-system flow to gate delete/restore on a filed task.
+ """
+ return Task.objects.filter(task_visibility_q(user_id), pk=task_id).exists()
+
+
+def get_sandbox_snapshot(snapshot_id: str | UUID) -> contracts.SandboxSnapshotDTO | None:
+ """Fetch a sandbox snapshot as a DTO."""
+ snapshot = SandboxSnapshot.objects.filter(id=snapshot_id).first()
+ return _sandbox_snapshot_to_dto(snapshot) if snapshot is not None else None
+
+
+def get_latest_pr_url_by_task(task_ids: Iterable[str | UUID]) -> dict[str, str]:
+ """Latest non-empty ``output.pr_url`` per task, for the supplied task ids."""
+ ids = [str(t) for t in task_ids]
+ if not ids:
+ return {}
+ rows = (
+ TaskRun.objects.filter(task_id__in=ids, output__pr_url__isnull=False)
+ .exclude(output__pr_url="")
+ .order_by("task_id", "-created_at", "-id")
+ .annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
+ .values("task_id", "output_pr_url_text")
+ .distinct("task_id")
+ )
+ return {str(row["task_id"]): row["output_pr_url_text"] for row in rows if row["output_pr_url_text"]}
+
+
+def task_run_pr_url_exists_subquery(**task_run_filter) -> Exists:
+ """``Exists`` over runs matching ``task_run_filter`` that produced a non-empty output.pr_url.
+
+ The caller supplies the correlation filter (e.g. ``task__signal_report_tasks__report_id=
+ OuterRef("id")`` plus its own relationship value). Returns a query expression to embed in
+ the caller's queryset — no ORM instances cross the boundary, and the tasks facade stays
+ free of the caller's domain.
+ """
+ return Exists(TaskRun.objects.filter(**task_run_filter, output__pr_url__isnull=False).exclude(output__pr_url=""))
+
+
+def latest_task_run_pr_url_subquery(**task_run_filter) -> Subquery:
+ """``Subquery`` of the latest non-empty output.pr_url for runs matching ``task_run_filter``."""
+ return Subquery(
+ TaskRun.objects.filter(**task_run_filter, output__pr_url__isnull=False)
+ .exclude(output__pr_url="")
+ .order_by("-created_at")
+ .annotate(output_pr_url_text=KeyTextTransform("pr_url", "output"))
+ .values("output_pr_url_text")[:1],
+ output_field=CharField(),
+ )
+
+
+def get_latest_run_by_task(task_ids: Iterable[str | UUID]) -> dict[str, contracts.TaskRunDTO]:
+ """Most-recent run per task (by ``created_at`` then ``id``), for the supplied task ids."""
+ ids = [str(t) for t in task_ids]
+ if not ids:
+ return {}
+ runs = (
+ TaskRun.objects.filter(task_id__in=ids)
+ .select_related("task", "task__created_by")
+ .order_by("task_id", "-created_at", "-id")
+ .distinct("task_id")
+ )
+ return {str(run.task_id): _task_run_to_dto(run) for run in runs}
+
+
+def get_stale_queued_task_run_ids(older_than: timedelta, limit: int) -> list[UUID]:
+ """Ids of runs stuck in QUEUED with ``updated_at`` older than the cutoff.
+
+ Intentionally cross-team — the janitor sweep runs without a team context.
+ """
+ cutoff = django_timezone.now() - older_than
+ return list(
+ TaskRun.objects.filter( # nosemgrep: celery-task-team-scope-audit
+ status=TaskRun.Status.QUEUED, updated_at__lt=cutoff
+ )
+ .order_by("updated_at")
+ .values_list("id", flat=True)[:limit]
+ )
+
+
+def _gauge_rows(values_qs, value_key: str, *, with_status: bool, now=None) -> list[contracts.TaskRunGaugeRow]:
+ rows = []
+ for row in values_qs:
+ raw = row[value_key]
+ value = (now - raw).total_seconds() if now is not None else raw
+ rows.append(
+ contracts.TaskRunGaugeRow(
+ environment=row["environment"],
+ origin_product=row["task__origin_product"] or "unknown",
+ value=value,
+ status=row["status"] if with_status else None,
+ )
+ )
+ return rows
+
+
+def collect_task_run_state_metrics(
+ *,
+ open_statuses: Sequence[str],
+ age_statuses: Sequence[str],
+ terminal_statuses: Sequence[str],
+ window_seconds: int,
+) -> contracts.TaskRunStateMetricsDTO:
+ """Aggregate TaskRun state for monitoring gauges.
+
+ The caller (a core celery task) owns which statuses count as open/age/terminal and the
+ recency window; this returns the raw numbers grouped by (status, environment,
+ parent origin_product) so no ORM leaks across the boundary.
+ """
+ now = django_timezone.now()
+ window_start = now - timedelta(seconds=window_seconds)
+ return contracts.TaskRunStateMetricsDTO(
+ runs_in_status=_gauge_rows(
+ TaskRun.objects.filter(status__in=open_statuses)
+ .values("status", "environment", "task__origin_product")
+ .annotate(count=Count("id")),
+ "count",
+ with_status=True,
+ ),
+ oldest_open_age_seconds=_gauge_rows(
+ TaskRun.objects.filter(status__in=age_statuses)
+ .values("status", "environment", "task__origin_product")
+ .annotate(oldest_created_at=Min("created_at")),
+ "oldest_created_at",
+ with_status=True,
+ now=now,
+ ),
+ created_recently=_gauge_rows(
+ TaskRun.objects.filter(created_at__gte=window_start)
+ .values("environment", "task__origin_product")
+ .annotate(count=Count("id")),
+ "count",
+ with_status=False,
+ ),
+ terminal_recently=_gauge_rows(
+ TaskRun.objects.filter(status__in=terminal_statuses, updated_at__gte=window_start)
+ .values("status", "environment", "task__origin_product")
+ .annotate(count=Count("id")),
+ "count",
+ with_status=True,
+ ),
+ )
+
+
+# --- Writes ---
+
+
+def create_and_run_task(
+ *,
+ team,
+ title: str,
+ description: str,
+ origin_product: "Task.OriginProduct",
+ user_id: int,
+ repository: str | None = None,
+ create_pr: bool = True,
+ mode: str = "background",
+ start_workflow: bool = True,
+ branch: str | None = None,
+ signal_report_id: str | None = None,
+ internal: bool = False,
+ sandbox_environment_id: str | None = None,
+ **extra,
+) -> contracts.CreatedTaskDTO:
+ """Create a task and (optionally) kick off its processing workflow.
+
+ Thin wrapper over ``Task.create_and_run`` that returns ids + the created run as a DTO
+ instead of leaking the ORM ``Task``. ``team`` is a core ``posthog.Team`` (not a tasks
+ model). Less-common keyword arguments are forwarded verbatim via ``**extra``.
+ """
+ task = Task.create_and_run(
+ team=team,
+ title=title,
+ description=description,
+ origin_product=origin_product,
+ user_id=user_id,
+ repository=repository,
+ create_pr=create_pr,
+ mode=mode,
+ start_workflow=start_workflow,
+ branch=branch,
+ signal_report_id=signal_report_id,
+ internal=internal,
+ sandbox_environment_id=sandbox_environment_id,
+ **extra,
+ )
+ latest = task.latest_run
+ return contracts.CreatedTaskDTO(
+ task_id=task.id,
+ team_id=task.team_id,
+ latest_run=_task_run_to_dto(latest, task=task) if latest is not None else None,
+ )
+
+
+def create_run(
+ task_id: str | UUID,
+ *,
+ mode: str = "background",
+ extra_state: dict | None = None,
+ branch: str | None = None,
+) -> contracts.TaskRunDTO:
+ """Create a new run for an existing task (e.g. resuming an interactive sandbox session)."""
+ task = Task.objects.get(id=task_id)
+ run = task.create_run(mode=mode, extra_state=extra_state, branch=branch)
+ return _task_run_to_dto(run, task=task)
+
+
+def update_task_run_state(
+ run_id: str | UUID,
+ *,
+ updates: dict | None = None,
+ remove_keys: Iterable[str] | None = None,
+) -> dict:
+ """Atomically merge state updates into a run's ``state`` and return the new state."""
+ return TaskRun.update_state_atomic(run_id, updates=updates, remove_keys=remove_keys)
+
+
+def fail_task_run(run_id: str | UUID, error: str) -> bool:
+ """Mark a QUEUED run as failed. Returns whether a run was acted on.
+
+ Refetches filtered on ``status=QUEUED`` so a run that left the queue between the
+ candidate scan and this call is skipped. Intentionally cross-team (janitor sweep).
+ """
+ run = TaskRun.objects.filter(
+ pk=run_id, status=TaskRun.Status.QUEUED
+ ).first() # nosemgrep: celery-task-team-scope-audit
+ if run is None:
+ return False
+ run.mark_failed(error)
+ return True
+
+
+def claim_and_fail_stale_run(run_id: str | UUID, error: str) -> bool:
+ """Compare-and-set reap of a stranded run. Returns whether this caller won the claim.
+
+ Atomically flips a run still in ``QUEUED``/``IN_PROGRESS`` to ``FAILED`` via a conditional
+ update, so concurrent reapers of the same row resolve to exactly one winner (the losers match
+ zero rows). The winner finalizes via ``mark_failed`` (error message, ``completed_at``, stream +
+ analytics). Intentionally cross-team (janitor sweep).
+ """
+ claimed = TaskRun.objects.filter(
+ id=run_id,
+ status__in=(TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS),
+ ).update(status=TaskRun.Status.FAILED) # nosemgrep: celery-task-team-scope-audit
+ if not claimed:
+ return False
+ run = TaskRun.objects.filter(pk=run_id).first() # nosemgrep: celery-task-team-scope-audit
+ if run is not None:
+ run.mark_failed(error)
+ return True
+
+
+def upsert_internal_sandbox_env(
+ team_id: int,
+ name: str,
+ network_access_level: "SandboxEnvironment.NetworkAccessLevel",
+ *,
+ private: bool = False,
+ internal: bool = True,
+ allowed_domains: list[str] | None = None,
+ include_default_domains: bool = False,
+) -> UUID:
+ """Get-or-create an internal sandbox environment, reasserting policy on every call.
+
+ ``SandboxEnvironment`` has no unique constraint on ``(team_id, name)``, so concurrent
+ callers can both INSERT. We dedupe on ``MultipleObjectsReturned`` by keeping the oldest
+ row and deleting the rest.
+ """
+ defaults: dict = {
+ "network_access_level": network_access_level,
+ "private": private,
+ "internal": internal,
+ }
+ if allowed_domains is not None:
+ defaults["allowed_domains"] = allowed_domains
+ defaults["include_default_domains"] = include_default_domains
+ try:
+ env, _ = SandboxEnvironment.objects.update_or_create(team_id=team_id, name=name, defaults=defaults)
+ return env.id
+ except SandboxEnvironment.MultipleObjectsReturned:
+ with transaction.atomic():
+ dupes = list(SandboxEnvironment.objects.filter(team_id=team_id, name=name).order_by("created_at"))
+ keeper = dupes[0]
+ SandboxEnvironment.objects.filter(id__in=[d.id for d in dupes[1:]]).delete()
+ for key, value in defaults.items():
+ setattr(keeper, key, value)
+ keeper.save(update_fields=list(defaults.keys()))
+ return keeper.id
+
+
+def create_completed_sandbox_snapshot(external_id: str) -> UUID:
+ """Record a completed sandbox snapshot for an externally-built image; return its id."""
+ snapshot = SandboxSnapshot.objects.create(external_id=external_id, status=SandboxSnapshot.Status.COMPLETE)
+ return snapshot.id
+
+
+# --- Code invites ---
+
+
+def redeem_code_invite(code: str, user_id: int) -> contracts.CodeInviteRedeemResult:
+ """Redeem a PostHog Code invite for a user.
+
+ Idempotent: a user who already redeemed this code gets ``REDEEMED`` without a second
+ redemption row. A fresh redemption takes a row lock on the invite, re-checks
+ redeemability under the lock, records the redemption, bumps ``redemption_count``, and
+ captures the activation analytics — all in one transaction, mirroring the original view.
+ """
+ code_str = code.strip()
+
+ try:
+ invite_code = CodeInvite.objects.get(code__iexact=code_str)
+ except CodeInvite.DoesNotExist:
+ return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_INVALID_CODE)
+
+ user = User.objects.get(pk=user_id)
+
+ if CodeInviteRedemption.objects.filter(invite_code=invite_code, user=user).exists():
+ return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_REDEEMED)
+
+ with transaction.atomic():
+ invite_code = CodeInvite.objects.select_for_update().get(id=invite_code.id)
+
+ if not invite_code.is_redeemable:
+ return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_NOT_REDEEMABLE)
+
+ organization = user.organization if hasattr(user, "organization") else None
+
+ CodeInviteRedemption.objects.create(
+ invite_code=invite_code,
+ user=user,
+ organization=organization,
+ )
+
+ CodeInvite.objects.filter(id=invite_code.id).update(redemption_count=F("redemption_count") + 1)
+
+ posthoganalytics.capture(
+ distinct_id=str(user.distinct_id),
+ event="code_invite_redeemed",
+ groups=groups(organization=organization),
+ )
+
+ return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_REDEEMED)
+
+
+# --- Sandbox environments (presentation CRUD) ---
+# Visibility: an environment is reachable by a team member if it is non-private, or it is
+# theirs (``created_by``). ``list`` additionally hides ``internal`` environments.
+
+
+def is_valid_sandbox_env_var_key(key: str) -> bool:
+ """Whether ``key`` is a valid environment-variable name (``[A-Za-z_][A-Za-z0-9_]*``)."""
+ return SandboxEnvironment.is_valid_env_var_key(key)
+
+
+def _accessible_sandbox_envs(team_id: int, user_id: int):
+ return (
+ SandboxEnvironment.objects.filter(team_id=team_id)
+ .filter(Q(private=False) | Q(created_by_id=user_id))
+ .select_related("created_by")
+ )
+
+
+def list_sandbox_environments(team_id: int, user_id: int) -> list[contracts.SandboxEnvironmentDTO]:
+ """Non-internal environments visible to the user, for the list view."""
+ return [_sandbox_env_to_dto(env) for env in _accessible_sandbox_envs(team_id, user_id).filter(internal=False)]
+
+
+def get_sandbox_environment(env_id: str | UUID, team_id: int, user_id: int) -> contracts.SandboxEnvironmentDTO | None:
+ """A single environment visible to the user (internal ones are retrievable by id)."""
+ env = _accessible_sandbox_envs(team_id, user_id).filter(pk=env_id).first()
+ return _sandbox_env_to_dto(env) if env is not None else None
+
+
+def create_sandbox_environment(
+ team_id: int,
+ user_id: int,
+ *,
+ name: str,
+ network_access_level: str,
+ allowed_domains: list[str],
+ include_default_domains: bool,
+ repositories: list[str],
+ environment_variables: dict,
+ private: bool,
+) -> contracts.SandboxEnvironmentDTO:
+ """Create a team environment owned by the user and return it as a DTO."""
+ env = SandboxEnvironment.objects.create(
+ team_id=team_id,
+ created_by_id=user_id,
+ name=name,
+ network_access_level=network_access_level,
+ allowed_domains=allowed_domains,
+ include_default_domains=include_default_domains,
+ repositories=repositories,
+ environment_variables=environment_variables,
+ private=private,
+ )
+ return _sandbox_env_to_dto(SandboxEnvironment.objects.select_related("created_by").get(pk=env.pk))
+
+
+def update_sandbox_environment(
+ env_id: str | UUID, team_id: int, user_id: int, **fields
+) -> contracts.SandboxEnvironmentDTO | None:
+ """Partially update a visible environment. Returns ``None`` if not found/visible."""
+ env = _accessible_sandbox_envs(team_id, user_id).filter(pk=env_id).first()
+ if env is None:
+ return None
+ for key, value in fields.items():
+ setattr(env, key, value)
+ env.save()
+ return _sandbox_env_to_dto(SandboxEnvironment.objects.select_related("created_by").get(pk=env.pk))
+
+
+def delete_sandbox_environment(env_id: str | UUID, team_id: int, user_id: int) -> bool:
+ """Delete a visible environment. Returns whether a row was deleted."""
+ env = _accessible_sandbox_envs(team_id, user_id).filter(pk=env_id).first()
+ if env is None:
+ return False
+ env.delete()
+ return True
+
+
+# --- Task automations (presentation CRUD) ---
+# Visibility mirrors the task-run visibility filter traversed via the automation's ``task`` FK
+# (creator, legacy unowned tasks, and signals-pipeline tasks). Most read fields proxy off the
+# linked ``Task``; the schedule (Temporal) is kept in sync from inside the write functions.
+
+
+def _task_automation_to_dto(automation: TaskAutomation) -> contracts.TaskAutomationDTO:
+ return contracts.TaskAutomationDTO(
+ id=automation.id,
+ name=automation.name,
+ prompt=automation.prompt,
+ repository=automation.repository,
+ github_integration=automation.github_integration_id,
+ cron_expression=automation.cron_expression,
+ timezone=automation.timezone,
+ template_id=automation.template_id,
+ enabled=automation.enabled,
+ last_run_at=automation.last_run_at,
+ last_run_status=automation.last_run_status,
+ last_task_id=str(automation.task_id),
+ last_task_run_id=str(automation.last_task_run_id) if automation.last_task_run_id else None,
+ last_error=automation.last_error,
+ created_at=automation.created_at,
+ updated_at=automation.updated_at,
+ )
+
+
+def _visible_task_automations(team_id: int, user_id: int | None):
+ return TaskAutomation.objects.filter(task__team_id=team_id).filter(task_run_visibility_q(user_id))
+
+
+def list_task_automations(team_id: int, user_id: int | None) -> list[contracts.TaskAutomationDTO]:
+ """Automations for the team visible to the user, ordered by task title then newest first."""
+ automations = _visible_task_automations(team_id, user_id).order_by("task__title", "-created_at")
+ return [_task_automation_to_dto(automation) for automation in automations]
+
+
+def get_task_automation(
+ automation_id: str | UUID, team_id: int, user_id: int | None
+) -> contracts.TaskAutomationDTO | None:
+ """A single automation visible to the user. Returns ``None`` if not found/visible."""
+ automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
+ return _task_automation_to_dto(automation) if automation is not None else None
+
+
+def create_task_automation(
+ team_id: int,
+ user_id: int | None,
+ *,
+ name: str,
+ prompt: str,
+ repository: str,
+ github_integration_id: int | None = None,
+ cron_expression: str,
+ timezone: str = "UTC",
+ template_id: str | None = None,
+ enabled: bool = True,
+) -> contracts.TaskAutomationDTO:
+ """Create an automation (and its backing task) and sync its Temporal schedule.
+
+ Falls back to the team's default GitHub integration when none is supplied, mirroring the
+ original serializer behavior.
+ """
+ if github_integration_id is None:
+ default_integration = Integration.objects.filter(team_id=team_id, kind="github").first()
+ github_integration_id = default_integration.id if default_integration else None
+
+ with transaction.atomic():
+ task = Task.objects.create(
+ team_id=team_id,
+ created_by_id=user_id,
+ title=name,
+ description=prompt,
+ origin_product=Task.OriginProduct.AUTOMATION,
+ repository=repository,
+ github_integration_id=github_integration_id,
+ )
+ automation = TaskAutomation.objects.create(
+ task=task,
+ cron_expression=cron_expression,
+ timezone=timezone,
+ template_id=template_id,
+ enabled=enabled,
+ )
+
+ _sync_automation_schedule(automation)
+ return _task_automation_to_dto(automation)
+
+
+def update_task_automation(
+ automation_id: str | UUID, team_id: int, user_id: int | None, **fields
+) -> contracts.TaskAutomationDTO | None:
+ """Partially update a visible automation (and its backing task) and re-sync its schedule.
+
+ Returns ``None`` if the automation is not found/visible. The ``github_integration_id``
+ key (when present) updates the backing task's GitHub integration.
+ """
+ automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
+ if automation is None:
+ return None
+
+ task_field_map = {
+ "name": "title",
+ "prompt": "description",
+ "repository": "repository",
+ "github_integration_id": "github_integration_id",
+ }
+ task_updates = {task_field_map[key]: fields.pop(key) for key in list(fields) if key in task_field_map}
+
+ with transaction.atomic():
+ for key, value in fields.items():
+ setattr(automation, key, value)
+ automation.save()
+
+ if task_updates:
+ task = automation.task
+ fields_to_update = []
+ for field, value in task_updates.items():
+ if getattr(task, field) != value:
+ setattr(task, field, value)
+ fields_to_update.append(field)
+ if fields_to_update:
+ fields_to_update.append("updated_at")
+ task.save(update_fields=fields_to_update)
+
+ _sync_automation_schedule(automation)
+ return _task_automation_to_dto(automation)
+
+
+def delete_task_automation(automation_id: str | UUID, team_id: int, user_id: int | None) -> bool:
+ """Delete a visible automation and its Temporal schedule. Returns whether a row was deleted."""
+ automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
+ if automation is None:
+ return False
+
+ from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
+ delete_automation_schedule,
+ )
+
+ delete_automation_schedule(automation)
+ automation.delete()
+ return True
+
+
+def run_task_automation_now(
+ automation_id: str | UUID, team_id: int, user_id: int | None
+) -> contracts.TaskAutomationDTO | None:
+ """Trigger an automation run immediately and return the refreshed automation DTO.
+
+ Returns ``None`` if the automation is not found/visible.
+ """
+ automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
+ if automation is None:
+ return None
+
+ from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
+ run_task_automation,
+ )
+
+ run_task_automation(str(automation.id))
+ automation.refresh_from_db()
+ return _task_automation_to_dto(automation)
+
+
+def _sync_automation_schedule(automation: TaskAutomation) -> None:
+ from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
+ sync_automation_schedule,
+ )
+
+ sync_automation_schedule(automation)
+
+
+# --- Task runs (presentation lifecycle) ---
+# Every function takes ids/primitives and returns a TaskRunDetailDTO (or a small result),
+# moving all ORM access and Temporal/Slack/S3 orchestration behind the facade. Visibility on
+# the parent task is enforced via ``task_visibility_q``; runs are always team-scoped.
+
+# Run-state keys that are server-owned and must never be mutable through the PATCH endpoint:
+# - github_credential_source / pr_authorship_mode fix the run's GitHub identity at creation;
+# a caller could otherwise flip a caller-token run to ``server_integration`` and have the
+# task creator's server-side token injected into their sandbox.
+# - sandbox_id is the credential-propagation target; a caller could otherwise repoint a visible
+# run at a sandbox they control and capture the run owner's token on the next rotation.
+# - sandbox_cpu_cores / sandbox_memory_gb / sandbox_ttl_seconds / inactivity_timeout_seconds set
+# the run's compute and lifetime at creation; a caller could otherwise PATCH a queued run to
+# provision an oversized or long-lived sandbox beyond what they're entitled to.
+# All are written only server-side (run creation + the temporal workflow), never via PATCH.
+_PROTECTED_RUN_STATE_KEYS = frozenset(
+ {
+ "github_credential_source",
+ "pr_authorship_mode",
+ "sandbox_id",
+ "sandbox_cpu_cores",
+ "sandbox_memory_gb",
+ "sandbox_ttl_seconds",
+ "inactivity_timeout_seconds",
+ }
+)
+
+_TERMINAL_TASK_RUN_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)
+
+
+def _task_run_queryset():
+ return TaskRun.objects.select_related(
+ "task", "task__created_by", "task__github_integration", "task__github_user_integration"
+ )
+
+
+def _get_task_for_run_visibility(task_id: str | UUID, team_id: int, user_id: int | None) -> Task | None:
+ return Task.objects.filter(id=task_id, team_id=team_id).filter(task_visibility_q(user_id)).first()
+
+
+def _get_visible_run(run_id: str | UUID, task_id: str | UUID, team_id: int) -> TaskRun | None:
+ """A run scoped to its parent task + team. Caller is responsible for task visibility."""
+ return _task_run_queryset().filter(pk=run_id, team_id=team_id, task_id=task_id).first()
+
+
+def task_accessible_for_run_view(
+ task_id: str | UUID, team_id: int, user_id: int | None, *, bypass_visibility: bool = False
+) -> bool:
+ """Whether the parent task exists and (unless bypassed) is visible to the user.
+
+ Mirrors the parent-task gate in ``TaskRunViewSet.safely_get_queryset``: runs are always scoped
+ to a task, and access to that task is gated by ``task_visibility_q`` except for internal-debug
+ read actions, which the caller signals via ``bypass_visibility``.
+ """
+ task_filter = Task.objects.filter(id=task_id, team_id=team_id)
+ if not bypass_visibility:
+ task_filter = task_filter.filter(task_visibility_q(user_id))
+ return task_filter.exists()
+
+
+def list_task_runs(task_id: str | UUID, team_id: int) -> list[contracts.TaskRunDetailDTO]:
+ """All runs for a task, team-scoped. Caller enforces task visibility."""
+ runs = _task_run_queryset().filter(team_id=team_id, task_id=task_id)
+ return [_task_run_detail_to_dto(run) for run in runs]
+
+
+def get_task_run_detail(run_id: str | UUID, task_id: str | UUID, team_id: int) -> contracts.TaskRunDetailDTO | None:
+ """A single run as a detail DTO, scoped to its task + team."""
+ run = _get_visible_run(run_id, task_id, team_id)
+ return _task_run_detail_to_dto(run) if run is not None else None
+
+
+def get_task_run_stream_info(
+ run_id: str | UUID, task_id: str | UUID, team_id: int
+) -> contracts.TaskRunStreamInfoDTO | None:
+ """The minimal run facts the SSE stream view needs. ``None`` if the run isn't found."""
+ from products.tasks.backend.metrics import ( # noqa: PLC0415 — keep prometheus deps off the api import path
+ origin_product_label,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ return contracts.TaskRunStreamInfoDTO(
+ id=run.id,
+ state=run.state or {},
+ origin_product=origin_product_label(run),
+ )
+
+
+def signal_workflow_completion(run_id: str | UUID, status: str, error_message: str | None) -> None:
+ """Send a completion signal to a run's Temporal workflow (best-effort)."""
+ import asyncio # noqa: PLC0415 — only needed when signalling
+
+ from posthog.temporal.common.client import sync_connect # noqa: PLC0415 — keep temporalio off the api import path
+
+ from products.tasks.backend.temporal.process_task.workflow import ( # noqa: PLC0415 — keep temporalio off the api import path
+ ProcessTaskWorkflow,
+ )
+
+ run = TaskRun.objects.filter(pk=run_id).first()
+ if run is None:
+ return
+ try:
+ client = sync_connect()
+ handle = client.get_workflow_handle(run.workflow_id)
+ asyncio.run(handle.signal(ProcessTaskWorkflow.complete_task, args=[status, error_message]))
+ logger.info("Signaled workflow completion for task run %s with status %s", run.id, status)
+ except Exception as e:
+ logger.warning("Failed to signal workflow completion for task run %s: %s", run.id, e)
+
+
+def _post_slack_update_for_pr(run: TaskRun) -> None:
+ pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else None
+ if not pr_url:
+ return
+
+ from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
+ SlackThreadTaskMapping,
+ )
+ from products.tasks.backend.temporal.process_task.activities.post_slack_update import ( # noqa: PLC0415 — keep temporalio off the api import path
+ PostSlackUpdateInput,
+ post_slack_update,
+ )
+
+ try:
+ mapping = (
+ SlackThreadTaskMapping.objects.filter(task_run=run)
+ .order_by("-updated_at")
+ .values("integration_id", "channel", "thread_ts", "mentioning_slack_user_id")
+ .first()
+ )
+ if not mapping:
+ return
+ post_slack_update(
+ PostSlackUpdateInput(
+ run_id=str(run.id),
+ slack_thread_context={
+ "integration_id": mapping["integration_id"],
+ "channel": mapping["channel"],
+ "thread_ts": mapping["thread_ts"],
+ "mentioning_slack_user_id": mapping["mentioning_slack_user_id"],
+ },
+ )
+ )
+ except Exception:
+ logger.exception("task_run_slack_update_for_pr_failed for run %s", run.id)
+
+
+def update_task_run(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, validated_data: dict
+) -> contracts.TaskRunDetailDTO | None:
+ """Apply a PATCH to a run: merge output/state, set completion, then dispatch side effects.
+
+ Mirrors ``TaskRunViewSet.partial_update`` byte-for-byte: protected state keys are stripped,
+ output/state merges take a row lock, terminal transitions signal Temporal + dispatch
+ push/Slack updates after commit, and a cloud→local transition cancels the workflow.
+ """
+ from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
+ update_automation_run_result,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+
+ validated_data = dict(validated_data)
+ has_output_merge = "output" in validated_data and isinstance(validated_data["output"], dict)
+ has_state_merge = "state" in validated_data and isinstance(validated_data["state"], dict)
+ if has_state_merge:
+ validated_data["state"] = {
+ k: v for k, v in validated_data["state"].items() if k not in _PROTECTED_RUN_STATE_KEYS
+ }
+ state_remove_keys = [
+ k for k in (validated_data.get("state_remove_keys") or []) if k not in _PROTECTED_RUN_STATE_KEYS
+ ]
+ has_state_mutation = has_state_merge or bool(state_remove_keys)
+ update_fields: set[str] = set()
+
+ with transaction.atomic():
+ if has_output_merge or has_state_mutation:
+ run = TaskRun.objects.select_for_update().get(pk=run.pk)
+
+ old_status = run.status
+ old_environment = run.environment
+ old_pr_url = (run.output or {}).get("pr_url") if isinstance(run.output, dict) else None
+
+ for key, value in validated_data.items():
+ if key == "output" and isinstance(value, dict):
+ existing_output = run.output if isinstance(run.output, dict) else {}
+ setattr(run, key, {**existing_output, **value})
+ update_fields.add(key)
+ continue
+ if key == "state_remove_keys":
+ continue
+ if key == "state" and has_state_merge:
+ existing_state = run.state if isinstance(run.state, dict) else {}
+ next_state = dict(existing_state)
+ for remove_key in state_remove_keys:
+ next_state.pop(remove_key, None)
+ next_state.update(value)
+ setattr(run, key, next_state)
+ update_fields.add(key)
+ continue
+ setattr(run, key, value)
+ update_fields.add(key)
+
+ if state_remove_keys and not has_state_merge:
+ existing_state = run.state if isinstance(run.state, dict) else {}
+ next_state = dict(existing_state)
+ for remove_key in state_remove_keys:
+ next_state.pop(remove_key, None)
+ run.state = next_state
+ update_fields.add("state")
+
+ new_status = validated_data.get("status")
+ if new_status in _TERMINAL_TASK_RUN_STATUSES:
+ if not run.completed_at:
+ run.completed_at = django_timezone.now()
+ update_fields.add("completed_at")
+
+ update_fields.add("updated_at")
+ run.save(update_fields=list(update_fields))
+ run.publish_stream_state_event()
+
+ update_automation_run_result(run)
+
+ if new_status in _TERMINAL_TASK_RUN_STATUSES and old_status != new_status:
+ signal_workflow_completion(run.id, new_status, validated_data.get("error_message"))
+ if new_status == TaskRun.Status.CANCELLED:
+ from products.tasks.backend.push_dispatcher import ( # noqa: PLC0415 — keep push deps off the api import path
+ notify_task_run_cancelled,
+ )
+
+ 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 None
+ if new_pr_url and new_pr_url != old_pr_url:
+ _post_slack_update_for_pr(run)
+
+ return _task_run_detail_to_dto(run)
+
+
+def validate_set_output(run_id: str | UUID, task_id: str | UUID, team_id: int, *, output: dict) -> str | None:
+ """Validate output against the task's json_schema. Returns an error message or ``None``."""
+ import jsonschema # noqa: PLC0415 — only needed when a json_schema is set
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ task = run.task
+ if task.json_schema:
+ try:
+ jsonschema.validate(instance=output, schema=task.json_schema)
+ except jsonschema.ValidationError as e:
+ return f"Output validation error: {e.message}"
+ return None
+
+
+def set_task_run_output(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, output: dict
+) -> contracts.TaskRunDetailDTO | None:
+ """Persist a run's output. Completes the run for structured-output tasks; posts Slack PR update."""
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ task = run.task
+ run.output = output
+ run.save(update_fields=["output", "updated_at"])
+ if task.json_schema:
+ signal_workflow_completion(run.id, TaskRun.Status.COMPLETED, None)
+ run.publish_stream_state_event()
+ _post_slack_update_for_pr(run)
+ return _task_run_detail_to_dto(run)
+
+
+def append_task_run_log(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, entries: list[dict]
+) -> contracts.TaskRunDetailDTO | None:
+ """Append log entries to a run's S3 log and heartbeat its workflow."""
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ run.append_log(entries)
+ run.heartbeat_workflow(agent_active=True)
+ return _task_run_detail_to_dto(run)
+
+
+def task_run_has_slack_mapping(run_id: str | UUID, task_id: str | UUID, team_id: int) -> bool | None:
+ """Whether a run is mapped to a Slack thread. ``None`` if the run isn't found."""
+ from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
+ SlackThreadTaskMapping,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ return SlackThreadTaskMapping.objects.filter(task_run=run).exists()
+
+
+def task_run_is_terminal(run_id: str | UUID, task_id: str | UUID, team_id: int) -> bool | None:
+ """Whether a run is in a terminal state. ``None`` if the run isn't found."""
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ return run.is_terminal
+
+
+# --- Task run artifacts (S3 + manifest) ---
+
+
+def _build_artifact_storage_path(run: TaskRun, artifact_id: str, name: str) -> tuple[str, str]:
+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path
+ get_safe_artifact_name,
+ )
+
+ safe_name = get_safe_artifact_name(name)
+ prefix = run.get_artifact_s3_prefix()
+ return safe_name, f"{prefix}/{artifact_id[:8]}_{safe_name}"
+
+
+def _tag_artifact_object(run: TaskRun, storage_path: str) -> None:
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ try:
+ object_storage.tag(storage_path, {"ttl_days": "30", "team_id": str(run.team_id)})
+ except Exception as exc:
+ logger.warning(
+ "task_run.artifact_tag_failed",
+ extra={"task_run_id": str(run.id), "storage_path": storage_path, "error": str(exc)},
+ )
+
+
+def _build_artifact_manifest_entry(
+ *,
+ artifact_id: str,
+ name: str,
+ artifact_type: str,
+ source: str,
+ size: int,
+ content_type: str,
+ storage_path: str,
+ uploaded_at: str,
+) -> dict[str, str | int]:
+ return {
+ "id": artifact_id,
+ "name": name,
+ "type": artifact_type,
+ "source": source,
+ "size": size,
+ "content_type": content_type,
+ "storage_path": storage_path,
+ "uploaded_at": uploaded_at,
+ }
+
+
+def _find_artifact_manifest_entry(manifest: list[dict], artifact_id: str, storage_path: str) -> dict | None:
+ return next(
+ (e for e in manifest if e.get("id") == artifact_id or e.get("storage_path") == storage_path),
+ None,
+ )
+
+
+def _save_artifact_manifest(run: TaskRun, manifest: list[dict]) -> None:
+ run.artifacts = manifest
+ run.save(update_fields=["artifacts", "updated_at"])
+
+
+def upload_task_run_artifacts(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifacts: list[dict]
+) -> list[dict] | None:
+ """Write artifact bytes to S3 and append them to the run manifest. Returns the full manifest."""
+ import uuid as uuid_module # noqa: PLC0415
+
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+
+ uploaded: list[dict] = []
+ for artifact in artifacts:
+ artifact_id = uuid_module.uuid4().hex
+ safe_name, storage_path = _build_artifact_storage_path(run, artifact_id, artifact["name"])
+
+ content_bytes = artifact["content_bytes"]
+ extras: dict[str, str] = {}
+ content_type = artifact.get("content_type")
+ if content_type:
+ extras["ContentType"] = content_type
+
+ object_storage.write(storage_path, content_bytes, extras or None)
+ _tag_artifact_object(run, storage_path)
+
+ uploaded.append(
+ _build_artifact_manifest_entry(
+ artifact_id=artifact_id,
+ name=safe_name,
+ artifact_type=artifact["type"],
+ source=artifact.get("source") or "",
+ size=len(content_bytes),
+ content_type=content_type or "",
+ storage_path=storage_path,
+ uploaded_at=django_timezone.now().isoformat(),
+ )
+ )
+ logger.info(
+ "task_run.artifact_uploaded",
+ extra={
+ "task_run_id": str(run.id),
+ "storage_path": storage_path,
+ "artifact_type": artifact["type"],
+ "size": len(content_bytes),
+ },
+ )
+
+ with transaction.atomic():
+ run = TaskRun.objects.select_for_update().get(pk=run.pk)
+ manifest = list(run.artifacts or [])
+ manifest.extend(uploaded)
+ _save_artifact_manifest(run, manifest)
+
+ return manifest
+
+
+def prepare_task_run_artifact_uploads(
+ run_id: str | UUID,
+ task_id: str | UUID,
+ team_id: int,
+ *,
+ artifacts: list[dict],
+ upload_expiration_seconds: int,
+ form_overhead_bytes: int,
+) -> tuple[list[dict] | None, bool]:
+ """Reserve S3 keys and presigned POST forms for direct artifact uploads.
+
+ Returns ``(prepared, ok)``: ``(None, _)`` when the run isn't found, ``(None, False)`` when a
+ presigned POST could not be generated, else ``(prepared, True)``.
+ """
+ import uuid as uuid_module # noqa: PLC0415
+
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None, True
+
+ prepared: list[dict] = []
+ for artifact in artifacts:
+ artifact_id = uuid_module.uuid4().hex
+ safe_name, storage_path = _build_artifact_storage_path(run, artifact_id, artifact["name"])
+ content_type = artifact.get("content_type") or ""
+ conditions: list[list[str | int]] = [["content-length-range", 0, artifact["size"] + form_overhead_bytes]]
+
+ presigned_post = object_storage.get_presigned_post(
+ storage_path, conditions=conditions, expiration=upload_expiration_seconds
+ )
+ if not presigned_post:
+ return None, False
+
+ prepared.append(
+ {
+ "id": artifact_id,
+ "name": safe_name,
+ "type": artifact["type"],
+ "source": artifact.get("source") or "",
+ "size": artifact["size"],
+ "content_type": content_type,
+ "storage_path": storage_path,
+ "expires_in": upload_expiration_seconds,
+ "presigned_post": presigned_post,
+ }
+ )
+ return prepared, True
+
+
+def finalize_task_run_artifact_uploads(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifacts: list[dict]
+) -> tuple[list[dict] | None, str | None]:
+ """Verify directly-uploaded S3 objects and attach them to the run manifest.
+
+ Returns ``(finalized_entries, error)``: ``(None, None)`` when the run isn't found,
+ ``(None, error_message)`` on a validation failure, else ``(finalized_entries, None)``.
+ """
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path
+ get_safe_artifact_name,
+ )
+ from products.tasks.backend.presentation.serializers import ( # noqa: PLC0415 — pure size helpers, kept off the api import path
+ build_task_run_artifact_size_error,
+ get_task_run_artifact_max_size_bytes,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None, None
+
+ manifest = list(run.artifacts or [])
+ artifact_prefix = f"{run.get_artifact_s3_prefix()}/"
+ finalized_entries: list[dict] = []
+ new_storage_paths: list[str] = []
+
+ for artifact in artifacts:
+ artifact_id = artifact["id"]
+ storage_path = artifact["storage_path"]
+
+ if not storage_path.startswith(artifact_prefix) or f"/{artifact_id[:8]}_" not in storage_path:
+ return None, "Artifact storage path is invalid for this run"
+
+ existing_entry = _find_artifact_manifest_entry(manifest, artifact_id, storage_path)
+ if existing_entry is not None:
+ finalized_entries.append(existing_entry)
+ continue
+
+ s3_object = object_storage.head_object(storage_path)
+ if not s3_object:
+ return None, "Artifact upload not found in object storage"
+
+ safe_name = get_safe_artifact_name(artifact["name"])
+ content_type = artifact.get("content_type") or s3_object.get("ContentType") or ""
+ content_length = s3_object.get("ContentLength")
+ if not isinstance(content_length, int):
+ return None, "Artifact upload metadata is unavailable"
+
+ max_size_bytes = get_task_run_artifact_max_size_bytes(safe_name, content_type, artifact.get("type"))
+ if content_length > max_size_bytes:
+ return None, build_task_run_artifact_size_error(safe_name, max_size_bytes)
+
+ entry = _build_artifact_manifest_entry(
+ artifact_id=artifact_id,
+ name=safe_name,
+ artifact_type=artifact["type"],
+ source=artifact.get("source") or "",
+ size=content_length,
+ content_type=content_type,
+ storage_path=storage_path,
+ uploaded_at=django_timezone.now().isoformat(),
+ )
+ manifest.append(entry)
+ finalized_entries.append(entry)
+ new_storage_paths.append(storage_path)
+
+ _save_artifact_manifest(run, manifest)
+ for storage_path in new_storage_paths:
+ _tag_artifact_object(run, storage_path)
+
+ return finalized_entries, None
+
+
+def presign_task_run_artifact(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, storage_path: str
+) -> tuple[str | None, str | None]:
+ """Presign a download URL for an artifact on the run.
+
+ Returns ``(url, error)``: ``(None, None)`` if the run isn't found, ``(None, "not_found")`` if
+ the artifact isn't on the run, ``(None, "unavailable")`` if presigning fails, else ``(url, None)``.
+ """
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None, None
+
+ artifacts = run.artifacts or []
+ if not any(artifact.get("storage_path") == storage_path for artifact in artifacts):
+ return None, "not_found"
+
+ url = object_storage.get_presigned_url(storage_path)
+ if not url:
+ return None, "unavailable"
+ return url, None
+
+
+def read_task_run_artifact(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, storage_path: str
+) -> tuple[bytes | None, dict | None, str | None]:
+ """Read artifact bytes for download, walking the resume chain.
+
+ Returns ``(content, artifact_entry, error)``. ``error`` is one of ``None`` (run not found),
+ ``"not_found"`` (artifact not on the run/chain), ``"read_failed"`` (storage read raised), or
+ ``"content_missing"`` (object absent). On success returns ``(content, artifact_entry, None)``.
+ """
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None, None, None
+
+ artifact = run.find_artifact_in_resume_chain(storage_path)
+ if artifact is None:
+ return None, None, "not_found"
+
+ try:
+ content = object_storage.read_bytes(storage_path, missing_ok=True)
+ except Exception:
+ logger.exception(
+ "task_run.artifact_download_failed",
+ extra={"task_run_id": str(run.id), "storage_path": storage_path},
+ )
+ return None, artifact, "read_failed"
+
+ if content is None:
+ return None, artifact, "content_missing"
+ return content, artifact, None
+
+
+def read_task_run_logs(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:
+ """Concatenated JSONL logs across the run's resume chain (oldest ancestor first)."""
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+
+ parts: list[str] = []
+ for ancestor in run.get_resume_chain():
+ chunk = object_storage.read(ancestor.log_url, missing_ok=True) or ""
+ if chunk:
+ if not chunk.endswith("\n"):
+ chunk = chunk + "\n"
+ parts.append(chunk)
+ return "".join(parts)
+
+
+def read_task_run_session_log_content(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:
+ """Raw session-log JSONL for a run. ``None`` if the run isn't found."""
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ return object_storage.read(run.log_url, missing_ok=True) or ""
+
+
+def create_task_run_connection_token(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, user_id: int, distinct_id: str
+) -> str | None:
+ """Mint a sandbox connection token for a run. ``None`` if the run isn't found."""
+ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the api import path
+ create_sandbox_connection_token as _create,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ return _create(task_run=run, user_id=user_id, distinct_id=distinct_id)
+
+
+# --- Task run commands (user_message signal + sandbox proxy) ---
+
+
+def validate_task_run_artifact_ids(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_ids: list[str]
+) -> tuple[list[str], bool]:
+ """Resolve artifact ids for a run. Returns ``(missing_ids, found)``; ``found=False`` if the run isn't found."""
+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path
+ get_task_run_artifacts_by_id,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return [], False
+ _, missing_artifact_ids = get_task_run_artifacts_by_id(run, artifact_ids)
+ return missing_artifact_ids, True
+
+
+def signal_task_run_user_message(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, content: str | None, artifact_ids: list[str]
+) -> bool | None:
+ """Queue a user_message follow-up signal on the run's workflow.
+
+ Returns ``True`` on success, ``False`` if signalling failed, ``None`` if the run isn't found.
+ """
+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path
+ signal_task_followup_message,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+ try:
+ signal_task_followup_message(run.workflow_id, content, artifact_ids)
+ except Exception:
+ logger.exception("Failed to signal follow-up message for task run %s", run.id)
+ return False
+ return True
+
+
+def get_task_run_sandbox_connection(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, user_id: int, distinct_id: str
+) -> contracts.TaskRunSandboxConnectionDTO | None:
+ """Sandbox connection details for proxying a command. ``None`` if the run isn't found.
+
+ ``sandbox_url`` is ``None`` when the run has no active sandbox (no connection token is minted
+ in that case).
+ """
+ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the api import path
+ create_sandbox_connection_token as _create,
+ )
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ parse_run_state,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None
+
+ run_state = parse_run_state(run.state)
+ if not run_state.sandbox_url:
+ return contracts.TaskRunSandboxConnectionDTO(sandbox_url=None, sandbox_connect_token=None)
+
+ connection_token = _create(task_run=run, user_id=user_id, distinct_id=distinct_id)
+ return contracts.TaskRunSandboxConnectionDTO(
+ sandbox_url=run_state.sandbox_url,
+ sandbox_connect_token=run_state.sandbox_connect_token,
+ connection_token=connection_token,
+ )
+
+
+# --- Task run relay (Slack) ---
+
+
+def relay_task_run_message(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, text: str
+) -> tuple[str, str | None]:
+ """Queue a Slack relay workflow for a run message.
+
+ Returns ``(status, relay_id)`` where status is ``"accepted"`` (relay_id set), ``"skipped"``
+ (run not found / terminal / no Slack mapping / empty text), or ``"failed"``.
+ """
+ from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
+ SlackThreadTaskMapping,
+ )
+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path
+ execute_posthog_code_agent_relay_workflow,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None or run.is_terminal:
+ return "skipped", None
+ if not SlackThreadTaskMapping.objects.filter(task_run=run).exists():
+ return "skipped", None
+
+ trimmed = text.strip()
+ if not trimmed:
+ return "skipped", None
+
+ try:
+ relay_id = execute_posthog_code_agent_relay_workflow(run_id=str(run.id), text=trimmed, delete_progress=True)
+ except Exception:
+ logger.exception("task_run_relay_message_enqueue_failed", extra={"run_id": str(run.id)})
+ return "failed", None
+ return "accepted", relay_id
+
+
+# --- Task run creation / start / cloud resume ---
+
+
+def _ensure_task_team_github_integration(task: Task) -> bool:
+ if task.github_integration_id is not None:
+ return True
+ github_integration = Integration.objects.filter(team_id=task.team_id, kind="github").first()
+ if github_integration is None:
+ return False
+ task.github_integration = github_integration
+ task.save(update_fields=["github_integration", "updated_at"])
+ return True
+
+
+def _resolve_cloud_pr_authorship_mode(
+ task: Task,
+ *,
+ pr_authorship_mode,
+ request_user_id: int | None,
+ github_user_token: str | None,
+):
+ """Resolve the effective PR-authorship mode for a cloud run.
+
+ Returns ``(mode, error)``: ``error`` is a ``TaskRunValidationError`` when authorship can't be
+ established (mode is then ``None``); otherwise ``error`` is ``None`` and ``mode`` is the
+ resolved value. Mirrors the original view helper exactly.
+ """
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ PrAuthorshipMode,
+ resolve_user_github_integration_for_task,
+ user_github_integration_is_usable,
+ )
+
+ if pr_authorship_mode != PrAuthorshipMode.USER or github_user_token:
+ return pr_authorship_mode, None
+
+ if task.created_by_id != request_user_id:
+ return None, contracts.TaskRunValidationError(
+ kind="validation_error",
+ code="github_authorization_required",
+ detail="User-authored runs must be started by the task creator, or provide github_user_token.",
+ attr="pr_authorship_mode",
+ )
+
+ user_github_integration = resolve_user_github_integration_for_task(task, allow_refresh=False)
+ if user_github_integration is not None and user_github_integration_is_usable(user_github_integration):
+ if task.github_user_integration_id != user_github_integration.integration.id:
+ task.github_user_integration = user_github_integration.integration
+ task.save(update_fields=["github_user_integration", "updated_at"])
+ return PrAuthorshipMode.USER, None
+
+ if _ensure_task_team_github_integration(task):
+ return PrAuthorshipMode.BOT, None
+
+ return None, contracts.TaskRunValidationError(
+ kind="validation_error",
+ code="github_authorization_required",
+ detail="Link a GitHub account with repo access before running user-authored cloud tasks.",
+ attr="pr_authorship_mode",
+ )
+
+
+def _github_credential_source_extra_state(pr_authorship_mode, github_user_token: str | None) -> dict[str, str]:
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ GitHubCredentialSource,
+ PrAuthorshipMode,
+ )
+
+ if pr_authorship_mode != PrAuthorshipMode.USER:
+ return {}
+ source = GitHubCredentialSource.CALLER_TOKEN if github_user_token else GitHubCredentialSource.SERVER_INTEGRATION
+ return {"github_credential_source": source.value}
+
+
+def bootstrap_task_run(
+ task_id: str | UUID, team_id: int, user_id: int | None, *, validated_data: dict
+) -> contracts.TaskRunCreateResult | None:
+ """Create a task run (without starting execution) from validated bootstrap data.
+
+ Returns ``None`` if the task isn't found/visible (the view raises 404). Otherwise returns a
+ ``TaskRunCreateResult`` carrying either the created run DTO or a structured validation error.
+ Mirrors ``TaskRunViewSet.create`` byte-for-byte (minus the usage gate, which the view applies).
+ """
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ PrAuthorshipMode,
+ RunSource,
+ cache_github_user_token,
+ get_provider_for_runtime_adapter,
+ get_reasoning_effort_error,
+ )
+
+ task = _get_task_for_run_visibility(task_id, team_id, user_id)
+ if task is None:
+ return None
+
+ mode = validated_data.get("mode", "background")
+ environment = validated_data.get("environment", TaskRun.Environment.LOCAL)
+ branch = validated_data.get("branch")
+ sandbox_environment_id = validated_data.get("sandbox_environment_id")
+ pr_authorship_mode = validated_data.get("pr_authorship_mode")
+ run_source = validated_data.get("run_source")
+ signal_report_id = validated_data.get("signal_report_id")
+ runtime_adapter = validated_data.get("runtime_adapter")
+ model = validated_data.get("model")
+ reasoning_effort = validated_data.get("reasoning_effort")
+ github_user_token = validated_data.get("github_user_token")
+ initial_permission_mode = validated_data.get("initial_permission_mode")
+ home_quick_action = validated_data.get("home_quick_action")
+ if run_source == RunSource.SIGNAL_REPORT:
+ pr_authorship_mode = PrAuthorshipMode.BOT
+
+ extra_state: dict | None = None
+ if initial_permission_mode is not None:
+ extra_state = {"initial_permission_mode": initial_permission_mode}
+
+ provider = get_provider_for_runtime_adapter(runtime_adapter)
+ for key, value in {
+ "pr_base_branch": branch,
+ "pr_authorship_mode": pr_authorship_mode,
+ "run_source": run_source,
+ "signal_report_id": signal_report_id,
+ "runtime_adapter": runtime_adapter,
+ "provider": provider,
+ "model": model,
+ "reasoning_effort": reasoning_effort,
+ "home_quick_action": home_quick_action,
+ }.items():
+ if value is not None:
+ extra_state = extra_state or {}
+ extra_state[key] = value.value if hasattr(value, "value") else value
+
+ reasoning_effort_error = get_reasoning_effort_error(
+ runtime_adapter=runtime_adapter, model=model, reasoning_effort=reasoning_effort
+ )
+ if reasoning_effort_error is not None:
+ return contracts.TaskRunCreateResult(
+ error=contracts.TaskRunValidationError(
+ kind="validation_error", code="invalid_input", detail=reasoning_effort_error, attr="reasoning_effort"
+ )
+ )
+
+ pr_authorship_mode, validation_error = _resolve_cloud_pr_authorship_mode(
+ task,
+ pr_authorship_mode=pr_authorship_mode,
+ request_user_id=user_id,
+ github_user_token=github_user_token,
+ )
+ if validation_error is not None:
+ return contracts.TaskRunCreateResult(error=validation_error)
+ if pr_authorship_mode is not None:
+ extra_state = extra_state or {}
+ extra_state["pr_authorship_mode"] = (
+ pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
+ )
+
+ if credential_source := _github_credential_source_extra_state(pr_authorship_mode, github_user_token):
+ extra_state = extra_state or {}
+ extra_state.update(credential_source)
+
+ if sandbox_environment_id is not None:
+ sandbox_environment = SandboxEnvironment.get_accessible_for_task(
+ environment_id=sandbox_environment_id,
+ team_id=task.team_id,
+ task_created_by_id=task.created_by_id,
+ )
+ if sandbox_environment is None:
+ return contracts.TaskRunCreateResult(
+ error=contracts.TaskRunValidationError(kind="detail", detail="Invalid sandbox_environment_id")
+ )
+ extra_state = extra_state or {}
+ extra_state["sandbox_environment_id"] = str(sandbox_environment.id)
+ logger.info(
+ "Applying sandbox environment to task run",
+ extra={
+ "task_id": str(task.id),
+ "sandbox_environment_id": str(sandbox_environment.id),
+ "sandbox_environment_name": sandbox_environment.name,
+ "network_access_level": sandbox_environment.network_access_level,
+ },
+ )
+
+ logger.info(
+ "Creating task run for task %s with mode=%s, branch=%s, environment=%s", task.id, mode, branch, environment
+ )
+ run = task.create_run(environment=environment, mode=mode, branch=branch, extra_state=extra_state)
+
+ if github_user_token and pr_authorship_mode == PrAuthorshipMode.USER:
+ cache_github_user_token(str(run.id), github_user_token)
+
+ return contracts.TaskRunCreateResult(run=_task_run_detail_to_dto(_task_run_queryset().get(pk=run.pk)))
+
+
+def _trigger_task_processing_workflow(
+ task: Task, run: TaskRun, user_id: int | None, *, raise_on_error: bool = False
+) -> None:
+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path
+ execute_task_processing_workflow,
+ )
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ RunSource,
+ parse_run_state,
+ )
+
+ full_mcp_run_sources = frozenset({None, RunSource.MANUAL})
+ run_source = parse_run_state(run.state).run_source
+ posthog_mcp_scopes: Literal["read_only", "full"] = "full" if run_source in full_mcp_run_sources else "read_only"
+ try:
+ logger.info("Attempting to trigger task processing workflow for task %s, run %s", task.id, run.id)
+ execute_task_processing_workflow(
+ task_id=str(task.id),
+ run_id=str(run.id),
+ team_id=task.team.id,
+ user_id=user_id,
+ posthog_mcp_scopes=posthog_mcp_scopes,
+ )
+ logger.info("Workflow trigger completed for task %s, run %s", task.id, run.id)
+ except Exception as e:
+ logger.exception("Failed to trigger task processing workflow for task %s, run %s: %s", task.id, run.id, e)
+ if raise_on_error:
+ raise
+
+
+# Statuses from which a cloud run may be started via the start endpoint.
+_STARTABLE_TASK_RUN_STATUSES = (TaskRun.Status.NOT_STARTED, TaskRun.Status.QUEUED)
+
+
+def check_task_run_startable(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str:
+ """Whether a run can be started via the start endpoint.
+
+ Returns ``"not_found"`` (run missing), ``"not_cloud"``, ``"bad_status:<current>"``, or
+ ``"ok"``. The usage gate (429) is applied by the view between this check and ``start_task_run``.
+ """
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return "not_found"
+ if run.environment != TaskRun.Environment.CLOUD:
+ return "not_cloud"
+ if run.status not in _STARTABLE_TASK_RUN_STATUSES:
+ return f"bad_status:{run.status}"
+ return "ok"
+
+
+def start_task_run(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, user_id: int | None, *, validated_data: dict
+) -> tuple[str, UUID | None]:
+ """Apply run-scoped attachments and trigger the cloud workflow for a startable run.
+
+ Caller must have already verified startability and applied the usage gate. Returns
+ ``(outcome, task_id)``: ``"not_found"``, ``"missing_artifacts:<csv>"``, or ``"started"``
+ (``task_id`` set). Rolls back any pending-state writes on failure (re-raising), mirroring
+ the original view.
+ """
+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path
+ get_task_run_artifacts_by_id,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return "not_found", None
+ task = run.task
+
+ pending_user_message = validated_data.get("pending_user_message")
+ pending_user_artifact_ids = validated_data.get("pending_user_artifact_ids") or []
+
+ if pending_user_artifact_ids:
+ _, missing_artifact_ids = get_task_run_artifacts_by_id(run, pending_user_artifact_ids)
+ if missing_artifact_ids:
+ return "missing_artifacts:" + ",".join(missing_artifact_ids), None
+
+ state_updates: dict = {}
+ if pending_user_message is not None:
+ state_updates["pending_user_message"] = pending_user_message
+ if pending_user_artifact_ids:
+ state_updates["pending_user_artifact_ids"] = pending_user_artifact_ids
+
+ previous_state = dict(run.state or {})
+ try:
+ if state_updates:
+ TaskRun.update_state_atomic(run.id, updates=state_updates)
+ run.refresh_from_db()
+ logger.info("Triggering workflow for task %s, existing run %s", task.id, run.id)
+ _trigger_task_processing_workflow(task, run, user_id, raise_on_error=True)
+ except Exception:
+ if state_updates:
+ rollback_updates = {
+ key: previous_state[key] for key in state_updates.keys() if key in previous_state
+ } or None
+ rollback_remove_keys = [key for key in state_updates.keys() if key not in previous_state] or None
+ TaskRun.update_state_atomic(run.id, updates=rollback_updates, remove_keys=rollback_remove_keys)
+ raise
+
+ return "started", task.id
+
+
+def resume_task_run_in_cloud(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, user_id: int | None
+) -> tuple[str, contracts.TaskRunDetailDTO | None, str | None]:
+ """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), ``"auth_error:<detail>"`` (400, github auth), ``"workflow_failed"``
+ (502), or ``"resumed"`` (run_dto set). Mirrors ``TaskRunViewSet.resume_in_cloud``.
+ """
+ from django.conf import settings # noqa: PLC0415
+
+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path
+ resume_task_in_cloud_workflow,
+ )
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ PrAuthorshipMode,
+ get_pr_authorship_mode,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return "not_found", None, None
+
+ logger.info(
+ "resume_in_cloud_called",
+ extra={
+ "task_run_id": str(run.id),
+ "task_id": str(run.task_id),
+ "prior_status": run.status,
+ "prior_environment": run.environment,
+ "prior_state_keys": sorted((run.state or {}).keys()),
+ "prior_snapshot_external_id": (run.state or {}).get("snapshot_external_id"),
+ "use_modal_resume_snapshots": settings.TASKS_USE_MODAL_RESUME_SNAPSHOTS,
+ },
+ )
+
+ with transaction.atomic():
+ run = (
+ TaskRun.objects.select_for_update(of=("self",))
+ .select_related("task", "task__created_by", "task__github_integration", "task__github_user_integration")
+ .get(pk=run.pk)
+ )
+
+ is_cloud_active = run.environment == TaskRun.Environment.CLOUD and run.status in (
+ TaskRun.Status.QUEUED,
+ TaskRun.Status.IN_PROGRESS,
+ )
+ if is_cloud_active:
+ return "already_active", None, None
+
+ if get_pr_authorship_mode(run.task, run.state) == PrAuthorshipMode.USER:
+ pr_authorship_mode, validation_error = _resolve_cloud_pr_authorship_mode(
+ run.task,
+ pr_authorship_mode=PrAuthorshipMode.USER,
+ request_user_id=user_id,
+ github_user_token=None,
+ )
+ if validation_error is not None:
+ return f"auth_error:{validation_error.detail}", None, None
+ if pr_authorship_mode is not None:
+ run.state = {
+ **(run.state or {}),
+ "pr_authorship_mode": (
+ pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
+ ),
+ }
+
+ prior_status = run.status
+ prior_environment = run.environment
+ prior_completed_at = run.completed_at
+ prior_state = dict(run.state or {})
+ run.prepare_for_cloud_handoff()
+
+ logger.info("Resuming task run in cloud", extra={"task_run_id": str(run.id), "task_id": str(run.task_id)})
+
+ try:
+ 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)})
+ with transaction.atomic():
+ run = TaskRun.objects.select_for_update().get(pk=run.pk)
+ run.status = prior_status
+ run.environment = prior_environment
+ run.completed_at = prior_completed_at
+ run.state = prior_state
+ run.error_message = "Failed to start cloud workflow"
+ run.save(update_fields=["status", "environment", "completed_at", "state", "error_message", "updated_at"])
+ run.publish_stream_state_event()
+ return "workflow_failed", None, None
+
+ return "resumed", _task_run_detail_to_dto(run), None
+
+
+# --- Task presentation CRUD + actions ---
+# These back the thin ``TaskViewSet``. They mirror the original viewset's querysets
+# (team scoping, ``task_visibility_q`` visibility, ordering, filters, annotations) and
+# orchestration (title generation, signal-report linkage, workflow triggers, S3 artifact
+# staging, presence beacons) byte-for-byte.
+
+
+def signal_report_queryset():
+ """The ``SignalReport`` manager queryset, for the task write serializer's report FK field.
+
+ Kept here so presentation never imports the ``signals`` product's models directly; team
+ scoping on the selected report is enforced by the serializer's ``validate_signal_report``.
+ """
+ from products.signals.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
+ SignalReport,
+ )
+
+ return SignalReport.objects.all()
+
+
+def is_internal_debug_team(team_id: int | None) -> bool:
+ """Whether the team is the PostHog-internal debugging team. Mirrors the original view helper."""
+ from django.conf import settings # noqa: PLC0415
+
+ if settings.DEBUG and not settings.TEST:
+ return team_id == 1
+ return team_id == 2 and settings.CLOUD_DEPLOYMENT == "US"
+
+
+def _task_detail_queryset():
+ return Task.objects.select_related(
+ "created_by", "team", "github_integration", "github_user_integration"
+ ).prefetch_related("runs")
+
+
+def _visible_task_qs(team_id: int, user_id: int | None, *, bypass_visibility: bool = False):
+ qs = Task.objects.filter(team_id=team_id, deleted=False)
+ if not bypass_visibility:
+ qs = qs.filter(task_visibility_q(user_id))
+ return qs
+
+
+def get_task_detail(
+ task_id: str | UUID, team_id: int, user_id: int | None, *, bypass_visibility: bool = False
+) -> contracts.TaskDetailDTO | None:
+ """A single task as a detail DTO, team-scoped and visibility-gated.
+
+ ``bypass_visibility`` mirrors the ``?ph_debug=true`` retrieve path for internal-debug teams.
+ """
+ task = (
+ _visible_task_qs(team_id, user_id, bypass_visibility=bypass_visibility)
+ .select_related("created_by", "team", "github_integration", "github_user_integration")
+ .prefetch_related("runs")
+ .filter(id=task_id)
+ .first()
+ )
+ return _task_detail_to_dto(task) if task is not None else None
+
+
+def task_visible(task_id: str | UUID, team_id: int, user_id: int | None) -> bool:
+ """Whether a non-deleted task exists for the team and is visible to the user.
+
+ Mirrors the existence gate ``TaskViewSet.get_object()`` applied (team + ``deleted=False`` +
+ ``task_visibility_q``). Used by the ``run`` action to 404 before the usage gate, preserving
+ the original ordering.
+ """
+ return _visible_task_qs(team_id, user_id).filter(id=task_id).exists()
+
+
+def list_tasks(
+ team_id: int, user_id: int | None, *, filters: dict, is_debug_or_staff: bool
+) -> list[contracts.TaskDetailDTO]:
+ """All visible tasks for the team, mirroring ``TaskViewSet.safely_get_queryset`` for ``list``.
+
+ ``filters`` carries the request query params (origin_product, stage, organization, repository,
+ created_by, search, status, internal, archived). ``is_debug_or_staff`` gates the ``internal``
+ filter exactly as the original view did (``settings.DEBUG or request.user.is_staff``).
+ """
+ qs = _visible_task_qs(team_id, user_id).order_by("-created_at")
+
+ origin_product = filters.get("origin_product")
+ if origin_product:
+ qs = qs.filter(origin_product=origin_product)
+
+ stage = filters.get("stage")
+ if stage:
+ qs = qs.filter(runs__stage=stage)
+
+ organization = filters.get("organization")
+ repository = filters.get("repository")
+ created_by = filters.get("created_by")
+ search = filters.get("search")
+ status_filter = filters.get("status")
+
+ if repository:
+ repo_str = repository.strip().lower()
+ if "/" in repo_str:
+ qs = qs.filter(repository__iexact=repo_str)
+ else:
+ qs = qs.filter(repository__iendswith=f"/{repo_str}")
+
+ if organization:
+ org_str = organization.strip().lower()
+ qs = qs.filter(repository__istartswith=f"{org_str}/")
+
+ if created_by:
+ qs = qs.filter(created_by_id=created_by)
+
+ if search:
+ search_term = search.strip()
+ if search_term:
+ search_q = Q(title__icontains=search_term) | Q(description__icontains=search_term)
+ number_part = search_term.split("-")[-1].strip()
+ if number_part.isdigit():
+ search_q |= Q(task_number=int(number_part))
+ qs = qs.filter(search_q)
+
+ if status_filter:
+ latest_run_status = (
+ TaskRun.objects.filter(task=OuterRef("pk")).order_by("-created_at", "-id").values("status")[:1]
+ )
+ qs = qs.annotate(_latest_run_status=Subquery(latest_run_status)).filter(_latest_run_status=status_filter)
+
+ internal_param = filters.get("internal")
+ if internal_param is True and is_debug_or_staff:
+ qs = qs.filter(internal=True)
+ else:
+ qs = qs.filter(internal=False)
+
+ archived_param = filters.get("archived")
+ if archived_param == "true":
+ qs = qs.filter(archived=True)
+ elif archived_param == "all":
+ pass
+ else:
+ qs = qs.filter(archived=False)
+
+ qs = qs.select_related("created_by", "team", "github_integration", "github_user_integration").prefetch_related(
+ "runs"
+ )
+
+ if stage:
+ qs = qs.distinct()
+
+ return [_task_detail_to_dto(task) for task in qs]
+
+
+def list_task_repositories(team_id: int, user_id: int | None) -> list[str]:
+ """Distinct repositories used by non-deleted, non-internal visible tasks for the team."""
+ repositories = (
+ Task.objects.filter(team_id=team_id, deleted=False, internal=False)
+ .filter(task_visibility_q(user_id))
+ .exclude(repository__isnull=True)
+ .exclude(repository__exact="")
+ .values_list("repository", flat=True)
+ .distinct()
+ .order_by("repository")
+ )
+ return [repo for repo in repositories if repo is not None]
+
+
+def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[contracts.TaskSummaryDTO]:
+ """Summary fields for the requested tasks, mirroring ``TaskViewSet.summaries``."""
+ from django.db.models.functions import JSONObject # noqa: PLC0415
+
+ latest_run = (
+ TaskRun.objects.filter(task=OuterRef("pk"))
+ .order_by("-created_at", "-id")
+ .annotate(_data=JSONObject(status="status", environment="environment"))
+ )
+ tasks = (
+ Task.objects.filter(team_id=team_id, deleted=False, id__in=ids)
+ .filter(task_visibility_q(user_id))
+ .annotate(_latest_run=Subquery(latest_run.values("_data")[:1]))
+ .order_by("-created_at", "id")
+ )
+ summaries: list[contracts.TaskSummaryDTO] = []
+ for task in tasks:
+ raw = getattr(task, "_latest_run", None)
+ latest = (
+ contracts.TaskLatestRunSummaryDTO(status=raw.get("status"), environment=raw.get("environment"))
+ if isinstance(raw, dict)
+ else None
+ )
+ summaries.append(
+ contracts.TaskSummaryDTO(
+ id=task.id,
+ title=task.title,
+ repository=task.repository,
+ created_at=task.created_at,
+ updated_at=task.updated_at,
+ latest_run=latest,
+ )
+ )
+ return summaries
+
+
+def compute_repository_readiness(team_id: int, *, repository: str, window_days: int, refresh: bool) -> dict:
+ """Autonomy-readiness details for a repository. Thin wrapper over the internal computation."""
+ from posthog.models import Team # noqa: PLC0415
+
+ from products.tasks.backend.repository_readiness import ( # noqa: PLC0415 — keep readiness deps off the api import path
+ compute_repository_readiness as _compute,
+ )
+
+ team = Team.objects.get(id=team_id)
+ return _compute(team=team, repository=repository, window_days=window_days, refresh=refresh)
+
+
+def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> contracts.TaskDetailDTO:
+ """Create a task, mirroring ``TaskSerializer.create`` byte-for-byte.
+
+ Absorbs the cross-product ``SignalReportTask`` linkage, ``generate_task_title``, and
+ ``resolve_user_github_integration_for_task`` so no internal/other-product import leaks into
+ presentation. ``validated_data`` carries the validated write fields (integrations already
+ resolved to instances by the write serializer's PK fields).
+ """
+ from posthog.models import Team # noqa: PLC0415
+
+ from products.signals.backend.models import ( # noqa: PLC0415 — cross-product write kept off the api import path
+ SignalReportTask,
+ )
+ from products.tasks.backend.logic.services.title_generator import generate_task_title # noqa: PLC0415
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ resolve_user_github_integration_for_task,
+ )
+
+ team = Team.objects.get(id=team_id)
+ validated_data = dict(validated_data)
+ validated_data["team"] = team
+ validated_data.setdefault("origin_product", Task.OriginProduct.USER_CREATED)
+
+ if user_id is not None:
+ validated_data["created_by"] = User.objects.get(id=user_id)
+
+ link_relationship = validated_data.pop(
+ "signal_report_task_relationship",
+ SignalReportTask.Relationship.IMPLEMENTATION,
+ )
+
+ if not validated_data.get("github_integration"):
+ default_integration = Integration.objects.filter(team=team, kind="github").first()
+ if default_integration:
+ validated_data["github_integration"] = default_integration
+
+ if (
+ validated_data.get("repository")
+ and validated_data.get("origin_product", Task.OriginProduct.USER_CREATED) == Task.OriginProduct.USER_CREATED
+ and not validated_data.get("github_user_integration")
+ ):
+ task_stub = Task(
+ team=team,
+ created_by=validated_data.get("created_by"),
+ origin_product=Task.OriginProduct.USER_CREATED,
+ repository=validated_data["repository"],
+ github_integration=validated_data.get("github_integration"),
+ )
+ github_user_integration = resolve_user_github_integration_for_task(task_stub, allow_refresh=False)
+ if github_user_integration is not None:
+ validated_data["github_user_integration"] = github_user_integration.integration
+
+ title = (validated_data.get("title") or "").strip()
+ if not title and validated_data.get("description"):
+ validated_data["title"] = generate_task_title(validated_data["description"])
+ validated_data.setdefault("title_manually_set", False)
+ elif title:
+ validated_data.setdefault("title_manually_set", True)
+
+ logger.info("Creating task with data: %s", validated_data)
+ with transaction.atomic():
+ task = Task.objects.create(**validated_data)
+ if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT:
+ SignalReportTask.objects.create(
+ team_id=task.team_id,
+ report_id=task.signal_report_id,
+ task=task,
+ relationship=link_relationship,
+ )
+
+ return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))
+
+
+def update_task(
+ task_id: str | UUID, team_id: int, user_id: int | None, *, validated_data: dict
+) -> contracts.TaskDetailDTO | None:
+ """Update a task, mirroring ``TaskSerializer.update``. ``None`` if not found/visible."""
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id).first()
+ if task is None:
+ return None
+
+ validated_data = dict(validated_data)
+ # Immutable after creation; origin_product controls visibility, signal_report is set-once.
+ validated_data.pop("signal_report", None)
+ validated_data.pop("signal_report_task_relationship", None)
+ validated_data.pop("origin_product", None)
+ if "title" in validated_data and "title_manually_set" not in validated_data:
+ validated_data["title_manually_set"] = True
+ if "archived" in validated_data and validated_data["archived"] != task.archived:
+ validated_data["archived_at"] = django_timezone.now() if validated_data["archived"] else None
+
+ logger.info("perform_update called for task %s with validated_data: %s", task.id, validated_data)
+ for key, value in validated_data.items():
+ setattr(task, key, value)
+ task.save()
+ logger.info("Task %s updated successfully", task.id)
+
+ return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))
+
+
+def soft_delete_task(task_id: str | UUID, team_id: int, user_id: int | None) -> bool:
+ """Soft-delete a task. Returns whether a task was found/visible and deleted."""
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id).first()
+ if task is None:
+ return False
+ logger.info("Soft deleting task %s", task.id)
+ task.soft_delete()
+ return True
+
+
+# --- Task staged artifacts (S3 + cache, attached to the next run) ---
+
+
+_TASK_STAGED_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024
+
+
+def prepare_task_staged_artifacts(
+ task_id: str | UUID,
+ team_id: int,
+ user_id: int | None,
+ *,
+ artifacts: list[dict],
+ upload_expiration_seconds: int,
+) -> contracts.StagedArtifactPrepareResult | None:
+ """Reserve S3 keys + presigned POST forms for task attachments. ``None`` if task not found."""
+ from posthog.storage import object_storage # noqa: PLC0415
+
+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415
+ build_task_staged_artifact_storage_path,
+ get_safe_artifact_name,
+ )
+
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id).first()
+ if task is None:
+ return None
+
+ prepared: list[contracts.StagedArtifactPreparedDTO] = []
+ for artifact in artifacts:
+ artifact_id = uuid4().hex
+ safe_name = get_safe_artifact_name(artifact["name"])
+ storage_path = build_task_staged_artifact_storage_path(task, artifact_id, safe_name)
+ presigned_post = object_storage.get_presigned_post(
+ storage_path,
+ conditions=[
+ ["content-length-range", 0, artifact["size"] + _TASK_STAGED_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES]
+ ],
+ expiration=upload_expiration_seconds,
+ )
+ if not presigned_post:
+ return contracts.StagedArtifactPrepareResult(error="Unable to generate upload URL")
+
+ prepared.append(
+ contracts.StagedArtifactPreparedDTO(
+ id=artifact_id,
+ name=safe_name,
+ type=artifact["type"],
+ source=artifact.get("source") or "",
+ size=artifact["size"],
+ content_type=artifact.get("content_type") or "",
+ storage_path=storage_path,
+ expires_in=upload_expiration_seconds,
+ presigned_post=presigned_post,
+ )
+ )
+
+ return contracts.StagedArtifactPrepareResult(artifacts=prepared)
+
+
+def finalize_task_staged_artifacts(
+ task_id: str | UUID,
+ team_id: int,
+ user_id: int | None,
+ *,
+ artifacts: list[dict],
+) -> contracts.StagedArtifactFinalizeResult | None:
+ """Verify staged S3 uploads and cache their metadata. ``None`` if task not found."""
+ from django.conf import settings # noqa: PLC0415
+
+ from posthog.storage import object_storage # noqa: PLC0415
+
+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415
+ STAGED_ARTIFACT_TTL_DAYS,
+ build_task_artifact_entry,
+ cache_task_staged_artifact,
+ get_safe_artifact_name,
+ tag_task_artifact,
+ )
+ from products.tasks.backend.presentation.serializers import ( # noqa: PLC0415
+ build_task_run_artifact_size_error,
+ get_task_run_artifact_max_size_bytes,
+ )
+
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id).first()
+ if task is None:
+ return None
+
+ artifact_prefix = f"{settings.OBJECT_STORAGE_TASKS_FOLDER}/artifacts/team_{task.team_id}/task_{task.id}/staged/"
+ finalized: list[dict] = []
+ for artifact in artifacts:
+ artifact_id = artifact["id"]
+ storage_path = artifact["storage_path"]
+ if not storage_path.startswith(artifact_prefix) or f"/{artifact_id}/" not in storage_path:
+ return contracts.StagedArtifactFinalizeResult(error="Artifact storage path is invalid for this task")
+
+ s3_object = object_storage.head_object(storage_path)
+ if not s3_object:
+ return contracts.StagedArtifactFinalizeResult(error="Artifact upload not found in object storage")
+
+ content_length = s3_object.get("ContentLength")
+ if not isinstance(content_length, int):
+ return contracts.StagedArtifactFinalizeResult(error="Artifact upload metadata is unavailable")
+
+ safe_name = get_safe_artifact_name(artifact["name"])
+ content_type = artifact.get("content_type") or s3_object.get("ContentType") or ""
+ max_size_bytes = get_task_run_artifact_max_size_bytes(safe_name, content_type, artifact.get("type"))
+ if content_length > max_size_bytes:
+ return contracts.StagedArtifactFinalizeResult(
+ error=build_task_run_artifact_size_error(safe_name, max_size_bytes)
+ )
+
+ finalized.append(
+ build_task_artifact_entry(
+ artifact_id=artifact_id,
+ name=safe_name,
+ artifact_type=artifact["type"],
+ source=artifact.get("source") or "",
+ size=content_length,
+ content_type=content_type,
+ storage_path=storage_path,
+ )
+ )
+
+ for entry in finalized:
+ cache_task_staged_artifact(task, entry)
+ tag_task_artifact(entry["storage_path"], ttl_days=STAGED_ARTIFACT_TTL_DAYS, team_id=task.team_id)
+
+ return contracts.StagedArtifactFinalizeResult(artifacts=finalized)
+
+
+# --- Task run (the ``run`` action) ---
+
+
+def run_task(
+ task_id: str | UUID, team_id: int, user_id: int | None, *, validated_data: dict
+) -> contracts.TaskRunResult | None:
+ """Create a run for a task and kick off its workflow, mirroring ``TaskViewSet.run``.
+
+ Returns ``None`` if the task isn't found/visible (the view raises 404). Otherwise a
+ ``TaskRunResult`` carrying the refreshed task detail DTO or a structured error. The usage
+ gate (429) is applied by the view before calling this.
+ """
+ from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415
+ RUN_ARTIFACT_TTL_DAYS,
+ build_task_staged_artifact_cache_key,
+ get_task_staged_artifacts,
+ tag_task_artifact,
+ )
+ from products.tasks.backend.redis import get_tasks_cache # noqa: PLC0415
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ PrAuthorshipMode,
+ RunSource,
+ cache_github_user_token,
+ get_provider_for_runtime_adapter,
+ get_reasoning_effort_error,
+ parse_run_state,
+ )
+
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id).first()
+ if task is None:
+ return None
+
+ mode = validated_data.get("mode", "background")
+ branch = validated_data.get("branch")
+ resume_from_run_id = validated_data.get("resume_from_run_id")
+ pending_user_message = validated_data.get("pending_user_message")
+ pending_user_artifact_ids = validated_data.get("pending_user_artifact_ids") or []
+ sandbox_environment_id = validated_data.get("sandbox_environment_id")
+ sandbox_environment_id_supplied_by_user = sandbox_environment_id is not None
+ pr_authorship_mode = validated_data.get("pr_authorship_mode")
+ run_source = validated_data.get("run_source")
+ signal_report_id = validated_data.get("signal_report_id")
+ runtime_adapter = validated_data.get("runtime_adapter")
+ model = validated_data.get("model")
+ reasoning_effort = validated_data.get("reasoning_effort")
+ github_user_token = validated_data.get("github_user_token")
+ initial_permission_mode = validated_data.get("initial_permission_mode")
+ if run_source == RunSource.SIGNAL_REPORT:
+ pr_authorship_mode = PrAuthorshipMode.BOT
+
+ runtime_state_fields = {
+ "pr_authorship_mode": pr_authorship_mode,
+ "run_source": run_source,
+ "signal_report_id": signal_report_id,
+ "runtime_adapter": runtime_adapter,
+ "model": model,
+ "reasoning_effort": reasoning_effort,
+ }
+
+ extra_state: dict | None = None
+ if pending_user_message is not None:
+ extra_state = {"pending_user_message": pending_user_message}
+ if pending_user_artifact_ids:
+ extra_state = extra_state or {}
+ extra_state["pending_user_artifact_ids"] = pending_user_artifact_ids
+ if initial_permission_mode is not None:
+ extra_state = extra_state or {}
+ extra_state["initial_permission_mode"] = initial_permission_mode
+
+ if resume_from_run_id:
+ previous_run = task.runs.filter(id=resume_from_run_id).first()
+ if not previous_run:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(kind="detail", detail="Invalid resume_from_run_id")
+ )
+
+ prev_state = parse_run_state(previous_run.state)
+ extra_state = extra_state or {}
+ extra_state["resume_from_run_id"] = str(resume_from_run_id)
+ if prev_state.snapshot_external_id:
+ extra_state["snapshot_external_id"] = prev_state.snapshot_external_id
+
+ if prev_state.sandbox_environment_id and sandbox_environment_id is None:
+ sandbox_environment_id = prev_state.sandbox_environment_id
+
+ for field_name in runtime_state_fields:
+ if runtime_state_fields[field_name] is None:
+ runtime_state_fields[field_name] = getattr(prev_state, field_name)
+
+ pr_authorship_mode = runtime_state_fields["pr_authorship_mode"]
+ run_source = runtime_state_fields["run_source"]
+ signal_report_id = runtime_state_fields["signal_report_id"]
+ runtime_adapter = runtime_state_fields["runtime_adapter"]
+ model = runtime_state_fields["model"]
+ reasoning_effort = runtime_state_fields["reasoning_effort"]
+ if branch is None and prev_state.pr_base_branch is not None:
+ branch = prev_state.pr_base_branch
+
+ provider = get_provider_for_runtime_adapter(runtime_adapter)
+
+ for key, value in {
+ "pr_base_branch": branch,
+ "pr_authorship_mode": pr_authorship_mode,
+ "run_source": run_source,
+ "signal_report_id": signal_report_id,
+ "runtime_adapter": runtime_adapter,
+ "provider": provider,
+ "model": model,
+ "reasoning_effort": reasoning_effort,
+ }.items():
+ if value is not None:
+ extra_state = extra_state or {}
+ extra_state[key] = value.value if hasattr(value, "value") else value
+
+ reasoning_effort_error = get_reasoning_effort_error(
+ runtime_adapter=runtime_adapter, model=model, reasoning_effort=reasoning_effort
+ )
+ if reasoning_effort_error is not None:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind="validation_error", code="invalid_input", detail=reasoning_effort_error, attr="reasoning_effort"
+ )
+ )
+
+ pr_authorship_mode, validation_error = _resolve_cloud_pr_authorship_mode(
+ task,
+ pr_authorship_mode=pr_authorship_mode,
+ request_user_id=user_id,
+ github_user_token=github_user_token,
+ )
+ if validation_error is not None:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind=validation_error.kind,
+ detail=validation_error.detail,
+ code=validation_error.code,
+ attr=validation_error.attr,
+ )
+ )
+ if pr_authorship_mode is not None:
+ extra_state = extra_state or {}
+ extra_state["pr_authorship_mode"] = (
+ pr_authorship_mode.value if hasattr(pr_authorship_mode, "value") else pr_authorship_mode
+ )
+
+ if credential_source := _github_credential_source_extra_state(pr_authorship_mode, github_user_token):
+ extra_state = extra_state or {}
+ extra_state.update(credential_source)
+
+ if sandbox_environment_id is not None:
+ sandbox_environment = SandboxEnvironment.get_accessible_for_task(
+ environment_id=sandbox_environment_id,
+ team_id=task.team_id,
+ task_created_by_id=task.created_by_id,
+ )
+ if sandbox_environment is None:
+ if sandbox_environment_id_supplied_by_user:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(kind="detail", detail="Invalid sandbox_environment_id")
+ )
+ else:
+ extra_state = extra_state or {}
+ extra_state["sandbox_environment_id"] = str(sandbox_environment.id)
+ logger.info(
+ "Applying sandbox environment to task run",
+ extra={
+ "task_id": str(task.id),
+ "sandbox_environment_id": str(sandbox_environment.id),
+ "sandbox_environment_name": sandbox_environment.name,
+ "network_access_level": sandbox_environment.network_access_level,
+ },
+ )
+
+ staged_artifacts: list[dict] = []
+ if pending_user_artifact_ids:
+ staged_artifacts, missing_artifact_ids = get_task_staged_artifacts(task, pending_user_artifact_ids)
+ if missing_artifact_ids:
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind="detail",
+ detail="Some pending_user_artifact_ids are invalid or expired",
+ missing_artifact_ids=missing_artifact_ids,
+ )
+ )
+
+ logger.info("Creating task run for task %s with mode=%s, branch=%s", task.id, mode, branch)
+ task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state)
+
+ if pending_user_artifact_ids:
+ run_artifacts: list[dict] = []
+ for staged_artifact in staged_artifacts:
+ storage_path = str(staged_artifact["storage_path"])
+ tag_task_artifact(storage_path, ttl_days=RUN_ARTIFACT_TTL_DAYS, team_id=task.team_id)
+ run_artifacts.append(dict(staged_artifact))
+
+ task_run.artifacts = run_artifacts
+ task_run.save(update_fields=["artifacts", "updated_at"])
+
+ for artifact_id in pending_user_artifact_ids:
+ get_tasks_cache().delete(build_task_staged_artifact_cache_key(str(task.id), artifact_id))
+
+ if github_user_token and pr_authorship_mode == PrAuthorshipMode.USER:
+ cache_github_user_token(str(task_run.id), github_user_token)
+
+ logger.info("Triggering workflow for task %s, run %s", task.id, task_run.id)
+ _trigger_task_processing_workflow(task, task_run, user_id, raise_on_error=False)
+
+ return contracts.TaskRunResult(task=get_task_detail(task.id, team_id, user_id))
+
+
+# --- Task presence beacons ---
+
+
+def beacon_task_presence(task_id: str | UUID, team_id: int, user_id: int | None, *, device_id) -> str:
+ """Idempotent upsert of a presence row for a device watching a task.
+
+ Returns ``"not_found"`` (task not visible or device_id doesn't match the caller's push
+ token), or ``"ok"``. Mirrors ``TaskViewSet._presence_beacon``.
+ """
+ from posthog.models.user_push_token import UserPushToken # noqa: PLC0415
+
+ from products.tasks.backend.models import TASK_PRESENCE_TTL_SECONDS, TaskPresence # noqa: PLC0415
+
+ if user_id is None:
+ return "not_found"
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id).first()
+ if task is None:
+ return "not_found"
+ push_token = UserPushToken.objects.filter(user_id=user_id, id=device_id).first()
+ if push_token is None:
+ return "not_found"
+
+ now = django_timezone.now()
+ # nosemgrep: idor-lookup-without-team — team scope is enforced by TaskScopedManager
+ # and via the `task` FK whose row is fetched (visibility-gated) above.
+ TaskPresence.objects.update_or_create(
+ task=task,
+ push_token=push_token,
+ defaults={
+ "team": task.team,
+ "user_id": user_id,
+ "expires_at": now + timedelta(seconds=TASK_PRESENCE_TTL_SECONDS),
+ },
+ )
+ return "ok"
+
+
+def leave_task_presence(task_id: str | UUID, team_id: int, user_id: int | None, *, device_id) -> str:
+ """Best-effort delete of a presence row. ``"not_found"`` if the task isn't visible, else ``"ok"``.
+
+ No 404 on missing presence rows — leave runs from blur/background handlers. Mirrors
+ ``TaskViewSet._presence_leave``.
+ """
+ from products.tasks.backend.models import TaskPresence # noqa: PLC0415
+
+ if user_id is None:
+ return "not_found"
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id).first()
+ if task is None:
+ return "not_found"
+ TaskPresence.objects.filter(task=task, push_token_id=device_id, user_id=user_id).delete()
+ return "ok"
+
+
+# --- Slack thread context (internal debug) ---
+
+
+def _temporal_workflow_url(workflow_id: str | None) -> str | None:
+ from django.conf import settings # noqa: PLC0415
+
+ if not workflow_id:
+ return None
+ base = getattr(settings, "TEMPORAL_UI_HOST", None)
+ namespace = getattr(settings, "TEMPORAL_NAMESPACE", None)
+ if not base or not namespace:
+ return None
+ return f"{base.rstrip('/')}/namespaces/{namespace}/workflows/{workflow_id}"
+
+
+def _slack_repo_research_dto(
+ team_id: int, state: dict, repo_research_runs_by_id: dict, *, build_task_view_url
+) -> contracts.SlackThreadContextRepoResearchDTO | None:
+ from posthog.storage import object_storage # noqa: PLC0415
+
+ research_task_id = state.get("repo_research_task_id")
+ research_run_id = state.get("repo_research_run_id")
+ if not research_task_id or not research_run_id:
+ return None
+ research_run = repo_research_runs_by_id.get(research_run_id)
+ sandbox_url = None
+ log_url = None
+ run_status = None
+ if research_run is not None:
+ sandbox_url = (research_run.state if isinstance(research_run.state, dict) else {}).get("sandbox_url")
+ run_status = research_run.status
+ try:
+ log_url = object_storage.get_presigned_url(research_run.log_url, expiration=3600)
+ except Exception:
+ logger.exception("slack_thread_context_research_log_presign_failed", extra={"run_id": research_run_id})
+ log_url = None
+ workflow_id = TaskRun.get_workflow_id(research_task_id, research_run_id)
+ return contracts.SlackThreadContextRepoResearchDTO(
+ task_id=research_task_id,
+ run_id=research_run_id,
+ status=run_status,
+ task_processing_workflow_id=workflow_id,
+ task_processing_workflow_url=_temporal_workflow_url(workflow_id),
+ sandbox_url=sandbox_url,
+ task_view_url=build_task_view_url(
+ f"/project/{team_id}/tasks/{research_task_id}?runId={research_run_id}&ph_debug=true"
+ ),
+ log_url=log_url,
+ )
+
+
+def resolve_slack_thread_context(
+ team_id: int, *, channel: str, thread_ts: str, url: str, build_url
+) -> contracts.SlackThreadContextResult:
+ """Resolve a parsed Slack permalink to its task, runs, and Temporal workflow handles.
+
+ Caller passes the already-parsed ``(channel, thread_ts)`` and a ``build_url`` callable
+ (``request.build_absolute_uri``) so the facade stays request-agnostic. Caller also enforces
+ the internal-debug gate before calling. Mirrors ``TaskViewSet.slack_thread_context``.
+ """
+ from posthog.storage import object_storage # noqa: PLC0415
+
+ from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
+ SlackThreadTaskMapping,
+ )
+
+ mapping = (
+ SlackThreadTaskMapping.objects.select_related("task", "task__created_by")
+ .filter(channel=channel, thread_ts=thread_ts)
+ .first()
+ )
+ if mapping is None:
+ return contracts.SlackThreadContextResult(
+ outcome="no_mapping",
+ no_mapping_thread=contracts.SlackThreadContextThreadDTO(
+ url=url,
+ channel=channel,
+ thread_ts=thread_ts,
+ slack_workspace_id=None,
+ mentioning_slack_user_id=None,
+ ),
+ )
+
+ task = mapping.task
+ runs = list(TaskRun.objects.filter(task=task).order_by("created_at", "id"))
+ repo_research_run_ids = [
+ rid for run in runs if (rid := (run.state if isinstance(run.state, dict) else {}).get("repo_research_run_id"))
+ ]
+ repo_research_runs_by_id = (
+ {str(r.id): r for r in TaskRun.objects.filter(team=task.team, id__in=repo_research_run_ids)}
+ if repo_research_run_ids
+ else {}
+ )
+ task_url = build_url(f"/project/{task.team_id}/tasks/{task.id}?ph_debug=true")
+
+ run_dtos: list[contracts.SlackThreadContextRunDTO] = []
+ for run in runs:
+ state = run.state if isinstance(run.state, dict) else {}
+ output = run.output if isinstance(run.output, dict) else {}
+ task_processing_workflow_id = TaskRun.get_workflow_id(task.id, run.id)
+ mention_workflow_id = state.get("slack_mention_workflow_id")
+ try:
+ presigned_log_url = object_storage.get_presigned_url(run.log_url, expiration=3600)
+ except Exception:
+ logger.exception("slack_thread_context_log_presign_failed", extra={"run_id": str(run.id)})
+ presigned_log_url = None
+ run_dtos.append(
+ contracts.SlackThreadContextRunDTO(
+ id=str(run.id),
+ status=run.status,
+ created_at=run.created_at,
+ completed_at=run.completed_at,
+ sandbox_url=state.get("sandbox_url"),
+ pr_url=output.get("pr_url"),
+ error_message=run.error_message,
+ task_processing_workflow_id=task_processing_workflow_id,
+ task_processing_workflow_url=_temporal_workflow_url(task_processing_workflow_id),
+ mention_workflow_id=mention_workflow_id,
+ mention_workflow_url=_temporal_workflow_url(mention_workflow_id),
+ task_view_url=build_url(f"/project/{task.team_id}/tasks/{task.id}?runId={run.id}&ph_debug=true"),
+ log_url=presigned_log_url,
+ repo_research=_slack_repo_research_dto(
+ task.team_id, state, repo_research_runs_by_id, build_task_view_url=build_url
+ ),
+ )
+ )
+
+ context = contracts.SlackThreadContextDTO(
+ thread=contracts.SlackThreadContextThreadDTO(
+ url=url,
+ channel=channel,
+ thread_ts=thread_ts,
+ slack_workspace_id=mapping.slack_workspace_id,
+ mentioning_slack_user_id=mapping.mentioning_slack_user_id,
+ ),
+ task=contracts.SlackThreadContextTaskDTO(
+ id=str(task.id),
+ team_id=task.team_id,
+ title=task.title,
+ repository=task.repository,
+ origin_product=task.origin_product,
+ created_at=task.created_at,
+ url=task_url,
+ ),
+ runs=run_dtos,
+ )
+ return contracts.SlackThreadContextResult(outcome="ok", context=context)
+
+
+# --- Code workflow config (presentation CRUD) ---
+# A user's per-team binding configuration. Reads seed a default config on first access;
+# saves are optimistic-locked on ``version`` and validate the bindings before persisting.
+
+
+def _epoch_ms(dt: datetime) -> int:
+ return int(dt.timestamp() * 1000)
+
+
+def _code_workflow_config_to_dto(config: CodeWorkflowConfig) -> contracts.CodeWorkflowConfigDTO:
+ return contracts.CodeWorkflowConfigDTO(
+ id=str(config.id),
+ version=config.version,
+ updated_at=config.updated_at,
+ bindings=config.bindings,
+ )
+
+
+def get_code_workflow_config(team_id: int, user_id: int) -> contracts.CodeWorkflowConfigDTO:
+ """Return the user's config for the team, seeding a default one on first access."""
+ config, _ = CodeWorkflowConfig.objects.get_or_create(
+ team_id=team_id,
+ user_id=user_id,
+ defaults={"bindings": build_default_bindings(), "version": 1},
+ )
+ return _code_workflow_config_to_dto(config)
+
+
+def save_code_workflow_bindings(
+ team_id: int, user_id: int, *, bindings: dict, expected_version: object
+) -> contracts.CodeWorkflowSaveResult:
+ """Validate and save bindings under optimistic locking.
+
+ Returns a ``conflict`` result when ``expected_version`` is not an int or does not match
+ the stored version, an ``invalid`` result (with diagnostics) when validation fails, or a
+ ``saved`` result with the version-bumped config.
+ """
+ with transaction.atomic():
+ current, _ = CodeWorkflowConfig.objects.select_for_update().get_or_create(
+ team_id=team_id,
+ user_id=user_id,
+ defaults={"bindings": build_default_bindings(), "version": 1},
+ )
+ if not isinstance(expected_version, int) or current.version != expected_version:
+ return contracts.CodeWorkflowSaveResult(
+ outcome=CODE_WORKFLOW_CONFLICT,
+ config=_code_workflow_config_to_dto(current),
+ )
+
+ result = validate_bindings(bindings)
+ if not result.can_save:
+ return contracts.CodeWorkflowSaveResult(
+ outcome=CODE_WORKFLOW_INVALID,
+ config=_code_workflow_config_to_dto(current),
+ diagnostics=[
+ contracts.CodeWorkflowDiagnosticDTO(
+ severity=d.severity,
+ code=d.code,
+ message=d.message,
+ situation_id=d.situation_id,
+ action_id=d.action_id,
+ )
+ for d in result.diagnostics
+ ],
+ )
+
+ current.bindings = bindings
+ current.version = current.version + 1
+ current.save(update_fields=["bindings", "version", "updated_at"])
+
+ return contracts.CodeWorkflowSaveResult(
+ outcome=CODE_WORKFLOW_SAVED,
+ config=_code_workflow_config_to_dto(current),
+ )
+
+
+def reset_code_workflow_bindings(team_id: int, user_id: int) -> contracts.CodeWorkflowConfigDTO:
+ """Reset the user's bindings back to the defaults and bump the version."""
+ with transaction.atomic():
+ config, _ = CodeWorkflowConfig.objects.select_for_update().get_or_create(
+ team_id=team_id,
+ user_id=user_id,
+ defaults={"bindings": build_default_bindings(), "version": 1},
+ )
+ config.bindings = build_default_bindings()
+ config.version = config.version + 1
+ config.save(update_fields=["bindings", "version", "updated_at"])
+ return _code_workflow_config_to_dto(config)
+
+
+# --- Code home board ---
+# Active agents are computed live off in-flight runs; workstreams are persisted by the
+# worker and split into board columns by their stored ``state``.
+
+
+def _code_home_workstream_to_dto(ws: CodeWorkstream) -> contracts.CodeHomeWorkstreamDTO:
+ return contracts.CodeHomeWorkstreamDTO(
+ id=ws.key,
+ repo_name=ws.repo_name,
+ repo_full_path=ws.repo_full_path,
+ branch=ws.branch,
+ pr_url=ws.pr_url,
+ pr=ws.pr,
+ primary_situation=ws.primary_situation,
+ last_activity_at=_epoch_ms(ws.last_activity_at),
+ tasks=[
+ contracts.CodeHomeWorkstreamTaskDTO(
+ id=t.get("id"),
+ title=t.get("title"),
+ status=t.get("status"),
+ is_generating=False,
+ needs_permission=False,
+ quick_action=t.get("quick_action"),
+ )
+ for t in (ws.tasks or [])
+ ],
+ situations=ws.situations or [],
+ )
+
+
+def _code_home_active_agents(team_id: int, user_id: int) -> list[contracts.CodeHomeActiveAgentDTO]:
+ cutoff = django_timezone.now() - CODE_HOME_ACTIVE_AGENT_WINDOW
+ runs = (
+ TaskRun.objects.filter(
+ team_id=team_id,
+ task__created_by_id=user_id,
+ task__archived=False,
+ task__deleted=False,
+ status__in=_CODE_HOME_RUNNING_STATUSES,
+ updated_at__gte=cutoff,
+ )
+ .select_related("task")
+ .order_by("-updated_at")
+ )
+
+ seen_tasks: set[str] = set()
+ agents: list[contracts.CodeHomeActiveAgentDTO] = []
+ for run in runs.iterator():
+ task = run.task
+ if str(task.id) in seen_tasks:
+ continue
+ if (run.output or {}).get("pr_url"):
+ continue
+ seen_tasks.add(str(task.id))
+ agents.append(
+ contracts.CodeHomeActiveAgentDTO(
+ task_id=str(task.id),
+ title=task.title,
+ repo_name=task.repository.split("/")[-1] if task.repository else None,
+ branch=run.branch,
+ status=run.status,
+ last_activity_at=_epoch_ms(run.updated_at),
+ needs_permission=False,
+ cloud_pr_url=None,
+ )
+ )
+ return agents
+
+
+def get_code_home(team_id: int, user_id: int) -> contracts.CodeHomeDTO:
+ """Assemble the code-home board: live active agents plus persisted workstreams by column."""
+ workstreams = CodeWorkstream.objects.filter(team_id=team_id, user_id=user_id)
+ needs_attention: list[contracts.CodeHomeWorkstreamDTO] = []
+ in_progress: list[contracts.CodeHomeWorkstreamDTO] = []
+ for ws in workstreams.iterator():
+ dto = _code_home_workstream_to_dto(ws)
+ if ws.state == CodeWorkstream.WorkstreamState.ATTENTION:
+ needs_attention.append(dto)
+ else:
+ in_progress.append(dto)
+
+ return contracts.CodeHomeDTO(
+ active_agents=_code_home_active_agents(team_id, user_id),
+ needs_attention=needs_attention,
+ in_progress=in_progress,
+ )
+
+
+def refresh_team_code_workstreams(team_id: int) -> bool:
+ """Trigger an on-demand evaluation of the team's code workstreams.
+
+ Returns whether a new evaluation workflow was started (``False`` if one was already
+ running).
+ """
+ from products.tasks.backend.temporal.code_workstreams.client import ( # noqa: PLC0415 — keep temporalio off the api import path
+ trigger_team_code_workstreams_evaluation,
+ )
+
+ return trigger_team_code_workstreams_evaluation(team_id)
+
+
+# --- Id-based bridges to the sandbox/agent-command surface ---
+# These take a run id (not an ORM TaskRun) so callers never hold a tasks model. The heavy
+# service modules are imported lazily to keep them off this module's import path.
+
+
+def create_sandbox_connection_token(run_id: str | UUID, user_id: int, distinct_id: str) -> str:
+ """Mint a short-lived connection token for talking to a run's live sandbox."""
+ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the api import path
+ create_sandbox_connection_token as _create,
+ )
+
+ run = TaskRun.objects.select_related("task").get(id=run_id)
+ return _create(run, user_id, distinct_id)
+
+
+def send_user_message(
+ run_id: str | UUID,
+ message: str | None = None,
+ *,
+ artifacts: list[dict] | None = None,
+ auth_token: str | None = None,
+ timeout: int | None = None,
+):
+ """Push a follow-up user message (and/or artifacts) into a run's live sandbox."""
+ from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415 — keep sandbox deps off the api import path
+ send_user_message as _send,
+ )
+
+ run = TaskRun.objects.select_related("task").get(id=run_id)
+ # Forward only explicitly-provided optionals so the underlying call shape is unchanged.
+ extra: dict = {}
+ if artifacts is not None:
+ extra["artifacts"] = artifacts
+ if timeout is not None:
+ extra["timeout"] = timeout
+ return _send(run, message, auth_token=auth_token, **extra)
+
+
+def send_cancel(run_id: str | UUID, *, auth_token: str | None = None):
+ """Cancel the agent running in a run's live sandbox."""
+ from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415 — keep sandbox deps off the api import path
+ send_cancel as _send_cancel,
+ )
+
+ run = TaskRun.objects.select_related("task").get(id=run_id)
+ return _send_cancel(run, auth_token=auth_token)
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
new file mode 100644
index 000000000000..21b764d825f7
--- /dev/null
+++ b/products/tasks/backend/facade/contracts.py
@@ -0,0 +1,589 @@
+"""
+Contract types for the tasks product.
+
+Stable, framework-free frozen dataclasses describing the data the tasks product
+exposes across product boundaries. No Django, no DRF — just stdlib/pydantic types.
+
+These use ``pydantic.dataclasses.dataclass`` (same shape as the stdlib variant, but
+with runtime validation on construction) so a malformed mapper surfaces a
+``ValidationError`` at the boundary instead of a confusing failure deep in a caller.
+
+Behavioral/wiring surfaces (sandbox classes, the multi-turn agent machinery, temporal
+workflows, max tools, webhook handlers) are NOT data and are not modelled here — they
+are re-exported as objects through the sibling facade submodules (``sandbox``,
+``agents``, ``temporal``, ``max_tools``, ``webhooks``, …).
+"""
+
+from datetime import datetime
+from uuid import UUID
+
+from pydantic import Field
+from pydantic.dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class TaskDTO:
+ """A code task."""
+
+ id: UUID
+ team_id: int
+ title: str
+ description: str
+ origin_product: str
+ repository: str | None
+ internal: bool
+ archived: bool
+ created_at: datetime
+ updated_at: datetime
+ created_by_id: int | None = None
+ task_number: int | None = None
+ slug: str = ""
+
+
+@dataclass(frozen=True)
+class TaskRunDTO:
+ """A single execution of a task.
+
+ Carries the derived fields external callers read off a ``TaskRun`` ORM instance
+ (``is_terminal``, ``workflow_id``, ``mode``) plus a few denormalised parent-task
+ values (``task_origin_product``, ``created_by_distinct_id``, ``pr_url``) so callers
+ never need to traverse the ORM relation themselves.
+ """
+
+ id: UUID
+ task_id: UUID
+ team_id: int
+ status: str
+ environment: str
+ stage: str | None
+ branch: str | None
+ error_message: str | None
+ output: dict | None
+ state: dict
+ artifacts: list = Field(default_factory=list)
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+ completed_at: datetime | None = None
+ is_terminal: bool = False
+ workflow_id: str = ""
+ mode: str = "background"
+ task_origin_product: str | None = None
+ created_by_id: int | None = None
+ created_by_distinct_id: str | None = None
+ pr_url: str | None = None
+
+
+@dataclass(frozen=True)
+class TaskDetailDTO:
+ """The HTTP detail representation of a task.
+
+ Mirrors exactly the fields ``TaskSerializer`` emits, in order. ``github_integration`` and
+ ``github_user_integration`` are the integration primary keys (or ``None``), matching the
+ original ``PrimaryKeyRelatedField`` output. ``signal_report`` is the linked report id (or
+ ``None``). ``latest_run`` is the most-recent run as a ``TaskRunDetailDTO`` (or ``None``).
+ ``created_by`` mirrors core ``UserBasicSerializer`` output.
+ """
+
+ id: UUID
+ task_number: int | None
+ slug: str
+ title: str
+ title_manually_set: bool
+ description: str
+ origin_product: str
+ repository: str | None
+ github_integration: int | None
+ github_user_integration: UUID | None
+ signal_report: UUID | None
+ json_schema: dict | None
+ internal: bool
+ archived: bool
+ archived_at: datetime | None
+ ci_prompt: str | None
+ latest_run: "TaskRunDetailDTO | None" = None
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+ created_by: "TaskUserBasicInfo | None" = None
+
+
+@dataclass(frozen=True)
+class TaskLatestRunSummaryDTO:
+ """The latest-run status/environment pair nested in a task summary response."""
+
+ status: str | None
+ environment: str | None
+
+
+@dataclass(frozen=True)
+class TaskSummaryDTO:
+ """The HTTP summary representation of a task.
+
+ Mirrors exactly the fields ``TaskSummarySerializer`` emits. ``latest_run`` carries the
+ most-recent run's ``status`` and ``environment`` (or ``None`` when the task has no runs).
+ """
+
+ id: UUID
+ title: str
+ repository: str | None
+ created_at: datetime
+ updated_at: datetime
+ latest_run: TaskLatestRunSummaryDTO | None = None
+
+
+@dataclass(frozen=True)
+class TaskValidationError:
+ """A structured validation-error payload the presentation layer renders as a 400/404.
+
+ ``kind`` distinguishes the response shape the original task views built:
+ - ``"validation_error"`` -> the ``{type, code, detail, attr}`` body.
+ - ``"detail"`` -> a plain ``{"detail": detail}`` body.
+ - ``"error"`` -> the ``{"error": detail}`` body.
+ ``missing_artifact_ids`` is included on the body only when set.
+ """
+
+ kind: str
+ detail: str
+ code: str | None = None
+ attr: str | None = None
+ missing_artifact_ids: list[str] | None = None
+
+
+@dataclass(frozen=True)
+class TaskRunResult:
+ """Outcome of the task ``run`` action.
+
+ Exactly one of ``task`` / ``error`` is set. ``task`` is the refreshed task detail DTO with
+ its new latest run; ``error`` carries the structured error the original view returned inline.
+ """
+
+ task: "TaskDetailDTO | None" = None
+ error: TaskValidationError | None = None
+
+
+@dataclass(frozen=True)
+class StagedArtifactPreparedDTO:
+ """One prepared staged upload, mirroring ``TaskStagedArtifactPrepareUploadResponseSerializer``."""
+
+ id: str
+ name: str
+ type: str
+ source: str
+ size: int
+ content_type: str
+ storage_path: str
+ expires_in: int
+ presigned_post: dict
+
+
+@dataclass(frozen=True)
+class StagedArtifactPrepareResult:
+ """Outcome of preparing staged uploads. ``error`` is set when a presigned POST could not be minted."""
+
+ artifacts: list[StagedArtifactPreparedDTO] | None = None
+ error: str | None = None
+
+
+@dataclass(frozen=True)
+class StagedArtifactFinalizeResult:
+ """Outcome of finalizing staged uploads. ``error`` is set on the first invalid/missing artifact."""
+
+ artifacts: list[dict] | None = None
+ error: str | None = None
+
+
+@dataclass(frozen=True)
+class SlackThreadContextRepoResearchDTO:
+ """The internal sandbox run the discovery agent used to pick a run's repo."""
+
+ task_id: str
+ run_id: str
+ status: str | None
+ task_processing_workflow_id: str
+ task_processing_workflow_url: str | None
+ sandbox_url: str | None
+ task_view_url: str
+ log_url: str | None
+
+
+@dataclass(frozen=True)
+class SlackThreadContextRunDTO:
+ """One TaskRun and its associated Temporal workflow handles for the slack-thread debug view."""
+
+ id: str
+ status: str
+ created_at: datetime | None
+ completed_at: datetime | None
+ sandbox_url: str | None
+ pr_url: str | None
+ error_message: str | None
+ task_processing_workflow_id: str
+ task_processing_workflow_url: str | None
+ mention_workflow_id: str | None
+ mention_workflow_url: str | None
+ task_view_url: str
+ log_url: str | None
+ repo_research: SlackThreadContextRepoResearchDTO | None = None
+
+
+@dataclass(frozen=True)
+class SlackThreadContextThreadDTO:
+ """Slack-side identifiers and mapping metadata for a thread → task lookup."""
+
+ url: str
+ channel: str
+ thread_ts: str
+ slack_workspace_id: str | None
+ mentioning_slack_user_id: str | None
+
+
+@dataclass(frozen=True)
+class SlackThreadContextTaskDTO:
+ """The PostHog Task linked to a Slack thread."""
+
+ id: str
+ team_id: int
+ title: str
+ repository: str | None
+ origin_product: str
+ created_at: datetime | None
+ url: str
+
+
+@dataclass(frozen=True)
+class SlackThreadContextDTO:
+ """Top-level response for the slack-thread debug endpoint."""
+
+ thread: SlackThreadContextThreadDTO
+ task: SlackThreadContextTaskDTO | None = None
+ runs: list[SlackThreadContextRunDTO] = Field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class SlackThreadContextResult:
+ """Outcome of resolving a slack-thread context.
+
+ ``outcome`` is one of ``"forbidden"`` (403), ``"bad_url"`` (400), ``"no_mapping"`` (404), or
+ ``"ok"`` (``context`` set). The error variants carry the partial payload the original view
+ returned in the body.
+ """
+
+ outcome: str
+ context: SlackThreadContextDTO | None = None
+ bad_url: str | None = None
+ no_mapping_thread: SlackThreadContextThreadDTO | None = None
+
+
+@dataclass(frozen=True)
+class TaskRunDetailDTO:
+ """The HTTP detail representation of a task run.
+
+ Mirrors exactly the fields ``TaskRunDetailSerializer`` emits, in order. ``task`` is the
+ parent task id (rendered as a string, matching the original ``PrimaryKeyRelatedField``).
+ The SMF-derived fields are computed in the facade mapper ``_task_run_detail_to_dto``:
+ ``log_url`` is a presigned S3 URL (cached); ``runtime_adapter`` / ``provider`` / ``model`` /
+ ``reasoning_effort`` are parsed off the run ``state``. ``artifacts`` carries the run's
+ artifact manifest entries verbatim. Reused by the run-detail responses and nested as
+ ``latest_run`` by the task detail response.
+ """
+
+ id: UUID
+ task: UUID
+ stage: str | None
+ branch: str | None
+ status: str
+ environment: str
+ runtime_adapter: str | None
+ provider: str | None
+ model: str | None
+ reasoning_effort: str | None
+ log_url: str | None
+ error_message: str | None
+ output: dict | None
+ state: dict
+ artifacts: list = Field(default_factory=list)
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+ completed_at: datetime | None = None
+
+
+@dataclass(frozen=True)
+class TaskRunValidationError:
+ """A structured validation-error payload the presentation layer renders as a 400.
+
+ ``kind`` distinguishes the response shape the original view built:
+ - ``"validation_error"`` -> the ``{type, code, detail, attr}`` body, fields carried here.
+ - ``"detail"`` -> a plain ``{"detail": detail}`` body.
+ """
+
+ kind: str
+ detail: str
+ code: str | None = None
+ attr: str | None = None
+
+
+@dataclass(frozen=True)
+class TaskRunCreateResult:
+ """Outcome of bootstrapping a task run.
+
+ Exactly one of ``run`` / ``error`` is set. ``error`` carries the structured validation
+ error the original view returned inline; the presentation layer maps it to a 400.
+ """
+
+ run: "TaskRunDetailDTO | None" = None
+ error: TaskRunValidationError | None = None
+
+
+@dataclass(frozen=True)
+class TaskRunStreamInfoDTO:
+ """The minimal run facts the SSE stream view needs without holding a model.
+
+ ``id`` keys the Redis stream, ``state`` decides dedicated-stream routing, and
+ ``origin_product`` is the bounded metric label resolved off the parent task.
+ """
+
+ id: UUID
+ state: dict
+ origin_product: str
+
+
+@dataclass(frozen=True)
+class TaskRunSandboxConnectionDTO:
+ """A run's live-sandbox connection details, for proxying agent-server commands.
+
+ Carries the sandbox URL and connect token parsed off the run state plus a freshly-minted
+ connection token. ``sandbox_url`` is ``None`` when the run has no active sandbox.
+ """
+
+ sandbox_url: str | None
+ sandbox_connect_token: str | None
+ connection_token: str | None = None
+
+
+@dataclass(frozen=True)
+class CreatedTaskDTO:
+ """Result of creating-and-running a task.
+
+ ``Task.create_and_run`` returns an ORM instance whose ``latest_run`` is read by
+ callers; this contract hands back the ids (and the run, if one was created) without
+ leaking the model.
+ """
+
+ task_id: UUID
+ team_id: int
+ latest_run: TaskRunDTO | None = None
+
+
+@dataclass(frozen=True)
+class CodeInviteRedeemResult:
+ """Outcome of attempting to redeem a PostHog Code invite.
+
+ ``outcome`` is one of ``redeemed`` (or ``already_redeemed``), ``invalid_code``, or
+ ``not_redeemable``. The presentation layer maps it to the success/error HTTP response;
+ the ORM redemption, idempotency check, count increment, and analytics capture all
+ happen inside the facade so no model leaks across the boundary.
+ """
+
+ outcome: str
+
+
+@dataclass(frozen=True)
+class TaskAutomationDTO:
+ """A scheduled task automation.
+
+ Mirrors exactly the fields ``TaskAutomationSerializer`` emits. Most read fields are
+ proxied off the underlying ``Task`` (``name``/``prompt``/``repository``/
+ ``github_integration``) or derived from the linked last run (``last_run_at``/
+ ``last_run_status``). ``github_integration`` is the integration's primary key (or
+ ``None``). ``last_task_id`` is always present (the automation's task id as a string);
+ ``last_task_run_id`` is the most recent run's id as a string, or ``None``.
+ """
+
+ id: UUID
+ name: str
+ prompt: str
+ repository: str | None
+ github_integration: int | None
+ cron_expression: str
+ timezone: str
+ template_id: str | None
+ enabled: bool
+ last_run_at: datetime | None
+ last_run_status: str | None
+ last_task_id: str
+ last_task_run_id: str | None
+ last_error: str | None
+ created_at: datetime
+ updated_at: datetime
+
+
+@dataclass(frozen=True)
+class CodeWorkflowConfigDTO:
+ """A user's per-team code-workflow binding configuration.
+
+ Mirrors exactly the JSON shape the code-workflow endpoints emit: ``id`` and
+ ``updatedAt`` are stringified, ``version`` powers optimistic locking, and
+ ``bindings`` is the situation-id → ordered action-list mapping.
+ """
+
+ id: str
+ version: int
+ updated_at: datetime
+ bindings: dict
+
+
+@dataclass(frozen=True)
+class CodeWorkflowDiagnosticDTO:
+ """One binding-validation diagnostic.
+
+ Mirrors a ``ValidationDiagnostic``; ``situation_id`` / ``action_id`` are present only
+ when the diagnostic is scoped to a specific situation or action.
+ """
+
+ severity: str
+ code: str
+ message: str
+ situation_id: str | None = None
+ action_id: str | None = None
+
+
+@dataclass(frozen=True)
+class CodeWorkflowSaveResult:
+ """Outcome of attempting to save code-workflow bindings.
+
+ ``outcome`` is one of ``saved`` (bindings persisted, version bumped), ``conflict``
+ (``expected_version`` did not match the stored version), or ``invalid`` (validation
+ failed). ``config`` is always the resulting/current config; ``diagnostics`` is only
+ populated on the ``invalid`` outcome.
+ """
+
+ outcome: str
+ config: CodeWorkflowConfigDTO
+ diagnostics: list[CodeWorkflowDiagnosticDTO] = Field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class CodeHomeWorkstreamTaskDTO:
+ """One grouped task inside a workstream card."""
+
+ id: str | None
+ title: str | None
+ status: str | None
+ is_generating: bool = False
+ needs_permission: bool = False
+ quick_action: str | None = None
+
+
+@dataclass(frozen=True)
+class CodeHomeWorkstreamDTO:
+ """A persisted workstream card for the code-home board."""
+
+ id: str
+ repo_name: str | None
+ repo_full_path: str | None
+ branch: str | None
+ pr_url: str | None
+ pr: dict | None
+ primary_situation: str | None
+ last_activity_at: int
+ tasks: list[CodeHomeWorkstreamTaskDTO] = Field(default_factory=list)
+ situations: list = Field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class CodeHomeActiveAgentDTO:
+ """A live, in-flight agent run shown on the code-home board."""
+
+ task_id: str
+ title: str
+ repo_name: str | None
+ branch: str | None
+ status: str
+ last_activity_at: int
+ needs_permission: bool = False
+ cloud_pr_url: str | None = None
+
+
+@dataclass(frozen=True)
+class CodeHomeDTO:
+ """The full code-home board: live agents plus persisted workstreams by column."""
+
+ active_agents: list[CodeHomeActiveAgentDTO] = Field(default_factory=list)
+ needs_attention: list[CodeHomeWorkstreamDTO] = Field(default_factory=list)
+ in_progress: list[CodeHomeWorkstreamDTO] = Field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class TaskUserBasicInfo:
+ """Lightweight user info for display, mirroring core ``UserBasicSerializer`` output.
+
+ Carries exactly the fields that serializer emits so presentation responses stay
+ byte-identical when a task/run/environment exposes its ``created_by``.
+ """
+
+ id: int
+ uuid: UUID
+ distinct_id: str
+ first_name: str
+ last_name: str
+ email: str
+ is_email_verified: bool | None = None
+ hedgehog_config: dict | None = None
+ role_at_organization: str | None = None
+
+
+@dataclass(frozen=True)
+class SandboxEnvironmentDTO:
+ """A sandbox execution environment."""
+
+ id: UUID
+ team_id: int
+ name: str
+ network_access_level: str
+ private: bool
+ internal: bool
+ include_default_domains: bool
+ allowed_domains: list[str] = Field(default_factory=list)
+ repositories: list[str] = Field(default_factory=list)
+ effective_domains: list[str] = Field(default_factory=list)
+ has_environment_variables: bool = False
+ created_by: TaskUserBasicInfo | None = None
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+
+
+@dataclass(frozen=True)
+class SandboxSnapshotDTO:
+ """A snapshot of a sandbox image."""
+
+ id: UUID
+ external_id: str
+ status: str
+ repos: list[str] = Field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class SignalReportPrUrlDTO:
+ """The PR URL produced by the latest task run for a signal report."""
+
+ report_id: str
+ pr_url: str
+
+
+@dataclass(frozen=True)
+class TaskRunGaugeRow:
+ """One metric value keyed by (status, environment, origin_product)."""
+
+ environment: str
+ origin_product: str
+ value: float
+ status: str | None = None
+
+
+@dataclass(frozen=True)
+class TaskRunStateMetricsDTO:
+ """Aggregations describing the current state of the TaskRun table, for monitoring gauges."""
+
+ runs_in_status: list[TaskRunGaugeRow] = Field(default_factory=list)
+ oldest_open_age_seconds: list[TaskRunGaugeRow] = Field(default_factory=list)
+ created_recently: list[TaskRunGaugeRow] = Field(default_factory=list)
+ terminal_recently: list[TaskRunGaugeRow] = Field(default_factory=list)
diff --git a/products/tasks/backend/facade/exceptions.py b/products/tasks/backend/facade/exceptions.py
new file mode 100644
index 000000000000..1498089c9988
--- /dev/null
+++ b/products/tasks/backend/facade/exceptions.py
@@ -0,0 +1,10 @@
+"""
+Facade re-exports for tasks exceptions that cross the boundary.
+
+``SandboxProvisionError`` is raised by sandbox provisioning and caught by callers (e.g. the
+notebooks API) to surface a typed failure.
+"""
+
+from products.tasks.backend.exceptions import SandboxProvisionError
+
+__all__ = ["SandboxProvisionError"]
diff --git a/products/tasks/backend/facade/file_system.py b/products/tasks/backend/facade/file_system.py
new file mode 100644
index 000000000000..233fe9850283
--- /dev/null
+++ b/products/tasks/backend/facade/file_system.py
@@ -0,0 +1,14 @@
+"""
+Facade re-export for file-system registry wiring.
+
+Core's file-system "unfiled" sync is a generic registry keyed by model class — it calls
+``model_cls.get_file_system_unfiled(...)`` and ``instance.get_file_system_representation()``
+on each registered ``FileSystemSyncMixin`` model. That dispatch needs the model class
+itself, so ``Task`` crosses the boundary as a class (registry wiring), not as data.
+
+Do NOT use this to query tasks from other products — use ``facade.api`` functions for that.
+"""
+
+from products.tasks.backend.models import Task
+
+__all__ = ["Task"]
diff --git a/products/tasks/backend/facade/max_tools.py b/products/tasks/backend/facade/max_tools.py
new file mode 100644
index 000000000000..a076299c537d
--- /dev/null
+++ b/products/tasks/backend/facade/max_tools.py
@@ -0,0 +1,26 @@
+"""
+Facade re-exports for the tasks Max tools.
+
+These ``MaxTool`` subclasses are registered into the Max AI toolkit by core. They cross the
+boundary as classes (registry wiring); each tool's implementation stays inside the product.
+"""
+
+from products.tasks.backend.max_tools import (
+ CreateTaskTool,
+ GetTaskRunLogsTool,
+ GetTaskRunTool,
+ ListRepositoriesTool,
+ ListTaskRunsTool,
+ ListTasksTool,
+ RunTaskTool,
+)
+
+__all__ = [
+ "CreateTaskTool",
+ "GetTaskRunLogsTool",
+ "GetTaskRunTool",
+ "ListRepositoriesTool",
+ "ListTaskRunsTool",
+ "ListTasksTool",
+ "RunTaskTool",
+]
diff --git a/products/tasks/backend/facade/metrics.py b/products/tasks/backend/facade/metrics.py
new file mode 100644
index 000000000000..be5dd1178f4e
--- /dev/null
+++ b/products/tasks/backend/facade/metrics.py
@@ -0,0 +1,25 @@
+"""
+Facade re-exports for task-run stream observability.
+
+The SSE stream view records connection lifecycle metrics (open/close/length/resume-gap)
+and labels them by origin product. These are framework-free observability primitives; the
+view imports them from here rather than reaching the internal ``metrics`` module.
+"""
+
+from products.tasks.backend.metrics import (
+ StreamConnectionOutcome,
+ observe_stream_connection_closed,
+ observe_stream_connection_opened,
+ observe_stream_length_on_connect,
+ observe_stream_resume_gap,
+ origin_product_label,
+)
+
+__all__ = [
+ "StreamConnectionOutcome",
+ "observe_stream_connection_closed",
+ "observe_stream_connection_opened",
+ "observe_stream_length_on_connect",
+ "observe_stream_resume_gap",
+ "origin_product_label",
+]
diff --git a/products/tasks/backend/facade/repo_selection.py b/products/tasks/backend/facade/repo_selection.py
new file mode 100644
index 000000000000..8e8746d1a8a1
--- /dev/null
+++ b/products/tasks/backend/facade/repo_selection.py
@@ -0,0 +1,25 @@
+"""
+Facade re-exports for repository selection.
+
+The repo-selection agent picks a GitHub repository for a task given free-text context. Its
+result type and errors are framework-free; other products call ``select_repository`` and
+handle the typed outcomes.
+"""
+
+from products.tasks.backend.logic.repo_selection import (
+ REPO_SELECTION_DUMMY_REPOSITORY,
+ RepoSelectionRejectedError,
+ RepoSelectionResult,
+ RepoSelectionUnavailableError,
+ resolve_team_github_integration,
+ select_repository,
+)
+
+__all__ = [
+ "REPO_SELECTION_DUMMY_REPOSITORY",
+ "RepoSelectionRejectedError",
+ "RepoSelectionResult",
+ "RepoSelectionUnavailableError",
+ "resolve_team_github_integration",
+ "select_repository",
+]
diff --git a/products/tasks/backend/facade/run_config.py b/products/tasks/backend/facade/run_config.py
new file mode 100644
index 000000000000..17b3edb9fe47
--- /dev/null
+++ b/products/tasks/backend/facade/run_config.py
@@ -0,0 +1,45 @@
+"""
+Facade re-exports for task-run configuration value types.
+
+These are the framework-free enums, constants, and pure parse/validation helpers that
+describe how a run is configured (runtime adapter, provider, authorship mode, run source,
+permission mode, reasoning effort). Presentation imports them from here for serializer field
+choices and request validation rather than reaching the internal ``constants`` /
+``temporal.process_task.utils`` modules. ORM-touching helpers (github-integration resolution,
+token caching, pr-authorship inference off a Task) are deliberately NOT exposed — those are
+absorbed into the run-lifecycle facade functions in ``api.py``.
+"""
+
+from products.tasks.backend.constants import (
+ ALL_INITIAL_PERMISSION_MODE_CHOICES,
+ CODEX_INITIAL_PERMISSION_MODE_CHOICES,
+ INITIAL_PERMISSION_MODE_CHOICES,
+)
+from products.tasks.backend.temporal.process_task.utils import (
+ PUBLIC_REASONING_EFFORTS,
+ GitHubCredentialSource,
+ LLMProvider,
+ PrAuthorshipMode,
+ RunSource,
+ RunState,
+ RuntimeAdapter,
+ get_provider_for_runtime_adapter,
+ get_reasoning_effort_error,
+ parse_run_state,
+)
+
+__all__ = [
+ "ALL_INITIAL_PERMISSION_MODE_CHOICES",
+ "CODEX_INITIAL_PERMISSION_MODE_CHOICES",
+ "INITIAL_PERMISSION_MODE_CHOICES",
+ "PUBLIC_REASONING_EFFORTS",
+ "GitHubCredentialSource",
+ "LLMProvider",
+ "PrAuthorshipMode",
+ "RunSource",
+ "RunState",
+ "RuntimeAdapter",
+ "get_provider_for_runtime_adapter",
+ "get_reasoning_effort_error",
+ "parse_run_state",
+]
diff --git a/products/tasks/backend/facade/sandbox.py b/products/tasks/backend/facade/sandbox.py
new file mode 100644
index 000000000000..63048b81a9ff
--- /dev/null
+++ b/products/tasks/backend/facade/sandbox.py
@@ -0,0 +1,32 @@
+"""
+Facade re-exports for the sandbox execution surface.
+
+These are behavioral primitives (abstract base class + config/value types + factory
+functions), not data — other products construct and drive sandboxes through them. They
+cross the boundary as objects, per the wiring pattern. Kept out of ``facade/api.py`` so the
+heavy docker/modal dependencies stay off the light data-surface import path.
+"""
+
+from products.tasks.backend.logic.services.sandbox import (
+ SandboxBase,
+ SandboxClass,
+ SandboxConfig,
+ SandboxResources,
+ SandboxStatus,
+ SandboxTemplate,
+ get_sandbox_class,
+ get_sandbox_class_for_backend,
+ is_public_sandbox_repo,
+)
+
+__all__ = [
+ "SandboxBase",
+ "SandboxClass",
+ "SandboxConfig",
+ "SandboxResources",
+ "SandboxStatus",
+ "SandboxTemplate",
+ "get_sandbox_class",
+ "get_sandbox_class_for_backend",
+ "is_public_sandbox_repo",
+]
diff --git a/products/tasks/backend/facade/streams.py b/products/tasks/backend/facade/streams.py
new file mode 100644
index 000000000000..aaccea943072
--- /dev/null
+++ b/products/tasks/backend/facade/streams.py
@@ -0,0 +1,32 @@
+"""
+Facade re-exports for the task-run event stream.
+
+The Redis stream primitives and the ASGI ingest handler are behavioral wiring: core's ASGI
+app mounts the ingest handler, and Max's sandbox mode reads a run's live stream through the
+stream client. The SSE stream view also reads the connection-wait tuning constants and the
+dedicated-stream flag helper from here.
+"""
+
+from products.tasks.backend.logic.stream.event_ingest import handle_task_run_event_ingest
+from products.tasks.backend.logic.stream.redis_stream import (
+ TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
+ TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,
+ TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
+ TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS,
+ TaskRunRedisStream,
+ TaskRunStreamError,
+ get_task_run_stream_key,
+)
+from products.tasks.backend.redis import run_uses_dedicated_stream
+
+__all__ = [
+ "TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS",
+ "TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS",
+ "TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS",
+ "TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS",
+ "TaskRunRedisStream",
+ "TaskRunStreamError",
+ "get_task_run_stream_key",
+ "handle_task_run_event_ingest",
+ "run_uses_dedicated_stream",
+]
diff --git a/products/tasks/backend/facade/temporal.py b/products/tasks/backend/facade/temporal.py
new file mode 100644
index 000000000000..3d56d649977c
--- /dev/null
+++ b/products/tasks/backend/facade/temporal.py
@@ -0,0 +1,41 @@
+"""
+Facade re-exports for the tasks Temporal surface.
+
+Wiring that core registers and dispatches on, as objects: the worker registers
+``WORKFLOWS``/``ACTIVITIES`` and the workflow class, the common worker reads the histogram
+metric config, the schedule bootstrap creates the code-workstreams schedule, and callers
+trigger a run via ``execute_task_processing_workflow``. Isolated from ``facade/api.py`` so
+``temporalio`` never lands on the light data-surface import path.
+"""
+
+from products.tasks.backend.temporal import ACTIVITIES, WORKFLOWS
+from products.tasks.backend.temporal.client import (
+ execute_posthog_code_agent_relay_workflow,
+ execute_task_processing_workflow,
+ execute_task_processing_workflow_async,
+ resume_task_in_cloud_workflow,
+ signal_task_followup_message,
+)
+from products.tasks.backend.temporal.code_workstreams.schedule import create_evaluate_code_workstreams_schedule
+from products.tasks.backend.temporal.metrics import TASKS_LATENCY_HISTOGRAM_BUCKETS, TASKS_LATENCY_HISTOGRAM_METRICS
+from products.tasks.backend.temporal.process_task.activities.post_slack_update import (
+ PostSlackUpdateInput,
+ post_slack_update,
+)
+from products.tasks.backend.temporal.process_task.workflow import ProcessTaskWorkflow
+
+__all__ = [
+ "ACTIVITIES",
+ "TASKS_LATENCY_HISTOGRAM_BUCKETS",
+ "TASKS_LATENCY_HISTOGRAM_METRICS",
+ "WORKFLOWS",
+ "PostSlackUpdateInput",
+ "ProcessTaskWorkflow",
+ "create_evaluate_code_workstreams_schedule",
+ "execute_posthog_code_agent_relay_workflow",
+ "execute_task_processing_workflow",
+ "execute_task_processing_workflow_async",
+ "post_slack_update",
+ "resume_task_in_cloud_workflow",
+ "signal_task_followup_message",
+]
diff --git a/products/tasks/backend/facade/webhooks.py b/products/tasks/backend/facade/webhooks.py
new file mode 100644
index 000000000000..4d8f3ccbe0fb
--- /dev/null
+++ b/products/tasks/backend/facade/webhooks.py
@@ -0,0 +1,18 @@
+"""
+Facade re-exports for the GitHub webhook handlers.
+
+Core's unified GitHub webhook view dispatches to these: it verifies the signature on every
+POST and routes pull-request events to the tasks handler.
+"""
+
+from products.tasks.backend.webhooks import (
+ get_github_webhook_secret,
+ handle_pull_request_event,
+ verify_github_signature,
+)
+
+__all__ = [
+ "get_github_webhook_secret",
+ "handle_pull_request_event",
+ "verify_github_signature",
+]
diff --git a/products/tasks/backend/logic/__init__.py b/products/tasks/backend/logic/__init__.py
new file mode 100644
index 000000000000..f6384fbb24bc
--- /dev/null
+++ b/products/tasks/backend/logic/__init__.py
@@ -0,0 +1 @@
+"""Internal business logic for the tasks product (sealed behind backend/facade)."""
diff --git a/products/tasks/backend/services/__init__.py b/products/tasks/backend/logic/code_workstreams/__init__.py
similarity index 100%
rename from products/tasks/backend/services/__init__.py
rename to products/tasks/backend/logic/code_workstreams/__init__.py
diff --git a/products/tasks/backend/code_workstreams/classify.py b/products/tasks/backend/logic/code_workstreams/classify.py
similarity index 100%
rename from products/tasks/backend/code_workstreams/classify.py
rename to products/tasks/backend/logic/code_workstreams/classify.py
diff --git a/products/tasks/backend/code_workstreams/default_workflow.py b/products/tasks/backend/logic/code_workstreams/default_workflow.py
similarity index 100%
rename from products/tasks/backend/code_workstreams/default_workflow.py
rename to products/tasks/backend/logic/code_workstreams/default_workflow.py
diff --git a/products/tasks/backend/code_workstreams/grouping.py b/products/tasks/backend/logic/code_workstreams/grouping.py
similarity index 100%
rename from products/tasks/backend/code_workstreams/grouping.py
rename to products/tasks/backend/logic/code_workstreams/grouping.py
diff --git a/products/tasks/backend/code_workstreams/situations.py b/products/tasks/backend/logic/code_workstreams/situations.py
similarity index 100%
rename from products/tasks/backend/code_workstreams/situations.py
rename to products/tasks/backend/logic/code_workstreams/situations.py
diff --git a/products/tasks/backend/code_workstreams/test_classify.py b/products/tasks/backend/logic/code_workstreams/test_classify.py
similarity index 97%
rename from products/tasks/backend/code_workstreams/test_classify.py
rename to products/tasks/backend/logic/code_workstreams/test_classify.py
index 2d2d52d4d558..75243ae6856d 100644
--- a/products/tasks/backend/code_workstreams/test_classify.py
+++ b/products/tasks/backend/logic/code_workstreams/test_classify.py
@@ -2,7 +2,7 @@ from dataclasses import replace
import pytest
-from products.tasks.backend.code_workstreams.classify import (
+from products.tasks.backend.logic.code_workstreams.classify import (
STALE_THRESHOLD_MS,
ClassifyInput,
ClassifyPr,
diff --git a/products/tasks/backend/code_workstreams/test_grouping.py b/products/tasks/backend/logic/code_workstreams/test_grouping.py
similarity index 98%
rename from products/tasks/backend/code_workstreams/test_grouping.py
rename to products/tasks/backend/logic/code_workstreams/test_grouping.py
index c1221ad3653c..8515323d9480 100644
--- a/products/tasks/backend/code_workstreams/test_grouping.py
+++ b/products/tasks/backend/logic/code_workstreams/test_grouping.py
@@ -2,8 +2,8 @@ from dataclasses import replace
import pytest
-from products.tasks.backend.code_workstreams.classify import STALE_THRESHOLD_MS
-from products.tasks.backend.code_workstreams.grouping import (
+from products.tasks.backend.logic.code_workstreams.classify import STALE_THRESHOLD_MS
+from products.tasks.backend.logic.code_workstreams.grouping import (
RUNNING_STALE_THRESHOLD_MS,
PrInput,
TaskInput,
diff --git a/products/tasks/backend/code_workstreams/test_validation.py b/products/tasks/backend/logic/code_workstreams/test_validation.py
similarity index 87%
rename from products/tasks/backend/code_workstreams/test_validation.py
rename to products/tasks/backend/logic/code_workstreams/test_validation.py
index 0ff881e71370..abec6abceff8 100644
--- a/products/tasks/backend/code_workstreams/test_validation.py
+++ b/products/tasks/backend/logic/code_workstreams/test_validation.py
@@ -1,6 +1,6 @@
-from products.tasks.backend.code_workstreams.default_workflow import build_default_bindings
-from products.tasks.backend.code_workstreams.situations import SITUATION_IDS
-from products.tasks.backend.code_workstreams.validation import validate_bindings
+from products.tasks.backend.logic.code_workstreams.default_workflow import build_default_bindings
+from products.tasks.backend.logic.code_workstreams.situations import SITUATION_IDS
+from products.tasks.backend.logic.code_workstreams.validation import validate_bindings
def test_default_bindings_cover_every_situation():
diff --git a/products/tasks/backend/code_workstreams/validation.py b/products/tasks/backend/logic/code_workstreams/validation.py
similarity index 100%
rename from products/tasks/backend/code_workstreams/validation.py
rename to products/tasks/backend/logic/code_workstreams/validation.py
diff --git a/products/tasks/backend/repo_selection/__init__.py b/products/tasks/backend/logic/repo_selection/__init__.py
similarity index 86%
rename from products/tasks/backend/repo_selection/__init__.py
rename to products/tasks/backend/logic/repo_selection/__init__.py
index 3fde370a698e..736e79d94dc5 100644
--- a/products/tasks/backend/repo_selection/__init__.py
+++ b/products/tasks/backend/logic/repo_selection/__init__.py
@@ -1,4 +1,4 @@
-from products.tasks.backend.repo_selection.agent import (
+from products.tasks.backend.logic.repo_selection.agent import (
REPO_SELECTION_DUMMY_REPOSITORY,
RepoSelectionRejectedError,
RepoSelectionResult,
diff --git a/products/tasks/backend/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
similarity index 97%
rename from products/tasks/backend/repo_selection/agent.py
rename to products/tasks/backend/logic/repo_selection/agent.py
index 0421ccd0d6d2..f829e25a5700 100644
--- a/products/tasks/backend/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -14,13 +14,13 @@ from posthog.models.team.team import Team
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.sync import database_sync_to_async
+from products.tasks.backend.logic.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import MultiTurnSession
+from products.tasks.backend.logic.services.sandbox import SandboxResources
from products.tasks.backend.models import Task
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
-from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
-from products.tasks.backend.services.sandbox import SandboxResources
if TYPE_CHECKING:
- from products.tasks.backend.services.custom_prompt_internals import OutputFn
+ from products.tasks.backend.logic.services.custom_prompt_internals import OutputFn
logger = logging.getLogger(__name__)
diff --git a/products/tasks/backend/services/tests/__init__.py b/products/tasks/backend/logic/services/__init__.py
similarity index 100%
rename from products/tasks/backend/services/tests/__init__.py
rename to products/tasks/backend/logic/services/__init__.py
diff --git a/products/tasks/backend/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.py
similarity index 100%
rename from products/tasks/backend/services/agent_command.py
rename to products/tasks/backend/logic/services/agent_command.py
diff --git a/products/tasks/backend/services/agentsh.py b/products/tasks/backend/logic/services/agentsh.py
similarity index 100%
rename from products/tasks/backend/services/agentsh.py
rename to products/tasks/backend/logic/services/agentsh.py
diff --git a/products/tasks/backend/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.py
similarity index 98%
rename from products/tasks/backend/services/code_usage_gate.py
rename to products/tasks/backend/logic/services/code_usage_gate.py
index 85fd18658f80..88d5354c4ad5 100644
--- a/products/tasks/backend/services/code_usage_gate.py
+++ b/products/tasks/backend/logic/services/code_usage_gate.py
@@ -12,7 +12,7 @@ from posthog.models import OAuthAccessToken
from posthog.temporal.oauth import create_oauth_access_token_for_user
from posthog.utils import get_instance_region
-from products.tasks.backend.serializers import TaskRunErrorResponseSerializer
+from products.tasks.backend.presentation.serializers import TaskRunErrorResponseSerializer
logger = logging.getLogger(__name__)
diff --git a/products/tasks/backend/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.py
similarity index 98%
rename from products/tasks/backend/services/connection_token.py
rename to products/tasks/backend/logic/services/connection_token.py
index 40be7cd23833..98f3fc6c63fb 100644
--- a/products/tasks/backend/services/connection_token.py
+++ b/products/tasks/backend/logic/services/connection_token.py
@@ -12,7 +12,7 @@ import jwt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
-from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS
+from products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDS
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
diff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
similarity index 99%
rename from products/tasks/backend/services/custom_prompt_internals.py
rename to products/tasks/backend/logic/services/custom_prompt_internals.py
index 279d5a0472cf..3b32665025ee 100644
--- a/products/tasks/backend/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -20,7 +20,7 @@ from products.tasks.backend.models import Task, TaskRun
if TYPE_CHECKING:
from temporalio.client import WorkflowHandle
- from products.tasks.backend.services.sandbox import SandboxResources
+ from products.tasks.backend.logic.services.sandbox import SandboxResources
logger = logging.getLogger(__name__)
diff --git a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
similarity index 99%
rename from products/tasks/backend/services/custom_prompt_multi_turn_runner.py
rename to products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
index c63c4b9c8037..43ca16bdea22 100644
--- a/products/tasks/backend/services/custom_prompt_multi_turn_runner.py
+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
@@ -15,7 +15,7 @@ if TYPE_CHECKING:
from temporalio.client import WorkflowHandle
from posthog.temporal.common.client import async_connect
-from products.tasks.backend.services.custom_prompt_internals import (
+from products.tasks.backend.logic.services.custom_prompt_internals import (
CustomPromptSandboxContext,
EmptyAgentTurnError,
OutputFn,
diff --git a/products/tasks/backend/services/dev_sandbox_context.py b/products/tasks/backend/logic/services/dev_sandbox_context.py
similarity index 93%
rename from products/tasks/backend/services/dev_sandbox_context.py
rename to products/tasks/backend/logic/services/dev_sandbox_context.py
index 80ca3831f350..5b09c5056a14 100644
--- a/products/tasks/backend/services/dev_sandbox_context.py
+++ b/products/tasks/backend/logic/services/dev_sandbox_context.py
@@ -4,7 +4,7 @@ from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.logic.services.custom_prompt_internals import CustomPromptSandboxContext
def resolve_sandbox_context_for_local_dev(repository: str) -> CustomPromptSandboxContext:
diff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
similarity index 100%
rename from products/tasks/backend/services/docker_sandbox.py
rename to products/tasks/backend/logic/services/docker_sandbox.py
diff --git a/products/tasks/backend/services/local_packages.py b/products/tasks/backend/logic/services/local_packages.py
similarity index 100%
rename from products/tasks/backend/services/local_packages.py
rename to products/tasks/backend/logic/services/local_packages.py
diff --git a/products/tasks/backend/services/local_skills.py b/products/tasks/backend/logic/services/local_skills.py
similarity index 100%
rename from products/tasks/backend/services/local_skills.py
rename to products/tasks/backend/logic/services/local_skills.py
diff --git a/products/tasks/backend/services/modal_provision_diagnostics.py b/products/tasks/backend/logic/services/modal_provision_diagnostics.py
similarity index 100%
rename from products/tasks/backend/services/modal_provision_diagnostics.py
rename to products/tasks/backend/logic/services/modal_provision_diagnostics.py
diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
similarity index 99%
rename from products/tasks/backend/services/modal_sandbox.py
rename to products/tasks/backend/logic/services/modal_sandbox.py
index 02c9f1c214d1..8f9b3665506b 100644
--- a/products/tasks/backend/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -36,8 +36,7 @@ from products.tasks.backend.exceptions import (
SandboxTimeoutError,
SnapshotCreationError,
)
-from products.tasks.backend.models import SandboxSnapshot
-from products.tasks.backend.services.agentsh import (
+from products.tasks.backend.logic.services.agentsh import (
AGENTSH_DAEMON_PORT,
BASH_ENV_SCRIPT,
ENV_FILE,
@@ -50,24 +49,25 @@ from products.tasks.backend.services.agentsh import (
generate_env_wrapper,
generate_policy_yaml,
)
-from products.tasks.backend.services.local_packages import get_local_posthog_code_packages
-from products.tasks.backend.services.local_skills import (
+from products.tasks.backend.logic.services.local_packages import get_local_posthog_code_packages
+from products.tasks.backend.logic.services.local_skills import (
BUILT_SKILLS_RELATIVE_PATH as LOCAL_BUILT_SKILLS_PATH,
LocalSkillsCache,
populate_skills_directory,
)
-from products.tasks.backend.services.modal_provision_diagnostics import (
+from products.tasks.backend.logic.services.modal_provision_diagnostics import (
SandboxProvisionDiagnostics,
capture_modal_output_if_debug,
summarize_modal_output,
)
-from products.tasks.backend.services.sandbox import (
+from products.tasks.backend.logic.services.sandbox import (
WORKING_DIR,
SandboxBase,
build_agent_runtime_env_prefix,
redact_sandbox_command,
wait_for_health_check,
)
+from products.tasks.backend.models import SandboxSnapshot
from .sandbox import AgentServerResult, ExecutionResult, ExecutionStream, SandboxConfig, SandboxStatus, SandboxTemplate
diff --git a/products/tasks/backend/services/mts_example/README.md b/products/tasks/backend/logic/services/mts_example/README.md
similarity index 100%
rename from products/tasks/backend/services/mts_example/README.md
rename to products/tasks/backend/logic/services/mts_example/README.md
diff --git a/products/tasks/backend/logic/services/mts_example/__init__.py b/products/tasks/backend/logic/services/mts_example/__init__.py
new file mode 100644
index 000000000000..e0fb39e8751d
--- /dev/null
+++ b/products/tasks/backend/logic/services/mts_example/__init__.py
@@ -0,0 +1,8 @@
+from products.tasks.backend.logic.services.mts_example.runner import run_cursed_identifier_research
+from products.tasks.backend.logic.services.mts_example.schemas import CursedItem, CursedItemCandidates
+
+__all__ = [
+ "CursedItem",
+ "CursedItemCandidates",
+ "run_cursed_identifier_research",
+]
diff --git a/products/tasks/backend/services/mts_example/prompts.py b/products/tasks/backend/logic/services/mts_example/prompts.py
similarity index 98%
rename from products/tasks/backend/services/mts_example/prompts.py
rename to products/tasks/backend/logic/services/mts_example/prompts.py
index 7045aa4253dc..d0535a3f0b47 100644
--- a/products/tasks/backend/services/mts_example/prompts.py
+++ b/products/tasks/backend/logic/services/mts_example/prompts.py
@@ -8,7 +8,7 @@ from products.signals.backend.report_generation.research import (
ReportPresentationOutput,
SignalFinding,
)
-from products.tasks.backend.services.mts_example.schemas import CursedItemCandidates
+from products.tasks.backend.logic.services.mts_example.schemas import CursedItemCandidates
_PREAMBLE = """You are an agent surfacing cursed code — the worst-named identifiers and the ugliest stale comments — inside the PostHog/posthog repository.
Your job is to discover a small set of genuinely cursed items, then research each one thoroughly enough that a downstream coding agent could act on it (rename, delete, document).
diff --git a/products/tasks/backend/services/mts_example/runner.py b/products/tasks/backend/logic/services/mts_example/runner.py
similarity index 91%
rename from products/tasks/backend/services/mts_example/runner.py
rename to products/tasks/backend/logic/services/mts_example/runner.py
index 434a29283f08..6bdb8a75bafd 100644
--- a/products/tasks/backend/services/mts_example/runner.py
+++ b/products/tasks/backend/logic/services/mts_example/runner.py
@@ -11,16 +11,16 @@ from products.signals.backend.report_generation.research import (
ReportResearchOutput,
SignalFinding,
)
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext, OutputFn
-from products.tasks.backend.services.custom_prompt_multi_turn_runner import MultiTurnSession
-from products.tasks.backend.services.mts_example.prompts import (
+from products.tasks.backend.logic.services.custom_prompt_internals import CustomPromptSandboxContext, OutputFn
+from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import MultiTurnSession
+from products.tasks.backend.logic.services.mts_example.prompts import (
build_actionability_prompt,
build_discovery_prompt,
build_presentation_prompt,
build_priority_prompt,
build_research_prompt,
)
-from products.tasks.backend.services.mts_example.schemas import CursedItemCandidates
+from products.tasks.backend.logic.services.mts_example.schemas import CursedItemCandidates
logger = logging.getLogger(__name__)
diff --git a/products/tasks/backend/services/mts_example/schemas.py b/products/tasks/backend/logic/services/mts_example/schemas.py
similarity index 100%
rename from products/tasks/backend/services/mts_example/schemas.py
rename to products/tasks/backend/logic/services/mts_example/schemas.py
diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
similarity index 99%
rename from products/tasks/backend/services/sandbox.py
rename to products/tasks/backend/logic/services/sandbox.py
index 0f5afeb96cb1..96aae84e1518 100644
--- a/products/tasks/backend/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -26,7 +26,7 @@ from django.conf import settings
import structlog
from pydantic import BaseModel
-from products.tasks.backend.services.sandbox_config import (
+from products.tasks.backend.logic.services.sandbox_config import (
BURSTABLE_REQUEST_CPU_CORES,
BURSTABLE_REQUEST_MEMORY_MB,
SANDBOX_TTL_SECONDS,
diff --git a/products/tasks/backend/services/sandbox_config.py b/products/tasks/backend/logic/services/sandbox_config.py
similarity index 100%
rename from products/tasks/backend/services/sandbox_config.py
rename to products/tasks/backend/logic/services/sandbox_config.py
diff --git a/products/tasks/backend/services/staged_artifacts.py b/products/tasks/backend/logic/services/staged_artifacts.py
similarity index 100%
rename from products/tasks/backend/services/staged_artifacts.py
rename to products/tasks/backend/logic/services/staged_artifacts.py
diff --git a/products/tasks/backend/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.py
similarity index 93%
rename from products/tasks/backend/services/test_docker_sandbox.py
rename to products/tasks/backend/logic/services/test_docker_sandbox.py
index 4dc232c28f67..8fc0e80dc34d 100644
--- a/products/tasks/backend/services/test_docker_sandbox.py
+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py
@@ -6,8 +6,8 @@ import pytest
from unittest.mock import MagicMock, patch
from products.tasks.backend.exceptions import SandboxExecutionError
-from products.tasks.backend.services.docker_sandbox import DockerSandbox
-from products.tasks.backend.services.sandbox import (
+from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
+from products.tasks.backend.logic.services.sandbox import (
ExecutionResult,
SandboxConfig,
SandboxStatus,
@@ -47,7 +47,7 @@ def is_ci() -> bool:
class TestSandboxFactory:
"""Tests for sandbox factory and production safety."""
- @patch("products.tasks.backend.services.sandbox.settings")
+ @patch("products.tasks.backend.logic.services.sandbox.settings")
def test_docker_sandbox_blocked_in_production(self, mock_settings):
mock_settings.SANDBOX_PROVIDER = "docker"
mock_settings.DEBUG = False
@@ -55,7 +55,7 @@ class TestSandboxFactory:
with pytest.raises(RuntimeError, match="DockerSandbox cannot be used in production"):
get_sandbox_class()
- @patch("products.tasks.backend.services.sandbox.settings")
+ @patch("products.tasks.backend.logic.services.sandbox.settings")
def test_docker_sandbox_opt_in_with_debug(self, mock_settings):
mock_settings.SANDBOX_PROVIDER = "docker"
mock_settings.DEBUG = True
@@ -63,22 +63,22 @@ class TestSandboxFactory:
sandbox_class = get_sandbox_class()
assert sandbox_class == DockerSandbox
- @patch("products.tasks.backend.services.sandbox.settings")
+ @patch("products.tasks.backend.logic.services.sandbox.settings")
def test_modal_sandbox_default_in_debug(self, mock_settings):
mock_settings.SANDBOX_PROVIDER = None
mock_settings.DEBUG = True
- from products.tasks.backend.services.modal_sandbox import ModalSandbox
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
sandbox_class = get_sandbox_class()
assert sandbox_class == ModalSandbox
- @patch("products.tasks.backend.services.sandbox.settings")
+ @patch("products.tasks.backend.logic.services.sandbox.settings")
def test_modal_sandbox_default_in_production(self, mock_settings):
mock_settings.SANDBOX_PROVIDER = None
mock_settings.DEBUG = False
- from products.tasks.backend.services.modal_sandbox import ModalSandbox
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
sandbox_class = get_sandbox_class()
assert sandbox_class == ModalSandbox
@@ -116,8 +116,8 @@ class TestDockerSandboxUnit:
result = DockerSandbox._transform_url_for_docker(input_url)
assert result == expected_url
- @patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
- @patch("products.tasks.backend.services.docker_sandbox.os.path.exists")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.os.path.exists")
def test_create_transforms_posthog_api_url(self, mock_exists, mock_run):
mock_exists.return_value = False
mock_run.return_value = MagicMock(stdout="abc123container", returncode=0)
@@ -141,8 +141,8 @@ class TestDockerSandboxUnit:
assert "POSTHOG_API_URL=http://host.docker.internal:8000" in env_args
assert "POSTHOG_PROJECT_ID=1" in env_args
- @patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
- @patch("products.tasks.backend.services.docker_sandbox.os.path.exists")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.os.path.exists")
def test_create_transforms_callback_url_env_vars(self, mock_exists, mock_run):
# Streamlit sandboxes call back to PostHog via POSTHOG_SITE_URL and the
# OTEL endpoint. Inside Docker, localhost is the container itself, so
@@ -170,7 +170,7 @@ class TestDockerSandboxUnit:
# Non-URL env vars must pass through untouched.
assert "POSTHOG_TEAM_ID=1" in env_args
- @patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")
def test_get_status_running(self, mock_run):
mock_run.return_value = MagicMock(stdout="true", returncode=0)
@@ -182,7 +182,7 @@ class TestDockerSandboxUnit:
assert sandbox.get_status() == SandboxStatus.RUNNING
assert sandbox.is_running()
- @patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")
def test_get_status_shutdown(self, mock_run):
mock_run.return_value = MagicMock(stdout="false", returncode=0)
@@ -194,7 +194,7 @@ class TestDockerSandboxUnit:
assert sandbox.get_status() == SandboxStatus.SHUTDOWN
assert not sandbox.is_running()
- @patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")
def test_execute_returns_result(self, mock_run):
mock_run.side_effect = [
MagicMock(stdout="true", returncode=0), # is_running check
@@ -212,7 +212,7 @@ class TestDockerSandboxUnit:
assert result.stdout == "hello world"
assert result.stderr == ""
- @patch("products.tasks.backend.services.docker_sandbox.DockerSandbox._run")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.DockerSandbox._run")
def test_execute_redacts_event_ingest_token_from_error_context(self, mock_run):
mock_run.side_effect = [
MagicMock(stdout="true", returncode=0),
@@ -372,7 +372,7 @@ class TestDockerSandboxUnit:
sandbox.clone_repository("PostHog/posthog", github_token="tok")
mock_execute.assert_called_once()
- @patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
+ @patch("products.tasks.backend.logic.services.docker_sandbox.subprocess.run")
def test_create_adds_volume_mounts(self, mock_run, tmp_path):
mock_run.return_value = MagicMock(stdout="abc123container", returncode=0)
@@ -469,11 +469,11 @@ class TestDockerSandboxUnit:
with (
patch(
- "products.tasks.backend.services.docker_sandbox.generate_config_yaml", return_value="config"
+ "products.tasks.backend.logic.services.docker_sandbox.generate_config_yaml", return_value="config"
) as mock_config,
- patch("products.tasks.backend.services.docker_sandbox.generate_policy_yaml", return_value="policy"),
- patch("products.tasks.backend.services.docker_sandbox.generate_env_wrapper", return_value="wrapper"),
- patch("products.tasks.backend.services.docker_sandbox.build_setup_script", return_value="setup"),
+ patch("products.tasks.backend.logic.services.docker_sandbox.generate_policy_yaml", return_value="policy"),
+ patch("products.tasks.backend.logic.services.docker_sandbox.generate_env_wrapper", return_value="wrapper"),
+ patch("products.tasks.backend.logic.services.docker_sandbox.build_setup_script", return_value="setup"),
patch.object(sandbox, "write_file") as mock_write_file,
patch.object(sandbox, "execute") as mock_execute,
):
diff --git a/products/tasks/backend/services/test_local_skills.py b/products/tasks/backend/logic/services/test_local_skills.py
similarity index 99%
rename from products/tasks/backend/services/test_local_skills.py
rename to products/tasks/backend/logic/services/test_local_skills.py
index bf707920003b..a03f73b466fb 100644
--- a/products/tasks/backend/services/test_local_skills.py
+++ b/products/tasks/backend/logic/services/test_local_skills.py
@@ -6,7 +6,7 @@ from pathlib import Path
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
-from products.tasks.backend.services.local_skills import (
+from products.tasks.backend.logic.services.local_skills import (
BUILD_HASH_FILENAME,
BUILT_SKILLS_RELATIVE_PATH,
LocalSkillsCache,
diff --git a/products/tasks/backend/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.py
similarity index 84%
rename from products/tasks/backend/services/test_modal_sandbox.py
rename to products/tasks/backend/logic/services/test_modal_sandbox.py
index c690b9cb9b59..08641dcb5083 100644
--- a/products/tasks/backend/services/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py
@@ -1,8 +1,8 @@
import pytest
from unittest.mock import MagicMock
-from products.tasks.backend.services.modal_sandbox import ModalSandbox
-from products.tasks.backend.services.sandbox import SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
+from products.tasks.backend.logic.services.sandbox import SandboxConfig, SandboxTemplate
@pytest.fixture
@@ -12,7 +12,7 @@ def patched_modal(mocker):
mocker.patch.object(ModalSandbox, "_get_app_for_template", return_value=MagicMock())
mocker.patch(
- "products.tasks.backend.services.modal_sandbox._get_template_image",
+ "products.tasks.backend.logic.services.modal_sandbox._get_template_image",
return_value=MagicMock(),
)
create = mocker.patch("modal.Sandbox.create", return_value=fake_sandbox)
diff --git a/products/tasks/backend/services/test_sandbox.py b/products/tasks/backend/logic/services/test_sandbox.py
similarity index 96%
rename from products/tasks/backend/services/test_sandbox.py
rename to products/tasks/backend/logic/services/test_sandbox.py
index 77a224a6ba2a..8eab228cf0ab 100644
--- a/products/tasks/backend/services/test_sandbox.py
+++ b/products/tasks/backend/logic/services/test_sandbox.py
@@ -2,7 +2,7 @@ import os
import pytest
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxStatus, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxStatus, SandboxTemplate
class TestSandboxIntegration:
diff --git a/products/tasks/backend/services/test_title_generator.py b/products/tasks/backend/logic/services/test_title_generator.py
similarity index 97%
rename from products/tasks/backend/services/test_title_generator.py
rename to products/tasks/backend/logic/services/test_title_generator.py
index 8a3ee949b0e9..434e263b6869 100644
--- a/products/tasks/backend/services/test_title_generator.py
+++ b/products/tasks/backend/logic/services/test_title_generator.py
@@ -2,7 +2,7 @@ import pytest
from unittest.mock import MagicMock, patch
from products.ai_observability.backend.llm.types import StreamChunk
-from products.tasks.backend.services.title_generator import _fallback_title, generate_task_title
+from products.tasks.backend.logic.services.title_generator import _fallback_title, generate_task_title
class TestTitleGenerator:
diff --git a/products/tasks/backend/stream/__init__.py b/products/tasks/backend/logic/services/tests/__init__.py
similarity index 100%
rename from products/tasks/backend/stream/__init__.py
rename to products/tasks/backend/logic/services/tests/__init__.py
diff --git a/products/tasks/backend/services/tests/test_agent_command.py b/products/tasks/backend/logic/services/tests/test_agent_command.py
similarity index 84%
rename from products/tasks/backend/services/tests/test_agent_command.py
rename to products/tasks/backend/logic/services/tests/test_agent_command.py
index ec630f6ea81b..47ca0a97f9f3 100644
--- a/products/tasks/backend/services/tests/test_agent_command.py
+++ b/products/tasks/backend/logic/services/tests/test_agent_command.py
@@ -5,7 +5,7 @@ from django.test import override_settings
import requests
-from products.tasks.backend.services.agent_command import (
+from products.tasks.backend.logic.services.agent_command import (
REFRESH_SESSION_METHOD,
REFRESH_TIMEOUT_SECONDS,
CommandResult,
@@ -59,7 +59,7 @@ class TestValidateSandboxUrl:
],
ids=["loopback", "class_a_private", "class_b_private", "class_c_private"],
)
- @patch("products.tasks.backend.services.agent_command.socket.getaddrinfo")
+ @patch("products.tasks.backend.logic.services.agent_command.socket.getaddrinfo")
def test_ssrf_blocked_private_ips(self, mock_getaddrinfo, hostname):
mock_getaddrinfo.return_value = [
(2, 1, 6, "", (hostname, 443)),
@@ -68,7 +68,7 @@ class TestValidateSandboxUrl:
assert result is not None
assert "blocked range" in result
- @patch("products.tasks.backend.services.agent_command.socket.getaddrinfo")
+ @patch("products.tasks.backend.logic.services.agent_command.socket.getaddrinfo")
def test_ssrf_allows_public_ip(self, mock_getaddrinfo):
mock_getaddrinfo.return_value = [
(2, 1, 6, "", ("52.1.2.3", 443)),
@@ -77,14 +77,14 @@ class TestValidateSandboxUrl:
assert result is None
@override_settings(DEBUG=True)
- @patch("products.tasks.backend.services.agent_command.socket.getaddrinfo")
+ @patch("products.tasks.backend.logic.services.agent_command.socket.getaddrinfo")
def test_localhost_http_allowed_in_debug(self, mock_getaddrinfo):
result = validate_sandbox_url("http://localhost:1234/command")
assert result is None
mock_getaddrinfo.assert_not_called()
@override_settings(DEBUG=True)
- @patch("products.tasks.backend.services.agent_command.socket.getaddrinfo")
+ @patch("products.tasks.backend.logic.services.agent_command.socket.getaddrinfo")
def test_loopback_http_allowed_in_debug(self, mock_getaddrinfo):
result = validate_sandbox_url("http://127.0.0.1:1234/command")
assert result is None
@@ -144,7 +144,7 @@ class TestSendAgentCommand:
assert result.error == "No sandbox URL available"
assert not result.retryable
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url")
def test_ssrf_blocked(self, mock_validate):
mock_validate.return_value = "Address 127.0.0.1 is in blocked range"
task_run = self._make_task_run(sandbox_url="https://evil.local/rpc")
@@ -154,8 +154,8 @@ class TestSendAgentCommand:
assert "validation failed" in error
assert not result.retryable
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_success(self, mock_post, mock_validate):
mock_resp = MagicMock()
mock_resp.status_code = 200
@@ -174,8 +174,8 @@ class TestSendAgentCommand:
assert call_kwargs.kwargs["json"]["method"] == "user_message"
assert call_kwargs.args[0] == "https://sandbox.modal.run/rpc/command"
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_appends_command_path_when_missing_trailing_slash(self, mock_post, mock_validate):
mock_resp = MagicMock()
mock_resp.status_code = 200
@@ -188,8 +188,8 @@ class TestSendAgentCommand:
assert result.success
assert mock_post.call_args.args[0] == "http://localhost:6001/command"
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_tunnel_auth_with_auth_token(self, mock_post, mock_validate):
mock_resp = MagicMock()
mock_resp.status_code = 200
@@ -204,8 +204,8 @@ class TestSendAgentCommand:
assert call_kwargs.kwargs["headers"]["Authorization"] == "Bearer jwt-tok"
assert call_kwargs.kwargs["params"] == {"_modal_connect_token": "modal-tok"}
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_connection_error_is_retryable(self, mock_post, mock_validate):
mock_post.side_effect = requests.ConnectionError("refused")
task_run = self._make_task_run(sandbox_url="https://sandbox.modal.run/rpc")
@@ -214,8 +214,8 @@ class TestSendAgentCommand:
assert result.status_code == 502
assert result.retryable
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_timeout_is_retryable(self, mock_post, mock_validate):
mock_post.side_effect = requests.Timeout("timed out")
task_run = self._make_task_run(sandbox_url="https://sandbox.modal.run/rpc")
@@ -224,8 +224,8 @@ class TestSendAgentCommand:
assert result.status_code == 504
assert result.retryable
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_5xx_is_retryable(self, mock_post, mock_validate):
mock_resp = MagicMock()
mock_resp.status_code = 502
@@ -236,8 +236,8 @@ class TestSendAgentCommand:
assert not result.success
assert result.retryable
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_4xx_is_not_retryable(self, mock_post, mock_validate):
mock_resp = MagicMock()
mock_resp.status_code = 401
@@ -248,8 +248,8 @@ class TestSendAgentCommand:
assert not result.success
assert not result.retryable
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_no_active_session_400_is_retryable(self, mock_post, mock_validate):
mock_resp = MagicMock()
mock_resp.status_code = 400
@@ -262,8 +262,8 @@ class TestSendAgentCommand:
assert result.retryable
assert result.error == "No active session for this run"
- @patch("products.tasks.backend.services.agent_command.validate_sandbox_url", return_value=None)
- @patch("products.tasks.backend.services.agent_command.requests.post")
+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_jsonrpc_error_in_200_response_is_detected(self, mock_post, mock_validate):
mock_resp = MagicMock()
mock_resp.status_code = 200
@@ -282,7 +282,7 @@ class TestSendAgentCommand:
class TestSendUserMessage:
- @patch("products.tasks.backend.services.agent_command.send_agent_command")
+ @patch("products.tasks.backend.logic.services.agent_command.send_agent_command")
@pytest.mark.parametrize(
"message,artifacts,expected_params",
[
@@ -315,7 +315,7 @@ class TestSendUserMessage:
class TestSendCancel:
- @patch("products.tasks.backend.services.agent_command.send_agent_command")
+ @patch("products.tasks.backend.logic.services.agent_command.send_agent_command")
def test_sends_cancel_method(self, mock_send):
mock_send.return_value = CommandResult(success=True, status_code=200)
task_run = MagicMock()
@@ -330,7 +330,7 @@ class TestSendCancel:
class TestSendRefreshSession:
- @patch("products.tasks.backend.services.agent_command.send_agent_command")
+ @patch("products.tasks.backend.logic.services.agent_command.send_agent_command")
def test_sends_refresh_session_method(self, mock_send):
mock_send.return_value = CommandResult(success=True, status_code=200, data={"result": {"refreshed": True}})
task_run = MagicMock()
diff --git a/products/tasks/backend/services/tests/test_local_packages.py b/products/tasks/backend/logic/services/tests/test_local_packages.py
similarity index 94%
rename from products/tasks/backend/services/tests/test_local_packages.py
rename to products/tasks/backend/logic/services/tests/test_local_packages.py
index 06d493b1ecf9..809769c41e0c 100644
--- a/products/tasks/backend/services/tests/test_local_packages.py
+++ b/products/tasks/backend/logic/services/tests/test_local_packages.py
@@ -5,7 +5,7 @@ from pathlib import Path
import pytest
from unittest.mock import patch
-from products.tasks.backend.services.local_packages import (
+from products.tasks.backend.logic.services.local_packages import (
BUILD_OUTPUT_SUBDIR,
PACKAGE_NAMES,
get_local_posthog_code_packages,
@@ -24,7 +24,7 @@ def _populate_monorepo(root: Path, *, with_dist: bool = True, package_names: tup
@contextmanager
def _env(*, debug: bool, monorepo_root: str | None) -> Iterator[None]:
- with patch("products.tasks.backend.services.local_packages.settings") as s:
+ with patch("products.tasks.backend.logic.services.local_packages.settings") as s:
s.DEBUG = debug
env = {"LOCAL_POSTHOG_CODE_MONOREPO_ROOT": monorepo_root or "", "LOCAL_TWIG_MONOREPO_ROOT": ""}
with patch.dict("os.environ", env):
diff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
similarity index 95%
rename from products/tasks/backend/services/tests/test_modal_sandbox.py
rename to products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index 72116c94ede3..5a0af251bcd2 100644
--- a/products/tasks/backend/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -6,11 +6,11 @@ from unittest.mock import MagicMock, patch
from requests.exceptions import ConnectionError, Timeout
from products.tasks.backend.exceptions import SandboxExecutionError, SandboxProvisionError
-from products.tasks.backend.services.modal_provision_diagnostics import (
+from products.tasks.backend.logic.services.modal_provision_diagnostics import (
MAX_PROVISION_LOG_EXCERPT_LINES,
summarize_modal_output,
)
-from products.tasks.backend.services.modal_sandbox import (
+from products.tasks.backend.logic.services.modal_sandbox import (
_GHCR_RESOLVE_MAX_ATTEMPTS,
AGENT_SERVER_PORT,
DEFAULT_MODAL_REGION,
@@ -21,7 +21,7 @@ from products.tasks.backend.services.modal_sandbox import (
_image_ref_cache,
_resource_create_kwargs,
)
-from products.tasks.backend.services.sandbox import AgentServerResult, ExecutionResult, SandboxConfig
+from products.tasks.backend.logic.services.sandbox import AgentServerResult, ExecutionResult, SandboxConfig
def _agent_server_launch_command(mock_execute: Any) -> str:
@@ -80,12 +80,12 @@ class TestGetSandboxImageReference:
@pytest.fixture(autouse=True)
def _no_backoff_sleep(self):
- with patch("products.tasks.backend.services.modal_sandbox.time.sleep"):
+ with patch("products.tasks.backend.logic.services.modal_sandbox.time.sleep"):
yield
def test_returns_digest_reference_on_success(self):
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=[_mock_token_response(), _mock_manifest_response(digest="sha256:abc123")],
):
result = _get_sandbox_image_reference()
@@ -95,7 +95,7 @@ class TestGetSandboxImageReference:
@pytest.mark.parametrize("status_code", [401, 403, 404, 500, 502, 503])
def test_fails_closed_on_token_request_failure(self, status_code: int):
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
return_value=_mock_token_response(status_code=status_code),
) as mock_get:
with pytest.raises(SandboxProvisionError, match="refusing to fall back to the mutable"):
@@ -105,7 +105,7 @@ class TestGetSandboxImageReference:
def test_fails_closed_when_token_missing(self):
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
return_value=_mock_token_response(token=None),
):
with pytest.raises(SandboxProvisionError):
@@ -114,7 +114,7 @@ class TestGetSandboxImageReference:
@pytest.mark.parametrize("status_code", [401, 403, 404, 500, 502, 503])
def test_fails_closed_on_manifest_request_failure(self, status_code: int):
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=_ghcr_side_effect(
token_resp=_mock_token_response(),
manifest_resp=_mock_manifest_response(status_code=status_code),
@@ -125,7 +125,7 @@ class TestGetSandboxImageReference:
def test_fails_closed_when_digest_header_missing(self):
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=_ghcr_side_effect(
token_resp=_mock_token_response(),
manifest_resp=_mock_manifest_response(digest=None),
@@ -144,7 +144,7 @@ class TestGetSandboxImageReference:
)
def test_fails_closed_on_request_exception(self, exception: Exception):
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=exception,
):
with pytest.raises(SandboxProvisionError):
@@ -162,7 +162,7 @@ class TestGetSandboxImageReference:
return _mock_manifest_response(digest="sha256:recovered")
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=_side,
):
result = _get_sandbox_image_reference()
@@ -173,14 +173,14 @@ class TestGetSandboxImageReference:
def test_failure_is_not_cached(self):
"""A failed resolution must re-attempt on the next call (never cache the failure)."""
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
return_value=_mock_token_response(status_code=503),
):
with pytest.raises(SandboxProvisionError):
_get_sandbox_image_reference()
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=[_mock_token_response(), _mock_manifest_response(digest="sha256:after")],
):
result = _get_sandbox_image_reference()
@@ -189,7 +189,7 @@ class TestGetSandboxImageReference:
def test_caches_result_across_calls(self):
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=[_mock_token_response(), _mock_manifest_response(digest="sha256:cached123")],
) as mock_get:
result1 = _get_sandbox_image_reference()
@@ -202,7 +202,7 @@ class TestGetSandboxImageReference:
def test_re_resolves_after_cache_expiry(self):
"""After TTL expiry (simulated via clear), a fresh GHCR query picks up the new digest."""
with patch(
- "products.tasks.backend.services.modal_sandbox.requests.get",
+ "products.tasks.backend.logic.services.modal_sandbox.requests.get",
side_effect=[
_mock_token_response(),
_mock_manifest_response(digest="sha256:old"),
@@ -249,7 +249,7 @@ class TestGetModalRegion:
],
)
def test_returns_correct_region(self, cloud_deployment, expected_region):
- with patch("products.tasks.backend.services.modal_sandbox.CLOUD_DEPLOYMENT", cloud_deployment):
+ with patch("products.tasks.backend.logic.services.modal_sandbox.CLOUD_DEPLOYMENT", cloud_deployment):
assert _get_modal_region() == expected_region
@@ -298,7 +298,7 @@ class TestModalSandboxAgentServer:
mock_sandbox._sandbox.exec.side_effect = RuntimeError("failed POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=secret-token")
with (
- patch("products.tasks.backend.services.modal_sandbox.capture_exception") as capture_exception,
+ patch("products.tasks.backend.logic.services.modal_sandbox.capture_exception") as capture_exception,
pytest.raises(SandboxExecutionError) as exc,
):
getattr(mock_sandbox, method_name)("env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=secret-token agent-server")
diff --git a/products/tasks/backend/services/title_generator.py b/products/tasks/backend/logic/services/title_generator.py
similarity index 100%
rename from products/tasks/backend/services/title_generator.py
rename to products/tasks/backend/logic/services/title_generator.py
diff --git a/products/tasks/backend/logic/stream/__init__.py b/products/tasks/backend/logic/stream/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/tasks/backend/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
similarity index 99%
rename from products/tasks/backend/stream/event_ingest.py
rename to products/tasks/backend/logic/stream/event_ingest.py
index 314e398dddaa..9dc9788e1bac 100644
--- a/products/tasks/backend/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -10,18 +10,18 @@ import structlog
from asgiref.sync import sync_to_async
from jwt import PyJWTError
-from products.tasks.backend.models import TaskRun
-from products.tasks.backend.services.connection_token import (
+from products.tasks.backend.logic.services.connection_token import (
SandboxEventIngestTokenPayload,
validate_sandbox_event_ingest_token,
)
-from products.tasks.backend.stream.redis_stream import (
+from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
TaskRunStreamSequenceGap,
get_task_run_stream_key,
)
+from products.tasks.backend.models import TaskRun
from ee.hogai.sandbox import is_turn_complete
diff --git a/products/tasks/backend/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.py
similarity index 99%
rename from products/tasks/backend/stream/redis_stream.py
rename to products/tasks/backend/logic/stream/redis_stream.py
index 927aca310dd7..9d7c601564e0 100644
--- a/products/tasks/backend/stream/redis_stream.py
+++ b/products/tasks/backend/logic/stream/redis_stream.py
@@ -9,9 +9,9 @@ import structlog
import redis.exceptions as redis_exceptions
from asgiref.sync import async_to_sync
+from products.tasks.backend.logic.services.connection_token import SANDBOX_EVENT_INGEST_TOKEN_TTL
+from products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDS
from products.tasks.backend.redis import get_tasks_stream_redis_async
-from products.tasks.backend.services.connection_token import SANDBOX_EVENT_INGEST_TOKEN_TTL
-from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS
logger = structlog.get_logger(__name__)
diff --git a/products/tasks/backend/stream/tests/test_redis_stream.py b/products/tasks/backend/logic/stream/tests/test_redis_stream.py
similarity index 98%
rename from products/tasks/backend/stream/tests/test_redis_stream.py
rename to products/tasks/backend/logic/stream/tests/test_redis_stream.py
index cfebf11cdaed..5cf3dcfbf1e9 100644
--- a/products/tasks/backend/stream/tests/test_redis_stream.py
+++ b/products/tasks/backend/logic/stream/tests/test_redis_stream.py
@@ -3,7 +3,7 @@ from uuid import uuid4
import pytest
-from products.tasks.backend.stream.redis_stream import (
+from products.tasks.backend.logic.stream.redis_stream import (
DATA_KEY,
TaskRunRedisStream,
TaskRunStreamAlreadyCompleted,
diff --git a/products/tasks/backend/management/commands/demo_mts_example.py b/products/tasks/backend/management/commands/demo_mts_example.py
index 3de76a3b47d7..4cd7271d7582 100644
--- a/products/tasks/backend/management/commands/demo_mts_example.py
+++ b/products/tasks/backend/management/commands/demo_mts_example.py
@@ -12,8 +12,8 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from products.signals.backend.report_generation.research import ReportResearchOutput
-from products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext
-from products.tasks.backend.services.mts_example import run_cursed_identifier_research
+from products.tasks.backend.logic.services.custom_prompt_internals import CustomPromptSandboxContext
+from products.tasks.backend.logic.services.mts_example import run_cursed_identifier_research
REPOSITORY = "PostHog/posthog"
BRANCH: str | None = None
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 02dd3eb3b44e..50196d5ed58b 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -15,7 +15,7 @@ from pydantic import BaseModel
if TYPE_CHECKING:
from products.slack_app.backend.slack_thread import SlackThreadContext
- from products.tasks.backend.services.sandbox import SandboxResources
+ from products.tasks.backend.logic.services.sandbox import SandboxResources
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
@@ -41,9 +41,9 @@ from posthog.storage import object_storage
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINS
+from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_event
from products.tasks.backend.metrics import observe_task_run_created
from products.tasks.backend.redis import evaluate_dedicated_stream_flag, run_uses_dedicated_stream
-from products.tasks.backend.stream.redis_stream import publish_task_run_stream_event
logger = structlog.get_logger(__name__)
@@ -349,7 +349,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
created_by = User.objects.get(id=user_id)
- from products.tasks.backend.services.sandbox import is_public_sandbox_repo
+ from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
from products.tasks.backend.temporal.process_task.utils import (
PrAuthorshipMode,
RunSource,
@@ -1203,7 +1203,7 @@ class SandboxSnapshot(UUIDModel):
def delete(self, *args, **kwargs):
if self.external_id:
- from products.tasks.backend.services.sandbox import Sandbox
+ from products.tasks.backend.logic.services.sandbox import Sandbox
if os.environ.get("MODAL_TOKEN_ID") and os.environ.get("MODAL_TOKEN_SECRET") and not settings.TEST:
try:
diff --git a/products/tasks/backend/presentation/__init__.py b/products/tasks/backend/presentation/__init__.py
new file mode 100644
index 000000000000..cb48e21edc87
--- /dev/null
+++ b/products/tasks/backend/presentation/__init__.py
@@ -0,0 +1 @@
+"""HTTP presentation layer of the tasks product (DRF viewsets and serializers)."""
diff --git a/products/tasks/backend/serializers.py b/products/tasks/backend/presentation/serializers.py
similarity index 80%
rename from products/tasks/backend/serializers.py
rename to products/tasks/backend/presentation/serializers.py
index e2e7a8b8031c..01611bdf1a26 100644
--- a/products/tasks/backend/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1,43 +1,46 @@
import base64
import binascii
+from typing import cast
from zoneinfo import available_timezones
-from django.db import transaction
-from django.utils import timezone
-
from croniter import croniter
-from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
+from drf_spectacular.utils import PolymorphicProxySerializer
from rest_framework import serializers
+from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
-from posthog.api.shared import UserBasicSerializer
from posthog.models.integration import Integration
from posthog.models.user_integration import UserIntegration
-from posthog.storage import object_storage
-
-from products.signals.backend.models import SignalReportTask
-from .constants import (
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.contracts import (
+ SandboxEnvironmentDTO,
+ TaskAutomationDTO,
+ TaskDetailDTO,
+ TaskRunDetailDTO,
+ TaskSummaryDTO,
+ TaskUserBasicInfo,
+)
+from products.tasks.backend.facade.run_config import (
ALL_INITIAL_PERMISSION_MODE_CHOICES,
CODEX_INITIAL_PERMISSION_MODE_CHOICES,
INITIAL_PERMISSION_MODE_CHOICES,
-)
-from .models import SandboxEnvironment, Task, TaskAutomation, TaskRun
-from .redis import get_tasks_cache
-from .services.title_generator import generate_task_title
-from .temporal.process_task.utils import (
PUBLIC_REASONING_EFFORTS,
LLMProvider,
PrAuthorshipMode,
RunSource,
- RunState,
RuntimeAdapter,
get_reasoning_effort_error,
- parse_run_state,
- resolve_user_github_integration_for_task,
)
-PRESIGNED_URL_CACHE_TTL = 55 * 60 # 55 minutes (less than 1 hour URL expiry)
+
+class TaskUserBasicInfoSerializer(DataclassSerializer):
+ """Response shape for a `created_by` user — mirrors core `UserBasicSerializer` output."""
+
+ class Meta:
+ dataclass = TaskUserBasicInfo
+
+
TASK_RUN_ARTIFACT_MAX_SIZE_BYTES = 30 * 1024 * 1024
TASK_RUN_PDF_ARTIFACT_MAX_SIZE_BYTES = 10 * 1024 * 1024
TASK_RUN_ARTIFACT_TYPE_CHOICES = [
@@ -81,218 +84,6 @@ def build_task_run_artifact_size_error(
return f"{artifact_name or 'Artifact'} exceeds the {max_mb}MB attachment limit"
-class TaskSerializer(serializers.ModelSerializer):
- repository = serializers.CharField(
- max_length=255,
- required=False,
- allow_blank=True,
- allow_null=True,
- help_text="Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).",
- )
- # UserIntegration is scoped to request.user in validate_github_user_integration.
- github_user_integration = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
- queryset=UserIntegration.objects.filter(kind="github"),
- required=False,
- allow_null=True,
- help_text="User-scoped GitHub integration to use for user-authored cloud runs.",
- )
- latest_run = serializers.SerializerMethodField()
- created_by = UserBasicSerializer(read_only=True)
-
- title = serializers.CharField(
- max_length=255,
- required=False,
- allow_blank=True,
- help_text="Short human-readable title. Auto-generated from `description` when omitted.",
- )
- description = serializers.CharField(
- required=False,
- allow_blank=True,
- help_text="Free-form description of the work to be done. Used as the prompt passed to the agent.",
- )
- origin_product = serializers.ChoiceField(
- choices=Task.OriginProduct.choices,
- required=False,
- help_text="PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).",
- )
- # Write-only: which SignalReportTask row to create when linking a task to a report from the
- # public task API (e.g. PostHog Code inbox). Only implementation is supported; research/repo
- # selection links are created by server-side flows.
- signal_report_task_relationship = serializers.ChoiceField(
- choices=[
- (
- SignalReportTask.Relationship.IMPLEMENTATION.value,
- SignalReportTask.Relationship.IMPLEMENTATION.label,
- ),
- ],
- required=False,
- write_only=True,
- )
-
- class Meta:
- model = Task
- fields = [
- "id",
- "task_number",
- "slug",
- "title",
- "title_manually_set",
- "description",
- "origin_product",
- "repository",
- "github_integration",
- "github_user_integration",
- "signal_report",
- "signal_report_task_relationship",
- "json_schema",
- "internal",
- "archived",
- "archived_at",
- "latest_run",
- "created_at",
- "updated_at",
- "created_by",
- "ci_prompt",
- ]
- read_only_fields = [
- "id",
- "task_number",
- "slug",
- "archived_at",
- "created_at",
- "updated_at",
- "created_by",
- "latest_run",
- ]
-
- @extend_schema_field(serializers.DictField(allow_null=True, help_text="Latest run details for this task"))
- def get_latest_run(self, obj):
- latest_run = obj.latest_run
- if latest_run:
- return TaskRunDetailSerializer(latest_run, context=self.context).data
- return None
-
- def validate_github_integration(self, value):
- """Validate that the GitHub integration belongs to the same team"""
- if value and value.team_id != self.context["team"].id:
- raise serializers.ValidationError("Integration must belong to the same team")
- return value
-
- def validate_github_user_integration(self, value):
- """Validate that the GitHub user integration belongs to the authenticated user."""
- request = self.context.get("request")
- user = getattr(request, "user", None)
- if value and value.user_id != getattr(user, "id", None):
- raise serializers.ValidationError("User integration must belong to the authenticated user")
- return value
-
- def validate_repository(self, value):
- """Validate repository configuration"""
- if not value:
- return value
-
- parts = value.split("/")
- if len(parts) != 2 or not parts[0] or not parts[1]:
- raise serializers.ValidationError("Repository must be in the format organization/repository")
-
- return value.lower()
-
- def validate_signal_report(self, value):
- if value and value.team_id != self.context["team"].id:
- raise serializers.ValidationError("Signal report must belong to the same team")
- return value
-
- def validate(self, attrs: dict) -> dict:
- rel = attrs.get("signal_report_task_relationship")
- if rel is not None:
- if not attrs.get("signal_report"):
- raise serializers.ValidationError(
- {"signal_report_task_relationship": "Requires signal_report when set."}
- )
- if attrs.get("origin_product") != Task.OriginProduct.SIGNAL_REPORT:
- raise serializers.ValidationError(
- {"signal_report_task_relationship": ("Requires origin_product signal_report when set.")}
- )
- if (
- attrs.get("origin_product") == Task.OriginProduct.SIGNAL_REPORT
- and attrs.get("github_user_integration") is not None
- ):
- raise serializers.ValidationError(
- {"github_user_integration": "Signal report tasks use the team GitHub integration."}
- )
- return attrs
-
- def create(self, validated_data):
- validated_data["team"] = self.context["team"]
- validated_data.setdefault("origin_product", Task.OriginProduct.USER_CREATED)
-
- if "request" in self.context and hasattr(self.context["request"], "user"):
- validated_data["created_by"] = self.context["request"].user
-
- link_relationship = validated_data.pop(
- "signal_report_task_relationship",
- SignalReportTask.Relationship.IMPLEMENTATION,
- )
-
- # Set default GitHub integration if not provided
- if not validated_data.get("github_integration"):
- default_integration = Integration.objects.filter(team=self.context["team"], kind="github").first()
- if default_integration:
- validated_data["github_integration"] = default_integration
-
- if (
- validated_data.get("repository")
- and validated_data.get("origin_product", Task.OriginProduct.USER_CREATED) == Task.OriginProduct.USER_CREATED
- and not validated_data.get("github_user_integration")
- ):
- task_stub = Task(
- team=self.context["team"],
- created_by=validated_data.get("created_by"),
- origin_product=Task.OriginProduct.USER_CREATED,
- repository=validated_data["repository"],
- github_integration=validated_data.get("github_integration"),
- )
- github_user_integration = resolve_user_github_integration_for_task(task_stub, allow_refresh=False)
- if github_user_integration is not None:
- validated_data["github_user_integration"] = github_user_integration.integration
-
- title = validated_data.get("title", "").strip()
- if not title and validated_data.get("description"):
- validated_data["title"] = generate_task_title(validated_data["description"])
- validated_data.setdefault("title_manually_set", False)
- elif title:
- validated_data.setdefault("title_manually_set", True)
-
- # Inbox / PostHog Code: tasks created via this API with a signal report use the same
- # origin_product as server-side flows, but only those flows previously called
- # SignalReportTask.objects.create. Link implementation tasks here so report task
- # listings (e.g. getSignalReportTasks) match autostarted implementations.
- with transaction.atomic():
- task = super().create(validated_data)
- if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT:
- SignalReportTask.objects.create(
- team_id=task.team_id,
- report_id=task.signal_report_id,
- task=task,
- relationship=link_relationship,
- )
- return task
-
- def update(self, instance, validated_data):
- # These fields are immutable after creation. origin_product controls
- # team-wide visibility (SIGNAL_REPORT tasks are visible to all members),
- # so allowing updates would let a user escalate a private task's visibility.
- # signal_report and its relationship are set-once associations.
- validated_data.pop("signal_report", None)
- validated_data.pop("signal_report_task_relationship", None)
- validated_data.pop("origin_product", None)
- if "title" in validated_data and "title_manually_set" not in validated_data:
- validated_data["title_manually_set"] = True
- if "archived" in validated_data and validated_data["archived"] != instance.archived:
- validated_data["archived_at"] = timezone.now() if validated_data["archived"] else None
- return super().update(instance, validated_data)
-
-
class AgentDefinitionSerializer(serializers.Serializer):
"""Serializer for agent definitions"""
@@ -349,24 +140,44 @@ class TaskRunArtifactResponseSerializer(serializers.Serializer):
uploaded_at = serializers.CharField(help_text="Timestamp when the artifact was uploaded")
-class TaskRunDetailSerializer(serializers.ModelSerializer):
- _run_state_cache: dict[str, RunState]
+class TaskRunDetailSerializer(DataclassSerializer):
+ """Detail response for a task run.
+
+ Reads from a frozen ``TaskRunDetailDTO`` produced by the facade mapper (which computes the
+ presigned ``log_url`` and parses ``runtime_adapter`` / ``provider`` / ``model`` /
+ ``reasoning_effort`` off the run state). ``task`` is the parent task id. Reused as the nested
+ ``latest_run`` shape by the task detail response.
+ """
- log_url = serializers.SerializerMethodField(help_text="Presigned S3 URL for log access (valid for 1 hour).")
+ task = serializers.UUIDField(help_text="Parent task id this run belongs to.")
+ log_url = serializers.URLField(
+ allow_null=True, required=False, help_text="Presigned S3 URL for log access (valid for 1 hour)."
+ )
artifacts = TaskRunArtifactResponseSerializer(many=True, read_only=True)
- runtime_adapter = serializers.SerializerMethodField(
- help_text="Configured runtime adapter for this run, such as 'claude' or 'codex'."
+ runtime_adapter = serializers.ChoiceField(
+ choices=[adapter.value for adapter in RuntimeAdapter],
+ allow_null=True,
+ required=False,
+ help_text="Configured runtime adapter for this run, such as 'claude' or 'codex'.",
+ )
+ provider = serializers.ChoiceField(
+ choices=[provider.value for provider in LLMProvider],
+ allow_null=True,
+ required=False,
+ help_text="Configured LLM provider for this run, such as 'anthropic' or 'openai'.",
)
- provider = serializers.SerializerMethodField(
- help_text="Configured LLM provider for this run, such as 'anthropic' or 'openai'."
+ model = serializers.CharField(
+ allow_null=True, required=False, help_text="Configured LLM model identifier for this run."
)
- model = serializers.SerializerMethodField(help_text="Configured LLM model identifier for this run.")
- reasoning_effort = serializers.SerializerMethodField(
- help_text="Configured reasoning effort for this run when the selected model supports it."
+ reasoning_effort = serializers.ChoiceField(
+ choices=[effort.value for effort in PUBLIC_REASONING_EFFORTS],
+ allow_null=True,
+ required=False,
+ help_text="Configured reasoning effort for this run when the selected model supports it.",
)
class Meta:
- model = TaskRun
+ dataclass = TaskRunDetailDTO
fields = [
"id",
"task",
@@ -387,103 +198,192 @@ class TaskRunDetailSerializer(serializers.ModelSerializer):
"updated_at",
"completed_at",
]
- read_only_fields = [
- "id",
- "task",
- "log_url",
- "created_at",
- "updated_at",
- "completed_at",
- ]
- @extend_schema_field(
- serializers.URLField(allow_null=True, help_text="Presigned S3 URL for log access (valid for 1 hour).")
- )
- def get_log_url(self, obj: TaskRun) -> str | None:
- """Return presigned S3 URL for log access, cached to avoid regeneration."""
- cache_key = f"task_run_log_url:{obj.id}"
- cached_url = get_tasks_cache().get(cache_key)
- if cached_url:
- return cached_url
+# Only implementation is supported when linking a task to a report from the public task API
+# (e.g. PostHog Code inbox); research/repo-selection links are created by server-side flows.
+# The value/label mirror `signals` `SignalReportTask.Relationship.IMPLEMENTATION` — kept inline
+# so presentation never imports the other product's models.
+SIGNAL_REPORT_TASK_RELATIONSHIP_IMPLEMENTATION = "implementation"
- presigned_url = object_storage.get_presigned_url(obj.log_url, expiration=3600)
- if presigned_url:
- get_tasks_cache().set(cache_key, presigned_url, timeout=PRESIGNED_URL_CACHE_TTL)
+class TaskSerializer(DataclassSerializer):
+ """Detail response for a task.
- return presigned_url
+ 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``.
+ """
- def _get_run_state(self, obj: TaskRun) -> RunState:
- if not hasattr(self, "_run_state_cache"):
- self._run_state_cache = {}
+ latest_run = TaskRunDetailSerializer(allow_null=True, required=False, help_text="Latest run details for this task")
+ created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
- cache_key = str(obj.id)
- cached_state = self._run_state_cache.get(cache_key)
- if cached_state is not None:
- return cached_state
+ class Meta:
+ dataclass = TaskDetailDTO
+ fields = [
+ "id",
+ "task_number",
+ "slug",
+ "title",
+ "title_manually_set",
+ "description",
+ "origin_product",
+ "repository",
+ "github_integration",
+ "github_user_integration",
+ "signal_report",
+ "json_schema",
+ "internal",
+ "archived",
+ "archived_at",
+ "latest_run",
+ "created_at",
+ "updated_at",
+ "created_by",
+ "ci_prompt",
+ ]
- parsed_state = parse_run_state(obj.state)
- self._run_state_cache[cache_key] = parsed_state
- return parsed_state
- @extend_schema_field(
- serializers.ChoiceField(
- choices=[adapter.value for adapter in RuntimeAdapter],
- allow_null=True,
- help_text="Configured runtime adapter for this run, such as 'claude' or 'codex'.",
- )
- )
- def get_runtime_adapter(self, obj: TaskRun) -> str | None:
- state = self._get_run_state(obj)
- return state.runtime_adapter.value if state.runtime_adapter is not None else None
+class TaskWriteSerializer(serializers.Serializer):
+ """Request body for creating or updating a task.
- @extend_schema_field(
- serializers.ChoiceField(
- choices=[provider.value for provider in LLMProvider],
- allow_null=True,
- help_text="Configured LLM provider for this run, such as 'anthropic' or 'openai'.",
- )
- )
- def get_provider(self, obj: TaskRun) -> str | None:
- state = self._get_run_state(obj)
- return state.provider.value if state.provider is not None else None
+ Field required/default semantics match the ``Task`` model. The view passes
+ ``validated_data`` (integration/report PK fields already resolved to instances) to the
+ facade ``create_task`` / ``update_task`` functions.
+ """
- @extend_schema_field(
- serializers.CharField(allow_null=True, help_text="Configured LLM model identifier for this run.")
+ title = serializers.CharField(
+ max_length=255,
+ required=False,
+ allow_blank=True,
+ help_text="Short human-readable title. Auto-generated from `description` when omitted.",
)
- def get_model(self, obj: TaskRun) -> str | None:
- return self._get_run_state(obj).model
-
- @extend_schema_field(
- serializers.ChoiceField(
- choices=[effort.value for effort in PUBLIC_REASONING_EFFORTS],
- allow_null=True,
- help_text="Configured reasoning effort for this run when the selected model supports it.",
- )
+ title_manually_set = serializers.BooleanField(
+ required=False,
+ help_text="Whether the title was set by a human (vs auto-generated from the description).",
+ )
+ description = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Free-form description of the work to be done. Used as the prompt passed to the agent.",
+ )
+ origin_product = serializers.ChoiceField(
+ choices=tasks_facade.TaskOriginProduct.choices,
+ required=False,
+ help_text="PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).",
+ )
+ repository = serializers.CharField(
+ max_length=255,
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ help_text="Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).",
+ )
+ github_integration = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
+ queryset=Integration.objects.filter(kind="github"),
+ required=False,
+ allow_null=True,
+ help_text="GitHub integration for this task.",
+ )
+ # UserIntegration is scoped to request.user in validate_github_user_integration.
+ github_user_integration = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
+ queryset=UserIntegration.objects.filter(kind="github"),
+ required=False,
+ allow_null=True,
+ help_text="User-scoped GitHub integration to use for user-authored cloud runs.",
+ )
+ # Mirrors the ModelSerializer-generated FK field: queryset is the full report manager
+ # (team scope is enforced by validate_signal_report below). Bound lazily in __init__ so
+ # importing this module never touches the signals model.
+ signal_report = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
+ queryset=Integration.objects.none(),
+ required=False,
+ allow_null=True,
+ help_text="Signal report this task implements, when created from a report.",
+ )
+ # Write-only: which SignalReportTask row to create when linking a task to a report.
+ signal_report_task_relationship = serializers.ChoiceField(
+ choices=[(SIGNAL_REPORT_TASK_RELATIONSHIP_IMPLEMENTATION, "Implementation")],
+ required=False,
+ write_only=True,
+ )
+ json_schema = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ help_text="JSON schema used to validate the output of the task.",
+ )
+ internal = serializers.BooleanField(
+ required=False,
+ help_text="If true, this task is for internal use and should not be exposed to end users.",
+ )
+ archived = serializers.BooleanField(
+ required=False,
+ help_text="If true, the task is hidden from default list responses.",
+ )
+ ci_prompt = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Custom prompt for CI fixes. If blank, a default prompt will be used.",
)
- def get_reasoning_effort(self, obj: TaskRun) -> str | None:
- state = self._get_run_state(obj)
- return state.reasoning_effort.value if state.reasoning_effort is not None else None
- def validate_task(self, value):
- team = self.context.get("team")
- if team and value.team_id != team.id:
- raise serializers.ValidationError("Task must belong to the same team")
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # SignalReport is scoped to the request team by the field; bind its queryset lazily so
+ # importing this module never touches the signals model at import time.
+ cast(
+ serializers.PrimaryKeyRelatedField, self.fields["signal_report"]
+ ).queryset = tasks_facade.signal_report_queryset()
+
+ def validate_github_integration(self, value):
+ """Validate that the GitHub integration belongs to the same team"""
+ if value and value.team_id != self.context["team"].id:
+ raise serializers.ValidationError("Integration must belong to the same team")
return value
- def create(self, validated_data):
- validated_data["team"] = self.context["team"]
- return super().create(validated_data)
+ def validate_github_user_integration(self, value):
+ """Validate that the GitHub user integration belongs to the authenticated user."""
+ request = self.context.get("request")
+ user = getattr(request, "user", None)
+ if value and value.user_id != getattr(user, "id", None):
+ raise serializers.ValidationError("User integration must belong to the authenticated user")
+ return value
- def update(self, instance, validated_data):
- # Never allow task reassignment through updates
- validated_data.pop("task", None)
+ def validate_repository(self, value):
+ """Validate repository configuration"""
+ if not value:
+ return value
- status = validated_data.get("status")
- if status in [TaskRun.Status.COMPLETED, TaskRun.Status.FAILED] and not validated_data.get("completed_at"):
- validated_data["completed_at"] = timezone.now()
- return super().update(instance, validated_data)
+ parts = value.split("/")
+ if len(parts) != 2 or not parts[0] or not parts[1]:
+ raise serializers.ValidationError("Repository must be in the format organization/repository")
+
+ return value.lower()
+
+ def validate_signal_report(self, value):
+ if value and value.team_id != self.context["team"].id:
+ raise serializers.ValidationError("Signal report must belong to the same team")
+ return value
+
+ def validate(self, attrs: dict) -> dict:
+ rel = attrs.get("signal_report_task_relationship")
+ if rel is not None:
+ if not attrs.get("signal_report"):
+ raise serializers.ValidationError(
+ {"signal_report_task_relationship": "Requires signal_report when set."}
+ )
+ if attrs.get("origin_product") != tasks_facade.TaskOriginProduct.SIGNAL_REPORT:
+ raise serializers.ValidationError(
+ {"signal_report_task_relationship": ("Requires origin_product signal_report when set.")}
+ )
+ if (
+ attrs.get("origin_product") == tasks_facade.TaskOriginProduct.SIGNAL_REPORT
+ and attrs.get("github_user_integration") is not None
+ ):
+ raise serializers.ValidationError(
+ {"github_user_integration": "Signal report tasks use the team GitHub integration."}
+ )
+ return attrs
class TaskRunSetOutputRequestSerializer(serializers.Serializer):
@@ -846,21 +746,18 @@ class TaskSummariesRequestSerializer(serializers.Serializer):
class TaskRunSummarySerializer(serializers.Serializer):
- status = serializers.ChoiceField(choices=TaskRun.Status.choices, allow_null=True)
- environment = serializers.ChoiceField(choices=TaskRun.Environment.choices, allow_null=True)
+ status = serializers.ChoiceField(choices=tasks_facade.TaskRunStatus.choices, allow_null=True)
+ environment = serializers.ChoiceField(choices=tasks_facade.TaskRunEnvironment.choices, allow_null=True)
+
+class TaskSummarySerializer(DataclassSerializer):
+ """Summary response for a task — reads from a frozen ``TaskSummaryDTO``."""
-class TaskSummarySerializer(serializers.ModelSerializer):
- latest_run = serializers.SerializerMethodField()
+ latest_run = TaskRunSummarySerializer(allow_null=True, required=False)
class Meta:
- model = Task
+ dataclass = TaskSummaryDTO
fields = ["id", "title", "repository", "created_at", "updated_at", "latest_run"]
- read_only_fields = fields
-
- @extend_schema_field(TaskRunSummarySerializer(allow_null=True))
- def get_latest_run(self, obj):
- return getattr(obj, "_latest_run", None)
class TaskListQuerySerializer(serializers.Serializer):
@@ -880,7 +777,7 @@ class TaskListQuerySerializer(serializers.Serializer):
)
status = serializers.ChoiceField(
required=False,
- choices=[choice.value for choice in TaskRun.Status],
+ choices=[choice.value for choice in tasks_facade.TaskRunStatus],
help_text="Filter tasks by the status of their most recent run.",
)
internal = serializers.BooleanField(
@@ -1122,9 +1019,9 @@ class TaskRunBootstrapCreateRequestSerializer(serializers.Serializer):
REASONING_EFFORT_CHOICES = [effort.value for effort in PUBLIC_REASONING_EFFORTS]
environment = serializers.ChoiceField(
- choices=[environment.value for environment in TaskRun.Environment],
+ choices=[environment.value for environment in tasks_facade.TaskRunEnvironment],
required=False,
- default=TaskRun.Environment.LOCAL,
+ default=tasks_facade.TaskRunEnvironment.LOCAL,
help_text="Execution environment for the new run. Use 'cloud' for remote sandbox runs and 'local' for desktop sessions.",
)
mode = serializers.ChoiceField(
@@ -1509,20 +1406,11 @@ class TaskRunSessionLogsQuerySerializer(serializers.Serializer):
)
-class TaskAutomationSerializer(serializers.ModelSerializer):
- name = serializers.CharField(max_length=255)
- prompt = serializers.CharField()
- repository = serializers.CharField(max_length=255)
- github_integration = TeamScopedPrimaryKeyRelatedField(
- queryset=Integration.objects.filter(kind="github"),
- required=False,
- allow_null=True,
- )
- last_task_id = serializers.SerializerMethodField()
- last_task_run_id = serializers.SerializerMethodField()
+class TaskAutomationSerializer(DataclassSerializer):
+ """Detail/create/update/run response for a task automation."""
class Meta:
- model = TaskAutomation
+ dataclass = TaskAutomationDTO
fields = [
"id",
"name",
@@ -1541,22 +1429,38 @@ class TaskAutomationSerializer(serializers.ModelSerializer):
"created_at",
"updated_at",
]
- read_only_fields = [
- "id",
- "last_run_at",
- "last_run_status",
- "last_task_id",
- "last_task_run_id",
- "last_error",
- "created_at",
- "updated_at",
- ]
- def get_last_task_id(self, instance: TaskAutomation) -> str | None:
- return str(instance.task_id)
- def get_last_task_run_id(self, instance: TaskAutomation) -> str | None:
- return str(instance.last_task_run_id) if instance.last_task_run_id else None
+class TaskAutomationWriteSerializer(serializers.Serializer):
+ """Request body for creating or updating a task automation."""
+
+ name = serializers.CharField(max_length=255, help_text="Display name (stored as the backing task's title).")
+ prompt = serializers.CharField(help_text="The automation prompt (stored as the backing task's description).")
+ repository = serializers.CharField(
+ max_length=255, help_text="Target repository in the format organization/repository."
+ )
+ github_integration = TeamScopedPrimaryKeyRelatedField(
+ queryset=Integration.objects.filter(kind="github"),
+ required=False,
+ allow_null=True,
+ help_text="GitHub integration to run as. Defaults to the team's GitHub integration when omitted.",
+ )
+ cron_expression = serializers.CharField(
+ max_length=100, help_text="Standard 5-field cron expression (minute hour day month weekday)."
+ )
+ timezone = serializers.CharField(
+ max_length=128, required=False, default="UTC", help_text="IANA timezone the schedule runs in."
+ )
+ template_id = serializers.CharField(
+ max_length=255,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Optional template identifier this automation was created from.",
+ )
+ enabled = serializers.BooleanField(
+ required=False, default=True, help_text="Whether the schedule is active; paused when false."
+ )
def validate_github_integration(self, value):
if value and value.team_id != self.context["team"].id:
@@ -1589,70 +1493,14 @@ class TaskAutomationSerializer(serializers.ModelSerializer):
raise serializers.ValidationError(f"'{value}' is not a valid IANA timezone.")
return value
- def create(self, validated_data):
- if not validated_data.get("github_integration"):
- default_integration = Integration.objects.filter(team=self.context["team"], kind="github").first()
- if default_integration:
- validated_data["github_integration"] = default_integration
-
- with transaction.atomic():
- task = Task.objects.create(
- team=self.context["team"],
- created_by=self.context["request"].user,
- title=validated_data.pop("name"),
- description=validated_data.pop("prompt"),
- origin_product=Task.OriginProduct.AUTOMATION,
- repository=validated_data.pop("repository"),
- github_integration=validated_data.pop("github_integration", None),
- )
- return TaskAutomation.objects.create(task=task, **validated_data)
-
- def update(self, instance, validated_data):
- task_fields = {
- "name": "title",
- "prompt": "description",
- "repository": "repository",
- "github_integration": "github_integration",
- }
- task_updates = {}
- for serializer_field, task_field in task_fields.items():
- if serializer_field in validated_data:
- task_updates[task_field] = validated_data.pop(serializer_field)
-
- with transaction.atomic():
- automation = super().update(instance, validated_data)
-
- if task_updates:
- task = automation.task
- fields_to_update = []
- for field, value in task_updates.items():
- if getattr(task, field) != value:
- setattr(task, field, value)
- fields_to_update.append(field)
- if fields_to_update:
- fields_to_update.append("updated_at")
- task.save(update_fields=fields_to_update)
-
- return automation
-
-
-class SandboxEnvironmentSerializer(serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
- effective_domains = serializers.SerializerMethodField(
- help_text="Computed domain allowlist based on network_access_level and allowed_domains"
- )
- environment_variables = serializers.JSONField(
- write_only=True,
- required=False,
- default=dict,
- help_text="Encrypted environment variables (write-only, never returned in responses)",
- )
- has_environment_variables = serializers.SerializerMethodField(
- help_text="Whether this environment has any environment variables set"
- )
+
+class SandboxEnvironmentSerializer(DataclassSerializer):
+ """Detail/create/update response for a sandbox environment."""
+
+ created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
- model = SandboxEnvironment
+ dataclass = SandboxEnvironmentDTO
fields = [
"id",
"name",
@@ -1660,7 +1508,6 @@ class SandboxEnvironmentSerializer(serializers.ModelSerializer):
"allowed_domains",
"include_default_domains",
"repositories",
- "environment_variables",
"has_environment_variables",
"private",
"internal",
@@ -1669,43 +1516,15 @@ class SandboxEnvironmentSerializer(serializers.ModelSerializer):
"created_at",
"updated_at",
]
- read_only_fields = [
- "id",
- "internal",
- "created_by",
- "created_at",
- "updated_at",
- "effective_domains",
- "has_environment_variables",
- ]
- def get_effective_domains(self, obj: SandboxEnvironment) -> list[str]:
- return obj.get_effective_domains()
- def get_has_environment_variables(self, obj: SandboxEnvironment) -> bool:
- return bool(obj.environment_variables)
+class SandboxEnvironmentListSerializer(DataclassSerializer):
+ """List response for sandbox environments (subset of fields)."""
- def validate_environment_variables(self, value):
- if value:
- for key in value:
- if not SandboxEnvironment.is_valid_env_var_key(key):
- raise serializers.ValidationError(
- f"Invalid environment variable key: {key!r}. Must match [A-Za-z_][A-Za-z0-9_]*"
- )
- return value
-
- def create(self, validated_data):
- validated_data["team"] = self.context["team"]
- if "request" in self.context and hasattr(self.context["request"], "user"):
- validated_data["created_by"] = self.context["request"].user
- return super().create(validated_data)
-
-
-class SandboxEnvironmentListSerializer(serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
+ created_by = TaskUserBasicInfoSerializer(allow_null=True, required=False)
class Meta:
- model = SandboxEnvironment
+ dataclass = SandboxEnvironmentDTO
fields = [
"id",
"name",
@@ -1720,6 +1539,55 @@ class SandboxEnvironmentListSerializer(serializers.ModelSerializer):
]
+class SandboxEnvironmentWriteSerializer(serializers.Serializer):
+ """Request body for creating or updating a sandbox environment."""
+
+ name = serializers.CharField(max_length=255, help_text="Display name for the environment.")
+ network_access_level = serializers.ChoiceField(
+ choices=tasks_facade.SandboxNetworkAccessLevel.choices,
+ required=False,
+ default=tasks_facade.SandboxNetworkAccessLevel.FULL,
+ help_text="Network access policy: trusted (default allowlist), full (unrestricted), or custom.",
+ )
+ allowed_domains = serializers.ListField(
+ child=serializers.CharField(max_length=255),
+ required=False,
+ default=list,
+ help_text="Allowed domains for custom network access.",
+ )
+ include_default_domains = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="Whether to include default trusted domains (GitHub, npm, PyPI).",
+ )
+ repositories = serializers.ListField(
+ child=serializers.CharField(max_length=255),
+ required=False,
+ default=list,
+ help_text="Repositories this environment applies to (format: org/repo).",
+ )
+ environment_variables = serializers.JSONField(
+ write_only=True,
+ required=False,
+ default=dict,
+ help_text="Encrypted environment variables (write-only, never returned in responses).",
+ )
+ private = serializers.BooleanField(
+ required=False,
+ default=True,
+ help_text="If true, only the creator can see this environment; otherwise the whole team can.",
+ )
+
+ def validate_environment_variables(self, value):
+ if value:
+ for key in value:
+ if not tasks_facade.is_valid_sandbox_env_var_key(key):
+ raise serializers.ValidationError(
+ f"Invalid environment variable key: {key!r}. Must match [A-Za-z_][A-Za-z0-9_]*"
+ )
+ return value
+
+
class TaskPresenceBeaconRequestSerializer(serializers.Serializer):
"""Request body for the presence beacon and beacon-leave endpoints.
diff --git a/products/tasks/backend/presentation/views/__init__.py b/products/tasks/backend/presentation/views/__init__.py
new file mode 100644
index 000000000000..400154a9b86d
--- /dev/null
+++ b/products/tasks/backend/presentation/views/__init__.py
@@ -0,0 +1,3 @@
+"""DRF viewsets for tasks — submodule paths (`backend.presentation.views.*`) are part
+of the shared tach interface for isolated products.
+"""
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
new file mode 100644
index 000000000000..6d63a12261c3
--- /dev/null
+++ b/products/tasks/backend/presentation/views/api.py
@@ -0,0 +1,1813 @@
+import os
+import re
+import json
+import asyncio
+import logging
+from collections.abc import AsyncGenerator
+from datetime import datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+from django.conf import settings
+from django.http import HttpResponse, JsonResponse, StreamingHttpResponse
+
+import requests as http_requests
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import status, viewsets
+from rest_framework.authentication import SessionAuthentication
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound
+from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+
+from posthog.api.mixins import validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.utils import ServerTimingsGathered
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.permissions import APIScopePermission
+from posthog.rate_limit import CodeInviteThrottle
+from posthog.renderers import ServerSentEventRenderer
+
+from products.tasks.backend.facade import (
+ access as tasks_access,
+ api as tasks_facade,
+ contracts as tasks_contracts,
+)
+from products.tasks.backend.facade.access import cloud_usage_limit_response
+from products.tasks.backend.facade.metrics import (
+ StreamConnectionOutcome,
+ observe_stream_connection_closed,
+ observe_stream_connection_opened,
+ observe_stream_length_on_connect,
+ observe_stream_resume_gap,
+)
+from products.tasks.backend.facade.streams import (
+ TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
+ TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,
+ TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
+ TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS,
+ TaskRunRedisStream,
+ TaskRunStreamError,
+ get_task_run_stream_key,
+ run_uses_dedicated_stream,
+)
+from products.tasks.backend.presentation.serializers import (
+ CodeInviteRedeemRequestSerializer,
+ ConnectionTokenResponseSerializer,
+ RepositoryReadinessQuerySerializer,
+ RepositoryReadinessResponseSerializer,
+ SandboxEnvironmentListSerializer,
+ SandboxEnvironmentSerializer,
+ SandboxEnvironmentWriteSerializer,
+ SlackThreadContextQuerySerializer,
+ SlackThreadContextResponseSerializer,
+ TaskAutomationSerializer,
+ TaskAutomationWriteSerializer,
+ TaskListQuerySerializer,
+ TaskPresenceBeaconRequestSerializer,
+ TaskRepositoriesResponseSerializer,
+ TaskRunAppendLogRequestSerializer,
+ TaskRunArtifactPresignRequestSerializer,
+ TaskRunArtifactPresignResponseSerializer,
+ TaskRunArtifactsFinalizeUploadRequestSerializer,
+ TaskRunArtifactsFinalizeUploadResponseSerializer,
+ TaskRunArtifactsPrepareUploadRequestSerializer,
+ TaskRunArtifactsPrepareUploadResponseSerializer,
+ TaskRunArtifactsUploadRequestSerializer,
+ TaskRunArtifactsUploadResponseSerializer,
+ TaskRunBootstrapCreateRequestSerializer,
+ TaskRunCommandRequestSerializer,
+ TaskRunCommandResponseSerializer,
+ TaskRunCreateRequestSchemaSerializer,
+ TaskRunCreateRequestSerializer,
+ TaskRunDetailSerializer,
+ TaskRunErrorResponseSerializer,
+ TaskRunRelayMessageRequestSerializer,
+ TaskRunRelayMessageResponseSerializer,
+ TaskRunSessionLogsQuerySerializer,
+ TaskRunSetOutputRequestSerializer,
+ TaskRunStartRequestSerializer,
+ TaskRunUpdateSerializer,
+ TaskSerializer,
+ TaskStagedArtifactsFinalizeUploadRequestSerializer,
+ TaskStagedArtifactsFinalizeUploadResponseSerializer,
+ TaskStagedArtifactsPrepareUploadRequestSerializer,
+ TaskStagedArtifactsPrepareUploadResponseSerializer,
+ TaskSummariesRequestSerializer,
+ TaskSummarySerializer,
+ TaskWriteSerializer,
+)
+
+from ee.hogai.utils.aio import async_to_sync
+
+logger = logging.getLogger(__name__)
+TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS = 20.0
+TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME = "keepalive"
+TASK_RUN_STREAM_KEEPALIVE_PAYLOAD = {"type": "keepalive"}
+TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS = 60 * 60
+
+
+TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024
+
+
+def _is_internal_debug_team(team_id: int | None) -> bool:
+ if settings.DEBUG and not settings.TEST:
+ return team_id == 1
+ return team_id == 2 and settings.CLOUD_DEPLOYMENT == "US"
+
+
+class _SchemaAwareLimitOffsetPagination(LimitOffsetPagination):
+ """LimitOffsetPagination subclass that surfaces `default_limit`/`max_limit` in the OpenAPI schema."""
+
+ def get_schema_operation_parameters(self, view):
+ parameters = super().get_schema_operation_parameters(view)
+ for parameter in parameters:
+ if parameter.get("name") == self.limit_query_param:
+ parameter["schema"]["default"] = self.default_limit
+ if self.max_limit is not None:
+ parameter["schema"]["maximum"] = self.max_limit
+ parameter["schema"]["minimum"] = 1
+ elif parameter.get("name") == self.offset_query_param:
+ parameter["schema"]["default"] = 0
+ parameter["schema"]["minimum"] = 0
+ return parameters
+
+
+class TasksPagination(_SchemaAwareLimitOffsetPagination):
+ default_limit = 50
+ max_limit = 100
+
+
+def _parse_slack_thread_url(url: str) -> tuple[str, str] | None:
+ """Parse a Slack permalink into `(channel, thread_ts)`"""
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ match = re.search(r"/archives/(?P<channel>[A-Z0-9]+)/p(?P<ts>\d+)", parsed.path)
+ if not match:
+ return None
+ channel = match.group("channel")
+ # Reply permalinks put the parent thread_ts in the query string; that wins over the in-path ts.
+ thread_ts_from_query = parse_qs(parsed.query).get("thread_ts", [None])[0]
+ if thread_ts_from_query:
+ return channel, thread_ts_from_query
+ raw_ts = match.group("ts")
+ if len(raw_ts) < 7:
+ return None
+ return channel, f"{raw_ts[:-6]}.{raw_ts[-6:]}"
+
+
+@extend_schema(tags=["tasks"])
+class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """
+ API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
+ """
+
+ authentication_classes = [
+ SessionAuthentication,
+ PersonalAPIKeyAuthentication,
+ OAuthAccessTokenAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "task"
+ pagination_class = TasksPagination
+ # Fallback for drf-spectacular introspection only; every action declares its own
+ # request/response schema via @validated_request / @extend_schema.
+ serializer_class = TaskSerializer
+
+ def _user_id(self) -> int | None:
+ return getattr(self.request.user, "id", None)
+
+ def _write_serializer(self, data, *, partial: bool = False) -> TaskWriteSerializer:
+ serializer = TaskWriteSerializer(
+ data=data,
+ partial=partial,
+ context={"team": self.team, "team_id": self.team.id, "request": self.request},
+ )
+ serializer.is_valid(raise_exception=True)
+ return serializer
+
+ @validated_request(
+ query_serializer=TaskListQuerySerializer,
+ responses={
+ 200: OpenApiResponse(response=TaskSerializer, description="List of tasks"),
+ },
+ summary="List tasks",
+ description="Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, and created_by.",
+ )
+ def list(self, request, *args, **kwargs):
+ # Flatten the query-param multidict to single values, matching the original `params.get(...)`.
+ filters = {key: request.query_params.get(key) for key in request.query_params}
+ # internal/archived come from the validated query serializer (typed bool / choice).
+ filters["internal"] = getattr(request, "validated_query_data", {}).get("internal")
+ filters["archived"] = getattr(request, "validated_query_data", {}).get("archived")
+ is_debug_or_staff = settings.DEBUG or request.user.is_staff
+ tasks = tasks_facade.list_tasks(
+ self.team_id, self._user_id(), filters=filters, is_debug_or_staff=is_debug_or_staff
+ )
+ page = self.paginate_queryset(tasks)
+ if page is not None:
+ return self.get_paginated_response(TaskSerializer(page, many=True).data)
+ return Response(TaskSerializer(tasks, many=True).data)
+
+ @extend_schema(
+ responses={200: OpenApiResponse(response=TaskSerializer, description="Task")},
+ summary="Get task",
+ description="Retrieve a single task by ID.",
+ )
+ def retrieve(self, request, pk=None, **kwargs):
+ bypass_visibility = _is_internal_debug_team(self.team_id) and request.query_params.get("ph_debug") == "true"
+ task = tasks_facade.get_task_detail(pk, self.team_id, self._user_id(), bypass_visibility=bypass_visibility)
+ if task is None:
+ raise NotFound()
+ return Response(TaskSerializer(task).data)
+
+ @extend_schema(request=TaskWriteSerializer, responses={201: TaskSerializer})
+ def create(self, request, **kwargs):
+ serializer = self._write_serializer(request.data)
+ task = tasks_facade.create_task(self.team_id, self._user_id(), validated_data=dict(serializer.validated_data))
+ return Response(TaskSerializer(task).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(request=TaskWriteSerializer, responses={200: TaskSerializer})
+ def update(self, request, pk=None, **kwargs):
+ return self.partial_update(request, pk=pk, **kwargs)
+
+ @extend_schema(request=TaskWriteSerializer, responses={200: TaskSerializer})
+ def partial_update(self, request, pk=None, **kwargs):
+ serializer = self._write_serializer(request.data, partial=True)
+ task = tasks_facade.update_task(
+ pk, self.team_id, self._user_id(), validated_data=dict(serializer.validated_data)
+ )
+ if task is None:
+ raise NotFound()
+ return Response(TaskSerializer(task).data)
+
+ @extend_schema(responses={204: None})
+ def destroy(self, request, pk=None, **kwargs):
+ if not tasks_facade.soft_delete_task(pk, self.team_id, self._user_id()):
+ raise NotFound()
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRepositoriesResponseSerializer,
+ description="Distinct repositories used by tasks in the current project.",
+ ),
+ },
+ summary="List distinct task repositories",
+ description="Return the set of repositories referenced by non-deleted, non-internal tasks in the current project. Used to populate repository filter pickers without being constrained by task list pagination.",
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path="repositories",
+ required_scopes=["task:read"],
+ pagination_class=None,
+ filter_backends=[],
+ )
+ def repositories(self, request, **kwargs):
+ repositories = tasks_facade.list_task_repositories(self.team_id, self._user_id())
+ serializer = TaskRepositoriesResponseSerializer({"repositories": repositories})
+ return Response(serializer.data)
+
+ @validated_request(
+ request_serializer=TaskSummariesRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskSummarySerializer(many=True),
+ description="Summary fields for the requested tasks",
+ ),
+ },
+ summary="Fetch task summaries by ID",
+ description=(
+ "Returns summary for the requested tasks: `id`, `title`, `repository`, `created_at`, "
+ "`updated_at`, and the latest run's `status` and `environment`."
+ ),
+ parameters=[
+ OpenApiParameter(
+ name="limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Page size for the paginated response.",
+ ),
+ OpenApiParameter(
+ name="offset",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Offset into the result set for pagination.",
+ ),
+ ],
+ )
+ @action(
+ detail=False,
+ methods=["post"],
+ url_path="summaries",
+ required_scopes=["task:read"],
+ filter_backends=[],
+ )
+ def summaries(self, request, **kwargs):
+ ids = request.validated_data["ids"]
+ summaries = tasks_facade.get_task_summaries(self.team_id, self._user_id(), ids=ids)
+ page = self.paginate_queryset(summaries)
+ if page is not None:
+ return self.get_paginated_response(TaskSummarySerializer(page, many=True).data)
+ return Response(TaskSummarySerializer(summaries, many=True).data)
+
+ @validated_request(
+ query_serializer=RepositoryReadinessQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=RepositoryReadinessResponseSerializer,
+ description="Repository readiness status",
+ ),
+ },
+ summary="Get repository readiness",
+ description="Get autonomy readiness details for a specific repository in the current project.",
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path="repository_readiness",
+ required_scopes=["task:read"],
+ )
+ def repository_readiness(self, request, **kwargs):
+ repository = request.validated_query_data["repository"]
+ window_days = request.validated_query_data["window_days"]
+ refresh = request.validated_query_data["refresh"]
+
+ result = tasks_facade.compute_repository_readiness(
+ self.team_id,
+ repository=repository,
+ window_days=window_days,
+ refresh=refresh,
+ )
+ return Response(result)
+
+ @validated_request(
+ query_serializer=SlackThreadContextQuerySerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=SlackThreadContextResponseSerializer,
+ description="Task, runs, and Temporal workflow handles for the Slack thread.",
+ ),
+ 400: OpenApiResponse(description="Malformed Slack URL or unparseable thread identifiers."),
+ 403: OpenApiResponse(description="Endpoint is gated to PostHog-internal debugging."),
+ 404: OpenApiResponse(description="No SlackThreadTaskMapping exists for the parsed (channel, thread_ts)."),
+ },
+ summary="Resolve a Slack thread to its task, runs, and Temporal workflows",
+ description=(
+ "PostHog-internal debug tool. Resolves a Slack permalink to the linked task, its runs, "
+ "the task-processing and mention-dispatch Temporal workflow ids/URLs, and presigned log URLs."
+ ),
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path="slack_thread_context",
+ required_scopes=["task:read"],
+ pagination_class=None,
+ filter_backends=[],
+ )
+ def slack_thread_context(self, request, **kwargs):
+ if not _is_internal_debug_team(self.team_id):
+ return Response(
+ {"detail": "slack-thread-context is restricted to PostHog-internal debugging."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ url = request.validated_query_data["url"]
+ parsed = _parse_slack_thread_url(url)
+ if parsed is None:
+ return Response(
+ {"detail": "Could not parse channel/thread_ts from the provided Slack URL.", "url": url},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ channel, thread_ts = parsed
+ result = tasks_facade.resolve_slack_thread_context(
+ self.team_id, channel=channel, thread_ts=thread_ts, url=url, build_url=request.build_absolute_uri
+ )
+ if result.outcome == "no_mapping" and (thread := result.no_mapping_thread) is not None:
+ return Response(
+ {
+ "detail": "no_mapping",
+ "thread": {
+ "url": thread.url,
+ "channel": thread.channel,
+ "thread_ts": thread.thread_ts,
+ "slack_workspace_id": thread.slack_workspace_id,
+ "mentioning_slack_user_id": thread.mentioning_slack_user_id,
+ },
+ },
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ serializer = SlackThreadContextResponseSerializer(result.context)
+ return Response(serializer.data)
+
+ @validated_request(
+ request_serializer=TaskStagedArtifactsPrepareUploadRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskStagedArtifactsPrepareUploadResponseSerializer,
+ description="Prepared staged uploads for the requested artifacts",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
+ 404: OpenApiResponse(description="Task not found"),
+ },
+ summary="Prepare staged direct uploads for task attachments",
+ description="Reserve S3 object keys for task attachments before creating a new run and return presigned POST forms for direct uploads.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="staged_artifacts/prepare_upload",
+ required_scopes=["task:write"],
+ )
+ def staged_artifacts_prepare_upload(self, request, pk=None, **kwargs):
+ result = tasks_facade.prepare_task_staged_artifacts(
+ pk,
+ self.team_id,
+ self._user_id(),
+ artifacts=request.validated_data["artifacts"],
+ upload_expiration_seconds=TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS,
+ )
+ if result is None:
+ raise NotFound()
+ if result.error is not None:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": result.error}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ serializer = TaskStagedArtifactsPrepareUploadResponseSerializer({"artifacts": result.artifacts})
+ return Response(serializer.data)
+
+ @validated_request(
+ request_serializer=TaskStagedArtifactsFinalizeUploadRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskStagedArtifactsFinalizeUploadResponseSerializer,
+ description="Finalized staged artifacts available for the next task run",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
+ 404: OpenApiResponse(description="Task not found"),
+ },
+ summary="Finalize staged direct uploads for task attachments",
+ description="Verify staged S3 uploads and cache their metadata so they can be attached to the next run created for this task.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="staged_artifacts/finalize_upload",
+ required_scopes=["task:write"],
+ )
+ def staged_artifacts_finalize_upload(self, request, pk=None, **kwargs):
+ result = tasks_facade.finalize_task_staged_artifacts(
+ pk, self.team_id, self._user_id(), artifacts=request.validated_data["artifacts"]
+ )
+ if result is None:
+ raise NotFound()
+ if result.error is not None:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": result.error}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ serializer = TaskStagedArtifactsFinalizeUploadResponseSerializer({"artifacts": result.artifacts})
+ return Response(serializer.data)
+
+ @extend_schema(request=TaskRunCreateRequestSchemaSerializer)
+ @validated_request(
+ request_serializer=TaskRunCreateRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),
+ 404: OpenApiResponse(description="Task not found"),
+ 429: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
+ ),
+ },
+ summary="Run task",
+ description="Create a new task run and kick off the workflow.",
+ )
+ @action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])
+ def run(self, request, pk=None, **kwargs):
+ # Original order: 404 if the task isn't visible, then gate (always cloud) before the run.
+ if not tasks_facade.task_visible(pk, self.team_id, self._user_id()):
+ raise NotFound()
+
+ if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
+ return limit_response
+
+ result = tasks_facade.run_task(pk, self.team_id, self._user_id(), validated_data=dict(request.validated_data))
+ if result is None:
+ raise NotFound()
+ if result.error is not None:
+ return self._task_error_response(result.error)
+ return Response(TaskSerializer(result.task).data)
+
+ @staticmethod
+ def _task_error_response(error: tasks_contracts.TaskValidationError) -> Response:
+ if error.kind == "error":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": error.detail}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if error.kind == "detail":
+ body: dict[str, Any] = {"detail": error.detail}
+ if error.missing_artifact_ids is not None:
+ body["missing_artifact_ids"] = error.missing_artifact_ids
+ return Response(body, status=status.HTTP_400_BAD_REQUEST)
+ return Response(
+ {"type": "validation_error", "code": error.code, "detail": error.detail, "attr": error.attr},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ @validated_request(
+ request_serializer=TaskPresenceBeaconRequestSerializer,
+ responses={
+ 204: OpenApiResponse(description="Presence recorded for this device."),
+ 404: OpenApiResponse(description="`device_id` does not match a push token registered by the caller."),
+ },
+ summary="Beacon presence for a device watching this task",
+ description=(
+ "Idempotent upsert: marks the calling user + `device_id` as actively watching this task "
+ "for the next ~60 seconds. While at least one device for the user has a non-expired "
+ "presence row for this task, the push fanout will skip ALL of that user's other "
+ "registered devices for task notifications — the contract is 'if any device is "
+ "demonstrably watching, suppress the others'. Clients call this every ~30s while the "
+ "task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row."
+ ),
+ )
+ @action(
+ detail=True,
+ methods=["post", "delete"],
+ url_path="presence",
+ required_scopes=["task:write"],
+ )
+ def presence(self, request, pk=None, **kwargs):
+ device_id = request.validated_data["device_id"]
+ if request.method == "DELETE":
+ outcome = tasks_facade.leave_task_presence(pk, self.team_id, self._user_id(), device_id=device_id)
+ else:
+ outcome = tasks_facade.beacon_task_presence(pk, self.team_id, self._user_id(), device_id=device_id)
+ if outcome == "not_found":
+ raise NotFound("device_id does not match a push token registered by the caller")
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+@extend_schema(tags=["task-automations"])
+class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """API for managing scheduled task automations."""
+
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "task"
+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]
+
+ def _write_serializer(self, data, *, partial: bool = False) -> TaskAutomationWriteSerializer:
+ serializer = TaskAutomationWriteSerializer(
+ data=data, partial=partial, context={"team": self.team, "team_id": self.team.id}
+ )
+ serializer.is_valid(raise_exception=True)
+ return serializer
+
+ @staticmethod
+ def _facade_kwargs(validated_data: dict) -> dict:
+ """Translate the resolved ``github_integration`` instance to its id for the facade."""
+ kwargs = dict(validated_data)
+ if "github_integration" in kwargs:
+ integration = kwargs.pop("github_integration")
+ kwargs["github_integration_id"] = integration.id if integration is not None else None
+ return kwargs
+
+ @extend_schema(responses={200: TaskAutomationSerializer(many=True)})
+ def list(self, request, **kwargs):
+ automations = tasks_facade.list_task_automations(self.team_id, getattr(request.user, "id", None))
+ page = self.paginate_queryset(automations)
+ if page is not None:
+ return self.get_paginated_response(TaskAutomationSerializer(page, many=True).data)
+ return Response(TaskAutomationSerializer(automations, many=True).data)
+
+ @extend_schema(responses={200: TaskAutomationSerializer})
+ def retrieve(self, request, pk=None, **kwargs):
+ automation = tasks_facade.get_task_automation(pk, self.team_id, getattr(request.user, "id", None))
+ if automation is None:
+ raise NotFound()
+ return Response(TaskAutomationSerializer(automation).data)
+
+ @extend_schema(request=TaskAutomationWriteSerializer, responses={201: TaskAutomationSerializer})
+ def create(self, request, **kwargs):
+ serializer = self._write_serializer(request.data)
+ automation = tasks_facade.create_task_automation(
+ self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data)
+ )
+ return Response(TaskAutomationSerializer(automation).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(request=TaskAutomationWriteSerializer, responses={200: TaskAutomationSerializer})
+ def partial_update(self, request, pk=None, **kwargs):
+ serializer = self._write_serializer(request.data, partial=True)
+ automation = tasks_facade.update_task_automation(
+ pk, self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data)
+ )
+ if automation is None:
+ raise NotFound()
+ return Response(TaskAutomationSerializer(automation).data)
+
+ @extend_schema(responses={204: None})
+ def destroy(self, request, pk=None, **kwargs):
+ if not tasks_facade.delete_task_automation(pk, self.team_id, getattr(request.user, "id", None)):
+ raise NotFound()
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ @extend_schema(request=None, responses={200: TaskAutomationSerializer})
+ @action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])
+ def run(self, request, pk=None, **kwargs):
+ automation = tasks_facade.run_task_automation_now(pk, self.team_id, getattr(request.user, "id", None))
+ if automation is None:
+ raise NotFound()
+ return Response(TaskAutomationSerializer(automation).data)
+
+
+@extend_schema(tags=["task-runs", "tasks"])
+class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """
+ API for managing task runs. Each run represents an execution of a task.
+ """
+
+ authentication_classes = [
+ SessionAuthentication,
+ PersonalAPIKeyAuthentication,
+ OAuthAccessTokenAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "task"
+ http_method_names = ["get", "post", "patch", "head", "options"]
+ pagination_class = TasksPagination
+ # Fallback for drf-spectacular introspection only; every action declares its own
+ # request/response schema via @validated_request / @extend_schema.
+ serializer_class = TaskRunDetailSerializer
+
+ def get_serializer_context(self):
+ return {**super().get_serializer_context(), "team": self.team, "team_id": self.team.id}
+
+ def _task_id(self) -> str:
+ task_id = self.kwargs.get("parent_lookup_task_id")
+ if not task_id:
+ raise NotFound("Task ID is required")
+ return task_id
+
+ def _user_id(self) -> int | None:
+ return getattr(self.request.user, "id", None)
+
+ def _ensure_task_accessible(self) -> str:
+ """Gate access to the parent task, mirroring the old ``safely_get_queryset``.
+
+ ``?ph_debug=true`` lets internal-debug teams read other members' runs through read-only
+ actions; connection_token is a GET but mints a write-capable token, so it stays gated.
+ """
+ task_id = self._task_id()
+ is_internal_debug_read = (
+ _is_internal_debug_team(self.team_id)
+ and self.action in ("list", "retrieve", "logs", "session_logs", "stream")
+ and self.request.query_params.get("ph_debug") == "true"
+ )
+ if not tasks_facade.task_accessible_for_run_view(
+ task_id, self.team_id, self._user_id(), bypass_visibility=is_internal_debug_read
+ ):
+ raise NotFound("Task not found")
+ return task_id
+
+ def _get_run_or_404(self, pk) -> tasks_contracts.TaskRunDetailDTO:
+ task_id = self._ensure_task_accessible()
+ run = tasks_facade.get_task_run_detail(pk, task_id, self.team_id)
+ if run is None:
+ raise NotFound()
+ return run
+
+ @validated_request(
+ responses={
+ 200: OpenApiResponse(response=TaskRunDetailSerializer, description="List of task runs"),
+ },
+ summary="List task runs",
+ description="Get a list of runs for a specific task.",
+ )
+ def list(self, request, *args, **kwargs):
+ task_id = self._ensure_task_accessible()
+ runs = tasks_facade.list_task_runs(task_id, self.team_id)
+ page = self.paginate_queryset(runs)
+ if page is not None:
+ return self.get_paginated_response(TaskRunDetailSerializer(page, many=True).data)
+ return Response(TaskRunDetailSerializer(runs, many=True).data)
+
+ @validated_request(
+ responses={
+ 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Task run"),
+ 404: OpenApiResponse(description="Task run not found"),
+ },
+ summary="Get task run",
+ description="Retrieve a single run for a specific task.",
+ )
+ def retrieve(self, request, pk=None, **kwargs):
+ return Response(TaskRunDetailSerializer(self._get_run_or_404(pk)).data)
+
+ def _validation_error_response(self, error: tasks_contracts.TaskRunValidationError) -> Response:
+ if error.kind == "detail":
+ return Response({"detail": error.detail}, status=status.HTTP_400_BAD_REQUEST)
+ return Response(
+ {"type": "validation_error", "code": error.code, "detail": error.detail, "attr": error.attr},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ @validated_request(
+ request_serializer=TaskRunBootstrapCreateRequestSerializer,
+ responses={
+ 201: OpenApiResponse(response=TaskRunDetailSerializer, description="Created task run"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid task run payload"),
+ 429: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
+ ),
+ },
+ summary="Create task run",
+ description="Create a new run for a specific task without starting execution.",
+ )
+ def create(self, request, *args, **kwargs):
+ task_id = self._task_id()
+ environment = request.validated_data.get("environment", tasks_facade.TaskRunEnvironment.LOCAL)
+
+ # Gate cloud runs before the run row is created; local runs aren't limited.
+ if environment == tasks_facade.TaskRunEnvironment.CLOUD:
+ if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
+ return limit_response
+
+ result = tasks_facade.bootstrap_task_run(
+ task_id, self.team_id, self._user_id(), validated_data=dict(request.validated_data)
+ )
+ if result is None:
+ raise NotFound("Task not found")
+ if result.error is not None:
+ return self._validation_error_response(result.error)
+ return Response(TaskRunDetailSerializer(result.run).data, status=status.HTTP_201_CREATED)
+
+ @validated_request(
+ request_serializer=TaskRunStartRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=TaskSerializer, description="Task with updated latest run"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid start payload"),
+ 404: OpenApiResponse(description="Task run not found"),
+ 429: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
+ ),
+ },
+ summary="Start task run",
+ description="Start an existing cloud run after any initial run-scoped attachments have been uploaded.",
+ )
+ @action(detail=True, methods=["post"], url_path="start", required_scopes=["task:write"])
+ def start(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+
+ startable = tasks_facade.check_task_run_startable(pk, task_id, self.team_id)
+ if startable == "not_found":
+ raise NotFound()
+ if startable == "not_cloud":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Only cloud runs can be started via this endpoint"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if startable.startswith("bad_status:"):
+ current_status = startable.split(":", 1)[1]
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {
+ "error": f"Only queued or not_started cloud runs can be started (current status: {current_status})"
+ }
+ ).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ # Backstop: don't launch the cloud workflow for an over-limit team.
+ if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
+ return limit_response
+
+ outcome, started_task_id = tasks_facade.start_task_run(
+ pk, task_id, self.team_id, self._user_id(), validated_data=dict(request.validated_data)
+ )
+ if outcome == "not_found":
+ raise NotFound()
+ if outcome.startswith("missing_artifacts:"):
+ missing = [m for m in outcome.split(":", 1)[1].split(",") if m]
+ return Response(
+ {
+ "detail": "Some pending_user_artifact_ids are invalid for this run",
+ "missing_artifact_ids": missing,
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ if started_task_id is None:
+ raise NotFound()
+ task_dto = tasks_facade.get_task_detail(started_task_id, self.team_id, self._user_id())
+ if task_dto is None:
+ raise NotFound()
+ return Response(TaskSerializer(task_dto).data)
+
+ @validated_request(
+ request_serializer=TaskRunUpdateSerializer,
+ responses={
+ 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Updated task run"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid update data"),
+ 404: OpenApiResponse(description="Task run not found"),
+ },
+ summary="Update task run",
+ description="Update a task run with status, stage, branch, output, and state information.",
+ strict_request_validation=True,
+ )
+ def update(self, request, *args, **kwargs):
+ return self.partial_update(request, *args, **kwargs)
+
+ @validated_request(
+ request_serializer=TaskRunUpdateSerializer,
+ responses={
+ 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Updated task run"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid update data"),
+ 404: OpenApiResponse(description="Task run not found"),
+ },
+ summary="Update task run",
+ strict_request_validation=True,
+ )
+ def partial_update(self, request, *args, **kwargs):
+ pk = kwargs.get("pk")
+ if pk is None:
+ raise NotFound()
+ task_id = self._ensure_task_accessible()
+ run = tasks_facade.update_task_run(pk, task_id, self.team_id, validated_data=dict(request.validated_data))
+ if run is None:
+ raise NotFound()
+ return Response(TaskRunDetailSerializer(run).data)
+
+ @validated_request(
+ request_serializer=TaskRunSetOutputRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run with updated output"),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Set run output",
+ description="Update the output field for a task run (e.g., PR URL, commit SHA, etc.)",
+ )
+ @action(
+ detail=True,
+ methods=["patch"],
+ url_path="set_output",
+ required_scopes=["task:write"],
+ )
+ def set_output(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ output_data = request.validated_data["output"]
+
+ validation_error = tasks_facade.validate_set_output(pk, task_id, self.team_id, output=output_data)
+ if validation_error is not None:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": validation_error}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ run = tasks_facade.set_task_run_output(pk, task_id, self.team_id, output=output_data)
+ if run is None:
+ raise NotFound()
+ return Response(TaskRunDetailSerializer(run).data)
+
+ @validated_request(
+ request_serializer=TaskRunAppendLogRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run with updated log"),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid log entries"),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Append log entries",
+ description="Append one or more log entries to the task run log array",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="append_log",
+ required_scopes=["task:write"],
+ )
+ def append_log(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ timer = ServerTimingsGathered()
+
+ entries = request.validated_data["entries"]
+ with timer("s3_append"):
+ run = tasks_facade.append_task_run_log(pk, task_id, self.team_id, entries=entries)
+ if run is None:
+ raise NotFound()
+
+ response = Response(TaskRunDetailSerializer(run).data)
+ response["Server-Timing"] = timer.to_header_string()
+ return response
+
+ @validated_request(
+ request_serializer=TaskRunRelayMessageRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunRelayMessageResponseSerializer,
+ description="Relay accepted",
+ ),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Relay run message to Slack",
+ description="Queue a Slack relay workflow to post a run message into the mapped Slack thread.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="relay_message",
+ required_scopes=["task:write"],
+ )
+ def relay_message(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ relay_status, relay_id = tasks_facade.relay_task_run_message(
+ pk, task_id, self.team_id, text=request.validated_data["text"]
+ )
+ if relay_status == "failed":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Failed to queue Slack relay"}).data,
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ if relay_status == "accepted":
+ return Response({"status": "accepted", "relay_id": relay_id})
+ return Response({"status": "skipped"})
+
+ @validated_request(
+ request_serializer=TaskRunArtifactsUploadRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunArtifactsUploadResponseSerializer,
+ description="Run with updated artifact manifest",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Upload artifacts for a task run",
+ description="Persist task artifacts to S3 and attach them to the run manifest.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="artifacts",
+ required_scopes=["task:write"],
+ )
+ def artifacts(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ manifest = tasks_facade.upload_task_run_artifacts(
+ pk, task_id, self.team_id, artifacts=request.validated_data["artifacts"]
+ )
+ if manifest is None:
+ raise NotFound()
+ serializer = TaskRunArtifactsUploadResponseSerializer({"artifacts": manifest})
+ return Response(serializer.data)
+
+ @validated_request(
+ request_serializer=TaskRunArtifactsPrepareUploadRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunArtifactsPrepareUploadResponseSerializer,
+ description="Prepared uploads for the requested artifacts",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Prepare direct uploads for task run artifacts",
+ description="Reserve S3 object keys for task artifacts and return presigned POST forms for direct uploads.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="artifacts/prepare_upload",
+ required_scopes=["task:write"],
+ )
+ def artifacts_prepare_upload(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ prepared, ok = tasks_facade.prepare_task_run_artifact_uploads(
+ pk,
+ task_id,
+ self.team_id,
+ artifacts=request.validated_data["artifacts"],
+ upload_expiration_seconds=TASK_RUN_ARTIFACT_UPLOAD_EXPIRATION_SECONDS,
+ form_overhead_bytes=TASK_RUN_ARTIFACT_UPLOAD_FORM_OVERHEAD_BYTES,
+ )
+ if prepared is None and ok:
+ raise NotFound()
+ if not ok:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Unable to generate upload URL"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ serializer = TaskRunArtifactsPrepareUploadResponseSerializer({"artifacts": prepared})
+ return Response(serializer.data)
+
+ @validated_request(
+ request_serializer=TaskRunArtifactsFinalizeUploadRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunArtifactsFinalizeUploadResponseSerializer,
+ description="Run with updated artifact manifest",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid artifact payload"),
+ 404: OpenApiResponse(description="Run not found"),
+ },
+ summary="Finalize direct uploads for task run artifacts",
+ description="Verify directly uploaded S3 objects and attach them to the run artifact manifest.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="artifacts/finalize_upload",
+ required_scopes=["task:write"],
+ )
+ def artifacts_finalize_upload(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ finalized_entries, error = tasks_facade.finalize_task_run_artifact_uploads(
+ pk, task_id, self.team_id, artifacts=request.validated_data["artifacts"]
+ )
+ if finalized_entries is None and error is None:
+ raise NotFound()
+ if error is not None:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": error}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ serializer = TaskRunArtifactsFinalizeUploadResponseSerializer({"artifacts": finalized_entries})
+ return Response(serializer.data)
+
+ @validated_request(
+ request_serializer=TaskRunArtifactPresignRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunArtifactPresignResponseSerializer,
+ description="Presigned URL for the requested artifact",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request"),
+ 404: OpenApiResponse(description="Artifact not found"),
+ },
+ summary="Generate presigned URL for an artifact",
+ description="Returns a temporary, signed URL that can be used to download a specific artifact.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="artifacts/presign",
+ required_scopes=["task:read"],
+ )
+ def artifacts_presign(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ storage_path = request.validated_data["storage_path"]
+ url, error = tasks_facade.presign_task_run_artifact(pk, task_id, self.team_id, storage_path=storage_path)
+ if url is None and error is None:
+ raise NotFound()
+ if error == "not_found":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ if error == "unavailable":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Unable to generate download URL"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ serializer = TaskRunArtifactPresignResponseSerializer({"url": url, "expires_in": 3600})
+ return Response(serializer.data)
+
+ @validated_request(
+ request_serializer=TaskRunArtifactPresignRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ description="Artifact content",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Invalid request"),
+ 404: OpenApiResponse(description="Artifact not found"),
+ },
+ summary="Download an artifact through the backend",
+ description="Streams artifact content for a task run artifact after validating that it belongs to the run.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="artifacts/download",
+ required_scopes=["task:read"],
+ )
+ def artifacts_download(self, request, pk=None, **kwargs):
+ 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.
+ content, artifact, error = tasks_facade.read_task_run_artifact(
+ pk, task_id, self.team_id, storage_path=storage_path
+ )
+ if content is None and artifact is None and error is None:
+ raise NotFound()
+ if error == "not_found":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Artifact not found on this run"}).data,
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ if error == "read_failed":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Unable to read artifact"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if error == "content_missing":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Artifact content not found"}).data,
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ if artifact is None:
+ raise NotFound()
+
+ response = HttpResponse(
+ content,
+ content_type=str(artifact.get("content_type") or "application/octet-stream"),
+ )
+ response["Cache-Control"] = "no-cache"
+ response["Content-Disposition"] = (
+ f'attachment; filename="{os.path.basename(str(artifact.get("name") or "artifact"))}"'
+ )
+ return response
+
+ @extend_schema(
+ extensions={"x-product": "logs"},
+ responses={
+ 200: OpenApiResponse(description="Log content in JSONL format"),
+ 404: OpenApiResponse(description="Task run not found"),
+ },
+ summary="Get task run logs",
+ description=(
+ "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."
+ ),
+ )
+ @action(detail=True, methods=["get"], url_path="logs", required_scopes=["task:read"])
+ def logs(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ timer = ServerTimingsGathered()
+ with timer("s3_read"):
+ log_content = tasks_facade.read_task_run_logs(pk, task_id, self.team_id)
+ if log_content is None:
+ raise NotFound()
+
+ response = HttpResponse(log_content, content_type="application/jsonl")
+ response["Cache-Control"] = "no-cache"
+ response["Server-Timing"] = timer.to_header_string()
+ return response
+
+ @validated_request(
+ responses={
+ 200: OpenApiResponse(
+ response=ConnectionTokenResponseSerializer,
+ description="Connection token for direct sandbox connection",
+ ),
+ 404: OpenApiResponse(description="Task run not found"),
+ },
+ summary="Get sandbox connection token",
+ description="Generate a JWT token for direct connection to the sandbox. Valid for 24 hours.",
+ )
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="connection_token",
+ required_scopes=["task:write"],
+ )
+ def connection_token(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ user = request.user
+ token = tasks_facade.create_task_run_connection_token(
+ pk, task_id, self.team_id, user_id=user.id, distinct_id=user.distinct_id
+ )
+ if token is None:
+ raise NotFound()
+ return Response(ConnectionTokenResponseSerializer({"token": token}).data)
+
+ @validated_request(
+ request_serializer=TaskRunCommandRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=TaskRunCommandResponseSerializer,
+ description="Agent server response",
+ ),
+ 400: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="Invalid command or no active sandbox",
+ ),
+ 404: OpenApiResponse(description="Task run not found"),
+ 502: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Agent server unreachable"),
+ },
+ summary="Send command to task run",
+ description="Queue user_message JSON-RPC commands through the task workflow and forward sandbox control "
+ "commands to the agent server. Supports user_message, cancel, close, permission_response, "
+ "and set_config_option commands.",
+ strict_request_validation=True,
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="command",
+ required_scopes=["task:write"],
+ )
+ def command(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ method = request.validated_data["method"]
+ request_id = request.validated_data.get("id")
+ params = request.validated_data.get("params")
+
+ if method == "user_message":
+ command_params = dict(params or {})
+ artifact_ids = command_params.pop("artifact_ids", [])
+ if artifact_ids:
+ missing_artifact_ids, found = tasks_facade.validate_task_run_artifact_ids(
+ pk, task_id, self.team_id, artifact_ids=artifact_ids
+ )
+ if not found:
+ raise NotFound()
+ if missing_artifact_ids:
+ return Response(
+ {
+ "error": "Some artifact_ids are invalid for this run",
+ "missing_artifact_ids": missing_artifact_ids,
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ signal_result = tasks_facade.signal_task_run_user_message(
+ pk, task_id, self.team_id, content=command_params.get("content"), artifact_ids=artifact_ids
+ )
+ if signal_result is None:
+ raise NotFound()
+ if signal_result is False:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Failed to queue user message for task run"}).data,
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ response_payload: dict[str, Any] = {
+ "jsonrpc": request.validated_data["jsonrpc"],
+ "result": {"queued": True},
+ }
+ if request_id is not None:
+ response_payload["id"] = request_id
+ return Response(TaskRunCommandResponseSerializer(response_payload).data)
+
+ connection = tasks_facade.get_task_run_sandbox_connection(
+ pk, task_id, self.team_id, user_id=request.user.id, distinct_id=request.user.distinct_id
+ )
+ if connection is None:
+ raise NotFound()
+
+ if not connection.sandbox_url:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "No active sandbox for this task run"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ if not self._is_valid_sandbox_url(connection.sandbox_url):
+ logger.warning(f"Blocked request to disallowed sandbox URL for task run {pk}")
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Invalid sandbox URL"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ command_payload: dict = {
+ "jsonrpc": request.validated_data["jsonrpc"],
+ "method": method,
+ }
+ if params:
+ command_params = dict(params)
+ if command_params:
+ command_payload["params"] = command_params
+ if request_id is not None:
+ command_payload["id"] = request_id
+
+ try:
+ agent_response = self._proxy_command_to_agent_server(
+ sandbox_url=connection.sandbox_url,
+ connection_token=connection.connection_token,
+ sandbox_connect_token=connection.sandbox_connect_token,
+ payload=command_payload,
+ )
+
+ if agent_response.ok:
+ return Response(agent_response.json())
+
+ try:
+ error_body = agent_response.json()
+ except Exception:
+ error_body = {}
+
+ if agent_response.status_code == 401:
+ error_msg = error_body.get("error", "Agent server authentication failed")
+ logger.warning(f"Agent server auth failed for task run {pk}: {error_msg}")
+ elif agent_response.status_code == 400:
+ error_msg = error_body.get("error", "Agent server rejected the command")
+ logger.warning(f"Agent server rejected command for task run {pk}: {error_msg}")
+ else:
+ error_msg = error_body.get("error", f"Agent server returned {agent_response.status_code}")
+
+ return Response(
+ TaskRunErrorResponseSerializer({"error": error_msg}).data,
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ except http_requests.ConnectionError:
+ logger.warning(f"Agent server unreachable for task run {pk}")
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Agent server is not reachable"}).data,
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ except http_requests.Timeout:
+ logger.warning(f"Agent server request timed out for task run {pk}")
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Agent server request timed out"}).data,
+ status=status.HTTP_504_GATEWAY_TIMEOUT,
+ )
+ except Exception:
+ logger.exception(f"Failed to proxy command to agent server for task run {pk}")
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Failed to send command to agent server"}).data,
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ @staticmethod
+ def _is_valid_sandbox_url(url: str) -> bool:
+ """Validate sandbox URL against allowlist to prevent SSRF.
+
+ Only allows:
+ - http://localhost:{port} (Docker sandboxes)
+ - http://127.0.0.1:{port} (Docker sandboxes)
+ - https://*.modal.run (Modal sandboxes)
+ - https://*.modal.host (Modal connect token sandboxes)
+ """
+ from urllib.parse import urlparse
+
+ try:
+ parsed = urlparse(url)
+ except Exception:
+ return False
+
+ if parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1"):
+ return True
+
+ if (
+ parsed.scheme == "https"
+ and parsed.hostname
+ and (parsed.hostname.endswith(".modal.run") or parsed.hostname.endswith(".modal.host"))
+ ):
+ return True
+
+ return False
+
+ @staticmethod
+ def _proxy_command_to_agent_server(
+ sandbox_url: str,
+ connection_token: str | None,
+ sandbox_connect_token: str | None,
+ payload: dict,
+ ) -> http_requests.Response:
+ headers = {
+ "Content-Type": "application/json",
+ "Authorization": f"Bearer {connection_token}",
+ }
+
+ command_url = f"{sandbox_url.rstrip('/')}/command"
+
+ # Modal connect tokens use Authorization: Bearer for tunnel auth,
+ # which conflicts with the JWT auth the agent server expects.
+ # Pass the Modal token as a query parameter instead so both
+ # auth mechanisms can coexist.
+ params = {}
+ if sandbox_connect_token:
+ params["_modal_connect_token"] = sandbox_connect_token
+
+ return http_requests.post(
+ command_url,
+ json=payload,
+ headers=headers,
+ params=params,
+ timeout=600,
+ )
+
+ @validated_request(
+ query_serializer=TaskRunSessionLogsQuerySerializer,
+ responses={
+ 200: OpenApiResponse(description="Filtered log events as JSON array"),
+ 404: OpenApiResponse(description="Task run not found"),
+ },
+ summary="Get filtered task run session logs",
+ description="Fetch session log entries for a task run with optional filtering by timestamp, event type, and limit.",
+ )
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="session_logs",
+ required_scopes=["task:read"],
+ )
+ def session_logs(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ timer = ServerTimingsGathered()
+
+ with timer("s3_read"):
+ log_content = tasks_facade.read_task_run_session_log_content(pk, task_id, self.team_id)
+ if log_content is None:
+ raise NotFound()
+
+ if not log_content.strip():
+ response = JsonResponse([], safe=False)
+ response["X-Total-Count"] = "0"
+ response["X-Filtered-Count"] = "0"
+ response["X-Matching-Count"] = "0"
+ response["X-Has-More"] = "false"
+ response["Cache-Control"] = "no-cache"
+ response["Server-Timing"] = timer.to_header_string()
+ return response
+
+ # Parse all JSONL entries
+ all_entries = []
+ for line in log_content.strip().split("\n"):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ all_entries.append(json.loads(line))
+ except json.JSONDecodeError:
+ continue
+
+ total_count = len(all_entries)
+
+ # Apply filters from validated query params
+ params = request.validated_query_data
+ after = params.get("after")
+ event_types_str = params.get("event_types")
+ exclude_types_str = params.get("exclude_types")
+ limit = params.get("limit", 1000)
+ offset = params.get("offset", 0)
+
+ event_types = {t.strip() for t in event_types_str.split(",") if t.strip()} if event_types_str else None
+ exclude_types = {t.strip() for t in exclude_types_str.split(",") if t.strip()} if exclude_types_str else None
+
+ with timer("filter"):
+ filtered = []
+ for entry in all_entries:
+ # Filter by timestamp (parse to avoid Z vs +00:00 and fractional second mismatches)
+ if after:
+ entry_ts = entry.get("timestamp", "")
+ if not entry_ts:
+ continue # Skip entries without timestamps
+ try:
+ entry_dt = datetime.fromisoformat(entry_ts.replace("Z", "+00:00"))
+ if entry_dt <= after:
+ continue
+ except (ValueError, TypeError):
+ continue # Skip entries with unparseable timestamps
+
+ # Determine the event type for filtering
+ event_type = self._get_event_type(entry)
+
+ if event_types and event_type not in event_types:
+ continue
+ if exclude_types and event_type in exclude_types:
+ continue
+
+ filtered.append(entry)
+
+ matching_count = len(filtered)
+ page = filtered[offset : offset + limit]
+ has_more = offset + len(page) < matching_count
+
+ response = JsonResponse(page, safe=False)
+ response["X-Total-Count"] = str(total_count)
+ response["X-Filtered-Count"] = str(matching_count)
+ response["X-Matching-Count"] = str(matching_count)
+ response["X-Has-More"] = "true" if has_more else "false"
+ response["Cache-Control"] = "no-cache"
+ response["Server-Timing"] = timer.to_header_string()
+ return response
+
+ @validated_request(
+ responses={
+ 200: OpenApiResponse(response=TaskRunDetailSerializer, description="Run resumed in cloud"),
+ 400: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer, description="Run already active or workflow failed"
+ ),
+ 429: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"
+ ),
+ },
+ summary="Resume task run in cloud",
+ description="Resume an existing task run in a cloud sandbox. Terminates any existing workflow and starts a new one.",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="resume_in_cloud",
+ required_scopes=["task:write"],
+ )
+ def resume_in_cloud(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ if tasks_facade.get_task_run_detail(pk, task_id, self.team_id) is None:
+ raise NotFound()
+
+ # Resume also runs in cloud: gate before handoff.
+ if (limit_response := cloud_usage_limit_response(request.user, self.team_id)) is not None:
+ return limit_response
+
+ outcome, run, _ = tasks_facade.resume_task_run_in_cloud(pk, task_id, self.team_id, self._user_id())
+ if outcome == "not_found":
+ raise NotFound()
+ if outcome == "already_active":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Run is already active in cloud"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if outcome.startswith("auth_error:"):
+ detail = outcome.split(":", 1)[1]
+ return Response(
+ {
+ "type": "validation_error",
+ "code": "github_authorization_required",
+ "detail": detail,
+ "attr": "pr_authorship_mode",
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if outcome == "workflow_failed":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Failed to start cloud workflow"}).data,
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ return Response(TaskRunDetailSerializer(run).data)
+
+ @staticmethod
+ def _format_sse_event(data: dict, *, event_id: str | None = None, event_name: str | None = None) -> bytes:
+ parts: list[str] = []
+ if event_name:
+ parts.append(f"event: {event_name}")
+ if event_id:
+ parts.append(f"id: {event_id}")
+ parts.append(f"data: {json.dumps(data)}")
+ return ("\n".join(parts) + "\n\n").encode()
+
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="stream",
+ required_scopes=["task:read"],
+ renderer_classes=[ServerSentEventRenderer],
+ )
+ def stream(self, request, pk=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ stream_info = tasks_facade.get_task_run_stream_info(pk, task_id, self.team_id)
+ if stream_info is None:
+ raise NotFound()
+
+ stream_key = get_task_run_stream_key(str(stream_info.id))
+ use_dedicated_stream = run_uses_dedicated_stream(stream_info.state)
+ last_event_id = request.headers.get("Last-Event-ID")
+ start_latest = request.GET.get("start") == "latest"
+ format_sse_event = self._format_sse_event
+ origin_product = stream_info.origin_product
+
+ async def async_stream() -> AsyncGenerator[bytes]:
+ redis_stream = TaskRunRedisStream(stream_key, use_dedicated_stream)
+ connection_started_at = asyncio.get_running_loop().time()
+ # Default to client_disconnect: any exit that isn't an explicit
+ # completion/error/unavailable is the client (or proxy) going away.
+ outcome: StreamConnectionOutcome = "client_disconnect"
+ # Record opened inside the try so the closed counter only fires when
+ # the open succeeded — keeps opened/closed balanced for the
+ # active-connections gauge regardless of which increment fails.
+ opened = False
+ try:
+ observe_stream_connection_opened(origin_product)
+ opened = True
+ delay = TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS
+ wait_started_at = asyncio.get_running_loop().time()
+ last_keepalive_at = wait_started_at
+
+ while not await redis_stream.exists():
+ now = asyncio.get_running_loop().time()
+ if now - wait_started_at >= TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS:
+ outcome = "unavailable"
+ yield format_sse_event({"error": "Stream not available"}, event_name="error")
+ return
+
+ if now - last_keepalive_at >= TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS:
+ last_keepalive_at = now
+ yield format_sse_event(
+ TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,
+ event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,
+ )
+
+ await asyncio.sleep(delay)
+ delay = min(
+ delay + TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
+ TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
+ )
+
+ # Only reconnects (Last-Event-ID set) can suffer a trimmed resume
+ # point, and that's the only case where stream depth vs the trim
+ # cap is interesting — so skip the extra Redis reads on fresh
+ # connects. Best-effort: never break the stream.
+ if last_event_id:
+ try:
+ observe_stream_length_on_connect(await redis_stream.get_length())
+ if await redis_stream.resume_point_trimmed(last_event_id):
+ observe_stream_resume_gap(origin_product)
+ logger.warning(
+ "task_run_stream_resume_gap",
+ extra={"stream_key": stream_key, "last_event_id": last_event_id},
+ )
+ except Exception:
+ logger.warning(
+ "task_run_stream_attach_observe_failed",
+ extra={"stream_key": stream_key},
+ exc_info=True,
+ )
+
+ start_id = last_event_id or "0"
+ if not last_event_id and start_latest:
+ start_id = await redis_stream.get_latest_stream_id() or "0"
+ try:
+ async for stream_item in redis_stream.read_stream_entries(
+ start_id=start_id,
+ keepalive_interval_seconds=TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS,
+ ):
+ if stream_item is None:
+ yield format_sse_event(
+ TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,
+ event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,
+ )
+ continue
+ event_id, event = stream_item
+ yield format_sse_event(event, event_id=event_id)
+ outcome = "completed"
+ except TaskRunStreamError as e:
+ outcome = "stream_error"
+ logger.error("TaskRunRedisStream error for stream %s: %s", stream_key, e, exc_info=True)
+ yield format_sse_event({"error": str(e)}, event_name="error")
+ finally:
+ if opened:
+ duration = asyncio.get_running_loop().time() - connection_started_at
+ observe_stream_connection_closed(origin_product, outcome, duration)
+
+ return StreamingHttpResponse(
+ async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream()),
+ content_type="text/event-stream",
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
+
+ @staticmethod
+ def _get_event_type(entry: dict) -> str:
+ """Extract the event type from a log entry for filtering purposes.
+
+ For _posthog/* events, returns the notification method (e.g., '_posthog/console').
+ For session/update events, returns the sessionUpdate value (e.g., 'agent_message_chunk').
+ """
+ notification = entry.get("notification", {})
+ if not isinstance(notification, dict):
+ return ""
+ method = notification.get("method", "")
+
+ if method == "session/update":
+ params = notification.get("params", {})
+ update = params.get("update", {}) if isinstance(params, dict) else {}
+ return str(update.get("sessionUpdate", method)) if isinstance(update, dict) else method
+
+ return method
+
+
+@extend_schema(tags=["code-invites"])
+class CodeInviteViewSet(viewsets.ViewSet):
+ """API for redeeming PostHog Code invite codes."""
+
+ authentication_classes = [
+ SessionAuthentication,
+ PersonalAPIKeyAuthentication,
+ OAuthAccessTokenAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+
+ scope_object = "task"
+
+ http_method_names = ["get", "post", "head", "options"]
+ throttle_classes = [CodeInviteThrottle]
+
+ def get_permissions(self):
+ # Both endpoints are user-account-level operations (not project data).
+ if self.action in ("check_access", "redeem"):
+ return [IsAuthenticated()]
+ return super().get_permissions()
+
+ @validated_request(
+ request_serializer=CodeInviteRedeemRequestSerializer,
+ responses={
+ 200: OpenApiResponse(description="Invite code redeemed successfully"),
+ 400: OpenApiResponse(
+ response=TaskRunErrorResponseSerializer,
+ description="Invalid or expired invite code",
+ ),
+ },
+ summary="Redeem invite code",
+ description="Redeem a PostHog Code invite code to enable access.",
+ )
+ @action(detail=False, methods=["post"], url_path="redeem")
+ def redeem(self, request, **kwargs):
+ result = tasks_facade.redeem_code_invite(request.validated_data["code"], request.user.id)
+
+ if result.outcome == tasks_facade.CODE_INVITE_INVALID_CODE:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Invalid invite code"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if result.outcome == tasks_facade.CODE_INVITE_NOT_REDEEMABLE:
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "This invite code is no longer valid"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ return Response({"success": True})
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(description="Access check result"),
+ },
+ summary="Check access",
+ description="Check whether the authenticated user has access to PostHog Code.",
+ )
+ @action(detail=False, methods=["get"], url_path="check-access")
+ def check_access(self, request, **kwargs):
+ return Response({"has_access": tasks_access.has_tasks_access(request.user)})
+
+
+@extend_schema(tags=["sandbox-environments"])
+class SandboxEnvironmentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """API for managing sandbox environments that control network access for task runs."""
+
+ authentication_classes = [
+ SessionAuthentication,
+ PersonalAPIKeyAuthentication,
+ OAuthAccessTokenAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "task"
+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]
+
+ @extend_schema(responses={200: SandboxEnvironmentListSerializer(many=True)})
+ def list(self, request, **kwargs):
+ envs = tasks_facade.list_sandbox_environments(self.team_id, request.user.id)
+ page = self.paginate_queryset(envs)
+ if page is not None:
+ return self.get_paginated_response(SandboxEnvironmentListSerializer(page, many=True).data)
+ return Response(SandboxEnvironmentListSerializer(envs, many=True).data)
+
+ @extend_schema(responses={200: SandboxEnvironmentSerializer})
+ def retrieve(self, request, pk=None, **kwargs):
+ env = tasks_facade.get_sandbox_environment(pk, self.team_id, request.user.id)
+ if env is None:
+ raise NotFound()
+ return Response(SandboxEnvironmentSerializer(env).data)
+
+ @extend_schema(request=SandboxEnvironmentWriteSerializer, responses={201: SandboxEnvironmentSerializer})
+ def create(self, request, **kwargs):
+ serializer = SandboxEnvironmentWriteSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ env = tasks_facade.create_sandbox_environment(self.team_id, request.user.id, **serializer.validated_data)
+ return Response(SandboxEnvironmentSerializer(env).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(request=SandboxEnvironmentWriteSerializer, responses={200: SandboxEnvironmentSerializer})
+ def partial_update(self, request, pk=None, **kwargs):
+ serializer = SandboxEnvironmentWriteSerializer(data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ env = tasks_facade.update_sandbox_environment(pk, self.team_id, request.user.id, **serializer.validated_data)
+ if env is None:
+ raise NotFound()
+ return Response(SandboxEnvironmentSerializer(env).data)
+
+ @extend_schema(responses={204: None})
+ def destroy(self, request, pk=None, **kwargs):
+ if not tasks_facade.delete_sandbox_environment(pk, self.team_id, request.user.id):
+ raise NotFound()
+ return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/tasks/backend/presentation/views/code_home_api.py b/products/tasks/backend/presentation/views/code_home_api.py
new file mode 100644
index 000000000000..731ccc5ca745
--- /dev/null
+++ b/products/tasks/backend/presentation/views/code_home_api.py
@@ -0,0 +1,142 @@
+from rest_framework import status, viewsets
+from rest_framework.authentication import SessionAuthentication
+from rest_framework.decorators import action
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.permissions import APIScopePermission
+
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.contracts import (
+ CodeHomeDTO,
+ CodeHomeWorkstreamDTO,
+ CodeWorkflowConfigDTO,
+ CodeWorkflowDiagnosticDTO,
+)
+
+_AUTH_CLASSES = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+
+
+def _serialize_diagnostic(d: CodeWorkflowDiagnosticDTO) -> dict:
+ out = {"severity": d.severity, "code": d.code, "message": d.message}
+ if d.situation_id is not None:
+ out["situationId"] = d.situation_id
+ if d.action_id is not None:
+ out["actionId"] = d.action_id
+ return out
+
+
+def _serialize_config(config: CodeWorkflowConfigDTO) -> dict:
+ return {
+ "id": config.id,
+ "version": config.version,
+ "updatedAt": config.updated_at.isoformat(),
+ "bindings": config.bindings,
+ }
+
+
+def _serialize_home(home: CodeHomeDTO) -> dict:
+ return {
+ "activeAgents": [
+ {
+ "taskId": agent.task_id,
+ "title": agent.title,
+ "repoName": agent.repo_name,
+ "branch": agent.branch,
+ "status": agent.status,
+ "lastActivityAt": agent.last_activity_at,
+ "needsPermission": agent.needs_permission,
+ "cloudPrUrl": agent.cloud_pr_url,
+ }
+ for agent in home.active_agents
+ ],
+ "needsAttention": [_serialize_workstream(ws) for ws in home.needs_attention],
+ "inProgress": [_serialize_workstream(ws) for ws in home.in_progress],
+ }
+
+
+def _serialize_workstream(ws: CodeHomeWorkstreamDTO) -> dict:
+ return {
+ "id": ws.id,
+ "repoName": ws.repo_name,
+ "repoFullPath": ws.repo_full_path,
+ "branch": ws.branch,
+ "prUrl": ws.pr_url,
+ "pr": ws.pr,
+ "tasks": [
+ {
+ "id": t.id,
+ "title": t.title,
+ "status": t.status,
+ "isGenerating": t.is_generating,
+ "needsPermission": t.needs_permission,
+ "quickAction": t.quick_action,
+ }
+ for t in ws.tasks
+ ],
+ "situations": ws.situations,
+ "primarySituation": ws.primary_situation,
+ "lastActivityAt": ws.last_activity_at,
+ }
+
+
+class CodeWorkflowViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "task"
+ authentication_classes = _AUTH_CLASSES
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ hide_api_docs = True
+
+ def list(self, request, *args, **kwargs):
+ config = tasks_facade.get_code_workflow_config(self.team_id, request.user.id)
+ return Response(_serialize_config(config))
+
+ @action(detail=False, methods=["post"], url_path="save", required_scopes=["task:write"])
+ def save(self, request, **kwargs):
+ config_in = request.data.get("config") or {}
+ expected_version = request.data.get("expectedVersion")
+ bindings = config_in.get("bindings") or {}
+
+ result = tasks_facade.save_code_workflow_bindings(
+ self.team_id,
+ request.user.id,
+ bindings=bindings,
+ expected_version=expected_version,
+ )
+
+ if result.outcome == tasks_facade.CODE_WORKFLOW_CONFLICT:
+ return Response(
+ {"status": "conflict", "config": _serialize_config(result.config)},
+ status=status.HTTP_409_CONFLICT,
+ )
+ if result.outcome == tasks_facade.CODE_WORKFLOW_INVALID:
+ return Response(
+ {
+ "status": "invalid",
+ "config": _serialize_config(result.config),
+ "diagnostics": [_serialize_diagnostic(d) for d in result.diagnostics],
+ },
+ status=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ )
+ return Response({"status": "saved", "config": _serialize_config(result.config)})
+
+ @action(detail=False, methods=["post"], url_path="reset", required_scopes=["task:write"])
+ def reset(self, request, **kwargs):
+ config = tasks_facade.reset_code_workflow_bindings(self.team_id, request.user.id)
+ return Response(_serialize_config(config))
+
+
+class CodeHomeViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "task"
+ authentication_classes = _AUTH_CLASSES
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ hide_api_docs = True
+
+ def list(self, request, *args, **kwargs):
+ return Response(_serialize_home(tasks_facade.get_code_home(self.team_id, request.user.id)))
+
+ @action(detail=False, methods=["post"], url_path="refresh", required_scopes=["task:write"])
+ def refresh(self, request, **kwargs):
+ started = tasks_facade.refresh_team_code_workstreams(self.team_id)
+ return Response({"started": started}, status=status.HTTP_202_ACCEPTED)
diff --git a/products/tasks/backend/seat_api.py b/products/tasks/backend/presentation/views/seat_api.py
similarity index 100%
rename from products/tasks/backend/seat_api.py
rename to products/tasks/backend/presentation/views/seat_api.py
diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.py
index 5f50b1ad10de..fe594f096010 100644
--- a/products/tasks/backend/routes.py
+++ b/products/tasks/backend/routes.py
@@ -1,8 +1,8 @@
from posthog.api.routing import RouterRegistry
-import products.tasks.backend.api as tasks
-import products.tasks.backend.seat_api as seats
-import products.tasks.backend.code_home_api as code_home
+import products.tasks.backend.presentation.views.api as tasks
+import products.tasks.backend.presentation.views.seat_api as seats
+import products.tasks.backend.presentation.views.code_home_api as code_home
def register_routes(routers: RouterRegistry) -> None:
diff --git a/products/tasks/backend/services/mts_example/__init__.py b/products/tasks/backend/services/mts_example/__init__.py
deleted file mode 100644
index b2b932f3ea44..000000000000
--- a/products/tasks/backend/services/mts_example/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from products.tasks.backend.services.mts_example.runner import run_cursed_identifier_research
-from products.tasks.backend.services.mts_example.schemas import CursedItem, CursedItemCandidates
-
-__all__ = [
- "CursedItem",
- "CursedItemCandidates",
- "run_cursed_identifier_research",
-]
diff --git a/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
index 252037c0d395..482f4849ee7e 100644
--- a/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
+++ b/products/tasks/backend/temporal/code_workstreams/activities/rebuild_workstreams.py
@@ -12,8 +12,8 @@ from posthog.models.scoping import team_scope
from posthog.models.user_integration import UserIntegration
from posthog.temporal.common.utils import close_db_connections
-from products.tasks.backend.code_workstreams.classify import pick_primary_situation
-from products.tasks.backend.code_workstreams.grouping import (
+from products.tasks.backend.logic.code_workstreams.classify import pick_primary_situation
+from products.tasks.backend.logic.code_workstreams.grouping import (
PrInput,
TaskInput,
Workstream,
diff --git a/products/tasks/backend/temporal/conftest.py b/products/tasks/backend/temporal/conftest.py
index c0daef6a94c1..c91b4be99b9a 100644
--- a/products/tasks/backend/temporal/conftest.py
+++ b/products/tasks/backend/temporal/conftest.py
@@ -8,8 +8,8 @@ from temporalio.testing import ActivityEnvironment
from posthog.models import Integration, OAuthApplication, Organization, OrganizationMembership, Team, User
from posthog.temporal.common.logger import configure_logger
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.create_snapshot.activities.get_snapshot_context import SnapshotContext
from products.tasks.backend.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/create_snapshot/activities/cleanup_sandbox.py
index 20bc58545b84..4d4f02710e78 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/cleanup_sandbox.py
@@ -5,7 +5,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
-from products.tasks.backend.services.sandbox import Sandbox
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.temporal.observability import log_activity_execution
logger = logging.getLogger(__name__)
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py
index 2e12191107f7..681bf8d8f873 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/clone_repository.py
@@ -5,7 +5,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import GitHubAuthenticationError, RepositoryCloneError
-from products.tasks.backend.services.sandbox import Sandbox
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.temporal.observability import log_activity_execution
from ..utils import get_github_token
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py b/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py
index f9d5a40060bc..12978e2995a5 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/create_sandbox.py
@@ -5,7 +5,7 @@ from temporalio import activity
from posthog.models import Integration
from posthog.temporal.common.utils import asyncify
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_user
from products.tasks.backend.temporal.observability import log_activity_execution
from products.tasks.backend.temporal.process_task.utils import get_github_token, get_sandbox_api_url
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/create_snapshot.py b/products/tasks/backend/temporal/create_snapshot/activities/create_snapshot.py
index f54ed1ed6538..35f82628ac14 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/create_snapshot.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/create_snapshot.py
@@ -4,8 +4,8 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.models import SandboxSnapshot
-from products.tasks.backend.services.sandbox import Sandbox
from products.tasks.backend.temporal.observability import log_activity_execution
from .get_snapshot_context import SnapshotContext
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.py
index 1f693c45bf39..1fe084faa0dd 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/setup_repository.py
@@ -5,7 +5,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import RetryableRepositorySetupError
-from products.tasks.backend.services.sandbox import Sandbox
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.temporal.observability import log_activity_execution
from .get_snapshot_context import SnapshotContext
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_cleanup_sandbox.py
index 858fbd291183..41592802bb47 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_cleanup_sandbox.py
@@ -6,7 +6,7 @@ import pytest
import modal
from asgiref.sync import async_to_sync
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.create_snapshot.activities.cleanup_sandbox import (
CleanupSandboxInput,
cleanup_sandbox,
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.py
index 64c0f719f272..9b27f95ba97a 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_clone_repository.py
@@ -6,7 +6,7 @@ from unittest.mock import patch
from asgiref.sync import async_to_sync
from products.tasks.backend.exceptions import RepositoryCloneError, SandboxNotFoundError
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.create_snapshot.activities.clone_repository import (
CloneRepositoryInput,
clone_repository,
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py
index 225e460d58c4..f0df8a7f29c6 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_create_snapshot.py
@@ -6,8 +6,8 @@ import pytest
from asgiref.sync import async_to_sync
from products.tasks.backend.exceptions import SandboxNotFoundError, SnapshotCreationError
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.models import SandboxSnapshot
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.create_snapshot.activities.create_snapshot import (
CreateSnapshotInput,
create_snapshot,
diff --git a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.py b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.py
index dcc57c0c3fcb..b512b073c451 100644
--- a/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.py
+++ b/products/tasks/backend/temporal/create_snapshot/activities/tests/test_setup_repository.py
@@ -5,7 +5,7 @@ import pytest
from asgiref.sync import async_to_sync
from products.tasks.backend.exceptions import SandboxNotFoundError
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.create_snapshot.activities.get_snapshot_context import SnapshotContext
from products.tasks.backend.temporal.create_snapshot.activities.setup_repository import (
SetupRepositoryInput,
diff --git a/products/tasks/backend/temporal/create_snapshot/tests/test_workflow.py b/products/tasks/backend/temporal/create_snapshot/tests/test_workflow.py
index 38e1b58a09f1..d78695a7d255 100644
--- a/products/tasks/backend/temporal/create_snapshot/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/create_snapshot/tests/test_workflow.py
@@ -14,8 +14,8 @@ from temporalio.common import RetryPolicy
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxStatus
from products.tasks.backend.models import SandboxSnapshot
-from products.tasks.backend.services.sandbox import Sandbox, SandboxStatus
from products.tasks.backend.temporal.create_snapshot.activities import (
cleanup_sandbox,
clone_repository,
diff --git a/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py b/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
index b9e7ece832e0..dd5c83d8aae4 100644
--- a/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
+++ b/products/tasks/backend/temporal/execute_sandbox/activities/reap_orphaned_sandbox.py
@@ -22,8 +22,8 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.models import TaskRun
-from products.tasks.backend.services.sandbox import Sandbox
from products.tasks.backend.temporal.execute_sandbox.activities.sandbox_state import SANDBOX_ID_STATE_KEY
from products.tasks.backend.temporal.observability import log_activity_execution
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index 5687947074b9..5c717507cb51 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -24,7 +24,7 @@ from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.oauth import PosthogMcpScopes
-from products.tasks.backend.services.sandbox import is_public_sandbox_repo
+from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
from products.tasks.backend.temporal.constants import (
OUTBOUND_RETRY_BACKOFF,
PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,
diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
index ad77b225162b..0f83cc145406 100644
--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
@@ -6,10 +6,10 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import SandboxNotFoundError
+from products.tasks.backend.logic.services.sandbox import Sandbox
+from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_complete
from products.tasks.backend.models import TaskRun
from products.tasks.backend.redis import run_uses_dedicated_stream
-from products.tasks.backend.services.sandbox import Sandbox
-from products.tasks.backend.stream.redis_stream import publish_task_run_stream_complete
from products.tasks.backend.temporal.observability import log_activity_execution
logger = logging.getLogger(__name__)
diff --git a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
index e5cdd9f24fd4..0e1beadade34 100644
--- a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
@@ -5,8 +5,8 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.logic.services.sandbox import get_sandbox_class
from products.tasks.backend.models import TaskRun
-from products.tasks.backend.services.sandbox import get_sandbox_class
logger = structlog.get_logger(__name__)
diff --git a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py
index d7e3f7dfad7c..7ef1ae7fd3a2 100644
--- a/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/create_sandbox_from_snapshot.py
@@ -11,8 +11,8 @@ from products.tasks.backend.exceptions import (
SnapshotNotReadyError,
TaskNotFoundError,
)
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.models import SandboxSnapshot, Task
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.oauth import create_oauth_access_token
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
from products.tasks.backend.temporal.process_task.utils import (
diff --git a/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.py b/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.py
index 9d32ca562f3d..b3d70e289188 100644
--- a/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/execute_task_in_sandbox.py
@@ -6,8 +6,8 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import SandboxExecutionError, TaskExecutionFailedError
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.models import TaskRun
-from products.tasks.backend.services.sandbox import Sandbox
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
from .get_task_processing_context import TaskProcessingContext
diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
index 4733b5d74131..7ab0d9054bf0 100644
--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
@@ -49,10 +49,10 @@ def forward_pending_user_message(run_id: str) -> None:
successful delivery or non-retryable failure. Keeps it in state on retryable
failure to preserve recoverability.
"""
+ from products.tasks.backend.logic.services.agent_command import send_user_message
+ from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_token
+ from products.tasks.backend.logic.services.staged_artifacts import get_task_run_artifacts_by_id
from products.tasks.backend.models import TaskRun
- from products.tasks.backend.services.agent_command import send_user_message
- from products.tasks.backend.services.connection_token import create_sandbox_connection_token
- from products.tasks.backend.services.staged_artifacts import get_task_run_artifacts_by_id
try:
task_run = TaskRun.objects.select_related("task__created_by").get(id=run_id)
diff --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.py
index 1a5085073cff..03de15981ad5 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
@@ -9,18 +9,18 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundError
-from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
-from products.tasks.backend.services.connection_token import (
+from products.tasks.backend.logic.services.connection_token import (
SANDBOX_JWT_STATE_KID_KEY,
get_primary_sandbox_jwt_kid,
get_sandbox_jwt_public_key,
)
-from products.tasks.backend.services.sandbox import (
+from products.tasks.backend.logic.services.sandbox import (
Sandbox,
SandboxConfig,
SandboxTemplate,
parse_sandbox_repo_mount_map,
)
+from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import StepTimer, increment_snapshot_usage
from products.tasks.backend.temporal.oauth import create_oauth_access_token
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
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.py
index be9c95f80bc6..a96dc1e8feef 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
@@ -17,12 +17,12 @@ from products.tasks.backend.constants import (
SANDBOX_EVENT_INGEST_FEATURE_FLAG,
)
from products.tasks.backend.exceptions import TaskInvalidStateError, TaskNotFoundError
-from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun
-from products.tasks.backend.services.sandbox_config import (
+from products.tasks.backend.logic.services.sandbox_config import (
MAX_SANDBOX_CPU_CORES,
MAX_SANDBOX_MEMORY_GB,
MAX_SANDBOX_TTL_SECONDS,
)
+from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun
from products.tasks.backend.temporal.constants import resolve_inactivity_timeout
from products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_context
from products.tasks.backend.temporal.process_task.utils import (
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index a55527d7a7e2..8ee6d5382229 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -9,14 +9,14 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import GitHubAuthenticationError, OAuthTokenError, TaskNotFoundError
-from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
-from products.tasks.backend.services.agentsh import ENV_FILE, INFRASTRUCTURE_DOMAINS, _get_debug_only_domains
-from products.tasks.backend.services.connection_token import (
+from products.tasks.backend.logic.services.agentsh import ENV_FILE, INFRASTRUCTURE_DOMAINS, _get_debug_only_domains
+from products.tasks.backend.logic.services.connection_token import (
SANDBOX_JWT_STATE_KID_KEY,
get_primary_sandbox_jwt_kid,
get_sandbox_jwt_public_key,
)
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.models import SandboxSnapshot, Task, TaskRun
from products.tasks.backend.temporal.metrics import StepTimer, increment_sandbox_created, increment_snapshot_usage
from products.tasks.backend.temporal.oauth import create_oauth_access_token
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
diff --git a/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.py b/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.py
index 33bfc37acf86..65433adfb6a8 100644
--- a/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.py
+++ b/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.py
@@ -6,7 +6,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
-from products.tasks.backend.services.sandbox import Sandbox
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.temporal.observability import log_activity_execution
logger = logging.getLogger(__name__)
@@ -53,7 +53,7 @@ def read_sandbox_logs(input: ReadSandboxLogsInput) -> str:
# agentsh audit events (network policy decisions)
try:
- from products.tasks.backend.services.agentsh import build_audit_query_command
+ from products.tasks.backend.logic.services.agentsh import build_audit_query_command
audit_result = sandbox.execute(build_audit_query_command(), timeout_seconds=10)
audit_output = audit_result.stdout.strip()
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index 78edcc66b933..d556fe26c0ce 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -6,10 +6,10 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify
from products.tasks.backend.exceptions import SandboxNotFoundError, SandboxNotRunningError, TaskNotFoundError
+from products.tasks.backend.logic.services.agent_command import send_refresh_session
+from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_token
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.models import Task, TaskRun
-from products.tasks.backend.services.agent_command import send_refresh_session
-from products.tasks.backend.services.connection_token import create_sandbox_connection_token
-from products.tasks.backend.services.sandbox import Sandbox
from products.tasks.backend.temporal.metrics import increment_credential_refresh
from products.tasks.backend.temporal.observability import log_activity_execution, track_event
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
index fcd8d9fc6ae5..46ba983a34c6 100644
--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
@@ -13,14 +13,14 @@ from temporalio import activity
from posthog.temporal.common.utils import close_db_connections
+from products.tasks.backend.logic.services.agent_command import validate_sandbox_url
+from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_token
+from products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
from products.tasks.backend.models import (
Task as TaskModel,
TaskRun as TaskRunModel,
)
from products.tasks.backend.redis import run_uses_dedicated_stream
-from products.tasks.backend.services.agent_command import validate_sandbox_url
-from products.tasks.backend.services.connection_token import create_sandbox_connection_token
-from products.tasks.backend.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDS, resolve_inactivity_timeout
from ee.hogai.sandbox import is_turn_complete
@@ -423,8 +423,8 @@ _is_end_of_turn = is_turn_complete
async def _emit_agentsh_events(sandbox_id: str, run_id: str, last_ts_ns: list[int]) -> None:
"""Read recent agentsh network events and emit as debug console logs."""
- from products.tasks.backend.services.agentsh import build_audit_query_command
- from products.tasks.backend.services.sandbox import Sandbox
+ from products.tasks.backend.logic.services.agentsh import build_audit_query_command
+ from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.temporal.observability import emit_agent_log
try:
diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
index 5e72c64fe674..dac2a26f8917 100644
--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
@@ -9,18 +9,18 @@ from temporalio import activity
from posthog.temporal.common.utils import close_db_connections
from posthog.temporal.oauth import PosthogMcpScopes
-from products.tasks.backend.models import TaskRun
-from products.tasks.backend.redis import get_tasks_stream_redis_sync, run_uses_dedicated_stream
-from products.tasks.backend.services.agent_command import (
+from products.tasks.backend.logic.services.agent_command import (
FOLLOWUP_TIMEOUT_SECONDS,
REFRESH_TIMEOUT_SECONDS,
CommandResult,
send_refresh_session,
send_user_message,
)
-from products.tasks.backend.services.connection_token import create_sandbox_connection_token
-from products.tasks.backend.services.staged_artifacts import get_task_run_artifacts_by_id
-from products.tasks.backend.stream.redis_stream import get_task_run_stream_key
+from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_token
+from products.tasks.backend.logic.services.staged_artifacts import get_task_run_artifacts_by_id
+from products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_key
+from products.tasks.backend.models import TaskRun
+from products.tasks.backend.redis import get_tasks_stream_redis_sync, run_uses_dedicated_stream
from products.tasks.backend.temporal.oauth import create_oauth_access_token
from products.tasks.backend.temporal.process_task.utils import (
get_sandbox_ph_mcp_configs,
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 bd34c09f561c..6865d1d3597a 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
@@ -8,10 +8,10 @@ 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.logic.services.agentsh import ENV_FILE, ENV_WRAPPER_SCRIPT, build_exec_prefix
+from products.tasks.backend.logic.services.connection_token import create_sandbox_event_ingest_token
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxBase
from products.tasks.backend.models import Task, TaskRun
-from products.tasks.backend.services.agentsh import ENV_FILE, ENV_WRAPPER_SCRIPT, build_exec_prefix
-from products.tasks.backend.services.connection_token import create_sandbox_event_ingest_token
-from products.tasks.backend.services.sandbox import Sandbox, SandboxBase
from products.tasks.backend.temporal.oauth import create_oauth_access_token
from products.tasks.backend.temporal.observability import emit_agent_log, log_activity_execution
from products.tasks.backend.temporal.process_task.utils import (
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
index 8cad11bed5fa..07a6fdf795fc 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
@@ -8,8 +8,8 @@ import modal
from asgiref.sync import async_to_sync
from products.tasks.backend.exceptions import SandboxNotFoundError
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
-from products.tasks.backend.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
from products.tasks.backend.temporal.process_task.activities.cleanup_sandbox import CleanupSandboxInput, cleanup_sandbox
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.py
index 1f95a84a3ed2..853fd365fd6b 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_execute_task_in_sandbox.py
@@ -5,7 +5,7 @@ import pytest
from asgiref.sync import async_to_sync
from products.tasks.backend.exceptions import SandboxNotFoundError
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxTemplate
from products.tasks.backend.temporal.process_task.activities.execute_task_in_sandbox import (
ExecuteTaskInput,
execute_task_in_sandbox,
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py
index 74c231ca77a0..e705a54b5db9 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_sandbox_for_repository.py
@@ -5,8 +5,8 @@ import pytest
from asgiref.sync import async_to_sync
+from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.models import SandboxSnapshot
-from products.tasks.backend.services.sandbox import Sandbox
from products.tasks.backend.temporal.process_task.activities.get_sandbox_for_repository import (
GetSandboxForRepositoryInput,
get_sandbox_for_repository,
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py
index 013efc2e3570..24513037d82b 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_inject_fresh_tokens_on_resume.py
@@ -5,9 +5,9 @@ from asgiref.sync import async_to_sync
from posthog.models import OrganizationMembership, User
+from products.tasks.backend.logic.services.agentsh import ENV_FILE
+from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.models import SandboxEnvironment
-from products.tasks.backend.services.agentsh import ENV_FILE
-from products.tasks.backend.services.sandbox import ExecutionResult
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.provision_sandbox import (
InjectFreshTokensOnResumeInput,
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index 9fcfc3006fa9..d019ea8ca5cb 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -4,7 +4,7 @@ from unittest.mock import MagicMock, patch
from asgiref.sync import async_to_sync
from products.tasks.backend.exceptions import SandboxExecutionError, SandboxNotFoundError, SandboxNotRunningError
-from products.tasks.backend.services.sandbox import ExecutionResult
+from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (
RefreshSandboxCredentialsInput,
refresh_sandbox_credentials,
diff --git a/products/tasks/backend/temporal/process_task/sandbox_credentials.py b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
index cd189b07af91..e3343112dff3 100644
--- a/products/tasks/backend/temporal/process_task/sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/sandbox_credentials.py
@@ -11,8 +11,8 @@ import redis
from posthog.models.user_integration import UserGitHubIntegration
from posthog.redis import get_client
+from products.tasks.backend.logic.services.agentsh import ENV_FILE
from products.tasks.backend.models import Task, TaskRun
-from products.tasks.backend.services.agentsh import ENV_FILE
from products.tasks.backend.temporal.process_task.utils import (
PrAuthorshipMode,
get_pr_authorship_mode,
@@ -22,7 +22,7 @@ from products.tasks.backend.temporal.process_task.utils import (
)
if TYPE_CHECKING:
- from products.tasks.backend.services.sandbox import SandboxBase
+ from products.tasks.backend.logic.services.sandbox import SandboxBase
from .activities.get_task_processing_context import TaskProcessingContext
@@ -155,7 +155,7 @@ def _live_sandboxes_for_user_integration(user_integration_id: int) -> list[tuple
def _propagate_user_token(user_integration_id: int, token: str) -> int:
- from products.tasks.backend.services.sandbox import Sandbox # noqa: PLC0415
+ from products.tasks.backend.logic.services.sandbox import Sandbox # noqa: PLC0415
applied = 0
for run_id, sandbox_id, repository in _live_sandboxes_for_user_integration(user_integration_id):
diff --git a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
index 4db77a8a004a..945245b81f36 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py
@@ -66,8 +66,8 @@ class TestForwardPendingUserMessage(TestCase):
run.refresh_from_db()
assert run.state == {"mode": "background"}
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_pending_message_delivered_successfully(self, mock_send, mock_token):
run = self._make_run(
state={
@@ -84,9 +84,9 @@ class TestForwardPendingUserMessage(TestCase):
run.refresh_from_db()
assert "pending_user_message" not in run.state
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
@patch("products.tasks.backend.temporal.observability.posthoganalytics.capture")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_timeout_skips_retry_to_avoid_duplicate_delivery(self, mock_send, mock_capture, mock_token):
run = self._make_run(
state={
@@ -105,8 +105,8 @@ class TestForwardPendingUserMessage(TestCase):
run.refresh_from_db()
assert run.state.get("pending_user_message") == "fix the tests"
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_connection_error_retries_with_longer_timeout(self, mock_send, mock_token):
run = self._make_run(
state={
@@ -124,8 +124,8 @@ class TestForwardPendingUserMessage(TestCase):
run.refresh_from_db()
assert run.state.get("pending_user_message") == "fix the tests"
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_non_retryable_failure_clears_message_from_state(self, mock_send, mock_token):
run = self._make_run(
state={
@@ -142,7 +142,7 @@ class TestForwardPendingUserMessage(TestCase):
assert "pending_user_message" not in run.state
@patch(
- "products.tasks.backend.services.staged_artifacts.get_task_run_artifacts_by_id",
+ "products.tasks.backend.logic.services.staged_artifacts.get_task_run_artifacts_by_id",
return_value=([], ["artifact-123"]),
)
def test_missing_pending_artifacts_raises_and_preserves_state(self, mock_get_artifacts):
@@ -162,8 +162,8 @@ class TestForwardPendingUserMessage(TestCase):
assert run.state["pending_user_artifact_ids"] == ["artifact-123"]
@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_slack_origin_posts_reply_and_cleans_progress(
self,
mock_send,
@@ -208,8 +208,8 @@ class TestForwardPendingUserMessage(TestCase):
assert "pending_user_message_ts" not in run.state
@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_slack_origin_non_retryable_failure_posts_error(
self,
mock_send,
@@ -252,8 +252,8 @@ class TestForwardPendingUserMessage(TestCase):
assert "pending_user_message" not in run.state
@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
- @patch("products.tasks.backend.services.connection_token.create_sandbox_connection_token", return_value="jwt")
- @patch("products.tasks.backend.services.agent_command.send_user_message")
+ @patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")
+ @patch("products.tasks.backend.logic.services.agent_command.send_user_message")
def test_slack_origin_posts_fallback_when_reply_text_missing(self, mock_send, mock_token, mock_enqueue_relay):
run = self._make_run(
state={
diff --git a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
index efa1899bf2b8..709212421066 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_sandbox_credentials.py
@@ -3,7 +3,7 @@ import base64
import pytest
from unittest.mock import MagicMock, patch
-from products.tasks.backend.services.sandbox import ExecutionResult
+from products.tasks.backend.logic.services.sandbox import ExecutionResult
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
DEFAULT_REFRESH_INTERVAL_SECONDS,
diff --git a/products/tasks/backend/temporal/process_task/tests/test_sandbox_resource_overrides.py b/products/tasks/backend/temporal/process_task/tests/test_sandbox_resource_overrides.py
index 75d0319013ae..c4b14ce8d5c8 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_sandbox_resource_overrides.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_sandbox_resource_overrides.py
@@ -1,6 +1,6 @@
import pytest
-from products.tasks.backend.services.sandbox_config import (
+from products.tasks.backend.logic.services.sandbox_config import (
MAX_SANDBOX_CPU_CORES,
MAX_SANDBOX_MEMORY_GB,
MAX_SANDBOX_TTL_SECONDS,
diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
index 16e5ff27da5d..471fb3f60f3e 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
@@ -3,7 +3,7 @@ from unittest.mock import MagicMock, patch
from django.core.cache import cache
-from products.tasks.backend.services.agent_command import CommandResult
+from products.tasks.backend.logic.services.agent_command import CommandResult
from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (
REFRESH_RETRY_DELAY_SECONDS,
SendFollowupToSandboxInput,
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 9da487d50727..ca2ed0148b02 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -16,8 +16,8 @@ from temporalio.exceptions import ActivityError, RetryState
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxStatus, SandboxTemplate
from products.tasks.backend.models import SandboxSnapshot
-from products.tasks.backend.services.sandbox import Sandbox, SandboxConfig, SandboxStatus, SandboxTemplate
from products.tasks.backend.temporal.process_task import workflow as process_task_workflow_module
from products.tasks.backend.temporal.process_task.activities import (
CreateSandboxForRepositoryOutput,
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 3114a2512330..0753e8b209f3 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -677,7 +677,7 @@ def build_sandbox_environment_variables(
User-provided env vars are applied first so system vars always take precedence,
preventing a malicious SandboxEnvironment from overriding security-critical values.
"""
- from products.tasks.backend.services.connection_token import get_sandbox_jwt_public_key
+ from products.tasks.backend.logic.services.connection_token import get_sandbox_jwt_public_key
env_vars: dict[str, str] = {}
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index a4fa7f3b820b..4de266ce77e8 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -15,7 +15,7 @@ from temporalio.workflow import ParentClosePolicy
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.oauth import PosthogMcpScopes
-from products.tasks.backend.services.sandbox import is_public_sandbox_repo
+from products.tasks.backend.logic.services.sandbox import is_public_sandbox_repo
from products.tasks.backend.temporal.create_snapshot.workflow import CreateSnapshotForRepositoryInput
from products.tasks.backend.temporal.process_task.activities.get_pr_context import GetPrContextInput, get_pr_context
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index 8e1e09af372d..b49bfeb77502 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -8,7 +8,7 @@ from django.test import TestCase, override_settings
import yaml
from parameterized import parameterized
-from products.tasks.backend.services.agentsh import (
+from products.tasks.backend.logic.services.agentsh import (
AGENTSH_AUDIT_DB,
ENV_WRAPPER_SCRIPT,
INFRASTRUCTURE_DOMAINS,
@@ -274,7 +274,7 @@ class TestBuildExecPrefix(TestCase):
@override_settings(DEBUG=True, SANDBOX_PROVIDER="modal")
class TestModalSandboxAgentShWrapping(TestCase):
def test_command_without_domains_skips_agentsh_exec(self):
- from products.tasks.backend.services.modal_sandbox import ModalSandbox
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
sandbox = ModalSandbox.__new__(ModalSandbox)
cmd = sandbox._build_agent_server_command(
@@ -292,7 +292,7 @@ class TestModalSandboxAgentShWrapping(TestCase):
self.assertIn("nohup", cmd)
def test_command_includes_allowed_domains(self):
- from products.tasks.backend.services.modal_sandbox import ModalSandbox
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
sandbox = ModalSandbox.__new__(ModalSandbox)
cmd = sandbox._build_agent_server_command(
@@ -310,7 +310,7 @@ class TestModalSandboxAgentShWrapping(TestCase):
self.assertIn("example.com,api.example.com", cmd)
def test_command_includes_runtime_environment_variables(self):
- from products.tasks.backend.services.modal_sandbox import ModalSandbox
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
sandbox = ModalSandbox.__new__(ModalSandbox)
cmd = sandbox._build_agent_server_command(
@@ -330,8 +330,8 @@ class TestModalSandboxAgentShWrapping(TestCase):
self.assertIn("POSTHOG_CODE_REASONING_EFFORT=high", cmd)
def test_write_file_uses_filesystem_api_before_rename(self):
- from products.tasks.backend.services.modal_sandbox import ModalSandbox
- from products.tasks.backend.services.sandbox import ExecutionResult, SandboxConfig
+ from products.tasks.backend.logic.services.modal_sandbox import ModalSandbox
+ from products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfig
sandbox = ModalSandbox.__new__(ModalSandbox)
sandbox.id = "sb-123"
diff --git a/products/tasks/backend/tests/test_agentsh_docker.py b/products/tasks/backend/tests/test_agentsh_docker.py
index 3f731296eb86..53b058403769 100644
--- a/products/tasks/backend/tests/test_agentsh_docker.py
+++ b/products/tasks/backend/tests/test_agentsh_docker.py
@@ -82,14 +82,14 @@ class TestAgentshDockerEnforcement:
settings.SANDBOX_PROVIDER = "docker"
def _create_sandbox(self, sandbox_image):
- from products.tasks.backend.services.docker_sandbox import DockerSandbox
- from products.tasks.backend.services.sandbox import SandboxConfig
+ from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
+ from products.tasks.backend.logic.services.sandbox import SandboxConfig
config = SandboxConfig(name="test-agentsh")
return DockerSandbox.create(config)
def _setup_agentsh_and_exec(self, sandbox, test_command: str, allowed_domains: list[str]):
- from products.tasks.backend.services.agentsh import build_exec_prefix
+ from products.tasks.backend.logic.services.agentsh import build_exec_prefix
repo_path = "/tmp/workspace"
sandbox._setup_agentsh(repo_path, allowed_domains)
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 556f4f159b37..cab1cb815355 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -27,6 +27,23 @@ from posthog.models.user_integration import UserIntegration
from posthog.models.utils import generate_random_token_personal
from posthog.storage import object_storage
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.logic.services.code_usage_gate import (
+ CodeUsageStatus,
+ _gateway_usage_url,
+ get_posthog_code_usage,
+)
+from products.tasks.backend.logic.services.connection_token import (
+ get_sandbox_jwt_public_key,
+ reset_sandbox_jwt_key_cache,
+)
+from products.tasks.backend.logic.services.staged_artifacts import (
+ RUN_ARTIFACT_TTL_DAYS,
+ build_task_artifact_entry,
+ cache_task_staged_artifact,
+ get_task_staged_artifacts,
+)
+from products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
from products.tasks.backend.models import (
CodeInvite,
CodeInviteRedemption,
@@ -35,20 +52,10 @@ from products.tasks.backend.models import (
TaskAutomation,
TaskRun,
)
-from products.tasks.backend.serializers import (
+from products.tasks.backend.presentation.serializers import (
TASK_RUN_ARTIFACT_MAX_SIZE_BYTES,
TASK_RUN_PDF_ARTIFACT_MAX_SIZE_BYTES,
- TaskAutomationSerializer,
-)
-from products.tasks.backend.services.code_usage_gate import CodeUsageStatus, _gateway_usage_url, get_posthog_code_usage
-from products.tasks.backend.services.connection_token import get_sandbox_jwt_public_key, reset_sandbox_jwt_key_cache
-from products.tasks.backend.services.staged_artifacts import (
- RUN_ARTIFACT_TTL_DAYS,
- build_task_artifact_entry,
- cache_task_staged_artifact,
- get_task_staged_artifacts,
)
-from products.tasks.backend.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
from products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token
@@ -434,7 +441,7 @@ class TestTaskCreatorScoping(BaseTaskAPITest):
ids = sorted(item["id"] for item in response.json()["results"])
self.assertEqual(ids, [str(mine.id)])
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_other_user_task_returns_404(self, mock_workflow):
other_user = self.create_organization_user("victim")
task = self.create_task(created_by=other_user)
@@ -568,7 +575,7 @@ class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):
# can't easily force the row id, so substitute the test team's id and
# keep the deployment-region clause intact so off-US tests still flip.
self._bypass_patch = patch(
- "products.tasks.backend.api._is_internal_debug_team",
+ "products.tasks.backend.presentation.views.api._is_internal_debug_team",
side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",
)
self._bypass_patch.start()
@@ -656,7 +663,7 @@ class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_write_action_on_other_user_task_still_returns_404(self, _mock_workflow):
# POST /tasks/<id>/run/ is a write — bypass must NOT fire even when the
# `?ph_debug=true` opt-in is set; that param is read-only.
@@ -692,7 +699,7 @@ class TestTaskVisibilityInternalDebugRegionGate(BaseTaskAPITest):
# `team.id` match would pass on its own, leaving `CLOUD_DEPLOYMENT` as
# the only thing each test varies.
self._bypass_patch = patch(
- "products.tasks.backend.api._is_internal_debug_team",
+ "products.tasks.backend.presentation.views.api._is_internal_debug_team",
side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",
)
self._bypass_patch.start()
@@ -1123,7 +1130,7 @@ class TestTaskAPI(BaseTaskAPITest):
# archived_at should not be re-stamped because the value did not transition.
self.assertEqual(task.archived_at, original_archived_at)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_triggers_workflow(self, mock_workflow):
task = self.create_task()
@@ -1158,7 +1165,7 @@ class TestTaskAPI(BaseTaskAPITest):
("signal_report", {"run_source": "signal_report"}, "read_only"),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_resolves_mcp_scope_from_run_source(self, _name, payload, expected_scope, mock_workflow):
task = self.create_task()
@@ -1171,7 +1178,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(mock_workflow.call_args.kwargs["posthog_mcp_scopes"], expected_scope)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_sandbox_environment_id(self, mock_workflow):
task = self.create_task(created_by=self.user)
sandbox_environment = SandboxEnvironment.objects.create(
@@ -1204,7 +1211,7 @@ class TestTaskAPI(BaseTaskAPITest):
),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoints_reject_other_users_private_sandbox_environment(
self, _name, endpoint, payload_template, mock_workflow
):
@@ -1233,7 +1240,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertFalse(TaskRun.objects.filter(task=task).exists())
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_drops_inaccessible_inherited_sandbox_environment_id(self, mock_workflow):
other_user = self.create_organization_user("victim")
task = self.create_task(created_by=self.user)
@@ -1263,7 +1270,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertNotIn("sandbox_environment_id", run.state)
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_pending_user_message(self, mock_workflow):
task = self.create_task()
@@ -1284,7 +1291,7 @@ class TestTaskAPI(BaseTaskAPITest):
@patch("posthog.storage.object_storage.copy")
@patch("posthog.storage.object_storage.tag")
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_attaches_staged_artifacts(self, mock_workflow, mock_tag, mock_copy):
task = self.create_task()
staged_artifact = build_task_artifact_entry(
@@ -1334,7 +1341,7 @@ class TestTaskAPI(BaseTaskAPITest):
@patch("posthog.storage.object_storage.copy")
@patch("posthog.storage.object_storage.tag")
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_ignores_copy_failures_for_staged_artifacts(self, mock_workflow, mock_tag, mock_copy):
mock_copy.side_effect = AssertionError("copy should not be called")
task = self.create_task()
@@ -1375,7 +1382,7 @@ class TestTaskAPI(BaseTaskAPITest):
)
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_run_endpoint_creates_cloud_run_without_triggering_workflow(self, mock_workflow):
task = self.create_task()
@@ -1409,7 +1416,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(task_run.state["run_source"], "manual")
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_run_endpoint_caches_user_github_token(self, mock_workflow):
integration = Integration.objects.create(team=self.team, kind="github", config={"access_token": "token"})
task = Task.objects.create(
@@ -1437,7 +1444,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(get_cached_github_user_token(str(task_run.id)), "ghu_test_token")
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_run_endpoint_rejects_user_authorship_without_github_identity_when_no_repo(self, mock_workflow):
task = self.create_task()
@@ -1455,7 +1462,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(response.json()["code"], "github_authorization_required")
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_run_endpoint_persists_user_integration_when_no_repo(self, mock_workflow):
task = self.create_task(created_by=self.user)
user_integration = _grant_user_github_access(self.user)
@@ -1475,7 +1482,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(task.github_user_integration_id, user_integration.id)
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_create_run_endpoint_falls_back_to_team_integration_when_no_user_integration(self, mock_workflow):
integration = Integration.objects.create(team=self.team, kind="github", config={"access_token": "token"})
task = self.create_task(created_by=self.user)
@@ -1498,7 +1505,7 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(task_run.state["pr_authorship_mode"], "bot")
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_start_run_endpoint_triggers_workflow_for_existing_cloud_run(self, mock_workflow):
task = self.create_task()
task_run = task.create_run(environment=TaskRun.Environment.CLOUD)
@@ -1536,7 +1543,7 @@ class TestTaskAPI(BaseTaskAPITest):
posthog_mcp_scopes="full",
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_start_run_endpoint_rejects_missing_run_artifacts(self, mock_workflow):
task = self.create_task()
task_run = task.create_run(environment=TaskRun.Environment.CLOUD)
@@ -1557,7 +1564,7 @@ class TestTaskAPI(BaseTaskAPITest):
)
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_start_run_endpoint_rejects_non_startable_status(self, mock_workflow):
task = self.create_task()
task_run = task.create_run(environment=TaskRun.Environment.CLOUD)
@@ -1577,7 +1584,7 @@ class TestTaskAPI(BaseTaskAPITest):
)
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_start_run_endpoint_rolls_back_pending_state_when_workflow_trigger_fails(self, mock_workflow):
mock_workflow.side_effect = RuntimeError("workflow start failed")
task = self.create_task()
@@ -1626,7 +1633,7 @@ class TestTaskAPI(BaseTaskAPITest):
("auto",),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_initial_permission_mode(self, mode, mock_workflow):
task = self.create_task()
@@ -1641,7 +1648,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task_run.state["initial_permission_mode"] == mode
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_omits_initial_permission_mode_when_not_set(self, mock_workflow):
task = self.create_task()
@@ -1652,7 +1659,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert "initial_permission_mode" not in (task_run.state or {})
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_invalid_initial_permission_mode(self, mock_workflow):
task = self.create_task()
@@ -1665,7 +1672,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_combines_pending_user_message_and_initial_permission_mode(self, mock_workflow):
task = self.create_task()
@@ -1686,7 +1693,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task_run.state["initial_permission_mode"] == "plan"
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_pr_authorship_metadata(self, mock_workflow):
task = self.create_task()
task.repository = "posthog/posthog"
@@ -1715,7 +1722,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task.github_user_integration_id == user_integration.id
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_caches_github_user_token_backcompat(self, mock_workflow):
"""Backward-compat: callers that ship ``github_user_token`` have it cached per-run."""
task = self.create_task()
@@ -1741,7 +1748,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task_run.state["github_credential_source"] == "caller_token"
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_accepts_token_even_without_linked_identity(self, mock_workflow):
"""A caller-supplied token satisfies the preflight on its own (no identity required)."""
task = self.create_task()
@@ -1770,7 +1777,7 @@ class TestTaskAPI(BaseTaskAPITest):
("gpt_5_5_xhigh", "gpt-5.5", "xhigh"),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_runtime_metadata(self, _case_name, model, reasoning_effort, mock_workflow):
task = self.create_task()
@@ -1799,7 +1806,7 @@ class TestTaskAPI(BaseTaskAPITest):
mock_workflow.assert_called_once()
@parameterized.expand([("auto",), ("read-only",), ("full-access",)])
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_preserves_codex_initial_permission_mode(self, initial_permission_mode, mock_workflow):
task = self.create_task()
@@ -1837,7 +1844,7 @@ class TestTaskAPI(BaseTaskAPITest):
),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_mismatched_permission_mode(
self,
_case_name,
@@ -1869,7 +1876,7 @@ class TestTaskAPI(BaseTaskAPITest):
}
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_user_authorship_without_github_identity(self, mock_workflow):
task = self.create_task()
task.repository = "posthog/posthog"
@@ -1889,7 +1896,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.json()["code"] == "github_authorization_required"
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_user_authorship_when_refresh_token_expired(self, mock_workflow):
task = self.create_task()
task.repository = "posthog/posthog"
@@ -1913,7 +1920,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.json()["code"] == "github_authorization_required"
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_non_creator_with_404(self, mock_workflow: MagicMock) -> None:
# Cross-user run attempts are blocked at the queryset level: a teammate
# cannot see (let alone run) someone else's task. The previous
@@ -1940,7 +1947,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert not TaskRun.objects.filter(task=task).exists()
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_user_authorship_when_access_token_missing(self, mock_workflow: MagicMock) -> None:
task = self.create_task(created_by=self.user)
task.repository = "posthog/posthog"
@@ -1971,7 +1978,7 @@ class TestTaskAPI(BaseTaskAPITest):
("missing_model", {"runtime_adapter": "codex"}, "model"),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_incomplete_runtime_selection(self, _case_name, payload, expected_attr, mock_workflow):
task = self.create_task()
@@ -1997,7 +2004,7 @@ class TestTaskAPI(BaseTaskAPITest):
("gpt_5_5_max", "gpt-5.5", "max", "low, medium, high, xhigh"),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_unsupported_codex_reasoning_effort(
self, _case_name, model, reasoning_effort, supported_values, mock_workflow
):
@@ -2025,7 +2032,7 @@ class TestTaskAPI(BaseTaskAPITest):
}
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_unsupported_claude_reasoning_effort(self, mock_workflow):
task = self.create_task()
@@ -2060,7 +2067,7 @@ class TestTaskAPI(BaseTaskAPITest):
("max",),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_accepts_fable_reasoning_effort(self, reasoning_effort, mock_workflow):
task = self.create_task()
@@ -2081,7 +2088,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task_run.state["reasoning_effort"] == reasoning_effort
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_derives_provider_from_runtime_adapter(self, mock_workflow):
task = self.create_task()
@@ -2101,7 +2108,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert latest_run["provider"] == "openai"
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_rejects_user_authorship_without_github_identity_when_no_repo(self, mock_workflow):
task = self.create_task()
@@ -2119,7 +2126,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.json()["code"] == "github_authorization_required"
mock_workflow.assert_not_called()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_persists_user_integration_when_no_repo(self, mock_workflow):
task = self.create_task(created_by=self.user)
user_integration = _grant_user_github_access(self.user)
@@ -2139,7 +2146,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task.github_user_integration_id == user_integration.id
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_falls_back_to_team_integration_when_no_user_integration(self, mock_workflow):
integration = Integration.objects.create(team=self.team, kind="github", config={"access_token": "token"})
task = self.create_task(created_by=self.user)
@@ -2163,7 +2170,7 @@ class TestTaskAPI(BaseTaskAPITest):
assert task_run.state["pr_authorship_mode"] == "bot"
mock_workflow.assert_called_once()
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_resume_carries_forward_pr_authorship_metadata(self, mock_workflow):
task = self.create_task()
previous_run = TaskRun.objects.create(
@@ -2207,7 +2214,7 @@ class TestTaskAPI(BaseTaskAPITest):
# Token passed on a BOT resume must not be cached — only USER mode runs use it.
assert get_cached_github_user_token(str(task_run.id)) is None
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_resume_rejects_inherited_invalid_reasoning_effort(self, mock_workflow):
task = self.create_task()
previous_run = TaskRun.objects.create(
@@ -2908,7 +2915,7 @@ class TestTaskSummariesAPI(BaseTaskAPITest):
class TestTaskAutomationAPI(BaseTaskAPITest):
- @patch("products.tasks.backend.api.sync_automation_schedule")
+ @patch("products.tasks.backend.automation_service.sync_automation_schedule")
def test_create_automation(self, mock_sync_schedule):
response = self.client.post(
"/api/projects/@current/task_automations/",
@@ -2997,25 +3004,22 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
},
)
- def test_create_automation_rolls_back_task_when_automation_create_fails(self):
- serializer = TaskAutomationSerializer(
- data={
- "name": "Daily PRs",
- "prompt": "Check my GitHub PRs",
- "repository": "posthog/posthog",
- "cron_expression": "0 9 * * *",
- "timezone": "Europe/London",
- },
- context={"team": self.team, "request": MagicMock(user=self.user)},
- )
- serializer.is_valid(raise_exception=True)
-
+ @patch("products.tasks.backend.facade.api._sync_automation_schedule")
+ def test_create_automation_rolls_back_task_when_automation_create_fails(self, mock_sync_schedule):
with patch(
- "products.tasks.backend.serializers.TaskAutomation.objects.create",
+ "products.tasks.backend.facade.api.TaskAutomation.objects.create",
side_effect=RuntimeError("automation create failed"),
):
with self.assertRaises(RuntimeError):
- serializer.save()
+ tasks_facade.create_task_automation(
+ self.team.id,
+ self.user.id,
+ name="Daily PRs",
+ prompt="Check my GitHub PRs",
+ repository="posthog/posthog",
+ cron_expression="0 9 * * *",
+ timezone="Europe/London",
+ )
self.assertFalse(
Task.objects.filter(
@@ -3025,7 +3029,7 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
).exists()
)
- @patch("products.tasks.backend.api.sync_automation_schedule")
+ @patch("products.tasks.backend.automation_service.sync_automation_schedule")
def test_update_automation(self, mock_sync_schedule):
automation = self.create_automation()
@@ -3052,30 +3056,26 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
self.assertFalse(automation.enabled)
mock_sync_schedule.assert_called_once_with(automation)
- def test_update_automation_rolls_back_automation_when_task_update_fails(self):
+ @patch("products.tasks.backend.facade.api._sync_automation_schedule")
+ def test_update_automation_rolls_back_automation_when_task_update_fails(self, mock_sync_schedule):
automation = self.create_automation()
- serializer = TaskAutomationSerializer(
- automation,
- data={
- "name": "Updated PR check",
- "cron_expression": "30 14 * * *",
- },
- partial=True,
- context={"team": self.team, "request": MagicMock(user=self.user)},
- )
- serializer.is_valid(raise_exception=True)
-
with patch.object(Task, "save", side_effect=RuntimeError("task update failed")):
with self.assertRaises(RuntimeError):
- serializer.save()
+ tasks_facade.update_task_automation(
+ automation.id,
+ self.team.id,
+ self.user.id,
+ name="Updated PR check",
+ cron_expression="30 14 * * *",
+ )
automation.refresh_from_db()
automation.task.refresh_from_db()
self.assertEqual(automation.cron_expression, "0 9 * * *")
self.assertEqual(automation.task.title, "Daily PRs")
- @patch("products.tasks.backend.api.delete_automation_schedule")
+ @patch("products.tasks.backend.automation_service.delete_automation_schedule")
def test_delete_automation(self, mock_delete_schedule):
automation = self.create_automation()
@@ -3085,7 +3085,7 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
mock_delete_schedule.assert_called_once()
self.assertFalse(TaskAutomation.objects.filter(id=automation.id).exists())
- @patch("products.tasks.backend.api.run_task_automation")
+ @patch("products.tasks.backend.automation_service.run_task_automation")
def test_run(self, mock_run_task_automation):
automation = self.create_automation()
@@ -3097,7 +3097,7 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
class TestTaskRunAPI(BaseTaskAPITest):
@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
def test_update_run_status_publishes_stream_state_event(self, mock_signal, mock_publish_stream_state_event):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
@@ -3172,7 +3172,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["sandbox_id"] == "sb-real" # protected key survives removal
assert "scratch" not in run.state # non-protected key removed
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
def test_update_run_status_to_completed_signals_workflow(self, mock_signal):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
@@ -3193,7 +3193,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(run.status, TaskRun.Status.COMPLETED)
self.assertIsNotNone(run.completed_at)
- @patch("products.tasks.backend.api.resume_task_in_cloud_workflow")
+ @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(
@@ -3213,7 +3213,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(run.status, TaskRun.Status.COMPLETED)
mock_resume.assert_not_called()
- @patch("products.tasks.backend.api.resume_task_in_cloud_workflow")
+ @patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow")
def test_resume_in_cloud_persists_user_integration_when_no_repo(self, mock_resume):
task = self.create_task(created_by=self.user)
user_integration = _grant_user_github_access(self.user)
@@ -3235,7 +3235,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(run.status, TaskRun.Status.QUEUED)
mock_resume.assert_called_once_with(str(run.id), run.workflow_id)
- @patch("products.tasks.backend.api.resume_task_in_cloud_workflow")
+ @patch("products.tasks.backend.temporal.client.resume_task_in_cloud_workflow")
def test_resume_in_cloud_falls_back_to_team_integration_when_no_user_integration(self, mock_resume):
integration = Integration.objects.create(team=self.team, kind="github", config={"access_token": "token"})
task = self.create_task(created_by=self.user)
@@ -3259,7 +3259,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(run.status, TaskRun.Status.QUEUED)
mock_resume.assert_called_once_with(str(run.id), run.workflow_id)
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
def test_update_run_status_to_failed_signals_workflow_with_error(self, mock_signal):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
@@ -3280,7 +3280,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(run.status, TaskRun.Status.FAILED)
self.assertEqual(run.error_message, "Something went wrong")
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
def test_update_run_status_to_cancelled_signals_workflow(self, mock_signal):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
@@ -3296,7 +3296,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
call_args = mock_signal.call_args
self.assertEqual(call_args[0][1], "cancelled")
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
@patch("products.tasks.backend.push_dispatcher.notify_task_run_cancelled")
def test_update_run_status_to_cancelled_triggers_push(self, mock_notify, _mock_signal):
"""Cancellation only flows through the API PATCH path — mark_completed / mark_failed
@@ -3314,7 +3314,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
mock_notify.assert_called_once()
self.assertEqual(str(mock_notify.call_args.args[0].id), str(run.id))
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
@patch("products.tasks.backend.push_dispatcher.notify_task_run_cancelled")
def test_update_run_status_to_non_cancelled_terminal_does_not_trigger_cancel_push(self, mock_notify, _mock_signal):
"""Sanity check: a PATCH to completed/failed must NOT fire the cancelled push."""
@@ -3329,7 +3329,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
mock_notify.assert_not_called()
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
def test_update_run_non_terminal_status_does_not_signal(self, mock_signal):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
@@ -3343,7 +3343,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
mock_signal.assert_not_called()
- @patch("products.tasks.backend.api.TaskRunViewSet._signal_workflow_completion")
+ @patch("products.tasks.backend.facade.api.signal_workflow_completion")
def test_update_run_same_terminal_status_does_not_signal(self, mock_signal):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
@@ -3585,7 +3585,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
remove_keys=["pending_user_message", "pending_user_artifact_ids"],
)
- with patch("products.tasks.backend.api.TaskRunViewSet.get_object", return_value=stale_run):
+ with patch("products.tasks.backend.presentation.views.api.TaskRunViewSet.get_object", return_value=stale_run):
response = self.client.patch(
f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
{"stage": "executing"},
@@ -3619,7 +3619,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
updates={"sandbox_id": "sandbox-123"},
)
- with patch("products.tasks.backend.api.TaskRunViewSet.get_object", return_value=stale_run):
+ with patch("products.tasks.backend.presentation.views.api.TaskRunViewSet.get_object", return_value=stale_run):
response = self.client.patch(
f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
{"state_remove_keys": ["pending_user_message", "pending_user_artifact_ids"]},
@@ -3633,7 +3633,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertNotIn("pending_user_message", run.state)
self.assertNotIn("pending_user_artifact_ids", run.state)
- @patch("products.tasks.backend.api.execute_posthog_code_agent_relay_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
def test_relay_message_enqueues_slack_relay_workflow(self, mock_execute_relay):
from posthog.models.integration import Integration
@@ -3670,7 +3670,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
delete_progress=True,
)
- @patch("products.tasks.backend.api.execute_posthog_code_agent_relay_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
def test_relay_message_skips_when_no_slack_mapping(self, mock_execute_relay):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
@@ -3685,7 +3685,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.json(), {"status": "skipped"})
mock_execute_relay.assert_not_called()
- @patch("products.tasks.backend.api.execute_posthog_code_agent_relay_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
def test_relay_message_skips_for_terminal_run(self, mock_execute_relay):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
@@ -3700,7 +3700,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.json(), {"status": "skipped"})
mock_execute_relay.assert_not_called()
- @patch("products.tasks.backend.api.execute_posthog_code_agent_relay_workflow")
+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")
def test_relay_message_rejects_blank_text(self, mock_execute_relay):
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
@@ -3715,7 +3715,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
mock_execute_relay.assert_not_called()
@patch(
- "products.tasks.backend.api.execute_posthog_code_agent_relay_workflow", side_effect=Exception("temporal down")
+ "products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow",
+ side_effect=Exception("temporal down"),
)
def test_relay_message_returns_503_on_enqueue_failure(self, mock_execute_relay):
from posthog.models.integration import Integration
@@ -4293,7 +4294,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
mock_head_object.assert_not_called()
@patch("posthog.storage.object_storage.head_object")
- @patch("products.tasks.backend.api.tag_task_artifact")
+ @patch("products.tasks.backend.logic.services.staged_artifacts.tag_task_artifact")
def test_finalize_artifact_uploads_returns_only_newly_finalized(self, mock_tag, mock_head_object):
mock_head_object.return_value = {"ContentLength": 4096, "ContentType": "application/pdf"}
task = self.create_task()
@@ -4343,7 +4344,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(sorted(stored_ids), sorted([existing_artifact_id, new_artifact_id]))
@patch("posthog.storage.object_storage.head_object")
- @patch("products.tasks.backend.api.tag_task_artifact")
+ @patch("products.tasks.backend.logic.services.staged_artifacts.tag_task_artifact")
def test_finalize_artifact_uploads_is_idempotent_for_existing_entry(self, mock_tag, mock_head_object):
task = self.create_task()
artifact_id = uuid.uuid4().hex
@@ -4443,7 +4444,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertIn("10MB attachment limit for PDFs", response.json()["error"])
@patch("posthog.storage.object_storage.head_object")
- @patch("products.tasks.backend.api.tag_task_artifact")
+ @patch("products.tasks.backend.logic.services.staged_artifacts.tag_task_artifact")
def test_finalize_artifact_uploads_is_atomic_for_partial_failures(self, mock_tag, mock_head_object):
mock_head_object.side_effect = [
{"ContentLength": 4096, "ContentType": "application/pdf"},
@@ -5368,7 +5369,7 @@ class TestTaskRunStreamKeepaliveAPI(BaseTaskAPITest):
with (
patch.object(TaskRunRedisStream, "exists", new=AsyncMock(side_effect=[False, True])),
patch.object(TaskRunRedisStream, "read_stream_entries", new=fake_read_stream_entries),
- patch("products.tasks.backend.api.TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.presentation.views.api.TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS", 0),
):
response = cast(
StreamingHttpResponse,
@@ -5656,7 +5657,7 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
class TestTaskRepositoryReadinessAPI(BaseTaskAPITest):
- @patch("products.tasks.backend.api.compute_repository_readiness")
+ @patch("products.tasks.backend.facade.api.compute_repository_readiness")
def test_repository_readiness_endpoint(self, mock_compute):
mock_compute.return_value = {
"repository": "posthog/posthog",
@@ -5739,7 +5740,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
mock_resp.text = json.dumps(body) if isinstance(body, dict) else str(body)
mock_post.return_value = mock_resp
- @patch("products.tasks.backend.api.signal_task_followup_message")
+ @patch("products.tasks.backend.temporal.client.signal_task_followup_message")
def test_command_signals_user_message(self, mock_signal_followup):
task = self.create_task()
run = self._create_run_with_sandbox(task)
@@ -5757,7 +5758,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
mock_signal_followup.assert_called_once_with(run.workflow_id, "Hello agent", [])
- @patch("products.tasks.backend.api.signal_task_followup_message")
+ @patch("products.tasks.backend.temporal.client.signal_task_followup_message")
def test_command_signals_user_message_without_active_sandbox(self, mock_signal_followup):
task = self.create_task()
run = TaskRun.objects.create(
@@ -5777,7 +5778,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertTrue(response.json()["result"]["queued"])
mock_signal_followup.assert_called_once_with(run.workflow_id, "Hello agent", [])
- @patch("products.tasks.backend.api.signal_task_followup_message")
+ @patch("products.tasks.backend.temporal.client.signal_task_followup_message")
def test_command_signals_user_message_artifact_ids(self, mock_signal_followup):
task = self.create_task()
run = self._create_run_with_sandbox(task)
@@ -5809,7 +5810,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertTrue(response.json()["result"]["queued"])
mock_signal_followup.assert_called_once_with(run.workflow_id, "See attached", ["artifact-123"])
- @patch("products.tasks.backend.api.signal_task_followup_message")
+ @patch("products.tasks.backend.temporal.client.signal_task_followup_message")
def test_command_returns_502_when_user_message_signal_fails(self, mock_signal_followup):
mock_signal_followup.side_effect = RuntimeError("temporal unavailable")
task = self.create_task()
@@ -5825,7 +5826,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(response.json()["error"], "Failed to queue user message for task run")
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_rejects_unknown_artifact_ids(self, mock_post):
reset_sandbox_jwt_key_cache()
task = self.create_task()
@@ -5848,7 +5849,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
mock_post.assert_not_called()
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_proxies_cancel(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(
@@ -5873,7 +5874,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertTrue(response.json()["result"]["cancelled"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_proxies_close(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(
@@ -5898,7 +5899,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertTrue(response.json()["result"]["closed"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_proxies_permission_response(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(
@@ -5927,7 +5928,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_kwargs["json"]["params"]["optionId"], "allow")
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_proxies_set_config_option(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(
@@ -6019,7 +6020,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_passes_modal_connect_token_as_query_param(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})
@@ -6043,7 +6044,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertNotIn("_modal_connect_token", call_kwargs["headers"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_no_query_params_for_docker(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})
@@ -6062,7 +6063,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_kwargs["params"], {})
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_returns_502_on_connection_error(self, mock_post):
reset_sandbox_jwt_key_cache()
mock_post.side_effect = __import__("requests").ConnectionError("Connection refused")
@@ -6080,7 +6081,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertIn("not reachable", response.json()["error"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_returns_504_on_timeout(self, mock_post):
reset_sandbox_jwt_key_cache()
mock_post.side_effect = __import__("requests").Timeout("Request timed out")
@@ -6098,7 +6099,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertIn("timed out", response.json()["error"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_forwards_agent_server_auth_error(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(
@@ -6120,7 +6121,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertIn("Missing authorization header", response.json()["error"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_forwards_agent_server_no_session_error(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(
@@ -6142,7 +6143,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertIn("No active session", response.json()["error"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_sends_jwt_with_correct_claims(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})
@@ -6174,7 +6175,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(decoded["user_id"], self.user.id)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_posts_to_correct_url(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})
@@ -6232,7 +6233,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_with_trailing_slash_sandbox_url(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})
@@ -6250,7 +6251,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_args[0][0], "http://localhost:47821/command")
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_accepts_numeric_id(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": 42, "result": {}})
@@ -6269,7 +6270,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_kwargs["json"]["id"], 42)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_uses_600s_timeout(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})
@@ -6287,7 +6288,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_kwargs["timeout"], 600)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_omits_params_for_cancel(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {"cancelled": True}})
@@ -6343,7 +6344,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
]
)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_allows_valid_sandbox_urls(self, _name, valid_url, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})
@@ -6377,7 +6378,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertIn("No active sandbox", response.json()["error"])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_accepts_id_zero(self, mock_post):
reset_sandbox_jwt_key_cache()
self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": 0, "result": {}})
@@ -6396,7 +6397,7 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_kwargs["json"]["id"], 0)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- @patch("products.tasks.backend.api.http_requests.post")
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
def test_command_generic_error_does_not_leak_details(self, mock_post):
reset_sandbox_jwt_key_cache()
mock_post.side_effect = RuntimeError("internal DNS resolve failed for secret-host.internal:8080")
@@ -6691,7 +6692,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
status=status_value,
)
- @patch("products.tasks.backend.services.code_usage_gate.get_posthog_code_usage")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_run_over_limit_returns_429_and_creates_no_run(self, mock_gate):
mock_gate.return_value = self.OVER_LIMIT
task = self.create_task()
@@ -6707,7 +6708,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.json()["limit_type"], "burst")
self.assertFalse(TaskRun.objects.filter(task=task).exists())
- @patch("products.tasks.backend.services.code_usage_gate.get_posthog_code_usage")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_create_cloud_run_over_limit_returns_429_and_creates_no_run(self, mock_gate):
mock_gate.return_value = self.OVER_LIMIT
task = self.create_task()
@@ -6722,7 +6723,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
self.assertEqual(response.json()["code"], "usage_limit_exceeded")
self.assertFalse(TaskRun.objects.filter(task=task).exists())
- @patch("products.tasks.backend.services.code_usage_gate.get_posthog_code_usage")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_create_local_run_is_not_gated(self, mock_gate):
mock_gate.return_value = self.OVER_LIMIT
task = self.create_task()
@@ -6737,7 +6738,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
mock_gate.assert_not_called()
self.assertTrue(TaskRun.objects.filter(task=task).exists())
- @patch("products.tasks.backend.services.code_usage_gate.get_posthog_code_usage")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_start_over_limit_returns_429(self, mock_gate):
mock_gate.return_value = self.OVER_LIMIT
task = self.create_task()
@@ -6754,7 +6755,7 @@ class TestCloudUsageGate(BaseTaskAPITest):
run.refresh_from_db()
self.assertEqual(run.status, TaskRun.Status.QUEUED)
- @patch("products.tasks.backend.services.code_usage_gate.get_posthog_code_usage")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_resume_in_cloud_over_limit_returns_429(self, mock_gate):
mock_gate.return_value = self.OVER_LIMIT
task = self.create_task()
@@ -6780,8 +6781,8 @@ class TestCloudUsageGate(BaseTaskAPITest):
("under_limit", CodeUsageStatus(is_rate_limited=False, limit_type=None, reset_at=None, is_pro=False)),
]
)
- @patch("products.tasks.backend.api.execute_task_processing_workflow")
- @patch("products.tasks.backend.services.code_usage_gate.get_posthog_code_usage")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_run_proceeds_when_not_blocked(self, _name, gate_return, mock_gate, mock_workflow):
mock_gate.return_value = gate_return
task = self.create_task()
@@ -6800,8 +6801,8 @@ class TestCloudUsageGate(BaseTaskAPITest):
class TestGetPosthogCodeUsage(TestCase):
@override_settings(CLOUD_DEPLOYMENT="US")
- @patch("products.tasks.backend.services.code_usage_gate.requests.get")
- @patch("products.tasks.backend.services.code_usage_gate.create_oauth_access_token_for_user")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.requests.get")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
def test_parses_rate_limited_usage(self, mock_token, mock_get):
mock_token.return_value = "tok"
mock_get.return_value = MagicMock(
@@ -6828,9 +6829,9 @@ class TestGetPosthogCodeUsage(TestCase):
self.assertEqual(_gateway_usage_url(), "http://localhost:3308/v1/usage/posthog_code")
@override_settings(CLOUD_DEPLOYMENT="US")
- @patch("products.tasks.backend.services.code_usage_gate.OAuthAccessToken")
- @patch("products.tasks.backend.services.code_usage_gate.requests.get")
- @patch("products.tasks.backend.services.code_usage_gate.create_oauth_access_token_for_user")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.OAuthAccessToken")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.requests.get")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
def test_token_cleanup_error_does_not_break_fail_open(self, mock_token, mock_get, mock_oauth_model):
mock_token.return_value = "tok"
mock_get.return_value = MagicMock(
@@ -6856,8 +6857,8 @@ class TestGetPosthogCodeUsage(TestCase):
]
)
@override_settings(CLOUD_DEPLOYMENT="US")
- @patch("products.tasks.backend.services.code_usage_gate.requests.get")
- @patch("products.tasks.backend.services.code_usage_gate.create_oauth_access_token_for_user")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.requests.get")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
def test_fails_open_on_gateway_error(self, _name, status_code, _unused, mock_token, mock_get):
mock_token.return_value = "tok"
if status_code is None:
@@ -6868,7 +6869,7 @@ class TestGetPosthogCodeUsage(TestCase):
self.assertIsNone(get_posthog_code_usage(MagicMock(), 1))
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="DEV")
- @patch("products.tasks.backend.services.code_usage_gate.create_oauth_access_token_for_user")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.create_oauth_access_token_for_user")
def test_fails_open_when_no_gateway_url(self, mock_token):
self.assertIsNone(get_posthog_code_usage(MagicMock(), 1))
mock_token.assert_not_called()
diff --git a/products/tasks/backend/tests/test_check_logs.py b/products/tasks/backend/tests/test_check_logs.py
index 9eba81aca17e..738f26676941 100644
--- a/products/tasks/backend/tests/test_check_logs.py
+++ b/products/tasks/backend/tests/test_check_logs.py
@@ -1,6 +1,6 @@
from unittest.mock import patch
-from products.tasks.backend.services.custom_prompt_internals import _check_logs, _stream_new_lines
+from products.tasks.backend.logic.services.custom_prompt_internals import _check_logs, _stream_new_lines
from products.tasks.backend.tests.agent_log_fixtures import (
FakeTaskRun,
_agent_message_line,
diff --git a/products/tasks/backend/tests/test_connection_token.py b/products/tasks/backend/tests/test_connection_token.py
index 44eb627adb3c..70039d302008 100644
--- a/products/tasks/backend/tests/test_connection_token.py
+++ b/products/tasks/backend/tests/test_connection_token.py
@@ -8,8 +8,7 @@ import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
-from products.tasks.backend.models import TaskRun
-from products.tasks.backend.services.connection_token import (
+from products.tasks.backend.logic.services.connection_token import (
SANDBOX_CONNECTION_AUDIENCE,
SANDBOX_JWT_STATE_KID_KEY,
_compute_kid,
@@ -21,6 +20,7 @@ from products.tasks.backend.services.connection_token import (
reset_sandbox_jwt_key_cache,
validate_sandbox_event_ingest_token,
)
+from products.tasks.backend.models import TaskRun
def _generate_private_key_pem() -> str:
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index 1af373932c77..7f66c1203013 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -13,21 +13,20 @@ from parameterized import parameterized
from posthog.models import Organization, Team
from posthog.redis import TEST_clear_clients
-from products.tasks.backend.models import Task, TaskRun
-from products.tasks.backend.services.connection_token import (
+from products.tasks.backend.logic.services.connection_token import (
SANDBOX_EVENT_INGEST_TOKEN_TTL,
create_sandbox_connection_token,
create_sandbox_event_ingest_token,
reset_sandbox_jwt_key_cache,
)
-from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS
-from products.tasks.backend.stream.event_ingest import (
+from products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDS
+from products.tasks.backend.logic.stream.event_ingest import (
MAX_EVENT_LINE_BYTES,
MAX_EVENTS_PER_REQUEST,
STREAM_COMPLETE_CONTROL_TYPE,
handle_task_run_event_ingest,
)
-from products.tasks.backend.stream.redis_stream import (
+from products.tasks.backend.logic.stream.redis_stream import (
TASK_RUN_STREAM_SEQUENCE_TIMEOUT,
TASK_RUN_STREAM_TIMEOUT,
TaskRunRedisStream,
@@ -35,6 +34,7 @@ from products.tasks.backend.stream.redis_stream import (
get_task_run_stream_key,
get_task_run_stream_sequence_key,
)
+from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
@@ -254,7 +254,9 @@ class TestTaskRunEventIngest(TestCase):
)
return sent[0]["status"], json.loads(sent[1]["body"])
- with patch("products.tasks.backend.stream.event_ingest._heartbeat_workflow", side_effect=blocking_heartbeat):
+ with patch(
+ "products.tasks.backend.logic.stream.event_ingest._heartbeat_workflow", side_effect=blocking_heartbeat
+ ):
status, body = async_to_sync(_call)()
self.assertEqual(status, 200)
diff --git a/products/tasks/backend/tests/test_extract_json_from_text.py b/products/tasks/backend/tests/test_extract_json_from_text.py
index fd8c8a57c268..8706d9edbfb5 100644
--- a/products/tasks/backend/tests/test_extract_json_from_text.py
+++ b/products/tasks/backend/tests/test_extract_json_from_text.py
@@ -2,7 +2,7 @@ import pytest
from parameterized import parameterized
-from products.tasks.backend.services.custom_prompt_internals import extract_json_from_text
+from products.tasks.backend.logic.services.custom_prompt_internals import extract_json_from_text
EXPECTED = {"answer": "hello world"}
JSON_STR = '{"answer": "hello world"}'
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
new file mode 100644
index 000000000000..4f6fdf4ed04a
--- /dev/null
+++ b/products/tasks/backend/tests/test_facade.py
@@ -0,0 +1,214 @@
+import importlib
+from datetime import timedelta
+from typing import ClassVar
+
+from unittest.mock import patch
+
+from django.test import TestCase
+from django.utils import timezone as django_timezone
+
+from parameterized import parameterized
+
+from posthog.models import Integration, Organization, Team
+from posthog.models.user import User
+
+from products.tasks.backend.facade import (
+ api as facade,
+ contracts,
+)
+from products.tasks.backend.models import SandboxEnvironment, Task, TaskRun
+
+FACADE_MODULES = [
+ "products.tasks.backend.facade.api",
+ "products.tasks.backend.facade.contracts",
+ "products.tasks.backend.facade.agents",
+ "products.tasks.backend.facade.sandbox",
+ "products.tasks.backend.facade.exceptions",
+ "products.tasks.backend.facade.repo_selection",
+ "products.tasks.backend.facade.streams",
+ "products.tasks.backend.facade.temporal",
+ "products.tasks.backend.facade.max_tools",
+ "products.tasks.backend.facade.webhooks",
+ "products.tasks.backend.facade.file_system",
+]
+
+
+class TestFacadeImports(TestCase):
+ @parameterized.expand([(m,) for m in FACADE_MODULES])
+ def test_module_imports_and_all_symbols_resolve(self, module_path):
+ module = importlib.import_module(module_path)
+ for symbol in getattr(module, "__all__", []):
+ self.assertTrue(hasattr(module, symbol), f"{module_path} is missing exported symbol {symbol}")
+
+ def test_enum_reexports_match_models(self):
+ self.assertIs(facade.TaskRunStatus, TaskRun.Status)
+ self.assertIs(facade.TaskRunEnvironment, TaskRun.Environment)
+ self.assertIs(facade.TaskOriginProduct, Task.OriginProduct)
+ self.assertIs(facade.SandboxNetworkAccessLevel, SandboxEnvironment.NetworkAccessLevel)
+
+
+class TestFacadeReadsAndMappers(TestCase):
+ organization: ClassVar[Organization]
+ team: ClassVar[Team]
+ user: ClassVar[User]
+
+ @classmethod
+ def setUpTestData(cls):
+ cls.organization = Organization.objects.create(name="Test Org")
+ cls.team = Team.objects.create(organization=cls.organization, name="Test Team")
+ cls.user = User.objects.create(email="[email protected]", distinct_id="facade-distinct")
+
+ def _make_task(self, **kwargs) -> Task:
+ defaults = {
+ "team": self.team,
+ "title": "A task",
+ "description": "desc",
+ "origin_product": Task.OriginProduct.USER_CREATED,
+ "created_by": self.user,
+ "repository": "posthog/posthog",
+ }
+ defaults.update(kwargs)
+ return Task.objects.create(**defaults)
+
+ def test_get_task_run_maps_all_fields(self):
+ task = self._make_task()
+ run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ environment=TaskRun.Environment.CLOUD,
+ output={"pr_url": "https://github.com/posthog/posthog/pull/1"},
+ state={"mode": "interactive"},
+ )
+
+ dto = facade.get_task_run(run.id)
+ assert dto is not None
+ self.assertIsInstance(dto, contracts.TaskRunDTO)
+ self.assertEqual(dto.id, run.id)
+ self.assertEqual(dto.task_id, task.id)
+ self.assertEqual(dto.team_id, self.team.id)
+ self.assertEqual(dto.status, TaskRun.Status.COMPLETED.value)
+ self.assertTrue(dto.is_terminal)
+ self.assertEqual(dto.mode, "interactive")
+ self.assertEqual(dto.workflow_id, run.workflow_id)
+ self.assertEqual(dto.task_origin_product, Task.OriginProduct.USER_CREATED.value)
+ self.assertEqual(dto.created_by_distinct_id, "facade-distinct")
+ self.assertEqual(dto.pr_url, "https://github.com/posthog/posthog/pull/1")
+
+ def test_get_task_run_team_scope(self):
+ task = self._make_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+
+ self.assertIsNotNone(facade.get_task_run(run.id, team_id=self.team.id))
+ self.assertIsNone(facade.get_task_run(run.id, team_id=other_team.id))
+ self.assertIsNone(facade.get_task_run("00000000-0000-0000-0000-000000000000"))
+
+ def test_task_exists_and_visibility(self):
+ task = self._make_task()
+ self.assertTrue(facade.task_exists(task.id, self.team.id))
+ self.assertFalse(facade.task_exists(task.id, self.team.id + 999))
+ # Creator can see it; an unrelated user cannot.
+ self.assertTrue(facade.is_task_visible_to_user(task.id, self.user.id))
+ other_user = User.objects.create(email="[email protected]", distinct_id="other")
+ self.assertFalse(facade.is_task_visible_to_user(task.id, other_user.id))
+
+ def test_get_latest_pr_url_and_run_by_task(self):
+ task = self._make_task()
+ TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/1"}
+ )
+ latest = TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, output={"pr_url": "https://x/pull/2"}
+ )
+
+ pr_urls = facade.get_latest_pr_url_by_task([task.id])
+ self.assertEqual(pr_urls, {str(task.id): "https://x/pull/2"})
+
+ latest_runs = facade.get_latest_run_by_task([task.id])
+ self.assertEqual(latest_runs[str(task.id)].id, latest.id)
+
+ self.assertEqual(facade.get_latest_pr_url_by_task([]), {})
+
+ def test_stale_queued_and_fail(self):
+ 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)
+ past = django_timezone.now() - timedelta(hours=48)
+ TaskRun.objects.filter(pk=stale.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)
+ self.assertNotIn(fresh.id, stale_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
+ self.assertFalse(facade.fail_task_run(stale.id, "boom again"))
+ stale.refresh_from_db()
+ self.assertEqual(stale.status, TaskRun.Status.FAILED.value)
+ self.assertEqual(stale.error_message, "boom")
+
+ def test_update_task_run_state(self):
+ task = self._make_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED, state={"mode": "bg"})
+ new_state = facade.update_task_run_state(run.id, updates={"foo": "bar"}, remove_keys=["mode"])
+ self.assertEqual(new_state.get("foo"), "bar")
+ self.assertNotIn("mode", new_state)
+ run.refresh_from_db()
+ self.assertEqual(run.state.get("foo"), "bar")
+
+ def test_collect_task_run_state_metrics(self):
+ task = self._make_task()
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)
+
+ metrics = facade.collect_task_run_state_metrics(
+ open_statuses=["queued", "in_progress"],
+ age_statuses=["queued", "in_progress"],
+ terminal_statuses=["completed", "failed", "cancelled"],
+ window_seconds=3600,
+ )
+ open_counts = {(r.status, r.origin_product): r.value for r in metrics.runs_in_status}
+ self.assertEqual(open_counts[(TaskRun.Status.QUEUED.value, Task.OriginProduct.USER_CREATED.value)], 2)
+ # COMPLETED is terminal, not open
+ self.assertNotIn((TaskRun.Status.COMPLETED.value, Task.OriginProduct.USER_CREATED.value), open_counts)
+ terminal_counts = {(r.status, r.origin_product): r.value for r in metrics.terminal_recently}
+ self.assertEqual(terminal_counts[(TaskRun.Status.COMPLETED.value, Task.OriginProduct.USER_CREATED.value)], 1)
+ self.assertEqual(sum(r.value for r in metrics.created_recently), 3)
+ self.assertTrue(all(r.value >= 0 for r in metrics.oldest_open_age_seconds))
+
+ def test_upsert_internal_sandbox_env(self):
+ env_id = facade.upsert_internal_sandbox_env(self.team.id, "SIGNALS_X", facade.SandboxNetworkAccessLevel.TRUSTED)
+ env = SandboxEnvironment.objects.get(id=env_id)
+ self.assertFalse(env.private)
+ self.assertTrue(env.internal)
+ self.assertEqual(env.network_access_level, SandboxEnvironment.NetworkAccessLevel.TRUSTED.value)
+
+ # Re-asserts policy and returns the same row.
+ env.private = True
+ env.save(update_fields=["private"])
+ env_id_2 = facade.upsert_internal_sandbox_env(
+ self.team.id, "SIGNALS_X", facade.SandboxNetworkAccessLevel.TRUSTED
+ )
+ self.assertEqual(env_id_2, env_id)
+ env.refresh_from_db()
+ self.assertFalse(env.private)
+
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_create_and_run_task_returns_contract(self, _mock_workflow):
+ Integration.objects.create(team=self.team, kind="github", config={})
+ created = facade.create_and_run_task(
+ team=self.team,
+ title="Created via facade",
+ description="desc",
+ origin_product=facade.TaskOriginProduct.USER_CREATED,
+ user_id=self.user.id,
+ repository="posthog/posthog",
+ )
+ self.assertIsInstance(created, contracts.CreatedTaskDTO)
+ self.assertEqual(created.team_id, self.team.id)
+ self.assertTrue(Task.objects.filter(id=created.task_id).exists())
+ assert created.latest_run is not None
+ self.assertEqual(created.latest_run.task_id, created.task_id)
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index f220f151b94b..32f9b4608261 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -13,8 +13,7 @@ from posthog.models import Integration, Organization, Team
from posthog.models.user import User
from posthog.storage.object_storage import ObjectStorageError
-from products.tasks.backend.models import TaskRun
-from products.tasks.backend.services.custom_prompt_internals import (
+from products.tasks.backend.logic.services.custom_prompt_internals import (
AgentError,
CustomPromptSandboxContext,
EmptyAgentTurnError,
@@ -22,7 +21,11 @@ from products.tasks.backend.services.custom_prompt_internals import (
create_task_and_trigger,
poll_for_turn,
)
-from products.tasks.backend.services.custom_prompt_multi_turn_runner import _EMPTY_TURN_RETRY_NUDGE, MultiTurnSession
+from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import (
+ _EMPTY_TURN_RETRY_NUDGE,
+ MultiTurnSession,
+)
+from products.tasks.backend.models import TaskRun
from products.tasks.backend.tests.agent_log_fixtures import (
FakeTaskRun,
_agent_error_line,
@@ -58,7 +61,7 @@ class TestPollForTurnEmptyEndTurn:
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
patch(
- "products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS",
+ "products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS",
0,
),
):
@@ -98,7 +101,7 @@ class TestPollForTurnEmptyEndTurn:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
last_message, _, total_lines, _ = await poll_for_turn(fake_task_run, skip_lines=skip)
@@ -127,7 +130,7 @@ class TestPollForTurnEmptyEndTurn:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
last_message, _, total_lines, printed_lines = await poll_for_turn(
@@ -156,9 +159,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
@@ -186,8 +189,8 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 600),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 600),
# STALE_TURN_SALVAGE_SECONDS intentionally NOT patched — exercise the production floor.
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
@@ -217,9 +220,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
@@ -237,9 +240,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="timed out"):
@@ -254,8 +257,8 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 100),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 100),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="after 30s"):
@@ -277,9 +280,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -304,9 +307,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 50),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 50),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="timed out"):
@@ -331,9 +334,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="timed out"):
@@ -356,9 +359,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -389,9 +392,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -416,9 +419,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -451,9 +454,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="timed out"):
@@ -479,9 +482,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="timed out"):
@@ -512,9 +515,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 60),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 60),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -538,9 +541,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(ObjectStorageError):
@@ -563,9 +566,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -587,8 +590,8 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
patch("products.tasks.backend.models.TaskRun.objects.get", side_effect=next_status),
):
with pytest.raises(RuntimeError, match="terminal status"):
@@ -610,7 +613,7 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
@@ -634,9 +637,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="timed out"):
@@ -671,9 +674,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", side_effect=next_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -694,9 +697,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
with pytest.raises(RuntimeError, match="timed out"):
@@ -714,9 +717,9 @@ class TestPollForTurnStaleSalvage:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
- patch("products.tasks.backend.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
- patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
last_message, _, _, _ = await poll_for_turn(fake, skip_lines=0)
@@ -751,7 +754,7 @@ class TestPollForTurnTerminalDrain:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
with pytest.raises(RuntimeError, match="terminal status"):
@@ -778,7 +781,7 @@ class TestPollForTurnTerminalDrain:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
last_message, _, _, _ = await poll_for_turn(fake_task_run, skip_lines=skip)
@@ -800,7 +803,7 @@ class TestPollForTurnTerminalDrain:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
):
last_message, _, _, _ = await poll_for_turn(fake_task_run, skip_lines=0)
@@ -886,10 +889,10 @@ class TestPollForTurnSurfacesAgentError:
with (
patch("posthog.storage.object_storage.read", return_value=log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
patch(
- "products.tasks.backend.services.custom_prompt_internals._persist_task_run_error_message",
+ "products.tasks.backend.logic.services.custom_prompt_internals._persist_task_run_error_message",
new=persist,
),
):
@@ -915,10 +918,10 @@ class TestPollForTurnSurfacesAgentError:
with (
patch("posthog.storage.object_storage.read", return_value="\n".join(turn)),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
patch(
- "products.tasks.backend.services.custom_prompt_internals._persist_task_run_error_message",
+ "products.tasks.backend.logic.services.custom_prompt_internals._persist_task_run_error_message",
new=persist,
),
):
@@ -941,10 +944,10 @@ class TestPollForTurnSurfacesAgentError:
with (
patch("posthog.storage.object_storage.read", return_value="\n".join(turn)),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
patch(
- "products.tasks.backend.services.custom_prompt_internals._persist_task_run_error_message",
+ "products.tasks.backend.logic.services.custom_prompt_internals._persist_task_run_error_message",
new=persist,
),
):
@@ -966,10 +969,10 @@ class TestPollForTurnSurfacesAgentError:
with (
patch("posthog.storage.object_storage.read", return_value="\n".join(turn)),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
patch(
- "products.tasks.backend.services.custom_prompt_internals._persist_task_run_error_message",
+ "products.tasks.backend.logic.services.custom_prompt_internals._persist_task_run_error_message",
new=persist,
),
):
@@ -993,10 +996,10 @@ class TestPollForTurnSurfacesAgentError:
with (
patch("posthog.storage.object_storage.read", return_value="\n".join(turn)),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
patch(
- "products.tasks.backend.services.custom_prompt_internals._persist_task_run_error_message",
+ "products.tasks.backend.logic.services.custom_prompt_internals._persist_task_run_error_message",
new=persist,
),
):
@@ -1028,7 +1031,7 @@ class TestMultiTurnSessionRetry:
agent_response = json.dumps({"value": "ok"})
with patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.poll_for_turn",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
new=AsyncMock(return_value=(agent_response, None, 10, 5)),
):
result = await session.send_followup("hello", _Resp, label="unit")
@@ -1049,7 +1052,7 @@ class TestMultiTurnSessionRetry:
]
)
with patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.poll_for_turn",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
new=poll_mock,
):
result = await session.send_followup("please prioritize", _Resp, label="priority")
@@ -1075,7 +1078,7 @@ class TestMultiTurnSessionRetry:
]
)
with patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.poll_for_turn",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
new=poll_mock,
):
with pytest.raises(EmptyAgentTurnError, match="twice"):
@@ -1124,7 +1127,7 @@ class TestMultiTurnSessionRetry:
with (
patch("posthog.storage.object_storage.read", side_effect=current_log),
patch("asyncio.sleep", new=AsyncMock()),
- patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
):
result = await session.send_followup("please respond", _Resp, label="priority")
@@ -1156,7 +1159,7 @@ class TestMultiTurnSessionRetry:
return (agent_response, None, 120, 60)
with patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.poll_for_turn",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
new=fake_poll,
):
await session.send_followup("x", _Resp, label="priority")
@@ -1189,11 +1192,11 @@ class TestMultiTurnSessionStartBranch:
with (
patch("products.tasks.backend.temporal.client.execute_task_processing_workflow"),
patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.async_connect",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.async_connect",
new=AsyncMock(return_value=MagicMock(get_workflow_handle=MagicMock(return_value=AsyncMock()))),
),
patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.poll_for_turn",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
new=AsyncMock(return_value=(agent_response, None, 1, 1)),
),
):
@@ -1230,15 +1233,15 @@ class TestMultiTurnSessionStartCleanup:
with (
patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.create_task_and_trigger",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.create_task_and_trigger",
new=AsyncMock(return_value=(fake_task, fake_run)),
),
patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.async_connect",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.async_connect",
new=AsyncMock(return_value=mock_client),
),
patch(
- "products.tasks.backend.services.custom_prompt_multi_turn_runner.poll_for_turn",
+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",
new=AsyncMock(side_effect=RuntimeError("storage explode")),
),
pytest.raises(RuntimeError, match="storage explode"),
@@ -1288,7 +1291,7 @@ class TestCreateTaskAndTriggerForwardsContext:
mock_task = MagicMock()
mock_task.latest_run = MagicMock()
with patch(
- "products.tasks.backend.services.custom_prompt_internals.Task.create_and_run",
+ "products.tasks.backend.logic.services.custom_prompt_internals.Task.create_and_run",
return_value=mock_task,
) as mock_create:
await create_task_and_trigger("prompt", context)
@@ -1306,7 +1309,7 @@ class TestCreateTaskAndTriggerForwardsContext:
mock_task = MagicMock()
mock_task.latest_run = MagicMock()
with patch(
- "products.tasks.backend.services.custom_prompt_internals.Task.create_and_run",
+ "products.tasks.backend.logic.services.custom_prompt_internals.Task.create_and_run",
return_value=mock_task,
) as mock_create:
await create_task_and_trigger("prompt", context, ai_stage=ai_stage)
diff --git a/products/slack_app/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.py
similarity index 100%
rename from products/slack_app/backend/tests/test_post_slack_update.py
rename to products/tasks/backend/tests/test_post_slack_update.py
diff --git a/products/tasks/backend/tests/test_seat_api.py b/products/tasks/backend/tests/test_seat_api.py
index 9b38f6a2ebe2..e8959787efb1 100644
--- a/products/tasks/backend/tests/test_seat_api.py
+++ b/products/tasks/backend/tests/test_seat_api.py
@@ -70,44 +70,44 @@ class BaseSeatAPITest(TestCase):
self.client.force_authenticate(self.user)
-@patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
-@patch("products.tasks.backend.seat_api.get_cached_instance_license", return_value=MagicMock())
+@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())
class TestSeatAPIAdminPermissions(BaseSeatAPITest):
"""Non-admin users should be blocked from list and non-me operations."""
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_list_requires_admin(self, mock_request, _mock_license, _mock_token):
self._auth_as_member()
response = self.client.get("/api/seats/?product_key=posthog_code")
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_list_allowed_for_admin(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seats": [MOCK_SEAT]})
self._auth_as_admin()
response = self.client.get("/api/seats/?product_key=posthog_code")
assert response.status_code == status.HTTP_200_OK
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_retrieve_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):
self._auth_as_member()
response = self.client.get(f"/api/seats/{self.admin_user.distinct_id}/?product_key=posthog_code")
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_retrieve_me_allowed_for_member(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_member()
response = self.client.get("/api/seats/me/?product_key=posthog_code")
assert response.status_code == status.HTTP_200_OK
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_delete_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):
self._auth_as_member()
response = self.client.delete(f"/api/seats/{self.admin_user.distinct_id}/?product_key=posthog_code")
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_patch_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):
self._auth_as_member()
response = self.client.patch(
@@ -117,7 +117,7 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
)
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_create_without_user_distinct_id_returns_400(self, mock_request, _mock_license, _mock_token):
self._auth_as_member()
response = self.client.post(
@@ -128,7 +128,7 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["detail"] == "user_distinct_id is required"
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_create_for_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):
self._auth_as_member()
response = self.client.post(
@@ -138,7 +138,7 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
)
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_create_for_self_allowed_for_member(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_member()
@@ -153,19 +153,19 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
)
assert response.status_code == status.HTTP_200_OK
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_reactivate_other_user_requires_admin(self, mock_request, _mock_license, _mock_token):
self._auth_as_member()
response = self.client.post(f"/api/seats/{self.admin_user.distinct_id}/reactivate/", format="json")
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_retrieve_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):
self._auth_as_admin()
response = self.client.get(f"/api/seats/{self.external_user.distinct_id}/?product_key=posthog_code")
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_patch_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):
self._auth_as_admin()
response = self.client.patch(
@@ -175,13 +175,13 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
)
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_delete_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):
self._auth_as_admin()
response = self.client.delete(f"/api/seats/{self.external_user.distinct_id}/?product_key=posthog_code")
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_create_for_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):
self._auth_as_admin()
response = self.client.post(
@@ -195,19 +195,19 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
)
assert response.status_code == status.HTTP_403_FORBIDDEN
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_reactivate_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):
self._auth_as_admin()
response = self.client.post(f"/api/seats/{self.external_user.distinct_id}/reactivate/", format="json")
assert response.status_code == status.HTTP_403_FORBIDDEN
-@patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
-@patch("products.tasks.backend.seat_api.get_cached_instance_license", return_value=MagicMock())
+@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())
class TestSeatAPIMeResolution(BaseSeatAPITest):
"""``me`` in the URL should resolve to the authenticated user's distinct_id."""
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_retrieve_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_member()
@@ -215,7 +215,7 @@ class TestSeatAPIMeResolution(BaseSeatAPITest):
_, kwargs = mock_request.call_args
assert str(self.user.distinct_id) in kwargs["url"]
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_delete_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response(status_code=204)
self._auth_as_member()
@@ -223,7 +223,7 @@ class TestSeatAPIMeResolution(BaseSeatAPITest):
_, kwargs = mock_request.call_args
assert str(self.user.distinct_id) in kwargs["url"]
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_patch_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_member()
@@ -235,7 +235,7 @@ class TestSeatAPIMeResolution(BaseSeatAPITest):
_, kwargs = mock_request.call_args
assert str(self.user.distinct_id) in kwargs["url"]
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_reactivate_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_member()
@@ -244,8 +244,8 @@ class TestSeatAPIMeResolution(BaseSeatAPITest):
assert str(self.user.distinct_id) in kwargs["url"]
-@patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
-@patch("products.tasks.backend.seat_api.get_cached_instance_license")
+@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license")
class TestSeatAPIBillingUnavailability(BaseSeatAPITest):
"""Graceful handling when the billing service is unreachable or misconfigured."""
@@ -256,7 +256,10 @@ class TestSeatAPIBillingUnavailability(BaseSeatAPITest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["detail"] == "No organization or license found"
- @patch("products.tasks.backend.seat_api.requests.request", side_effect=Exception("connection refused"))
+ @patch(
+ "products.tasks.backend.presentation.views.seat_api.requests.request",
+ side_effect=Exception("connection refused"),
+ )
def test_billing_request_exception_returns_502(self, mock_request, mock_license, _mock_token):
import requests as req
@@ -266,7 +269,7 @@ class TestSeatAPIBillingUnavailability(BaseSeatAPITest):
response = self.client.get("/api/seats/me/?product_key=posthog_code")
assert response.status_code == status.HTTP_502_BAD_GATEWAY
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_billing_invalid_json_returns_502(self, mock_request, mock_license, _mock_token):
mock_license.return_value = MagicMock()
billing_resp = MagicMock()
@@ -280,12 +283,12 @@ class TestSeatAPIBillingUnavailability(BaseSeatAPITest):
assert response.json()["detail"] == "Invalid response from billing service"
-@patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
-@patch("products.tasks.backend.seat_api.get_cached_instance_license", return_value=MagicMock())
+@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())
class TestSeatAPIResponseUnwrapping(BaseSeatAPITest):
"""Successful responses with a ``seat`` key are unwrapped; errors pass through."""
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_retrieve_unwraps_seat_envelope(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT, "extra": "ignored"})
self._auth_as_member()
@@ -294,7 +297,7 @@ class TestSeatAPIResponseUnwrapping(BaseSeatAPITest):
assert response.json()["id"] == "seat_123"
assert "extra" not in response.json()
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_list_does_not_unwrap(self, mock_request, _mock_license, _mock_token):
payload = {"seats": [MOCK_SEAT]}
mock_request.return_value = _billing_response(payload)
@@ -303,7 +306,7 @@ class TestSeatAPIResponseUnwrapping(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert "seats" in response.json()
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_error_response_passes_through(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"error": "seat not found"}, status_code=404, ok=False)
self._auth_as_member()
@@ -311,7 +314,7 @@ class TestSeatAPIResponseUnwrapping(BaseSeatAPITest):
assert response.status_code == 404
assert response.json()["error"] == "seat not found"
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_204_returns_no_content(self, mock_request, _mock_license, _mock_token):
billing_resp = MagicMock()
billing_resp.status_code = 204
@@ -320,7 +323,7 @@ class TestSeatAPIResponseUnwrapping(BaseSeatAPITest):
response = self.client.delete("/api/seats/me/?product_key=posthog_code")
assert response.status_code == status.HTTP_204_NO_CONTENT
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_response_without_seat_key_passes_through(self, mock_request, _mock_license, _mock_token):
payload = {"message": "ok", "some_data": 123}
mock_request.return_value = _billing_response(payload)
@@ -367,7 +370,7 @@ MOCK_PRO_V2_SEAT = {
}
-@patch("products.tasks.backend.seat_api.get_cached_instance_license", return_value=MagicMock())
+@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())
class TestSeatAPIBestPlan(BaseSeatAPITest):
"""``best=true`` returns the highest-tier seat across all orgs."""
@@ -379,8 +382,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
cls.org2 = Organization.objects.create(name="Second Org")
cls.org2.members.add(cls.user)
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_single_org_returns_that_seat(self, _mock_token, mock_request, _mock_license):
mock_request.return_value = _billing_response({"seat": MOCK_FREE_SEAT})
self._auth_as_admin()
@@ -390,8 +393,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.json()["organization_id"] == str(self.organization.id)
assert response.json()["organization_name"] == "Test Org"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_multi_org_returns_pro_over_free(self, _mock_token, mock_request, _mock_license):
mock_request.side_effect = [
_billing_response({"seat": MOCK_FREE_SEAT}),
@@ -403,8 +406,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.json()["plan_key"] == "posthog-code-200-20260301"
assert "organization_id" in response.json()
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_multi_org_returns_pro_regardless_of_order(self, _mock_token, mock_request, _mock_license):
mock_request.side_effect = [
_billing_response({"seat": MOCK_PRO_SEAT}),
@@ -415,16 +418,16 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["plan_key"] == "posthog-code-200-20260301"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_all_billing_failures_returns_404(self, _mock_token, mock_request, _mock_license):
mock_request.return_value = _billing_response({"error": "fail"}, status_code=500, ok=False)
self._auth_as_member()
response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")
assert response.status_code == status.HTTP_404_NOT_FOUND
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_partial_failure_returns_best_available(self, _mock_token, mock_request, _mock_license):
mock_request.side_effect = [
_billing_response({"error": "fail"}, status_code=500, ok=False),
@@ -435,8 +438,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["plan_key"] == "posthog-code-200-20260301"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_best_ignored_for_non_me_pk(self, _mock_token, mock_request, _mock_license):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_admin()
@@ -444,8 +447,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert mock_request.call_count == 1
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_without_best_param_does_single_call(self, _mock_token, mock_request, _mock_license):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_member()
@@ -453,14 +456,14 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert mock_request.call_count == 1
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_no_orgs_returns_400(self, _mock_token, _mock_license):
self.client.force_authenticate(self.external_user)
response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_pro_v2_prefix_recognized(self, _mock_token, mock_request, _mock_license):
mock_request.side_effect = [
_billing_response({"seat": MOCK_FREE_SEAT}),
@@ -471,8 +474,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["plan_key"] == "posthog-code-pro-200-20260422"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_no_plan_key_loses_to_free(self, _mock_token, mock_request, _mock_license):
no_plan_seat = {**MOCK_FREE_SEAT, "plan_key": None, "id": "seat_none"}
mock_request.side_effect = [
@@ -484,8 +487,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["plan_key"] == "posthog-code-free-20260301"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_active_free_beats_canceled_pro(self, _mock_token, mock_request, _mock_license):
canceled_pro = {**MOCK_PRO_SEAT, "status": "canceled", "id": "seat_canceled_pro"}
mock_request.side_effect = [
@@ -498,8 +501,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.json()["plan_key"] == "posthog-code-free-20260301"
assert response.json()["status"] == "active"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_canceling_pro_beats_active_free(self, _mock_token, mock_request, _mock_license):
canceling_pro = {
**MOCK_PRO_SEAT,
@@ -517,8 +520,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.json()["plan_key"] == MOCK_PRO_SEAT["plan_key"]
assert response.json()["status"] == "canceling"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_future_exception_handled_gracefully(self, _mock_token, mock_request, _mock_license):
mock_request.side_effect = [
RuntimeError("connection reset"),
@@ -529,8 +532,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["plan_key"] == "posthog-code-200-20260301"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token")
def test_partial_header_failure_returns_available_seat(self, mock_token, mock_request, _mock_license):
mock_token.side_effect = [NotAuthenticated("no member"), MOCK_BILLING_TOKEN]
mock_request.return_value = _billing_response({"seat": MOCK_FREE_SEAT})
@@ -539,8 +542,8 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["plan_key"] == "posthog-code-free-20260301"
- @patch("products.tasks.backend.seat_api.requests.request")
- @patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
def test_same_tier_picks_oldest_seat(self, _mock_token, mock_request, _mock_license):
newer_pro = {**MOCK_PRO_SEAT, "id": "seat_newer", "created_at": "2026-06-01T00:00:00Z"}
older_pro = {**MOCK_PRO_SEAT, "id": "seat_older", "created_at": "2026-03-01T00:00:00Z"}
@@ -554,12 +557,12 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
assert response.json()["id"] == "seat_older"
-@patch("products.tasks.backend.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
-@patch("products.tasks.backend.seat_api.get_cached_instance_license", return_value=MagicMock())
+@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license", return_value=MagicMock())
class TestSeatAPIKeyAccess(BaseSeatAPITest):
"""Personal API keys are allowed so the LLM gateway can resolve seats."""
- @patch("products.tasks.backend.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_personal_api_key_allowed(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
token = generate_random_token_personal()
diff --git a/products/tasks/backend/tests/test_slack_thread_context.py b/products/tasks/backend/tests/test_slack_thread_context.py
index 04ec7df4176b..21c52905cd02 100644
--- a/products/tasks/backend/tests/test_slack_thread_context.py
+++ b/products/tasks/backend/tests/test_slack_thread_context.py
@@ -37,7 +37,7 @@ class _SlackThreadContextBase(TestCase):
# can't easily force the test row to id 2, so substitute self.team.id
# for the constant while keeping the deployment clause intact.
self._gate_patcher = patch(
- "products.tasks.backend.api._is_internal_debug_team",
+ "products.tasks.backend.presentation.views.api._is_internal_debug_team",
side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",
)
self._gate_patcher.start()
@@ -92,7 +92,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
def test_non_internal_team_is_forbidden(self):
# Override the base-class gate patcher so this call lands on the
# "not the internal team" branch of `_is_internal_debug_team`.
- with patch("products.tasks.backend.api._is_internal_debug_team", return_value=False):
+ with patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=False):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
assert response.status_code == status.HTTP_403_FORBIDDEN
@@ -116,7 +116,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
def test_happy_path_returns_task_and_runs(self):
task, run, mapping = self._create_fixture()
with patch(
- "products.tasks.backend.api.object_storage.get_presigned_url",
+ "posthog.storage.object_storage.get_presigned_url",
return_value="https://s3.example/presigned",
):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
@@ -152,7 +152,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
# Presign failures must degrade to a null log_url, not 500.
self._create_fixture()
with patch(
- "products.tasks.backend.api.object_storage.get_presigned_url",
+ "posthog.storage.object_storage.get_presigned_url",
side_effect=Exception("boto signing error"),
):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
@@ -165,7 +165,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
"https://posthog.slack.com/archives/C0ACRAMJUAG/p1779957091477899"
"?thread_ts=1779956938.619299&cid=C0ACRAMJUAG"
)
- with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ with patch("posthog.storage.object_storage.get_presigned_url", return_value=None):
response = self.client.get(self._url(reply_url))
assert response.status_code == status.HTTP_200_OK, response.content
body = response.json()
@@ -185,7 +185,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
"slack_mention_workflow_id": "posthog-code-mention-T_SLACK:Ev02",
},
)
- with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ with patch("posthog.storage.object_storage.get_presigned_url", return_value=None):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
assert response.status_code == status.HTTP_200_OK
body = response.json()
@@ -196,7 +196,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
@override_settings(TEMPORAL_UI_HOST="")
def test_temporal_url_null_when_ui_host_unset(self):
self._create_fixture()
- with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ with patch("posthog.storage.object_storage.get_presigned_url", return_value=None):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
assert response.status_code == status.HTTP_200_OK
body = response.json()
@@ -207,7 +207,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
@override_settings(TEMPORAL_UI_HOST="https://temporal.example.com", TEMPORAL_NAMESPACE="prod")
def test_temporal_url_includes_workflow_id_when_configured(self):
task, run, _ = self._create_fixture()
- with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ with patch("posthog.storage.object_storage.get_presigned_url", return_value=None):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
assert response.status_code == status.HTTP_200_OK
body = response.json()
@@ -221,7 +221,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
def test_mention_workflow_id_null_for_old_runs(self):
self._create_fixture(slack_mention_workflow_id=None)
- with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ with patch("posthog.storage.object_storage.get_presigned_url", return_value=None):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
assert response.status_code == status.HTTP_200_OK
body = response.json()
@@ -231,7 +231,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
def test_repo_research_null_for_unambiguous_run(self):
# The default fixture run has no repo_research_* state — it should report null.
self._create_fixture()
- with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ with patch("posthog.storage.object_storage.get_presigned_url", return_value=None):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
assert response.status_code == status.HTTP_200_OK
assert response.json()["runs"][0]["repo_research"] is None
@@ -263,7 +263,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
with override_settings(TEMPORAL_UI_HOST="https://temporal.example.com", TEMPORAL_NAMESPACE="prod"):
with patch(
- "products.tasks.backend.api.object_storage.get_presigned_url",
+ "posthog.storage.object_storage.get_presigned_url",
return_value="https://s3.example/research-log",
):
response = self.client.get(
@@ -295,7 +295,7 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):
"repo_research_run_id": "22222222-2222-2222-2222-222222222222",
}
run.save(update_fields=["state"])
- with patch("products.tasks.backend.api.object_storage.get_presigned_url", return_value=None):
+ with patch("posthog.storage.object_storage.get_presigned_url", return_value=None):
response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))
assert response.status_code == status.HTTP_200_OK
research = response.json()["runs"][0]["repo_research"]
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index d89db9ec9c96..f661531cd659 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -75,7 +75,7 @@ class TestGitHubPRWebhook(TestCase):
headers={"x-hub-signature-256": signature, "x-github-event": event_type},
)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_merged_webhook(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -100,7 +100,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(call_kwargs["properties"]["run_id"], str(self.task_run.id))
self.assertEqual(call_kwargs["properties"]["pr_source"], "task")
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_closed_without_merge_webhook(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -121,7 +121,7 @@ class TestGitHubPRWebhook(TestCase):
call_kwargs = mock_capture.call_args[1]
self.assertEqual(call_kwargs["event"], "pr_closed")
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_opened_webhook(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -142,7 +142,7 @@ class TestGitHubPRWebhook(TestCase):
call_kwargs = mock_capture.call_args[1]
self.assertEqual(call_kwargs["event"], "pr_created")
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_opened_backfills_pr_url_on_branch_match(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -171,7 +171,7 @@ class TestGitHubPRWebhook(TestCase):
assert run.output is not None
self.assertEqual(run.output["pr_url"], pr_url)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_opened_from_fork_does_not_backfill_pr_url(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -198,7 +198,7 @@ class TestGitHubPRWebhook(TestCase):
run.refresh_from_db()
self.assertEqual(run.output, {})
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_opened_does_not_overwrite_existing_pr_url(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -227,7 +227,7 @@ class TestGitHubPRWebhook(TestCase):
assert run.output is not None
self.assertEqual(run.output["pr_url"], existing)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_invalid_signature_rejected(self, mock_get_secret):
"""Test that requests with invalid signatures are rejected."""
mock_get_secret.return_value = self.webhook_secret
@@ -244,7 +244,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 403)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_missing_signature_rejected(self, mock_get_secret):
"""Test that requests without signatures are rejected."""
mock_get_secret.return_value = self.webhook_secret
@@ -260,7 +260,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 403)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_unmatched_pr_without_installation_not_captured(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -278,7 +278,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 200)
mock_capture.assert_not_called()
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_non_pr_non_issue_event_ignored(self, mock_get_secret):
"""Test that events other than pull_request/issues/issue_comment are acknowledged but ignored."""
mock_get_secret.return_value = self.webhook_secret
@@ -289,7 +289,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 200)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_ignored_pr_actions(self, mock_get_secret):
"""Test that PR actions other than opened/closed are acknowledged but ignored."""
mock_get_secret.return_value = self.webhook_secret
@@ -308,7 +308,7 @@ class TestGitHubPRWebhook(TestCase):
def test_webhook_secret_not_configured(self):
"""Test that webhook returns 500 if secret is not configured."""
- with patch("products.tasks.backend.webhooks.get_github_webhook_secret", return_value=None):
+ with patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret", return_value=None):
payload = {"action": "closed", "pull_request": {"html_url": "https://github.com/org/repo/pull/1"}}
response = self.client.post(
@@ -325,7 +325,7 @@ class TestGitHubPRWebhook(TestCase):
response = self.client.get("/webhooks/github/pr/")
self.assertEqual(response.status_code, 405)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_webhook_does_not_attribute_foreign_repo_pr_to_unrelated_run(self, mock_capture, mock_get_secret):
# Regression: a PR opened on a repo that has no matching TaskRun must
@@ -441,7 +441,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
),
]
)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_event_transitions_linked_report(
self, _name, action, merged, initial_status, expected_status, _mock_capture, mock_get_secret
@@ -457,7 +457,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
self.report.refresh_from_db()
self.assertEqual(self.report.status, expected_status)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_merge_on_task_without_linked_report_is_a_noop(self, _mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -525,7 +525,7 @@ class TestExternalPRWebhook(TestCase):
("merged", "closed", True, "pr_merged"),
]
)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_external_pr_event_attributes_to_installation_team(
self, _name, action, merged, expected_event, mock_capture, mock_get_secret
@@ -551,7 +551,7 @@ class TestExternalPRWebhook(TestCase):
self.assertIsNone(props["origin_product"])
self.assertIsNone(props["title"])
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_external_pr_event_is_deduplicated_per_action(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -565,7 +565,7 @@ class TestExternalPRWebhook(TestCase):
second_uuid = mock_capture.call_args_list[1][1]["uuid"]
self.assertEqual(first_uuid, second_uuid)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_external_pr_without_resolvable_installation_is_dropped(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -578,7 +578,7 @@ class TestExternalPRWebhook(TestCase):
self.assertEqual(response.status_code, 200)
mock_capture.assert_not_called()
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_external_pr_shared_installation_resolves_deterministically(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -594,7 +594,7 @@ class TestExternalPRWebhook(TestCase):
distinct_ids = {call[1]["distinct_id"] for call in mock_capture.call_args_list}
self.assertEqual(distinct_ids, {str(expected_team.uuid)})
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_external_pr_without_installation_block_is_dropped(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
@@ -800,7 +800,7 @@ class TestGitHubWebhookFanout(TestCase):
]
)
@patch("products.conversations.backend.api.github_events.process_github_event")
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_issues_event_dispatched_to_conversations(self, _name, url, mock_secret, mock_task):
mock_secret.return_value = self.webhook_secret
mock_task.delay = MagicMock()
@@ -823,7 +823,7 @@ class TestGitHubWebhookFanout(TestCase):
self.assertEqual(call_kwargs["repo"], "myorg/myrepo")
@patch("products.conversations.backend.api.github_events.process_github_event")
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_issue_comment_event_dispatched_to_conversations(self, mock_secret, mock_task):
mock_secret.return_value = self.webhook_secret
mock_task.delay = MagicMock()
@@ -844,7 +844,7 @@ class TestGitHubWebhookFanout(TestCase):
self.assertEqual(mock_task.delay.call_args[1]["event_type"], "issue_comment")
@patch("products.conversations.backend.api.github_events.process_github_event")
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_issues_event_without_matching_team_returns_200(self, mock_secret, mock_task):
mock_secret.return_value = self.webhook_secret
mock_task.delay = MagicMock()
@@ -868,7 +868,7 @@ class TestGitHubWebhookFanout(TestCase):
("unified_url", "/webhooks/github/"),
]
)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pull_request_routed(self, _name, url, mock_capture, mock_secret):
mock_secret.return_value = self.webhook_secret
@@ -887,7 +887,7 @@ class TestGitHubWebhookFanout(TestCase):
mock_capture.assert_called_once()
self.assertEqual(mock_capture.call_args[1]["event"], "pr_merged")
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_unified_url_unknown_event_returns_200(self, mock_secret):
mock_secret.return_value = self.webhook_secret
@@ -896,7 +896,7 @@ class TestGitHubWebhookFanout(TestCase):
self.assertEqual(response.status_code, 200)
- @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
def test_unified_url_bad_signature_returns_403(self, mock_secret):
mock_secret.return_value = self.webhook_secret
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index c7b9875dc59a..afbdbcc5c7f4 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -48,243 +48,433 @@ export interface TaskRunErrorResponseApi {
}
/**
- * * `trusted` - Trusted
- * * `full` - Full
- * * `custom` - Custom
+ * @nullable
*/
-export type NetworkAccessLevelEnumApi = (typeof NetworkAccessLevelEnumApi)[keyof typeof NetworkAccessLevelEnumApi]
-
-export const NetworkAccessLevelEnumApi = {
- Trusted: 'trusted',
- Full: 'full',
- Custom: 'custom',
-} as const
+export type TaskUserBasicInfoApiHedgehogConfig = { [key: string]: unknown } | null
/**
- * * `engineering` - Engineering
- * * `data` - Data
- * * `product` - Product Management
- * * `founder` - Founder
- * * `leadership` - Leadership
- * * `marketing` - Marketing
- * * `sales` - Sales / Success
- * * `other` - Other
+ * Response shape for a `created_by` user — mirrors core `UserBasicSerializer` output.
*/
-export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
-
-export const RoleAtOrganizationEnumApi = {
- Engineering: 'engineering',
- Data: 'data',
- Product: 'product',
- Founder: 'founder',
- Leadership: 'leadership',
- Marketing: 'marketing',
- Sales: 'sales',
- Other: 'other',
-} as const
-
-export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
-
-export const BlankEnumApi = {
- '': '',
-} as const
-
-/**
- * @nullable
- */
-export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
-
-export interface UserBasicApi {
- readonly id: number
- readonly uuid: string
- /**
- * @maxLength 200
- * @nullable
- */
- distinct_id?: string | null
- /** @maxLength 150 */
- first_name?: string
- /** @maxLength 150 */
- last_name?: string
- /** @maxLength 254 */
+export interface TaskUserBasicInfoApi {
+ id: number
+ uuid: string
+ distinct_id: string
+ first_name: string
+ last_name: string
email: string
/** @nullable */
is_email_verified?: boolean | null
/** @nullable */
- readonly hedgehog_config: UserBasicApiHedgehogConfig
- role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
+ hedgehog_config?: TaskUserBasicInfoApiHedgehogConfig
+ /** @nullable */
+ role_at_organization?: string | null
}
-export interface SandboxEnvironmentListApi {
- readonly id: string
- /** @maxLength 255 */
+/**
+ * List response for sandbox environments (subset of fields).
+ */
+export interface SandboxEnvironmentDTOApi {
+ id: string
name: string
- network_access_level?: NetworkAccessLevelEnumApi
- /**
- * List of allowed domains for custom network access
- * @items.maxLength 255
- */
+ network_access_level: string
allowed_domains?: string[]
- /**
- * List of repositories this environment applies to (format: org/repo)
- * @items.maxLength 255
- */
repositories?: string[]
- /** If true, only the creator can see this environment. Otherwise visible to whole team. */
- private?: boolean
- /** If true, this environment is for internal use (e.g. signals pipeline) and should not be exposed to end users. */
- internal?: boolean
- readonly created_by: UserBasicApi
- readonly created_at: string
- readonly updated_at: string
+ private: boolean
+ internal: boolean
+ created_by?: TaskUserBasicInfoApi | null
+ /** @nullable */
+ created_at?: string | null
+ /** @nullable */
+ updated_at?: string | null
}
-export interface PaginatedSandboxEnvironmentListListApi {
+export interface PaginatedSandboxEnvironmentDTOListApi {
count: number
/** @nullable */
next?: string | null
/** @nullable */
previous?: string | null
- results: SandboxEnvironmentListApi[]
+ results: SandboxEnvironmentDTOApi[]
}
-export interface SandboxEnvironmentApi {
- readonly id: string
- /** @maxLength 255 */
+/**
+ * * `trusted` - Trusted
+ * * `full` - Full
+ * * `custom` - Custom
+ */
+export type NetworkAccessLevelEnumApi = (typeof NetworkAccessLevelEnumApi)[keyof typeof NetworkAccessLevelEnumApi]
+
+export const NetworkAccessLevelEnumApi = {
+ Trusted: 'trusted',
+ Full: 'full',
+ Custom: 'custom',
+} as const
+
+/**
+ * Request body for creating or updating a sandbox environment.
+ */
+export interface SandboxEnvironmentWriteApi {
+ /**
+ * Display name for the environment.
+ * @maxLength 255
+ */
name: string
+ /** Network access policy: trusted (default allowlist), full (unrestricted), or custom.
+ *
+ * * `trusted` - Trusted
+ * * `full` - Full
+ * * `custom` - Custom */
network_access_level?: NetworkAccessLevelEnumApi
/**
- * List of allowed domains for custom network access
+ * Allowed domains for custom network access.
* @items.maxLength 255
*/
allowed_domains?: string[]
- /** Whether to include default trusted domains (GitHub, npm, PyPI) */
+ /** Whether to include default trusted domains (GitHub, npm, PyPI). */
include_default_domains?: boolean
/**
- * List of repositories this environment applies to (format: org/repo)
+ * Repositories this environment applies to (format: org/repo).
* @items.maxLength 255
*/
repositories?: string[]
- /** Encrypted environment variables (write-only, never returned in responses) */
+ /** Encrypted environment variables (write-only, never returned in responses). */
environment_variables?: unknown
- /** Whether this environment has any environment variables set */
- readonly has_environment_variables: boolean
- /** If true, only the creator can see this environment. Otherwise visible to whole team. */
+ /** If true, only the creator can see this environment; otherwise the whole team can. */
private?: boolean
- /** If true, this environment is for internal use (e.g. signals pipeline) and should not be exposed to end users. */
- readonly internal: boolean
- /** Computed domain allowlist based on network_access_level and allowed_domains */
- readonly effective_domains: readonly string[]
- readonly created_by: UserBasicApi
- readonly created_at: string
- readonly updated_at: string
-}
-
-export interface PatchedSandboxEnvironmentApi {
- readonly id?: string
- /** @maxLength 255 */
+}
+
+/**
+ * Request body for creating or updating a sandbox environment.
+ */
+export interface PatchedSandboxEnvironmentWriteApi {
+ /**
+ * Display name for the environment.
+ * @maxLength 255
+ */
name?: string
+ /** Network access policy: trusted (default allowlist), full (unrestricted), or custom.
+ *
+ * * `trusted` - Trusted
+ * * `full` - Full
+ * * `custom` - Custom */
network_access_level?: NetworkAccessLevelEnumApi
/**
- * List of allowed domains for custom network access
+ * Allowed domains for custom network access.
* @items.maxLength 255
*/
allowed_domains?: string[]
- /** Whether to include default trusted domains (GitHub, npm, PyPI) */
+ /** Whether to include default trusted domains (GitHub, npm, PyPI). */
include_default_domains?: boolean
/**
- * List of repositories this environment applies to (format: org/repo)
+ * Repositories this environment applies to (format: org/repo).
* @items.maxLength 255
*/
repositories?: string[]
- /** Encrypted environment variables (write-only, never returned in responses) */
+ /** Encrypted environment variables (write-only, never returned in responses). */
environment_variables?: unknown
- /** Whether this environment has any environment variables set */
- readonly has_environment_variables?: boolean
- /** If true, only the creator can see this environment. Otherwise visible to whole team. */
+ /** If true, only the creator can see this environment; otherwise the whole team can. */
private?: boolean
- /** If true, this environment is for internal use (e.g. signals pipeline) and should not be exposed to end users. */
- readonly internal?: boolean
- /** Computed domain allowlist based on network_access_level and allowed_domains */
- readonly effective_domains?: readonly string[]
- readonly created_by?: UserBasicApi
- readonly created_at?: string
- readonly updated_at?: string
-}
-
-export interface TaskAutomationApi {
- readonly id: string
- /** @maxLength 255 */
+}
+
+/**
+ * Detail/create/update/run response for a task automation.
+ */
+export interface TaskAutomationDTOApi {
+ id: string
name: string
prompt: string
- /** @maxLength 255 */
- repository: string
/** @nullable */
- github_integration?: number | null
- /** @maxLength 100 */
+ repository: string | null
+ /** @nullable */
+ github_integration: number | null
cron_expression: string
- /** @maxLength 128 */
- timezone?: string
- /**
- * @maxLength 255
- * @nullable
- */
- template_id?: string | null
- enabled?: boolean
+ timezone: string
/** @nullable */
- readonly last_run_at: string | null
+ template_id: string | null
+ enabled: boolean
/** @nullable */
- readonly last_run_status: string | null
+ last_run_at: string | null
/** @nullable */
- readonly last_task_id: string | null
+ last_run_status: string | null
+ last_task_id: string
/** @nullable */
- readonly last_task_run_id: string | null
+ last_task_run_id: string | null
/** @nullable */
- readonly last_error: string | null
- readonly created_at: string
- readonly updated_at: string
+ last_error: string | null
+ created_at: string
+ updated_at: string
}
-export interface PaginatedTaskAutomationListApi {
+export interface PaginatedTaskAutomationDTOListApi {
count: number
/** @nullable */
next?: string | null
/** @nullable */
previous?: string | null
- results: TaskAutomationApi[]
+ results: TaskAutomationDTOApi[]
}
-export interface PatchedTaskAutomationApi {
- readonly id?: string
- /** @maxLength 255 */
+/**
+ * Request body for creating or updating a task automation.
+ */
+export interface TaskAutomationWriteApi {
+ /**
+ * Display name (stored as the backing task's title).
+ * @maxLength 255
+ */
+ name: string
+ /** The automation prompt (stored as the backing task's description). */
+ prompt: string
+ /**
+ * Target repository in the format organization/repository.
+ * @maxLength 255
+ */
+ repository: string
+ /**
+ * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
+ * @nullable
+ */
+ github_integration?: number | null
+ /**
+ * Standard 5-field cron expression (minute hour day month weekday).
+ * @maxLength 100
+ */
+ cron_expression: string
+ /**
+ * IANA timezone the schedule runs in.
+ * @maxLength 128
+ */
+ timezone?: string
+ /**
+ * Optional template identifier this automation was created from.
+ * @maxLength 255
+ * @nullable
+ */
+ template_id?: string | null
+ /** Whether the schedule is active; paused when false. */
+ enabled?: boolean
+}
+
+/**
+ * Request body for creating or updating a task automation.
+ */
+export interface PatchedTaskAutomationWriteApi {
+ /**
+ * Display name (stored as the backing task's title).
+ * @maxLength 255
+ */
name?: string
+ /** The automation prompt (stored as the backing task's description). */
prompt?: string
- /** @maxLength 255 */
+ /**
+ * Target repository in the format organization/repository.
+ * @maxLength 255
+ */
repository?: string
- /** @nullable */
+ /**
+ * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
+ * @nullable
+ */
github_integration?: number | null
- /** @maxLength 100 */
+ /**
+ * Standard 5-field cron expression (minute hour day month weekday).
+ * @maxLength 100
+ */
cron_expression?: string
- /** @maxLength 128 */
+ /**
+ * IANA timezone the schedule runs in.
+ * @maxLength 128
+ */
timezone?: string
/**
+ * Optional template identifier this automation was created from.
* @maxLength 255
* @nullable
*/
template_id?: string | null
+ /** Whether the schedule is active; paused when false. */
enabled?: boolean
+}
+
+/**
+ * * `claude` - claude
+ * * `codex` - codex
+ */
+export type RuntimeAdapterEnumApi = (typeof RuntimeAdapterEnumApi)[keyof typeof RuntimeAdapterEnumApi]
+
+export const RuntimeAdapterEnumApi = {
+ Claude: 'claude',
+ Codex: 'codex',
+} as const
+
+/**
+ * * `anthropic` - anthropic
+ * * `openai` - openai
+ */
+export type TaskRunDetailDTOProviderEnumApi =
+ (typeof TaskRunDetailDTOProviderEnumApi)[keyof typeof TaskRunDetailDTOProviderEnumApi]
+
+export const TaskRunDetailDTOProviderEnumApi = {
+ Anthropic: 'anthropic',
+ Openai: 'openai',
+} as const
+
+/**
+ * * `low` - low
+ * * `medium` - medium
+ * * `high` - high
+ * * `xhigh` - xhigh
+ * * `max` - max
+ */
+export type ReasoningEffortEnumApi = (typeof ReasoningEffortEnumApi)[keyof typeof ReasoningEffortEnumApi]
+
+export const ReasoningEffortEnumApi = {
+ Low: 'low',
+ Medium: 'medium',
+ High: 'high',
+ Xhigh: 'xhigh',
+ Max: 'max',
+} as const
+
+export interface TaskRunArtifactResponseApi {
+ /** Stable identifier for the artifact within this run */
+ id?: string
+ /** Artifact file name */
+ name: string
+ /** Artifact classification (plan, context, etc.) */
+ type: string
+ /** Source of the artifact, such as agent_output or user_attachment */
+ source?: string
+ /** Artifact size in bytes */
+ size?: number
+ /** Optional MIME type */
+ content_type?: string
+ /** S3 object key for the artifact */
+ storage_path: string
+ /** Timestamp when the artifact was uploaded */
+ uploaded_at: string
+}
+
+/**
+ * @nullable
+ */
+export type TaskRunDetailDTOApiOutput = { [key: string]: unknown } | null
+
+export type TaskRunDetailDTOApiState = { [key: string]: unknown }
+
+/**
+ * Detail response for a task run.
+ *
+ * Reads from a frozen ``TaskRunDetailDTO`` produced by the facade mapper (which computes the
+ * presigned ``log_url`` and parses ``runtime_adapter`` / ``provider`` / ``model`` /
+ * ``reasoning_effort`` off the run state). ``task`` is the parent task id. Reused as the nested
+ * ``latest_run`` shape by the task detail response.
+ */
+export interface TaskRunDetailDTOApi {
+ id: string
+ /** Parent task id this run belongs to. */
+ task: string
+ /** @nullable */
+ stage: string | null
+ /** @nullable */
+ branch: string | null
+ status: string
+ environment: string
+ /** Configured runtime adapter for this run, such as 'claude' or 'codex'.
+ *
+ * * `claude` - claude
+ * * `codex` - codex */
+ runtime_adapter?: RuntimeAdapterEnumApi | null
+ /** Configured LLM provider for this run, such as 'anthropic' or 'openai'.
+ *
+ * * `anthropic` - anthropic
+ * * `openai` - openai */
+ provider?: TaskRunDetailDTOProviderEnumApi | null
+ /**
+ * Configured LLM model identifier for this run.
+ * @nullable
+ */
+ model?: string | null
+ /** Configured reasoning effort for this run when the selected model supports it.
+ *
+ * * `low` - low
+ * * `medium` - medium
+ * * `high` - high
+ * * `xhigh` - xhigh
+ * * `max` - max */
+ reasoning_effort?: ReasoningEffortEnumApi | null
+ /**
+ * Presigned S3 URL for log access (valid for 1 hour).
+ * @nullable
+ */
+ log_url?: string | null
+ /** @nullable */
+ error_message: string | null
+ /** @nullable */
+ output: TaskRunDetailDTOApiOutput
+ state: TaskRunDetailDTOApiState
+ readonly artifacts: readonly TaskRunArtifactResponseApi[]
+ /** @nullable */
+ created_at?: string | null
+ /** @nullable */
+ updated_at?: string | null
+ /** @nullable */
+ completed_at?: string | null
+}
+
+/**
+ * @nullable
+ */
+export type TaskDetailDTOApiJsonSchema = { [key: string]: unknown } | null
+
+/**
+ * Detail response for a task.
+ *
+ * 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``.
+ */
+export interface TaskDetailDTOApi {
+ id: string
+ /** @nullable */
+ task_number: number | null
+ slug: string
+ title: string
+ title_manually_set: boolean
+ description: string
+ origin_product: string
+ /** @nullable */
+ repository: string | null
+ /** @nullable */
+ github_integration: number | null
+ /** @nullable */
+ github_user_integration: string | null
+ /** @nullable */
+ signal_report: string | null
/** @nullable */
- readonly last_run_at?: string | null
+ json_schema: TaskDetailDTOApiJsonSchema
+ internal: boolean
+ archived: boolean
/** @nullable */
- readonly last_run_status?: string | null
+ archived_at: string | null
+ /** Latest run details for this task */
+ latest_run?: TaskRunDetailDTOApi | null
/** @nullable */
- readonly last_task_id?: string | null
+ created_at?: string | null
/** @nullable */
- readonly last_task_run_id?: string | null
+ updated_at?: string | null
+ created_by?: TaskUserBasicInfoApi | null
/** @nullable */
- readonly last_error?: string | null
- readonly created_at?: string
- readonly updated_at?: string
+ ci_prompt: string | null
+}
+
+export interface PaginatedTaskDetailDTOListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: TaskDetailDTOApi[]
}
/**
@@ -325,21 +515,19 @@ export const SignalReportTaskRelationshipEnumApi = {
} as const
/**
- * Latest run details for this task
- * @nullable
+ * Request body for creating or updating a task.
+ *
+ * Field required/default semantics match the ``Task`` model. The view passes
+ * ``validated_data`` (integration/report PK fields already resolved to instances) to the
+ * facade ``create_task`` / ``update_task`` functions.
*/
-export type TaskApiLatestRun = { [key: string]: unknown } | null
-
-export interface TaskApi {
- readonly id: string
- /** @nullable */
- readonly task_number: number | null
- readonly slug: string
+export interface TaskWriteApi {
/**
* Short human-readable title. Auto-generated from `description` when omitted.
* @maxLength 255
*/
title?: string
+ /** Whether the title was set by a human (vs auto-generated from the description). */
title_manually_set?: boolean
/** Free-form description of the work to be done. Used as the prompt passed to the agent. */
description?: string
@@ -363,7 +551,7 @@ export interface TaskApi {
*/
repository?: string | null
/**
- * GitHub integration for this task
+ * GitHub integration for this task.
* @nullable
*/
github_integration?: number | null
@@ -372,25 +560,18 @@ export interface TaskApi {
* @nullable
*/
github_user_integration?: string | null
- /** @nullable */
+ /**
+ * Signal report this task implements, when created from a report.
+ * @nullable
+ */
signal_report?: string | null
signal_report_task_relationship?: SignalReportTaskRelationshipEnumApi
- /** JSON schema for the task. This is used to validate the output of the task. */
+ /** JSON schema used to validate the output of the task. */
json_schema?: unknown
/** If true, this task is for internal use and should not be exposed to end users. */
internal?: boolean
- /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */
+ /** If true, the task is hidden from default list responses. */
archived?: boolean
- /** @nullable */
- readonly archived_at: string | null
- /**
- * Latest run details for this task
- * @nullable
- */
- readonly latest_run: TaskApiLatestRun
- readonly created_at: string
- readonly updated_at: string
- readonly created_by: UserBasicApi
/**
* Custom prompt for CI fixes. If blank, a default prompt will be used.
* @nullable
@@ -398,31 +579,20 @@ export interface TaskApi {
ci_prompt?: string | null
}
-export interface PaginatedTaskListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: TaskApi[]
-}
-
/**
- * Latest run details for this task
- * @nullable
+ * Request body for creating or updating a task.
+ *
+ * Field required/default semantics match the ``Task`` model. The view passes
+ * ``validated_data`` (integration/report PK fields already resolved to instances) to the
+ * facade ``create_task`` / ``update_task`` functions.
*/
-export type PatchedTaskApiLatestRun = { [key: string]: unknown } | null
-
-export interface PatchedTaskApi {
- readonly id?: string
- /** @nullable */
- readonly task_number?: number | null
- readonly slug?: string
+export interface PatchedTaskWriteApi {
/**
* Short human-readable title. Auto-generated from `description` when omitted.
* @maxLength 255
*/
title?: string
+ /** Whether the title was set by a human (vs auto-generated from the description). */
title_manually_set?: boolean
/** Free-form description of the work to be done. Used as the prompt passed to the agent. */
description?: string
@@ -446,7 +616,7 @@ export interface PatchedTaskApi {
*/
repository?: string | null
/**
- * GitHub integration for this task
+ * GitHub integration for this task.
* @nullable
*/
github_integration?: number | null
@@ -455,25 +625,18 @@ export interface PatchedTaskApi {
* @nullable
*/
github_user_integration?: string | null
- /** @nullable */
+ /**
+ * Signal report this task implements, when created from a report.
+ * @nullable
+ */
signal_report?: string | null
signal_report_task_relationship?: SignalReportTaskRelationshipEnumApi
- /** JSON schema for the task. This is used to validate the output of the task. */
+ /** JSON schema used to validate the output of the task. */
json_schema?: unknown
/** If true, this task is for internal use and should not be exposed to end users. */
internal?: boolean
- /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */
+ /** If true, the task is hidden from default list responses. */
archived?: boolean
- /** @nullable */
- readonly archived_at?: string | null
- /**
- * Latest run details for this task
- * @nullable
- */
- readonly latest_run?: PatchedTaskApiLatestRun
- readonly created_at?: string
- readonly updated_at?: string
- readonly created_by?: UserBasicApi
/**
* Custom prompt for CI fixes. If blank, a default prompt will be used.
* @nullable
@@ -538,23 +701,6 @@ export const ClaudeRuntimeAdapterEnumApi = {
Claude: 'claude',
} as const
-/**
- * * `low` - low
- * * `medium` - medium
- * * `high` - high
- * * `xhigh` - xhigh
- * * `max` - max
- */
-export type ReasoningEffortEnumApi = (typeof ReasoningEffortEnumApi)[keyof typeof ReasoningEffortEnumApi]
-
-export const ReasoningEffortEnumApi = {
- Low: 'low',
- Medium: 'medium',
- High: 'high',
- Xhigh: 'xhigh',
- Max: 'max',
-} as const
-
/**
* * `default` - default
* * `acceptEdits` - acceptEdits
@@ -822,25 +968,6 @@ export interface TaskStagedArtifactsFinalizeUploadRequestApi {
artifacts: TaskStagedArtifactFinalizeUploadApi[]
}
-export interface TaskRunArtifactResponseApi {
- /** Stable identifier for the artifact within this run */
- id?: string
- /** Artifact file name */
- name: string
- /** Artifact classification (plan, context, etc.) */
- type: string
- /** Source of the artifact, such as agent_output or user_attachment */
- source?: string
- /** Artifact size in bytes */
- size?: number
- /** Optional MIME type */
- content_type?: string
- /** S3 object key for the artifact */
- storage_path: string
- /** Timestamp when the artifact was uploaded */
- uploaded_at: string
-}
-
export interface TaskStagedArtifactsFinalizeUploadResponseApi {
/** Finalized staged artifacts available for attachment to a new run */
artifacts: TaskRunArtifactResponseApi[]
@@ -923,115 +1050,13 @@ export interface TaskStagedArtifactsPrepareUploadResponseApi {
artifacts: TaskStagedArtifactPrepareUploadResponseApi[]
}
-/**
- * * `not_started` - Not Started
- * * `queued` - Queued
- * * `in_progress` - In Progress
- * * `completed` - Completed
- * * `failed` - Failed
- * * `cancelled` - Cancelled
- */
-export type TaskRunStatusEnumApi = (typeof TaskRunStatusEnumApi)[keyof typeof TaskRunStatusEnumApi]
-
-export const TaskRunStatusEnumApi = {
- NotStarted: 'not_started',
- Queued: 'queued',
- InProgress: 'in_progress',
- Completed: 'completed',
- Failed: 'failed',
- Cancelled: 'cancelled',
-} as const
-
-/**
- * * `local` - Local
- * * `cloud` - Cloud
- */
-export type TaskRunEnvironmentEnumApi = (typeof TaskRunEnvironmentEnumApi)[keyof typeof TaskRunEnvironmentEnumApi]
-
-export const TaskRunEnvironmentEnumApi = {
- Local: 'local',
- Cloud: 'cloud',
-} as const
-
-/**
- * * `claude` - claude
- * * `codex` - codex
- */
-export type RuntimeAdapterEnumApi = (typeof RuntimeAdapterEnumApi)[keyof typeof RuntimeAdapterEnumApi]
-
-export const RuntimeAdapterEnumApi = {
- Claude: 'claude',
- Codex: 'codex',
-} as const
-
-export type TaskRunDetailProviderEnumApi =
- (typeof TaskRunDetailProviderEnumApi)[keyof typeof TaskRunDetailProviderEnumApi]
-
-export const TaskRunDetailProviderEnumApi = {
- Anthropic: 'anthropic',
- Openai: 'openai',
-} as const
-
-export interface TaskRunDetailApi {
- readonly id: string
- readonly task: string
- /**
- * Current stage for this run (e.g., 'research', 'plan', 'build')
- * @maxLength 100
- * @nullable
- */
- stage?: string | null
- /**
- * Branch name for the run
- * @maxLength 255
- * @nullable
- */
- branch?: string | null
- status?: TaskRunStatusEnumApi
- /** Execution environment
- *
- * * `local` - Local
- * * `cloud` - Cloud */
- environment?: TaskRunEnvironmentEnumApi
- /** Configured runtime adapter for this run, such as 'claude' or 'codex'. */
- readonly runtime_adapter: RuntimeAdapterEnumApi | null
- /** Configured LLM provider for this run, such as 'anthropic' or 'openai'. */
- readonly provider: TaskRunDetailProviderEnumApi | null
- /**
- * Configured LLM model identifier for this run.
- * @nullable
- */
- readonly model: string | null
- /** Configured reasoning effort for this run when the selected model supports it. */
- readonly reasoning_effort: ReasoningEffortEnumApi | null
- /**
- * Presigned S3 URL for log access (valid for 1 hour).
- * @nullable
- */
- readonly log_url: string | null
- /**
- * Error message if execution failed
- * @nullable
- */
- error_message?: string | null
- /** Run output data (e.g., PR URL, commit SHA, etc.) */
- output?: unknown
- /** Run state data for resuming or tracking execution state */
- state?: unknown
- readonly artifacts: readonly TaskRunArtifactResponseApi[]
- readonly created_at: string
- readonly updated_at: string
- /** @nullable */
- readonly completed_at: string | null
-}
-
-export interface PaginatedTaskRunDetailListApi {
+export interface PaginatedTaskRunDetailDTOListApi {
count: number
/** @nullable */
next?: string | null
/** @nullable */
previous?: string | null
- results: TaskRunDetailApi[]
+ results: TaskRunDetailDTOApi[]
}
/**
@@ -1752,28 +1777,61 @@ export interface TaskSummariesRequestApi {
ids: string[]
}
+/**
+ * * `not_started` - Not Started
+ * * `queued` - Queued
+ * * `in_progress` - In Progress
+ * * `completed` - Completed
+ * * `failed` - Failed
+ * * `cancelled` - Cancelled
+ */
+export type TaskRunStatusEnumApi = (typeof TaskRunStatusEnumApi)[keyof typeof TaskRunStatusEnumApi]
+
+export const TaskRunStatusEnumApi = {
+ NotStarted: 'not_started',
+ Queued: 'queued',
+ InProgress: 'in_progress',
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+} as const
+
+/**
+ * * `local` - Local
+ * * `cloud` - Cloud
+ */
+export type TaskRunEnvironmentEnumApi = (typeof TaskRunEnvironmentEnumApi)[keyof typeof TaskRunEnvironmentEnumApi]
+
+export const TaskRunEnvironmentEnumApi = {
+ Local: 'local',
+ Cloud: 'cloud',
+} as const
+
export interface TaskRunSummaryApi {
status: TaskRunStatusEnumApi | null
environment: TaskRunEnvironmentEnumApi | null
}
-export interface TaskSummaryApi {
- readonly id: string
- readonly title: string
+/**
+ * Summary response for a task — reads from a frozen ``TaskSummaryDTO``.
+ */
+export interface TaskSummaryDTOApi {
+ id: string
+ title: string
/** @nullable */
- readonly repository: string | null
- readonly created_at: string
- readonly updated_at: string
- readonly latest_run: TaskRunSummaryApi | null
+ repository: string | null
+ created_at: string
+ updated_at: string
+ latest_run?: TaskRunSummaryApi | null
}
-export interface PaginatedTaskSummaryListApi {
+export interface PaginatedTaskSummaryDTOListApi {
count: number
/** @nullable */
next?: string | null
/** @nullable */
previous?: string | null
- results: TaskSummaryApi[]
+ results: TaskSummaryDTOApi[]
}
export type SandboxListParams = {
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 59a86ed8c480..8e58bf76090b 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -11,23 +11,25 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
CodeInviteRedeemRequestApi,
ConnectionTokenResponseApi,
- PaginatedSandboxEnvironmentListListApi,
- PaginatedTaskAutomationListApi,
- PaginatedTaskListApi,
- PaginatedTaskRunDetailListApi,
- PaginatedTaskSummaryListApi,
- PatchedSandboxEnvironmentApi,
- PatchedTaskApi,
- PatchedTaskAutomationApi,
+ PaginatedSandboxEnvironmentDTOListApi,
+ PaginatedTaskAutomationDTOListApi,
+ PaginatedTaskDetailDTOListApi,
+ PaginatedTaskRunDetailDTOListApi,
+ PaginatedTaskSummaryDTOListApi,
+ PatchedSandboxEnvironmentWriteApi,
+ PatchedTaskAutomationWriteApi,
PatchedTaskRunSetOutputRequestApi,
PatchedTaskRunUpdateApi,
+ PatchedTaskWriteApi,
RepositoryReadinessResponseApi,
- SandboxEnvironmentApi,
+ SandboxEnvironmentDTOApi,
+ SandboxEnvironmentWriteApi,
SandboxListParams,
SlackThreadContextResponseApi,
- TaskApi,
- TaskAutomationApi,
+ TaskAutomationDTOApi,
+ TaskAutomationWriteApi,
TaskAutomationsListParams,
+ TaskDetailDTOApi,
TaskPresenceBeaconRequestApi,
TaskRepositoriesResponseApi,
TaskRunAppendLogRequestApi,
@@ -43,7 +45,7 @@ import type {
TaskRunCommandRequestApi,
TaskRunCommandResponseApi,
TaskRunCreateRequestSchemaApi,
- TaskRunDetailApi,
+ TaskRunDetailDTOApi,
TaskRunRelayMessageRequestApi,
TaskRunRelayMessageResponseApi,
TaskRunStartRequestApi,
@@ -52,6 +54,7 @@ import type {
TaskStagedArtifactsPrepareUploadRequestApi,
TaskStagedArtifactsPrepareUploadResponseApi,
TaskSummariesRequestApi,
+ TaskWriteApi,
TasksListParams,
TasksRepositoryReadinessRetrieveParams,
TasksRunsListParams,
@@ -60,23 +63,6 @@ import type {
TasksSummariesCreateParams,
} from './api.schemas'
-// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
-type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
-
-type WritableKeys<T> = {
- [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
-}[keyof T]
-
-type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
-type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
-
-type Writable<T> = Pick<T, WritableKeys<T>>
-type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
- ? {
- [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
- }
- : DistributeReadOnlyOverUnions<T>
-
export const getCodeInvitesCheckAccessRetrieveUrl = () => {
return `/api/code/invites/check-access/`
}
@@ -135,8 +121,8 @@ export const sandboxList = async (
projectId: string,
params?: SandboxListParams,
options?: RequestInit
-): Promise<PaginatedSandboxEnvironmentListListApi> => {
- return apiMutator<PaginatedSandboxEnvironmentListListApi>(getSandboxListUrl(projectId, params), {
+): Promise<PaginatedSandboxEnvironmentDTOListApi> => {
+ return apiMutator<PaginatedSandboxEnvironmentDTOListApi>(getSandboxListUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -151,14 +137,14 @@ export const getSandboxCreateUrl = (projectId: string) => {
*/
export const sandboxCreate = async (
projectId: string,
- sandboxEnvironmentApi: NonReadonly<SandboxEnvironmentApi>,
+ sandboxEnvironmentWriteApi: SandboxEnvironmentWriteApi,
options?: RequestInit
-): Promise<SandboxEnvironmentApi> => {
- return apiMutator<SandboxEnvironmentApi>(getSandboxCreateUrl(projectId), {
+): Promise<SandboxEnvironmentDTOApi> => {
+ return apiMutator<SandboxEnvironmentDTOApi>(getSandboxCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(sandboxEnvironmentApi),
+ body: JSON.stringify(sandboxEnvironmentWriteApi),
})
}
@@ -173,8 +159,8 @@ export const sandboxRetrieve = async (
projectId: string,
id: string,
options?: RequestInit
-): Promise<SandboxEnvironmentApi> => {
- return apiMutator<SandboxEnvironmentApi>(getSandboxRetrieveUrl(projectId, id), {
+): Promise<SandboxEnvironmentDTOApi> => {
+ return apiMutator<SandboxEnvironmentDTOApi>(getSandboxRetrieveUrl(projectId, id), {
...options,
method: 'GET',
})
@@ -190,14 +176,14 @@ export const getSandboxPartialUpdateUrl = (projectId: string, id: string) => {
export const sandboxPartialUpdate = async (
projectId: string,
id: string,
- patchedSandboxEnvironmentApi?: NonReadonly<PatchedSandboxEnvironmentApi>,
+ patchedSandboxEnvironmentWriteApi?: PatchedSandboxEnvironmentWriteApi,
options?: RequestInit
-): Promise<SandboxEnvironmentApi> => {
- return apiMutator<SandboxEnvironmentApi>(getSandboxPartialUpdateUrl(projectId, id), {
+): Promise<SandboxEnvironmentDTOApi> => {
+ return apiMutator<SandboxEnvironmentDTOApi>(getSandboxPartialUpdateUrl(projectId, id), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedSandboxEnvironmentApi),
+ body: JSON.stringify(patchedSandboxEnvironmentWriteApi),
})
}
@@ -231,12 +217,15 @@ export const getTaskAutomationsListUrl = (projectId: string, params?: TaskAutoma
: `/api/projects/${projectId}/task_automations/`
}
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsList = async (
projectId: string,
params?: TaskAutomationsListParams,
options?: RequestInit
-): Promise<PaginatedTaskAutomationListApi> => {
- return apiMutator<PaginatedTaskAutomationListApi>(getTaskAutomationsListUrl(projectId, params), {
+): Promise<PaginatedTaskAutomationDTOListApi> => {
+ return apiMutator<PaginatedTaskAutomationDTOListApi>(getTaskAutomationsListUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -246,16 +235,19 @@ export const getTaskAutomationsCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/task_automations/`
}
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsCreate = async (
projectId: string,
- taskAutomationApi: NonReadonly<TaskAutomationApi>,
+ taskAutomationWriteApi: TaskAutomationWriteApi,
options?: RequestInit
-): Promise<TaskAutomationApi> => {
- return apiMutator<TaskAutomationApi>(getTaskAutomationsCreateUrl(projectId), {
+): Promise<TaskAutomationDTOApi> => {
+ return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taskAutomationApi),
+ body: JSON.stringify(taskAutomationWriteApi),
})
}
@@ -263,50 +255,38 @@ export const getTaskAutomationsRetrieveUrl = (projectId: string, id: string) =>
return `/api/projects/${projectId}/task_automations/${id}/`
}
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsRetrieve = async (
projectId: string,
id: string,
options?: RequestInit
-): Promise<TaskAutomationApi> => {
- return apiMutator<TaskAutomationApi>(getTaskAutomationsRetrieveUrl(projectId, id), {
+): Promise<TaskAutomationDTOApi> => {
+ return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsRetrieveUrl(projectId, id), {
...options,
method: 'GET',
})
}
-export const getTaskAutomationsUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/task_automations/${id}/`
-}
-
-export const taskAutomationsUpdate = async (
- projectId: string,
- id: string,
- taskAutomationApi: NonReadonly<TaskAutomationApi>,
- options?: RequestInit
-): Promise<TaskAutomationApi> => {
- return apiMutator<TaskAutomationApi>(getTaskAutomationsUpdateUrl(projectId, id), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taskAutomationApi),
- })
-}
-
export const getTaskAutomationsPartialUpdateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/task_automations/${id}/`
}
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsPartialUpdate = async (
projectId: string,
id: string,
- patchedTaskAutomationApi?: NonReadonly<PatchedTaskAutomationApi>,
+ patchedTaskAutomationWriteApi?: PatchedTaskAutomationWriteApi,
options?: RequestInit
-): Promise<TaskAutomationApi> => {
- return apiMutator<TaskAutomationApi>(getTaskAutomationsPartialUpdateUrl(projectId, id), {
+): Promise<TaskAutomationDTOApi> => {
+ return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsPartialUpdateUrl(projectId, id), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedTaskAutomationApi),
+ body: JSON.stringify(patchedTaskAutomationWriteApi),
})
}
@@ -314,6 +294,9 @@ export const getTaskAutomationsDestroyUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/task_automations/${id}/`
}
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
return apiMutator<void>(getTaskAutomationsDestroyUrl(projectId, id), {
...options,
@@ -325,17 +308,17 @@ export const getTaskAutomationsRunCreateUrl = (projectId: string, id: string) =>
return `/api/projects/${projectId}/task_automations/${id}/run/`
}
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsRunCreate = async (
projectId: string,
id: string,
- taskAutomationApi: NonReadonly<TaskAutomationApi>,
options?: RequestInit
-): Promise<TaskAutomationApi> => {
- return apiMutator<TaskAutomationApi>(getTaskAutomationsRunCreateUrl(projectId, id), {
+): Promise<TaskAutomationDTOApi> => {
+ return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsRunCreateUrl(projectId, id), {
...options,
method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taskAutomationApi),
})
}
@@ -363,8 +346,8 @@ export const tasksList = async (
projectId: string,
params?: TasksListParams,
options?: RequestInit
-): Promise<PaginatedTaskListApi> => {
- return apiMutator<PaginatedTaskListApi>(getTasksListUrl(projectId, params), {
+): Promise<PaginatedTaskDetailDTOListApi> => {
+ return apiMutator<PaginatedTaskDetailDTOListApi>(getTasksListUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -379,14 +362,14 @@ export const getTasksCreateUrl = (projectId: string) => {
*/
export const tasksCreate = async (
projectId: string,
- taskApi?: NonReadonly<TaskApi>,
+ taskWriteApi?: TaskWriteApi,
options?: RequestInit
-): Promise<TaskApi> => {
- return apiMutator<TaskApi>(getTasksCreateUrl(projectId), {
+): Promise<TaskDetailDTOApi> => {
+ return apiMutator<TaskDetailDTOApi>(getTasksCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taskApi),
+ body: JSON.stringify(taskWriteApi),
})
}
@@ -395,10 +378,15 @@ export const getTasksRetrieveUrl = (projectId: string, id: string) => {
}
/**
- * API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
+ * Retrieve a single task by ID.
+ * @summary Get task
*/
-export const tasksRetrieve = async (projectId: string, id: string, options?: RequestInit): Promise<TaskApi> => {
- return apiMutator<TaskApi>(getTasksRetrieveUrl(projectId, id), {
+export const tasksRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<TaskDetailDTOApi> => {
+ return apiMutator<TaskDetailDTOApi>(getTasksRetrieveUrl(projectId, id), {
...options,
method: 'GET',
})
@@ -414,14 +402,14 @@ export const getTasksUpdateUrl = (projectId: string, id: string) => {
export const tasksUpdate = async (
projectId: string,
id: string,
- taskApi?: NonReadonly<TaskApi>,
+ taskWriteApi?: TaskWriteApi,
options?: RequestInit
-): Promise<TaskApi> => {
- return apiMutator<TaskApi>(getTasksUpdateUrl(projectId, id), {
+): Promise<TaskDetailDTOApi> => {
+ return apiMutator<TaskDetailDTOApi>(getTasksUpdateUrl(projectId, id), {
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taskApi),
+ body: JSON.stringify(taskWriteApi),
})
}
@@ -435,14 +423,14 @@ export const getTasksPartialUpdateUrl = (projectId: string, id: string) => {
export const tasksPartialUpdate = async (
projectId: string,
id: string,
- patchedTaskApi?: NonReadonly<PatchedTaskApi>,
+ patchedTaskWriteApi?: PatchedTaskWriteApi,
options?: RequestInit
-): Promise<TaskApi> => {
- return apiMutator<TaskApi>(getTasksPartialUpdateUrl(projectId, id), {
+): Promise<TaskDetailDTOApi> => {
+ return apiMutator<TaskDetailDTOApi>(getTasksPartialUpdateUrl(projectId, id), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedTaskApi),
+ body: JSON.stringify(patchedTaskWriteApi),
})
}
@@ -510,8 +498,8 @@ export const tasksRunCreate = async (
id: string,
taskRunCreateRequestSchemaApi?: TaskRunCreateRequestSchemaApi,
options?: RequestInit
-): Promise<TaskApi> => {
- return apiMutator<TaskApi>(getTasksRunCreateUrl(projectId, id), {
+): Promise<TaskDetailDTOApi> => {
+ return apiMutator<TaskDetailDTOApi>(getTasksRunCreateUrl(projectId, id), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -594,8 +582,8 @@ export const tasksRunsList = async (
taskId: string,
params?: TasksRunsListParams,
options?: RequestInit
-): Promise<PaginatedTaskRunDetailListApi> => {
- return apiMutator<PaginatedTaskRunDetailListApi>(getTasksRunsListUrl(projectId, taskId, params), {
+): Promise<PaginatedTaskRunDetailDTOListApi> => {
+ return apiMutator<PaginatedTaskRunDetailDTOListApi>(getTasksRunsListUrl(projectId, taskId, params), {
...options,
method: 'GET',
})
@@ -614,8 +602,8 @@ export const tasksRunsCreate = async (
taskId: string,
taskRunBootstrapCreateRequestApi?: TaskRunBootstrapCreateRequestApi,
options?: RequestInit
-): Promise<TaskRunDetailApi> => {
- return apiMutator<TaskRunDetailApi>(getTasksRunsCreateUrl(projectId, taskId), {
+): Promise<TaskRunDetailDTOApi> => {
+ return apiMutator<TaskRunDetailDTOApi>(getTasksRunsCreateUrl(projectId, taskId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -628,15 +616,16 @@ export const getTasksRunsRetrieveUrl = (projectId: string, taskId: string, id: s
}
/**
- * API for managing task runs. Each run represents an execution of a task.
+ * Retrieve a single run for a specific task.
+ * @summary Get task run
*/
export const tasksRunsRetrieve = async (
projectId: string,
taskId: string,
id: string,
options?: RequestInit
-): Promise<TaskRunDetailApi> => {
- return apiMutator<TaskRunDetailApi>(getTasksRunsRetrieveUrl(projectId, taskId, id), {
+): Promise<TaskRunDetailDTOApi> => {
+ return apiMutator<TaskRunDetailDTOApi>(getTasksRunsRetrieveUrl(projectId, taskId, id), {
...options,
method: 'GET',
})
@@ -656,8 +645,8 @@ export const tasksRunsPartialUpdate = async (
id: string,
patchedTaskRunUpdateApi?: PatchedTaskRunUpdateApi,
options?: RequestInit
-): Promise<TaskRunDetailApi> => {
- return apiMutator<TaskRunDetailApi>(getTasksRunsPartialUpdateUrl(projectId, taskId, id), {
+): Promise<TaskRunDetailDTOApi> => {
+ return apiMutator<TaskRunDetailDTOApi>(getTasksRunsPartialUpdateUrl(projectId, taskId, id), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -679,8 +668,8 @@ export const tasksRunsAppendLogCreate = async (
id: string,
taskRunAppendLogRequestApi: TaskRunAppendLogRequestApi,
options?: RequestInit
-): Promise<TaskRunDetailApi> => {
- return apiMutator<TaskRunDetailApi>(getTasksRunsAppendLogCreateUrl(projectId, taskId, id), {
+): Promise<TaskRunDetailDTOApi> => {
+ return apiMutator<TaskRunDetailDTOApi>(getTasksRunsAppendLogCreateUrl(projectId, taskId, id), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -888,8 +877,8 @@ export const tasksRunsResumeInCloudCreate = async (
taskId: string,
id: string,
options?: RequestInit
-): Promise<TaskRunDetailApi> => {
- return apiMutator<TaskRunDetailApi>(getTasksRunsResumeInCloudCreateUrl(projectId, taskId, id), {
+): Promise<TaskRunDetailDTOApi> => {
+ return apiMutator<TaskRunDetailDTOApi>(getTasksRunsResumeInCloudCreateUrl(projectId, taskId, id), {
...options,
method: 'POST',
})
@@ -947,8 +936,8 @@ export const tasksRunsSetOutputPartialUpdate = async (
id: string,
patchedTaskRunSetOutputRequestApi?: PatchedTaskRunSetOutputRequestApi,
options?: RequestInit
-): Promise<TaskRunDetailApi> => {
- return apiMutator<TaskRunDetailApi>(getTasksRunsSetOutputPartialUpdateUrl(projectId, taskId, id), {
+): Promise<TaskRunDetailDTOApi> => {
+ return apiMutator<TaskRunDetailDTOApi>(getTasksRunsSetOutputPartialUpdateUrl(projectId, taskId, id), {
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -970,8 +959,8 @@ export const tasksRunsStartCreate = async (
id: string,
taskRunStartRequestApi?: TaskRunStartRequestApi,
options?: RequestInit
-): Promise<TaskApi> => {
- return apiMutator<TaskApi>(getTasksRunsStartCreateUrl(projectId, taskId, id), {
+): Promise<TaskDetailDTOApi> => {
+ return apiMutator<TaskDetailDTOApi>(getTasksRunsStartCreateUrl(projectId, taskId, id), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -991,8 +980,8 @@ export const tasksRunsStreamRetrieve = async (
taskId: string,
id: string,
options?: RequestInit
-): Promise<TaskRunDetailApi> => {
- return apiMutator<TaskRunDetailApi>(getTasksRunsStreamRetrieveUrl(projectId, taskId, id), {
+): Promise<TaskRunDetailDTOApi> => {
+ return apiMutator<TaskRunDetailDTOApi>(getTasksRunsStreamRetrieveUrl(projectId, taskId, id), {
...options,
method: 'GET',
})
@@ -1109,8 +1098,8 @@ export const tasksSummariesCreate = async (
taskSummariesRequestApi: TaskSummariesRequestApi,
params?: TasksSummariesCreateParams,
options?: RequestInit
-): Promise<PaginatedTaskSummaryListApi> => {
- return apiMutator<PaginatedTaskSummaryListApi>(getTasksSummariesCreateUrl(projectId, params), {
+): Promise<PaginatedTaskSummaryDTOListApi> => {
+ return apiMutator<PaginatedTaskSummaryDTOListApi>(getTasksSummariesCreateUrl(projectId, params), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index d6c3082caeea..0bbe12673f7b 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -24,158 +24,203 @@ export const CodeInvitesRedeemCreateBody = /* @__PURE__ */ zod.object({
*/
export const sandboxCreateBodyNameMax = 255
+export const sandboxCreateBodyNetworkAccessLevelDefault = `full`
export const sandboxCreateBodyAllowedDomainsItemMax = 255
+export const sandboxCreateBodyIncludeDefaultDomainsDefault = false
export const sandboxCreateBodyRepositoriesItemMax = 255
-export const SandboxCreateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(sandboxCreateBodyNameMax),
- network_access_level: zod
- .enum(['trusted', 'full', 'custom'])
- .optional()
- .describe('\* `trusted` - Trusted\n\* `full` - Full\n\* `custom` - Custom'),
- allowed_domains: zod
- .array(zod.string().max(sandboxCreateBodyAllowedDomainsItemMax))
- .optional()
- .describe('List of allowed domains for custom network access'),
- include_default_domains: zod
- .boolean()
- .optional()
- .describe('Whether to include default trusted domains (GitHub, npm, PyPI)'),
- repositories: zod
- .array(zod.string().max(sandboxCreateBodyRepositoriesItemMax))
- .optional()
- .describe('List of repositories this environment applies to (format: org\/repo)'),
- environment_variables: zod
- .unknown()
- .optional()
- .describe('Encrypted environment variables (write-only, never returned in responses)'),
- private: zod
- .boolean()
- .optional()
- .describe('If true, only the creator can see this environment. Otherwise visible to whole team.'),
-})
+export const sandboxCreateBodyPrivateDefault = true
+
+export const SandboxCreateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod.string().max(sandboxCreateBodyNameMax).describe('Display name for the environment.'),
+ network_access_level: zod
+ .enum(['trusted', 'full', 'custom'])
+ .describe('\* `trusted` - Trusted\n\* `full` - Full\n\* `custom` - Custom')
+ .default(sandboxCreateBodyNetworkAccessLevelDefault)
+ .describe(
+ 'Network access policy: trusted (default allowlist), full (unrestricted), or custom.\n\n\* `trusted` - Trusted\n\* `full` - Full\n\* `custom` - Custom'
+ ),
+ allowed_domains: zod
+ .array(zod.string().max(sandboxCreateBodyAllowedDomainsItemMax))
+ .optional()
+ .describe('Allowed domains for custom network access.'),
+ include_default_domains: zod
+ .boolean()
+ .default(sandboxCreateBodyIncludeDefaultDomainsDefault)
+ .describe('Whether to include default trusted domains (GitHub, npm, PyPI).'),
+ repositories: zod
+ .array(zod.string().max(sandboxCreateBodyRepositoriesItemMax))
+ .optional()
+ .describe('Repositories this environment applies to (format: org\/repo).'),
+ environment_variables: zod
+ .unknown()
+ .optional()
+ .describe('Encrypted environment variables (write-only, never returned in responses).'),
+ private: zod
+ .boolean()
+ .default(sandboxCreateBodyPrivateDefault)
+ .describe('If true, only the creator can see this environment; otherwise the whole team can.'),
+ })
+ .describe('Request body for creating or updating a sandbox environment.')
/**
* API for managing sandbox environments that control network access for task runs.
*/
export const sandboxPartialUpdateBodyNameMax = 255
+export const sandboxPartialUpdateBodyNetworkAccessLevelDefault = `full`
export const sandboxPartialUpdateBodyAllowedDomainsItemMax = 255
+export const sandboxPartialUpdateBodyIncludeDefaultDomainsDefault = false
export const sandboxPartialUpdateBodyRepositoriesItemMax = 255
-export const SandboxPartialUpdateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(sandboxPartialUpdateBodyNameMax).optional(),
- network_access_level: zod
- .enum(['trusted', 'full', 'custom'])
- .optional()
- .describe('\* `trusted` - Trusted\n\* `full` - Full\n\* `custom` - Custom'),
- allowed_domains: zod
- .array(zod.string().max(sandboxPartialUpdateBodyAllowedDomainsItemMax))
- .optional()
- .describe('List of allowed domains for custom network access'),
- include_default_domains: zod
- .boolean()
- .optional()
- .describe('Whether to include default trusted domains (GitHub, npm, PyPI)'),
- repositories: zod
- .array(zod.string().max(sandboxPartialUpdateBodyRepositoriesItemMax))
- .optional()
- .describe('List of repositories this environment applies to (format: org\/repo)'),
- environment_variables: zod
- .unknown()
- .optional()
- .describe('Encrypted environment variables (write-only, never returned in responses)'),
- private: zod
- .boolean()
- .optional()
- .describe('If true, only the creator can see this environment. Otherwise visible to whole team.'),
-})
+export const sandboxPartialUpdateBodyPrivateDefault = true
+export const SandboxPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(sandboxPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Display name for the environment.'),
+ network_access_level: zod
+ .enum(['trusted', 'full', 'custom'])
+ .describe('\* `trusted` - Trusted\n\* `full` - Full\n\* `custom` - Custom')
+ .default(sandboxPartialUpdateBodyNetworkAccessLevelDefault)
+ .describe(
+ 'Network access policy: trusted (default allowlist), full (unrestricted), or custom.\n\n\* `trusted` - Trusted\n\* `full` - Full\n\* `custom` - Custom'
+ ),
+ allowed_domains: zod
+ .array(zod.string().max(sandboxPartialUpdateBodyAllowedDomainsItemMax))
+ .optional()
+ .describe('Allowed domains for custom network access.'),
+ include_default_domains: zod
+ .boolean()
+ .default(sandboxPartialUpdateBodyIncludeDefaultDomainsDefault)
+ .describe('Whether to include default trusted domains (GitHub, npm, PyPI).'),
+ repositories: zod
+ .array(zod.string().max(sandboxPartialUpdateBodyRepositoriesItemMax))
+ .optional()
+ .describe('Repositories this environment applies to (format: org\/repo).'),
+ environment_variables: zod
+ .unknown()
+ .optional()
+ .describe('Encrypted environment variables (write-only, never returned in responses).'),
+ private: zod
+ .boolean()
+ .default(sandboxPartialUpdateBodyPrivateDefault)
+ .describe('If true, only the creator can see this environment; otherwise the whole team can.'),
+ })
+ .describe('Request body for creating or updating a sandbox environment.')
+
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsCreateBodyNameMax = 255
export const taskAutomationsCreateBodyRepositoryMax = 255
export const taskAutomationsCreateBodyCronExpressionMax = 100
+export const taskAutomationsCreateBodyTimezoneDefault = `UTC`
export const taskAutomationsCreateBodyTimezoneMax = 128
export const taskAutomationsCreateBodyTemplateIdMax = 255
-export const TaskAutomationsCreateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(taskAutomationsCreateBodyNameMax),
- prompt: zod.string(),
- repository: zod.string().max(taskAutomationsCreateBodyRepositoryMax),
- github_integration: zod.number().nullish(),
- cron_expression: zod.string().max(taskAutomationsCreateBodyCronExpressionMax),
- timezone: zod.string().max(taskAutomationsCreateBodyTimezoneMax).optional(),
- template_id: zod.string().max(taskAutomationsCreateBodyTemplateIdMax).nullish(),
- enabled: zod.boolean().optional(),
-})
-
-export const taskAutomationsUpdateBodyNameMax = 255
-
-export const taskAutomationsUpdateBodyRepositoryMax = 255
-
-export const taskAutomationsUpdateBodyCronExpressionMax = 100
-
-export const taskAutomationsUpdateBodyTimezoneMax = 128
-
-export const taskAutomationsUpdateBodyTemplateIdMax = 255
+export const taskAutomationsCreateBodyEnabledDefault = true
-export const TaskAutomationsUpdateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(taskAutomationsUpdateBodyNameMax),
- prompt: zod.string(),
- repository: zod.string().max(taskAutomationsUpdateBodyRepositoryMax),
- github_integration: zod.number().nullish(),
- cron_expression: zod.string().max(taskAutomationsUpdateBodyCronExpressionMax),
- timezone: zod.string().max(taskAutomationsUpdateBodyTimezoneMax).optional(),
- template_id: zod.string().max(taskAutomationsUpdateBodyTemplateIdMax).nullish(),
- enabled: zod.boolean().optional(),
-})
+export const TaskAutomationsCreateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(taskAutomationsCreateBodyNameMax)
+ .describe("Display name (stored as the backing task's title)."),
+ prompt: zod.string().describe("The automation prompt (stored as the backing task's description)."),
+ repository: zod
+ .string()
+ .max(taskAutomationsCreateBodyRepositoryMax)
+ .describe('Target repository in the format organization\/repository.'),
+ github_integration: zod
+ .number()
+ .nullish()
+ .describe("GitHub integration to run as. Defaults to the team's GitHub integration when omitted."),
+ cron_expression: zod
+ .string()
+ .max(taskAutomationsCreateBodyCronExpressionMax)
+ .describe('Standard 5-field cron expression (minute hour day month weekday).'),
+ timezone: zod
+ .string()
+ .max(taskAutomationsCreateBodyTimezoneMax)
+ .default(taskAutomationsCreateBodyTimezoneDefault)
+ .describe('IANA timezone the schedule runs in.'),
+ template_id: zod
+ .string()
+ .max(taskAutomationsCreateBodyTemplateIdMax)
+ .nullish()
+ .describe('Optional template identifier this automation was created from.'),
+ enabled: zod
+ .boolean()
+ .default(taskAutomationsCreateBodyEnabledDefault)
+ .describe('Whether the schedule is active; paused when false.'),
+ })
+ .describe('Request body for creating or updating a task automation.')
+/**
+ * API for managing scheduled task automations.
+ */
export const taskAutomationsPartialUpdateBodyNameMax = 255
export const taskAutomationsPartialUpdateBodyRepositoryMax = 255
export const taskAutomationsPartialUpdateBodyCronExpressionMax = 100
+export const taskAutomationsPartialUpdateBodyTimezoneDefault = `UTC`
export const taskAutomationsPartialUpdateBodyTimezoneMax = 128
export const taskAutomationsPartialUpdateBodyTemplateIdMax = 255
-export const TaskAutomationsPartialUpdateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(taskAutomationsPartialUpdateBodyNameMax).optional(),
- prompt: zod.string().optional(),
- repository: zod.string().max(taskAutomationsPartialUpdateBodyRepositoryMax).optional(),
- github_integration: zod.number().nullish(),
- cron_expression: zod.string().max(taskAutomationsPartialUpdateBodyCronExpressionMax).optional(),
- timezone: zod.string().max(taskAutomationsPartialUpdateBodyTimezoneMax).optional(),
- template_id: zod.string().max(taskAutomationsPartialUpdateBodyTemplateIdMax).nullish(),
- enabled: zod.boolean().optional(),
-})
-
-export const taskAutomationsRunCreateBodyNameMax = 255
-
-export const taskAutomationsRunCreateBodyRepositoryMax = 255
-
-export const taskAutomationsRunCreateBodyCronExpressionMax = 100
-
-export const taskAutomationsRunCreateBodyTimezoneMax = 128
+export const taskAutomationsPartialUpdateBodyEnabledDefault = true
-export const taskAutomationsRunCreateBodyTemplateIdMax = 255
-
-export const TaskAutomationsRunCreateBody = /* @__PURE__ */ zod.object({
- name: zod.string().max(taskAutomationsRunCreateBodyNameMax),
- prompt: zod.string(),
- repository: zod.string().max(taskAutomationsRunCreateBodyRepositoryMax),
- github_integration: zod.number().nullish(),
- cron_expression: zod.string().max(taskAutomationsRunCreateBodyCronExpressionMax),
- timezone: zod.string().max(taskAutomationsRunCreateBodyTimezoneMax).optional(),
- template_id: zod.string().max(taskAutomationsRunCreateBodyTemplateIdMax).nullish(),
- enabled: zod.boolean().optional(),
-})
+export const TaskAutomationsPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ name: zod
+ .string()
+ .max(taskAutomationsPartialUpdateBodyNameMax)
+ .optional()
+ .describe("Display name (stored as the backing task's title)."),
+ prompt: zod.string().optional().describe("The automation prompt (stored as the backing task's description)."),
+ repository: zod
+ .string()
+ .max(taskAutomationsPartialUpdateBodyRepositoryMax)
+ .optional()
+ .describe('Target repository in the format organization\/repository.'),
+ github_integration: zod
+ .number()
+ .nullish()
+ .describe("GitHub integration to run as. Defaults to the team's GitHub integration when omitted."),
+ cron_expression: zod
+ .string()
+ .max(taskAutomationsPartialUpdateBodyCronExpressionMax)
+ .optional()
+ .describe('Standard 5-field cron expression (minute hour day month weekday).'),
+ timezone: zod
+ .string()
+ .max(taskAutomationsPartialUpdateBodyTimezoneMax)
+ .default(taskAutomationsPartialUpdateBodyTimezoneDefault)
+ .describe('IANA timezone the schedule runs in.'),
+ template_id: zod
+ .string()
+ .max(taskAutomationsPartialUpdateBodyTemplateIdMax)
+ .nullish()
+ .describe('Optional template identifier this automation was created from.'),
+ enabled: zod
+ .boolean()
+ .default(taskAutomationsPartialUpdateBodyEnabledDefault)
+ .describe('Whether the schedule is active; paused when false.'),
+ })
+ .describe('Request body for creating or updating a task automation.')
/**
* API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
@@ -184,68 +229,70 @@ export const tasksCreateBodyTitleMax = 255
export const tasksCreateBodyRepositoryMax = 255
-export const TasksCreateBody = /* @__PURE__ */ zod.object({
- title: zod
- .string()
- .max(tasksCreateBodyTitleMax)
- .optional()
- .describe('Short human-readable title. Auto-generated from `description` when omitted.'),
- title_manually_set: zod.boolean().optional(),
- description: zod
- .string()
- .optional()
- .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
- origin_product: zod
- .enum([
- 'error_tracking',
- 'eval_clusters',
- 'user_created',
- 'automation',
- 'slack',
- 'support_queue',
- 'session_summaries',
- 'signal_report',
- 'signals_scout',
- 'support_reply',
- ])
- .describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
- )
- .optional()
- .describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
- ),
- repository: zod
- .string()
- .max(tasksCreateBodyRepositoryMax)
- .nullish()
- .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),
- github_integration: zod.number().nullish().describe('GitHub integration for this task'),
- github_user_integration: zod
- .uuid()
- .nullish()
- .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),
- signal_report: zod.uuid().nullish(),
- signal_report_task_relationship: zod
- .enum(['implementation'])
- .describe('\* `implementation` - Implementation')
- .optional(),
- json_schema: zod
- .unknown()
- .optional()
- .describe('JSON schema for the task. This is used to validate the output of the task.'),
- internal: zod
- .boolean()
- .optional()
- .describe('If true, this task is for internal use and should not be exposed to end users.'),
- archived: zod
- .boolean()
- .optional()
- .describe(
- 'If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile.'
- ),
- ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
-})
+export const TasksCreateBody = /* @__PURE__ */ zod
+ .object({
+ title: zod
+ .string()
+ .max(tasksCreateBodyTitleMax)
+ .optional()
+ .describe('Short human-readable title. Auto-generated from `description` when omitted.'),
+ title_manually_set: zod
+ .boolean()
+ .optional()
+ .describe('Whether the title was set by a human (vs auto-generated from the description).'),
+ description: zod
+ .string()
+ .optional()
+ .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
+ origin_product: zod
+ .enum([
+ 'error_tracking',
+ 'eval_clusters',
+ 'user_created',
+ 'automation',
+ 'slack',
+ 'support_queue',
+ 'session_summaries',
+ 'signal_report',
+ 'signals_scout',
+ 'support_reply',
+ ])
+ .describe(
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ )
+ .optional()
+ .describe(
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ ),
+ repository: zod
+ .string()
+ .max(tasksCreateBodyRepositoryMax)
+ .nullish()
+ .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),
+ github_integration: zod.number().nullish().describe('GitHub integration for this task.'),
+ github_user_integration: zod
+ .uuid()
+ .nullish()
+ .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),
+ signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),
+ signal_report_task_relationship: zod
+ .enum(['implementation'])
+ .describe('\* `implementation` - Implementation')
+ .optional(),
+ json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),
+ internal: zod
+ .boolean()
+ .optional()
+ .describe('If true, this task is for internal use and should not be exposed to end users.'),
+ archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),
+ ci_prompt: zod
+ .string()
+ .nullish()
+ .describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
+ })
+ .describe(
+ 'Request body for creating or updating a task.\n\nField required\/default semantics match the ``Task`` model. The view passes\n``validated_data`` (integration\/report PK fields already resolved to instances) to the\nfacade ``create_task`` \/ ``update_task`` functions.'
+ )
/**
* API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
@@ -254,68 +301,70 @@ export const tasksUpdateBodyTitleMax = 255
export const tasksUpdateBodyRepositoryMax = 255
-export const TasksUpdateBody = /* @__PURE__ */ zod.object({
- title: zod
- .string()
- .max(tasksUpdateBodyTitleMax)
- .optional()
- .describe('Short human-readable title. Auto-generated from `description` when omitted.'),
- title_manually_set: zod.boolean().optional(),
- description: zod
- .string()
- .optional()
- .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
- origin_product: zod
- .enum([
- 'error_tracking',
- 'eval_clusters',
- 'user_created',
- 'automation',
- 'slack',
- 'support_queue',
- 'session_summaries',
- 'signal_report',
- 'signals_scout',
- 'support_reply',
- ])
- .describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
- )
- .optional()
- .describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
- ),
- repository: zod
- .string()
- .max(tasksUpdateBodyRepositoryMax)
- .nullish()
- .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),
- github_integration: zod.number().nullish().describe('GitHub integration for this task'),
- github_user_integration: zod
- .uuid()
- .nullish()
- .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),
- signal_report: zod.uuid().nullish(),
- signal_report_task_relationship: zod
- .enum(['implementation'])
- .describe('\* `implementation` - Implementation')
- .optional(),
- json_schema: zod
- .unknown()
- .optional()
- .describe('JSON schema for the task. This is used to validate the output of the task.'),
- internal: zod
- .boolean()
- .optional()
- .describe('If true, this task is for internal use and should not be exposed to end users.'),
- archived: zod
- .boolean()
- .optional()
- .describe(
- 'If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile.'
- ),
- ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
-})
+export const TasksUpdateBody = /* @__PURE__ */ zod
+ .object({
+ title: zod
+ .string()
+ .max(tasksUpdateBodyTitleMax)
+ .optional()
+ .describe('Short human-readable title. Auto-generated from `description` when omitted.'),
+ title_manually_set: zod
+ .boolean()
+ .optional()
+ .describe('Whether the title was set by a human (vs auto-generated from the description).'),
+ description: zod
+ .string()
+ .optional()
+ .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
+ origin_product: zod
+ .enum([
+ 'error_tracking',
+ 'eval_clusters',
+ 'user_created',
+ 'automation',
+ 'slack',
+ 'support_queue',
+ 'session_summaries',
+ 'signal_report',
+ 'signals_scout',
+ 'support_reply',
+ ])
+ .describe(
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ )
+ .optional()
+ .describe(
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ ),
+ repository: zod
+ .string()
+ .max(tasksUpdateBodyRepositoryMax)
+ .nullish()
+ .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),
+ github_integration: zod.number().nullish().describe('GitHub integration for this task.'),
+ github_user_integration: zod
+ .uuid()
+ .nullish()
+ .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),
+ signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),
+ signal_report_task_relationship: zod
+ .enum(['implementation'])
+ .describe('\* `implementation` - Implementation')
+ .optional(),
+ json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),
+ internal: zod
+ .boolean()
+ .optional()
+ .describe('If true, this task is for internal use and should not be exposed to end users.'),
+ archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),
+ ci_prompt: zod
+ .string()
+ .nullish()
+ .describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
+ })
+ .describe(
+ 'Request body for creating or updating a task.\n\nField required\/default semantics match the ``Task`` model. The view passes\n``validated_data`` (integration\/report PK fields already resolved to instances) to the\nfacade ``create_task`` \/ ``update_task`` functions.'
+ )
/**
* API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
@@ -324,68 +373,70 @@ export const tasksPartialUpdateBodyTitleMax = 255
export const tasksPartialUpdateBodyRepositoryMax = 255
-export const TasksPartialUpdateBody = /* @__PURE__ */ zod.object({
- title: zod
- .string()
- .max(tasksPartialUpdateBodyTitleMax)
- .optional()
- .describe('Short human-readable title. Auto-generated from `description` when omitted.'),
- title_manually_set: zod.boolean().optional(),
- description: zod
- .string()
- .optional()
- .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
- origin_product: zod
- .enum([
- 'error_tracking',
- 'eval_clusters',
- 'user_created',
- 'automation',
- 'slack',
- 'support_queue',
- 'session_summaries',
- 'signal_report',
- 'signals_scout',
- 'support_reply',
- ])
- .describe(
- '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
- )
- .optional()
- .describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
- ),
- repository: zod
- .string()
- .max(tasksPartialUpdateBodyRepositoryMax)
- .nullish()
- .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),
- github_integration: zod.number().nullish().describe('GitHub integration for this task'),
- github_user_integration: zod
- .uuid()
- .nullish()
- .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),
- signal_report: zod.uuid().nullish(),
- signal_report_task_relationship: zod
- .enum(['implementation'])
- .describe('\* `implementation` - Implementation')
- .optional(),
- json_schema: zod
- .unknown()
- .optional()
- .describe('JSON schema for the task. This is used to validate the output of the task.'),
- internal: zod
- .boolean()
- .optional()
- .describe('If true, this task is for internal use and should not be exposed to end users.'),
- archived: zod
- .boolean()
- .optional()
- .describe(
- 'If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile.'
- ),
- ci_prompt: zod.string().nullish().describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
-})
+export const TasksPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ title: zod
+ .string()
+ .max(tasksPartialUpdateBodyTitleMax)
+ .optional()
+ .describe('Short human-readable title. Auto-generated from `description` when omitted.'),
+ title_manually_set: zod
+ .boolean()
+ .optional()
+ .describe('Whether the title was set by a human (vs auto-generated from the description).'),
+ description: zod
+ .string()
+ .optional()
+ .describe('Free-form description of the work to be done. Used as the prompt passed to the agent.'),
+ origin_product: zod
+ .enum([
+ 'error_tracking',
+ 'eval_clusters',
+ 'user_created',
+ 'automation',
+ 'slack',
+ 'support_queue',
+ 'session_summaries',
+ 'signal_report',
+ 'signals_scout',
+ 'support_reply',
+ ])
+ .describe(
+ '\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ )
+ .optional()
+ .describe(
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).\n\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply'
+ ),
+ repository: zod
+ .string()
+ .max(tasksPartialUpdateBodyRepositoryMax)
+ .nullish()
+ .describe('Target GitHub repository in `organization\/repo` format (e.g. `posthog\/posthog-js`).'),
+ github_integration: zod.number().nullish().describe('GitHub integration for this task.'),
+ github_user_integration: zod
+ .uuid()
+ .nullish()
+ .describe('User-scoped GitHub integration to use for user-authored cloud runs.'),
+ signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),
+ signal_report_task_relationship: zod
+ .enum(['implementation'])
+ .describe('\* `implementation` - Implementation')
+ .optional(),
+ json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),
+ internal: zod
+ .boolean()
+ .optional()
+ .describe('If true, this task is for internal use and should not be exposed to end users.'),
+ archived: zod.boolean().optional().describe('If true, the task is hidden from default list responses.'),
+ ci_prompt: zod
+ .string()
+ .nullish()
+ .describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
+ })
+ .describe(
+ 'Request body for creating or updating a task.\n\nField required\/default semantics match the ``Task`` model. The view passes\n``validated_data`` (integration\/report PK fields already resolved to instances) to the\nfacade ``create_task`` \/ ``update_task`` functions.'
+ )
/**
* Idempotent upsert: marks the calling user + `device_id` as actively watching this task for the next ~60 seconds. While at least one device for the user has a non-expired presence row for this task, the push fanout will skip ALL of that user's other registered devices for task notifications — the contract is 'if any device is demonstrably watching, suppress the others'. Clients call this every ~30s while the task screen is foregrounded. `device_id` is the UUID of the caller's UserPushToken row.
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index a6dbf4103a43..f461e7d3416d 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -48,9 +48,6 @@ tools:
task-automations-run-create:
operation: task_automations_run_create
enabled: false
- task-automations-update:
- operation: task_automations_update
- enabled: false
tasks-create:
operation: tasks_create
enabled: false
diff --git a/products/tasks/package.json b/products/tasks/package.json
index 021abb472f38..0b70e0fa896d 100644
--- a/products/tasks/package.json
+++ b/products/tasks/package.json
@@ -1,7 +1,8 @@
{
"name": "@posthog/products-tasks",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/services backend/stream/tests backend/code_workstreams -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/logic -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
},
"dependencies": {
"fast-deep-equal": "catalog:",
diff --git a/products/tasks/scripts/run_agent_in_docker.py b/products/tasks/scripts/run_agent_in_docker.py
index 5a3d262e2cc5..9ee2f254c570 100755
--- a/products/tasks/scripts/run_agent_in_docker.py
+++ b/products/tasks/scripts/run_agent_in_docker.py
@@ -28,9 +28,9 @@ from posthog.models import Integration, PersonalAPIKey, Team, User
from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox
+from products.tasks.backend.logic.services.sandbox import SandboxConfig, SandboxTemplate
from products.tasks.backend.models import Task, TaskRun
-from products.tasks.backend.services.docker_sandbox import DockerSandbox
-from products.tasks.backend.services.sandbox import SandboxConfig, SandboxTemplate
def create_test_task(repository=None):
diff --git a/products/tasks/tsconfig.json b/products/tasks/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/tasks/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/tasks/turbo.json b/products/tasks/turbo.json
new file mode 100644
index 000000000000..34a16b3d30ce
--- /dev/null
+++ b/products/tasks/turbo.json
@@ -0,0 +1,10 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": ["backend/facade/**", "backend/presentation/**"],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bc76320c2224..ea7047dadd9c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31036,37 +31036,54 @@ export namespace Schemas {
results: Run[];
}
- export interface SandboxEnvironmentList {
- readonly id: string;
- /** @maxLength 255 */
+ /**
+ * @nullable
+ */
+ export type TaskUserBasicInfoHedgehogConfig = { [key: string]: unknown } | null;
+
+ /**
+ * Response shape for a `created_by` user — mirrors core `UserBasicSerializer` output.
+ */
+ export interface TaskUserBasicInfo {
+ id: number;
+ uuid: string;
+ distinct_id: string;
+ first_name: string;
+ last_name: string;
+ email: string;
+ /** @nullable */
+ is_email_verified?: boolean | null;
+ /** @nullable */
+ hedgehog_config?: TaskUserBasicInfoHedgehogConfig;
+ /** @nullable */
+ role_at_organization?: string | null;
+ }
+
+ /**
+ * List response for sandbox environments (subset of fields).
+ */
+ export interface SandboxEnvironmentDTO {
+ id: string;
name: string;
- network_access_level?: NetworkAccessLevelEnum;
- /**
- * List of allowed domains for custom network access
- * @items.maxLength 255
- */
+ network_access_level: string;
allowed_domains?: string[];
- /**
- * List of repositories this environment applies to (format: org/repo)
- * @items.maxLength 255
- */
repositories?: string[];
- /** If true, only the creator can see this environment. Otherwise visible to whole team. */
- private?: boolean;
- /** If true, this environment is for internal use (e.g. signals pipeline) and should not be exposed to end users. */
- internal?: boolean;
- readonly created_by: UserBasic;
- readonly created_at: string;
- readonly updated_at: string;
+ private: boolean;
+ internal: boolean;
+ created_by?: TaskUserBasicInfo | null;
+ /** @nullable */
+ created_at?: string | null;
+ /** @nullable */
+ updated_at?: string | null;
}
- export interface PaginatedSandboxEnvironmentListList {
+ export interface PaginatedSandboxEnvironmentDTOList {
count: number;
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
- results: SandboxEnvironmentList[];
+ results: SandboxEnvironmentDTO[];
}
/**
@@ -32359,139 +32376,216 @@ export namespace Schemas {
results: Tagger[];
}
- export interface TaskAutomation {
- readonly id: string;
- /** @maxLength 255 */
+ /**
+ * Detail/create/update/run response for a task automation.
+ */
+ export interface TaskAutomationDTO {
+ id: string;
name: string;
prompt: string;
- /** @maxLength 255 */
- repository: string;
/** @nullable */
- github_integration?: number | null;
- /** @maxLength 100 */
+ repository: string | null;
+ /** @nullable */
+ github_integration: number | null;
cron_expression: string;
- /** @maxLength 128 */
- timezone?: string;
- /**
- * @maxLength 255
- * @nullable
- */
- template_id?: string | null;
- enabled?: boolean;
+ timezone: string;
/** @nullable */
- readonly last_run_at: string | null;
+ template_id: string | null;
+ enabled: boolean;
/** @nullable */
- readonly last_run_status: string | null;
+ last_run_at: string | null;
/** @nullable */
- readonly last_task_id: string | null;
+ last_run_status: string | null;
+ last_task_id: string;
/** @nullable */
- readonly last_task_run_id: string | null;
+ last_task_run_id: string | null;
/** @nullable */
- readonly last_error: string | null;
- readonly created_at: string;
- readonly updated_at: string;
+ last_error: string | null;
+ created_at: string;
+ updated_at: string;
}
- export interface PaginatedTaskAutomationList {
+ export interface PaginatedTaskAutomationDTOList {
count: number;
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
- results: TaskAutomation[];
+ results: TaskAutomationDTO[];
}
/**
- * * `implementation` - Implementation
+ * * `claude` - claude
+ * * `codex` - codex
*/
- export type SignalReportTaskRelationshipEnum = typeof SignalReportTaskRelationshipEnum[keyof typeof SignalReportTaskRelationshipEnum];
+ export type RuntimeAdapterEnum = typeof RuntimeAdapterEnum[keyof typeof RuntimeAdapterEnum];
- export const SignalReportTaskRelationshipEnum = {
- Implementation: 'implementation',
+ export const RuntimeAdapterEnum = {
+ Claude: 'claude',
+ Codex: 'codex',
} as const;
/**
- * Latest run details for this task
+ * * `anthropic` - anthropic
+ * * `openai` - openai
+ */
+ export type TaskRunDetailDTOProviderEnum = typeof TaskRunDetailDTOProviderEnum[keyof typeof TaskRunDetailDTOProviderEnum];
+
+
+ export const TaskRunDetailDTOProviderEnum = {
+ Anthropic: 'anthropic',
+ Openai: 'openai',
+ } as const;
+
+ export interface TaskRunArtifactResponse {
+ /** Stable identifier for the artifact within this run */
+ id?: string;
+ /** Artifact file name */
+ name: string;
+ /** Artifact classification (plan, context, etc.) */
+ type: string;
+ /** Source of the artifact, such as agent_output or user_attachment */
+ source?: string;
+ /** Artifact size in bytes */
+ size?: number;
+ /** Optional MIME type */
+ content_type?: string;
+ /** S3 object key for the artifact */
+ storage_path: string;
+ /** Timestamp when the artifact was uploaded */
+ uploaded_at: string;
+ }
+
+ /**
* @nullable
*/
- export type TaskLatestRun = { [key: string]: unknown } | null;
+ export type TaskRunDetailDTOOutput = { [key: string]: unknown } | null;
- export interface Task {
- readonly id: string;
+ export type TaskRunDetailDTOState = { [key: string]: unknown };
+
+ /**
+ * Detail response for a task run.
+ *
+ * Reads from a frozen ``TaskRunDetailDTO`` produced by the facade mapper (which computes the
+ * presigned ``log_url`` and parses ``runtime_adapter`` / ``provider`` / ``model`` /
+ * ``reasoning_effort`` off the run state). ``task`` is the parent task id. Reused as the nested
+ * ``latest_run`` shape by the task detail response.
+ */
+ export interface TaskRunDetailDTO {
+ id: string;
+ /** Parent task id this run belongs to. */
+ task: string;
/** @nullable */
- readonly task_number: number | null;
- readonly slug: string;
- /**
- * Short human-readable title. Auto-generated from `description` when omitted.
- * @maxLength 255
- */
- title?: string;
- title_manually_set?: boolean;
- /** Free-form description of the work to be done. Used as the prompt passed to the agent. */
- description?: string;
- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
+ stage: string | null;
+ /** @nullable */
+ branch: string | null;
+ status: string;
+ environment: string;
+ /** Configured runtime adapter for this run, such as 'claude' or 'codex'.
*
- * * `error_tracking` - Error Tracking
- * * `eval_clusters` - Eval Clusters
- * * `user_created` - User Created
- * * `automation` - Automation
- * * `slack` - Slack
- * * `support_queue` - Support Queue
- * * `session_summaries` - Session Summaries
- * * `signal_report` - Signal Report
- * * `signals_scout` - Signals Scout
- * * `support_reply` - Support Reply */
- origin_product?: OriginProductEnum;
- /**
- * Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
- * @maxLength 255
- * @nullable
- */
- repository?: string | null;
+ * * `claude` - claude
+ * * `codex` - codex */
+ runtime_adapter?: RuntimeAdapterEnum | null;
+ /** Configured LLM provider for this run, such as 'anthropic' or 'openai'.
+ *
+ * * `anthropic` - anthropic
+ * * `openai` - openai */
+ provider?: TaskRunDetailDTOProviderEnum | null;
/**
- * GitHub integration for this task
+ * Configured LLM model identifier for this run.
* @nullable
*/
- github_integration?: number | null;
+ model?: string | null;
+ /** Configured reasoning effort for this run when the selected model supports it.
+ *
+ * * `low` - low
+ * * `medium` - medium
+ * * `high` - high
+ * * `xhigh` - xhigh
+ * * `max` - max */
+ reasoning_effort?: ReasoningEffortEnum | null;
/**
- * User-scoped GitHub integration to use for user-authored cloud runs.
+ * Presigned S3 URL for log access (valid for 1 hour).
* @nullable
*/
- github_user_integration?: string | null;
+ log_url?: string | null;
/** @nullable */
- signal_report?: string | null;
- signal_report_task_relationship?: SignalReportTaskRelationshipEnum;
- /** JSON schema for the task. This is used to validate the output of the task. */
- json_schema?: unknown;
- /** If true, this task is for internal use and should not be exposed to end users. */
- internal?: boolean;
- /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */
- archived?: boolean;
+ error_message: string | null;
/** @nullable */
- readonly archived_at: string | null;
- /**
- * Latest run details for this task
- * @nullable
- */
- readonly latest_run: TaskLatestRun;
- readonly created_at: string;
- readonly updated_at: string;
- readonly created_by: UserBasic;
- /**
- * Custom prompt for CI fixes. If blank, a default prompt will be used.
- * @nullable
- */
- ci_prompt?: string | null;
+ output: TaskRunDetailDTOOutput;
+ state: TaskRunDetailDTOState;
+ readonly artifacts: readonly TaskRunArtifactResponse[];
+ /** @nullable */
+ created_at?: string | null;
+ /** @nullable */
+ updated_at?: string | null;
+ /** @nullable */
+ completed_at?: string | null;
+ }
+
+ /**
+ * @nullable
+ */
+ export type TaskDetailDTOJsonSchema = { [key: string]: unknown } | null;
+
+ /**
+ * Detail response for a task.
+ *
+ * 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``.
+ */
+ export interface TaskDetailDTO {
+ id: string;
+ /** @nullable */
+ task_number: number | null;
+ slug: string;
+ title: string;
+ title_manually_set: boolean;
+ description: string;
+ origin_product: string;
+ /** @nullable */
+ repository: string | null;
+ /** @nullable */
+ github_integration: number | null;
+ /** @nullable */
+ github_user_integration: string | null;
+ /** @nullable */
+ signal_report: string | null;
+ /** @nullable */
+ json_schema: TaskDetailDTOJsonSchema;
+ internal: boolean;
+ archived: boolean;
+ /** @nullable */
+ archived_at: string | null;
+ /** Latest run details for this task */
+ latest_run?: TaskRunDetailDTO | null;
+ /** @nullable */
+ created_at?: string | null;
+ /** @nullable */
+ updated_at?: string | null;
+ created_by?: TaskUserBasicInfo | null;
+ /** @nullable */
+ ci_prompt: string | null;
+ }
+
+ export interface PaginatedTaskDetailDTOList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: TaskDetailDTO[];
}
- export interface PaginatedTaskList {
+ export interface PaginatedTaskRunDetailDTOList {
count: number;
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
- results: Task[];
+ results: TaskRunDetailDTO[];
}
/**
@@ -32526,129 +32620,31 @@ export namespace Schemas {
Cloud: 'cloud',
} as const;
- /**
- * * `claude` - claude
- * * `codex` - codex
- */
- export type RuntimeAdapterEnum = typeof RuntimeAdapterEnum[keyof typeof RuntimeAdapterEnum];
-
-
- export const RuntimeAdapterEnum = {
- Claude: 'claude',
- Codex: 'codex',
- } as const;
-
- export type TaskRunDetailProviderEnum = typeof TaskRunDetailProviderEnum[keyof typeof TaskRunDetailProviderEnum];
-
-
- export const TaskRunDetailProviderEnum = {
- Anthropic: 'anthropic',
- Openai: 'openai',
- } as const;
-
- export interface TaskRunArtifactResponse {
- /** Stable identifier for the artifact within this run */
- id?: string;
- /** Artifact file name */
- name: string;
- /** Artifact classification (plan, context, etc.) */
- type: string;
- /** Source of the artifact, such as agent_output or user_attachment */
- source?: string;
- /** Artifact size in bytes */
- size?: number;
- /** Optional MIME type */
- content_type?: string;
- /** S3 object key for the artifact */
- storage_path: string;
- /** Timestamp when the artifact was uploaded */
- uploaded_at: string;
- }
-
- export interface TaskRunDetail {
- readonly id: string;
- readonly task: string;
- /**
- * Current stage for this run (e.g., 'research', 'plan', 'build')
- * @maxLength 100
- * @nullable
- */
- stage?: string | null;
- /**
- * Branch name for the run
- * @maxLength 255
- * @nullable
- */
- branch?: string | null;
- status?: TaskRunStatusEnum;
- /** Execution environment
- *
- * * `local` - Local
- * * `cloud` - Cloud */
- environment?: TaskRunEnvironmentEnum;
- /** Configured runtime adapter for this run, such as 'claude' or 'codex'. */
- readonly runtime_adapter: RuntimeAdapterEnum | null;
- /** Configured LLM provider for this run, such as 'anthropic' or 'openai'. */
- readonly provider: TaskRunDetailProviderEnum | null;
- /**
- * Configured LLM model identifier for this run.
- * @nullable
- */
- readonly model: string | null;
- /** Configured reasoning effort for this run when the selected model supports it. */
- readonly reasoning_effort: ReasoningEffortEnum | null;
- /**
- * Presigned S3 URL for log access (valid for 1 hour).
- * @nullable
- */
- readonly log_url: string | null;
- /**
- * Error message if execution failed
- * @nullable
- */
- error_message?: string | null;
- /** Run output data (e.g., PR URL, commit SHA, etc.) */
- output?: unknown;
- /** Run state data for resuming or tracking execution state */
- state?: unknown;
- readonly artifacts: readonly TaskRunArtifactResponse[];
- readonly created_at: string;
- readonly updated_at: string;
- /** @nullable */
- readonly completed_at: string | null;
- }
-
- export interface PaginatedTaskRunDetailList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: TaskRunDetail[];
- }
-
export interface TaskRunSummary {
status: TaskRunStatusEnum | null;
environment: TaskRunEnvironmentEnum | null;
}
- export interface TaskSummary {
- readonly id: string;
- readonly title: string;
+ /**
+ * Summary response for a task — reads from a frozen ``TaskSummaryDTO``.
+ */
+ export interface TaskSummaryDTO {
+ id: string;
+ title: string;
/** @nullable */
- readonly repository: string | null;
- readonly created_at: string;
- readonly updated_at: string;
- readonly latest_run: TaskRunSummary | null;
+ repository: string | null;
+ created_at: string;
+ updated_at: string;
+ latest_run?: TaskRunSummary | null;
}
- export interface PaginatedTaskSummaryList {
+ export interface PaginatedTaskSummaryDTOList {
count: number;
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
- results: TaskSummary[];
+ results: TaskSummaryDTO[];
}
/**
@@ -38299,36 +38295,37 @@ export namespace Schemas {
readonly is_default?: boolean;
}
- export interface PatchedSandboxEnvironment {
- readonly id?: string;
- /** @maxLength 255 */
+ /**
+ * Request body for creating or updating a sandbox environment.
+ */
+ export interface PatchedSandboxEnvironmentWrite {
+ /**
+ * Display name for the environment.
+ * @maxLength 255
+ */
name?: string;
+ /** Network access policy: trusted (default allowlist), full (unrestricted), or custom.
+ *
+ * * `trusted` - Trusted
+ * * `full` - Full
+ * * `custom` - Custom */
network_access_level?: NetworkAccessLevelEnum;
/**
- * List of allowed domains for custom network access
+ * Allowed domains for custom network access.
* @items.maxLength 255
*/
allowed_domains?: string[];
- /** Whether to include default trusted domains (GitHub, npm, PyPI) */
+ /** Whether to include default trusted domains (GitHub, npm, PyPI). */
include_default_domains?: boolean;
/**
- * List of repositories this environment applies to (format: org/repo)
+ * Repositories this environment applies to (format: org/repo).
* @items.maxLength 255
*/
repositories?: string[];
- /** Encrypted environment variables (write-only, never returned in responses) */
+ /** Encrypted environment variables (write-only, never returned in responses). */
environment_variables?: unknown;
- /** Whether this environment has any environment variables set */
- readonly has_environment_variables?: boolean;
- /** If true, only the creator can see this environment. Otherwise visible to whole team. */
+ /** If true, only the creator can see this environment; otherwise the whole team can. */
private?: boolean;
- /** If true, this environment is for internal use (e.g. signals pipeline) and should not be exposed to end users. */
- readonly internal?: boolean;
- /** Computed domain allowlist based on network_access_level and allowed_domains */
- readonly effective_domains?: readonly string[];
- readonly created_by?: UserBasic;
- readonly created_at?: string;
- readonly updated_at?: string;
}
export interface PatchedSavedHeatmapRequest {
@@ -39471,110 +39468,44 @@ export namespace Schemas {
}
/**
- * Latest run details for this task
- * @nullable
+ * Request body for creating or updating a task automation.
*/
- export type PatchedTaskLatestRun = { [key: string]: unknown } | null;
-
- export interface PatchedTask {
- readonly id?: string;
- /** @nullable */
- readonly task_number?: number | null;
- readonly slug?: string;
+ export interface PatchedTaskAutomationWrite {
/**
- * Short human-readable title. Auto-generated from `description` when omitted.
+ * Display name (stored as the backing task's title).
* @maxLength 255
*/
- title?: string;
- title_manually_set?: boolean;
- /** Free-form description of the work to be done. Used as the prompt passed to the agent. */
- description?: string;
- /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
- *
- * * `error_tracking` - Error Tracking
- * * `eval_clusters` - Eval Clusters
- * * `user_created` - User Created
- * * `automation` - Automation
- * * `slack` - Slack
- * * `support_queue` - Support Queue
- * * `session_summaries` - Session Summaries
- * * `signal_report` - Signal Report
- * * `signals_scout` - Signals Scout
- * * `support_reply` - Support Reply */
- origin_product?: OriginProductEnum;
+ name?: string;
+ /** The automation prompt (stored as the backing task's description). */
+ prompt?: string;
/**
- * Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
+ * Target repository in the format organization/repository.
* @maxLength 255
- * @nullable
*/
- repository?: string | null;
+ repository?: string;
/**
- * GitHub integration for this task
+ * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
* @nullable
*/
github_integration?: number | null;
/**
- * User-scoped GitHub integration to use for user-authored cloud runs.
- * @nullable
- */
- github_user_integration?: string | null;
- /** @nullable */
- signal_report?: string | null;
- signal_report_task_relationship?: SignalReportTaskRelationshipEnum;
- /** JSON schema for the task. This is used to validate the output of the task. */
- json_schema?: unknown;
- /** If true, this task is for internal use and should not be exposed to end users. */
- internal?: boolean;
- /** If true, the task is hidden from default list responses. Used by PostHog Code clients to share archive state across desktop and mobile. */
- archived?: boolean;
- /** @nullable */
- readonly archived_at?: string | null;
- /**
- * Latest run details for this task
- * @nullable
+ * Standard 5-field cron expression (minute hour day month weekday).
+ * @maxLength 100
*/
- readonly latest_run?: PatchedTaskLatestRun;
- readonly created_at?: string;
- readonly updated_at?: string;
- readonly created_by?: UserBasic;
+ cron_expression?: string;
/**
- * Custom prompt for CI fixes. If blank, a default prompt will be used.
- * @nullable
+ * IANA timezone the schedule runs in.
+ * @maxLength 128
*/
- ci_prompt?: string | null;
- }
-
- export interface PatchedTaskAutomation {
- readonly id?: string;
- /** @maxLength 255 */
- name?: string;
- prompt?: string;
- /** @maxLength 255 */
- repository?: string;
- /** @nullable */
- github_integration?: number | null;
- /** @maxLength 100 */
- cron_expression?: string;
- /** @maxLength 128 */
timezone?: string;
/**
+ * Optional template identifier this automation was created from.
* @maxLength 255
* @nullable
*/
template_id?: string | null;
+ /** Whether the schedule is active; paused when false. */
enabled?: boolean;
- /** @nullable */
- readonly last_run_at?: string | null;
- /** @nullable */
- readonly last_run_status?: string | null;
- /** @nullable */
- readonly last_task_id?: string | null;
- /** @nullable */
- readonly last_task_run_id?: string | null;
- /** @nullable */
- readonly last_error?: string | null;
- readonly created_at?: string;
- readonly updated_at?: string;
}
export interface PatchedTaskRunSetOutputRequest {
@@ -39649,6 +39580,81 @@ export namespace Schemas {
environment?: TaskRunUpdateEnvironmentEnum;
}
+ /**
+ * * `implementation` - Implementation
+ */
+ export type SignalReportTaskRelationshipEnum = typeof SignalReportTaskRelationshipEnum[keyof typeof SignalReportTaskRelationshipEnum];
+
+
+ export const SignalReportTaskRelationshipEnum = {
+ Implementation: 'implementation',
+ } as const;
+
+ /**
+ * Request body for creating or updating a task.
+ *
+ * Field required/default semantics match the ``Task`` model. The view passes
+ * ``validated_data`` (integration/report PK fields already resolved to instances) to the
+ * facade ``create_task`` / ``update_task`` functions.
+ */
+ export interface PatchedTaskWrite {
+ /**
+ * Short human-readable title. Auto-generated from `description` when omitted.
+ * @maxLength 255
+ */
+ title?: string;
+ /** Whether the title was set by a human (vs auto-generated from the description). */
+ title_manually_set?: boolean;
+ /** Free-form description of the work to be done. Used as the prompt passed to the agent. */
+ description?: string;
+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
+ *
+ * * `error_tracking` - Error Tracking
+ * * `eval_clusters` - Eval Clusters
+ * * `user_created` - User Created
+ * * `automation` - Automation
+ * * `slack` - Slack
+ * * `support_queue` - Support Queue
+ * * `session_summaries` - Session Summaries
+ * * `signal_report` - Signal Report
+ * * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply */
+ origin_product?: OriginProductEnum;
+ /**
+ * Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
+ * @maxLength 255
+ * @nullable
+ */
+ repository?: string | null;
+ /**
+ * GitHub integration for this task.
+ * @nullable
+ */
+ github_integration?: number | null;
+ /**
+ * User-scoped GitHub integration to use for user-authored cloud runs.
+ * @nullable
+ */
+ github_user_integration?: string | null;
+ /**
+ * Signal report this task implements, when created from a report.
+ * @nullable
+ */
+ signal_report?: string | null;
+ signal_report_task_relationship?: SignalReportTaskRelationshipEnum;
+ /** JSON schema used to validate the output of the task. */
+ json_schema?: unknown;
+ /** If true, this task is for internal use and should not be exposed to end users. */
+ internal?: boolean;
+ /** If true, the task is hidden from default list responses. */
+ archived?: boolean;
+ /**
+ * Custom prompt for CI fixes. If blank, a default prompt will be used.
+ * @nullable
+ */
+ ci_prompt?: string | null;
+ }
+
export type PatchedTeamDefaultModifiers = { [key: string]: unknown };
export type PatchedTeamGroupTypesItem = { [key: string]: unknown };
@@ -44863,36 +44869,37 @@ export namespace Schemas {
fields: S3PresignedPostFields;
}
- export interface SandboxEnvironment {
- readonly id: string;
- /** @maxLength 255 */
+ /**
+ * Request body for creating or updating a sandbox environment.
+ */
+ export interface SandboxEnvironmentWrite {
+ /**
+ * Display name for the environment.
+ * @maxLength 255
+ */
name: string;
+ /** Network access policy: trusted (default allowlist), full (unrestricted), or custom.
+ *
+ * * `trusted` - Trusted
+ * * `full` - Full
+ * * `custom` - Custom */
network_access_level?: NetworkAccessLevelEnum;
/**
- * List of allowed domains for custom network access
+ * Allowed domains for custom network access.
* @items.maxLength 255
*/
allowed_domains?: string[];
- /** Whether to include default trusted domains (GitHub, npm, PyPI) */
+ /** Whether to include default trusted domains (GitHub, npm, PyPI). */
include_default_domains?: boolean;
/**
- * List of repositories this environment applies to (format: org/repo)
+ * Repositories this environment applies to (format: org/repo).
* @items.maxLength 255
*/
repositories?: string[];
- /** Encrypted environment variables (write-only, never returned in responses) */
+ /** Encrypted environment variables (write-only, never returned in responses). */
environment_variables?: unknown;
- /** Whether this environment has any environment variables set */
- readonly has_environment_variables: boolean;
- /** If true, only the creator can see this environment. Otherwise visible to whole team. */
+ /** If true, only the creator can see this environment; otherwise the whole team can. */
private?: boolean;
- /** If true, this environment is for internal use (e.g. signals pipeline) and should not be exposed to end users. */
- readonly internal: boolean;
- /** Computed domain allowlist based on network_access_level and allowed_domains */
- readonly effective_domains: readonly string[];
- readonly created_by: UserBasic;
- readonly created_at: string;
- readonly updated_at: string;
}
export interface SavedHeatmapListResponse {
@@ -48085,6 +48092,47 @@ export namespace Schemas {
deleted?: boolean;
}
+ /**
+ * Request body for creating or updating a task automation.
+ */
+ export interface TaskAutomationWrite {
+ /**
+ * Display name (stored as the backing task's title).
+ * @maxLength 255
+ */
+ name: string;
+ /** The automation prompt (stored as the backing task's description). */
+ prompt: string;
+ /**
+ * Target repository in the format organization/repository.
+ * @maxLength 255
+ */
+ repository: string;
+ /**
+ * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
+ * @nullable
+ */
+ github_integration?: number | null;
+ /**
+ * Standard 5-field cron expression (minute hour day month weekday).
+ * @maxLength 100
+ */
+ cron_expression: string;
+ /**
+ * IANA timezone the schedule runs in.
+ * @maxLength 128
+ */
+ timezone?: string;
+ /**
+ * Optional template identifier this automation was created from.
+ * @maxLength 255
+ * @nullable
+ */
+ template_id?: string | null;
+ /** Whether the schedule is active; paused when false. */
+ enabled?: boolean;
+ }
+
/**
* Request body for the presence beacon and beacon-leave endpoints.
*
@@ -48657,6 +48705,71 @@ export namespace Schemas {
ids: string[];
}
+ /**
+ * Request body for creating or updating a task.
+ *
+ * Field required/default semantics match the ``Task`` model. The view passes
+ * ``validated_data`` (integration/report PK fields already resolved to instances) to the
+ * facade ``create_task`` / ``update_task`` functions.
+ */
+ export interface TaskWrite {
+ /**
+ * Short human-readable title. Auto-generated from `description` when omitted.
+ * @maxLength 255
+ */
+ title?: string;
+ /** Whether the title was set by a human (vs auto-generated from the description). */
+ title_manually_set?: boolean;
+ /** Free-form description of the work to be done. Used as the prompt passed to the agent. */
+ description?: string;
+ /** PostHog product or surface that created this task (e.g. error_tracking, slack, user_created).
+ *
+ * * `error_tracking` - Error Tracking
+ * * `eval_clusters` - Eval Clusters
+ * * `user_created` - User Created
+ * * `automation` - Automation
+ * * `slack` - Slack
+ * * `support_queue` - Support Queue
+ * * `session_summaries` - Session Summaries
+ * * `signal_report` - Signal Report
+ * * `signals_scout` - Signals Scout
+ * * `support_reply` - Support Reply */
+ origin_product?: OriginProductEnum;
+ /**
+ * Target GitHub repository in `organization/repo` format (e.g. `posthog/posthog-js`).
+ * @maxLength 255
+ * @nullable
+ */
+ repository?: string | null;
+ /**
+ * GitHub integration for this task.
+ * @nullable
+ */
+ github_integration?: number | null;
+ /**
+ * User-scoped GitHub integration to use for user-authored cloud runs.
+ * @nullable
+ */
+ github_user_integration?: string | null;
+ /**
+ * Signal report this task implements, when created from a report.
+ * @nullable
+ */
+ signal_report?: string | null;
+ signal_report_task_relationship?: SignalReportTaskRelationshipEnum;
+ /** JSON schema used to validate the output of the task. */
+ json_schema?: unknown;
+ /** If true, this task is for internal use and should not be exposed to end users. */
+ internal?: boolean;
+ /** If true, the task is hidden from default list responses. */
+ archived?: boolean;
+ /**
+ * Custom prompt for CI fixes. If blank, a default prompt will be used.
+ * @nullable
+ */
+ ci_prompt?: string | null;
+ }
+
export type TeamDefaultModifiers = { [key: string]: unknown };
export type TeamGroupTypesItem = { [key: string]: unknown };
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index 13f2b945af57..d955c5921dfb 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -70,10 +70,11 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({
})
/**
- * API for managing tasks within a project. Tasks represent units of work to be performed by an agent.
+ * Retrieve a single task by ID.
+ * @summary Get task
*/
export const TasksRetrieveParams = /* @__PURE__ */ zod.object({
- id: zod.string().describe('A UUID string identifying this task.'),
+ id: zod.string(),
project_id: zod
.string()
.describe(
@@ -115,10 +116,11 @@ export const TasksRunsListQueryParams = /* @__PURE__ */ zod.object({
})
/**
- * API for managing task runs. Each run represents an execution of a task.
+ * Retrieve a single run for a specific task.
+ * @summary Get task run
*/
export const TasksRunsRetrieveParams = /* @__PURE__ */ zod.object({
- id: zod.string().describe('A UUID string identifying this task run.'),
+ id: zod.string(),
project_id: zod
.string()
.describe(
@@ -132,7 +134,7 @@ export const TasksRunsRetrieveParams = /* @__PURE__ */ zod.object({
* @summary Get filtered task run session logs
*/
export const TasksRunsSessionLogsRetrieveParams = /* @__PURE__ */ zod.object({
- id: zod.string().describe('A UUID string identifying this task run.'),
+ id: zod.string(),
project_id: zod
.string()
.describe(
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index 095335686bfa..593345824557 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -16,12 +16,12 @@ import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const TasksListSchema = TasksListQueryParams
-const tasksList = (): ToolBase<typeof TasksListSchema, WithPostHogUrl<Schemas.PaginatedTaskList>> => ({
+const tasksList = (): ToolBase<typeof TasksListSchema, WithPostHogUrl<Schemas.PaginatedTaskDetailDTOList>> => ({
name: 'tasks-list',
schema: TasksListSchema,
handler: async (context: Context, params: z.infer<typeof TasksListSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedTaskList>({
+ const result = await context.api.request<Schemas.PaginatedTaskDetailDTOList>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/`,
query: {
@@ -69,12 +69,12 @@ const tasksList = (): ToolBase<typeof TasksListSchema, WithPostHogUrl<Schemas.Pa
const TasksRetrieveSchema = TasksRetrieveParams.omit({ project_id: true })
-const tasksRetrieve = (): ToolBase<typeof TasksRetrieveSchema, WithPostHogUrl<Schemas.Task>> => ({
+const tasksRetrieve = (): ToolBase<typeof TasksRetrieveSchema, WithPostHogUrl<Schemas.TaskDetailDTO>> => ({
name: 'tasks-retrieve',
schema: TasksRetrieveSchema,
handler: async (context: Context, params: z.infer<typeof TasksRetrieveSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.Task>({
+ const result = await context.api.request<Schemas.TaskDetailDTO>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(params.id))}/`,
})
@@ -89,12 +89,15 @@ const tasksRetrieve = (): ToolBase<typeof TasksRetrieveSchema, WithPostHogUrl<Sc
const TasksRunsListSchema = TasksRunsListParams.omit({ project_id: true }).extend(TasksRunsListQueryParams.shape)
-const tasksRunsList = (): ToolBase<typeof TasksRunsListSchema, WithPostHogUrl<Schemas.PaginatedTaskRunDetailList>> => ({
+const tasksRunsList = (): ToolBase<
+ typeof TasksRunsListSchema,
+ WithPostHogUrl<Schemas.PaginatedTaskRunDetailDTOList>
+> => ({
name: 'tasks-runs-list',
schema: TasksRunsListSchema,
handler: async (context: Context, params: z.infer<typeof TasksRunsListSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedTaskRunDetailList>({
+ const result = await context.api.request<Schemas.PaginatedTaskRunDetailDTOList>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(params.task_id))}/runs/`,
query: {
@@ -126,12 +129,12 @@ const tasksRunsList = (): ToolBase<typeof TasksRunsListSchema, WithPostHogUrl<Sc
const TasksRunsRetrieveSchema = TasksRunsRetrieveParams.omit({ project_id: true })
-const tasksRunsRetrieve = (): ToolBase<typeof TasksRunsRetrieveSchema, Schemas.TaskRunDetail> => ({
+const tasksRunsRetrieve = (): ToolBase<typeof TasksRunsRetrieveSchema, Schemas.TaskRunDetailDTO> => ({
name: 'tasks-runs-retrieve',
schema: TasksRunsRetrieveSchema,
handler: async (context: Context, params: z.infer<typeof TasksRunsRetrieveSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.TaskRunDetail>({
+ const result = await context.api.request<Schemas.TaskRunDetailDTO>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tasks/${encodeURIComponent(String(params.task_id))}/runs/${encodeURIComponent(String(params.id))}/`,
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json
index f0289641c9e3..f9bfd8020ef3 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-retrieve.json
@@ -2,7 +2,6 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"id": {
- "description": "A UUID string identifying this task.",
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-retrieve.json
index 9d85a8bd3f26..8e1be0b16ab9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-retrieve.json
@@ -2,7 +2,6 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"id": {
- "description": "A UUID string identifying this task run.",
"type": "string"
},
"task_id": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-session-logs-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-session-logs-retrieve.json
index d0d176d4111d..21585e1006f7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-session-logs-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-runs-session-logs-retrieve.json
@@ -18,7 +18,6 @@
"type": "string"
},
"id": {
- "description": "A UUID string identifying this task run.",
"type": "string"
},
"limit": {
diff --git a/tach.toml b/tach.toml
index e5ead3ac2145..dd2268ebe2d8 100644
--- a/tach.toml
+++ b/tach.toml
@@ -690,7 +690,7 @@ expose = [
"backend\\.routes.*",
]
from = [
- "products\\.(customer_analytics|error_tracking|experiments|mcp_analytics|mcp_store|metrics|notifications|streamlit_apps|tracing|user_interviews|visual_review)",
+ "products\\.(customer_analytics|error_tracking|experiments|mcp_analytics|mcp_store|metrics|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review)",
]
# TODO: Experiments-specific temporary interface
diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.py
index 3f3a43eaea05..678d630ea007 100644
--- a/tools/hogli-commands/hogli_commands/product/checks.py
+++ b/tools/hogli-commands/hogli_commands/product/checks.py
@@ -490,6 +490,10 @@ class MisplacedFilesCheck(ProductCheck):
# `temporal` is the established home for Temporal workflow + activity code
# across products (batch_exports, data_warehouse, tasks, experiments, and
# others), so it is allowed in isolated products on the same grounds.
+ # `sandbox` holds Docker build context (Dockerfiles + helper scripts) for
+ # sandboxed execution, not importable Python — its path is referenced by
+ # image-build workflows and COPY directives, so it can't follow the
+ # Python-package convention and is allowed at backend root.
_KNOWN_DIRS = {
"facade",
"presentation",
@@ -502,6 +506,7 @@ class MisplacedFilesCheck(ProductCheck):
"logic",
"hogql_queries",
"temporal",
+ "sandbox",
"templates",
"admin",
"__pycache__",
diff --git a/tools/hogli-commands/hogli_commands/product/isolate.py b/tools/hogli-commands/hogli_commands/product/isolate.py
index 6b8a16464236..21eb073d36e1 100644
--- a/tools/hogli-commands/hogli_commands/product/isolate.py
+++ b/tools/hogli-commands/hogli_commands/product/isolate.py
@@ -360,8 +360,13 @@ def _module_dotted(name: str, rel: Path) -> str:
``api/heatmaps_api.py`` -> ``products.<name>.backend.api.heatmaps_api`` — the
intermediate package matters, so derive from the full relative path, not the stem.
+
+ ``rel`` may also be a directory (the package containing a file). A backend-root
+ file has parent ``Path('.')``, whose ``with_suffix`` raises on an empty name —
+ that case is just the backend package itself.
"""
- return ".".join((f"products.{name}.backend", *rel.with_suffix("").parts))
+ parts = rel.with_suffix("").parts if rel != Path(".") else ()
+ return ".".join((f"products.{name}.backend", *parts))
@dataclass
diff --git a/tools/query-performance-ai/query_performance_ai/orchestrator/coordinator.py b/tools/query-performance-ai/query_performance_ai/orchestrator/coordinator.py
index 8c9c643c27c7..1c356e96774f 100644
--- a/tools/query-performance-ai/query_performance_ai/orchestrator/coordinator.py
+++ b/tools/query-performance-ai/query_performance_ai/orchestrator/coordinator.py
@@ -44,7 +44,7 @@ from .server import ServerInfo, generate_token, make_server, serve_forever_in_th
from .slow_queries import SlowQuery, fetch_available_columns, fetch_available_dictionaries, fetch_slow_queries
if TYPE_CHECKING:
- from products.tasks.backend.services.sandbox import SandboxBase
+ from products.tasks.backend.facade.sandbox import SandboxBase
PRODUCT_DIR = Path(__file__).resolve().parent.parent
RUNS_DIR = PRODUCT_DIR / "data" / "runs"
@@ -212,7 +212,7 @@ def _spawn_one_sandbox(
# Lazy import: SandboxBase pulls in Django settings, structlog, etc.
# Keeping it inside the worker means `--no-spawn` doesn't pay for it.
_ensure_django_setup()
- from products.tasks.backend.services.sandbox import ( # noqa: PLC0415
+ from products.tasks.backend.facade.sandbox import ( # noqa: PLC0415
SandboxConfig,
SandboxTemplate,
get_sandbox_class_for_backend,
@@ -640,7 +640,7 @@ def main(argv: list[str] | None = None) -> int:
_load_repo_dotenv()
# Set DJANGO_SETTINGS_MODULE + SANDBOX_PROVIDER before any worker thread
- # might import `products.tasks.backend.services.sandbox`. Workers also
+ # might import `products.tasks.backend.logic.services.sandbox`. Workers also
# call this defensively (idempotent), but doing it here means the first
# `import` from a worker thread doesn't race with the env-var write.
_ensure_django_setup()
diff --git a/tools/query-performance-ai/query_performance_ai/orchestrator/harvest.py b/tools/query-performance-ai/query_performance_ai/orchestrator/harvest.py
index 43de4c824f2d..16a3cbab56cf 100644
--- a/tools/query-performance-ai/query_performance_ai/orchestrator/harvest.py
+++ b/tools/query-performance-ai/query_performance_ai/orchestrator/harvest.py
@@ -6,7 +6,7 @@ import json
import shlex
from dataclasses import dataclass, field
-from products.tasks.backend.services.sandbox import SandboxBase
+from products.tasks.backend.facade.sandbox import SandboxBase
WORKSPACE_PATH = "/tmp/autoresearch-campaign" # must match run_campaign.py
LLM_GATEWAY_PRODUCT_SLUG = "background_agents" # posthog/llm/gateway_client.py Product literal