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): let task creation take run options (#123798)

Charles Vien1a7aabab444c
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 19165546770d..783db8314fbb 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -104,7 +104,7 @@ from products.tasks.backend.constants import (
)
from products.tasks.backend.error_telemetry import truncate_error_message
from products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_token
-from products.tasks.backend.facade.profiles import TaskProfile, resolve_task_origin
+from products.tasks.backend.facade.profiles import TaskProfile, TaskRunOptions, resolve_task_origin
from products.tasks.backend.feature_flags import (
get_model_access_error,
own_subscription_cloud_enabled as own_subscription_cloud_enabled,
@@ -2265,6 +2265,7 @@ def create_task_without_run(
repository: str | None = None,
mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,
channel: Channel | None = None,
+ options: TaskRunOptions | None = None,
) -> UUID:
"""Create a Task row with no initial run, returning its id.
@@ -2288,6 +2289,7 @@ def create_task_without_run(
repository=repository,
channel=channel,
mcp_builtin_agent_key=mcp_builtin_agent_key,
+ options=options,
)
return task.id
diff --git a/products/tasks/backend/facade/profiles.py b/products/tasks/backend/facade/profiles.py
index 0a8618c1c971..4453f85315f6 100644
--- a/products/tasks/backend/facade/profiles.py
+++ b/products/tasks/backend/facade/profiles.py
@@ -76,7 +76,7 @@ class TaskProfile:
Each product defines its own profiles and registers them when its app loads, so the tasks
product never imports another product. A task keeps its profile for its whole life. Values
- that change per call go in RunOptions, which can only choose from or narrow what the profile
+ that change per call go in TaskRunOptions, which can only choose from or narrow what the profile
allows.
"""
@@ -88,7 +88,7 @@ class TaskProfile:
origin_product: str
# True lets callers create this kind of task through the public task API.
public: bool
- # The RunOptions fields a public API caller may set. The server refuses any other field from
+ # The TaskRunOptions fields a public API caller may set. The server refuses any other field from
# a public caller.
public_options: frozenset[str]
# The kind of row that started the task, such as "signal_report". The server checks that the
@@ -131,7 +131,7 @@ class TaskProfile:
# gets that agent's MCP servers instead of its creator's MCP store connections. None means the
# task uses its creator's connections.
mcp_agent: str | None
- # The widest PostHog MCP scope preset the agent can get. RunOptions.mcp_scopes can narrow it
+ # The widest PostHog MCP scope preset the agent can get. TaskRunOptions.mcp_scopes can narrow it
# but never widen it.
mcp_scopes: PosthogMcpScopes
# True installs the team's MCP store servers in the sandbox. False installs none, personal
@@ -148,7 +148,7 @@ class TaskProfile:
# True lets runs open pull requests as the creator through their personal GitHub installation.
# A creator without a usable installation falls back to the bot. False always uses the bot.
user_authorable_prs: bool
- # Who authors pull requests when the run does not set RunOptions.pr_authorship_mode.
+ # Who authors pull requests when the run does not set TaskRunOptions.pr_authorship_mode.
default_pr_authorship: PrAuthorship
# True gives the agent a finish tool that moves the task to done.
finish_tool: bool
@@ -157,7 +157,7 @@ class TaskProfile:
done_on_turn_close: bool
# How long the sandbox stays up after a turn closes, in case someone replies. After that the
- # task snapshots, releases the sandbox and goes idle. RunOptions.idle_minutes can lower it.
+ # task snapshots, releases the sandbox and goes idle. TaskRunOptions.idle_minutes can lower it.
idle_minutes: int
# How long an open turn may go without an agent heartbeat. After that the run fails, so a retry
# can pick the task back up.
@@ -193,11 +193,11 @@ class Repository:
@frozen
-class RunOptions:
+class TaskRunOptions:
"""Per-call settings for one task, checked against its TaskProfile.
- A public API caller can only set the fields in TaskProfile.public_options. None or an empty
- tuple means the profile's default.
+ A public API caller can only set the fields in TaskProfile.public_options. A field left at its
+ default falls back to the profile's value.
"""
# "acp" or "pi". It must be one of TaskProfile.runtimes and cannot change after create.
@@ -222,9 +222,9 @@ class RunOptions:
github_access: GithubAccess | None = None
# It can narrow TaskProfile.mcp_scopes but never widen it.
mcp_scopes: PosthogMcpScopes | None = None
- # The MCP servers to install, by ID. Only server callers can set it. The profile must have an
- # mcp_agent.
- mcp_server_ids: tuple[str, ...] = ()
+ # The MCP servers to install, by ID. An empty tuple allows no servers. Only server callers can set
+ # it. The profile must have an mcp_agent.
+ mcp_server_ids: tuple[str, ...] | None = None
# Context window size for models that support the 1M window.
context_window: str | None = None
# Fast mode for models that support it.
@@ -249,6 +249,10 @@ class TaskProfileError(ValueError):
pass
+class TaskRunOptionsError(ValueError):
+ pass
+
+
# Tasks stored without a profile and SQL filters only know a task's origin_product, so every profile
# that shares an origin must agree on these fields.
_ORIGIN_SCOPED_FIELDS = (
diff --git a/products/tasks/backend/migrations/0144_task_options.py b/products/tasks/backend/migrations/0144_task_options.py
new file mode 100644
index 000000000000..3183faf7079f
--- /dev/null
+++ b/products/tasks/backend/migrations/0144_task_options.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-27 05:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0143_agent_startup_success_index"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="task",
+ name="options",
+ field=models.JSONField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 606ea9bc34bf..4434490791b7 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0143_agent_startup_success_index
+0144_task_options
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 3228ae3d6fb9..e89c086b2e1b 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -52,7 +52,7 @@ from products.tasks.backend.dev_stack_image_models import (
DevStackImageTarget as DevStackImageTarget,
)
from products.tasks.backend.error_telemetry import truncate_error_message
-from products.tasks.backend.facade.profiles import TaskProfile, resolve_task_origin
+from products.tasks.backend.facade.profiles import TaskProfile, TaskRunOptions, resolve_task_origin
from products.tasks.backend.feature_flags import (
is_task_run_stream_presence_gated,
is_task_run_stream_thin_tail,
@@ -68,6 +68,7 @@ from products.tasks.backend.metrics import (
)
from products.tasks.backend.pr_urls import read_pr_urls
from products.tasks.backend.redis import dedicated_stream_configured, run_uses_dedicated_stream
+from products.tasks.backend.run_options import RunSettings, apply_run_options, run_options_record
from products.tasks.backend.storage import append_jsonl_object
logger = structlog.get_logger(__name__)
@@ -458,6 +459,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
description = models.TextField()
origin_product = models.CharField(max_length=20, choices=task_origin_product_choices)
profile = models.CharField(max_length=64, null=True, blank=True)
+ options = models.JSONField(null=True, blank=True)
client_provenance = models.CharField(
max_length=32,
choices=task_client_provenance_choices,
@@ -1560,6 +1562,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
client_provenance: TaskClientProvenance | None = None,
mcp_credential_owner_id: int | None = None,
mcp_gateway_server_ids: list[str] | None = None,
+ options: TaskRunOptions | None = None,
) -> "Task":
"""Create the Task row without an initial run or workflow.
@@ -1568,6 +1571,22 @@ class Task(Taggable, DeletedMetaFields, models.Model):
own state. The run `extra_state` assembled by `_build_task` is discarded here.
"""
origin = resolve_task_origin(profile=profile, origin_product=origin_product, internal=internal)
+ runtime = Task.Runtime.ACP.value
+ if options is not None:
+ settings = apply_run_options(
+ options,
+ RunSettings(
+ repository=repository,
+ repositories=repositories,
+ output_schema=output_schema,
+ mcp_gateway_server_ids=mcp_gateway_server_ids,
+ ),
+ creates_run=False,
+ )
+ runtime = settings.runtime
+ repositories = settings.repositories
+ output_schema = settings.output_schema
+ mcp_gateway_server_ids = settings.mcp_gateway_server_ids
task, _ = Task._build_task(
team=team,
title=title,
@@ -1586,6 +1605,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
internal=origin.internal,
output_schema=output_schema,
interaction_origin=interaction_origin,
+ runtime=runtime,
model=model,
initial_permission_mode=initial_permission_mode,
mcp_builtin_agent_key=mcp_builtin_agent_key,
@@ -1593,6 +1613,8 @@ class Task(Taggable, DeletedMetaFields, models.Model):
mcp_credential_owner_id=mcp_credential_owner_id,
mcp_gateway_server_ids=mcp_gateway_server_ids,
)
+ if options is not None:
+ task.options = run_options_record(options)
task.save()
return task
@@ -1654,6 +1676,7 @@ class Task(Taggable, DeletedMetaFields, models.Model):
mcp_gateway_server_ids: list[str] | None = None,
mcp_tool_allowlist: list[str] | None = None,
before_task_dispatch: Callable[[uuid.UUID], dict[str, JsonValue] | None] | None = None,
+ options: TaskRunOptions | None = None,
) -> "Task":
startup_requested_at = django_timezone.now()
from products.tasks.backend.logic.services.workflow_dispatch import (
@@ -1674,6 +1697,41 @@ class Task(Taggable, DeletedMetaFields, models.Model):
origin = resolve_task_origin(profile=profile, origin_product=origin_product, internal=internal)
origin_product = cast("Task.OriginProduct", origin.origin_product)
internal = origin.internal
+ if options is not None:
+ settings = apply_run_options(
+ options,
+ RunSettings(
+ runtime=runtime,
+ runtime_adapter=runtime_adapter,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ repository=repository,
+ repositories=repositories,
+ branch=branch,
+ sandbox_template=sandbox_template,
+ output_schema=output_schema,
+ inactivity_timeout_seconds=inactivity_timeout_seconds,
+ github_read_access=github_read_access,
+ posthog_mcp_scopes=posthog_mcp_scopes,
+ initial_permission_mode=initial_permission_mode,
+ mcp_gateway_server_ids=mcp_gateway_server_ids,
+ extra_run_state=extra_run_state,
+ ),
+ )
+ runtime = settings.runtime
+ runtime_adapter = settings.runtime_adapter
+ model = settings.model
+ reasoning_effort = settings.reasoning_effort
+ repositories = settings.repositories
+ branch = settings.branch
+ sandbox_template = settings.sandbox_template
+ output_schema = settings.output_schema
+ inactivity_timeout_seconds = settings.inactivity_timeout_seconds
+ github_read_access = settings.github_read_access
+ posthog_mcp_scopes = settings.posthog_mcp_scopes
+ initial_permission_mode = settings.initial_permission_mode
+ mcp_gateway_server_ids = settings.mcp_gateway_server_ids
+ extra_run_state = settings.extra_run_state
task, extra_state = Task._build_task(
team=team,
title=title,
@@ -1720,6 +1778,8 @@ class Task(Taggable, DeletedMetaFields, models.Model):
mcp_gateway_server_ids=mcp_gateway_server_ids,
mcp_tool_allowlist=mcp_tool_allowlist,
)
+ if options is not None:
+ task.options = run_options_record(options)
run_extra_state = dict(extra_state or {})
# Caller-supplied run state (e.g. a workflow action's config_snapshot) wins over the
diff --git a/products/tasks/backend/run_options.py b/products/tasks/backend/run_options.py
new file mode 100644
index 000000000000..dd271b136adc
--- /dev/null
+++ b/products/tasks/backend/run_options.py
@@ -0,0 +1,126 @@
+import json
+from dataclasses import asdict, replace
+from typing import TYPE_CHECKING, Any
+
+from pydantic import BaseModel
+
+from posthog.dataclasses import frozen
+
+from products.tasks.backend.facade.profiles import GithubAccess, TaskRunOptions, TaskRunOptionsError
+
+if TYPE_CHECKING:
+ from posthog.temporal.oauth import PosthogMcpScopes
+
+
+@frozen
+class RunSettings:
+ runtime: str = "acp"
+ runtime_adapter: str | None = None
+ model: str | None = None
+ reasoning_effort: str | None = None
+ repository: str | None = None
+ repositories: list[str] | None = None
+ branch: str | None = None
+ sandbox_template: str | None = None
+ output_schema: type[BaseModel] | dict | None = None
+ inactivity_timeout_seconds: int | None = None
+ github_read_access: bool = False
+ posthog_mcp_scopes: "PosthogMcpScopes" = "full"
+ initial_permission_mode: str | None = None
+ mcp_gateway_server_ids: list[str] | None = None
+ extra_run_state: dict[str, Any] | None = None
+
+
+TASK_SETTINGS = frozenset({"runtime", "repositories", "output_schema", "mcp_gateway_server_ids"})
+
+_SETTING_RUN_STATE_KEYS = {
+ "runtime_adapter": "runtime_adapter",
+ "model": "model",
+ "reasoning_effort": "reasoning_effort",
+ "repositories": "repositories",
+ "branch": "pr_base_branch",
+ "inactivity_timeout_seconds": "inactivity_timeout_seconds",
+ "github_read_access": "github_read_access",
+ "initial_permission_mode": "initial_permission_mode",
+}
+
+_OPTION_NAMES = {
+ "runtime_adapter": "adapter",
+ "branch": "initial_branch",
+ "inactivity_timeout_seconds": "idle_minutes",
+ "github_read_access": "github_access",
+ "posthog_mcp_scopes": "mcp_scopes",
+ "initial_permission_mode": "permission_mode",
+}
+
+
+def _settings_from(options: TaskRunOptions) -> dict[str, Any]:
+ settings: dict[str, Any] = {}
+ if options.runtime is not None:
+ settings["runtime"] = options.runtime
+ if options.adapter is not None:
+ settings["runtime_adapter"] = options.adapter
+ if options.model is not None:
+ settings["model"] = options.model
+ if options.reasoning_effort is not None:
+ settings["reasoning_effort"] = options.reasoning_effort
+ if options.repositories:
+ settings["repositories"] = [repository.name for repository in options.repositories]
+ if options.repositories[0].initial_branch:
+ settings["branch"] = options.repositories[0].initial_branch
+ if options.sandbox_template is not None:
+ settings["sandbox_template"] = options.sandbox_template
+ if options.output_schema is not None:
+ settings["output_schema"] = options.output_schema
+ if options.idle_minutes is not None:
+ settings["inactivity_timeout_seconds"] = options.idle_minutes * 60
+ if options.github_access == GithubAccess.READ:
+ settings["github_read_access"] = True
+ if options.mcp_scopes is not None:
+ settings["posthog_mcp_scopes"] = options.mcp_scopes
+ if options.mcp_server_ids is not None:
+ settings["mcp_gateway_server_ids"] = list(options.mcp_server_ids)
+ if options.permission_mode is not None:
+ settings["initial_permission_mode"] = options.permission_mode
+ return settings
+
+
+def _run_state_from(options: TaskRunOptions) -> dict[str, Any]:
+ state: dict[str, Any] = {}
+ if options.context_window is not None:
+ state["context_window"] = options.context_window
+ if options.fast_mode is not None:
+ state["fast_mode"] = options.fast_mode
+ if options.auto_publish is not None:
+ state["auto_publish"] = options.auto_publish
+ if options.pr_authorship_mode is not None:
+ state["pr_authorship_mode"] = options.pr_authorship_mode.value
+ return state
+
+
+def apply_run_options(options: TaskRunOptions, given: RunSettings, *, creates_run: bool = True) -> RunSettings:
+ if options.github_access == GithubAccess.NONE:
+ raise TaskRunOptionsError("github_access=none is not supported yet")
+ settings = _settings_from(options)
+ run_state = _run_state_from(options)
+ if not creates_run:
+ run_only = sorted(
+ {*(_OPTION_NAMES.get(name, name) for name in settings if name not in TASK_SETTINGS), *run_state}
+ )
+ if run_only:
+ raise TaskRunOptionsError(f"{', '.join(run_only)} only apply to a run. Pass them when the run is created")
+ given_run_state = given.extra_run_state or {}
+ defaults = RunSettings()
+ conflicts = [name for name in settings if getattr(given, name) != getattr(defaults, name)]
+ if "repositories" in settings and given.repository is not None:
+ conflicts.append("repository")
+ conflicts.extend(name for name in settings if _SETTING_RUN_STATE_KEYS.get(name) in given_run_state)
+ conflicts.extend(key for key in run_state if key in given_run_state)
+ if conflicts:
+ raise TaskRunOptionsError(f"Set {', '.join(sorted(set(conflicts)))} in options or as arguments, not both")
+ extra_run_state = {**given_run_state, **run_state} if run_state else given.extra_run_state
+ return replace(given, **settings, extra_run_state=extra_run_state)
+
+
+def run_options_record(options: TaskRunOptions) -> dict[str, Any]:
+ return json.loads(json.dumps(asdict(options)))
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index fe9eea498160..e030f1218fca 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -28,7 +28,7 @@ from products.tasks.backend.facade import (
contracts,
warm as warm_facade,
)
-from products.tasks.backend.facade.profiles import TaskProfileError, get_task_profile
+from products.tasks.backend.facade.profiles import Repository, TaskProfileError, TaskRunOptions, get_task_profile
from products.tasks.backend.models import (
TASK_OWNERSHIP_VERSION_STATE_KEY,
Channel,
@@ -40,6 +40,7 @@ from products.tasks.backend.models import (
TaskWorkflowDispatch,
)
from products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PLACEHOLDER, build_wizard_pr_agent_prompt
+from products.tasks.backend.run_options import run_options_record
FACADE_MODULES = [
"products.tasks.backend.facade.api",
@@ -1795,6 +1796,24 @@ class TestFacadeReadsAndMappers(TestCase):
task = Task.objects.get(id=created if isinstance(created, UUID) else created.task_id)
self.assertEqual((task.origin_product, task.internal, task.profile), expected)
+ @parameterized.expand([("create_and_run_task",), ("create_task_without_run",)])
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_facade_applies_and_stores_run_options(self, entry: str, _mock_workflow) -> None:
+ Integration.objects.create(team=self.team, kind="github", config={})
+ options = TaskRunOptions(repositories=(Repository(name="posthog/posthog"),))
+
+ created = getattr(facade, entry)(
+ team=self.team,
+ title="t",
+ description="d",
+ user_id=self.user.id,
+ origin_product=facade.TaskOriginProduct.USER_CREATED,
+ options=options,
+ )
+
+ task = Task.objects.get(id=created if isinstance(created, UUID) else created.task_id)
+ self.assertEqual((task.repositories, task.options), (["posthog/posthog"], run_options_record(options)))
+
@parameterized.expand(
[
("create_and_run_task_neither", "create_and_run_task", {}),
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index ffafc66930b1..3dd05499cd51 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -2,6 +2,7 @@ import json
import uuid
from contextlib import nullcontext
from datetime import UTC, datetime, timedelta
+from functools import partial
from typing import Any, ClassVar
from unittest.mock import AsyncMock, patch
@@ -21,10 +22,19 @@ from posthog.models.user import User
from posthog.models.user_integration import UserIntegration
from posthog.storage import object_storage
-from products.tasks.backend.facade.profiles import TaskProfileError, get_task_profile
+from products.tasks.backend.facade.profiles import (
+ GithubAccess,
+ PrAuthorship,
+ Repository,
+ TaskProfileError,
+ TaskRunOptions,
+ TaskRunOptionsError,
+ get_task_profile,
+)
from products.tasks.backend.models import (
MAX_PENDING_FOLLOWUP_CONTENT_CHARS,
MAX_PENDING_FOLLOWUP_MESSAGES,
+ MCP_GATEWAY_SERVER_ALLOWLIST_STATE_KEY,
TASK_OWNERSHIP_VERSION_STATE_KEY,
SandboxEnvironment,
SandboxSnapshot,
@@ -34,6 +44,7 @@ from products.tasks.backend.models import (
TaskThreadMessage,
bump_task_activity,
)
+from products.tasks.backend.run_options import run_options_record
BUSINESS_KNOWLEDGE = get_task_profile("business_knowledge")
@@ -41,6 +52,15 @@ BUSINESS_KNOWLEDGE = get_task_profile("business_knowledge")
# clock did *not* move.
STALE_ACTIVITY_AT = datetime(2020, 1, 1, tzinfo=UTC)
+_VOLATILE_RUN_STATE_KEYS = frozenset({"startup_requested_at", TASK_OWNERSHIP_VERSION_STATE_KEY})
+
+
+def _task_settings(task: Task) -> tuple:
+ run = task.latest_run
+ assert run is not None
+ state = {key: value for key, value in run.state.items() if key not in _VOLATILE_RUN_STATE_KEYS}
+ return (task.repository, task.repositories, task.json_schema, task.runtime, run.branch, state)
+
class TestTask(TestCase):
organization: ClassVar[Organization]
@@ -175,6 +195,180 @@ class TestTask(TestCase):
self.assertFalse(Task.objects.filter(team=self.team).exists())
+ @parameterized.expand(
+ [
+ ("model", {"model": "claude-sonnet-5"}, TaskRunOptions(model="claude-sonnet-5")),
+ ("adapter", {"runtime_adapter": "codex"}, TaskRunOptions(adapter="codex")),
+ ("reasoning_effort", {"reasoning_effort": "high"}, TaskRunOptions(reasoning_effort="high")),
+ (
+ "repositories",
+ {"repositories": ["posthog/posthog"], "branch": "main"},
+ TaskRunOptions(repositories=(Repository(name="posthog/posthog", initial_branch="main"),)),
+ ),
+ (
+ "sandbox_template",
+ {"sandbox_template": "autoresearch_base"},
+ TaskRunOptions(sandbox_template="autoresearch_base"),
+ ),
+ ("output_schema", {"output_schema": {"type": "object"}}, TaskRunOptions(output_schema={"type": "object"})),
+ ("idle_minutes", {"inactivity_timeout_seconds": 300}, TaskRunOptions(idle_minutes=5)),
+ ("github_access", {"github_read_access": True}, TaskRunOptions(github_access=GithubAccess.READ)),
+ ("mcp_scopes", {"posthog_mcp_scopes": "read_only"}, TaskRunOptions(mcp_scopes="read_only")),
+ ("permission_mode", {"initial_permission_mode": "plan"}, TaskRunOptions(permission_mode="plan")),
+ ("context_window", {"extra_run_state": {"context_window": "1m"}}, TaskRunOptions(context_window="1m")),
+ ("fast_mode", {"extra_run_state": {"fast_mode": True}}, TaskRunOptions(fast_mode=True)),
+ ("auto_publish", {"extra_run_state": {"auto_publish": True}}, TaskRunOptions(auto_publish=True)),
+ (
+ "pr_authorship_mode",
+ {"extra_run_state": {"pr_authorship_mode": "user"}},
+ TaskRunOptions(pr_authorship_mode=PrAuthorship.USER),
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_run_options_build_the_same_task_as_the_legacy_arguments(
+ self, name: str, legacy_kwargs: dict, options: TaskRunOptions, _mock_execute_workflow
+ ) -> None:
+ user = User.objects.create(email=f"{name}@test.com")
+ Integration.objects.create(team=self.team, kind="github", config={})
+ create = partial(
+ Task.create_and_run,
+ team=self.team,
+ title="t",
+ description="d",
+ user_id=user.id,
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+
+ legacy = create(**legacy_kwargs)
+ from_options = create(options=options)
+ legacy.refresh_from_db()
+ from_options.refresh_from_db()
+
+ self.assertEqual(_task_settings(from_options), _task_settings(legacy))
+ self.assertEqual((legacy.options, from_options.options), (None, run_options_record(options)))
+
+ @parameterized.expand(
+ [
+ ("same_argument", {"model": "claude-sonnet-5"}, TaskRunOptions(model="claude-opus-5")),
+ (
+ "repository_and_repositories",
+ {"repository": "posthog/posthog"},
+ TaskRunOptions(repositories=(Repository(name="posthog/posthog-js"),)),
+ ),
+ ("non_default_scopes", {"posthog_mcp_scopes": "read_only"}, TaskRunOptions(mcp_scopes="full")),
+ ("run_state_key", {"extra_run_state": {"fast_mode": True}}, TaskRunOptions(fast_mode=False)),
+ (
+ "template_in_run_state",
+ {"extra_run_state": {"sandbox_template": "default_base"}},
+ TaskRunOptions(sandbox_template="autoresearch_base"),
+ ),
+ (
+ "setting_in_run_state",
+ {"extra_run_state": {"model": "claude-opus-5"}},
+ TaskRunOptions(model="claude-sonnet-5"),
+ ),
+ ("no_github_access", {}, TaskRunOptions(github_access=GithubAccess.NONE)),
+ ]
+ )
+ def test_run_options_refuse_a_setting_they_cannot_apply(
+ self, name: str, legacy_kwargs: dict, options: TaskRunOptions
+ ) -> None:
+ user = User.objects.create(email=f"{name}@test.com")
+
+ with self.assertRaises(TaskRunOptionsError):
+ Task.create_and_run(
+ team=self.team,
+ title="t",
+ description="d",
+ user_id=user.id,
+ origin_product=Task.OriginProduct.USER_CREATED,
+ options=options,
+ **legacy_kwargs,
+ )
+
+ self.assertFalse(Task.objects.filter(team=self.team).exists())
+
+ @parameterized.expand([("empty", []), ("one_server", ["server-1"])])
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_run_options_keep_the_mcp_server_allowlist(
+ self, name: str, server_ids: list[str], _mock_execute_workflow
+ ) -> None:
+ user = User.objects.create(email=f"{name}@test.com")
+ create = partial(
+ Task.create_and_run,
+ team=self.team,
+ title="t",
+ description="d",
+ user_id=user.id,
+ origin_product=Task.OriginProduct.WORKFLOW,
+ mcp_builtin_agent_key="workflow",
+ )
+
+ legacy = create(mcp_gateway_server_ids=server_ids)
+ from_options = create(options=TaskRunOptions(mcp_server_ids=tuple(server_ids)))
+
+ self.assertEqual(
+ (
+ (legacy.state or {}).get(MCP_GATEWAY_SERVER_ALLOWLIST_STATE_KEY),
+ (from_options.state or {}).get(MCP_GATEWAY_SERVER_ALLOWLIST_STATE_KEY),
+ ),
+ (server_ids, server_ids),
+ )
+
+ @parameterized.expand(
+ [
+ ("runtime", TaskRunOptions(runtime="pi"), ("pi", [])),
+ (
+ "repositories",
+ TaskRunOptions(repositories=(Repository(name="posthog/posthog"),)),
+ ("acp", ["posthog/posthog"]),
+ ),
+ ]
+ )
+ def test_create_without_run_applies_task_settings(
+ self, name: str, options: TaskRunOptions, expected: tuple[str, list[str]]
+ ) -> None:
+ user = User.objects.create(email=f"{name}@test.com")
+ Integration.objects.create(team=self.team, kind="github", config={})
+
+ task = Task.create_without_run(
+ team=self.team,
+ title="t",
+ description="d",
+ user_id=user.id,
+ origin_product=Task.OriginProduct.USER_CREATED,
+ options=options,
+ )
+
+ task.refresh_from_db()
+ self.assertEqual((task.runtime, task.repositories), expected)
+
+ @parameterized.expand(
+ [
+ ("model", TaskRunOptions(model="claude-sonnet-5")),
+ ("read_only", TaskRunOptions(github_access=GithubAccess.READ, mcp_scopes="read_only")),
+ (
+ "initial_branch",
+ TaskRunOptions(repositories=(Repository(name="posthog/posthog", initial_branch="main"),)),
+ ),
+ ]
+ )
+ def test_create_without_run_refuses_settings_that_need_a_run(self, name: str, options: TaskRunOptions) -> None:
+ user = User.objects.create(email=f"{name}@test.com")
+
+ with self.assertRaises(TaskRunOptionsError):
+ Task.create_without_run(
+ team=self.team,
+ title="t",
+ description="d",
+ user_id=user.id,
+ origin_product=Task.OriginProduct.USER_CREATED,
+ options=options,
+ )
+
+ self.assertFalse(Task.objects.filter(team=self.team).exists())
+
@parameterized.expand([("committed", False), ("rolled_back", True)])
def test_create_and_run_captures_only_committed_tasks(self, _name: str, rolled_back: bool) -> None:
user = User.objects.create(email="[email protected]")