:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(wizard): add wizard run interface (#89523)
Fernando Gomesda9d568eca05
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1791c7876a69..55652abf26e3 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4689,9 +4689,9 @@ snapshots:lemon-ui-lemon-tag--close-on-click--light:hash: v1.k794b7964.08032a7c3cec8a3f88c4e7a1f24f9446bb66d0746f126b2561398959e5b8d779.6NWwLXVPVrt9EQ1nqCIelwWQ4P6eVkL2Av5FpKoegZ8lemon-ui-lemon-tag--lemon-tag--dark:- hash: v1.k794b7964.f01e0c47fd75b1b421128a4ab0ed4b6a1d6cb580a91d1f5ef44c6de5f757180e.Uy6WBwrAQdZ30DVYcTHH-Rp-gEmuixAWPIicfGHJq88+ hash: v1.k794b7964.763db9a688b3a604545ac0053f4653465759b5f92a39c3cdc36d1186b3df7b2c.AEdTxelRTOQASaja0PzskFODGMhpqFL6G5IQ0dki9z8lemon-ui-lemon-tag--lemon-tag--light:- hash: v1.k794b7964.2c84d517fcf42811d71b2dbaf342d89db6ad574f71c3c34878f4afa14d0d4f3f.ObdYZeTvIPQOc2zZ3z6Jz2cSmjmWO3UHg-QqD0EXMXE+ hash: v1.k794b7964.a9c1c036b48556d8a21790a170f9f11aaf22dd58c23c5aecbf93e3b086140ebb.8Pz7i0PEE5oV13eCEesFULKPik7SUcVisUjjOdg6wnolemon-ui-lemon-text-area--basic--dark:hash: v1.k794b7964.9c52e2f1b2ff9fc37c28bb208e1e260812d48835299c23877f76c65fd3c666f6.KxmF5vGtkonEfIEIXn7hs4ZIl73Y6SI5nTVoimirQ_Ulemon-ui-lemon-text-area--basic--light:@@ -5760,6 +5760,14 @@ snapshots:hash: v1.k794b7964.fc4421d5eb2f507adff62378c528a85f0d2afda601f5c64c427c01f8be0017e6.CwCi0RyySiohuekOKlnZxKFInJdQLJTSVx3upnSWs_gproducts-web-analytics-content-autopilot-workspace--site-settings--light:hash: v1.k794b7964.db7571e09c46c966f50fb87b8b34511803d4aef56c41faa405c2db039f17fa43.PUpkT3j7DpGmhBztUzWMk0vKk_5cA4nMK6WztMyXBRE+ products-wizard-wizard-run-diff-viewer--default--dark:+ hash: v1.k794b7964.38b0f793a49f8277d977bddcbd3edfc90f92e38e98d8b54c13e05c6d7e1b28b4.Kvklfi80aA5M9V1X9FgSiqiA_Vj0h-5JL3qj-UiLO_I+ products-wizard-wizard-run-diff-viewer--default--light:+ hash: v1.k794b7964.b71c04e98905a5859ed80f4662a76e93ab0952d129f7aed177555bfcc59e11df.wIj6xU2WrUOoIYYGaGaxFrarlbvHXGkNpL52lVzq6lY+ products-wizard-wizard-run-diff-viewer--narrow--dark:+ hash: v1.k794b7964.51f791d9535f2640bdbb6de0e85a0e78aba8009dd61358b3656cd827f3cf3011.tYWRUI0IhtTNhxt99LRyhJ-v2FwuS8uBA7_12QfvEB4+ products-wizard-wizard-run-diff-viewer--narrow--light:+ hash: v1.k794b7964.704115354c970d7d0556406b7aa40937696c8d7d9586945d5007020108adab39.k2QTkiw86U8z8unsFf9sXAfzgMzaui-7D55GLUlsFEAproducts-workflows-customerioimportmodal--all-steps-completed--dark:hash: v1.k794b7964.da9d1ebf1836700267307224631511bd8fe3b9fb0906654a383e545e1c6f98f1.lPijIVizKAMxsGEVt28x0Y5izfhcfnbjbPhoHzriWFgproducts-workflows-customerioimportmodal--all-steps-completed--light:@@ -9093,9 +9101,9 @@ snapshots:scenes-app-settings-user--settings-user-danger-zone--light:hash: v1.k794b7964.79eed09f0cfe8e6549abccd8227287b15a0646d4825cbed200a4eba872f39154.4oekofwaE2cUfD8BER8Cy-_z3BLisKp5Wk735NkF6kIscenes-app-settings-user--settings-user-navigation--dark:- hash: v1.k794b7964.87ca468f0949495f6fb53cc8b07900f724e8cecdcd38c3791d49c6683a83f379.nPpp4yuzr2RtTIvFvDjlxk835WS_N7K8qVWNNxPCxgQ+ hash: v1.k794b7964.08bdbd1339c52cd6422d6a239225c5f1a840a45811e17d766f0c0ac2e8398281.UOOQEacR9XH_5Su2oGccTie8s9yFkAC_iE6KaLMAkwcscenes-app-settings-user--settings-user-navigation--light:- hash: v1.k794b7964.90007325cf24bd688266d36edca8206e11eb24d6aa98fc0208533ba74adb668b.Vjg6puokORg18-P-bIOttdR-X6L8hXOxoOklyUTlkiY+ hash: v1.k794b7964.82cd75d315bdb6d00f3981ee6cd4212449a1a826cf7f5eb125c8596e7053a969.UkMkh-ocaZ9Zqjvvdx9WZQOWQ-5o6xQpUpttZfEs9Ioscenes-app-settings-user--settings-user-notifications--dark:hash: v1.k794b7964.c8335086f8abd883b6dd1741a29670701c64dcc461080e1340e9b77d2fece219.WOZKv6IhgYXYbZEYmUDVx-mkYXMNYo2dZpv0s4ERQQ0scenes-app-settings-user--settings-user-notifications--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex ad30b7d4326d..dd1c0287f0f6 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -60,6 +60,11 @@ const ERROR_FILTER_ALLOW_LIST = ['loadInstrumentationChecklist', // AI observability hides its checklist entirely rather than accusing a project on data it could not read'loadFullEmail', // Its failure listener shows a retry toast and closes the modal'draftScannerFromGoal', // replayScannerLogic's failure listener toasts and routes back to the goal questions+ 'loadRunDiff', // The Wizard run drawer renders its own diff error banner with a retry+ 'loadRunArtifacts', // The Wizard run drawer renders its own artifact error banner with a retry+ 'loadRuns', // The Wizard runs table shows a persistent stale-data banner; a poll failure must not toast every 10s+ 'loadRunDetails', // The Wizard run drawer shows a stale-state banner with a retry+ 'cancelRunRequest', // wizardRunDetailsLogic shows its own cancel-failure toast]/*diff --git a/frontend/src/layout/panel-layout/sidebarToolMeta.ts b/frontend/src/layout/panel-layout/sidebarToolMeta.tsindex ae44dd356c9c..42f042ab971b 100644--- a/frontend/src/layout/panel-layout/sidebarToolMeta.ts+++ b/frontend/src/layout/panel-layout/sidebarToolMeta.ts@@ -18,6 +18,7 @@ export const SIDEBAR_TOOLS_WITHOUT_DOCS = new Set<string>(['Pulse','User research','Visual review',+ 'Wizard',])export interface SidebarToolMeta {diff --git a/frontend/src/layout/scenes/components/SceneTitleSection.tsx b/frontend/src/layout/scenes/components/SceneTitleSection.tsxindex 4662a56bad53..478e5150d491 100644--- a/frontend/src/layout/scenes/components/SceneTitleSection.tsx+++ b/frontend/src/layout/scenes/components/SceneTitleSection.tsx@@ -201,6 +201,7 @@ type SceneMainTitleProps = {* @default false*/actions?: JSX.Element+ hideProductSetupButton?: boolean/*** If provided, the back button will be forced to this breadcrumb* @default undefined@@ -246,6 +247,7 @@ export function SceneTitleSection({noBorder = false,noPadding = false,actions,+ hideProductSetupButton = false,forceBackTo,className,onGenerateMetadata,@@ -267,7 +269,7 @@ export function SceneTitleSection({// Product auto-selection is handled by SceneContent via globalSetupLogicconst effectiveActions = (<>- <ProductSetupButton />+ {!hideProductSetupButton && <ProductSetupButton />}{actions}</>)diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 178fdca0dcdc..b74556d2b0bf 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -561,6 +561,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TILE_SKELETONS: 'web-analytics-tile-skeletons', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics+ WIZARD_UI_ENABLED: 'wizard-ui-enabled', // owner: @fercgomes #team-growth — gates the /wizard/runs interface and its sidebar entryWORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflowsWORKFLOW_RUN_SCOUT_ACTION: 'workflow-run-scout-action', // owner: #team-workflowsWORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflowsdiff --git a/frontend/src/lib/lemon-ui/LemonTag/LemonTag.scss b/frontend/src/lib/lemon-ui/LemonTag/LemonTag.scssindex 5bff4334f33f..2bcba826d111 100644--- a/frontend/src/lib/lemon-ui/LemonTag/LemonTag.scss+++ b/frontend/src/lib/lemon-ui/LemonTag/LemonTag.scss@@ -45,6 +45,18 @@border-color: var(--color-accent);}+ &.LemonTag--info {+ color: var(--color-blue-600);+ background: var(--color-bg-fill-info-tertiary);+ border-color: var(--color-border-info);++ [theme='dark'] & {+ // --color-blue-600 on the dark info background falls below the WCAG AA text ratio,+ // so lift the text to a lighter blue that clears 4.5:1.+ color: var(--color-blue-400);+ }+ }+&.LemonTag--warning {color: var(--warning);background-color: none;diff --git a/frontend/src/lib/lemon-ui/LemonTag/LemonTag.stories.tsx b/frontend/src/lib/lemon-ui/LemonTag/LemonTag.stories.tsxindex 54059c8bfc12..74a31c491baf 100644--- a/frontend/src/lib/lemon-ui/LemonTag/LemonTag.stories.tsx+++ b/frontend/src/lib/lemon-ui/LemonTag/LemonTag.stories.tsx@@ -19,6 +19,7 @@ const ALL_COLORS: LemonTagType[] = ['primary','option','highlight',+ 'info','warning','danger','success',diff --git a/frontend/src/lib/lemon-ui/LemonTag/LemonTag.tsx b/frontend/src/lib/lemon-ui/LemonTag/LemonTag.tsxindex c08fc3a87b3c..b9a5b26bdd97 100644--- a/frontend/src/lib/lemon-ui/LemonTag/LemonTag.tsx+++ b/frontend/src/lib/lemon-ui/LemonTag/LemonTag.tsx@@ -12,6 +12,7 @@ export type LemonTagType =| 'primary'| 'option'| 'highlight'+ | 'info'| 'warning'| 'danger'| 'success'diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex d568dafb51fe..1c303cd1eed5 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -160,6 +160,7 @@ export const productScenes: Record<string, () => Promise<any>> = {HeatmapNew: () => import('../../products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapNewScene'),HeatmapRecording: () =>import('../../products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapRecordingScene'),+ WizardRuns: () => import('../../products/wizard/frontend/WizardRunsScene'),Workflows: () => import('../../products/workflows/frontend/WorkflowsScene'),Workflow: () => import('../../products/workflows/frontend/Workflows/WorkflowScene'),WorkflowsLibraryTemplate: () => import('../../products/workflows/frontend/TemplateLibrary/MessageTemplate'),diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex 53a7f8ee6f66..d77b07d7fec9 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -270,6 +270,7 @@"type": null,"intents": ["web_analytics"]},+ { "path": "Wizard", "category": "Tools", "iconType": null, "type": "wizard", "intents": [] },{"path": "Workflows","category": "Tools",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 33d27bfc1309..bd4eb08ac92f 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -264,6 +264,7 @@ export const productRoutes: Record<string, [string, string]> = {'/heatmaps/new': ['HeatmapNew', 'heatmapNew'],'/heatmaps/recording': ['HeatmapRecording', 'heatmapRecording'],'/heatmaps/:id': ['Heatmap', 'heatmap'],+ '/wizard/runs': ['WizardRuns', 'wizardRuns'],'/workflows': ['Workflows', 'workflows'],'/workflows/:tab': ['Workflows', 'workflows'],'/workflows/:id/:tab': ['Workflow', 'workflowTab'],@@ -1002,6 +1003,13 @@ export const productConfiguration: Record<string, any> = {Heatmap: { name: 'Heatmap', projectBased: true, iconType: 'heatmap' },HeatmapNew: { name: 'New heatmap', projectBased: true, iconType: 'heatmap' },HeatmapRecording: { name: 'Heatmap recording', projectBased: true, iconType: 'heatmap' },+ WizardRuns: {+ projectBased: true,+ name: 'Wizard runs',+ description: 'Run the setup agent in the cloud, then review the changes it produces.',+ layout: 'app-container',+ iconType: 'llm_prompts',+ },Workflows: {name: 'Workflows',iconType: 'workflows',@@ -1555,6 +1563,7 @@ export const productUrls = {heatmapRecording: (params?: string): string =>`/heatmaps/recording${params ? `?${params.startsWith('?') ? params.slice(1) : params}` : ''}`,heatmap: (id: string | number): string => `/heatmaps/${id}`,+ wizardRuns: (): string => '/wizard/runs',workflows: (tab?: WorkflowsSceneTab): string => `/workflows${tab ? `/${tab}` : ''}`,workflow: (id: string, tab: string): string => `/workflows/${id}/${tab}`,workflowNew: (): string => '/workflows/new/workflow',@@ -1934,6 +1943,7 @@ export type ProductTreePath =| 'Visual review'| 'Web analytics'| 'Web scripts'+ | 'Wizard'| 'Workflows'/** This const is auto-generated, as is the whole file */@@ -2685,6 +2695,17 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [sceneKey: 'WebScripts',sceneKeys: ['WebScripts'],},+ {+ path: 'Wizard',+ intents: [],+ category: ProductItemCategory.TOOLS,+ type: 'wizard',+ iconType: 'llm_prompts' as FileSystemIconType,+ href: '/wizard/runs',+ flag: FEATURE_FLAGS.WIZARD_UI_ENABLED,+ sceneKey: 'WizardRuns',+ sceneKeys: ['WizardRuns'],+ },{path: 'Workflows',intents: [ProductKey.WORKFLOWS],diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 10e650ba638a..a87a29423ffc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4910,12 +4910,27 @@ importers:products/wizard:dependencies:+ '@pierre/diffs':+ specifier: 1.2.11+ version: 1.2.11(@shikijs/[email protected])([email protected]([email protected]))([email protected])+ '@posthog/icons':+ specifier: 'catalog:'+ '@posthog/lemon-ui':+ specifier: '*'+ version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])))([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))([email protected]([email protected]))([email protected])+ '@storybook/react':+ specifier: 'catalog:'+ version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@types/react':specifier: 18.3.27version: 18.3.27kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-loaders:+ specifier: 'catalog:'+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))posthog-js:specifier: 'catalog:'version: 1.428.8(@types/[email protected])([email protected])@@ -4923,6 +4938,9 @@ importers:specifier: 18.3.1version: 18.3.1devDependencies:+ '@testing-library/react':+ specifier: ^14.3.1+ version: 14.3.1(@types/[email protected])([email protected]([email protected]))([email protected])kea-test-utils:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))diff --git a/products/wizard/frontend/WizardRunsScene.tsx b/products/wizard/frontend/WizardRunsScene.tsxnew file mode 100644index 000000000000..7d9700a9d224--- /dev/null+++ b/products/wizard/frontend/WizardRunsScene.tsx@@ -0,0 +1,237 @@+import { useActions, useValues } from 'kea'++import { IconBook, IconRefresh, IconSearch, IconSparkles } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { dayjs } from 'lib/dayjs'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { SceneExport } from 'scenes/sceneTypes'+import { userLogic } from 'scenes/userLogic'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { WizardLibraryModal } from './library/WizardLibraryModal'+import { WizardRunDetailsDrawer } from './runs/WizardRunDetailsDrawer'+import { WizardRunTable } from './runs/WizardRunTable'+import { wizardLibraryLogic } from './wizardLibraryLogic'+import { wizardRunDetailsLogic } from './wizardRunDetailsLogic'+import { wizardRunsLogic } from './wizardRunsLogic'++export const scene: SceneExport = {+ component: WizardRunsScene,+ logic: wizardRunsLogic,+}++export function WizardRunsScene(): JSX.Element {+ const wizardUiEnabled = useFeatureFlag('WIZARD_UI_ENABLED')+ const { user } = useValues(userLogic)+ const {+ environment,+ filteredRuns,+ hasRunFilters,+ refreshingRuns,+ runs,+ runsFailed,+ runsInitialLoading,+ runsLastLoadedAt,+ search,+ status,+ } = useValues(wizardRunsLogic)+ const { clearRunFilters, refreshRuns, setEnvironment, setSearch, setStatus } = useActions(wizardRunsLogic)++ const {+ commandCopied,+ connectGitHubUrl,+ createRunError,+ createRunRequestLoading,+ filteredPrograms,+ githubIntegration,+ integrationsLoading,+ isLibraryOpen,+ libraryEnvironment,+ librarySearch,+ programSelectionInvalidated,+ registryFailed,+ registryInitialLoading,+ repository,+ requiredPrograms,+ selectedProgram,+ selectedProgramCommand,+ wizardCloudRunAvailable,+ } = useValues(wizardLibraryLogic)+ const {+ closeLibrary,+ copyCommand,+ markCommandCopied,+ createRun,+ openLibrary,+ runAgain,+ selectProgram,+ setLibraryEnvironment,+ setLibrarySearch,+ setRepository,+ } = useActions(wizardLibraryLogic)++ const {+ cancelRunRequestLoading,+ runArtifactsError,+ runDetailsError,+ runDetailsLoading,+ runDiffError,+ runDiffLoading,+ selectedRun,+ selectedRunArtifacts,+ selectedRunArtifactsInitialLoading,+ selectedRunDiffArtifactId,+ selectedRunDiffContent,+ selectedRunId,+ } = useValues(wizardRunDetailsLogic)+ const { cancelRun, closeRunDiff, copyRunId, openRunDiff, refreshSelectedRun, selectRun } =+ useActions(wizardRunDetailsLogic)++ if (!wizardUiEnabled) {+ return <NotFound object="Wizard" caption="This feature is not enabled for your project." />+ }++ return (+ <SceneContent>+ <SceneTitleSection+ name="Wizard"+ description="Run the setup agent in the cloud, then review the changes it produces."+ descriptionAlwaysVisible+ hideProductSetupButton+ resourceType={{ type: 'default_icon_type', forceIcon: <IconSparkles className="text-ai" /> }}+ actions={+ <LemonButton+ type="primary"+ icon={<IconBook />}+ onClick={() => openLibrary()}+ disabledReason={+ wizardCloudRunAvailable ? undefined : 'Cloud runs are not available on this instance.'+ }+ >+ Open Wizard Library+ </LemonButton>+ }+ />++ <div className="mb-4 flex flex-wrap items-center gap-2">+ <LemonInput+ value={search}+ onChange={setSearch}+ prefix={<IconSearch />}+ placeholder="Search Wizard runs"+ className="w-[280px]"+ />++ <div className="flex-1" />++ {!runsInitialLoading && !runsFailed && filteredRuns.length > 0 && runsLastLoadedAt && (+ <span className="flex items-center gap-1 whitespace-nowrap text-xs text-success">+ <span className="size-2 rounded-full bg-success" />+ Updated {dayjs(runsLastLoadedAt).fromNow()}+ </span>+ )}++ <LemonSelect+ className="min-w-40"+ value={environment}+ onChange={setEnvironment}+ options={[+ { value: 'all', label: 'All environments' },+ { value: 'cloud', label: 'Cloud' },+ { value: 'local', label: 'Local' },+ ]}+ />+ <LemonSelect+ className="min-w-36"+ value={status}+ onChange={setStatus}+ options={[+ { value: 'all', label: 'All statuses' },+ { value: 'created', label: 'Starting' },+ { value: 'running', label: 'Running' },+ { value: 'completed', label: 'Completed' },+ { value: 'failed', label: 'Failed' },+ { value: 'cancelled', label: 'Canceled' },+ ]}+ />+ <LemonButton icon={<IconRefresh />} onClick={refreshRuns} loading={refreshingRuns}>+ Refresh+ </LemonButton>+ </div>++ <WizardRunTable+ runs={filteredRuns}+ totalRuns={runs.length}+ selectedRunId={selectedRunId}+ currentUserId={user?.id ?? null}+ loading={runsInitialLoading}+ failed={runsFailed}+ hasActiveFilters={hasRunFilters}+ refreshing={refreshingRuns}+ cancelling={cancelRunRequestLoading}+ onOpenLibrary={openLibrary}+ onClearFilters={clearRunFilters}+ onRefreshRuns={refreshRuns}+ onSelect={selectRun}+ onRefreshRun={refreshRuns}+ onCopyRunId={copyRunId}+ onCancel={cancelRun}+ />++ <WizardLibraryModal+ isOpen={isLibraryOpen}+ filteredPrograms={filteredPrograms}+ loading={registryInitialLoading}+ failed={registryFailed}+ selectedProgram={selectedProgram}+ requiredPrograms={requiredPrograms}+ search={librarySearch}+ command={selectedProgramCommand}+ environment={libraryEnvironment}+ repository={repository}+ githubIntegrationId={githubIntegration?.id ?? null}+ githubConnected={!!githubIntegration && githubIntegration.installation_status !== 'unavailable'}+ githubIntegrationLoading={integrationsLoading}+ connectGitHubUrl={connectGitHubUrl}+ creating={createRunRequestLoading}+ createError={createRunError}+ commandCopied={commandCopied}+ selectionInvalidated={programSelectionInvalidated}+ onClose={closeLibrary}+ onSearch={setLibrarySearch}+ onSelect={selectProgram}+ onEnvironmentChange={setLibraryEnvironment}+ onRepositoryChange={setRepository}+ onCreate={createRun}+ onCopyCommand={copyCommand}+ onCommandCopied={markCommandCopied}+ />++ <WizardRunDetailsDrawer+ run={selectedRun}+ artifacts={selectedRunArtifacts}+ artifactsError={runArtifactsError}+ artifactsLoading={selectedRunArtifactsInitialLoading}+ currentUserId={user?.id ?? null}+ detailsError={runDetailsError}+ refreshing={runDetailsLoading}+ cancelling={cancelRunRequestLoading}+ diffArtifactId={selectedRunDiffArtifactId}+ diffContent={selectedRunDiffContent}+ diffError={runDiffError}+ diffLoading={runDiffLoading}+ onClose={() => selectRun(null)}+ onCloseDiff={closeRunDiff}+ onOpenDiff={openRunDiff}+ onRefresh={refreshSelectedRun}+ onCopyRunId={copyRunId}+ onCancel={cancelRun}+ onRunAgain={runAgain}+ />+ </SceneContent>+ )+}diff --git a/products/wizard/frontend/library/WizardCommand.tsx b/products/wizard/frontend/library/WizardCommand.tsxnew file mode 100644index 000000000000..4d079f951a10--- /dev/null+++ b/products/wizard/frontend/library/WizardCommand.tsx@@ -0,0 +1,41 @@+import { IconCheck } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'++export function WizardCommand({+ command,+ showCopyButton,+ copied,+ onCopy,+ onCopied,+}: {+ command: string+ showCopyButton: boolean+ copied: boolean+ onCopy: () => void+ onCopied: () => void+}): JSX.Element {+ return (+ <div className="space-y-2">+ <CodeSnippet+ language={Language.Text}+ thing="Wizard command"+ onCopy={onCopied}+ className="[&_.CodeSnippet__actions]:!bg-gray-900 [&_.CodeSnippet__actions_.LemonButton]:!border-0 [&_.CodeSnippet__actions_.LemonButton]:!bg-transparent [&_.CodeSnippet__actions_.LemonButton]:!shadow-none [&_.LemonButton]:![--lemon-button-color:#fff] [&_code]:!font-normal [&_code]:!text-gray-100 [&_pre]:!border-gray-900 [&_pre]:!bg-gray-900 [&_pre]:!px-4 [&_pre]:!py-4"+ >+ {command}+ </CodeSnippet>+ {showCopyButton && (+ <LemonButton type="secondary" onClick={onCopy}>+ Copy command+ </LemonButton>+ )}+ {copied && (+ <div className="flex items-center gap-1 text-sm font-medium text-success">+ <IconCheck /> Command copied.+ </div>+ )}+ </div>+ )+}diff --git a/products/wizard/frontend/library/WizardLibraryModal.tsx b/products/wizard/frontend/library/WizardLibraryModal.tsxnew file mode 100644index 000000000000..6b22021291c7--- /dev/null+++ b/products/wizard/frontend/library/WizardLibraryModal.tsx@@ -0,0 +1,106 @@+import { LemonModal } from '@posthog/lemon-ui'++import type { RunEnvironmentEnumApi, WizardProgramApi } from '../generated/api.schemas'+import { WizardProgramDetails } from './WizardProgramDetails'+import { WizardProgramList } from './WizardProgramList'++export function WizardLibraryModal({+ isOpen,+ filteredPrograms,+ loading,+ failed,+ selectedProgram,+ requiredPrograms,+ search,+ command,+ environment,+ repository,+ githubIntegrationId,+ githubConnected,+ githubIntegrationLoading,+ connectGitHubUrl,+ creating,+ createError,+ commandCopied,+ selectionInvalidated,+ onClose,+ onSearch,+ onSelect,+ onEnvironmentChange,+ onRepositoryChange,+ onCreate,+ onCopyCommand,+ onCommandCopied,+}: {+ isOpen: boolean+ filteredPrograms: WizardProgramApi[]+ loading: boolean+ failed: boolean+ selectedProgram: WizardProgramApi | null+ requiredPrograms: WizardProgramApi[]+ search: string+ command: string+ environment: RunEnvironmentEnumApi+ repository: string+ githubIntegrationId: number | null+ githubConnected: boolean+ githubIntegrationLoading: boolean+ connectGitHubUrl: string+ creating: boolean+ createError: string | null+ commandCopied: boolean+ selectionInvalidated: boolean+ onClose: () => void+ onSearch: (search: string) => void+ onSelect: (program: WizardProgramApi) => void+ onEnvironmentChange: (environment: RunEnvironmentEnumApi) => void+ onRepositoryChange: (repository: string) => void+ onCreate: () => void+ onCopyCommand: () => void+ onCommandCopied: () => void+}): JSX.Element {+ return (+ <LemonModal+ isOpen={isOpen}+ onClose={onClose}+ title="Wizard Library"+ description="Choose what you want the setup agent to do."+ width={1000}+ maxWidth="95vw"+ >+ <div className="@container">+ <div className="flex h-[min(680px,75vh)] min-h-0 flex-col gap-5 @3xl:flex-row">+ <WizardProgramList+ programs={filteredPrograms}+ selectedProgram={selectedProgram}+ search={search}+ loading={loading}+ failed={failed}+ onSearch={onSearch}+ onSelect={onSelect}+ />+ <WizardProgramDetails+ program={selectedProgram}+ requiredPrograms={requiredPrograms}+ command={command}+ environment={environment}+ repository={repository}+ githubIntegrationId={githubIntegrationId}+ githubConnected={githubConnected}+ githubIntegrationLoading={githubIntegrationLoading}+ connectGitHubUrl={connectGitHubUrl}+ creating={creating}+ createError={createError}+ commandCopied={commandCopied}+ selectionInvalidated={selectionInvalidated}+ onEnvironmentChange={onEnvironmentChange}+ onRepositoryChange={onRepositoryChange}+ onCreate={onCreate}+ onCopyCommand={onCopyCommand}+ onCommandCopied={onCommandCopied}+ />+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/wizard/frontend/library/WizardProgramDetails.tsx b/products/wizard/frontend/library/WizardProgramDetails.tsxnew file mode 100644index 000000000000..410b93b9c101--- /dev/null+++ b/products/wizard/frontend/library/WizardProgramDetails.tsx@@ -0,0 +1,212 @@+import { IconCloud, IconGithub, IconLaptop } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDivider, LemonTabs, LemonTag } from '@posthog/lemon-ui'++import type { RunEnvironmentEnumApi, WizardProgramApi } from '../generated/api.schemas'+import { WIZARD_LOCAL_RUNS_VISIBLE } from '../wizardRunDisplay'+import { WizardCommand } from './WizardCommand'+import { WizardRepositoryPicker } from './WizardRepositoryPicker'++export function WizardProgramDetails({+ program,+ requiredPrograms,+ command,+ environment,+ repository,+ githubIntegrationId,+ githubConnected,+ githubIntegrationLoading,+ connectGitHubUrl,+ creating,+ createError,+ commandCopied,+ selectionInvalidated,+ onEnvironmentChange,+ onRepositoryChange,+ onCreate,+ onCopyCommand,+ onCommandCopied,+}: {+ program: WizardProgramApi | null+ requiredPrograms: WizardProgramApi[]+ command: string+ environment: RunEnvironmentEnumApi+ repository: string+ githubIntegrationId: number | null+ githubConnected: boolean+ githubIntegrationLoading: boolean+ connectGitHubUrl: string+ creating: boolean+ createError: string | null+ commandCopied: boolean+ selectionInvalidated: boolean+ onEnvironmentChange: (environment: RunEnvironmentEnumApi) => void+ onRepositoryChange: (repository: string) => void+ onCreate: () => void+ onCopyCommand: () => void+ onCommandCopied: () => void+}): JSX.Element {+ if (selectionInvalidated) {+ return (+ <LemonBanner type="warning">+ <div className="font-semibold">This program is no longer available.</div>+ <div className="text-sm">Refresh the Library and choose another program.</div>+ </LemonBanner>+ )+ }++ if (!program) {+ return <div className="flex h-full items-center justify-center text-sm text-muted">Select a program.</div>+ }++ const supportsCloud = program.supported_environments.includes('cloud')+ const supportsLocal = program.supported_environments.includes('local')++ return (+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-1 @3xl:pl-3">+ <div>+ <h3 className="mb-1 text-xl">{program.name}</h3>+ <p className="m-0 text-sm text-muted">{program.description}</p>+ </div>++ <div className="mt-3">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs font-semibold uppercase text-muted">Supported</span>+ {supportsCloud && (+ <LemonTag type="info" size="small" icon={<IconCloud />}>+ Cloud+ </LemonTag>+ )}+ {WIZARD_LOCAL_RUNS_VISIBLE && supportsLocal && (+ <LemonTag size="small" icon={<IconLaptop />}>+ Local+ </LemonTag>+ )}+ </div>+ <div className="mt-3 text-sm text-muted">Runs with Wizard {program.wizard_version}</div>+ </div>++ {requiredPrograms.length > 0 && (+ <div className="mt-5 rounded border border-info bg-info-highlight p-3">+ <div className="text-xs font-semibold uppercase text-muted">Run first</div>+ {requiredPrograms.map((requiredProgram) => (+ <div key={requiredProgram.id} className="mt-1 font-semibold underline">+ {requiredProgram.name}+ </div>+ ))}+ </div>+ )}++ {WIZARD_LOCAL_RUNS_VISIBLE && supportsLocal && environment === 'cloud' && githubConnected && (+ <div className="mt-3">+ <WizardCommand+ command={command}+ showCopyButton={false}+ copied={commandCopied}+ onCopy={onCopyCommand}+ onCopied={onCommandCopied}+ />+ </div>+ )}++ <LemonDivider className="my-5" />++ <LemonTabs+ activeKey={environment}+ onChange={onEnvironmentChange}+ tabs={[+ supportsCloud && {+ key: 'cloud',+ label: (+ <span className="flex items-center gap-1.5">+ <span>Cloud</span>+ <span className="text-xs font-normal text-muted">Recommended</span>+ </span>+ ),+ },+ WIZARD_LOCAL_RUNS_VISIBLE && supportsLocal && { key: 'local', label: 'Local' },+ ]}+ />++ <div className="mt-5">+ {environment === 'cloud' ? (+ githubIntegrationLoading ? (+ <div className="text-sm text-muted">Checking the GitHub integration…</div>+ ) : githubConnected ? (+ <div className="space-y-3">+ <div>+ <label className="mb-1 block text-sm font-semibold">GitHub repository</label>+ {githubIntegrationId === null ? (+ <div className="text-sm text-muted">Checking the GitHub integration…</div>+ ) : (+ <WizardRepositoryPicker+ integrationId={githubIntegrationId}+ value={repository}+ onChange={onRepositoryChange}+ disabledReason={creating ? 'A cloud run is starting.' : undefined}+ />+ )}+ <div className="mt-1 text-xs text-muted">+ <IconGithub className="mr-1 inline" />+ Choose a repository available to the connected GitHub integration.+ </div>+ </div>++ {createError && <LemonBanner type="error">{createError}</LemonBanner>}++ <LemonButton+ type="primary"+ onClick={() => onCreate()}+ loading={creating}+ disabledReason={repository ? undefined : 'Select a GitHub repository.'}+ >+ Start cloud run+ </LemonButton>+ </div>+ ) : (+ <div className="space-y-3">+ <LemonBanner type="warning">+ <div className="space-y-3">+ <div className="font-semibold">+ Connect GitHub to run this program in the cloud.+ </div>+ <div className="flex">+ <LemonButton type="secondary" to={connectGitHubUrl} disableClientSideRouting>+ Connect GitHub+ </LemonButton>+ </div>+ </div>+ </LemonBanner>++ {WIZARD_LOCAL_RUNS_VISIBLE && (+ <div>+ <div className="mb-2 text-xs font-semibold uppercase text-muted">Local command</div>+ <p className="text-sm">You can still run this program from your project folder.</p>+ <WizardCommand+ command={command}+ showCopyButton={false}+ copied={commandCopied}+ onCopy={onCopyCommand}+ onCopied={onCommandCopied}+ />+ </div>+ )}+ </div>+ )+ ) : (+ <div>+ <h4 className="mb-1">Run from your project folder</h4>+ <p className="text-sm text-muted">Open a terminal in the project root, then run:</p>+ <WizardCommand+ command={command}+ showCopyButton+ copied={commandCopied}+ onCopy={onCopyCommand}+ onCopied={onCommandCopied}+ />+ <div className="mt-3 text-xs text-muted">Requires Node.js 22.22 or later.</div>+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/products/wizard/frontend/library/WizardProgramList.tsx b/products/wizard/frontend/library/WizardProgramList.tsxnew file mode 100644index 000000000000..5a186ca23b9d--- /dev/null+++ b/products/wizard/frontend/library/WizardProgramList.tsx@@ -0,0 +1,103 @@+import { IconSearch } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSkeleton } from '@posthog/lemon-ui'++import type { WizardProgramApi } from '../generated/api.schemas'+import { WIZARD_LOCAL_RUNS_VISIBLE } from '../wizardRunDisplay'++export function WizardProgramList({+ programs,+ selectedProgram,+ search,+ loading,+ failed,+ onSearch,+ onSelect,+}: {+ programs: WizardProgramApi[]+ selectedProgram: WizardProgramApi | null+ search: string+ loading: boolean+ failed: boolean+ onSearch: (search: string) => void+ onSelect: (program: WizardProgramApi) => void+}): JSX.Element {+ return (+ <div className="flex h-1/2 min-h-0 w-full flex-col gap-3 border-b pb-4 @3xl:h-full @3xl:w-90 @3xl:border-b-0 @3xl:border-r @3xl:pb-0 @3xl:pr-4">+ <LemonInput+ value={search}+ onChange={onSearch}+ prefix={<IconSearch />}+ placeholder="Search programs"+ fullWidth+ disabled={loading}+ />++ <div className="min-h-0 flex-1 overflow-y-auto">+ {loading ? (+ <div className="space-y-3 p-2">+ <LemonSkeleton repeat={7} className="h-14 w-full" />+ </div>+ ) : failed ? (+ <div className="p-4 text-center text-sm text-muted">+ Couldn’t load the Wizard Library. Close and reopen it to try again.+ </div>+ ) : programs.length === 0 ? (+ search.trim() ? (+ <div className="p-6 text-center">+ <div className="font-semibold">No matching programs</div>+ <p className="mt-1 text-sm text-muted">+ Try a different search, or clear it to see all programs.+ </p>+ <div className="mt-3 flex justify-center">+ <LemonButton type="secondary" size="small" onClick={() => onSearch('')}>+ Clear search+ </LemonButton>+ </div>+ </div>+ ) : (+ <div className="p-6 text-center">+ <div className="font-semibold">No programs are available</div>+ <p className="mt-1 text-sm text-muted">+ Refresh the page, or contact support if you expected to see a program.+ </p>+ </div>+ )+ ) : (+ <div className="flex flex-col">+ {programs.map((program) => (+ <LemonButton+ key={program.id}+ type="tertiary"+ fullWidth+ className={`h-auto justify-start !rounded-none border-l-2 px-3 py-2 text-left ${+ selectedProgram?.id === program.id+ ? 'border-l-accent bg-fill-highlight-100'+ : 'border-l-transparent'+ }`}+ onClick={() => onSelect(program)}+ >+ <div className="w-full min-w-0">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0 font-semibold">{program.name}</div>+ <span className="shrink-0 whitespace-nowrap text-xs font-normal text-muted">+ {program.supported_environments+ .filter(+ (environment) =>+ WIZARD_LOCAL_RUNS_VISIBLE || environment === 'cloud'+ )+ .map((environment) => (environment === 'cloud' ? 'Cloud' : 'Local'))+ .join(' · ')}+ </span>+ </div>+ <div className="line-clamp-2 text-xs font-normal text-muted">+ {program.description}+ </div>+ </div>+ </LemonButton>+ ))}+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/products/wizard/frontend/library/WizardRepositoryPicker.tsx b/products/wizard/frontend/library/WizardRepositoryPicker.tsxnew file mode 100644index 000000000000..f45fbf8a629c--- /dev/null+++ b/products/wizard/frontend/library/WizardRepositoryPicker.tsx@@ -0,0 +1,81 @@+import { useActions, useValues } from 'kea'++import { IconCheck, IconRefresh, IconSearch } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInput, LemonSkeleton, Spinner } from '@posthog/lemon-ui'++import { githubRepositorySearchLogic } from 'lib/integrations/githubRepositorySearchLogic'++export function WizardRepositoryPicker({+ integrationId,+ value,+ onChange,+ disabledReason,+}: {+ integrationId: number+ value: string+ onChange: (repository: string) => void+ disabledReason?: string+}): JSX.Element {+ const logic = githubRepositorySearchLogic({ id: integrationId })+ const { repositories, loading, hasMore, searchQuery, error } = useValues(logic)+ const { setSearchQuery, loadMore, refresh } = useActions(logic)++ // Archived and read-only repositories cannot receive the run's pull request.+ const eligible = repositories.filter((repository) => !repository.archived && repository.can_push !== false)++ return (+ <div className="flex flex-col gap-1">+ <LemonInput+ value={searchQuery}+ onChange={setSearchQuery}+ prefix={<IconSearch />}+ placeholder="Search repositories"+ fullWidth+ data-attr="wizard-cloud-repository-search"+ />+ {error ? (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: refresh }}>+ {error}+ </LemonBanner>+ ) : loading && repositories.length === 0 ? (+ <LemonSkeleton repeat={3} className="h-10 w-full" />+ ) : (+ <div className="max-h-44 overflow-y-auto rounded border border-primary">+ {eligible.length === 0 ? (+ <p className="m-0 px-3 py-2 text-sm text-muted">+ {searchQuery ? 'No matching repositories.' : 'No repositories available.'}+ </p>+ ) : (+ eligible.map((repository) => (+ <LemonButton+ key={repository.id}+ onClick={() => onChange(repository.full_name)}+ active={repository.full_name === value}+ disabledReason={disabledReason}+ fullWidth+ icon={repository.full_name === value ? <IconCheck /> : undefined}+ className="justify-start"+ data-attr="wizard-cloud-repository-option"+ >+ {repository.full_name}+ </LemonButton>+ ))+ )}+ </div>+ )}+ <div className="flex items-center gap-2">+ {hasMore && !error && (+ <LemonButton size="small" onClick={loadMore} loading={loading} disabledReason={disabledReason}>+ Load more+ </LemonButton>+ )}+ {hasMore && !error && !loading && (+ <LemonButton size="small" icon={<IconRefresh />} onClick={refresh} disabledReason={disabledReason}>+ Refresh+ </LemonButton>+ )}+ {loading && repositories.length > 0 && <Spinner className="size-4" />}+ </div>+ </div>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunActionsMenu.tsx b/products/wizard/frontend/runs/WizardRunActionsMenu.tsxnew file mode 100644index 000000000000..af6aa4b16ea7--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunActionsMenu.tsx@@ -0,0 +1,73 @@+import { IconCopy, IconEllipsis, IconListCheck, IconRefresh, IconStopFilled } from '@posthog/icons'+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'++import type { LemonMenuItems } from 'lib/lemon-ui/LemonMenu'++import type { WizardRunApi } from '../generated/api.schemas'+import { wizardRunCanCancel } from '../wizardRunDisplay'++export function WizardRunActionsMenu({+ run,+ currentUserId,+ refreshing,+ cancelling,+ onView,+ onRefresh,+ onCopyRunId,+ onCancel,+}: {+ run: WizardRunApi+ currentUserId: number | null+ refreshing: boolean+ cancelling: boolean+ onView: (run: WizardRunApi) => void+ onRefresh: (run: WizardRunApi) => void+ onCopyRunId: (runId: string) => void+ onCancel: (run: WizardRunApi) => void+}): JSX.Element {+ const items: LemonMenuItems = [+ {+ items: [+ {+ label: 'View run details',+ icon: <IconListCheck />,+ onClick: () => onView(run),+ },+ {+ label: 'Refresh status',+ icon: <IconRefresh />,+ disabledReason: refreshing ? 'Refreshing…' : null,+ onClick: () => onRefresh(run),+ },+ {+ label: 'Copy run ID',+ icon: <IconCopy />,+ onClick: () => onCopyRunId(run.id),+ },+ ],+ },+ wizardRunCanCancel(run, currentUserId) && {+ items: [+ {+ label: 'Cancel run',+ icon: <IconStopFilled />,+ status: 'danger',+ disabledReason: cancelling ? 'Canceling…' : null,+ onClick: () => onCancel(run),+ },+ ],+ },+ ]++ return (+ <LemonMenu items={items} placement="bottom-end" className="min-w-56">+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconEllipsis />}+ aria-label={`More options for ${run.program.name}`}+ onClick={(event) => event.stopPropagation()}+ />+ </LemonMenu>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunDetailsArtifacts.tsx b/products/wizard/frontend/runs/WizardRunDetailsArtifacts.tsxnew file mode 100644index 000000000000..b3ab696680f3--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunDetailsArtifacts.tsx@@ -0,0 +1,99 @@+import { IconArrowRight, IconExternal, IconGitBranch, IconGithub } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonSkeleton } from '@posthog/lemon-ui'++import type { WizardRunApi, WizardRunArtifactApi, WizardRunGitDiffArtifactApi } from '../generated/api.schemas'+import { formatArtifactSize } from '../wizardRunDisplay'+import { WizardRunDiffStats } from './WizardRunDiffStats'++export function WizardRunDetailsArtifacts({+ run,+ artifacts,+ error,+ loading,+ onOpenDiff,+ onRetry,+}: {+ run: WizardRunApi+ artifacts: WizardRunArtifactApi[]+ error: string | null+ loading: boolean+ onOpenDiff: (artifact: WizardRunGitDiffArtifactApi) => void+ onRetry: () => void+}): JSX.Element {+ if (loading) {+ return <LemonSkeleton repeat={2} className="h-12 w-full" />+ }++ if (error && artifacts.length === 0) {+ return (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: onRetry }}>+ {error}+ </LemonBanner>+ )+ }++ if (artifacts.length === 0) {+ return (+ <p className="m-0 text-sm text-muted">+ {run.status === 'created' || run.status === 'running'+ ? 'Artifacts will appear here when the Wizard produces them.'+ : 'This run did not produce any artifacts.'}+ </p>+ )+ }++ const pullRequest = artifacts.find((artifact) => artifact.artifact_type === 'pull_request')+ const gitDiff = artifacts.find((artifact) => artifact.artifact_type === 'git_diff')++ return (+ <div className="divide-y divide-primary overflow-hidden rounded border border-primary">+ {pullRequest && (+ <LemonButton+ type="tertiary"+ fullWidth+ to={pullRequest.url}+ targetBlank+ hideExternalLinkIcon+ icon={<IconGithub />}+ className="h-auto rounded-none px-3 py-3"+ >+ <span className="flex w-full min-w-0 items-center justify-between gap-3">+ <span className="flex min-w-0 flex-col items-start gap-1">+ <span className="font-semibold">Pull request #{pullRequest.number}</span>+ <span className="flex min-w-0 items-center gap-1 text-xs text-muted">+ <IconGitBranch className="shrink-0" />+ <span className="truncate">{pullRequest.base_branch}</span>+ <IconArrowRight className="shrink-0" />+ <span className="truncate">{pullRequest.head_branch}</span>+ </span>+ </span>+ <span className="flex shrink-0 items-center gap-2">+ {gitDiff && (+ <WizardRunDiffStats additions={gitDiff.additions} removals={gitDiff.removals} />+ )}+ <IconExternal className="size-4 text-muted" />+ </span>+ </span>+ </LemonButton>+ )}+ {gitDiff && (+ <LemonButton+ type="tertiary"+ fullWidth+ icon={<IconGitBranch />}+ onClick={() => onOpenDiff(gitDiff)}+ data-attr="wizard-run-open-git-diff"+ className="h-auto rounded-none px-3 py-3"+ >+ <span className="flex w-full min-w-0 items-center justify-between gap-3">+ <span className="flex min-w-0 flex-col items-start gap-1">+ <span className="font-semibold">Git diff</span>+ <span className="text-xs text-muted">{formatArtifactSize(gitDiff.size_bytes)}</span>+ </span>+ <WizardRunDiffStats additions={gitDiff.additions} removals={gitDiff.removals} />+ </span>+ </LemonButton>+ )}+ </div>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunDetailsDrawer.tsx b/products/wizard/frontend/runs/WizardRunDetailsDrawer.tsxnew file mode 100644index 000000000000..db78ae3e0d4e--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunDetailsDrawer.tsx@@ -0,0 +1,278 @@+import { Suspense } from 'react'++import { IconArrowLeft, IconCopy, IconFolder, IconGithub, IconRefresh, IconStopFilled } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDrawer, LemonSkeleton } from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { TZLabel } from 'lib/components/TZLabel'+import { lazyWithRetry } from 'lib/utils/retryImport'++import type { WizardRunApi, WizardRunArtifactApi, WizardRunGitDiffArtifactApi } from '../generated/api.schemas'+import {+ WIZARD_LOCAL_RUNS_VISIBLE,+ wizardGithubRepositoryUrl,+ wizardRunCanCancel,+ wizardRunDiffCanRender,+ wizardRunIsActive,+ wizardRunTerminalLabel,+ wizardWorkspaceLabel,+} from '../wizardRunDisplay'+import { WizardRunDetailsArtifacts } from './WizardRunDetailsArtifacts'+import { WizardRunDiffStats } from './WizardRunDiffStats'+import { WizardRunEnvironmentTag } from './WizardRunEnvironmentTag'+import { WizardRunProgress } from './WizardRunProgress'+import { WizardRunStatusTag } from './WizardRunStatusTag'++// The diff renderer pulls in @pierre/diffs and Shiki, so load it only when a user opens a diff+// instead of shipping it in the runs scene chunk.+const WizardRunDiffViewer = lazyWithRetry(() =>+ import('./WizardRunDiffViewer').then((module) => ({ default: module.WizardRunDiffViewer }))+)++export function WizardRunDetailsDrawer({+ run,+ artifacts,+ artifactsError,+ artifactsLoading,+ currentUserId,+ detailsError,+ refreshing,+ cancelling,+ diffArtifactId,+ diffContent,+ diffError,+ diffLoading,+ onClose,+ onCloseDiff,+ onOpenDiff,+ onRefresh,+ onCopyRunId,+ onCancel,+ onRunAgain,+}: {+ run: WizardRunApi | null+ artifacts: WizardRunArtifactApi[]+ artifactsError: string | null+ artifactsLoading: boolean+ currentUserId: number | null+ detailsError: string | null+ refreshing: boolean+ cancelling: boolean+ diffArtifactId: string | null+ diffContent: string | null+ diffError: string | null+ diffLoading: boolean+ onClose: () => void+ onCloseDiff: () => void+ onOpenDiff: (artifact: WizardRunGitDiffArtifactApi) => void+ onRefresh: () => void+ onCopyRunId: (runId: string) => void+ onCancel: (run: WizardRunApi) => void+ onRunAgain: (run: WizardRunApi) => void+}): JSX.Element {+ const pullRequest = artifacts.find((artifact) => artifact.artifact_type === 'pull_request')+ const gitDiff = artifacts.find((artifact) => artifact.artifact_type === 'git_diff')+ const selectedDiff = gitDiff?.id === diffArtifactId ? gitDiff : null++ return (+ <LemonDrawer+ isOpen={!!run}+ onClose={onClose}+ width={selectedDiff ? 960 : 460}+ overlayTransparent+ title={+ run ? (+ <div className="flex w-full items-center justify-between gap-2 pr-8">+ <span>{run.program.name}</span>+ <WizardRunStatusTag status={run.status} />+ </div>+ ) : (+ 'Wizard run'+ )+ }+ footer={+ run ? (+ <div className="flex w-full items-center justify-between gap-2">+ <LemonButton icon={<IconCopy />} onClick={() => onCopyRunId(run.id)}>+ Copy run ID+ </LemonButton>++ {pullRequest ? (+ <LemonButton type="primary" to={pullRequest.url} targetBlank>+ Open pull request+ </LemonButton>+ ) : wizardRunCanCancel(run, currentUserId) ? (+ <LemonButton+ status="danger"+ icon={<IconStopFilled />}+ onClick={() => onCancel(run)}+ loading={cancelling}+ >+ Cancel run+ </LemonButton>+ ) : run.status === 'failed' && (WIZARD_LOCAL_RUNS_VISIBLE || run.environment === 'cloud') ? (+ <LemonButton type="primary" onClick={() => onRunAgain(run)}>+ Run again+ </LemonButton>+ ) : null}+ </div>+ ) : null+ }+ >+ {run && selectedDiff ? (+ <div className="flex min-w-0 flex-col gap-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <LemonButton+ icon={<IconArrowLeft />}+ onClick={onCloseDiff}+ data-attr="wizard-run-close-git-diff"+ >+ Run details+ </LemonButton>+ <WizardRunDiffStats additions={selectedDiff.additions} removals={selectedDiff.removals} />+ </div>+ <Suspense fallback={<LemonSkeleton repeat={8} className="h-6 w-full" />}>+ {!wizardRunDiffCanRender(selectedDiff.size_bytes) ? (+ <WizardRunDiffViewer+ diff=""+ contentHash={selectedDiff.content_hash}+ sizeBytes={selectedDiff.size_bytes}+ pullRequestUrl={pullRequest?.url ?? null}+ />+ ) : diffLoading ? (+ <LemonSkeleton repeat={8} className="h-6 w-full" />+ ) : diffError ? (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: () => onOpenDiff(selectedDiff) }}+ >+ {diffError}+ </LemonBanner>+ ) : diffContent !== null ? (+ <WizardRunDiffViewer+ diff={diffContent}+ contentHash={selectedDiff.content_hash}+ sizeBytes={selectedDiff.size_bytes}+ pullRequestUrl={pullRequest?.url ?? null}+ />+ ) : (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: () => onOpenDiff(selectedDiff) }}+ >+ Couldn't load this diff. Try again.+ </LemonBanner>+ )}+ </Suspense>+ </div>+ ) : run ? (+ <div className="space-y-5">+ <dl className="space-y-3 text-sm">+ <div className="grid grid-cols-[120px_1fr] items-center gap-3">+ <dt className="text-xs font-semibold uppercase text-muted">Workspace</dt>+ <dd className="m-0 min-w-0">+ {run.workspace.type === 'git_repository' ? (+ <LemonButton+ size="small"+ type="tertiary"+ icon={<IconGithub />}+ to={wizardGithubRepositoryUrl(run.workspace.repository)}+ targetBlank+ className="w-fit max-w-full"+ >+ {run.workspace.repository}+ </LemonButton>+ ) : (+ <span className="inline-flex items-center gap-1 px-2 py-1 text-sm font-medium">+ <IconFolder />+ {wizardWorkspaceLabel(run)}+ </span>+ )}+ </dd>+ </div>+ <div className="grid grid-cols-[120px_1fr] items-center gap-3">+ <dt className="text-xs font-semibold uppercase text-muted">Environment</dt>+ <dd className="m-0">+ <WizardRunEnvironmentTag environment={run.environment} />+ </dd>+ </div>+ <div className="grid grid-cols-[120px_1fr] items-center gap-3">+ <dt className="text-xs font-semibold uppercase text-muted">Started</dt>+ <dd className="m-0">+ {run.started_at ? (+ <TZLabel time={run.started_at} />+ ) : (+ <span className="text-muted">Not started</span>+ )}+ </dd>+ </div>+ <div className="grid grid-cols-[120px_1fr] items-center gap-3">+ <dt className="text-xs font-semibold uppercase text-muted">Run ID</dt>+ <dd className="m-0 font-mono text-xs">+ <CopyToClipboardInline+ explicitValue={run.id}+ >{`${run.id.slice(0, 8)}…`}</CopyToClipboardInline>+ </dd>+ </div>+ </dl>++ <section>+ <div className="mb-3 flex items-center justify-between">+ <h4 className="m-0">Artifacts</h4>+ {wizardRunIsActive(run) && <span className="text-xs text-muted">Pending</span>}+ </div>+ {detailsError && (+ <LemonBanner+ type="warning"+ className="mb-3"+ action={{ children: 'Try again', onClick: onRefresh }}+ >+ {detailsError}+ </LemonBanner>+ )}+ <WizardRunDetailsArtifacts+ run={run}+ artifacts={artifacts}+ error={artifactsError}+ loading={artifactsLoading}+ onOpenDiff={onOpenDiff}+ onRetry={onRefresh}+ />+ </section>++ <section>+ <h4 className="mb-4">Run progress</h4>+ <WizardRunProgress run={run} />+ <div className="mt-4 flex items-center justify-between text-xs text-muted">+ <span>+ {wizardRunIsActive(run) ? (+ 'Updates automatically.'+ ) : run.finished_at ? (+ <>+ {wizardRunTerminalLabel(run.status)} <TZLabel time={run.finished_at} />.+ </>+ ) : (+ `${wizardRunTerminalLabel(run.status)}.`+ )}+ </span>+ {run.status === 'failed' && (WIZARD_LOCAL_RUNS_VISIBLE || run.environment === 'cloud') ? (+ <LemonButton size="small" onClick={() => onRunAgain(run)}>+ Run again+ </LemonButton>+ ) : wizardRunIsActive(run) ? (+ <LemonButton+ size="small"+ icon={<IconRefresh />}+ onClick={onRefresh}+ loading={refreshing}+ >+ Refresh+ </LemonButton>+ ) : null}+ </div>+ </section>+ </div>+ ) : null}+ </LemonDrawer>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunDiffStats.tsx b/products/wizard/frontend/runs/WizardRunDiffStats.tsxnew file mode 100644index 000000000000..b970d1363c76--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunDiffStats.tsx@@ -0,0 +1,18 @@+export function WizardRunDiffStats({+ additions,+ removals,+}: {+ additions: number | null+ removals: number | null+}): JSX.Element | null {+ if (additions === null || removals === null) {+ return null+ }++ return (+ <span className="flex items-center gap-1.5 text-xs font-medium" data-attr="wizard-run-diff-stats">+ <span className="text-success">+{additions.toLocaleString()}</span>+ <span className="text-danger">-{removals.toLocaleString()}</span>+ </span>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunDiffViewer.stories.tsx b/products/wizard/frontend/runs/WizardRunDiffViewer.stories.tsxnew file mode 100644index 000000000000..86e3cfd70af4--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunDiffViewer.stories.tsx@@ -0,0 +1,75 @@+import type { Meta, StoryObj } from '@storybook/react'++import { WizardRunDiffViewer } from './WizardRunDiffViewer'++const diff = `diff --git a/src/analytics.ts b/src/analytics.ts+index 8dc2f8a..c825f2d 100644+--- a/src/analytics.ts++++ b/src/analytics.ts+@@ -1,9 +1,15 @@+ import posthog from 'posthog-js'+ ${''}+ export function initializeAnalytics(): void {+- posthog.init('phc_example')++ posthog.init('phc_example', {++ api_host: 'https://us.i.posthog.com',++ defaults: '2025-05-24',++ })+ }+ ${''}+ export function trackSignup(plan: string): void {+- posthog.capture('user signed up', { plan })++ posthog.capture('user signed up', {++ plan,++ source: 'onboarding',++ })+ }+diff --git a/src/identify.ts b/src/identify.ts+new file mode 100644+index 0000000..0ad1795+--- /dev/null++++ b/src/identify.ts+@@ -0,0 +1,7 @@++import posthog from 'posthog-js'++++export function identifyUser(id: string, email: string): void {++ posthog.identify(id, {++ email,++ })++}+`++const meta: Meta<typeof WizardRunDiffViewer> = {+ title: 'Products/Wizard/Wizard run diff viewer',+ component: WizardRunDiffViewer,+ parameters: { layout: 'fullscreen' },+ args: {+ diff,+ contentHash: 'sample-diff',+ sizeBytes: diff.length,+ pullRequestUrl: 'https://github.com/PostHog/posthog/pull/123',+ },+ decorators: [+ (Story) => (+ <div className="mx-auto w-full max-w-5xl p-6">+ <Story />+ </div>+ ),+ ],+}++export default meta++type Story = StoryObj<typeof WizardRunDiffViewer>++export const Default: Story = {}++export const Narrow: Story = {+ decorators: [+ (Story) => (+ <div className="w-full max-w-lg p-4">+ <Story />+ </div>+ ),+ ],+}diff --git a/products/wizard/frontend/runs/WizardRunDiffViewer.test.tsx b/products/wizard/frontend/runs/WizardRunDiffViewer.test.tsxnew file mode 100644index 000000000000..8d251a4d6b67--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunDiffViewer.test.tsx@@ -0,0 +1,92 @@+import '@testing-library/jest-dom'++import { parsePatchFiles } from '@pierre/diffs'+import type { FileDiffMetadata } from '@pierre/diffs'+import { cleanup, render, screen } from '@testing-library/react'++import { initKeaTests } from '~/test/init'++import { WizardRunDiffViewer } from './WizardRunDiffViewer'++// @pierre/diffs ships ESM-only, which Jest cannot resolve — stub both entry points.+jest.mock('@pierre/diffs', () => ({ parsePatchFiles: jest.fn() }), { virtual: true })+jest.mock('@pierre/diffs/react', () => ({ FileDiff: () => null }), { virtual: true })++const mockParsePatchFiles = jest.mocked(parsePatchFiles)++function makeFile(overrides: Partial<FileDiffMetadata> = {}): FileDiffMetadata {+ return {+ name: 'src/app.ts',+ type: 'change',+ hunks: [],+ splitLineCount: 0,+ unifiedLineCount: 0,+ isPartial: true,+ deletionLines: [],+ additionLines: [],+ ...overrides,+ }+}++describe('WizardRunDiffViewer', () => {+ beforeEach(() => {+ initKeaTests()+ mockParsePatchFiles.mockReset()+ })++ afterEach(cleanup)++ it('renders file cards for a well-formed diff', () => {+ mockParsePatchFiles.mockReturnValue([{ files: [makeFile({ unifiedLineCount: 4 })] }])++ render(<WizardRunDiffViewer diff="patch" contentHash="hash-1" sizeBytes={512} pullRequestUrl={null} />)++ expect(screen.getByText('src/app.ts')).toBeInTheDocument()+ })++ it('shows an error banner instead of an empty result for a malformed diff', () => {+ mockParsePatchFiles.mockImplementation(() => {+ throw new Error('malformed patch')+ })++ render(+ <WizardRunDiffViewer+ diff="not a valid patch"+ contentHash="hash-2"+ sizeBytes={512}+ pullRequestUrl="https://github.com/posthog/posthog/pull/1"+ />+ )++ expect(screen.getByText(/Couldn't display this diff/)).toBeInTheDocument()+ expect(screen.getByText(/Open the pull request/)).toBeInTheDocument()+ })++ it('describes a mode-only change instead of rendering zero lines', () => {+ mockParsePatchFiles.mockReturnValue([{ files: [makeFile({ prevMode: '100644', mode: '100755' })] }])++ render(<WizardRunDiffViewer diff="patch" contentHash="hash-3" sizeBytes={512} pullRequestUrl={null} />)++ expect(screen.getByText(/File mode changed from 100644 to 100755/)).toBeInTheDocument()+ })++ it('describes a binary change instead of rendering zero lines', () => {+ mockParsePatchFiles.mockReturnValue([{ files: [makeFile({ name: 'assets/logo.png' })] }])++ render(<WizardRunDiffViewer diff="patch" contentHash="hash-4" sizeBytes={512} pullRequestUrl={null} />)++ expect(screen.getByText(/Binary file changed/)).toBeInTheDocument()+ })++ it('does not promise a pull request when there is none', () => {+ mockParsePatchFiles.mockImplementation(() => {+ throw new Error('malformed patch')+ })++ render(+ <WizardRunDiffViewer diff="not a valid patch" contentHash="hash-5" sizeBytes={512} pullRequestUrl={null} />+ )++ expect(screen.queryByText(/Open the pull request/)).not.toBeInTheDocument()+ })+})diff --git a/products/wizard/frontend/runs/WizardRunDiffViewer.tsx b/products/wizard/frontend/runs/WizardRunDiffViewer.tsxnew file mode 100644index 000000000000..37859d84459f--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunDiffViewer.tsx@@ -0,0 +1,153 @@+import { parsePatchFiles } from '@pierre/diffs'+import type { FileDiffMetadata, FileDiffOptions } from '@pierre/diffs'+import { FileDiff } from '@pierre/diffs/react'+import { useValues } from 'kea'+import { useMemo } from 'react'++import { LemonBanner, LemonCard } from '@posthog/lemon-ui'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'++import { MAX_RENDERED_WIZARD_DIFF_LINES, wizardRunDiffCanRender } from '../wizardRunDisplay'+const DIFF_THEME = { light: 'github-light', dark: 'github-dark' } as const++function lineCounts(file: FileDiffMetadata): { additions: number; removals: number } {+ return file.hunks.reduce(+ (counts, hunk) => ({+ additions: counts.additions + hunk.additionLines,+ removals: counts.removals + hunk.deletionLines,+ }),+ { additions: 0, removals: 0 }+ )+}++function describeNonTextChange(file: FileDiffMetadata): string | null {+ if (file.hunks.length > 0) {+ return null+ }+ if (file.prevMode && file.mode && file.prevMode !== file.mode) {+ return `File mode changed from ${file.prevMode} to ${file.mode}.`+ }+ if (file.type === 'rename-pure') {+ return 'File renamed without content changes.'+ }+ // git diff --binary emits binary changes without text hunks.+ return 'Binary file changed. The content is not shown.'+}++export function WizardRunDiffViewer({+ diff,+ contentHash,+ sizeBytes,+ pullRequestUrl,+}: {+ diff: string+ contentHash: string+ sizeBytes: number+ pullRequestUrl: string | null+}): JSX.Element {+ const { isDarkModeOn } = useValues(themeLogic)+ const hasPullRequest = !!pullRequestUrl+ const pullRequestAction = pullRequestUrl+ ? { children: 'Open pull request', to: pullRequestUrl, targetBlank: true }+ : undefined++ // Poll updates re-render the drawer with unchanged props, so parse only on real content changes.+ const parsed = useMemo<[boolean, FileDiffMetadata[]]>(() => {+ try {+ // throwOnError: the parser otherwise logs and returns an empty result, which reads+ // as "no changes" instead of a failure.+ return [false, parsePatchFiles(diff, contentHash, true).flatMap((patch) => patch.files)]+ } catch {+ return [true, []]+ }+ }, [diff, contentHash])+ const [parseFailed, files] = parsed++ if (!wizardRunDiffCanRender(sizeBytes)) {+ return (+ <LemonBanner type="warning" action={pullRequestAction}>+ {hasPullRequest+ ? 'This diff is too large to display here. Open the pull request to review the full change.'+ : 'This diff is too large to display here.'}+ </LemonBanner>+ )+ }++ const renderedLines = files.reduce((total, file) => total + file.unifiedLineCount, 0)++ if (parseFailed) {+ return (+ <LemonBanner type="error" action={pullRequestAction}>+ {hasPullRequest+ ? "Couldn't display this diff. Open the pull request to review the changes."+ : "Couldn't display this diff."}+ </LemonBanner>+ )+ }++ if (files.length === 0) {+ return <p className="m-0 text-sm text-muted">No file changes to display.</p>+ }++ if (renderedLines > MAX_RENDERED_WIZARD_DIFF_LINES) {+ return (+ <LemonBanner type="warning" action={pullRequestAction}>+ {hasPullRequest+ ? 'This diff has too many changes to display here. Open the pull request to review the full change.'+ : 'This diff has too many changes to display here.'}+ </LemonBanner>+ )+ }++ const options: FileDiffOptions<never> = {+ theme: DIFF_THEME,+ themeType: isDarkModeOn ? 'dark' : 'light',+ diffStyle: 'unified',+ stickyHeader: true,+ overflow: 'scroll',+ }++ return (+ <div className="flex min-w-0 flex-col gap-3">+ {files.map((file) => {+ const counts = lineCounts(file)+ const path = file.prevName ? `${file.prevName} → ${file.name}` : file.name+ const nonTextChange = describeNonTextChange(file)+ const header = (+ <div className="flex min-w-0 items-center gap-3 border-b border-primary bg-surface-secondary px-3 py-2">+ <span className="truncate font-mono text-xs font-semibold" title={path}>+ {path}+ </span>+ <span className="ml-auto flex shrink-0 gap-2 font-mono text-xs tabular-nums">+ <span className="text-success">+{counts.additions.toLocaleString()}</span>+ <span className="text-danger">-{counts.removals.toLocaleString()}</span>+ </span>+ </div>+ )++ return (+ <LemonCard+ key={`${file.name}-${file.cacheKey ?? ''}`}+ hoverEffect={false}+ className="p-0 overflow-clip"+ >+ {nonTextChange ? (+ <>+ {header}+ <p className="m-0 px-3 py-2 text-sm text-muted">{nonTextChange}</p>+ </>+ ) : (+ <FileDiff<never>+ fileDiff={file}+ options={options}+ renderCustomHeader={() => header}+ disableWorkerPool+ />+ )}+ </LemonCard>+ )+ })}+ </div>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunEnvironmentTag.tsx b/products/wizard/frontend/runs/WizardRunEnvironmentTag.tsxnew file mode 100644index 000000000000..78ed376a23e5--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunEnvironmentTag.tsx@@ -0,0 +1,16 @@+import { IconCloud, IconLaptop } from '@posthog/icons'+import { LemonTag } from '@posthog/lemon-ui'++import type { RunEnvironmentEnumApi } from '../generated/api.schemas'++export function WizardRunEnvironmentTag({ environment }: { environment: RunEnvironmentEnumApi }): JSX.Element {+ return (+ <LemonTag+ type={environment === 'cloud' ? 'info' : 'default'}+ size="medium"+ icon={environment === 'cloud' ? <IconCloud /> : <IconLaptop />}+ >+ {environment === 'cloud' ? 'Cloud' : 'Local'}+ </LemonTag>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunError.tsx b/products/wizard/frontend/runs/WizardRunError.tsxnew file mode 100644index 000000000000..2bf64656b4f8--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunError.tsx@@ -0,0 +1,18 @@+import type { WizardRunErrorDetails } from './wizardRunErrorCatalog'++export function WizardRunError({ error }: { error: WizardRunErrorDetails }): JSX.Element {+ return (+ <div className="space-y-2">+ <div>+ <div className="font-semibold">{error.title}</div>+ {error.description !== error.title && <div className="text-sm">{error.description}</div>}+ </div>+ {error.resolution && (+ <div>+ <div className="text-sm font-semibold">What to do?</div>+ <div className="text-sm">{error.resolution}</div>+ </div>+ )}+ </div>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunProgress.tsx b/products/wizard/frontend/runs/WizardRunProgress.tsxnew file mode 100644index 000000000000..a173ce04886c--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunProgress.tsx@@ -0,0 +1,181 @@+import { IconCheckCircle, IconClock, IconWarning, IconXCircle } from '@posthog/icons'+import { Spinner } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import type { WizardRunApi } from '../generated/api.schemas'+import { wizardRunFailureStage, wizardWorkspaceLabel } from '../wizardRunDisplay'+import { wizardRunErrorDetails } from './wizardRunErrorCatalog'++type ProgressState = 'complete' | 'active' | 'pending' | 'failed'++function stagePosition(run: WizardRunApi): number {+ if (run.status === 'completed') {+ return 4+ }+ if (run.status === 'created') {+ return 0+ }++ const stage = run.status === 'failed' ? wizardRunFailureStage(run) : run.stage++ switch (stage) {+ case 'dispatching':+ case 'provisioning':+ return 0+ case 'preparing_workspace':+ return 1+ case 'executing_wizard':+ return 2+ case 'creating_artifacts':+ return 3+ default:+ return run.status === 'running' ? 2 : 0+ }+}++function progressState(run: WizardRunApi, step: number): ProgressState {+ if (run.status === 'cancelled') {+ // A terminal transition clears the stage, so how far a canceled run got is unknown.+ return step === 0 ? 'complete' : 'pending'+ }++ const position = stagePosition(run)++ if (run.status === 'failed') {+ if (wizardRunFailureStage(run) === null) {+ return step === 0 ? 'complete' : 'pending'+ }+ if (position === step) {+ return 'failed'+ }+ }+ if (position > step) {+ return 'complete'+ }+ if (position === step && run.status !== 'completed') {+ return 'active'+ }+ return 'pending'+}++function ProgressIcon({ state }: { state: ProgressState }): JSX.Element {+ if (state === 'complete') {+ return <IconCheckCircle className="text-success" />+ }+ if (state === 'active') {+ return <Spinner textColored />+ }+ if (state === 'failed') {+ return <IconXCircle className="text-danger" />+ }+ return <IconClock className="text-muted" />+}++function RunLevelOutcome({ run }: { run: WizardRunApi }): JSX.Element | null {+ if (run.status === 'cancelled') {+ return (+ <div className="flex items-center gap-1 text-xs text-muted">+ <IconXCircle className="shrink-0" /> Run canceled+ {run.finished_at && (+ <>+ {' '}+ <TZLabel time={run.finished_at} />+ </>+ )}+ .+ </div>+ )+ }++ if (run.status !== 'failed') {+ return null+ }++ const runError = wizardRunErrorDetails(run.error_code, run.error_message)++ return (+ <div className="space-y-1 text-xs">+ <div className="flex items-center gap-1 text-danger">+ <IconXCircle className="shrink-0" /> {runError.title}+ </div>+ {runError.description !== runError.title && <div className="text-muted">{runError.description}</div>}+ {runError.resolution && (+ <div className="flex items-start gap-1 text-muted">+ <IconWarning className="mt-0.5 shrink-0" /> {runError.resolution}+ </div>+ )}+ </div>+ )+}++export function WizardRunProgress({ run }: { run: WizardRunApi }): JSX.Element {+ const runError = wizardRunErrorDetails(run.error_code, run.error_message)+ const failedAtStep = run.status === 'failed' && wizardRunFailureStage(run)+ const steps = [+ {+ title: 'Starting run',+ detail: run.created_at ? <TZLabel time={run.created_at} /> : 'Waiting to start',+ },+ {+ title: 'Preparing workspace',+ detail:+ run.workspace.type === 'git_repository'+ ? `Repository: ${run.workspace.repository}`+ : `Folder: ${wizardWorkspaceLabel(run)}`,+ },+ {+ title: 'Running Wizard',+ detail: `Program: ${run.program.name}`,+ },+ {+ title: 'Finishing up',+ detail:+ run.status === 'completed'+ ? 'Changes and artifacts are ready'+ : stagePosition(run) === 3+ ? 'Saving changes and artifacts'+ : 'Starts after the program finishes',+ },+ ]++ return (+ <div className="space-y-0">+ {steps.map((step, index) => {+ const state = progressState(run, index)+ return (+ <div key={step.title} className="relative flex gap-3 pb-5 last:pb-0">+ {index < steps.length - 1 && (+ <div className="absolute left-[7px] top-5 h-[calc(100%-12px)] border-l border-primary" />+ )}+ <div className="relative z-10 mt-0.5 flex size-4 shrink-0 items-center justify-center bg-surface-primary">+ <ProgressIcon state={state} />+ </div>+ <div className="min-w-0">+ <div className="font-semibold">{step.title}</div>+ <div className="text-xs text-muted">{step.detail}</div>+ {state === 'failed' && (+ <div className="mt-1 space-y-1 text-xs">+ <div className="flex items-center gap-1 text-danger">+ <IconWarning /> {runError.title}+ </div>+ {runError.description !== runError.title && (+ <div className="text-muted">{runError.description}</div>+ )}+ {runError.resolution && (+ <div className="text-muted">Next step: {runError.resolution}</div>+ )}+ </div>+ )}+ </div>+ </div>+ )+ })}+ {(run.status === 'cancelled' || (run.status === 'failed' && !failedAtStep)) && (+ <div className="border-t border-primary pt-3">+ <RunLevelOutcome run={run} />+ </div>+ )}+ </div>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunStatusTag.tsx b/products/wizard/frontend/runs/WizardRunStatusTag.tsxnew file mode 100644index 000000000000..4f9ca6be903a--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunStatusTag.tsx@@ -0,0 +1,44 @@+import { IconCheckCircle, IconClock, IconX, IconXCircle } from '@posthog/icons'+import { LemonTag, Spinner } from '@posthog/lemon-ui'++import type { WizardRunApi } from '../generated/api.schemas'++export function WizardRunStatusTag({ status }: { status: WizardRunApi['status'] }): JSX.Element {+ if (status === 'completed') {+ return (+ <LemonTag type="success" size="medium" icon={<IconCheckCircle />}>+ Completed+ </LemonTag>+ )+ }++ if (status === 'failed') {+ return (+ <LemonTag type="danger" size="medium" icon={<IconXCircle />}>+ Failed+ </LemonTag>+ )+ }++ if (status === 'running') {+ return (+ <LemonTag type="warning" size="medium" icon={<Spinner textColored />}>+ Running+ </LemonTag>+ )+ }++ if (status === 'cancelled') {+ return (+ <LemonTag type="muted" size="medium" icon={<IconX />}>+ Canceled+ </LemonTag>+ )+ }++ return (+ <LemonTag type="warning" size="medium" icon={<IconClock />}>+ Starting+ </LemonTag>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunTable.tsx b/products/wizard/frontend/runs/WizardRunTable.tsxnew file mode 100644index 000000000000..925807d22453--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunTable.tsx@@ -0,0 +1,175 @@+import { IconFolder, IconGithub } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'++import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'+import { TZLabel } from 'lib/components/TZLabel'++import type { WizardRunApi } from '../generated/api.schemas'+import { wizardGithubRepositoryUrl, wizardWorkspaceLabel } from '../wizardRunDisplay'+import { WizardRunActionsMenu } from './WizardRunActionsMenu'+import { WizardRunEnvironmentTag } from './WizardRunEnvironmentTag'+import { WizardRunsEmptyState } from './WizardRunsEmptyState'+import { WizardRunStatusTag } from './WizardRunStatusTag'++export function WizardRunTable({+ runs,+ totalRuns,+ selectedRunId,+ currentUserId,+ loading,+ failed,+ hasActiveFilters,+ refreshing,+ cancelling,+ onOpenLibrary,+ onClearFilters,+ onRefreshRuns,+ onSelect,+ onRefreshRun,+ onCopyRunId,+ onCancel,+}: {+ runs: WizardRunApi[]+ totalRuns: number+ selectedRunId: string | null+ currentUserId: number | null+ loading: boolean+ failed: boolean+ hasActiveFilters: boolean+ refreshing: boolean+ cancelling: boolean+ onOpenLibrary: () => void+ onClearFilters: () => void+ onRefreshRuns: () => void+ onSelect: (run: WizardRunApi) => void+ onRefreshRun: (run: WizardRunApi) => void+ onCopyRunId: (runId: string) => void+ onCancel: (run: WizardRunApi) => void+}): JSX.Element {+ const columns: LemonTableColumns<WizardRunApi> = [+ {+ title: 'Program',+ key: 'program',+ render: (_, run) => (+ <div className="min-w-44">+ <div className="font-semibold">{run.program.name}</div>+ <div className="text-xs text-muted">Wizard {run.program.wizard_version}</div>+ </div>+ ),+ },+ {+ title: 'Workspace',+ key: 'workspace',+ render: (_, run) => {+ if (run.workspace.type === 'git_repository') {+ return (+ <LemonButton+ size="small"+ type="tertiary"+ icon={<IconGithub />}+ to={wizardGithubRepositoryUrl(run.workspace.repository)}+ targetBlank+ className="w-fit"+ onClick={(e) => e.stopPropagation()}+ >+ {run.workspace.repository}+ </LemonButton>+ )+ }+ return (+ <span className="inline-flex items-center gap-1 px-2 py-1 text-sm font-medium">+ <IconFolder />+ {wizardWorkspaceLabel(run)}+ </span>+ )+ },+ },+ {+ title: 'Environment',+ key: 'environment',+ render: (_, run) => <WizardRunEnvironmentTag environment={run.environment} />,+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, run) => (+ <div className="flex min-w-36 flex-col items-start gap-1">+ <WizardRunStatusTag status={run.status} />+ {run.status === 'failed' && run.error_message && (+ <span className="max-w-52 text-xs text-muted" title={run.error_message}>+ {run.error_message}+ </span>+ )}+ </div>+ ),+ },+ {+ title: 'Started',+ key: 'started_at',+ render: (_, run) =>+ run.started_at ? (+ <TZLabel time={run.started_at} className="whitespace-nowrap text-xs" />+ ) : (+ <span className="whitespace-nowrap text-xs text-muted">Not started</span>+ ),+ },+ ]++ // Judge failure against the unfiltered list: a background poll can fail while a filter+ // legitimately matches nothing.+ if (failed && totalRuns === 0) {+ return (+ <LemonBanner type="error" action={{ children: 'Refresh', onClick: onRefreshRuns }}>+ <div className="font-semibold">Couldn’t load Wizard runs.</div>+ <div className="text-sm">Refresh the page and try again.</div>+ </LemonBanner>+ )+ }++ return (+ <div className="flex flex-col gap-2">+ {failed && totalRuns > 0 && (+ <LemonBanner type="warning" action={{ children: 'Refresh', onClick: onRefreshRuns }}>+ Live updates stopped. The list may be out of date.+ </LemonBanner>+ )}+ <LemonTable+ id="wizard-runs"+ dataSource={runs}+ columns={columns}+ rowKey="id"+ loading={loading}+ loadingSkeletonRows={7}+ nouns={['Wizard run', 'Wizard runs']}+ pagination={{ pageSize: 25, hideOnSinglePage: false, useUrl: false }}+ rowClassName="h-[68px]"+ rowStatus={(run) => (run.id === selectedRunId ? 'highlighted' : null)}+ onRow={(run) => ({ onClick: () => onSelect(run), className: 'cursor-pointer' })}+ emptyState={+ hasActiveFilters ? (+ <EmptyMessage+ title="No matching Wizard runs"+ description="Try another search or clear the current filters."+ buttonText="Clear filters"+ buttonOnClick={onClearFilters}+ />+ ) : (+ <WizardRunsEmptyState onOpenLibrary={onOpenLibrary} />+ )+ }+ rowActions={(run) => (+ <WizardRunActionsMenu+ run={run}+ currentUserId={currentUserId}+ refreshing={refreshing}+ cancelling={cancelling}+ onView={onSelect}+ onRefresh={onRefreshRun}+ onCopyRunId={onCopyRunId}+ onCancel={onCancel}+ />+ )}+ />+ </div>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunsEmptyState.tsx b/products/wizard/frontend/runs/WizardRunsEmptyState.tsxnew file mode 100644index 000000000000..4d71399231c5--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunsEmptyState.tsx@@ -0,0 +1,17 @@+import { IconDocument } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++export function WizardRunsEmptyState({ onOpenLibrary }: { onOpenLibrary: () => void }): JSX.Element {+ return (+ <div className="flex min-h-[440px] flex-col items-center justify-center gap-3 py-16 text-center">+ <IconDocument className="text-4xl text-muted" />+ <div className="font-semibold">No Wizard runs yet</div>+ <p className="m-0 max-w-md text-sm text-muted">+ Choose a program from the Wizard Library to start a cloud run.+ </p>+ <LemonButton type="primary" onClick={onOpenLibrary}>+ Open Wizard Library+ </LemonButton>+ </div>+ )+}diff --git a/products/wizard/frontend/runs/wizardRunErrorCatalog.test.ts b/products/wizard/frontend/runs/wizardRunErrorCatalog.test.tsnew file mode 100644index 000000000000..6d81ce1b0df1--- /dev/null+++ b/products/wizard/frontend/runs/wizardRunErrorCatalog.test.ts@@ -0,0 +1,28 @@+import { wizardRunErrorDetails } from './wizardRunErrorCatalog'++describe('wizardRunErrorDetails', () => {+ it('returns guidance for a catalogued Wizard error', () => {+ expect(wizardRunErrorDetails('PHW_DETECT_NO_POSTHOG_SDK', null)).toEqual({+ title: 'No PostHog SDK was found',+ description: 'This program needs an existing PostHog SDK installation.',+ resolution:+ 'Run the PostHog integration program first, merge its pull request, then run this program again.',+ })+ })++ it('returns guidance for a detect-stage failure with no SDKs', () => {+ expect(wizardRunErrorDetails('PHW_DETECT_NO_SDKS', null).title).toBe('No PostHog or Stripe SDK was found')+ expect(wizardRunErrorDetails('PHW_DETECT_NO_PACKAGE_JSON', null).title).toBe('No package.json was found')+ expect(wizardRunErrorDetails('PHW_DETECT_MISSING_STRIPE', null).title).toBe('No Stripe SDK was found')+ expect(wizardRunErrorDetails('PHW_DETECT_UNCLASSIFIED', null).title).toBe(+ 'The Wizard could not inspect this project'+ )+ })++ it('uses the safe backend message for an unknown error', () => {+ expect(wizardRunErrorDetails('PHW_FUTURE_ERROR', 'The Wizard could not finish.')).toEqual({+ title: 'The Wizard could not finish.',+ description: 'The Wizard could not finish.',+ })+ })+})diff --git a/products/wizard/frontend/runs/wizardRunErrorCatalog.ts b/products/wizard/frontend/runs/wizardRunErrorCatalog.tsnew file mode 100644index 000000000000..dd170b4fd5ef--- /dev/null+++ b/products/wizard/frontend/runs/wizardRunErrorCatalog.ts@@ -0,0 +1,237 @@+export interface WizardRunErrorDetails {+ title: string+ description: string+ resolution?: string+}++const WIZARD_RUN_ERROR_CATALOG: Record<string, WizardRunErrorDetails> = {+ PHW_CLI_NODE_VERSION: {+ title: 'The Node.js version is not supported',+ description: 'The Wizard cannot run with the Node.js version in this workspace.',+ resolution: 'Run the program again. If it keeps failing, contact PostHog support.',+ },+ PHW_CLI_BAD_ARGS: {+ title: 'The Wizard command is invalid',+ description: 'The command contains an unknown option or program name.',+ },+ PHW_CLI_FLAG_UNAVAILABLE: {+ title: 'A Wizard option is not available',+ description: 'The selected Wizard version does not support one of the command options.',+ },+ PHW_CLI_INTERACTIVE_REQUIRED: {+ title: 'This program needs an interactive terminal',+ description: 'The program cannot run unattended in the cloud.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_ARGS_MISSING_API_KEY: {+ title: 'The Wizard could not authenticate',+ description: 'The run did not receive a PostHog API key.',+ },+ PHW_ARGS_MISSING_INSTALL_DIR: {+ title: 'The project folder is missing',+ description: 'The run did not receive a project folder.',+ },+ PHW_ARGS_MISSING_EMAIL: {+ title: 'An email address is required',+ description: 'The selected signup flow needs an email address.',+ },+ PHW_ARGS_SIGNUP_PROVISION_FAILED: {+ title: 'PostHog account setup failed',+ description: 'The Wizard could not finish account setup.',+ resolution: 'Try the program again. If it still fails, contact PostHog support.',+ },+ PHW_AUTH_KEY_TYPE: {+ title: 'The API key type is not supported',+ description: 'The Wizard received a key that cannot authenticate this program.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_AUTH_MISSING_SCOPE: {+ title: 'The API key needs more access',+ description: 'The current key does not include a scope required by this program.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_AUTH_REGION_MISMATCH: {+ title: 'The PostHog region does not match',+ description: 'The credentials belong to a different PostHog region.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_AUTH_INVALID_OR_EXPIRED: {+ title: 'The PostHog credentials are invalid or expired',+ description: 'The Wizard could not use the current credentials.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_AUTH_SETTINGS_CONFLICT: {+ title: 'Local settings override PostHog authentication',+ description: 'A Claude settings file replaces the credentials provided by the Wizard.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_AUTH_STORED_LOGIN_CONFLICT: {+ title: 'A stored Claude login overrides PostHog authentication',+ description: 'The agent used a stored login instead of the credentials provided by the Wizard.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_AUTH_PROJECT_FETCH_FAILED: {+ title: 'The Wizard could not load the PostHog project',+ description: 'PostHog project data was unavailable during the run.',+ resolution: 'Try the program again. If it still fails, contact PostHog support.',+ },+ PHW_ENV_LOCAL_SERVICES_DOWN: {+ title: 'Required local services are not running',+ description: 'The Wizard cannot reach a service needed for local development.',+ resolution: 'Start the required local services, then run the program again.',+ },+ PHW_ENV_SERVICE_OUTAGE: {+ title: 'A required service is unavailable',+ description: 'The Wizard cannot reach a service needed to complete this program.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_DETECT_BAD_DIRECTORY: {+ title: 'The project folder is not accessible',+ description: 'The selected folder is missing, unreadable, or not a directory.',+ resolution: 'Run the Wizard from a readable project folder.',+ },+ PHW_DETECT_NO_FRAMEWORK: {+ title: 'No supported framework was found',+ description: 'The Wizard could not detect a supported framework in this workspace.',+ resolution: 'Select the repository that contains your project root, then run the program again.',+ },+ PHW_DETECT_UNSUPPORTED_VERSION: {+ title: 'The framework version is not supported',+ description: 'The detected framework version is older than the Wizard supports.',+ resolution: 'Update the framework, then run the program again.',+ },+ PHW_DETECT_UNSUPPORTED_PLATFORM: {+ title: 'This project does not support the selected program',+ description: 'The Wizard has no compatible setup path for the detected platform.',+ resolution: 'Choose a program that supports this project, or follow the manual setup guide.',+ },+ PHW_DETECT_NO_POSTHOG_SDK: {+ title: 'No PostHog SDK was found',+ description: 'This program needs an existing PostHog SDK installation.',+ resolution: 'Run the PostHog integration program first, merge its pull request, then run this program again.',+ },+ PHW_DETECT_NO_PROJECT_FILES: {+ title: 'No project files were found',+ description: 'The workspace does not contain files that this program can update.',+ resolution: 'Select a repository that contains your project, then run the program again.',+ },+ PHW_DETECT_NO_SOURCES: {+ title: 'No data warehouse sources were found',+ description: 'This program needs at least one connected data warehouse source.',+ resolution: 'Connect a data warehouse source in PostHog, then run the program again.',+ },+ PHW_DETECT_NO_PACKAGE_JSON: {+ title: 'No package.json was found',+ description:+ 'The Wizard scans only Node.js and TypeScript projects, and the connected repository has no package.json at its root.',+ resolution:+ 'Select a repository that contains your Node.js or TypeScript project root, then run the program again.',+ },+ PHW_DETECT_NO_SDKS: {+ title: 'No PostHog or Stripe SDK was found',+ description: 'The program scanned the repository and found neither a PostHog SDK nor a Stripe SDK.',+ resolution:+ 'Run the PostHog integration program first, install a Stripe SDK in your project, then run this program again.',+ },+ PHW_DETECT_MISSING_STRIPE: {+ title: 'No Stripe SDK was found',+ description: 'The program found a PostHog SDK, but revenue analytics currently supports Stripe only.',+ resolution: 'Install a Stripe SDK in your project, then run the program again.',+ },+ PHW_DETECT_UNCLASSIFIED: {+ title: 'The Wizard could not inspect this project',+ description: 'The project inspection step failed before the Wizard could classify the project.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_SKILL_MENU_FETCH_FAILED: {+ title: 'The Wizard could not load its setup programs',+ description: 'The program catalog was unavailable during the run.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_SKILL_NOT_FOUND: {+ title: 'The selected setup program is unavailable',+ description: 'The Wizard could not find the selected program in its catalog.',+ resolution: 'Return to the Wizard Library and select an available program.',+ },+ PHW_SKILL_DOWNLOAD_FAILED: {+ title: 'The setup program could not be downloaded',+ description: 'The Wizard could not prepare the selected program.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_AGENT_ABORT: {+ title: 'The setup agent stopped the run',+ description: 'The agent found a condition that prevented it from continuing safely.',+ resolution: 'Review the project requirements, then run the program again.',+ },+ PHW_AGENT_MCP_MISSING: {+ title: 'The setup agent could not connect to PostHog',+ description: 'The PostHog tools required by the agent were unavailable.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_AGENT_RESOURCE_MISSING: {+ title: 'A required setup resource is unavailable',+ description: 'The agent could not load a resource needed by this program.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_AGENT_RATE_LIMIT: {+ title: 'The setup agent reached a rate limit',+ description: 'The AI service temporarily stopped accepting requests.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_AGENT_API_ERROR: {+ title: 'The setup agent lost access to a required service',+ description: 'An API request failed while the program was running.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_AGENT_YARA_VIOLATION: {+ title: 'A security check stopped the run',+ description: 'The agent produced content that did not pass the security check.',+ },+ PHW_AGENT_NO_PROGRESS: {+ title: 'The setup agent made no changes',+ description: 'The agent stopped before it could inspect or update the project.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+ PHW_AGENT_INCOMPLETE_TASKS: {+ title: 'The setup agent did not finish every task',+ description: 'The run ended with required setup work still open.',+ resolution: 'Run the program again to finish the remaining work.',+ },+ PHW_AGENT_ORCHESTRATOR_SKILL_VARIANT_MISSING: {+ title: 'A required setup program is unavailable',+ description: 'The agent could not download a program for one of its planned tasks.',+ resolution: 'Wait a few minutes, then run the program again.',+ },+ PHW_AGENT_ORCHESTRATOR_TASKS_FAILED: {+ title: 'One or more setup tasks failed',+ description: 'The agent could not complete all required tasks.',+ resolution: 'Run the program again. If it still fails, review the project requirements.',+ },+ PHW_AGENT_ORCHESTRATOR_SINK_INVARIANT: {+ title: 'The setup plan is invalid',+ description: 'The agent could not create a safe plan for the selected program.',+ },+ PHW_SETTINGS_UNFIXABLE_CONFLICT: {+ title: 'A local settings conflict cannot be fixed automatically',+ description: 'A managed or read-only Claude setting conflicts with the Wizard.',+ resolution: 'Update the conflicting setting, then run the program again.',+ },+ PHW_INTERNAL_UNHANDLED: {+ title: 'The Wizard encountered an unexpected error',+ description: 'The program stopped because of an error that the Wizard did not recognize.',+ resolution: 'Run the program again. If it still fails, contact PostHog support.',+ },+}++export function wizardRunErrorDetails(errorCode: string | null, fallbackMessage: string | null): WizardRunErrorDetails {+ if (errorCode && WIZARD_RUN_ERROR_CATALOG[errorCode]) {+ return WIZARD_RUN_ERROR_CATALOG[errorCode]+ }++ const description = fallbackMessage || 'The Wizard run failed before it could finish.'++ return {+ title: description,+ description,+ }+}diff --git a/products/wizard/frontend/wizardApi.ts b/products/wizard/frontend/wizardApi.tsnew file mode 100644index 000000000000..89c94030ab9c--- /dev/null+++ b/products/wizard/frontend/wizardApi.ts@@ -0,0 +1,18 @@+import api from 'lib/api'++import { getWizardRunsArtifactsContentRetrieveUrl, wizardRunsArtifactsList } from './generated/api'+import type { WizardRunArtifactApi } from './generated/api.schemas'++export async function loadWizardRunArtifacts(projectId: string, runId: string): Promise<WizardRunArtifactApi[]> {+ return (await wizardRunsArtifactsList(projectId, runId)).results+}++export async function loadWizardRunArtifactContent(+ projectId: string,+ runId: string,+ artifactId: string+): Promise<string> {+ const response = await api.getResponse(getWizardRunsArtifactsContentRetrieveUrl(projectId, runId, artifactId))++ return response.text()+}diff --git a/products/wizard/frontend/wizardLibraryLogic.test.ts b/products/wizard/frontend/wizardLibraryLogic.test.tsnew file mode 100644index 000000000000..4816e4c12f47--- /dev/null+++ b/products/wizard/frontend/wizardLibraryLogic.test.ts@@ -0,0 +1,179 @@+import { expectLogic } from 'kea-test-utils'++import { preflightLogic } from 'lib/logic/preflightLogic'+import { projectLogic } from 'scenes/projectLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { wizardRegistryList, wizardRunsCreate } from './generated/api'+import type { WizardProgramApi, WizardRunApi } from './generated/api.schemas'+import { wizardLibraryLogic } from './wizardLibraryLogic'+import { wizardRunDetailsLogic } from './wizardRunDetailsLogic'++jest.mock('./generated/api', () => ({+ wizardRegistryList: jest.fn(),+ wizardRunsCreate: jest.fn(),+ wizardRunsList: jest.fn().mockResolvedValue({ count: 0, next: null, previous: null, results: [] }),+}))++const mockWizardRegistryList = wizardRegistryList as jest.Mock+const mockWizardRunsCreate = wizardRunsCreate as jest.Mock++const program: WizardProgramApi = {+ id: 'posthog-integration',+ name: 'PostHog integration',+ description: 'Set up PostHog',+ wizard_version: '2.67.0',+ command: [],+ tags: [],+ required_programs: [],+ supported_environments: ['local', 'cloud'],+}++const localProgram: WizardProgramApi = {+ ...program,+ id: 'local-program',+ name: 'Local program',+ supported_environments: ['local'],+}++describe('wizardLibraryLogic', () => {+ let logic: ReturnType<typeof wizardLibraryLogic.build>++ beforeEach(async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/integrations/': () => [200, { results: [] }],+ },+ })+ jest.spyOn(console, 'error').mockImplementation()+ initKeaTests()+ mockWizardRegistryList.mockResolvedValue({+ count: 2,+ next: null,+ previous: null,+ results: [program, localProgram],+ })+ mockWizardRunsCreate.mockReset()+ await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })+ logic = wizardLibraryLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ preflightLogic.actions.loadPreflightSuccess({ wizard_cloud_run_available: true } as any)+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ it('hides programs that only support local runs', () => {+ expect(logic.values.filteredPrograms).toEqual([program])+ })++ it('reuses the idempotency key after a failed cloud request', async () => {+ mockWizardRunsCreate.mockRejectedValue(new Error('request failed'))+ logic.actions.openLibrary('stable-key')+ logic.actions.selectProgram(program)+ logic.actions.setRepository('posthog/posthog')++ logic.actions.createRun()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.createRun()+ await expectLogic(logic).toFinishAllListeners()++ expect(mockWizardRunsCreate).toHaveBeenCalledTimes(2)+ expect(mockWizardRunsCreate.mock.calls[0][1].idempotency_key).toBe('stable-key')+ expect(mockWizardRunsCreate.mock.calls[1][1].idempotency_key).toBe('stable-key')+ })++ it('does not create a server run for local execution', async () => {+ logic.actions.openLibrary('stable-key')+ logic.actions.selectProgram(program)+ logic.actions.setLibraryEnvironment('local')++ logic.actions.createRun()+ await expectLogic(logic).toFinishAllListeners()++ expect(mockWizardRunsCreate).not.toHaveBeenCalled()+ })++ it('runs the program version shown in the Library', async () => {+ logic.actions.openLibrary('stable-key')+ logic.actions.selectProgram(program)+ logic.actions.setRepository('posthog/posthog')++ logic.actions.createRun()+ await expectLogic(logic).toFinishAllListeners()++ expect(mockWizardRunsCreate.mock.calls[0][1].wizard_version).toBe('2.67.0')+ })++ it('does not open the cloud-only Library when cloud runs are unavailable', async () => {+ preflightLogic.actions.loadPreflightSuccess({ wizard_cloud_run_available: false } as any)++ logic.actions.openLibrary('stable-key')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.isLibraryOpen).toBe(false)+ expect(mockWizardRunsCreate).not.toHaveBeenCalled()+ })++ it('follows the new run after a successful start', async () => {+ const createdRun = { id: 'run-new' } as WizardRunApi+ mockWizardRunsCreate.mockResolvedValueOnce(createdRun)+ const detailsLogic = wizardRunDetailsLogic()+ detailsLogic.mount()+ logic.actions.openLibrary('stable-key')+ logic.actions.selectProgram(program)+ logic.actions.setRepository('posthog/posthog')++ logic.actions.createRun()+ await expectLogic(logic).toFinishAllListeners()++ expect(detailsLogic.values.selectedRunSummary?.id).toBe('run-new')+ })++ it('selects the retried program after the registry reloads', async () => {+ mockWizardRegistryList.mockResolvedValue({+ count: 2,+ next: null,+ previous: null,+ results: [program, localProgram],+ })+ const run = {+ id: 'run-old',+ program: { id: 'posthog-integration' },+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'posthog/posthog' },+ }++ logic.actions.runAgain(run as any)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.isLibraryOpen).toBe(true)+ expect(logic.values.selectedProgram?.id).toBe('posthog-integration')+ })++ it('marks the selection unavailable when the retried program is gone', async () => {+ mockWizardRegistryList.mockResolvedValue({+ count: 1,+ next: null,+ previous: null,+ results: [localProgram],+ })+ const run = {+ id: 'run-old',+ program: { id: 'posthog-integration' },+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'posthog/posthog' },+ }++ logic.actions.runAgain(run as any)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.selectedProgram).toBeNull()+ expect(logic.values.programSelectionInvalidated).toBe(true)+ })+})diff --git a/products/wizard/frontend/wizardLibraryLogic.ts b/products/wizard/frontend/wizardLibraryLogic.tsnew file mode 100644index 000000000000..3a24026dd4fd--- /dev/null+++ b/products/wizard/frontend/wizardLibraryLogic.ts@@ -0,0 +1,418 @@+import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api, { ApiError } from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { preflightLogic } from 'lib/logic/preflightLogic'+import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { uuid } from 'lib/utils/dom'+import { projectLogic } from 'scenes/projectLogic'+import { urls } from 'scenes/urls'++import type { IntegrationType, PreflightStatus } from '../../../frontend/src/types'+import { wizardRegistryList, wizardRunsCreate } from './generated/api'+import type {+ RunEnvironmentEnumApi,+ WizardProgramApi,+ WizardRunApi,+ WizardRunCreateRequestApi,+} from './generated/api.schemas'+import { wizardRunDetailsLogic } from './wizardRunDetailsLogic'+import { WIZARD_LOCAL_RUNS_VISIBLE, wizardCommand } from './wizardRunDisplay'+import { wizardRunsLogic } from './wizardRunsLogic'++function requestError(error: unknown, fallback: string): string {+ return error instanceof ApiError && error.detail ? error.detail : fallback+}++export interface wizardLibraryLogicValues {+ currentProjectId: number | null+ githubIntegrations: IntegrationType[]+ integrationsLoading: boolean+ preflight: PreflightStatus | null+ commandCopied: boolean+ connectGitHubUrl: string+ createRunError: string | null+ createRunIdempotencyKey: string | null+ createRunRequest: WizardRunApi | null+ createRunRequestLoading: boolean+ filteredPrograms: WizardProgramApi[]+ githubIntegration: IntegrationType | null+ isLibraryOpen: boolean+ libraryEnvironment: RunEnvironmentEnumApi+ librarySearch: string+ programSelectionInvalidated: boolean+ registry: WizardProgramApi[]+ registryFailed: boolean+ registryInitialLoading: boolean+ registryLoading: boolean+ repository: string+ requiredPrograms: WizardProgramApi[]+ selectedProgram: WizardProgramApi | null+ selectedProgramCommand: string+ wizardCloudRunAvailable: boolean+}++export interface wizardLibraryLogicActions {+ closeLibrary: () => { value: true }+ copyCommand: () => { value: true }+ createRun: () => { value: true }+ createRunRequest: ({ projectId, body }: { projectId: string; body: WizardRunCreateRequestApi }) => {+ projectId: string+ body: WizardRunCreateRequestApi+ }+ createRunRequestFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ createRunRequestSuccess: (+ createRunRequest: WizardRunApi,+ payload?: { projectId: string; body: WizardRunCreateRequestApi }+ ) => {+ createRunRequest: WizardRunApi+ payload?: { projectId: string; body: WizardRunCreateRequestApi }+ }+ invalidateProgramSelection: () => { value: true }+ loadIntegrations: () => { value: true }+ loadRegistry: () => { value: true }+ loadRegistryFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ loadRegistrySuccess: (registry: WizardProgramApi[]) => { registry: WizardProgramApi[] }+ markCommandCopied: () => { value: true }+ openLibrary: (idempotencyKey?: string) => { idempotencyKey: string }+ refreshRuns: () => { value: true }+ runAgain: (run: WizardRunApi) => { run: WizardRunApi }+ selectProgram: (program: WizardProgramApi) => { program: WizardProgramApi }+ setLibraryEnvironment: (environment: RunEnvironmentEnumApi) => { environment: RunEnvironmentEnumApi }+ setLibrarySearch: (search: string) => { search: string }+ setRepository: (repository: string) => { repository: string }+ selectRun: (run: WizardRunApi | null) => { run: WizardRunApi | null }+}++export interface wizardLibraryLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ connectGitHubUrl: () => string+ filteredPrograms: (registry: WizardProgramApi[], librarySearch: string) => WizardProgramApi[]+ githubIntegration: (githubIntegrations: IntegrationType[]) => IntegrationType | null+ registryInitialLoading: (registryLoading: boolean, registry: WizardProgramApi[]) => boolean+ requiredPrograms: (selectedProgram: WizardProgramApi | null, registry: WizardProgramApi[]) => WizardProgramApi[]+ selectedProgramCommand: (selectedProgram: WizardProgramApi | null) => string+ }+}++export type wizardLibraryLogicType = MakeLogicType<+ wizardLibraryLogicValues,+ wizardLibraryLogicActions,+ Record<string, never>,+ wizardLibraryLogicMeta+>++export const wizardLibraryLogic = kea<wizardLibraryLogicType>([+ path(['products', 'wizard', 'wizardLibraryLogic']),+ connect(() => ({+ values: [+ projectLogic,+ ['currentProjectId'],+ integrationsLogic,+ ['githubIntegrations', 'integrationsLoading'],+ preflightLogic,+ ['preflight'],+ ],+ actions: [+ integrationsLogic,+ ['loadIntegrations'],+ wizardRunDetailsLogic,+ ['selectRun'],+ wizardRunsLogic,+ ['refreshRuns'],+ ],+ })),+ actions({+ openLibrary: (idempotencyKey = uuid()) => ({ idempotencyKey }),+ closeLibrary: true,+ setLibrarySearch: (search: string) => ({ search }),+ selectProgram: (program: WizardProgramApi) => ({ program }),+ invalidateProgramSelection: true,+ setLibraryEnvironment: (environment: RunEnvironmentEnumApi) => ({ environment }),+ setRepository: (repository: string) => ({ repository }),+ copyCommand: true,+ markCommandCopied: true,+ runAgain: (run: WizardRunApi) => ({ run }),+ createRun: true,+ }),+ reducers({+ isLibraryOpen: [false, { openLibrary: () => true, closeLibrary: () => false }],+ createRunIdempotencyKey: [+ null as string | null,+ {+ openLibrary: (_, { idempotencyKey }) => idempotencyKey,+ closeLibrary: () => null,+ },+ ],+ librarySearch: ['', { setLibrarySearch: (_, { search }) => search, openLibrary: () => '' }],+ selectedProgram: [+ null as WizardProgramApi | null,+ {+ selectProgram: (_, { program }) => program,+ invalidateProgramSelection: () => null,+ },+ ],+ programSelectionInvalidated: [+ false,+ {+ selectProgram: () => false,+ invalidateProgramSelection: () => true,+ closeLibrary: () => false,+ },+ ],+ libraryEnvironment: [+ 'cloud' as RunEnvironmentEnumApi,+ { setLibraryEnvironment: (_, { environment }) => environment },+ ],+ repository: ['', { setRepository: (_, { repository }) => repository, closeLibrary: () => '' }],+ commandCopied: [+ false,+ {+ markCommandCopied: () => true,+ selectProgram: () => false,+ closeLibrary: () => false,+ },+ ],+ registryFailed: [false, { loadRegistry: () => false, loadRegistryFailure: () => true }],+ createRunError: [+ null as string | null,+ {+ createRun: () => null,+ setRepository: () => null,+ closeLibrary: () => null,+ createRunRequestFailure: (_, { errorObject }) =>+ requestError(errorObject, "Couldn't start the cloud run. Check the repository and try again."),+ },+ ],+ }),+ loaders(({ values }) => ({+ registry: [+ [] as WizardProgramApi[],+ {+ loadRegistry: async () => {+ if (!values.currentProjectId) {+ return []+ }++ const response = await wizardRegistryList(String(values.currentProjectId), {+ limit: 100,+ offset: 0,+ })++ return response.results+ },+ },+ ],+ createRunRequest: [+ null as WizardRunApi | null,+ {+ createRunRequest: async ({ projectId, body }: { projectId: string; body: WizardRunCreateRequestApi }) =>+ wizardRunsCreate(projectId, body),+ },+ ],+ })),+ selectors({+ filteredPrograms: [+ (s) => [s.registry, s.librarySearch],+ (programs: WizardProgramApi[], search: string): WizardProgramApi[] => {+ const availablePrograms = WIZARD_LOCAL_RUNS_VISIBLE+ ? programs+ : programs.filter((program) => program.supported_environments.includes('cloud'))+ const searchText = search.trim().toLowerCase()++ if (!searchText) {+ return availablePrograms+ }++ return availablePrograms.filter((program) =>+ `${program.name} ${program.description} ${program.tags.join(' ')}`+ .toLowerCase()+ .includes(searchText)+ )+ },+ ],+ githubIntegration: [+ (s) => [s.githubIntegrations],+ (githubIntegrations: IntegrationType[]): IntegrationType | null => {+ // Mirror the backend's team-level resolution: skip installations that GitHub has+ // removed or suspended, prefer organization installations, then oldest first.+ const usable = githubIntegrations.filter(+ (integration) => integration.kind === 'github' && integration.installation_status !== 'unavailable'+ )++ return (+ [...usable].sort((a, b) => {+ const aOrg = a.config?.account?.type === 'Organization' ? 0 : 1+ const bOrg = b.config?.account?.type === 'Organization' ? 0 : 1++ return aOrg - bOrg || a.created_at.localeCompare(b.created_at)+ })[0] ?? null+ )+ },+ ],+ connectGitHubUrl: [+ () => [],+ (): string => api.integrations.authorizeUrl({ kind: 'github', next: urls.wizardRuns() }),+ ],+ selectedProgramCommand: [+ (s) => [s.selectedProgram],+ (program: WizardProgramApi | null): string =>+ program ? wizardCommand(program.wizard_version, program.command) : '',+ ],+ requiredPrograms: [+ (s) => [s.selectedProgram, s.registry],+ (program: WizardProgramApi | null, registry: WizardProgramApi[]): WizardProgramApi[] =>+ program+ ? program.required_programs+ .map((requiredId) => registry.find((candidate) => candidate.id === requiredId))+ .filter((candidate): candidate is WizardProgramApi => !!candidate)+ : [],+ ],+ registryInitialLoading: [+ (s) => [s.registryLoading, s.registry],+ (registryLoading: boolean, registry: WizardProgramApi[]): boolean =>+ registryLoading && registry.length === 0,+ ],+ wizardCloudRunAvailable: [+ (s) => [s.preflight],+ (preflight: PreflightStatus | null): boolean => !!preflight?.wizard_cloud_run_available,+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ openLibrary: () => {+ if (!values.preflight?.wizard_cloud_run_available) {+ lemonToast.error('Cloud runs are not available on this instance.')+ actions.closeLibrary()++ return+ }++ actions.loadRegistry()+ actions.loadIntegrations()++ if (!WIZARD_LOCAL_RUNS_VISIBLE) {+ actions.setLibraryEnvironment('cloud')+ }++ if (!values.selectedProgram && values.filteredPrograms.length > 0) {+ actions.selectProgram(values.filteredPrograms[0])+ }+ },+ selectProgram: ({ program }) => {+ const environment =+ WIZARD_LOCAL_RUNS_VISIBLE && !program.supported_environments.includes('cloud') ? 'local' : 'cloud'++ actions.setLibraryEnvironment(environment)+ },+ copyCommand: () => {+ if (values.selectedProgramCommand) {+ void copyToClipboard(values.selectedProgramCommand, 'Wizard command').then((copied) => {+ if (copied) {+ actions.markCommandCopied()+ }+ })+ }+ },+ runAgain: ({ run }) => {+ if (!WIZARD_LOCAL_RUNS_VISIBLE && run.environment === 'local') {+ return+ }++ // Resolve the program only after the registry (re)loads, so a stale or absent+ // selection can never start an unrelated program.+ cache.pendingRunAgainProgramId = run.program.id+ actions.invalidateProgramSelection()++ actions.setLibraryEnvironment(run.environment)++ if (run.workspace.type === 'git_repository') {+ actions.setRepository(run.workspace.repository)+ }++ actions.openLibrary()+ },+ createRun: () => {+ const projectId = values.currentProjectId+ const program = values.selectedProgram++ if (+ !projectId ||+ !program ||+ values.libraryEnvironment !== 'cloud' ||+ !values.createRunIdempotencyKey ||+ !values.preflight?.wizard_cloud_run_available+ ) {+ return+ }++ const workspace: WizardRunCreateRequestApi['workspace'] = {+ type: 'git_repository',+ repository: values.repository,+ }++ actions.createRunRequest({+ projectId: String(projectId),+ body: {+ program_id: program.id,+ environment: values.libraryEnvironment,+ workspace,+ idempotency_key: values.createRunIdempotencyKey,+ // Run the version shown in the Library, not the backend default.+ wizard_version: program.wizard_version,+ },+ })+ },+ createRunRequestSuccess: ({ createRunRequest }) => {+ lemonToast.success('Cloud run started.')++ // Follow the new run in the drawer so the old failed run cannot reappear.+ if (createRunRequest) {+ actions.selectRun(createRunRequest)+ }++ actions.closeLibrary()+ actions.refreshRuns()+ },+ loadRegistrySuccess: ({ registry }) => {+ const availablePrograms = WIZARD_LOCAL_RUNS_VISIBLE+ ? registry+ : registry.filter((program) => program.supported_environments.includes('cloud'))++ const pendingRunAgainProgramId: string | null = cache.pendingRunAgainProgramId ?? null++ if (pendingRunAgainProgramId) {+ cache.pendingRunAgainProgramId = null+ const match = availablePrograms.find((program) => program.id === pendingRunAgainProgramId)++ if (match) {+ actions.selectProgram(match)+ } else {+ actions.invalidateProgramSelection()+ }++ return+ }++ if (+ values.selectedProgram &&+ !availablePrograms.some((program) => program.id === values.selectedProgram?.id)+ ) {+ actions.invalidateProgramSelection()+ } else if (!values.selectedProgram && availablePrograms.length > 0) {+ actions.selectProgram(availablePrograms[0])+ }+ },+ closeLibrary: () => {+ cache.pendingRunAgainProgramId = null+ },+ })),+ events(({ actions }) => ({+ afterMount: () => {+ actions.loadRegistry()+ actions.loadIntegrations()+ },+ })),+])diff --git a/products/wizard/frontend/wizardRunDetailsLogic.test.ts b/products/wizard/frontend/wizardRunDetailsLogic.test.tsnew file mode 100644index 000000000000..27144bee3d1d--- /dev/null+++ b/products/wizard/frontend/wizardRunDetailsLogic.test.ts@@ -0,0 +1,227 @@+import { expectLogic } from 'kea-test-utils'++import { LemonDialog } from '@posthog/lemon-ui'++import { projectLogic } from 'scenes/projectLogic'++import { initKeaTests } from '~/test/init'++import { wizardRunsRetrieve } from './generated/api'+import type { WizardRunApi, WizardRunGitDiffArtifactApi } from './generated/api.schemas'+import { loadWizardRunArtifactContent, loadWizardRunArtifacts } from './wizardApi'+import { wizardRunDetailsLogic } from './wizardRunDetailsLogic'++jest.mock('./generated/api', () => ({+ wizardRunsList: jest.fn().mockResolvedValue({ count: 0, next: null, previous: null, results: [] }),+ wizardRunsPartialUpdate: jest.fn(),+ wizardRunsRetrieve: jest.fn(),+}))++jest.mock('./wizardApi', () => ({+ loadWizardRunArtifactContent: jest.fn(),+ loadWizardRunArtifacts: jest.fn(),+}))++const mockLoadWizardRunArtifactContent = loadWizardRunArtifactContent as jest.Mock+const mockLoadWizardRunArtifacts = loadWizardRunArtifacts as jest.Mock+const mockWizardRunsRetrieve = wizardRunsRetrieve as jest.Mock++const gitDiffArtifact: WizardRunGitDiffArtifactApi = {+ id: 'artifact-1',+ team_id: 1,+ run_id: 'run-1',+ artifact_type: 'git_diff',+ size_bytes: 512,+ content_hash: 'diff-hash',+ additions: 2,+ removals: 1,+ created_at: '2026-08-26T10:02:00Z',+}++function makeRun(): WizardRunApi {+ return {+ id: 'run-1',+ team_id: 1,+ created_by_id: 1,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'posthog/posthog' },+ program: {+ id: 'posthog-integration',+ name: 'PostHog integration',+ description: 'Set up PostHog',+ wizard_version: '2.6.0',+ command: [],+ tags: [],+ required_programs: [],+ supported_environments: ['local', 'cloud'],+ },+ status: 'running',+ error_code: null,+ error_message: null,+ stage: 'executing_wizard',+ created_at: '2026-08-26T10:00:00Z',+ updated_at: '2026-08-26T10:01:00Z',+ started_at: '2026-08-26T10:00:30Z',+ finished_at: null,+ deadline_at: '2026-08-26T11:00:00Z',+ }+}++describe('wizardRunDetailsLogic', () => {+ let logic: ReturnType<typeof wizardRunDetailsLogic.build>++ beforeEach(async () => {+ initKeaTests()+ mockWizardRunsRetrieve.mockReset()+ mockLoadWizardRunArtifactContent.mockReset()+ mockLoadWizardRunArtifacts.mockReset()+ mockWizardRunsRetrieve.mockResolvedValue(makeRun())+ mockLoadWizardRunArtifactContent.mockResolvedValue('diff content')+ mockLoadWizardRunArtifacts.mockResolvedValue([])+ await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })+ logic = wizardRunDetailsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ it('loads run details and artifacts through separate endpoints', async () => {+ logic.actions.selectRun(makeRun())++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ selectedRun: expect.objectContaining({ id: 'run-1' }),+ selectedRunArtifacts: [],+ selectedRunArtifactsInitialLoading: false,+ })++ expect(mockWizardRunsRetrieve).toHaveBeenCalledWith(expect.any(String), 'run-1')+ expect(mockLoadWizardRunArtifacts).toHaveBeenCalledWith(expect.any(String), 'run-1')+ expect(mockLoadWizardRunArtifactContent).not.toHaveBeenCalled()+ })++ it('loads git diff content only after the artifact is opened', async () => {+ mockLoadWizardRunArtifacts.mockResolvedValue([gitDiffArtifact])+ logic.actions.selectRun(makeRun())+ await expectLogic(logic).toFinishAllListeners()++ expect(mockLoadWizardRunArtifactContent).not.toHaveBeenCalled()++ logic.actions.openRunDiff(gitDiffArtifact)++ await expectLogic(logic).toFinishAllListeners().toMatchValues({+ selectedRunDiffArtifactId: 'artifact-1',+ selectedRunDiffContent: 'diff content',+ runDiffLoading: false,+ })+ expect(mockLoadWizardRunArtifactContent).toHaveBeenCalledWith(expect.any(String), 'run-1', 'artifact-1')+ })++ it('reuses downloaded diff content when the same artifact is reopened', async () => {+ mockLoadWizardRunArtifacts.mockResolvedValue([gitDiffArtifact])+ logic.actions.selectRun(makeRun())+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.openRunDiff(gitDiffArtifact)+ await expectLogic(logic).toFinishAllListeners()+ expect(mockLoadWizardRunArtifactContent).toHaveBeenCalledTimes(1)++ logic.actions.closeRunDiff()+ logic.actions.openRunDiff(gitDiffArtifact)++ await expectLogic(logic).toFinishAllListeners().toMatchValues({+ selectedRunDiffContent: 'diff content',+ })+ expect(mockLoadWizardRunArtifactContent).toHaveBeenCalledTimes(1)+ })++ it('fetches artifacts once more when a poll reveals the run finished', async () => {+ logic.actions.selectRun(makeRun())+ await expectLogic(logic).toFinishAllListeners()++ mockWizardRunsRetrieve.mockResolvedValue({ ...makeRun(), status: 'completed', stage: null })++ logic.actions.loadRunDetails({ runId: 'run-1' })+ await expectLogic(logic).toFinishAllListeners()++ expect(mockLoadWizardRunArtifacts).toHaveBeenCalledTimes(2)++ await expectLogic(logic).toFinishAllListeners()+ logic.actions.loadRunDetails({ runId: 'run-1' })+ await expectLogic(logic).toFinishAllListeners()+ expect(mockLoadWizardRunArtifacts).toHaveBeenCalledTimes(2)+ })++ it('does not download a diff that is too large to render', async () => {+ const largeArtifact = { ...gitDiffArtifact, size_bytes: 2 * 1024 * 1024 + 1 }++ logic.actions.openRunDiff(largeArtifact)+ await expectLogic(logic).toFinishAllListeners()++ expect(mockLoadWizardRunArtifactContent).not.toHaveBeenCalled()+ })++ it('asks for confirmation before canceling a run', async () => {+ const openDialog = jest.spyOn(LemonDialog, 'open').mockReturnValue(undefined)++ logic.actions.cancelRun(makeRun())+ await expectLogic(logic).toFinishAllListeners()++ expect(openDialog).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Cancel Wizard run?',+ primaryButton: expect.objectContaining({ children: 'Cancel run', status: 'danger' }),+ })+ )+ })++ it('prefers a newer run summary over stale cached details', async () => {+ logic.actions.selectRun(makeRun())+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ selectedRun: expect.objectContaining({ status: 'running' }) })++ // Reopen after the run finished while the drawer was closed: the table summary is newer+ // than the details still cached from the previous session, and the refresh has not landed.+ mockWizardRunsRetrieve.mockReturnValue(new Promise(() => {}))+ logic.actions.selectRun({+ ...makeRun(),+ status: 'completed',+ updated_at: '2026-08-26T10:05:00Z',+ finished_at: '2026-08-26T10:05:00Z',+ })++ await expectLogic(logic).toMatchValues({+ selectedRun: expect.objectContaining({ status: 'completed' }),+ })+ })++ it('records an artifact load failure and clears it on a successful retry', async () => {+ mockLoadWizardRunArtifacts.mockRejectedValueOnce(new Error('network down'))+ logic.actions.selectRun(makeRun())+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ runArtifactsError: expect.any(String) })++ mockLoadWizardRunArtifacts.mockResolvedValue([])+ logic.actions.refreshSelectedRun()+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ runArtifactsError: null })+ })++ it('keeps resolved artifact state visible during a refresh', async () => {+ logic.actions.selectRun(makeRun())+ await expectLogic(logic).toFinishAllListeners()++ mockLoadWizardRunArtifacts.mockReturnValue(new Promise(() => {}))+ logic.actions.refreshSelectedRun()++ await expectLogic(logic).toMatchValues({+ runArtifactsLoading: true,+ selectedRunArtifactsInitialLoading: false,+ })+ })+})diff --git a/products/wizard/frontend/wizardRunDetailsLogic.ts b/products/wizard/frontend/wizardRunDetailsLogic.tsnew file mode 100644index 000000000000..f6701edd61eb--- /dev/null+++ b/products/wizard/frontend/wizardRunDetailsLogic.ts@@ -0,0 +1,402 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import type { BreakPointFunction } from 'kea'+import { loaders } from 'kea-loaders'++import { LemonDialog, lemonToast } from '@posthog/lemon-ui'++import { ApiError } from 'lib/api'+import { dayjs } from 'lib/dayjs'+import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { projectLogic } from 'scenes/projectLogic'++import { wizardRunsPartialUpdate, wizardRunsRetrieve } from './generated/api'+import type { WizardRunApi, WizardRunArtifactApi, WizardRunGitDiffArtifactApi } from './generated/api.schemas'+import { loadWizardRunArtifactContent, loadWizardRunArtifacts } from './wizardApi'+import { wizardRunDiffCanRender, wizardRunIsActive } from './wizardRunDisplay'+import { wizardRunsLogic } from './wizardRunsLogic'++const RUN_DETAIL_POLL_INTERVAL_MS = 10_000++type WizardRunDiffContent = {+ artifactId: string+ content: string+}++function requestError(error: unknown, fallback: string): string {+ return error instanceof ApiError && error.detail ? error.detail : fallback+}++// Rethrows the original error only when the request is still current; a superseded+// rejection must not dispatch a failure action against newer data.+async function rejectUnlessCurrent(breakpoint: BreakPointFunction, error: unknown): Promise<never> {+ await breakpoint()+ throw error+}++export interface wizardRunDetailsLogicValues {+ currentProjectId: number | null+ artifactRunIdsLoaded: string[]+ cancelRunRequest: WizardRunApi | null+ cancelRunRequestLoading: boolean+ runArtifacts: WizardRunArtifactApi[]+ runArtifactsError: string | null+ runArtifactsLoading: boolean+ runDetails: WizardRunApi | null+ runDetailsError: string | null+ runDetailsLoading: boolean+ runDiff: WizardRunDiffContent | null+ runDiffError: string | null+ runDiffLoading: boolean+ selectedRun: WizardRunApi | null+ selectedRunArtifacts: WizardRunArtifactApi[]+ selectedRunArtifactsInitialLoading: boolean+ selectedRunDiffArtifactId: string | null+ selectedRunDiffContent: string | null+ selectedRunId: string | null+ selectedRunSummary: WizardRunApi | null+}++export interface wizardRunDetailsLogicActions {+ cancelRun: (run: WizardRunApi) => { run: WizardRunApi }+ cancelRunRequest: ({ runId }: { runId: string }) => { runId: string }+ cancelRunRequestFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ cancelRunRequestSuccess: (+ cancelRunRequest: WizardRunApi | null,+ payload?: { runId: string }+ ) => {+ cancelRunRequest: WizardRunApi | null+ payload?: { runId: string }+ }+ closeRunDiff: () => { value: true }+ copyRunId: (runId: string) => { runId: string }+ loadRunArtifacts: ({ runId }: { runId: string }) => { runId: string }+ loadRunArtifactsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ loadRunArtifactsSuccess: (+ runArtifacts: WizardRunArtifactApi[],+ payload?: { runId: string }+ ) => {+ runArtifacts: WizardRunArtifactApi[]+ payload?: { runId: string }+ }+ loadRunDetails: ({ runId }: { runId: string }) => { runId: string }+ loadRunDetailsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ loadRunDetailsSuccess: (+ runDetails: WizardRunApi | null,+ payload?: { runId: string }+ ) => {+ runDetails: WizardRunApi | null+ payload?: { runId: string }+ }+ loadRunDiff: ({ artifactId, runId }: { artifactId: string; runId: string }) => {+ artifactId: string+ runId: string+ }+ loadRunDiffFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ loadRunDiffSuccess: (+ runDiff: WizardRunDiffContent | null,+ payload?: { artifactId: string; runId: string }+ ) => {+ runDiff: WizardRunDiffContent | null+ payload?: { artifactId: string; runId: string }+ }+ openRunDiff: (artifact: WizardRunGitDiffArtifactApi) => { artifact: WizardRunGitDiffArtifactApi }+ refreshRuns: () => { value: true }+ refreshSelectedRun: () => { value: true }+ selectRun: (run: WizardRunApi | null) => { run: WizardRunApi | null }+}++export interface wizardRunDetailsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ selectedRun: (runDetails: WizardRunApi | null, selectedRunSummary: WizardRunApi | null) => WizardRunApi | null+ selectedRunArtifacts: (+ selectedRunId: string | null,+ runArtifacts: WizardRunArtifactApi[]+ ) => WizardRunArtifactApi[]+ selectedRunArtifactsInitialLoading: (+ selectedRunId: string | null,+ runArtifactsLoading: boolean,+ artifactRunIdsLoaded: string[]+ ) => boolean+ selectedRunDiffContent: (+ selectedRunDiffArtifactId: string | null,+ runDiff: WizardRunDiffContent | null+ ) => string | null+ selectedRunId: (selectedRunSummary: WizardRunApi | null) => string | null+ }+}++export type wizardRunDetailsLogicType = MakeLogicType<+ wizardRunDetailsLogicValues,+ wizardRunDetailsLogicActions,+ Record<string, never>,+ wizardRunDetailsLogicMeta+>++export const wizardRunDetailsLogic = kea<wizardRunDetailsLogicType>([+ path(['products', 'wizard', 'wizardRunDetailsLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ actions: [wizardRunsLogic, ['refreshRuns']],+ })),+ actions({+ selectRun: (run: WizardRunApi | null) => ({ run }),+ openRunDiff: (artifact: WizardRunGitDiffArtifactApi) => ({ artifact }),+ closeRunDiff: true,+ refreshSelectedRun: true,+ cancelRun: (run: WizardRunApi) => ({ run }),+ copyRunId: (runId: string) => ({ runId }),+ }),+ reducers({+ selectedRunSummary: [+ null as WizardRunApi | null,+ {+ selectRun: (_, { run }) => run,+ cancelRunRequestSuccess: (state, { cancelRunRequest }) =>+ state?.id === cancelRunRequest?.id ? cancelRunRequest : state,+ },+ ],+ artifactRunIdsLoaded: [+ [] as string[],+ {+ loadRunArtifactsSuccess: (state, { payload }) => {+ const runId = payload?.runId++ return runId && !state.includes(runId) ? [...state, runId] : state+ },+ },+ ],+ runArtifactsError: [+ null as string | null,+ {+ loadRunArtifacts: () => null,+ loadRunArtifactsSuccess: () => null,+ loadRunArtifactsFailure: (_, { errorObject }) => requestError(errorObject, "Couldn't load artifacts."),+ },+ ],+ runDetailsError: [+ null as string | null,+ {+ loadRunDetails: () => null,+ loadRunDetailsSuccess: () => null,+ loadRunDetailsFailure: (_, { errorObject }) =>+ requestError(errorObject, "Couldn't load the latest run state."),+ },+ ],+ selectedRunDiffArtifactId: [+ null as string | null,+ {+ openRunDiff: (_, { artifact }) => artifact.id,+ closeRunDiff: () => null,+ selectRun: () => null,+ },+ ],+ runDiffError: [+ null as string | null,+ {+ openRunDiff: () => null,+ closeRunDiff: () => null,+ loadRunDiffSuccess: () => null,+ loadRunDiffFailure: (_, { errorObject }) =>+ requestError(errorObject, "Couldn't load this diff. Try again."),+ },+ ],+ }),+ loaders(({ values }) => ({+ runDetails: [+ null as WizardRunApi | null,+ {+ loadRunDetails: async ({ runId }: { runId: string }, breakpoint) => {+ if (!values.currentProjectId) {+ return null+ }++ try {+ const run = await wizardRunsRetrieve(String(values.currentProjectId), runId)++ await breakpoint()++ return run+ } catch (error) {+ return await rejectUnlessCurrent(breakpoint, error)+ }+ },+ },+ ],+ runArtifacts: [+ [] as WizardRunArtifactApi[],+ {+ loadRunArtifacts: async ({ runId }: { runId: string }, breakpoint) => {+ if (!values.currentProjectId) {+ return []+ }++ try {+ const artifacts = await loadWizardRunArtifacts(String(values.currentProjectId), runId)++ await breakpoint()++ return [...values.runArtifacts.filter((artifact) => artifact.run_id !== runId), ...artifacts]+ } catch (error) {+ return await rejectUnlessCurrent(breakpoint, error)+ }+ },+ },+ ],+ runDiff: [+ null as WizardRunDiffContent | null,+ {+ loadRunDiff: async ({ artifactId, runId }: { artifactId: string; runId: string }, breakpoint) => {+ if (!values.currentProjectId) {+ return null+ }++ try {+ const content = await loadWizardRunArtifactContent(+ String(values.currentProjectId),+ runId,+ artifactId+ )++ await breakpoint()++ return { artifactId, content }+ } catch (error) {+ return await rejectUnlessCurrent(breakpoint, error)+ }+ },+ },+ ],+ cancelRunRequest: [+ null as WizardRunApi | null,+ {+ cancelRunRequest: async ({ runId }: { runId: string }) => {+ if (!values.currentProjectId) {+ return null+ }++ return wizardRunsPartialUpdate(String(values.currentProjectId), runId, { status: 'cancelled' })+ },+ },+ ],+ })),+ selectors({+ selectedRunId: [+ (s) => [s.selectedRunSummary],+ (selectedRunSummary: WizardRunApi | null): string | null => selectedRunSummary?.id ?? null,+ ],+ selectedRun: [+ (s) => [s.runDetails, s.selectedRunSummary],+ (runDetails: WizardRunApi | null, selectedRunSummary: WizardRunApi | null): WizardRunApi | null => {+ if (!runDetails || runDetails.id !== selectedRunSummary?.id) {+ return selectedRunSummary+ }++ // Details cached from an earlier drawer session can be older than a fresh table+ // summary or a cancellation response, so defer to whichever changed more recently.+ const detailsTime = runDetails.updated_at ? dayjs(runDetails.updated_at).valueOf() : 0+ const summaryTime = selectedRunSummary.updated_at ? dayjs(selectedRunSummary.updated_at).valueOf() : 0++ return summaryTime > detailsTime ? selectedRunSummary : runDetails+ },+ ],+ selectedRunArtifacts: [+ (s) => [s.selectedRunId, s.runArtifacts],+ (selectedRunId: string | null, runArtifacts: WizardRunArtifactApi[]): WizardRunArtifactApi[] =>+ selectedRunId ? runArtifacts.filter((artifact) => artifact.run_id === selectedRunId) : [],+ ],+ selectedRunArtifactsInitialLoading: [+ (s) => [s.selectedRunId, s.runArtifactsLoading, s.artifactRunIdsLoaded],+ (selectedRunId: string | null, runArtifactsLoading: boolean, artifactRunIdsLoaded: string[]): boolean =>+ !!selectedRunId && runArtifactsLoading && !artifactRunIdsLoaded.includes(selectedRunId),+ ],+ selectedRunDiffContent: [+ (s) => [s.selectedRunDiffArtifactId, s.runDiff],+ (selectedRunDiffArtifactId: string | null, runDiff: WizardRunDiffContent | null): string | null =>+ selectedRunDiffArtifactId && runDiff?.artifactId === selectedRunDiffArtifactId ? runDiff.content : null,+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ selectRun: ({ run }) => {+ cache.disposables.dispose('wizardRunDetailPolling')++ if (!run) {+ return+ }++ actions.loadRunDetails({ runId: run.id })+ actions.loadRunArtifacts({ runId: run.id })++ if (wizardRunIsActive(run)) {+ cache.disposables.add(() => {+ const timerId = window.setInterval(() => {+ actions.loadRunDetails({ runId: run.id })+ actions.loadRunArtifacts({ runId: run.id })+ }, RUN_DETAIL_POLL_INTERVAL_MS)++ return () => window.clearInterval(timerId)+ }, 'wizardRunDetailPolling')+ }+ },+ openRunDiff: ({ artifact }) => {+ if (!wizardRunDiffCanRender(artifact.size_bytes)) {+ return+ }++ // Artifacts are immutable, so reuse the cached content instead of re-downloading it.+ if (values.runDiff?.artifactId !== artifact.id) {+ actions.loadRunDiff({ runId: artifact.run_id, artifactId: artifact.id })+ }+ },+ refreshSelectedRun: () => {+ if (values.selectedRunId) {+ actions.loadRunDetails({ runId: values.selectedRunId })+ actions.loadRunArtifacts({ runId: values.selectedRunId })+ }+ },+ loadRunDetailsSuccess: ({ runDetails }) => {+ if (!runDetails || runDetails.id !== values.selectedRunId) {+ return+ }++ if (wizardRunIsActive(runDetails)) {+ return+ }++ cache.disposables.dispose('wizardRunDetailPolling')++ // The artifacts request of the same poll cycle can read before the run finished,+ // so fetch artifacts once more now that the run is terminal.+ if (cache.terminalArtifactFetchRunId !== runDetails.id) {+ cache.terminalArtifactFetchRunId = runDetails.id+ actions.loadRunArtifacts({ runId: runDetails.id })+ }+ },+ cancelRun: ({ run }) => {+ LemonDialog.open({+ title: 'Cancel Wizard run?',+ description: 'The agent stops this run. You cannot resume it.',+ primaryButton: {+ children: 'Cancel run',+ status: 'danger',+ onClick: () => actions.cancelRunRequest({ runId: run.id }),+ },+ secondaryButton: { children: 'Keep running' },+ })+ },+ cancelRunRequestSuccess: ({ cancelRunRequest }) => {+ lemonToast.success('Wizard run canceled.')++ actions.refreshRuns()+ if (cancelRunRequest?.id === values.selectedRunId) {+ actions.loadRunDetails({ runId: cancelRunRequest.id })+ actions.loadRunArtifacts({ runId: cancelRunRequest.id })+ }+ },+ cancelRunRequestFailure: ({ errorObject }) => {+ lemonToast.error(requestError(errorObject, "Couldn't cancel the Wizard run. Try again."))+ },+ copyRunId: ({ runId }) => {+ void copyToClipboard(runId, 'Wizard run ID')+ },+ })),+])diff --git a/products/wizard/frontend/wizardRunDisplay.test.ts b/products/wizard/frontend/wizardRunDisplay.test.tsnew file mode 100644index 000000000000..75683aad09f4--- /dev/null+++ b/products/wizard/frontend/wizardRunDisplay.test.ts@@ -0,0 +1,80 @@+import type { WizardRunApi } from './generated/api.schemas'+import { wizardGithubRepositoryUrl, wizardRunCanCancel, wizardRunFailureStage } from './wizardRunDisplay'++function makeRun(overrides: Partial<WizardRunApi>): WizardRunApi {+ return {+ id: 'run-1',+ team_id: 1,+ created_by_id: 1,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'posthog/posthog' },+ program: {+ id: 'posthog-integration',+ name: 'PostHog integration',+ description: 'Set up PostHog',+ wizard_version: '2.67.0',+ command: [],+ tags: [],+ required_programs: [],+ supported_environments: ['local', 'cloud'],+ },+ status: 'failed',+ error_code: null,+ error_message: null,+ stage: null,+ created_at: '2026-08-28T10:00:00Z',+ started_at: null,+ finished_at: null,+ workspace_type: 'git_repository',+ program_id: 'posthog-integration',+ ...overrides,+ } as WizardRunApi+}++describe('wizardRunFailureStage', () => {+ test.each([+ ['dispatch_failed', 'dispatching'],+ ['provisioning_failed', 'provisioning'],+ ['repository_access_failed', 'preparing_workspace'],+ ['workspace_preparation_failed', 'preparing_workspace'],+ ['artifact_creation_failed', 'creating_artifacts'],+ ['PHW_CLI_BAD_ARGS', 'executing_wizard'],+ [null, 'executing_wizard'],+ ])('derives the failure stage from error code %s', (errorCode, expectedStage) => {+ const run = makeRun({ status: 'failed', error_code: errorCode, stage: null })++ expect(wizardRunFailureStage(run)).toBe(expectedStage)+ })++ test('has no stage for a timeout, which can hit any step', () => {+ const run = makeRun({ status: 'failed', error_code: 'timeout', stage: null })++ expect(wizardRunFailureStage(run)).toBeNull()+ })++ test('prefers the current stage when the run reports one', () => {+ const run = makeRun({ status: 'failed', error_code: 'PHW_CLI_BAD_ARGS', stage: 'creating_artifacts' })++ expect(wizardRunFailureStage(run)).toBe('creating_artifacts')+ })+})++describe('wizardGithubRepositoryUrl', () => {+ test('builds the GitHub URL for a repository', () => {+ expect(wizardGithubRepositoryUrl('posthog/posthog')).toBe('https://github.com/posthog/posthog')+ })+})++describe('wizardRunCanCancel', () => {+ test.each([+ ['creator sees cancel on an active run', 'running', 7, 7, true],+ ['teammate cannot cancel someone else’s run', 'running', 7, 9, false],+ ['no cancel once the run is terminal', 'completed', 7, 7, false],+ ['runs without a creator hide cancel from everyone', 'running', null, 7, false],+ ['unknown current user hides cancel', 'running', 7, null, false],+ ])('%s', (_label, status, createdById, currentUserId, expected) => {+ const run = makeRun({ status: status as WizardRunApi['status'], created_by_id: createdById })++ expect(wizardRunCanCancel(run, currentUserId)).toBe(expected)+ })+})diff --git a/products/wizard/frontend/wizardRunDisplay.ts b/products/wizard/frontend/wizardRunDisplay.tsnew file mode 100644index 000000000000..8a16bb6674b3--- /dev/null+++ b/products/wizard/frontend/wizardRunDisplay.ts@@ -0,0 +1,108 @@+import { WizardRunApi, WizardRunStageEnumApi } from './generated/api.schemas'+import { wizardRunErrorDetails } from './runs/wizardRunErrorCatalog'++export const MAX_RENDERED_WIZARD_DIFF_BYTES = 2 * 1024 * 1024+// Byte size does not bound DOM nodes: many short lines can pass the byte cap and still stall the page.+export const MAX_RENDERED_WIZARD_DIFF_LINES = 20_000+export const WIZARD_LOCAL_RUNS_VISIBLE = false++export function wizardRunDiffCanRender(sizeBytes: number): boolean {+ return sizeBytes <= MAX_RENDERED_WIZARD_DIFF_BYTES+}++export function wizardWorkspaceLabel(run: WizardRunApi): string {+ return run.workspace.type === 'git_repository' ? run.workspace.repository : run.workspace.project_name+}++export function wizardCommand(packageVersion: string, command: readonly string[]): string {+ return ['npx', `@posthog/wizard@${packageVersion}`, ...command].join(' ')+}++export function wizardRunIsActive(run: WizardRunApi): boolean {+ return run.status === 'created' || run.status === 'running'+}++export function wizardRunTerminalLabel(status: WizardRunApi['status']): string {+ switch (status) {+ case 'completed':+ return 'Completed'+ case 'failed':+ return 'Failed'+ case 'cancelled':+ return 'Canceled'+ default:+ return 'Finished'+ }+}++export function wizardRunCanCancel(run: WizardRunApi, currentUserId: number | null): boolean {+ // The API only lets the run's creator cancel it, so hide the control for everyone else.+ // A run with no creator has no owner who can cancel it, so hide it there too.+ return wizardRunIsActive(run) && run.created_by_id !== null && run.created_by_id === currentUserId+}++const FAILURE_STAGE_BY_ERROR_CODE: Record<string, WizardRunStageEnumApi> = {+ dispatch_failed: WizardRunStageEnumApi.Dispatching,+ provisioning_failed: WizardRunStageEnumApi.Provisioning,+ repository_access_failed: WizardRunStageEnumApi.PreparingWorkspace,+ workspace_preparation_failed: WizardRunStageEnumApi.PreparingWorkspace,+ timeout: WizardRunStageEnumApi.ExecutingWizard,+ artifact_creation_failed: WizardRunStageEnumApi.CreatingArtifacts,+}++export function wizardRunFailureStage(run: WizardRunApi): WizardRunStageEnumApi | null {+ if (run.stage) {+ return run.stage+ }++ // Timeouts are recorded with a generic code regardless of which step ran out of time,+ // so the failed stage is unknowable and the failure can only be shown at run level.+ if (run.error_code === 'timeout') {+ return null+ }++ return FAILURE_STAGE_BY_ERROR_CODE[run.error_code ?? ''] ?? WizardRunStageEnumApi.ExecutingWizard+}++export function wizardGithubRepositoryUrl(repository: string): string {+ return `https://github.com/${repository}`+}++export function formatArtifactSize(sizeBytes: number): string {+ if (sizeBytes < 1024) {+ return `${sizeBytes} B`+ }+ if (sizeBytes < 1024 * 1024) {+ return `${(sizeBytes / 1024).toFixed(1)} KB`+ }+ return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`+}++export function wizardRunCurrentState(run: WizardRunApi): string {+ if (run.status === 'completed') {+ return 'Completed successfully'+ }+ if (run.status === 'failed') {+ return wizardRunErrorDetails(run.error_code, run.error_message).title+ }+ if (run.status === 'cancelled') {+ return 'Run canceled'+ }++ switch (run.stage) {+ case WizardRunStageEnumApi.Dispatching:+ return 'Starting the Wizard Worker'+ case WizardRunStageEnumApi.Provisioning:+ return 'Provisioning the Wizard Worker'+ case WizardRunStageEnumApi.PreparingWorkspace:+ return 'Preparing the repository'+ case WizardRunStageEnumApi.ExecutingWizard:+ return run.program.name.endsWith('audit')+ ? `Running the ${run.program.name}`+ : `Running ${run.program.name}`+ case WizardRunStageEnumApi.CreatingArtifacts:+ return 'Creating run artifacts'+ default:+ return run.status === 'running' ? 'Running the Wizard' : 'Starting the Wizard run'+ }+}diff --git a/products/wizard/frontend/wizardRunsLogic.test.ts b/products/wizard/frontend/wizardRunsLogic.test.tsnew file mode 100644index 000000000000..06a3311d4e1f--- /dev/null+++ b/products/wizard/frontend/wizardRunsLogic.test.ts@@ -0,0 +1,184 @@+import { expectLogic } from 'kea-test-utils'++import { projectLogic } from 'scenes/projectLogic'++import { initKeaTests } from '~/test/init'++import { wizardRunsList } from './generated/api'+import type { WizardRunApi } from './generated/api.schemas'+import { wizardRunsLogic } from './wizardRunsLogic'++jest.mock('./generated/api', () => ({ wizardRunsList: jest.fn() }))++const mockWizardRunsList = wizardRunsList as jest.Mock++type WizardRunsResponse = Awaited<ReturnType<typeof wizardRunsList>>++function makeRun(id = 'run-1'): WizardRunApi {+ return {+ id,+ team_id: 1,+ created_by_id: 1,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'posthog/posthog' },+ program: {+ id: 'posthog-integration',+ name: 'PostHog integration',+ description: 'Set up PostHog',+ wizard_version: '2.6.0',+ command: [],+ tags: [],+ required_programs: [],+ supported_environments: ['local', 'cloud'],+ },+ status: 'running',+ error_code: null,+ error_message: null,+ stage: 'executing_wizard',+ created_at: '2026-08-26T10:00:00Z',+ updated_at: '2026-08-26T10:01:00Z',+ started_at: '2026-08-26T10:00:30Z',+ finished_at: null,+ deadline_at: '2026-08-26T11:00:00Z',+ }+}++function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((promiseResolve) => {+ resolve = promiseResolve+ })+ return { promise, resolve }+}++describe('wizardRunsLogic', () => {+ let logic: ReturnType<typeof wizardRunsLogic.build>++ beforeEach(async () => {+ initKeaTests()+ mockWizardRunsList.mockReset()+ mockWizardRunsList.mockResolvedValue({ count: 1, next: null, previous: null, results: [makeRun()] })+ await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })+ logic = wizardRunsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('keeps resolved rows visible during background polling', async () => {+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ runsInitialLoading: false,+ runs: [expect.objectContaining({ id: 'run-1' })],+ })++ mockWizardRunsList.mockReturnValue(new Promise(() => {}))+ logic.actions.loadRuns()++ await expectLogic(logic).toMatchValues({+ runsLoading: true,+ runsInitialLoading: false,+ runs: [expect.objectContaining({ id: 'run-1' })],+ })+ })++ it('keeps the newest overlapping response', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const olderRequest = deferred<WizardRunsResponse>()+ const newerRequest = deferred<WizardRunsResponse>()+ mockWizardRunsList.mockImplementationOnce(() => olderRequest.promise)+ mockWizardRunsList.mockImplementationOnce(() => newerRequest.promise)++ logic.actions.loadRuns()+ logic.actions.loadRuns()+ newerRequest.resolve({ count: 1, next: null, previous: null, results: [makeRun('newer-run')] })+ await Promise.resolve()+ await Promise.resolve()++ expect(logic.values.runs).toEqual([expect.objectContaining({ id: 'newer-run' })])++ olderRequest.resolve({ count: 1, next: null, previous: null, results: [makeRun('older-run')] })+ await Promise.resolve()+ await Promise.resolve()++ expect(logic.values.runs).toEqual([expect.objectContaining({ id: 'newer-run' })])+ })++ it('loads every page before filtering runs', async () => {+ await expectLogic(logic).toFinishAllListeners()+ mockWizardRunsList.mockClear()+ const firstPage = Array.from({ length: 100 }, (_, index) => makeRun(`run-${index}`))+ mockWizardRunsList+ .mockResolvedValueOnce({ count: 101, next: 'next', previous: null, results: firstPage })+ .mockResolvedValueOnce({ count: 101, next: null, previous: 'previous', results: [makeRun('run-100')] })++ logic.actions.loadRuns()++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ runs: [...firstPage, makeRun('run-100')] })+ expect(mockWizardRunsList).toHaveBeenNthCalledWith(1, expect.any(String), { limit: 100, offset: 0 })+ expect(mockWizardRunsList).toHaveBeenNthCalledWith(2, expect.any(String), { limit: 100, offset: 100 })+ })++ it('merges a background poll into the cached list without reloading old pages', async () => {+ await expectLogic(logic).toFinishAllListeners()++ mockWizardRunsList.mockResolvedValueOnce({+ count: 2,+ next: null,+ previous: null,+ results: [makeRun('run-new')],+ })++ logic.actions.loadRuns({ poll: true })++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ runs: [expect.objectContaining({ id: 'run-new' }), expect.objectContaining({ id: 'run-1' })],+ })+ expect(mockWizardRunsList).toHaveBeenCalledTimes(2)+ })++ it('shows the initial loading state during a retry after a failed load', async () => {+ await expectLogic(logic).toFinishAllListeners()+ logic.unmount()++ mockWizardRunsList.mockRejectedValueOnce(new Error('boom'))+ logic = wizardRunsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.runsFailed).toBe(true)++ mockWizardRunsList.mockReturnValue(new Promise(() => {}))+ logic.actions.loadRuns({ poll: false })++ await expectLogic(logic).toMatchValues({ runsInitialLoading: true })+ })++ it('searches runs by repository name', async () => {+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSearch('posthog/posthog')++ await expectLogic(logic).toMatchValues({+ filteredRuns: [expect.objectContaining({ id: 'run-1' })],+ })+ })++ it('distinguishes filtered results from an empty run history', async () => {+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSearch('missing program')++ await expectLogic(logic).toMatchValues({+ filteredRuns: [],+ hasRunFilters: true,+ runs: [expect.objectContaining({ id: 'run-1' })],+ })+ })+})diff --git a/products/wizard/frontend/wizardRunsLogic.ts b/products/wizard/frontend/wizardRunsLogic.tsnew file mode 100644index 000000000000..0fe607a083b6--- /dev/null+++ b/products/wizard/frontend/wizardRunsLogic.ts@@ -0,0 +1,233 @@+import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { dayjs } from 'lib/dayjs'+import { projectLogic } from 'scenes/projectLogic'++import { wizardRunsList } from './generated/api'+import type { RunEnvironmentEnumApi, WizardRunApi, WizardRunStatusEnumApi } from './generated/api.schemas'+import { wizardWorkspaceLabel } from './wizardRunDisplay'++const RUN_POLL_INTERVAL_MS = 10_000+const RUN_PAGE_SIZE = 100++export interface wizardRunsLogicValues {+ currentProjectId: number | null+ environment: RunEnvironmentEnumApi | 'all'+ filteredRuns: WizardRunApi[]+ hasRunFilters: boolean+ refreshingRuns: boolean+ runs: WizardRunApi[]+ runsFailed: boolean+ runsInitialLoading: boolean+ runsLastLoadedAt: string | null+ runsLoaded: boolean+ runsLoading: boolean+ search: string+ status: WizardRunApi['status'] | 'all'+}++export interface wizardRunsLogicActions {+ clearRunFilters: () => { value: true }+ loadRuns: (payload?: { poll?: boolean }) => { poll?: boolean }+ loadRunsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ loadRunsSuccess: (runs: WizardRunApi[]) => { runs: WizardRunApi[] }+ refreshRuns: () => { value: true }+ scheduleNextRunPoll: () => { value: true }+ setEnvironment: (environment: RunEnvironmentEnumApi | 'all') => { environment: RunEnvironmentEnumApi | 'all' }+ setSearch: (search: string) => { search: string }+ setStatus: (status: WizardRunApi['status'] | 'all') => { status: WizardRunApi['status'] | 'all' }+}++export interface wizardRunsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ filteredRuns: (+ runs: WizardRunApi[],+ search: string,+ environment: RunEnvironmentEnumApi | 'all',+ status: WizardRunStatusEnumApi | 'all'+ ) => WizardRunApi[]+ hasRunFilters: (+ search: string,+ environment: RunEnvironmentEnumApi | 'all',+ status: WizardRunStatusEnumApi | 'all'+ ) => boolean+ runsInitialLoading: (runsLoaded: boolean, runsLoading: boolean, runs: WizardRunApi[]) => boolean+ }+}++export type wizardRunsLogicType = MakeLogicType<+ wizardRunsLogicValues,+ wizardRunsLogicActions,+ Record<string, never>,+ wizardRunsLogicMeta+>++export const wizardRunsLogic = kea<wizardRunsLogicType>([+ path(['products', 'wizard', 'wizardRunsLogic']),+ connect(() => ({ values: [projectLogic, ['currentProjectId']] })),+ actions({+ refreshRuns: true,+ scheduleNextRunPoll: true,+ clearRunFilters: true,+ setSearch: (search: string) => ({ search }),+ setEnvironment: (environment: RunEnvironmentEnumApi | 'all') => ({ environment }),+ setStatus: (status: WizardRunApi['status'] | 'all') => ({ status }),+ }),+ reducers({+ search: [+ '',+ {+ setSearch: (_, { search }) => search,+ clearRunFilters: () => '',+ },+ ],+ environment: [+ 'all' as RunEnvironmentEnumApi | 'all',+ {+ setEnvironment: (_, { environment }) => environment,+ clearRunFilters: () => 'all',+ },+ ],+ status: [+ 'all' as WizardRunApi['status'] | 'all',+ {+ setStatus: (_, { status }) => status,+ clearRunFilters: () => 'all',+ },+ ],+ runsLoaded: [+ false,+ {+ loadRunsSuccess: () => true,+ loadRunsFailure: () => true,+ },+ ],+ runsFailed: [+ false,+ {+ loadRuns: () => false,+ loadRunsFailure: () => true,+ },+ ],+ runsLastLoadedAt: [+ null as string | null,+ {+ loadRunsSuccess: () => dayjs().toISOString(),+ },+ ],+ refreshingRuns: [+ false,+ {+ refreshRuns: () => true,+ loadRunsSuccess: () => false,+ loadRunsFailure: () => false,+ },+ ],+ }),+ loaders(({ values }) => ({+ runs: [+ [] as WizardRunApi[],+ {+ loadRuns: async ({ poll = false }: { poll?: boolean } = {}, breakpoint) => {+ if (!values.currentProjectId) {+ return []+ }++ try {+ if (poll) {+ // Background polls fetch only the newest page and merge it into the+ // cached list, so cost stays flat as the run history grows.+ const response = await wizardRunsList(String(values.currentProjectId), {+ limit: RUN_PAGE_SIZE,+ offset: 0,+ })+ await breakpoint()++ const freshIds = new Set(response.results.map((run) => run.id))++ return [...response.results, ...values.runs.filter((run) => !freshIds.has(run.id))]+ }++ const runs: WizardRunApi[] = []+ let offset = 0++ while (true) {+ const response = await wizardRunsList(String(values.currentProjectId), {+ limit: RUN_PAGE_SIZE,+ offset,+ })+ breakpoint()+ runs.push(...response.results)++ if (!response.next) {+ return runs+ }++ offset += RUN_PAGE_SIZE+ }+ } catch (error) {+ // A superseded request must not report failure against newer data.+ await breakpoint()+ throw error+ }+ },+ },+ ],+ })),+ selectors({+ filteredRuns: [+ (s) => [s.runs, s.search, s.environment, s.status],+ (+ runs: WizardRunApi[],+ search: string,+ environment: RunEnvironmentEnumApi | 'all',+ status: WizardRunApi['status'] | 'all'+ ): WizardRunApi[] => {+ const searchText = search.trim().toLowerCase()++ return runs.filter((run) => {+ const text = `${run.program.name} ${wizardWorkspaceLabel(run)} ${run.id}`.toLowerCase()++ return (+ text.includes(searchText) &&+ (environment === 'all' || run.environment === environment) &&+ (status === 'all' || run.status === status)+ )+ })+ },+ ],+ hasRunFilters: [+ (s) => [s.search, s.environment, s.status],+ (+ search: string,+ environment: RunEnvironmentEnumApi | 'all',+ status: WizardRunApi['status'] | 'all'+ ): boolean => !!search.trim() || environment !== 'all' || status !== 'all',+ ],+ runsInitialLoading: [+ (s) => [s.runsLoaded, s.runsLoading, s.runs],+ (runsLoaded: boolean, runsLoading: boolean, runs: WizardRunApi[]): boolean =>+ !runsLoaded || (runsLoading && runs.length === 0),+ ],+ }),+ listeners(({ actions, cache }) => ({+ refreshRuns: () => actions.loadRuns({ poll: false }),+ loadRunsSuccess: () => actions.scheduleNextRunPoll(),+ loadRunsFailure: () => actions.scheduleNextRunPoll(),+ // Each poll starts only after the previous load settles, so a slow load can never be+ // cut short by the next tick.+ scheduleNextRunPoll: () => {+ cache.disposables.add(() => {+ const timerId = window.setTimeout(() => actions.loadRuns({ poll: true }), RUN_POLL_INTERVAL_MS)++ return () => window.clearTimeout(timerId)+ }, 'wizardRunPolling')+ },+ })),+ events(({ actions }) => ({+ afterMount: () => {+ actions.loadRuns({ poll: false })+ },+ })),+])diff --git a/products/wizard/manifest.tsx b/products/wizard/manifest.tsxindex fc44473de229..be286fbe68c8 100644--- a/products/wizard/manifest.tsx+++ b/products/wizard/manifest.tsx@@ -1,23 +1,39 @@-/**- * Product manifest for wizard.- *- * Defines scenes, routes, URLs, and navigation for this product.- */+import { FEATURE_FLAGS } from 'lib/constants'++import { FileSystemIconType, ProductItemCategory } from '../../frontend/src/queries/schema/schema-general'import { ProductManifest } from '../../frontend/src/types'export const manifest: ProductManifest = {name: 'Wizard',scenes: {- // Define scenes here+ WizardRuns: {+ import: () => import('./frontend/WizardRunsScene'),+ projectBased: true,+ name: 'Wizard runs',+ description: 'Run the setup agent in the cloud, then review the changes it produces.',+ layout: 'app-container',+ iconType: 'llm_prompts',+ },},routes: {- // Define routes here+ '/wizard/runs': ['WizardRuns', 'wizardRuns'],},redirects: {},urls: {- // Define URL helpers here+ wizardRuns: (): string => '/wizard/runs',},fileSystemTypes: {},treeItemsNew: [],- treeItemsProducts: [],+ treeItemsProducts: [+ {+ path: 'Wizard',+ intents: [],+ category: ProductItemCategory.TOOLS,+ type: 'wizard',+ iconType: 'llm_prompts' as FileSystemIconType,+ href: '/wizard/runs',+ flag: FEATURE_FLAGS.WIZARD_UI_ENABLED,+ sceneKey: 'WizardRuns',+ },+ ],}diff --git a/products/wizard/package.json b/products/wizard/package.jsonindex 1d8c6404879b..e399b99d31fb 100644--- a/products/wizard/package.json+++ b/products/wizard/package.json@@ -5,13 +5,19 @@"backend:contract-check": "echo 'Contract files unchanged'"},"dependencies": {+ "@pierre/diffs": "1.2.11","kea": "catalog:",+ "kea-loaders": "catalog:","posthog-js": "catalog:"},"devDependencies": {+ "@testing-library/react": "^14.3.1","kea-test-utils": "catalog:"},"peerDependencies": {+ "@posthog/icons": "catalog:",+ "@posthog/lemon-ui": "*",+ "@storybook/react": "catalog:","@types/react": "*","react": "*"}diff --git a/products/wizard/turbo.json b/products/wizard/turbo.jsonindex 71041022421c..c63d3c0f92c3 100644--- a/products/wizard/turbo.json+++ b/products/wizard/turbo.json@@ -9,7 +9,8 @@"backend/tasks/**","backend/temporal/**","backend/models.py",- "backend/migrations/**"+ "backend/migrations/**",+ "backend/temporal/**"],"outputs": [],"cache": truediff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 3d3c5777525b..24e81b33c2e0 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -1754,6 +1754,11 @@"params": [],"scope": "project"},+ "wizardRuns": {+ "template": "/wizard/runs",+ "params": [],+ "scope": "project"+ },"workflow": {"template": "/workflows/{id}/{tab}","params": ["id", "tab"],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 b53e49367374..e28aee311498 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/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\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"}},