: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(web-analytics): add agent analytics dashboard (#88041)
Jordan Mryyand04fc8f2b585
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 62fbe6e10d7b..b08d7905db38 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8416,6 +8416,30 @@ snapshots:hash: v1.k794b7964.4985b07e9f0062954fa68380bc57ba975141f437e96ac938c8025540aae5d92b.Pae87mHyCuaDYoeU92NuOV9zJx0hqar1R0vunkOZUN0scenes-app-web-analytics-achievements--weekly-only-arm--light:hash: v1.k794b7964.eb042d165752cd9ff0145ee3b49f0769671244ca00e931c8ece93ec0d01a9a6f.YlQzVwE6qBKZs4cKyA1-lYowaxlhGEGt_K4jt076OSE+ scenes-app-web-analytics-agent-analytics--agent-analytics-issue-detail--dark:+ hash: v1.k794b7964.db05514590a9c1cb5c0e51f0d2f456cdd4cb846404a92c072ba2f4732fb37237.2gbpC1h70Xx2wmsbIPUIbCOBrMFhSuGAhyB9_E4uQpI+ scenes-app-web-analytics-agent-analytics--agent-analytics-issue-detail--light:+ hash: v1.k794b7964.32269b6b42d424c5474a6b177493c3f11047c45a3e235f767effde374ccb28a0.B2i2JuzGStYHeRNIZUpf5OcVEWs3RYNr3HyonMRspL8+ scenes-app-web-analytics-agent-analytics--agent-analytics-issues--dark:+ hash: v1.k794b7964.1bfde0afefcac295e73d7514c956f614a4f491f213a7721f8e234b0cf55629ca.xt_Xg1LAQ9Nz7aqK1gWhLiSVPpkjiRjt23q1cTW-49o+ scenes-app-web-analytics-agent-analytics--agent-analytics-issues--light:+ hash: v1.k794b7964.9644f789015f929cdfb726d1c0cd62f49733d05d8f0f165466b492f674073102.uEAbIDN2ujoi-RLrY6oprqOe-FgUJlKzgbfw2UbFjXk+ scenes-app-web-analytics-agent-analytics--agent-analytics-journey-detail--dark:+ hash: v1.k794b7964.a41af94b2f159564c15f466c86d0013477b5da1852171ce3517dc3a5b7945c3f.XJKSaN7lj3vUaFek_cyUycRbB7GMYDwwS1yl-ubyc5c+ scenes-app-web-analytics-agent-analytics--agent-analytics-journey-detail--light:+ hash: v1.k794b7964.7423c0f038b2414ad75227d6f51ac444598b6fbe292d6ccb96c77accb2065248.wDAKbneqR4cdPd-jUHIUkJ_KRR9Q6l-5eJvHnz5Xbow+ scenes-app-web-analytics-agent-analytics--agent-analytics-journeys--dark:+ hash: v1.k794b7964.5d435ad587a4f4192840b2651c64e267994b08e49083d9134127a1cc3851dc86.Bt5Byc4MIlv3lqOY00iXNzZmQyo0CUCb2p5QZfOVCAg+ scenes-app-web-analytics-agent-analytics--agent-analytics-journeys--light:+ hash: v1.k794b7964.3f3aca6b28942025bc67ce2f08639d9c19d310499029fbc7378fb627b4498031.d7oSuGU9H6WaDcRwhDWHMk4nIwBM0KFUKOYlvj1bANE+ scenes-app-web-analytics-agent-analytics--agent-analytics-overview--dark:+ hash: v1.k794b7964.b0b3586ff4f7f3d86097d97e944d4f7b768a7b91f0276b538ca562dee9d25696.cHhmwRrHysTx3VhAreWIs2xEQXw1K8yBuAoWcTWF6h8+ scenes-app-web-analytics-agent-analytics--agent-analytics-overview--light:+ hash: v1.k794b7964.580cc782dae93151a24cb8153e2f9f42c99e8bcc5f7fa66e51a33a87d611f99a.heo7GLCPFpJVm2ydxI-9Tdc3KA1bld8MWRkrlqtlQ8Q+ scenes-app-web-analytics-agent-analytics--agent-analytics-readiness--dark:+ hash: v1.k794b7964.cb09b07338a12112460c07ab1fcab00aee290078783f0abca3e9c8c3735af0bc.Iy7sIApgk4h6wWAHgMaXZdIVIMavLZqYqciU1CPyNyE+ scenes-app-web-analytics-agent-analytics--agent-analytics-readiness--light:+ hash: v1.k794b7964.013722ac9f9e514367b74214571d1640593aaa13749f46281ab12a9d076e9719.diwQCGsQ1KdebPGaogDBrVx0xISAm23do_CmBaJZG6Uscenes-app-web-analytics-livemetricscharts--bot-events-per-minute--dark:hash: v1.k794b7964.933ca8aa37de16e55b07b9be45e8784e14b6a9aa8d7119882340e8858c5f9afd.FWPAiDTJNN-96zh7GPc5h6lH7TSlCDPeLmG0lk3YW1Iscenes-app-web-analytics-livemetricscharts--bot-events-per-minute--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex f32e89782463..a86d6a85ac62 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -536,6 +536,7 @@ export const FEATURE_FLAGS = {WAREHOUSE_ACCOUNT_PROPERTIES_S3_SYNC: 'warehouse-account-properties-s3-sync', // owner: @arthurdedeus #team-customer-analytics, gates staged account-property sync and its run historyWAREHOUSE_PERSON_PROPERTIES: 'warehouse-person-properties', // owner: @tomowers #team-warehouse-sources, gates warehouse -> person properties (person-target custom property sources)WEB_ANALYTICS_ACHIEVEMENTS: 'web-analytics-achievements', // owner: @jordanm-posthog #team-web-analytics+ WEB_ANALYTICS_AGENT_ANALYTICS: 'web-analytics-agent-analytics', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_BACK_NAVIGATION_RESET: 'web-analytics-back-navigation-reset', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_BOT_ANALYSIS: 'web-analytics-bot-analysis', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_CONVERSION_GOAL_PREAGG: 'web-analytics-conversion-goal-preagg', // owner: @lricoy #team-web-analyticsdiff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex d5a559eb1461..2daae1a2bf19 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -762,6 +762,7 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.webAnalyticsWebVitals()]: [Scene.WebAnalytics, 'webAnalyticsWebVitals'],[urls.webAnalyticsBotAnalytics()]: [Scene.WebAnalytics, 'webAnalyticsBotAnalytics'],[urls.webAnalyticsPagePerformance()]: [Scene.WebAnalytics, 'webAnalyticsPagePerformance'],+ [urls.webAnalyticsAgents()]: [Scene.WebAnalytics, 'webAnalyticsAgents'],[urls.webAnalyticsHealth()]: [Scene.WebAnalyticsHealth, 'webAnalyticsHealth'],[urls.webAnalyticsLive()]: [Scene.WebAnalyticsLive, 'webAnalyticsLive'],[urls.webAnalyticsRecap()]: [Scene.WebAnalyticsRecap, 'webAnalyticsRecap'],diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 34b5d7c2d78f..f7b91cebabf3 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -330,6 +330,7 @@ export const urls = {: '/health/alerts',webAnalyticsBotAnalytics: (): string => '/web/bots',webAnalyticsPagePerformance: (): string => '/web/page-performance',+ webAnalyticsAgents: (): string => '/web/agents',webAnalyticsHealth: (): string => '/web/health',webAnalyticsRecap: (): string => '/web/recap',pipelineStatus: (): string => '/health/pipeline-status',diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsxindex 54f5a10749f0..4df69052f96c 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx@@ -58,6 +58,9 @@ import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollecimport { ProductIntentContext, ProductKey, QuerySchema } from '~/queries/schema/schema-general'import { InsightLogicProps, OnboardingStepKey, TeamPublicType, TeamType } from '~/types'+import { AgentAnalytics } from 'products/web_analytics/frontend/agent_analytics/AgentAnalytics'+import { AgentAnalyticsFilters } from 'products/web_analytics/frontend/agent_analytics/AgentAnalyticsFilters'+import { BotAnalyticsFilters } from './BotAnalyticsFilters'import { botAnalyticsLogic } from './botAnalyticsLogic'import { HealthStatusTab, webAnalyticsHealthLogic } from './health'@@ -647,6 +650,8 @@ const Filters = ({ tabs }: { tabs: JSX.Element }): JSX.Element | null => {return <BotAnalyticsFilters tabs={tabs} />case ProductTab.PAGE_PERFORMANCE:return <PagePerformanceFilters tabs={tabs} />+ case ProductTab.AGENTS:+ return <AgentAnalyticsFilters tabs={tabs} />default:return <WebAnalyticsFilters tabs={tabs} />}@@ -675,6 +680,10 @@ const MainContent = (): JSX.Element => {return <PagePerformance />}+ if (productTab === ProductTab.AGENTS) {+ return <AgentAnalytics />+ }+return <Tiles />}@@ -777,6 +786,27 @@ const pagePerformanceTab = (]}+const agentAnalyticsTab = (+ featureFlags: FeatureFlagsSet+): { key: ProductTab; label: string | JSX.Element; link: string }[] => {+ if (!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_AGENT_ANALYTICS]) {+ return []+ }++ return [+ {+ key: ProductTab.AGENTS,+ label: (+ <div className="flex items-center gap-1">+ Agents+ <LemonTag type="completion">Alpha</LemonTag>+ </div>+ ),+ link: urls.webAnalyticsAgents(),+ },+ ]+}+const WebAnalyticsSurveyModal = (): JSX.Element | null => {const { surveyModalPath } = useValues(webAnalyticsLogic)const { closeSurveyModal } = useActions(webAnalyticsLogic)@@ -891,6 +921,7 @@ const WebAnalyticsTabs = (): JSX.Element => {...liveTab(),...botAnalyticsTab(featureFlags),...pagePerformanceTab(featureFlags),+ ...agentAnalyticsTab(featureFlags),...healthTab(),]}sceneInsetdiff --git a/frontend/src/scenes/web-analytics/common.ts b/frontend/src/scenes/web-analytics/common.tsindex ac46a5a94c84..542f95c969cf 100644--- a/frontend/src/scenes/web-analytics/common.ts+++ b/frontend/src/scenes/web-analytics/common.ts@@ -119,6 +119,7 @@ export enum ProductTab {LIVE = 'live',BOT_ANALYTICS = 'bots',PAGE_PERFORMANCE = 'page-performance',+ AGENTS = 'agents',}export type DeviceType = 'Desktop' | 'Mobile'diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsxindex 79b65544c9a5..c35beda03927 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx@@ -3054,6 +3054,10 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([return []}+ if (productTab === ProductTab.AGENTS) {+ return []+ }+return allTiles.filter(isNotNil).filter((tile) =>@@ -3175,6 +3179,20 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([urlParams.delete('referrer')}return `/web/page-performance${urlParams.toString() ? '?' + urlParams.toString() : ''}`+ } else if (productTab === ProductTab.AGENTS) {+ urlParams.delete('filters')+ if (dateFrom !== INITIAL_DATE_FROM || dateTo !== INITIAL_DATE_TO || interval !== INITIAL_INTERVAL) {+ urlParams.set('date_from', dateFrom ?? '')+ urlParams.set('date_to', dateTo ?? '')+ urlParams.set('interval', interval ?? '')+ } else {+ urlParams.delete('date_from')+ urlParams.delete('date_to')+ urlParams.delete('interval')+ }+ urlParams.set('filter_test_accounts', shouldFilterTestAccounts.toString())+ urlParams.set('compare_filter', JSON.stringify(rawCompareFilter))+ return `/web/agents${urlParams.toString() ? '?' + urlParams.toString() : ''}`}// Make sure we're storing the raw filters only, or else we'll have issues with the domain/device type filters@@ -3338,6 +3356,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([ProductTab.LIVE,ProductTab.BOT_ANALYTICS,ProductTab.PAGE_PERFORMANCE,+ ProductTab.AGENTS,].includes(productTab)) {return@@ -3360,6 +3379,11 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([return}+ if (productTab === ProductTab.AGENTS && !values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_AGENT_ANALYTICS]) {+ router.actions.replace(urls.webAnalytics())+ return+ }+cache.hasRestoredWebUrl = true// Stamp the last-used timestamp for feature flag targeting (throttled to once per day per browser).@@ -3377,7 +3401,10 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([if (botLogic && !objectsEqual(nextFilters, botLogic.values.rawBotAnalyticsFilters)) {botLogic.actions.setBotAnalyticsFilters(nextFilters)}- } else if (!objectsEqual(nextFilters, values.rawWebAnalyticsFilters)) {+ } else if (+ productTab !== ProductTab.AGENTS &&+ !objectsEqual(nextFilters, values.rawWebAnalyticsFilters)+ ) {actions.setWebAnalyticsFilters(nextFilters)}}@@ -3552,6 +3579,9 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>(['/web/bots': (_, searchParams) => {toAction({ productTab: ProductTab.BOT_ANALYTICS }, searchParams)},+ '/web/agents': (_, searchParams) => {+ toAction({ productTab: ProductTab.AGENTS }, searchParams)+ },'/web/:productTab': toAction,}}),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0745f3b8befd..3cef0cbc3be6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4677,6 +4677,9 @@ importers:kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-forms:+ specifier: 'catalog:'+ version: 3.2.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))kea-loaders:specifier: 'catalog:'version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))diff --git a/products/web_analytics/backend/hogql_queries/agent_analytics_definitions.py b/products/web_analytics/backend/hogql_queries/agent_analytics_definitions.pyindex f4e65b6cb294..3d9650a92838 100644--- a/products/web_analytics/backend/hogql_queries/agent_analytics_definitions.py+++ b/products/web_analytics/backend/hogql_queries/agent_analytics_definitions.py@@ -71,3 +71,10 @@ def referrer_expr() -> ast.Expr:def response_status_code_expr() -> ast.Expr:return parse_expr("toInt(coalesce(nullIf(toString(properties.proxy_status_code), ''), '0'))")+++def content_gap_expr() -> ast.Expr:+ return parse_expr(+ "{status} = 404 AND NOT ({malformed})",+ placeholders={"status": response_status_code_expr(), "malformed": malformed_path_expr()},+ )diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.py b/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.pyindex 696032eee859..3a4271fe64b0 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_agent_analytics.py@@ -167,6 +167,32 @@ class TestWebAgentAnalyticsQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(rows[0]["variants"], 2)self.assertEqual(rows[1]["intent_key"], "example.com/Docs/SDK")+ def test_exact_grouping_keeps_each_requested_url_separate(self) -> None:+ _create_person(team_id=self.team.pk, distinct_ids=["assistant"], properties={})+ self._create_http_event("assistant", "/docs/sdk-2.4.1.md", 404)+ self._create_http_event("assistant", "/docs/sdk-3.0.0.html", 404)+ flush_persons_and_events()++ rows = self._rows(self._run(WebAgentAnalyticsQueryType.ISSUES, content_grouping=WebAgentContentGrouping.EXACT))++ self.assertEqual(+ {row["intent_path"] for row in rows},+ {"/docs/sdk-2.4.1.md", "/docs/sdk-3.0.0.html"},+ )++ def test_malformed_paths_are_counted_as_malformed_and_not_as_content_gaps(self) -> None:+ _create_person(team_id=self.team.pk, distinct_ids=["assistant"], properties={})+ self._create_http_event("assistant", "/docs/null", 404)+ self._create_http_event("assistant", "/docs/undefined", 404)+ self._create_http_event("assistant", "/docs/sdk-2.4.1.md", 404)+ flush_persons_and_events()++ issue_paths = {row["intent_path"] for row in self._rows(self._run(WebAgentAnalyticsQueryType.ISSUES))}+ overview = self._first_row(self._run(WebAgentAnalyticsQueryType.OVERVIEW))++ self.assertEqual(issue_paths, {"/docs/sdk"})+ self.assertEqual(overview["malformed"], 2)+def test_issue_variants_return_only_exact_paths_for_the_selected_intent(self) -> None:_create_person(team_id=self.team.pk, distinct_ids=["assistant"], properties={})self._create_http_event("assistant", "/docs/sdk-2.4.1.md", 404)diff --git a/products/web_analytics/backend/hogql_queries/web_agent_analytics.py b/products/web_analytics/backend/hogql_queries/web_agent_analytics.pyindex 1f49a9402413..00c77dfc100a 100644--- a/products/web_analytics/backend/hogql_queries/web_agent_analytics.py+++ b/products/web_analytics/backend/hogql_queries/web_agent_analytics.py@@ -29,6 +29,7 @@ from products.web_analytics.backend.hogql_queries.agent_analytics_definitions imINACTIVITY_WINDOW_SECONDS,MAX_JOURNEY_STEPS,NAVIGATION_WINDOW_SECONDS,+ content_gap_expr,malformed_path_expr,markdown_path_expr,normalized_path_expr,@@ -555,6 +556,7 @@ class WebAgentAnalyticsQueryRunner(WebAnalyticsQueryRunner[WebAgentAnalyticsQuerstatus = response_status_code_expr()is_200 = parse_expr("{status} = 200", placeholders={"status": status})is_md = markdown_path_expr()+ malformed_path = malformed_path_expr()excluded_path = static_asset_expr()included_path = ast.Not(expr=excluded_path)agent_scope = parse_expr(@@ -587,12 +589,12 @@ class WebAgentAnalyticsQueryRunner(WebAnalyticsQueryRunner[WebAgentAnalyticsQuer"periods": self._periods_expression("timestamp"),"all_properties": self.all_properties(),"status": status,- "is_404": parse_expr("{status} = 404", placeholders={"status": status}),+ "is_404": content_gap_expr(),"is_200": is_200,"is_md": is_md,"is_md_hit": parse_expr("{is_200} AND {is_md}", placeholders={"is_200": is_200, "is_md": is_md}),"is_html_hit": parse_expr("{is_200} AND NOT ({is_md})", placeholders={"is_200": is_200, "is_md": is_md}),- "malformed_path": malformed_path_expr(),+ "malformed_path": malformed_path,"excluded_path": excluded_path,"included_path": included_path,"included_request": ast.And(exprs=[agent_scope, included_path]),diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalytics.stories.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalytics.stories.tsxnew file mode 100644index 000000000000..12d91434935a--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalytics.stories.tsx@@ -0,0 +1,270 @@+import { Meta } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'+import { WebAgentAnalyticsQueryType } from '~/queries/schema/schema-general'++const overviewResponse = {+ columns: [+ 'active_clients',+ 'agent_families',+ 'server_requests',+ 'client_navigations',+ 'status_observed',+ 'client_errors',+ 'active_clients_prev',+ 'server_requests_prev',+ 'client_navigations_prev',+ 'client_errors_prev',+ 'malformed',+ 'malformed_prev',+ 'llms_txt_fetches',+ 'excluded_requests',+ 'wasted',+ 'wasted_prev',+ 'waste_pages',+ 'converted_agents',+ 'converted_agents_prev',+ ],+ results: [[128, 4, 2460, 310, 2460, 83, 104, 2210, 270, 99, 5, 3, 42, 190, 61, 74, 4, 14, 9]],+}++const issuesResponse = {+ columns: ['intent_key', 'intent_path', 'demand', 'demand_prev', 'variants', 'top_agent', 'first_seen', 'last_seen'],+ results: [+ [+ 'example.com/guides/access-tokens',+ '/guides/access-tokens',+ 48,+ 39,+ 3,+ 'Claude-User',+ '2026-08-13 10:00:00',+ '2026-08-19 12:00:00',+ ],+ [+ 'example.com/reference/file-uploads',+ '/reference/file-uploads',+ 31,+ 28,+ 2,+ 'ChatGPT-User',+ '2026-08-14 09:00:00',+ '2026-08-19 11:00:00',+ ],+ ],+}++const pagesResponse = {+ columns: ['page', 'fetches', 'md_fetches', 'html_fetches', 'paired_clients'],+ results: [+ ['example.com/guides/getting-started', 420, 280, 140, 18],+ ['example.com/reference/imports', 310, 62, 248, 7],+ ['example.com/pricing', 205, 0, 205, 0],+ ],+}++const nextHopsResponse = {+ columns: ['next_path', 'requests', 'not_found'],+ results: [+ ['/guides/getting-started', 74, 0],+ ['/reference/imports', 41, 0],+ ['/guides/access-tokens', 26, 26],+ ],+}++const demandResponse = {+ columns: ['page', 'host', 'path', 'demand'],+ results: [+ ['example.com/guides/getting-started', 'example.com', '/guides/getting-started', 420],+ ['example.com/reference/imports', 'example.com', '/reference/imports', 310],+ ['example.com/pricing', 'example.com', '/pricing', 205],+ ],+}++const variantsResponse = {+ columns: ['variant', 'demand', 'top_agent', 'first_seen'],+ results: [+ ['/guides/access-tokens', 29, 'Claude User', '2026-08-13 10:00:00'],+ ['/guides/access-tokens.md', 14, 'ChatGPT', '2026-08-15 11:00:00'],+ ['/guides/access-tokens-v2', 5, 'Claude User', '2026-08-18 08:00:00'],+ ],+}++const requestAnatomyResponse = {+ columns: ['agent', 'requests', 'requested_markdown', 'retry_pairs', 'errors'],+ results: [+ ['Claude User', 120, 72, 18, 4],+ ['ChatGPT User', 100, 35, 7, 8],+ ],+}++const journeySummaryResponse = {+ columns: ['total_journeys', 'median_pages', 'median_requests', 'median_duration_seconds', 'journeys_with_errors'],+ results: [[84, 3, 5, 72, 19]],+}++interface MockQueryResponse {+ columns: string[]+ results: unknown[][]+ hasMore?: boolean+}++const paginatedResponse = (response: MockQueryResponse, offset?: number): MockQueryResponse =>+ offset ? { ...response, results: response.results.slice(-1), hasMore: false } : { ...response, hasMore: true }++const journeysResponse = {+ columns: ['journey_key', 'started', 'agent', 'host', 'pages', 'requests', 'duration_seconds', 'errors'],+ results: [+ ['journey-example', '2026-08-19 14:02:01', 'Claude User', 'example.com', 4, 7, 11, 2],+ ['journey-inferred', '2026-08-19 13:44:12', 'ChatGPT User', 'example.com', 3, 4, 38, 0],+ ],+ hasMore: true,+}++const journeysNextPageResponse = {+ ...journeysResponse,+ results: [['journey-older', '2026-08-18 09:20:00', 'Claude User', 'docs.example.com', 2, 3, 19, 0]],+ hasMore: false,+}++const journeyDetailResponse = {+ columns: ['timestamp', 'path', 'status', 'format', 'referrer', 'transition'],+ results: [+ ['2026-08-19 14:02:01', '/llms.txt', 200, 'html', '', 'start'],+ ['2026-08-19 14:02:04', '/guides/getting-started', 200, 'html', 'https://example.com/llms.txt', 'confirmed'],+ ['2026-08-19 14:02:05', '/guides/getting-started.md', 200, 'markdown', '', 'sequential'],+ ['2026-08-19 14:02:09', '/guides/access-tokens', 404, 'html', '', 'sequential'],+ ['2026-08-19 14:02:09', '/guides/access-tokens.md', 404, 'markdown', '', 'parallel'],+ ],+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Web Analytics/Agent analytics',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-08-19',+ pageUrl: urls.webAnalyticsAgents(),+ featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_AGENT_ANALYTICS, FEATURE_FLAGS.WEB_ANALYTICS_FILTERS_V2],+ testOptions: {+ includeNavigationInSnapshot: true,+ waitForLoadersToDisappear: true,+ },+ },+ decorators: [+ mswDecorator({+ get: {+ '/stats': () => [200, { users_on_product: 128 }],+ '/api/projects/:team_id/event_definitions': () => [200, { count: 5 }],+ '/api/projects/:team_id/health_issues/': () => [200, { results: [] }],+ '/api/environments/:team_id/health_issues/summary/': () => [200, {}],+ },+ post: {+ '/api/projects/:team_id/web_analytics/llms_txt/': () => [+ 200,+ {+ content: [+ '# Example documentation',+ '- [Getting started](https://example.com/guides/getting-started)',+ '- [Pricing](https://example.com/pricing)',+ ].join('\n'),+ url: 'https://example.com/llms.txt',+ },+ ],+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ interface MockQuerySource {+ kind?: string+ queryType?: WebAgentAnalyticsQueryType+ offset?: number+ }+ const requestBody = (await request.json()) as {+ query?: MockQuerySource & { source?: MockQuerySource }+ }+ const source = requestBody.query?.source ?? requestBody.query++ if (source?.kind === 'DatabaseSchemaQuery') {+ return [200, { tables: {}, joins: [] }]+ }+ switch (source?.queryType) {+ case WebAgentAnalyticsQueryType.Overview:+ return [200, overviewResponse]+ case WebAgentAnalyticsQueryType.Issues:+ return [200, paginatedResponse(issuesResponse, source.offset)]+ case WebAgentAnalyticsQueryType.PageRequests:+ return [200, pagesResponse]+ case WebAgentAnalyticsQueryType.Transitions:+ return [200, paginatedResponse(nextHopsResponse, source.offset)]+ case WebAgentAnalyticsQueryType.Demand:+ return [200, paginatedResponse(demandResponse, source.offset)]+ case WebAgentAnalyticsQueryType.IssueVariants:+ return [200, paginatedResponse(variantsResponse, source.offset)]+ case WebAgentAnalyticsQueryType.RequestAnatomy:+ return [200, paginatedResponse(requestAnatomyResponse, source.offset)]+ case WebAgentAnalyticsQueryType.JourneySummary:+ return [200, journeySummaryResponse]+ case WebAgentAnalyticsQueryType.Journeys:+ return [200, source.offset ? journeysNextPageResponse : journeysResponse]+ case WebAgentAnalyticsQueryType.JourneyDetail:+ return [200, journeyDetailResponse]+ }+ return [200, { columns: [], results: [] }]+ },+ },+ }),+ ],+}++export default meta++export function AgentAnalyticsOverview(): JSX.Element {+ return <App />+}++AgentAnalyticsOverview.parameters = {+ pageUrl: `${urls.webAnalyticsAgents()}?conversionGoal.customEventName=completed_signup`,+}++export function AgentAnalyticsReadiness(): JSX.Element {+ return <App />+}++AgentAnalyticsReadiness.parameters = {+ pageUrl: `${urls.webAnalyticsAgents()}?view=readiness&conversionGoal.customEventName=completed_signup`,+}++export function AgentAnalyticsJourneys(): JSX.Element {+ return <App />+}++AgentAnalyticsJourneys.parameters = {+ pageUrl: `${urls.webAnalyticsAgents()}?view=journeys`,+}++export function AgentAnalyticsIssues(): JSX.Element {+ return <App />+}++AgentAnalyticsIssues.parameters = {+ pageUrl: `${urls.webAnalyticsAgents()}?view=issues`,+}++export function AgentAnalyticsJourneyDetail(): JSX.Element {+ return <App />+}++AgentAnalyticsJourneyDetail.parameters = {+ pageUrl: `${urls.webAnalyticsAgents()}?view=journeys&journey=journey-example`,+}++export function AgentAnalyticsIssueDetail(): JSX.Element {+ return <App />+}++AgentAnalyticsIssueDetail.parameters = {+ pageUrl: `${urls.webAnalyticsAgents()}?view=issues&issue=${encodeURIComponent('example.com/guides/access-tokens')}`,+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalytics.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalytics.tsxnew file mode 100644index 000000000000..c5dd39acb3c8--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalytics.tsx@@ -0,0 +1,45 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { LemonBanner, LemonSegmentedButton } from '@posthog/lemon-ui'++import { AgentAnalyticsIssues } from './AgentAnalyticsIssues'+import { AgentAnalyticsJourneys } from './AgentAnalyticsJourneys'+import { AgentView, agentAnalyticsLogic } from './agentAnalyticsLogic'+import { AgentAnalyticsOverview } from './AgentAnalyticsOverview'+import { AgentAnalyticsReadiness } from './AgentAnalyticsReadiness'++const VIEW_OPTIONS: { value: AgentView; label: string }[] = [+ { value: 'overview', label: 'Overview' },+ { value: 'journeys', label: 'Journeys' },+ { value: 'issues', label: 'Issues' },+ { value: 'readiness', label: 'Readiness' },+]++export const AgentAnalytics = (): JSX.Element => {+ useMountedLogic(agentAnalyticsLogic)+ const { view } = useValues(agentAnalyticsLogic)+ const { setView } = useActions(agentAnalyticsLogic)++ return (+ <div className="flex flex-col gap-4">+ <LemonBanner+ type="info"+ dismissKey="web-analytics-agent-analytics-feedback-banner"+ action={{ children: 'Send feedback', id: 'web-analytics-agent-analytics-feedback-button' }}+ >+ Track what AI agents read, where requests fail, and which fixes have the most demand. Connect+ server-side HTTP logs for complete coverage.+ </LemonBanner>+ <LemonSegmentedButton value={view} onChange={setView} options={VIEW_OPTIONS} size="small" />+ {view === 'overview' ? (+ <AgentAnalyticsOverview />+ ) : view === 'journeys' ? (+ <AgentAnalyticsJourneys />+ ) : view === 'issues' ? (+ <AgentAnalyticsIssues />+ ) : (+ <AgentAnalyticsReadiness />+ )}+ </div>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalyticsFilters.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsFilters.tsxnew file mode 100644index 000000000000..57742497060e--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsFilters.tsx@@ -0,0 +1,66 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'+import { LemonButton, LemonSegmentedButton, Spinner } from '@posthog/lemon-ui'++import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'+import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { FilterBar } from 'lib/components/FilterBar'+import { webAnalyticsDateMapping } from 'scenes/web-analytics/constants'+import { WebAnalyticsDomainSelector } from 'scenes/web-analytics/WebAnalyticsFilters'+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'+import { WebConversionGoal } from 'scenes/web-analytics/WebConversionGoal'+import { WebPropertyFilters } from 'scenes/web-analytics/WebPropertyFilters'++import { AgentScope, agentAnalyticsLogic } from './agentAnalyticsLogic'++const SCOPE_OPTIONS: { value: AgentScope; label: string }[] = [+ { value: 'live', label: 'Agents' },+ { value: 'all', label: 'Agents and crawlers' },+]++export const AgentAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Element => {+ const {+ dateFilter: { dateTo, dateFrom },+ compareFilter,+ conversionGoal,+ } = useValues(webAnalyticsLogic)+ const { setDates, setCompareFilter, setConversionGoal } = useActions(webAnalyticsLogic)+ const { scope, anyLoading } = useValues(agentAnalyticsLogic)+ const { setScope, refresh } = useActions(agentAnalyticsLogic)++ return (+ <FilterBar+ top={tabs}+ left={+ <>+ <LemonButton+ type="secondary"+ size="small"+ onClick={refresh}+ icon={anyLoading ? <Spinner textColored /> : <IconRefresh />}+ disabledReason={anyLoading ? 'Loading' : undefined}+ aria-label="Reload agent analytics"+ data-attr="agent-analytics-reload"+ />+ <DateFilter+ dateOptions={webAnalyticsDateMapping}+ allowTimePrecision+ dateFrom={dateFrom}+ dateTo={dateTo}+ onChange={setDates}+ />+ <CompareFilter compareFilter={compareFilter} updateCompareFilter={setCompareFilter} />+ <WebConversionGoal value={conversionGoal} onChange={setConversionGoal} />+ </>+ }+ right={+ <>+ <WebAnalyticsDomainSelector />+ <WebPropertyFilters />+ <LemonSegmentedButton size="small" value={scope} onChange={setScope} options={SCOPE_OPTIONS} />+ </>+ }+ />+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalyticsIssues.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsIssues.tsxnew file mode 100644index 000000000000..5eda5f5d3389--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsIssues.tsx@@ -0,0 +1,93 @@+import { useActions, useValues } from 'kea'++import { LemonTable, LemonTableColumns } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'++import { WebAgentAnalyticsQueryType } from '~/queries/schema/schema-general'++import { AgentIssue, agentAnalyticsLogic } from './agentAnalyticsLogic'+import { AgentAnalyticsSection } from './AgentAnalyticsSection'+import { AgentIssueChangeIndicator } from './AgentIssueChangeIndicator'+import { AgentIssueDetail } from './AgentIssueDetail'+import { AgentIssueTypeTag } from './AgentIssueTypeTag'+import { AgentQueryError } from './AgentQueryError'++const issueColumns: LemonTableColumns<AgentIssue> = [+ {+ title: 'Issue',+ key: 'issue',+ render: (_, issue) => (+ <div className="flex flex-col gap-1 py-1">+ <div className="flex items-center gap-2 min-w-0">+ <AgentIssueTypeTag type={issue.type} />+ <span className="truncate font-semibold">{issue.title}</span>+ </div>+ <span className="text-xs text-secondary">{issue.subtitle}</span>+ </div>+ ),+ },+ {+ title: 'Requests',+ key: 'demand',+ align: 'right',+ sorter: (a, b) => a.demand - b.demand,+ render: (_, issue) => (+ <div className="flex items-center justify-end gap-3">+ <div className="flex flex-col items-end">+ <span className="font-medium whitespace-nowrap">{humanFriendlyLargeNumber(issue.demand)}</span>+ <AgentIssueChangeIndicator changePct={issue.changePct} />+ </div>+ </div>+ ),+ },+ {+ title: 'Top agent',+ key: 'agent',+ render: (_, issue) => issue.topAgent ?? <span className="text-secondary">-</span>,+ },+ {+ title: 'First seen in range',+ key: 'first_seen',+ render: (_, issue) =>+ issue.firstSeen ? <TZLabel time={issue.firstSeen} /> : <span className="text-secondary">-</span>,+ },+]++export const AgentAnalyticsIssues = (): JSX.Element => {+ const { issues, contentGapIssuesLoading, contentGapIssuesError, selectedIssueKey, resultPaginations } =+ useValues(agentAnalyticsLogic)+ const { setSelectedIssueKey, loadIssues } = useActions(agentAnalyticsLogic)++ return (+ <AgentAnalyticsSection+ title="Issues"+ description="Missing pages, repeated format requests, and malformed paths ranked by affected agent requests."+ >+ <AgentQueryError+ error={contentGapIssuesError}+ subject="agent issues"+ onRetry={loadIssues}+ loading={contentGapIssuesLoading}+ >+ <LemonTable+ columns={issueColumns}+ dataSource={issues}+ expandable={{+ isRowExpanded: (issue) => issue.key === selectedIssueKey,+ onRowExpand: (issue) => setSelectedIssueKey(issue.key),+ onRowCollapse: () => setSelectedIssueKey(null),+ expandedRowRender: (issue) => <AgentIssueDetail issue={issue} />,+ }}+ loading={contentGapIssuesLoading}+ defaultSorting={{ columnKey: 'demand', order: -1 }}+ emptyState="No agent issues were found in this range. Widen the date range or include AI crawlers."+ rowKey="key"+ nouns={['issue', 'issues']}+ pagination={resultPaginations[WebAgentAnalyticsQueryType.Issues]}+ />+ </AgentQueryError>+ </AgentAnalyticsSection>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalyticsJourneys.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsJourneys.tsxnew file mode 100644index 000000000000..324853b55006--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsJourneys.tsx@@ -0,0 +1,248 @@+import { useActions, useValues } from 'kea'++import { IconInfo } from '@posthog/icons'+import { LemonButton, LemonCard, LemonSkeleton, LemonTable, LemonTableColumns, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { humanFriendlyLargeNumber, percentage } from 'lib/utils/numbers'+import { tryDecodeURIComponent } from 'lib/utils/url'++import { WebAgentAnalyticsQueryType } from '~/queries/schema/schema-general'++import { EMPTY_JOURNEY_SUMMARY, JourneyRow, JourneySummary, NextHop, agentAnalyticsLogic } from './agentAnalyticsLogic'+import { AgentAnalyticsSection } from './AgentAnalyticsSection'+import { AgentJourneyDetail } from './AgentJourneyDetail'+import { AgentQueryError } from './AgentQueryError'++interface SummaryStat {+ key: string+ label: string+ value: string+ description: string+}++const summaryStats = (summary: JourneySummary): SummaryStat[] => [+ {+ key: 'total',+ label: 'Journeys',+ value: humanFriendlyLargeNumber(summary.totalJourneys),+ description: 'Request sequences from one client and agent on one domain in this range.',+ },+ {+ key: 'median-pages',+ label: 'Median pages',+ value: humanFriendlyLargeNumber(summary.medianPages),+ description: 'Distinct pages requested in a typical journey.',+ },+ {+ key: 'median-duration',+ label: 'Median duration',+ value: summary.medianDurationSeconds > 0 ? humanFriendlyDuration(summary.medianDurationSeconds) : '0s',+ description: 'Time between the first and last request of a typical journey.',+ },+ {+ key: 'with-errors',+ label: 'Journeys with errors',+ value: humanFriendlyLargeNumber(summary.journeysWithErrors),+ description: 'Journeys that hit at least one 4xx or 5xx response.',+ },+]++const SummaryStatCard = ({ stat, loading }: { stat: SummaryStat; loading: boolean }): JSX.Element => (+ <LemonCard className="flex min-h-24 flex-col justify-between gap-2" hoverEffect={false}>+ <div className="flex items-center gap-1 text-sm font-medium text-secondary">+ <span>{stat.label}</span>+ <Tooltip title={stat.description}>+ <IconInfo className="text-tertiary" />+ </Tooltip>+ </div>+ {loading ? (+ <LemonSkeleton className="h-8 w-16" />+ ) : (+ <span className="text-2xl font-semibold tabular-nums">{stat.value}</span>+ )}+ </LemonCard>+)++const journeyColumns = (openJourney: (journey: JourneyRow) => void): LemonTableColumns<JourneyRow> => [+ {+ title: 'Started',+ key: 'started',+ render: (_, journey) =>+ journey.started ? <TZLabel time={journey.started} /> : <span className="text-secondary">-</span>,+ },+ {+ title: 'Agent',+ key: 'agent',+ render: (_, journey) => <span className="font-medium">{journey.agent}</span>,+ },+ {+ title: 'Domain',+ key: 'host',+ render: (_, journey) => journey.host || <span className="text-secondary">Unknown</span>,+ },+ {+ title: 'Pages',+ key: 'pages',+ align: 'right',+ render: (_, journey) => humanFriendlyLargeNumber(journey.pages),+ },+ {+ title: 'Requests',+ key: 'requests',+ align: 'right',+ render: (_, journey) => humanFriendlyLargeNumber(journey.requests),+ },+ {+ title: 'Duration',+ key: 'duration',+ align: 'right',+ render: (_, journey) => (journey.durationSeconds > 0 ? humanFriendlyDuration(journey.durationSeconds) : '0s'),+ },+ {+ title: 'Errors',+ key: 'errors',+ align: 'right',+ render: (_, journey) =>+ journey.errors > 0 ? (+ <span className="font-semibold text-danger">{humanFriendlyLargeNumber(journey.errors)}</span>+ ) : (+ <span className="text-secondary">0</span>+ ),+ },+ {+ title: '',+ key: 'actions',+ align: 'right',+ render: (_, journey) => (+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={() => openJourney(journey)}+ data-attr="agent-analytics-view-journey"+ >+ View timeline+ </LemonButton>+ ),+ },+]++const nextHopColumns = (total: number): LemonTableColumns<NextHop> => [+ {+ title: 'Next page',+ key: 'path',+ render: (_, hop) => (+ <span className="flex items-center gap-2 truncate">+ <span className="font-medium truncate">{tryDecodeURIComponent(hop.path)}</span>+ {hop.notFound > 0 ? <span className="text-danger text-xs font-semibold">404</span> : null}+ </span>+ ),+ },+ {+ title: 'Requests',+ key: 'requests',+ align: 'right',+ render: (_, hop) => humanFriendlyLargeNumber(hop.requests),+ },+ {+ title: 'Share on page',+ key: 'share',+ align: 'right',+ render: (_, hop) => (total > 0 ? percentage(hop.requests / total, 0) : '-'),+ },+]++export const AgentAnalyticsJourneys = (): JSX.Element => {+ const {+ journeySummary,+ journeySummaryError,+ journeySummaryLoading,+ journeys,+ journeysLoading,+ journeysError,+ resultPaginations,+ nextHops,+ nextHopsLoading,+ nextHopsError,+ } = useValues(agentAnalyticsLogic)+ const { setSelectedJourneyKey, loadJourneySummary, loadJourneys, loadNextHops } = useActions(agentAnalyticsLogic)++ const openJourney = (journey: JourneyRow): void => setSelectedJourneyKey(journey.journeyKey)+ const nextHopTotal = nextHops.reduce((sum, hop) => sum + hop.requests, 0)++ return (+ <div className="flex flex-col gap-6">+ <AgentAnalyticsSection+ title="Journeys"+ description="A journey is a run of requests from one client and agent on one domain. Journeys are inferred: a new one starts after 30 minutes of inactivity. A shared agent IP can mix several clients, so this does not represent a conversation."+ >+ <AgentQueryError+ error={journeySummaryError}+ subject="journey summaries"+ onRetry={loadJourneySummary}+ loading={journeySummaryLoading}+ >+ <div className="@container">+ <div className="grid grid-cols-2 gap-3 @md:grid-cols-3 @3xl:grid-cols-5">+ {summaryStats(journeySummary ?? EMPTY_JOURNEY_SUMMARY).map((stat) => (+ <SummaryStatCard key={stat.key} stat={stat} loading={!journeySummary} />+ ))}+ </div>+ </div>+ </AgentQueryError>+ </AgentAnalyticsSection>++ <AgentAnalyticsSection+ title="Recent journeys"+ description="The most recent request sequences, newest first. Open one to see its timeline and how each step connects."+ >+ <AgentQueryError+ error={journeysError}+ subject="journeys"+ onRetry={loadJourneys}+ loading={journeysLoading}+ >+ <LemonTable+ columns={journeyColumns(openJourney)}+ dataSource={journeys}+ loading={journeysLoading}+ size="small"+ nouns={['journey', 'journeys']}+ pagination={resultPaginations[WebAgentAnalyticsQueryType.Journeys]}+ emptyState="No agent journeys were found in this range. Connect server-side HTTP logs, widen the date range, or include AI crawlers."+ />+ </AgentQueryError>+ </AgentAnalyticsSection>++ <AgentAnalyticsSection+ title="Requests after llms.txt"+ description="The first different page requested by the same agent client within 30 minutes of fetching llms.txt."+ >+ <AgentQueryError+ error={nextHopsError}+ subject="requests after llms.txt"+ onRetry={loadNextHops}+ loading={nextHopsLoading}+ >+ <LemonTable+ columns={nextHopColumns(nextHopTotal)}+ dataSource={nextHops}+ loading={nextHopsLoading}+ size="small"+ nouns={['page', 'pages']}+ pagination={resultPaginations[WebAgentAnalyticsQueryType.Transitions]}+ emptyState={+ <span className="text-secondary">+ No requests after <Link to="https://llmstxt.org/">llms.txt</Link> were captured. Connect+ server-side HTTP logs to include agents that do not run JavaScript.+ </span>+ }+ />+ </AgentQueryError>+ </AgentAnalyticsSection>++ <AgentJourneyDetail />+ </div>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalyticsOverview.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsOverview.tsxnew file mode 100644index 000000000000..2f8da3b1a390--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsOverview.tsx@@ -0,0 +1,381 @@+import { useActions, useValues } from 'kea'++import { IconInfo } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonCard,+ LemonSkeleton,+ LemonTag,+ LemonTable,+ LemonTableColumns,+ Spinner,+ Tooltip,+} from '@posthog/lemon-ui'++import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { humanFriendlyLargeNumber, percentage } from 'lib/utils/numbers'+import { tryDecodeURIComponent } from 'lib/utils/url'++import {+ AgentIssue,+ EMPTY_JOURNEY_SUMMARY,+ JourneySummary,+ OverviewStats,+ PageRead,+ agentAnalyticsLogic,+ changePct,+} from './agentAnalyticsLogic'+import { AgentAnalyticsSection } from './AgentAnalyticsSection'+import { AgentIssueChangeIndicator, ChangeSentiment } from './AgentIssueChangeIndicator'+import { AgentIssueTypeTag } from './AgentIssueTypeTag'+import { AgentQueryError } from './AgentQueryError'++interface OverviewMetric {+ key: string+ label: string+ description: string+ value: number | null+ previous: number | null+ sentiment: ChangeSentiment+}++const overviewMetrics = (overview: OverviewStats | null, hasConversionGoal: boolean): OverviewMetric[] => [+ {+ key: 'active-clients',+ label: 'Active agent clients',+ description: 'Distinct agent client identifiers observed in server requests or client navigations.',+ value: overview?.activeClients ?? 0,+ previous: overview?.activeClientsPrev ?? null,+ sentiment: 'neutral',+ },+ {+ key: 'agent-families',+ label: 'Agent families',+ description: 'Distinct classified agent names observed in this period.',+ value: overview?.agentFamilies ?? 0,+ previous: null,+ sentiment: 'neutral',+ },+ {+ key: 'server-requests',+ label: 'Server requests',+ description: 'Agent HTTP requests captured by server-side HTTP logs.',+ value: overview?.serverRequests ?? 0,+ previous: overview?.serverRequestsPrev ?? null,+ sentiment: 'neutral',+ },+ {+ key: 'client-navigations',+ label: 'Client navigations',+ description: 'Agent pageviews and screen events captured by client-side tracking.',+ value: overview?.clientNavigations ?? 0,+ previous: overview?.clientNavigationsPrev ?? null,+ sentiment: 'neutral',+ },+ {+ key: '4xx-responses',+ label: 'Client errors',+ description: 'Agent requests that received a 4xx response.',+ value: overview?.clientErrors ?? 0,+ previous: overview?.clientErrorsPrev ?? null,+ sentiment: 'lower-is-better',+ },+ {+ key: 'wasted-fetches',+ label: 'Repeated fetches',+ description: 'Markdown requests made within 30 minutes of an HTML request for the same page and client.',+ value: overview?.wasted ?? 0,+ previous: overview?.wastedPrev ?? null,+ sentiment: 'lower-is-better',+ },+ {+ key: 'converted-clients',+ label: 'Converted agent clients',+ description: 'Agent clients followed by the selected conversion goal within 24 hours.',+ value: hasConversionGoal ? (overview?.convertedClients ?? 0) : null,+ previous: hasConversionGoal ? (overview?.convertedClientsPrev ?? null) : null,+ sentiment: 'higher-is-better',+ },+]++const OverviewMetricCard = ({ metric, loading }: { metric: OverviewMetric; loading: boolean }): JSX.Element => (+ <LemonCard+ className="flex min-h-24 flex-col justify-between gap-3"+ hoverEffect={false}+ data-attr={`agent-analytics-metric-${metric.key}`}+ >+ <div className="flex items-center gap-1 text-sm font-medium text-secondary">+ <span>{metric.label}</span>+ <Tooltip title={metric.description}>+ <IconInfo className="text-tertiary" />+ </Tooltip>+ </div>+ {loading ? (+ <LemonSkeleton className="h-8 w-20" />+ ) : metric.value === null ? (+ <>+ <span className="text-lg font-semibold text-secondary">Not set</span>+ <span className="text-xs text-tertiary">Select a conversion goal</span>+ </>+ ) : (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-2xl font-semibold tabular-nums">{humanFriendlyLargeNumber(metric.value)}</span>+ <AgentIssueChangeIndicator+ changePct={changePct(metric.value, metric.previous)}+ sentiment={metric.sentiment}+ />+ </div>+ )}+ </LemonCard>+)++const markdownShare = (page: PageRead): number => {+ const total = page.mdFetches + page.htmlFetches+ return total > 0 ? page.mdFetches / total : 0+}++const whatAgentsReadColumns: LemonTableColumns<PageRead> = [+ {+ title: 'Page',+ key: 'page',+ render: (_, page) => <span className="font-medium truncate">{tryDecodeURIComponent(page.page)}</span>,+ },+ {+ title: 'Requests',+ key: 'fetches',+ align: 'right',+ render: (_, page) => humanFriendlyLargeNumber(page.fetches),+ },+ {+ title: 'Response formats',+ key: 'md',+ render: (_, page) => {+ const share = markdownShare(page)+ return (+ <div className="flex min-w-36 flex-col gap-1">+ <div className="flex items-center gap-2">+ <LemonProgress className="w-20" percent={share * 100} />+ <span className="text-xs font-medium tabular-nums">{percentage(share, 0)} markdown</span>+ </div>+ <span className="text-xs text-tertiary">+ {humanFriendlyLargeNumber(page.mdFetches)} markdown ·{' '}+ {humanFriendlyLargeNumber(page.htmlFetches)} HTML+ </span>+ </div>+ )+ },+ },+ {+ title: 'Repeated requests',+ key: 'waste',+ align: 'right',+ render: (_, page) =>+ page.pairedClients > 0 ? (+ <Tooltip+ title={`${humanFriendlyLargeNumber(page.pairedClients)} agent ${page.pairedClients === 1 ? 'client fetched' : 'clients fetched'} both the HTML and markdown versions of this page.`}+ >+ <LemonTag type="warning" size="small">+ {humanFriendlyLargeNumber(page.pairedClients)} {page.pairedClients === 1 ? 'client' : 'clients'}+ </LemonTag>+ </Tooltip>+ ) : (+ <span className="text-secondary">-</span>+ ),+ },+]++const journeySummaryHighlights = (summary: JourneySummary): { key: string; label: string; value: string }[] => [+ { key: 'total', label: 'Journeys', value: humanFriendlyLargeNumber(summary.totalJourneys) },+ { key: 'median-pages', label: 'Median pages', value: humanFriendlyLargeNumber(summary.medianPages) },+ {+ key: 'median-duration',+ label: 'Median duration',+ value: summary.medianDurationSeconds > 0 ? humanFriendlyDuration(summary.medianDurationSeconds) : '0s',+ },+ { key: 'with-errors', label: 'With errors', value: humanFriendlyLargeNumber(summary.journeysWithErrors) },+]++export const AgentAnalyticsOverview = (): JSX.Element => {+ const {+ overview,+ overviewLoading,+ overviewError,+ conversionGoal,+ topIssues,+ contentGapIssuesLoading,+ contentGapIssuesError,+ whatAgentsRead,+ whatAgentsReadLoading,+ whatAgentsReadError,+ journeySummary,+ journeySummaryLoading,+ journeySummaryError,+ } = useValues(agentAnalyticsLogic)+ const { setView, setSelectedIssueKey, loadOverview, loadIssues, loadWhatAgentsRead, loadJourneySummary } =+ useActions(agentAnalyticsLogic)++ const openIssue = (issue: AgentIssue): void => {+ setView('issues')+ setSelectedIssueKey(issue.key)+ }++ return (+ <div className="flex flex-col gap-6">+ <AgentAnalyticsSection+ title="Key metrics"+ description="Agent activity and request quality for the selected period."+ right={+ overview && overview.excludedRequests > 0 ? (+ <Tooltip title="Static asset requests, like images, stylesheets, and fonts, are excluded from content analysis.">+ <LemonTag type="muted" icon={<IconInfo />}>+ {humanFriendlyLargeNumber(overview.excludedRequests)} static asset requests excluded+ </LemonTag>+ </Tooltip>+ ) : undefined+ }+ >+ <AgentQueryError+ error={overviewError}+ subject="the overview"+ onRetry={loadOverview}+ loading={overviewLoading}+ >+ <div className="@container">+ <div className="grid grid-cols-1 gap-3 @md:grid-cols-2 @3xl:grid-cols-4">+ {overviewMetrics(overview, conversionGoal !== null).map((metric) => (+ <OverviewMetricCard key={metric.key} metric={metric} loading={!overview} />+ ))}+ </div>+ </div>+ </AgentQueryError>+ {overview && overview.serverRequests > 0 && overview.statusObserved === 0 ? (+ <LemonBanner type="info">+ Server requests were captured without response status codes. Client error, missing page, and+ successful page reports need the <code>proxy_status_code</code> property.+ </LemonBanner>+ ) : overview && overview.serverRequests === 0 && overview.clientNavigations > 0 ? (+ <LemonBanner type="info">+ Client navigations are available, but server requests are not. Connect server-side HTTP logs to+ analyze response status, content formats, and llms.txt requests without double-counting+ navigations.+ </LemonBanner>+ ) : null}+ </AgentAnalyticsSection>++ <AgentAnalyticsSection+ title="Needs attention"+ description="Issues ranked by the number of agent requests they affect."+ right={+ <LemonButton size="small" type="secondary" onClick={() => setView('issues')}>+ View all issues+ </LemonButton>+ }+ >+ <AgentQueryError+ error={contentGapIssuesError}+ subject="agent issues"+ onRetry={loadIssues}+ loading={contentGapIssuesLoading}+ >+ {contentGapIssuesLoading && topIssues.length === 0 ? (+ <div className="flex min-h-20 items-center justify-center">+ <Spinner />+ </div>+ ) : topIssues.length === 0 ? (+ <LemonCard hoverEffect={false} className="text-secondary">+ No agent issues were found in this range. Widen the date range or include AI crawlers.+ </LemonCard>+ ) : (+ <LemonCard hoverEffect={false} className="divide-y divide-primary overflow-hidden p-0">+ {topIssues.map((issue) => (+ <LemonButton+ key={issue.key}+ fullWidth+ onClick={() => openIssue(issue)}+ size="small"+ type="tertiary"+ className="rounded-none px-3 py-2"+ data-attr="agent-analytics-open-issue"+ >+ <span className="flex w-full min-w-0 flex-wrap items-center justify-between gap-3 text-left">+ <span className="flex min-w-0 items-start gap-2">+ <AgentIssueTypeTag type={issue.type} />+ <span className="flex min-w-0 flex-col gap-0.5">+ <span className="truncate font-medium">{issue.title}</span>+ <span className="truncate text-xs text-secondary">+ {issue.subtitle}+ </span>+ </span>+ </span>+ <span className="flex items-center gap-2 shrink-0 text-secondary">+ <span>{humanFriendlyLargeNumber(issue.demand)}</span>+ <AgentIssueChangeIndicator changePct={issue.changePct} />+ </span>+ </span>+ </LemonButton>+ ))}+ </LemonCard>+ )}+ </AgentQueryError>+ </AgentAnalyticsSection>++ <AgentAnalyticsSection+ title="What agents read"+ description="The five most requested pages from server-side agent traffic."+ >+ <AgentQueryError+ error={whatAgentsReadError}+ subject="page requests"+ onRetry={loadWhatAgentsRead}+ loading={whatAgentsReadLoading}+ >+ <LemonTable+ columns={whatAgentsReadColumns}+ dataSource={whatAgentsRead}+ loading={whatAgentsReadLoading}+ size="small"+ emptyState="No agent page requests were found in this range. Widen the date range or include AI crawlers."+ />+ </AgentQueryError>+ </AgentAnalyticsSection>++ <AgentAnalyticsSection+ title="Agent journeys"+ description="How agents move through the site across a sequence of requests."+ right={+ <LemonButton size="small" type="secondary" onClick={() => setView('journeys')}>+ View journeys+ </LemonButton>+ }+ >+ <AgentQueryError+ error={journeySummaryError}+ subject="agent journeys"+ onRetry={loadJourneySummary}+ loading={journeySummaryLoading}+ >+ <div className="@container">+ <div className="grid grid-cols-2 gap-3 @md:grid-cols-4">+ {journeySummaryHighlights(journeySummary ?? EMPTY_JOURNEY_SUMMARY).map((highlight) => (+ <LemonCard+ key={highlight.key}+ className="flex min-h-20 flex-col justify-between gap-2"+ hoverEffect={false}+ >+ <span className="text-sm font-medium text-secondary">{highlight.label}</span>+ {journeySummary ? (+ <span className="text-2xl font-semibold tabular-nums">{highlight.value}</span>+ ) : (+ <LemonSkeleton className="h-8 w-16" />+ )}+ </LemonCard>+ ))}+ </div>+ </div>+ </AgentQueryError>+ </AgentAnalyticsSection>+ </div>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalyticsReadiness.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsReadiness.tsxnew file mode 100644index 000000000000..b80f66497f1e--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsReadiness.tsx@@ -0,0 +1,289 @@+import { useActions, useValues } from 'kea'+import { Field, Form } from 'kea-forms'++import { IconCheck, IconInfo, IconWarning } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonCard,+ LemonInput,+ LemonSkeleton,+ LemonTable,+ LemonTableColumns,+ LemonTag,+ Link,+} from '@posthog/lemon-ui'++import { humanFriendlyLargeNumber, percentage } from 'lib/utils/numbers'+import { humanList } from 'lib/utils/strings'+import { tryDecodeURIComponent } from 'lib/utils/url'++import { WebAgentAnalyticsQueryType } from '~/queries/schema/schema-general'++import { DemandRow, LlmsTxtLink, OverviewStats, agentAnalyticsLogic, isDemandCovered } from './agentAnalyticsLogic'+import { AgentAnalyticsSection } from './AgentAnalyticsSection'+import { AgentQueryError } from './AgentQueryError'+import { AgentRequestAnatomy } from './AgentRequestAnatomy'++interface ReadinessCheck {+ status: 'success' | 'warning' | 'neutral'+ statusLabel: string+ label: string+ evidence: string+}++const readinessChecks = (overview: OverviewStats, hasConversionGoal: boolean): ReadinessCheck[] => [+ {+ status: overview.serverRequests > 0 ? 'success' : overview.clientNavigations > 0 ? 'warning' : 'neutral',+ statusLabel:+ overview.serverRequests > 0 ? 'Connected' : overview.clientNavigations > 0 ? 'Partial data' : 'No data',+ label: 'Server request data is available',+ evidence:+ overview.serverRequests > 0+ ? `${humanFriendlyLargeNumber(overview.serverRequests)} server requests were observed in this range`+ : overview.clientNavigations > 0+ ? 'Client navigations were observed, but response status and format reports need server-side HTTP logs'+ : 'No agent server requests or client navigations were observed in this range',+ },+ {+ status: overview.llmsTxtFetches > 0 ? 'success' : 'neutral',+ statusLabel: overview.llmsTxtFetches > 0 ? 'Observed' : 'Not observed',+ label: 'Agents can discover llms.txt',+ evidence:+ overview.llmsTxtFetches > 0+ ? `${humanFriendlyLargeNumber(overview.llmsTxtFetches)} successful requests in this range`+ : 'No successful llms.txt requests were observed in this range',+ },+ {+ status: overview.serverRequests === 0 ? 'neutral' : overview.wasted > 0 ? 'warning' : 'success',+ statusLabel: overview.serverRequests === 0 ? 'No data' : overview.wasted > 0 ? 'Needs attention' : 'Ready',+ label: 'Agents avoid repeated format requests',+ evidence:+ overview.serverRequests === 0+ ? 'No agent server requests were observed in this range'+ : overview.wasted > 0+ ? `${humanFriendlyLargeNumber(overview.wasted)} markdown requests were made near an HTML request for the same client session across ${overview.wastePages} pages`+ : 'No repeated HTML and markdown request patterns were detected',+ },+ {+ status: hasConversionGoal && overview.convertedClients > 0 ? 'success' : 'neutral',+ statusLabel: !hasConversionGoal+ ? 'Not configured'+ : overview.convertedClients > 0+ ? 'Observed'+ : 'Not observed',+ label: 'Agent conversions are measurable',+ evidence: !hasConversionGoal+ ? 'Select a conversion goal to measure agent conversions'+ : overview.convertedClients > 0+ ? `${humanFriendlyLargeNumber(overview.convertedClients)} agent clients reached the selected conversion goal in this range`+ : 'No agent clients reached the selected conversion goal in this range',+ },+]++const demandColumns = (llmsTxtLinks: Map<string, LlmsTxtLink>, hasInput: boolean): LemonTableColumns<DemandRow> => [+ {+ title: 'Page agents requested',+ key: 'page',+ render: (_, row) => (+ <div className="flex min-w-0 items-baseline gap-1">+ <span className="shrink-0 text-xs text-secondary">{row.host || 'Unknown domain'}</span>+ <span className="font-medium truncate">{tryDecodeURIComponent(row.path)}</span>+ </div>+ ),+ },+ {+ title: 'Requests',+ key: 'demand',+ align: 'right',+ render: (_, row) => humanFriendlyLargeNumber(row.demand),+ },+ {+ title: 'Listed in llms.txt',+ key: 'covered',+ align: 'center',+ render: (_, row) => {+ if (!hasInput) {+ return <span className="text-xs text-secondary">Load to compare</span>+ }+ return isDemandCovered(row, llmsTxtLinks) ? (+ <LemonTag type="success" size="small" icon={<IconCheck />}>+ Listed+ </LemonTag>+ ) : (+ <LemonTag type="warning" size="small">+ Missing+ </LemonTag>+ )+ },+ },+]++export const AgentAnalyticsReadiness = (): JSX.Element => {+ const {+ overview,+ overviewLoading,+ overviewError,+ demandRows,+ demandRowsLoading,+ demandRowsError,+ llmsTxtLinks,+ llmsTxtSource,+ isLlmsTxtSourceSubmitting,+ llmsTxtFetchError,+ llmsTxtLoadedUrl,+ conversionGoal,+ resultPaginations,+ demandCoverage,+ } = useValues(agentAnalyticsLogic)+ const { loadOverview, loadDemandRows } = useActions(agentAnalyticsLogic)+ const hasInput = llmsTxtLinks.size > 0+ const { missingPages, totalDemand, listedDemand, observedHosts, hasMatchingHost } = demandCoverage+ const observedHostSummary =+ observedHosts.length > 3+ ? `${observedHosts.slice(0, 3).join(', ')}, and ${observedHosts.length - 3} more`+ : humanList(observedHosts)++ return (+ <div className="flex flex-col gap-6">+ <AgentAnalyticsSection+ title="Readiness checks"+ description="Checks based on agent traffic observed in this project."+ >+ <AgentQueryError+ error={overviewError}+ subject="readiness checks"+ onRetry={loadOverview}+ loading={overviewLoading}+ >+ {overview ? (+ <LemonCard hoverEffect={false} className="divide-y divide-primary overflow-hidden p-0">+ {readinessChecks(overview, conversionGoal !== null).map((check) => (+ <div+ key={check.label}+ className="flex flex-wrap items-start justify-between gap-3 px-4 py-3"+ >+ <div className="flex min-w-0 items-start gap-2">+ {check.status === 'success' ? (+ <IconCheck className="mt-0.5 shrink-0 text-success" />+ ) : check.status === 'warning' ? (+ <IconWarning className="mt-0.5 shrink-0 text-warning" />+ ) : (+ <IconInfo className="mt-0.5 shrink-0 text-secondary" />+ )}+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="font-medium">{check.label}</span>+ <span className="text-xs text-secondary">{check.evidence}</span>+ </div>+ </div>+ <LemonTag type={check.status === 'neutral' ? 'muted' : check.status} size="small">+ {check.statusLabel}+ </LemonTag>+ </div>+ ))}+ </LemonCard>+ ) : (+ <LemonCard hoverEffect={false} className="divide-y divide-primary overflow-hidden p-0">+ {[0, 1, 2, 3].map((index) => (+ <div key={index} className="flex items-center gap-3 px-4 py-3">+ <LemonSkeleton.Circle className="size-4" />+ <div className="flex flex-1 flex-col gap-1.5">+ <LemonSkeleton className="h-4 w-64 max-w-full" />+ <LemonSkeleton className="h-3 w-96 max-w-full" />+ </div>+ <LemonSkeleton className="h-5 w-20" />+ </div>+ ))}+ </LemonCard>+ )}+ </AgentQueryError>+ </AgentAnalyticsSection>++ <AgentRequestAnatomy />++ <AgentAnalyticsSection+ title="llms.txt coverage"+ description={+ <>+ Load your <Link to="https://llmstxt.org/">llms.txt</Link> file to compare its pages with+ successful agent requests. Absolute links match their origin and case-sensitive path, with an+ appended <code>.md</code> treated as the same page. Relative links use the loaded file URL.+ </>+ }+ right={+ hasInput ? (+ <div className="flex items-center gap-1">+ <LemonTag type="success" size="small">+ {totalDemand > 0 ? percentage(listedDemand / totalDemand, 0) : '0%'} of requests on this+ page listed+ </LemonTag>+ <LemonTag type="warning" size="small">+ {humanFriendlyLargeNumber(missingPages)} of{' '}+ {humanFriendlyLargeNumber(demandRows.length)} pages missing on this page+ </LemonTag>+ </div>+ ) : undefined+ }+ >+ <Form logic={agentAnalyticsLogic} formKey="llmsTxtSource" enableFormOnSubmit className="@container">+ <div className="flex flex-col gap-2 @md:flex-row @md:items-end">+ <div className="min-w-0 flex-1">+ <Field+ name="url"+ label="llms.txt URL"+ help="PostHog loads up to 1 MB from a public HTTP or HTTPS URL. The file is used for this comparison and is not saved."+ >+ <LemonInput+ type="url"+ inputMode="url"+ placeholder="https://example.com/llms.txt"+ maxLength={2048}+ fullWidth+ />+ </Field>+ </div>+ <LemonButton+ type="secondary"+ htmlType="submit"+ loading={isLlmsTxtSourceSubmitting}+ disabledReason={!llmsTxtSource.url.trim() ? 'Enter a URL to load' : undefined}+ data-attr="agent-analytics-load-llms-txt"+ >+ Load file+ </LemonButton>+ </div>+ </Form>+ {llmsTxtFetchError ? <LemonBanner type="error">{llmsTxtFetchError}</LemonBanner> : null}+ {llmsTxtLoadedUrl ? (+ <LemonBanner type="success">+ Loaded from <span className="break-all font-medium">{llmsTxtLoadedUrl}</span>.+ </LemonBanner>+ ) : null}+ {hasInput && demandRows.length > 0 && observedHosts.length > 0 && !hasMatchingHost ? (+ <LemonBanner type="warning">+ None of the links in this file match the observed{' '}+ {observedHosts.length === 1 ? 'domain' : 'domains'}{' '}+ <span className="font-medium">{observedHostSummary}</span>. Select a matching domain or load its+ llms.txt file.+ </LemonBanner>+ ) : null}+ <AgentQueryError+ error={demandRowsError}+ subject="requested pages"+ onRetry={loadDemandRows}+ loading={demandRowsLoading}+ >+ <LemonTable+ columns={demandColumns(llmsTxtLinks, hasInput)}+ dataSource={demandRows}+ loading={demandRowsLoading}+ size="small"+ nouns={['page', 'pages']}+ pagination={resultPaginations[WebAgentAnalyticsQueryType.Demand]}+ emptyState="No successful agent page requests were found in this range."+ />+ </AgentQueryError>+ </AgentAnalyticsSection>+ </div>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentAnalyticsSection.tsx b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsSection.tsxnew file mode 100644index 000000000000..5137ae5e3c8d--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentAnalyticsSection.tsx@@ -0,0 +1,29 @@+import clsx from 'clsx'+import { ReactNode } from 'react'++export interface AgentAnalyticsSectionProps {+ title: string+ description?: ReactNode+ right?: ReactNode+ children: ReactNode+ className?: string+}++export const AgentAnalyticsSection = ({+ title,+ description,+ right,+ children,+ className,+}: AgentAnalyticsSectionProps): JSX.Element => (+ <section className={clsx('flex flex-col gap-3', className)}>+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="flex min-w-0 flex-col gap-1">+ <h2 className="text-lg font-semibold">{title}</h2>+ {description ? <p className="m-0 max-w-3xl text-sm text-secondary">{description}</p> : null}+ </div>+ {right}+ </div>+ {children}+ </section>+)diff --git a/products/web_analytics/frontend/agent_analytics/AgentIssueChangeIndicator.tsx b/products/web_analytics/frontend/agent_analytics/AgentIssueChangeIndicator.tsxnew file mode 100644index 000000000000..da0f430b6851--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentIssueChangeIndicator.tsx@@ -0,0 +1,48 @@+import clsx from 'clsx'++import { IconTrending } from '@posthog/icons'+import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'++import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'+import { percentage } from 'lib/utils/numbers'++export type ChangeSentiment = 'higher-is-better' | 'lower-is-better' | 'neutral'++export const AgentIssueChangeIndicator = ({+ changePct,+ sentiment = 'lower-is-better',+}: {+ changePct: number | null+ sentiment?: ChangeSentiment+}): JSX.Element | null => {+ if (changePct === null) {+ return null+ }++ const increased = changePct > 0+ const decreased = changePct < 0+ const Icon = increased ? IconTrending : decreased ? IconTrendingDown : IconTrendingFlat+ const favorable = sentiment === 'neutral' ? null : sentiment === 'higher-is-better' ? increased : decreased+ const tagType: LemonTagType = favorable === null ? 'muted' : favorable ? 'success' : 'danger'+ const direction = increased ? 'more' : decreased ? 'fewer' : 'the same as'++ return (+ <Tooltip+ title={+ changePct === 0+ ? 'No change from the previous period'+ : `${percentage(Math.abs(changePct) / 100, 0)} ${direction} than the previous period`+ }+ >+ <LemonTag+ type={tagType}+ size="small"+ icon={<Icon />}+ className={clsx('tabular-nums', sentiment === 'neutral' && 'text-secondary')}+ >+ {changePct > 0 ? '+' : ''}+ {percentage(changePct / 100, 0)}+ </LemonTag>+ </Tooltip>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentIssueDetail.tsx b/products/web_analytics/frontend/agent_analytics/AgentIssueDetail.tsxnew file mode 100644index 000000000000..21bbe6123bec--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentIssueDetail.tsx@@ -0,0 +1,84 @@+import { useActions, useValues } from 'kea'++import { LemonTable, LemonTableColumns } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'+import { tryDecodeURIComponent } from 'lib/utils/url'++import { WebAgentAnalyticsQueryType } from '~/queries/schema/schema-general'++import { AgentIssue, IssueVariant, agentAnalyticsLogic } from './agentAnalyticsLogic'+import { AgentQueryError } from './AgentQueryError'++const variantColumns: LemonTableColumns<IssueVariant> = [+ {+ title: 'Requested URL',+ key: 'variant',+ render: (_, variant) => <span className="font-mono text-xs">{tryDecodeURIComponent(variant.variant)}</span>,+ },+ {+ title: 'Requests',+ key: 'demand',+ align: 'right',+ render: (_, variant) => humanFriendlyLargeNumber(variant.demand),+ },+ {+ title: 'Top agent',+ key: 'agent',+ render: (_, variant) => variant.topAgent ?? <span className="text-secondary">-</span>,+ },+ {+ title: 'First seen in range',+ key: 'first_seen',+ render: (_, variant) =>+ variant.firstSeen ? <TZLabel time={variant.firstSeen} /> : <span className="text-secondary">-</span>,+ },+]++export const AgentIssueDetail = ({ issue }: { issue: AgentIssue }): JSX.Element => {+ const { variants, variantsLoading, variantsError, resultPaginations } = useValues(agentAnalyticsLogic)+ const { loadVariants } = useActions(agentAnalyticsLogic)++ return (+ <div className="flex flex-col gap-4 py-2">+ <div className="flex flex-col gap-2">+ <span className="text-sm font-medium">Recommended fix</span>+ <ol className="ml-4 flex list-decimal flex-col gap-1 text-sm">+ {issue.recommendedFix.map((step) => (+ <li key={step}>{step}</li>+ ))}+ </ol>+ </div>++ {issue.type === 'content_gap' ? (+ <div className="flex flex-col gap-2">+ <span className="flex flex-wrap items-center gap-2 text-sm font-medium">+ Requested URL variants+ {issue.lastSeen ? (+ <span className="text-xs font-normal text-secondary">+ last seen <TZLabel time={issue.lastSeen} />+ </span>+ ) : null}+ </span>+ <AgentQueryError+ error={variantsError}+ subject="URL variants"+ onRetry={loadVariants}+ loading={variantsLoading}+ >+ <LemonTable+ columns={variantColumns}+ dataSource={variants}+ loading={variantsLoading}+ size="small"+ nouns={['variant', 'variants']}+ pagination={resultPaginations[WebAgentAnalyticsQueryType.IssueVariants]}+ emptyState="No URL variants were found in this range."+ />+ </AgentQueryError>+ </div>+ ) : null}+ </div>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentIssueTypeTag.tsx b/products/web_analytics/frontend/agent_analytics/AgentIssueTypeTag.tsxnew file mode 100644index 000000000000..67710663c96d--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentIssueTypeTag.tsx@@ -0,0 +1,14 @@+import { LemonTag, LemonTagType } from '@posthog/lemon-ui'++import { AgentIssueType } from './agentAnalyticsLogic'++const ISSUE_TYPE_CONFIG: Record<AgentIssueType, { label: string; tagType: LemonTagType }> = {+ content_gap: { label: 'Content gap', tagType: 'danger' },+ waste: { label: 'Waste', tagType: 'warning' },+ malformed: { label: 'Malformed', tagType: 'caution' },+}++export const AgentIssueTypeTag = ({ type }: { type: AgentIssueType }): JSX.Element => {+ const config = ISSUE_TYPE_CONFIG[type]+ return <LemonTag type={config.tagType}>{config.label}</LemonTag>+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentJourneyDetail.tsx b/products/web_analytics/frontend/agent_analytics/AgentJourneyDetail.tsxnew file mode 100644index 000000000000..fb2118c5cef6--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentJourneyDetail.tsx@@ -0,0 +1,146 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonModal, LemonTag, LemonTagType, Spinner, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'+import { tryDecodeURIComponent } from 'lib/utils/url'++import { JourneyStep, JourneyTransition, agentAnalyticsLogic } from './agentAnalyticsLogic'+import { AgentQueryError } from './AgentQueryError'++const TRANSITION_CONFIG: Record<JourneyTransition, { label: string; help: string }> = {+ start: { label: 'First request', help: 'The first request observed in this journey.' },+ confirmed: {+ label: 'Followed a link',+ help: 'The referrer points to the previous page, so this request followed a link from it.',+ },+ sequential: {+ label: 'Next request',+ help: 'This request came after the previous one in time. There is no referrer linking them.',+ },+ parallel: {+ label: 'Simultaneous',+ help: 'This request shares a timestamp with the previous one, so their order is ambiguous.',+ },+}++const statusTagType = (status: number): LemonTagType => {+ if (status >= 500) {+ return 'danger'+ }+ if (status >= 400) {+ return 'warning'+ }+ if (status >= 300) {+ return 'caution'+ }+ return 'success'+}++const offsetLabel = (step: JourneyStep, firstTimestamp: string | null): string => {+ if (!step.timestamp || !firstTimestamp) {+ return ''+ }+ const seconds = dayjs(step.timestamp).diff(dayjs(firstTimestamp), 'second')+ if (seconds <= 0) {+ return 'start'+ }+ return `+${humanFriendlyDuration(seconds, { maxUnits: 2 })}`+}++const JourneyStepRow = ({+ step,+ firstTimestamp,+}: {+ step: JourneyStep+ firstTimestamp: string | null+}): JSX.Element => {+ const transition = TRANSITION_CONFIG[step.transition]+ return (+ <li className="flex gap-3">+ <span className="w-16 shrink-0 pt-0.5 text-right text-xs tabular-nums text-tertiary">+ {offsetLabel(step, firstTimestamp)}+ </span>+ <div className="flex min-w-0 flex-col gap-1 border-l border-primary pb-4 pl-3">+ <span className="truncate font-medium">{tryDecodeURIComponent(step.path) || '/'}</span>+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <LemonTag type={statusTagType(step.status)} size="small">+ {step.status || 'No status'}+ </LemonTag>+ <span className="text-secondary">{step.format === 'markdown' ? 'Markdown' : 'HTML'}</span>+ <Tooltip title={transition.help}>+ <span className="text-tertiary">· {transition.label}</span>+ </Tooltip>+ </div>+ </div>+ </li>+ )+}++export const AgentJourneyDetail = (): JSX.Element => {+ const { selectedJourney, selectedJourneyKey, journeyDetail, journeyDetailLoading, journeyDetailError } =+ useValues(agentAnalyticsLogic)+ const { setSelectedJourneyKey, loadJourneyDetail } = useActions(agentAnalyticsLogic)++ const firstTimestamp = journeyDetail[0]?.timestamp ?? null++ return (+ <LemonModal+ isOpen={selectedJourneyKey !== null}+ onClose={() => setSelectedJourneyKey(null)}+ title="Journey timeline"+ description={+ selectedJourney ? (+ <span className="flex flex-wrap items-center gap-2">+ <span className="font-medium text-default">{selectedJourney.agent}</span>+ <span className="text-secondary">on {selectedJourney.host || 'unknown domain'}</span>+ {selectedJourney.started ? (+ <span className="text-secondary">+ started <TZLabel time={selectedJourney.started} />+ </span>+ ) : null}+ </span>+ ) : (+ 'This request sequence is ordered by time, not proven to be one conversation.'+ )+ }+ width={640}+ >+ <AgentQueryError+ error={journeyDetailError}+ subject="this journey"+ onRetry={loadJourneyDetail}+ loading={journeyDetailLoading}+ >+ {journeyDetailLoading && journeyDetail.length === 0 ? (+ <div className="flex min-h-32 items-center justify-center">+ <Spinner />+ </div>+ ) : journeyDetail.length === 0 ? (+ <p className="text-secondary">No requests were found for this journey in this range.</p>+ ) : (+ <>+ <ol className="m-0 flex list-none flex-col p-0">+ {journeyDetail.map((step, index) => (+ <JourneyStepRow+ key={`${step.path}-${index}`}+ step={step}+ firstTimestamp={firstTimestamp}+ />+ ))}+ </ol>+ {selectedJourney && selectedJourney.requests > journeyDetail.length ? (+ <LemonBanner type="info">+ Showing the first {humanFriendlyLargeNumber(journeyDetail.length)} of{' '}+ {humanFriendlyLargeNumber(selectedJourney.requests)} requests in this journey.+ </LemonBanner>+ ) : null}+ </>+ )}+ </AgentQueryError>+ </LemonModal>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentQueryError.tsx b/products/web_analytics/frontend/agent_analytics/AgentQueryError.tsxnew file mode 100644index 000000000000..eaea0c8268d3--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentQueryError.tsx@@ -0,0 +1,22 @@+import { ReactNode } from 'react'++import { LemonBanner } from '@posthog/lemon-ui'++interface AgentQueryErrorProps {+ error: string | null+ subject: string+ onRetry: () => void+ loading: boolean+ children: ReactNode+}++export const AgentQueryError = ({ error, subject, onRetry, loading, children }: AgentQueryErrorProps): JSX.Element => {+ if (error) {+ return (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: onRetry, loading }}>+ {`Could not load ${subject}. Try again. If it keeps happening, contact support.`}+ </LemonBanner>+ )+ }+ return <>{children}</>+}diff --git a/products/web_analytics/frontend/agent_analytics/AgentRequestAnatomy.tsx b/products/web_analytics/frontend/agent_analytics/AgentRequestAnatomy.tsxnew file mode 100644index 000000000000..04ec52f29a05--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/AgentRequestAnatomy.tsx@@ -0,0 +1,97 @@+import { useActions, useValues } from 'kea'++import { LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { humanFriendlyLargeNumber, percentage } from 'lib/utils/numbers'++import { WebAgentAnalyticsQueryType } from '~/queries/schema/schema-general'++import { RequestAnatomyRow, agentAnalyticsLogic } from './agentAnalyticsLogic'+import { AgentAnalyticsSection } from './AgentAnalyticsSection'+import { AgentQueryError } from './AgentQueryError'++const markdownShare = (row: RequestAnatomyRow): number => (row.requests > 0 ? row.requestedMarkdown / row.requests : 0)++const anatomyColumns: LemonTableColumns<RequestAnatomyRow> = [+ {+ title: 'Agent',+ key: 'agent',+ render: (_, row) => <span className="font-medium">{row.agent}</span>,+ },+ {+ title: 'Requests',+ key: 'requests',+ align: 'right',+ render: (_, row) => humanFriendlyLargeNumber(row.requests),+ },+ {+ title: 'Requested format',+ key: 'requested',+ render: (_, row) => {+ const share = markdownShare(row)+ return (+ <div className="flex min-w-32 items-center gap-2">+ <LemonProgress className="w-16" percent={share * 100} />+ <span className="text-xs tabular-nums">{percentage(share, 0)} markdown</span>+ </div>+ )+ },+ },+ {+ title: 'HTML then markdown',+ key: 'retry',+ align: 'right',+ render: (_, row) =>+ row.retryPairs > 0 ? (+ <Tooltip title="Requests where the agent fetched a page as HTML and then re-fetched its markdown twin. Advertising the markdown version avoids the second request.">+ <LemonTag type="warning" size="small">+ {percentage(row.retryPairs / row.requests, 0)}+ </LemonTag>+ </Tooltip>+ ) : (+ <span className="text-secondary">-</span>+ ),+ },+ {+ title: 'Errors',+ key: 'errors',+ align: 'right',+ render: (_, row) =>+ row.errors > 0 ? (+ <span className="font-semibold text-danger">{percentage(row.errors / row.requests, 1)}</span>+ ) : (+ <span className="text-secondary">0%</span>+ ),+ },+]++export const AgentRequestAnatomy = (): JSX.Element => {+ const { requestAnatomy, requestAnatomyLoading, requestAnatomyError, resultPaginations } =+ useValues(agentAnalyticsLogic)+ const { loadRequestAnatomy } = useActions(agentAnalyticsLogic)++ return (+ <AgentAnalyticsSection+ title="Request anatomy"+ description="How each agent asks for content. Format is read from the request URL."+ >+ <AgentQueryError+ error={requestAnatomyError}+ subject="request anatomy"+ onRetry={loadRequestAnatomy}+ loading={requestAnatomyLoading}+ >+ <LemonTable+ columns={anatomyColumns}+ dataSource={requestAnatomy}+ loading={requestAnatomyLoading}+ size="small"+ nouns={['agent', 'agents']}+ pagination={resultPaginations[WebAgentAnalyticsQueryType.RequestAnatomy]}+ emptyState="No per-agent request data was found. Connect server-side HTTP logs, widen the date range, or include AI crawlers."+ />+ </AgentQueryError>+ </AgentAnalyticsSection>+ )+}diff --git a/products/web_analytics/frontend/agent_analytics/agentAnalyticsLogic.test.ts b/products/web_analytics/frontend/agent_analytics/agentAnalyticsLogic.test.tsnew file mode 100644index 000000000000..389072447b42--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/agentAnalyticsLogic.test.ts@@ -0,0 +1,388 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'++import { performQuery } from '~/queries/query'+import { WebAgentAnalyticsQuery, WebAgentAnalyticsQueryType } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { webAnalyticsFetchLlmsTxt } from 'products/web_analytics/frontend/generated/api'++import {+ OverviewStats,+ agentAnalyticsLogic,+ isDemandCovered,+ parseIssuesResponse,+ parseLlmsTxtLinks,+ parseOverviewRow,+ summarizeDemandCoverage,+ synthesizeAuxIssues,+} from './agentAnalyticsLogic'++jest.mock('products/web_analytics/frontend/generated/api', () => ({+ webAnalyticsFetchLlmsTxt: jest.fn(),+}))+jest.mock('~/queries/query', () => ({+ performQuery: jest.fn().mockResolvedValue({ columns: [], results: [] }),+}))++const mockFetchLlmsTxt = webAnalyticsFetchLlmsTxt as jest.Mock+const mockPerformQuery = performQuery as jest.Mock++const emptyOverview = (overrides: Partial<OverviewStats>): OverviewStats => ({+ activeClients: 0,+ activeClientsPrev: 0,+ agentFamilies: 0,+ serverRequests: 0,+ serverRequestsPrev: 0,+ clientNavigations: 0,+ clientNavigationsPrev: 0,+ statusObserved: 0,+ clientErrors: 0,+ clientErrorsPrev: 0,+ wasted: 0,+ wastedPrev: 0,+ wastePages: 0,+ convertedClients: 0,+ convertedClientsPrev: 0,+ malformed: 0,+ malformedPrev: 0,+ llmsTxtFetches: 0,+ excludedRequests: 0,+ ...overrides,+})++describe('agentAnalyticsLogic', () => {+ describe('parseIssuesResponse', () => {+ const columns = [+ 'intent_key',+ 'intent_path',+ 'demand',+ 'demand_prev',+ 'variants',+ 'top_agent',+ 'first_seen',+ 'last_seen',+ ]++ it('reads current and previous demand for each grouped intent', () => {+ const results = [+ [+ 'example.com/guides/token-security',+ '/guides/token-security',+ 100,+ 80,+ 3,+ 'ChatGPT',+ '2026-08-08 01:00:00',+ '2026-08-14 01:00:00',+ ],+ [+ 'example.com/reference/imports',+ '/reference/imports',+ 50,+ 0,+ 1,+ 'Claude',+ '2026-08-11 00:00:00',+ '2026-08-13 00:00:00',+ ],+ ]++ const issues = parseIssuesResponse(columns, results)++ expect(issues.map((issue) => issue.key)).toEqual([+ 'example.com/guides/token-security',+ 'example.com/reference/imports',+ ])+ const first = issues[0]+ expect(first.demand).toBe(100)+ expect(first.demandPrev).toBe(80)+ expect(first.changePct).toBe(25)+ expect(first.subtitle).toBe('3 requested URL variants')+ expect(first.topAgent).toBe('ChatGPT')+ expect(first.type).toBe('content_gap')+ })+ })++ describe('synthesizeAuxIssues', () => {+ it.each([+ [+ 'waste when double-fetch waste exists',+ emptyOverview({ wasted: 120, wastePages: 9 }),+ 'waste:md-twins',+ true,+ ],+ ['no waste when there is none', emptyOverview({ wasted: 0 }), 'waste:md-twins', false],+ ['malformed when present', emptyOverview({ malformed: 5 }), 'malformed:null-urls', true],+ ['no malformed when zero', emptyOverview({ malformed: 0 }), 'malformed:null-urls', false],+ ])('%s', (_name, overview, key, present) => {+ const keys = synthesizeAuxIssues(overview).map((issue) => issue.key)+ expect(keys.includes(key)).toBe(present)+ })+ })++ describe('parseLlmsTxtLinks', () => {+ it('resolves relative links against the loaded URL and preserves origin and path case', () => {+ const input = [+ '# My site',+ '- [Docs](https://example.com/docs/api/)',+ '- [Pricing](/pricing)',+ '- [Guide](Guides/Start)',+ 'https://example.com/DOCS/Session-Replay',+ 'not a link at all',+ ].join('\n')++ const links = parseLlmsTxtLinks(input, 'https://example.com/reference/llms.txt')++ expect(isDemandCovered({ page: '', host: 'example.com', path: '/docs/api/', demand: 1 }, links)).toBe(true)+ expect(isDemandCovered({ page: '', host: 'example.com', path: '/pricing', demand: 1 }, links)).toBe(true)+ expect(+ isDemandCovered({ page: '', host: 'example.com', path: '/reference/Guides/Start', demand: 1 }, links)+ ).toBe(true)+ expect(+ isDemandCovered({ page: '', host: 'example.com', path: '/docs/session-replay', demand: 1 }, links)+ ).toBe(false)+ expect(isDemandCovered({ page: '', host: 'other.example', path: '/pricing', demand: 1 }, links)).toBe(false)+ })++ it('treats a pasted root-relative path as applying to any host', () => {+ const links = parseLlmsTxtLinks('/pricing', null)++ expect(isDemandCovered({ page: '', host: 'other.example', path: '/pricing', demand: 1 }, links)).toBe(true)+ expect(parseLlmsTxtLinks('', null).size).toBe(0)+ })++ it('matches an appended .md representation to the original page URL', () => {+ const links = parseLlmsTxtLinks(+ '- [Libraries](https://example.com/docs/libraries.md)',+ 'https://example.com/llms.txt'+ )++ expect(isDemandCovered({ page: '', host: 'example.com', path: '/docs/libraries', demand: 1 }, links)).toBe(+ true+ )+ expect(+ isDemandCovered({ page: '', host: 'example.com', path: '/docs/libraries.md', demand: 1 }, links)+ ).toBe(true)+ expect(isDemandCovered({ page: '', host: 'example.com', path: '/docs/library', demand: 1 }, links)).toBe(+ false+ )+ })++ it('reports when the file does not list any observed domains', () => {+ const links = parseLlmsTxtLinks('- [API](https://posthog.com/docs/api.md)', 'https://posthog.com/llms.txt')++ expect(+ summarizeDemandCoverage(+ [+ { page: 'example.com/docs/api.md', host: 'example.com', path: '/docs/api.md', demand: 75 },+ { page: 'hedgebox.net/docs/api.md', host: 'hedgebox.net', path: '/docs/api.md', demand: 33 },+ ],+ links+ )+ ).toEqual({+ listedPages: 0,+ missingPages: 2,+ totalDemand: 108,+ listedDemand: 0,+ observedHosts: ['example.com', 'hedgebox.net'],+ hasMatchingHost: false,+ })+ })+ })++ describe('llms.txt URL loading', () => {+ let logic: ReturnType<typeof agentAnalyticsLogic.build>++ beforeEach(() => {+ initKeaTests()+ mockFetchLlmsTxt.mockReset()+ logic = agentAnalyticsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('loads URL content into the coverage comparison', async () => {+ mockFetchLlmsTxt.mockResolvedValue({+ content: '# Example\n/docs\n/pricing',+ url: 'https://www.example.com/llms.txt',+ })+ logic.actions.setLlmsTxtSourceValue('url', 'https://example.com/llms.txt')++ await expectLogic(logic, () => logic.actions.submitLlmsTxtSource())+ .toFinishAllListeners()+ .toMatchValues({+ llmsTxtInput: '# Example\n/docs\n/pricing',+ llmsTxtLoadedUrl: 'https://www.example.com/llms.txt',+ llmsTxtFetchError: null,+ isLlmsTxtSourceSubmitting: false,+ })++ expect(mockFetchLlmsTxt).toHaveBeenCalledWith(expect.any(String), {+ url: 'https://example.com/llms.txt',+ })+ })++ it('shows the URL-specific server error when loading fails', async () => {+ mockFetchLlmsTxt.mockRejectedValue({ data: { url: ['The URL returned HTTP 404.'] } })+ logic.actions.setLlmsTxtSourceValue('url', 'https://example.com/missing.txt')++ await expectLogic(logic, () => logic.actions.submitLlmsTxtSource())+ .toFinishAllListeners()+ .toMatchValues({+ llmsTxtFetchError: 'The URL returned HTTP 404.',+ isLlmsTxtSourceSubmitting: false,+ })+ })++ it('drops the previous file when a later load fails', async () => {+ mockFetchLlmsTxt.mockResolvedValue({+ content: '# Example\n/docs\n/pricing',+ url: 'https://www.example.com/llms.txt',+ })+ logic.actions.setLlmsTxtSourceValue('url', 'https://example.com/llms.txt')+ await expectLogic(logic, () => logic.actions.submitLlmsTxtSource()).toFinishAllListeners()+ expect(logic.values.llmsTxtLinks.size).toBeGreaterThan(0)++ mockFetchLlmsTxt.mockRejectedValue({ data: { url: ['The URL returned HTTP 404.'] } })+ logic.actions.setLlmsTxtSourceValue('url', 'https://example.com/missing.txt')++ await expectLogic(logic, () => logic.actions.submitLlmsTxtSource())+ .toFinishAllListeners()+ .toMatchValues({+ llmsTxtInput: '',+ llmsTxtLoadedUrl: null,+ llmsTxtFetchError: 'The URL returned HTTP 404.',+ })+ expect(logic.values.llmsTxtLinks.size).toBe(0)+ })+ })++ describe('query construction', () => {+ let logic: ReturnType<typeof agentAnalyticsLogic.build>+ let unmountWebAnalyticsLogic: (() => void) | undefined++ beforeEach(() => {+ initKeaTests()+ Object.assign(posthog, { setPersonProperties: jest.fn() })+ mockPerformQuery.mockReset().mockResolvedValue({ columns: [], results: [] })+ unmountWebAnalyticsLogic = webAnalyticsLogic.mount()+ webAnalyticsLogic.actions.setConversionGoal({ actionId: 42 })+ logic = agentAnalyticsLogic()+ logic.mount()+ mockPerformQuery.mockClear()+ })++ afterEach(() => {+ logic?.unmount()+ unmountWebAnalyticsLogic?.()+ })++ it('sends the selected goal with the overview query', async () => {+ await expectLogic(logic, () => logic.actions.loadOverview()).toFinishAllListeners()++ expect(mockPerformQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryType: WebAgentAnalyticsQueryType.Overview,+ conversionGoal: { actionId: 42 },+ }),+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ })++ it('limits the What agents read query to five rows', async () => {+ await expectLogic(logic, () => logic.actions.loadWhatAgentsRead()).toFinishAllListeners()++ expect(mockPerformQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryType: WebAgentAnalyticsQueryType.PageRequests,+ limit: 5,+ }),+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ })++ it.each([+ [WebAgentAnalyticsQueryType.Issues, 23],+ [WebAgentAnalyticsQueryType.Transitions, 25],+ [WebAgentAnalyticsQueryType.Demand, 25],+ [WebAgentAnalyticsQueryType.RequestAnatomy, 25],+ [WebAgentAnalyticsQueryType.Journeys, 25],+ ])('loads the next %s page from the server', async (queryType, expectedOffset) => {+ logic.actions.setResultHasMore(queryType, true)++ await expectLogic(logic, () => logic.values.resultPaginations[queryType]?.onForward?.())+ .toFinishAllListeners()+ .toMatchValues({ resultPages: { [queryType]: 2 } })++ expect(mockPerformQuery).toHaveBeenLastCalledWith(+ expect.objectContaining({+ queryType,+ limit: 25,+ offset: expectedOffset,+ }),+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ })++ it('keeps a failed query on its own section instead of failing the loader', async () => {+ mockPerformQuery.mockImplementation((node: WebAgentAnalyticsQuery) =>+ node.queryType === WebAgentAnalyticsQueryType.Overview+ ? Promise.reject({ status: 500, detail: 'Query timed out' })+ : Promise.resolve({ columns: [], results: [] })+ )++ await expectLogic(logic, () => logic.actions.loadOverview())+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['loadOverviewFailure'])+ .toMatchValues({+ overviewError: 'Query timed out',+ overviewLoading: false,+ journeysError: null,+ })+ })++ it('caps journey timelines at fifty requests', async () => {+ await expectLogic(logic, () =>+ logic.actions.setSelectedJourneyKey('journey-example')+ ).toFinishAllListeners()++ expect(mockPerformQuery).toHaveBeenLastCalledWith(+ expect.objectContaining({+ queryType: WebAgentAnalyticsQueryType.JourneyDetail,+ journeyKey: 'journey-example',+ limit: 50,+ }),+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ })+ })++ describe('parseOverviewRow', () => {+ it('maps result columns to stats by name and defaults missing columns to zero', () => {+ const columns = [+ 'active_clients',+ 'server_requests',+ 'client_errors',+ 'converted_agents',+ 'converted_agents_prev',+ ]+ const stats = parseOverviewRow(columns, [[18, 360, 35, 7, 4]])+ expect(stats.activeClients).toBe(18)+ expect(stats.serverRequests).toBe(360)+ expect(stats.clientErrors).toBe(35)+ expect(stats.convertedClients).toBe(7)+ expect(stats.convertedClientsPrev).toBe(4)+ expect(stats.wasted).toBe(0)+ })++ it('returns zeroed stats when there are no rows', () => {+ expect(parseOverviewRow([], []).activeClients).toBe(0)+ })+ })+})diff --git a/products/web_analytics/frontend/agent_analytics/agentAnalyticsLogic.ts b/products/web_analytics/frontend/agent_analytics/agentAnalyticsLogic.tsnew file mode 100644index 000000000000..97e3b4b24088--- /dev/null+++ b/products/web_analytics/frontend/agent_analytics/agentAnalyticsLogic.ts@@ -0,0 +1,1680 @@+import type { BreakPointFunction } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import type { PaginationManual } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'+import type { DateFilterState } from 'scenes/web-analytics/webAnalyticsLogic'++import { performQuery } from '~/queries/query'+import {+ CompareFilter,+ NodeKind,+ WebAgentContentGrouping,+ WebAgentAnalyticsQuery,+ WebAgentAnalyticsQueryType,+ WebAnalyticsConversionGoal,+ WebAnalyticsPropertyFilters,+} from '~/queries/schema/schema-general'+import { IntervalType, TeamPublicType, TeamType } from '~/types'++import * as webAnalyticsApi from 'products/web_analytics/frontend/generated/api'++export type AgentScope = 'live' | 'all'+export type AgentView = 'overview' | 'journeys' | 'issues' | 'readiness'+export type AgentIssueType = 'content_gap' | 'waste' | 'malformed'+export type JourneyTransition = 'start' | 'confirmed' | 'sequential' | 'parallel'++export interface OverviewStats {+ activeClients: number+ activeClientsPrev: number+ agentFamilies: number+ serverRequests: number+ serverRequestsPrev: number+ clientNavigations: number+ clientNavigationsPrev: number+ statusObserved: number+ clientErrors: number+ clientErrorsPrev: number+ wasted: number+ wastedPrev: number+ wastePages: number+ convertedClients: number+ convertedClientsPrev: number+ malformed: number+ malformedPrev: number+ llmsTxtFetches: number+ excludedRequests: number+}++export interface AgentIssue {+ key: string+ type: AgentIssueType+ title: string+ subtitle: string+ demand: number+ demandPrev: number+ changePct: number | null+ topAgent: string | null+ firstSeen: string | null+ lastSeen: string | null+ recommendedFix: string[]+}++export interface PageRead {+ page: string+ fetches: number+ mdFetches: number+ htmlFetches: number+ pairedClients: number+}++export interface NextHop {+ path: string+ requests: number+ notFound: number+}++export interface DemandRow {+ page: string+ host: string+ path: string+ demand: number+}++export interface IssueVariant {+ variant: string+ demand: number+ topAgent: string | null+ firstSeen: string | null+}++export interface RequestAnatomyRow {+ agent: string+ requests: number+ requestedMarkdown: number+ retryPairs: number+ errors: number+}++export interface JourneySummary {+ totalJourneys: number+ medianPages: number+ medianRequests: number+ medianDurationSeconds: number+ journeysWithErrors: number+}++export interface JourneyRow {+ journeyKey: string+ started: string | null+ agent: string+ host: string+ pages: number+ requests: number+ durationSeconds: number+ errors: number+}++export interface JourneyStep {+ timestamp: string | null+ path: string+ status: number+ format: string+ referrer: string+ transition: JourneyTransition+}++export interface LlmsTxtSourceForm {+ url: string+}++export interface LlmsTxtLink {+ host: string | null+ path: string+}++export interface DemandCoverage {+ listedPages: number+ missingPages: number+ totalDemand: number+ listedDemand: number+ observedHosts: string[]+ hasMatchingHost: boolean+}++const EMPTY_OVERVIEW: OverviewStats = {+ activeClients: 0,+ activeClientsPrev: 0,+ agentFamilies: 0,+ serverRequests: 0,+ serverRequestsPrev: 0,+ clientNavigations: 0,+ clientNavigationsPrev: 0,+ statusObserved: 0,+ clientErrors: 0,+ clientErrorsPrev: 0,+ wasted: 0,+ wastedPrev: 0,+ wastePages: 0,+ convertedClients: 0,+ convertedClientsPrev: 0,+ malformed: 0,+ malformedPrev: 0,+ llmsTxtFetches: 0,+ excludedRequests: 0,+}++export const EMPTY_JOURNEY_SUMMARY: JourneySummary = {+ totalJourneys: 0,+ medianPages: 0,+ medianRequests: 0,+ medianDurationSeconds: 0,+ journeysWithErrors: 0,+}++const validateLlmsTxtSource = ({ url }: LlmsTxtSourceForm): { url: string | undefined } => {+ if (!url.trim()) {+ return { url: 'Enter the URL of your llms.txt file' }+ }+ try {+ const parsedUrl = new URL(url)+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {+ return { url: 'Enter an HTTP or HTTPS URL' }+ }+ } catch {+ return { url: 'Enter a valid URL' }+ }+ return { url: undefined }+}++const llmsTxtFetchErrorMessage = (error: unknown): string => {+ const apiError = error as {+ data?: { url?: string[]; detail?: string }+ detail?: string+ message?: string+ }+ return (+ apiError.data?.url?.[0] ??+ apiError.data?.detail ??+ apiError.detail ??+ apiError.message ??+ 'Could not load llms.txt. Check the URL and try again.'+ )+}++const queryErrorMessage = (error: unknown): string => {+ const apiError = error as { detail?: string; message?: string }+ return apiError?.detail ?? apiError?.message ?? 'Could not load this query.'+}++const errorForQuery =+ (queryType: WebAgentAnalyticsQueryType) =>+ (state: string | null, payload: { queryType: WebAgentAnalyticsQueryType; error: string | null }): string | null =>+ payload.queryType === queryType ? payload.error : state++const num = (value: unknown): number => Number(value ?? 0)++const str = (value: unknown): string => (value == null ? '' : String(value))++const columnIndex = (columns: string[] | undefined, name: string): number => (columns ?? []).indexOf(name)++export const parseOverviewRow = (columns: string[] | undefined, results: unknown[][] | undefined): OverviewStats => {+ const row = (results ?? [])[0]+ if (!Array.isArray(row)) {+ return EMPTY_OVERVIEW+ }+ const get = (name: string): number => {+ const idx = columnIndex(columns, name)+ return idx >= 0 ? num(row[idx]) : 0+ }+ return {+ activeClients: get('active_clients'),+ activeClientsPrev: get('active_clients_prev'),+ agentFamilies: get('agent_families'),+ serverRequests: get('server_requests'),+ serverRequestsPrev: get('server_requests_prev'),+ clientNavigations: get('client_navigations'),+ clientNavigationsPrev: get('client_navigations_prev'),+ statusObserved: get('status_observed'),+ clientErrors: get('client_errors'),+ clientErrorsPrev: get('client_errors_prev'),+ wasted: get('wasted'),+ wastedPrev: get('wasted_prev'),+ wastePages: get('waste_pages'),+ convertedClients: get('converted_agents'),+ convertedClientsPrev: get('converted_agents_prev'),+ malformed: get('malformed'),+ malformedPrev: get('malformed_prev'),+ llmsTxtFetches: get('llms_txt_fetches'),+ excludedRequests: get('excluded_requests'),+ }+}++export const changePct = (current: number, previous: number | null): number | null => {+ if (previous === null || previous <= 0) {+ return null+ }+ return Math.round(((current - previous) / previous) * 100)+}++const contentGapFix = (path: string): string[] => [+ path+ ? `Publish a page at ${path}, or redirect it if the content moved`+ : 'Publish the requested page, or redirect it if the content moved',+ 'Redirect the other requested URLs listed below to that page',+ 'List the page in llms.txt and link its markdown version',+]++const WASTE_FIX = ['List markdown versions in llms.txt', 'Advertise markdown versions with an HTTP Link header']++const MALFORMED_FIX = [+ 'Check whether your own pages link to unfilled URL templates',+ 'Redirect the malformed paths to the closest valid page',+]++export const parseIssuesResponse = (columns: string[] | undefined, results: unknown[][] | undefined): AgentIssue[] => {+ const keyIdx = columnIndex(columns, 'intent_key')+ const pathIdx = columnIndex(columns, 'intent_path')+ const demandIdx = columnIndex(columns, 'demand')+ const demandPrevIdx = columnIndex(columns, 'demand_prev')+ const variantsIdx = columnIndex(columns, 'variants')+ const agentIdx = columnIndex(columns, 'top_agent')+ const firstSeenIdx = columnIndex(columns, 'first_seen')+ const lastSeenIdx = columnIndex(columns, 'last_seen')++ return (results ?? [])+ .filter(Array.isArray)+ .map((row): AgentIssue | null => {+ const key = str(row[keyIdx])+ if (!key) {+ return null+ }+ const intentPath = str(row[pathIdx])+ const demand = num(row[demandIdx])+ const demandPrev = num(row[demandPrevIdx])+ const variants = num(row[variantsIdx])+ return {+ key,+ type: 'content_gap',+ title: `Agents requested ${intentPath || '(unknown page)'}`,+ subtitle: `${variants} requested URL ${variants === 1 ? 'variant' : 'variants'}`,+ demand,+ demandPrev,+ changePct: changePct(demand, demandPrev),+ topAgent: str(row[agentIdx]) || null,+ firstSeen: str(row[firstSeenIdx]) || null,+ lastSeen: str(row[lastSeenIdx]) || null,+ recommendedFix: contentGapFix(intentPath),+ }+ })+ .filter((issue): issue is AgentIssue => issue !== null)+}++export const synthesizeAuxIssues = (overview: OverviewStats): AgentIssue[] => {+ const issues: AgentIssue[] = []+ if (overview.wasted > 0) {+ issues.push({+ key: 'waste:md-twins',+ type: 'waste',+ title: 'Agents fetch both HTML and markdown versions',+ subtitle: `${overview.wastePages} ${overview.wastePages === 1 ? 'page' : 'pages'} affected`,+ demand: overview.wasted,+ demandPrev: overview.wastedPrev,+ changePct: changePct(overview.wasted, overview.wastedPrev),+ topAgent: null,+ firstSeen: null,+ lastSeen: null,+ recommendedFix: WASTE_FIX,+ })+ }+ if (overview.malformed > 0) {+ issues.push({+ key: 'malformed:null-urls',+ type: 'malformed',+ title: 'Agents request malformed /null URLs',+ subtitle: 'The requested path contains an unfilled URL template value',+ demand: overview.malformed,+ demandPrev: overview.malformedPrev,+ changePct: changePct(overview.malformed, overview.malformedPrev),+ topAgent: null,+ firstSeen: null,+ lastSeen: null,+ recommendedFix: MALFORMED_FIX,+ })+ }+ return issues+}++export const parseWhatAgentsRead = (columns: string[] | undefined, results: unknown[][] | undefined): PageRead[] => {+ const pageIdx = columnIndex(columns, 'page')+ const fetchesIdx = columnIndex(columns, 'fetches')+ const mdIdx = columnIndex(columns, 'md_fetches')+ const htmlIdx = columnIndex(columns, 'html_fetches')+ const pairedClientsIdx = columnIndex(columns, 'paired_clients')+ return (results ?? []).filter(Array.isArray).map((row) => ({+ page: str(row[pageIdx]),+ fetches: num(row[fetchesIdx]),+ mdFetches: num(row[mdIdx]),+ htmlFetches: num(row[htmlIdx]),+ pairedClients: num(row[pairedClientsIdx]),+ }))+}++export const parseNextHops = (columns: string[] | undefined, results: unknown[][] | undefined): NextHop[] => {+ const pathIdx = columnIndex(columns, 'next_path')+ const requestsIdx = columnIndex(columns, 'requests')+ const notFoundIdx = columnIndex(columns, 'not_found')+ return (results ?? []).filter(Array.isArray).map((row) => ({+ path: str(row[pathIdx]),+ requests: num(row[requestsIdx]),+ notFound: num(row[notFoundIdx]),+ }))+}++export const parseDemandRows = (columns: string[] | undefined, results: unknown[][] | undefined): DemandRow[] => {+ const pageIdx = columnIndex(columns, 'page')+ const hostIdx = columnIndex(columns, 'host')+ const pathIdx = columnIndex(columns, 'path')+ const demandIdx = columnIndex(columns, 'demand')+ return (results ?? []).filter(Array.isArray).map((row) => ({+ page: str(row[pageIdx]),+ host: str(row[hostIdx]),+ path: str(row[pathIdx]),+ demand: num(row[demandIdx]),+ }))+}++export const parseVariants = (columns: string[] | undefined, results: unknown[][] | undefined): IssueVariant[] => {+ const variantIdx = columnIndex(columns, 'variant')+ const demandIdx = columnIndex(columns, 'demand')+ const agentIdx = columnIndex(columns, 'top_agent')+ const firstSeenIdx = columnIndex(columns, 'first_seen')+ return (results ?? []).filter(Array.isArray).map((row) => ({+ variant: str(row[variantIdx]),+ demand: num(row[demandIdx]),+ topAgent: str(row[agentIdx]) || null,+ firstSeen: str(row[firstSeenIdx]) || null,+ }))+}++export const parseRequestAnatomy = (+ columns: string[] | undefined,+ results: unknown[][] | undefined+): RequestAnatomyRow[] => {+ const agentIdx = columnIndex(columns, 'agent')+ const requestsIdx = columnIndex(columns, 'requests')+ const requestedMdIdx = columnIndex(columns, 'requested_markdown')+ const retryIdx = columnIndex(columns, 'retry_pairs')+ const errorsIdx = columnIndex(columns, 'errors')+ return (results ?? []).filter(Array.isArray).map((row) => ({+ agent: str(row[agentIdx]) || 'Unclassified agent',+ requests: num(row[requestsIdx]),+ requestedMarkdown: num(row[requestedMdIdx]),+ retryPairs: num(row[retryIdx]),+ errors: num(row[errorsIdx]),+ }))+}++export const parseJourneySummary = (+ columns: string[] | undefined,+ results: unknown[][] | undefined+): JourneySummary => {+ const row = (results ?? [])[0]+ if (!Array.isArray(row)) {+ return EMPTY_JOURNEY_SUMMARY+ }+ const get = (name: string): number => {+ const idx = columnIndex(columns, name)+ return idx >= 0 ? num(row[idx]) : 0+ }+ return {+ totalJourneys: get('total_journeys'),+ medianPages: get('median_pages'),+ medianRequests: get('median_requests'),+ medianDurationSeconds: get('median_duration_seconds'),+ journeysWithErrors: get('journeys_with_errors'),+ }+}++export const parseJourneys = (columns: string[] | undefined, results: unknown[][] | undefined): JourneyRow[] => {+ const keyIdx = columnIndex(columns, 'journey_key')+ const startedIdx = columnIndex(columns, 'started')+ const agentIdx = columnIndex(columns, 'agent')+ const hostIdx = columnIndex(columns, 'host')+ const pagesIdx = columnIndex(columns, 'pages')+ const requestsIdx = columnIndex(columns, 'requests')+ const durationIdx = columnIndex(columns, 'duration_seconds')+ const errorsIdx = columnIndex(columns, 'errors')+ return (results ?? [])+ .filter(Array.isArray)+ .map((row): JourneyRow | null => {+ const journeyKey = str(row[keyIdx])+ if (!journeyKey) {+ return null+ }+ return {+ journeyKey,+ started: str(row[startedIdx]) || null,+ agent: str(row[agentIdx]) || 'Unclassified agent',+ host: str(row[hostIdx]),+ pages: num(row[pagesIdx]),+ requests: num(row[requestsIdx]),+ durationSeconds: num(row[durationIdx]),+ errors: num(row[errorsIdx]),+ }+ })+ .filter((journey): journey is JourneyRow => journey !== null)+}++const JOURNEY_TRANSITIONS: JourneyTransition[] = ['start', 'confirmed', 'sequential', 'parallel']++export const parseJourneyDetail = (columns: string[] | undefined, results: unknown[][] | undefined): JourneyStep[] => {+ const timestampIdx = columnIndex(columns, 'timestamp')+ const pathIdx = columnIndex(columns, 'path')+ const statusIdx = columnIndex(columns, 'status')+ const formatIdx = columnIndex(columns, 'format')+ const referrerIdx = columnIndex(columns, 'referrer')+ const transitionIdx = columnIndex(columns, 'transition')+ return (results ?? []).filter(Array.isArray).map((row) => {+ const transition = str(row[transitionIdx])+ return {+ timestamp: str(row[timestampIdx]) || null,+ path: str(row[pathIdx]),+ status: num(row[statusIdx]),+ format: str(row[formatIdx]),+ referrer: str(row[referrerIdx]),+ transition: (JOURNEY_TRANSITIONS.includes(transition as JourneyTransition)+ ? transition+ : 'sequential') as JourneyTransition,+ }+ })+}++const llmsTxtContentPath = (path: string): string => (path.endsWith('.md') ? path.slice(0, -3) || '/' : path)++export const llmsTxtLinkKey = (host: string | null, path: string): string =>+ `${host?.toLowerCase() ?? '*'}\n${llmsTxtContentPath(path)}`++export const parseLlmsTxtLinks = (input: string, baseUrl: string | null): Map<string, LlmsTxtLink> => {+ const links = new Map<string, LlmsTxtLink>()+ for (const rawLine of input.split('\n')) {+ const candidates = new Set<string>()+ for (const match of rawLine.matchAll(/\]\(\s*<?([^\s)>]+)>?(?:\s+['"][^'"]*['"])?\s*\)/g)) {+ candidates.add(match[1])+ }+ for (const match of rawLine.match(/https?:\/\/[^\s)<]+|\/[^\s)<]+/g) ?? []) {+ candidates.add(match)+ }+ for (const candidate of candidates) {+ try {+ if (candidate.startsWith('/') && !baseUrl) {+ const link = { host: null, path: candidate }+ links.set(llmsTxtLinkKey(link.host, link.path), link)+ continue+ }+ const parsedUrl = baseUrl ? new URL(candidate, baseUrl) : new URL(candidate)+ if (!['http:', 'https:'].includes(parsedUrl.protocol)) {+ continue+ }+ const link = { host: parsedUrl.host.toLowerCase(), path: parsedUrl.pathname || '/' }+ links.set(llmsTxtLinkKey(link.host, link.path), link)+ } catch {+ continue+ }+ }+ }+ return links+}++export const isDemandCovered = (row: DemandRow, links: Map<string, LlmsTxtLink>): boolean =>+ links.has(llmsTxtLinkKey(row.host, row.path)) || links.has(llmsTxtLinkKey(null, row.path))++export const summarizeDemandCoverage = (+ demandRows: DemandRow[],+ llmsTxtLinks: Map<string, LlmsTxtLink>+): DemandCoverage => {+ let listedPages = 0+ let totalDemand = 0+ let listedDemand = 0+ const observedHosts = new Set<string>()+ const listedHosts = new Set<string>()+ let hasWildcardLinks = false++ for (const link of llmsTxtLinks.values()) {+ if (link.host) {+ listedHosts.add(link.host.toLowerCase())+ } else {+ hasWildcardLinks = true+ }+ }+ for (const row of demandRows) {+ const host = row.host.toLowerCase()+ if (host) {+ observedHosts.add(host)+ }+ totalDemand += row.demand+ if (isDemandCovered(row, llmsTxtLinks)) {+ listedPages += 1+ listedDemand += row.demand+ }+ }++ const sortedObservedHosts = [...observedHosts].sort()+ return {+ listedPages,+ missingPages: demandRows.length - listedPages,+ totalDemand,+ listedDemand,+ observedHosts: sortedObservedHosts,+ hasMatchingHost: hasWildcardLinks || sortedObservedHosts.some((host) => listedHosts.has(host)),+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface agentAnalyticsLogicValues {+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ compareFilter: CompareFilter // webAnalyticsLogic+ conversionGoal: WebAnalyticsConversionGoal | null // webAnalyticsLogic+ dateFilter: DateFilterState // webAnalyticsLogic+ filterTestAccounts: boolean // webAnalyticsLogic+ webAnalyticsFilters: WebAnalyticsPropertyFilters // webAnalyticsLogic+ anyLoading: boolean+ contentGapIssues: AgentIssue[]+ contentGapIssuesError: string | null+ contentGapIssuesLoading: boolean+ demandCoverage: DemandCoverage+ demandRows: DemandRow[]+ demandRowsError: string | null+ demandRowsLoading: boolean+ includeCrawlers: boolean+ isLlmsTxtSourceSubmitting: boolean+ isLlmsTxtSourceValid: boolean+ issues: AgentIssue[]+ issuesPage: number+ journeyDetail: JourneyStep[]+ journeyDetailError: string | null+ journeyDetailLoading: boolean+ journeySummary: JourneySummary | null+ journeySummaryError: string | null+ journeySummaryLoading: boolean+ journeys: JourneyRow[]+ journeysError: string | null+ journeysLoading: boolean+ llmsTxtFetchError: string | null+ llmsTxtInput: string+ llmsTxtLinks: Map<string, LlmsTxtLink>+ llmsTxtLoadedUrl: string | null+ llmsTxtSource: LlmsTxtSourceForm+ llmsTxtSourceAllErrors: Record<string, any>+ llmsTxtSourceChanged: boolean+ llmsTxtSourceErrors: DeepPartialMap<LlmsTxtSourceForm, ValidationErrorType>+ llmsTxtSourceHasErrors: boolean+ llmsTxtSourceManualErrors: Record<string, any>+ llmsTxtSourceTouched: boolean+ llmsTxtSourceTouches: Record<string, boolean>+ llmsTxtSourceValidationErrors: DeepPartialMap<LlmsTxtSourceForm, ValidationErrorType>+ nextHops: NextHop[]+ nextHopsError: string | null+ nextHopsLoading: boolean+ overview: OverviewStats | null+ overviewError: string | null+ overviewLoading: boolean+ requestAnatomy: RequestAnatomyRow[]+ requestAnatomyError: string | null+ requestAnatomyLoading: boolean+ resultHasMore: Partial<Record<WebAgentAnalyticsQueryType, boolean>>+ resultPages: Partial<Record<WebAgentAnalyticsQueryType, number>>+ resultPaginations: Partial<Record<WebAgentAnalyticsQueryType, PaginationManual>>+ scope: AgentScope+ selectedIssue: AgentIssue | null+ selectedIssueKey: string | null+ selectedJourney: JourneyRow | null+ selectedJourneyKey: string | null+ showLlmsTxtSourceErrors: boolean+ topIssues: AgentIssue[]+ variants: IssueVariant[]+ variantsError: string | null+ variantsLoading: boolean+ view: AgentView+ whatAgentsRead: PageRead[]+ whatAgentsReadError: string | null+ whatAgentsReadLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface agentAnalyticsLogicActions {+ setWebAnalyticsCompareFilter: (compareFilter: CompareFilter) => {+ compareFilter: CompareFilter+ } // webAnalyticsLogic+ setWebAnalyticsConversionGoal: (conversionGoal: WebAnalyticsConversionGoal | null) => {+ conversionGoal: WebAnalyticsConversionGoal | null+ } // webAnalyticsLogic+ setWebAnalyticsCountryFilter: (countryCode: string | null) => {+ countryCode: string | null+ } // webAnalyticsLogic+ setWebAnalyticsDateInterval: (interval: IntervalType) => {+ interval: IntervalType+ } // webAnalyticsLogic+ setWebAnalyticsDates: (+ dateFrom: string | null,+ dateTo: string | null+ ) => {+ dateFrom: string | null+ dateTo: string | null+ } // webAnalyticsLogic+ setWebAnalyticsDatesAndInterval: (+ dateFrom: string | null,+ dateTo: string | null,+ interval: IntervalType+ ) => {+ dateFrom: string | null+ dateTo: string | null+ interval: IntervalType+ } // webAnalyticsLogic+ setWebAnalyticsDeviceTypeFilter: (deviceType: null | import('scenes/web-analytics/common').DeviceType) => {+ deviceType: null | import('scenes/web-analytics/common').DeviceType+ } // webAnalyticsLogic+ setWebAnalyticsDomainFilter: (domain: string | null) => {+ domain: string | null+ } // webAnalyticsLogic+ setWebAnalyticsFilterTestAccounts: (shouldFilterTestAccounts: boolean) => {+ shouldFilterTestAccounts: boolean+ } // webAnalyticsLogic+ setWebAnalyticsFilters: (webAnalyticsFilters: WebAnalyticsPropertyFilters) => {+ webAnalyticsFilters: WebAnalyticsPropertyFilters+ } // webAnalyticsLogic+ setWebAnalyticsReferrerFilter: (referrer: string | null) => {+ referrer: string | null+ } // webAnalyticsLogic+ loadDemandRows: () => {+ value: true+ }+ loadDemandRowsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadDemandRowsSuccess: (+ demandRows: DemandRow[],+ payload?: {+ value: true+ }+ ) => {+ demandRows: DemandRow[]+ payload?: {+ value: true+ }+ }+ loadIssues: () => {+ value: true+ }+ loadIssuesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadIssuesSuccess: (+ contentGapIssues: AgentIssue[],+ payload?: {+ value: true+ }+ ) => {+ contentGapIssues: AgentIssue[]+ payload?: {+ value: true+ }+ }+ loadJourneyDetail: () => {+ value: true+ }+ loadJourneyDetailFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadJourneyDetailSuccess: (+ journeyDetail: JourneyStep[],+ payload?: {+ value: true+ }+ ) => {+ journeyDetail: JourneyStep[]+ payload?: {+ value: true+ }+ }+ loadJourneySummary: () => {+ value: true+ }+ loadJourneySummaryFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadJourneySummarySuccess: (+ journeySummary: JourneySummary,+ payload?: {+ value: true+ }+ ) => {+ journeySummary: JourneySummary+ payload?: {+ value: true+ }+ }+ loadJourneys: () => {+ value: true+ }+ loadJourneysFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadJourneysSuccess: (+ journeys: JourneyRow[],+ payload?: {+ value: true+ }+ ) => {+ journeys: JourneyRow[]+ payload?: {+ value: true+ }+ }+ loadNextHops: () => {+ value: true+ }+ loadNextHopsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadNextHopsSuccess: (+ nextHops: NextHop[],+ payload?: {+ value: true+ }+ ) => {+ nextHops: NextHop[]+ payload?: {+ value: true+ }+ }+ loadOverview: () => {+ value: true+ }+ loadOverviewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOverviewSuccess: (+ overview: OverviewStats,+ payload?: {+ value: true+ }+ ) => {+ overview: OverviewStats+ payload?: {+ value: true+ }+ }+ loadRequestAnatomy: () => {+ value: true+ }+ loadRequestAnatomyFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRequestAnatomySuccess: (+ requestAnatomy: RequestAnatomyRow[],+ payload?: {+ value: true+ }+ ) => {+ requestAnatomy: RequestAnatomyRow[]+ payload?: {+ value: true+ }+ }+ loadVariants: () => {+ value: true+ }+ loadVariantsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadVariantsSuccess: (+ variants: IssueVariant[],+ payload?: {+ value: true+ }+ ) => {+ variants: IssueVariant[]+ payload?: {+ value: true+ }+ }+ loadWhatAgentsRead: () => {+ value: true+ }+ loadWhatAgentsReadFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadWhatAgentsReadSuccess: (+ whatAgentsRead: PageRead[],+ payload?: {+ value: true+ }+ ) => {+ whatAgentsRead: PageRead[]+ payload?: {+ value: true+ }+ }+ refresh: () => {+ value: true+ }+ resetLlmsTxtSource: (values?: LlmsTxtSourceForm) => {+ values?: LlmsTxtSourceForm+ }+ setLlmsTxtFromUrl: (+ content: string,+ url: string+ ) => {+ content: string+ url: string+ }+ setLlmsTxtSourceManualErrors: (errors: Record<string, any>) => {+ errors: Record<string, any>+ }+ setLlmsTxtSourceValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ }+ setLlmsTxtSourceValues: (values: DeepPartial<LlmsTxtSourceForm>) => {+ values: DeepPartial<LlmsTxtSourceForm>+ }+ setQueryError: (+ queryType: WebAgentAnalyticsQueryType,+ error: string | null+ ) => {+ error: string | null+ queryType: WebAgentAnalyticsQueryType+ }+ setResultHasMore: (+ queryType: WebAgentAnalyticsQueryType,+ hasMore: boolean+ ) => {+ hasMore: boolean+ queryType: WebAgentAnalyticsQueryType+ }+ setResultPage: (+ queryType: WebAgentAnalyticsQueryType,+ page: number+ ) => {+ page: number+ queryType: WebAgentAnalyticsQueryType+ }+ setScope: (scope: AgentScope) => {+ scope: AgentScope+ }+ setSelectedIssueKey: (key: string | null) => {+ key: string | null+ }+ setSelectedJourneyKey: (journeyKey: string | null) => {+ journeyKey: string | null+ }+ setView: (view: AgentView) => {+ view: AgentView+ }+ submitLlmsTxtSource: () => {+ value: boolean+ }+ submitLlmsTxtSourceFailure: (+ error: Error,+ errors: Record<string, any>+ ) => {+ error: Error+ errors: Record<string, any>+ }+ submitLlmsTxtSourceRequest: (llmsTxtSource: LlmsTxtSourceForm) => {+ llmsTxtSource: LlmsTxtSourceForm+ }+ submitLlmsTxtSourceSuccess: (llmsTxtSource: LlmsTxtSourceForm) => {+ llmsTxtSource: LlmsTxtSourceForm+ }+ touchLlmsTxtSourceField: (key: string) => {+ key: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface agentAnalyticsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ includeCrawlers: (scope: AgentScope) => boolean+ anyLoading: (+ overviewLoading: boolean,+ contentGapIssuesLoading: boolean,+ whatAgentsReadLoading: boolean,+ nextHopsLoading: boolean,+ demandRowsLoading: boolean,+ variantsLoading: boolean,+ requestAnatomyLoading: boolean,+ journeySummaryLoading: boolean,+ journeysLoading: boolean,+ journeyDetailLoading: boolean+ ) => boolean+ demandCoverage: (demandRows: DemandRow[], llmsTxtLinks: Map<string, LlmsTxtLink>) => DemandCoverage+ issuesPage: (resultPages: Partial<Record<WebAgentAnalyticsQueryType, number>>) => number+ issues: (contentGapIssues: AgentIssue[], overview: OverviewStats | null, issuesPage: number) => AgentIssue[]+ topIssues: (issues: AgentIssue[]) => AgentIssue[]+ selectedIssue: (issues: AgentIssue[], selectedIssueKey: string | null) => AgentIssue | null+ selectedJourney: (journeys: JourneyRow[], selectedJourneyKey: string | null) => JourneyRow | null+ resultPaginations: (+ resultPages: Partial<Record<WebAgentAnalyticsQueryType, number>>,+ resultHasMore: Partial<Record<WebAgentAnalyticsQueryType, boolean>>+ ) => Partial<Record<WebAgentAnalyticsQueryType, PaginationManual>>+ llmsTxtLinks: (llmsTxtInput: string, llmsTxtLoadedUrl: string | null) => Map<string, LlmsTxtLink>+ }+}++export type agentAnalyticsLogicType = MakeLogicType<+ agentAnalyticsLogicValues,+ agentAnalyticsLogicActions,+ Record<string, any>,+ agentAnalyticsLogicMeta+>++const OVERVIEW_ISSUE_COUNT = 4+const WHAT_AGENTS_READ_LIMIT = 5+const RESULT_PAGE_SIZE = 25+const FIRST_PAGE_ISSUE_RESULT_LIMIT = RESULT_PAGE_SIZE - 2+const JOURNEY_DETAIL_LIMIT = 50++const PAGINATED_QUERY_TYPES: readonly WebAgentAnalyticsQueryType[] = [+ WebAgentAnalyticsQueryType.Issues,+ WebAgentAnalyticsQueryType.Transitions,+ WebAgentAnalyticsQueryType.Demand,+ WebAgentAnalyticsQueryType.IssueVariants,+ WebAgentAnalyticsQueryType.RequestAnatomy,+ WebAgentAnalyticsQueryType.Journeys,+]++interface QueryOptions {+ intentKey?: string+ journeyKey?: string+ limit?: number+ offset?: number+}++const resultPage = (+ resultPages: Partial<Record<WebAgentAnalyticsQueryType, number>>,+ queryType: WebAgentAnalyticsQueryType+): number => resultPages[queryType] ?? 1++const paginatedQueryOptions = (+ resultPages: Partial<Record<WebAgentAnalyticsQueryType, number>>,+ queryType: WebAgentAnalyticsQueryType+): QueryOptions => {+ const page = resultPage(resultPages, queryType)+ if (queryType === WebAgentAnalyticsQueryType.Issues) {+ return page === 1+ ? { limit: FIRST_PAGE_ISSUE_RESULT_LIMIT, offset: 0 }+ : {+ limit: RESULT_PAGE_SIZE,+ offset: FIRST_PAGE_ISSUE_RESULT_LIMIT + (page - 2) * RESULT_PAGE_SIZE,+ }+ }+ return { limit: RESULT_PAGE_SIZE, offset: (page - 1) * RESULT_PAGE_SIZE }+}++export const agentAnalyticsLogic = kea<agentAnalyticsLogicType>([+ path(['products', 'webAnalytics', 'agentAnalyticsLogic']),+ connect(() => ({+ actions: [+ webAnalyticsLogic,+ [+ 'setCompareFilter as setWebAnalyticsCompareFilter',+ 'setDateInterval as setWebAnalyticsDateInterval',+ 'setDates as setWebAnalyticsDates',+ 'setDatesAndInterval as setWebAnalyticsDatesAndInterval',+ 'setShouldFilterTestAccounts as setWebAnalyticsFilterTestAccounts',+ 'setConversionGoal as setWebAnalyticsConversionGoal',+ 'setWebAnalyticsFilters',+ 'setDomainFilter as setWebAnalyticsDomainFilter',+ 'setDeviceTypeFilter as setWebAnalyticsDeviceTypeFilter',+ 'setCountryFilter as setWebAnalyticsCountryFilter',+ 'setReferrerFilter as setWebAnalyticsReferrerFilter',+ ],+ ],+ values: [+ webAnalyticsLogic,+ [+ 'dateFilter',+ 'shouldFilterTestAccounts as filterTestAccounts',+ 'compareFilter',+ 'conversionGoal',+ 'webAnalyticsFilters',+ ],+ teamLogic,+ ['currentTeam'],+ ],+ })),+ actions({+ setView: (view: AgentView) => ({ view }),+ setScope: (scope: AgentScope) => ({ scope }),+ setSelectedJourneyKey: (journeyKey: string | null) => ({ journeyKey }),+ setResultHasMore: (queryType: WebAgentAnalyticsQueryType, hasMore: boolean) => ({ queryType, hasMore }),+ setResultPage: (queryType: WebAgentAnalyticsQueryType, page: number) => ({ queryType, page }),+ setQueryError: (queryType: WebAgentAnalyticsQueryType, error: string | null) => ({ queryType, error }),+ setSelectedIssueKey: (key: string | null) => ({ key }),+ setLlmsTxtFromUrl: (content: string, url: string) => ({ content, url }),+ refresh: true,+ loadOverview: true,+ loadIssues: true,+ loadWhatAgentsRead: true,+ loadNextHops: true,+ loadDemandRows: true,+ loadVariants: true,+ loadRequestAnatomy: true,+ loadJourneySummary: true,+ loadJourneys: true,+ loadJourneyDetail: true,+ }),+ forms(({ actions, values }) => ({+ llmsTxtSource: {+ defaults: { url: '' } as LlmsTxtSourceForm,+ errors: validateLlmsTxtSource,+ submit: async ({ url }: LlmsTxtSourceForm) => {+ if (!values.currentTeam) {+ throw new Error('Select a project before loading llms.txt.')+ }+ const normalizedUrl = url.trim()+ const response = await webAnalyticsApi.webAnalyticsFetchLlmsTxt(String(values.currentTeam.id), {+ url: normalizedUrl,+ })+ actions.setLlmsTxtFromUrl(response.content, response.url)+ },+ },+ })),+ loaders(({ values, actions, cache }) => {+ const signalFor = (key: string): AbortSignal => {+ const abortController = new AbortController()+ cache.disposables.add(() => () => abortController.abort(), key, { pauseOnPageHidden: false })+ return abortController.signal+ }++ const runQuery = async (+ queryType: WebAgentAnalyticsQueryType,+ breakpoint: BreakPointFunction,+ opts: QueryOptions = {}+ ): Promise<{ columns?: string[]; results?: unknown[][] }> => {+ await breakpoint(300)+ const paginated = PAGINATED_QUERY_TYPES.includes(queryType)+ const { limit, offset, intentKey, journeyKey } = {+ ...(paginated ? paginatedQueryOptions(values.resultPages, queryType) : {}),+ ...opts,+ }+ const node: WebAgentAnalyticsQuery = {+ kind: NodeKind.WebAgentAnalyticsQuery,+ queryType,+ includeCrawlers: values.includeCrawlers,+ contentGrouping: WebAgentContentGrouping.Normalized,+ llmsTxtUrl: values.llmsTxtLoadedUrl ?? undefined,+ limit:+ limit ??+ (queryType === WebAgentAnalyticsQueryType.PageRequests ? WHAT_AGENTS_READ_LIMIT : undefined),+ offset,+ intentKey,+ journeyKey,+ dateRange: {+ date_from: values.dateFilter.dateFrom,+ date_to: values.dateFilter.dateTo,+ },+ interval: values.dateFilter.interval,+ compareFilter: values.compareFilter,+ conversionGoal: queryType === WebAgentAnalyticsQueryType.Overview ? values.conversionGoal : undefined,+ filterTestAccounts: values.filterTestAccounts,+ properties: values.webAnalyticsFilters,+ }+ let response+ try {+ response = await performQuery(node, { signal: signalFor(queryType) })+ } catch (error) {+ breakpoint()+ actions.setQueryError(queryType, queryErrorMessage(error))+ return {}+ }+ breakpoint()+ if (paginated) {+ actions.setResultHasMore(queryType, response.hasMore ?? false)+ }+ return {+ columns: response.columns as string[] | undefined,+ results: response.results as unknown[][] | undefined,+ }+ }++ return {+ overview: [+ null as OverviewStats | null,+ {+ loadOverview: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(WebAgentAnalyticsQueryType.Overview, breakpoint)+ return parseOverviewRow(columns, results)+ },+ },+ ],+ contentGapIssues: [+ [] as AgentIssue[],+ {+ loadIssues: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(WebAgentAnalyticsQueryType.Issues, breakpoint)+ return parseIssuesResponse(columns, results)+ },+ },+ ],+ whatAgentsRead: [+ [] as PageRead[],+ {+ loadWhatAgentsRead: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(WebAgentAnalyticsQueryType.PageRequests, breakpoint)+ return parseWhatAgentsRead(columns, results)+ },+ },+ ],+ nextHops: [+ [] as NextHop[],+ {+ loadNextHops: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(WebAgentAnalyticsQueryType.Transitions, breakpoint)+ return parseNextHops(columns, results)+ },+ },+ ],+ demandRows: [+ [] as DemandRow[],+ {+ loadDemandRows: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(WebAgentAnalyticsQueryType.Demand, breakpoint)+ return parseDemandRows(columns, results)+ },+ },+ ],+ variants: [+ [] as IssueVariant[],+ {+ loadVariants: async (_, breakpoint: BreakPointFunction) => {+ const { selectedIssueKey, selectedIssue } = values+ if (!selectedIssueKey || selectedIssue?.type !== 'content_gap') {+ return []+ }+ const { columns, results } = await runQuery(+ WebAgentAnalyticsQueryType.IssueVariants,+ breakpoint,+ { intentKey: selectedIssueKey }+ )+ return parseVariants(columns, results)+ },+ },+ ],+ requestAnatomy: [+ [] as RequestAnatomyRow[],+ {+ loadRequestAnatomy: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(+ WebAgentAnalyticsQueryType.RequestAnatomy,+ breakpoint+ )+ return parseRequestAnatomy(columns, results)+ },+ },+ ],+ journeySummary: [+ null as JourneySummary | null,+ {+ loadJourneySummary: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(+ WebAgentAnalyticsQueryType.JourneySummary,+ breakpoint+ )+ return parseJourneySummary(columns, results)+ },+ },+ ],+ journeys: [+ [] as JourneyRow[],+ {+ loadJourneys: async (_, breakpoint: BreakPointFunction) => {+ const { columns, results } = await runQuery(WebAgentAnalyticsQueryType.Journeys, breakpoint)+ return parseJourneys(columns, results)+ },+ },+ ],+ journeyDetail: [+ [] as JourneyStep[],+ {+ loadJourneyDetail: async (_, breakpoint: BreakPointFunction) => {+ const { selectedJourneyKey } = values+ if (!selectedJourneyKey) {+ return []+ }+ const { columns, results } = await runQuery(+ WebAgentAnalyticsQueryType.JourneyDetail,+ breakpoint,+ { journeyKey: selectedJourneyKey, limit: JOURNEY_DETAIL_LIMIT }+ )+ return parseJourneyDetail(columns, results)+ },+ },+ ],+ }+ }),+ reducers({+ view: [+ 'overview' as AgentView,+ {+ setView: (_, { view }) => view,+ },+ ],+ scope: [+ 'live' as AgentScope,+ {+ setScope: (_, { scope }) => scope,+ },+ ],+ resultHasMore: [+ {} as Partial<Record<WebAgentAnalyticsQueryType, boolean>>,+ {+ setResultHasMore: (state, { queryType, hasMore }) =>+ state[queryType] === hasMore ? state : { ...state, [queryType]: hasMore },+ },+ ],+ resultPages: [+ {} as Partial<Record<WebAgentAnalyticsQueryType, number>>,+ {+ refresh: () => ({}),+ setResultPage: (state, { queryType, page }) => ({ ...state, [queryType]: page }),+ setSelectedIssueKey: (state) => ({ ...state, [WebAgentAnalyticsQueryType.IssueVariants]: 1 }),+ },+ ],+ selectedIssueKey: [+ null as string | null,+ {+ setView: () => null,+ setSelectedIssueKey: (_, { key }) => key,+ },+ ],+ selectedJourneyKey: [+ null as string | null,+ {+ setView: () => null,+ setSelectedJourneyKey: (_, { journeyKey }) => journeyKey,+ },+ ],+ llmsTxtInput: [+ '',+ {+ setLlmsTxtFromUrl: (_, { content }) => content,+ submitLlmsTxtSourceFailure: () => '',+ },+ ],+ llmsTxtLoadedUrl: [+ null as string | null,+ {+ setLlmsTxtFromUrl: (_, { url }) => url,+ submitLlmsTxtSourceFailure: () => null,+ },+ ],+ llmsTxtFetchError: [+ null as string | null,+ {+ submitLlmsTxtSource: () => null,+ submitLlmsTxtSourceSuccess: () => null,+ submitLlmsTxtSourceFailure: (_, { error }) => llmsTxtFetchErrorMessage(error),+ },+ ],+ variants: [+ [] as IssueVariant[],+ {+ setSelectedIssueKey: () => [],+ },+ ],+ journeyDetail: [+ [] as JourneyStep[],+ {+ setSelectedJourneyKey: () => [],+ },+ ],+ overviewError: [+ null as string | null,+ {+ loadOverview: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.Overview),+ },+ ],+ contentGapIssuesError: [+ null as string | null,+ {+ loadIssues: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.Issues),+ },+ ],+ whatAgentsReadError: [+ null as string | null,+ {+ loadWhatAgentsRead: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.PageRequests),+ },+ ],+ nextHopsError: [+ null as string | null,+ {+ loadNextHops: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.Transitions),+ },+ ],+ demandRowsError: [+ null as string | null,+ {+ loadDemandRows: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.Demand),+ },+ ],+ variantsError: [+ null as string | null,+ {+ loadVariants: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.IssueVariants),+ },+ ],+ requestAnatomyError: [+ null as string | null,+ {+ loadRequestAnatomy: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.RequestAnatomy),+ },+ ],+ journeySummaryError: [+ null as string | null,+ {+ loadJourneySummary: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.JourneySummary),+ },+ ],+ journeysError: [+ null as string | null,+ {+ loadJourneys: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.Journeys),+ },+ ],+ journeyDetailError: [+ null as string | null,+ {+ loadJourneyDetail: () => null,+ setQueryError: errorForQuery(WebAgentAnalyticsQueryType.JourneyDetail),+ },+ ],+ }),+ selectors(({ actions }) => ({+ includeCrawlers: [(s) => [s.scope], (scope: AgentScope): boolean => scope === 'all'],+ anyLoading: [+ (s) => [+ s.overviewLoading,+ s.contentGapIssuesLoading,+ s.whatAgentsReadLoading,+ s.nextHopsLoading,+ s.demandRowsLoading,+ s.variantsLoading,+ s.requestAnatomyLoading,+ s.journeySummaryLoading,+ s.journeysLoading,+ s.journeyDetailLoading,+ ],+ (...loading: boolean[]): boolean => loading.some(Boolean),+ ],+ demandCoverage: [+ (s) => [s.demandRows, s.llmsTxtLinks],+ (demandRows: DemandRow[], llmsTxtLinks: Map<string, LlmsTxtLink>): DemandCoverage =>+ summarizeDemandCoverage(demandRows, llmsTxtLinks),+ ],+ issuesPage: [+ (s) => [s.resultPages],+ (resultPages: Partial<Record<WebAgentAnalyticsQueryType, number>>): number =>+ resultPage(resultPages, WebAgentAnalyticsQueryType.Issues),+ ],+ issues: [+ (s) => [s.contentGapIssues, s.overview, s.issuesPage],+ (contentGapIssues: AgentIssue[], overview: OverviewStats | null, issuesPage: number): AgentIssue[] =>+ [...(overview && issuesPage === 1 ? synthesizeAuxIssues(overview) : []), ...contentGapIssues].sort(+ (a, b) => b.demand - a.demand+ ),+ ],+ topIssues: [(s) => [s.issues], (issues: AgentIssue[]): AgentIssue[] => issues.slice(0, OVERVIEW_ISSUE_COUNT)],+ selectedIssue: [+ (s) => [s.issues, s.selectedIssueKey],+ (issues: AgentIssue[], selectedIssueKey: string | null): AgentIssue | null =>+ selectedIssueKey ? (issues.find((issue) => issue.key === selectedIssueKey) ?? null) : null,+ ],+ selectedJourney: [+ (s) => [s.journeys, s.selectedJourneyKey],+ (journeys: JourneyRow[], selectedJourneyKey: string | null): JourneyRow | null =>+ selectedJourneyKey+ ? (journeys.find((journey) => journey.journeyKey === selectedJourneyKey) ?? null)+ : null,+ ],+ resultPaginations: [+ (s) => [s.resultPages, s.resultHasMore],+ (+ resultPages: Partial<Record<WebAgentAnalyticsQueryType, number>>,+ resultHasMore: Partial<Record<WebAgentAnalyticsQueryType, boolean>>+ ): Partial<Record<WebAgentAnalyticsQueryType, PaginationManual>> =>+ Object.fromEntries(+ PAGINATED_QUERY_TYPES.map((queryType) => {+ const page = resultPage(resultPages, queryType)+ return [+ queryType,+ {+ controlled: true,+ useUrl: false,+ currentPage: page,+ pageSize: RESULT_PAGE_SIZE,+ onBackward: page > 1 ? () => actions.setResultPage(queryType, page - 1) : undefined,+ onForward: resultHasMore[queryType]+ ? () => actions.setResultPage(queryType, page + 1)+ : undefined,+ },+ ]+ })+ ),+ ],+ llmsTxtLinks: [+ (s) => [s.llmsTxtInput, s.llmsTxtLoadedUrl],+ (llmsTxtInput: string, llmsTxtLoadedUrl: string | null): Map<string, LlmsTxtLink> =>+ parseLlmsTxtLinks(llmsTxtInput, llmsTxtLoadedUrl),+ ],+ })),+ listeners(({ values, actions }) => {+ const refreshResults = (): void => actions.refresh()++ const replaceSearchParams = (mutate: (params: URLSearchParams) => void): void => {+ const params = new URLSearchParams(router.values.location.search)+ mutate(params)+ const query = params.toString()+ router.actions.replace(`${router.values.location.pathname}${query ? `?${query}` : ''}`)+ }++ return {+ refresh: () => {+ const { view } = values+ if (view === 'overview') {+ actions.loadOverview()+ actions.loadIssues()+ actions.loadWhatAgentsRead()+ actions.loadJourneySummary()+ } else if (view === 'journeys') {+ actions.loadJourneySummary()+ actions.loadJourneys()+ actions.loadNextHops()+ if (values.selectedJourneyKey) {+ actions.loadJourneyDetail()+ }+ } else if (view === 'issues') {+ actions.loadOverview()+ actions.loadIssues()+ } else if (view === 'readiness') {+ actions.loadOverview()+ actions.loadDemandRows()+ actions.loadRequestAnatomy()+ }+ },+ loadIssuesSuccess: () => {+ if (+ values.selectedIssueKey &&+ values.selectedIssue?.type === 'content_gap' &&+ !values.variants.length+ ) {+ actions.loadVariants()+ }+ },+ loadJourneysSuccess: () => {+ if (values.selectedJourneyKey && values.selectedJourney && !values.journeyDetail.length) {+ actions.loadJourneyDetail()+ }+ },+ setResultPage: ({ queryType }) => {+ const reload: Partial<Record<WebAgentAnalyticsQueryType, () => void>> = {+ [WebAgentAnalyticsQueryType.Issues]: actions.loadIssues,+ [WebAgentAnalyticsQueryType.Transitions]: actions.loadNextHops,+ [WebAgentAnalyticsQueryType.Demand]: actions.loadDemandRows,+ [WebAgentAnalyticsQueryType.IssueVariants]: actions.loadVariants,+ [WebAgentAnalyticsQueryType.RequestAnatomy]: actions.loadRequestAnatomy,+ [WebAgentAnalyticsQueryType.Journeys]: actions.loadJourneys,+ }+ reload[queryType]?.()+ },+ setSelectedIssueKey: ({ key }) => {+ if (key && values.selectedIssue?.type === 'content_gap') {+ actions.loadVariants()+ }+ replaceSearchParams((params) => {+ if (key) {+ params.set('issue', key)+ } else {+ params.delete('issue')+ }+ })+ },+ setSelectedJourneyKey: ({ journeyKey }) => {+ if (journeyKey) {+ actions.loadJourneyDetail()+ }+ replaceSearchParams((params) => {+ if (journeyKey) {+ params.set('journey', journeyKey)+ } else {+ params.delete('journey')+ }+ })+ },+ setView: [+ ({ view }) => {+ replaceSearchParams((params) => {+ params.set('view', view)+ params.delete('issue')+ params.delete('journey')+ })+ },+ refreshResults,+ ],+ setScope: [+ ({ scope }) => {+ replaceSearchParams((params) => {+ if (scope === 'all') {+ params.set('scope', scope)+ } else {+ params.delete('scope')+ }+ })+ },+ refreshResults,+ ],+ setWebAnalyticsCompareFilter: refreshResults,+ setWebAnalyticsDateInterval: refreshResults,+ setWebAnalyticsDates: refreshResults,+ setWebAnalyticsDatesAndInterval: refreshResults,+ setWebAnalyticsFilterTestAccounts: refreshResults,+ setWebAnalyticsConversionGoal: refreshResults,+ setWebAnalyticsFilters: refreshResults,+ setWebAnalyticsDomainFilter: refreshResults,+ setWebAnalyticsDeviceTypeFilter: refreshResults,+ setWebAnalyticsCountryFilter: refreshResults,+ setWebAnalyticsReferrerFilter: refreshResults,+ setLlmsTxtFromUrl: () => actions.loadOverview(),+ }+ }),+ afterMount(({ actions }) => {+ const { view, issue, journey, scope } = router.values.searchParams+ let refreshTriggered = false+ if (scope === 'all') {+ actions.setScope(scope)+ refreshTriggered = true+ }+ const deepLinkedView: AgentView | null =+ view === 'issues' || view === 'readiness' || view === 'journeys'+ ? view+ : typeof issue === 'string' && issue+ ? 'issues'+ : typeof journey === 'string' && journey+ ? 'journeys'+ : null+ if (deepLinkedView) {+ actions.setView(deepLinkedView)+ refreshTriggered = true+ }+ if (typeof issue === 'string' && issue) {+ actions.setSelectedIssueKey(issue)+ }+ if (typeof journey === 'string' && journey) {+ actions.setSelectedJourneyKey(journey)+ }+ if (!refreshTriggered) {+ actions.refresh()+ }+ }),+])diff --git a/products/web_analytics/package.json b/products/web_analytics/package.jsonindex ec0503e01185..694a2e3f1d8d 100644--- a/products/web_analytics/package.json+++ b/products/web_analytics/package.json@@ -5,6 +5,7 @@},"dependencies": {"kea": "catalog:",+ "kea-forms": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:","kea-subscriptions": "catalog:",diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 9309db194dd5..e456a9093eea 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -1694,6 +1694,11 @@"params": [],"scope": "project"},+ "webAnalyticsAgents": {+ "template": "/web/agents",+ "params": [],+ "scope": "project"+ },"webAnalyticsBotAnalytics": {"template": "/web/bots","params": [],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex 2ec2ddce0c6e..e5d43b055fac 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/actions/{actionId}\n/replay-vision/actions/{actionId}/edit\n/replay-vision/actions/{actionId}/runs/{runId}\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay-vision/{scannerId}/actions/new\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/actions/{actionId}\n/replay-vision/actions/{actionId}/edit\n/replay-vision/actions/{actionId}/runs/{runId}\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay-vision/{scannerId}/actions/new\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},