: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): attribute wizard runs to the user who started them (#74373)
Rafael Audibert03f79f898c1c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d1a56ba7831f..0f5d96d0b434 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7727,9 +7727,9 @@ snapshots:scenes-other-onboarding-shared-wizard-cloud-run--run-it-yourself--light:hash: v1.k794b7964.6929d887dd4bcc9ac0c6fcc32e16d829771b0f97f38af905b7e62752c0b39a97.p5weyrIGjeKhnV6FuarEp-O82xPcQjs8cKYuLGLiEzcscenes-other-onboarding-shared-wizard-sync-card--all-states--dark:- hash: v1.k794b7964.610af7be0cbae0d8376dd7e61322612efdddbcb3d05be1fc6ac207652703b43a.bedJrmXY8fLxRiAI-ETzr2ook0bKDAyyluxsI0fgAPA+ hash: v1.k794b7964.65526a55e7a2c0658e60e0c330a015430f561d3d80b3c2463408d6120b6cd078.a3tsBW_wyWyuhTAvUbgNVRx6rqStiMURSToOppQEIbgscenes-other-onboarding-shared-wizard-sync-card--all-states--light:- hash: v1.k794b7964.4d66c7e4d4abbf5853fd62ca35c61eab1a81a53074d7353dfeb99475160505f5.Ineb2GA1mTqEg3KwUd_P0Y6hbdM6FKJRxuBzCNfYOFU+ hash: v1.k794b7964.f744986e88baa2e34e13bb3c2dd9cfdec58e6e1741599ef7be96174720f3396a.IU3v7Hpl82zzZjvuQxEnRkXUTF0GEPAF2NBWdwCqcZgscenes-other-onboarding-shared-wizard-sync-card--cloud-keeping-ci-green--dark:hash: v1.k794b7964.fba9c3af456f60a00dec760305609433d1d8ffb609f1573352f71cb29f1fa6b2.2tmy7T0O1t2rw1SYTOXCMCePVPleYZWjuUnc4EU5a7Qscenes-other-onboarding-shared-wizard-sync-card--cloud-keeping-ci-green--light:@@ -7766,6 +7766,10 @@ snapshots:hash: v1.k794b7964.f074463c40fd8b34d0ca55c651b409fb35668ecc69fefb4e631208b3f5db1bde.zioGxlu5eKa64EXl2wzmAT4K-EC_0eK5uoUMxZIu98Yscenes-other-onboarding-shared-wizard-sync-card--local-waiting-for-sensitive-input--light:hash: v1.k794b7964.57524d53d6835dd9472c87a6aca291266fb8e8971d95ba311842386f94347fc8.sMjUBzJVzLkCThwa5LT8ntVK63w5tJ0lYltmn2pD70E+ scenes-other-onboarding-shared-wizard-sync-card--local-running-started-by-teammate--dark:+ hash: v1.k794b7964.9238cd8306270044b6be400d8b253942a6ebc7639dac27e091afe3afb5900291.1tQS7yVR_gZ7fmjjzoegrw7GXmePG9-QafLgOaddLfo+ scenes-other-onboarding-shared-wizard-sync-card--local-running-started-by-teammate--light:+ hash: v1.k794b7964.311090aa83634a64027ca60d44a1ac93ecb22124f9144032439c364e0e513105.jEWKZmu_Lw9ugOlP0970x-jQom-SKcWM7N__q-UTgT8scenes-other-onboarding-shared-wizard-sync-card--playground--dark:hash: v1.k794b7964.c69534afe39d0311b0ed3247beb145b94381706a25f2e6c7b5d3415c87564375.ViSw0_amXLmDYynCEuR_kgnY5Ncm4ULveglgIJoTIaUscenes-other-onboarding-shared-wizard-sync-card--playground--light:diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsxindex a698543c981c..749263a7afa5 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/InstallationProgressView.stories.tsx@@ -53,6 +53,7 @@ function progress(overrides: Partial<InstallationProgress>): InstallationProgresprMerged: false,isCurrent: true,pendingInput: null,+ startedBy: null,...overrides,}}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.stories.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.stories.tsxindex 47a1262fd012..60c1ed310b01 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.stories.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.stories.tsx@@ -58,6 +58,7 @@ function progress(overrides: Partial<InstallationProgress>): InstallationProgresprMerged: false,isCurrent: true,pendingInput: null,+ startedBy: null,...overrides,}}@@ -153,6 +154,22 @@ export const LocalRunning: Story = {},}+// Local run started by a teammate: the chip names them instead of "On your machine".+export const LocalRunningStartedByTeammate: Story = {+ args: {+ mode: 'local',+ elapsedSeconds: 47,+ startedByLabel: 'Edwin',+ progress: progress({+ steps: [+ { id: 'plan', label: 'Plan event tracking', status: 'completed', detail: null },+ { id: 'install', label: 'Install PostHog', status: 'in_progress', detail: null },+ { id: 'capture', label: 'Capture events', status: 'pending', detail: null },+ ],+ }),+ },+}+export const Completed: Story = {args: {mode: 'cloud',@@ -220,6 +237,7 @@ export const AllStates: Story = {{ label: 'Cloud, wizard running', args: CloudWizardRunning.args },{ label: 'Cloud, keeping CI green', args: CloudKeepingCiGreen.args },{ label: 'Local, running', args: LocalRunning.args },+ { label: 'Local, started by a teammate', args: LocalRunningStartedByTeammate.args },{ label: 'Completed', args: Completed.args },{ label: 'Completed, local (dashboard payoff)', args: CompletedLocal.args },{ label: 'Stalled', args: Stalled.args },@@ -235,6 +253,7 @@ export const AllStates: Story = {elapsedSeconds={args!.elapsedSeconds!}mode={args!.mode!}stale={args!.stale}+ startedByLabel={args!.startedByLabel}dashboard={args!.dashboard}onExpand={() => {}}onDismiss={() => {}}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsxindex 2a383c290a8a..eff161e24fe5 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncCard.tsx@@ -48,12 +48,16 @@ export function StatusGlyph({ progress }: { progress: InstallationProgress }): Jreturn <Spinner className="text-xl shrink-0 text-accent" textColored />}+export function localModeLabel(startedByLabel?: string | null): string {+ return startedByLabel ? `On ${startedByLabel}'s machine` : 'On your machine'+}+// Tiny chip naming where the run is happening, so cloud and local runs read distinctly.-function ModeChip({ mode }: { mode: WizardSyncMode }): JSX.Element {+function ModeChip({ mode, startedByLabel }: { mode: WizardSyncMode; startedByLabel?: string | null }): JSX.Element {return (<span className="inline-flex items-center gap-1 text-xs text-muted">{mode === 'cloud' ? <IconCloud className="text-sm" /> : <IconLaptop className="text-sm" />}- {mode === 'cloud' ? 'Cloud run' : 'On your machine'}+ {mode === 'cloud' ? 'Cloud run' : localModeLabel(startedByLabel)}</span>)}@@ -74,12 +78,15 @@ export function WizardSyncCard({onExpand,onDismiss,dismissTooltip = 'Dismiss',+ startedByLabel,}: {progress: InstallationProgresselapsedSeconds: numbermode: WizardSyncMode/** The run has gone quiet: the clock is replaced by the reason it stopped meaning anything. */stale?: boolean+ /** A teammate's name for a local run they started (null when it's the viewer's own run or unknown). */+ startedByLabel?: string | null/** Dashboard the wizard built, when detected — the completed card's payoff for runs with no PR. */dashboard?: DetectedDashboard | null/** Telemetry hook for the dashboard CTA — navigation itself rides the button's `to`. */@@ -157,7 +164,7 @@ export function WizardSyncCard({</button><div className="flex items-center justify-between gap-2 px-3.5 py-2 border-t border-primary">- <ModeChip mode={mode} />+ <ModeChip mode={mode} startedByLabel={startedByLabel} /><div className="flex items-center gap-1">{progress.prUrl && (// ph-no-capture: the label carries the customer's repo name and the hrefdiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsxindex 9c94deb13180..df162be1bd5a 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncFab.tsx@@ -6,6 +6,7 @@ import { LemonButton, LemonModal } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { cn } from 'lib/utils/css-classes'import { elapsedSecondsFrom } from 'lib/utils/datetime'+import { userLogic } from 'scenes/userLogic'import { onboardingEventUsageLogic } from '../../onboardingEventUsageLogic'import { activeCloudRunLogic, CloudRunHandle } from './activeCloudRunLogic'@@ -19,9 +20,20 @@ import {import { InstallationProgressContent } from './InstallationProgressView'import { wizardActiveSessionDetectorLogic } from './wizardActiveSessionDetectorLogic'import { DetectedDashboard, wizardDashboardLogic } from './wizardDashboardLogic'-import { StatusGlyph, WizardSyncCard, WizardSyncMode } from './WizardSyncCard'+import { localModeLabel, StatusGlyph, WizardSyncCard, WizardSyncMode } from './WizardSyncCard'import { wizardSyncUiLogic } from './wizardSyncUiLogic'+// The teammate's name, or null for the viewer's own run (matched on email) or an unknown initiator.+function resolveStartedByLabel(+ startedBy: InstallationProgress['startedBy'],+ currentUserEmail: string | undefined+): string | null {+ if (!startedBy || startedBy.email === currentUserEmail) {+ return null+ }+ return startedBy.name+}+// Corner anchor for the collapsed card and the minimized launcher. The dialog is a portal, so it// positions itself.const CORNER = 'fixed bottom-5 right-5 z-[60]'@@ -89,6 +101,7 @@ function WizardSyncDialog({onCancel,cancelling = false,stale = false,+ startedByLabel,onDashboardClick,}: {progress: InstallationProgress@@ -102,6 +115,8 @@ function WizardSyncDialog({cancelling?: boolean/** The run has gone quiet for long enough that it can be dismissed without orphaning live work. */stale?: boolean+ /** A teammate's name for a local run they started (null when it's the viewer's own run or unknown). */+ startedByLabel?: string | nullonDashboardClick?: () => void}): JSX.Element {const isTerminal = progress.phase === 'completed' || progress.phase === 'error'@@ -111,7 +126,8 @@ function WizardSyncDialog({<div className="flex items-center justify-between text-xs"><span className={cn('font-medium', toneTextClass(progress))}>{syncHeadline(progress)}</span><span className="text-muted tabular-nums">- {mode === 'cloud' ? 'Cloud run' : 'On your machine'} · {elapsedLabel(elapsedSeconds, stale)}+ {mode === 'cloud' ? 'Cloud run' : localModeLabel(startedByLabel)} ·{' '}+ {elapsedLabel(elapsedSeconds, stale)}</span></div><InstallationProgressContent@@ -181,6 +197,8 @@ function WizardSyncSurface({}): JSX.Element {const { dismissedKey, dialogOpen } = useValues(wizardSyncUiLogic)const { dismiss, restore, openDialog, closeDialog } = useActions(wizardSyncUiLogic)+ const { user } = useValues(userLogic)+ const startedByLabel = resolveStartedByLabel(progress.startedBy, user?.email)const {reportWizardSyncExpanded,reportWizardSyncMinimized,@@ -260,6 +278,7 @@ function WizardSyncSurface({elapsedSeconds={elapsedSeconds}mode={mode}stale={stale}+ startedByLabel={startedByLabel}dashboard={dashboard}onDashboardClick={handleDashboardClick}onExpand={() => {@@ -280,6 +299,7 @@ function WizardSyncSurface({elapsedSeconds={elapsedSeconds}mode={mode}stale={stale}+ startedByLabel={startedByLabel}dashboard={dashboard}onDashboardClick={handleDashboardClick}isOpen={dialogOpen}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/finishedLocalRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/finishedLocalRunLogic.tsindex e89a06553b2a..e069336c32b3 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/finishedLocalRunLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/finishedLocalRunLogic.ts@@ -4,6 +4,7 @@ import { projectLogic } from 'scenes/projectLogic'import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'+import { startedByFromSession } from './helpers'import { wizardDashboardLogic } from './wizardDashboardLogic'/** A terminal local wizard run, snapshotted so its handoff outlives the session stream. */@@ -16,6 +17,7 @@ export interface FinishedLocalRunHandle {runPhase: 'completed' | 'error'tasks: { id: string; title: string; status: string }[]error: { message?: string } | null+ startedBy?: { name: string; email: string } | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -135,6 +137,7 @@ export const finishedLocalRunLogic = kea<finishedLocalRunLogicType>([runPhase: session.run_phase === 'error' ? 'error' : 'completed',tasks: (session.tasks ?? []).map((t) => ({ id: t.id, title: t.title, status: t.status })),error: (session.error as { message?: string } | null) ?? null,+ startedBy: startedByFromSession(session),})if (session.run_phase === 'completed') {actions.detectWizardDashboard({ startedAt: session.started_at })diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.tsindex 9c1c74adb429..1305970cad97 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/helpers.ts@@ -1,6 +1,17 @@-import { InstallationProgress, InstallationStep, InstallationStepStatus } from './installationProgressLogic'+import type { WizardSessionDTOApi } from 'products/wizard/frontend/generated/api.schemas'++import type { InstallationProgress, InstallationStep, InstallationStepStatus } from './installationProgressLogic'import type { TaskRunConnectionStatus } from './taskRunStreamLogic'+// Prefer a real name; fall back to email so we never render a blank attribution.+export function startedByFromSession(session: WizardSessionDTOApi | null): { name: string; email: string } | null {+ const createdBy = session?.created_by+ if (!createdBy) {+ return null+ }+ return { name: createdBy.first_name || createdBy.email, email: createdBy.email }+}+// Ceiling on the displayed elapsed time. The clock is driven by a persisted handle that outlives the// run it names, so without a cap a run nobody ever settled counts up for as long as the browser keeps// the handle. Display only: telemetry keeps the true elapsed.diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.tsindex 499f96cb29f8..c9dee592e25f 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.test.ts@@ -326,6 +326,20 @@ describe('installationProgressLogic merge', () => {// flag alone would keep the completed panel pinned until the next remount.expect(localProgress(session({ run_phase: 'completed' }), 'open', true, true).isCurrent).toBe(false)})++ it('names the initiator, preferring first name and falling back to email', () => {+ // The card reads "On <name>'s machine"; a blank first_name must fall back to email so it+ // never renders "On 's machine".+ expect(+ localProgress(session({ created_by: { id: 1, first_name: 'Edwin', email: '[email protected]' } }), 'open', true)+ .startedBy+ ).toEqual({ name: 'Edwin', email: '[email protected]' })+ expect(+ localProgress(session({ created_by: { id: 1, first_name: '', email: '[email protected]' } }), 'open', true)+ .startedBy+ ).toEqual({ name: '[email protected]', email: '[email protected]' })+ expect(localProgress(session(), 'open', true).startedBy).toBeNull()+ })})describe('pendingInput', () => {@@ -402,9 +416,19 @@ describe('installationProgressLogic merge', () => {prMerged: false,isCurrent: true,pendingInput: null,+ startedBy: null,})})+ it('carries the snapshotted initiator so the finished-run handoff can still name them', () => {+ // The handle outlives the session stream; without this the card would drop the+ // attribution the moment it switched from the live stream to the snapshot.+ const result = progressFromFinishedLocalRun(+ handle({ startedBy: { name: 'Edwin', email: '[email protected]' } })+ )+ expect(result.startedBy).toEqual({ name: 'Edwin', email: '[email protected]' })+ })+it('surfaces the persisted error on failed runs', () => {const result = progressFromFinishedLocalRun(handle({ runPhase: 'error', error: { message: 'boom' } }))expect(result.phase).toBe('error')diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.tsindex 848bf4956406..540df63bc8b5 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/installationProgressLogic.ts@@ -23,6 +23,7 @@ import type { WizardConnectionStatus } from '../../../../../../products/wizard/fimport { activeCloudRunLogic } from './activeCloudRunLogic'import type { CloudRunHandle } from './activeCloudRunLogic'import { finishedLocalRunLogic, FinishedLocalRunHandle } from './finishedLocalRunLogic'+import { startedByFromSession } from './helpers'import {taskRunPrMerged,taskRunPrUrl,@@ -141,6 +142,8 @@ export interface InstallationProgress {/** Set while the wizard is waiting on the user in the terminal — the widget's attention state.* Cleared by the next session push without the field (answered, cancelled, or timed out). */pendingInput: WizardPendingInput | null+ /** Who started the run (null when unknown). `email` is for the "is this me?" check. */+ startedBy: { name: string; email: string } | null}export interface InstallationProgressLogicProps {@@ -329,6 +332,7 @@ export function cloudProgress(prMerged,isCurrent: phase !== 'idle',pendingInput: phase === 'running' ? pendingInputFromSession(session) : null,+ startedBy: startedByFromSession(session),}}@@ -351,6 +355,7 @@ export function localProgress(prMerged: false,isCurrent: false,pendingInput: null,+ startedBy: null,}}@@ -388,6 +393,7 @@ export function localProgress(prMerged: false,isCurrent: sessionIsCurrent && !dismissed,pendingInput: phase === 'running' && !dismissed ? pendingInputFromSession(latestSession) : null,+ startedBy: startedByFromSession(latestSession),}}@@ -405,6 +411,7 @@ export function progressFromFinishedLocalRun(handle: FinishedLocalRunHandle): InprMerged: false,isCurrent: true,pendingInput: null,+ startedBy: handle.startedBy ?? null,}}diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.tsindex 4acdcb47f8f7..17362f07b517 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardActiveSessionDetectorLogic.test.ts@@ -27,6 +27,7 @@ function makeSession(overrides: Partial<WizardSessionDTOApi> = {}): WizardSessioevent_plan: null,error: null,pending_input: null,+ created_by: null,created_at: new Date().toISOString(),updated_at: new Date().toISOString(),is_stale: false,diff --git a/products/wizard/backend/facade/contracts.py b/products/wizard/backend/facade/contracts.pyindex a405850a4231..168436dc7e86 100644--- a/products/wizard/backend/facade/contracts.py+++ b/products/wizard/backend/facade/contracts.py@@ -21,6 +21,13 @@ class WizardTaskDTO:status: TaskStatus+@dataclass(frozen=True)+class WizardSessionUserDTO:+ id: int+ first_name: str+ email: str++@dataclass(frozen=True)class WizardSessionDTO:session_id: str@@ -33,11 +40,16 @@ class WizardSessionDTO:event_plan: dict[str, Any] | Noneerror: dict[str, Any] | Nonepending_input: dict[str, Any] | None+ created_by: WizardSessionUserDTO | Nonecreated_at: datetimeupdated_at: datetimeis_stale: bool+class WizardSessionOwnershipError(Exception):+ """Raised when an upsert would overwrite a session owned by a different user."""++@dataclass(frozen=True)class UpsertWizardSessionRequest:"""What the wizard CLI POSTs. team_id is derived from the URL, not the body."""@@ -65,3 +77,5 @@ class UpsertWizardSessionInput:event_plan: dict[str, Any] | Noneerror: dict[str, Any] | Nonepending_input: dict[str, Any] | None+ # Set on create only, never overwritten on later pushes for the same run.+ created_by_id: int | None = Nonediff --git a/products/wizard/backend/logic/sessions.py b/products/wizard/backend/logic/sessions.pyindex f7e7f80bb80a..36d95f37e2cb 100644--- a/products/wizard/backend/logic/sessions.py+++ b/products/wizard/backend/logic/sessions.py@@ -7,7 +7,13 @@ from functools import partialfrom django.db import transaction-from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardSessionDTO, WizardTaskDTO+from products.wizard.backend.facade.contracts import (+ UpsertWizardSessionInput,+ WizardSessionDTO,+ WizardSessionOwnershipError,+ WizardSessionUserDTO,+ WizardTaskDTO,+)from products.wizard.backend.facade.enums import RunPhase, TaskStatusfrom products.wizard.backend.logic.pubsub import publish_session_updatefrom products.wizard.backend.logic.utils import is_stale@@ -35,30 +41,45 @@ def upsert_session(params: UpsertWizardSessionInput) -> tuple[WizardSessionDTO,.first())previous_run_phase = previous_session.run_phase if previous_session else None++ # A session belongs to the user who created it. A later push from a+ # different user would overwrite the run data while `created_by` stays+ # the original owner, so reject it. Legacy rows with a null+ # `created_by_id` predate attribution and stay updatable by anyone.+ if (+ previous_session is not None+ and previous_session.created_by_id is not None+ and previous_session.created_by_id != params.created_by_id+ ):+ raise WizardSessionOwnershipError("This wizard session belongs to a different user and can't be updated.")+event_plan = params.event_planif event_plan is None and params.run_phase == RunPhase.COMPLETED and previous_session:event_plan = previous_session.event_plan+ defaults = {+ "workflow_id": params.workflow_id,+ "skill_id": params.skill_id,+ "started_at": params.started_at,+ "run_phase": params.run_phase.value,+ "tasks": [+ {+ "id": task.id,+ "title": task.title,+ "status": task.status.value,+ }+ for task in params.tasks+ ],+ "event_plan": event_plan,+ "error": params.error,+ "pending_input": params.pending_input,+ }+ # created_by only in create_defaults so a later push for the same run can't reattribute it.instance, created = WizardSession.objects.update_or_create(team_id=params.team_id,session_id=params.session_id,- defaults={- "workflow_id": params.workflow_id,- "skill_id": params.skill_id,- "started_at": params.started_at,- "run_phase": params.run_phase.value,- "tasks": [- {- "id": task.id,- "title": task.title,- "status": task.status.value,- }- for task in params.tasks- ],- "event_plan": event_plan,- "error": params.error,- "pending_input": params.pending_input,- },+ defaults=defaults,+ create_defaults={**defaults, "created_by_id": params.created_by_id},)if previous_run_phase != RunPhase.COMPLETED.value and params.run_phase == RunPhase.COMPLETED:transaction.on_commit(@@ -80,12 +101,12 @@ def _enqueue_event_definition_sync(team_id: int, session_id: str) -> None:def get_session(team_id: int, session_id: str) -> WizardSessionDTO | None:- instance = WizardSession.objects.filter(team_id=team_id, session_id=session_id).first()+ instance = WizardSession.objects.select_related("created_by").filter(team_id=team_id, session_id=session_id).first()return _to_dto(instance) if instance else Nonedef get_latest_session(team_id: int, workflow_id: str, skill_id: str | None = None) -> WizardSessionDTO | None:- qs = WizardSession.objects.filter(team_id=team_id, workflow_id=workflow_id)+ qs = WizardSession.objects.select_related("created_by").filter(team_id=team_id, workflow_id=workflow_id)if skill_id:qs = qs.filter(skill_id=skill_id)# created_at breaks ties on equal (client-supplied, second-granularity) started_at@@ -107,7 +128,7 @@ def list_sessions(cost stays bounded regardless of how many sessions the team has. The viewlayer should always pass a `limit`."""- qs = WizardSession.objects.filter(team_id=team_id)+ qs = WizardSession.objects.select_related("created_by").filter(team_id=team_id)if workflow_id:qs = qs.filter(workflow_id=workflow_id)if skill_id:@@ -123,6 +144,7 @@ def list_sessions(def _to_dto(instance: WizardSession) -> WizardSessionDTO:run_phase = RunPhase(instance.run_phase)+ created_by = instance.created_byreturn WizardSessionDTO(session_id=instance.session_id,team_id=instance.team_id,@@ -142,6 +164,11 @@ def _to_dto(instance: WizardSession) -> WizardSessionDTO:event_plan=instance.event_plan,error=instance.error,pending_input=instance.pending_input,+ created_by=(+ WizardSessionUserDTO(id=created_by.id, first_name=created_by.first_name, email=created_by.email)+ if created_by is not None+ else None+ ),created_at=instance.created_at,updated_at=instance.updated_at,)diff --git a/products/wizard/backend/migrations/0004_wizardsession_created_by.py b/products/wizard/backend/migrations/0004_wizardsession_created_by.pynew file mode 100644index 000000000000..b4953c3328c4--- /dev/null+++ b/products/wizard/backend/migrations/0004_wizardsession_created_by.py@@ -0,0 +1,25 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ("wizard", "0003_wizardsession_pending_input"),+ ]++ operations = [+ migrations.AddField(+ model_name="wizardsession",+ name="created_by",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ]diff --git a/products/wizard/backend/migrations/max_migration.txt b/products/wizard/backend/migrations/max_migration.txtindex e7f6648296ff..146cb913701c 100644--- a/products/wizard/backend/migrations/max_migration.txt+++ b/products/wizard/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_wizardsession_pending_input+0004_wizardsession_created_bydiff --git a/products/wizard/backend/models.py b/products/wizard/backend/models.pyindex 84cbe8afa6f2..239f84a0b245 100644--- a/products/wizard/backend/models.py+++ b/products/wizard/backend/models.py@@ -10,14 +10,24 @@ disallow reverse relations with related_name='+'.from django.db import modelsfrom posthog.models.scoping.root_mixin import TeamScopedRootMixin-from posthog.models.utils import UUIDModel+from posthog.models.utils import CreatedMetaFields, UUIDModelfrom products.wizard.backend.facade.enums import RunPhase-class WizardSession(UUIDModel, TeamScopedRootMixin):+class WizardSession(UUIDModel, TeamScopedRootMixin, CreatedMetaFields):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")+ # db_constraint=False because posthog_user is a hot table (a constrained FK would lock it).+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="+",+ db_constraint=False,+ )+session_id = models.CharField(max_length=255)workflow_id = models.CharField(max_length=255)skill_id = models.CharField(max_length=255)@@ -33,7 +43,6 @@ class WizardSession(UUIDModel, TeamScopedRootMixin):# question is just the next upsert without the field.pending_input = models.JSONField(null=True, blank=True)- created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)class Meta(TeamScopedRootMixin.Meta):diff --git a/products/wizard/backend/presentation/serializers.py b/products/wizard/backend/presentation/serializers.pyindex 783342318611..1e92ca4f7ad0 100644--- a/products/wizard/backend/presentation/serializers.py+++ b/products/wizard/backend/presentation/serializers.py@@ -66,6 +66,14 @@ class WizardSessionSerializer(DataclassSerializer):class Meta:dataclass = WizardSessionDTO+ extra_kwargs = {+ "created_by": {+ "help_text": (+ "The user who initiated this wizard run (null for runs created before "+ "attribution existed). Lets the UI name whose run it is."+ ),+ },+ }class UpsertWizardSessionRequestSerializer(DataclassSerializer):diff --git a/products/wizard/backend/presentation/views.py b/products/wizard/backend/presentation/views.pyindex 799945ecfa37..9027bea634e9 100644--- a/products/wizard/backend/presentation/views.py+++ b/products/wizard/backend/presentation/views.py@@ -18,7 +18,7 @@ import posthoganalyticsfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import NotFound, ValidationError+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom rest_framework.renderers import BaseRendererfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -33,6 +33,7 @@ from products.wizard.backend.facade.contracts import (UpsertWizardSessionInput,UpsertWizardSessionRequest,WizardSessionDTO,+ WizardSessionOwnershipError,)from products.wizard.backend.facade.enums import RunPhasefrom products.wizard.backend.presentation.serializers import (@@ -271,6 +272,7 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={200: WizardSessionSerializer,201: WizardSessionSerializer,+ 403: OpenApiResponse(description="The session belongs to a different user."),},)def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:@@ -278,20 +280,27 @@ class WizardSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer.is_valid(raise_exception=True)req: UpsertWizardSessionRequest = serializer.save()- dto, created = wizard_facade.upsert(- UpsertWizardSessionInput(- team_id=self.team_id,- session_id=req.session_id,- workflow_id=req.workflow_id,- skill_id=req.skill_id,- started_at=req.started_at,- run_phase=req.run_phase,- tasks=tuple(req.tasks),- event_plan=req.event_plan,- error=req.error,- pending_input=req.pending_input,+ user = getattr(request, "user", None)+ created_by_id = user.id if user is not None and not user.is_anonymous else None++ try:+ dto, created = wizard_facade.upsert(+ UpsertWizardSessionInput(+ team_id=self.team_id,+ session_id=req.session_id,+ workflow_id=req.workflow_id,+ skill_id=req.skill_id,+ started_at=req.started_at,+ run_phase=req.run_phase,+ tasks=tuple(req.tasks),+ event_plan=req.event_plan,+ error=req.error,+ pending_input=req.pending_input,+ created_by_id=created_by_id,+ ))- )+ except WizardSessionOwnershipError:+ raise PermissionDenied("This wizard session belongs to a different user.")response_status = status.HTTP_201_CREATED if created else status.HTTP_200_OKreturn Response(WizardSessionSerializer(dto).data, status=response_status)diff --git a/products/wizard/backend/tests/test_logic.py b/products/wizard/backend/tests/test_logic.pyindex 652d3d9227d5..0b4b441c7ce0 100644--- a/products/wizard/backend/tests/test_logic.py+++ b/products/wizard/backend/tests/test_logic.py@@ -5,11 +5,15 @@ from unittest.mock import patchfrom django.test import override_settings-from posthog.models import Team+from posthog.models import Team, Userfrom products.event_definitions.backend.models import EventDefinitionfrom products.wizard.backend.facade import api as wizard_facade-from products.wizard.backend.facade.contracts import UpsertWizardSessionInput, WizardTaskDTO+from products.wizard.backend.facade.contracts import (+ UpsertWizardSessionInput,+ WizardSessionOwnershipError,+ WizardTaskDTO,+)from products.wizard.backend.facade.enums import RunPhase, TaskStatusfrom products.wizard.backend.metrics import WIZARD_SESSIONS_FINISHED_TOTALfrom products.wizard.backend.tasks.tasks import sync_wizard_event_definitions@@ -250,6 +254,44 @@ def test_upsert_with_different_session_id_creates_new_row(team):assert len(wizard_facade.list_for_team(team.id, limit=100)) == 2+def test_created_by_is_set_on_create_and_preserved_on_owner_update(team, user):+ created, _ = wizard_facade.upsert(_input(team.id, created_by_id=user.id))+ assert created.created_by is not None+ assert created.created_by.id == user.id++ updated, was_created = wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED, created_by_id=user.id))+ assert was_created is False+ assert updated.created_by is not None+ assert updated.created_by.id == user.id+++def test_upsert_by_a_different_user_is_rejected(team, user):+ other_user = User.objects.create(email="[email protected]", first_name="Second")+ wizard_facade.upsert(_input(team.id, run_phase=RunPhase.RUNNING, created_by_id=user.id))++ with pytest.raises(WizardSessionOwnershipError):+ wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED, created_by_id=other_user.id))++ # The owner's run data is left untouched.+ current = wizard_facade.get(team.id, _input(team.id).session_id)+ assert current is not None+ assert current.run_phase == RunPhase.RUNNING+ assert current.created_by is not None+ assert current.created_by.id == user.id+++def test_upsert_allows_update_of_legacy_unattributed_session(team, user):+ # Rows created before attribution existed carry a null created_by and stay updatable by anyone.+ wizard_facade.upsert(_input(team.id, created_by_id=None))++ updated, was_created = wizard_facade.upsert(_input(team.id, run_phase=RunPhase.COMPLETED, created_by_id=user.id))+ assert was_created is False+ assert updated.run_phase == RunPhase.COMPLETED++@pytest.mark.django_dbdef test_get_session_returns_matching_row(team):wizard_facade.upsert(_input(team.id, session_id="run-1"))diff --git a/products/wizard/backend/tests/test_presentation.py b/products/wizard/backend/tests/test_presentation.pyindex f51d9a76342e..7ae6e9e8789b 100644--- a/products/wizard/backend/tests/test_presentation.py+++ b/products/wizard/backend/tests/test_presentation.py@@ -4,7 +4,7 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Organization, PersonalAPIKey+from posthog.models import Organization, PersonalAPIKey, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.wizard.backend.models import WizardSession@@ -64,6 +64,15 @@ class TestWizardSessionViewSet(APIBaseTest):self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 1)+ def test_create_session_attributes_run_to_authenticated_user(self):+ response = self.client.post(self._url(), self._payload(), format="json")++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ created_by = response.json()["created_by"]+ self.assertEqual(created_by["id"], self.user.id)+ self.assertEqual(created_by["email"], self.user.email)+ self.assertEqual(created_by["first_name"], self.user.first_name)+def test_completed_session_requires_event_definition_write_scope(self):self._authenticate_personal_api_key(["wizard_session:write"])@@ -119,6 +128,21 @@ class TestWizardSessionViewSet(APIBaseTest):self.assertEqual(WizardSession.objects.unscoped().filter(team=self.team).count(), 1)+ def test_repost_by_a_different_user_is_forbidden(self):+ first = self.client.post(self._url(), self._payload(), format="json")+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)++ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ self.client.force_login(other_user)++ response = self.client.post(+ self._url(),+ self._payload(run_phase="completed"),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+def test_different_session_id_creates_new_row(self):self.client.post(self._url(), self._payload(), format="json")diff --git a/products/wizard/backend/tests/test_pubsub.py b/products/wizard/backend/tests/test_pubsub.pyindex cee36a6cc581..eea6f12bd129 100644--- a/products/wizard/backend/tests/test_pubsub.py+++ b/products/wizard/backend/tests/test_pubsub.py@@ -28,6 +28,7 @@ def _dto(team_id: int = 1) -> WizardSessionDTO:event_plan=None,error=None,pending_input=None,+ created_by=None,created_at=now,updated_at=now,)diff --git a/products/wizard/frontend/generated/api.schemas.ts b/products/wizard/frontend/generated/api.schemas.tsindex c70c9e8abb12..b358a4e55400 100644--- a/products/wizard/frontend/generated/api.schemas.ts+++ b/products/wizard/frontend/generated/api.schemas.ts@@ -73,6 +73,12 @@ export interface WizardTaskDTOApi {status: WizardTaskDTOStatusEnumApi}+export interface WizardSessionUserDTOApi {+ id: number+ first_name: string+ email: string+}+/*** @nullable*/@@ -100,6 +106,8 @@ export interface WizardSessionDTOApi {event_plan: WizardSessionDTOApiEventPlan/** @nullable */error: WizardSessionDTOApiError+ /** The user who initiated this wizard run (null for runs created before attribution existed). Lets the UI name whose run it is. */+ created_by: WizardSessionUserDTOApi | nullcreated_at: stringupdated_at: stringis_stale: booleandiff --git a/products/wizard/frontend/wizardSessionStreamLogic.test.ts b/products/wizard/frontend/wizardSessionStreamLogic.test.tsindex 16631bfa620e..6d8a05e9258b 100644--- a/products/wizard/frontend/wizardSessionStreamLogic.test.ts+++ b/products/wizard/frontend/wizardSessionStreamLogic.test.ts@@ -34,6 +34,7 @@ function makeSession(overrides: Partial<WizardSessionDTOApi> = {}): WizardSessioevent_plan: null,error: null,pending_input: null,+ created_by: null,created_at: '2026-01-01T00:00:00Z',updated_at: '2026-01-01T00:00:00Z',is_stale: false,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4512d7390993..fe6f38ee5de2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47204,6 +47204,12 @@ export namespace Schemas {status: WizardTaskDTOStatusEnum;}+ export interface WizardSessionUserDTO {+ id: number;+ first_name: string;+ email: string;+ }+/*** @nullable*/@@ -47231,6 +47237,8 @@ export namespace Schemas {event_plan: WizardSessionDTOEventPlan;/** @nullable */error: WizardSessionDTOError;+ /** The user who initiated this wizard run (null for runs created before attribution existed). Lets the UI name whose run it is. */+ created_by: WizardSessionUserDTO | null;created_at: string;updated_at: string;is_stale: boolean;