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): warm cloud sandbox while composing, reuse on submit (#65541)

Alessandro Pogliaghi878613a76b32
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 99f5e3f3f82d..284d9ce8c95c 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -180,6 +180,7 @@ __all__ = [
"upsert_internal_sandbox_env",
"validate_set_output",
"validate_task_run_artifact_ids",
+ "warm_task_sandbox",
]
@@ -2575,10 +2576,29 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> c
validated_data = dict(validated_data)
validated_data["team"] = team
validated_data.setdefault("origin_product", Task.OriginProduct.USER_CREATED)
+ warm_branch_provided = "branch" in validated_data
+ warm_branch = validated_data.pop("branch", None)
if user_id is not None:
validated_data["created_by"] = User.objects.get(id=user_id)
+ if (
+ warm_branch_provided
+ and validated_data["origin_product"] == Task.OriginProduct.USER_CREATED
+ and validated_data.get("repository")
+ and user_id is not None
+ ):
+ warm_run = _find_idling_warm_run(team_id, user_id, repository=validated_data["repository"], branch=warm_branch)
+ if warm_run is not None:
+ warm_task = warm_run.task
+ message = (validated_data.get("description") or "").strip()
+ if message and not (warm_task.title or "").strip():
+ warm_task.title = generate_task_title(message)
+ warm_task.title_manually_set = False
+ warm_task.save(update_fields=["title", "title_manually_set", "updated_at"])
+ _activate_warm_run(warm_run, warm_task, team_id, message=message or None, artifact_ids=[])
+ return _task_detail_to_dto(_task_detail_queryset().get(pk=warm_task.pk))
+
# Only IMPLEMENTATION is accepted; pop it so it isn't forwarded to the model. The link itself
# is recorded by record_implementation_task below.
validated_data.pop("signal_report_task_relationship", None)
@@ -2639,6 +2659,7 @@ def update_task(
validated_data.pop("signal_report", None)
validated_data.pop("signal_report_task_relationship", None)
validated_data.pop("origin_product", None)
+ validated_data.pop("branch", 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:
@@ -2792,6 +2813,142 @@ def finalize_task_staged_artifacts(
return contracts.StagedArtifactFinalizeResult(artifacts=finalized)
+def resolve_team_github_integration_id(team_id: int, github_integration_id: int) -> int | None:
+ """Return the integration id only if it is a GitHub integration owned by this team.
+
+ Re-scoping guard for the collection-level warm endpoint, which accepts a bare PK with
+ no serializer team context. Returns ``None`` for any id that doesn't belong to the team —
+ the caller treats that as "skip warming" (the submit later falls through to a cold create+run).
+ """
+ exists = Integration.objects.filter(id=github_integration_id, team_id=team_id, kind="github").exists()
+ return github_integration_id if exists else None
+
+
+def _find_idling_warm_run(
+ team_id: int, user_id: int | None, *, repository: str | None, branch: str | None
+) -> TaskRun | None:
+ """Most-recent idling pre-warmed Run matching this user's cloud composing selection, or ``None``.
+
+ A warm Run is a non-terminal ``USER_CREATED`` Run for the same repo+branch still awaiting its
+ first user message (the ``await_user_message`` state marker). This is the backend's single source
+ of truth for the warm pool: it dedupes warm provisioning (so a repeated ``warm`` call reuses the
+ live Run instead of spawning a second) and lets the normal create+run path transparently reuse a
+ warm Run on submit. Team + user scoped; branch compared as ``None``-normalized exact match.
+
+ Runs on a hot path (warm fires on every typing debounce), so every predicate is pushed into the
+ query — ``await_user_message`` is JSON-queryable (see ``SandboxWarmer.at_capacity``) — and only the
+ single most-recent match is fetched.
+ """
+ if user_id is None or not repository:
+ return None
+ return (
+ TaskRun.objects.filter( # nosemgrep: idor-lookup-without-team — team_id filter applied via the task FK below
+ task__team_id=team_id,
+ task__created_by_id=user_id,
+ task__origin_product=Task.OriginProduct.USER_CREATED,
+ task__repository__iexact=repository,
+ task__deleted=False,
+ state__await_user_message=True,
+ branch=branch or None,
+ )
+ .exclude(status__in=_TERMINAL_TASK_RUN_STATUSES)
+ .select_related("task")
+ .order_by("-created_at")
+ .first()
+ )
+
+
+def _idling_warm_run_for_task(task: Task) -> TaskRun | None:
+ """The task's latest run iff it is an idling pre-warmed Run (non-terminal, awaiting first message)."""
+ run = task.latest_run
+ if run is None or run.is_terminal:
+ return None
+ if not (run.state or {}).get("await_user_message"):
+ return None
+ return run
+
+
+def _activate_warm_run(run: TaskRun, task: Task, team_id: int, *, message: str | None, artifact_ids: list[str]) -> None:
+ """Activate an idling warm Run: set the draft Task's description (when empty), forward the first
+ message to the already-running agent, and drop the ``await_user_message`` marker so the Run leaves
+ the warm pool. Mirrors ``message_routing._handle_first_message``; no fresh agent start."""
+ if message and not (task.description or "").strip():
+ task.description = message
+ task.save(update_fields=["description", "updated_at"])
+ signal_task_run_user_message(run.id, task.id, team_id, content=message, artifact_ids=artifact_ids)
+ TaskRun.update_state_atomic(run.id, remove_keys=["await_user_message"])
+
+
+def warm_task_sandbox(
+ team_id: int,
+ user_id: int,
+ *,
+ repository: str,
+ github_integration_id: int,
+ branch: str | None,
+) -> contracts.WarmTaskDTO | None:
+ """Warm a full idling Run for a Code-app cloud task while the user composes.
+
+ Births a draft Task (``USER_CREATED``), then ``SandboxWarmer.warm()`` provisions an interactive
+ Run that boots + clones + checks out ``branch`` + starts the agent, then idles awaiting the first
+ ``user_message``. The Run is dispatched with ``create_pr=True`` so that, once activated on submit,
+ it completes autonomously and opens a PR like a normal Code-app cloud task.
+
+ Best-effort: returns ``None`` (not an HTTP error) when warming is gated — over quota
+ (``QuotaLimitExceeded``), product not enabled (``PermissionDenied``), or the warm pool is full
+ (``Throttled``). The caller treats ``None`` as "no warm run; fall through to a cold create+run".
+
+ ``github_integration_id`` must already be re-scoped to ``team_id`` by the caller
+ (see :func:`resolve_team_github_integration_id`).
+ """
+ from rest_framework.exceptions import ( # noqa: PLC0415 — keep DRF exception types off the api import path
+ PermissionDenied,
+ Throttled,
+ )
+
+ from posthog.exceptions import QuotaLimitExceeded # noqa: PLC0415 — keep billing deps off the api import path
+ from posthog.models import Team # noqa: PLC0415
+
+ from products.tasks.backend.logic.services.warm import (
+ SandboxWarmer, # noqa: PLC0415 — keep warming deps off the api import path
+ )
+
+ existing = _find_idling_warm_run(team_id, user_id, repository=repository, branch=branch)
+ if existing is not None:
+ return contracts.WarmTaskDTO(task_id=existing.task_id, run_id=existing.id)
+
+ team = Team.objects.get(id=team_id)
+ github_integration = Integration.objects.filter(id=github_integration_id, team_id=team_id, kind="github").first()
+ if github_integration is None:
+ return None
+
+ task = Task.create_without_run(
+ team=team,
+ title="",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ user_id=user_id,
+ repository=repository,
+ )
+ assert task.created_by is not None # create_without_run always sets created_by from user_id
+
+ try:
+ result = SandboxWarmer(task, user=task.created_by).warm(
+ mode="interactive",
+ extra_state={
+ "branch": branch,
+ "initial_permission_mode": "default",
+ "use_modal_network_allowlist": False,
+ },
+ create_pr=True,
+ )
+ except (Throttled, PermissionDenied, QuotaLimitExceeded):
+ task.soft_delete()
+ return None
+
+ return contracts.WarmTaskDTO(task_id=task.id, run_id=result.run.id)
+
+
# --- Task run (the ``run`` action) ---
@@ -2828,6 +2985,21 @@ def run_task(
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")
+
+ if not resume_from_run_id:
+ warm_run = _idling_warm_run_for_task(task)
+ # Only activate when the requested branch matches the branch the warm Run was provisioned on —
+ # otherwise the run would work the wrong branch in the warm sandbox. On mismatch, fall through
+ # to the cold path so a fresh run is created for the requested branch.
+ if warm_run is not None and (branch or None) == (warm_run.branch or None):
+ _activate_warm_run(
+ warm_run,
+ task,
+ team_id,
+ message=pending_user_message or (task.description or None),
+ artifact_ids=validated_data.get("pending_user_artifact_ids") or [],
+ )
+ return contracts.TaskRunResult(task=get_task_detail(task.id, team_id, user_id))
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
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 7f5fcbf22a3d..34c790d8fb4f 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -583,6 +583,14 @@ class SignalReportPrUrlDTO:
pr_url: str
+@dataclass(frozen=True)
+class WarmTaskDTO:
+ """The draft Task + warm Run birthed by a Code-app warm request."""
+
+ task_id: UUID
+ run_id: UUID
+
+
@dataclass(frozen=True)
class TaskRunGaugeRow:
"""One metric value keyed by (status, environment, origin_product)."""
diff --git a/products/tasks/backend/logic/services/tests/test_warm.py b/products/tasks/backend/logic/services/tests/test_warm.py
index 5e07307f939e..a9d4e54f52b2 100644
--- a/products/tasks/backend/logic/services/tests/test_warm.py
+++ b/products/tasks/backend/logic/services/tests/test_warm.py
@@ -114,7 +114,7 @@ class TestSandboxWarmerWarm(APIBaseTest):
def test_unregistered_origin_product_is_rejected(self):
# Fail-closed: only origin products with a registered quota gate may warm.
- task = self._task(origin=Task.OriginProduct.USER_CREATED)
+ task = self._task(origin=Task.OriginProduct.ERROR_TRACKING)
with self.assertRaises(PermissionDenied):
SandboxWarmer(task, user=self.user).warm()
assert task.runs.count() == 0
diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.py
index 0e7fcb74f463..93b55b81b24d 100644
--- a/products/tasks/backend/logic/services/warm.py
+++ b/products/tasks/backend/logic/services/warm.py
@@ -67,15 +67,20 @@ class SandboxWarmer:
# A warm Run is non-terminal and idling; these are the statuses it can hold before activation.
_NON_TERMINAL_STATUSES: frozenset[str] = frozenset({TaskRun.Status.QUEUED, TaskRun.Status.IN_PROGRESS})
- # Each checker returns None or raises a DRF APIException; the in-process caller can't return an HTTP
- # Response, so the contract is exception-based and DRF renders the status from any depth. Fail-closed:
- # a product warms only once it registers a gate here, else it would provision sandboxes with no ceiling.
- ORIGIN_PRODUCT_QUOTA: dict[str, Callable[[Team, User], None]] = {
+ # Maps an origin product to its pre-warm quota gate. A checker returns None or raises a DRF
+ # APIException (the in-process caller can't return an HTTP Response, so the contract is exception-
+ # based and DRF renders the status from any depth). ``None`` means the origin may warm with no
+ # billing quota — gated only by enablement + the warm-pool caps (e.g. USER_CREATED, the Code-app
+ # origin: gated by the ``tasks-prewarm-sandbox`` flag at the endpoint, not an AI-credit budget).
+ # Fail-closed: an origin absent from this registry cannot warm at all.
+ ORIGIN_PRODUCT_QUOTA: dict[str, Callable[[Team, User], None] | None] = {
Task.OriginProduct.POSTHOG_AI: _ai_credits_checker,
+ Task.OriginProduct.USER_CREATED: None,
}
ORIGIN_PRODUCT_CAPS: dict[str, WarmPoolCaps] = {
Task.OriginProduct.POSTHOG_AI: WarmPoolCaps(per_user=2, per_org=10),
+ Task.OriginProduct.USER_CREATED: WarmPoolCaps(per_user=2, per_org=50),
}
_DEFAULT_CAPS: WarmPoolCaps = WarmPoolCaps(per_user=2, per_org=10)
@@ -85,11 +90,16 @@ class SandboxWarmer:
@classmethod
def enforce_quota(cls, origin_product: str, team: Team, user: User) -> None:
- """Raise if ``team`` may not warm a Run for ``origin_product`` (over quota, or product not registered)."""
- checker = cls.ORIGIN_PRODUCT_QUOTA.get(origin_product)
- if checker is None:
+ """Raise if ``team`` may not warm a Run for ``origin_product`` (over quota, or origin not registered).
+
+ Fail-closed: an origin absent from the registry is denied. A registered origin whose gate is
+ ``None`` is allowed with no billing quota (enablement + caps gate it elsewhere).
+ """
+ if origin_product not in cls.ORIGIN_PRODUCT_QUOTA:
raise PermissionDenied(f"Warming is not enabled for origin product '{origin_product}'.")
- checker(team, user)
+ checker = cls.ORIGIN_PRODUCT_QUOTA[origin_product]
+ if checker is not None:
+ checker(team, user)
@classmethod
def at_capacity(cls, origin_product: str, team: Team, user: User) -> bool:
@@ -115,14 +125,18 @@ class SandboxWarmer:
return True
return warm_runs.filter(task__team__organization_id=team.organization_id).count() >= caps.per_org
- def warm(self, *, mode: str = "interactive", extra_state: dict[str, Any] | None = None) -> WarmResult:
+ def warm(
+ self, *, mode: str = "interactive", extra_state: dict[str, Any] | None = None, create_pr: bool = False
+ ) -> WarmResult:
"""Idempotently ensure the Task has a warm Run, then dispatch the processing workflow after commit.
- Idempotent: if the Task already has a non-terminal Run, return it without provisioning.
- Fresh: a Task with no Runs gets a new warm Run; a Task whose latest Run is terminal gets a
successor that resumes from it (filesystem reuse via ``snapshot_external_id``).
- ``extra_state`` carries product-specific Run state the generic warmer can't know (e.g. PostHog
- AI's ``systemPrompt``); it is merged into the warm Run's initial state.
+ AI's ``systemPrompt``, or a target ``branch``); it is merged into the warm Run's initial state.
+ - ``create_pr`` is forwarded to the processing workflow; it defaults to ``False`` (PostHog AI warm
+ runs don't open PRs). The Code-app caller passes ``True`` so the activated run opens a PR.
Raises ``QuotaLimitExceeded`` (402) / ``PermissionDenied`` (403) when gated, and ``Throttled``
(429) when the warm pool is full.
@@ -153,7 +167,7 @@ class SandboxWarmer:
if snapshot_external_id:
run_state["snapshot_external_id"] = snapshot_external_id
- new_run = locked.create_run(mode=mode, extra_state=run_state)
+ new_run = locked.create_run(mode=mode, extra_state=run_state, branch=run_state.get("branch"))
# Dispatch only after the row commits, so a rollback can't leave an orphaned sandbox.
task_id, run_id, team_id, user_id = str(locked.id), str(new_run.id), self.task.team_id, self.user.pk
@@ -163,8 +177,9 @@ class SandboxWarmer:
run_id=run_id,
team_id=team_id,
user_id=user_id,
- create_pr=False,
+ create_pr=create_pr,
posthog_mcp_scopes="full",
+ prewarmed=True,
)
)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 4ae18ce47af8..7e6d3bb85f7d 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -326,6 +326,18 @@ class TaskWriteSerializer(serializers.Serializer):
allow_blank=True,
help_text="Custom prompt for CI fixes. If blank, a default prompt will be used.",
)
+ branch = serializers.CharField(
+ max_length=255,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ write_only=True,
+ help_text=(
+ "Branch the user has selected for this cloud task. Write-only and not persisted on the "
+ "task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch "
+ "is otherwise carried on the run). Omit to match a warm Run on the default branch."
+ ),
+ )
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -1165,6 +1177,50 @@ class TaskRunBootstrapCreateRequestSerializer(serializers.Serializer):
return attrs
+class WarmTaskRequestSerializer(serializers.Serializer):
+ """Request body for warming a full idling Run while composing a Code-app cloud task.
+
+ Collection-level: no task exists yet at typing time. The warmer births a draft Task and an
+ interactive Run that boots, clones, checks out `branch`, and starts the agent, then idles awaiting
+ the first message. `github_integration` is a plain integration PK (an integer); the view re-scopes
+ it to the caller's team before use.
+ """
+
+ repository = serializers.CharField(
+ max_length=255,
+ help_text="Target GitHub repository to clone, in `organization/repo` format (e.g. `posthog/posthog`).",
+ )
+ github_integration = serializers.IntegerField(
+ help_text="Primary key of the team's GitHub integration to clone with.",
+ )
+ branch = serializers.CharField(
+ required=False,
+ default=None,
+ allow_blank=True,
+ allow_null=True,
+ max_length=255,
+ help_text="Branch to check out in the warm sandbox. Defaults to the repository's default branch when omitted.",
+ )
+
+ def validate_repository(self, value: str) -> str:
+ normalized = value.strip().lower()
+ parts = normalized.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 normalized
+
+
+class WarmTaskResponseSerializer(serializers.Serializer):
+ """Response for a successful warm request — the draft Task + idling warm Run reused on submit."""
+
+ task_id = serializers.UUIDField(
+ help_text="Id of the draft Task birthed for the warm Run.",
+ )
+ run_id = serializers.UUIDField(
+ help_text="Id of the idling warm Run. The normal create+run path reuses and activates it on submit.",
+ )
+
+
class TaskRunStartRequestSerializer(serializers.Serializer):
pending_user_message = serializers.CharField(
required=False,
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 9d15bda6cb38..ccaaf2cd0e0d 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -12,6 +12,7 @@ from django.conf import settings
from django.http import HttpResponse, JsonResponse
import requests as http_requests
+import posthoganalytics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import status, viewsets
@@ -100,11 +101,16 @@ from products.tasks.backend.presentation.serializers import (
TaskSummariesRequestSerializer,
TaskSummarySerializer,
TaskWriteSerializer,
+ WarmTaskRequestSerializer,
+ WarmTaskResponseSerializer,
)
from ee.hogai.utils.aio import async_to_sync
logger = logging.getLogger(__name__)
+
+TASKS_PREWARM_SANDBOX_FLAG = "tasks-prewarm-sandbox"
+
TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS = 20.0
TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME = "keepalive"
TASK_RUN_STREAM_KEEPALIVE_PAYLOAD = {"type": "keepalive"}
@@ -521,6 +527,70 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return self._task_error_response(result.error)
return Response(TaskSerializer(result.task).data)
+ def _warm_enabled(self) -> bool:
+ """Person + org level gate for the sandbox-warming feature. Fail-closed on any error."""
+ user = self.request.user
+ distinct_id = getattr(user, "distinct_id", None) or str(getattr(user, "uuid", ""))
+ organization_id = str(getattr(self.team, "organization_id", "") or "")
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ TASKS_PREWARM_SANDBOX_FLAG,
+ distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("tasks-prewarm-sandbox flag check failed; treating as disabled")
+ return False
+
+ @validated_request(
+ request_serializer=WarmTaskRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=WarmTaskResponseSerializer,
+ description="Warm Run provisioned (`task_id`/`run_id` to activate on submit), or an empty body when the feature is off, capped, or the integration didn't resolve.",
+ ),
+ },
+ summary="Warm a task sandbox",
+ description=(
+ "Warm a full idling Run for a Code-app cloud task while the user composes: boot a sandbox, "
+ "clone the repo, check out the branch, and start the agent, then idle awaiting the first "
+ "message. On submit the normal create+run path transparently reuses and activates this Run; "
+ "abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty "
+ "body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't "
+ "belong to the team."
+ ),
+ )
+ @action(detail=False, methods=["post"], url_path="warm", required_scopes=["task:write"])
+ def warm(self, request, **kwargs):
+ if not self._warm_enabled():
+ return Response(status=status.HTTP_200_OK)
+
+ user_id = self._user_id()
+ if user_id is None:
+ return Response(status=status.HTTP_200_OK)
+
+ github_integration_id = tasks_facade.resolve_team_github_integration_id(
+ self.team_id, request.validated_data["github_integration"]
+ )
+ if github_integration_id is None:
+ return Response(status=status.HTTP_200_OK)
+
+ result = tasks_facade.warm_task_sandbox(
+ self.team_id,
+ user_id,
+ repository=request.validated_data["repository"],
+ github_integration_id=github_integration_id,
+ branch=request.validated_data.get("branch"),
+ )
+ if result is None:
+ return Response(status=status.HTTP_200_OK)
+ return Response(WarmTaskResponseSerializer({"task_id": result.task_id, "run_id": result.run_id}).data)
+
@staticmethod
def _task_error_response(error: tasks_contracts.TaskValidationError) -> Response:
if error.kind == "error":
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index a9eed796ae64..341abfbd2a35 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -145,6 +145,7 @@ async def execute_task_processing_workflow_async(
slack_thread_context: Optional[Any] = None,
skip_user_check: bool = False,
posthog_mcp_scopes: PosthogMcpScopes = "read_only",
+ prewarmed: bool = False,
) -> None:
"""
Start the task processing workflow asynchronously. Fire-and-forget.
@@ -168,6 +169,7 @@ async def execute_task_processing_workflow_async(
create_pr=create_pr,
slack_thread_context=slack_context_dict,
posthog_mcp_scopes=posthog_mcp_scopes,
+ prewarmed=prewarmed,
)
logger.info(
@@ -219,6 +221,7 @@ def execute_task_processing_workflow(
slack_thread_context: Optional["SlackThreadContext"] = None,
skip_user_check: bool = False,
posthog_mcp_scopes: PosthogMcpScopes = "read_only",
+ prewarmed: bool = False,
) -> None:
"""
Start the task processing workflow synchronously. Fire-and-forget.
@@ -243,6 +246,7 @@ def execute_task_processing_workflow(
create_pr=create_pr,
slack_thread_context=slack_context_dict,
posthog_mcp_scopes=posthog_mcp_scopes,
+ prewarmed=prewarmed,
)
logger.info(
diff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.py
index b0b48f551ea5..5ffe8f7e9903 100644
--- a/products/tasks/backend/temporal/constants.py
+++ b/products/tasks/backend/temporal/constants.py
@@ -49,6 +49,8 @@ def resolve_inactivity_timeout(*, is_user_origin: bool = False, state: dict | No
# don't have task context. The CI follow-up timing lives in `task_management`.
INACTIVITY_TIMEOUT = resolve_inactivity_timeout()
+WARM_IDLE_TIMEOUT = timedelta(minutes=10)
+
# CI follow-up cadence after the agent has been idle.
CI_FOLLOW_UP_DELAY = timedelta(minutes=15)
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 ca2ed0148b02..eadb57e4cd68 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1,4 +1,5 @@
import os
+import json
import uuid
import random
import asyncio
@@ -18,6 +19,7 @@ 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.temporal.constants import INACTIVITY_TIMEOUT_USER_SECONDS, WARM_IDLE_TIMEOUT
from products.tasks.backend.temporal.process_task import workflow as process_task_workflow_module
from products.tasks.backend.temporal.process_task.activities import (
CreateSandboxForRepositoryOutput,
@@ -336,6 +338,21 @@ class TestProcessTaskWorkflowUnit:
assert workflow._should_forward_pending_user_message() is expected
+ @pytest.mark.parametrize(
+ "payload, expected_prewarmed",
+ [
+ ({"run_id": "r1"}, False),
+ ({"run_id": "r1", "prewarmed": False}, False),
+ ({"run_id": "r1", "prewarmed": True}, True),
+ ],
+ )
+ def test_parse_inputs_reads_prewarmed(self, payload: dict, expected_prewarmed: bool):
+ parsed = ProcessTaskWorkflow.parse_inputs([json.dumps(payload)])
+ assert parsed.prewarmed is expected_prewarmed
+
+ def test_warm_idle_timeout_is_shorter_than_active_inactivity(self):
+ assert WARM_IDLE_TIMEOUT < timedelta(seconds=INACTIVITY_TIMEOUT_USER_SECONDS)
+
async def test_run_cleans_up_sandbox_when_provisioning_fails_after_creation(self, monkeypatch):
workflow = ProcessTaskWorkflow()
get_task_processing_context_mock = AsyncMock(return_value=_build_context(github_integration_id=123))
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 4f18fde02184..1060cacc6bd0 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -58,6 +58,7 @@ class ProcessTaskInput:
create_pr: bool = True
slack_thread_context: Optional[dict[str, Any]] = None
posthog_mcp_scopes: PosthogMcpScopes = "read_only"
+ prewarmed: bool = False
@dataclass
@@ -95,6 +96,7 @@ from products.tasks.backend.temporal.constants import ( # noqa: E402
MAX_CI_REPETITIONS,
PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,
RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
+ WARM_IDLE_TIMEOUT,
)
# Rolling-deploy deprecation bundle (TODO slug: tasks-ci-follow-up-pr-context-cleanup)
@@ -147,6 +149,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._completion_status: str = "completed"
self._completion_error: Optional[str] = None
self._heartbeat_received: bool = False
+ self._prewarmed: bool = False
+ self._first_user_message_received: bool = False
self._pending_followup: PendingFollowup | None = None
self._pending_followups: list[PendingFollowup] = []
self._ci_repetitions: int = 0
@@ -175,6 +179,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
create_pr=loaded.get("create_pr", True),
slack_thread_context=loaded.get("slack_thread_context"),
posthog_mcp_scopes=loaded.get("posthog_mcp_scopes", "read_only"),
+ prewarmed=loaded.get("prewarmed", False),
)
@staticmethod
@@ -236,8 +241,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):
return TaskEvent.CI_FOLLOW_UP
async def _wait_for_event(self) -> TaskEvent:
+ warm_idle = self._prewarmed and not self._first_user_message_received
+
ci_follow_up_scheduled = (
- self._context is not None
+ not warm_idle
+ and self._context is not None
and self._context.create_pr
and self._context.pr_loop_enabled
and self._ci_repetitions < MAX_CI_REPETITIONS
@@ -251,11 +259,12 @@ class ProcessTaskWorkflow(PostHogWorkflow):
testing_override_active = bool(settings.TASKS_INACTIVITY_TIMEOUT_SECONDS) and (
base_timeout < ci_follow_up_floor
)
- inactivity_timeout = (
- max(base_timeout, ci_follow_up_floor)
- if ci_follow_up_scheduled and not testing_override_active
- else base_timeout
- )
+ if warm_idle:
+ inactivity_timeout = min(WARM_IDLE_TIMEOUT, base_timeout)
+ elif ci_follow_up_scheduled and not testing_override_active:
+ inactivity_timeout = max(base_timeout, ci_follow_up_floor)
+ else:
+ inactivity_timeout = base_timeout
possible_events: list[asyncio.Task[TaskEvent]] = [
asyncio.create_task(self._wait_for_task_external_event()),
asyncio.create_task(self._wait_for_inactivity(inactivity_timeout)),
@@ -371,6 +380,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
run_id = input.run_id
self._sandbox_id_for_cleanup = None
self._slack_thread_context = input.slack_thread_context
+ self._prewarmed = input.prewarmed
credential_refresh_task: asyncio.Task[None] | None = None
try:
self._context = await self._get_task_processing_context(input)
@@ -483,6 +493,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
else:
pending_followup = self._pending_followups.pop(0)
self._last_active_time = workflow.now()
+ self._first_user_message_received = True
message = pending_followup.message
artifact_ids = pending_followup.artifact_ids
if self._should_skip_followup(message, artifact_ids):
diff --git a/products/tasks/backend/tests/test_cold_run_path_after_prewarm_removal.py b/products/tasks/backend/tests/test_cold_run_path_after_prewarm_removal.py
new file mode 100644
index 000000000000..5ec2ce6b8739
--- /dev/null
+++ b/products/tasks/backend/tests/test_cold_run_path_after_prewarm_removal.py
@@ -0,0 +1,64 @@
+"""Regression guard for the bare-sandbox prewarm removal.
+
+Agent warming (an idling Run via SandboxWarmer) replaced the bare-sandbox prewarm. After that
+removal there must be exactly one provisioning path: the cold path that boots a fresh sandbox, then
+clones and checks out. These tests fail closed if any prewarm artifact creeps back — a lingering
+``prewarmed_sandbox_id`` field, a leased-box branch in the provision activity, or the deleted
+prewarm modules being reintroduced.
+"""
+
+import inspect
+import importlib
+import dataclasses
+
+from django.test import SimpleTestCase
+
+from products.tasks.backend.temporal.process_task import workflow as workflow_module
+from products.tasks.backend.temporal.process_task.activities import provision_sandbox
+
+PREWARM_TOKENS = ("prewarmed_sandbox_id", "prewarmed_sandbox", "seeded_env", "lease_prewarmed")
+
+
+class TestPrewarmArtifactsRemoved(SimpleTestCase):
+ def test_prewarm_modules_are_gone(self):
+ for module_path in (
+ "products.tasks.backend.logic.services.prewarmed_sandbox",
+ "products.tasks.backend.temporal.prewarm_sandbox",
+ ):
+ with self.assertRaises(ModuleNotFoundError, msg=f"{module_path} should have been removed"):
+ importlib.import_module(module_path)
+
+ def test_process_task_input_has_no_prewarm_field(self):
+ field_names = {f.name for f in dataclasses.fields(workflow_module.ProcessTaskInput)}
+ assert "prewarmed_sandbox_id" not in field_names
+ assert not (field_names & set(PREWARM_TOKENS))
+
+ def test_cold_provision_input_types_have_no_prewarm_field(self):
+ for input_cls in (
+ provision_sandbox.CreateSandboxForRepositoryInput,
+ provision_sandbox.CloneRepositoryInSandboxInput,
+ provision_sandbox.CheckoutBranchInSandboxInput,
+ ):
+ field_names = {f.name for f in dataclasses.fields(input_cls)}
+ assert not (field_names & set(PREWARM_TOKENS)), f"{input_cls.__name__} still references a prewarm field"
+
+
+class TestColdProvisionPathIntact(SimpleTestCase):
+ def test_create_activity_cold_creates_via_sandbox_create(self):
+ source = inspect.getsource(provision_sandbox.create_sandbox_for_repository)
+ assert "Sandbox.create(config)" in source
+ for token in PREWARM_TOKENS:
+ assert token not in source, f"create_sandbox_for_repository still references {token}"
+
+ def test_workflow_runs_create_then_clone_then_checkout(self):
+ source = inspect.getsource(workflow_module.ProcessTaskWorkflow._get_sandbox_for_repository)
+ create_at = source.index("create_sandbox_for_repository,")
+ clone_at = source.index("clone_repository_in_sandbox,")
+ checkout_at = source.index("checkout_branch_in_sandbox,")
+ assert create_at < clone_at < checkout_at
+
+ def test_no_prewarm_references_in_provision_or_workflow_source(self):
+ for module in (provision_sandbox, workflow_module):
+ source = inspect.getsource(module)
+ for token in PREWARM_TOKENS:
+ assert token not in source, f"{module.__name__} still references {token}"
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
new file mode 100644
index 000000000000..3d35bc22e430
--- /dev/null
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -0,0 +1,301 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework.exceptions import PermissionDenied, Throttled
+
+from posthog.exceptions import QuotaLimitExceeded
+from posthog.models import Integration, User
+
+from products.tasks.backend.facade import (
+ api as facade,
+ contracts,
+)
+from products.tasks.backend.logic.services.warm import WarmResult
+from products.tasks.backend.models import Task, TaskRun
+
+FACADE = "products.tasks.backend.facade.api"
+WARM_SRC = "products.tasks.backend.logic.services.warm.SandboxWarmer"
+TITLE_SRC = "products.tasks.backend.logic.services.title_generator"
+
+
+class TestWarmTaskSandbox(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.integration = Integration.objects.create(team=self.team, kind="github", config={})
+
+ def _warm(self, **overrides):
+ kwargs: dict[str, Any] = {
+ "team_id": self.team.id,
+ "user_id": self.user.id,
+ "repository": "posthog/posthog",
+ "github_integration_id": self.integration.id,
+ "branch": "main",
+ }
+ kwargs.update(overrides)
+ return facade.warm_task_sandbox(**kwargs)
+
+ def test_births_draft_task_and_returns_warm_dto(self):
+ def fake_warm(self_warmer, **kwargs):
+ run = self_warmer.task.create_run(mode="interactive", extra_state={"await_user_message": True})
+ return WarmResult(run=run, just_created=True)
+
+ with patch(f"{WARM_SRC}.warm", autospec=True, side_effect=fake_warm):
+ result = self._warm()
+
+ assert isinstance(result, contracts.WarmTaskDTO)
+ task = Task.objects.get(id=result.task_id)
+ assert task.origin_product == Task.OriginProduct.USER_CREATED
+ assert task.created_by_id == self.user.id
+ assert task.repository == "posthog/posthog"
+ assert task.github_integration_id == self.integration.id
+ assert task.description == ""
+ assert task.runs.filter(id=result.run_id).exists()
+
+ def test_returns_none_and_soft_deletes_draft_when_capped(self):
+ with patch(f"{WARM_SRC}.warm", side_effect=Throttled()):
+ result = self._warm()
+
+ assert result is None
+ task = Task.objects.get(team=self.team)
+ assert task.deleted is True
+
+ def test_returns_none_when_quota_exceeded(self):
+ with patch(f"{WARM_SRC}.warm", side_effect=QuotaLimitExceeded("over")):
+ result = self._warm()
+ assert result is None
+ assert Task.objects.get(team=self.team).deleted is True
+
+ def test_returns_none_when_product_not_enabled(self):
+ with patch(f"{WARM_SRC}.warm", side_effect=PermissionDenied()):
+ result = self._warm()
+ assert result is None
+ assert Task.objects.get(team=self.team).deleted is True
+
+ def test_returns_none_when_github_integration_missing(self):
+ with patch(f"{WARM_SRC}.warm") as m_warm:
+ result = self._warm(github_integration_id=self.integration.id + 9999)
+ assert result is None
+ m_warm.assert_not_called()
+ assert not Task.objects.filter(team=self.team).exists()
+
+ def test_dedups_an_existing_idling_warm_for_the_same_selection(self):
+ def fake_warm(self_warmer, **kwargs):
+ run = self_warmer.task.create_run(
+ mode="interactive", extra_state={"await_user_message": True, "branch": "main"}, branch="main"
+ )
+ return WarmResult(run=run, just_created=True)
+
+ with patch(f"{WARM_SRC}.warm", autospec=True, side_effect=fake_warm) as m_warm:
+ first = self._warm()
+ second = self._warm()
+
+ assert first is not None and second is not None
+ assert second.run_id == first.run_id
+ assert second.task_id == first.task_id
+ m_warm.assert_called_once()
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 1
+
+ def test_does_not_dedup_across_a_different_branch(self):
+ def fake_warm(self_warmer, **kwargs):
+ branch = (kwargs.get("extra_state") or {}).get("branch")
+ run = self_warmer.task.create_run(
+ mode="interactive", extra_state={"await_user_message": True, "branch": branch}, branch=branch
+ )
+ return WarmResult(run=run, just_created=True)
+
+ with patch(f"{WARM_SRC}.warm", autospec=True, side_effect=fake_warm) as m_warm:
+ first = self._warm(branch="main")
+ second = self._warm(branch="feature/x")
+
+ assert first is not None and second is not None
+ assert second.run_id != first.run_id
+ assert m_warm.call_count == 2
+
+
+class TestCreateTaskWarmReuse(APIBaseTest):
+ """The normal create path reuses a matching idling warm Run instead of minting a cold Task."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.integration = Integration.objects.create(team=self.team, kind="github", config={})
+
+ def _warm_run(self, *, repository="posthog/posthog", branch="main", created_by=None) -> tuple[Task, TaskRun]:
+ task = Task.objects.create(
+ team=self.team,
+ title="",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=created_by or self.user,
+ repository=repository,
+ github_integration=self.integration,
+ )
+ run = task.create_run(
+ mode="interactive", extra_state={"await_user_message": True, "branch": branch}, branch=branch
+ )
+ return task, run
+
+ def _create(self, **data):
+ validated = {"description": "fix the bug", "repository": "posthog/posthog", "branch": "main"}
+ validated.update(data)
+ return facade.create_task(self.team.id, self.user.id, validated_data=validated)
+
+ def test_reuses_matching_warm_task_and_activates_it_in_place(self):
+ warm_task, run = self._warm_run()
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True) as m_signal:
+ dto = self._create()
+
+ assert str(dto.id) == str(warm_task.id)
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 1
+ warm_task.refresh_from_db()
+ run.refresh_from_db()
+ assert warm_task.description == "fix the bug"
+ assert warm_task.title
+ m_signal.assert_called_once()
+ _, kwargs = m_signal.call_args
+ assert kwargs["content"] == "fix the bug"
+ assert "await_user_message" not in run.state
+
+ def test_does_not_overwrite_existing_warm_description(self):
+ warm_task, _ = self._warm_run()
+ warm_task.description = "already there"
+ warm_task.save(update_fields=["description"])
+
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True):
+ self._create(description="new prompt")
+ warm_task.refresh_from_db()
+ assert warm_task.description == "already there"
+
+ def test_branch_mismatch_creates_a_new_cold_task(self):
+ warm_task, _ = self._warm_run(branch="main")
+ with patch(f"{TITLE_SRC}.generate_task_title", return_value="T"):
+ dto = self._create(branch="feature/x")
+
+ assert str(dto.id) != str(warm_task.id)
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 2
+
+ def test_terminal_warm_run_is_not_reused(self):
+ warm_task, run = self._warm_run()
+ run.status = TaskRun.Status.COMPLETED
+ run.save(update_fields=["status"])
+ with patch(f"{TITLE_SRC}.generate_task_title", return_value="T"):
+ dto = self._create()
+
+ assert str(dto.id) != str(warm_task.id)
+
+ def test_local_submit_without_branch_key_never_reuses_a_warm(self):
+ warm_task, _ = self._warm_run(branch=None)
+ with patch(f"{TITLE_SRC}.generate_task_title", return_value="T"):
+ dto = facade.create_task(
+ self.team.id,
+ self.user.id,
+ validated_data={"description": "local task", "repository": "posthog/posthog"},
+ )
+
+ assert str(dto.id) != str(warm_task.id)
+ assert Task.objects.filter(team=self.team, deleted=False).count() == 2
+
+
+class TestRunTaskWarmActivation(APIBaseTest):
+ """The normal run path activates an idling warm Run instead of dispatching a fresh workflow."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.integration = Integration.objects.create(team=self.team, kind="github", config={})
+
+ def _warm_run(self, *, branch="main") -> tuple[Task, TaskRun]:
+ task = Task.objects.create(
+ team=self.team,
+ title="",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=self.user,
+ repository="posthog/posthog",
+ github_integration=self.integration,
+ )
+ run = task.create_run(
+ mode="interactive", extra_state={"await_user_message": True, "branch": branch}, branch=branch
+ )
+ return task, run
+
+ def test_activates_idling_warm_run_without_creating_a_new_run(self):
+ task, run = self._warm_run()
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True) as m_signal:
+ result = facade.run_task(
+ task.id,
+ self.team.id,
+ self.user.id,
+ validated_data={"mode": "interactive", "branch": "main", "pending_user_message": "do the thing"},
+ )
+
+ assert result is not None and result.error is None
+ assert task.runs.count() == 1
+ m_signal.assert_called_once()
+ _, kwargs = m_signal.call_args
+ assert kwargs["content"] == "do the thing"
+ run.refresh_from_db()
+ assert "await_user_message" not in run.state
+
+ def test_falls_back_to_description_when_no_pending_message(self):
+ task, run = self._warm_run()
+ task.description = "from description"
+ task.save(update_fields=["description"])
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True) as m_signal:
+ facade.run_task(
+ task.id, self.team.id, self.user.id, validated_data={"mode": "interactive", "branch": "main"}
+ )
+
+ _, kwargs = m_signal.call_args
+ assert kwargs["content"] == "from description"
+
+ def test_branch_mismatch_does_not_activate_warm_run(self):
+ # Requesting a different branch than the warm Run was provisioned on must NOT activate it
+ # (it would work the wrong branch); fall through to the cold path instead.
+ task, run = self._warm_run(branch="main")
+ with (
+ patch(f"{FACADE}.signal_task_run_user_message") as m_signal,
+ patch(f"{FACADE}._trigger_task_processing_workflow") as m_trigger,
+ ):
+ facade.run_task(
+ task.id,
+ self.team.id,
+ self.user.id,
+ validated_data={"mode": "interactive", "branch": "feature/x", "pending_user_message": "do it"},
+ )
+
+ m_signal.assert_not_called()
+ m_trigger.assert_called_once() # cold path: a fresh run was created + dispatched
+ assert task.runs.count() == 2
+ run.refresh_from_db()
+ assert run.state.get("await_user_message") is True # warm run untouched
+
+ def test_explicit_resume_does_not_trigger_warm_activation(self):
+ task, run = self._warm_run()
+ with patch(f"{FACADE}.signal_task_run_user_message") as m_signal:
+ facade.run_task(
+ task.id,
+ self.team.id,
+ self.user.id,
+ validated_data={"mode": "interactive", "resume_from_run_id": str(run.id)},
+ )
+ m_signal.assert_not_called()
+
+ def test_other_team_member_cannot_activate_a_users_warm_run(self):
+ # A USER_CREATED warm run is private to its creator. The task-visibility gate in run_task
+ # must block a different team member before activation, so they cannot push the first message
+ # into another user's already-running, credential-bearing warm sandbox.
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ task, run = self._warm_run(branch="main")
+ with patch(f"{FACADE}.signal_task_run_user_message") as m_signal:
+ result = facade.run_task(
+ task.id,
+ self.team.id,
+ other.id,
+ validated_data={"mode": "interactive", "branch": "main", "pending_user_message": "do it"},
+ )
+
+ assert result is None # task not visible -> 404, no activation
+ m_signal.assert_not_called()
+ run.refresh_from_db()
+ assert run.state.get("await_user_message") is True # warm run untouched
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 8a8514a6a068..053e0511dd09 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -458,6 +458,12 @@ export interface TaskWriteApi {
* @nullable
*/
ci_prompt?: string | null
+ /**
+ * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * @maxLength 255
+ * @nullable
+ */
+ branch?: string | null
}
/**
@@ -524,6 +530,12 @@ export interface PatchedTaskWriteApi {
* @nullable
*/
ci_prompt?: string | null
+ /**
+ * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * @maxLength 255
+ * @nullable
+ */
+ branch?: string | null
}
/**
@@ -1855,6 +1867,40 @@ export interface PaginatedTaskSummaryDTOListApi {
results: TaskSummaryDTOApi[]
}
+/**
+ * Request body for warming a full idling Run while composing a Code-app cloud task.
+ *
+ * Collection-level: no task exists yet at typing time. The warmer births a draft Task and an
+ * interactive Run that boots, clones, checks out `branch`, and starts the agent, then idles awaiting
+ * the first message. `github_integration` is a plain integration PK (an integer); the view re-scopes
+ * it to the caller's team before use.
+ */
+export interface WarmTaskRequestApi {
+ /**
+ * Target GitHub repository to clone, in `organization/repo` format (e.g. `posthog/posthog`).
+ * @maxLength 255
+ */
+ repository: string
+ /** Primary key of the team's GitHub integration to clone with. */
+ github_integration: number
+ /**
+ * Branch to check out in the warm sandbox. Defaults to the repository's default branch when omitted.
+ * @maxLength 255
+ * @nullable
+ */
+ branch?: string | null
+}
+
+/**
+ * Response for a successful warm request — the draft Task + idling warm Run reused on submit.
+ */
+export interface WarmTaskResponseApi {
+ /** Id of the draft Task birthed for the warm Run. */
+ task_id: string
+ /** Id of the idling warm Run. The normal create+run path reuses and activates it on submit. */
+ run_id: string
+}
+
export type SandboxListParams = {
/**
* Number of results to return per page.
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 698b8de5f147..13210350c8ca 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -63,6 +63,8 @@ import type {
TasksRunsStreamRetrieveParams,
TasksSlackThreadContextRetrieveParams,
TasksSummariesCreateParams,
+ WarmTaskRequestApi,
+ WarmTaskResponseApi,
} from './api.schemas'
export const getCodeInvitesCheckAccessRetrieveUrl = () => {
@@ -1152,3 +1154,24 @@ export const tasksSummariesCreate = async (
body: JSON.stringify(taskSummariesRequestApi),
})
}
+
+export const getTasksWarmCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/tasks/warm/`
+}
+
+/**
+ * Warm a full idling Run for a Code-app cloud task while the user composes: boot a sandbox, clone the repo, check out the branch, and start the agent, then idle awaiting the first message. On submit the normal create+run path transparently reuses and activates this Run; abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't belong to the team.
+ * @summary Warm a task sandbox
+ */
+export const tasksWarmCreate = async (
+ projectId: string,
+ warmTaskRequestApi: WarmTaskRequestApi,
+ options?: RequestInit
+): Promise<WarmTaskResponseApi> => {
+ return apiMutator<WarmTaskResponseApi>(getTasksWarmCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(warmTaskRequestApi),
+ })
+}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 2e2d7c65f48f..2694bdb0be4c 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -229,6 +229,8 @@ export const tasksCreateBodyTitleMax = 255
export const tasksCreateBodyRepositoryMax = 255
+export const tasksCreateBodyBranchMax = 255
+
export const TasksCreateBody = /* @__PURE__ */ zod
.object({
title: zod
@@ -290,6 +292,13 @@ export const TasksCreateBody = /* @__PURE__ */ zod
.string()
.nullish()
.describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
+ branch: zod
+ .string()
+ .max(tasksCreateBodyBranchMax)
+ .nullish()
+ .describe(
+ 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'
+ ),
})
.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.'
@@ -302,6 +311,8 @@ export const tasksUpdateBodyTitleMax = 255
export const tasksUpdateBodyRepositoryMax = 255
+export const tasksUpdateBodyBranchMax = 255
+
export const TasksUpdateBody = /* @__PURE__ */ zod
.object({
title: zod
@@ -363,6 +374,13 @@ export const TasksUpdateBody = /* @__PURE__ */ zod
.string()
.nullish()
.describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
+ branch: zod
+ .string()
+ .max(tasksUpdateBodyBranchMax)
+ .nullish()
+ .describe(
+ 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'
+ ),
})
.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.'
@@ -375,6 +393,8 @@ export const tasksPartialUpdateBodyTitleMax = 255
export const tasksPartialUpdateBodyRepositoryMax = 255
+export const tasksPartialUpdateBodyBranchMax = 255
+
export const TasksPartialUpdateBody = /* @__PURE__ */ zod
.object({
title: zod
@@ -436,6 +456,13 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
.string()
.nullish()
.describe('Custom prompt for CI fixes. If blank, a default prompt will be used.'),
+ branch: zod
+ .string()
+ .max(tasksPartialUpdateBodyBranchMax)
+ .nullish()
+ .describe(
+ 'Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.'
+ ),
})
.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.'
@@ -1164,3 +1191,30 @@ export const TasksSummariesCreateBody = /* @__PURE__ */ zod.object({
'Task IDs to fetch summaries for (max 5000). Response is paginated; follow the `next` cursor to retrieve all results.'
),
})
+
+/**
+ * Warm a full idling Run for a Code-app cloud task while the user composes: boot a sandbox, clone the repo, check out the branch, and start the agent, then idle awaiting the first message. On submit the normal create+run path transparently reuses and activates this Run; abandoned warms are reaped by the Run's inactivity timeout. Best-effort: returns an empty body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't belong to the team.
+ * @summary Warm a task sandbox
+ */
+export const tasksWarmCreateBodyRepositoryMax = 255
+
+export const tasksWarmCreateBodyBranchMax = 255
+
+export const TasksWarmCreateBody = /* @__PURE__ */ zod
+ .object({
+ repository: zod
+ .string()
+ .max(tasksWarmCreateBodyRepositoryMax)
+ .describe('Target GitHub repository to clone, in `organization\/repo` format (e.g. `posthog\/posthog`).'),
+ github_integration: zod.number().describe("Primary key of the team's GitHub integration to clone with."),
+ branch: zod
+ .string()
+ .max(tasksWarmCreateBodyBranchMax)
+ .nullish()
+ .describe(
+ "Branch to check out in the warm sandbox. Defaults to the repository's default branch when omitted."
+ ),
+ })
+ .describe(
+ "Request body for warming a full idling Run while composing a Code-app cloud task.\n\nCollection-level: no task exists yet at typing time. The warmer births a draft Task and an\ninteractive Run that boots, clones, checks out `branch`, and starts the agent, then idles awaiting\nthe first message. `github_integration` is a plain integration PK (an integer); the view re-scopes\nit to the caller's team before use."
+ )
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index edbe24323e9e..82b782523c70 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -252,3 +252,6 @@ tools:
tasks-update:
operation: tasks_update
enabled: false
+ tasks-warm-create:
+ operation: tasks_warm_create
+ enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 53fe3f668702..19fff8f64148 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40293,6 +40293,12 @@ export namespace Schemas {
* @nullable
*/
ci_prompt?: string | null;
+ /**
+ * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * @maxLength 255
+ * @nullable
+ */
+ branch?: string | null;
}
export type PatchedTeamDefaultModifiers = { [key: string]: unknown };
@@ -49696,6 +49702,12 @@ export namespace Schemas {
* @nullable
*/
ci_prompt?: string | null;
+ /**
+ * Branch the user has selected for this cloud task. Write-only and not persisted on the task itself: used only to reuse a matching pre-warmed sandbox Run on creation (the branch is otherwise carried on the run). Omit to match a warm Run on the default branch.
+ * @maxLength 255
+ * @nullable
+ */
+ branch?: string | null;
}
export type TeamDefaultModifiers = { [key: string]: unknown };
@@ -50534,6 +50546,40 @@ export namespace Schemas {
table_suffix: string | null;
}
+ /**
+ * Request body for warming a full idling Run while composing a Code-app cloud task.
+ *
+ * Collection-level: no task exists yet at typing time. The warmer births a draft Task and an
+ * interactive Run that boots, clones, checks out `branch`, and starts the agent, then idles awaiting
+ * the first message. `github_integration` is a plain integration PK (an integer); the view re-scopes
+ * it to the caller's team before use.
+ */
+ export interface WarmTaskRequest {
+ /**
+ * Target GitHub repository to clone, in `organization/repo` format (e.g. `posthog/posthog`).
+ * @maxLength 255
+ */
+ repository: string;
+ /** Primary key of the team's GitHub integration to clone with. */
+ github_integration: number;
+ /**
+ * Branch to check out in the warm sandbox. Defaults to the repository's default branch when omitted.
+ * @maxLength 255
+ * @nullable
+ */
+ branch?: string | null;
+ }
+
+ /**
+ * Response for a successful warm request — the draft Task + idling warm Run reused on submit.
+ */
+ export interface WarmTaskResponse {
+ /** Id of the draft Task birthed for the warm Run. */
+ task_id: string;
+ /** Id of the idling warm Run. The normal create+run path reuses and activates it on submit. */
+ run_id: string;
+ }
+
export interface WeeklyDigestResponse {
/** Unique visitors. */
visitors: NumericMetric;