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(wizard): let agents start and check cloud setup runs (#118853)

Rafael Audibert1c0a6082eb3d
diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.md
index 7351cb5f9872..3d6cac1800c2 100644
--- a/docs/internal/wizard-runs.md
+++ b/docs/internal/wizard-runs.md
@@ -78,12 +78,33 @@ Local agents can create runs and update runs they created.
The browser does not offer cancellation for local runs because the server cannot stop a local Wizard process. Users stop those runs in their terminal.
These operations accept OAuth tokens with `wizard_run:write`; browser sessions can also create and manage runs.
Run creation uses the existing per-user creation throttle for both environments.
-Cloud creation requires a signed-in browser session and enabled cloud execution.
+Cloud creation on this endpoint requires a signed-in browser session and enabled cloud execution.
+Agents start cloud runs through the install endpoint instead.
Cloud lifecycle updates are owned by the Wizard Worker.
Run lookups, transitions, and artifact access verify the project boundary.
A user cannot update another user's local run.
+## Agent-started cloud runs
+
+An agent connected to the MCP server starts and follows a cloud run through two endpoints:
+
+```text
+POST /api/projects/{project_id}/wizard/installs/
+GET /api/projects/{project_id}/wizard/installs/{run_id}/
+```
+
+The request takes a `repository` in `owner/name` format, an optional `branch`, and an optional `idempotency_key`.
+The server picks the `posthog-integration` program and uses the project's GitHub integration.
+When the repository is missing from the integration's cached repository list, the server refreshes the list once, at most once a minute, before it refuses with `repository_not_accessible`.
+A `branch` is cloned instead of the default branch and becomes the pull request's base branch.
+The status response returns `status`, `stage`, `error_code`, `error_message`, `pull_request_url`, the task names and statuses, and a `next_step` sentence for the agent to relay.
+
+Both endpoints accept browser sessions and OAuth access tokens, not personal API keys.
+Start needs `task:write` and status needs `task:read`.
+Both return `404` unless cloud execution is enabled.
+Start uses the same per-user admission limits as browser-started cloud runs, and checks the AI gateway access rules with the caller's IP.
+
## Cloud execution
Cloud creation verifies that the project has a GitHub integration with access to the requested repository.
diff --git a/products/wizard/backend/facade/api.py b/products/wizard/backend/facade/api.py
index 52137133e84b..88fad4389087 100644
--- a/products/wizard/backend/facade/api.py
+++ b/products/wizard/backend/facade/api.py
@@ -21,8 +21,10 @@ from products.wizard.backend.facade.contracts import (
CreateWizardRunInput,
ListWizardRunsInput,
RecordWizardScanInput,
+ StartWizardInstallInput,
UpdateWizardRunTaskInput,
UpsertWizardSessionInput,
+ WizardInstallStatusDTO,
WizardProgram,
WizardRunArtifactDTO,
WizardRunCreationResult,
@@ -43,6 +45,7 @@ from products.wizard.backend.logic import (
sessions,
)
from products.wizard.backend.logic.artifacts import service as artifacts
+from products.wizard.backend.logic.installs import service as installs
from products.wizard.backend.logic.runs import pubsub as run_pubsub
from products.wizard.backend.logic.sessions import pubsub
from products.wizard.backend.tool_catalog.catalog import tool_catalog_json
@@ -133,6 +136,17 @@ def get_run(team_id: int, run_id: UUID) -> WizardRunDTO:
return run_service.get_run(team_id, run_id)
+def start_install(params: StartWizardInstallInput) -> WizardRunCreationResult:
+ """
+ Starts the PostHog setup program in the cloud on a GitHub repository of the project.
+ """
+ return installs.start_install(params)
+
+
+def get_install_status(team_id: int, run_id: UUID) -> WizardInstallStatusDTO:
+ return installs.get_install_status(team_id, run_id)
+
+
@asynccontextmanager
async def subscribe_to_run_updates(team_id: int, run_id: UUID) -> AsyncIterator[PubSub]:
async with run_pubsub.subscribe(team_id, run_id) as subscription:
@@ -199,5 +213,9 @@ def validate_git_repository(repository: str) -> None:
run_service.validate_git_repository_name(repository)
+def validate_git_branch(branch: str) -> None:
+ run_service.validate_git_branch_name(branch)
+
+
def validate_wizard_version(wizard_version: object) -> str:
return validate_wizard_version_value(wizard_version)
diff --git a/products/wizard/backend/facade/contracts.py b/products/wizard/backend/facade/contracts.py
index 1c1e3b4f0f60..e7b0bc0921ad 100644
--- a/products/wizard/backend/facade/contracts.py
+++ b/products/wizard/backend/facade/contracts.py
@@ -104,6 +104,8 @@ class LocalFolderWorkspace:
@frozen
class GitRepositoryWorkspace:
repository: str
+ # None means the repository's default branch.
+ branch: str | None = None
type: Literal["git_repository"] = "git_repository"
@@ -139,6 +141,19 @@ class CreateWizardRunInput:
idempotency_key: str | None = None
+@frozen
+class StartWizardInstallInput:
+ """
+ Starts the PostHog setup program in the cloud on a GitHub repository of the project.
+ """
+
+ team_id: int
+ created_by_id: int
+ repository: str
+ branch: str | None = None
+ idempotency_key: str | None = None
+
+
@frozen
class WizardRunCreationResult:
run: "WizardRunDTO"
@@ -216,6 +231,13 @@ class WizardRunDTO:
tasks: tuple[WizardRunTaskDTO, ...] = ()
+@frozen
+class WizardInstallStatusDTO:
+ run: WizardRunDTO
+ pull_request_url: str | None
+ next_step: str
+
+
@frozen
class ListWizardRunsInput:
team_id: int
diff --git a/products/wizard/backend/facade/enums.py b/products/wizard/backend/facade/enums.py
index 8c19e1ffb3d4..9aa804919f71 100644
--- a/products/wizard/backend/facade/enums.py
+++ b/products/wizard/backend/facade/enums.py
@@ -36,12 +36,12 @@ class WizardTaskStatus(LabeledStrEnum):
FAILED = "failed", "failed"
-class WizardRunStatus(StrEnum):
- CREATED = "created"
- RUNNING = "running"
- COMPLETED = "completed"
- FAILED = "failed"
- CANCELLED = "cancelled"
+class WizardRunStatus(LabeledStrEnum):
+ CREATED = "created", "created"
+ RUNNING = "running", "running"
+ COMPLETED = "completed", "completed"
+ FAILED = "failed", "failed"
+ CANCELLED = "cancelled", "cancelled"
class WizardRunDispatchStatus(StrEnum):
@@ -49,12 +49,12 @@ class WizardRunDispatchStatus(StrEnum):
DISPATCHED = "dispatched"
-class WizardRunStage(StrEnum):
- DISPATCHING = "dispatching"
- PROVISIONING = "provisioning"
- PREPARING_WORKSPACE = "preparing_workspace"
- EXECUTING_WIZARD = "executing_wizard"
- CREATING_ARTIFACTS = "creating_artifacts"
+class WizardRunStage(LabeledStrEnum):
+ DISPATCHING = "dispatching", "dispatching"
+ PROVISIONING = "provisioning", "provisioning"
+ PREPARING_WORKSPACE = "preparing_workspace", "preparing_workspace"
+ EXECUTING_WIZARD = "executing_wizard", "executing_wizard"
+ CREATING_ARTIFACTS = "creating_artifacts", "creating_artifacts"
class WizardWorkerCleanupStatus(StrEnum):
diff --git a/products/wizard/backend/facade/errors.py b/products/wizard/backend/facade/errors.py
index 78013b27d837..b817d545f36f 100644
--- a/products/wizard/backend/facade/errors.py
+++ b/products/wizard/backend/facade/errors.py
@@ -17,6 +17,10 @@ class InvalidRepositoryError(Exception):
pass
+class InvalidBranchError(Exception):
+ pass
+
+
class WizardProgramNotAvailableError(Exception):
pass
diff --git a/products/wizard/backend/facade/validation.py b/products/wizard/backend/facade/validation.py
index 56b351eb49ab..46bb21731ea7 100644
--- a/products/wizard/backend/facade/validation.py
+++ b/products/wizard/backend/facade/validation.py
@@ -86,3 +86,9 @@ def validate_workspace_metadata_value(metadata: object, key: str) -> str:
if not isinstance(value, str):
raise ValueError(f"Wizard workspace metadata field {key!r} must be a string")
return value
+
+
+def validate_optional_workspace_metadata_value(metadata: object, key: str) -> str | None:
+ if isinstance(metadata, dict) and metadata.get(key) is None:
+ return None
+ return validate_workspace_metadata_value(metadata, key)
diff --git a/products/wizard/backend/logic/artifacts/store.py b/products/wizard/backend/logic/artifacts/store.py
index 62a3c62472a8..35565263bfe8 100644
--- a/products/wizard/backend/logic/artifacts/store.py
+++ b/products/wizard/backend/logic/artifacts/store.py
@@ -87,6 +87,15 @@ def upsert_pull_request(
return result
+def get_pull_request_url(team_id: int, run_id: UUID) -> str | None:
+ return (
+ WizardRunArtifact.objects.for_team(team_id)
+ .filter(run_id=run_id, type=WizardRunArtifactType.PULL_REQUEST.value)
+ .values_list("external_url", flat=True)
+ .first()
+ )
+
+
def list_artifacts(team_id: int, run_id: UUID) -> list[WizardRunArtifactDTO]:
artifacts = WizardRunArtifact.objects.for_team(team_id).filter(run_id=run_id).order_by("created_at", "id")
return [record_to_artifact(artifact) for artifact in artifacts]
diff --git a/products/wizard/backend/logic/installs/next_step.py b/products/wizard/backend/logic/installs/next_step.py
new file mode 100644
index 000000000000..1a3ae6f28085
--- /dev/null
+++ b/products/wizard/backend/logic/installs/next_step.py
@@ -0,0 +1,65 @@
+from products.wizard.backend.facade.contracts import WizardRunDTO
+from products.wizard.backend.facade.enums import WizardRunErrorCode, WizardRunStage, WizardRunStatus
+
+LOCAL_WIZARD_COMMAND = "npx -y @posthog/wizard@latest"
+
+_CHECK_AGAIN = "Check the status again in about 30 seconds."
+_START_AGAIN = "Start a new run when the user is ready."
+_RUN_LOCALLY = f"Start a new run, or suggest running Wizard on their machine with `{LOCAL_WIZARD_COMMAND}`."
+
+
+def next_step(run: WizardRunDTO, pull_request_url: str | None) -> str:
+ """
+ A sentence an agent can relay to the user about what happens next with a cloud setup run.
+ """
+ match run.status:
+ case WizardRunStatus.CREATED:
+ return f"The setup agent is queued. {_CHECK_AGAIN}"
+ case WizardRunStatus.RUNNING:
+ return f"{_running_stage(run.stage)} {_CHECK_AGAIN}"
+ case WizardRunStatus.COMPLETED if pull_request_url is not None:
+ return (
+ "The setup agent opened a pull request. Share the link with the user so they can review and merge it."
+ )
+ case WizardRunStatus.COMPLETED:
+ return (
+ "The setup agent finished without changing any files. The repository may already have PostHog set up."
+ )
+ case WizardRunStatus.CANCELLED:
+ return f"This run was canceled. {_START_AGAIN}"
+ case _:
+ return _failure(run.error_code)
+
+
+def _running_stage(stage: WizardRunStage | None) -> str:
+ match stage:
+ case WizardRunStage.PREPARING_WORKSPACE:
+ return "The setup agent is cloning the repository."
+ case WizardRunStage.EXECUTING_WIZARD:
+ return "The setup agent is adding PostHog to the code. This usually takes a few minutes."
+ case WizardRunStage.CREATING_ARTIFACTS:
+ return "The setup agent is opening a pull request."
+ case _:
+ return "The setup agent is starting a cloud workspace."
+
+
+def _failure(error_code: str | None) -> str:
+ match error_code:
+ case WizardRunErrorCode.REPOSITORY_ACCESS_FAILED:
+ return (
+ "PostHog could not access the repository. Ask the user to give the PostHog GitHub App access to it, "
+ "then start a new run."
+ )
+ case WizardRunErrorCode.WORKSPACE_PREPARATION_FAILED:
+ return "The setup agent could not clone the repository. Check that the branch exists, then start a new run."
+ case WizardRunErrorCode.PROVISIONING_FAILED | WizardRunErrorCode.DISPATCH_FAILED:
+ return "PostHog could not start a cloud workspace. Wait a few minutes, then start a new run."
+ case WizardRunErrorCode.ARTIFACT_CREATION_FAILED:
+ return (
+ "The setup agent made changes but could not open a pull request. Check that the PostHog GitHub App "
+ "can write to the repository, then start a new run."
+ )
+ case WizardRunErrorCode.TIMEOUT:
+ return f"The run took too long and stopped. {_RUN_LOCALLY}"
+ case _:
+ return f"The setup agent could not finish. {_RUN_LOCALLY}"
diff --git a/products/wizard/backend/logic/installs/service.py b/products/wizard/backend/logic/installs/service.py
new file mode 100644
index 000000000000..eec8f86824e9
--- /dev/null
+++ b/products/wizard/backend/logic/installs/service.py
@@ -0,0 +1,53 @@
+from uuid import UUID, uuid4
+
+from products.wizard.backend.facade.contracts import (
+ CreateWizardRunInput,
+ GitRepositoryWorkspace,
+ StartWizardInstallInput,
+ WizardInstallStatusDTO,
+ WizardRunCreationResult,
+)
+from products.wizard.backend.facade.enums import WizardRunEnvironment
+from products.wizard.backend.facade.errors import RepositoryNotAccessibleError, WizardRunNotFoundError
+from products.wizard.backend.logic.artifacts import store as artifacts_store
+from products.wizard.backend.logic.installs.next_step import next_step
+from products.wizard.backend.logic.registry.config import POSTHOG_INTEGRATION_PROGRAM
+from products.wizard.backend.logic.runs import lifecycle, store
+from products.wizard.backend.logic.runs.repository_access import refresh_repository_cache
+from products.wizard.backend.logic.runs.validation import validate_git_branch_name, validate_git_repository_name
+from products.wizard.backend.observability.tracing import wizard_span
+
+
+@wizard_span("wizard.install.start")
+def start_install(params: StartWizardInstallInput) -> WizardRunCreationResult:
+ validate_git_repository_name(params.repository)
+ if params.branch is not None:
+ validate_git_branch_name(params.branch)
+
+ run_params = CreateWizardRunInput(
+ team_id=params.team_id,
+ created_by_id=params.created_by_id,
+ environment=WizardRunEnvironment.CLOUD,
+ workspace=GitRepositoryWorkspace(repository=params.repository, branch=params.branch),
+ program_id=POSTHOG_INTEGRATION_PROGRAM.id,
+ idempotency_key=params.idempotency_key or f"install-{uuid4()}",
+ )
+
+ try:
+ return lifecycle.create_run_with_result(run_params)
+ except RepositoryNotAccessibleError:
+ if not refresh_repository_cache(params.team_id):
+ raise
+ return lifecycle.create_run_with_result(run_params)
+
+
+def get_install_status(team_id: int, run_id: UUID) -> WizardInstallStatusDTO:
+ run = store.get_run(team_id, run_id)
+ if run.environment != WizardRunEnvironment.CLOUD:
+ raise WizardRunNotFoundError
+
+ pull_request_url = artifacts_store.get_pull_request_url(team_id, run.id)
+
+ return WizardInstallStatusDTO(
+ run=run, pull_request_url=pull_request_url, next_step=next_step(run, pull_request_url)
+ )
diff --git a/products/wizard/backend/logic/runs/__init__.py b/products/wizard/backend/logic/runs/__init__.py
index e8cee8aa714d..61d7e220a22c 100644
--- a/products/wizard/backend/logic/runs/__init__.py
+++ b/products/wizard/backend/logic/runs/__init__.py
@@ -11,7 +11,7 @@ from products.wizard.backend.logic.runs.lifecycle import (
update_run_stage,
update_run_task_list,
)
-from products.wizard.backend.logic.runs.validation import validate_git_repository_name
+from products.wizard.backend.logic.runs.validation import validate_git_branch_name, validate_git_repository_name
__all__ = [
"cancel_run",
@@ -24,6 +24,7 @@ __all__ = [
"start_run",
"transition_run",
"update_run_stage",
+ "validate_git_branch_name",
"validate_git_repository_name",
"update_run_task_list",
]
diff --git a/products/wizard/backend/logic/runs/mappers.py b/products/wizard/backend/logic/runs/mappers.py
index 33230d9de7ac..ffa826670177 100644
--- a/products/wizard/backend/logic/runs/mappers.py
+++ b/products/wizard/backend/logic/runs/mappers.py
@@ -15,7 +15,10 @@ from products.wizard.backend.facade.enums import (
WizardTaskStatus,
WizardWorkspaceType,
)
-from products.wizard.backend.facade.validation import validate_workspace_metadata_value
+from products.wizard.backend.facade.validation import (
+ validate_optional_workspace_metadata_value,
+ validate_workspace_metadata_value,
+)
from products.wizard.backend.logic.programs import program_from_mapping
from products.wizard.backend.models import WizardRun
@@ -24,8 +27,10 @@ def workspace_to_record(workspace: WizardWorkspace) -> tuple[WizardWorkspaceType
match workspace:
case LocalFolderWorkspace(project_name=project_name):
return WizardWorkspaceType.LOCAL_FOLDER, {"project_name": project_name}
- case GitRepositoryWorkspace(repository=repository):
+ case GitRepositoryWorkspace(repository=repository, branch=None):
return WizardWorkspaceType.GIT_REPOSITORY, {"repository": repository}
+ case GitRepositoryWorkspace(repository=repository, branch=branch):
+ return WizardWorkspaceType.GIT_REPOSITORY, {"repository": repository, "branch": branch}
def record_to_workspace(workspace_type: str, metadata: object) -> WizardWorkspace:
@@ -33,7 +38,10 @@ def record_to_workspace(workspace_type: str, metadata: object) -> WizardWorkspac
case WizardWorkspaceType.LOCAL_FOLDER:
return LocalFolderWorkspace(project_name=validate_workspace_metadata_value(metadata, "project_name"))
case WizardWorkspaceType.GIT_REPOSITORY:
- return GitRepositoryWorkspace(repository=validate_workspace_metadata_value(metadata, "repository"))
+ return GitRepositoryWorkspace(
+ repository=validate_workspace_metadata_value(metadata, "repository"),
+ branch=validate_optional_workspace_metadata_value(metadata, "branch"),
+ )
def record_to_run(run: WizardRun) -> WizardRunDTO:
diff --git a/products/wizard/backend/logic/runs/repository_access.py b/products/wizard/backend/logic/runs/repository_access.py
index fb71f70b972d..d8e1faa7ecf9 100644
--- a/products/wizard/backend/logic/runs/repository_access.py
+++ b/products/wizard/backend/logic/runs/repository_access.py
@@ -1,8 +1,16 @@
+import logging
+
+from django.core.cache import cache
+
from products.tasks.backend.facade import repo_selection
from products.wizard.backend.facade.errors import MissingGitHubIntegrationError, RepositoryNotAccessibleError
from products.wizard.backend.logic.runs.validation import validate_git_repository_name
from products.wizard.backend.observability.tracing import wizard_span
+logger = logging.getLogger(__name__)
+
+REPOSITORY_CACHE_MIN_REFRESH_INTERVAL_SECONDS = 60
+
@wizard_span("wizard.repository.authorize")
def authorize_git_repository_access(team_id: int, repository: str) -> int:
@@ -16,3 +24,31 @@ def authorize_git_repository_access(team_id: int, repository: str) -> int:
raise RepositoryNotAccessibleError
return integration_id
+
+
+def refresh_repository_cache(team_id: int) -> bool:
+ """
+ Sync the project's cached GitHub repository list. Returns whether a sync ran and succeeded.
+
+ The cached list can miss a repository added to the GitHub App a moment ago.
+ """
+ github = repo_selection.resolve_team_github_integration(team_id, team_only=True)
+ if github is None:
+ return False
+
+ # A sync pages through every repository of the installation. One reservation per interval stops concurrent
+ # misses, and repeated failures, from each starting their own sync.
+ reservation_key = f"wizard:repository-cache-refresh:{github.integration.id}"
+ if not cache.add(reservation_key, 1, timeout=REPOSITORY_CACHE_MIN_REFRESH_INTERVAL_SECONDS):
+ return False
+
+ try:
+ github.sync_repository_cache(min_refresh_interval_seconds=REPOSITORY_CACHE_MIN_REFRESH_INTERVAL_SECONDS)
+ except Exception:
+ logger.warning(
+ "wizard_repository_cache_refresh_failed",
+ exc_info=True,
+ extra={"team_id": team_id, "integration_id": github.integration.id},
+ )
+ return False
+ return True
diff --git a/products/wizard/backend/logic/runs/validation.py b/products/wizard/backend/logic/runs/validation.py
index ce3f9d7c662b..1ae4caccf7f8 100644
--- a/products/wizard/backend/logic/runs/validation.py
+++ b/products/wizard/backend/logic/runs/validation.py
@@ -1,4 +1,10 @@
-from products.wizard.backend.facade.errors import InvalidRepositoryError
+import re
+
+from products.wizard.backend.facade.errors import InvalidBranchError, InvalidRepositoryError
+
+GIT_BRANCH_NAME_MAX_LENGTH = 255
+# Stricter than git's ref name rules: it admits only the characters that branch names use in practice.
+_GIT_BRANCH_NAME_PATTERN = re.compile(r"^[A-Za-z0-9._/-]+$")
def validate_git_repository_name(repository: str) -> None:
@@ -6,3 +12,17 @@ def validate_git_repository_name(repository: str) -> None:
if not separator or not owner or not name or "/" in name:
raise InvalidRepositoryError
+
+
+def validate_git_branch_name(branch: str) -> None:
+ if (
+ not branch
+ or len(branch) > GIT_BRANCH_NAME_MAX_LENGTH
+ or _GIT_BRANCH_NAME_PATTERN.fullmatch(branch) is None
+ or branch.startswith(("-", "/", "."))
+ or branch.endswith(("/", ".", ".lock"))
+ or ".." in branch
+ or "//" in branch
+ or "/." in branch
+ ):
+ raise InvalidBranchError
diff --git a/products/wizard/backend/logic/workers/repository_publisher.py b/products/wizard/backend/logic/workers/repository_publisher.py
index 498904d8a62e..9319be1fc766 100644
--- a/products/wizard/backend/logic/workers/repository_publisher.py
+++ b/products/wizard/backend/logic/workers/repository_publisher.py
@@ -299,6 +299,7 @@ def create_pull_request(
title: str,
body: str,
source: str,
+ base_branch: str | None = None,
) -> RepositoryPullRequest:
repository_name = _repository_parts(repository)
integration = Integration.objects.filter(team_id=team_id, id=integration_id, kind="github").first()
@@ -309,7 +310,7 @@ def create_pull_request(
if github.organization().casefold() != repository_name.owner.casefold():
raise RepositoryPublishingError("GitHub integration does not own the repository.")
- base_branch = github.get_default_branch(repository_name.name)
+ base_branch = base_branch or github.get_default_branch(repository_name.name)
existing = _matching_pull_request(
github.list_pull_requests(repository_name.name),
repository,
diff --git a/products/wizard/backend/logic/workers/service.py b/products/wizard/backend/logic/workers/service.py
index c0345cd38f46..72cef9a68611 100644
--- a/products/wizard/backend/logic/workers/service.py
+++ b/products/wizard/backend/logic/workers/service.py
@@ -81,6 +81,7 @@ class GitRepositoryCloneRequest:
sandbox_id: str
github_integration_id: int
repository: str
+ branch: str | None = None
@frozen
@@ -101,6 +102,7 @@ class GitRepositoryHandoffRequest:
workspace_path: str
github_integration_id: int
repository: str
+ base_branch: str | None = None
@frozen
@@ -178,7 +180,9 @@ def clone_repository(request: GitRepositoryCloneRequest) -> str:
with wizard_span("wizard.repository.credentials"):
github_token = get_github_token(request.github_integration_id) or ""
with wizard_span("wizard.repository.clone") as span:
- clone_result = sandbox.clone_repository(request.repository, github_token=github_token, shallow=True)
+ clone_result = sandbox.clone_repository(
+ request.repository, github_token=github_token, shallow=True, branch=request.branch
+ )
span.set_attribute("process.exit.code", clone_result.exit_code)
_raise_for_failure(
@@ -316,6 +320,7 @@ def create_git_repository_handoff(request: GitRepositoryHandoffRequest) -> Wizar
integration_id=request.github_integration_id,
repository=request.repository,
head_branch=branch,
+ base_branch=request.base_branch,
title=PULL_REQUEST_TITLE,
body=handoff_body,
source="wizard",
diff --git a/products/wizard/backend/presentation/installs/__init__.py b/products/wizard/backend/presentation/installs/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/wizard/backend/presentation/installs/errors.py b/products/wizard/backend/presentation/installs/errors.py
new file mode 100644
index 000000000000..23e33661b165
--- /dev/null
+++ b/products/wizard/backend/presentation/installs/errors.py
@@ -0,0 +1,69 @@
+from typing import Never
+
+from rest_framework.exceptions import APIException, NotFound, Throttled, ValidationError
+
+from posthog.exceptions import Conflict
+
+from products.wizard.backend.facade.errors import (
+ ActiveWizardRunError,
+ InvalidBranchError,
+ InvalidRepositoryError,
+ InvalidWorkspaceEnvironmentError,
+ MissingGitHubIntegrationError,
+ RepositoryNotAccessibleError,
+ WizardProgramEnvironmentNotSupportedError,
+ WizardProgramNotAvailableError,
+ WizardRunDailyLimitError,
+ WizardRunHourlyLimitError,
+ WizardRunIdempotencyConflictError,
+)
+from products.wizard.backend.presentation.runs.errors import WIZARD_RUN_CREATION_ERRORS, WizardRunCreationError
+
+WizardInstallStartError = WizardRunCreationError | InvalidBranchError
+
+WIZARD_INSTALL_START_ERRORS = (*WIZARD_RUN_CREATION_ERRORS, InvalidBranchError)
+
+
+def install_start_api_error(error: WizardInstallStartError) -> APIException:
+ match error:
+ case InvalidRepositoryError():
+ return ValidationError("Enter a repository in owner/name format.", code="invalid_repository")
+ case InvalidBranchError():
+ return ValidationError("Enter a valid branch name, such as main.", code="invalid_branch")
+ case MissingGitHubIntegrationError():
+ return ValidationError(
+ "This project isn't connected to GitHub. Connect GitHub to the project, then try again.",
+ code="github_not_connected",
+ )
+ case RepositoryNotAccessibleError():
+ return ValidationError(
+ "PostHog can't access this repository. Add it to the repositories the PostHog GitHub App can "
+ "access, then try again.",
+ code="repository_not_accessible",
+ )
+ case ActiveWizardRunError():
+ return Conflict(
+ "You already have a setup run in progress for this project. Wait for it to finish, then try again.",
+ code="run_already_active",
+ )
+ case WizardRunIdempotencyConflictError():
+ return Conflict(
+ "This idempotency key was already used for a different setup run. Use a new key.",
+ code="idempotency_conflict",
+ )
+ case WizardRunHourlyLimitError():
+ return Throttled(detail="You've reached the hourly limit for setup runs. Try again in an hour.")
+ case WizardRunDailyLimitError():
+ return Throttled(detail="You've reached the daily limit for setup runs. Try again tomorrow.")
+ case (
+ WizardProgramNotAvailableError()
+ | WizardProgramEnvironmentNotSupportedError()
+ | InvalidWorkspaceEnvironmentError()
+ ):
+ return NotFound("Cloud setup runs aren't available for this project.")
+
+ _unexpected_install_start_error(error)
+
+
+def _unexpected_install_start_error(error: Never) -> Never:
+ raise AssertionError(f"Unexpected Wizard install start error: {error!r}")
diff --git a/products/wizard/backend/presentation/installs/serializers.py b/products/wizard/backend/presentation/installs/serializers.py
new file mode 100644
index 000000000000..4dddbcdd23a8
--- /dev/null
+++ b/products/wizard/backend/presentation/installs/serializers.py
@@ -0,0 +1,104 @@
+from rest_framework import serializers
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.enums import WizardRunStage, WizardRunStatus, WizardTaskStatus
+from products.wizard.backend.facade.errors import InvalidBranchError, InvalidRepositoryError
+
+
+class WizardInstallStartRequestSerializer(serializers.Serializer):
+ repository = serializers.CharField(
+ allow_blank=False,
+ max_length=255,
+ help_text=(
+ "GitHub repository to set up, in owner/name format. The project's GitHub connection must have access to it."
+ ),
+ )
+ branch = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ max_length=255,
+ help_text="Branch to start from and to open the pull request against. Defaults to the repository's default branch.",
+ )
+ idempotency_key = serializers.CharField(
+ required=False,
+ allow_blank=False,
+ max_length=255,
+ help_text="Unique key for this request. A retry with the same key returns the same run instead of starting another.",
+ )
+
+ def validate_repository(self, value: str) -> str:
+ repository = value.strip()
+ try:
+ wizard_facade.validate_git_repository(repository)
+ except InvalidRepositoryError:
+ raise serializers.ValidationError("Enter a repository in owner/name format.")
+ return repository
+
+ def validate_branch(self, value: str) -> str:
+ branch = value.strip()
+ try:
+ wizard_facade.validate_git_branch(branch)
+ except InvalidBranchError:
+ raise serializers.ValidationError("Enter a valid branch name, such as main.")
+ return branch
+
+
+class WizardInstallStartSerializer(serializers.Serializer):
+ run_id = serializers.UUIDField(read_only=True, help_text="ID of the setup run. Pass it to the status endpoint.")
+ status = serializers.ChoiceField(
+ read_only=True,
+ choices=WizardRunStatus.choices,
+ help_text="Current lifecycle status of the setup run.",
+ )
+ url = serializers.URLField(read_only=True, help_text="PostHog page where the user can follow their setup runs.")
+
+
+class WizardInstallTaskSerializer(serializers.Serializer):
+ name = serializers.CharField(source="title", read_only=True, help_text="Task the setup agent planned.")
+ status = serializers.ChoiceField(
+ read_only=True,
+ choices=WizardTaskStatus.choices,
+ help_text="Current task status reported by the setup agent.",
+ )
+
+
+class WizardInstallStatusSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ source="run.status",
+ read_only=True,
+ choices=WizardRunStatus.choices,
+ help_text="Lifecycle status of the setup run. created and running mean it is still in progress.",
+ )
+ stage = serializers.ChoiceField(
+ source="run.stage",
+ read_only=True,
+ allow_null=True,
+ choices=WizardRunStage.choices,
+ help_text="Step the setup run is on while it is in progress, or null otherwise.",
+ )
+ error_code = serializers.CharField(
+ source="run.error_code",
+ read_only=True,
+ allow_null=True,
+ help_text="Machine-readable failure reason, or null if the run has not failed.",
+ )
+ error_message = serializers.CharField(
+ source="run.error_message",
+ read_only=True,
+ allow_null=True,
+ help_text="Failure explanation, or null if the run has not failed.",
+ )
+ pull_request_url = serializers.URLField(
+ read_only=True,
+ allow_null=True,
+ help_text="Pull request with the setup changes, or null until the run opens one.",
+ )
+ tasks = WizardInstallTaskSerializer(
+ source="run.tasks",
+ many=True,
+ read_only=True,
+ help_text="Tasks the setup agent planned, in order.",
+ )
+ next_step = serializers.CharField(
+ read_only=True, help_text="What happens next, in a sentence to relay to the user."
+ )
diff --git a/products/wizard/backend/presentation/installs/views.py b/products/wizard/backend/presentation/installs/views.py
new file mode 100644
index 000000000000..d90583100398
--- /dev/null
+++ b/products/wizard/backend/presentation/installs/views.py
@@ -0,0 +1,128 @@
+from typing import cast
+from uuid import UUID
+
+from django.conf import settings
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import status, viewsets
+from rest_framework.exceptions import NotFound
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import User
+from posthog.utils import absolute_uri
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import StartWizardInstallInput
+from products.wizard.backend.facade.errors import WizardRunNotFoundError
+from products.wizard.backend.presentation.installs.errors import (
+ WIZARD_INSTALL_START_ERRORS,
+ WizardInstallStartError,
+ install_start_api_error,
+)
+from products.wizard.backend.presentation.installs.serializers import (
+ WizardInstallStartRequestSerializer,
+ WizardInstallStartSerializer,
+ WizardInstallStatusSerializer,
+)
+from products.wizard.backend.presentation.permissions import WizardInstallAuthenticationRequired
+from products.wizard.backend.presentation.runs.serializers import WizardRunErrorSerializer
+from products.wizard.backend.presentation.security import refuse_blocked_gateway_identity
+from products.wizard.backend.presentation.throttles import WizardRunCreateThrottle, WizardRunReadThrottle
+
+
+class WizardInstallViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """
+ Start a cloud setup run on a GitHub repository of the project and check on it.
+
+ Agents connected through MCP call these endpoints with an OAuth access token.
+ """
+
+ permission_classes = [WizardInstallAuthenticationRequired]
+ scope_object = "task"
+ scope_object_read_actions = ["retrieve"]
+ scope_object_write_actions = ["create"]
+ http_method_names = ["get", "post", "head", "options"]
+ lookup_field = "run_id"
+ lookup_value_regex = "[0-9a-fA-F-]{36}"
+ pagination_class = None
+
+ def get_throttles(self) -> list:
+ if self.action == "create":
+ return [WizardRunCreateThrottle()]
+ return [WizardRunReadThrottle()]
+
+ @validated_request(
+ request_serializer=WizardInstallStartRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=WizardInstallStartSerializer, description="A retry returned the run it already started."
+ ),
+ 201: OpenApiResponse(response=WizardInstallStartSerializer, description="The setup run started."),
+ 400: OpenApiResponse(response=WizardRunErrorSerializer),
+ 403: OpenApiResponse(response=WizardRunErrorSerializer),
+ 404: OpenApiResponse(response=WizardRunErrorSerializer),
+ 409: OpenApiResponse(response=WizardRunErrorSerializer),
+ 429: OpenApiResponse(response=WizardRunErrorSerializer),
+ },
+ summary="Start a setup run",
+ description=(
+ "Start the setup agent in the cloud on a GitHub repository of this project. "
+ "It adds PostHog to the code and opens a pull request. "
+ "Each user can have one setup run active per project at a time."
+ ),
+ )
+ # POST /projects/:projectId/wizard/installs
+ def create(self, request: ValidatedRequest, *args: object, **kwargs: object) -> Response:
+ user = cast(User, request.user)
+ self._require_cloud_execution()
+ refuse_blocked_gateway_identity(request, self.team.organization_id, call_site="wizard_install")
+
+ try:
+ result = wizard_facade.start_install(
+ StartWizardInstallInput(
+ team_id=self.team_id,
+ created_by_id=user.id,
+ repository=request.validated_data["repository"],
+ branch=request.validated_data.get("branch"),
+ idempotency_key=request.validated_data.get("idempotency_key"),
+ )
+ )
+ except WIZARD_INSTALL_START_ERRORS as error:
+ raise install_start_api_error(cast(WizardInstallStartError, error))
+
+ data = WizardInstallStartSerializer(
+ {
+ "run_id": result.run.id,
+ "status": result.run.status,
+ "url": absolute_uri(f"/project/{self.team_id}/wizard/runs"),
+ }
+ ).data
+ return Response(data, status=status.HTTP_201_CREATED if result.created else status.HTTP_200_OK)
+
+ @extend_schema(
+ responses={
+ 200: WizardInstallStatusSerializer,
+ 404: OpenApiResponse(response=WizardRunErrorSerializer),
+ },
+ summary="Get a setup run's status",
+ description=(
+ "Get the status of a cloud setup run, its task list, the pull request link once it exists, "
+ "and a next step to relay to the user."
+ ),
+ )
+ # GET /projects/:projectId/wizard/installs/:runId
+ def retrieve(self, request: Request, *args: object, **kwargs: object) -> Response:
+ self._require_cloud_execution()
+ try:
+ install_status = wizard_facade.get_install_status(self.team_id, UUID(cast(str, self.kwargs["run_id"])))
+ except (ValueError, WizardRunNotFoundError):
+ raise NotFound("No setup run was found for this project.")
+ return Response(WizardInstallStatusSerializer(install_status).data)
+
+ @staticmethod
+ def _require_cloud_execution() -> None:
+ if not settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID:
+ raise NotFound("Cloud setup runs aren't available for this project.")
diff --git a/products/wizard/backend/presentation/permissions.py b/products/wizard/backend/presentation/permissions.py
index fe326bfde0ec..a17a019e5a8a 100644
--- a/products/wizard/backend/presentation/permissions.py
+++ b/products/wizard/backend/presentation/permissions.py
@@ -13,3 +13,15 @@ class WizardRunSessionAuthenticationRequired(BasePermission):
if isinstance(request.successful_authenticator, OAuthAccessTokenAuthentication):
return True
return isinstance(request.successful_authenticator, SessionAuthentication)
+
+
+class WizardInstallAuthenticationRequired(BasePermission):
+ """
+ Setup runs start from the browser or from an agent that holds an OAuth access token.
+ Personal API keys stay out, so every agent caller went through a consent screen.
+ """
+
+ message = "Sign in, or connect through OAuth, to start a setup run."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return isinstance(request.successful_authenticator, SessionAuthentication | OAuthAccessTokenAuthentication)
diff --git a/products/wizard/backend/presentation/runs/views.py b/products/wizard/backend/presentation/runs/views.py
index 946e94d88f37..41a471a24446 100644
--- a/products/wizard/backend/presentation/runs/views.py
+++ b/products/wizard/backend/presentation/runs/views.py
@@ -6,7 +6,6 @@ from django.conf import settings
from django.http import HttpResponse
from django.http.response import HttpResponseBase
-import structlog
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import status, viewsets
from rest_framework.exceptions import NotFound, PermissionDenied
@@ -18,13 +17,7 @@ from posthog.api.streaming import sse_streaming_response
from posthog.api.utils import action
from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication
from posthog.exceptions import Conflict
-from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL
-from posthog.models import User
-from posthog.utils import get_trusted_client_ip
-from products.security.backend.facade.api import access_refused as security_access_refused
-from products.security.backend.facade.contracts import SubjectInput as SecuritySubject
-from products.security.backend.facade.enums import Surface as SecuritySurface
from products.wizard.backend.facade import api as wizard_facade
from products.wizard.backend.facade.contracts import WizardRunDTO
from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStatus
@@ -45,11 +38,10 @@ from products.wizard.backend.presentation.runs.serializers import (
WizardRunTaskListSerializer,
)
from products.wizard.backend.presentation.runs.stream import wizard_run_event_stream
+from products.wizard.backend.presentation.security import refuse_blocked_gateway_identity
from products.wizard.backend.presentation.sessions.views import EventStreamRenderer, _wizard_sync_killswitch_enabled
from products.wizard.backend.presentation.throttles import WizardRunCreateThrottle, WizardRunReadThrottle
-logger = structlog.get_logger(__name__)
-
class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
@@ -124,7 +116,7 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if params.environment == WizardRunEnvironment.CLOUD:
self._validate_cloud_creation(request)
- self._refuse_blocked_gateway_identity(request)
+ refuse_blocked_gateway_identity(request, self.team.organization_id, call_site="wizard_run")
try:
result = wizard_facade.create_run_with_result(params)
@@ -135,30 +127,6 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(WizardRunSerializer(result.run).data, status=response_status)
- def _refuse_blocked_gateway_identity(self, request: Request) -> None:
- """Refuse a cloud run to an identity an enforced AI gateway rule blocks.
-
- The run mints its gateway token later, in a workflow with no request, so this is the only
- point where a rule on the caller's IP can match.
- """
- user = cast(User, request.user)
- try:
- refused = security_access_refused(
- SecuritySubject(
- email=user.email,
- user_uuid=str(user.uuid),
- organization_ids=(str(self.team.organization_id),),
- ip=get_trusted_client_ip(getattr(request, "_request", request)),
- ),
- SecuritySurface.AI_GATEWAY,
- call_site="wizard_run",
- )
- except Exception:
- logger.exception("security_access_check_site_failed", call_site="wizard_run")
- refused = False
- if refused:
- raise PermissionDenied(WIZARD_BLOCKED_DETAIL)
-
@staticmethod
def _validate_cloud_creation(request: Request) -> None:
if not settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID:
diff --git a/products/wizard/backend/presentation/security.py b/products/wizard/backend/presentation/security.py
new file mode 100644
index 000000000000..ffe61861f6dd
--- /dev/null
+++ b/products/wizard/backend/presentation/security.py
@@ -0,0 +1,41 @@
+from typing import cast
+from uuid import UUID
+
+import structlog
+from rest_framework.exceptions import PermissionDenied
+from rest_framework.request import Request
+
+from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL
+from posthog.models import User
+from posthog.utils import get_trusted_client_ip
+
+from products.security.backend.facade.api import access_refused as security_access_refused
+from products.security.backend.facade.contracts import SubjectInput as SecuritySubject
+from products.security.backend.facade.enums import Surface as SecuritySurface
+
+logger = structlog.get_logger(__name__)
+
+
+def refuse_blocked_gateway_identity(request: Request, organization_id: UUID, *, call_site: str) -> None:
+ """Refuse a cloud run to an identity an enforced AI gateway rule blocks.
+
+ The run mints its gateway token later, in a workflow with no request, so this is the only
+ point where a rule on the caller's IP can match.
+ """
+ user = cast(User, request.user)
+ try:
+ refused = security_access_refused(
+ SecuritySubject(
+ email=user.email,
+ user_uuid=str(user.uuid),
+ organization_ids=(str(organization_id),),
+ ip=get_trusted_client_ip(getattr(request, "_request", request)),
+ ),
+ SecuritySurface.AI_GATEWAY,
+ call_site=call_site,
+ )
+ except Exception:
+ logger.exception("security_access_check_site_failed", call_site=call_site)
+ refused = False
+ if refused:
+ raise PermissionDenied(WIZARD_BLOCKED_DETAIL)
diff --git a/products/wizard/backend/routes.py b/products/wizard/backend/routes.py
index f6edbdad11f1..5532f21b5574 100644
--- a/products/wizard/backend/routes.py
+++ b/products/wizard/backend/routes.py
@@ -1,6 +1,7 @@
from posthog.api.routing import RouterRegistry
from products.wizard.backend.presentation.artifacts.views import WizardRunArtifactViewSet
+from products.wizard.backend.presentation.installs.views import WizardInstallViewSet
from products.wizard.backend.presentation.registry.views import WizardRegistryViewSet
from products.wizard.backend.presentation.runs.views import WizardRunTasksViewSet, WizardRunViewSet
from products.wizard.backend.presentation.scans.views import WizardScanViewSet
@@ -33,5 +34,8 @@ def register_routes(routers: RouterRegistry) -> None:
["project_id", "run_id"],
)
+ # Cloud setup runs started by agents
+ routers.projects.register(r"wizard/installs", WizardInstallViewSet, "project_wizard_installs", ["project_id"])
+
# Wizard Registry
routers.projects.register(r"wizard/registry", WizardRegistryViewSet, "project_wizard_registry", ["project_id"])
diff --git a/products/wizard/backend/temporal/activities/handoff.py b/products/wizard/backend/temporal/activities/handoff.py
index a3ceab150846..0b1ac19d7f31 100644
--- a/products/wizard/backend/temporal/activities/handoff.py
+++ b/products/wizard/backend/temporal/activities/handoff.py
@@ -35,6 +35,7 @@ def create_run_artifacts(input: PreparedGitRepositoryWorkspace) -> None:
workspace_path=input.root_path,
github_integration_id=input.github_integration_id,
repository=input.repository,
+ base_branch=input.base_branch,
)
)
except cloud_worker.WizardWorkerExecutionError as error:
diff --git a/products/wizard/backend/temporal/activities/workspace.py b/products/wizard/backend/temporal/activities/workspace.py
index 92ff09a68a9d..e18f326ba61e 100644
--- a/products/wizard/backend/temporal/activities/workspace.py
+++ b/products/wizard/backend/temporal/activities/workspace.py
@@ -115,6 +115,7 @@ def clone_repository(input: ProvisionedWizardWorker) -> PreparedGitRepositoryWor
sandbox_id=input.sandbox_id,
github_integration_id=integration_id,
repository=run.workspace.repository,
+ branch=run.workspace.branch,
)
)
except cloud_worker.WizardWorkerExecutionError as error:
@@ -133,6 +134,7 @@ def clone_repository(input: ProvisionedWizardWorker) -> PreparedGitRepositoryWor
root_path=root_path,
github_integration_id=integration_id,
use_local_wizard_source=input.use_local_wizard_source,
+ base_branch=run.workspace.branch,
)
diff --git a/products/wizard/backend/temporal/contracts.py b/products/wizard/backend/temporal/contracts.py
index 7cbb29e726f8..829ddaabb8f1 100644
--- a/products/wizard/backend/temporal/contracts.py
+++ b/products/wizard/backend/temporal/contracts.py
@@ -44,3 +44,5 @@ class PreparedGitRepositoryWorkspace:
root_path: str
github_integration_id: int
use_local_wizard_source: bool = False
+ # None means the repository's default branch.
+ base_branch: str | None = None
diff --git a/products/wizard/backend/tests/runs/test_cloud_activities.py b/products/wizard/backend/tests/runs/test_cloud_activities.py
index 35912dcccf6f..058f6a8be599 100644
--- a/products/wizard/backend/tests/runs/test_cloud_activities.py
+++ b/products/wizard/backend/tests/runs/test_cloud_activities.py
@@ -1,3 +1,4 @@
+from dataclasses import replace
from datetime import timedelta
from pathlib import Path
from uuid import uuid4
@@ -67,6 +68,7 @@ def _create_cloud_run(
*,
program_id: str = "posthog-integration",
registry_payload: object = None,
+ branch: str | None = None,
) -> WizardRunDTO:
with (
patch("posthoganalytics.get_feature_flag_payload", return_value=registry_payload),
@@ -85,7 +87,7 @@ def _create_cloud_run(
created_by_id=user_id,
environment=WizardRunEnvironment.CLOUD,
idempotency_key="test-cloud-activity",
- workspace=GitRepositoryWorkspace(repository="posthog/posthog"),
+ workspace=GitRepositoryWorkspace(repository="posthog/posthog", branch=branch),
program_id=program_id,
)
)
@@ -188,9 +190,10 @@ def test_provision_worker_uses_persisted_run_identity(team, user) -> None:
provision.assert_not_called()
[email protected]("branch", [None, "release/next"])
@pytest.mark.django_db(transaction=True)
-def test_clone_repository_rechecks_access_before_preparing_workspace(team, user) -> None:
- run = _create_cloud_run(team.id, user.id)
+def test_clone_repository_rechecks_access_before_preparing_workspace(team, user, branch: str | None) -> None:
+ run = _create_cloud_run(team.id, user.id, branch=branch)
worker = _worker(run)
with (
@@ -209,7 +212,7 @@ def test_clone_repository_rechecks_access_before_preparing_workspace(team, user)
):
result = async_to_sync(_run_clone_repository)(worker)
- assert result == _workspace(run)
+ assert result == replace(_workspace(run), base_branch=branch)
assert wizard_facade.get_run(team.id, run.id).stage == "preparing_workspace"
resolve_integration.assert_called_once_with(team.id)
repository_accessible.assert_called_once_with(team.id, 456, "posthog/posthog")
@@ -218,6 +221,7 @@ def test_clone_repository_rechecks_access_before_preparing_workspace(team, user)
sandbox_id=worker.sandbox_id,
github_integration_id=456,
repository="posthog/posthog",
+ branch=branch,
)
)
diff --git a/products/wizard/backend/tests/runs/test_cloud_worker.py b/products/wizard/backend/tests/runs/test_cloud_worker.py
index 07ba8d4e27a4..cbe1f05c9108 100644
--- a/products/wizard/backend/tests/runs/test_cloud_worker.py
+++ b/products/wizard/backend/tests/runs/test_cloud_worker.py
@@ -208,7 +208,9 @@ def test_clone_repository_uses_integration_token(
assert root_path == "/tmp/workspace/repos/posthog/posthog"
get_sandbox_class.return_value.get_by_id.assert_called_once_with(request.sandbox_id)
- sandbox.clone_repository.assert_called_once_with(request.repository, github_token="github-secret", shallow=True)
+ sandbox.clone_repository.assert_called_once_with(
+ request.repository, github_token="github-secret", shallow=True, branch=None
+ )
sanitize_command = sandbox.execute.call_args.args[0]
assert "github-secret" not in sanitize_command
assert "https://github.com/PostHog/PostHog.git" in sanitize_command
@@ -470,6 +472,7 @@ def test_git_repository_handoff_captures_diff_and_publishes_pull_request(
workspace_path="/tmp/workspace/repos/posthog/posthog",
github_integration_id=17,
repository="PostHog/PostHog",
+ base_branch="release/next",
)
sandbox = get_sandbox_class.return_value.get_by_id.return_value
sandbox.execute.side_effect = (
@@ -509,6 +512,7 @@ def test_git_repository_handoff_captures_diff_and_publishes_pull_request(
integration_id=request.github_integration_id,
repository=request.repository,
head_branch=branch,
+ base_branch="release/next",
title="Instrument application with PostHog",
body="# Setup report\n\nAll done.",
source="wizard",
diff --git a/products/wizard/backend/tests/runs/test_install_next_step.py b/products/wizard/backend/tests/runs/test_install_next_step.py
new file mode 100644
index 000000000000..b3708e5128cc
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_install_next_step.py
@@ -0,0 +1,60 @@
+from datetime import UTC, datetime
+from uuid import uuid4
+
+import pytest
+
+from products.wizard.backend.facade.contracts import GitRepositoryWorkspace, WizardRunDTO
+from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStage, WizardRunStatus
+from products.wizard.backend.logic.installs.next_step import next_step
+from products.wizard.backend.logic.registry.config import POSTHOG_INTEGRATION_PROGRAM
+
+
+def _run(status: WizardRunStatus, stage: WizardRunStage | None = None, error_code: str | None = None) -> WizardRunDTO:
+ return WizardRunDTO(
+ id=uuid4(),
+ team_id=1,
+ created_by_id=1,
+ environment=WizardRunEnvironment.CLOUD,
+ workspace=GitRepositoryWorkspace(repository="posthog/posthog"),
+ program=POSTHOG_INTEGRATION_PROGRAM,
+ status=status,
+ error_code=error_code,
+ error_message=None,
+ stage=stage,
+ created_at=datetime(2026, 1, 1, tzinfo=UTC),
+ updated_at=None,
+ started_at=None,
+ finished_at=None,
+ deadline_at=None,
+ )
+
+
+ ("run", "pull_request_url", "expected_start"),
+ [
+ (_run(WizardRunStatus.CREATED), None, "The setup agent is queued."),
+ (_run(WizardRunStatus.RUNNING, WizardRunStage.PROVISIONING), None, "The setup agent is starting"),
+ (_run(WizardRunStatus.RUNNING, WizardRunStage.EXECUTING_WIZARD), None, "The setup agent is adding PostHog"),
+ (_run(WizardRunStatus.COMPLETED), "https://github.com/posthog/posthog/pull/1", "The setup agent opened"),
+ (_run(WizardRunStatus.COMPLETED), None, "The setup agent finished without changing any files."),
+ (_run(WizardRunStatus.CANCELLED), None, "This run was canceled."),
+ (_run(WizardRunStatus.FAILED, error_code="repository_access_failed"), None, "PostHog could not access"),
+ (
+ _run(WizardRunStatus.FAILED, error_code="workspace_preparation_failed"),
+ None,
+ "The setup agent could not clone",
+ ),
+ (_run(WizardRunStatus.FAILED, error_code="timeout"), None, "The run took too long"),
+ (
+ _run(WizardRunStatus.FAILED, error_code="PHW_DETECT_NO_POSTHOG_SDK"),
+ None,
+ "The setup agent could not finish.",
+ ),
+ ],
+)
+def test_next_step_follows_the_run(run: WizardRunDTO, pull_request_url: str | None, expected_start: str) -> None:
+ step = next_step(run, pull_request_url)
+
+ assert step.startswith(expected_start)
+ if run.status in (WizardRunStatus.CREATED, WizardRunStatus.RUNNING):
+ assert step.endswith("Check the status again in about 30 seconds.")
diff --git a/products/wizard/backend/tests/runs/test_install_presentation.py b/products/wizard/backend/tests/runs/test_install_presentation.py
new file mode 100644
index 000000000000..98467e829ee6
--- /dev/null
+++ b/products/wizard/backend/tests/runs/test_install_presentation.py
@@ -0,0 +1,257 @@
+from datetime import timedelta
+from typing import TYPE_CHECKING
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import PersonalAPIKey
+from posthog.models.integration import Integration
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.utils import absolute_uri
+
+from products.wizard.backend.facade import api as wizard_facade
+from products.wizard.backend.facade.contracts import CreatePullRequestArtifactInput, UpdateWizardRunTaskInput
+from products.wizard.backend.facade.enums import WizardRunStatus, WizardTaskStatus
+from products.wizard.backend.models import WizardRun
+
+if TYPE_CHECKING:
+ from rest_framework.response import _MonkeyPatchedResponse
+
+REPOSITORY_ACCESS = "products.wizard.backend.logic.runs.repository_access.repo_selection"
+
+
+@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
+class TestWizardInstallViewSet(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.integration = Integration.objects.create(team=self.team, kind="github", config={})
+ self.resolve_integration = patch(
+ f"{REPOSITORY_ACCESS}.resolve_team_github_integration_id", return_value=self.integration.id
+ )
+ self.repository_accessible = patch(
+ f"{REPOSITORY_ACCESS}.repository_accessible_via_integration", return_value=True
+ )
+ self.resolve_integration.start()
+ self.accessible = self.repository_accessible.start()
+ self.addCleanup(patch.stopall)
+
+ def _url(self, run_id: str = "") -> str:
+ return f"/api/projects/{self.team.id}/wizard/installs/{run_id}"
+
+ def _authenticate_oauth(self, scope: str) -> None:
+ application = OAuthApplication.objects.create(
+ name="Chat client",
+ user=self.user,
+ organization=self.organization,
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ )
+ token = f"pha_{uuid4().hex}"
+ OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token=token,
+ expires=timezone.now() + timedelta(hours=1),
+ scope=scope,
+ scoped_teams=[self.team.id],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ def _authenticate_personal_api_key(self) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Install test key", user=self.user, secure_value=hash_key_value(token), scopes=["*"]
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ def _start(self, **payload: str) -> "_MonkeyPatchedResponse":
+ return self.client.post(self._url(), {"repository": "posthog/posthog", **payload}, format="json")
+
+ @parameterized.expand(
+ [
+ ("session", None, status.HTTP_201_CREATED),
+ ("oauth_task_write", "task:write", status.HTTP_201_CREATED),
+ ("oauth_task_read_only", "task:read", status.HTTP_403_FORBIDDEN),
+ ("oauth_other_scope", "insight:write", status.HTTP_403_FORBIDDEN),
+ ("personal_api_key", "personal_api_key", status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_start_accepts_sessions_and_oauth_tokens_with_task_write(
+ self, _name: str, credential: str | None, expected_status: int
+ ) -> None:
+ if credential == "personal_api_key":
+ self._authenticate_personal_api_key()
+ elif credential is not None:
+ self._authenticate_oauth(credential)
+
+ response = self._start(idempotency_key="auth-check")
+
+ self.assertEqual(response.status_code, expected_status, response.content)
+ self.assertEqual(WizardRun.objects.for_team(self.team.id).exists(), expected_status == status.HTTP_201_CREATED)
+ if expected_status == status.HTTP_201_CREATED:
+ run = WizardRun.objects.for_team(self.team.id).get()
+ self.assertEqual(
+ response.json(),
+ {
+ "run_id": str(run.id),
+ "status": "created",
+ "url": absolute_uri(f"/project/{self.team.id}/wizard/runs"),
+ },
+ )
+ self.assertEqual(run.program["id"], "posthog-integration")
+ self.assertEqual(run.environment, "cloud")
+
+ def test_status_reads_with_task_read(self) -> None:
+ run_id = self._start(idempotency_key="status-scope").json()["run_id"]
+ self._authenticate_oauth("task:read")
+
+ response = self.client.get(self._url(run_id))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+ def test_disabled_cloud_execution_hides_both_endpoints(self) -> None:
+ run_id = self._start(idempotency_key="before-cloud-off").json()["run_id"]
+
+ with override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID=""):
+ start = self._start(idempotency_key="cloud-off")
+ status_response = self.client.get(self._url(run_id))
+
+ self.assertEqual(start.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(status_response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(WizardRun.objects.for_team(self.team.id).count(), 1)
+
+ @parameterized.expand([("pending", False), ("legacy", None)])
+ def test_start_allows_users_without_a_verified_email(self, _name: str, is_email_verified: bool | None) -> None:
+ self.user.is_email_verified = is_email_verified
+ self.user.save()
+
+ response = self._start(idempotency_key=f"unverified-{_name}")
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+
+ def test_start_refuses_a_second_active_run_for_the_same_user(self) -> None:
+ self._start(idempotency_key="first-run")
+
+ response = self._start(idempotency_key="second-run")
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertEqual(response.json()["code"], "run_already_active")
+ self.assertEqual(WizardRun.objects.for_team(self.team.id).count(), 1)
+
+ def test_idempotency_key_reuse_for_another_repository_conflicts(self) -> None:
+ self._start(idempotency_key="reused")
+
+ response = self._start(idempotency_key="reused", repository="posthog/posthog-js")
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertEqual(response.json()["code"], "idempotency_conflict")
+
+ def test_start_records_the_branch(self) -> None:
+ response = self._start(idempotency_key="branch", branch="release/next")
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ run = WizardRun.objects.for_team(self.team.id).get()
+ self.assertEqual(run.workspace, {"repository": "posthog/posthog", "branch": "release/next"})
+
+ @parameterized.expand([("leading_dash", "-x"), ("dot_dot", "a..b"), ("space", "my branch"), ("lock", "main.lock")])
+ def test_start_rejects_invalid_branches(self, _name: str, branch: str) -> None:
+ response = self._start(idempotency_key="bad-branch", branch=branch)
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "branch")
+
+ def test_unreachable_repository_refreshes_the_repository_cache_once(self) -> None:
+ self.accessible.side_effect = [False, True]
+
+ with patch("posthog.models.integration.GitHubIntegration.sync_repository_cache") as sync:
+ response = self._start(idempotency_key="fresh-install")
+ self.accessible.side_effect = None
+ self.accessible.return_value = False
+ missing = self._start(idempotency_key="missing-repository", repository="posthog/missing")
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertEqual(missing.json()["code"], "repository_not_accessible")
+ sync.assert_called_once_with(min_refresh_interval_seconds=60)
+
+ @parameterized.expand(
+ [
+ ("not_connected", None, "github_not_connected"),
+ ("not_accessible", True, "repository_not_accessible"),
+ ]
+ )
+ def test_start_explains_missing_repository_access(self, _name: str, connected: bool | None, code: str) -> None:
+ self.accessible.return_value = False
+ if connected is None:
+ patch(f"{REPOSITORY_ACCESS}.resolve_team_github_integration_id", return_value=None).start()
+
+ with patch("posthog.models.integration.GitHubIntegration.sync_repository_cache"):
+ response = self._start(idempotency_key=f"access-{_name}")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], code)
+ self.assertFalse(WizardRun.objects.for_team(self.team.id).exists())
+
+ def test_status_reports_tasks_pull_request_and_next_step(self) -> None:
+ run_id = self._start(idempotency_key="status").json()["run_id"]
+ run = WizardRun.objects.for_team(self.team.id).get()
+ wizard_facade.update_run_task_list(
+ self.team.id,
+ run.id,
+ (UpdateWizardRunTaskInput(title="Install the SDK", status=WizardTaskStatus.COMPLETED),),
+ )
+ WizardRun.objects.for_team(self.team.id).filter(id=run.id).update(
+ status=WizardRunStatus.COMPLETED.value, stage=None
+ )
+ wizard_facade.create_pull_request_artifact(
+ CreatePullRequestArtifactInput(
+ team_id=self.team.id,
+ run_id=run.id,
+ url="https://github.com/posthog/posthog/pull/1",
+ number=1,
+ repository="posthog/posthog",
+ head_branch="posthog/wizard-1",
+ base_branch="main",
+ )
+ )
+
+ response = self.client.get(self._url(run_id))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json(),
+ {
+ "status": "completed",
+ "stage": None,
+ "error_code": None,
+ "error_message": None,
+ "pull_request_url": "https://github.com/posthog/posthog/pull/1",
+ "tasks": [{"name": "Install the SDK", "status": "completed"}],
+ "next_step": (
+ "The setup agent opened a pull request. Share the link with the user so they can review and merge it."
+ ),
+ },
+ )
+
+ def test_status_does_not_disclose_another_projects_run(self) -> None:
+ run_id = self._start(idempotency_key="other-project").json()["run_id"]
+ other_team = self.create_team_with_organization(organization=self.organization)
+
+ response = self.client.get(f"/api/projects/{other_team.id}/wizard/installs/{run_id}")
+ malformed = self.client.get(self._url("-" * 36))
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(malformed.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/products/wizard/backend/tests/runs/test_presentation.py b/products/wizard/backend/tests/runs/test_presentation.py
index 938a6553d314..2fddcb6deaf5 100644
--- a/products/wizard/backend/tests/runs/test_presentation.py
+++ b/products/wizard/backend/tests/runs/test_presentation.py
@@ -347,7 +347,7 @@ class TestWizardRunViewSet(APIBaseTest):
) -> None:
# The run mints its gateway token later with no request, so an IP rule only matches here.
with patch(
- "products.wizard.backend.presentation.runs.views.security_access_refused", return_value=refused
+ "products.wizard.backend.presentation.security.security_access_refused", return_value=refused
) as check:
response = self.client.post(
self._url(), self._cloud_payload(idempotency_key=f"rules-{_name}"), format="json"
diff --git a/products/wizard/backend/tests/runs/test_workspace.py b/products/wizard/backend/tests/runs/test_workspace.py
index 139be83c0dad..7212d7539a45 100644
--- a/products/wizard/backend/tests/runs/test_workspace.py
+++ b/products/wizard/backend/tests/runs/test_workspace.py
@@ -18,6 +18,11 @@ from products.wizard.backend.logic.runs.mappers import record_to_workspace, work
{"repository": "posthog/posthog"},
GitRepositoryWorkspace(repository="posthog/posthog"),
),
+ (
+ WizardWorkspaceType.GIT_REPOSITORY,
+ {"repository": "posthog/posthog", "branch": "release/next"},
+ GitRepositoryWorkspace(repository="posthog/posthog", branch="release/next"),
+ ),
],
)
def test_workspace_serialization_round_trip(
diff --git a/products/wizard/frontend/generated/api.schemas.ts b/products/wizard/frontend/generated/api.schemas.ts
index 59002dc6355a..b73f3ecc2767 100644
--- a/products/wizard/frontend/generated/api.schemas.ts
+++ b/products/wizard/frontend/generated/api.schemas.ts
@@ -7,6 +7,152 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface WizardInstallStartRequestApi {
+ /**
+ * GitHub repository to set up, in owner/name format. The project's GitHub connection must have access to it.
+ * @maxLength 255
+ */
+ repository: string
+ /**
+ * Branch to start from and to open the pull request against. Defaults to the repository's default branch.
+ * @maxLength 255
+ */
+ branch?: string
+ /**
+ * Unique key for this request. A retry with the same key returns the same run instead of starting another.
+ * @maxLength 255
+ */
+ idempotency_key?: string
+}
+
+/**
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled
+ */
+export type WizardRunStatusEnumApi = (typeof WizardRunStatusEnumApi)[keyof typeof WizardRunStatusEnumApi]
+
+export const WizardRunStatusEnumApi = {
+ Created: 'created',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+ Cancelled: 'cancelled',
+} as const
+
+export interface WizardInstallStartApi {
+ /** ID of the setup run. Pass it to the status endpoint. */
+ readonly run_id: string
+ /** Current lifecycle status of the setup run.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ readonly status: WizardRunStatusEnumApi
+ /** PostHog page where the user can follow their setup runs. */
+ readonly url: string
+}
+
+export interface WizardRunErrorApi {
+ /** Error category. */
+ readonly type: string
+ /** Machine-readable error code. */
+ readonly code: string
+ /** What happened and how to continue. */
+ readonly detail: string
+ /**
+ * Request field associated with the error, when available.
+ * @nullable
+ */
+ readonly attr: string | null
+}
+
+/**
+ * * `dispatching` - dispatching
+ * * `provisioning` - provisioning
+ * * `preparing_workspace` - preparing_workspace
+ * * `executing_wizard` - executing_wizard
+ * * `creating_artifacts` - creating_artifacts
+ */
+export type WizardRunStageEnumApi = (typeof WizardRunStageEnumApi)[keyof typeof WizardRunStageEnumApi]
+
+export const WizardRunStageEnumApi = {
+ Dispatching: 'dispatching',
+ Provisioning: 'provisioning',
+ PreparingWorkspace: 'preparing_workspace',
+ ExecutingWizard: 'executing_wizard',
+ CreatingArtifacts: 'creating_artifacts',
+} as const
+
+/**
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ */
+export type WizardTaskStatusEnumApi = (typeof WizardTaskStatusEnumApi)[keyof typeof WizardTaskStatusEnumApi]
+
+export const WizardTaskStatusEnumApi = {
+ Created: 'created',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+} as const
+
+export interface WizardInstallTaskApi {
+ /** Task the setup agent planned. */
+ readonly name: string
+ /** Current task status reported by the setup agent.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed */
+ readonly status: WizardTaskStatusEnumApi
+}
+
+export interface WizardInstallStatusApi {
+ /** Lifecycle status of the setup run. created and running mean it is still in progress.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ readonly status: WizardRunStatusEnumApi
+ /** Step the setup run is on while it is in progress, or null otherwise.
+ *
+ * * `dispatching` - dispatching
+ * * `provisioning` - provisioning
+ * * `preparing_workspace` - preparing_workspace
+ * * `executing_wizard` - executing_wizard
+ * * `creating_artifacts` - creating_artifacts */
+ readonly stage: WizardRunStageEnumApi | null
+ /**
+ * Machine-readable failure reason, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_code: string | null
+ /**
+ * Failure explanation, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_message: string | null
+ /**
+ * Pull request with the setup changes, or null until the run opens one.
+ * @nullable
+ */
+ readonly pull_request_url: string | null
+ /** Tasks the setup agent planned, in order. */
+ readonly tasks: readonly WizardInstallTaskApi[]
+ /** What happens next, in a sentence to relay to the user. */
+ readonly next_step: string
+}
+
/**
* * `local` - local
* * `cloud` - cloud
@@ -98,40 +244,6 @@ export interface GitRepositoryWorkspaceApi {
export type WizardWorkspaceApi = LocalFolderWorkspaceApi | GitRepositoryWorkspaceApi
-/**
- * * `created` - created
- * * `running` - running
- * * `completed` - completed
- * * `failed` - failed
- * * `cancelled` - cancelled
- */
-export type WizardRunStatusEnumApi = (typeof WizardRunStatusEnumApi)[keyof typeof WizardRunStatusEnumApi]
-
-export const WizardRunStatusEnumApi = {
- Created: 'created',
- Running: 'running',
- Completed: 'completed',
- Failed: 'failed',
- Cancelled: 'cancelled',
-} as const
-
-/**
- * * `dispatching` - dispatching
- * * `provisioning` - provisioning
- * * `preparing_workspace` - preparing_workspace
- * * `executing_wizard` - executing_wizard
- * * `creating_artifacts` - creating_artifacts
- */
-export type WizardRunStageEnumApi = (typeof WizardRunStageEnumApi)[keyof typeof WizardRunStageEnumApi]
-
-export const WizardRunStageEnumApi = {
- Dispatching: 'dispatching',
- Provisioning: 'provisioning',
- PreparingWorkspace: 'preparing_workspace',
- ExecutingWizard: 'executing_wizard',
- CreatingArtifacts: 'creating_artifacts',
-} as const
-
export interface WizardRunApi {
/** Unique ID of the Wizard run. */
readonly id: string
@@ -234,20 +346,6 @@ export interface WizardRunCreateRequestApi {
wizard_version?: string
}
-export interface WizardRunErrorApi {
- /** Error category. */
- readonly type: string
- /** Machine-readable error code. */
- readonly code: string
- /** What happened and how to continue. */
- readonly detail: string
- /**
- * Request field associated with the error, when available.
- * @nullable
- */
- readonly attr: string | null
-}
-
/**
* * `completed` - completed
* * `failed` - failed
@@ -366,21 +464,6 @@ export interface PaginatedWizardRunArtifactListApi {
results: WizardRunArtifactApi[]
}
-/**
- * * `created` - created
- * * `running` - running
- * * `completed` - completed
- * * `failed` - failed
- */
-export type WizardTaskStatusEnumApi = (typeof WizardTaskStatusEnumApi)[keyof typeof WizardTaskStatusEnumApi]
-
-export const WizardTaskStatusEnumApi = {
- Created: 'created',
- Running: 'running',
- Completed: 'completed',
- Failed: 'failed',
-} as const
-
export interface WizardRunTaskApi {
/** Task name, unique within this run. */
readonly name: string
diff --git a/products/wizard/frontend/generated/api.ts b/products/wizard/frontend/generated/api.ts
index 8b0661f12d6e..86a383f04853 100644
--- a/products/wizard/frontend/generated/api.ts
+++ b/products/wizard/frontend/generated/api.ts
@@ -17,6 +17,9 @@ import type {
RecordWizardScanRequestApi,
UpdateWizardRunTaskListApi,
UpsertWizardSessionRequestApi,
+ WizardInstallStartApi,
+ WizardInstallStartRequestApi,
+ WizardInstallStatusApi,
WizardRegistryListParams,
WizardRunApi,
WizardRunCreateRequestApi,
@@ -31,6 +34,46 @@ import type {
WizardToolCatalogApi,
} from './api.schemas'
+export const getWizardInstallsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/wizard/installs/`
+}
+
+/**
+ * Start the setup agent in the cloud on a GitHub repository of this project. It adds PostHog to the code and opens a pull request. Each user can have one setup run active per project at a time.
+ * @summary Start a setup run
+ */
+export const wizardInstallsCreate = async (
+ projectId: string,
+ wizardInstallStartRequestApi: WizardInstallStartRequestApi,
+ options?: RequestInit
+): Promise<WizardInstallStartApi> => {
+ return apiMutator<WizardInstallStartApi>(getWizardInstallsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(wizardInstallStartRequestApi),
+ })
+}
+
+export const getWizardInstallsRetrieveUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/wizard/installs/${runId}/`
+}
+
+/**
+ * Get the status of a cloud setup run, its task list, the pull request link once it exists, and a next step to relay to the user.
+ * @summary Get a setup run's status
+ */
+export const wizardInstallsRetrieve = async (
+ projectId: string,
+ runId: string,
+ options?: RequestInit
+): Promise<WizardInstallStatusApi> => {
+ return apiMutator<WizardInstallStatusApi>(getWizardInstallsRetrieveUrl(projectId, runId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getWizardRegistryListUrl = (projectId: string, params?: WizardRegistryListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/wizard/frontend/generated/api.zod.ts b/products/wizard/frontend/generated/api.zod.ts
index 8270d52c049f..a8cb8054c587 100644
--- a/products/wizard/frontend/generated/api.zod.ts
+++ b/products/wizard/frontend/generated/api.zod.ts
@@ -9,6 +9,39 @@
*/
import * as zod from 'zod'
+/**
+ * Start the setup agent in the cloud on a GitHub repository of this project. It adds PostHog to the code and opens a pull request. Each user can have one setup run active per project at a time.
+ * @summary Start a setup run
+ */
+export const wizardInstallsCreateBodyRepositoryMax = 255
+
+export const wizardInstallsCreateBodyBranchMax = 255
+
+export const wizardInstallsCreateBodyIdempotencyKeyMax = 255
+
+export const WizardInstallsCreateBody = /* @__PURE__ */ zod.object({
+ repository: zod
+ .string()
+ .max(wizardInstallsCreateBodyRepositoryMax)
+ .describe(
+ "GitHub repository to set up, in owner\/name format. The project's GitHub connection must have access to it."
+ ),
+ branch: zod
+ .string()
+ .max(wizardInstallsCreateBodyBranchMax)
+ .optional()
+ .describe(
+ "Branch to start from and to open the pull request against. Defaults to the repository's default branch."
+ ),
+ idempotency_key: zod
+ .string()
+ .max(wizardInstallsCreateBodyIdempotencyKeyMax)
+ .optional()
+ .describe(
+ 'Unique key for this request. A retry with the same key returns the same run instead of starting another.'
+ ),
+})
+
/**
* Create a local or cloud Wizard run for a project workspace.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 944cd64beb2a..708e00280a6a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -116778,6 +116778,89 @@ export namespace Schemas {
started_at?: string | null;
}
+ export interface WizardInstallStart {
+ /** ID of the setup run. Pass it to the status endpoint. */
+ readonly run_id: string;
+ /** Current lifecycle status of the setup run.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ readonly status: WizardRunStatusEnum;
+ /** PostHog page where the user can follow their setup runs. */
+ readonly url: string;
+ }
+
+ export interface WizardInstallStartRequest {
+ /**
+ * GitHub repository to set up, in owner/name format. The project's GitHub connection must have access to it.
+ * @maxLength 255
+ */
+ repository: string;
+ /**
+ * Branch to start from and to open the pull request against. Defaults to the repository's default branch.
+ * @maxLength 255
+ */
+ branch?: string;
+ /**
+ * Unique key for this request. A retry with the same key returns the same run instead of starting another.
+ * @maxLength 255
+ */
+ idempotency_key?: string;
+ }
+
+ export interface WizardInstallTask {
+ /** Task the setup agent planned. */
+ readonly name: string;
+ /** Current task status reported by the setup agent.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed */
+ readonly status: WizardTaskStatusEnum;
+ }
+
+ export interface WizardInstallStatus {
+ /** Lifecycle status of the setup run. created and running mean it is still in progress.
+ *
+ * * `created` - created
+ * * `running` - running
+ * * `completed` - completed
+ * * `failed` - failed
+ * * `cancelled` - cancelled */
+ readonly status: WizardRunStatusEnum;
+ /** Step the setup run is on while it is in progress, or null otherwise.
+ *
+ * * `dispatching` - dispatching
+ * * `provisioning` - provisioning
+ * * `preparing_workspace` - preparing_workspace
+ * * `executing_wizard` - executing_wizard
+ * * `creating_artifacts` - creating_artifacts */
+ readonly stage: WizardRunStageEnum | null;
+ /**
+ * Machine-readable failure reason, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_code: string | null;
+ /**
+ * Failure explanation, or null if the run has not failed.
+ * @nullable
+ */
+ readonly error_message: string | null;
+ /**
+ * Pull request with the setup changes, or null until the run opens one.
+ * @nullable
+ */
+ readonly pull_request_url: string | null;
+ /** Tasks the setup agent planned, in order. */
+ readonly tasks: readonly WizardInstallTask[];
+ /** What happens next, in a sentence to relay to the user. */
+ readonly next_step: string;
+ }
+
export interface WizardRunCreateRequest {
/**
* Registry program to run.