: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(mcp-analytics): filter activity and session views (#103011)
Lucas Faria66b1badafb0c
diff --git a/docs/internal/mcp-analytics-filter-navigation.md b/docs/internal/mcp-analytics-filter-navigation.mdindex 2880ea6c488b..e49a06273397 100644--- a/docs/internal/mcp-analytics-filter-navigation.md+++ b/docs/internal/mcp-analytics-filter-navigation.md@@ -4,6 +4,9 @@ The Dashboard stores its property filters and internal/test-user choice in the UTab links, KPI links, and tool-report links carry those parameters so the Dashboard restores the same selection when someone returns.An absent or invalid `filter_test_accounts` value follows the project's default; `true` and `false` are explicit overrides.-The Tool quality queries accept event, person, and session property filters and the test-account choice.-The Tool quality tab will not apply them until its UI wiring lands.-Tool reports, Sessions, and Activity still need query and UI wiring before their metrics can be described as filtered by these parameters.+The Dashboard, Tool quality, tool reports, Sessions, and Activity apply the shared property filters and test-account choice.+Their query runners and API endpoints accept event, person, and session property filters and reject executable HogQL, cohort, and warehouse filters under the MCP analytics read scope.++Each report keeps its own date range.+Changing a shared filter closes open failure details and reloads the report.+The shared toolbar wraps active property filters onto a second row when space is limited.diff --git a/docs/published/docs/mcp-analytics/activity.mdx b/docs/published/docs/mcp-analytics/activity.mdxindex 954b3e6b4d4b..1105bb35e732 100644--- a/docs/published/docs/mcp-analytics/activity.mdx+++ b/docs/published/docs/mcp-analytics/activity.mdx@@ -5,6 +5,10 @@ title: Activity tab and recent activityThe **Activity** tab is where a new MCP analytics project lands until it has enough tool calls for the dashboard's charts to mean something.It answers "what are agents doing with my server?" one call at a time.+Property and internal user filters are shared across Overview, Tool quality, Activity, Sessions, and individual tool reports.+They stay selected when you switch sections and are saved in the URL.+Each report keeps its own date range.+## What is on the tab- A one-line summary of the last 30 days: calls, clients, the most used tool, and how many calls failed. Select the failure count to filter the feed to failed calls.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7d82c67a6b23..68b23adacd8f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10181,9 +10181,9 @@ snapshots:scenes-app-max-ai-replay-vision-scan-widget--with-skipped--light:hash: v1.k794b7964.c543228b0f31abb2aae3b274819abdee4ba6a89fb3324fc6aaa2b18aefee5815.S9etTEY8oT2JhOgLO5hdc6VqvbvYhD-nU4P1WKh24ygscenes-app-mcp-analytics--activity--dark:- hash: v1.k794b7964.053ce58d65ad7c1afed42253ee8145de6e4d7dcedae011774df038dc4bc99463.mtjBtxh7-xuLO9Da1fWP6b4iJkOR_rVQ8ZEBLXMsl_Q+ hash: v1.k794b7964.ee472b720195e99557f4c941702fdd1e34daca0a38f002139069e204a32c1fd8.1FmvB6ytIRhdKJhtz_d9X53T8fFs3dIoMPjBoyEk7gwscenes-app-mcp-analytics--activity--light:- hash: v1.k794b7964.aa6f1e0fc90466a186712d7e02a717ecdc7fbdb9ac8217c6e7d7965dd4c39744.eQrokHfce0EIKg6C6H33jFxPjovtPFGvRTOePKxFqa8+ hash: v1.k794b7964.68c0bb50d3b68ed5d85c6bf380d7201c8e2bc228c13f8c713874ab11d22e0e12.IF6iwaZqG4W5AX3HO2N6E-CheAcO1qjEF2M7sk7kpfMscenes-app-mcp-analytics--dashboard--medium--dark:hash: v1.k794b7964.2ef1f525242659b2834e0b6c1ebc7813fe9215f5dc8f1c5168a8083329922047.3_w9VHYw_4dJuCI7bb92f7yXzlMokllKG5rd5NHHBuEscenes-app-mcp-analytics--dashboard--medium--light:@@ -10205,9 +10205,9 @@ snapshots:scenes-app-mcp-analytics--intent-clustering--light:hash: v1.k794b7964.82fd6a9108a34ff8808b23b9c1e9255dcbe4f38562bb9e99333877dd303c08b2.qjDLxTHFZT3vcTHmPeG35-orU88GSS277RR2DdXxBdwscenes-app-mcp-analytics--sessions--dark:- hash: v1.k794b7964.a66e676a524e1de75d68579adb63b097fc17ed5db94ca86dccbf9e6265b169ac.sVkiD6KMNejyrVPs1hOZjHQWspPL2a7lvOWA6VcPNps+ hash: v1.k794b7964.d7e2a435b3c2d3baa85c1eaae02324089794b2728e31a92b9dedfcb1d92e2858.s2HRNIx6nrjdi0xwEqEzhqoYODlq0JVCIHaHy5ha_Wkscenes-app-mcp-analytics--sessions--light:- hash: v1.k794b7964.17f5e27f60024ff6e083bc6b799427b40e475fddb3bf7900aaab5f935d509b23.cgze06ZKpLRtg_doPvcuWuj_yfLplR3PlkqRGeqxzfE+ hash: v1.k794b7964.d2363c5259b989b50bf770f821715c3782dbb35641a7f308555f31198583e392.OgecAQt-4DF27Tyv3e7qfOkwpT6kDr1sSuN-9OS0iAMscenes-app-mcp-analytics--tool-quality--dark:hash: v1.k794b7964.3ad8d8cd5279b4a71f6c5f92cae80fa1b23ab125c30a1ca04b1f3b7ee7a9c8f0.08GjLTK6WJtlxDfcmYZhOKAsud2lE7V4CakPEJ0hjjAscenes-app-mcp-analytics--tool-quality--light:diff --git a/products/mcp_analytics/frontend/components/toolCallFeedQuery.ts b/products/mcp_analytics/frontend/components/toolCallFeedQuery.tsindex 07a886b83977..9d23645f7f05 100644--- a/products/mcp_analytics/frontend/components/toolCallFeedQuery.ts+++ b/products/mcp_analytics/frontend/components/toolCallFeedQuery.ts@@ -71,6 +71,13 @@ export function buildRecentToolCallsQuery(filters: HogQLFilters): DataTableNode}}+export function withSharedFilters(+ query: DataTableNode,+ filters: Required<Pick<HogQLFilters, 'filterTestAccounts' | 'properties'>>+): DataTableNode {+ return query.source.kind === NodeKind.EventsQuery ? { ...query, source: { ...query.source, ...filters } } : query+}+// Matches both encodings the backend counts as failures (see MCP_ERROR_VALUES in ToolCallFeed).const FAILED_CALLS_FILTER: AnyPropertyFilter = {key: '$mcp_is_error',diff --git a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsxindex 12ade5f11b38..5536814b955d 100644--- a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx+++ b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx@@ -4,6 +4,7 @@ import { LemonSkeleton, Link } from '@posthog/lemon-ui'import { urls } from 'scenes/urls'+import { McpSharedFilters } from '../components/McpSharedFilters'import { formatNumber } from '../dashboard/formatters'import { METRICS_UNLOCK_LIFETIME_CALLS, mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'import { ActivityCallers } from './ActivityCallers'@@ -20,8 +21,17 @@ import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'* the Dashboard tab but can always come here for recency.*/export function MCPAnalyticsActivityDashboard(): JSX.Element {+ const { harnessRowsLoading, modelRowsLoading, overviewLoading } = useValues(mcpEarlyDataLogic)+ const { refreshAll } = useActions(mcpEarlyDataLogic)+return (<div className="flex flex-col gap-4" data-attr="mcp-analytics-activity">+ <McpSharedFilters+ pageKey="mcp-activity"+ dataAttrPrefix="mcp-activity"+ onRefresh={refreshAll}+ refreshing={overviewLoading || harnessRowsLoading || modelRowsLoading}+ /><ActivitySummary /><ActivityNextSteps /><ActivityFeed />diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.tsnew file mode 100644index 000000000000..742933d169d4--- /dev/null+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts@@ -0,0 +1,74 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { initKeaTests } from '~/test/init'+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'++import { mcpAnalyticsSessionsActivityOverview } from '../generated/api'+import { mcpAnalyticsFiltersLogic } from '../mcpAnalyticsFiltersLogic'+import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'++jest.mock('lib/api')+jest.mock('../generated/api', () => ({ mcpAnalyticsSessionsActivityOverview: jest.fn() }))++const overviewMock = mcpAnalyticsSessionsActivityOverview as jest.Mock+const TOOL_FILTER: AnyPropertyFilter = {+ key: '$mcp_tool_name',+ value: ['create_insight'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+}++describe('mcpEarlyDataLogic', () => {+ let logic: ReturnType<typeof mcpEarlyDataLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.spyOn(api as jest.Mocked<typeof api>, 'query').mockResolvedValue({ results: [] } as any)+ jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({+ count: 0,+ next: null,+ previous: null,+ results: [],+ })+ overviewMock.mockResolvedValue(null)+ logic = mcpEarlyDataLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.clearAllMocks()+ })++ it.each([+ [+ 'restored URL filters',+ () => mcpAnalyticsFiltersLogic.actions.hydrateFilters(true, [TOOL_FILTER]),+ { filter_test_accounts: true, properties: expect.stringContaining('$mcp_tool_name') },+ { filterTestAccounts: true, properties: [TOOL_FILTER] },+ ],+ [+ 'property filters',+ () => mcpAnalyticsFiltersLogic.actions.setPropertyFilters([TOOL_FILTER]),+ { properties: expect.stringContaining('$mcp_tool_name') },+ { filterTestAccounts: false, properties: [TOOL_FILTER] },+ ],+ [+ 'the test-account switch',+ () => mcpAnalyticsFiltersLogic.actions.setFilterTestAccounts(true),+ { filter_test_accounts: true },+ { filterTestAccounts: true, properties: [] },+ ],+ ])('refetches activity with %s', async (_label, change, expectedParams, expectedQuery) => {+ await expectLogic(logic).toFinishAllListeners()+ overviewMock.mockClear()++ await expectLogic(logic, change).toDispatchActions(['loadOverviewSuccess'])++ expect(overviewMock).toHaveBeenCalledTimes(1)+ expect(overviewMock.mock.calls[0][1]).toMatchObject(expectedParams)+ expect(logic.values.activityQuery.source).toMatchObject(expectedQuery)+ })+})diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.tsindex 2e7f0193a097..22c76ebfa0d8 100644--- a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts@@ -18,9 +18,11 @@ import {DEFAULT_MCP_ACTIVITY_QUERY,MCP_ACTIVITY_DATA_COLLECTION_ID,withFailedCallsOnly,+ withSharedFilters,} from '../components/toolCallFeedQuery'import { mcpAnalyticsSessionsActivityOverview } from '../generated/api'import type { MCPActivityOverviewApi } from '../generated/api.schemas'+import { type MCPSharedQueryFilters, mcpAnalyticsFiltersLogic, sharedFilterParams } from '../mcpAnalyticsFiltersLogic'import { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'import type { MCPOnboardingSignals } from '../mcpAnalyticsOnboardingLogic'import type { HarnessRow, ModelRow } from '../mcpDashboardOverviewLogic'@@ -57,6 +59,7 @@ const REFRESH_INTERVAL_MS = 60000// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpEarlyDataLogicValues {+ sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogicnotifications: HogFunctionType[] // mcpAnalyticsNotificationsLogicsignals: MCPOnboardingSignals | null // mcpAnalyticsOnboardingLogiccurrentProjectId: number | string // teamLogic@@ -79,6 +82,19 @@ export interface mcpEarlyDataLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpEarlyDataLogicActions {reloadActivityQuery: () => {} // dataNodeCollectionLogic+ hydrateFilters: (+ filterTestAccountsOverride: boolean | null,+ propertyFilters: import('~/types').AnyPropertyFilter[]+ ) => {+ filterTestAccountsOverride: boolean | null+ propertyFilters: import('~/types').AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogic+ setFilterTestAccounts: (filterTestAccounts: boolean | null) => {+ filterTestAccounts: boolean | null+ } // mcpAnalyticsFiltersLogic+ setPropertyFilters: (properties: import('~/types').AnyPropertyFilter[]) => {+ properties: import('~/types').AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogicloadNotifications: () => any // mcpAnalyticsNotificationsLogicloadNotificationsSuccess: (notifications: HogFunctionType[],@@ -136,6 +152,9 @@ export interface mcpEarlyDataLogicActions {refreshAll: () => {value: true}+ refreshFilteredActivity: () => {+ value: true+ }setActivityQuery: (query: DataTableNode) => {query: DataTableNode}@@ -171,6 +190,8 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([['signals'],teamLogic,['currentProjectId'],+ mcpAnalyticsFiltersLogic,+ ['queryFilters as sharedQueryFilters'],mcpAnalyticsNotificationsLogic,['notifications'],],@@ -179,6 +200,8 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([// advance even after the onboarding signal poll stops.mcpAnalyticsOnboardingLogic,['loadSignals'],+ mcpAnalyticsFiltersLogic,+ ['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters'],mcpAnalyticsNotificationsLogic,['loadNotifications', 'loadNotificationsSuccess'],dataNodeCollectionLogic({ key: MCP_ACTIVITY_DATA_COLLECTION_ID }),@@ -187,6 +210,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([})),actions({refreshAll: true,+ refreshFilteredActivity: true,setActivityQuery: (query: DataTableNode) => ({ query }),showFailedCallsOnly: true,}),@@ -202,7 +226,10 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([if (!values.currentProjectId) {return null}- const response = await mcpAnalyticsSessionsActivityOverview(String(values.currentProjectId))+ const response = await mcpAnalyticsSessionsActivityOverview(+ String(values.currentProjectId),+ sharedFilterParams(values.sharedQueryFilters)+ )breakpoint()return response},@@ -214,6 +241,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([const response = (await api.query({kind: NodeKind.MCPHarnessBreakdownQuery,...ACTIVITY_FILTERS,+ ...values.sharedQueryFilters,})) as { results?: MCPHarnessBreakdownItem[] }breakpoint()return (response?.results ?? []).map((r) => ({@@ -233,6 +261,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([const response = (await api.query({kind: NodeKind.MCPModelBreakdownQuery,...ACTIVITY_FILTERS,+ ...values.sharedQueryFilters,})) as { results?: MCPModelBreakdownItem[] }breakpoint()return response?.results ?? []@@ -291,17 +320,27 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([listeners(({ actions, values }) => ({refreshAll: () => {actions.loadSignals()- actions.loadOverview()actions.loadNotifications()+ actions.refreshFilteredActivity()+ },+ refreshFilteredActivity: () => {+ actions.setActivityQuery(withSharedFilters(values.activityQuery, values.sharedQueryFilters))+ actions.loadOverview()actions.loadHarnessRows()actions.loadModelRows()actions.reloadActivityQuery()},+ hydrateFilters: () => actions.refreshFilteredActivity(),+ setFilterTestAccounts: () => actions.refreshFilteredActivity(),+ setPropertyFilters: () => actions.refreshFilteredActivity(),showFailedCallsOnly: () => {actions.setActivityQuery(withFailedCallsOnly(values.activityQuery))},})),afterMount(({ actions, cache }) => {+ actions.setActivityQuery(+ withSharedFilters(DEFAULT_MCP_ACTIVITY_QUERY, mcpAnalyticsFiltersLogic.values.queryFilters)+ )actions.loadOverview()actions.loadNotifications()actions.loadHarnessRows()diff --git a/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.tsindex 38820f56a4d9..464ad8b6db3d 100644--- a/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.ts+++ b/products/mcp_analytics/frontend/mcpAnalyticsFiltersLogic.ts@@ -12,6 +12,18 @@ import type { TeamPublicType } from '../../../frontend/src/types'export type MCPSharedQueryFilters = Required<Pick<HogQLFilters, 'filterTestAccounts' | 'properties'>>+export interface MCPSharedFilterParams {+ properties?: string+ filter_test_accounts?: boolean+}++export function sharedFilterParams(filters: MCPSharedQueryFilters): MCPSharedFilterParams {+ return {+ properties: filters.properties.length > 0 ? JSON.stringify(filters.properties) : undefined,+ filter_test_accounts: filters.filterTestAccounts || undefined,+ }+}+export const MCP_ANALYTICS_FILTER_ROUTES = [urls.mcpAnalyticsActivity(),urls.mcpAnalyticsDashboard(),diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsxindex 39598e0933cd..2b8566cb1ca5 100644--- a/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx+++ b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx@@ -27,7 +27,7 @@ function MetaBadge({ icon, label }: { icon: React.ReactNode; label: React.ReactNexport function MCPSessionDetail(): JSX.Element {const { selectedSession, selectedSessionToolCalls, selectedSessionIntent, isSelectedSessionGenerating } =useValues(mcpSessionsLogic)- const { generateIntent, loadMoreToolCalls } = useActions(mcpSessionsLogic)+ const { generateIntent, loadMoreToolCalls, loadToolCalls } = useActions(mcpSessionsLogic)if (!selectedSession) {return (@@ -46,7 +46,7 @@ export function MCPSessionDetail(): JSX.Element {// The panel's view of the selected session's calls: the list, whether more pages exist, whether// the first page is still loading (skeleton), and whether a "Load more" append is in flight.- const { calls: toolCalls, hasNext, loading, loadingMore } = selectedSessionToolCalls+ const { calls: toolCalls, hasNext, loading, loadingMore, error } = selectedSessionToolCallsreturn (<div className="flex flex-col h-full min-h-0">@@ -131,6 +131,13 @@ export function MCPSessionDetail(): JSX.Element {<div className="flex flex-col gap-2"><LemonSkeleton repeat={3} className="h-16 w-full" /></div>+ ) : error ? (+ <div className="flex flex-col items-start gap-2 text-sm text-secondary">+ Could not load this session's tool calls.+ <LemonButton size="small" onClick={() => loadToolCalls(selectedSession.session_id)}>+ Retry+ </LemonButton>+ </div>) : toolCalls.length === 0 ? (<div className="text-sm text-secondary">No tool calls captured for this session.</div>) : (diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsxindex 2f57f09f1158..a449a7d1f5de 100644--- a/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx+++ b/products/mcp_analytics/frontend/sessions/MCPSessionsPlaylist.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { memo, useRef } from 'react'-import { IconBolt, IconClock, IconRefresh, IconSearch, IconSparkles } from '@posthog/icons'+import { IconBolt, IconClock, IconSearch, IconSparkles } from '@posthog/icons'import {Button,InputGroup,@@ -26,6 +26,7 @@ import { cn } from 'lib/utils/css-classes'import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'import { McpDateFilter } from '../components/McpDateFilter'+import { McpSharedFilters } from '../components/McpSharedFilters'import type { MCPSessionApi } from '../generated/api.schemas'import { MCPSessionDetail } from './MCPSessionDetail'import { type MCPSessionOrderBy, type MCPSessionSorting, mcpSessionsLogic, orderByParam } from './mcpSessionsLogic'@@ -52,17 +53,29 @@ function valueToSorting(value: MCPSessionOrderBy): MCPSessionSorting {export function MCPSessionsPlaylist(): JSX.Element {const { sidePanelWidth } = useValues(panelLayoutLogic)+ const { dateFilter, sessionsLoading, toolCallsLoading } = useValues(mcpSessionsLogic)+ const { setDateFilter, refreshSessions } = useActions(mcpSessionsLogic)const { isWindowLessThan } = useWindowSize({ widthOffset: sidePanelWidth })const isVerticalLayout = isWindowLessThan('xl')return (- <div- className={cn(- 'w-full h-[calc(100vh-13rem)] min-h-[25rem] flex',- isVerticalLayout ? 'flex-col' : 'flex-row gap-2'- )}- >- {isVerticalLayout ? <VerticalLayout /> : <HorizontalLayout />}+ <div className="flex w-full h-[calc(100vh-13rem)] min-h-[25rem] flex-col gap-2">+ <McpSharedFilters+ pageKey="mcp-sessions"+ dataAttrPrefix="mcp-sessions"+ onRefresh={refreshSessions}+ refreshing={sessionsLoading || toolCallsLoading}+ >+ <McpDateFilter+ dateFrom={dateFilter.dateFrom}+ dateTo={dateFilter.dateTo}+ onChange={(dateFrom, dateTo) => setDateFilter(dateFrom, dateTo)}+ dataAttr="mcp-sessions-date-filter"+ />+ </McpSharedFilters>+ <div className={cn('flex min-h-0 flex-1', isVerticalLayout ? 'flex-col' : 'flex-row gap-2')}>+ {isVerticalLayout ? <VerticalLayout /> : <HorizontalLayout />}+ </div></div>)}@@ -134,17 +147,15 @@ function SessionDetailPanel({ className }: { className?: string }): JSX.Element}function SessionsListPanel(): JSX.Element {- const { setFilters, setDateFilter, loadSessions, loadMoreSessions, setSorting, selectSession } =- useActions(mcpSessionsLogic)- const { sessions, sessionsLoading, filters, dateFilter, sorting, hasNext, selectedSessionId } =- useValues(mcpSessionsLogic)+ const { setFilters, loadMoreSessions, setSorting, selectSession } = useActions(mcpSessionsLogic)+ const { sessions, sessionsLoading, filters, sorting, hasNext, selectedSessionId } = useValues(mcpSessionsLogic)return (<div className="flex flex-col h-full min-h-0 overflow-hidden rounded border border-primary bg-surface-primary"><div className="shrink-0 flex flex-col gap-2 border-b border-primary p-2"><div className="flex flex-col gap-2" data-quill>- <div className="flex items-center gap-2">- <InputGroup className="flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <InputGroup className="min-w-40 flex-1"><InputGroupAddon align="inline-start"><InputGroupText><IconSearch />@@ -157,24 +168,6 @@ function SessionsListPanel(): JSX.Element {value={filters.search}/></InputGroup>- <Button- variant="outline"- size="icon"- className="size-8"- onClick={() => loadSessions()}- disabled={sessionsLoading}- title="Reload sessions"- >- {sessionsLoading ? <Spinner /> : <IconRefresh />}- </Button>- </div>- <div className="flex items-center justify-between gap-1">- <McpDateFilter- dateFrom={dateFilter.dateFrom}- dateTo={dateFilter.dateTo}- onChange={(dateFrom, dateTo) => setDateFilter(dateFrom, dateTo)}- dataAttr="mcp-sessions-date-filter"- /><Selectvalue={sortingToValue(sorting)}onValueChange={(value) => setSorting(valueToSorting(value as MCPSessionOrderBy))}diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.tsindex 15f157c923da..3c5722420e76 100644--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.test.ts@@ -1,8 +1,10 @@import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import { mcpAnalyticsSessionsList, mcpAnalyticsSessionsToolCalls } from '../generated/api'+import { mcpAnalyticsFiltersLogic } from '../mcpAnalyticsFiltersLogic'import { mcpSessionsLogic } from './mcpSessionsLogic'jest.mock('../generated/api', () => ({@@ -39,6 +41,48 @@ describe('mcpSessionsLogic', () => {jest.clearAllMocks()})+ it('refreshes the list and selected session calls together', async () => {+ listMock.mockResolvedValue({ results: [{ session_id: 'A', session_start: '2026-01-01T00:00:00Z' }] })+ toolCallsMock.mockResolvedValue({ results: [toolCall('first')], has_next: false })+ await expectLogic(logic, () => logic.actions.loadSessions()).toDispatchActions([+ 'loadSessionsSuccess',+ 'loadToolCallsSuccess',+ ])+ listMock.mockClear()+ toolCallsMock.mockClear()+ toolCallsMock.mockResolvedValue({ results: [toolCall('updated')], has_next: false })++ await expectLogic(logic, () => logic.actions.refreshSessions()).toDispatchActions([+ 'loadSessionsSuccess',+ 'loadToolCallsSuccess',+ ])++ expect(listMock).toHaveBeenCalledTimes(1)+ expect(toolCallsMock).toHaveBeenCalledTimes(1)+ expect(logic.values.selectedSessionId).toBe('A')+ expect(logic.values.selectedSessionToolCalls.calls.map((call) => call.event_id)).toEqual(['updated'])+ })++ it('ignores a failed request for a previously selected session', async () => {+ let rejectFirst: (error: Error) => void = () => {}+ toolCallsMock.mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ rejectFirst = reject+ })+ )+ await expectLogic(logic, () => logic.actions.selectSession('A')).toDispatchActions(['loadToolCalls'])+ toolCallsMock.mockResolvedValueOnce({ results: [toolCall('b1')], has_next: false })+ await expectLogic(logic, () => logic.actions.selectSession('B')).toDispatchActions(['loadToolCallsSuccess'])++ rejectFirst(new Error('Unavailable'))+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.selectedSessionId).toBe('B')+ expect(logic.values.selectedSessionToolCalls.calls.map((call) => call.event_id)).toEqual(['b1'])+ expect(logic.values.selectedSessionToolCalls.error).toBe(false)+ })+it('keeps the skeleton on the newly selected session when a prior load-more resolves late', async () => {// Session A: a first page with a further page available.toolCallsMock.mockResolvedValueOnce({ results: [toolCall('a1')], has_next: true })@@ -70,4 +114,181 @@ describe('mcpSessionsLogic', () => {expect(logic.values.selectedSessionToolCalls.loading).toBe(true)expect(logic.values.selectedSessionToolCalls.calls.map((c) => c.event_id)).not.toContain('a2')})++ it('drops a session page when a refresh starts with the same filters', async () => {+ listMock.mockResolvedValueOnce({+ results: [{ session_id: 'old', session_start: '2026-01-01T00:00:00Z' }],+ has_next: true,+ })+ toolCallsMock.mockResolvedValue({ results: [], has_next: false })+ await expectLogic(logic, () => logic.actions.loadSessions()).toDispatchActions(['loadSessionsSuccess'])++ let resolveMore: (value: any) => void = () => {}+ listMock.mockImplementationOnce(() => new Promise((resolve) => (resolveMore = resolve)))+ await expectLogic(logic, () => logic.actions.loadMoreSessions()).toDispatchActions(['loadMoreSessions'])++ listMock.mockResolvedValueOnce({+ results: [{ session_id: 'fresh', session_start: '2026-01-01T00:01:00Z' }],+ has_next: false,+ })+ await expectLogic(logic, () => logic.actions.loadSessions()).toDispatchActions(['loadSessionsSuccess'])+ await expectLogic(logic, () =>+ resolveMore({ results: [{ session_id: 'stale' }], has_next: false })+ ).toDispatchActions(['loadMoreSessionsSuccess'])++ expect(logic.values.sessions.map((session) => session.session_id)).toEqual(['fresh'])+ })++ it('drops a tool-call page when a refresh starts for the same session', async () => {+ toolCallsMock.mockResolvedValueOnce({ results: [toolCall('old')], has_next: true })+ await expectLogic(logic, () => logic.actions.selectSession('A')).toDispatchActions(['loadToolCallsSuccess'])++ let resolveMore: (value: any) => void = () => {}+ toolCallsMock.mockImplementationOnce(() => new Promise((resolve) => (resolveMore = resolve)))+ await expectLogic(logic, () => logic.actions.loadMoreToolCalls()).toDispatchActions(['loadMoreToolCalls'])++ toolCallsMock.mockResolvedValueOnce({ results: [toolCall('fresh')], has_next: false })+ await expectLogic(logic, () => logic.actions.loadToolCalls('A')).toDispatchActions(['loadToolCallsSuccess'])+ await expectLogic(logic, () =>+ resolveMore({ results: [toolCall('stale')], has_next: false })+ ).toDispatchActions(['loadMoreToolCallsSuccess'])++ expect(logic.values.selectedSessionToolCalls.calls.map((call) => call.event_id)).toEqual(['fresh'])+ })++ describe('shared filters', () => {+ const TOOL_FILTER: AnyPropertyFilter = {+ key: '$mcp_tool_name',+ value: ['create_insight'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ }++ it.each([+ [+ 'restored URL filters',+ () => mcpAnalyticsFiltersLogic.actions.hydrateFilters(true, [TOOL_FILTER]),+ { filter_test_accounts: true, properties: JSON.stringify([TOOL_FILTER]) },+ ],+ [+ 'property filters',+ () => mcpAnalyticsFiltersLogic.actions.setPropertyFilters([TOOL_FILTER]),+ { properties: JSON.stringify([TOOL_FILTER]) },+ ],+ [+ 'the test-account switch',+ () => mcpAnalyticsFiltersLogic.actions.setFilterTestAccounts(true),+ { filter_test_accounts: true },+ ],+ ])('reloads the list with %s', async (_label, change, expectedParams) => {+ listMock.mockClear()++ await expectLogic(logic, change).toDispatchActions(['loadSessionsSuccess'])++ expect(listMock).toHaveBeenCalledTimes(1)+ expect(listMock.mock.calls[0][1]).toMatchObject(expectedParams)+ })++ it.each([false, true])("reloads the selected session's calls with failure=%s", async (fails) => {+ const consoleErrorSpy = fails ? jest.spyOn(console, 'error').mockImplementation(() => {}) : null+ listMock.mockResolvedValue({+ results: [{ session_id: 'A', session_start: '2026-01-01T00:05:00Z' }],+ has_next: true,+ })+ toolCallsMock.mockResolvedValueOnce({ results: [toolCall('a1')], has_next: true })+ await expectLogic(logic, () => {+ logic.actions.loadSessions()+ }).toDispatchActions(['loadSessionsSuccess', 'loadToolCallsSuccess'])+ toolCallsMock.mockClear()++ let resolveFiltered: (value: any) => void = () => {}+ let rejectFiltered: (error: Error) => void = () => {}+ toolCallsMock.mockImplementationOnce(+ () =>+ new Promise((resolve, reject) => {+ resolveFiltered = resolve+ rejectFiltered = reject+ })+ )+ await expectLogic(logic, () => {+ mcpAnalyticsFiltersLogic.actions.setPropertyFilters([TOOL_FILTER])+ }).toDispatchActions(['loadToolCalls'])++ expect(logic.values.selectedSessionToolCalls.loading).toBe(true)+ expect(logic.values.selectedSessionToolCalls.calls).toEqual([])+ expect(logic.values.selectedSessionToolCalls.hasNext).toBe(false)++ await expectLogic(logic, () => {+ if (fails) {+ rejectFiltered(new Error('Unavailable'))+ } else {+ resolveFiltered({ results: [toolCall('filtered')], has_next: false })+ }+ }).toDispatchActions([fails ? 'loadToolCallsFailure' : 'loadToolCallsSuccess'])++ expect(toolCallsMock.mock.calls[0][2]).toMatchObject({+ properties: JSON.stringify([TOOL_FILTER]),+ date_from: '2026-01-01T00:05:00Z',+ })+ expect(logic.values.selectedSessionToolCalls.loading).toBe(false)+ expect(logic.values.selectedSessionToolCalls.error).toBe(fails)+ expect(logic.values.selectedSessionToolCalls.calls.map((c) => c.event_id)).toEqual(+ fails ? [] : ['filtered']+ )+ if (consoleErrorSpy) {+ expect(consoleErrorSpy).toHaveBeenCalledTimes(1)+ consoleErrorSpy.mockRestore()+ }+ })++ it('drops a load-more page fetched under the previous filters', async () => {+ listMock.mockResolvedValue({+ results: [{ session_id: 'A', session_start: '2026-01-01T00:05:00Z' }],+ has_next: false,+ })+ toolCallsMock.mockResolvedValueOnce({ results: [toolCall('a1')], has_next: true })+ await expectLogic(logic, () => {+ logic.actions.selectSession('A')+ }).toDispatchActions(['loadToolCallsSuccess'])++ let resolveMore: (value: any) => void = () => {}+ toolCallsMock.mockImplementationOnce(() => new Promise((resolve) => (resolveMore = resolve)))+ await expectLogic(logic, () => {+ logic.actions.loadMoreToolCalls()+ }).toDispatchActions(['loadMoreToolCalls'])++ toolCallsMock.mockResolvedValue({ results: [toolCall('filtered')], has_next: false })+ await expectLogic(logic, () => {+ mcpAnalyticsFiltersLogic.actions.setPropertyFilters([TOOL_FILTER])+ }).toDispatchActions(['loadToolCallsSuccess'])++ await expectLogic(logic, () => {+ resolveMore({ results: [toolCall('a2')], has_next: false })+ }).toDispatchActions(['loadMoreToolCallsSuccess'])++ expect(logic.values.selectedSessionToolCalls.calls.map((c) => c.event_id)).toEqual(['filtered'])+ })++ it('drops a superseded session page', async () => {+ let resolveFirst: (value: any) => void = () => {}+ listMock.mockImplementationOnce(() => new Promise((resolve) => (resolveFirst = resolve)))+ await expectLogic(logic, () => {+ mcpAnalyticsFiltersLogic.actions.setPropertyFilters([TOOL_FILTER])+ }).toDispatchActions(['loadSessions'])++ listMock.mockResolvedValue({+ results: [{ session_id: 'current', session_start: '2026-01-01T00:00:00Z' }],+ has_next: false,+ })+ toolCallsMock.mockResolvedValue({ results: [], has_next: false })+ await expectLogic(logic, () => {+ mcpAnalyticsFiltersLogic.actions.setPropertyFilters([])+ }).toDispatchActions(['loadSessionsSuccess'])++ resolveFirst({ results: [{ session_id: 'superseded', session_start: '2026-01-01T00:09:00Z' }] })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.sessions.map((s) => s.session_id)).toEqual(['current'])+ })+ })})diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.tsindex 0fd1538c78f8..2a24d1cf4897 100644--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts@@ -6,12 +6,15 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { AnyPropertyFilter } from '~/types'+import {mcpAnalyticsSessionsGenerateIntent,mcpAnalyticsSessionsList,mcpAnalyticsSessionsToolCalls,} from '../generated/api'import type { MCPSessionApi, MCPSessionIntentApi, MCPToolCallApi } from '../generated/api.schemas'+import { type MCPSharedQueryFilters, mcpAnalyticsFiltersLogic, sharedFilterParams } from '../mcpAnalyticsFiltersLogic'export interface MCPSessionsFilters {search: string@@ -62,17 +65,14 @@ export function orderByParam(sorting: MCPSessionSorting | null): MCPSessionOrderreturn sorting ? `${sorting.order === -1 ? '-' : ''}${sorting.column}` : undefined}-// A session's loaded tool calls, tagged with which session they belong to and whether more pages-// exist. Carrying the session id in the value lets the panel tell "the selected session is still-// loading" from "these are a previous session's calls" with a plain comparison — no separate-// tracking reducer, and no reliance on the shared loader flag that a concurrent load-more can flip.export interface SessionToolCalls {sessionId: string | null+ filters: MCPSharedQueryFilters | nullcalls: MCPToolCallApi[]hasNext: boolean}-const EMPTY_TOOL_CALLS: SessionToolCalls = { sessionId: null, calls: [], hasNext: false }+const EMPTY_TOOL_CALLS: SessionToolCalls = { sessionId: null, filters: null, calls: [], hasNext: false }// Fetch one page of a session's tool calls, unwrapped into { calls, hasNext }. session_id comes from// untrusted event properties, so encode it — path/query delimiters must not redirect the request to@@ -82,18 +82,21 @@ async function fetchToolCallsPage(projectId: string | number,sessionId: string,sessionStart: string | null | undefined,- offset: number+ offset: number,+ sharedFilters: MCPSharedQueryFilters): Promise<{ calls: MCPToolCallApi[]; hasNext: boolean }> {const response = await mcpAnalyticsSessionsToolCalls(String(projectId), encodeURIComponent(sessionId), {date_from: sessionStart || undefined,limit: TOOL_CALLS_PAGE_SIZE,offset,+ ...sharedFilterParams(sharedFilters),})return { calls: response.results ?? [], hasNext: response.has_next ?? false }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpSessionsLogicValues {+ sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogiccurrentProjectId: number | string // teamLogicdateFilter: MCPSessionsDateFilterfilters: MCPSessionsFilters@@ -108,6 +111,7 @@ export interface mcpSessionsLogicValues {selectedSessionIntent: stringselectedSessionToolCalls: {calls: MCPToolCallApi[]+ error: booleanhasNext: booleanloading: booleanloadingMore: boolean@@ -116,11 +120,25 @@ export interface mcpSessionsLogicValues {sessionsLoading: booleansorting: MCPSessionSorting | nulltoolCalls: SessionToolCalls+ toolCallsLoadFailed: booleantoolCallsLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface mcpSessionsLogicActions {+ hydrateFilters: (+ filterTestAccountsOverride: boolean | null,+ propertyFilters: AnyPropertyFilter[]+ ) => {+ filterTestAccountsOverride: boolean | null+ propertyFilters: AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogic+ setFilterTestAccounts: (filterTestAccounts: boolean | null) => {+ filterTestAccounts: boolean | null+ } // mcpAnalyticsFiltersLogic+ setPropertyFilters: (properties: AnyPropertyFilter[]) => {+ properties: AnyPropertyFilter[]+ } // mcpAnalyticsFiltersLogicgenerateIntent: (sessionId: string) => stringgenerateIntentFailure: (error: string,@@ -214,6 +232,9 @@ export interface mcpSessionsLogicActions {toolCalls: SessionToolCallspayload?: string}+ refreshSessions: () => {+ value: true+ }selectSession: (sessionId: string | null) => {sessionId: string | null}@@ -252,9 +273,14 @@ export interface mcpSessionsLogicMeta {selectedSessionToolCalls: (toolCalls: SessionToolCalls,selectedSessionId: string | null,- toolCallsLoading: boolean+ toolCallsLoading: boolean,+ sharedQueryFilters: Required<+ Pick<import('~/queries/schema').HogQLFilters, 'filterTestAccounts' | 'properties'>+ >,+ toolCallsLoadFailed: boolean) => {calls: MCPToolCallApi[]+ error: booleanhasNext: booleanloading: booleanloadingMore: boolean@@ -272,7 +298,8 @@ export type mcpSessionsLogicType = MakeLogicType<export const mcpSessionsLogic = kea<mcpSessionsLogicType>([path(['products', 'mcp_analytics', 'frontend', 'sessions', 'mcpSessionsLogic']),connect(() => ({- values: [teamLogic, ['currentProjectId']],+ values: [teamLogic, ['currentProjectId'], mcpAnalyticsFiltersLogic, ['queryFilters as sharedQueryFilters']],+ actions: [mcpAnalyticsFiltersLogic, ['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters']],})),actions({// Declared explicitly so kea-typegen emits a no-arg signature for the loader@@ -281,18 +308,20 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([loadSessions: true,loadMoreSessions: true,loadMoreToolCalls: true,+ refreshSessions: true,setFilters: (filters: Partial<MCPSessionsFilters>) => ({ filters }),setDateFilter: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setSorting: (sorting: MCPSessionSorting | null) => ({ sorting }),setHasNext: (hasNext: boolean) => ({ hasNext }),selectSession: (sessionId: string | null) => ({ sessionId }),}),- loaders(({ values, actions }) => ({+ loaders(({ values, actions, cache }) => ({sessions: [[] as MCPSessionApi[],{// First page / reset (search or sort change). Replaces the list.loadSessions: async (_, breakpoint) => {+ cache.sessionsGeneration = (cache.sessionsGeneration ?? 0) + 1if (values.filters.search) {await breakpoint(SEARCH_DEBOUNCE_MS)}@@ -306,7 +335,12 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([date_to: values.dateFilter.dateTo || undefined,limit: SESSIONS_PAGE_SIZE,offset: 0,+ ...sharedFilterParams(values.sharedQueryFilters),})+ // A newer reset load supersedes this one. Publishing a superseded page would+ // put stale session rows on screen, and loadSessionsSuccess reads session_start+ // off them to bound the selected session's detail scan.+ breakpoint()actions.setHasNext(response.has_next ?? false)return [...(response.results ?? [])]},@@ -321,10 +355,12 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([// the list — so we both offset and merge from the snapshot, and drop this// page entirely if the query changed underneath us.const baseSessions = values.sessions+ const generation = cache.sessionsGeneration ?? 0const search = values.filters.searchconst orderBy = orderByParam(values.sorting)const dateFrom = values.dateFilter.dateFromconst dateTo = values.dateFilter.dateTo+ const sharedFilters = values.sharedQueryFiltersconst response = await mcpAnalyticsSessionsList(String(values.currentProjectId), {search: search || undefined,order_by: orderBy,@@ -332,12 +368,15 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([date_to: dateTo || undefined,limit: SESSIONS_PAGE_SIZE,offset: baseSessions.length,+ ...sharedFilterParams(sharedFilters),})if (+ generation !== cache.sessionsGeneration ||search !== values.filters.search ||orderBy !== orderByParam(values.sorting) ||dateFrom !== values.dateFilter.dateFrom ||- dateTo !== values.dateFilter.dateTo+ dateTo !== values.dateFilter.dateTo ||+ sharedFilters !== values.sharedQueryFilters) {return values.sessions}@@ -351,21 +390,28 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([{// First page for a session. Replaces the value, tagged with the session it's for.loadToolCalls: async (sessionId: string, breakpoint) => {+ cache.toolCallsGeneration = (cache.toolCallsGeneration ?? 0) + 1if (!values.currentProjectId || !sessionId) {return EMPTY_TOOL_CALLS}+ const filters = values.sharedQueryFiltersconst page = await fetchToolCallsPage(values.currentProjectId,sessionId,values.selectedSession?.session_start,- 0- )+ 0,+ filters+ ).catch((error) => {+ breakpoint()+ throw error+ })breakpoint()- return { sessionId, ...page }+ return { sessionId, filters, ...page }},// Load more: append the next page at offset = current length.loadMoreToolCalls: async () => {- const { sessionId, calls } = values.toolCalls+ const { sessionId, filters, calls } = values.toolCalls+ const generation = cache.toolCallsGeneration ?? 0if (!values.currentProjectId || !sessionId) {return values.toolCalls}@@ -373,15 +419,21 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([values.currentProjectId,sessionId,values.selectedSession?.session_start,- calls.length+ calls.length,+ filters ?? values.sharedQueryFilters)- // If the user switched sessions while this page was loading, drop it — appending- // one session's calls onto another's list would show the wrong data. The backend- // orders by (timestamp, event_id), so pages don't overlap and need no dedupe.- if (sessionId !== values.selectedSessionId) {+ // If the user switched sessions or changed the shared filters while this page+ // was loading, drop it: appending one set's calls onto another's would show the+ // wrong data. The backend orders by (timestamp, event_id), so pages that do+ // belong together don't overlap and need no dedupe.+ if (+ generation !== cache.toolCallsGeneration ||+ sessionId !== values.selectedSessionId ||+ filters !== values.sharedQueryFilters+ ) {return values.toolCalls}- return { sessionId, calls: [...calls, ...page.calls], hasNext: page.hasNext }+ return { sessionId, filters, calls: [...calls, ...page.calls], hasNext: page.hasNext }},},],@@ -394,7 +446,9 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([}// session_id comes from untrusted event properties — encode it so path/query// delimiters can't redirect this POST to another same-origin endpoint. Bound the- // intent scan by the session's start so older sessions resolve, mirroring loadToolCalls.+ // intent scan by the session's start so older sessions resolve, mirroring+ // loadToolCalls. The shared filters never move session_start, so this bound+ // still covers the whole session, which is what the persisted summary describes.return await mcpAnalyticsSessionsGenerateIntent(String(values.currentProjectId),encodeURIComponent(sessionId),@@ -405,6 +459,13 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([],})),reducers({+ toolCallsLoadFailed: [+ false,+ {+ loadToolCalls: () => false,+ loadToolCallsFailure: () => true,+ },+ ],filters: [DEFAULT_FILTERS,{@@ -494,62 +555,78 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([// the new session's header. A plain comparison — no shared loader flag a concurrent load// more could flip.selectedSessionToolCalls: [- (s) => [s.toolCalls, s.selectedSessionId, s.toolCallsLoading],+ (s) => [s.toolCalls, s.selectedSessionId, s.toolCallsLoading, s.sharedQueryFilters, s.toolCallsLoadFailed],(toolCalls: SessionToolCalls,selectedSessionId: string | null,- toolCallsLoading: boolean- ): { calls: MCPToolCallApi[]; hasNext: boolean; loading: boolean; loadingMore: boolean } => {- const isCurrent = toolCalls.sessionId === selectedSessionId+ toolCallsLoading: boolean,+ sharedQueryFilters: MCPSharedQueryFilters,+ toolCallsLoadFailed: boolean+ ): {+ calls: MCPToolCallApi[]+ hasNext: boolean+ loading: boolean+ loadingMore: boolean+ error: boolean+ } => {+ const isCurrent = toolCalls.sessionId === selectedSessionId && toolCalls.filters === sharedQueryFiltersreturn {calls: isCurrent ? toolCalls.calls : [],hasNext: isCurrent && toolCalls.hasNext,// First page still loading: the loaded value isn't for the selected session yet.- loading: selectedSessionId !== null && !isCurrent,+ loading: selectedSessionId !== null && !isCurrent && !toolCallsLoadFailed,+ error: selectedSessionId !== null && toolCallsLoadFailed,// A "Load more" append is in flight for the session already on screen.loadingMore: isCurrent && toolCallsLoading,}},],}),- listeners(({ actions, values }) => ({- // A new filter or sort changes the result set — reload from the first page.- setFilters: () => {- actions.loadSessions()- },- setDateFilter: () => {+ listeners(({ actions, values }) => {+ const reloadForSharedFilters = (): void => {actions.loadSessions()- },- setSorting: () => {- actions.loadSessions()- },- selectSession: ({ sessionId }) => {- if (sessionId) {- actions.loadToolCalls(sessionId)+ if (values.selectedSessionId) {+ actions.loadToolCalls(values.selectedSessionId)}- },- // The button just resets to its idle state on failure; surface a toast so the user- // knows the request failed (e.g. a 503 when intent generation is unavailable).- generateIntentFailure: () => {- lemonToast.error('Could not generate the session intent. Please try again.')- },- // Only fires on a reset load (not on loadMore), so appending more pages doesn't- // steal the user's selection. Auto-selects the first row when the set changes.- loadSessionsSuccess: ({ sessions }) => {- if (sessions.length === 0) {- if (values.selectedSessionId) {- actions.selectSession(null)+ }+ return {+ setFilters: () => {+ actions.loadSessions()+ },+ setDateFilter: () => {+ actions.loadSessions()+ },+ setSorting: () => {+ actions.loadSessions()+ },+ hydrateFilters: reloadForSharedFilters,+ setFilterTestAccounts: reloadForSharedFilters,+ setPropertyFilters: reloadForSharedFilters,+ refreshSessions: reloadForSharedFilters,+ selectSession: ({ sessionId }) => {+ if (sessionId) {+ actions.loadToolCalls(sessionId)}- return- }- const stillVisible = values.selectedSessionId- ? sessions.some((s) => s.session_id === values.selectedSessionId)- : false- if (!stillVisible) {- actions.selectSession(sessions[0].session_id)- }- },- })),+ },+ generateIntentFailure: () => {+ lemonToast.error('Could not generate the session intent. Please try again.')+ },+ loadSessionsSuccess: ({ sessions }) => {+ if (sessions.length === 0) {+ if (values.selectedSessionId) {+ actions.selectSession(null)+ }+ return+ }+ const stillVisible = values.selectedSessionId+ ? sessions.some((s) => s.session_id === values.selectedSessionId)+ : false+ if (!stillVisible) {+ actions.selectSession(sessions[0].session_id)+ }+ },+ }+ }),// Mirror the filters to the URL so they survive a refresh and follow across tabs (date_from /// date_to are shared with the dashboard; search is Sessions-only and also lets the dashboard// deep-link a session by pre-filling its id).