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): schedule one-off runs through API and MCP (#103087)

Oliver Browne28996ca793fa
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 1ceba692be27..2033e58347c3 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -601,6 +601,7 @@ def _task_run_detail_to_dto(
updated_at=run.updated_at,
completed_at=run.completed_at,
preview_available=task_run_preview_ready(run.state),
+ scheduled_at=run.scheduled_at,
)
@@ -2805,7 +2806,7 @@ def signal_workflow_completion(run_id: str | UUID, status: str, error_message: s
)
run = TaskRun.objects.filter(pk=run_id).first()
- if run is None:
+ if run is None or (run.scheduled_at is not None and run.queued_at is None):
return
try:
client = sync_connect()
@@ -3024,6 +3025,7 @@ def update_task_run(
*,
validated_data: dict,
only_if_non_terminal: bool = False,
+ only_if_not_started: bool = False,
caller_is_agent: bool = False,
) -> contracts.TaskRunDetailDTO | None:
"""Apply a PATCH to a run: merge output/state, set completion, then dispatch side effects.
@@ -3085,8 +3087,16 @@ def update_task_run(
update_fields: set[str] = set()
with transaction.atomic():
- if has_output_merge or has_state_mutation or only_if_non_terminal or "status" in validated_data:
+ if (
+ has_output_merge
+ or has_state_mutation
+ or only_if_non_terminal
+ or only_if_not_started
+ or "status" in validated_data
+ ):
run = TaskRun.objects.select_for_update().get(pk=run.pk)
+ if only_if_not_started and run.status != TaskRun.Status.NOT_STARTED:
+ return None
if only_if_non_terminal and run.is_terminal:
if validated_data.get("status") == run.status:
transaction.on_commit(lambda: resume_workflow_step_for_run(run))
@@ -3142,6 +3152,10 @@ def update_task_run(
update_fields.add("state")
new_status = validated_data.get("status")
+ if only_if_not_started and new_status == TaskRun.Status.CANCELLED:
+ # A dormant run has no workflow to complete its stream after cancellation.
+ run.state = {**(run.state or {}), "cancel_fallback_cleanup_complete": True}
+ update_fields.add("state")
if (
caller_is_agent
and new_status == TaskRun.Status.COMPLETED
@@ -5419,16 +5433,15 @@ def _trigger_task_processing_workflow(
enqueue_or_start_workflow,
)
from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
- RunSource,
+ mcp_scopes_for_run_source,
parse_run_state,
)
from products.tasks.backend.temporal.process_task.workflow import PendingFollowup # noqa: PLC0415
# SIGNAL_REPORT: implementation runs log their work on the report (notes, code references)
# via the task:write artefact tools.
- full_mcp_run_sources = frozenset({None, RunSource.MANUAL, RunSource.SIGNAL_REPORT})
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"
+ posthog_mcp_scopes = mcp_scopes_for_run_source(run_source)
try:
logger.info("Attempting to trigger task processing workflow for task %s, run %s", task.id, run.id)
message = None
@@ -6520,6 +6533,7 @@ def create_task(
pending_user_message = (validated_data.pop("pending_user_message", None) or "").strip() or None
pending_user_artifact_ids = validated_data.pop("pending_user_artifact_ids", None) or []
warm_auto_publish = validated_data.pop("auto_publish", None)
+ validated_data.pop("scheduled_at", None)
# Names the task from the pasted content while `description` stays the bare prompt. Write-only,
# never persisted, so it must be popped before `Task.objects.create(**validated_data)`.
naming_source = (validated_data.pop("naming_source", None) or "").strip() or None
@@ -7396,12 +7410,16 @@ def _attach_staged_artifacts_to_run(
storage_path = str(staged_artifact["storage_path"])
if _find_artifact_manifest_entry(manifest, str(staged_artifact.get("id")), storage_path):
continue
- tag_task_artifact(storage_path, ttl_days=RUN_ARTIFACT_TTL_DAYS, team_id=task.team_id)
+ # Scheduled attachments are tagged before the run-creation transaction takes its locks.
+ if run.scheduled_at is None:
+ tag_task_artifact(storage_path, ttl_days=RUN_ARTIFACT_TTL_DAYS, team_id=task.team_id)
manifest.append(dict(staged_artifact))
_save_artifact_manifest(run, manifest)
- get_tasks_cache().delete_many(
- [build_task_staged_artifact_cache_key(str(task.id), artifact_id) for artifact_id in artifact_ids]
- )
+ cache_keys = [build_task_staged_artifact_cache_key(str(task.id), artifact_id) for artifact_id in artifact_ids]
+ if run.scheduled_at is not None:
+ transaction.on_commit(lambda: get_tasks_cache().delete_many(cache_keys), robust=True)
+ else:
+ get_tasks_cache().delete_many(cache_keys)
REPORT_WARM_RUN_NOT_ACTIVATED = "This sandbox is waiting for the report's Ask AI question. Send it from the report."
@@ -8000,8 +8018,11 @@ def run_task(
is_report_implementation_task,
)
from products.tasks.backend.logic.services.staged_artifacts import ( # noqa: PLC0415
+ RUN_ARTIFACT_TTL_DAYS,
get_task_run_artifacts_by_id,
get_task_staged_artifacts,
+ staged_artifacts_expire_by,
+ tag_task_artifact,
)
from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
PrAuthorshipMode,
@@ -8009,6 +8030,7 @@ def run_task(
cache_github_user_token,
get_provider_for_runtime_adapter,
get_reasoning_effort_error,
+ mcp_scopes_for_run_source,
parse_run_state,
)
@@ -8051,6 +8073,7 @@ def run_task(
)
mode = validated_data.get("mode", "background")
run_source = validated_data.get("run_source")
+ scheduled_at = validated_data.get("scheduled_at")
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")
@@ -8115,7 +8138,16 @@ def run_task(
if claude_model_access is None and previous_state is not None:
claude_model_access = previous_state.claude_model_access
- warm_run = None if run_source == RunSource.AGENT else _idling_warm_run_for_task(task)
+ if scheduled_at is not None and claude_model_access == "own-subscription":
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind="validation_error",
+ code="invalid_input",
+ detail="Scheduled runs must use the PostHog gateway.",
+ attr="claude_model_access",
+ )
+ )
+ warm_run = None if scheduled_at is not None or run_source == RunSource.AGENT else _idling_warm_run_for_task(task)
if warm_run is not None and claude_model_access == "own-subscription":
warm_run = None
if warm_run is not None:
@@ -8435,14 +8467,43 @@ def run_task(
)
)
+ if scheduled_at is not None and staged_artifacts_expire_by(staged_artifacts, scheduled_at):
+ return contracts.TaskRunResult(
+ error=contracts.TaskValidationError(
+ kind="validation_error",
+ code="invalid_input",
+ detail="The attached files expire before this run can start. Choose an earlier time or upload new files.",
+ attr="scheduled_at",
+ )
+ )
+
logger.info("Creating task run for task %s with mode=%s, branch=%s", task.id, mode, branch)
+ if scheduled_at is not None:
+ for staged_artifact in staged_artifacts:
+ tag_task_artifact(
+ str(staged_artifact["storage_path"]),
+ ttl_days=RUN_ARTIFACT_TTL_DAYS,
+ team_id=task.team_id,
+ raise_on_error=True,
+ )
+ extra_state["pending_dispatch"] = {
+ "user_id": user_id,
+ "create_pr": True,
+ "posthog_mcp_scopes": mcp_scopes_for_run_source(run_source),
+ }
try:
with transaction.atomic():
- task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state, acting_user_id=user_id)
+ task_run = task.create_run(
+ mode=mode, branch=branch, extra_state=extra_state, acting_user_id=user_id, scheduled_at=scheduled_at
+ )
if report_id_for_slot_check is not None:
enforce_report_implementation_rerun_cap(
team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)
)
+ if scheduled_at is not None and pending_user_artifact_ids:
+ _attach_staged_artifacts_to_run(
+ task_run, task, staged_artifacts=staged_artifacts, artifact_ids=pending_user_artifact_ids
+ )
except InvalidTaskOriginError as error:
return contracts.TaskRunResult(
error=contracts.TaskValidationError(
@@ -8467,7 +8528,7 @@ def run_task(
update_fields.append("relayed_mcp_servers")
task_run.save(update_fields=update_fields)
- if pending_user_artifact_ids:
+ if pending_user_artifact_ids and scheduled_at is None:
_attach_staged_artifacts_to_run(
task_run, task, staged_artifacts=staged_artifacts, artifact_ids=pending_user_artifact_ids
)
@@ -8475,6 +8536,11 @@ def run_task(
if github_user_token and pr_authorship_mode == PrAuthorshipMode.USER:
cache_github_user_token(str(task_run.id), github_user_token)
+ if scheduled_at is not None:
+ return contracts.TaskRunResult(
+ task=_task_detail_to_dto(task, latest_run=task_run, include_latest_run_log_url=False)
+ )
+
logger.info("Triggering workflow for task %s, run %s", task.id, task_run.id)
if is_pi_task:
initial_message = (
diff --git a/products/tasks/backend/facade/cancellation.py b/products/tasks/backend/facade/cancellation.py
index 82549fda56a3..dd76641142ce 100644
--- a/products/tasks/backend/facade/cancellation.py
+++ b/products/tasks/backend/facade/cancellation.py
@@ -88,7 +88,7 @@ def _publish_cancel_fallback_completion(run: TaskRun) -> bool:
publish_run_stream_completion(str(run.id))
TaskRun.update_state_atomic(run.id, updates={"cancel_fallback_cleanup_complete": False})
except Exception:
- logger.warning("Failed to complete stream for workflow-gone run %s", run.id, exc_info=True)
+ logger.warning("Failed to complete stream for cancelled run %s", run.id, exc_info=True)
return False
return True
@@ -127,6 +127,18 @@ def cancel_task_run(
status_at_request = run.status
error_message = (reason or "").strip()[:500] or "Stopped by user"
+ def capture_cancel_request(task_run: TaskRun, signal_outcome: str) -> None:
+ task_run.capture_event(
+ "task_run_cancel_requested",
+ {
+ "cancel_source": source,
+ "cancel_reason": error_message,
+ "requested_by_user_id": requested_by_user_id,
+ "workflow_signal_outcome": signal_outcome,
+ "status_at_request": status_at_request,
+ },
+ )
+
marker: dict[str, Any] = {
"cancel_requested_at": django_timezone.now().isoformat(),
"cancel_source": source,
@@ -154,6 +166,28 @@ def cancel_task_run(
if only_if_awaiting_first_message:
return "unavailable", tasks_api._task_run_detail_to_dto(run)
+ if run.scheduled_at is not None and run.status == TaskRun.Status.NOT_STARTED:
+ dto = tasks_api.update_task_run(
+ run.id,
+ task_id,
+ team_id,
+ validated_data={"status": TaskRun.Status.CANCELLED, "error_message": error_message},
+ only_if_not_started=True,
+ )
+ if dto is not None:
+ capture_cancel_request(run, "not_needed")
+ run.refresh_from_db(fields=["state"])
+ if not _publish_cancel_fallback_completion(run):
+ return "unavailable", dto
+ return "accepted", dto
+ run = tasks_api._get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return "not_found", None
+ if run.is_terminal:
+ if not _publish_cancel_fallback_completion(run):
+ return "unavailable", tasks_api._task_run_detail_to_dto(run)
+ return "already_terminal", tasks_api._task_run_detail_to_dto(run)
+
_interrupt_agent_turn(run, requested_by_user_id, requested_by_distinct_id)
signal_outcome = _signal_complete_task(run, TaskRun.Status.CANCELLED, error_message)
@@ -185,14 +219,5 @@ def cancel_task_run(
push_dispatcher.notify_task_run_cancelled(run)
dto = tasks_api._task_run_detail_to_dto(run)
- run.capture_event(
- "task_run_cancel_requested",
- {
- "cancel_source": source,
- "cancel_reason": error_message,
- "requested_by_user_id": requested_by_user_id,
- "workflow_signal_outcome": signal_outcome,
- "status_at_request": status_at_request,
- },
- )
+ capture_cancel_request(run, signal_outcome)
return "accepted", dto
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 20836bc92009..24a7ca04398b 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -598,6 +598,7 @@ class TaskRunDetailDTO:
updated_at: datetime | None = None
completed_at: datetime | None = None
preview_available: bool = False
+ scheduled_at: datetime | None = None
@dataclass(frozen=True)
diff --git a/products/tasks/backend/logic/services/staged_artifacts.py b/products/tasks/backend/logic/services/staged_artifacts.py
index a216e1b76f25..b5b9a662a724 100644
--- a/products/tasks/backend/logic/services/staged_artifacts.py
+++ b/products/tasks/backend/logic/services/staged_artifacts.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import os
+from datetime import datetime, timedelta
from typing import Any
from django.conf import settings
@@ -122,7 +123,20 @@ def get_task_run_artifacts_by_id(task_run: TaskRun, artifact_ids: list[str]) ->
return resolved_artifacts, missing_ids
-def tag_task_artifact(storage_path: str, *, ttl_days: str, team_id: int) -> None:
+def staged_artifacts_expire_by(artifacts: list[dict], scheduled_at: datetime) -> bool:
+ for artifact in artifacts:
+ stored_object = object_storage.head_object_strict(str(artifact["storage_path"]))
+ uploaded_at = stored_object.get("LastModified") if stored_object else None
+ if (
+ not isinstance(uploaded_at, datetime)
+ or timezone.is_naive(uploaded_at)
+ or scheduled_at >= uploaded_at + timedelta(days=int(RUN_ARTIFACT_TTL_DAYS))
+ ):
+ return True
+ return False
+
+
+def tag_task_artifact(storage_path: str, *, ttl_days: str, team_id: int, raise_on_error: bool = False) -> None:
try:
object_storage.tag(
storage_path,
@@ -139,3 +153,5 @@ def tag_task_artifact(storage_path: str, *, ttl_days: str, team_id: int) -> None
team_id=team_id,
error=str(exc),
)
+ if raise_on_error:
+ raise
diff --git a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
index e0027c0d13d2..5179a58da567 100644
--- a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
+++ b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
@@ -11,7 +11,7 @@ from time import monotonic
from django.conf import settings
from django.core.management.base import BaseCommand
-from django.db import DatabaseError
+from django.db import DatabaseError, close_old_connections
from asgiref.sync import sync_to_async
from prometheus_client import start_http_server
@@ -25,6 +25,7 @@ from posthog.models.user import User
from posthog.temporal.common.client import async_connect
from posthog.user_permissions import UserPermissions
+from products.tasks.backend.logic.services.code_usage_gate import usage_limit_response
from products.tasks.backend.logic.services.workflow_dispatch import (
WorkflowDispatchOptions,
claim_dispatches,
@@ -46,15 +47,18 @@ from products.tasks.backend.metrics import (
WORKFLOW_DISPATCH_START_RPC_DURATION_SECONDS,
observe_task_run_workflow_start,
)
-from products.tasks.backend.models import TaskRun, TaskWorkflowDispatch
+from products.tasks.backend.models import Task, TaskRun, TaskWorkflowDispatch
from products.tasks.backend.temporal.client import _capture_run_feature_flags
from products.tasks.backend.temporal.process_task.workflow import ProcessTaskInput
+from products.tasks.backend.visibility import task_control_q
logger = logging.getLogger(__name__)
SCHEDULED_RUN_MATERIALIZATION_BATCH_SIZE = 500
-def _user_can_dispatch(run: TaskRun, options: WorkflowDispatchOptions | None) -> bool:
+def _user_can_dispatch(
+ run: TaskRun, options: WorkflowDispatchOptions | None, *, require_task_control: bool = False
+) -> bool:
if options is not None and options.skip_user_check:
return True
user_id = options.user_id if options is not None else run.task.created_by_id
@@ -63,10 +67,24 @@ def _user_can_dispatch(run: TaskRun, options: WorkflowDispatchOptions | None) ->
user = User.objects.filter(id=user_id, is_active=True).first()
if user is None:
return False
- return UserPermissions(user=user, team=run.task.team).current_team.effective_membership_level is not None
+ if UserPermissions(user=user, team=run.task.team).current_team.effective_membership_level is None:
+ return False
+ return (
+ not require_task_control
+ or Task.objects.filter(task_control_q(user_id), id=run.task_id, team_id=run.team_id).exists()
+ )
+
+
+def _scheduled_run_usage_error(user: User, team_id: int) -> str | None:
+ close_old_connections()
+ try:
+ response = usage_limit_response(user, team_id)
+ return str(response.data["error"]) if response is not None else None
+ finally:
+ close_old_connections()
-async def restart_attempt_already_started(client: Client, dispatch: TaskWorkflowDispatch) -> bool:
+async def dispatch_attempt_already_started(client: Client, dispatch: TaskWorkflowDispatch) -> bool:
try:
description = await client.get_workflow_handle(dispatch.workflow_id).describe(
rpc_timeout=timedelta(seconds=settings.TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS)
@@ -75,7 +93,13 @@ async def restart_attempt_already_started(client: Client, dispatch: TaskWorkflow
if error.status == RPCStatusCode.NOT_FOUND:
return False
raise
- return description.status == WorkflowExecutionStatus.RUNNING and description.start_time >= dispatch.enqueued_at
+ if dispatch.dispatch_kind == TaskWorkflowDispatch.Kind.RESTART:
+ return description.status == WorkflowExecutionStatus.RUNNING and description.start_time >= dispatch.enqueued_at
+ return description.status in (
+ WorkflowExecutionStatus.RUNNING,
+ WorkflowExecutionStatus.COMPLETED,
+ WorkflowExecutionStatus.CONTINUED_AS_NEW,
+ )
class Command(BaseCommand):
@@ -194,23 +218,38 @@ class Command(BaseCommand):
try:
await Team.objects.aget(id=run.team_id)
is_restart = dispatch.dispatch_kind == TaskWorkflowDispatch.Kind.RESTART
+ is_scheduled_create = run.scheduled_at is not None and not is_restart
if is_restart:
requester_id, _ = parse_restart_payload(dispatch.payload)
options = WorkflowDispatchOptions(user_id=requester_id)
- if dispatch.attempt_count > 1 and await restart_attempt_already_started(client, dispatch):
- await sync_to_async(mark_accepted)(dispatch.id, instance_id)
- WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(
- kind=dispatch.dispatch_kind, outcome="already_started"
- ).inc()
- return
else:
options = parse_create_payload(dispatch.payload)
- if not await sync_to_async(_user_can_dispatch)(run, options):
+ if (
+ (is_restart or is_scheduled_create)
+ and dispatch.attempt_count > 1
+ and await dispatch_attempt_already_started(client, dispatch)
+ ):
+ await sync_to_async(mark_accepted)(dispatch.id, instance_id)
+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="already_started").inc()
+ return
+ if not await sync_to_async(_user_can_dispatch)(run, options, require_task_control=is_scheduled_create):
await sync_to_async(mark_dead)(
- dispatch.id, instance_id, "User no longer has team access", "permission"
+ dispatch.id,
+ instance_id,
+ "User no longer has task access" if is_scheduled_create else "User no longer has team access",
+ "permission",
)
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()
return
+ if is_scheduled_create:
+ user = await User.objects.aget(id=options.user_id)
+ usage_error = await sync_to_async(_scheduled_run_usage_error, thread_sensitive=False)(
+ user, run.team_id
+ )
+ if usage_error is not None:
+ await sync_to_async(mark_dead)(dispatch.id, instance_id, usage_error, "usage_limit")
+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()
+ return
await sync_to_async(_capture_run_feature_flags, thread_sensitive=False)(str(run.id))
if is_restart:
from products.tasks.backend.facade.streams import reset_task_run_stream # noqa: PLC0415
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 996b52e75753..dfe81c823671 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -3,7 +3,7 @@ import json
import base64
import logging
import binascii
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any, cast
from django.conf import settings
@@ -53,7 +53,7 @@ from products.tasks.backend.facade.contracts import (
WizardCloudRunDTO,
)
from products.tasks.backend.facade.enums import CHANNEL_WRITE_TYPE_CHOICES
-from products.tasks.backend.facade.model_catalogue import ModelChoice
+from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, ModelChoice, available_model_choices
from products.tasks.backend.facade.run_config import (
ALL_INITIAL_PERMISSION_MODE_CHOICES,
CODEX_INITIAL_PERMISSION_MODE_CHOICES,
@@ -465,6 +465,12 @@ class TaskRunDetailSerializer(DataclassSerializer):
"""
task = serializers.UUIDField(help_text="Parent task id this run belongs to.")
+ scheduled_at = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ default_timezone=UTC,
+ help_text="Earliest start time in UTC. Null for runs without a schedule.",
+ )
log_url = serializers.URLField(
allow_null=True, required=False, help_text="Presigned S3 URL for log access (valid for 1 hour)."
)
@@ -525,6 +531,7 @@ class TaskRunDetailSerializer(DataclassSerializer):
"created_at",
"updated_at",
"completed_at",
+ "scheduled_at",
"preview_available",
]
@@ -1034,12 +1041,37 @@ class TaskWriteSerializer(serializers.Serializer):
return attrs
-class TaskCreateSerializer(TaskWriteSerializer):
+@extend_schema_field(OpenApiTypes.STR)
+class TaskRunScheduledAtField(serializers.DateTimeField):
+ pass
+
+
+class TaskRunScheduleSerializer(serializers.Serializer):
+ scheduled_at = TaskRunScheduledAtField(
+ required=False,
+ allow_null=True,
+ default_timezone=UTC,
+ help_text=(
+ "Earliest start time for a one-off cloud run, in ISO 8601 format. "
+ "Must be in the future and within 30 days. Times without an offset use UTC. "
+ "Omit or send null to start immediately."
+ ),
+ )
+
+ def validate_scheduled_at(self, value: datetime | None) -> datetime | None:
+ if value is not None:
+ now = django_timezone.now()
+ if value <= now or value > now + timedelta(days=30):
+ raise serializers.ValidationError("Choose a future time within 30 days.")
+ return value
+
+
+class TaskCreateSerializer(TaskWriteSerializer, TaskRunScheduleSerializer):
start_run = serializers.BooleanField(
required=False,
default=False,
write_only=True,
- help_text="Start the task's first cloud run immediately after creation.",
+ help_text="Create the first cloud run. It starts immediately unless scheduled_at is set.",
)
signal_report_discussion_question = serializers.CharField(
required=False,
@@ -1085,6 +1117,8 @@ class TaskCreateSerializer(TaskWriteSerializer):
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
attrs = super().validate(attrs)
+ if attrs.get("scheduled_at") is not None and not attrs.get("start_run"):
+ raise serializers.ValidationError({"scheduled_at": "Set start_run to true to schedule a run."})
# Mirror image of the signal_report_task_relationship check: a report-less signal_report
# task still mints under the Signals OAuth app with the interactive run scope, but skips
# the per-report cap entirely. Require the report so the cap and interactive budget always
@@ -1116,6 +1150,7 @@ class TaskCreateSerializer(TaskWriteSerializer):
"initial_permission_mode",
"pending_user_message",
"auto_publish",
+ "scheduled_at",
)
if attrs.get(key) is not None
}
@@ -1126,7 +1161,9 @@ class TaskCreateSerializer(TaskWriteSerializer):
)
run_serializer.is_valid(raise_exception=True)
attrs["run_data"] = {
- key: run_serializer.validated_data[key] for key in run_payload if key in run_serializer.validated_data
+ key: run_serializer.validated_data[key]
+ for key in (*run_payload, "runtime_adapter")
+ if key in run_serializer.validated_data
}
return attrs
@@ -3365,7 +3402,7 @@ class TaskRunPreferencesFieldMixin(serializers.Serializer):
class TaskRunCreateRequestSerializer(
- ImportedMcpServersFieldMixin, RelayedMcpServersFieldMixin, TaskRunPreferencesFieldMixin, serializers.Serializer
+ ImportedMcpServersFieldMixin, RelayedMcpServersFieldMixin, TaskRunPreferencesFieldMixin, TaskRunScheduleSerializer
):
"""Request body for creating a new task run"""
@@ -3452,7 +3489,7 @@ class TaskRunCreateRequestSerializer(
required=False,
default=None,
allow_blank=False,
- help_text="LLM model identifier to run in the selected runtime.",
+ help_text="LLM model identifier. The server derives the runtime adapter when it is omitted.",
)
reasoning_effort = serializers.ChoiceField(
choices=REASONING_EFFORT_CHOICES,
@@ -3498,6 +3535,25 @@ class TaskRunCreateRequestSerializer(
_validate_subscription_caller(attrs, self.context)
errors: dict[str, str] = {}
is_pi_task = _is_pi_task_run_request(self.context)
+ if attrs.get("scheduled_at") is not None:
+ if is_pi_task or attrs.get("mode") != "background":
+ errors["scheduled_at"] = "Scheduling requires a background ACP run."
+ for field in ("github_user_token", "imported_mcp_servers", "relayed_mcp_servers"):
+ if attrs.get(field):
+ errors[field] = "Scheduled runs cannot use credentials or connections from a connected desktop."
+ if attrs.get("claude_model_access") == "own-subscription":
+ errors["claude_model_access"] = "Scheduled runs must use the PostHog gateway."
+ if attrs.get("model") and attrs.get("runtime_adapter") is None:
+ attrs["runtime_adapter"] = get_runtime_adapter_for_model(attrs["model"]) or next(
+ (
+ RuntimeAdapter(choice.runtime_adapter)
+ for choice in available_model_choices(TASK_RUN_GATEWAY_PRODUCT)
+ if choice.model == attrs["model"]
+ ),
+ None,
+ )
+ if attrs["runtime_adapter"] is None:
+ errors["model"] = "Unknown model. Use tasks-models-retrieve to list available models."
if is_pi_task:
for field in ("runtime_adapter", "model", "reasoning_effort", "initial_permission_mode"):
if attrs.get(field) is not None:
@@ -4082,7 +4138,12 @@ class CodexTaskRunCreateSchemaSerializer(TaskRunCreateRequestSerializer):
)
-class TaskRunResumeRequestSchemaSerializer(serializers.Serializer):
+class TaskRunResumeRequestSchemaSerializer(TaskRunScheduleSerializer):
+ model = serializers.CharField(required=False, allow_blank=False)
+ reasoning_effort = serializers.ChoiceField(
+ choices=TaskRunCreateRequestSerializer.REASONING_EFFORT_CHOICES, required=False
+ )
+
mode = serializers.ChoiceField(
choices=TaskExecutionMode.choices,
required=False,
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 75fe5afa9221..46bbcf9d65ba 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -472,7 +472,7 @@ def _resolve_mcp_scopes(task_run: TaskRun) -> PosthogMcpScopes:
independently gate on the skill's ``allowed_tools`` opt-in.
"""
from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — avoid an import cycle
- RunSource,
+ mcp_scopes_for_run_source,
parse_run_state,
)
@@ -489,7 +489,7 @@ def _resolve_mcp_scopes(task_run: TaskRun) -> PosthogMcpScopes:
return "read_only"
run_source = parse_run_state(task_run.state).run_source
- return "full" if run_source in (None, RunSource.MANUAL, RunSource.SIGNAL_REPORT) else "read_only"
+ return mcp_scopes_for_run_source(run_source)
def redispatch_orphaned_task_run(run_id: str) -> str:
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 79f0cad6bd90..2354f9b514eb 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -90,6 +90,10 @@ class RunSource(StrEnum):
AGENT = "agent"
+def mcp_scopes_for_run_source(run_source: RunSource | None) -> Literal["read_only", "full"]:
+ return "full" if run_source in (None, RunSource.MANUAL, RunSource.SIGNAL_REPORT) else "read_only"
+
+
# Origins whose runs are meant to carry a human git identity; everything else is bot-authored.
USER_AUTHORABLE_ORIGIN_PRODUCTS: tuple[str, ...] = ("user_created", "slack")
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 77243e9f4086..fedd33368608 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -10,6 +10,7 @@ from decimal import Decimal
from typing import Any, ClassVar, cast
from urllib.parse import quote
+import time_machine
from unittest.mock import ANY, AsyncMock, MagicMock, call, patch
from django.conf import settings
@@ -48,6 +49,7 @@ from products.tasks.backend.facade import (
)
from products.tasks.backend.facade.repo_selection import RepoSelectionResult
from products.tasks.backend.facade.run_config import TaskArtifactAdapter, TaskArtifactType
+from products.tasks.backend.logic.services.ai_run_defaults import update_team_ai_run_preferences
from products.tasks.backend.logic.services.code_usage_gate import (
CodeUsageStatus,
_gateway_usage_url,
@@ -68,6 +70,7 @@ from products.tasks.backend.logic.services.staged_artifacts import (
get_task_staged_artifacts,
)
from products.tasks.backend.logic.services.task_usage import TaskTokenUsageUnavailable, TaskUsage
+from products.tasks.backend.logic.services.workflow_dispatch import materialize_due_scheduled_task_runs
from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
TaskRunStreamEntryOrKeepalive,
@@ -90,6 +93,7 @@ from products.tasks.backend.models import (
TaskSession,
TaskThreadMessage,
TaskThreadMessageMention,
+ TaskWorkflowDispatch,
)
from products.tasks.backend.presentation.serializers import (
TASK_RUN_ARTIFACT_MAX_SIZE_BYTES,
@@ -98,6 +102,7 @@ from products.tasks.backend.presentation.serializers import (
TaskSerializer,
)
from products.tasks.backend.presentation.views import api as views_api
+from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token
# The catalog gates no model behind a rollout flag now, so the write paths that re-check
@@ -1578,6 +1583,188 @@ class TestTaskAPI(BaseTaskAPITest):
self.assertEqual(run.state["run_source"], "agent")
self.assertEqual(mock_workflow.call_args.kwargs["posthog_mcp_scopes"], "read_only")
+ @parameterized.expand([(True, False), (True, True), (False, False), (False, True)])
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ @patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_schedule_task_run(self, combined_create, explicit_model, mock_workflow, _mock_internal_team):
+ update_team_ai_run_preferences(self.team.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort="high")
+ task = self.create_task()
+ url = "/api/projects/@current/tasks/" if combined_create else f"/api/projects/@current/tasks/{task.id}/run/"
+ payload: dict[str, str | bool] = {
+ "scheduled_at": "2026-09-19T12:00:00",
+ "branch": "main",
+ "pending_user_message": "Check the result after more data arrives.",
+ "run_source": "agent",
+ }
+ if combined_create:
+ payload.update(description="Check the result", start_run=True)
+ if explicit_model:
+ payload.update(model="claude-sonnet-4-6", reasoning_effort="medium")
+ response = self.client.post(url, payload, format="json")
+
+ assert response.status_code == (201 if combined_create else 200), response.json()
+ assert "run_error" not in response.json()
+ run = TaskRun.objects.get(id=response.json()["latest_run"]["id"])
+ assert run.status == TaskRun.Status.NOT_STARTED
+ assert run.queued_at is None
+ assert run.branch == "main"
+ assert response.json()["latest_run"]["scheduled_at"] == "2026-09-19T12:00:00Z"
+ assert run.state["model"] == ("claude-sonnet-4-6" if explicit_model else "gpt-5.5")
+ assert run.state["runtime_adapter"] == ("claude" if explicit_model else "codex")
+ assert run.state["reasoning_effort"] == ("medium" if explicit_model else "high")
+ assert run.state["pending_user_message"] == payload["pending_user_message"]
+ assert not TaskWorkflowDispatch.objects.for_team(self.team.id).filter(task_run=run).exists()
+ mock_workflow.assert_not_called()
+
+ assert materialize_due_scheduled_task_runs(100) == 0
+ update_team_ai_run_preferences(self.team.id, runtime_adapter="codex", model="gpt-5.5", reasoning_effort="low")
+ with time_machine.travel("2026-09-19T12:00:00Z", tick=False):
+ assert materialize_due_scheduled_task_runs(100) == 1
+ assert materialize_due_scheduled_task_runs(100) == 0
+ run.refresh_from_db()
+ assert run.status == TaskRun.Status.QUEUED
+ assert run.state["reasoning_effort"] == ("medium" if explicit_model else "high")
+ dispatch = TaskWorkflowDispatch.objects.for_team(self.team.id).get(task_run=run)
+ assert dispatch.payload["user_id"] == self.user.id
+ assert dispatch.payload["posthog_mcp_scopes"] == "read_only"
+
+ @parameterized.expand(
+ [
+ ("before_expiry", "2026-10-17T23:59:59Z", True, True),
+ ("at_expiry", "2026-10-18T00:00:00Z", True, False),
+ ("after_expiry", "2026-10-18T12:00:00Z", True, False),
+ ("missing_file", "2026-09-19T12:00:00Z", False, False),
+ ]
+ )
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ @patch("posthog.storage.object_storage.tag")
+ @patch("posthog.storage.object_storage.head_object_strict")
+ def test_schedule_checks_attachment_lifetime(
+ self, name: str, scheduled_at: str, exists: bool, allowed: bool, head: MagicMock, tag: MagicMock
+ ) -> None:
+ task = self.create_task()
+ artifact = build_task_artifact_entry(
+ artifact_id="artifact-123",
+ name="spec.pdf",
+ artifact_type="user_attachment",
+ source="user_attachment",
+ size=4096,
+ content_type="application/pdf",
+ storage_path=f"tasks/artifacts/team_{self.team.id}/task_{task.id}/staged/artifact-123/spec.pdf",
+ )
+ cache_task_staged_artifact(task, artifact)
+ head.return_value = {"LastModified": datetime(2026, 9, 18, tzinfo=UTC)} if exists else None
+ transaction_depth = len(connection.atomic_blocks)
+ tag.side_effect = lambda *_args: self.assertEqual(len(connection.atomic_blocks), transaction_depth)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tasks/{task.id}/run/",
+ {"scheduled_at": scheduled_at, "pending_user_artifact_ids": ["artifact-123"]},
+ format="json",
+ )
+
+ if allowed:
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ run = TaskRun.objects.get(task=task)
+ assert run.status == TaskRun.Status.NOT_STARTED
+ assert run.artifacts == [artifact]
+ tag.assert_called_once_with(artifact["storage_path"], {"ttl_days": "30", "team_id": str(self.team.id)})
+ assert get_task_staged_artifacts(task, ["artifact-123"]) == ([], ["artifact-123"])
+ else:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "scheduled_at"
+ assert not TaskRun.objects.filter(task=task).exists()
+ assert get_task_staged_artifacts(task, ["artifact-123"]) == ([artifact], [])
+ tag.assert_not_called()
+ assert not TaskWorkflowDispatch.objects.for_team(self.team.id).filter(task_run__task=task).exists()
+
+ @parameterized.expand([("retention",), ("partial_retention",), ("manifest",), ("cache",)])
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ @patch("posthog.storage.object_storage.tag")
+ @patch("posthog.storage.object_storage.head_object_strict")
+ def test_schedule_attachment_setup_failure(self, failure: str, head: MagicMock, tag: MagicMock) -> None:
+ task = self.create_task()
+ artifact = build_task_artifact_entry(
+ artifact_id="artifact-123",
+ name="spec.pdf",
+ artifact_type="user_attachment",
+ source="user_attachment",
+ size=4096,
+ content_type="application/pdf",
+ storage_path=f"tasks/artifacts/team_{self.team.id}/task_{task.id}/staged/artifact-123/spec.pdf",
+ )
+ cache_task_staged_artifact(task, artifact)
+ head.return_value = {"LastModified": django_timezone.now()}
+ artifact_ids = ["artifact-123"]
+ if failure == "partial_retention":
+ second_artifact = {**artifact, "id": "artifact-456", "storage_path": artifact["storage_path"] + "-second"}
+ cache_task_staged_artifact(task, second_artifact)
+ artifact_ids.append("artifact-456")
+ payload = {"scheduled_at": "2026-09-19T12:00:00Z", "pending_user_artifact_ids": artifact_ids}
+ url = f"/api/projects/{self.team.id}/tasks/{task.id}/run/"
+
+ if failure == "cache":
+ with (
+ patch.object(get_tasks_cache(), "delete_many", side_effect=RuntimeError("Cache unavailable")),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ response = self.client.post(url, payload, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert TaskRun.objects.get(task=task).artifacts == [artifact]
+ else:
+ failure_path = (
+ "posthog.storage.object_storage.tag"
+ if failure in ("retention", "partial_retention")
+ else "products.tasks.backend.facade.api._save_artifact_manifest"
+ )
+ with (
+ patch(
+ failure_path,
+ side_effect=[None, RuntimeError("Attachment setup failed")]
+ if failure == "partial_retention"
+ else RuntimeError("Attachment setup failed"),
+ ),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ response = self.client.post(url, payload, format="json")
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ assert not TaskRun.objects.filter(task=task).exists()
+ assert not TaskWorkflowDispatch.objects.for_team(self.team.id).filter(task_run__task=task).exists()
+ assert get_task_staged_artifacts(task, ["artifact-123"]) == ([artifact], [])
+
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(url, payload, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert TaskRun.objects.filter(task=task).count() == 1
+
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ @patch("products.tasks.backend.facade.api._idling_warm_run_for_task")
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_schedule_resume_keeps_model_without_reusing_warm_run(self, mock_workflow, mock_warm):
+ task = self.create_task()
+ previous_run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ state={"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "high"},
+ )
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"resume_from_run_id": str(previous_run.id), "scheduled_at": "2026-09-19T12:00:00Z"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ run = TaskRun.objects.get(id=response.json()["latest_run"]["id"])
+ assert run.status == TaskRun.Status.NOT_STARTED
+ assert run.state["resume_from_run_id"] == str(previous_run.id)
+ assert run.state["model"] == "gpt-5.5"
+ assert run.state["reasoning_effort"] == "high"
+ mock_warm.assert_not_called()
+ mock_workflow.assert_not_called()
+
@patch("products.tasks.backend.presentation.views.api._is_internal_debug_team", return_value=True)
@patch(
"products.tasks.backend.temporal.client.execute_task_processing_workflow",
@@ -1633,7 +1820,7 @@ class TestTaskAPI(BaseTaskAPITest):
def test_create_task_validates_first_run_payload(self, _mock_internal_team):
response = self.client.post(
"/api/projects/@current/tasks/",
- {"description": "Invalid model", "model": "claude-sonnet-5", "start_run": True},
+ {"description": "Invalid model", "model": "unknown-model", "start_run": True},
format="json",
)
@@ -4615,7 +4802,7 @@ class TestTaskAPI(BaseTaskAPITest):
@parameterized.expand(
[
- ("missing_runtime_adapter", {"model": "gpt-5.3-codex"}, "runtime_adapter"),
+ ("missing_model_with_effort", {"runtime_adapter": "codex", "reasoning_effort": "high"}, "model"),
("missing_model", {"runtime_adapter": "codex"}, "model"),
]
)
@@ -9516,6 +9703,90 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
kwargs.setdefault("environment", TaskRun.Environment.CLOUD)
return TaskRun.objects.create(task=task, team=self.team, **kwargs)
+ @parameterized.expand([("success", False), ("retry", True)])
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ @patch("products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.publish_task_run_stream_complete")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ @patch("products.tasks.backend.push_dispatcher.notify_task_run_cancelled")
+ @patch("posthog.temporal.common.client.sync_connect")
+ @patch("products.tasks.backend.facade.cancellation._signal_complete_task")
+ @patch("products.tasks.backend.facade.api.send_cancel")
+ def test_cancel_scheduled_run_before_dispatch(
+ self,
+ _name,
+ fail_completion,
+ mock_send_cancel,
+ mock_signal,
+ mock_connect,
+ mock_notify,
+ mock_capture,
+ mock_complete,
+ ):
+ task = self.create_task()
+ transaction_depth = len(connection.atomic_blocks)
+ mock_notify.side_effect = lambda _run: self.assertEqual(len(connection.atomic_blocks), transaction_depth)
+ run = task.create_run(
+ scheduled_at=django_timezone.now() + timedelta(days=1),
+ extra_state={"pending_dispatch": {"user_id": self.user.id, "posthog_mcp_scopes": "read_only"}},
+ )
+
+ def complete_stream(run_id: str, use_dedicated: bool) -> bool:
+ self.assertEqual(len(connection.atomic_blocks), transaction_depth)
+ cancelled_run = TaskRun.objects.get(id=run_id)
+ assert cancelled_run.status == TaskRun.Status.CANCELLED
+ assert cancelled_run.state["cancel_fallback_cleanup_complete"] is True
+ return not (fail_completion and mock_complete.call_count == 1)
+
+ mock_complete.side_effect = complete_stream
+ first_status = status.HTTP_503_SERVICE_UNAVAILABLE if fail_completion else status.HTTP_202_ACCEPTED
+ for expected_status in (first_status, status.HTTP_200_OK, status.HTTP_200_OK):
+ response = self.client.post(self._cancel_url(task, run), {}, format="json")
+ assert response.status_code == expected_status
+ run.refresh_from_db()
+ assert run.status == TaskRun.Status.CANCELLED
+ assert run.completed_at is not None
+ assert run.state["cancel_fallback_cleanup_complete"] is False
+ assert mock_complete.call_count == (2 if fail_completion else 1)
+ assert mock_complete.call_args.args[0] == str(run.id)
+ mock_send_cancel.assert_not_called()
+ mock_signal.assert_not_called()
+ mock_connect.assert_not_called()
+ mock_notify.assert_called_once()
+ events = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_cancel_requested"]
+ assert len(events) == 1
+ assert events[0].kwargs["properties"]["workflow_signal_outcome"] == "not_needed"
+ with time_machine.travel("2026-09-20T12:00:00Z", tick=False):
+ assert materialize_due_scheduled_task_runs(100) == 0
+ assert not TaskWorkflowDispatch.objects.for_team(self.team.id).filter(task_run=run).exists()
+
+ @patch("products.tasks.backend.facade.api.create_sandbox_connection_token", return_value="token")
+ @patch("products.tasks.backend.facade.api.send_cancel")
+ @patch("products.tasks.backend.facade.cancellation._signal_complete_task", return_value="signaled")
+ @patch("products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.publish_task_run_stream_complete")
+ def test_cancel_scheduled_run_signals_workflow_if_dispatch_wins(
+ self, mock_complete, mock_signal, _mock_send_cancel, _mock_token
+ ):
+ task = self.create_task()
+ run = task.create_run(scheduled_at=django_timezone.now() + timedelta(days=1))
+ update_run = tasks_facade.update_task_run
+
+ def dispatch_then_update(
+ run_id: str | uuid.UUID, task_id: str | uuid.UUID, team_id: int, **kwargs: Any
+ ) -> None:
+ TaskRun.objects.filter(id=run.id).update(status=TaskRun.Status.QUEUED, queued_at=django_timezone.now())
+ assert update_run(run_id, task_id, team_id, **kwargs) is None
+
+ with patch("products.tasks.backend.facade.api.update_task_run", side_effect=dispatch_then_update):
+ response = self.client.post(self._cancel_url(task, run), {}, format="json")
+
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ run.refresh_from_db()
+ assert run.status == TaskRun.Status.QUEUED
+ assert not run.state.get("cancel_fallback_cleanup_complete")
+ mock_complete.assert_not_called()
+ mock_signal.assert_called_once()
+ assert mock_signal.call_args.args[0].status == TaskRun.Status.QUEUED
+
@patch("products.tasks.backend.models.posthoganalytics.capture")
@patch("products.tasks.backend.facade.api.create_sandbox_connection_token", return_value="token")
@patch("products.tasks.backend.facade.api.send_cancel")
diff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.py
index 0f5824a348ec..17e7fe967479 100644
--- a/products/tasks/backend/tests/test_presentation_serializers.py
+++ b/products/tasks/backend/tests/test_presentation_serializers.py
@@ -1,9 +1,11 @@
import ipaddress
from types import SimpleNamespace
+import time_machine
from unittest.mock import patch
from django.test import SimpleTestCase
+from django.utils import timezone as django_timezone
from parameterized import parameterized
@@ -16,9 +18,11 @@ from posthog.temporal.oauth import (
)
from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.model_catalogue import GatewayModel
from products.tasks.backend.presentation.serializers import (
TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES,
SandboxEnvironmentWriteSerializer,
+ TaskCreateSerializer,
TaskRunArtifactUploadSerializer,
TaskRunBootstrapCreateRequestSerializer,
TaskRunCommandRequestSerializer,
@@ -98,6 +102,75 @@ class TestTaskRunLivingArtifactCreateRequestSerializer(SimpleTestCase):
class TestTaskRunCreateRequestSerializer(SimpleTestCase):
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ def test_schedule_requires_start_run(self) -> None:
+ serializer = TaskCreateSerializer(data={"scheduled_at": "2026-09-19T12:00:00Z"})
+ assert not serializer.is_valid()
+ assert "scheduled_at" in serializer.errors
+
+ @parameterized.expand(
+ [
+ ("utc", "2026-09-19T12:00:00Z", "2026-09-19T12:00:00+00:00"),
+ ("offset", "2026-09-19T14:00:00+02:00", "2026-09-19T12:00:00+00:00"),
+ ("no_offset", "2026-09-19T12:00:00", "2026-09-19T12:00:00+00:00"),
+ ("limit", "2026-10-18T12:00:00Z", "2026-10-18T12:00:00+00:00"),
+ ("now", "2026-09-18T12:00:00Z", None),
+ ("past", "2026-09-17T12:00:00Z", None),
+ ("too_far", "2026-10-18T12:00:01Z", None),
+ ("invalid", "tomorrow", None),
+ ]
+ )
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ def test_schedule_window(self, _name: str, scheduled_at: str, expected: str | None) -> None:
+ for serializer_class in (TaskRunCreateRequestSerializer, TaskCreateSerializer):
+ serializer = serializer_class(data={"scheduled_at": scheduled_at, "start_run": True})
+ with django_timezone.override("America/New_York"):
+ assert serializer.is_valid() is (expected is not None), serializer.errors
+ if expected is None:
+ assert "scheduled_at" in serializer.errors
+ else:
+ assert serializer.validated_data["scheduled_at"].isoformat() == expected
+
+ @parameterized.expand(
+ [
+ ("interactive", {"mode": "interactive"}, "scheduled_at"),
+ ("pi", {}, "scheduled_at"),
+ ("token", {"github_user_token": "test-token"}, "github_user_token"),
+ (
+ "imported",
+ {"imported_mcp_servers": [{"type": "http", "name": "example", "url": "https://example.com"}]},
+ "imported_mcp_servers",
+ ),
+ ]
+ )
+ @time_machine.travel("2026-09-18T12:00:00Z", tick=False)
+ @patch("posthog.security.url_validation.resolve_host_ips", return_value={ipaddress.ip_address("93.184.216.34")})
+ def test_schedule_rejects_unsupported_inputs(self, name: str, payload: dict, field: str, _resolve_host_ips) -> None:
+ serializer = TaskRunCreateRequestSerializer(data={"scheduled_at": "2026-09-19T12:00:00", **payload})
+ with patch(
+ "products.tasks.backend.presentation.serializers._is_pi_task_run_request", return_value=name == "pi"
+ ):
+ assert not serializer.is_valid()
+ assert field in serializer.errors
+
+ @parameterized.expand(
+ [
+ ("gpt-5.3-codex", "high", "codex"),
+ ("claude-sonnet-4-6", "medium", "claude"),
+ ("unknown-model", "high", None),
+ ("gpt-5.3-codex", "ultracode", None),
+ ]
+ )
+ @patch(
+ "products.tasks.backend.logic.services.model_catalogue.list_gateway_models",
+ return_value=(GatewayModel(id="gpt-5.3-codex", owned_by="openai", context_window=200_000),),
+ )
+ def test_model_only_selection(self, model: str, effort: str, adapter: str | None, _models) -> None:
+ serializer = TaskRunCreateRequestSerializer(data={"model": model, "reasoning_effort": effort})
+ assert serializer.is_valid() is (adapter is not None), serializer.errors
+ if adapter is not None:
+ assert serializer.validated_data["runtime_adapter"] == adapter
+
@parameterized.expand([([],), ([["run_source", "manual"]],), (None,), ("manual",), (1,), (False,)])
def test_rejects_non_object_run_state(self, state):
serializer = TaskRunUpdateSerializer(data={"state": state})
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index 99f4cb8daab6..649dfb3174d9 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -486,7 +486,14 @@ class TestRedispatchOrphanedTaskRun(TestCase):
_, workflow_input = start_workflow.call_args.args
self.assertEqual(workflow_input.posthog_mcp_scopes, expected_scopes)
- def test_falls_back_to_scout_scopes_for_signals_scout_run(self) -> None:
+ @parameterized.expand(
+ [
+ (Task.OriginProduct.SIGNALS_SCOUT, "signals_scout_reports"),
+ (Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, "read_only"),
+ (Task.OriginProduct.LOOP, "read_only"),
+ ]
+ )
+ def test_falls_back_to_origin_scopes(self, origin: str, expected_scopes: str) -> None:
# A scout run reconciled without a persisted scope must keep its scout posture — falling back
# to "full"/"read_only" strips every signal_scout_* scope, so the scout can't emit a report,
# write scratchpad, or build its profile, and every signals-scout-* tool reads as "Unknown tool".
@@ -495,7 +502,7 @@ class TestRedispatchOrphanedTaskRun(TestCase):
created_by=self.user,
title="Scout Task",
description="Scout Description",
- origin_product=Task.OriginProduct.SIGNALS_SCOUT,
+ origin_product=origin,
)
run = TaskRun.objects.create(task=scout_task, team=self.team, status=TaskRun.Status.QUEUED, state={})
start_workflow = AsyncMock()
@@ -504,7 +511,7 @@ class TestRedispatchOrphanedTaskRun(TestCase):
self.assertEqual(outcome, "recovered")
_, workflow_input = start_workflow.call_args.args
- self.assertEqual(workflow_input.posthog_mcp_scopes, "signals_scout_reports")
+ self.assertEqual(workflow_input.posthog_mcp_scopes, expected_scopes)
def test_does_not_fail_run_when_workflow_already_started(self) -> None:
run = self._orphaned_run()
diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.py
index b4c06a924b69..dc3454aa1224 100644
--- a/products/tasks/backend/tests/test_workflow_dispatch.py
+++ b/products/tasks/backend/tests/test_workflow_dispatch.py
@@ -1,4 +1,5 @@
import asyncio
+import threading
from datetime import timedelta
from typing import cast
@@ -9,11 +10,13 @@ from django.db import transaction
from django.test import SimpleTestCase, TestCase
from django.utils import timezone as django_timezone
+from asgiref.sync import async_to_sync
from parameterized import parameterized
from temporalio.client import WorkflowExecutionStatus
from temporalio.exceptions import WorkflowAlreadyStartedError
+from temporalio.service import RPCError, RPCStatusCode
-from posthog.models import Organization, Team
+from posthog.models import Organization, OrganizationMembership, Team
from posthog.models.user import User
from products.tasks.backend.facade.api import (
@@ -23,6 +26,7 @@ from products.tasks.backend.facade.api import (
maintain_workflow_dispatch_outbox,
resume_task_run_in_cloud,
)
+from products.tasks.backend.logic.services.code_usage_gate import CodeUsageStatus
from products.tasks.backend.logic.services.workflow_dispatch import (
RestartSnapshot,
WorkflowDispatchFlags,
@@ -42,11 +46,12 @@ from products.tasks.backend.logic.services.workflow_dispatch import (
)
from products.tasks.backend.management.commands.run_task_workflow_dispatcher import (
Command,
+ _scheduled_run_usage_error,
_user_can_dispatch,
- restart_attempt_already_started,
+ dispatch_attempt_already_started,
)
from products.tasks.backend.metrics import WORKFLOW_DISPATCH_ATTEMPT_TOTAL
-from products.tasks.backend.models import Task, TaskRun, TaskWorkflowDispatch
+from products.tasks.backend.models import Channel, ChannelMembership, Task, TaskRun, TaskWorkflowDispatch
from products.tasks.backend.temporal.client import execute_task_processing_workflow
from products.tasks.backend.temporal.process_task.workflow import PendingFollowup
@@ -69,13 +74,15 @@ class TestWorkflowDispatchPayload(SimpleTestCase):
def test_restart_retry_recognizes_workflow_started_by_prior_attempt(self) -> None:
enqueued_at = django_timezone.now()
- dispatch = Mock(workflow_id="workflow-id", enqueued_at=enqueued_at)
+ dispatch = Mock(
+ workflow_id="workflow-id", enqueued_at=enqueued_at, dispatch_kind=TaskWorkflowDispatch.Kind.RESTART
+ )
description = Mock(status=WorkflowExecutionStatus.RUNNING, start_time=enqueued_at + timedelta(seconds=1))
handle = Mock(describe=AsyncMock(return_value=description))
client = Mock()
client.get_workflow_handle.return_value = handle
- self.assertTrue(asyncio.run(restart_attempt_already_started(client, dispatch)))
+ self.assertTrue(asyncio.run(dispatch_attempt_already_started(client, dispatch)))
handle.describe.assert_awaited_once_with(
rpc_timeout=timedelta(seconds=settings.TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS)
)
@@ -145,6 +152,172 @@ class TestWorkflowDispatchPersistence(TestCase):
)
self.task_run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
+ @parameterized.expand(
+ [
+ ("scheduled_over_limit", True, True, False),
+ ("scheduled_allowed", True, False, False),
+ ("scheduled_deactivated", True, False, True),
+ ("immediate_unchanged", False, True, False),
+ ]
+ )
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher._capture_run_feature_flags")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.organization_deactivated")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ def test_dispatch_rechecks_scheduled_usage(
+ self,
+ name: str,
+ scheduled: bool,
+ limited: bool,
+ deactivated: bool,
+ get_usage: Mock,
+ organization_deactivated: Mock,
+ capture_flags: Mock,
+ ) -> None:
+ user = self.task_run.task.created_by
+ assert user is not None
+ OrganizationMembership.objects.create(organization=self.team.organization, user=user)
+ if scheduled:
+ self.task_run.scheduled_at = django_timezone.now() - timedelta(minutes=1)
+ self.task_run.save(update_fields=["scheduled_at"])
+ get_usage.return_value = CodeUsageStatus(limited, "burst" if limited else None, None, False)
+ organization_deactivated.return_value = deactivated
+ dispatch = create_dispatch(
+ self.task_run,
+ TaskWorkflowDispatch.Kind.CREATE,
+ build_create_payload(WorkflowDispatchOptions(user_id=user.id)),
+ self.task_run.workflow_id,
+ )
+ claimed = claim_dispatches("dispatcher-1", 1, timedelta(minutes=1))
+ self.assertEqual([row.id for row in claimed], [dispatch.id])
+ client = Mock(start_workflow=AsyncMock())
+
+ with self.captureOnCommitCallbacks(execute=True):
+ async_to_sync(Command()._process)(client, claimed[0], "dispatcher-1", asyncio.Semaphore(1))
+
+ dispatch.refresh_from_db()
+ self.task_run.refresh_from_db()
+ if scheduled and (limited or deactivated):
+ client.start_workflow.assert_not_called()
+ self.assertEqual(dispatch.status, TaskWorkflowDispatch.Status.DEAD)
+ self.assertEqual(self.task_run.status, TaskRun.Status.FAILED)
+ self.assertTrue(self.task_run.error_message)
+ self.assertEqual(self.task_run.error_message, dispatch.last_error)
+ else:
+ client.start_workflow.assert_awaited_once()
+ self.assertEqual(dispatch.status, TaskWorkflowDispatch.Status.ACCEPTED)
+ if not scheduled:
+ get_usage.assert_not_called()
+
+ @parameterized.expand([("member", True), ("removed", False)])
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher._capture_run_feature_flags")
+ @patch(
+ "products.tasks.backend.management.commands.run_task_workflow_dispatcher._scheduled_run_usage_error",
+ return_value=None,
+ )
+ def test_scheduled_dispatch_requires_private_channel_access(
+ self, name: str, member: bool, usage_error: Mock, capture_flags: Mock
+ ) -> None:
+ user = self.task_run.task.created_by
+ assert user is not None
+ OrganizationMembership.objects.create(organization=self.team.organization, user=user)
+ channel = Channel.objects.for_team(self.team.id).create(
+ team=self.team, name="Private", channel_type=Channel.ChannelType.PRIVATE
+ )
+ membership = ChannelMembership.objects.for_team(self.team.id).create(team=self.team, channel=channel, user=user)
+ task = self.task_run.task
+ task.channel = channel
+ task.save(update_fields=["channel"])
+ self.task_run.scheduled_at = django_timezone.now() - timedelta(minutes=1)
+ self.task_run.save(update_fields=["scheduled_at"])
+ dispatch = create_dispatch(
+ self.task_run,
+ TaskWorkflowDispatch.Kind.CREATE,
+ build_create_payload(WorkflowDispatchOptions(user_id=user.id)),
+ self.task_run.workflow_id,
+ )
+ if not member:
+ membership.delete()
+ claimed = claim_dispatches("dispatcher-1", 1, timedelta(minutes=1))
+ client = Mock(start_workflow=AsyncMock())
+
+ with self.captureOnCommitCallbacks(execute=True):
+ async_to_sync(Command()._process)(client, claimed[0], "dispatcher-1", asyncio.Semaphore(1))
+
+ dispatch.refresh_from_db()
+ self.task_run.refresh_from_db()
+ if member:
+ client.start_workflow.assert_awaited_once()
+ self.assertEqual(dispatch.status, TaskWorkflowDispatch.Status.ACCEPTED)
+ else:
+ client.start_workflow.assert_not_called()
+ usage_error.assert_not_called()
+ self.assertEqual(dispatch.status, TaskWorkflowDispatch.Status.DEAD)
+ self.assertEqual(self.task_run.status, TaskRun.Status.FAILED)
+ self.assertEqual(self.task_run.error_message, "User no longer has task access")
+
+ @parameterized.expand(
+ [
+ ("running", WorkflowExecutionStatus.RUNNING, "accepted"),
+ ("completed", WorkflowExecutionStatus.COMPLETED, "accepted"),
+ ("continued", WorkflowExecutionStatus.CONTINUED_AS_NEW, "accepted"),
+ ("failed", WorkflowExecutionStatus.FAILED, "dead"),
+ ("canceled", WorkflowExecutionStatus.CANCELED, "dead"),
+ ("terminated", WorkflowExecutionStatus.TERMINATED, "dead"),
+ ("timed_out", WorkflowExecutionStatus.TIMED_OUT, "dead"),
+ ("missing", RPCStatusCode.NOT_FOUND, "dead"),
+ ("unavailable", RPCStatusCode.UNAVAILABLE, "pending"),
+ ]
+ )
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher._capture_run_feature_flags")
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher._scheduled_run_usage_error")
+ def test_scheduled_retry_checks_temporal_before_rejecting_usage(
+ self,
+ name: str,
+ workflow_status: WorkflowExecutionStatus | RPCStatusCode,
+ expected_status: str,
+ usage_error: Mock,
+ capture_flags: Mock,
+ ) -> None:
+ user = self.task_run.task.created_by
+ assert user is not None
+ OrganizationMembership.objects.create(organization=self.team.organization, user=user)
+ self.task_run.scheduled_at = django_timezone.now() - timedelta(minutes=1)
+ self.task_run.save(update_fields=["scheduled_at"])
+ dispatch = create_dispatch(
+ self.task_run,
+ TaskWorkflowDispatch.Kind.CREATE,
+ build_create_payload(WorkflowDispatchOptions(user_id=user.id)),
+ self.task_run.workflow_id,
+ )
+ client = Mock(start_workflow=AsyncMock(side_effect=TimeoutError("Start response lost")))
+ usage_error.return_value = None
+ claimed = claim_dispatches("dispatcher-1", 1, timedelta(minutes=1))
+ async_to_sync(Command()._process)(client, claimed[0], "dispatcher-1", asyncio.Semaphore(1))
+
+ usage_error.return_value = "Usage limit reached"
+ if expected_status == "accepted":
+ OrganizationMembership.objects.filter(organization=self.team.organization, user=user).delete()
+ describe = AsyncMock(return_value=Mock(status=workflow_status))
+ if isinstance(workflow_status, RPCStatusCode):
+ describe.side_effect = RPCError("Lookup failed", workflow_status, b"")
+ client.get_workflow_handle.return_value.describe = describe
+ TaskWorkflowDispatch.objects.for_team(self.team.id).filter(id=dispatch.id).update(
+ next_attempt_at=django_timezone.now()
+ )
+ claimed = claim_dispatches("dispatcher-1", 1, timedelta(minutes=1))
+
+ with self.captureOnCommitCallbacks(execute=True):
+ async_to_sync(Command()._process)(client, claimed[0], "dispatcher-1", asyncio.Semaphore(1))
+
+ dispatch.refresh_from_db()
+ self.task_run.refresh_from_db()
+ self.assertEqual(dispatch.status, expected_status)
+ self.assertEqual(
+ self.task_run.status, TaskRun.Status.FAILED if expected_status == "dead" else TaskRun.Status.QUEUED
+ )
+ client.start_workflow.assert_awaited_once()
+ self.assertEqual(usage_error.call_count, 2 if expected_status == "dead" else 1)
+
@patch("products.tasks.backend.temporal.client._terminalize_unstarted_task_run")
def test_malformed_restart_payload_is_terminalized_after_marking_dispatch_dead(self, terminalize: Mock) -> None:
dispatch = TaskWorkflowDispatch.objects.for_team(self.team.id).create(
@@ -731,6 +904,64 @@ class TestWorkflowDispatchPersistence(TestCase):
class TestWorkflowDispatchPermissions(SimpleTestCase):
+ @parameterized.expand([("allowed", None), ("blocked", "Usage limit reached"), ("error", "error")])
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.close_old_connections")
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.usage_limit_response")
+ def test_usage_worker_releases_connections(
+ self, name: str, error: str | None, usage_response: Mock, close_connections: Mock
+ ) -> None:
+ user = Mock()
+ if name == "error":
+ usage_response.side_effect = RuntimeError(error)
+ with self.assertRaises(RuntimeError):
+ _scheduled_run_usage_error(user, 1)
+ else:
+ usage_response.return_value = Mock(data={"error": error}) if error is not None else None
+ self.assertEqual(_scheduled_run_usage_error(user, 1), error)
+ self.assertEqual(close_connections.call_count, 2)
+
+ def test_scheduled_usage_checks_do_not_block_each_other(self) -> None:
+ barrier = threading.Barrier(2, timeout=5)
+ run = Mock(status=TaskRun.Status.QUEUED, scheduled_at=django_timezone.now())
+ dispatches = [
+ Mock(
+ id=dispatch_id,
+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,
+ attempt_count=1,
+ payload=build_create_payload(WorkflowDispatchOptions(user_id=1)),
+ )
+ for dispatch_id in ("first", "second")
+ ]
+ client = Mock(start_workflow=AsyncMock())
+
+ def usage_error(user: User, team_id: int) -> None:
+ barrier.wait()
+
+ async def process() -> None:
+ semaphore = asyncio.Semaphore(2)
+ await asyncio.gather(
+ *(Command()._process(client, dispatch, "worker", semaphore) for dispatch in dispatches)
+ )
+
+ module = "products.tasks.backend.management.commands.run_task_workflow_dispatcher"
+ with (
+ patch(f"{module}.TaskRun.objects") as runs,
+ patch(f"{module}.Team.objects.aget", new_callable=AsyncMock),
+ patch(f"{module}.User.objects.aget", new_callable=AsyncMock),
+ patch(f"{module}.dispatch_exceeded_max_age", return_value=False),
+ patch(f"{module}._user_can_dispatch", return_value=True),
+ patch(f"{module}._scheduled_run_usage_error", side_effect=usage_error),
+ patch(f"{module}._capture_run_feature_flags"),
+ patch(f"{module}.mark_accepted"),
+ patch(f"{module}.observe_task_run_workflow_start"),
+ patch(f"{module}.reschedule") as reschedule_dispatch,
+ ):
+ runs.select_related.return_value.aget = AsyncMock(return_value=run)
+ asyncio.run(process())
+
+ self.assertEqual(client.start_workflow.await_count, 2)
+ reschedule_dispatch.assert_not_called()
+
@patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.UserPermissions")
@patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.User.objects")
def test_user_requires_current_effective_team_access(self, users: Mock, permissions: Mock) -> None:
diff --git a/products/tasks/docs/CHANNELS.md b/products/tasks/docs/CHANNELS.md
index 2b22069235d3..f5e981227c9d 100644
--- a/products/tasks/docs/CHANNELS.md
+++ b/products/tasks/docs/CHANNELS.md
@@ -91,6 +91,13 @@ Handoff locks the private channel before the task. It fails if the task moved to
## Task API
+`POST /tasks/` with `start_run: true` and `POST /tasks/{task_id}/run/` accept `scheduled_at`.
+So do `tasks-create-and-run` and `tasks-run-create` in MCP.
+Use a future ISO 8601 time within 30 days; missing offsets mean UTC. Omit or send null to start immediately. Attached files must remain valid until the scheduled time.
+Scheduled runs require background ACP execution, server-managed credentials, and the PostHog gateway. Dispatch rechecks task access and usage limits.
+Model settings use saved defaults or the previous run on resume. Use `tasks-models-retrieve` for explicit model and effort choices.
+The existing run cancellation endpoint also supports scheduled runs and closes their event streams. Retry a `503` response to complete stream cleanup.
+
- `TaskCreateSerializer` accepts a channel UUID from the same project. The requester must have access to the channel.
- An ordinary user task without a channel goes into the user's `#me` space.
- A user who controls a task can move it to a public channel, their own `#me` channel, or a private channel they belong to.
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 14eec86e4033..e49cc21c6189 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1838,6 +1838,11 @@ export interface TaskRunDetailDTOApi {
updated_at?: string | null
/** @nullable */
completed_at?: string | null
+ /**
+ * Earliest start time in UTC. Null for runs without a schedule.
+ * @nullable
+ */
+ scheduled_at?: string | null
/** True when this run's sandbox serves a dev stack preview, so clients can offer the preview link. Open it through the run's `preview/` endpoint, which mints a fresh access token on every request. */
preview_available?: boolean
}
@@ -2195,7 +2200,12 @@ export interface TaskCreateApi {
* @nullable
*/
channel?: string | null
- /** Start the task's first cloud run immediately after creation. */
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null
+ /** Create the first cloud run. It starts immediately unless scheduled_at is set. */
start_run?: boolean
/**
* Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task.
@@ -2887,6 +2897,11 @@ export interface ClaudeTaskRunCreateSchemaApi {
* * `posthog-gateway` - posthog-gateway
* * `own-subscription` - own-subscription */
claude_model_access?: ClaudeModelAccessEnumApi | null
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -3020,6 +3035,11 @@ export interface CodexTaskRunCreateSchemaApi {
* * `posthog-gateway` - posthog-gateway
* * `own-subscription` - own-subscription */
claude_model_access?: ClaudeModelAccessEnumApi | null
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -3099,6 +3119,13 @@ export interface CodexTaskRunCreateSchemaApi {
}
export interface TaskRunResumeRequestSchemaApi {
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null
+ model?: string
+ reasoning_effort?: ReasoningEffortEnumApi
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 6c36881b13db..ee721042beb7 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1398,10 +1398,16 @@ export const TasksCreateBody = /* @__PURE__ */ zod.object({
'When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
channel: zod.uuid().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
start_run: zod
.boolean()
.default(tasksCreateBodyStartRunDefault)
- .describe("Start the task's first cloud run immediately after creation."),
+ .describe('Create the first cloud run. It starts immediately unless scheduled_at is set.'),
signal_report_discussion_question: zod
.string()
.max(tasksCreateBodySignalReportDiscussionQuestionMax)
@@ -1886,6 +1892,12 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
"How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"
),
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
@@ -2050,6 +2062,12 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
"How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"
),
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
@@ -2150,6 +2168,19 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
})
.describe('Request body for creating a new task run'),
zod.object({
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
+ model: zod.string().optional(),
+ reasoning_effort: zod
+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+ .optional()
+ .describe(
+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index abbe82e44386..bcd9fa1e2316 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -481,12 +481,15 @@ tools:
idempotent: false
input_schema: TaskAgentCreateSchema
enrich_url: '{id}'
- title: Create task and start run
+ title: Create task and start or schedule run
description: >
- Create a task and start its first background run. Set `description` to the agent's instructions. For code
- tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error`
- if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is
- lost, search for the task before you retry. A repeated call can create another task.
+ Create a task and start its first background run, or set `scheduled_at` for a one-off run within 30 days.
+ Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit
+ model fields to use saved defaults. Use `tasks-models-retrieve` before an explicit model choice. Set
+ `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. Omit
+ `branch` to use the default branch. Check `run_error` if the run does not start. Poll `tasks-runs-list` or
+ `tasks-runs-retrieve` for progress. If the response is lost, search for the task before you retry. A
+ repeated call can create another task.
feature_flag: tasks-mcp-agent-run-start
response:
include:
@@ -499,6 +502,9 @@ tools:
- latest_run.stage
- latest_run.status
- run_error
+ - latest_run.scheduled_at
+ - latest_run.model
+ - latest_run.reasoning_effort
tasks-destroy:
operation: tasks_destroy
enabled: false
@@ -662,12 +668,14 @@ tools:
idempotent: false
input_schema: TaskAgentRunCreateSchema
enrich_url: '{id}'
- title: Start task run
+ title: Start or schedule task run
description: >
- Start a cloud run for an existing task. Use `pending_user_message` for follow-up work and
- `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress.
- Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated
- call can start another run.
+ Start a cloud run for an existing task, or set `scheduled_at` for a one-off run within 30 days. Times
+ without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model
+ fields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before an
+ explicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a
+ prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start
+ failure. If the response is lost, check the runs before you retry. A repeated call can start another run.
feature_flag: tasks-mcp-agent-run-start
response:
include:
@@ -680,6 +688,9 @@ tools:
- latest_run.id
- latest_run.stage
- latest_run.status
+ - latest_run.scheduled_at
+ - latest_run.model
+ - latest_run.reasoning_effort
tasks-runs-analysis-activity-create:
operation: tasks_runs_analysis_activity_create
enabled: false
@@ -756,6 +767,9 @@ tools:
- environment
- error_message
- state.sandbox_environment_id
+ - scheduled_at
+ - model
+ - reasoning_effort
- created_at
- updated_at
- completed_at
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index b94f6a917086..21acea70e537 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11725,11 +11725,11 @@
"feature_flag": "tasks"
},
"tasks-create-and-run": {
- "description": "Create a task and start its first background run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error` if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is lost, search for the task before you retry. A repeated call can create another task.",
+ "description": "Create a task and start its first background run, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults. Use `tasks-models-retrieve` before an explicit model choice. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error` if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is lost, search for the task before you retry. A repeated call can create another task.",
"category": "Tasks",
"feature": "tasks",
- "summary": "Create task and start run",
- "title": "Create task and start run",
+ "summary": "Create task and start or schedule run",
+ "title": "Create task and start or schedule run",
"required_scopes": ["task:write"],
"annotations": {
"destructiveHint": false,
@@ -11815,11 +11815,11 @@
"feature_flag": "tasks"
},
"tasks-run-create": {
- "description": "Start a cloud run for an existing task. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",
+ "description": "Start a cloud run for an existing task, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before an explicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",
"category": "Tasks",
"feature": "tasks",
- "summary": "Start task run",
- "title": "Start task run",
+ "summary": "Start or schedule task run",
+ "title": "Start or schedule task run",
"required_scopes": ["task:write"],
"annotations": {
"destructiveHint": false,
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index f11dec3a647a..ea4fc6df5f25 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -12370,11 +12370,11 @@
"feature_flag": "tasks"
},
"tasks-create-and-run": {
- "description": "Create a task and start its first background run. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error` if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is lost, search for the task before you retry. A repeated call can create another task.",
+ "description": "Create a task and start its first background run, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults. Use `tasks-models-retrieve` before an explicit model choice. Set `description` to the agent's instructions. For code tasks, set `repository` to `organization/repo`. Omit `branch` to use the default branch. Check `run_error` if the run does not start. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. If the response is lost, search for the task before you retry. A repeated call can create another task.",
"category": "Tasks",
"feature": "tasks",
- "summary": "Create task and start run",
- "title": "Create task and start run",
+ "summary": "Create task and start or schedule run",
+ "title": "Create task and start or schedule run",
"required_scopes": ["task:write"],
"annotations": {
"destructiveHint": false,
@@ -12460,11 +12460,11 @@
"feature_flag": "tasks"
},
"tasks-run-create": {
- "description": "Start a cloud run for an existing task. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",
+ "description": "Start a cloud run for an existing task, or set `scheduled_at` for a one-off run within 30 days. Times without an offset use UTC. Confirm the returned time; execution starts at or after that time. Omit model fields to use saved defaults, or the previous run's model on resume. Use `tasks-models-retrieve` before an explicit model choice. Use `pending_user_message` for follow-up work and `resume_from_run_id` to continue a prior run. Poll `tasks-runs-list` or `tasks-runs-retrieve` for progress. Check `run_error` for a start failure. If the response is lost, check the runs before you retry. A repeated call can start another run.",
"category": "Tasks",
"feature": "tasks",
- "summary": "Start task run",
- "title": "Start task run",
+ "summary": "Start or schedule task run",
+ "title": "Start or schedule task run",
"required_scopes": ["task:write"],
"annotations": {
"destructiveHint": false,
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 0dce1272d87a..f21fc5cc331c 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -1342,6 +1342,28 @@
"type": "null"
}
]
+ },
+ "scheduled_at": {
+ "description": "Earliest start time for a one-off run. Use a future ISO 8601 timestamp within 30 days. Times without an offset use UTC. Omit to start immediately.",
+ "anyOf": [
+ {
+ "type": "string",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z||([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "model": {
+ "description": "Omit to use saved defaults, or the prior model on resume. For an explicit choice, first call tasks-models-retrieve. The server derives the runtime adapter and saves the choice now.",
+ "type": "string",
+ "minLength": 1
+ },
+ "reasoning_effort": {
+ "description": "Optional effort supported by the selected model. Requires model. See tasks-models-retrieve.",
+ "type": "string",
+ "enum": ["low", "medium", "high", "xhigh", "max", "ultracode"]
}
},
"required": ["description"]
@@ -1376,6 +1398,28 @@
"pending_user_message": {
"description": "Initial or follow-up message for the run.",
"type": "string"
+ },
+ "scheduled_at": {
+ "description": "Earliest start time for a one-off run. Use a future ISO 8601 timestamp within 30 days. Times without an offset use UTC. Omit to start immediately.",
+ "anyOf": [
+ {
+ "type": "string",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z||([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "model": {
+ "description": "Omit to use saved defaults, or the prior model on resume. For an explicit choice, first call tasks-models-retrieve. The server derives the runtime adapter and saves the choice now.",
+ "type": "string",
+ "minLength": 1
+ },
+ "reasoning_effort": {
+ "description": "Optional effort supported by the selected model. Requires model. See tasks-models-retrieve.",
+ "type": "string",
+ "enum": ["low", "medium", "high", "xhigh", "max", "ultracode"]
}
},
"required": ["id"]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4022ba3cc090..a018d32d012a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20111,6 +20111,11 @@ export namespace Schemas {
* * `posthog-gateway` - posthog-gateway
* * `own-subscription` - own-subscription */
claude_model_access?: ClaudeModelAccessEnum | null;
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null;
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -20528,6 +20533,11 @@ export namespace Schemas {
* * `posthog-gateway` - posthog-gateway
* * `own-subscription` - own-subscription */
claude_model_access?: ClaudeModelAccessEnum | null;
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null;
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
@@ -67124,6 +67134,11 @@ export namespace Schemas {
updated_at?: string | null;
/** @nullable */
completed_at?: string | null;
+ /**
+ * Earliest start time in UTC. Null for runs without a schedule.
+ * @nullable
+ */
+ scheduled_at?: string | null;
/** True when this run's sandbox serves a dev stack preview, so clients can offer the preview link. Open it through the run's `preview/` endpoint, which mints a fresh access token on every request. */
preview_available?: boolean;
}
@@ -96063,7 +96078,12 @@ export namespace Schemas {
* @nullable
*/
channel?: string | null;
- /** Start the task's first cloud run immediately after creation. */
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null;
+ /** Create the first cloud run. It starts immediately unless scheduled_at is set. */
start_run?: boolean;
/**
* Question to forward to the signal report's scout when creating a discussion task. Send an empty string when there is no question. Omit only for older clients that embed the question in the task description. Not persisted on the task.
@@ -96761,6 +96781,13 @@ export namespace Schemas {
}
export interface TaskRunResumeRequestSchema {
+ /**
+ * Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.
+ * @nullable
+ */
+ scheduled_at?: string | null;
+ model?: string;
+ reasoning_effort?: ReasoningEffortEnum;
/** Execution mode: 'interactive' for user-connected runs, 'background' for autonomous runs
*
* * `interactive` - interactive
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index 9ba5815899f3..3fcfe8c513f0 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -1167,10 +1167,16 @@ export const TasksCreateBody = () => zod.object({
'When true, the agent pushes its work and opens a draft pull request on completion without an explicit request. Applies when start_run is true or creation reuses a pre-warmed run. Resumed runs keep this setting. Ignored if creation does not start a run. Write-only and not persisted on the task.'
),
channel: zod.string().nullish().describe('Channel this task is owned by (the channel it was kicked off in).'),
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
start_run: zod
.boolean()
.default(tasksCreateBodyStartRunDefault)
- .describe("Start the task's first cloud run immediately after creation."),
+ .describe('Create the first cloud run. It starts immediately unless scheduled_at is set.'),
signal_report_discussion_question: zod
.string()
.max(tasksCreateBodySignalReportDiscussionQuestionMax)
@@ -1345,6 +1351,12 @@ export const TasksRunCreateBody = () => zod.union([
.describe(
"How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"
),
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
@@ -1509,6 +1521,12 @@ export const TasksRunCreateBody = () => zod.union([
.describe(
"How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"
),
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
@@ -1609,6 +1627,19 @@ export const TasksRunCreateBody = () => zod.union([
})
.describe('Request body for creating a new task run'),
zod.object({
+ scheduled_at: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off cloud run, in ISO 8601 format. Must be in the future and within 30 days. Times without an offset use UTC. Omit or send null to start immediately.'
+ ),
+ model: zod.string().optional(),
+ reasoning_effort: zod
+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+ .optional()
+ .describe(
+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ ),
mode: zod
.enum(['interactive', 'background'])
.describe('\* `interactive` - interactive\n\* `background` - background')
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index f93fa9e5d72e..d7e5b13cbac0 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -673,13 +673,54 @@ export const ProjectSetActiveSchema = z.object({
projectId: z.number().int().positive(),
})
+const taskAgentRunOptions = {
+ // Use a pattern because JSON Schema's date-time format requires a timezone offset.
+ scheduled_at: z
+ .string()
+ .regex(z.regexes.datetime({ offset: true, local: true }))
+ .nullish()
+ .describe(
+ 'Earliest start time for a one-off run. Use a future ISO 8601 timestamp within 30 days. Times without an offset use UTC. Omit to start immediately.'
+ ),
+ model: z
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ 'Omit to use saved defaults, or the prior model on resume. For an explicit choice, first call tasks-models-retrieve. The server derives the runtime adapter and saves the choice now.'
+ ),
+ // Mirrors the run serializer's choices, unlike the deliberately loose `model`, so the tool
+ // cannot offer a depth the API rejects.
+ reasoning_effort: z
+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+ .optional()
+ .describe('Optional effort supported by the selected model. Requires model. See tasks-models-retrieve.'),
+}
+
+// Mirrors the run serializer's runtime-selection rule. Its 400 also names runtime_adapter, which
+// these tools do not expose, so fail here naming only the field the caller can set.
+function validateTaskAgentRunOptions(
+ data: { model?: string | undefined; reasoning_effort?: string | undefined },
+ ctx: z.RefinementCtx
+): void {
+ if (data.reasoning_effort && !data.model) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['model'],
+ message: 'Required when reasoning_effort is set. Call tasks-models-retrieve to choose a model.',
+ })
+ }
+}
+
export const TaskAgentCreateSchema = z
.object({
title: z.string().max(255).optional(),
description: z.string().min(1).describe('Instructions for the agent.'),
repository: z.string().nullish().describe('Repository in organization/repo format.'),
branch: z.string().min(1).max(255).nullish().describe('Base branch for the run.'),
+ ...taskAgentRunOptions,
})
+ .superRefine(validateTaskAgentRunOptions)
.transform((input) => ({ ...input, start_run: true as const }))
export const TaskAgentRunCreateSchema = z
@@ -688,7 +729,9 @@ export const TaskAgentRunCreateSchema = z
branch: z.string().max(255).nullish().describe('Git branch to check out in the sandbox.'),
resume_from_run_id: z.string().uuid().optional().describe('ID of a previous run to resume from.'),
pending_user_message: z.string().optional().describe('Initial or follow-up message for the run.'),
+ ...taskAgentRunOptions,
})
+ .superRefine(validateTaskAgentRunOptions)
.transform((input) => ({ ...input, mode: 'background' as const, run_source: 'agent' as const }))
// Debug MCP UI Apps
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index 8cd4a9cb6ef4..f2eb5f6d941e 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -612,6 +612,7 @@ const TasksCreateSchema = () => {
pending_user_artifact_ids: true,
auto_publish: true,
channel: true,
+ scheduled_at: true,
start_run: true,
signal_report_discussion_question: true,
naming_source: true,
@@ -692,6 +693,9 @@ const tasksCreateAndRun = (): ToolBase<ReturnType<typeof TasksCreateAndRunSchema
'latest_run.stage',
'latest_run.status',
'run_error',
+ 'latest_run.scheduled_at',
+ 'latest_run.model',
+ 'latest_run.reasoning_effort',
]) as typeof result
return await withPostHogUrl(context, filtered, `/tasks/${filtered.id}`)
},
@@ -901,6 +905,9 @@ const tasksRunCreate = (): ToolBase<ReturnType<typeof TasksRunCreateSchema>, Sch
'latest_run.id',
'latest_run.stage',
'latest_run.status',
+ 'latest_run.scheduled_at',
+ 'latest_run.model',
+ 'latest_run.reasoning_effort',
]) as typeof result
return await withPostHogUrl(context, filtered, `/tasks/${filtered.id}`)
},
@@ -940,6 +947,9 @@ const tasksRunsList = (): ToolBase<
'environment',
'error_message',
'state.sandbox_environment_id',
+ 'scheduled_at',
+ 'model',
+ 'reasoning_effort',
'created_at',
'updated_at',
'completed_at',
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-create-and-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-create-and-run.json
index 6366182713d3..b9cdec637eeb 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-create-and-run.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-create-and-run.json
@@ -19,6 +19,16 @@
"minLength": 1,
"type": "string"
},
+ "model": {
+ "description": "Omit to use saved defaults, or the prior model on resume. For an explicit choice, first call tasks-models-retrieve. The server derives the runtime adapter and saves the choice now.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "reasoning_effort": {
+ "description": "Optional effort supported by the selected model. Requires model. See tasks-models-retrieve.",
+ "enum": ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ "type": "string"
+ },
"repository": {
"anyOf": [
{
@@ -30,6 +40,18 @@
],
"description": "Repository in organization/repo format."
},
+ "scheduled_at": {
+ "anyOf": [
+ {
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z||([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Earliest start time for a one-off run. Use a future ISO 8601 timestamp within 30 days. Times without an offset use UTC. Omit to start immediately."
+ },
"title": {
"maxLength": 255,
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-run-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-run-create.json
index 5c6e8faf683b..5f585721db0e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-run-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-run-create.json
@@ -19,15 +19,37 @@
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
"type": "string"
},
+ "model": {
+ "description": "Omit to use saved defaults, or the prior model on resume. For an explicit choice, first call tasks-models-retrieve. The server derives the runtime adapter and saves the choice now.",
+ "minLength": 1,
+ "type": "string"
+ },
"pending_user_message": {
"description": "Initial or follow-up message for the run.",
"type": "string"
},
+ "reasoning_effort": {
+ "description": "Optional effort supported by the selected model. Requires model. See tasks-models-retrieve.",
+ "enum": ["low", "medium", "high", "xhigh", "max", "ultracode"],
+ "type": "string"
+ },
"resume_from_run_id": {
"description": "ID of a previous run to resume from.",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$",
"type": "string"
+ },
+ "scheduled_at": {
+ "anyOf": [
+ {
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z||([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Earliest start time for a one-off run. Use a future ISO 8601 timestamp within 30 days. Times without an offset use UTC. Omit to start immediately."
}
},
"required": ["id"],
diff --git a/services/mcp/tests/unit/tasks-generated.test.ts b/services/mcp/tests/unit/tasks-generated.test.ts
index e488e74b86be..72700752e77e 100644
--- a/services/mcp/tests/unit/tasks-generated.test.ts
+++ b/services/mcp/tests/unit/tasks-generated.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
+import { TasksCreateBody, TasksRunCreateBody } from '@/generated/tasks/api'
import { GENERATED_TOOL_MAP } from '@/tools/generated'
import type { Context } from '@/tools/types'
@@ -68,4 +69,59 @@ describe('Generated task tools', () => {
run_source: 'agent',
})
})
+
+ it.each(['tasks-create-and-run', 'tasks-run-create'])(
+ '%s sends scheduling options and returns the saved configuration',
+ async (name) => {
+ const id = '00000000-0000-4000-8000-000000000001'
+ const options = {
+ scheduled_at: '2026-09-19T12:00:00',
+ model: 'gpt-5.3-codex',
+ reasoning_effort: 'high',
+ }
+ const latestRun = { id, status: 'not_started', ...options, scheduled_at: '2026-09-19T12:00:00Z' }
+ const request = vi.fn().mockResolvedValue({ id, latest_run: latestRun })
+ const context = {
+ api: { request, getProjectBaseUrl: () => 'https://example.com/project/42' },
+ stateManager: { getProjectId: async () => '42' },
+ } as unknown as Context
+ const tool = GENERATED_TOOL_MAP[name]!()
+ const params = tool.schema.parse({ id, description: 'Check the result', ...options })
+
+ expect(await tool.handler(context, params)).toMatchObject({ latest_run: latestRun })
+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ body: expect.objectContaining(options) }))
+ }
+ )
+
+ it.each(['tasks-create-and-run', 'tasks-run-create'])('%s rejects a run option the API rejects', (name) => {
+ const schema = GENERATED_TOOL_MAP[name]!().schema
+ const base = { id: '00000000-0000-4000-8000-000000000001', description: 'Check the result' }
+
+ expect(() => schema.parse({ ...base, model: 'gpt-5.3-codex', reasoning_effort: 'very-high' })).toThrow()
+ expect(() => schema.parse({ ...base, reasoning_effort: 'high' })).toThrow()
+ expect(schema.parse({ ...base, model: 'gpt-5.3-codex', reasoning_effort: 'high' })).toMatchObject({
+ model: 'gpt-5.3-codex',
+ reasoning_effort: 'high',
+ })
+ })
+
+ it.each(['2026-09-19T12:00:00Z', '2026-09-19T14:00:00+02:00', '2026-09-19T12:00:00'])(
+ 'accepts scheduled time %s',
+ (scheduled_at) => {
+ const schema = GENERATED_TOOL_MAP['tasks-create-and-run']!().schema
+ expect(schema.parse({ description: 'Check the result', scheduled_at })).toMatchObject({ scheduled_at })
+ expect(TasksCreateBody().parse({ description: 'Check the result', scheduled_at })).toMatchObject({
+ scheduled_at,
+ })
+ expect(TasksRunCreateBody().parse({ scheduled_at })).toMatchObject({ scheduled_at })
+ const resume = {
+ scheduled_at,
+ resume_from_run_id: '00000000-0000-4000-8000-000000000001',
+ model: 'claude-sonnet-4-6',
+ reasoning_effort: 'medium',
+ }
+ expect(TasksRunCreateBody().parse(resume)).toMatchObject(resume)
+ expect(() => schema.parse({ description: 'Check the result', scheduled_at: 'tomorrow' })).toThrow()
+ }
+ )
})