: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
fix(wizard): remove the dead hash-based setup flow and its LLM proxy (#96922)
Matt Brookerab494e2d85c8
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex d27de4393a88..4070ad8c7d05 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1937,10 +1937,6 @@ export class ApiRequest {return this.coreMemory().addPathComponent(id)}- public authenticateWizard(): ApiRequest {- return this.wizard().addPathComponent('authenticate')- }-public messagingTemplates(): ApiRequest {return this.environmentsDetail().addPathComponent('messaging_templates')}@@ -2017,10 +2013,6 @@ export class ApiRequest {return this.hogFlowTemplates().addPathComponent(hogFlowTemplateId)}- public wizard(): ApiRequest {- return this.addPathComponent('wizard')- }-public evaluationRuns(teamId?: TeamType['id']): ApiRequest {return this.environmentsDetail(teamId).addPathComponent('evaluation_runs')}@@ -6522,11 +6514,6 @@ const api = {return await new ApiRequest().coreMemoryDetail(coreMemoryId).update({ data: coreMemory })},},- wizard: {- async authenticateWizard(data: { hash: string; projectId: number }): Promise<{ success: boolean }> {- return await new ApiRequest().authenticateWizard().create({ data })- },- },messaging: {async getTemplates(): Promise<PaginatedResponse<MessageTemplate>> {return await new ApiRequest().messagingTemplates().get()diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.tsindex d4de6b598c11..de5bd9d2a8eb 100644--- a/frontend/src/scenes/appScenes.ts+++ b/frontend/src/scenes/appScenes.ts@@ -134,7 +134,6 @@ export const appScenes: Record<Scene | string, () => any> = {[Scene.WebAnalyticsLive]: () => import('./web-analytics/WebAnalyticsScene'),[Scene.WebAnalyticsRecap]: () => import('./web-analytics/recap/WebAnalyticsRecapScene'),[Scene.WebAnalytics]: () => import('./web-analytics/WebAnalyticsScene'),- [Scene.Wizard]: () => import('./wizard/Wizard'),[Scene.OrganizationDeactivated]: () => import('./organization/Deactivated'),[Scene.OrganizationPendingDeletion]: () => import('./organization/PendingDeletion'),[Scene.ProjectPendingDeletion]: () => import('./project/PendingDeletion'),diff --git a/frontend/src/scenes/owners.yaml b/frontend/src/scenes/owners.yamlindex e34c82ae9197..66604a200b9d 100644--- a/frontend/src/scenes/owners.yaml+++ b/frontend/src/scenes/owners.yaml@@ -87,5 +87,5 @@ rules:owners: team-product-analytics- match: '/web-analytics/'owners: team-web-analytics- - match: ['/welcome/', '/wizard/']+ - match: '/welcome/'owners: team-growthdiff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex a8d7602e875b..a48ee8bafbda 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -107,7 +107,6 @@ const pathPrefixesOnboardingNotRequiredFor = ['/settings',urls.organizationBilling(),urls.billingAuthorizationStatus(),- urls.wizard(),'/instance',urls.moveToPostHogCloud(),urls.unsubscribe(),diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 8c7c2ae7e820..9d5e34b43d22 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -205,7 +205,6 @@ export enum Scene {Endpoint = 'Endpoint',Workflow = 'Workflow',Workflows = 'Workflows',- Wizard = 'Wizard',EarlyAccessFeature = 'EarlyAccessFeature',EndpointsScene = 'EndpointsScene',Game368Hedgehogs = 'Game368Hedgehogs',diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex e80499a12c9d..27988cbdd32d 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -583,7 +583,6 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {description: "A delightful weekly recap of this project's web analytics.",iconType: 'web_analytics',},- [Scene.Wizard]: { projectBased: true, name: 'Wizard', layout: 'plain' },[Scene.OrganizationDeactivated]: {projectBased: false,organizationBased: true,@@ -924,7 +923,6 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.links()]: [Scene.Links, 'links'],[urls.link(':id')]: [Scene.Link, 'link'],[urls.sessionAttributionExplorer()]: [Scene.SessionAttributionExplorer, 'sessionAttributionExplorer'],- [urls.wizard()]: [Scene.Wizard, 'wizard'],[urls.coupons(':campaign')]: [Scene.Coupons, 'coupons'],[urls.health()]: [Scene.Health, 'health'],[urls.pipelineStatus()]: [Scene.PipelineStatus, 'pipelineStatus'],diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 4fb4c44cbb8f..4ad0931e25cc 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -302,7 +302,6 @@ export const urls = {metrics: (): string => '/metrics',sessionAttributionExplorer: (): string => '/web/session-attribution-explorer',sessionProfile: (id: string): string => `/sessions/${id}`,- wizard: (): string => `/wizard`,coupons: (campaign: string): string => `/coupons/${campaign}`,startups: (referrer?: string): string => `/startups${referrer ? `/${referrer}` : ''}`,agenticAuthorize: (): string => '/agentic/authorize',diff --git a/frontend/src/scenes/wizard/Wizard.tsx b/frontend/src/scenes/wizard/Wizard.tsxdeleted file mode 100644index 026166fe05ae..000000000000--- a/frontend/src/scenes/wizard/Wizard.tsx+++ /dev/null@@ -1,92 +0,0 @@-import { useActions, useValues } from 'kea'--import * as heartPng from '@posthog/brand/hoggies/png/heart'-import * as shockedPng from '@posthog/brand/hoggies/png/shocked'--import { pngHoggie } from 'lib/brand/hoggies'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonSelect } from 'lib/lemon-ui/LemonSelect'-import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'-import { SceneExport } from 'scenes/sceneTypes'--import { wizardLogic } from './wizardLogic'--const HedgehogShocked = pngHoggie(shockedPng)-const HedgehogHeart = pngHoggie(heartPng)--export const scene: SceneExport = {- component: Wizard,- logic: wizardLogic,-}--export function Wizard(): JSX.Element {- const { view, selectedProjectId, availableProjects } = useValues(wizardLogic)- const { setSelectedProjectId, continueToAuthentication } = useActions(wizardLogic)-- return (- <div className="flex h-full w-full items-center justify-center">- <div className="px-12 py-8 text-center flex flex-col items-center max-w-160 w-full">- {view === 'project' && (- <div className="max-w-xs">- <div className="mb-8">- <h1 className="text-3xl font-bold mb-3">AI wizard</h1>- <p className="text-muted-alt">- Select which project the wizard should use to install PostHog.- </p>- </div>-- <div className="space-y-6">- <div className="justify-start items-start flex flex-col">- <label className="align-start block text-sm font-medium mb-3">Project</label>- <LemonSelect- value={selectedProjectId ?? undefined}- onChange={(projectId: number) => setSelectedProjectId(projectId)}- options={availableProjects}- placeholder="Choose a project..."- className="w-full"- />- </div>-- <div className="pt-4 flex items-center justify-center">- <LemonButton- type="primary"- onClick={continueToAuthentication}- disabledReason={- !selectedProjectId ? 'Please select a project to continue.' : undefined- }- className="w-auto"- >- Continue setup- </LemonButton>- </div>- </div>- </div>- )}- {view === 'pending' && (- <>- <h1 className="text-lg font-bold">Authenticating setup wizard...</h1>- <Spinner className="w-16 h-16 mt-12" />- </>- )}- {view === 'success' && (- <>- <h1 className="text-3xl font-bold">Success!</h1>- <div className="max-w-60 mb-12">- <HedgehogHeart className="w-48 h-48" />- </div>- <p className="text-lg">You're all set! You can return to the PostHog setup wizard.</p>- </>- )}- {view === 'invalid' && (- <>- <h1 className="text-xl font-bold">Something went wrong!</h1>- <HedgehogShocked className="h-48 w-48" />- <p className="text-lg">- There was a problem authenticating the setup wizard. Please try again later.- </p>- </>- )}- </div>- </div>- )-}diff --git a/frontend/src/scenes/wizard/wizardLogic.test.tsx b/frontend/src/scenes/wizard/wizardLogic.test.tsxdeleted file mode 100644index 999aed4d7310..000000000000--- a/frontend/src/scenes/wizard/wizardLogic.test.tsx+++ /dev/null@@ -1,122 +0,0 @@-import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_TEAM } from 'lib/api.mock'--import { router } from 'kea-router'-import { expectLogic } from 'kea-test-utils'--import { useMocks } from '~/mocks/jest'-import { initKeaTests } from '~/test/init'-import { AppContext } from '~/types'--import { wizardLogic } from './wizardLogic'--const MOCK_HASH = 'mock-hash'--describe('wizardLogic', () => {- let logic: ReturnType<typeof wizardLogic.build>-- beforeEach(async () => {- initKeaTests()- logic = wizardLogic()- logic.mount()- })-- describe('when hash is not present in the URL', () => {- it('sets view to invalid when no hash is provided in url', async () => {- router.actions.push('/wizard')-- await expectLogic(logic).toMatchValues({- view: 'invalid',- wizardHash: null,- })- })- })-- describe('if more than one project is available', () => {- beforeEach(() => {- window.POSTHOG_APP_CONTEXT = {- current_user: {- organization: {- teams: [MOCK_DEFAULT_TEAM, { ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 }],- },- },- } as unknown as AppContext- initKeaTests()- logic = wizardLogic()- logic.mount()- })- it('sets view to project', async () => {- router.actions.push('/wizard', { hash: MOCK_HASH })- await expectLogic(logic).toMatchValues({- view: 'project',- wizardHash: MOCK_HASH,- })- })- })-- describe('if only one project is available', () => {- beforeEach(() => {- window.POSTHOG_APP_CONTEXT = {- current_user: {- organization: {- ...MOCK_DEFAULT_ORGANIZATION,- teams: [MOCK_DEFAULT_TEAM],- },- },- } as unknown as AppContext- initKeaTests()- logic = wizardLogic()- logic.mount()- })-- it('sets view to pending', async () => {- router.actions.push('/wizard', { hash: MOCK_HASH })- await expectLogic(logic).toMatchValues({- view: 'pending',- wizardHash: MOCK_HASH,- })- // Drain the auto-triggered authenticate request: its trailing setView would- // otherwise dispatch into the next test's store and flip its view.- await expectLogic(logic).toFinishAllListeners()- })- })-- describe('if wizard authentication call fails', () => {- it('sets view to invalid when authentication fails', async () => {- useMocks({- post: {- '/api/wizard/authenticate/': () => [400, { status: 0 }],- },- })-- logic.actions.setWizardHash(MOCK_HASH)- logic.actions.setSelectedProjectId(MOCK_DEFAULT_TEAM.id)- logic.actions.continueToAuthentication()-- await expectLogic(logic).toFinishAllListeners()-- await expectLogic(logic).toMatchValues({- view: 'invalid',- })- })- })-- describe('if wizard authentication call succeeds', () => {- it('sets view to success when authentication succeeds', async () => {- useMocks({- post: {- '/api/wizard/authenticate/': () => [200, { status: 1 }],- },- })-- logic.actions.setWizardHash(MOCK_HASH)- logic.actions.setSelectedProjectId(MOCK_DEFAULT_TEAM.id)- logic.actions.continueToAuthentication()-- await expectLogic(logic).toFinishAllListeners()-- await expectLogic(logic).toMatchValues({- view: 'success',- })- })- })-})diff --git a/frontend/src/scenes/wizard/wizardLogic.tsx b/frontend/src/scenes/wizard/wizardLogic.tsxdeleted file mode 100644index 5cc97ae5fd51..000000000000--- a/frontend/src/scenes/wizard/wizardLogic.tsx+++ /dev/null@@ -1,239 +0,0 @@-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'-import { urlToAction } from 'kea-router'--import api from 'lib/api'-import { organizationLogic } from 'scenes/organizationLogic'-import { projectLogic } from 'scenes/projectLogic'--import type { OrganizationType, ProjectType } from '../../types'--export interface WizardTokenResponseType {- success: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardLogicValues {- currentOrganization: OrganizationType | null // organizationLogic- currentProject: ProjectType | null // projectLogic- availableProjects: {- api_token: string- label: string- organization: string- value: number- }[]- selectedProject:- | {- api_token: string- label: string- organization: string- value: number- }- | undefined- selectedProjectId: number | null- view: 'invalid' | 'pending' | 'project' | 'success'- wizardHash: string | null- wizardToken: WizardTokenResponseType | null- wizardTokenLoading: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardLogicActions {- authenticateWizard: (- wizardHash: string,- projectId: number- ) => {- projectId: number- wizardHash: string- }- authenticateWizardFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- authenticateWizardSuccess: (- wizardToken: WizardTokenResponseType,- payload?: {- projectId: number- wizardHash: string- }- ) => {- wizardToken: WizardTokenResponseType- payload?: {- projectId: number- wizardHash: string- }- }- continueToAuthentication: () => {}- handleWizardRouting: () => {}- setSelectedProjectId: (projectId: number | null) => {- projectId: number | null- }- setView: (view: 'invalid' | 'pending' | 'project' | 'success') => {- view: 'invalid' | 'pending' | 'project' | 'success'- }- setWizardHash: (wizardHash: string | null) => {- wizardHash: string | null- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface wizardLogicMeta {- __keaTypeGenInternalSelectorTypes: {- availableProjects: (currentOrganization: OrganizationType | null) => {- api_token: string- label: string- organization: string- value: number- }[]- selectedProject: (- availableProjects: {- api_token: string- label: string- organization: string- value: number- }[],- selectedProjectId: number | null- ) =>- | {- api_token: string- label: string- organization: string- value: number- }- | undefined- }-}--export type wizardLogicType = MakeLogicType<wizardLogicValues, wizardLogicActions, Record<string, any>, wizardLogicMeta>--export const wizardLogic = kea<wizardLogicType>([- path(['scenes', 'wizard', 'wizardLogic']),- connect(() => ({- values: [organizationLogic, ['currentOrganization'], projectLogic, ['currentProject']],- })),- actions({- setWizardHash: (wizardHash: string | null) => ({ wizardHash }),- setView: (view: 'project' | 'pending' | 'success' | 'invalid') => ({ view }),- setSelectedProjectId: (projectId: number | null) => ({ projectId }),- authenticateWizard: (wizardHash: string, projectId: number) => ({ wizardHash, projectId }),- continueToAuthentication: () => ({}),- handleWizardRouting: () => ({}),- }),- loaders(({ actions }) => ({- wizardToken: [- null as WizardTokenResponseType | null,- {- authenticateWizard: async ({ wizardHash, projectId }: { wizardHash: string; projectId: number }) => {- try {- actions.setView('pending')- const response: WizardTokenResponseType = await api.wizard.authenticateWizard({- hash: wizardHash,- projectId: projectId,- })- actions.setView('success')- return response- } catch {- actions.setView('invalid')-- return { success: false }- }- },- },- ],- })),- reducers({- wizardHash: [- null as string | null,- {- setWizardHash: (_, { wizardHash }) => wizardHash,- },- ],- view: [- 'project' as 'project' | 'pending' | 'success' | 'invalid',- {- setView: (_, { view }) => view,- },- ],- selectedProjectId: [- null as number | null,- {- setSelectedProjectId: (_, { projectId }) => projectId,- },- ],- }),- selectors({- availableProjects: [- (s) => [s.currentOrganization],- (currentOrganization: null | import('../../types').OrganizationType) => {- return (- currentOrganization?.teams?.map((team) => ({- value: team.id,- label: team.name,- api_token: team.api_token,- organization: currentOrganization.id,- })) || []- )- },- ],- selectedProject: [- (s) => [s.availableProjects, s.selectedProjectId],- (- availableProjects: {- api_token: string- label: string- organization: string- value: number- }[],- selectedProjectId: number | null- ) => {- return availableProjects.find((project) => project.value === selectedProjectId)- },- ],- }),- listeners(({ actions, values }) => ({- continueToAuthentication: () => {- const projectId = values.selectedProjectId- const wizardHash = values.wizardHash-- if (!projectId || !wizardHash) {- actions.setView('invalid')- return- }-- actions.setView('pending')- actions.authenticateWizard(wizardHash, projectId)- },- handleWizardRouting: () => {- const wizardHash = values.wizardHash-- if (!wizardHash) {- actions.setView('invalid')- return- }-- // If we have a current project, auto-select it- const currentProjectId = values.currentProject?.id- if (currentProjectId) {- actions.setSelectedProjectId(currentProjectId)- }-- // If there's only one project, skip selection and authenticate- if (values.availableProjects.length <= 1 && currentProjectId) {- actions.authenticateWizard(wizardHash, currentProjectId)- actions.setView('pending')- } else {- actions.setView('project')- }- },- })),- urlToAction(({ actions }) => ({- '/wizard': (_, params) => {- const wizardHash = params['hash']- actions.setWizardHash(wizardHash ?? null)- actions.handleWizardRouting()- },- })),-])diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex 0251ad40f0e7..fb45242d9314 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -1,27 +1,16 @@from __future__ import annotations-import jsonimport time-import hashlibfrom typing import NoReturn, castfrom django.conf import settingsfrom django.core.cache import cache-from django.utils.crypto import get_random_stringimport structlogimport posthoganalyticsfrom drf_spectacular.utils import extend_schema-from google.genai.types import GenerateContentConfig, Schema-from openai.types.chat import (- ChatCompletionMessageParam,- ChatCompletionSystemMessageParam,- ChatCompletionUserMessageParam,-)-from posthoganalytics.ai.gemini import genai-from posthoganalytics.ai.openai import OpenAIfrom prometheus_client import Counter-from rest_framework import exceptions, response, serializers, status, viewsets+from rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import AuthenticationFailed, ErrorDetailfrom rest_framework.permissions import IsAuthenticated@@ -29,9 +18,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.email_verification import email_verification_pending-from posthog.api.wizard.utils import json_schema_to_gemini_schemafrom posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication-from posthog.cloud_utils import get_api_hostfrom posthog.exceptions_capture import capture_exceptionfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL, wizard_identity_blockedfrom posthog.llm.wizard_gateway_token import (@@ -47,13 +34,10 @@ from posthog.llm.wizard_gateway_token import ()from posthog.models import Team, Userfrom posthog.models.project import Project-from posthog.permissions import APIScopePermissionfrom posthog.rate_limit import (- SetupWizardAuthenticationRateThrottle,SetupWizardCloudRunBurstRateThrottle,SetupWizardCloudRunSustainedRateThrottle,SetupWizardGatewayTokenRateThrottle,- SetupWizardQueryRateThrottle,refund_wizard_mint,reserve_wizard_mint,)@@ -66,18 +50,8 @@ from posthog.user_permissions import UserPermissionsfrom products.tasks.backend.facade import api as tasks_facadelogger = structlog.get_logger(__name__)--SETUP_WIZARD_CACHE_PREFIX = "setup-wizard:v1:"-SETUP_WIZARD_CACHE_TIMEOUT = 600-SETUP_WIZARD_DEFAULT_MODEL = "gpt-5-mini"--ERROR_GEMINI_API_KEY_NOT_CONFIGURED = "GEMINI_API_KEY is not configured"-ERROR_INVALID_GEMINI_RESPONSE = "Invalid response from Gemini"-ERROR_INVALID_OPENAI_JSON = "Invalid JSON response from OpenAI"ERROR_PROJECT_NOT_FOUND = "This project does not exist."-OPENAI_SUPPORTED_MODELS = {"o4-mini", "gpt-5-mini", "gpt-5-nano", "gpt-5"}-# Absolute ceiling on sandbox boots per user per day, reserved atomically right before run# creation. The DB-counted throttles above the view are read-then-create and can be raced by# parallel requests; this cache.incr cannot, so it is the hard bound a start-cancel or crash@@ -102,31 +76,6 @@ WIZARD_CLOUD_RUN_REQUESTS_TOTAL = Counter(labelnames=["outcome"],)-# Supported Gemini models-GEMINI_SUPPORTED_MODELS = {- "gemini-2.5-flash",- "gemini-2.5-pro",-}--ALL_SUPPORTED_MODELS = OPENAI_SUPPORTED_MODELS | GEMINI_SUPPORTED_MODELS--MODEL_SEED = 7678464---def _organization_ids_for_query(team_ids: list[int]) -> list[str]:- """The organizations the request itself pins.-- Deliberately not the user's current organization, which is writable through- `PATCH /api/users/@me/`: a ban keyed on it would let the banned account switch- itself out of the match.- """- if not team_ids:- return []- return [- str(organization_id)- for organization_id in Team.objects.filter(id__in=team_ids).values_list("organization_id", flat=True).distinct()- ]-def _refuse_mint(outcome: str,@@ -157,35 +106,6 @@ def _detail_text(exc: exceptions.APIException) -> str:return str(detail)-class SetupWizardSerializer(serializers.Serializer):- hash = serializers.CharField()-- def to_representation(self, instance: str) -> dict[str, str]:- return {"hash": instance}-- def create(self, validated_data: dict[str, str] | None = None) -> dict[str, str]:- hash = get_random_string(64, allowed_chars="abcdefghijklmnopqrstuvwxyz0123456789")- key = f"{SETUP_WIZARD_CACHE_PREFIX}{hash}"-- cache.set(key, {"project_api_key": None, "host": None}, SETUP_WIZARD_CACHE_TIMEOUT)-- return {"hash": hash}---class SetupWizardQuerySerializer(serializers.Serializer):- message = serializers.CharField()- json_schema = serializers.JSONField()- model = serializers.CharField(default=SETUP_WIZARD_DEFAULT_MODEL)-- def validate_model(self, value):- """Validate that the model is supported"""- if value not in ALL_SUPPORTED_MODELS:- raise serializers.ValidationError(- f"Model '{value}' is not supported. Supported models: {ALL_SUPPORTED_MODELS}"- )- return value--class SetupWizardCloudRunSerializer(serializers.Serializer):project_id = serializers.IntegerField(help_text="ID of the PostHog project to integrate PostHog into. The authenticated user must have access to it."@@ -220,22 +140,6 @@ class SetupWizardCloudRunResponseSerializer(serializers.Serializer):class SetupWizardViewSet(viewsets.ViewSet):permission_classes = ()- lookup_field = "hash"- lookup_url_kwarg = "hash"-- def dangerously_get_permissions(self):- # API Level permissions are only required during the authentication step.- # For all other actions we use a cache key to authenticate.- if self.action == "authenticate":- return [IsAuthenticated(), APIScopePermission()]-- raise NotImplementedError()-- def dangerously_get_required_scopes(self):- if self.action == "authenticate":- return ["project:read"]-- return []def throttled(self, request: Request, wait: float) -> NoReturn:# A rejection from DRF's own throttle check returns before the action body, so@@ -246,248 +150,6 @@ class SetupWizardViewSet(viewsets.ViewSet):WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL.labels(outcome="throttled").inc()super().throttled(request, wait)- @action(methods=["POST"], detail=False, url_path="initialize")- def initialize(self, request: Request) -> Response:- """- This endpoint is used to initialize the setup wizard. It creates a unique hash for the user to authenticate themselves.- """-- serializer = SetupWizardSerializer()-- return Response(serializer.create())-- @action(methods=["GET"], detail=False, url_path="data")- def data(self, request: Request, hash=None) -> Response:- """- This endpoint is used to get the data for the setup wizard to use.- """-- hash = request.headers.get("X-PostHog-Wizard-Hash")-- if not hash:- raise AuthenticationFailed("X-PostHog-Wizard-Hash header is required.")-- key = f"{SETUP_WIZARD_CACHE_PREFIX}{hash}"-- wizard_data = cache.get(key)-- if wizard_data is None:- return Response(status=404, data={"error": "Invalid hash."})-- if not wizard_data.get("project_api_key") or not wizard_data.get("host"):- return Response(status=400, data={"error": "Setup wizard not authenticated. Please login first"})-- return Response(wizard_data)-- @action(methods=["POST"], detail=False, url_path="query", throttle_classes=[SetupWizardQueryRateThrottle])- def query(self, request: Request) -> Response:- """- This endpoint acts as a proxy for the setup wizard when making AI calls.- """-- from django.conf import settings-- serializer = SetupWizardQuerySerializer(data=request.data)- if not serializer.is_valid():- return Response(serializer.errors, status=400)-- validated_data = serializer.validated_data- message = validated_data["message"]- json_schema = validated_data["json_schema"]- model = validated_data["model"]-- hash = request.headers.get("X-PostHog-Wizard-Hash")- fixture_generation = request.headers.get("X-PostHog-Wizard-Fixture-Generation")- trace_id = None-- if hash:- key = f"{SETUP_WIZARD_CACHE_PREFIX}{hash}"- wizard_data = cache.get(key)-- # wizard_data should only be mocked during the @posthog/wizard E2E tests, so that fixtures can be generated.- mock_wizard_data = settings.DEBUG and fixture_generation-- if mock_wizard_data:- wizard_data = {- "project_api_key": "mock-project-api-key",- "host": "http://localhost:8010",- "user_distinct_id": "mock-user-id",- "team_id": 1,- }- cache.set(key, wizard_data, SETUP_WIZARD_CACHE_TIMEOUT)-- if wizard_data is None:- raise AuthenticationFailed("Invalid hash.")-- if not wizard_data.get("project_api_key") or not wizard_data.get("host"):- raise AuthenticationFailed("Setup wizard not authenticated. Please login first")-- distinct_id = wizard_data.get("user_distinct_id")- team_id = wizard_data.get("team_id")- blocklist_team_ids = [team_id] if team_id else []- blocklist_user = None-- trace_id = trace_id or hashlib.sha256(hash.encode()).hexdigest()-- else:- authenticator = OAuthAccessTokenAuthentication()- result = authenticator.authenticate(request)-- if not result:- raise AuthenticationFailed("Invalid access token.")-- user, _ = result-- if not user:- raise AuthenticationFailed("Invalid access token.")-- distinct_id = user.distinct_id- scoped_team_ids = authenticator.access_token.scoped_teams or []- team_id = scoped_team_ids[0] if len(scoped_team_ids) == 1 else None- # Every scoped team, not the sole one `team_id` narrows to: a token- # spanning several still grants each, so a ban naming one must match.- blocklist_team_ids = list(scoped_team_ids)-- trace_id = request.headers.get("X-PostHog-Trace-Id") or hashlib.sha256(distinct_id.encode()).hexdigest()- blocklist_user = user-- if blocklist_user is None:- # The hash path proves a distinct_id, not a user, and the ban list is- # written against addresses.- blocklist_user = User.objects.filter(distinct_id=distinct_id).first()- if wizard_identity_blocked(- distinct_id=str(distinct_id),- email=blocklist_user.email if blocklist_user else None,- user_uuid=str(blocklist_user.uuid) if blocklist_user else "",- organization_ids=_organization_ids_for_query(blocklist_team_ids),- team_ids=blocklist_team_ids,- surface="query",- ):- # No outcome label: query labels no other exit, and the blocklist- # counter already carries this surface with its own denominator.- raise exceptions.PermissionDenied(WIZARD_BLOCKED_DETAIL)-- posthog_client = posthoganalytics.default_client-- if not posthog_client:- raise exceptions.ValidationError("PostHog client not found")-- system_prompt = (- "You are a PostHog setup wizard. Only answer messages about setting up PostHog and nothing else."- )-- if model in GEMINI_SUPPORTED_MODELS:- api_key = settings.GEMINI_API_KEY- if not api_key:- error = exceptions.ValidationError(ERROR_GEMINI_API_KEY_NOT_CONFIGURED)- capture_exception(- error,- {- "model": model,- "ai_product": "wizard",- },- )- raise error-- client = genai.Client(api_key=api_key, posthog_client=posthog_client)-- converted_schema = json_schema_to_gemini_schema(json_schema)-- response_schema = Schema(**converted_schema)-- config = GenerateContentConfig(- system_instruction=system_prompt,- temperature=0,- seed=MODEL_SEED,- response_mime_type="application/json",- response_schema=response_schema,- )-- response = client.models.generate_content(- model=model,- contents=message,- config=config,- posthog_distinct_id=distinct_id,- posthog_trace_id=trace_id,- posthog_properties={- "ai_product": "wizard",- "ai_feature": "query",- "team_id": team_id,- },- )-- if not response.parsed:- error = exceptions.ValidationError(ERROR_INVALID_GEMINI_RESPONSE)- capture_exception(- error,- {- "model": model,- "ai_product": "wizard",- "trace_id": trace_id,- "distinct_id": distinct_id,- },- )- raise error-- response_data = response.parsed-- elif model in OPENAI_SUPPORTED_MODELS:- system_message = ChatCompletionSystemMessageParam(- role="system",- content=system_prompt,- )-- user_message = ChatCompletionUserMessageParam(role="user", content=message)-- messages: list[ChatCompletionMessageParam] = [system_message, user_message]-- openai = OpenAI(posthog_client=posthog_client, base_url=settings.OPENAI_BASE_URL)-- result = openai.chat.completions.create(- model=model,- seed=MODEL_SEED,- messages=messages,- response_format={"type": "json_schema", "json_schema": json_schema},- posthog_distinct_id=distinct_id,- posthog_trace_id=trace_id,- posthog_properties={- "ai_product": "wizard",- "ai_feature": "query",- "team_id": team_id,- },- temperature=1.0,- )-- if (- not result.choices- or len(result.choices) == 0- or not result.choices[0].message- or not result.choices[0].message.content- ):- raise exceptions.ValidationError(ERROR_INVALID_OPENAI_JSON)-- try:- response_data = json.loads(result.choices[0].message.content)- except json.JSONDecodeError as e:- capture_exception(- e,- {- "model": model,- "ai_product": "wizard",- "trace_id": trace_id,- "distinct_id": distinct_id,- "response_content": result.choices[0].message.content[:500]- if result.choices[0].message.content- else None,- },- )- raise exceptions.ValidationError(ERROR_INVALID_OPENAI_JSON)-- else:- raise exceptions.ValidationError(f"Model '{model}' is not supported.")-- return Response({"data": response_data})-@action(methods=["POST"],detail=False,@@ -666,64 +328,6 @@ class SetupWizardViewSet(viewsets.ViewSet):status=status.HTTP_201_CREATED,)- @action(- methods=["POST"],- url_path="authenticate",- detail=False,- throttle_classes=[SetupWizardAuthenticationRateThrottle],- )- def authenticate(self, request, **kwargs):- hash = request.data.get("hash")- project_id = request.data.get("projectId")-- if not hash:- raise serializers.ValidationError({"hash": ["This field is required."]}, code="required")-- if not project_id:- raise serializers.ValidationError({"projectId": ["This field is required."]}, code="required")-- cache_key = f"{SETUP_WIZARD_CACHE_PREFIX}{hash}"- wizard_data = cache.get(cache_key)-- if wizard_data is None:- raise serializers.ValidationError({"hash": ["This hash is invalid or has expired."]}, code="invalid_hash")-- try:- # nosemgrep: idor-lookup-without-org, idor-taint-user-input-to-org-model (permission check after lookup)- project = Project.objects.get(id=project_id)-- # Verify user has access to this project- visible_project_ids = UserPermissions(request.user).project_ids_visible_for_user- if project.id not in visible_project_ids:- raise serializers.ValidationError(- {"projectId": ["You don't have access to this project."]}, code="permission_denied"- )-- project_api_token = project.passthrough_team.api_token- team_id = project.passthrough_team.id- except Project.DoesNotExist as e:- capture_exception(- e,- {- "project_id": project_id,- "user_id": request.user.id if request.user else None,- "user_distinct_id": request.user.distinct_id if request.user else None,- "ai_product": "wizard",- },- )- raise serializers.ValidationError({"projectId": [ERROR_PROJECT_NOT_FOUND]}, code="not_found")-- wizard_data = {- "project_api_key": project_api_token,- "host": get_api_host(),- "user_distinct_id": request.user.distinct_id,- "team_id": team_id,- }-- cache.set(cache_key, wizard_data, SETUP_WIZARD_CACHE_TIMEOUT)-- return response.Response({"success": True}, status=200)-@extend_schema(request=SetupWizardCloudRunSerializer,responses={200: SetupWizardCloudRunResponseSerializer},diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex 1fd3c274e90e..6a1801db7a78 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -8,7 +8,6 @@ from unittest.mock import MagicMock, patchfrom django.core.cache import cachefrom django.test import override_settings-from django.urls import reversefrom django.utils import timezonefrom prometheus_client import REGISTRY@@ -17,12 +16,7 @@ from rest_framework.exceptions import AuthenticationFailed, Throttledfrom rest_framework.request import Requestfrom rest_framework.test import APIRequestFactory-from posthog.api.wizard.http import (- SETUP_WIZARD_CACHE_PREFIX,- SETUP_WIZARD_CACHE_TIMEOUT,- WIZARD_EMAIL_UNVERIFIED_DETAIL,-)-from posthog.cloud_utils import get_api_host+from posthog.api.wizard.http import WIZARD_EMAIL_UNVERIFIED_DETAILfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAILfrom posthog.llm.wizard_gateway_token import _TIER_FLOORS, WizardGatewayMintErrorfrom posthog.models import Organization, PersonalAPIKey, User@@ -36,544 +30,6 @@ assert _active_mints is not None_ACTIVE_MINTS_PER_WEEK: int = _active_mints-class SetupWizardTests(APIBaseTest):- def setUp(self):- # Patched at the endpoint's seam: these tests replace default_client with a- # MagicMock that module-level feature_enabled delegates to, so an unpatched- # flag call reads truthy and every query 403s.- blocklist_patch = patch("posthog.api.wizard.http.wizard_identity_blocked", return_value=False)- self.mock_blocklist = blocklist_patch.start()- self.addCleanup(blocklist_patch.stop)- self.initialize_url = reverse("wizard-initialize")- self.data_url = reverse("wizard-data")- self.query_url = reverse("wizard-query")- self.hash = "testhash"- self.cache_key = f"{SETUP_WIZARD_CACHE_PREFIX}{self.hash}"- cache.set(- self.cache_key,- {"project_api_key": "test-key", "host": "http://localhost:8010", "team_id": self.team.id},- SETUP_WIZARD_CACHE_TIMEOUT,- )-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_from_a_blocked_identity_is_403(self, mock_openai):- self.mock_blocklist.return_value = True- response = self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )-- assert response.status_code == status.HTTP_403_FORBIDDEN, response.content- assert response.json()["detail"] == WIZARD_BLOCKED_DETAIL- # The proxy spends PostHog's own provider keys.- mock_openai.return_value.chat.completions.create.assert_not_called()-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_resolves_the_address_behind_the_hash(self, mock_openai):- # The hash proves a distinct_id only, and a domain ban needs the address.- cache.set(- self.cache_key,- {- "project_api_key": "test-key",- "host": "http://localhost:8010",- "team_id": self.team.id,- "user_distinct_id": str(self.user.distinct_id),- },- SETUP_WIZARD_CACHE_TIMEOUT,- )- mock_openai.return_value.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"foo": "bar"})))]- )-- self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )-- assert self.mock_blocklist.call_args.kwargs == {- "distinct_id": str(self.user.distinct_id),- "email": self.user.email,- "user_uuid": str(self.user.uuid),- "organization_ids": [str(self.team.organization_id)],- "team_ids": [self.team.id],- "surface": "query",- }-- def test_initialize_creates_hash(self):- response = self.client.post(self.initialize_url)- assert response.status_code == status.HTTP_200_OK- assert "hash" in response.data-- def test_data_endpoint_requires_hash_header(self):- response = self.client.get(self.data_url)- assert response.status_code == status.HTTP_401_UNAUTHORIZED-- def test_data_endpoint_returns_data(self):- response = self.client.get(self.data_url, headers={"x-posthog-wizard-hash": self.hash})- assert response.status_code == status.HTTP_200_OK- assert response.data["project_api_key"] == "test-key"- assert response.data["host"] == "http://localhost:8010"-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_requires_hash_header(self, mock_openai):- response = self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}- ),- content_type="application/json",- )-- assert response.status_code == status.HTTP_401_UNAUTHORIZED-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- @patch("django.conf.settings.DEBUG", False)- def test_query_endpoint_rate_limit(self, mock_openai):- mock_openai_instance = mock_openai.return_value- # Simulate an OpenAI response with JSON {"foo": "bar"}- mock_openai_instance.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"foo": "bar"})))]- )-- for _ in range(20): # Limit taken from rate_limit.py- response = self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )- assert response.status_code == status.HTTP_200_OK-- response = self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )- assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_invalid_hash(self, mock_openai):- response = self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}}}- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": "invalidhash"},- )- assert response.status_code == status.HTTP_401_UNAUTHORIZED-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint(self, mock_openai):- mock_openai_instance = mock_openai.return_value- mock_openai_instance.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"foo": "bar"})))]- )-- response = self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "number"}}}}- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"data": {"foo": "bar"}}- assert mock_openai_instance.chat.completions.create.call_args.kwargs["posthog_properties"] == {- "ai_product": "wizard",- "ai_feature": "query",- "team_id": self.team.id,- }-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_uses_oauth_scoped_team(self, mock_openai, mock_authentication):- mock_openai_instance = mock_openai.return_value- mock_openai_instance.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"foo": "bar"})))]- )- mock_authenticator = mock_authentication.return_value- mock_authenticator.authenticate.return_value = (self.user, None)- mock_authenticator.access_token.scoped_teams = [self.team.id]-- response = self.client.post(- self.query_url,- data=json.dumps(- {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "number"}}}}- ),- content_type="application/json",- headers={"authorization": "Bearer pha_test"},- )-- assert response.status_code == status.HTTP_200_OK- assert mock_openai_instance.chat.completions.create.call_args.kwargs["posthog_properties"] == {- "ai_product": "wizard",- "ai_feature": "query",- "team_id": self.team.id,- }-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_uses_default_model(self, mock_openai):- mock_openai_instance = mock_openai.return_value- mock_openai_instance.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"result": "success"})))]- )-- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test message",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )-- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"data": {"result": "success"}}-- mock_openai_instance.chat.completions.create.assert_called_once()-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_accepts_valid_openai_model(self, mock_openai):- mock_openai_instance = mock_openai.return_value- mock_openai_instance.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"result": "openai_success"})))]- )-- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test message",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- "model": "o4-mini",- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )-- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"data": {"result": "openai_success"}}- mock_openai_instance.chat.completions.create.assert_called_once()-- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.genai.Client")- @patch("django.conf.settings.GEMINI_API_KEY", "test-key")- def test_query_endpoint_accepts_valid_gemini_model(self, mock_genai_client):- mock_client_instance = mock_genai_client.return_value- mock_response = MagicMock()- mock_response.parsed = {"result": "gemini_success"}- mock_client_instance.models.generate_content.return_value = mock_response-- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test message",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- "model": "gemini-2.5-flash",- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )-- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"data": {"result": "gemini_success"}}- assert mock_client_instance.models.generate_content.call_args.kwargs["posthog_properties"] == {- "ai_product": "wizard",- "ai_feature": "query",- "team_id": self.team.id,- }-- def test_query_endpoint_rejects_invalid_model(self):- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test message",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- "model": "invalid-model",- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )-- assert response.status_code == status.HTTP_400_BAD_REQUEST- assert "model" in response.json()- assert "not supported" in response.json()["model"][0]-- @patch("django.conf.settings.DEBUG", True)- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_mock_wizard_data_in_debug_with_fixture_header(self, mock_openai):- """Test that mock wizard data is used when DEBUG=True and X-PostHog-Wizard-Fixture-Generation header is present"""- mock_openai_instance = mock_openai.return_value- mock_openai_instance.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"result": "mocked"})))]- )-- # Clear any existing cache data- cache.delete(self.cache_key)-- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash, "x-posthog-wizard-fixture-generation": "true"},- )-- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"data": {"result": "mocked"}}-- # Verify that mock data was cached- cached_data = cache.get(self.cache_key)- assert cached_data is not None- assert cached_data["project_api_key"] == "mock-project-api-key"- assert cached_data["host"] == "http://localhost:8010"- assert cached_data["user_distinct_id"] == "mock-user-id"- assert cached_data["team_id"] == 1-- @patch("django.conf.settings.DEBUG", True)- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_mock_wizard_data_overrides_existing_cache(self, mock_openai):- """Test that mock wizard data overrides existing cache data when conditions are met"""- mock_openai_instance = mock_openai.return_value- mock_openai_instance.chat.completions.create.return_value = MagicMock(- choices=[MagicMock(message=MagicMock(content=json.dumps({"result": "overridden"})))]- )-- # Set existing cache data- cache.set(- self.cache_key, {"project_api_key": "real-key", "host": "https://real-host.com"}, SETUP_WIZARD_CACHE_TIMEOUT- )-- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash, "x-posthog-wizard-fixture-generation": "true"},- )-- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"data": {"result": "overridden"}}-- # Verify that cache was overridden with mock data- cached_data = cache.get(self.cache_key)- assert cached_data["project_api_key"] == "mock-project-api-key"- assert cached_data["host"] == "http://localhost:8010"- assert cached_data["user_distinct_id"] == "mock-user-id"- assert cached_data["team_id"] == 1-- @patch("django.conf.settings.DEBUG", False)- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_no_mock_when_debug_false(self, mock_openai):- """Test that mock wizard data is NOT used when DEBUG=False even with fixture header"""- # Clear any existing cache data- cache.delete(self.cache_key)-- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash, "x-posthog-wizard-fixture-generation": "true"},- )-- # Should fail authentication because no cache data exists and mock is not used- assert response.status_code == status.HTTP_401_UNAUTHORIZED-- @patch("django.conf.settings.DEBUG", True)- @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())- @patch("posthog.api.wizard.http.OpenAI")- def test_query_endpoint_no_mock_without_fixture_header(self, mock_openai):- """Test that mock wizard data is NOT used when DEBUG=True but fixture header is missing"""- # Clear any existing cache data- cache.delete(self.cache_key)-- response = self.client.post(- self.query_url,- data=json.dumps(- {- "message": "test",- "json_schema": {"type": "object", "properties": {"name": {"type": "string"}}},- }- ),- content_type="application/json",- headers={"x-posthog-wizard-hash": self.hash},- )-- # Should fail authentication because no cache data exists and mock is not used- assert response.status_code == status.HTTP_401_UNAUTHORIZED-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- def test_authenticate_requires_hash(self):- response = self.client.post(f"/api/wizard/authenticate", data={}, format="json")- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- def test_authenticate_invalid_hash(self):- response = self.client.post(- f"/api/wizard/authenticate",- data={"hash": "nonexistent", "projectId": self.team.id},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- def test_authenticate_missing_projectId(self):- response = self.client.post(- f"/api/wizard/authenticate",- data={"hash": "valid_hash"},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- def test_authenticate_invalid_projectId(self):- response = self.client.post(- f"/api/wizard/authenticate",- data={"hash": "valid_hash", "projectId": 999999},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- def test_authenticate_successful(self):- self.client.force_login(self.user)- cache_key = f"{SETUP_WIZARD_CACHE_PREFIX}valid_hash"- cache.set(cache_key, {}, SETUP_WIZARD_CACHE_TIMEOUT)-- response = self.client.post(- f"/api/wizard/authenticate",- data={"hash": "valid_hash", "projectId": self.team.id},- format="json",- )- self.assertEqual(response.status_code, 200, response.content)- self.assertEqual(response.json(), {"success": True})-- updated_data = cache.get(cache_key)- self.assertIsNotNone(updated_data)- self.assertEqual(updated_data["project_api_key"], self.team.api_token)- self.assertEqual(updated_data["host"], get_api_host())- self.assertEqual(updated_data["user_distinct_id"], self.user.distinct_id)- self.assertEqual(updated_data["team_id"], self.team.id)-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- @patch("posthog.rate_limit.SetupWizardAuthenticationRateThrottle.rate", new="2/day")- def test_authenticate_rate_limited(self):- self.client.force_login(self.user)- cache_key = f"{SETUP_WIZARD_CACHE_PREFIX}valid_hash"- cache.set(cache_key, {}, SETUP_WIZARD_CACHE_TIMEOUT)-- url = f"/api/wizard/authenticate"- data = {"hash": "valid_hash", "projectId": self.team.id}-- response_1 = self.client.post(url, data=data, format="json")- self.assertEqual(response_1.status_code, status.HTTP_200_OK)-- response_2 = self.client.post(url, data=data, format="json")- self.assertEqual(response_2.status_code, status.HTTP_200_OK)-- response_3 = self.client.post(url, data=data, format="json")- self.assertEqual(response_3.status_code, status.HTTP_429_TOO_MANY_REQUESTS)-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- def test_authenticate_user_without_project_access(self):- other_org = Organization.objects.create(name="Other Org")- other_user = User.objects.create_and_join(other_org, "[email protected]", None)-- self.client.force_login(other_user)- cache_key = f"{SETUP_WIZARD_CACHE_PREFIX}valid_hash"- cache.set(cache_key, {}, SETUP_WIZARD_CACHE_TIMEOUT)-- url = f"/api/wizard/authenticate"- data = {"hash": "valid_hash", "projectId": self.team.id}-- response = self.client.post(url, data=data, format="json")- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- response_data = response.json()- self.assertEqual(response_data["code"], "permission_denied")- self.assertEqual(response_data["detail"], "You don't have access to this project.")- self.assertEqual(response_data["attr"], "projectId")-- def tearDown(self):- super().tearDown()- cache.clear() # Clears out all DRF throttle data--@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")class SetupWizardCloudRunTests(APIBaseTest):CLOUD_RUN_URL = "/api/wizard/cloud_run"diff --git a/posthog/api/wizard/test/test_utils.py b/posthog/api/wizard/test/test_utils.pydeleted file mode 100644index d900563caa18..000000000000--- a/posthog/api/wizard/test/test_utils.py+++ /dev/null@@ -1,159 +0,0 @@-from unittest import TestCase--from google.genai.types import Type--from ..utils import convert_schema, json_schema_to_gemini_schema---class TestSchemaConversion(TestCase):- def test_convert_schema_basic_types(self):- string_schema = {"type": "string"}- result = convert_schema(string_schema)- assert result["type"] == Type.STRING-- number_schema = {"type": "number"}- result = convert_schema(number_schema)- assert result["type"] == Type.NUMBER-- integer_schema = {"type": "integer"}- result = convert_schema(integer_schema)- assert result["type"] == Type.INTEGER-- def test_convert_schema_with_properties(self):- schema = {- "type": "object",- "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},- "required": ["name"],- }- result = convert_schema(schema)-- assert result["type"] == Type.OBJECT- assert "properties" in result- assert result["properties"]["name"]["type"] == Type.STRING- assert result["properties"]["age"]["type"] == Type.INTEGER- assert result["required"] == ["name"]-- def test_convert_schema_with_array(self):- schema = {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 10}- result = convert_schema(schema)-- assert result["type"] == Type.ARRAY- assert result["items"]["type"] == Type.STRING- assert result["min_items"] == 1- assert result["max_items"] == 10-- def test_convert_schema_with_constraints(self):- schema = {- "type": "string",- "minLength": 5,- "maxLength": 50,- "pattern": r"^[a-zA-Z]+$",- "description": "A name field",- "default": "Anonymous",- }- result = convert_schema(schema)-- assert result["type"] == Type.STRING- assert result["min_length"] == 5- assert result["max_length"] == 50- assert result["pattern"] == r"^[a-zA-Z]+$"- assert result["description"] == "A name field"- assert result["default"] == "Anonymous"-- def test_convert_schema_with_anyof(self):- schema = {"anyOf": [{"type": "string"}, {"type": "number"}]}- result = convert_schema(schema)-- assert "any_of" in result- assert len(result["any_of"]) == 2- assert result["any_of"][0]["type"] == Type.STRING- assert result["any_of"][1]["type"] == Type.NUMBER-- def test_json_schema_to_gemini_schema_wrapped_format(self):- input_schema = {- "schema": {- "type": "object",- "properties": {"files": {"type": "array", "items": {"type": "string"}}},- "required": ["files"],- "additionalProperties": False,- },- "name": "schema",- "strict": True,- }-- result = json_schema_to_gemini_schema(input_schema)-- assert result["type"] == Type.OBJECT- assert "properties" in result- assert "files" in result["properties"]- assert result["properties"]["files"]["type"] == Type.ARRAY- assert result["properties"]["files"]["items"]["type"] == Type.STRING- assert result["required"] == ["files"]-- def test_json_schema_to_gemini_schema_direct_format(self):- direct_schema = {- "type": "object",- "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},- "required": ["name"],- }-- result = json_schema_to_gemini_schema(direct_schema)-- assert result["type"] == Type.OBJECT- assert "properties" in result- assert result["properties"]["name"]["type"] == Type.STRING- assert result["properties"]["age"]["type"] == Type.INTEGER- assert result["required"] == ["name"]-- def test_complex_nested_schema(self):- complex_schema = {- "type": "object",- "properties": {- "user": {- "type": "object",- "properties": {- "name": {"type": "string", "minLength": 1},- "email": {"type": "string", "format": "email"},- "tags": {"type": "array", "items": {"type": "string"}, "minItems": 0, "maxItems": 5},- },- "required": ["name", "email"],- },- "metadata": {- "type": "object",- "properties": {- "created": {"type": "string", "format": "date-time"},- "version": {"type": "number", "minimum": 1},- },- },- },- "required": ["user"],- }-- result = json_schema_to_gemini_schema(complex_schema)-- assert result["type"] == Type.OBJECT- assert result["required"] == ["user"]-- # Check user object- user_schema = result["properties"]["user"]- assert user_schema["type"] == Type.OBJECT- assert user_schema["required"] == ["name", "email"]- assert user_schema["properties"]["name"]["type"] == Type.STRING- assert user_schema["properties"]["name"]["min_length"] == 1- assert user_schema["properties"]["email"]["type"] == Type.STRING- assert user_schema["properties"]["email"]["format"] == "email"-- # Check tags array- tags_schema = user_schema["properties"]["tags"]- assert tags_schema["type"] == Type.ARRAY- assert tags_schema["items"]["type"] == Type.STRING- assert tags_schema["min_items"] == 0- assert tags_schema["max_items"] == 5-- # Check metadata object- metadata_schema = result["properties"]["metadata"]- assert metadata_schema["type"] == Type.OBJECT- assert metadata_schema["properties"]["created"]["type"] == Type.STRING- assert metadata_schema["properties"]["created"]["format"] == "date-time"- assert metadata_schema["properties"]["version"]["type"] == Type.NUMBER- assert metadata_schema["properties"]["version"]["minimum"] == 1diff --git a/posthog/api/wizard/utils.py b/posthog/api/wizard/utils.pydeleted file mode 100644index 7fc3ff1456dc..000000000000--- a/posthog/api/wizard/utils.py+++ /dev/null@@ -1,74 +0,0 @@-from __future__ import annotations--from typing import Any--from google.genai.types import Type---def get_type_enum(json_type: str) -> Type:- """Convert JSON Schema type to Gemini Type enum"""- type_mapping = {- "string": Type.STRING,- "number": Type.NUMBER,- "integer": Type.INTEGER,- "boolean": Type.BOOLEAN,- "array": Type.ARRAY,- "object": Type.OBJECT,- }- return type_mapping.get(json_type, Type.STRING)---def get_field_mappings() -> dict[str, str]:- """Get mappings from JSON Schema field names to Gemini schema field names"""- return {- "description": "description",- "default": "default",- "enum": "enum",- "pattern": "pattern",- "minLength": "min_length",- "maxLength": "max_length",- "minimum": "minimum",- "maximum": "maximum",- "minItems": "min_items",- "maxItems": "max_items",- "minProperties": "min_properties",- "maxProperties": "max_properties",- "required": "required",- "nullable": "nullable",- "title": "title",- "example": "example",- }---def convert_schema(schema: dict) -> dict[str, Any]:- """Convert a single schema object from JSON Schema to Gemini format"""- result: dict[str, Any] = {}-- if "type" in schema:- result["type"] = get_type_enum(schema["type"])-- field_mappings = get_field_mappings()- for json_field, gemini_field in field_mappings.items():- if json_field in schema:- result[gemini_field] = schema[json_field]-- if "format" in schema:- result["format"] = schema["format"]-- if "properties" in schema:- result["properties"] = {key: convert_schema(value) for key, value in schema["properties"].items()}-- if "items" in schema:- result["items"] = convert_schema(schema["items"])-- if "anyOf" in schema:- result["any_of"] = [convert_schema(s) for s in schema["anyOf"]]-- return result---def json_schema_to_gemini_schema(json_schema: dict) -> dict[str, Any]:- """Convert JSON Schema to Gemini Schema format"""- actual_schema = json_schema.get("schema", json_schema)-- return convert_schema(actual_schema)diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 5272f8ba72a0..a1ea2f0dee00 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -1151,34 +1151,6 @@ class OnboardingSkipThrottle(UserRateThrottle):rate = "30/hour"-class SetupWizardAuthenticationRateThrottle(UserRateThrottle):- # Throttle class that is applied for authenticating the setup wizard- # This is more aggressive than other throttles because the wizard makes LLM calls- scope = "wizard_authentication"- rate = "20/day"---class SetupWizardQueryRateThrottle(SimpleRateThrottle):- def get_rate(self):- if settings.DEBUG:- return "1000/day"- return "20/day"-- # Throttle per wizard hash- def get_cache_key(self, request, view):- hash = request.headers.get("X-PostHog-Wizard-Hash")-- authorization_header = request.headers.get("Authorization")-- value = (hash or authorization_header or "").strip() or self.get_ident(request)-- sha_hash = hashlib.sha256(value.encode()).hexdigest()-- # this value isn't use controllable and can't generate html/js, so there's no risk of xss- # nosemgrep: python.flask.security.audit.directly-returned-format-string.directly-returned-format-string- return f"throttle_wizard_query_{sha_hash}"--class SetupWizardGatewayTokenRateThrottle(SimpleRateThrottle):"""Derives the per-user, per-program mint bucket. `reserve_wizard_mint` counts it.diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 24e81b33c2e0..14ab2463ead4 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -1749,11 +1749,6 @@"params": [],"scope": "project"},- "wizard": {- "template": "/wizard",- "params": [],- "scope": "project"- },"wizardRuns": {"template": "/wizard/runs","params": [],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex e28aee311498..3fa8f96934b6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},