Skip to content

: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.

feat(subscriptions): offer to take ownership when re-enabling is refused (#125588)

Alex Lider94bf72939eee
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index eb09178f5003..510654b45593 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -208,6 +208,7 @@ Every other failure on these actions still toasts and reports.
const VALIDATION_ERROR_SELF_HANDLED_BY_LOGIC_PATH: Record<string, string> = {
createTable: 'products.dataWarehouse.selfManagedSourceLogic',
updateTable: 'products.dataWarehouse.selfManagedSourceLogic',
+ setEnabled: 'scenes.subscriptions.subscriptionSceneLogic', // Toasts the refusal, or offers to take ownership
}
/*
diff --git a/frontend/src/lib/components/openTakeOwnershipDialog.test.ts b/frontend/src/lib/components/openTakeOwnershipDialog.test.ts
new file mode 100644
index 000000000000..3c0536975ad5
--- /dev/null
+++ b/frontend/src/lib/components/openTakeOwnershipDialog.test.ts
@@ -0,0 +1,107 @@
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api-error'
+import { LemonDialog, LemonDialogProps } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { openTakeOwnershipDialog } from './openTakeOwnershipDialog'
+
+describe('openTakeOwnershipDialog', () => {
+ let dialogProps: LemonDialogProps | null
+ let captureSpy: jest.SpyInstance
+ let errorSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ dialogProps = null
+ jest.spyOn(LemonDialog, 'open').mockImplementation((props) => {
+ dialogProps = props
+ })
+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(jest.fn())
+ errorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(jest.fn())
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ async function confirmAndClose(): Promise<void> {
+ await dialogProps?.primaryButton?.onClick?.({} as any)
+ dialogProps?.onAfterClose?.()
+ }
+
+ it('resolves true and reports the takeover once the request succeeds', async () => {
+ const takeOwnership = jest.fn().mockResolvedValue(undefined)
+ const result = openTakeOwnershipDialog({
+ resourceLabel: 'alert',
+ resourceId: 'alert-1',
+ owner: null,
+ cause: 'left',
+ takeOwnership,
+ })
+
+ await confirmAndClose()
+
+ expect(await result).toBe(true)
+ expect(takeOwnership).toHaveBeenCalledTimes(1)
+ expect(captureSpy).toHaveBeenCalledWith('alert ownership taken', { alert_id: 'alert-1' })
+ })
+
+ it('resolves false and toasts the API detail when the request fails', async () => {
+ const takeOwnership = jest
+ .fn()
+ .mockRejectedValue(new ApiError('refused', 400, undefined, { detail: 'No access to this insight.' }))
+ const result = openTakeOwnershipDialog({
+ resourceLabel: 'subscription',
+ resourceId: 7,
+ owner: null,
+ cause: 'left',
+ takeOwnership,
+ })
+
+ await confirmAndClose()
+
+ expect(await result).toBe(false)
+ expect(errorSpy).toHaveBeenCalledWith('No access to this insight.')
+ expect(captureSpy).not.toHaveBeenCalled()
+ })
+
+ it('waits for an in-flight takeover before reporting a dismissal', async () => {
+ let finishTakeover: () => void = () => {}
+ const takeOwnership = jest.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishTakeover = resolve
+ })
+ )
+ const result = openTakeOwnershipDialog({
+ resourceLabel: 'alert',
+ resourceId: 'alert-1',
+ owner: null,
+ cause: 'left',
+ takeOwnership,
+ })
+
+ const confirming = dialogProps?.primaryButton?.onClick?.({} as any)
+ dialogProps?.onAfterClose?.()
+ finishTakeover()
+ await confirming
+
+ expect(await result).toBe(true)
+ })
+
+ it('resolves false when the dialog is dismissed', async () => {
+ const takeOwnership = jest.fn()
+ const result = openTakeOwnershipDialog({
+ resourceLabel: 'subscription',
+ resourceId: 7,
+ owner: null,
+ cause: 'left',
+ takeOwnership,
+ })
+
+ dialogProps?.onAfterClose?.()
+
+ expect(await result).toBe(false)
+ expect(takeOwnership).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/lib/components/openTakeOwnershipDialog.tsx b/frontend/src/lib/components/openTakeOwnershipDialog.tsx
new file mode 100644
index 000000000000..69249efa3ac9
--- /dev/null
+++ b/frontend/src/lib/components/openTakeOwnershipDialog.tsx
@@ -0,0 +1,141 @@
+import posthog from 'posthog-js'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { ApiError } from 'lib/api'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { fullName, fullNameOrEmail } from 'lib/utils/strings'
+
+import { UserBasicType } from '~/types'
+
+// pinned: API error codes, match OWNER_LEFT_ORGANIZATION_CODE and OWNER_LOST_ACCESS_CODE in posthog/query_creator_access.py
+const OWNER_UNAVAILABLE_CAUSES = {
+ owner_left_organization: 'left',
+ owner_lost_access: 'lost_access',
+} as const
+
+export type OwnerUnavailableCause = (typeof OWNER_UNAVAILABLE_CAUSES)[keyof typeof OWNER_UNAVAILABLE_CAUSES]
+
+export type OwnedResourceLabel = 'subscription' | 'alert'
+
+export type ResourceOwner = Pick<UserBasicType, 'email'> & Partial<Pick<UserBasicType, 'first_name' | 'last_name'>>
+
+/** Why a write was refused because the resource's owner can no longer run it, or null for any other error. */
+export function ownerUnavailableCause(error: unknown): OwnerUnavailableCause | null {
+ if (!(error instanceof ApiError) || !error.code) {
+ return null
+ }
+ return OWNER_UNAVAILABLE_CAUSES[error.code as keyof typeof OWNER_UNAVAILABLE_CAUSES] ?? null
+}
+
+function OwnerChip({ owner }: { owner: ResourceOwner }): JSX.Element {
+ const name = fullName(owner)
+ return (
+ <Tooltip
+ title={
+ <span className="ph-no-capture">
+ {name ? (
+ <>
+ {name}
+ <br />
+ </>
+ ) : null}
+ {owner.email}
+ </span>
+ }
+ >
+ <span className="inline-flex items-center gap-1 align-middle font-semibold">
+ <ProfilePicture user={owner} size="xs" />
+ <span className="ph-no-capture">{fullNameOrEmail(owner)}</span>
+ </span>
+ </Tooltip>
+ )
+}
+
+function OwnerUnavailableContent({
+ resourceLabel,
+ owner,
+ cause,
+}: {
+ resourceLabel: OwnedResourceLabel
+ owner: ResourceOwner | null
+ cause: OwnerUnavailableCause
+}): JSX.Element {
+ return (
+ <div className="space-y-2">
+ <p className="m-0">
+ {resourceLabel === 'alert' ? "Can't enable this alert." : "Can't re-enable this subscription."}
+ </p>
+ <p className="m-0">
+ {owner ? (
+ <>
+ It runs with the access of its creator, <OwnerChip owner={owner} />,{' '}
+ {cause === 'left'
+ ? 'who is no longer in the organization.'
+ : 'who no longer has access to the data it reads.'}
+ </>
+ ) : (
+ // The creator foreign key is set to null when the account is deleted.
+ 'It runs with the access of its creator, whose account was deleted.'
+ )}{' '}
+ Take ownership to enable it with your access instead.
+ </p>
+ </div>
+ )
+}
+
+/**
+ * Offer to make the current user the owner of a subscription or alert whose owner can no longer run it.
+ * Resolves `true` once `takeOwnership` succeeded, `false` when the dialog was dismissed or the request failed.
+ */
+export function openTakeOwnershipDialog({
+ resourceLabel,
+ resourceId,
+ owner,
+ cause,
+ takeOwnership,
+}: {
+ resourceLabel: OwnedResourceLabel
+ resourceId: string | number
+ owner: ResourceOwner | null
+ cause: OwnerUnavailableCause
+ takeOwnership: () => Promise<void>
+}): Promise<boolean> {
+ return new Promise((resolve) => {
+ let taken = false
+ let request: Promise<void> = Promise.resolve()
+ LemonDialog.open({
+ title: `Take ownership of this ${resourceLabel}?`,
+ content: <OwnerUnavailableContent resourceLabel={resourceLabel} owner={owner} cause={cause} />,
+ // The modal grows to fit its text, so a long reason would stretch it across the screen.
+ maxWidth: '30rem',
+ shouldAwaitSubmit: true,
+ primaryButton: {
+ children: 'Take ownership and enable',
+ 'data-attr': `${resourceLabel}-take-ownership-confirm`,
+ onClick: async () => {
+ request = takeOwnership()
+ try {
+ await request
+ } catch (error) {
+ const detail = error instanceof ApiError ? error.detail : null
+ lemonToast.error(detail || `Could not take ownership of this ${resourceLabel}. Try again.`)
+ return
+ }
+ taken = true
+ posthog.capture(`${resourceLabel} ownership taken`, { [`${resourceLabel}_id`]: resourceId })
+ },
+ },
+ secondaryButton: { children: 'Cancel', 'data-attr': `${resourceLabel}-take-ownership-cancel` },
+ // A dismissal while the request is in flight waits for it, so a takeover that lands is still reported.
+ onAfterClose: () => {
+ void request.then(
+ () => resolve(taken),
+ () => resolve(taken)
+ )
+ },
+ })
+ })
+}
diff --git a/products/alerts/frontend/components/activityDescriptions.tsx b/products/alerts/frontend/components/activityDescriptions.tsx
index 0aa43f60e261..ed5e3b2f52b8 100644
--- a/products/alerts/frontend/components/activityDescriptions.tsx
+++ b/products/alerts/frontend/components/activityDescriptions.tsx
@@ -138,6 +138,27 @@ export function alertConfigurationActivityDescriber(
}
}
+ if (logItem.activity == 'took_ownership') {
+ const contextDesc = getContextDescription(logItem?.detail?.context)
+ return {
+ summary: activityLogSummary(
+ logItem,
+ 'Took ownership of the alert',
+ <>
+ {formattedName(logItem.detail.name)}
+ {contextDesc}
+ </>
+ ),
+ description: (
+ <>
+ <ActivityLogUserName logItem={logItem} /> took ownership of the alert{' '}
+ {formattedName(logItem?.detail.name)}
+ {contextDesc}
+ </>
+ ),
+ }
+ }
+
if (logItem.activity == 'updated') {
const contextDesc = getContextDescription(logItem?.detail?.context)
diff --git a/products/alerts/frontend/logic/alertFormLogic.test.ts b/products/alerts/frontend/logic/alertFormLogic.test.ts
index a45bdfe79343..78982dc4fc31 100644
--- a/products/alerts/frontend/logic/alertFormLogic.test.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.test.ts
@@ -5,6 +5,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api, { ApiError } from 'lib/api'
+import * as takeOwnership from 'lib/components/openTakeOwnershipDialog'
import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
@@ -389,6 +390,38 @@ describe('alertFormLogic', () => {
})
})
+ it('saves the edits disabled before offering to take ownership when the owner left', async () => {
+ const existingAlert = makeSavedAlert({ id: 'alert-existing-id' })
+ updateSpy.mockRejectedValueOnce(new ApiError('refused', 400, undefined, { code: 'owner_left_organization' }))
+ const dialogSpy = jest.spyOn(takeOwnership, 'openTakeOwnershipDialog').mockResolvedValue(false)
+ const logic = alertFormLogic({
+ alert: existingAlert,
+ insightId: 42,
+ onEditSuccess: jest.fn(),
+ insightVizDataLogicProps: insightLogicProps,
+ insightInterval: 'day',
+ })
+ logic.mount()
+ logic.actions.setAlertFormValues({
+ ...makeFormDefaults({ id: existingAlert.id }),
+ enabled: true,
+ checks: undefined,
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitAlertForm()
+ }).toFinishAllListeners()
+
+ // The refused save is retried with the alert still disabled, so the takeover's enable sees the saved edits.
+ expect(updateSpy).toHaveBeenCalledTimes(2)
+ expect(updateSpy.mock.calls[1][1].enabled).toBe(false)
+ expect(dialogSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceLabel: 'alert', resourceId: existingAlert.id, cause: 'left' })
+ )
+ expect(dialogSpy.mock.invocationCallOrder[0]).toBeGreaterThan(updateSpy.mock.invocationCallOrder[1])
+ expect(errorToastSpy).not.toHaveBeenCalled()
+ })
+
it('blocks save when threshold alert has no lower or upper bound', async () => {
const logic = mountForm()
logic.actions.setAlertFormValues({
diff --git a/products/alerts/frontend/logic/alertFormLogic.ts b/products/alerts/frontend/logic/alertFormLogic.ts
index 662e148acb78..2e52dd4c9909 100644
--- a/products/alerts/frontend/logic/alertFormLogic.ts
+++ b/products/alerts/frontend/logic/alertFormLogic.ts
@@ -8,7 +8,9 @@ import posthog from 'posthog-js'
import api, { ApiConfig, ApiError } from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
+import { openTakeOwnershipDialog, ownerUnavailableCause } from 'lib/components/openTakeOwnershipDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -24,7 +26,7 @@ import {
} from '~/queries/schema/schema-general'
import { AvailableFeature, InsightLogicProps, IntervalType, InsightModel } from '~/types'
-import { alertsSimulateCreate } from 'products/alerts/frontend/generated/api'
+import { alertsSimulateCreate, alertsTakeOwnershipCreate } from 'products/alerts/frontend/generated/api'
import {
blockSubmitWithoutEntitlement,
getDefaultSimulationRange,
@@ -564,7 +566,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
],
})),
- forms(({ props, values, actions }) => ({
+ forms(({ props, values, actions, cache }) => ({
alertForm: {
defaults: props.alert
? alertToFormType(props.alert, props.insightId)
@@ -692,6 +694,18 @@ export const alertFormLogic = kea<alertFormLogicType>([
? await api.alerts.create(payload)
: await api.alerts.update(existingAlertId, payload)
} catch (error: unknown) {
+ const cause = ownerUnavailableCause(error)
+ if (cause && existingAlertId !== undefined && !cache.takeOwnershipAfterSave) {
+ // The other edits are saved first, with the alert still disabled, so the takeover that
+ // enables it checks with the saved subscribers. The failure listener resubmits.
+ cache.takeOwnershipAfterSave = {
+ id: existingAlertId,
+ cause,
+ owner: alert.created_by ?? props.alert?.created_by ?? null,
+ resubmitted: false,
+ }
+ throw error
+ }
// `AlertViewSet` is a standard DRF ModelViewSet, so validation errors arrive as
// `{attr, detail}`. Anything else (network blip, non-ApiError thrown somehow) shouldn't
// be formatted with those fields or we end up with "undefined: undefined".
@@ -887,7 +901,7 @@ export const alertFormLogic = kea<alertFormLogicType>([
],
})),
- listeners(({ props, values, actions }) => {
+ listeners(({ props, values, actions, cache }) => {
const discardSimulation = (): void => {
actions.clearSimulation()
getParentLogic()?.actions.clearSimulationAnomalyPoints()
@@ -956,6 +970,21 @@ export const alertFormLogic = kea<alertFormLogicType>([
actions.setClearSnoozeLoading(false)
}
},
+ submitAlertFormFailure: () => {
+ const pendingTakeover = cache.takeOwnershipAfterSave
+ if (!pendingTakeover) {
+ return
+ }
+ if (pendingTakeover.resubmitted) {
+ // The save that was to precede the takeover failed, so put the switch back as the user left it.
+ cache.takeOwnershipAfterSave = undefined
+ actions.setAlertFormValue('enabled', true)
+ return
+ }
+ pendingTakeover.resubmitted = true
+ actions.setAlertFormValue('enabled', false)
+ actions.submitAlertForm()
+ },
submitAlertForm: () => {
actions.setAlertFormSubmitAttempted()
const validationErrors = Object.values(values.alertFormValidationErrors).filter(
@@ -967,6 +996,23 @@ export const alertFormLogic = kea<alertFormLogicType>([
}
},
submitAlertFormSuccess: async () => {
+ const pendingTakeover = cache.takeOwnershipAfterSave
+ if (pendingTakeover) {
+ cache.takeOwnershipAfterSave = undefined
+ void openTakeOwnershipDialog({
+ resourceLabel: 'alert',
+ resourceId: pendingTakeover.id,
+ owner: pendingTakeover.owner,
+ cause: pendingTakeover.cause,
+ takeOwnership: async () => {
+ await alertsTakeOwnershipCreate(String(getCurrentTeamId()), pendingTakeover.id)
+ },
+ }).then((taken) => {
+ if (taken) {
+ getParentLogic()?.actions.loadAlerts()
+ }
+ })
+ }
// Background sync to pick up any server-side changes
getParentLogic()?.actions.loadAlerts()
},
diff --git a/products/alerts/frontend/logic/alertsLogic.test.ts b/products/alerts/frontend/logic/alertsLogic.test.ts
index 028c6b6b033b..2f7147be749c 100644
--- a/products/alerts/frontend/logic/alertsLogic.test.ts
+++ b/products/alerts/frontend/logic/alertsLogic.test.ts
@@ -2,12 +2,16 @@ import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
+import * as takeOwnership from 'lib/components/openTakeOwnershipDialog'
import { urls } from 'scenes/urls'
import { AlertState } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { HogFunctionType } from '~/types'
+import * as generatedApi from 'products/alerts/frontend/generated/api'
+
import { AlertType } from '../types'
import { alertsLogic } from './alertsLogic'
@@ -124,6 +128,38 @@ describe('alertsLogic', () => {
logic.unmount()
})
+ it('offers to take ownership when enabling is refused for the owner, then reloads', async () => {
+ updateSpy = jest
+ .spyOn(api.alerts, 'update')
+ .mockRejectedValue(new ApiError('refused', 400, undefined, { code: 'owner_lost_access' }))
+ const takeSpy = jest.spyOn(generatedApi, 'alertsTakeOwnershipCreate').mockResolvedValue({} as any)
+ const dialogSpy = jest
+ .spyOn(takeOwnership, 'openTakeOwnershipDialog')
+ .mockImplementation(async ({ takeOwnership: take }) => {
+ await take()
+ return true
+ })
+
+ const logic = alertsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ listSpy.mockClear()
+
+ logic.actions.toggleAlertEnabled({ ...alert, enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dialogSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceLabel: 'alert', resourceId: alert.id, cause: 'lost_access' })
+ )
+ expect(takeSpy).toHaveBeenCalledWith(expect.any(String), alert.id)
+ expect(listSpy).toHaveBeenCalledTimes(1)
+ expect(logic.values.togglingAlertIds).toEqual(new Set())
+
+ takeSpy.mockRestore()
+ dialogSpy.mockRestore()
+ logic.unmount()
+ })
+
it('keeps the alert toggle loading and patches the latest alert list', async () => {
let resolveUpdate: (updatedAlert: AlertType) => void = () => {}
const updatePromise = new Promise<AlertType>((resolve) => {
diff --git a/products/alerts/frontend/logic/alertsLogic.ts b/products/alerts/frontend/logic/alertsLogic.ts
index 32c872bab5c7..5187ea747679 100644
--- a/products/alerts/frontend/logic/alertsLogic.ts
+++ b/products/alerts/frontend/logic/alertsLogic.ts
@@ -5,12 +5,16 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import { PaginationManual } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { openTakeOwnershipDialog, ownerUnavailableCause } from 'lib/components/openTakeOwnershipDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { objectClean } from 'lib/utils/objects'
import { urls } from 'scenes/urls'
import { AlertState } from '~/queries/schema/schema-general'
+import { alertsTakeOwnershipCreate } from 'products/alerts/frontend/generated/api'
+
import { AlertType } from '../types'
import { AlertLogicProps } from './alertLogic'
import { buildAlertFilterConfig } from './alertNotifications'
@@ -338,8 +342,27 @@ export const alertsLogic = kea<alertsLogicType>([
try {
const updatedAlert = await api.alerts.update(alert.id, { enabled: !alert.enabled })
actions.updateAlertInList(updatedAlert)
- } catch {
- lemonToast.error('Failed to update alert')
+ } catch (error) {
+ const cause = alert.enabled ? null : ownerUnavailableCause(error)
+ if (cause) {
+ // Not awaited, so the row's switch stops loading while the dialog is open.
+ void openTakeOwnershipDialog({
+ resourceLabel: 'alert',
+ resourceId: alert.id,
+ owner: alert.created_by ?? null,
+ cause,
+ takeOwnership: async () => {
+ await alertsTakeOwnershipCreate(String(getCurrentTeamId()), alert.id)
+ lemonToast.success('Alert enabled')
+ },
+ }).then((taken) => {
+ if (taken) {
+ actions.loadAlerts()
+ }
+ })
+ } else {
+ lemonToast.error('Failed to update alert')
+ }
} finally {
actions.setAlertToggling(alert.id, false)
}
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
index 4a29e97c3f97..ac425b2f0259 100644
--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
@@ -187,7 +187,7 @@ describe('mcpRecurringReportsLogic', () => {
await expectLogic(logic, () => logic.actions.toggleReportEnabled(1, false)).toFinishAllListeners()
expect(logic.values.reports[0].enabled).toBe(false)
- expect(mockedToggle).toHaveBeenCalledWith(1, false)
+ expect(mockedToggle).toHaveBeenCalledWith(1, false, null)
})
it('restores a deleted report when the delete is undone', async () => {
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
index 1120a3c6d363..947cb5b8b7f9 100644
--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
@@ -256,7 +256,7 @@ export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([
applyEnabled(enabled)
// `toggleSubscriptionEnabled` never rejects — it toasts the failure itself and reports
// false — so the revert hangs off the return value rather than a catch.
- if (!(await toggleSubscriptionEnabled(reportId, enabled))) {
+ if (!(await toggleSubscriptionEnabled(reportId, enabled, target.created_by ?? null))) {
applyEnabled(!enabled)
}
actions.toggleReportEnabledSettled(reportId)
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
index 75f53884c685..64be8fcf9200 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
@@ -4,7 +4,8 @@ import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
-import { ApiError } from 'lib/api'
+import api, { ApiError } from 'lib/api'
+import * as takeOwnership from 'lib/components/openTakeOwnershipDialog'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { getRecentSlackChannelIds } from 'lib/integrations/slackChannel'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
@@ -101,6 +102,30 @@ describe('subscriptionLogic', () => {
window.localStorage.clear()
})
+ it('saves the edits disabled before offering to take ownership when the owner left', async () => {
+ const updateSpy = jest
+ .spyOn(api.subscriptions, 'update')
+ .mockRejectedValueOnce(new ApiError('refused', 400, undefined, { code: 'owner_left_organization' }))
+ .mockResolvedValueOnce(fixtureSubscriptionResponse(1, { enabled: false }))
+ const dialogSpy = jest.spyOn(takeOwnership, 'openTakeOwnershipDialog').mockResolvedValue(false)
+ existingLogic.actions.loadSubscription()
+ await expectLogic(existingLogic).toFinishListeners()
+
+ existingLogic.actions.setSubscriptionValues({ enabled: true, target_value: '[email protected]' })
+ existingLogic.actions.submitSubscription()
+ await expectLogic(existingLogic).toFinishAllListeners()
+
+ // The refused save is retried with the subscription still disabled, so the takeover's delivery
+ // goes to the saved recipients.
+ expect(updateSpy).toHaveBeenCalledTimes(2)
+ expect(updateSpy.mock.calls[1][1]).toMatchObject({ enabled: false, target_value: '[email protected]' })
+ expect(dialogSpy).toHaveBeenCalledWith(expect.objectContaining({ resourceId: 1, cause: 'left' }))
+ expect(dialogSpy.mock.invocationCallOrder[0]).toBeGreaterThan(updateSpy.mock.invocationCallOrder[1])
+ expect(lemonToast.error).not.toHaveBeenCalled()
+ updateSpy.mockRestore()
+ dialogSpy.mockRestore()
+ })
+
it('loads existing subscription', async () => {
router.actions.push('/insights/123/subscriptions/1')
await expectLogic(existingLogic).toFinishListeners().toDispatchActions(['loadSubscriptionSuccess'])
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
index a89828655139..224b05e02c5c 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
@@ -20,6 +20,7 @@ import posthog from 'posthog-js'
import { z } from 'zod'
import api, { ApiError } from 'lib/api'
+import { openTakeOwnershipDialog, ownerUnavailableCause } from 'lib/components/openTakeOwnershipDialog'
import { dayjs } from 'lib/dayjs'
import { getInsightId } from 'lib/insights/getInsightId'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
@@ -36,6 +37,7 @@ import { DashboardTile, ExportedAssetType, ExporterFormat, SubscriptionResourceT
import {
subscriptionsDeliveriesList,
+ subscriptionsTakeOwnershipCreate,
subscriptionsTestDeliveryCreate,
} from 'products/subscriptions/frontend/generated/api'
import {
@@ -904,6 +906,24 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
actions.loadLastDelivery()
},
submitSubscriptionSuccess: ({ subscription }) => {
+ const pendingTakeover = cache.takeOwnershipAfterSave
+ if (pendingTakeover) {
+ cache.takeOwnershipAfterSave = undefined
+ void openTakeOwnershipDialog({
+ resourceLabel: 'subscription',
+ resourceId: pendingTakeover.id,
+ owner: pendingTakeover.owner,
+ cause: pendingTakeover.cause,
+ takeOwnership: async () => {
+ await subscriptionsTakeOwnershipCreate(String(getCurrentTeamId()), String(pendingTakeover.id))
+ },
+ }).then((taken) => {
+ if (taken) {
+ actions.loadSubscription()
+ subscriptionsLogic.findMounted(props)?.actions.loadAllSubscriptions()
+ }
+ })
+ }
if (subscription?.target_type === 'slack' && subscription.target_value && subscription.integration_id) {
recordRecentSlackChannel(subscription.integration_id, slackChannelId(subscription.target_value))
}
@@ -991,6 +1011,12 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
actions.setSubscriptionValues({ ai_prompt_config: { ...config, window } })
},
submitSubscriptionFailure: ({ error }) => {
+ const isResubmit = cache.takeOwnershipAfterSave !== undefined
+ if (isResubmit) {
+ // The save that was to precede the takeover failed, so put the switch back as the user left it.
+ cache.takeOwnershipAfterSave = undefined
+ actions.setSubscriptionValue('enabled', true)
+ }
// Not every error has a field that can render it, so name the section instead.
if (error instanceof Error && error.message === 'Validation Failed') {
const fields = invalidFieldNames(values.subscriptionAllErrors)
@@ -1002,6 +1028,15 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
lemonToast.error(blockedSaveMessage(fields))
return
}
+ const cause = ownerUnavailableCause(error)
+ if (props.id !== 'new' && cause && !isResubmit) {
+ // Enabling delivers at once, so the other edits are saved first, with the subscription still
+ // disabled, and the takeover that enables it is offered once they are in.
+ cache.takeOwnershipAfterSave = { id: props.id, cause, owner: values.subscription.created_by ?? null }
+ actions.setSubscriptionValue('enabled', false)
+ actions.submitSubscription()
+ return
+ }
const message = subscriptionSaveErrorMessage(error)
if (error instanceof ApiError && error.attr) {
actions.setSubscriptionManualErrors({ [error.attr]: message })
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.ts
index 13e457fe02ff..7adf4539295d 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.ts
@@ -172,7 +172,7 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([
],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
loadAllSubscriptions: () => {
actions.loadSubscriptions()
actions.loadInsightSubscriptions()
@@ -195,7 +195,8 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([
}
},
setSubscriptionEnabled: async ({ id, enabled }) => {
- const ok = await toggleSubscriptionEnabled(id, enabled)
+ const owner = values.subscriptions.find((subscription) => subscription.id === id)?.created_by ?? null
+ const ok = await toggleSubscriptionEnabled(id, enabled, owner)
if (ok) {
actions.setSubscriptionEnabledSuccess()
} else {
diff --git a/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.test.ts b/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.test.ts
index 783f9c21b284..10fedce7d3de 100644
--- a/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.test.ts
@@ -1,3 +1,5 @@
+import { ApiError } from 'lib/api-error'
+import * as takeOwnership from 'lib/components/openTakeOwnershipDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import * as generatedApi from 'products/subscriptions/frontend/generated/api'
@@ -26,7 +28,7 @@ describe('toggleSubscriptionEnabled', () => {
it('returns true and surfaces an enabled toast on success', async () => {
patchSpy.mockResolvedValueOnce({ id: 42, enabled: true } as any)
- const ok = await toggleSubscriptionEnabled(42, true)
+ const ok = await toggleSubscriptionEnabled(42, true, null)
expect(ok).toBe(true)
expect(patchSpy).toHaveBeenCalledWith('1', 42, { enabled: true })
@@ -37,7 +39,7 @@ describe('toggleSubscriptionEnabled', () => {
it('returns true and surfaces a disabled toast on success', async () => {
patchSpy.mockResolvedValueOnce({ id: 42, enabled: false } as any)
- const ok = await toggleSubscriptionEnabled(42, false)
+ const ok = await toggleSubscriptionEnabled(42, false, null)
expect(ok).toBe(true)
expect(successSpy).toHaveBeenCalledWith('Subscription disabled')
@@ -46,7 +48,7 @@ describe('toggleSubscriptionEnabled', () => {
it('returns false and surfaces the API detail on error', async () => {
patchSpy.mockRejectedValueOnce({ detail: 'Slack integration disconnected' })
- const ok = await toggleSubscriptionEnabled(42, true)
+ const ok = await toggleSubscriptionEnabled(42, true, null)
expect(ok).toBe(false)
expect(errorSpy).toHaveBeenCalledWith('Slack integration disconnected')
@@ -56,17 +58,37 @@ describe('toggleSubscriptionEnabled', () => {
it('returns false and uses the fallback toast when error has no detail', async () => {
patchSpy.mockRejectedValueOnce(new Error('network down'))
- const ok = await toggleSubscriptionEnabled(42, true)
+ const ok = await toggleSubscriptionEnabled(42, true, null)
expect(ok).toBe(false)
expect(errorSpy).toHaveBeenCalledWith('Could not update subscription')
})
+ it('offers to take ownership instead of toasting when the owner can no longer run it', async () => {
+ patchSpy.mockRejectedValueOnce(new ApiError('refused', 400, undefined, { code: 'owner_left_organization' }))
+ const takeSpy = jest.spyOn(generatedApi, 'subscriptionsTakeOwnershipCreate').mockResolvedValueOnce({} as any)
+ const dialogSpy = jest
+ .spyOn(takeOwnership, 'openTakeOwnershipDialog')
+ .mockImplementation(async ({ takeOwnership: take }) => {
+ await take()
+ return true
+ })
+
+ const ok = await toggleSubscriptionEnabled(42, true, null)
+
+ expect(ok).toBe(true)
+ expect(dialogSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceLabel: 'subscription', resourceId: 42, cause: 'left' })
+ )
+ expect(takeSpy).toHaveBeenCalledWith('1', '42')
+ expect(errorSpy).not.toHaveBeenCalled()
+ })
+
it('treats non-string detail as missing and uses the fallback toast', async () => {
// Defends against API drift where `detail` becomes an object/array/null.
patchSpy.mockRejectedValueOnce({ detail: { enabled: ['Schedule has reached its end date.'] } })
- const ok = await toggleSubscriptionEnabled(42, true)
+ const ok = await toggleSubscriptionEnabled(42, true, null)
expect(ok).toBe(false)
expect(errorSpy).toHaveBeenCalledWith('Could not update subscription')
diff --git a/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.ts b/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.ts
index f1b243ba7c27..b5d755e7383e 100644
--- a/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled.ts
@@ -1,14 +1,35 @@
+import { openTakeOwnershipDialog, ownerUnavailableCause, ResourceOwner } from 'lib/components/openTakeOwnershipDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
-import { subscriptionsPartialUpdate } from 'products/subscriptions/frontend/generated/api'
+import {
+ subscriptionsPartialUpdate,
+ subscriptionsTakeOwnershipCreate,
+} from 'products/subscriptions/frontend/generated/api'
-export async function toggleSubscriptionEnabled(id: number, enabled: boolean): Promise<boolean> {
+export async function toggleSubscriptionEnabled(
+ id: number,
+ enabled: boolean,
+ owner: ResourceOwner | null
+): Promise<boolean> {
try {
await subscriptionsPartialUpdate(String(getCurrentTeamId()), id, { enabled })
lemonToast.success(enabled ? 'Subscription enabled' : 'Subscription disabled')
return true
} catch (e: any) {
+ const cause = enabled ? ownerUnavailableCause(e) : null
+ if (cause) {
+ return await openTakeOwnershipDialog({
+ resourceLabel: 'subscription',
+ resourceId: id,
+ owner,
+ cause,
+ takeOwnership: async () => {
+ await subscriptionsTakeOwnershipCreate(String(getCurrentTeamId()), String(id))
+ lemonToast.success('Subscription enabled')
+ },
+ })
+ }
const detail = typeof e?.detail === 'string' ? e.detail : null
lemonToast.error(detail ?? 'Could not update subscription')
return false
diff --git a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx
index 93e79b0b4b46..56350011f4e7 100644
--- a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx
+++ b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx
@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
+import { openTakeOwnershipDialog, ownerUnavailableCause } from 'lib/components/openTakeOwnershipDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { sceneConfigurations } from 'scenes/scenes'
@@ -15,6 +16,7 @@ import {
subscriptionsDeliveriesList,
subscriptionsPartialUpdate,
subscriptionsRetrieve,
+ subscriptionsTakeOwnershipCreate,
subscriptionsTestDeliveryCreate,
} from 'products/subscriptions/frontend/generated/api'
import type {
@@ -359,7 +361,24 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([
}
lemonToast.success(subscription.enabled ? 'Subscription enabled' : 'Subscription disabled')
},
- setEnabledFailure: ({ errorObject }) => {
+ setEnabledFailure: async ({ errorObject }) => {
+ const cause = ownerUnavailableCause(errorObject)
+ if (cause) {
+ const taken = await openTakeOwnershipDialog({
+ resourceLabel: 'subscription',
+ resourceId: props.id,
+ owner: values.subscription?.created_by ?? null,
+ cause,
+ takeOwnership: async () => {
+ await subscriptionsTakeOwnershipCreate(String(getCurrentTeamId()), props.id)
+ lemonToast.success('Subscription enabled')
+ },
+ })
+ if (taken) {
+ actions.loadSubscription()
+ }
+ return
+ }
// Surface the serializer's actionable message (e.g. re-enabling a Slack
// sub with no integration) — backend already validates this.
const detail = errorObject?.detail
diff --git a/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx b/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx
index 6e0b36fdad82..0376b8291a33 100644
--- a/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx
+++ b/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx
@@ -652,7 +652,8 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([
}
},
setSubscriptionEnabled: async ({ id, enabled }) => {
- const ok = await toggleSubscriptionEnabled(id, enabled)
+ const owner = values.subscriptions.find((subscription) => subscription.id === id)?.created_by ?? null
+ const ok = await toggleSubscriptionEnabled(id, enabled, owner)
if (ok) {
actions.setSubscriptionEnabledSuccess(id)
} else {