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: show saved MCP recurring reports on the notifications tab (#79127)

Lucas Fariaf334eb1dc487
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index ce8b10cca818..416db5682f14 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -1014,6 +1014,10 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M
"insight__name",
"insight__derived_name",
"dashboard__name",
+ # An AI report's subject lives only in its prompt, so without this the only way to find the
+ # reports about a given thing is to fetch every ai_prompt row and sift them client-side.
+ # Scoped to one team by the viewset, so the ILIKE never widens past that team's rows.
+ "prompt",
]
ordering_fields = [
"created_at",
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 855f00d6d9a1..f8dfef24c0c6 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -1467,6 +1467,33 @@ class TestSubscriptionTemporal(APILicensedTest):
assert len(results) == 1
assert results[0]["title"] == "UniqueSearchableTitle"
+ def test_list_subscriptions_search_matches_ai_prompt_text(self):
+ # An AI report's subject exists only in its prompt, so without this a caller wanting the
+ # reports about one thing has to fetch every ai_prompt row and sift them client-side.
+ for title, prompt in [
+ ("Tool health", "Report on $mcp_tool_call errors this week."),
+ ("Pageviews", "Summarize $pageview trends this week."),
+ ]:
+ Subscription.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title=title,
+ prompt=prompt,
+ target_type="email",
+ target_value="[email protected]",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2022, 1, 1, tzinfo=UTC),
+ )
+
+ list_res = self.client.get(
+ f"/api/projects/{self.team.id}/subscriptions/",
+ {"resource_type": "ai_prompt", "search": "$mcp_"},
+ )
+
+ assert list_res.status_code == status.HTTP_200_OK
+ assert [r["title"] for r in list_res.json()["results"]] == ["Tool health"]
+
def test_list_subscriptions_filter_by_resource_type(self):
self.dashboard.tiles.create(insight=self.insight)
dash_res = self.client.post(
diff --git a/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx b/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx
index a1b1422ff49e..1f75e3483115 100644
--- a/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx
+++ b/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx
@@ -1,13 +1,66 @@
-import { IconCalendar, IconOpenSidebar } from '@posthog/icons'
-import { LemonButton, LemonCard, LemonTag, Link } from '@posthog/lemon-ui'
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+import { IconCalendar, IconOpenSidebar, IconPlus } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonSwitch, LemonTag, Link } from '@posthog/lemon-ui'
+
+import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'
+import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { urls } from 'scenes/urls'
+import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'
+
+import { AI_REPORT_LIST_LIMIT, mcpRecurringReportsLogic } from './mcpRecurringReportsLogic'
import { MCP_RECURRING_REPORTS, MCPRecurringReport, urlForRecurringReport } from './recurringReportDefinitions'
-function ReportCard({ report, enabled }: { report: MCPRecurringReport; enabled: boolean }): JSX.Element {
+function SavedReportRow({ report }: { report: SubscriptionApi }): JSX.Element {
+ const { pendingToggleIds } = useValues(mcpRecurringReportsLogic)
+ const { toggleReportEnabled, deleteReport } = useActions(mcpRecurringReportsLogic)
+
+ return (
+ <div className="flex items-center gap-2 rounded border p-2">
+ <div className="min-w-0 flex-1">
+ <Link to={urls.subscription(report.id)} className="truncate font-medium">
+ {report.title || 'Untitled report'}
+ </Link>
+ <div className="text-xs text-muted">
+ {report.summary}
+ {report.next_delivery_date && report.enabled ? (
+ <>
+ {' · next '}
+ <TZLabel time={report.next_delivery_date} />
+ </>
+ ) : null}
+ </div>
+ </div>
+ <LemonSwitch
+ checked={!!report.enabled}
+ onChange={() => toggleReportEnabled(report.id, !report.enabled)}
+ loading={!!pendingToggleIds[report.id]}
+ aria-label={`Enable ${report.title || 'report'}`}
+ />
+ <ConfirmDeleteButton
+ onDelete={() => deleteReport(report)}
+ disabledReason={
+ pendingToggleIds[report.id] ? 'Waiting for the enable/disable update to finish…' : undefined
+ }
+ data-attr="mcp-analytics-recurring-report-delete"
+ />
+ </div>
+ )
+}
+
+function ReportCard({
+ report,
+ enabled,
+ savedReports,
+}: {
+ report: MCPRecurringReport
+ enabled: boolean
+ savedReports: SubscriptionApi[]
+}): JSX.Element {
return (
<LemonCard hoverEffect={false} className="flex flex-col gap-2 p-3">
<div className="flex items-start justify-between gap-2">
@@ -22,13 +75,13 @@ function ReportCard({ report, enabled }: { report: MCPRecurringReport; enabled:
</div>
{enabled && (
<LemonButton
- type="primary"
+ type={savedReports.length > 0 ? 'secondary' : 'primary'}
size="xsmall"
- icon={<IconCalendar />}
+ icon={savedReports.length > 0 ? <IconPlus /> : <IconCalendar />}
to={urlForRecurringReport(report)}
data-attr={`mcp-analytics-recurring-report-${report.key}`}
>
- Set up
+ {savedReports.length > 0 ? 'Add' : 'Set up'}
</LemonButton>
)}
</div>
@@ -39,6 +92,14 @@ function ReportCard({ report, enabled }: { report: MCPRecurringReport; enabled:
<div className="text-xs font-medium text-muted">What it asks</div>
<p className="m-0 mt-0.5 text-xs">{report.prompt}</p>
</div>
+
+ {savedReports.length > 0 && (
+ <div className="flex flex-col gap-1">
+ {savedReports.map((saved) => (
+ <SavedReportRow key={saved.id} report={saved} />
+ ))}
+ </div>
+ )}
</LemonCard>
)
}
@@ -50,6 +111,20 @@ function ReportCard({ report, enabled }: { report: MCPRecurringReport; enabled:
*/
export function MCPRecurringReports(): JSX.Element {
const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')
+ const { reports, reportsLoaded, reportsFailed, reportsTruncated } = useValues(mcpRecurringReportsLogic)
+ const { loadReports } = useActions(mcpRecurringReportsLogic)
+
+ // Loaded even without the feature flag: a project can hold reports created before the flag was
+ // turned off, and hiding them would repeat the problem this list exists to fix.
+ useEffect(() => {
+ loadReports()
+ }, [loadReports])
+
+ // A saved report is tied back to the card that offers it by title, which is what the card's
+ // deep-link sets. Renaming one moves it to "Other MCP reports" rather than losing it.
+ const savedByTitle = (title: string): SubscriptionApi[] => reports.filter((saved) => saved.title === title)
+ const templateTitles = new Set(MCP_RECURRING_REPORTS.map((report) => report.title))
+ const otherReports = reports.filter((saved) => !saved.title || !templateTitles.has(saved.title))
return (
<section className="flex flex-col gap-2">
@@ -72,11 +147,48 @@ export function MCPRecurringReports(): JSX.Element {
</p>
)}
+ {reportsFailed && (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: () => loadReports() }}
+ data-attr="mcp-analytics-recurring-reports-load-error"
+ >
+ We couldn't load your MCP reports. Please try again in a moment.
+ </LemonBanner>
+ )}
+
+ {/* Say so rather than quietly dropping the tail — an invisible report is the bug this
+ whole section exists to fix. */}
+ {reportsTruncated && (
+ <p className="m-0 text-xs text-muted">
+ Showing the first {AI_REPORT_LIST_LIMIT} reports.{' '}
+ <Link to={urls.subscriptions()}>See all subscriptions</Link> for the rest.
+ </p>
+ )}
+
<div className="grid gap-2 md:grid-cols-2">
{MCP_RECURRING_REPORTS.map((report) => (
- <ReportCard key={report.key} report={report} enabled={aiSubscriptionsEnabled} />
+ <ReportCard
+ key={report.key}
+ report={report}
+ enabled={aiSubscriptionsEnabled}
+ savedReports={reportsLoaded ? savedByTitle(report.title) : []}
+ />
))}
</div>
+
+ {!reportsLoaded && !reportsFailed && <LemonSkeleton className="h-8 w-full" />}
+
+ {/* Anything MCP-related the cards don't account for still needs a home, so it can't be
+ silently dropped from the list. */}
+ {otherReports.length > 0 && (
+ <LemonCard hoverEffect={false} className="flex flex-col gap-1 p-3">
+ <h3 className="m-0 text-sm font-semibold">Other MCP reports</h3>
+ {otherReports.map((saved) => (
+ <SavedReportRow key={saved.id} report={saved} />
+ ))}
+ </LemonCard>
+ )}
</section>
)
}
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
new file mode 100644
index 000000000000..ba8b1c04846c
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
@@ -0,0 +1,194 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+
+import { initKeaTests } from '~/test/init'
+
+import { toggleSubscriptionEnabled } from 'products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled'
+import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'
+import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'
+
+import { isMCPRecurringReport, mcpRecurringReportsLogic } from './mcpRecurringReportsLogic'
+
+jest.mock('lib/utils/deleteWithUndo', () => ({ deleteWithUndo: jest.fn() }))
+jest.mock('products/subscriptions/frontend/generated/api', () => ({
+ subscriptionsList: jest.fn(),
+}))
+jest.mock('products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled', () => ({
+ toggleSubscriptionEnabled: jest.fn(),
+}))
+
+const mockedDeleteWithUndo = jest.mocked(deleteWithUndo)
+const mockedList = jest.mocked(subscriptionsList)
+const mockedToggle = jest.mocked(toggleSubscriptionEnabled)
+
+const MCP_PROMPT = 'Summarize $mcp_intent on $mcp_tool_call events this week.'
+
+function makeReport(id: number, overrides: Partial<SubscriptionApi> = {}): SubscriptionApi {
+ return {
+ id,
+ title: `Report ${id}`,
+ prompt: MCP_PROMPT,
+ enabled: true,
+ deleted: false,
+ summary: 'sent every week on the first Monday',
+ next_delivery_date: '2026-08-10T12:00:00Z',
+ ...overrides,
+ } as SubscriptionApi
+}
+
+function listReturns(results: SubscriptionApi[], next: string | null = null): void {
+ mockedList.mockResolvedValue({ next, previous: null, results } as any)
+}
+
+describe('mcpRecurringReportsLogic', () => {
+ let logic: ReturnType<typeof mcpRecurringReportsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ mockedDeleteWithUndo.mockReset().mockResolvedValue()
+ mockedToggle.mockReset().mockResolvedValue(true)
+ mockedList.mockReset()
+ listReturns([])
+
+ logic = mcpRecurringReportsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ // The Subscription model has no provenance field, so an ai_prompt report is identified by whether it
+ // actually queries MCP data. These are the cases that decide whether a row reaches the tab at all.
+ it.each([
+ ['names an $mcp_ property', MCP_PROMPT, true],
+ ['names $mcp_ mid-sentence', 'Report on $mcp_tool_call errors.', true],
+ ['only says the word MCP', 'Summarize how our MCP server did this week.', false],
+ ['is about something else', 'Summarize $pageview trends.', false],
+ ['has no prompt at all', null, false],
+ ])('%s -> %s', (_name, prompt, expected) => {
+ expect(isMCPRecurringReport({ prompt })).toBe(expected)
+ })
+
+ it('lists only the MCP reports among the project AI reports', async () => {
+ const mcpReport = makeReport(1)
+ listReturns([mcpReport, makeReport(2, { prompt: 'Weekly $pageview summary.' })])
+
+ await expectLogic(logic, () => logic.actions.loadReports())
+ .toFinishAllListeners()
+ .toMatchValues({ reports: [mcpReport], reportsLoaded: true, reportsFailed: false })
+
+ // The prompt match happens server-side, so only MCP rows cross the wire; the client-side
+ // filter is the precise re-check (search also spans title and insight/dashboard names).
+ expect(mockedList).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ resource_type: 'ai_prompt', search: '$mcp_' })
+ )
+ })
+
+ it.each([
+ ['flags truncation when the server has more', 'http://localhost/api/.../?offset=200', true],
+ ['does not flag a complete page', null, false],
+ ])('%s', async (_name, next, expected) => {
+ // A report the tab silently omits is the exact bug this section exists to fix, so a capped
+ // list has to say so rather than just ending.
+ listReturns([makeReport(1)], next as string | null)
+
+ await expectLogic(logic, () => logic.actions.loadReports())
+ .toFinishAllListeners()
+ .toMatchValues({ reportsTruncated: expected })
+ })
+
+ it('drops soft-deleted reports', async () => {
+ listReturns([makeReport(1, { deleted: true }), makeReport(2)])
+
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+
+ expect(logic.values.reports.map((report) => report.id)).toEqual([2])
+ })
+
+ it('flags a failed load so the banner can offer a retry', async () => {
+ mockedList.mockRejectedValue(new Error('nope'))
+
+ await expectLogic(logic, () => logic.actions.loadReports())
+ .toFinishAllListeners()
+ .toMatchValues({ reportsFailed: true, reportsLoaded: true })
+ })
+
+ it('reverts the toggle when the update is rejected', async () => {
+ listReturns([makeReport(1, { enabled: true })])
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+ mockedToggle.mockResolvedValue(false)
+
+ await expectLogic(logic, () => logic.actions.toggleReportEnabled(1, false)).toFinishAllListeners()
+
+ expect(logic.values.reports[0].enabled).toBe(true)
+ expect(logic.values.pendingToggleIds).toEqual({})
+ })
+
+ it('keeps the toggle when the update succeeds', async () => {
+ listReturns([makeReport(1, { enabled: true })])
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+
+ await expectLogic(logic, () => logic.actions.toggleReportEnabled(1, false)).toFinishAllListeners()
+
+ expect(logic.values.reports[0].enabled).toBe(false)
+ expect(mockedToggle).toHaveBeenCalledWith(1, false)
+ })
+
+ it('restores a deleted report when the delete is undone', async () => {
+ listReturns([makeReport(1), makeReport(2)])
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+ mockedDeleteWithUndo.mockImplementation(async ({ callback }: any) => callback(true, {}))
+
+ await expectLogic(logic, () => logic.actions.deleteReport(logic.values.reports[0])).toFinishAllListeners()
+
+ expect(logic.values.reports.map((report) => report.id)).toEqual([1, 2])
+ })
+
+ it('drops a deleted report from the list', async () => {
+ listReturns([makeReport(1), makeReport(2)])
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+ mockedDeleteWithUndo.mockImplementation(async ({ callback }: any) => callback(false, {}))
+
+ await expectLogic(logic, () => logic.actions.deleteReport(logic.values.reports[0])).toFinishAllListeners()
+
+ expect(logic.values.reports.map((report) => report.id)).toEqual([2])
+ })
+
+ it('puts the row back when the delete fails', async () => {
+ // deleteWithUndo swallows its own API errors and resolves without calling back, so the row
+ // would otherwise stay optimistically gone while the report is alive and still delivering.
+ listReturns([makeReport(1), makeReport(2)])
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+ mockedDeleteWithUndo.mockResolvedValue()
+
+ await expectLogic(logic, () => logic.actions.deleteReport(logic.values.reports[0])).toFinishAllListeners()
+
+ expect(logic.values.reports.map((report) => report.id).sort()).toEqual([1, 2])
+ })
+
+ it('undoing one delete does not resurrect a different deleted report', async () => {
+ // Restoring from a whole-list snapshot would replay the state before the second delete.
+ listReturns([makeReport(1), makeReport(2)])
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+
+ const [first, second] = logic.values.reports
+ let undoFirst: (() => void) | undefined
+ mockedDeleteWithUndo.mockImplementation(async ({ object, callback }: any) => {
+ if (object.id === first.id) {
+ undoFirst = () => callback(true, object)
+ } else {
+ callback(false, object)
+ }
+ })
+
+ await expectLogic(logic, () => logic.actions.deleteReport(first)).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.deleteReport(second)).toFinishAllListeners()
+ undoFirst?.()
+
+ expect(logic.values.reports.map((report) => report.id)).toEqual([first.id])
+ })
+})
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
new file mode 100644
index 000000000000..9d88513e8fc7
--- /dev/null
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
@@ -0,0 +1,222 @@
+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
+
+import { toggleSubscriptionEnabled } from 'products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled'
+import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'
+import { SubscriptionApi, SubscriptionsListResourceType } from 'products/subscriptions/frontend/generated/api.schemas'
+
+// A ceiling on what one tab render will pull. The server-side `search` below already narrows to MCP
+// reports, so reaching this means a project with hundreds of them — at which point the list is the
+// wrong tool anyway and `reportsTruncated` says so rather than quietly dropping the tail.
+export const AI_REPORT_LIST_LIMIT = 200
+
+/**
+ * A Subscription has no field saying which product created it — `resource_type` is derived from which
+ * of insight/dashboard/prompt is set, and an `ai_prompt` one carries nothing but free text. So "is this
+ * an MCP report?" is answered the way the instant-alert list answers it for hog functions: by what the
+ * thing actually queries. Every report the cards create names `$mcp_*` properties, and a hand-written
+ * one reporting on MCP data has to name them too.
+ *
+ * The cost of matching on content is that editing those property names out of a prompt drops it off
+ * this tab. The alternative is a provenance column on a model owned outside this product, which would
+ * also show nothing for the reports that already exist.
+ */
+const MCP_PROPERTY_PREFIX = '$mcp_'
+
+export function isMCPRecurringReport(subscription: Pick<SubscriptionApi, 'prompt'>): boolean {
+ return (subscription.prompt ?? '').includes(MCP_PROPERTY_PREFIX)
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface mcpRecurringReportsLogicValues {
+ pendingToggleIds: Record<number, true>
+ reports: SubscriptionApi[]
+ reportsFailed: boolean
+ reportsLoaded: boolean
+ reportsLoading: boolean
+ reportsTruncated: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface mcpRecurringReportsLogicActions {
+ deleteReport: (report: SubscriptionApi) => {
+ report: SubscriptionApi
+ }
+ loadReports: () => any
+ loadReportsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadReportsSuccess: (
+ reports: SubscriptionApi[],
+ payload?: any
+ ) => {
+ reports: SubscriptionApi[]
+ payload?: any
+ }
+ setReports: (reports: SubscriptionApi[]) => {
+ reports: SubscriptionApi[]
+ }
+ setReportsTruncated: (reportsTruncated: boolean) => {
+ reportsTruncated: boolean
+ }
+ toggleReportEnabled: (
+ reportId: number,
+ enabled: boolean
+ ) => {
+ enabled: boolean
+ reportId: number
+ }
+ toggleReportEnabledSettled: (reportId: number) => {
+ reportId: number
+ }
+ toggleReportEnabledStarted: (reportId: number) => {
+ reportId: number
+ }
+}
+
+export type mcpRecurringReportsLogicType = MakeLogicType<
+ mcpRecurringReportsLogicValues,
+ mcpRecurringReportsLogicActions
+>
+
+export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([
+ path(['products', 'mcp_analytics', 'frontend', 'notifications', 'mcpRecurringReportsLogic']),
+ actions({
+ toggleReportEnabled: (reportId: number, enabled: boolean) => ({ reportId, enabled }),
+ toggleReportEnabledStarted: (reportId: number) => ({ reportId }),
+ toggleReportEnabledSettled: (reportId: number) => ({ reportId }),
+ // Optimistic writes go through this rather than the loader's success action, which would also
+ // clear `reportsLoading` and hide a reload that is still in flight.
+ setReports: (reports: SubscriptionApi[]) => ({ reports }),
+ setReportsTruncated: (reportsTruncated: boolean) => ({ reportsTruncated }),
+ deleteReport: (report: SubscriptionApi) => ({ report }),
+ }),
+ loaders(({ actions }) => ({
+ reports: [
+ [] as SubscriptionApi[],
+ {
+ loadReports: async (): Promise<SubscriptionApi[]> => {
+ // `search` matches the prompt server-side, so the rows that cross the wire are
+ // already the MCP ones rather than every AI report the project has. It also spans
+ // title and insight/dashboard names, so `isMCPRecurringReport` still runs as the
+ // precise test — a report merely *titled* "$mcp_" is not one.
+ const response = await subscriptionsList(String(getCurrentTeamId()), {
+ resource_type: SubscriptionsListResourceType.AiPrompt,
+ search: MCP_PROPERTY_PREFIX,
+ limit: AI_REPORT_LIST_LIMIT,
+ })
+ actions.setReportsTruncated(!!response.next)
+ return response.results.filter(
+ (subscription) => !subscription.deleted && isMCPRecurringReport(subscription)
+ )
+ },
+ },
+ ],
+ })),
+ reducers({
+ reports: {
+ setReports: (_: SubscriptionApi[], { reports }: { reports: SubscriptionApi[] }) => reports,
+ },
+ pendingToggleIds: [
+ {} as Record<number, true>,
+ {
+ toggleReportEnabledStarted: (state, { reportId }) => ({ ...state, [reportId]: true }),
+ toggleReportEnabledSettled: (state, { reportId }) => {
+ const nextState = { ...state }
+ delete nextState[reportId]
+ return nextState
+ },
+ },
+ ],
+ reportsFailed: [
+ false,
+ {
+ loadReports: () => false,
+ loadReportsSuccess: () => false,
+ loadReportsFailure: () => true,
+ },
+ ],
+ reportsTruncated: [
+ false,
+ {
+ setReportsTruncated: (_, { reportsTruncated }) => reportsTruncated,
+ },
+ ],
+ // The list loads when the tab mounts; without this the first render would flash the empty state.
+ reportsLoaded: [
+ false,
+ {
+ loadReportsSuccess: () => true,
+ loadReportsFailure: () => true,
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ toggleReportEnabled: async ({ reportId, enabled }) => {
+ if (values.pendingToggleIds[reportId]) {
+ return
+ }
+ const target = values.reports.find((report) => report.id === reportId)
+ if (!target) {
+ return
+ }
+ actions.toggleReportEnabledStarted(reportId)
+
+ const applyEnabled = (next: boolean): void => {
+ actions.setReports(
+ values.reports.map((report) => (report.id === reportId ? { ...report, enabled: next } : report))
+ )
+ }
+
+ 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))) {
+ applyEnabled(!enabled)
+ }
+ actions.toggleReportEnabledSettled(reportId)
+ },
+ deleteReport: async ({ report }) => {
+ // Re-insert just this row at the position it held, rather than replaying a whole-list
+ // snapshot: a second delete may have landed in between, and replaying would resurrect what
+ // it removed.
+ const removedIndex = values.reports.findIndex((item) => item.id === report.id)
+ const restore = (): void => {
+ if (values.reports.some((item) => item.id === report.id)) {
+ return
+ }
+ const restored = [...values.reports]
+ restored.splice(Math.min(removedIndex, restored.length), 0, report)
+ actions.setReports(restored)
+ }
+
+ actions.setReports(values.reports.filter((item) => item.id !== report.id))
+
+ // `deleteWithUndo` swallows its own API errors and resolves without calling back, so a
+ // failed delete is only detectable by the callback never firing — otherwise the row stays
+ // optimistically gone while the report is alive and still delivering.
+ let callbackFired = false
+ await deleteWithUndo({
+ endpoint: api.subscriptions.determineDeleteEndpoint(),
+ object: { id: report.id, name: report.title ?? 'Report' },
+ callback: (undo) => {
+ callbackFired = true
+ if (undo) {
+ restore()
+ }
+ },
+ })
+ if (!callbackFired) {
+ restore()
+ }
+ },
+ })),
+])