: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): stream run tasks into the sync widget (#104690)
Fernando Gomes1a62aec3cd98
diff --git a/bin/ensure-local-setup b/bin/ensure-local-setupindex b3b5077a999f..22ecfe3d8a73 100755--- a/bin/ensure-local-setup+++ b/bin/ensure-local-setup@@ -30,7 +30,15 @@ from posthog.scopes import UNPRIVILEGED_SCOPES # noqa: E402# adds a scope, so grant everything unprivileged plus the privileged/hidden scopes the wizard# needs — same broad ceiling the hedgebox demo matrix sets on this app. Local-dev only.WIZARD_SCOPES = sorted(- UNPRIVILEGED_SCOPES | {"llm_gateway:read", "llm_gateway:write", "wizard_session:read", "wizard_session:write"}+ UNPRIVILEGED_SCOPES+ | {+ "llm_gateway:read",+ "llm_gateway:write",+ "wizard_run:read",+ "wizard_run:write",+ "wizard_session:read",+ "wizard_session:write",+ })diff --git a/docs/internal/wizard-runs.md b/docs/internal/wizard-runs.mdindex 3645918b0052..5d8571369250 100644--- a/docs/internal/wizard-runs.md+++ b/docs/internal/wizard-runs.md@@ -56,13 +56,27 @@ POST /api/projects/{project_id}/wizard/runs/GET /api/projects/{project_id}/wizard/runs/{run_id}/PATCH /api/projects/{project_id}/wizard/runs/{run_id}/GET /api/projects/{project_id}/wizard/runs/{run_id}/artifacts/+PUT /api/projects/{project_id}/wizard/runs/{run_id}/tasks/+GET /api/projects/{project_id}/wizard/runs/{run_id}/tasks/+GET /api/projects/{project_id}/wizard/runs/{run_id}/stream/```Run responses include the creator ID and basic creator details for attribution in project-level run lists.+Use `GET /api/projects/{project_id}/wizard/runs/?status=created,running&limit=5` to fetch the newest active runs; `count` gives the total number of active runs in the project. The `status` filter also accepts any individual run status.+The app-wide sync widget polls this summary and also fetches the five most recently created completed runs with `?status=completed&limit=5`.+It opens one event stream for the displayed active run. Completed runs do not open a stream.+It shows the newest active run by default, or the newest completed run when none are active.+The selector lists up to five active and five completed runs by workspace and status, with the selected run marked and the total active count shown separately.+The Wizard page lists any others. A manual selection stays in place while that run remains in either list, including when it completes.+Its card shows the current task, run stages, elapsed time, environment, and workspace. "Close" hides the current run until the page reloads, while "Don't show this run again" hides that run in this browser. New runs still show the widget, and run details remain on the Wizard page. Recent completed runs remain available after reloading unless dismissed.+The `wizard-run-sync` feature flag uses the `wizard-session` and `wizard-run` variants to select the sync widget in the authenticated shell.The PATCH request accepts a terminal `status`: `completed`, `failed`, or `cancelled`.Failed runs can also include an `error_code`.Local agents can create runs and update runs they created.+The browser does not offer cancellation for local runs because the server cannot stop a local Wizard process. Users stop those runs in their terminal.+These operations accept OAuth tokens with `wizard_run:write`; browser sessions can also create and manage runs.+Run creation uses the existing per-user creation throttle for both environments.Cloud creation requires a signed-in browser session and enabled cloud execution.Cloud lifecycle updates are owned by the Wizard Worker.@@ -80,6 +94,10 @@ The handoff activity marks the run as `completed` after it persists the Run ArtiIf a worker activity exhausts its retries or the workflow is canceled, one finalization activity records the terminal state.Sandbox cleanup does not change a completed run if cleanup fails.+The Worker passes the existing run ID to the setup agent through `POSTHOG_WIZARD_RUN_ID`.+The agent uses that ID to publish task snapshots instead of creating another run.+The Worker owns the cloud run's stages and terminal status.+The Worker:1. Resolves short-lived GitHub and Wizard credentials inside the activity.@@ -99,7 +117,7 @@ Tasks provides only generic repository-token and sandbox helpers through public## Analytics compatibility-Cloud lifecycle events keep their existing names and deterministic event UUIDs.+The service records `wizard run started`, `wizard run finished`, and `wizard run artifact created` with deterministic event UUIDs.They add the legacy properties `run_surface`, `project_id`, `version`, and `command`.The existing `environment`, `team_id`, `wizard_version`, and `wizard_run_id` properties remain available.`event_source` distinguishes `wizard_run_service` events from `wizard_ui` events.@@ -113,18 +131,25 @@ The CLI keeps its separate, process-level `run_id`.The CLI remains the only source of `setup wizard finished`.Its `status` values remain `success`, `error`, and `cancelled`.-Service completion events describe the full cloud lifecycle, including failures before CLI startup and failures during repository publication.+The service finish event describes the full cloud lifecycle, including failures before CLI startup and failures during repository publication.Do not add the CLI and service completion events together when counting runs.-The UI records library opens, successful command copies, create requests and outcomes, retry selections, run views, and diff opens.+The UI records library selections, create requests and failures, table searches, filters and pagination, detail dialog activity, FAB activity, run refreshes, copied run IDs, workspace opens, and artifact clicks.It also records confirmed cancellation requests and outcomes.Polling does not create more view events. Clipboard failures do not count as command copies.Use `wizard run create requested` and `wizard run create failed` to measure request failures, including limit responses.-Use `wizard_run_id` to join successful creation to existing lifecycle events, `wizard pull request created`, and `wizard run diff opened`.-Events omit repository names, paths, full shell commands, diff contents, tokens, and raw error messages.+Use `wizard_run_id` to join UI activity to run lifecycle and artifact events.+Events omit local paths, full shell commands, diff contents, tokens, and raw error messages.## Deployment configuration+### AI gateway URLs++`WIZARD_GATEWAY_URL` is the gateway address returned to the setup agent.+`WIZARD_GATEWAY_MINT_URL` optionally sets a separate address for the backend's token-mint requests and defaults to `WIZARD_GATEWAY_URL` when unset.+For local Docker sandboxes, set `WIZARD_GATEWAY_URL=http://host.docker.internal:8080` and `WIZARD_GATEWAY_MINT_URL=http://localhost:8080` in PostHog's `.env.local`.+Restart the backend after changing these settings.+### Distributed tracingCloud runs use the shared OpenTelemetry instrumentation described in the [distributed tracing guide](https://posthog.com/docs/distributed-tracing).@@ -182,6 +207,45 @@ Updated archives remain a future artifact type.## State synchronization+The setup agent sends its complete task snapshot to `PUT /api/projects/{project_id}/wizard/runs/{run_id}/tasks/`:++```json+{ "tasks": [{ "name": "Install SDK", "status": "running" }] }+```++The endpoint requires an OAuth token with `wizard_run:write` for the user who created the run.+Add `wizard_run:write` to the Wizard OAuth application's scope ceiling before switching the agent to these endpoints.+Agents that read snapshots also need `wizard_run:read`.+Existing tokens need these grants through renewed authorization; the backend does not widen them automatically.+It returns `204` with no body.+Both local and cloud agents write to their assigned run ID.+Task names must be unique within the snapshot and remain stable between updates: renaming a task creates a new task identity.+Each snapshot replaces the stored list, preserves its order, and removes omitted tasks.+An empty list clears the snapshot.+A snapshot accepts up to 100 tasks, with names up to 255 characters.+Task statuses are `created`, `running`, `completed`, and `failed`.+Multiple tasks may run at once, and a snapshot does not need to contain a running task.+Task statuses do not change the run's lifecycle status.++`GET /api/projects/{project_id}/wizard/runs/{run_id}/tasks/` returns the full list as `{"tasks": [...]}` without pagination.+Browser sessions and tokens with `wizard_run:read` can read the list within their project.+Each task includes `name`, `status`, `created_at`, `started_at`, `completed_at`, `failed_at`, and `error_message`.+The server preserves the first-observed timestamp for each state while the task remains in the snapshot.+A task first received as completed has no known start time, so `started_at` remains null.+The input does not include failure details; `error_message` remains null.+Timestamps use the server clock and are returned as ISO 8601 strings.+Snapshots are reconciled under a row lock so concurrent updates preserve recorded timestamps.+The server applies snapshots in arrival order; clients must await each update before sending the next.++The run's `stream/` endpoint requires a browser session and emits an initial state followed by updates after committed task, status, or stage changes.+Each SSE `data` event contains `tasks`, `status`, `stage`, `error_code`, `error_message`, `updated_at`, `started_at`, and `finished_at`.+Immutable run fields such as `id` are omitted.+Redis notifications are scoped by project and run ID, and each notification reloads the committed state.+Fanout is best effort: reconnecting reads the latest state, and GET remains available if a notification is missed.+The stream sends heartbeat comments and rotates after 15 minutes with `event: end` and `data: reconnect`.+It uses the existing `onboarding-wizard-sync-killswitch` flag; an enabled flag returns `204` so EventSource stops reconnecting.+Use EventSource rather than the generated fetch wrapper to consume the stream.+The existing Wizard session endpoint remains active during migration:```textdiff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.mdindex 3d946c2074fd..f0ad66188c60 100644--- a/docs/published/handbook/engineering/developing-locally.md+++ b/docs/published/handbook/engineering/developing-locally.md@@ -266,6 +266,11 @@ The first time you run typegen, it may get stuck. Cancel it (`Ctrl+C`), run `git**"layout.html is not defined" error**This happens on first startup. Wait for the frontend to finish compiling and try accessing the app again.+**Vite cannot resolve an installed Tiptap package**+Files under `products/*/frontend` cannot resolve packages installed only in `frontend/node_modules` through their parent directories.+Shared Tiptap packages, including `@tiptap/extension-image`, have individual aliases in `frontend/vite.config.mts`.+Check those aliases if an installed package fails to resolve from a product directory.+**Kafka segfaults on ARM**Kafka is an x86 container and may segfault randomly on ARM machines. Simply restart it when that happens.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2250bf9ec75b..03809b290d1f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6964,6 +6964,22 @@ snapshots:hash: v1.k794b7964.86d0cbd8d6aff26f2592a2b564534fb53fd5c0bb89c1383f0cc4e1c4029e6ad0.RjTbwWkbD4SNVNNM83vresibkwUxkliGjKwl5_LCWMEproducts-wizard-wizard-run-diff-viewer--narrow--light:hash: v1.k794b7964.2ea84850b2a15dfe74254e4439305686f9718b0627f1bc8ca05a0fd428fcebba.qvBX7qTpArw7bMv-azF7FL1HSBhsl9BhNblAoqlGpi8+ products-wizard-wizard-run-sync-card--completed--dark:+ hash: v1.k794b7964.b389514fabb5dec603e6ac02cfe893d90ee793ced7fa06fdee051ab218ed9e6f.ifpv5W-1BCjmRB-laDihXTly_4UxYYZfwk0_xRMcVoo+ products-wizard-wizard-run-sync-card--completed--light:+ hash: v1.k794b7964.0d171f1dd84ed010d842617f35781f5d1b31f4222c48631e6854b76a56106ad3.3MBXO6B3RlDeEPOSAIHl4RB3UffoZOLrBdN50j8GCH4+ products-wizard-wizard-run-sync-card--local-running--dark:+ hash: v1.k794b7964.070388138ab8bc5e20c611f5b42036c39901c3317beee7ba8f6aed70af62676f.sk2IJooQi8BK7jzJ2f_fBf7oRzT84m5IITvhwWu_09c+ products-wizard-wizard-run-sync-card--local-running--light:+ hash: v1.k794b7964.a38acaf7ddbfa37a3eaade8958875c54749471c262ddb52f0eade0d1d4b198ed.CbsNAL-B-ud5AUggvwVq5ub2-kDqUp8TWuRRxm1rO08+ products-wizard-wizard-run-sync-card--multiple-runs--dark:+ hash: v1.k794b7964.e789ca3d622fa2b08aee57c2baadd6bb0a52300e488a8f930de58cdab26cea69.DGYEtSMfDUbr2sATZhkHRT2_QvZGDJFNgDapxqrzThE+ products-wizard-wizard-run-sync-card--multiple-runs--light:+ hash: v1.k794b7964.69189adcaad12ad70369068150d954cd8c11f9d56c6c1bfb0bedee839a69b2dc.TkYYU8OORDZougolY7DYEZYahFzy4aEQCqeLS9DFsY8+ products-wizard-wizard-run-sync-card--running--dark:+ hash: v1.k794b7964.b59d3e3b569184f8fdd9029c1c2067b053e8e135173c37218bfe4c626079b7e3.v2d325yM8eofSv8GOhTRsOEFjAoT2k8AHsyUXsGxaHs+ products-wizard-wizard-run-sync-card--running--light:+ hash: v1.k794b7964.df30028d9399928f4b1c8d2ad87fadb9ce6597419600e07b57b35d34ac9ade93.zpJJ3MjyG1rhJm9eAq8JTYdRRteI3ptNuZor2nr8hOAproducts-workflows-customerioimportmodal--all-steps-completed--dark:hash: v1.k794b7964.da9d1ebf1836700267307224631511bd8fe3b9fb0906654a383e545e1c6f98f1.lPijIVizKAMxsGEVt28x0Y5izfhcfnbjbPhoHzriWFgproducts-workflows-customerioimportmodal--all-steps-completed--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 12c66ac56318..d5c77136d982 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -582,6 +582,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_RUN_SYNC: 'wizard-run-sync', // owner: #team-growth multivariate=wizard-session,wizard-run — selects the Wizard sync widgetWIZARD_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-workflowsdiff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsxindex 569f5f3bf7c0..ad17bdd58dd5 100644--- a/frontend/src/scenes/AuthenticatedShell.tsx+++ b/frontend/src/scenes/AuthenticatedShell.tsx@@ -22,6 +22,8 @@ import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { breadcrumbsLogic } from '~/layout/navigation/Breadcrumbs/breadcrumbsLogic'import { ImpersonationNotice } from '~/layout/navigation/ImpersonationNotice'+import { WizardRunSyncFab } from 'products/wizard/frontend/runs/WizardRunSyncFab'+import { sceneLogic } from './sceneLogic'const TerminalDock = lazyWithRetry(() =>@@ -38,6 +40,7 @@ export default function AuthenticatedShell({ children }: { children: React.Reactconst { sceneConfig } = useValues(sceneLogic)const { featureFlags } = useValues(featureFlagLogic)const { isDarkModeOn } = useValues(themeLogic)+ const runSyncEnabled = featureFlags[FEATURE_FLAGS.WIZARD_RUN_SYNC] === 'wizard-run'return (<>@@ -54,7 +57,7 @@ export default function AuthenticatedShell({ children }: { children: React.React)}<Command /><ImpersonationNotice />- <WizardSyncFab />+ {runSyncEnabled ? <WizardRunSyncFab /> : <WizardSyncFab />}{/* Separate from the FAB: the FAB stands down while an inline panel shows the run,but the doc dialog must be able to open from any surface. */}<WizardHandoffDialog />diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 5d4bf3e1cf3a..5509fc08981f 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -88,6 +88,7 @@ export default defineConfig(({ mode }) => {'@tiptap/core': resolve(__dirname, 'node_modules/@tiptap/core'),'@tiptap/react': resolve(__dirname, 'node_modules/@tiptap/react'),'@tiptap/pm': resolve(__dirname, 'node_modules/@tiptap/pm'),+ '@tiptap/extension-image': resolve(__dirname, 'node_modules/@tiptap/extension-image'),'@tiptap/extension-placeholder': resolve(__dirname, 'node_modules/@tiptap/extension-placeholder'),products: resolve(__dirname, '../products'),'@posthog/shared-onboarding': resolve(__dirname, '../docs/onboarding'),diff --git a/packages/quill/packages/components/AGENTS.md b/packages/quill/packages/components/AGENTS.mdindex e1c17f94e24c..f094aa8de291 100644--- a/packages/quill/packages/components/AGENTS.md+++ b/packages/quill/packages/components/AGENTS.md@@ -30,6 +30,7 @@ const columns: ColumnDef<Person>[] = [stickyHeader // or "page" to stick to document scrollfullWidthsize="sm" // tighten cell padding; pair with Card size="sm"+ onPageChange={(page, nextPage) => track(page, nextPage)} // one-based page numbersonRowClick={(row) => open(row)} // ignores links, buttons, and form controls inside the row/>```@@ -39,7 +40,7 @@ Rules:- Column defs are standard TanStack `ColumnDef`s; quill-specific options go in `meta`: `align: 'left' | 'center' | 'right'` (header + cells) and `expand: true` (absorb leftover width).- `fullWidth` needs exactly one column with `meta: { expand: true }` to decide which column stretches.- Sorting is client-side and on by default — click header toggles asc → desc → off. Opt out per column with `enableSorting: false`.-- Pagination is opt-in via `pageSize`; the component owns page state and resets to page 0 when `pageSize` changes. The pager is suppressed when the table has no rows — an empty table shows only its empty state, never a "0–0 of 0" pager.+- Pagination is opt-in via `pageSize`; the component owns page state, reports user navigation through `onPageChange`, and resets to page 0 when `pageSize` changes. The pager is suppressed when the table has no rows — an empty table shows only its empty state, never a "0–0 of 0" pager.- Custom empty state via the `empty` prop (ReactNode); default is a minimal "No results".- `onRowClick` makes non-interactive parts of each row clickable and keyboard accessible. Links, buttons, form controls, editable content, and custom controls keep their own behavior. Add `data-row-click-ignore` to a custom descendant that must not activate the row.- Don't rebuild tables from `Table` primitives when the data is row/column shaped and needs sorting or pagination — that's what DataTable is for. Drop to the `Table` primitive only for fully custom layouts.diff --git a/packages/quill/packages/components/src/data-table.test.tsx b/packages/quill/packages/components/src/data-table.test.tsxindex 2f02adc8773e..383dd277f0f6 100644--- a/packages/quill/packages/components/src/data-table.test.tsx+++ b/packages/quill/packages/components/src/data-table.test.tsx@@ -40,4 +40,21 @@ describe('DataTable', () => {expect(onRowClick).toHaveBeenCalledWith(data[0])})++ it('reports page changes with one-based page numbers', () => {+ const onPageChange = jest.fn()+ const columns: ColumnDef<TestRow>[] = [{ accessorKey: 'name', header: 'Name' }]+ render(+ <DataTable+ columns={columns}+ data={[{ name: 'Ada' }, { name: 'Grace' }]}+ pageSize={1}+ onPageChange={onPageChange}+ />+ )++ fireEvent.click(screen.getByLabelText('Go to page 2'))++ expect(onPageChange).toHaveBeenCalledWith(1, 2)+ })})diff --git a/packages/quill/packages/components/src/data-table.tsx b/packages/quill/packages/components/src/data-table.tsxindex 860181f3b400..811099b00123 100644--- a/packages/quill/packages/components/src/data-table.tsx+++ b/packages/quill/packages/components/src/data-table.tsx@@ -100,6 +100,8 @@ export interface DataTableProps<TData, TValue> {data: TData[]/** Opens or selects a record when the user clicks a non-interactive part of its row. */onRowClick?: (row: TData) => void+ /** Called when the user moves between pages. Page numbers are one-based. */+ onPageChange?: (page: number, nextPage: number) => void/** Sizing/scroll classes for the table container (forwarded to the Table primitive). */className?: string/** Sticky header mode, forwarded to the Table primitive. `'page'` sticks to document scroll. */@@ -155,9 +157,11 @@ const DEFAULT_EMPTY = (function DataTablePagination<TData>({table,pageSizeOptions,+ onPageChange,}: {table: TanstackTable<TData>pageSizeOptions?: number[]+ onPageChange?: (page: number, nextPage: number) => void}): React.ReactElement {const { pageIndex, pageSize } = table.getState().paginationconst pageCount = table.getPageCount()@@ -165,6 +169,10 @@ function DataTablePagination<TData>({const start = total === 0 ? 0 : pageIndex * pageSize + 1const end = Math.min((pageIndex + 1) * pageSize, total)const range = getPaginationRange(pageCount, pageIndex)+ const goToPage = (nextPageIndex: number): void => {+ onPageChange?.(pageIndex + 1, nextPageIndex + 1)+ table.setPageIndex(nextPageIndex)+ }// px-3 matches the cells' 0.75rem inline padding. Bottom padding keeps the// controls clear of a flush card's edge.@@ -194,7 +202,10 @@ function DataTablePagination<TData>({<Pagination className="w-auto"><PaginationContent><PaginationItem>- <PaginationPrevious disabled={!table.getCanPreviousPage()} onClick={() => table.previousPage()}>+ <PaginationPrevious+ disabled={!table.getCanPreviousPage()}+ onClick={() => goToPage(pageIndex - 1)}+ ><span className="sr-only">Previous</span></PaginationPrevious></PaginationItem>@@ -208,7 +219,7 @@ function DataTablePagination<TData>({<PaginationButtonisActive={item === pageIndex}aria-label={`Go to page ${item + 1}`}- onClick={() => table.setPageIndex(item)}+ onClick={() => goToPage(item)}>{item + 1}</PaginationButton>@@ -216,7 +227,7 @@ function DataTablePagination<TData>({))}<PaginationItem>- <PaginationNext disabled={!table.getCanNextPage()} onClick={() => table.nextPage()}>+ <PaginationNext disabled={!table.getCanNextPage()} onClick={() => goToPage(pageIndex + 1)}><span className="sr-only">Next</span></PaginationNext></PaginationItem>@@ -245,6 +256,7 @@ function DataTable<TData, TValue>({empty = DEFAULT_EMPTY,pageSize,pageSizeOptions,+ onPageChange,}: DataTableProps<TData, TValue>): React.ReactElement {const paginated = pageSize != nullconst [sorting, setSorting] = React.useState<SortingState>([])@@ -385,7 +397,7 @@ function DataTable<TData, TValue>({return (<div className="flex flex-col gap-2">{tableElement}- <DataTablePagination table={table} pageSizeOptions={pageSizeOptions} />+ <DataTablePagination table={table} pageSizeOptions={pageSizeOptions} onPageChange={onPageChange} /></div>)}diff --git a/posthog/llm/test_wizard_gateway_token.py b/posthog/llm/test_wizard_gateway_token.pyindex 134181fb1581..2b7f80eee65e 100644--- a/posthog/llm/test_wizard_gateway_token.py+++ b/posthog/llm/test_wizard_gateway_token.py@@ -37,6 +37,7 @@ from posthog.models.team.team import TeamMINT_SETTINGS = {"WIZARD_GATEWAY_URL": "https://ai-gateway.us.posthog.com",+ "WIZARD_GATEWAY_MINT_URL": "","WIZARD_GATEWAY_MINT_KEY": "phs_wizard_secret","WIZARD_GATEWAY_CLIENT_IDS": ["wizard-client-id"],# Not _DEFAULT_CAP_USD: equal values make the honored-setting and fell-back@@ -66,12 +67,24 @@ class TestMintWizardGatewayToken:with override_settings(**MINT_SETTINGS):yield- def test_posts_pinned_attribution_and_bearer(self):+ @pytest.mark.parametrize(+ "mint_url,expected_url",+ [+ ("", "https://ai-gateway.us.posthog.com/v1/tokens"),+ ("http://localhost:8080", "http://localhost:8080/v1/tokens"),+ ("http://localhost:8080/v1/", "http://localhost:8080/v1/tokens"),+ ],+ )+ def test_posts_pinned_attribution_and_bearer(self, mint_url: str, expected_url: str) -> None:minted = {"token": "phe_x", "expires_at": "2026-08-22T00:00:00Z", "cap_usd": "25"}- with patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post:+ with (+ override_settings(WIZARD_GATEWAY_MINT_URL=mint_url),+ patch("posthog.llm.wizard_gateway_token.requests.post", return_value=_Response(201, minted)) as post,+ ):assert mint_wizard_gateway_token(obo="7", user="user_1") == minted+ assert wizard_gateway_base_url() == "https://ai-gateway.us.posthog.com"- assert post.call_args[0][0] == "https://ai-gateway.us.posthog.com/v1/tokens"+ assert post.call_args[0][0] == expected_urlassert post.call_args.kwargs["json"] == {"cap_usd": "25.000000","ttl_seconds": 86400,@@ -116,7 +129,7 @@ class TestWizardModelAllowlist:assert set(efforts) <= set(WIZARD_EFFORT_LEVELS), modelassert normalize_model(model) == model, model- @override_settings(WIZARD_GATEWAY_URL="https://ai-gateway.us.posthog.com/v1/")+ @override_settings(WIZARD_GATEWAY_URL="https://ai-gateway.us.posthog.com/v1/", WIZARD_GATEWAY_MINT_URL="")def test_version_suffixed_setting_does_not_double_up(self):# The setting may carry /v1; both the mint path and the base handed to the# CLI must come out the same regardless.diff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pyindex 2669ad79353a..cc954a1bd745 100644--- a/posthog/llm/wizard_gateway_token.py+++ b/posthog/llm/wizard_gateway_token.py@@ -383,8 +383,7 @@ def wizard_gateway_configured() -> bool:def wizard_gateway_base_url() -> str:- """The gateway base without the version segment. The CLI gets the same string,- so both sides read one normalization of the setting."""+ """The gateway base returned to the CLI, without the version segment."""return settings.WIZARD_GATEWAY_URL.rstrip("/").removesuffix("/v1")@@ -404,7 +403,7 @@ def mint_wizard_gateway_token(bounded by the posture's ceiling, then the posture's own, then the flatsetting, which applies only when there is no posture."""- base_url = wizard_gateway_base_url()+ base_url = (settings.WIZARD_GATEWAY_MINT_URL or settings.WIZARD_GATEWAY_URL).rstrip("/").removesuffix("/v1")body = {"cap_usd": _cap_usd(cap_usd, program=program, posture=posture),"ttl_seconds": _ttl_seconds(posture),diff --git a/posthog/scopes.py b/posthog/scopes.pyindex dd218edcbc4b..49fbc915a710 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -137,6 +137,7 @@ APIScopeObject = Literal["web_analytics","webhook","wizard_session",+ "wizard_run",]@@ -211,6 +212,7 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"wizard_session",+ "wizard_run","query_performance",# Staff-only managed-migrations (batch import) support diagnostics, also gated by# `is_staff`. Distinct from the public `batch_import` object on purpose: that one isdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 808fe8a6059a..5c6e7a900fee 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -649,6 +649,7 @@ SPECTACULAR_SETTINGS = {## The definition site is a deliberately Django-free module (facade contracts,# signals taxonomy), so it cannot define a models.Choices class.+ "WizardTaskStatusEnum": "products.wizard.backend.facade.enums.WIZARD_TASK_STATUS_CHOICES","SignalSourceProductEnum": "products.signals.backend.enums.signal_source_product_choices","ReportLinkKindEnum": "products.signals.backend.enums.report_link_kind_choices","EngineeringAnalyticsPRStateEnum": "products.engineering_analytics.backend.facade.contracts.PRState",@@ -1312,6 +1313,7 @@ except ValueError:# Wizard gateway-token mint. Any of the four unset refuses every mint as# `unconfigured`, which ends the wizard run: there is no other gateway.WIZARD_GATEWAY_URL = get_from_env("WIZARD_GATEWAY_URL", "")+WIZARD_GATEWAY_MINT_URL = get_from_env("WIZARD_GATEWAY_MINT_URL", "")WIZARD_GATEWAY_MINT_KEY = get_from_env("WIZARD_GATEWAY_MINT_KEY", "")# OAuth application client ids allowed to mint: llm_gateway:read is an internal# scope on every sandbox and agent token, so the scope alone does not identify thediff --git a/products/wizard/backend/facade/api.py b/products/wizard/backend/facade/api.pyindex c878a910def4..0bc3be95d42a 100644--- a/products/wizard/backend/facade/api.py+++ b/products/wizard/backend/facade/api.py@@ -13,11 +13,14 @@ from contextlib import asynccontextmanagerfrom typing import Anyfrom uuid import UUID+from redis.asyncio.client import PubSub+from products.wizard.backend import metricsfrom products.wizard.backend.facade.contracts import (CreatePullRequestArtifactInput,CreateWizardRunInput,ListWizardRunsInput,+ UpdateWizardRunTaskInput,UpsertWizardSessionInput,WizardProgram,WizardRunArtifactDTO,@@ -26,6 +29,7 @@ from products.wizard.backend.facade.contracts import (WizardRunGitDiffArtifactDTO,WizardRunPage,WizardRunPullRequestArtifactDTO,+ WizardRunTaskDTO,WizardSessionDTO,)from products.wizard.backend.facade.enums import WizardRunStage, WizardRunStatus@@ -36,6 +40,7 @@ from products.wizard.backend.logic import (sessions,)from products.wizard.backend.logic.artifacts import service as artifacts+from products.wizard.backend.logic.runs import pubsub as run_pubsubfrom products.wizard.backend.logic.sessions import pubsub@@ -111,6 +116,12 @@ def get_run(team_id: int, run_id: UUID) -> WizardRunDTO:return run_service.get_run(team_id, run_id)+@asynccontextmanager+async def subscribe_to_run_updates(team_id: int, run_id: UUID) -> AsyncIterator[PubSub]:+ async with run_pubsub.subscribe(team_id, run_id) as subscription:+ yield subscription++def list_runs(params: ListWizardRunsInput) -> WizardRunPage:return run_service.list_runs(params)@@ -133,6 +144,12 @@ def update_run_status(return run_service.transition_run(team_id, run_id, status, error_code=error_code)+def update_run_task_list(+ team_id: int, run_id: UUID, tasks: tuple[UpdateWizardRunTaskInput, ...]+) -> tuple[WizardRunTaskDTO, ...]:+ return run_service.update_run_task_list(team_id, run_id, tasks)++def create_git_diff_artifact(team_id: int, run_id: UUID, content: bytes) -> WizardRunGitDiffArtifactDTO | None:"""Uploads a git diff generated in a Wizard run.diff --git a/products/wizard/backend/facade/contracts.py b/products/wizard/backend/facade/contracts.pyindex d55512f39196..6b38ebcafb11 100644--- a/products/wizard/backend/facade/contracts.py+++ b/products/wizard/backend/facade/contracts.py@@ -19,6 +19,7 @@ from .enums import (WizardRunStatus,WizardSessionRunPhase,WizardSessionTaskStatus,+ WizardTaskStatus,)STALE_AFTER = timedelta(minutes=10)@@ -152,6 +153,48 @@ class WizardRunCreatorDTO:email: str+@frozen+class UpdateWizardRunTaskInput:+ """+ Payload used to update a single task of a WizardRun.+ """++ title: str+ status: WizardTaskStatus+++@frozen+class UpdateWizardRunTaskListInput:+ """+ Payload used to update the list of tasks of a WizardRun.++ The Wizard's LLM generates and updates the task list, as a snaphost.+ This is why the input shape doesn't have timestamps. Those will computed+ server-side.+ """++ tasks: tuple[UpdateWizardRunTaskInput, ...]+++@frozen+class WizardRunTaskDTO:+ """+ A single task of a WizardRun.++ Note: the datetimes are computed server-side,+ since the Wizard only sends the current list's snapshot.+ This is why it is only shown to the user.+ """++ title: str+ status: WizardTaskStatus+ created_at: datetime+ started_at: datetime | None+ completed_at: datetime | None+ failed_at: datetime | None+ error_message: str | None++@frozenclass WizardRunDTO:id: UUID@@ -170,6 +213,7 @@ class WizardRunDTO:finished_at: datetime | Nonedeadline_at: datetime | Nonecreated_by: WizardRunCreatorDTO | None = None+ tasks: tuple[WizardRunTaskDTO, ...] = ()@frozen@@ -177,6 +221,7 @@ class ListWizardRunsInput:team_id: intoffset: intlimit: int+ statuses: tuple[WizardRunStatus, ...] = ()@frozendiff --git a/products/wizard/backend/facade/enums.py b/products/wizard/backend/facade/enums.pyindex ddad7daaa8f1..e422be18b12b 100644--- a/products/wizard/backend/facade/enums.py+++ b/products/wizard/backend/facade/enums.py@@ -26,6 +26,16 @@ class WizardSessionTaskStatus(StrEnum):CANCELED = "canceled"+class WizardTaskStatus(StrEnum):+ CREATED = "created"+ RUNNING = "running"+ COMPLETED = "completed"+ FAILED = "failed"+++WIZARD_TASK_STATUS_CHOICES = [(status.value, status.value) for status in WizardTaskStatus]++class WizardRunStatus(StrEnum):CREATED = "created"RUNNING = "running"diff --git a/products/wizard/backend/logic/runs/__init__.py b/products/wizard/backend/logic/runs/__init__.pyindex a07ac0f8d41d..e8cee8aa714d 100644--- a/products/wizard/backend/logic/runs/__init__.py+++ b/products/wizard/backend/logic/runs/__init__.py@@ -9,6 +9,7 @@ from products.wizard.backend.logic.runs.lifecycle import (start_run,transition_run,update_run_stage,+ update_run_task_list,)from products.wizard.backend.logic.runs.validation import validate_git_repository_name@@ -24,4 +25,5 @@ __all__ = ["transition_run","update_run_stage","validate_git_repository_name",+ "update_run_task_list",]diff --git a/products/wizard/backend/logic/runs/lifecycle.py b/products/wizard/backend/logic/runs/lifecycle.pyindex 1b45afbfff6e..895e7104dd58 100644--- a/products/wizard/backend/logic/runs/lifecycle.py+++ b/products/wizard/backend/logic/runs/lifecycle.py@@ -1,9 +1,11 @@import loggingfrom dataclasses import replace+from datetime import datetimefrom functools import partialfrom uuid import UUIDfrom django.db import transaction as database_transaction+from django.utils import timezonefrom posthog.models import Team, User@@ -13,15 +15,18 @@ from products.wizard.backend.facade.contracts import (GitRepositoryWorkspace,ListWizardRunsInput,LocalFolderWorkspace,+ UpdateWizardRunTaskInput,WizardRunCreationResult,WizardRunDTO,WizardRunPage,+ WizardRunTaskDTO,)from products.wizard.backend.facade.enums import (WizardRunEnvironment,WizardRunErrorCode,WizardRunStage,WizardRunStatus,+ WizardTaskStatus,)from products.wizard.backend.facade.errors import (IllegalStatusTransitionError,@@ -236,3 +241,45 @@ def transition_run(run_observability.run_transitioned(previous, run)return run+++def _compute_task_list_derived_fields(+ tasks: tuple[UpdateWizardRunTaskInput, ...],+ previous_tasks: tuple[WizardRunTaskDTO, ...],+ snapshot_timestamp: datetime,+) -> tuple[WizardRunTaskDTO, ...]:+ previous_by_title = {task.title: task for task in previous_tasks}+ updated_tasks = []+ for task in tasks:+ previous = previous_by_title.get(task.title)+ current = previous or WizardRunTaskDTO(+ title=task.title,+ status=task.status,+ created_at=snapshot_timestamp,+ started_at=None,+ completed_at=None,+ failed_at=None,+ error_message=None,+ )+ updated_tasks.append(+ replace(+ current,+ status=task.status,+ started_at=current.started_at+ or (snapshot_timestamp if task.status == WizardTaskStatus.RUNNING else None),+ completed_at=current.completed_at+ or (snapshot_timestamp if task.status == WizardTaskStatus.COMPLETED else None),+ failed_at=current.failed_at or (snapshot_timestamp if task.status == WizardTaskStatus.FAILED else None),+ )+ )+ return tuple(updated_tasks)+++def update_run_task_list(+ team_id: int, run_id: UUID, tasks: tuple[UpdateWizardRunTaskInput, ...]+) -> tuple[WizardRunTaskDTO, ...]:+ with database_transaction.atomic():+ current_run = store.get_run_for_update(team_id, run_id)+ updated_tasks = _compute_task_list_derived_fields(tasks, current_run.tasks, timezone.now())+ updated_run = store.update_run_task_list(team_id, run_id, updated_tasks)+ return updated_run.tasksdiff --git a/products/wizard/backend/logic/runs/mappers.py b/products/wizard/backend/logic/runs/mappers.pyindex 88ded36b1eba..33230d9de7ac 100644--- a/products/wizard/backend/logic/runs/mappers.py+++ b/products/wizard/backend/logic/runs/mappers.py@@ -1,14 +1,18 @@+from datetime import datetime+from products.wizard.backend.facade.contracts import (GitRepositoryWorkspace,LocalFolderWorkspace,WizardRunCreatorDTO,WizardRunDTO,+ WizardRunTaskDTO,WizardWorkspace,)from products.wizard.backend.facade.enums import (WizardRunEnvironment,WizardRunStage,WizardRunStatus,+ WizardTaskStatus,WizardWorkspaceType,)from products.wizard.backend.facade.validation import validate_workspace_metadata_value@@ -61,4 +65,16 @@ def record_to_run(run: WizardRun) -> WizardRunDTO:if creator is not Noneelse None),+ tasks=tuple(+ WizardRunTaskDTO(+ title=task["title"],+ status=WizardTaskStatus(task["status"]),+ created_at=datetime.fromisoformat(task["created_at"]),+ started_at=datetime.fromisoformat(task["started_at"]) if task["started_at"] else None,+ completed_at=datetime.fromisoformat(task["completed_at"]) if task["completed_at"] else None,+ failed_at=datetime.fromisoformat(task["failed_at"]) if task["failed_at"] else None,+ error_message=task["error_message"],+ )+ for task in run.tasks_snapshot or []+ ),)diff --git a/products/wizard/backend/logic/runs/pubsub.py b/products/wizard/backend/logic/runs/pubsub.pynew file mode 100644index 000000000000..a9cee65e9e04--- /dev/null+++ b/products/wizard/backend/logic/runs/pubsub.py@@ -0,0 +1,36 @@+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from uuid import UUID++from django.db import transaction++import structlog+from redis.asyncio.client import PubSub+from redis.exceptions import RedisError++from posthog.redis import get_async_client, get_client++logger = structlog.get_logger(__name__)+++def channel_name(team_id: int, run_id: UUID) -> str:+ return f"wizard_runs:team:{team_id}:run:{run_id}"+++def publish_run_update(team_id: int, run_id: UUID) -> None:+ def publish() -> None:+ try:+ # Subscribers reload committed state so delayed notifications cannot replay an older snapshot.+ get_client().publish(channel_name(team_id, run_id), b"{}")+ except RedisError:+ logger.exception("wizard_run_publish_failed", team_id=team_id, run_id=str(run_id))++ transaction.on_commit(publish)+++@asynccontextmanager+async def subscribe(team_id: int, run_id: UUID) -> AsyncIterator[PubSub]:+ client = get_async_client()+ async with client.pubsub(ignore_subscribe_messages=True) as pubsub:+ await pubsub.subscribe(channel_name(team_id, run_id))+ yield pubsubdiff --git a/products/wizard/backend/logic/runs/store.py b/products/wizard/backend/logic/runs/store.pyindex ac8c2edb1d0f..7eaec933c108 100644--- a/products/wizard/backend/logic/runs/store.py+++ b/products/wizard/backend/logic/runs/store.py@@ -14,6 +14,7 @@ from products.wizard.backend.facade.contracts import (WizardRunCreationResult,WizardRunDTO,WizardRunPage,+ WizardRunTaskDTO,WizardWorkspace,)from products.wizard.backend.facade.enums import (@@ -31,6 +32,7 @@ from products.wizard.backend.logic.runs.config import ()from products.wizard.backend.logic.runs.diagnostics import error_messagefrom products.wizard.backend.logic.runs.mappers import record_to_run, workspace_to_record+from products.wizard.backend.logic.runs.pubsub import publish_run_updatefrom products.wizard.backend.models import WizardRunlogger = logging.getLogger(__name__)@@ -158,6 +160,7 @@ def set_run_stage(team_id: int, run_id: UUID, stage: WizardRunStage) -> WizardRurun.stage = stage.valuerun.stage_started_at = timezone.now()run.save(update_fields=["stage", "stage_started_at", "updated_at"])+ publish_run_update(team_id, run_id)return record_to_run(run)@@ -176,6 +179,8 @@ def get_run_for_update(team_id: int, run_id: UUID) -> WizardRunDTO:def list_runs(params: ListWizardRunsInput) -> WizardRunPage:runs = WizardRun.objects.for_team(params.team_id).select_related("created_by").order_by("-created_at")+ if params.statuses:+ runs = runs.filter(status__in=params.statuses)page = runs[params.offset : params.offset + params.limit]results: list[WizardRunDTO] = []for run in page:@@ -215,5 +220,29 @@ def set_run_status(update_fields.extend(["finished_at", "stage", "stage_started_at"])run.save(update_fields=update_fields)+ publish_run_update(team_id, run_id)++ return record_to_run(run)+++def update_run_task_list(team_id: int, run_id: UUID, tasks: tuple[WizardRunTaskDTO, ...]) -> WizardRunDTO:+ run = _get_run_record(team_id, run_id)++ run.tasks_snapshot = [+ {+ "title": task.title,+ "status": task.status.value,+ "created_at": task.created_at.isoformat(),+ "started_at": task.started_at.isoformat() if task.started_at else None,+ "completed_at": task.completed_at.isoformat() if task.completed_at else None,+ "failed_at": task.failed_at.isoformat() if task.failed_at else None,+ "error_message": task.error_message,+ }+ for task in tasks+ ]++ run.tasks_snapshot_updated_at = timezone.now()+ run.save(update_fields=["tasks_snapshot", "tasks_snapshot_updated_at", "updated_at"])+ publish_run_update(team_id, run_id)return record_to_run(run)diff --git a/products/wizard/backend/logic/workers/service.py b/products/wizard/backend/logic/workers/service.pyindex eadcb2ff45e9..c0345cd38f46 100644--- a/products/wizard/backend/logic/workers/service.py+++ b/products/wizard/backend/logic/workers/service.py@@ -406,6 +406,7 @@ def _build_sandbox_config(request: WizardWorkerProvisionRequest, wizard_token: s"POSTHOG_API_URL": settings.SANDBOX_API_URL or settings.SITE_URL,"POSTHOG_PROJECT_ID": str(request.team_id),"POSTHOG_WIZARD_API_KEY": wizard_token,+ "POSTHOG_WIZARD_RUN_ID": str(request.run_id),"POSTHOG_TASK_RUN_ID": str(request.run_id),"POSTHOG_HANDOFF_OUTPUT_PATH": wizard_handoff_output_path(request.run_id),}diff --git a/products/wizard/backend/migrations/0009_wizardrun_tasks_snapshot_and_more.py b/products/wizard/backend/migrations/0009_wizardrun_tasks_snapshot_and_more.pynew file mode 100644index 000000000000..c5d33c5d6727--- /dev/null+++ b/products/wizard/backend/migrations/0009_wizardrun_tasks_snapshot_and_more.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.17 on 2026-09-22 18:31++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("wizard", "0008_create_wizard_worker"),+ ]++ operations = [+ migrations.AddField(+ model_name="wizardrun",+ name="tasks_snapshot",+ field=models.JSONField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="wizardrun",+ name="tasks_snapshot_updated_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/wizard/backend/migrations/max_migration.txt b/products/wizard/backend/migrations/max_migration.txtindex f08bf49c32fb..1db8be1ce7f3 100644--- a/products/wizard/backend/migrations/max_migration.txt+++ b/products/wizard/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_create_wizard_worker+0009_wizardrun_tasks_snapshot_and_morediff --git a/products/wizard/backend/models.py b/products/wizard/backend/models.pyindex 64926ab953eb..39abaacfc90e 100644--- a/products/wizard/backend/models.py+++ b/products/wizard/backend/models.py@@ -135,6 +135,13 @@ class WizardRun(UUIDModel, TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFicancellation_requested_at = models.DateTimeField(null=True, blank=True)cancellation_dispatched_at = models.DateTimeField(null=True, blank=True)+ # unified snapshot model of wizard tasks+ # we might want to have a log of task list changes,+ # so this fields holds what we consider to be the+ # latest and most correct snapshot of the task list+ tasks_snapshot = models.JSONField(null=True, blank=True)+ tasks_snapshot_updated_at = models.DateTimeField(null=True, blank=True)+class Meta(TeamScopedRootMixin.Meta):constraints = [models.UniqueConstraint(diff --git a/products/wizard/backend/observability/config.py b/products/wizard/backend/observability/config.pyindex 63d3e9950584..6da8cc58e836 100644--- a/products/wizard/backend/observability/config.py+++ b/products/wizard/backend/observability/config.py@@ -1,11 +1,9 @@-WIZARD_RUN_CREATED_EVENT = "wizard run created"+WIZARD_RUN_STARTED_EVENT = "wizard run started"WIZARD_RUN_DISPATCH_FINISHED_EVENT = "wizard run dispatch finished"WIZARD_RUN_STAGE_ENTERED_EVENT = "wizard run stage entered"-WIZARD_RUN_COMPLETED_EVENT = "wizard run completed"-WIZARD_RUN_FAILED_EVENT = "wizard run failed"-WIZARD_RUN_CANCELLED_EVENT = "wizard run cancelled"+WIZARD_RUN_FINISHED_EVENT = "wizard run finished"WIZARD_WORKER_USAGE_RECORDED_EVENT = "wizard worker usage recorded"-WIZARD_PULL_REQUEST_CREATED_EVENT = "wizard pull request created"+WIZARD_RUN_ARTIFACT_CREATED_EVENT = "wizard run artifact created"WIZARD_RUN_DURATION_BUCKETS = (30, 60, 120, 300, 600, 1200, 1800, 3600, 7200)WIZARD_WORKER_LIFETIME_BUCKETS = (30, 60, 120, 300, 600, 1200, 1800, 2700, 3600, 4500)diff --git a/products/wizard/backend/observability/events.py b/products/wizard/backend/observability/events.pyindex 774e1d6f3d78..982b3683c72e 100644--- a/products/wizard/backend/observability/events.py+++ b/products/wizard/backend/observability/events.py@@ -3,13 +3,19 @@ from uuid import NAMESPACE_URL, uuid5from posthog.models import Userfrom posthog.ph_client import ph_background_capture-from products.wizard.backend.facade.contracts import WizardRunDTO+from products.wizard.backend.facade.contracts import (+ WizardRunArtifactDTO,+ WizardRunDTO,+ WizardRunGitDiffArtifactDTO,+ WizardRunPullRequestArtifactDTO,+)from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunStagefrom products.wizard.backend.observability.config import (- WIZARD_PULL_REQUEST_CREATED_EVENT,- WIZARD_RUN_CREATED_EVENT,+ WIZARD_RUN_ARTIFACT_CREATED_EVENT,WIZARD_RUN_DISPATCH_FINISHED_EVENT,+ WIZARD_RUN_FINISHED_EVENT,WIZARD_RUN_STAGE_ENTERED_EVENT,+ WIZARD_RUN_STARTED_EVENT,WIZARD_WORKER_USAGE_RECORDED_EVENT,)from products.wizard.backend.observability.contracts import WizardRunDispatchOutcome, WizardWorkerUsageObservation@@ -19,7 +25,15 @@ type WizardEventProperties = dict[str, WizardEventProperty]def enqueue_run_created(run: WizardRunDTO) -> None:- _enqueue_run_event(run, WIZARD_RUN_CREATED_EVENT, "created")+ _enqueue_run_event(+ run,+ WIZARD_RUN_STARTED_EVENT,+ "started",+ {+ "location": "wizard_library",+ "program": run.program.name,+ },+ )def enqueue_dispatch_finished(run: WizardRunDTO, outcome: WizardRunDispatchOutcome) -> None:@@ -40,7 +54,7 @@ def enqueue_stage_entered(run: WizardRunDTO, stage: WizardRunStage) -> None:)-def enqueue_run_finished(run: WizardRunDTO, failure_stage: WizardRunStage | None, event: str) -> None:+def enqueue_run_finished(run: WizardRunDTO, failure_stage: WizardRunStage | None) -> None:properties: WizardEventProperties = {"status": run.status.value,"error_code": run.error_code,@@ -50,7 +64,7 @@ def enqueue_run_finished(run: WizardRunDTO, failure_stage: WizardRunStage | Noneif run.started_at is not None and run.finished_at is not None:properties["duration_seconds"] = max((run.finished_at - run.started_at).total_seconds(), 0)- _enqueue_run_event(run, event, f"terminal:{run.status.value}", properties)+ _enqueue_run_event(run, WIZARD_RUN_FINISHED_EVENT, f"terminal:{run.status.value}", properties)def enqueue_worker_usage(run: WizardRunDTO, usage: WizardWorkerUsageObservation) -> None:@@ -69,8 +83,17 @@ def enqueue_worker_usage(run: WizardRunDTO, usage: WizardWorkerUsageObservation))-def enqueue_pull_request_created(run: WizardRunDTO) -> None:- _enqueue_run_event(run, WIZARD_PULL_REQUEST_CREATED_EVENT, "artifact:pull_request")+def enqueue_artifact_created(run: WizardRunDTO, artifact: WizardRunArtifactDTO) -> None:+ if isinstance(artifact, WizardRunPullRequestArtifactDTO):+ properties: WizardEventProperties = {+ "type": "pull_request",+ "url": artifact.url,+ "name": f"Pull request #{artifact.number}",+ }+ elif isinstance(artifact, WizardRunGitDiffArtifactDTO):+ properties = {"type": "diff", "url": None, "name": "Git diff"}++ _enqueue_run_event(run, WIZARD_RUN_ARTIFACT_CREATED_EVENT, f"artifact:{artifact.id}", properties)def _enqueue_run_event(diff --git a/products/wizard/backend/observability/service.py b/products/wizard/backend/observability/service.pyindex fe1d0aadb581..fe632cceb79c 100644--- a/products/wizard/backend/observability/service.py+++ b/products/wizard/backend/observability/service.py@@ -9,11 +9,6 @@ from products.wizard.backend.facade.contracts import WizardRunArtifactDTO, Wizarfrom products.wizard.backend.facade.enums import WizardRunStatusfrom products.wizard.backend.logic.workers.contracts import WizardWorkerTelemetryfrom products.wizard.backend.observability import events, metrics-from products.wizard.backend.observability.config import (- WIZARD_RUN_CANCELLED_EVENT,- WIZARD_RUN_COMPLETED_EVENT,- WIZARD_RUN_FAILED_EVENT,-)from products.wizard.backend.observability.contracts import WizardRunDispatchOutcome, WizardWorkerCleanupOutcomefrom products.wizard.backend.observability.worker_usage import worker_usage_observation@@ -100,9 +95,15 @@ class WizardObservability:level=None,)- event = self._terminal_event(current.status)-- if event is None or previous.status == current.status:+ if (+ current.status+ not in {+ WizardRunStatus.COMPLETED,+ WizardRunStatus.FAILED,+ WizardRunStatus.CANCELLED,+ }+ or previous.status == current.status+ ):returnself._observe(@@ -114,7 +115,7 @@ class WizardObservability:"failure_stage": previous.stage.value if previous.stage is not None else None,},metric=partial(metrics.report_run_finished, current, previous.stage),- event=partial(events.enqueue_run_finished, current, previous.stage, event),+ event=partial(events.enqueue_run_finished, current, previous.stage),)def worker_usage_recorded(self, run: WizardRunDTO, telemetry: WizardWorkerTelemetry) -> None:@@ -162,7 +163,9 @@ class WizardObservability:name="wizard_artifact_created",context={**self._run_context(run), "artifact_type": artifact.artifact_type.value},metric=partial(metrics.report_artifact_created, artifact),+ event=partial(events.enqueue_artifact_created, run, artifact),metric_error="wizard_artifact_metric_failed",+ event_error="wizard_artifact_event_failed",)def pull_request_created(self, run: WizardRunDTO, artifact: WizardRunPullRequestArtifactDTO) -> None:@@ -175,7 +178,6 @@ class WizardObservability:"repository": artifact.repository,"pull_request_number": artifact.number,},- event=partial(events.enqueue_pull_request_created, run),)def worker_cleanup_finished(@@ -200,18 +202,6 @@ class WizardObservability:level=logging.WARNING,)- @staticmethod- def _terminal_event(status: WizardRunStatus) -> str | None:- match status:- case WizardRunStatus.COMPLETED:- return WIZARD_RUN_COMPLETED_EVENT- case WizardRunStatus.FAILED:- return WIZARD_RUN_FAILED_EVENT- case WizardRunStatus.CANCELLED:- return WIZARD_RUN_CANCELLED_EVENT- case _:- return None-@staticmethoddef _run_context(run: WizardRunDTO) -> dict[str, object]:return {diff --git a/products/wizard/backend/presentation/permissions.py b/products/wizard/backend/presentation/permissions.pyindex 4f42dad9a3e1..fe326bfde0ec 100644--- a/products/wizard/backend/presentation/permissions.py+++ b/products/wizard/backend/presentation/permissions.py@@ -2,11 +2,14 @@ from rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework.views import APIView-from posthog.auth import SessionAuthentication+from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthenticationclass WizardRunSessionAuthenticationRequired(BasePermission):message = "Sign in to use Wizard runs."def has_permission(self, request: Request, view: APIView) -> bool:+ if getattr(view, "action", None) in ("create", "partial_update"):+ if isinstance(request.successful_authenticator, OAuthAccessTokenAuthentication):+ return Truereturn isinstance(request.successful_authenticator, SessionAuthentication)diff --git a/products/wizard/backend/presentation/runs/pagination.py b/products/wizard/backend/presentation/runs/pagination.pyindex 2c206820737e..ed0a95ff0e64 100644--- a/products/wizard/backend/presentation/runs/pagination.py+++ b/products/wizard/backend/presentation/runs/pagination.py@@ -1,9 +1,11 @@+from rest_framework.exceptions import ValidationErrorfrom rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom products.wizard.backend.facade import api as wizard_facadefrom products.wizard.backend.facade.contracts import ListWizardRunsInput+from products.wizard.backend.facade.enums import WizardRunStatusfrom products.wizard.backend.presentation.runs.serializers import WizardRunSerializer@@ -15,7 +17,21 @@ class WizardRunPagination(LimitOffsetPagination):limit = self.get_limit(request)assert limit is not Noneoffset = self.get_offset(request)- page = wizard_facade.list_runs(ListWizardRunsInput(team_id=team_id, offset=offset, limit=limit))+ raw_status = request.query_params.get("status")+ try:+ statuses = (+ tuple(WizardRunStatus(value) for value in raw_status.split(",")) if raw_status is not None else ()+ )+ except ValueError as error:+ raise ValidationError({"status": "Invalid run status."}) from error+ page = wizard_facade.list_runs(+ ListWizardRunsInput(+ team_id=team_id,+ offset=offset,+ limit=limit,+ statuses=statuses,+ )+ )self.request = requestself.limit = limitself.offset = offsetdiff --git a/products/wizard/backend/presentation/runs/serializers.py b/products/wizard/backend/presentation/runs/serializers.pyindex 6a75315dd756..6e1d2bd6197d 100644--- a/products/wizard/backend/presentation/runs/serializers.py+++ b/products/wizard/backend/presentation/runs/serializers.py@@ -9,13 +9,16 @@ from products.wizard.backend.facade.contracts import (CreateWizardRunInput,GitRepositoryWorkspace,LocalFolderWorkspace,+ UpdateWizardRunTaskInput,WizardWorkspace,)from products.wizard.backend.facade.enums import (+ WIZARD_TASK_STATUS_CHOICES,WizardRunEnvironment,WizardRunErrorCode,WizardRunStage,WizardRunStatus,+ WizardTaskStatus,WizardWorkspaceType,)from products.wizard.backend.facade.errors import InvalidRepositoryError@@ -202,6 +205,69 @@ class WizardRunCreatorSerializer(serializers.Serializer):email = serializers.EmailField(read_only=True, help_text="Email address of the user who created the Wizard run.")+class UpdateWizardRunTaskSerializer(serializers.Serializer):+ name = serializers.CharField(+ max_length=255, help_text="Task name, unique within this run and stable across snapshots."+ )++ status = serializers.ChoiceField(+ choices=WIZARD_TASK_STATUS_CHOICES,+ help_text="Current task status reported by the setup agent.",+ )+++class UpdateWizardRunTaskListSerializer(serializers.Serializer):+ tasks: serializers.ListSerializer[dict[str, object]] = serializers.ListSerializer(+ child=UpdateWizardRunTaskSerializer(),+ max_length=100,+ help_text="Complete task snapshot. An empty list clears the run's tasks.",+ )++ def validate_tasks(self, value: list[dict[str, object]]) -> list[dict[str, object]]:+ names = [task["name"] for task in value]+ if len(set(names)) != len(names):+ raise serializers.ValidationError("Task names must be unique. Use a different name for each task.")+ return value++ def to_contract(self) -> tuple[UpdateWizardRunTaskInput, ...]:+ return tuple(+ UpdateWizardRunTaskInput(+ title=cast(str, task["name"]),+ status=WizardTaskStatus(cast(str, task["status"])),+ )+ for task in self.validated_data["tasks"]+ )+++class WizardRunTaskSerializer(serializers.Serializer):+ name = serializers.CharField(source="title", read_only=True, help_text="Task name, unique within this run.")++ status = serializers.ChoiceField(+ read_only=True,+ choices=WIZARD_TASK_STATUS_CHOICES,+ help_text="Current task status reported by the setup agent.",+ )++ created_at = serializers.DateTimeField(read_only=True, help_text="When the server first received this task.")+ started_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When the server first observed this task running."+ )+ completed_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When the server first observed this task completed."+ )+ failed_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When the server first observed this task failed."+ )++ error_message = serializers.CharField(+ read_only=True, allow_null=True, help_text="Task failure explanation, or null when none is available."+ )+++class WizardRunTaskListSerializer(serializers.Serializer):+ tasks = WizardRunTaskSerializer(many=True, read_only=True, help_text="Complete task list in snapshot order.")++class WizardRunSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Unique ID of the Wizard run.")team_id = serializers.IntegerField(read_only=True, help_text="Project that owns the Wizard run.")diff --git a/products/wizard/backend/presentation/runs/stream.py b/products/wizard/backend/presentation/runs/stream.pynew file mode 100644index 000000000000..2c5da8e4ae24--- /dev/null+++ b/products/wizard/backend/presentation/runs/stream.py@@ -0,0 +1,48 @@+import time+from collections.abc import AsyncGenerator+from uuid import UUID++import orjson++from posthog.models.scoping import team_scope+from posthog.sync import database_sync_to_async++from products.wizard.backend.facade import api as wizard_facade+from products.wizard.backend.presentation.runs.serializers import WizardRunSerializer, WizardRunTaskListSerializer+from products.wizard.backend.presentation.sessions import config+++def _read_run_state(team_id: int, run_id: UUID) -> bytes:+ with team_scope(team_id):+ run = wizard_facade.get_run(team_id, run_id)+ serialized = WizardRunSerializer(run).data+ state = {+ field: serialized[field]+ for field in ("status", "stage", "error_code", "error_message", "updated_at", "started_at", "finished_at")+ }+ state.update(WizardRunTaskListSerializer(run).data)+ return orjson.dumps(state)+++async def wizard_run_event_stream(team_id: int, run_id: UUID) -> AsyncGenerator[bytes]:+ started_at = time.monotonic()+ async with wizard_facade.subscribe_to_run_updates(team_id, run_id) as subscription:+ # Subscribe before reading so changes during the read remain queued on the Redis connection.+ yield (+ b"data: " + await database_sync_to_async(_read_run_state, thread_sensitive=False)(team_id, run_id) + b"\n\n"+ )+ last_heartbeat = time.monotonic()+ while time.monotonic() - started_at < config.SSE_MAX_DURATION_SECONDS:+ message = await subscription.get_message(timeout=config.SSE_POLL_TIMEOUT_SECONDS)+ now = time.monotonic()+ if message and message.get("type") == "message":+ yield (+ b"data: "+ + await database_sync_to_async(_read_run_state, thread_sensitive=False)(team_id, run_id)+ + b"\n\n"+ )+ last_heartbeat = now+ elif now - last_heartbeat >= config.SSE_HEARTBEAT_INTERVAL_SECONDS:+ yield b": ping\n\n"+ last_heartbeat = now+ yield b"event: end\ndata: reconnect\n\n"diff --git a/products/wizard/backend/presentation/runs/views.py b/products/wizard/backend/presentation/runs/views.pyindex 00f6adbd2629..adce55038cc3 100644--- a/products/wizard/backend/presentation/runs/views.py+++ b/products/wizard/backend/presentation/runs/views.py@@ -2,15 +2,19 @@ from typing import castfrom uuid import UUIDfrom django.conf import settings+from django.http import HttpResponse+from django.http.response import HttpResponseBase-from drf_spectacular.utils import OpenApiResponse, extend_schema+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import status, viewsetsfrom rest_framework.exceptions import NotFound, PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.auth import SessionAuthentication+from posthog.api.streaming import sse_streaming_response+from posthog.api.utils import action+from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthenticationfrom posthog.exceptions import Conflictfrom products.wizard.backend.facade import api as wizard_facade@@ -25,24 +29,39 @@ from products.wizard.backend.presentation.runs.errors import ()from products.wizard.backend.presentation.runs.pagination import WizardRunPaginationfrom products.wizard.backend.presentation.runs.serializers import (+ UpdateWizardRunTaskListSerializer,WizardRunCreateRequestSerializer,WizardRunErrorSerializer,WizardRunSerializer,WizardRunStatusUpdateRequestSerializer,+ WizardRunTaskListSerializer,)+from products.wizard.backend.presentation.runs.stream import wizard_run_event_stream+from products.wizard.backend.presentation.sessions.views import EventStreamRenderer, _wizard_sync_killswitch_enabledfrom products.wizard.backend.presentation.throttles import WizardRunCreateThrottle, WizardRunReadThrottleclass WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """+ API endpoints for managing Wizard runs. For browser–based access.+ """+permission_classes = [WizardRunSessionAuthenticationRequired]scope_object = "wizard_session"- scope_object_read_actions = ["list", "retrieve"]+ scope_object_read_actions = ["list", "retrieve", "stream"]scope_object_write_actions = ["create", "partial_update"]http_method_names = ["get", "post", "patch", "head", "options"]lookup_field = "run_id"lookup_value_regex = "[0-9a-fA-F-]{36}"pagination_class = WizardRunPagination+ def dangerously_get_required_scopes(self, request: Request, view: object) -> list[str] | None:+ if self.action in ("create", "partial_update") and isinstance(+ request.successful_authenticator, OAuthAccessTokenAuthentication+ ):+ return ["wizard_run:write"]+ return None+def get_throttles(self) -> list:if self.action == "create":return [WizardRunCreateThrottle()]@@ -50,6 +69,17 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@extend_schema(responses={200: WizardRunSerializer(many=True)},+ parameters=[+ OpenApiParameter(+ name="status",+ type=str,+ enum=[status.value for status in WizardRunStatus],+ many=True,+ style="form",+ explode=False,+ description="Filter by one or more comma-separated run statuses.",+ )+ ],description="List Wizard runs for this project, ordered from newest to oldest.",)def list(self, request: Request, *args: object, **kwargs: object) -> Response:@@ -73,8 +103,13 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer = WizardRunCreateRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)params = serializer.to_contract(team_id=self.team_id, created_by_id=cast(int, request.user.id))++ # TODO: if creating a local run, only allow the Wizard's client ID.+ # Users should not be allowed to create local runs.+if params.environment == WizardRunEnvironment.CLOUD:self._validate_cloud_creation(request)+try:result = wizard_facade.create_run_with_result(params)except WIZARD_RUN_CREATION_ERRORS as error:@@ -103,6 +138,19 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):run = self._get_run()return Response(WizardRunSerializer(run).data)+ @extend_schema(+ description="Stream the current run state and subsequent updates. Use EventSource to consume this endpoint.",+ responses={(200, "text/event-stream"): {"type": "string"}, 204: None},+ )+ @action(detail=True, methods=["get"], pagination_class=None, renderer_classes=[EventStreamRenderer])+ def stream(self, request: Request, *args: object, **kwargs: object) -> HttpResponseBase:+ if _wizard_sync_killswitch_enabled(str(getattr(request.user, "distinct_id", self.team_id))):+ return HttpResponse(status=204)+ run = self._get_run()+ if getattr(settings, "SERVER_GATEWAY_INTERFACE", "ASGI") != "ASGI":+ raise RuntimeError("wizard_runs.stream requires ASGI.")+ return sse_streaming_response(wizard_run_event_stream(self.team_id, run.id), endpoint="wizard_run")+@extend_schema(request=WizardRunStatusUpdateRequestSerializer,responses={@@ -167,3 +215,48 @@ class WizardRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise PermissionDenied("Only the user who started this Wizard run can update it.")return run+++class WizardRunTasksViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """+ API endpoints for managing Wizard run tasks. Access is scoped to the Wizard only.++ The Wizard should be the only client that can update the tasks of a run.+ """++ scope_object = "wizard_run"+ scope_object_read_actions = ["get_tasks"]+ scope_object_write_actions = ["tasks"]+ http_method_names = ["get", "put", "head", "options"]+ pagination_class = None+ lookup_field = "run_id"+ lookup_value_regex = "[0-9a-fA-F-]{36}"++ def get_throttles(self) -> list:+ return [WizardRunReadThrottle()]++ # PUT /projects/:projectId/wizard/runs/:runId/tasks+ @extend_schema(request=UpdateWizardRunTaskListSerializer, responses={204: None})+ @action(detail=True, methods=["put"], url_path="tasks")+ def tasks(self, request: Request, *args: object, **kwargs: object) -> Response:+ if not isinstance(request.successful_authenticator, OAuthAccessTokenAuthentication):+ raise PermissionDenied("Use the setup agent's OAuth credentials to update run tasks.")+ run = self._get_run()+ if run.created_by_id != request.user.id:+ raise PermissionDenied("Only the user who started this Wizard run can update it.")++ serializer = UpdateWizardRunTaskListSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ wizard_facade.update_run_task_list(self.team_id, run.id, serializer.to_contract())+ return Response(status=status.HTTP_204_NO_CONTENT)++ @extend_schema(responses={200: WizardRunTaskListSerializer})+ @tasks.mapping.get+ def get_tasks(self, request: Request, *args: object, **kwargs: object) -> Response:+ return Response(WizardRunTaskListSerializer(self._get_run()).data)++ def _get_run(self) -> WizardRunDTO:+ try:+ return wizard_facade.get_run(self.team_id, UUID(cast(str, self.kwargs["run_id"])))+ except WizardRunNotFoundError:+ raise NotFound("No Wizard run was found for this project.")diff --git a/products/wizard/backend/routes.py b/products/wizard/backend/routes.pyindex 3136ea64a0f3..e62caf065574 100644--- a/products/wizard/backend/routes.py+++ b/products/wizard/backend/routes.py@@ -2,19 +2,32 @@ from posthog.api.routing import RouterRegistryfrom products.wizard.backend.presentation.artifacts.views import WizardRunArtifactViewSetfrom products.wizard.backend.presentation.registry.views import WizardRegistryViewSet-from products.wizard.backend.presentation.runs.views import WizardRunViewSet+from products.wizard.backend.presentation.runs.views import WizardRunTasksViewSet, WizardRunViewSetfrom products.wizard.backend.presentation.sessions.views import WizardSessionViewSetdef register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"wizard/sessions", WizardSessionViewSet, "project_wizard_sessions", ["project_id"])++ # Wizard Runswizard_runs_router = routers.projects.register(r"wizard/runs", WizardRunViewSet, "project_wizard_runs", ["project_id"])++ routers.projects.register(+ r"wizard/runs",+ WizardRunTasksViewSet,+ "project_wizard_run_tasks",+ ["project_id"],+ )++ # Wizard Run Artifactswizard_runs_router.register(r"artifacts",WizardRunArtifactViewSet,"project_wizard_run_artifacts",["project_id", "run_id"],)++ # Wizard Registryrouters.projects.register(r"wizard/registry", WizardRegistryViewSet, "project_wizard_registry", ["project_id"])diff --git a/products/wizard/backend/tests/runs/test_cloud_worker.py b/products/wizard/backend/tests/runs/test_cloud_worker.pyindex 4582885c7b6d..07ba8d4e27a4 100644--- a/products/wizard/backend/tests/runs/test_cloud_worker.py+++ b/products/wizard/backend/tests/runs/test_cloud_worker.py@@ -98,7 +98,7 @@ def test_provision_worker_configures_wizard_environment(assert "GITHUB_TOKEN" not in config.environment_variablesassert config.environment_variables["POSTHOG_WIZARD_API_KEY"] == "wizard-secret"assert config.environment_variables["MCP_URL"] == "http://host.docker.internal:8787/mcp"- assert "POSTHOG_WIZARD_RUN_ID" not in config.environment_variables+ assert config.environment_variables["POSTHOG_WIZARD_RUN_ID"] == str(request.run_id)assert config.environment_variables["POSTHOG_TASK_RUN_ID"] == str(request.run_id)assert "POSTHOG_TASK_ID" not in config.environment_variablesassert config.environment_variables["POSTHOG_HANDOFF_OUTPUT_PATH"] == wizard_handoff_output_path(request.run_id)diff --git a/products/wizard/backend/tests/runs/test_lifecycle.py b/products/wizard/backend/tests/runs/test_lifecycle.pyindex 2103c137da5c..899e4b48b15d 100644--- a/products/wizard/backend/tests/runs/test_lifecycle.py+++ b/products/wizard/backend/tests/runs/test_lifecycle.py@@ -1,3 +1,5 @@+from datetime import UTC, datetime, timedelta+import pytestfrom unittest.mock import patch@@ -8,10 +10,63 @@ from products.wizard.backend.facade.contracts import (CreateWizardRunInput,GitRepositoryWorkspace,LocalFolderWorkspace,+ UpdateWizardRunTaskInput,WizardRunDTO,)-from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardRunErrorCode, WizardRunStatus+from products.wizard.backend.facade.enums import (+ WizardRunEnvironment,+ WizardRunErrorCode,+ WizardRunStatus,+ WizardTaskStatus,+)from products.wizard.backend.facade.errors import IllegalStatusTransitionError, WizardRunNotFoundError+from products.wizard.backend.logic.runs.lifecycle import _compute_task_list_derived_fields++[email protected]("status", tuple(WizardTaskStatus))+def test_task_snapshot_preserves_first_observed_timestamps(status: WizardTaskStatus) -> None:+ now = datetime(2026, 1, 1, tzinfo=UTC)+ tasks = (UpdateWizardRunTaskInput(title="Install SDK", status=status),)+ initial = _compute_task_list_derived_fields(tasks, (), now)+ repeated = _compute_task_list_derived_fields(tasks, initial, now + timedelta(minutes=1))+ assert repeated == initial+ assert initial[0].created_at == now+ assert initial[0].started_at == (now if status == WizardTaskStatus.RUNNING else None)+ assert initial[0].completed_at == (now if status == WizardTaskStatus.COMPLETED else None)+ assert initial[0].failed_at == (now if status == WizardTaskStatus.FAILED else None)+++def test_task_snapshots_round_trip_and_replace_in_order(team, user) -> None:+ run = _create_local_run(team.id, user.id)+ initial = wizard_facade.update_run_task_list(+ team.id,+ run.id,+ (+ UpdateWizardRunTaskInput(title="Install SDK", status=WizardTaskStatus.RUNNING),+ UpdateWizardRunTaskInput(title="Configure events", status=WizardTaskStatus.CREATED),+ UpdateWizardRunTaskInput(title="Remove me", status=WizardTaskStatus.CREATED),+ ),+ )+ updated = wizard_facade.update_run_task_list(+ team.id,+ run.id,+ (+ UpdateWizardRunTaskInput(title="Configure events", status=WizardTaskStatus.RUNNING),+ UpdateWizardRunTaskInput(title="Install SDK", status=WizardTaskStatus.COMPLETED),+ UpdateWizardRunTaskInput(title="Verify capture", status=WizardTaskStatus.FAILED),+ ),+ )+ assert wizard_facade.get_run(team.id, run.id).tasks == updated+ assert [task.title for task in updated] == ["Configure events", "Install SDK", "Verify capture"]+ assert updated[0].created_at == initial[1].created_at+ assert updated[0].started_at is not None+ assert updated[1].started_at == initial[0].started_at+ assert updated[1].completed_at is not None+ assert updated[2].failed_at is not None+ assert updated[2].started_at is None+ wizard_facade.update_run_task_list(team.id, run.id, ())+ assert wizard_facade.get_run(team.id, run.id).tasks == ()def _create_local_run(team_id: int, user_id: int) -> WizardRunDTO:diff --git a/products/wizard/backend/tests/runs/test_observability.py b/products/wizard/backend/tests/runs/test_observability.pyindex 99abf0897164..a7922a17a620 100644--- a/products/wizard/backend/tests/runs/test_observability.py+++ b/products/wizard/backend/tests/runs/test_observability.py@@ -480,3 +480,48 @@ def test_stage_event_has_deterministic_identity_and_run_properties(**({"task_run_id": str(run.id)} if environment == WizardRunEnvironment.CLOUD else {}),"stage": "provisioning",}+++def test_run_lifecycle_and_artifact_events_use_the_public_contract() -> None:+ run = _cloud_run()+ finished = replace(+ run,+ status=WizardRunStatus.COMPLETED,+ stage=None,+ started_at=run.created_at,+ finished_at=run.created_at + timedelta(minutes=1),+ )+ artifact = WizardRunGitDiffArtifactDTO(+ id=uuid4(),+ team_id=run.team_id,+ run_id=run.id,+ artifact_type=WizardRunArtifactType.GIT_DIFF,+ size_bytes=10,+ content_hash="hash",+ additions=1,+ removals=0,+ created_at=run.created_at,+ )++ with (+ patch.object(events, "ph_background_capture") as background_capture,+ patch.object(events.User.objects, "filter"),+ ):+ events.enqueue_run_created(run)+ events.enqueue_run_finished(finished, WizardRunStage.EXECUTING_WIZARD)+ events.enqueue_artifact_created(run, artifact)++ calls = background_capture.return_value.call_args_list+ assert [call.kwargs["event"] for call in calls] == [+ "wizard run started",+ "wizard run finished",+ "wizard run artifact created",+ ]+ assert calls[0].kwargs["properties"]["location"] == "wizard_library"+ assert calls[1].kwargs["properties"]["status"] == "completed"+ assert calls[1].kwargs["properties"]["duration_seconds"] == 60+ assert {key: calls[2].kwargs["properties"][key] for key in ("type", "url", "name")} == {+ "type": "diff",+ "url": None,+ "name": "Git diff",+ }diff --git a/products/wizard/backend/tests/runs/test_presentation.py b/products/wizard/backend/tests/runs/test_presentation.pyindex 74beaf2fdffc..c64c11400873 100644--- a/products/wizard/backend/tests/runs/test_presentation.py+++ b/products/wizard/backend/tests/runs/test_presentation.py@@ -135,6 +135,38 @@ class TestWizardRunViewSet(APIBaseTest):self.assertEqual(first.status_code, status.HTTP_200_OK)self.assertEqual(second.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ def test_list_runs_filters_by_status(self) -> None:+ run_ids = []+ for project_name in ("first-project", "second-project", "third-project"):+ response = self.client.post(+ self._url(),+ {+ "program_id": "posthog-integration",+ "environment": "local",+ "workspace": {"type": "local_folder", "project_name": project_name},+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ run_ids.append(response.json()["id"])++ WizardRun.objects.for_team(self.team.id).filter(id=run_ids[0]).update(status="running")+ WizardRun.objects.for_team(self.team.id).filter(id=run_ids[1]).update(status="completed")++ response = self.client.get(f"{self._url()}?status=created,running&limit=1")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 2)+ self.assertEqual([run["id"] for run in response.json()["results"]], [run_ids[2]])++ completed_response = self.client.get(f"{self._url()}?status=completed")+ self.assertEqual(completed_response.status_code, status.HTTP_200_OK)+ self.assertEqual(completed_response.json()["count"], 1)+ self.assertEqual([run["id"] for run in completed_response.json()["results"]], [run_ids[1]])++ invalid_response = self.client.get(f"{self._url()}?status=unknown")+ self.assertEqual(invalid_response.status_code, status.HTTP_400_BAD_REQUEST)+def test_create_requires_program_id(self) -> None:response = self.client.post(self._url(),diff --git a/products/wizard/backend/tests/runs/test_run_stream.py b/products/wizard/backend/tests/runs/test_run_stream.pynew file mode 100644index 000000000000..0e94c1253d85--- /dev/null+++ b/products/wizard/backend/tests/runs/test_run_stream.py@@ -0,0 +1,71 @@+import json++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from asgiref.sync import async_to_sync+from redis.exceptions import ConnectionError as RedisConnectionError++from posthog.sync import database_sync_to_async++from products.wizard.backend.facade import api as wizard_facade+from products.wizard.backend.facade.contracts import (+ CreateWizardRunInput,+ LocalFolderWorkspace,+ UpdateWizardRunTaskInput,+)+from products.wizard.backend.facade.enums import WizardRunEnvironment, WizardTaskStatus+from products.wizard.backend.presentation.runs.stream import wizard_run_event_stream+from products.wizard.backend.presentation.sessions import config++[email protected]_db(transaction=True)+def test_run_stream_reads_committed_state_and_closes_subscription(team, user) -> None:+ run = wizard_facade.create_run(+ CreateWizardRunInput(+ team_id=team.id,+ created_by_id=user.id,+ program_id="posthog-integration",+ environment=WizardRunEnvironment.LOCAL,+ workspace=LocalFolderWorkspace(project_name="example-project"),+ )+ )+ subscription = MagicMock()+ subscription.__aenter__ = AsyncMock(return_value=subscription)+ subscription.__aexit__ = AsyncMock()+ subscription.subscribe = AsyncMock()+ subscription.get_message = AsyncMock(return_value={"type": "message", "data": b"{}"})++ async def consume() -> None:+ stream = wizard_run_event_stream(team.id, run.id)+ try:+ initial = json.loads((await anext(stream)).removeprefix(b"data: "))+ assert initial["tasks"] == []+ assert initial["status"] == "running"+ assert "id" not in initial+ assert "team_id" not in initial++ await database_sync_to_async(wizard_facade.update_run_task_list, thread_sensitive=False)(+ team.id, run.id, (UpdateWizardRunTaskInput(title="Install SDK", status=WizardTaskStatus.RUNNING),)+ )+ updated = json.loads((await anext(stream)).removeprefix(b"data: "))+ assert updated["tasks"][0]["name"] == "Install SDK"+ assert updated["tasks"][0]["started_at"] is not None++ subscription.get_message.return_value = None+ with patch.object(config, "SSE_HEARTBEAT_INTERVAL_SECONDS", 0):+ assert await anext(stream) == b": ping\n\n"+ with patch.object(config, "SSE_MAX_DURATION_SECONDS", 0):+ assert await anext(stream) == b"event: end\ndata: reconnect\n\n"+ finally:+ await stream.aclose()++ with (+ patch("products.wizard.backend.logic.runs.pubsub.get_async_client") as async_client,+ patch("products.wizard.backend.logic.runs.pubsub.get_client") as client,+ ):+ async_client.return_value.pubsub.return_value = subscription+ client.return_value.publish.side_effect = RedisConnectionError("unavailable")+ async_to_sync(consume)()+ subscription.subscribe.assert_awaited_once_with(f"wizard_runs:team:{team.id}:run:{run.id}")+ subscription.__aexit__.assert_awaited_once()diff --git a/products/wizard/backend/tests/runs/test_serializers.py b/products/wizard/backend/tests/runs/test_serializers.pyindex f364d810cf2a..9adefac1624f 100644--- a/products/wizard/backend/tests/runs/test_serializers.py+++ b/products/wizard/backend/tests/runs/test_serializers.py@@ -2,7 +2,26 @@ import pytestfrom products.wizard.backend.facade.contracts import GitRepositoryWorkspace, LocalFolderWorkspacefrom products.wizard.backend.facade.enums import WizardRunEnvironment-from products.wizard.backend.presentation.runs.serializers import WizardRunCreateRequestSerializer+from products.wizard.backend.presentation.runs.serializers import (+ UpdateWizardRunTaskListSerializer,+ WizardRunCreateRequestSerializer,+)+++ "tasks",+ (+ [{"name": "Install SDK"}],+ [{"name": "Install SDK", "status": "unknown"}],+ [{"name": "Install SDK", "status": "created"}, {"name": "Install SDK", "status": "running"}],+ [{"name": " ", "status": "created"}],+ [{"name": str(i), "status": "created"} for i in range(101)],+ ),+)+def test_task_snapshot_rejects_invalid_tasks(tasks: list[dict[str, str]]) -> None:+ serializer = UpdateWizardRunTaskListSerializer(data={"tasks": tasks})+ assert not serializer.is_valid()+ assert "tasks" in serializer.errors@pytest.mark.parametrize(diff --git a/products/wizard/backend/tests/runs/test_task_presentation.py b/products/wizard/backend/tests/runs/test_task_presentation.pynew file mode 100644index 000000000000..5e805711ce0b--- /dev/null+++ b/products/wizard/backend/tests/runs/test_task_presentation.py@@ -0,0 +1,140 @@+from datetime import timedelta+from uuid import uuid4++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.utils import timezone++from parameterized import parameterized++from posthog.models import Team, User+from posthog.models.oauth import OAuthAccessToken, OAuthApplication++from products.wizard.backend.facade import api as wizard_facade+from products.wizard.backend.facade.contracts import CreateWizardRunInput, LocalFolderWorkspace+from products.wizard.backend.facade.enums import WizardRunEnvironment+++class TestWizardRunTasks(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.wizard_run = wizard_facade.create_run(+ CreateWizardRunInput(+ team_id=self.team.id,+ created_by_id=self.user.id,+ program_id="posthog-integration",+ environment=WizardRunEnvironment.LOCAL,+ workspace=LocalFolderWorkspace(project_name="example-project"),+ )+ )+ self.url = f"/api/projects/{self.team.id}/wizard/runs/{self.wizard_run.id}/tasks/"++ def _authenticate_agent(self, scope: str = "wizard_run:read wizard_run:write") -> None:+ application = OAuthApplication.objects.create(+ name="Wizard",+ user=self.user,+ organization=self.organization,+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ )+ token = f"pha_{uuid4().hex}"+ OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=token,+ expires=timezone.now() + timedelta(hours=1),+ scope=scope,+ scoped_teams=[self.team.id],+ )+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")++ def test_snapshot_write_read_and_validation(self) -> None:+ self._authenticate_agent()+ response = self.client.put(self.url, {"tasks": [{"name": "Install SDK"}]}, format="json")+ assert response.status_code == 400++ with (+ patch("products.wizard.backend.logic.runs.pubsub.get_client") as redis,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.put(+ self.url, {"tasks": [{"name": "Install SDK", "status": "running"}]}, format="json"+ )+ assert response.status_code == 204+ assert not response.content+ redis.return_value.publish.assert_not_called()+ assert redis.return_value.publish.call_args.args == (+ f"wizard_runs:team:{self.team.id}:run:{self.wizard_run.id}",+ b"{}",+ )++ data = self.client.get(self.url).json()+ assert set(data) == {"tasks"}+ assert data["tasks"] == [+ {+ "name": "Install SDK",+ "status": "running",+ "created_at": data["tasks"][0]["created_at"],+ "started_at": data["tasks"][0]["created_at"],+ "completed_at": None,+ "failed_at": None,+ "error_message": None,+ }+ ]+ response = self.client.put(self.url, {"tasks": []}, format="json")+ assert response.status_code == 204+ assert self.client.get(self.url).json() == {"tasks": []}++ @parameterized.expand([("session", 403), ("read_scope", 403), ("other_owner", 403), ("other_team", 404)])+ def test_task_write_permissions(self, case: str, expected: int) -> None:+ if case != "session":+ self._authenticate_agent("wizard_run:read" if case == "read_scope" else "wizard_run:write")+ if case in ("other_owner", "other_team"):+ owner = User.objects.create_and_join(self.organization, "[email protected]", None)+ team = self.team if case == "other_owner" else Team.objects.create(organization=self.organization)+ run = wizard_facade.create_run(+ CreateWizardRunInput(+ team_id=team.id,+ created_by_id=owner.id,+ program_id="posthog-integration",+ environment=WizardRunEnvironment.LOCAL,+ workspace=LocalFolderWorkspace(project_name="another-project"),+ )+ )+ self.url = f"/api/projects/{self.team.id}/wizard/runs/{run.id}/tasks/"+ response = self.client.put(self.url, {"tasks": []}, format="json")+ assert response.status_code == expected++ def test_agent_can_create_and_complete_local_run(self) -> None:+ self._authenticate_agent()+ response = self.client.post(+ f"/api/projects/{self.team.id}/wizard/runs/",+ {+ "program_id": "posthog-integration",+ "environment": "local",+ "workspace": {"type": "local_folder", "project_name": "another-project"},+ },+ format="json",+ )+ assert response.status_code == 201+ response = self.client.patch(+ f"/api/projects/{self.team.id}/wizard/runs/{response.json()['id']}/",+ {"status": "completed"},+ format="json",+ )+ assert response.status_code == 200+ assert response.json()["status"] == "completed"++ def test_run_stream_honors_killswitch(self) -> None:+ with patch(+ "products.wizard.backend.presentation.runs.views._wizard_sync_killswitch_enabled", return_value=True+ ):+ response = self.client.get(+ f"/api/projects/{self.team.id}/wizard/runs/{self.wizard_run.id}/stream/",+ HTTP_ACCEPT="text/event-stream",+ )+ assert response.status_code == 204diff --git a/products/wizard/frontend/WizardRunsScene.tsx b/products/wizard/frontend/WizardRunsScene.tsxindex 53a644d976db..b3f985c3319e 100644--- a/products/wizard/frontend/WizardRunsScene.tsx+++ b/products/wizard/frontend/WizardRunsScene.tsx@@ -25,7 +25,8 @@ import { userLogic } from 'scenes/userLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { WizardLibraryModal } from './library/WizardLibraryModal'-import { WizardRunDetailsDrawer } from './runs/WizardRunDetailsDrawer'+import { WizardRunDetailsDialog } from './runs/WizardRunDetailsDialog'+import { WizardRunSceneSyncDetailsDialog } from './runs/WizardRunSceneSyncDetailsDialog'import { WizardRunTable } from './runs/WizardRunTable'import { wizardLibraryLogic } from './wizardLibraryLogic'import { wizardRunDetailsLogic } from './wizardRunDetailsLogic'@@ -38,9 +39,11 @@ export const scene: SceneExport = {export function WizardRunsScene(): JSX.Element {const wizardUiEnabled = useFeatureFlag('WIZARD_UI_ENABLED')+ const runSyncEnabled = useFeatureFlag('WIZARD_RUN_SYNC', 'wizard-run')const { user } = useValues(userLogic)const {environment,+ currentProjectId,filteredRuns,hasRunFilters,refreshingRuns,@@ -51,7 +54,16 @@ export function WizardRunsScene(): JSX.Element {search,status,} = useValues(wizardRunsLogic)- const { clearRunFilters, refreshRuns, setEnvironment, setSearch, setStatus } = useActions(wizardRunsLogic)+ const {+ clearRunFilters,+ openWorkspace,+ refreshRun,+ refreshRuns,+ setEnvironment,+ setSearch,+ setStatus,+ trackPagination,+ } = useActions(wizardRunsLogic)const {commandCopied,@@ -84,21 +96,8 @@ export function WizardRunsScene(): JSX.Element {setRepository,} = useActions(wizardLibraryLogic)- const {- cancelRunRequestLoading,- runArtifactsError,- runDetailsError,- runDetailsLoading,- runDiffError,- runDiffLoading,- selectedRun,- selectedRunArtifacts,- selectedRunArtifactsInitialLoading,- selectedRunDiffArtifactId,- selectedRunDiffContent,- } = useValues(wizardRunDetailsLogic)- const { cancelRun, closeRunDiff, copyRunId, openRunDiff, refreshSelectedRun, selectRun } =- useActions(wizardRunDetailsLogic)+ const { cancelRunRequestLoading } = useValues(wizardRunDetailsLogic)+ const { cancelRun, copyRunId, selectRun } = useActions(wizardRunDetailsLogic)if (!wizardUiEnabled) {return <NotFound object="Wizard" caption="This feature is not enabled for your project." />@@ -208,9 +207,11 @@ export function WizardRunsScene(): JSX.Element {onOpenLibrary={openLibrary}onClearFilters={clearRunFilters}onRefreshRuns={refreshRuns}- onSelect={selectRun}- onRefreshRun={refreshRuns}+ onSelect={(run) => selectRun(run, 'wizard_datatable')}+ onRefreshRun={refreshRun}onCopyRunId={copyRunId}+ onOpenWorkspace={openWorkspace}+ onPaginate={trackPagination}onCancel={cancelRun}/>@@ -241,27 +242,11 @@ export function WizardRunsScene(): JSX.Element {onCopyCommand={copyCommand}/>- <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}- />+ {runSyncEnabled && currentProjectId ? (+ <WizardRunSceneSyncDetailsDialog projectId={String(currentProjectId)} onRunAgain={runAgain} />+ ) : (+ <WizardRunDetailsDialog onRunAgain={runAgain} />+ )}</SceneContent>)}diff --git a/products/wizard/frontend/generated/api.schemas.ts b/products/wizard/frontend/generated/api.schemas.tsindex 64be35f6b4b4..323c7298b8da 100644--- a/products/wizard/frontend/generated/api.schemas.ts+++ b/products/wizard/frontend/generated/api.schemas.ts@@ -366,6 +366,80 @@ export interface PaginatedWizardRunArtifactListApi {results: WizardRunArtifactApi[]}+/**+ * * `created` - created+ * * `running` - running+ * * `completed` - completed+ * * `failed` - failed+ */+export type WizardTaskStatusEnumApi = (typeof WizardTaskStatusEnumApi)[keyof typeof WizardTaskStatusEnumApi]++export const WizardTaskStatusEnumApi = {+ Created: 'created',+ Running: 'running',+ Completed: 'completed',+ Failed: 'failed',+} as const++export interface WizardRunTaskApi {+ /** Task name, unique within this run. */+ readonly name: string+ /** Current task status reported by the setup agent.+ *+ * * `created` - created+ * * `running` - running+ * * `completed` - completed+ * * `failed` - failed */+ readonly status: WizardTaskStatusEnumApi+ /** When the server first received this task. */+ readonly created_at: string+ /**+ * When the server first observed this task running.+ * @nullable+ */+ readonly started_at: string | null+ /**+ * When the server first observed this task completed.+ * @nullable+ */+ readonly completed_at: string | null+ /**+ * When the server first observed this task failed.+ * @nullable+ */+ readonly failed_at: string | null+ /**+ * Task failure explanation, or null when none is available.+ * @nullable+ */+ readonly error_message: string | null+}++export interface WizardRunTaskListApi {+ /** Complete task list in snapshot order. */+ readonly tasks: readonly WizardRunTaskApi[]+}++export interface UpdateWizardRunTaskApi {+ /**+ * Task name, unique within this run and stable across snapshots.+ * @maxLength 255+ */+ name: string+ /** Current task status reported by the setup agent.+ *+ * * `created` - created+ * * `running` - running+ * * `completed` - completed+ * * `failed` - failed */+ status: WizardTaskStatusEnumApi+}++export interface UpdateWizardRunTaskListApi {+ /** Complete task snapshot. An empty list clears the run's tasks. */+ tasks: UpdateWizardRunTaskApi[]+}+/*** The in-flight `wizard_ask` question. Typed rather than a free-form dict so the shape the* widget renders is enforced at the edge instead of trusted from the producer.@@ -587,8 +661,22 @@ export type WizardRunsListParams = {* The initial index from which to return the results.*/offset?: number+ /**+ * Filter by one or more comma-separated run statuses.+ */+ status?: WizardRunsListStatusItem[]}+export type WizardRunsListStatusItem = (typeof WizardRunsListStatusItem)[keyof typeof WizardRunsListStatusItem]++export const WizardRunsListStatusItem = {+ Cancelled: 'cancelled',+ Completed: 'completed',+ Created: 'created',+ Failed: 'failed',+ Running: 'running',+} as const+export type WizardRunsArtifactsListParams = {/*** Number of results to return per page.diff --git a/products/wizard/frontend/generated/api.ts b/products/wizard/frontend/generated/api.tsindex 026daf48eecc..96e9cc8b1038 100644--- a/products/wizard/frontend/generated/api.ts+++ b/products/wizard/frontend/generated/api.ts@@ -14,10 +14,12 @@ import type {PaginatedWizardRunListApi,PaginatedWizardSessionDTOListApi,PatchedWizardRunStatusUpdateRequestApi,+ UpdateWizardRunTaskListApi,UpsertWizardSessionRequestApi,WizardRegistryListParams,WizardRunApi,WizardRunCreateRequestApi,+ WizardRunTaskListApi,WizardRunsArtifactsListParams,WizardRunsListParams,WizardSessionDTOApi,@@ -199,6 +201,67 @@ export const wizardRunsArtifactsContentRetrieve = async (})}+export const getWizardRunsStreamRetrieveUrl = (projectId: string, runId: string) => {+ return `/api/projects/${projectId}/wizard/runs/${runId}/stream/`+}++/**+ * Stream the current run state and subsequent updates. Use EventSource to consume this endpoint.+ */+export const wizardRunsStreamRetrieve = async (+ projectId: string,+ runId: string,+ options?: RequestInit+): Promise<string | void> => {+ return apiMutator<string | void>(getWizardRunsStreamRetrieveUrl(projectId, runId), {+ ...options,+ method: 'GET',+ })+}++export const getWizardRunsTasksRetrieveUrl = (projectId: string, runId: string) => {+ return `/api/projects/${projectId}/wizard/runs/${runId}/tasks/`+}++/**+ * API endpoints for managing Wizard run tasks. Access is scoped to the Wizard only.+ *+ * The Wizard should be the only client that can update the tasks of a run.+ */+export const wizardRunsTasksRetrieve = async (+ projectId: string,+ runId: string,+ options?: RequestInit+): Promise<WizardRunTaskListApi> => {+ return apiMutator<WizardRunTaskListApi>(getWizardRunsTasksRetrieveUrl(projectId, runId), {+ ...options,+ method: 'GET',+ })+}++export const getWizardRunsTasksUpdateUrl = (projectId: string, runId: string) => {+ return `/api/projects/${projectId}/wizard/runs/${runId}/tasks/`+}++/**+ * API endpoints for managing Wizard run tasks. Access is scoped to the Wizard only.+ *+ * The Wizard should be the only client that can update the tasks of a run.+ */+export const wizardRunsTasksUpdate = async (+ projectId: string,+ runId: string,+ updateWizardRunTaskListApi: UpdateWizardRunTaskListApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getWizardRunsTasksUpdateUrl(projectId, runId), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(updateWizardRunTaskListApi),+ })+}+export const getWizardSessionsListUrl = (projectId: string, params?: WizardSessionsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/wizard/frontend/generated/api.zod.ts b/products/wizard/frontend/generated/api.zod.tsindex 1b0ae62d3768..1f3ecce7d992 100644--- a/products/wizard/frontend/generated/api.zod.ts+++ b/products/wizard/frontend/generated/api.zod.ts@@ -74,6 +74,34 @@ export const WizardRunsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Machine-readable reason the Wizard run failed.'),})+/**+ * API endpoints for managing Wizard run tasks. Access is scoped to the Wizard only.+ *+ * The Wizard should be the only client that can update the tasks of a run.+ */+export const wizardRunsTasksUpdateBodyTasksItemNameMax = 255++export const WizardRunsTasksUpdateBody = /* @__PURE__ */ zod.object({+ tasks: zod+ .array(+ zod.object({+ name: zod+ .string()+ .max(wizardRunsTasksUpdateBodyTasksItemNameMax)+ .describe('Task name, unique within this run and stable across snapshots.'),+ status: zod+ .enum(['created', 'running', 'completed', 'failed'])+ .describe(+ '\* `created` - created\n\* `running` - running\n\* `completed` - completed\n\* `failed` - failed'+ )+ .describe(+ 'Current task status reported by the setup agent.\n\n\* `created` - created\n\* `running` - running\n\* `completed` - completed\n\* `failed` - failed'+ ),+ })+ )+ .describe("Complete task snapshot. An empty list clears the run's tasks."),+})+/*** Upsert a wizard session. The `session_id` key is the idempotency anchor — reposting the same `session_id` replaces the existing row. Returns 201 on create, 200 on update.*/diff --git a/products/wizard/frontend/runs/WizardRunActionsMenu.tsx b/products/wizard/frontend/runs/WizardRunActionsMenu.tsxindex 57f0f3bd74cc..e03557ac0d17 100644--- a/products/wizard/frontend/runs/WizardRunActionsMenu.tsx+++ b/products/wizard/frontend/runs/WizardRunActionsMenu.tsx@@ -27,7 +27,7 @@ export function WizardRunActionsMenu({cancelling: booleanonView: (run: WizardRunApi) => voidonRefresh: (run: WizardRunApi) => void- onCopyRunId: (runId: string) => void+ onCopyRunId: (runId: string, location: 'bottom_button') => voidonCancel: (run: WizardRunApi) => void}): JSX.Element {return (@@ -53,7 +53,7 @@ export function WizardRunActionsMenu({<IconRefresh />{refreshing ? 'Refreshing…' : 'Refresh status'}</DropdownMenuItem>- <DropdownMenuItem onClick={() => onCopyRunId(run.id)}>+ <DropdownMenuItem onClick={() => onCopyRunId(run.id, 'bottom_button')}><IconCopy />Copy run ID</DropdownMenuItem>diff --git a/products/wizard/frontend/runs/WizardRunDetailsArtifacts.tsx b/products/wizard/frontend/runs/WizardRunDetailsArtifacts.tsxindex 74480585a0a7..ea8d3df62f67 100644--- a/products/wizard/frontend/runs/WizardRunDetailsArtifacts.tsx+++ b/products/wizard/frontend/runs/WizardRunDetailsArtifacts.tsx@@ -23,6 +23,7 @@ export function WizardRunDetailsArtifacts({error,loading,onOpenDiff,+ onArtifactClick,onRetry,}: {run: WizardRunApi@@ -30,6 +31,7 @@ export function WizardRunDetailsArtifacts({error: string | nullloading: booleanonOpenDiff: (artifact: WizardRunGitDiffArtifactApi) => void+ onArtifactClick: (artifact: WizardRunArtifactApi, source: 'artifacts_section') => voidonRetry: () => void}): JSX.Element {if (loading) {@@ -75,6 +77,7 @@ export function WizardRunDetailsArtifacts({variant="outline"className="hover:bg-fill-hover"render={<LinkPrimitive to={pullRequest.url} target="_blank" />}+ onClick={() => onArtifactClick(pullRequest, 'artifacts_section')}><ItemMedia><IconGithub />diff --git a/products/wizard/frontend/runs/WizardRunDetailsDialog.tsx b/products/wizard/frontend/runs/WizardRunDetailsDialog.tsxnew file mode 100644index 000000000000..22fb2c7964ee--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunDetailsDialog.tsx@@ -0,0 +1,63 @@+import { useActions, useValues } from 'kea'++import { userLogic } from 'scenes/userLogic'++import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'+import { wizardRunDetailsLogic } from '../wizardRunDetailsLogic'+import { WizardRunDetailsDrawer } from './WizardRunDetailsDrawer'++export function WizardRunDetailsDialog({+ onRunAgain,+ onClose,+ tasks = [],+}: {+ onRunAgain?: (run: WizardRunApi) => void+ onClose?: () => void+ tasks?: readonly WizardRunTaskApi[]+}): JSX.Element {+ const { user } = useValues(userLogic)+ const {+ cancelRunRequestLoading,+ runArtifactsError,+ runDetailsError,+ runDetailsLoading,+ runDiffError,+ runDiffLoading,+ selectedRun,+ selectedRunArtifacts,+ selectedRunArtifactsInitialLoading,+ selectedRunDiffArtifactId,+ selectedRunDiffContent,+ } = useValues(wizardRunDetailsLogic)+ const { artifactClicked, cancelRun, closeRunDiff, copyRunId, openRunDiff, refreshSelectedRun, selectRun } =+ useActions(wizardRunDetailsLogic)++ return (+ <WizardRunDetailsDrawer+ run={selectedRun}+ tasks={tasks}+ 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)+ onClose?.()+ }}+ onCloseDiff={closeRunDiff}+ onOpenDiff={openRunDiff}+ onArtifactClick={artifactClicked}+ onRefresh={refreshSelectedRun}+ onCopyRunId={copyRunId}+ onCancel={cancelRun}+ onRunAgain={onRunAgain}+ />+ )+}diff --git a/products/wizard/frontend/runs/WizardRunDetailsDrawer.tsx b/products/wizard/frontend/runs/WizardRunDetailsDrawer.tsxindex 9fce94dd5d65..b6d7c280aa0d 100644--- a/products/wizard/frontend/runs/WizardRunDetailsDrawer.tsx+++ b/products/wizard/frontend/runs/WizardRunDetailsDrawer.tsx@@ -15,12 +15,16 @@ import {Skeleton,} from '@posthog/quill-primitives'-import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { TZLabel } from 'lib/components/TZLabel'import { LinkPrimitive } from 'lib/lemon-ui/Link'import { lazyWithRetry } from 'lib/utils/retryImport'-import type { WizardRunApi, WizardRunArtifactApi, WizardRunGitDiffArtifactApi } from '../generated/api.schemas'+import type {+ WizardRunApi,+ WizardRunArtifactApi,+ WizardRunGitDiffArtifactApi,+ WizardRunTaskApi,+} from '../generated/api.schemas'import {WIZARD_LOCAL_RUNS_VISIBLE,wizardGithubRepositoryUrl,@@ -73,6 +77,7 @@ function RetryItem({export function WizardRunDetailsDrawer({run,+ tasks = [],artifacts,artifactsError,artifactsLoading,@@ -87,12 +92,14 @@ export function WizardRunDetailsDrawer({onClose,onCloseDiff,onOpenDiff,+ onArtifactClick,onRefresh,onCopyRunId,onCancel,onRunAgain,}: {run: WizardRunApi | null+ tasks?: readonly WizardRunTaskApi[]artifacts: WizardRunArtifactApi[]artifactsError: string | nullartifactsLoading: boolean@@ -108,9 +115,10 @@ export function WizardRunDetailsDrawer({onCloseDiff: () => voidonOpenDiff: (artifact: WizardRunGitDiffArtifactApi) => voidonRefresh: () => void- onCopyRunId: (runId: string) => void+ onArtifactClick: (artifact: WizardRunArtifactApi, source: 'button' | 'artifacts_section') => void+ onCopyRunId: (runId: string, location: 'bottom_button' | 'run_id_label') => voidonCancel: (run: WizardRunApi) => void- onRunAgain: (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')@@ -219,9 +227,14 @@ export function WizardRunDetailsDrawer({<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>+ <Button+ variant="link-muted"+ size="sm"+ onClick={() => onCopyRunId(run.id, 'run_id_label')}+ >+ {`${run.id.slice(0, 8)}…`}+ <IconCopy />+ </Button></dd></div></dl>@@ -246,17 +259,22 @@ export function WizardRunDetailsDrawer({error={artifactsError}loading={artifactsLoading}onOpenDiff={onOpenDiff}+ onArtifactClick={onArtifactClick}onRetry={onRefresh}/></section><section><h4 className="mb-4">Run progress</h4>- <WizardRunProgress run={run} />+ <WizardRunProgress run={run} tasks={tasks} /><div className="mt-4 flex items-center justify-between text-xs text-muted"><span>{wizardRunIsActive(run) ? (- 'Updates automatically.'+ run.environment === 'local' ? (+ 'Stop this run in the terminal where the Wizard is running.'+ ) : (+ 'Updates automatically.'+ )) : run.finished_at ? (<>{wizardRunTerminalLabel(run.status)}{' '}@@ -266,9 +284,10 @@ export function WizardRunDetailsDrawer({`${wizardRunTerminalLabel(run.status)}.`)}</span>- {run.status === 'failed' &&+ {onRunAgain &&+ run.status === 'failed' &&(WIZARD_LOCAL_RUNS_VISIBLE || run.environment === 'cloud') ? (- <Button size="sm" onClick={() => onRunAgain(run)}>+ <Button size="sm" onClick={() => onRunAgain?.(run)}>Run again</Button>) : wizardRunIsActive(run) ? (@@ -282,13 +301,14 @@ export function WizardRunDetailsDrawer({)}</DialogBody><DialogFooter className="flex-row justify-between">- <Button variant="outline" onClick={() => onCopyRunId(run.id)}>+ <Button variant="outline" onClick={() => onCopyRunId(run.id, 'bottom_button')}><IconCopy /> Copy run ID</Button>{pullRequest ? (<Buttonvariant="primary"render={<LinkPrimitive to={pullRequest.url} target="_blank" />}+ onClick={() => onArtifactClick(pullRequest, 'button')}>Open pull request</Button>@@ -296,9 +316,10 @@ export function WizardRunDetailsDrawer({<Button variant="destructive" onClick={() => onCancel(run)} loading={cancelling}><IconStopFilled /> Cancel run</Button>- ) : run.status === 'failed' &&+ ) : onRunAgain &&+ run.status === 'failed' &&(WIZARD_LOCAL_RUNS_VISIBLE || run.environment === 'cloud') ? (- <Button variant="primary" onClick={() => onRunAgain(run)}>+ <Button variant="primary" onClick={() => onRunAgain?.(run)}>Run again</Button>) : null}diff --git a/products/wizard/frontend/runs/WizardRunProgress.tsx b/products/wizard/frontend/runs/WizardRunProgress.tsxindex 55380d9d697a..8b717678ef65 100644--- a/products/wizard/frontend/runs/WizardRunProgress.tsx+++ b/products/wizard/frontend/runs/WizardRunProgress.tsx@@ -3,63 +3,17 @@ import { Spinner } from '@posthog/quill-primitives'import { TZLabel } from 'lib/components/TZLabel'-import type { WizardRunApi } from '../generated/api.schemas'-import { wizardRunFailureStage, wizardWorkspaceLabel } from '../wizardRunDisplay'+import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'+import type { WizardRunProgressState } from '../wizardRunDisplay'+import {+ wizardRunFailureStage,+ wizardRunProgressState,+ wizardRunStagePosition,+ 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 {+function ProgressIcon({ state }: { state: WizardRunProgressState }): JSX.Element {if (state === 'complete') {return <IconCheckCircle className="text-success" />}@@ -109,7 +63,13 @@ function RunLevelOutcome({ run }: { run: WizardRunApi }): JSX.Element | null {)}-export function WizardRunProgress({ run }: { run: WizardRunApi }): JSX.Element {+export function WizardRunProgress({+ run,+ tasks = [],+}: {+ run: WizardRunApi+ tasks?: readonly WizardRunTaskApi[]+}): JSX.Element {const runError = wizardRunErrorDetails(run.error_code, run.error_message)const failedAtStep = run.status === 'failed' && wizardRunFailureStage(run)const steps = [@@ -133,7 +93,7 @@ export function WizardRunProgress({ run }: { run: WizardRunApi }): JSX.Element {detail:run.status === 'completed'? 'Changes and artifacts are ready'- : stagePosition(run) === 3+ : wizardRunStagePosition(run) === 3? 'Saving changes and artifacts': 'Starts after the program finishes',},@@ -142,7 +102,7 @@ export function WizardRunProgress({ run }: { run: WizardRunApi }): JSX.Element {return (<div className="space-y-0">{steps.map((step, index) => {- const state = progressState(run, index)+ const state = wizardRunProgressState(run, index)return (<div key={step.title} className="relative flex gap-3 pb-5 last:pb-0">{index < steps.length - 1 && (@@ -154,6 +114,27 @@ export function WizardRunProgress({ run }: { run: WizardRunApi }): JSX.Element {<div className="min-w-0"><div className="font-semibold">{step.title}</div><div className="text-xs text-muted">{step.detail}</div>+ {index === 2 && run.status === 'running' && tasks.length > 0 && (+ <ul className="mt-2 space-y-1 text-xs">+ {tasks.map((task) => (+ <li key={task.name} className="flex items-center gap-2">+ <ProgressIcon+ state={+ task.status === 'completed'+ ? 'complete'+ : task.status === 'running'+ ? 'active'+ : task.status === 'failed'+ ? 'failed'+ : 'pending'+ }+ />+ <span className="break-words">{task.name}</span>+ <span className="sr-only">({task.status})</span>+ </li>+ ))}+ </ul>+ )}{state === 'failed' && (<div className="mt-1 space-y-1 text-xs"><div className="flex items-center gap-1 text-danger">diff --git a/products/wizard/frontend/runs/WizardRunSceneSyncDetailsDialog.tsx b/products/wizard/frontend/runs/WizardRunSceneSyncDetailsDialog.tsxnew file mode 100644index 000000000000..ec79c7c5d430--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSceneSyncDetailsDialog.tsx@@ -0,0 +1,19 @@+import { useValues } from 'kea'++import type { WizardRunApi } from '../generated/api.schemas'+import { wizardRunDetailsLogic } from '../wizardRunDetailsLogic'+import { WizardRunDetailsDialog } from './WizardRunDetailsDialog'+import { wizardRunSyncLogic } from './wizardRunSyncLogic'++export function WizardRunSceneSyncDetailsDialog({+ projectId,+ onRunAgain,+}: {+ projectId: string+ onRunAgain: (run: WizardRunApi) => void+}): JSX.Element {+ const { run, tasks } = useValues(wizardRunSyncLogic({ projectId }))+ const { selectedRun } = useValues(wizardRunDetailsLogic)++ return <WizardRunDetailsDialog tasks={selectedRun?.id === run?.id ? tasks : []} onRunAgain={onRunAgain} />+}diff --git a/products/wizard/frontend/runs/WizardRunSyncCard.stories.tsx b/products/wizard/frontend/runs/WizardRunSyncCard.stories.tsxnew file mode 100644index 000000000000..fb0a4947f06f--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSyncCard.stories.tsx@@ -0,0 +1,135 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'+import { WizardRunSyncCard } from './WizardRunSyncCard'+import { WizardRunSyncRunPicker } from './WizardRunSyncRunPicker'++const run: WizardRunApi = {+ id: '00000000-0000-4000-8000-000000000001',+ team_id: 1,+ created_by_id: 1,+ created_by: null,+ environment: 'cloud',+ workspace: { type: 'git_repository', repository: 'example/project' },+ program: {+ id: 'setup',+ name: 'PostHog setup',+ description: 'Set up analytics',+ wizard_version: '1.0.0',+ command: [],+ tags: [],+ required_programs: [],+ supported_environments: ['cloud'],+ },+ status: 'running',+ stage: 'executing_wizard',+ error_code: null,+ error_message: null,+ created_at: '2026-09-23T10:00:00Z',+ updated_at: '2026-09-23T10:01:00Z',+ started_at: '2026-09-23T10:00:30Z',+ finished_at: null,+ deadline_at: null,+}++const task = (name: string, status: WizardRunTaskApi['status']): WizardRunTaskApi => ({+ name,+ status,+ created_at: '2026-09-23T10:00:00Z',+ started_at: null,+ completed_at: null,+ failed_at: null,+ error_message: null,+})++const meta: Meta<typeof WizardRunSyncCard> = {+ title: 'Products/Wizard/Wizard run sync card',+ component: WizardRunSyncCard,+ parameters: { layout: 'fullscreen', testOptions: { waitForLoadersToDisappear: false } },+ decorators: [+ (Story) => (+ <div className="flex min-h-[640px] items-end justify-end bg-primary p-8">+ <Story />+ </div>+ ),+ ],+ args: {+ run,+ elapsedSeconds: 134,+ tasks: [+ task('Identify the existing analytics integration', 'completed'),+ task('Install the SDK and configure capture', 'running'),+ task('Verify events in PostHog', 'created'),+ ],+ onExpand: () => {},+ onExpandIcon: () => {},+ onClose: () => {},+ onHide: () => {},+ },+}++export default meta+type Story = StoryObj<typeof meta>++export const Running: Story = {}++export const MultipleRuns: Story = {+ render: function MultipleRunCard(args) {+ const runs = [+ run,+ {+ ...run,+ id: '00000000-0000-4000-8000-000000000002',+ environment: 'local' as const,+ workspace: { type: 'local_folder' as const, project_name: 'example-project' },+ created_at: '2026-09-23T09:30:00Z',+ },+ {+ ...run,+ id: '00000000-0000-4000-8000-000000000003',+ status: 'completed' as const,+ stage: null,+ finished_at: '2026-09-23T09:05:00Z',+ workspace: { type: 'git_repository' as const, repository: 'example/other-project' },+ created_at: '2026-09-23T09:00:00Z',+ },+ ]+ const [selectedRun, setSelectedRun] = useState<WizardRunApi>(run)++ return (+ <WizardRunSyncCard+ {...args}+ run={selectedRun}+ tasks={selectedRun.id === run.id ? args.tasks : []}+ runPicker={+ <WizardRunSyncRunPicker+ runs={runs}+ activeCount={2}+ currentRunId={selectedRun.id}+ onSelect={setSelectedRun}+ onOpen={() => {}}+ />+ }+ />+ )+ },+}++export const LocalRunning: Story = {+ args: {+ run: {+ ...run,+ environment: 'local',+ workspace: { type: 'local_folder', project_name: 'example-project' },+ stage: null,+ },+ },+}++export const Completed: Story = {+ args: {+ run: { ...run, status: 'completed', stage: null },+ tasks: [task('Install the SDK and configure capture', 'running')],+ },+}diff --git a/products/wizard/frontend/runs/WizardRunSyncCard.test.tsx b/products/wizard/frontend/runs/WizardRunSyncCard.test.tsxnew file mode 100644index 000000000000..080f941ae202--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSyncCard.test.tsx@@ -0,0 +1,72 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'+import { WizardRunSyncCard } from './WizardRunSyncCard'+import { WizardRunSyncRunPicker } from './WizardRunSyncRunPicker'++const run = {+ status: 'running',+ stage: 'executing_wizard',+ program: { name: 'PostHog setup' },+ workspace: { type: 'local_folder', project_name: 'example-project' },+ environment: 'local',+} as WizardRunApi++const tasks = [{ name: 'Install the SDK', status: 'running' }] as WizardRunTaskApi[]++describe('WizardRunSyncCard', () => {+ afterEach(cleanup)++ it('shows the current task only during the running stage', () => {+ const props = {+ run,+ tasks,+ elapsedSeconds: 10,+ onExpand: jest.fn(),+ onExpandIcon: jest.fn(),+ onClose: jest.fn(),+ onHide: jest.fn(),+ }+ const { rerender } = render(<WizardRunSyncCard {...props} />)++ expect(screen.getByText('Install the SDK')).toBeTruthy()++ rerender(<WizardRunSyncCard {...props} run={{ ...run, stage: 'creating_artifacts' }} />)+ expect(screen.queryByText('Install the SDK')).toBeNull()++ rerender(<WizardRunSyncCard {...props} run={{ ...run, status: 'completed', stage: null }} />)+ expect(screen.getByText('Completed successfully')).toBeTruthy()+ expect(screen.queryByText('Install the SDK')).toBeNull()+ })++ it('switches to a different run without restarting the selected run', () => {+ const currentRun = { ...run, id: 'current', created_at: '2026-01-01T10:00:00Z' }+ const otherRun = {+ ...currentRun,+ id: 'other',+ status: 'completed' as const,+ workspace: { type: 'local_folder' as const, project_name: 'other-project' },+ }+ const onSelect = jest.fn()+ render(+ <WizardRunSyncRunPicker+ runs={[currentRun, otherRun]}+ activeCount={1}+ currentRunId={currentRun.id}+ onSelect={onSelect}+ onOpen={jest.fn()}+ />+ )++ const trigger = screen.getByLabelText('Switch Wizard run, 2 recent runs, 1 active runs')+ fireEvent.click(trigger)+ expect(screen.getByText('Completed')).toBeTruthy()+ expect(screen.getByText('In progress')).toBeTruthy()+ fireEvent.click(screen.getByText('example-project'))+ expect(onSelect).not.toHaveBeenCalled()++ fireEvent.click(trigger)+ fireEvent.click(screen.getByText('other-project'))+ expect(onSelect).toHaveBeenCalledWith(otherRun)+ })+})diff --git a/products/wizard/frontend/runs/WizardRunSyncCard.tsx b/products/wizard/frontend/runs/WizardRunSyncCard.tsxnew file mode 100644index 000000000000..d5a78965bf1a--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSyncCard.tsx@@ -0,0 +1,155 @@+import type { ReactNode } from 'react'++import { IconCheckCircle, IconCloud, IconExpand45, IconLaptop, IconWarning, IconX } from '@posthog/icons'+import { LemonButton, LemonMenu, Spinner } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'+import { formatElapsed } from 'scenes/onboarding/shared/wizard-sync/helpers'++import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'+import type { WizardRunProgressState } from '../wizardRunDisplay'+import {+ wizardRunCurrentState,+ wizardRunProgressState,+ wizardRunStagePosition,+ wizardWorkspaceLabel,+} from '../wizardRunDisplay'++function RunStatusGlyph({ status }: { status: WizardRunApi['status'] }): JSX.Element {+ if (status === 'completed') {+ return <IconCheckCircle className="shrink-0 text-xl text-success" />+ }+ if (status === 'failed' || status === 'cancelled') {+ return <IconWarning className="shrink-0 text-xl text-danger" />+ }+ return <Spinner className="shrink-0 text-xl text-accent" textColored />+}++function pipClass(state: WizardRunProgressState): string {+ switch (state) {+ case 'complete':+ return 'bg-success'+ case 'active':+ return 'bg-accent animate-pulse'+ case 'failed':+ return 'bg-danger'+ default:+ return 'bg-border'+ }+}++export function WizardRunSyncCard({+ run,+ tasks,+ elapsedSeconds,+ onExpand,+ onExpandIcon,+ onClose,+ onHide,+ runPicker,+}: {+ run: WizardRunApi+ tasks: readonly WizardRunTaskApi[]+ elapsedSeconds: number+ onExpand: () => void+ onExpandIcon: () => void+ onClose: () => void+ onHide: () => void+ runPicker?: ReactNode+}): JSX.Element {+ const currentTask =+ run.status === 'running' && wizardRunStagePosition(run) === 2+ ? tasks.find((task) => task.status === 'running')+ : undefined+ const currentState = wizardRunCurrentState(run)+ const states = [0, 1, 2, 3].map((step) => wizardRunProgressState(run, step))+ const completed = states.filter((state) => state === 'complete').length+ const workspace = wizardWorkspaceLabel(run)++ return (+ <div+ className="w-[340px] max-w-full overflow-hidden rounded-xl border border-primary bg-surface-primary shadow-xl shadow-black/10"+ role="status"+ aria-live="polite"+ data-attr="wizard-run-sync-card"+ >+ {runPicker && <div className="border-b border-primary px-2 py-1">{runPicker}</div>}+ <button+ type="button"+ onClick={onExpand}+ aria-label="Expand Wizard run details"+ className="flex w-full cursor-pointer flex-col gap-2.5 px-3.5 py-3 text-left transition-colors hover:bg-fill-highlight-50"+ >+ <div className="flex items-center gap-2.5">+ <RunStatusGlyph status={run.status} />+ <div className="min-w-0 flex-1">+ <p+ className={cn(+ 'm-0 truncate text-sm font-semibold ph-no-capture',+ run.status === 'completed'+ ? 'text-success'+ : run.status === 'failed' || run.status === 'cancelled'+ ? 'text-danger'+ : 'text-accent'+ )}+ title={currentTask?.name}+ >+ {currentTask?.name ?? currentState}+ </p>+ <p className="m-0 truncate text-xs text-muted">+ {currentTask ? currentState : run.program.name}+ </p>+ </div>+ <span className="shrink-0 text-xs tabular-nums text-muted">{formatElapsed(elapsedSeconds)}</span>+ </div>+ <div className="flex items-center gap-2">+ <div className="flex w-full items-center gap-1" aria-hidden="true">+ {states.map((state, index) => (+ <span key={index} className={cn('h-1 flex-1 rounded-full', pipClass(state))} />+ ))}+ </div>+ <span className="shrink-0 text-xs tabular-nums text-muted">+ {completed}/{states.length}+ </span>+ </div>+ </button>+ <div className="flex items-center justify-between gap-2 border-t border-primary px-3.5 py-2">+ <span className="flex min-w-0 items-center gap-1 text-xs text-muted ph-no-capture">+ {run.environment === 'cloud' ? (+ <IconCloud className="shrink-0" />+ ) : (+ <IconLaptop className="shrink-0" />+ )}+ <span className="shrink-0">{run.environment === 'cloud' ? 'Cloud run' : 'Local run'}</span>+ <span aria-hidden="true">·</span>+ <span className="truncate" title={workspace}>+ {workspace}+ </span>+ </span>+ <div className="flex shrink-0 items-center gap-1">+ <LemonButton+ size="xsmall"+ icon={<IconExpand45 />}+ onClick={onExpandIcon}+ tooltip="See all the details"+ aria-label="Expand"+ />+ <LemonMenu+ items={[+ { label: 'Close', onClick: onClose },+ { label: "Don't show this run again", onClick: onHide },+ ]}+ placement="top-end"+ >+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ tooltip="Close options"+ aria-label="Close options"+ />+ </LemonMenu>+ </div>+ </div>+ </div>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunSyncDetailsDialog.tsx b/products/wizard/frontend/runs/WizardRunSyncDetailsDialog.tsxnew file mode 100644index 000000000000..691efce50291--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSyncDetailsDialog.tsx@@ -0,0 +1,28 @@+import { useActions, useMountedLogic } from 'kea'+import { useEffect } from 'react'++import type { WizardRunApi, WizardRunTaskApi } from '../generated/api.schemas'+import { type WizardRunDetailSource, wizardRunDetailsLogic } from '../wizardRunDetailsLogic'+import { WizardRunDetailsDialog } from './WizardRunDetailsDialog'++export function WizardRunSyncDetailsDialog({+ run,+ tasks,+ source,+ onClose,+}: {+ run: WizardRunApi+ tasks: readonly WizardRunTaskApi[]+ source: WizardRunDetailSource+ onClose: () => void+}): JSX.Element {+ useMountedLogic(wizardRunDetailsLogic)+ const { selectRun } = useActions(wizardRunDetailsLogic)++ useEffect(() => {+ selectRun(run, source)+ return () => selectRun(null)+ }, [run, selectRun, source])++ return <WizardRunDetailsDialog tasks={tasks} onClose={onClose} />+}diff --git a/products/wizard/frontend/runs/WizardRunSyncFab.tsx b/products/wizard/frontend/runs/WizardRunSyncFab.tsxnew file mode 100644index 000000000000..509a609b9722--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSyncFab.tsx@@ -0,0 +1,13 @@+import { useValues } from 'kea'++import { projectLogic } from 'scenes/projectLogic'++import { WizardRunSyncProject } from './WizardRunSyncProject'++export function WizardRunSyncFab(): JSX.Element | null {+ const { currentProjectId } = useValues(projectLogic)++ return currentProjectId ? (+ <WizardRunSyncProject key={currentProjectId} projectId={String(currentProjectId)} />+ ) : null+}diff --git a/products/wizard/frontend/runs/WizardRunSyncProject.tsx b/products/wizard/frontend/runs/WizardRunSyncProject.tsxnew file mode 100644index 000000000000..4490ea5fb553--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSyncProject.tsx@@ -0,0 +1,83 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useState } from 'react'++import { lemonToast } from '@posthog/lemon-ui'++import { useInterval } from 'lib/hooks/useInterval'+import { elapsedSecondsFrom } from 'lib/utils/datetime'+import { sceneLogic } from 'scenes/sceneLogic'++import type { WizardRunApi } from '../generated/api.schemas'+import { wizardRunDetailsLogic } from '../wizardRunDetailsLogic'+import type { WizardRunDetailSource } from '../wizardRunDetailsLogic'+import { wizardRunIsActive } from '../wizardRunDisplay'+import { WizardRunSyncCard } from './WizardRunSyncCard'+import { WizardRunSyncDetailsDialog } from './WizardRunSyncDetailsDialog'+import { wizardRunSyncLogic } from './wizardRunSyncLogic'+import { WizardRunSyncRunPicker } from './WizardRunSyncRunPicker'++export function WizardRunSyncProject({ projectId }: { projectId: string }): JSX.Element {+ const logic = wizardRunSyncLogic({ projectId })+ useMountedLogic(logic)+ const { activeCount, visibleRuns, closedRunIds, dismissedRunIds, run, tasks } = useValues(logic)+ const { closeRun, dismissRun, expandFab, selectRun: selectSyncRun } = useActions(logic)+ const { sceneKey } = useValues(sceneLogic)+ const [dialogRun, setDialogRun] = useState<{ run: WizardRunApi; source: WizardRunDetailSource } | null>(null)+ const [now, setNow] = useState(Date.now)+ const runHidden = run && (closedRunIds.includes(run.id) || dismissedRunIds.includes(run.id))+ useInterval(() => setNow(Date.now()), run && !runHidden && wizardRunIsActive(run) ? 1000 : null)++ const endMs = run?.finished_at ? new Date(run.finished_at).getTime() : now+ const elapsedSeconds = run ? elapsedSecondsFrom(run.started_at ?? run.created_at, endMs) : 0++ const openDetails = (source: WizardRunDetailSource): void => {+ if (!run) {+ return+ }+ if (sceneKey === 'wizardRuns') {+ wizardRunDetailsLogic.actions.selectRun(run, source)+ } else {+ setDialogRun({ run, source })+ }+ }++ return (+ <>+ {run && !runHidden && (+ <div className="fixed bottom-5 right-5 z-[60] max-w-[calc(100vw-2.5rem)]">+ <WizardRunSyncCard+ run={run}+ tasks={tasks}+ elapsedSeconds={elapsedSeconds}+ runPicker={+ (activeCount > 1 || visibleRuns.length > 1) && (+ <WizardRunSyncRunPicker+ runs={visibleRuns}+ activeCount={activeCount}+ currentRunId={run.id}+ onSelect={selectSyncRun}+ onOpen={() => expandFab(visibleRuns.length)}+ />+ )+ }+ onExpand={() => openDetails('fab_click')}+ onExpandIcon={() => openDetails('fab_expand_icon_click')}+ onClose={() => closeRun(run.id)}+ onHide={() => {+ dismissRun(run.id)+ lemonToast.info('You can still follow this run on the Wizard page.')+ }}+ />+ </div>+ )}+ {dialogRun && (+ <WizardRunSyncDetailsDialog+ run={dialogRun.run}+ tasks={dialogRun.run.id === run?.id ? tasks : []}+ source={dialogRun.source}+ onClose={() => setDialogRun(null)}+ />+ )}+ </>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunSyncRunPicker.tsx b/products/wizard/frontend/runs/WizardRunSyncRunPicker.tsxnew file mode 100644index 000000000000..276af44bc02e--- /dev/null+++ b/products/wizard/frontend/runs/WizardRunSyncRunPicker.tsx@@ -0,0 +1,64 @@+import { IconCheck, IconChevronDown, IconCloud, IconLaptop } from '@posthog/icons'+import { LemonButton, LemonMenu, type LemonMenuItems } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import type { WizardRunApi } from '../generated/api.schemas'+import { wizardRunIsActive, wizardRunTerminalLabel, wizardWorkspaceLabel } from '../wizardRunDisplay'++export function WizardRunSyncRunPicker({+ runs,+ activeCount,+ currentRunId,+ onSelect,+ onOpen,+}: {+ runs: readonly WizardRunApi[]+ activeCount: number+ currentRunId: string+ onSelect: (run: WizardRunApi) => void+ onOpen: () => void+}): JSX.Element {+ const currentIndex = runs.findIndex((run) => run.id === currentRunId)+ const items: LemonMenuItems = runs.map((run) => ({+ label: (+ <span className="block min-w-0 text-left ph-no-capture">+ <span className="block truncate font-medium">{wizardWorkspaceLabel(run)}</span>+ <span className="block text-xs text-muted">+ {wizardRunIsActive(run) ? 'In progress' : wizardRunTerminalLabel(run.status)}+ </span>+ <span className="block truncate text-xs text-muted">+ {run.program.name} ·{' '}+ {new Date(run.created_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}+ </span>+ </span>+ ),+ icon: run.environment === 'cloud' ? <IconCloud /> : <IconLaptop />,+ sideIcon: run.id === currentRunId ? <IconCheck aria-label="Selected run" /> : undefined,+ active: run.id === currentRunId,+ onClick: (): void => {+ if (run.id !== currentRunId) {+ onSelect(run)+ }+ },+ }))++ items.push({ label: 'View all runs', to: urls.wizardRuns() })++ return (+ <LemonMenu items={items} matchWidth placement="top-end">+ <LemonButton+ size="xsmall"+ fullWidth+ sideIcon={<IconChevronDown />}+ aria-label={`Switch Wizard run, ${runs.length} recent runs, ${activeCount} active runs`}+ // Keep the analytics selector stable when the picker layout changes.+ data-attr="wizard-run-sync-stack"+ onClick={onOpen}+ >+ <span>{currentIndex >= 0 ? `Run ${currentIndex + 1} of ${runs.length}` : 'Recent runs'}</span>+ {activeCount > 0 && <span className="ml-auto text-muted">{`${activeCount} active`}</span>}+ </LemonButton>+ </LemonMenu>+ )+}diff --git a/products/wizard/frontend/runs/WizardRunTable.tsx b/products/wizard/frontend/runs/WizardRunTable.tsxindex d2f7a994e6d7..031962007ba1 100644--- a/products/wizard/frontend/runs/WizardRunTable.tsx+++ b/products/wizard/frontend/runs/WizardRunTable.tsx@@ -44,6 +44,8 @@ export function WizardRunTable({onSelect,onRefreshRun,onCopyRunId,+ onOpenWorkspace,+ onPaginate,onCancel,}: {runs: WizardRunApi[]@@ -59,7 +61,9 @@ export function WizardRunTable({onRefreshRuns: () => voidonSelect: (run: WizardRunApi) => voidonRefreshRun: (run: WizardRunApi) => void- onCopyRunId: (runId: string) => void+ onCopyRunId: (runId: string, location: 'bottom_button') => void+ onOpenWorkspace: (run: WizardRunApi, url: string) => void+ onPaginate: (page: number, nextPage: number) => voidonCancel: (run: WizardRunApi) => void}): JSX.Element {const columns: DataTableProps<WizardRunApi, unknown>['columns'] = [@@ -88,15 +92,19 @@ export function WizardRunTable({cell: ({ row }) => {const run = row.originalif (run.workspace.type === 'git_repository') {+ const url = wizardGithubRepositoryUrl(run.workspace.repository)return (<Buttonvariant="link-muted"size="sm"render={<LinkPrimitive- to={wizardGithubRepositoryUrl(run.workspace.repository)}+ to={url}target="_blank"- onClick={(event) => event.stopPropagation()}+ onClick={(event) => {+ event.stopPropagation()+ onOpenWorkspace(run, url)+ }}/>}>@@ -106,8 +114,8 @@ export function WizardRunTable({)}return (- <Text size="sm" className="flex items-center gap-1">- <IconFolder />+ <Text size="xs" className="flex h-6 items-center gap-1 px-2">+ <IconFolder className="size-3" />{wizardWorkspaceLabel(run)}</Text>)@@ -244,6 +252,7 @@ export function WizardRunTable({pageSize={25}fullWidthonRowClick={onSelect}+ onPageChange={onPaginate}/></Card>)}diff --git a/products/wizard/frontend/runs/wizardRunSyncLogic.test.ts b/products/wizard/frontend/runs/wizardRunSyncLogic.test.tsnew file mode 100644index 000000000000..bb7611111e43--- /dev/null+++ b/products/wizard/frontend/runs/wizardRunSyncLogic.test.ts@@ -0,0 +1,243 @@+import { installMockEventSource, MockEventSource } from 'lib/wizard-sync/eventSource.mock'++import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { initKeaTests } from '~/test/init'++import { wizardRunsList } from '../generated/api'+import type { WizardRunApi } from '../generated/api.schemas'+import { wizardRunSyncLogic } from './wizardRunSyncLogic'++jest.mock('../generated/api', () => ({+ wizardRunsList: jest.fn(),+ getWizardRunsStreamRetrieveUrl: (projectId: string, runId: string) =>+ `/api/projects/${projectId}/wizard/runs/${runId}/stream/`,+}))++const mockWizardRunsList = wizardRunsList as jest.Mock++function mockRunPages(+ activePage: { count: number; results: WizardRunApi[] },+ completedRuns: WizardRunApi[] = []+): void {+ mockWizardRunsList.mockImplementation((_projectId, { status }) =>+ Promise.resolve(+ status.includes('completed') ? { count: completedRuns.length, results: completedRuns } : activePage+ )+ )+}++function run(id: string): WizardRunApi {+ return { id, status: 'running', stage: 'executing_wizard' } as WizardRunApi+}++describe('wizardRunSyncLogic', () => {+ let restoreEventSource: () => void+ let logic: ReturnType<typeof wizardRunSyncLogic.build>++ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ jest.spyOn(posthog, 'capture').mockClear()+ restoreEventSource = installMockEventSource()+ mockWizardRunsList.mockReset()+ mockRunPages({ count: 2, results: [run('newer')] })+ logic = wizardRunSyncLogic({ projectId: '1' })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ restoreEventSource()+ jest.restoreAllMocks()+ })++ it('streams only the newest active run and switches when it changes', async () => {+ await expectLogic(logic).toFinishAllListeners()++ expect(mockWizardRunsList).toHaveBeenCalledWith('1', { status: ['created', 'running'], limit: 5 })+ expect(logic.values.activeCount).toBe(2)+ expect(logic.values.run?.id).toBe('newer')+ expect(MockEventSource.instances).toHaveLength(1)++ const firstStream = MockEventSource.last()+ firstStream.emitMessage(+ JSON.stringify({+ status: 'running',+ stage: 'executing_wizard',+ tasks: [{ name: 'Install SDK', status: 'running' }],+ })+ )+ expect(logic.values.tasks).toEqual([{ name: 'Install SDK', status: 'running' }])++ mockRunPages({ count: 1, results: [run('older')] })+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()++ expect(firstStream.readyState).toBe(MockEventSource.CLOSED)+ expect(MockEventSource.instances).toHaveLength(2)+ expect(MockEventSource.last().url).toBe('/api/projects/1/wizard/runs/older/stream/')+ expect(logic.values.tasks).toEqual([])+ })++ it('keeps a selected run when it completes and lets another active run be selected', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const newerStream = MockEventSource.last()+ const older = run('older')+ mockRunPages({ count: 2, results: [run('newer'), older] })+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.selectRun(older)+ expect(logic.values.run?.id).toBe('older')+ expect(newerStream.readyState).toBe(MockEventSource.CLOSED)+ expect(MockEventSource.last().url).toBe('/api/projects/1/wizard/runs/older/stream/')++ const olderStream = MockEventSource.last()+ mockRunPages({ count: 3, results: [run('latest'), run('newer'), older] })+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.run?.id).toBe('older')+ expect(MockEventSource.instances).toHaveLength(2)++ const completed = { ...older, status: 'completed' as const, stage: null }+ mockRunPages({ count: 2, results: [run('latest'), run('newer')] }, [completed])+ olderStream.emitMessage(JSON.stringify({ status: 'completed', stage: null, tasks: [] }))+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.run?.id).toBe('older')+ expect(logic.values.visibleRuns.map((run) => run.id)).toEqual(['latest', 'newer', 'older'])+ expect(logic.values.activeCount).toBe(2)+ expect(MockEventSource.instances).toHaveLength(2)+ expect(olderStream.readyState).toBe(MockEventSource.CLOSED)++ logic.actions.selectRun(run('latest'))+ expect(MockEventSource.instances).toHaveLength(3)+ })++ it('loads completed runs after reloading, keeps them selectable, and respects dismissal', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const stream = MockEventSource.last()+ const completed = { ...run('newer'), status: 'completed' as const, stage: null }+ mockRunPages({ count: 0, results: [] }, [completed])++ stream.emitMessage(JSON.stringify({ status: 'completed', stage: null, tasks: [] }))+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.run?.status).toBe('completed')+ expect(stream.readyState).toBe(MockEventSource.CLOSED)++ logic.unmount()+ logic = wizardRunSyncLogic({ projectId: '1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(mockWizardRunsList).toHaveBeenCalledWith('1', { status: ['completed'], limit: 5 })+ expect(logic.values.run).toEqual(completed)+ expect(MockEventSource.instances).toHaveLength(1)++ mockRunPages({ count: 1, results: [run('next')] }, [completed])+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.run?.id).toBe('next')+ logic.actions.selectRun(completed)+ expect(MockEventSource.last().readyState).toBe(MockEventSource.CLOSED)+ expect(MockEventSource.instances).toHaveLength(2)++ logic.actions.dismissRun('newer')+ expect(logic.values.run?.id).toBe('next')+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.visibleRuns.map((run) => run.id)).toEqual(['next'])+ })++ it('handles a run completing between the active and completed responses', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const completed = { ...run('newer'), status: 'completed' as const, stage: null }+ mockRunPages({ count: 1, results: [run('newer')] }, [completed])+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.visibleRuns).toEqual([completed])+ expect(logic.values.run?.status).toBe('completed')+ expect(logic.values.activeCount).toBe(0)+ expect(MockEventSource.last().readyState).toBe(MockEventSource.CLOSED)+ })++ it('keeps a dismissed run hidden while polling and streams the next run', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const stream = MockEventSource.last()++ logic.actions.dismissRun('newer')+ expect(stream.readyState).toBe(MockEventSource.CLOSED)+ expect(logic.values.dismissedRunIds).toEqual(['newer'])++ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(MockEventSource.instances).toHaveLength(1)++ mockRunPages({ count: 1, results: [run('next')] })+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.run?.id).toBe('next')+ expect(MockEventSource.instances).toHaveLength(2)++ mockRunPages({ count: 1, results: [run('newer')] })+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.dismissedRunIds).toEqual(['newer'])+ expect(MockEventSource.instances).toHaveLength(2)++ logic.unmount()+ logic = wizardRunSyncLogic({ projectId: '1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.dismissedRunIds).toEqual(['newer'])+ expect(MockEventSource.instances).toHaveLength(2)+ })++ it('closes the current run until the page reloads', async () => {+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.closeRun('newer')+ expect(logic.values.closedRunIds).toEqual(['newer'])+ expect(logic.values.dismissedRunIds).toEqual([])+ expect(MockEventSource.last().readyState).toBe(MockEventSource.CLOSED)++ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(MockEventSource.instances).toHaveLength(1)++ logic.unmount()+ logic = wizardRunSyncLogic({ projectId: '1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.closedRunIds).toEqual([])+ expect(MockEventSource.instances).toHaveLength(2)++ mockRunPages({ count: 1, results: [run('next')] })+ logic.actions.checkRuns()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.run?.id).toBe('next')+ expect(MockEventSource.instances).toHaveLength(3)+ })++ it('tracks FAB expansion and both close options', async () => {+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.expandFab(3)+ logic.actions.closeRun('newer')+ logic.actions.dismissRun('older')++ expect(posthog.capture).toHaveBeenCalledWith('wizard run sync fab expanded', {+ event_source: 'wizard_ui',+ runs_count: 3,+ })+ expect(posthog.capture).toHaveBeenCalledWith(+ 'wizard run sync fab closed',+ expect.objectContaining({ wizard_run_id: 'newer', type: 'dismiss' })+ )+ expect(posthog.capture).toHaveBeenCalledWith(+ 'wizard run sync fab closed',+ expect.objectContaining({ wizard_run_id: 'older', type: 'close_forever' })+ )+ })+})diff --git a/products/wizard/frontend/runs/wizardRunSyncLogic.ts b/products/wizard/frontend/runs/wizardRunSyncLogic.tsnew file mode 100644index 000000000000..2e60a9312e8a--- /dev/null+++ b/products/wizard/frontend/runs/wizardRunSyncLogic.ts@@ -0,0 +1,229 @@+import { MakeLogicType, actions, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { getWizardRunsStreamRetrieveUrl, wizardRunsList } from '../generated/api'+import type { WizardRunApi, WizardRunTaskApi, WizardRunTaskListApi } from '../generated/api.schemas'+import { wizardRunIsActive } from '../wizardRunDisplay'++const RUN_POLL_MS = 30_000+// ponytail: show five active and five completed runs; the Wizard page lists the rest.+const RUN_LIST_LIMIT = 5++type RunStreamState = Pick<+ WizardRunApi,+ 'status' | 'stage' | 'error_code' | 'error_message' | 'updated_at' | 'started_at' | 'finished_at'+> &+ WizardRunTaskListApi++export interface wizardRunSyncLogicProps {+ projectId: string+}++export interface wizardRunSyncLogicValues {+ activeCount: number+ runs: WizardRunApi[]+ visibleRuns: WizardRunApi[]+ closedRunIds: string[]+ dismissedRunIds: string[]+ run: WizardRunApi | null+ selectedRunId: string | null+ tasks: readonly WizardRunTaskApi[]+}++export interface wizardRunSyncLogicActions {+ checkRuns: () => { value: true }+ runsLoaded: (count: number, runs: WizardRunApi[]) => { count: number; runs: WizardRunApi[] }+ clearTasks: () => { value: true }+ runUpdated: (state: RunStreamState) => { state: RunStreamState }+ showRun: (run: WizardRunApi | null) => { run: WizardRunApi | null }+ selectRun: (run: WizardRunApi) => { run: WizardRunApi }+ connectRun: () => { value: true }+ closeRun: (runId: string) => { runId: string }+ dismissRun: (runId: string) => { runId: string }+ expandFab: (runsCount: number) => { runsCount: number }+}++export type wizardRunSyncLogicType = MakeLogicType<+ wizardRunSyncLogicValues,+ wizardRunSyncLogicActions,+ wizardRunSyncLogicProps+>++export const wizardRunSyncLogic = kea<wizardRunSyncLogicType>([+ path(['products', 'wizard', 'wizardRunSyncLogic']),+ props({} as wizardRunSyncLogicProps),+ key((logicProps) => logicProps.projectId),+ actions({+ checkRuns: true,+ runsLoaded: (count: number, runs: WizardRunApi[]) => ({ count, runs }),+ clearTasks: true,+ runUpdated: (state: RunStreamState) => ({ state }),+ showRun: (run: WizardRunApi | null) => ({ run }),+ selectRun: (run: WizardRunApi) => ({ run }),+ connectRun: true,+ closeRun: (runId: string) => ({ runId }),+ dismissRun: (runId: string) => ({ runId }),+ expandFab: (runsCount: number) => ({ runsCount }),+ }),+ reducers({+ activeCount: [0, { runsLoaded: (_, { count }) => count }],+ runs: [[] as WizardRunApi[], { runsLoaded: (_, { runs }) => runs }],+ closedRunIds: [[] as string[], { closeRun: (current, { runId }) => [...current, runId] }],+ dismissedRunIds: [+ [] as string[],+ { persist: true },+ { dismissRun: (current, { runId }) => (current.includes(runId) ? current : [...current, runId]) },+ ],+ selectedRunId: [+ null as string | null,+ {+ runsLoaded: (current, { runs }) => (current && runs.some((run) => run.id === current) ? current : null),+ selectRun: (_, { run }) => run.id,+ closeRun: (current, { runId }) => (current === runId ? null : current),+ dismissRun: (current, { runId }) => (current === runId ? null : current),+ },+ ],+ run: [+ null as WizardRunApi | null,+ {+ runsLoaded: (current, { runs }) =>+ current ? (runs.find((run) => run.id === current.id) ?? current) : null,+ showRun: (_, { run }) => run,+ selectRun: (_, { run }) => run,+ runUpdated: (current, { state }) => (current ? { ...current, ...state } : null),+ closeRun: () => null,+ dismissRun: () => null,+ },+ ],+ tasks: [+ [] as readonly WizardRunTaskApi[],+ {+ clearTasks: () => [],+ showRun: () => [],+ selectRun: () => [],+ runUpdated: (_, { state }) => state.tasks,+ closeRun: () => [],+ dismissRun: () => [],+ },+ ],+ }),+ selectors({+ visibleRuns: [+ (s) => [s.runs, s.closedRunIds, s.dismissedRunIds],+ (runs: WizardRunApi[], closedRunIds: string[], dismissedRunIds: string[]): WizardRunApi[] =>+ runs.filter((run) => !closedRunIds.includes(run.id) && !dismissedRunIds.includes(run.id)),+ ],+ }),+ listeners(({ actions, cache, props: logicProps, values }) => ({+ checkRuns: async () => {+ if (cache.checking) {+ return+ }+ cache.checking = true+ try {+ const [activePage, completedPage] = await Promise.all([+ wizardRunsList(logicProps.projectId, {+ status: ['created', 'running'],+ limit: RUN_LIST_LIMIT,+ }),+ wizardRunsList(logicProps.projectId, { status: ['completed'], limit: RUN_LIST_LIMIT }),+ ])+ const activeRuns = activePage.results.filter(+ (run) => !completedPage.results.some((completedRun) => completedRun.id === run.id)+ )+ actions.runsLoaded(activePage.count - (activePage.results.length - activeRuns.length), [+ ...activeRuns,+ ...completedPage.results,+ ])+ } catch {+ return+ } finally {+ cache.checking = false+ }+ },+ runsLoaded: () => {+ const nextRun =+ values.visibleRuns.find((run) => run.id === values.selectedRunId) ??+ values.visibleRuns[0] ??+ (values.run && !wizardRunIsActive(values.run) ? values.run : null)+ if (nextRun?.id !== values.run?.id) {+ actions.showRun(nextRun)+ }+ actions.connectRun()+ },+ selectRun: () => {+ actions.connectRun()+ },+ connectRun: () => {+ const run = values.run+ if (+ !run ||+ values.closedRunIds.includes(run.id) ||+ values.dismissedRunIds.includes(run.id) ||+ !wizardRunIsActive(run)+ ) {+ cache.disposables.dispose('run-stream')+ cache.connectedRunId = undefined+ return+ }+ if (cache.connectedRunId === run.id) {+ return+ }+ cache.disposables.dispose('run-stream')+ cache.connectedRunId = run.id+ actions.clearTasks()+ cache.disposables.add(() => {+ const stream = new EventSource(getWizardRunsStreamRetrieveUrl(logicProps.projectId, run.id), {+ withCredentials: true,+ })+ stream.onmessage = (event: MessageEvent<string>): void => {+ try {+ const state = JSON.parse(event.data) as RunStreamState+ actions.runUpdated(state)+ if (!wizardRunIsActive({ ...run, ...state })) {+ actions.checkRuns()+ }+ } catch {+ actions.checkRuns()+ }+ }+ return () => stream.close()+ }, 'run-stream')+ },+ closeRun: ({ runId }) => {+ posthog.capture('wizard run sync fab closed', {+ event_source: 'wizard_ui',+ wizard_run_id: runId,+ type: 'dismiss',+ })+ cache.disposables.dispose('run-stream')+ cache.connectedRunId = undefined+ actions.runsLoaded(values.activeCount, values.runs)+ },+ dismissRun: ({ runId }) => {+ posthog.capture('wizard run sync fab closed', {+ event_source: 'wizard_ui',+ wizard_run_id: runId,+ type: 'close_forever',+ })+ cache.disposables.dispose('run-stream')+ cache.connectedRunId = undefined+ actions.runsLoaded(values.activeCount, values.runs)+ },+ expandFab: ({ runsCount }) => {+ posthog.capture('wizard run sync fab expanded', {+ event_source: 'wizard_ui',+ runs_count: runsCount,+ })+ },+ })),+ events(({ actions, cache }) => ({+ afterMount: () => {+ actions.checkRuns()+ cache.disposables.add(() => {+ const timer = window.setInterval(() => actions.checkRuns(), RUN_POLL_MS)+ return () => window.clearInterval(timer)+ }, 'active-run-poll')+ },+ })),+])diff --git a/products/wizard/frontend/wizardLibraryLogic.test.tsx b/products/wizard/frontend/wizardLibraryLogic.test.tsxindex a80e9ab7231f..891ef4102434 100644--- a/products/wizard/frontend/wizardLibraryLogic.test.tsx+++ b/products/wizard/frontend/wizardLibraryLogic.test.tsx@@ -225,20 +225,7 @@ describe('wizardLibraryLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(detailsLogic.values.selectedRunSummary?.id).toBe('run-new')- expect(posthog.capture).toHaveBeenCalledWith('wizard run create succeeded', {- event_source: 'wizard_ui',- project_id: '1',- environment: 'cloud',- run_surface: 'cloud',- wizard_run_id: 'run-new',- task_run_id: 'run-new',- program_id: program.id,- wizard_version: '2.67.0',- version: '2.67.0',- command: 'default',- workspace_type: 'git_repository',- status: 'created',- })+ expect(posthog.capture).not.toHaveBeenCalledWith('wizard run create succeeded', expect.anything())expect(posthog.capture).not.toHaveBeenCalledWith('setup wizard finished', expect.anything())expect(JSON.stringify(jest.mocked(posthog.capture).mock.calls)).not.toContain('example/private-project')detailsLogic.unmount()diff --git a/products/wizard/frontend/wizardLibraryLogic.ts b/products/wizard/frontend/wizardLibraryLogic.tsindex d53dd19dceec..837ab554dea9 100644--- a/products/wizard/frontend/wizardLibraryLogic.ts+++ b/products/wizard/frontend/wizardLibraryLogic.ts@@ -21,7 +21,7 @@ import type {WizardRunCreateRequestApi,} from './generated/api.schemas'import { wizardEventProperties, wizardRunEventProperties } from './wizardAnalytics'-import { wizardRunDetailsLogic } from './wizardRunDetailsLogic'+import { type WizardRunDetailSource, wizardRunDetailsLogic } from './wizardRunDetailsLogic'import { WIZARD_LOCAL_RUNS_VISIBLE, wizardCommand } from './wizardRunDisplay'import { wizardRunsLogic } from './wizardRunsLogic'@@ -86,7 +86,13 @@ export interface wizardLibraryLogicActions {setLibraryEnvironment: (environment: RunEnvironmentEnumApi) => { environment: RunEnvironmentEnumApi }setLibrarySearch: (search: string) => { search: string }setRepository: (repository: string) => { repository: string }- selectRun: (run: WizardRunApi | null) => { run: WizardRunApi | null }+ selectRun: (+ run: WizardRunApi | null,+ source?: WizardRunDetailSource+ ) => {+ run: WizardRunApi | null+ source?: WizardRunDetailSource+ }}export interface wizardLibraryLogicMeta {@@ -228,7 +234,6 @@ export const wizardLibraryLogic = kea<wizardLibraryLogicType>([posthog.capture('wizard run create requested', properties)try {const run = await wizardRunsCreate(projectId, body)- posthog.capture('wizard run create succeeded', wizardRunEventProperties(run))return run} catch (error) {posthog.capture('wizard run create failed', {@@ -318,7 +323,7 @@ export const wizardLibraryLogic = kea<wizardLibraryLogicType>([}posthog.capture(- 'wizard library opened',+ 'wizard run library opened',wizardEventProperties(values.currentProjectId,WIZARD_LOCAL_RUNS_VISIBLE ? values.libraryEnvironment : 'cloud'@@ -339,8 +344,23 @@ export const wizardLibraryLogic = kea<wizardLibraryLogicType>([const environment =WIZARD_LOCAL_RUNS_VISIBLE && !program.supported_environments.includes('cloud') ? 'local' : 'cloud'+ posthog.capture('wizard run library item selected', {+ ...wizardEventProperties(values.currentProjectId, environment),+ program_id: program.id,+ program: program.name,+ wizard_version: program.wizard_version,+ })actions.setLibraryEnvironment(environment)},+ setRepository: ({ repository }) => {+ if (repository) {+ posthog.capture('wizard run library repository selected', {+ ...wizardEventProperties(values.currentProjectId, values.libraryEnvironment),+ workspace_type: 'git_repository',+ program_id: values.selectedProgram?.id,+ })+ }+ },copyCommand: () => {const program = values.selectedProgramif (values.selectedProgramCommand) {@@ -413,7 +433,7 @@ export const wizardLibraryLogic = kea<wizardLibraryLogicType>([// Follow the new run in the drawer so the old failed run cannot reappear.if (createRunRequest) {- actions.selectRun(createRunRequest)+ actions.selectRun(createRunRequest, 'wizard_library')}actions.closeLibrary()diff --git a/products/wizard/frontend/wizardRunDetailsLogic.test.ts b/products/wizard/frontend/wizardRunDetailsLogic.test.tsindex a663e59b460d..21f2a8e94611 100644--- a/products/wizard/frontend/wizardRunDetailsLogic.test.ts+++ b/products/wizard/frontend/wizardRunDetailsLogic.test.ts@@ -93,7 +93,7 @@ describe('wizardRunDetailsLogic', () => {})it('loads run details and artifacts through separate endpoints', async () => {- logic.actions.selectRun(makeRun())+ logic.actions.selectRun(makeRun(), 'wizard_datatable')await expectLogic(logic).toFinishAllListeners()@@ -107,14 +107,21 @@ describe('wizardRunDetailsLogic', () => {expect(mockLoadWizardRunArtifacts).toHaveBeenCalledWith(expect.any(String), 'run-1')expect(mockLoadWizardRunArtifactContent).not.toHaveBeenCalled()expect(posthog.capture).toHaveBeenCalledWith(- 'wizard run viewed',+ 'wizard run detail dialog opened',expect.objectContaining({wizard_run_id: 'run-1',task_run_id: 'run-1',run_surface: 'cloud',version: '2.6.0',+ source: 'wizard_datatable',}))++ logic.actions.selectRun(null)+ expect(posthog.capture).toHaveBeenCalledWith(+ 'wizard run detail dialog closed',+ expect.objectContaining({ wizard_run_id: 'run-1' })+ )})it('loads git diff content only after the artifact is opened', async () => {@@ -133,10 +140,11 @@ describe('wizardRunDetailsLogic', () => {})expect(mockLoadWizardRunArtifactContent).toHaveBeenCalledWith(expect.any(String), 'run-1', 'artifact-1')expect(posthog.capture).toHaveBeenCalledWith(- 'wizard run diff opened',+ 'artifact clicked',expect.objectContaining({wizard_run_id: 'run-1',- artifact_type: 'git_diff',+ type: 'diff',+ source: 'artifacts_section',}))expect(JSON.stringify(jest.mocked(posthog.capture).mock.calls)).not.toContain('diff content')@@ -175,9 +183,9 @@ describe('wizardRunDetailsLogic', () => {logic.actions.loadRunDetails({ runId: 'run-1' })await expectLogic(logic).toFinishAllListeners()expect(mockLoadWizardRunArtifacts).toHaveBeenCalledTimes(2)- expect(jest.mocked(posthog.capture).mock.calls.filter(([event]) => event === 'wizard run viewed')).toHaveLength(- 1- )+ expect(+ jest.mocked(posthog.capture).mock.calls.filter(([event]) => event === 'wizard run detail dialog opened')+ ).toHaveLength(1)})it('does not download a diff that is too large to render', async () => {diff --git a/products/wizard/frontend/wizardRunDetailsLogic.ts b/products/wizard/frontend/wizardRunDetailsLogic.tsindex 8b7304319082..06290e212eca 100644--- a/products/wizard/frontend/wizardRunDetailsLogic.ts+++ b/products/wizard/frontend/wizardRunDetailsLogic.ts@@ -24,6 +24,10 @@ type WizardRunDiffContent = {content: string}+export type WizardRunDetailSource = 'fab_click' | 'fab_expand_icon_click' | 'wizard_datatable' | 'wizard_library'+export type WizardRunArtifactSource = 'button' | 'artifacts_section'+export type WizardRunIdLocation = 'bottom_button' | 'run_id_label'+function requestError(error: unknown, fallback: string): string {return error instanceof ApiError && error.detail ? error.detail : fallback}@@ -70,7 +74,14 @@ export interface wizardRunDetailsLogicActions {payload?: { runId: string }}closeRunDiff: () => { value: true }- copyRunId: (runId: string) => { runId: string }+ artifactClicked: (+ artifact: WizardRunArtifactApi,+ source: WizardRunArtifactSource+ ) => {+ artifact: WizardRunArtifactApi+ source: WizardRunArtifactSource+ }+ copyRunId: (runId: string, location: WizardRunIdLocation) => { runId: string; location: WizardRunIdLocation }loadRunArtifacts: ({ runId }: { runId: string }) => { runId: string }loadRunArtifactsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }loadRunArtifactsSuccess: (@@ -104,7 +115,13 @@ export interface wizardRunDetailsLogicActions {openRunDiff: (artifact: WizardRunGitDiffArtifactApi) => { artifact: WizardRunGitDiffArtifactApi }refreshRuns: () => { value: true }refreshSelectedRun: () => { value: true }- selectRun: (run: WizardRunApi | null) => { run: WizardRunApi | null }+ selectRun: (+ run: WizardRunApi | null,+ source?: WizardRunDetailSource+ ) => {+ run: WizardRunApi | null+ source?: WizardRunDetailSource+ }}export interface wizardRunDetailsLogicMeta {@@ -141,12 +158,13 @@ export const wizardRunDetailsLogic = kea<wizardRunDetailsLogicType>([actions: [wizardRunsLogic, ['refreshRuns']],})),actions({- selectRun: (run: WizardRunApi | null) => ({ run }),+ selectRun: (run: WizardRunApi | null, source?: WizardRunDetailSource) => ({ run, source }),openRunDiff: (artifact: WizardRunGitDiffArtifactApi) => ({ artifact }),+ artifactClicked: (artifact: WizardRunArtifactApi, source: WizardRunArtifactSource) => ({ artifact, source }),closeRunDiff: true,refreshSelectedRun: true,cancelRun: (run: WizardRunApi) => ({ run }),- copyRunId: (runId: string) => ({ runId }),+ copyRunId: (runId: string, location: WizardRunIdLocation) => ({ runId, location }),}),reducers({selectedRunSummary: [@@ -336,14 +354,22 @@ export const wizardRunDetailsLogic = kea<wizardRunDetailsLogicType>([],}),listeners(({ actions, values, cache }) => ({- selectRun: ({ run }) => {+ selectRun: ({ run, source }) => {cache.disposables.dispose('wizardRunDetailPolling')if (!run) {+ if (cache.openRun) {+ posthog.capture('wizard run detail dialog closed', wizardRunEventProperties(cache.openRun))+ cache.openRun = undefined+ }return}- posthog.capture('wizard run viewed', wizardRunEventProperties(run))+ cache.openRun = run+ posthog.capture('wizard run detail dialog opened', {+ ...wizardRunEventProperties(run),+ source,+ })actions.loadRunDetails({ runId: run.id })actions.loadRunArtifacts({ runId: run.id })@@ -363,12 +389,7 @@ export const wizardRunDetailsLogic = kea<wizardRunDetailsLogicType>([return}- posthog.capture('wizard run diff opened', {- ...(values.selectedRun?.id === artifact.run_id- ? wizardRunEventProperties(values.selectedRun)- : { event_source: 'wizard_ui', wizard_run_id: artifact.run_id }),- artifact_type: artifact.artifact_type,- })+ actions.artifactClicked(artifact, 'artifacts_section')// Artifacts are immutable, so reuse the cached content instead of re-downloading it.if (values.runDiff?.artifactId !== artifact.id) {@@ -377,6 +398,11 @@ export const wizardRunDetailsLogic = kea<wizardRunDetailsLogicType>([},refreshSelectedRun: () => {if (values.selectedRunId) {+ posthog.capture('wizard run refreshed', {+ ...(values.selectedRun ? wizardRunEventProperties(values.selectedRun) : {}),+ wizard_run_id: values.selectedRunId,+ location: 'detail_dialog',+ })actions.loadRunDetails({ runId: values.selectedRunId })actions.loadRunArtifacts({ runId: values.selectedRunId })}@@ -423,8 +449,27 @@ export const wizardRunDetailsLogic = kea<wizardRunDetailsLogicType>([cancelRunRequestFailure: ({ errorObject }) => {lemonToast.error(requestError(errorObject, "Couldn't cancel the Wizard run. Try again."))},- copyRunId: ({ runId }) => {- void copyToClipboard(runId, 'Wizard run ID')+ artifactClicked: ({ artifact, source }) => {+ posthog.capture('artifact clicked', {+ ...(values.selectedRun?.id === artifact.run_id+ ? wizardRunEventProperties(values.selectedRun)+ : { event_source: 'wizard_ui', wizard_run_id: artifact.run_id }),+ type: artifact.artifact_type === 'git_diff' ? 'diff' : 'pull_request',+ url: artifact.artifact_type === 'pull_request' ? artifact.url : null,+ name: artifact.artifact_type === 'pull_request' ? `Pull request #${artifact.number}` : 'Git diff',+ source,+ })+ },+ copyRunId: ({ runId, location }) => {+ void copyToClipboard(runId, 'Wizard run ID').then((copied) => {+ if (copied) {+ posthog.capture('run id copied', {+ event_source: 'wizard_ui',+ wizard_run_id: runId,+ location,+ })+ }+ })},})),])diff --git a/products/wizard/frontend/wizardRunDisplay.test.ts b/products/wizard/frontend/wizardRunDisplay.test.tsindex 75683aad09f4..ad09f84b61e8 100644--- a/products/wizard/frontend/wizardRunDisplay.test.ts+++ b/products/wizard/frontend/wizardRunDisplay.test.ts@@ -72,8 +72,13 @@ describe('wizardRunCanCancel', () => {['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 })+ ['local runs cannot be stopped from the browser', 'running', 7, 7, false, 'local'],+ ])('%s', (_label, status, createdById, currentUserId, expected, environment = 'cloud') => {+ const run = makeRun({+ status: status as WizardRunApi['status'],+ created_by_id: createdById,+ environment: environment as WizardRunApi['environment'],+ })expect(wizardRunCanCancel(run, currentUserId)).toBe(expected)})diff --git a/products/wizard/frontend/wizardRunDisplay.ts b/products/wizard/frontend/wizardRunDisplay.tsindex 8a16bb6674b3..53b467c11455 100644--- a/products/wizard/frontend/wizardRunDisplay.ts+++ b/products/wizard/frontend/wizardRunDisplay.ts@@ -36,9 +36,13 @@ export function wizardRunTerminalLabel(status: WizardRunApi['status']): string {}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+ // The server cannot stop a local process, even when it marks that run canceled.+ return (+ run.environment === 'cloud' &&+ wizardRunIsActive(run) &&+ run.created_by_id !== null &&+ run.created_by_id === currentUserId+ )}const FAILURE_STAGE_BY_ERROR_CODE: Record<string, WizardRunStageEnumApi> = {@@ -64,6 +68,57 @@ export function wizardRunFailureStage(run: WizardRunApi): WizardRunStageEnumApireturn FAILURE_STAGE_BY_ERROR_CODE[run.error_code ?? ''] ?? WizardRunStageEnumApi.ExecutingWizard}+export type WizardRunProgressState = 'complete' | 'active' | 'pending' | 'failed'++export function wizardRunStagePosition(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+ }+}++export function wizardRunProgressState(run: WizardRunApi, step: number): WizardRunProgressState {+ if (run.status === 'cancelled') {+ return step === 0 ? 'complete' : 'pending'+ }++ const position = wizardRunStagePosition(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'+}+export function wizardGithubRepositoryUrl(repository: string): string {return `https://github.com/${repository}`}diff --git a/products/wizard/frontend/wizardRunsLogic.test.ts b/products/wizard/frontend/wizardRunsLogic.test.tsindex 226bc4d2edf9..69c1f9bf7158 100644--- a/products/wizard/frontend/wizardRunsLogic.test.ts+++ b/products/wizard/frontend/wizardRunsLogic.test.ts@@ -1,4 +1,5 @@import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { projectLogic } from 'scenes/projectLogic'@@ -57,6 +58,7 @@ describe('wizardRunsLogic', () => {beforeEach(async () => {initKeaTests()+ jest.spyOn(posthog, 'capture').mockClear()mockWizardRunsList.mockReset()mockWizardRunsList.mockResolvedValue({ count: 1, next: null, previous: null, results: [makeRun()] })await expectLogic(projectLogic).toMatchValues({ currentProjectId: expect.any(Number) })@@ -66,6 +68,7 @@ describe('wizardRunsLogic', () => {afterEach(() => {logic.unmount()+ jest.restoreAllMocks()})it('keeps resolved rows visible during background polling', async () => {@@ -182,4 +185,25 @@ describe('wizardRunsLogic', () => {runs: [expect.objectContaining({ id: 'run-1' })],})})++ it('tracks table controls', async () => {+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSearch('setup')+ logic.actions.setEnvironment('cloud')+ logic.actions.setStatus('running')+ logic.actions.trackPagination(1, 2)+ logic.actions.openWorkspace(makeRun(), 'https://github.com/posthog/posthog')++ expect(posthog.capture).toHaveBeenCalledWith('wizard run datatable searched', { query: 'setup' })+ expect(posthog.capture).toHaveBeenCalledWith('wizard run datatable filters changed', {+ environment: 'cloud',+ status: 'running',+ })+ expect(posthog.capture).toHaveBeenCalledWith('wizard run datatable paginated', { page: 1, next_page: 2 })+ expect(posthog.capture).toHaveBeenCalledWith('wizard run datatable workspace opened', {+ workspace_type: 'git_repository',+ url: 'https://github.com/posthog/posthog',+ })+ })})diff --git a/products/wizard/frontend/wizardRunsLogic.ts b/products/wizard/frontend/wizardRunsLogic.tsindex 0fe607a083b6..f388111b75b7 100644--- a/products/wizard/frontend/wizardRunsLogic.ts+++ b/products/wizard/frontend/wizardRunsLogic.ts@@ -1,5 +1,6 @@import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import { dayjs } from 'lib/dayjs'import { projectLogic } from 'scenes/projectLogic'@@ -33,6 +34,9 @@ export interface wizardRunsLogicActions {loadRunsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }loadRunsSuccess: (runs: WizardRunApi[]) => { runs: WizardRunApi[] }refreshRuns: () => { value: true }+ refreshRun: (run: WizardRunApi) => { run: WizardRunApi }+ trackPagination: (page: number, nextPage: number) => { page: number; nextPage: number }+ openWorkspace: (run: WizardRunApi, url: string) => { run: WizardRunApi; url: string }scheduleNextRunPoll: () => { value: true }setEnvironment: (environment: RunEnvironmentEnumApi | 'all') => { environment: RunEnvironmentEnumApi | 'all' }setSearch: (search: string) => { search: string }@@ -68,6 +72,9 @@ export const wizardRunsLogic = kea<wizardRunsLogicType>([connect(() => ({ values: [projectLogic, ['currentProjectId']] })),actions({refreshRuns: true,+ refreshRun: (run: WizardRunApi) => ({ run }),+ trackPagination: (page: number, nextPage: number) => ({ page, nextPage }),+ openWorkspace: (run: WizardRunApi, url: string) => ({ run, url }),scheduleNextRunPoll: true,clearRunFilters: true,setSearch: (search: string) => ({ search }),@@ -211,8 +218,33 @@ export const wizardRunsLogic = kea<wizardRunsLogicType>([!runsLoaded || (runsLoading && runs.length === 0),],}),- listeners(({ actions, cache }) => ({+ listeners(({ actions, cache, values }) => ({refreshRuns: () => actions.loadRuns({ poll: false }),+ refreshRun: ({ run }) => {+ posthog.capture('wizard run refreshed', { wizard_run_id: run.id, location: 'wizard_datatable' })+ actions.refreshRuns()+ },+ setSearch: ({ search }) => {+ posthog.capture('wizard run datatable searched', { query: search })+ },+ setEnvironment: ({ environment }) => {+ posthog.capture('wizard run datatable filters changed', { environment, status: values.status })+ },+ setStatus: ({ status }) => {+ posthog.capture('wizard run datatable filters changed', { environment: values.environment, status })+ },+ clearRunFilters: () => {+ posthog.capture('wizard run datatable filters changed', { environment: 'all', status: 'all' })+ },+ trackPagination: ({ page, nextPage }) => {+ posthog.capture('wizard run datatable paginated', { page, next_page: nextPage })+ },+ openWorkspace: ({ run, url }) => {+ posthog.capture('wizard run datatable workspace opened', {+ workspace_type: run.workspace.type,+ url,+ })+ },loadRunsSuccess: () => actions.scheduleNextRunPoll(),loadRunsFailure: () => actions.scheduleNextRunPoll(),// Each poll starts only after the previous load settles, so a slow load can never bediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 228348a0fa1c..8acc41bfdbef 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -100250,6 +100250,42 @@ export namespace Schemas {success: boolean;}+ /**+ * * `created` - created+ * * `running` - running+ * * `completed` - completed+ * * `failed` - failed+ */+ export type WizardTaskStatusEnum = typeof WizardTaskStatusEnum[keyof typeof WizardTaskStatusEnum];+++ export const WizardTaskStatusEnum = {+ Created: 'created',+ Running: 'running',+ Completed: 'completed',+ Failed: 'failed',+ } as const;++ export interface UpdateWizardRunTask {+ /**+ * Task name, unique within this run and stable across snapshots.+ * @maxLength 255+ */+ name: string;+ /** Current task status reported by the setup agent.+ *+ * * `created` - created+ * * `running` - running+ * * `completed` - completed+ * * `failed` - failed */+ status: WizardTaskStatusEnum;+ }++ export interface UpdateWizardRunTaskList {+ /** Complete task snapshot. An empty list clears the run's tasks. */+ tasks: UpdateWizardRunTask[];+ }+export interface UploadReceipt {/** One acknowledgment per referenced item. */items: ItemReceipt[];@@ -102305,6 +102341,45 @@ export namespace Schemas {PullRequest: 'pull_request',} as const;+ export interface WizardRunTask {+ /** Task name, unique within this run. */+ readonly name: string;+ /** Current task status reported by the setup agent.+ *+ * * `created` - created+ * * `running` - running+ * * `completed` - completed+ * * `failed` - failed */+ readonly status: WizardTaskStatusEnum;+ /** When the server first received this task. */+ readonly created_at: string;+ /**+ * When the server first observed this task running.+ * @nullable+ */+ readonly started_at: string | null;+ /**+ * When the server first observed this task completed.+ * @nullable+ */+ readonly completed_at: string | null;+ /**+ * When the server first observed this task failed.+ * @nullable+ */+ readonly failed_at: string | null;+ /**+ * Task failure explanation, or null when none is available.+ * @nullable+ */+ readonly error_message: string | null;+ }++ export interface WizardRunTaskList {+ /** Complete task list in snapshot order. */+ readonly tasks: readonly WizardRunTask[];+ }+/*** Whether PostHog paused this one workflow's email sending, and why.*/@@ -118068,8 +118143,23 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Filter by one or more comma-separated run statuses.+ */+ status?: WizardRunsListStatusItem[];};+ export type WizardRunsListStatusItem = typeof WizardRunsListStatusItem[keyof typeof WizardRunsListStatusItem];+++ export const WizardRunsListStatusItem = {+ Cancelled: 'cancelled',+ Completed: 'completed',+ Created: 'created',+ Failed: 'failed',+ Running: 'running',+ } as const;+export type WizardRunsArtifactsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 67a965677464..c86789aa42bc 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -241,6 +241,8 @@ export const OAUTH_SCOPES_HIDDEN = ['batch_import_support:write','query_performance:read','query_performance:write',+ 'wizard_run:read',+ 'wizard_run:write','wizard_session:read','wizard_session:write',] as const