: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(onboarding): expose provisioned-user status to the frontend (#70150)
Rafael Audiberta10c09e9c2fa
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 473b0f202b6c..a5bc93b4cf17 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5246,10 +5246,6 @@ snapshots:hash: v1.k794b7964.8e92b27c0a63fafbd74a631f60b1bdea1b9983c7abbd30a4258e1f818ef63ecb.wvCGmys9jG3ZUP_O-3_k5uuNda7hMWnCsRypRDGtrBMscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:hash: v1.k794b7964.9b934a54cfcdee0d1448d2d8bfd579acd6ef2898d844498a8b06688b54c891fa.SK_-r5YH_iaVhdenzRzQMZK7XFMnOuBGUrMxXA9A-Hc- scenes-app-customer-analytics-accounts--row-expanded-usage-populated--dark:- hash: v1.k794b7964.592cdf275469f3860c47e207f3eafe64e4cbd4403153b67aa677184b2b608e01.RA0z4KST7z6GQ8OaV2hPNkv_xPk1azsfWS0Wzh3t7us- scenes-app-customer-analytics-accounts--row-expanded-usage-populated--light:- hash: v1.k794b7964.a5c5405f99c368124545f0f6dd5eca5442145b39c35a51d9230ab614a40d20d3.OGLkB5pB_o2HI56DCbuk4G-WUuHK25QQuwAKnSsqRf8scenes-app-customer-analytics-accounts--row-expanded-with-note--dark:hash: v1.k794b7964.c9b6f7b53e6c726a4578c832e45190e25544b8393de528d30edbed057ac44791.Ly4hzt_3vfZKOBOWl_agi_l3br3UxMEIRN9qfmLO1Jsscenes-app-customer-analytics-accounts--row-expanded-with-note--light:diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.tsindex cbfbc568597e..dab7b0affc78 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.test.ts@@ -1,4 +1,21 @@-import { CloudRunHandle, scopedCloudRun } from './activeCloudRunLogic'+import { MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { projectLogic } from 'scenes/projectLogic'+import { userLogic } from 'scenes/userLogic'++import { initKeaTests } from '~/test/init'++import { tasksActiveWizardRunRetrieve } from 'products/tasks/frontend/generated/api'++import { activeCloudRunLogic, CloudRunHandle, scopedCloudRun } from './activeCloudRunLogic'++jest.mock('products/tasks/frontend/generated/api', () => ({+ tasksActiveWizardRunRetrieve: jest.fn(),+}))++const mockActiveWizardRun = tasksActiveWizardRunRetrieve as jest.Mockconst handle: CloudRunHandle = {taskId: 'task-1',@@ -7,16 +24,110 @@ const handle: CloudRunHandle = {projectId: 2,}-describe('scopedCloudRun', () => {- it.each([- // The persisted handle is browser-wide localStorage — a fresh account inheriting another- // project's run must never surface it.- ['a handle from another project', handle, 7, null],- ['a legacy handle without a projectId', { ...handle, projectId: undefined }, 2, null],- ['no current project resolved yet', handle, null, null],- ['no handle at all', null, 2, null],- ['a handle for the current project', handle, 2, handle],- ])('returns %s correctly', (_name, persisted, currentProjectId, expected) => {- expect(scopedCloudRun(persisted, currentProjectId)).toEqual(expected)+function setUser(provisioned: boolean): void {+ userLogic.mount()+ userLogic.actions.loadUserSuccess({+ ...MOCK_DEFAULT_USER,+ onboarding_skipped_reason: provisioned ? 'provisioned' : null,+ })+}++describe('activeCloudRunLogic', () => {+ describe('scopedCloudRun', () => {+ it.each([+ // The persisted handle is browser-wide localStorage — a fresh account inheriting another+ // project's run must never surface it.+ ['a handle from another project', handle, 7, null],+ ['a legacy handle without a projectId', { ...handle, projectId: undefined }, 2, null],+ ['no current project resolved yet', handle, null, null],+ ['no handle at all', null, 2, null],+ ['a handle for the current project', handle, 2, handle],+ ])('returns %s correctly', (_name, persisted, currentProjectId, expected) => {+ expect(scopedCloudRun(persisted, currentProjectId as number | null)).toEqual(expected)+ })+ })++ describe('hydrateFromServer', () => {+ let logic: ReturnType<typeof activeCloudRunLogic.build>++ beforeEach(() => {+ // The handle is persisted to localStorage, so clear it or a seeded run leaks across tests.+ window.localStorage.clear()+ initKeaTests()+ mockActiveWizardRun.mockReset()+ projectLogic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('seeds the handle for a provisioned user when the server reports an active run', async () => {+ setUser(true)+ mockActiveWizardRun.mockResolvedValue({+ task_id: 'srv-task',+ run_id: 'srv-run',+ status: 'in_progress',+ started_at: '2026-02-02T00:00:00Z',+ })+ logic = activeCloudRunLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'setActiveCloudRun'])+ expect(mockActiveWizardRun).toHaveBeenCalledWith(String(MOCK_TEAM_ID))+ expect(logic.values.activeCloudRun).toMatchObject({+ taskId: 'srv-task',+ runId: 'srv-run',+ projectId: MOCK_TEAM_ID,+ })+ })++ it('does not call the server for a non-provisioned user', () => {+ setUser(false)+ logic = activeCloudRunLogic()+ logic.mount()++ // Gated before the request — a non-provisioned user never reaches server hydration.+ expect(mockActiveWizardRun).not.toHaveBeenCalled()+ expect(logic.values.activeCloudRun).toBeNull()+ })++ it('hydrates once the provisioned status loads after mount', async () => {+ // The user (and so isProvisionedUser) resolves asynchronously; mounting before it does+ // must not permanently skip the one server lookup — the original one-shot afterMount did.+ mockActiveWizardRun.mockResolvedValue({+ task_id: 'srv-task',+ run_id: 'srv-run',+ status: 'in_progress',+ started_at: '2026-02-02T00:00:00Z',+ })+ logic = activeCloudRunLogic()+ logic.mount()+ expect(mockActiveWizardRun).not.toHaveBeenCalled()++ setUser(true)++ await expectLogic(logic).toDispatchActions(['hydrateFromServer', 'setActiveCloudRun'])+ expect(mockActiveWizardRun).toHaveBeenCalledWith(String(MOCK_TEAM_ID))+ expect(logic.values.activeCloudRun).toMatchObject({ taskId: 'srv-task', runId: 'srv-run' })+ })++ it('does not clobber a fresher local handle', async () => {+ setUser(true)+ // Even if the server reports a run, a local handle already present must win.+ mockActiveWizardRun.mockResolvedValue({+ task_id: 'srv-task',+ run_id: 'srv-run',+ status: 'in_progress',+ started_at: null,+ })+ logic = activeCloudRunLogic()+ logic.mount()+ logic.actions.setActiveCloudRun('local-task', 'local-run', '2026-03-03T00:00:00Z', MOCK_TEAM_ID)++ logic.actions.hydrateFromServer()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.activeCloudRun).toMatchObject({ taskId: 'local-task' })+ })})})diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.tsindex d40efa213c2d..abfa06f369bd 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/activeCloudRunLogic.ts@@ -1,6 +1,10 @@-import { actions, connect, kea, path, reducers, selectors } from 'kea'+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { subscriptions } from 'kea-subscriptions'import { projectLogic } from 'scenes/projectLogic'+import { userLogic } from 'scenes/userLogic'++import { tasksActiveWizardRunRetrieve } from 'products/tasks/frontend/generated/api'import type { activeCloudRunLogicType } from './activeCloudRunLogicType'@@ -34,7 +38,7 @@ export function scopedCloudRun(handle: CloudRunHandle | null, currentProjectId:export const activeCloudRunLogic = kea<activeCloudRunLogicType>([path(['scenes', 'onboarding', 'activeCloudRunLogic']),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [projectLogic, ['currentProjectId'], userLogic, ['isProvisionedUser']],})),actions({setActiveCloudRun: (taskId: string, runId: string, startedAt: string, projectId: number) => ({@@ -49,6 +53,9 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([// Last-writer-wins boolean, not a refcount: at most ONE inline view may be mounted at a time,// or the first unmount un-hides the FAB while the second view is still on screen.setPanelMounted: (mounted: boolean) => ({ mounted }),+ // Ask the server whether the current project has an active wizard cloud run, seeding the+ // handle when the drop flow started the run server-side (so no local handle was ever written).+ hydrateFromServer: true,}),reducers({persistedCloudRun: [@@ -77,5 +84,52 @@ export const activeCloudRunLogic = kea<activeCloudRunLogicType>([(persistedCloudRun, currentProjectId): CloudRunHandle | null =>scopedCloudRun(persistedCloudRun, currentProjectId),],+ // The two inputs hydrateFromServer needs, both of which load asynchronously after mount.+ // We wait for this to flip true rather than firing once on mount, so a run started for a+ // provisioned user before their user/project loaded still gets hydrated.+ canHydrateFromServer: [+ (s) => [s.isProvisionedUser, s.currentProjectId],+ (isProvisionedUser, currentProjectId): boolean => isProvisionedUser && currentProjectId != null,+ ],}),+ listeners(({ actions, values }) => ({+ hydrateFromServer: async () => {+ // The drop flow starts the run server-side, so a freshly-signed-in provisioned user has+ // no localStorage handle. Only they need the extra request; everyone else already has a+ // client-written handle if a run exists.+ if (!values.isProvisionedUser) {+ return+ }+ const projectId = values.currentProjectId+ if (projectId == null || values.activeCloudRun) {+ // Never clobber a fresher local handle — server hydration is a fallback only.+ return+ }+ try {+ const handle = await tasksActiveWizardRunRetrieve(String(projectId))+ // 204 → void; nothing to surface.+ if (!handle || values.activeCloudRun) {+ return+ }+ actions.setActiveCloudRun(+ handle.task_id,+ handle.run_id,+ handle.started_at ?? new Date().toISOString(),+ projectId+ )+ } catch {+ // Best-effort: a failed hydration just means no FAB, same as before.+ }+ },+ })),+ subscriptions(({ actions }) => ({+ // Fires once on mount (with the current value) and again whenever readiness changes, so+ // hydration runs as soon as both inputs are available — not just if they happened to be+ // ready at mount. hydrateFromServer is idempotent, so a no-op false value is harmless.+ canHydrateFromServer: (canHydrate: boolean) => {+ if (canHydrate) {+ actions.hydrateFromServer()+ }+ },+ })),])diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex 904988e9c9cd..f1ce8f367065 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -643,6 +643,11 @@ export const userLogic = kea<userLogicType>([}},],+ // True for accounts created by a partner drop flow (onboarding skipped with reason+ // 'provisioned'). Drives the provisioned welcome experience — background-install FAB,+ // welcome dialog, quick-start seeding, and the homepage banner.+ isProvisionedUser: [(s) => [s.user], (user): boolean => user?.onboarding_skipped_reason === 'provisioned'],+otherOrganizations: [(s) => [s.user],(user): OrganizationBasicType[] =>diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex e2815cadbcca..30d8caf639a1 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -336,7 +336,7 @@ export type UserShortcutPosition = 'above' | 'below' | 'hidden'// Mirrors posthog.models.user.OnboardingSkippedReason. Kept as a union here to avoid a// hard dependency on generated types; when adopting generated `UserApi`, switch to// `OnboardingSkippedReasonEnumApi` from `~/generated/core/api.schemas`.-export type OnboardingSkippedReason = 'delegated' | 'later' | 'other' | null+export type OnboardingSkippedReason = 'delegated' | 'later' | 'other' | 'provisioned' | null/** Full User model. */export interface UserType extends UserBaseType {diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex d539240cb3c3..f46cf018a313 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -95,71 +95,6 @@ const ACCOUNT_WITHOUT_LINKS = {const EMPTY_INSIGHTS = { count: 0, next: null, previous: null, results: [] }-function insightsResponse(insight: Record<string, unknown>): Record<string, unknown> {- return { count: 1, next: null, previous: null, results: [insight] }-}--const BILLING_VARIABLES = {- 'var-org': { variableId: 'var-org', code_name: 'billing_org_id', value: '' },- 'var-start': { variableId: 'var-start', code_name: 'billing_start_date', value: '2026-04-21' },- 'var-end': { variableId: 'var-end', code_name: 'billing_end_date', value: '2026-05-21' },-}--const USAGE_INSIGHT = {- id: 9050931,- short_id: 'fiJDsKLp',- name: 'Billing usage by type (warehouse)',- filters: {},- saved: true,- deleted: false,- query: {- kind: 'DataVisualizationNode',- display: 'ActionsLineGraph',- source: {- kind: 'HogQLQuery',- query: 'SELECT date, ... FROM postgres.prod.billing_usagereport',- variables: BILLING_VARIABLES,- },- },-}--const USAGE_QUERY_RESPONSE = {- error: '',- hasMore: false,- is_cached: true,- query_status: null,- columns: ['date', 'Events', 'Recordings'],- types: [- ['date', 'Date'],- ['Events', 'Nullable(Float64)'],- ['Recordings', 'Nullable(Float64)'],- ],- results: [- ['2026-05-01', 1200, 30],- ['2026-05-08', 1800, 45],- ['2026-05-15', 1500, 38],- ['2026-05-21', 2100, 52],- ],-}--// Dispatches the shared query endpoint: account rows for the list, billing chart data for the embedded insight.-function mockAccountsAndBillingQuery(- rows: AccountRow[],- billingResponse: Record<string, unknown>-): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {- return async ({ request }) => {- const body = (await request.json()) as { query?: { kind?: string } }- const kind = body?.query?.kind- if (kind === 'AccountsQuery') {- return [200, buildAccountsQueryResponse(rows)]- }- if (kind === 'HogQLQuery') {- return [200, billingResponse]- }- return undefined- }-}-// Billing tab stories share the same account + notebooks mocks; they differ only in the insight and query responses.function billingTabDecorators(insightsGet: Record<string, unknown>,@@ -404,34 +339,3 @@ export const RowExpandedUsageNotFound: Story = {await within(canvasElement).findByText('No billing usage insight here')},}--export const RowExpandedUsagePopulated: Story = {- render: () => <App />,- parameters: {- testOptions: {- ...EXPANDED_ROW_TEST_OPTIONS,- // Wait for the canvas to render before snapshotting — the chart is async and can- // take a while in CI. Using waitForSelector (60s budget) instead of a play-function- // waitFor avoids exceeding the 60s Jest test timeout.- waitForSelector: [- '[data-attr="accounts-refresh"]',- '[data-attr="account-expansion"]',- '.DataVisualization canvas',- ],- },- },- decorators: billingTabDecorators(- insightsResponse(USAGE_INSIGHT),- mockAccountsAndBillingQuery(SINGLE_ROW, USAGE_QUERY_RESPONSE)- ),- play: async ({ canvasElement }) => {- // Minimal play: expand row and switch tab without waiting for sidebar links.- // The sidebar waits in expandAndOpenTab can take 20-30s under CI load, which- // combined with the postVisit waitForSelector for the canvas exceeds the 60s- // Jest timeout. We only need the tab switch here — the canvas is verified by- // waitForSelector in testOptions above.- const canvas = within(canvasElement)- await userEvent.click(await canvas.findByTitle('Show more'))- await userEvent.click(await canvas.findByRole('tab', { name: 'Usage' }))- },-}diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.tsindex 5f4a960b63e5..bf98c2ddc4f7 100644--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts@@ -97,5 +97,18 @@ describe('accountBillingLogic', () => {expect(nextQueryKey).toContain('2024-01-01')expect(nextQueryKey).toContain('2024-01-31')})++ // Environments without the saved billing insight (or a failing fetch) must degrade to an+ // empty list, which is what drives the tab's not-found state instead of a crash or broken chart.+ it.each([+ ['is absent', () => jest.spyOn(insightsApi, 'getByShortId').mockResolvedValue(null)],+ ['fails to load', () => jest.spyOn(insightsApi, 'getByShortId').mockRejectedValue(new Error('boom'))],+ ])('resolves to no saved insights when the billing insight %s', async (_label, mockGetByShortId) => {+ mockGetByShortId()+ mountForKind()++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.savedInsights).toEqual([])+ })})})diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex b0b9816812bf..ab3a86bd9776 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -145,6 +145,7 @@ __all__ = ["fail_task_run","finalize_task_run_artifact_uploads","finalize_task_staged_artifacts",+ "get_active_wizard_cloud_run","get_code_home","get_code_workflow_config","get_conversation_task_dtos",@@ -624,6 +625,51 @@ def get_latest_run_by_task(task_ids: Iterable[str | UUID]) -> dict[str, contractreturn {str(run.task_id): _task_run_to_dto(run) for run in runs}+def get_active_wizard_cloud_run(team_id: int) -> contracts.WizardCloudRunDTO | None:+ """The team's active onboarding wizard cloud run, for rehydrating the setup FAB.++ The drop flow starts the wizard cloud run server-side (``create_wizard_cloud_run``),+ so a freshly-signed-in user has no client-side handle. Returns the most recent run+ across the team's onboarding (``ORIGIN_PRODUCT == ONBOARDING``) tasks that's still+ running, or completed within the last day (so we can show "PostHog is wired up" ++ the PR); otherwise ``None``. Team-scoped.+ """+ onboarding_task_ids = Task.objects.filter(+ team_id=team_id, origin_product=Task.OriginProduct.ONBOARDING, archived=False+ ).values_list("id", flat=True)+ fresh_after = django_timezone.now() - timedelta(days=1)+ # Scan runs newest-first and surface the first that qualifies: picking the newest task up front+ # would let a newer onboarding task with no live run hide an older task's still-running one.+ # Both the task set and the run are scoped by team_id so a mismatched/legacy run row can't leak+ # another team's handle back to the requester.+ #+ # ``origin_product == ONBOARDING`` is caller-settable, so it alone can't tell a genuine+ # server-started wizard run from one a project member planted through the normal task APIs.+ # Also require the immutable markers ``create_wizard_cloud_run`` stamps: a cloud environment+ # and the ``wizard_config`` state key (a protected key callers cannot set, see the run PATCH+ # allowlist), so we never hand a provisioned user someone else's attacker-controlled handle.+ runs = TaskRun.objects.filter(+ task_id__in=onboarding_task_ids,+ team_id=team_id,+ environment=TaskRun.Environment.CLOUD,+ state__has_key="wizard_config",+ ).order_by("-created_at", "-id")+ for run in runs:+ # Non-terminal runs always surface; terminal ones only while the result is still+ # fresh enough to be worth showing on first landing.+ if run.is_terminal:+ anchor = run.updated_at or run.created_at+ if anchor is None or anchor < fresh_after:+ continue+ return contracts.WizardCloudRunDTO(+ task_id=run.task_id,+ run_id=run.id,+ status=run.status,+ started_at=run.created_at,+ )+ return None++def get_stale_queued_task_run_ids(older_than: timedelta,limit: int,diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 29b2007bf035..e7875b6dfc77 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -41,6 +41,21 @@ class TaskDTO:slug: str = ""+@dataclass(frozen=True)+class WizardCloudRunDTO:+ """A team's active onboarding wizard cloud run.++ Lets the frontend rehydrate the setup-progress FAB from the server when the drop+ flow started the run server-side (so no client-side localStorage handle exists).+ Carries only what the FAB's cloud stream needs to reconnect.+ """++ task_id: UUID+ run_id: UUID+ status: str+ started_at: datetime | None = None++@dataclass(frozen=True)class TaskRunDTO:"""A single execution of a task.diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 91d58f1f8f96..16e73a92884a 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -33,6 +33,7 @@ from products.tasks.backend.facade.contracts import (TaskSummaryDTO,TaskThreadMessageDTO,TaskUserBasicInfo,+ WizardCloudRunDTO,)from products.tasks.backend.facade.run_config import (ALL_INITIAL_PERMISSION_MODE_CHOICES,@@ -308,6 +309,22 @@ class TaskRunDetailSerializer(DataclassSerializer):]+class WizardCloudRunSerializer(DataclassSerializer):+ """The team's active onboarding wizard cloud run, used to rehydrate+ the setup-progress FAB when the run was started server-side (drop flow)."""++ task_id = serializers.UUIDField(help_text="Id of the onboarding wizard task.")+ run_id = serializers.UUIDField(help_text="Id of the task's latest run, for reconnecting to its progress stream.")+ status = serializers.CharField(help_text="Latest run status (e.g. queued, in_progress, completed, failed).")+ started_at = serializers.DateTimeField(+ allow_null=True, required=False, help_text="When the run was created, for the FAB's elapsed timer."+ )++ class Meta:+ dataclass = WizardCloudRunDTO+ fields = ["task_id", "run_id", "status", "started_at"]++# The relationship a client asserts between a task and a signal report when creating a task from the# report (e.g. PostHog Code inbox), recorded as a signals `task_run` work-log entry. This is a# free-form label — the same as the `task_run` artefact `(product, type)` values, which have neverdiff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 92237adb81ac..79c1d2fab414 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -114,6 +114,7 @@ from products.tasks.backend.presentation.serializers import (TaskWriteSerializer,WarmTaskRequestSerializer,WarmTaskResponseSerializer,+ WizardCloudRunSerializer,)from ee.hogai.utils.aio import async_to_sync@@ -322,6 +323,35 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer = TaskRepositoriesResponseSerializer({"repositories": repositories})return Response(serializer.data)+ @extend_schema(+ responses={+ 200: OpenApiResponse(+ response=WizardCloudRunSerializer,+ description="The team's active onboarding wizard cloud run.",+ ),+ 204: OpenApiResponse(description="No active onboarding wizard cloud run for this project."),+ },+ summary="Get the team's active onboarding wizard cloud run",+ description=(+ "Returns the most recent onboarding wizard cloud run for the current project when it is "+ "still running (or completed within the last day), so the setup-progress FAB can rehydrate "+ "after a drop-flow signup that started the run server-side. Returns 204 when there is none."+ ),+ )+ @action(+ detail=False,+ methods=["get"],+ url_path="active_wizard_run",+ required_scopes=["task:read"],+ pagination_class=None,+ filter_backends=[],+ )+ def active_wizard_run(self, request, **kwargs):+ run = tasks_facade.get_active_wizard_cloud_run(self.team_id)+ if run is None:+ return Response(status=status.HTTP_204_NO_CONTENT)+ return Response(WizardCloudRunSerializer(run).data)+@validated_request(request_serializer=TaskSummariesRequestSerializer,responses={diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex b0048467d089..2c23c637418a 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -115,6 +115,96 @@ class TestFacadeReadsAndMappers(TestCase):other_user = User.objects.create(email="[email protected]", distinct_id="other")self.assertFalse(facade.is_task_controllable_by_user(task.id, other_user.id))+ def _make_wizard_run(self, task: Task, status: TaskRun.Status, **kwargs) -> TaskRun:+ # A genuine server-started wizard run carries the markers create_wizard_cloud_run stamps:+ # a cloud environment and the (caller-unsettable) wizard_config state key.+ kwargs.setdefault("environment", TaskRun.Environment.CLOUD)+ kwargs.setdefault("state", {"wizard_config": {}})+ return TaskRun.objects.create(+ task=task,+ team=task.team,+ status=status,+ **kwargs,+ )++ def test_get_active_wizard_cloud_run_returns_latest_onboarding_run(self):+ task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ self._make_wizard_run(task, TaskRun.Status.QUEUED)+ latest = self._make_wizard_run(task, TaskRun.Status.IN_PROGRESS)++ run = facade.get_active_wizard_cloud_run(self.team.id)+ assert run is not None+ self.assertIsInstance(run, contracts.WizardCloudRunDTO)+ self.assertEqual(run.task_id, task.id)+ self.assertEqual(run.run_id, latest.id)+ self.assertEqual(run.status, TaskRun.Status.IN_PROGRESS.value)++ def test_get_active_wizard_cloud_run_ignores_non_onboarding_tasks(self):+ task = self._make_task(origin_product=Task.OriginProduct.USER_CREATED)+ self._make_wizard_run(task, TaskRun.Status.IN_PROGRESS)+ self.assertIsNone(facade.get_active_wizard_cloud_run(self.team.id))++ def test_get_active_wizard_cloud_run_ignores_user_created_run_without_wizard_markers(self):+ # A project member could create an onboarding task and bootstrap a cloud run through the+ # normal task APIs, but they can't set the protected wizard_config marker — so such a+ # planted run must never be surfaced to a provisioned teammate as the active wizard run.+ task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ TaskRun.objects.create(+ task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS, environment=TaskRun.Environment.CLOUD+ )+ self.assertIsNone(facade.get_active_wizard_cloud_run(self.team.id))++ genuine = self._make_wizard_run(task, TaskRun.Status.IN_PROGRESS)+ run = facade.get_active_wizard_cloud_run(self.team.id)+ assert run is not None+ self.assertEqual(run.run_id, genuine.id)++ def test_get_active_wizard_cloud_run_ignores_local_run(self):+ task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ self._make_wizard_run(task, TaskRun.Status.IN_PROGRESS, environment=TaskRun.Environment.LOCAL)+ self.assertIsNone(facade.get_active_wizard_cloud_run(self.team.id))++ def test_get_active_wizard_cloud_run_surfaces_recently_completed_run(self):+ task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ run = self._make_wizard_run(task, TaskRun.Status.COMPLETED)+ handle = facade.get_active_wizard_cloud_run(self.team.id)+ assert handle is not None+ self.assertEqual(handle.run_id, run.id)++ def test_get_active_wizard_cloud_run_drops_stale_completed_run(self):+ task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ run = self._make_wizard_run(task, TaskRun.Status.COMPLETED)+ # auto_now fields can't be set on create — force them past the freshness window.+ stale = django_timezone.now() - timedelta(days=2)+ TaskRun.objects.filter(id=run.id).update(created_at=stale, updated_at=stale)+ self.assertIsNone(facade.get_active_wizard_cloud_run(self.team.id))++ def test_get_active_wizard_cloud_run_is_team_scoped(self):+ other_team = Team.objects.create(organization=self.organization, name="Other")+ task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ self._make_wizard_run(task, TaskRun.Status.IN_PROGRESS)+ self.assertIsNone(facade.get_active_wizard_cloud_run(other_team.id))++ def test_get_active_wizard_cloud_run_surfaces_older_active_run_behind_newer_stale_task(self):+ # The newest onboarding task's run is stale, but an older task still has a live run:+ # keying off task-recency alone would return nothing and hide the active run.+ older_task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ active = self._make_wizard_run(older_task, TaskRun.Status.IN_PROGRESS)+ newer_task = self._make_task(origin_product=Task.OriginProduct.ONBOARDING)+ stale_run = self._make_wizard_run(newer_task, TaskRun.Status.COMPLETED)+ now = django_timezone.now()+ TaskRun.objects.filter(id=active.id).update(+ created_at=now - timedelta(days=3), updated_at=now - timedelta(days=3)+ )+ TaskRun.objects.filter(id=stale_run.id).update(+ created_at=now - timedelta(days=2), updated_at=now - timedelta(days=2)+ )++ handle = facade.get_active_wizard_cloud_run(self.team.id)+ assert handle is not None+ self.assertEqual(handle.task_id, older_task.id)+ self.assertEqual(handle.run_id, active.id)+def test_count_in_progress_runs_for_github_integration_scopes_to_live_runs_of_that_integration(self):integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})other_integration = Integration.objects.create(team=self.team, kind="github", config={}, sensitive_config={})diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 6f6ea91bfa81..576814191853 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -2281,6 +2281,24 @@ export interface TaskThreadMessageWriteApi {content: string}+/**+ * The team's active onboarding wizard cloud run, used to rehydrate+ * the setup-progress FAB when the run was started server-side (drop flow).+ */+export interface WizardCloudRunDTOApi {+ /** Id of the onboarding wizard task. */+ task_id: string+ /** Id of the task's latest run, for reconnecting to its progress stream. */+ run_id: string+ /** Latest run status (e.g. queued, in_progress, completed, failed). */+ status: string+ /**+ * When the run was created, for the FAB's elapsed timer.+ * @nullable+ */+ started_at?: string | null+}+export interface TaskRepositoriesResponseApi {/** Distinct repositories in use by non-deleted, non-internal tasks for the current team. */repositories: string[]diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex ebd3d4e46d85..4050ba8b3e1e 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -91,6 +91,7 @@ import type {TasksThreadMessagesListParams,WarmTaskRequestApi,WarmTaskResponseApi,+ WizardCloudRunDTOApi,} from './api.schemas'export const getCodeInvitesCheckAccessRetrieveUrl = () => {@@ -1605,6 +1606,24 @@ export const tasksThreadMessagesSendToAgentCreate = async (})}+export const getTasksActiveWizardRunRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/tasks/active_wizard_run/`+}++/**+ * Returns the most recent onboarding wizard cloud run for the current project when it is still running (or completed within the last day), so the setup-progress FAB can rehydrate after a drop-flow signup that started the run server-side. Returns 204 when there is none.+ * @summary Get the team's active onboarding wizard cloud run+ */+export const tasksActiveWizardRunRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<WizardCloudRunDTOApi | void> => {+ return apiMutator<WizardCloudRunDTOApi | void>(getTasksActiveWizardRunRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getTasksRepositoriesRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/tasks/repositories/`}diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yamlindex 0e3006ff5a59..9c66fbfcc29e 100644--- a/products/tasks/mcp/tools.yaml+++ b/products/tasks/mcp/tools.yaml@@ -87,6 +87,9 @@ tools:task-mentions-list:operation: task_mentions_listenabled: false+ tasks-active-wizard-run-retrieve:+ operation: tasks_active_wizard_run_retrieve+ enabled: falsetasks-create:operation: tasks_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 12d0572e5c66..787d1bab8c47 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -61477,6 +61477,24 @@ export namespace Schemas {results: WidgetCatalogEntry[];}+ /**+ * The team's active onboarding wizard cloud run, used to rehydrate+ * the setup-progress FAB when the run was started server-side (drop flow).+ */+ export interface WizardCloudRunDTO {+ /** Id of the onboarding wizard task. */+ task_id: string;+ /** Id of the task's latest run, for reconnecting to its progress stream. */+ run_id: string;+ /** Latest run status (e.g. queued, in_progress, completed, failed). */+ status: string;+ /**+ * When the run was created, for the FAB's elapsed timer.+ * @nullable+ */+ started_at?: string | null;+ }+export interface WorkflowHealthBucket {/** Bucket start, aligned to the item's granularity (top of hour, midnight, or Monday). */bucket_start: string;