: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): allow per-run model and reasoning settings (#103365)
snitkdan-pheec565e44b94
diff --git a/docs/internal/canvas-connectors.md b/docs/internal/canvas-connectors.mdindex 01d46902b041..390a44c2cccd 100644--- a/docs/internal/canvas-connectors.md+++ b/docs/internal/canvas-connectors.md@@ -11,6 +11,10 @@ but does not change the space's repository settings. The viewer must have accessand must submit the form before a run starts. Omitting both fields opens the usual empty task form.Do not use `tasks.create_and_run` for a repository override: that action inherits the space settings.+`tasks.create_and_run` accepts optional `model` and `reasoning_effort` fields (from the task model catalogue)+that apply to that one task and do not change saved run preferences. `reasoning_effort` requires `model`.+A retry with the same `idempotency_key` returns the existing task even if these fields change.+`ph.openExternal(url)` accepts HTTPS GitHub PR links as well as PostHog HTTPS URLs. GitHub linksmust use `github.com`, with no credentials, custom port, or query string. PR overview, files,commits, and checks paths are allowed, including fragment links. The host opens these PR linksdiff --git a/products/canvas/backend/actions.py b/products/canvas/backend/actions.pyindex 831e610bf365..563775cfeaeb 100644--- a/products/canvas/backend/actions.py+++ b/products/canvas/backend/actions.py@@ -81,6 +81,12 @@ class TaskCreatePayloadSerializer(serializers.Serializer):class TaskCreateAndRunPayloadSerializer(TaskCreatePayloadSerializer):idempotency_key = serializers.UUIDField(help_text="Reuse this UUID when retrying the same cloud task request.")+ model = serializers.CharField(+ required=False, max_length=255, help_text="Task model identifier. Omit to use the viewer's default model."+ )+ reasoning_effort = serializers.CharField(+ required=False, max_length=32, help_text="Reasoning effort supported by the selected model. Requires model."+ )def _create_annotation(team_id: int, user_id: int, canvas: "Canvas", payload: dict[str, Any]) -> dict[str, Any]:@@ -122,6 +128,8 @@ def _create_and_run_task(team_id: int, user_id: int, canvas: "Canvas", payload:description=payload["description"],idempotency_key=payload["idempotency_key"],before_create=check_usage,+ model=payload.get("model"),+ reasoning_effort=payload.get("reasoning_effort"),)return {"task_id": str(run.task_id), "run_id": str(run.id), "status": run.status}@@ -186,16 +194,19 @@ CANVAS_ACTIONS: dict[str, CanvasAction] = {),CanvasAction(verb="tasks.create_and_run",- summary="Create and start a cloud task in this space with default settings.",+ summary="Create and start a cloud task in this space, with optional model settings.",destructive=False,payload_serializer=TaskCreateAndRunPayloadSerializer,execute=_create_and_run_task,required_scopes=("task:write",),starts_cloud_run=True,usage=(- "Payload `{title, description?, idempotency_key}` returns `{task_id, run_id, status}`. "+ "Payload `{title, description?, idempotency_key, model?, reasoning_effort?}` returns "+ "`{task_id, run_id, status}`. ""Creates a task in the canvas's space as the viewer and queues its cloud run. ""Inherits the space's repositories and the viewer's default run settings. "+ "Optional model and reasoning_effort (from the task model catalogue) override those defaults for "+ "this task only; reasoning_effort requires model. ""The standard cloud access and usage limits apply. This action uses paid compute. ""Use a 'Start cloud task' button and disable it while the request is pending. ""Generate a UUID for idempotency_key once per intended task and reuse it on retries; "diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex f21a23608a5a..c2a9003c1e6e 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -2176,8 +2176,37 @@ class TestCanvasActions(CanvasAPIBaseTest):assert task.title == "Follow up"assert not task.runs.exists()- @parameterized.expand([("without_repository", []), ("space_repositories", ["example/app", "example/api"])])- def test_cloud_task_uses_space_and_viewer_defaults_once(self, _name: str, repositories: list[str]) -> None:+ @parameterized.expand(+ [+ (+ "without_repository",+ [],+ {},+ {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "medium"},+ ),+ (+ "space_repositories",+ ["example/app", "example/api"],+ {},+ {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "medium"},+ ),+ (+ "selected_model",+ [],+ {"model": "claude-opus-4-8", "reasoning_effort": "high"},+ {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"},+ ),+ (+ "selected_model_default_effort",+ [],+ {"model": "claude-opus-4-8"},+ {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": None},+ ),+ ]+ )+ def test_cloud_task_uses_space_and_viewer_defaults_once(+ self, _name: str, repositories: list[str], selection: dict[str, str], expected_state: dict[str, str | None]+ ) -> None:canvas_id = self._actions_canvas(verbs=("tasks.create_and_run",))integration = Integration.objects.create(team=self.team, kind="github", config={})self.channel.repositories = repositories@@ -2202,6 +2231,7 @@ class TestCanvasActions(CanvasAPIBaseTest):"title": "Review the signup flow","description": "Check the empty state.","idempotency_key": str(uuid4()),+ **selection,}with (@@ -2217,7 +2247,9 @@ class TestCanvasActions(CanvasAPIBaseTest):):response = self._invoke(canvas_id, "tasks.create_and_run", payload)usage.return_value = SimpleNamespace(is_rate_limited=True, limit_type="burst", reset_at=None, is_pro=False)- retry = self._invoke(canvas_id, "tasks.create_and_run", payload)+ retry = self._invoke(+ canvas_id, "tasks.create_and_run", {**payload, "model": "gpt-5.5", "reasoning_effort": "low"}+ )new_request = self._invoke(canvas_id, "tasks.create_and_run", {**payload, "idempotency_key": str(uuid4())})assert response.status_code == status.HTTP_200_OK, response.json()@@ -2231,12 +2263,41 @@ class TestCanvasActions(CanvasAPIBaseTest):assert task.repositories == repositoriesassert task.github_integration_id == integration.idassert run.environment == TaskRun.Environment.CLOUD- assert run.state["model"] == "gpt-5.5"- assert run.state["runtime_adapter"] == "codex"- assert run.state["reasoning_effort"] == "medium"+ assert {key: run.state.get(key) for key in expected_state} == expected_stateassert task.runs.count() == 1dispatch.assert_called_once()+ @parameterized.expand(+ [+ ("unknown_model", {"model": "unknown-model"}),+ ("unsupported_effort", {"model": "gpt-5.5", "reasoning_effort": "invalid"}),+ ("effort_without_model", {"reasoning_effort": "high"}),+ ]+ )+ def test_cloud_task_rejects_invalid_model_selection_without_creating_work(+ self, _name: str, selection: dict[str, str]+ ) -> None:+ canvas_id = self._actions_canvas(verbs=("tasks.create_and_run",))++ with (+ patch(+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",+ return_value=DesktopAccessDecision.ALLOWED,+ ),+ patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=None),+ patch("products.tasks.backend.temporal.client.execute_task_processing_workflow") as dispatch,+ ):+ response = self._invoke(+ canvas_id,+ "tasks.create_and_run",+ {"title": "Review", "idempotency_key": str(uuid4()), **selection},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert not Task.objects.exists()+ assert not TaskRun.objects.exists()+ dispatch.assert_not_called()+@parameterized.expand([("access_denied", False, False, 403), ("usage_limited", True, True, 429)])def test_cloud_task_checks_access_and_usage_before_creating_work(self, _name: str, allowed: bool, limited: bool, expected_status: intdiff --git a/products/tasks/backend/facade/canvas_tasks.py b/products/tasks/backend/facade/canvas_tasks.pyindex c0420eeb4cb5..faf87f53ff8d 100644--- a/products/tasks/backend/facade/canvas_tasks.py+++ b/products/tasks/backend/facade/canvas_tasks.py@@ -18,6 +18,8 @@ def create_and_run_channel_task(description: str,idempotency_key: UUID,before_create: Callable[[], None],+ model: str | None = None,+ reasoning_effort: str | None = None,) -> TaskRunDTO:with transaction.atomic():channel = (@@ -39,6 +41,7 @@ def create_and_run_channel_task(raise ValueError("The previous task has no run. Open the task to start work.")run_id = latest_run.idelse:+ run_options = _run_options(model, reasoning_effort)before_create()task = api.create_task(team_id,@@ -50,7 +53,7 @@ def create_and_run_channel_task("origin_key": origin_key,},)- result = api.run_task(task.id, team_id, user_id, validated_data={})+ result = api.run_task(task.id, team_id, user_id, validated_data=run_options)if result is None:raise ValueError("The task is no longer available.")if result.error is not None:@@ -63,3 +66,25 @@ def create_and_run_channel_task(if run is None:raise ValueError("The cloud run is no longer available.")return run+++def _run_options(model: str | None, reasoning_effort: str | None) -> dict[str, str]:+ """Run selection for `api.run_task`; empty when the caller pinned nothing, so saved defaults apply."""+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the import path+ get_reasoning_effort_error,+ get_runtime_adapter_for_model,+ )++ if model is None:+ if reasoning_effort is not None:+ raise ValueError("Select a model before setting reasoning effort.")+ return {}+ runtime_adapter = get_runtime_adapter_for_model(model)+ if runtime_adapter is None:+ raise ValueError("This model is not available. Select a model from the task model catalogue.")+ if error := get_reasoning_effort_error(runtime_adapter, model, reasoning_effort):+ raise ValueError(error)+ run_options = {"model": model, "runtime_adapter": runtime_adapter.value}+ if reasoning_effort is not None:+ run_options["reasoning_effort"] = reasoning_effort+ return run_options