Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(web-analytics): add content autopilot workspace (#91088)

Jordan Mryyan29c2f17c0880
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 48863553e168..c19b4d558902 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5712,6 +5712,34 @@ snapshots:
hash: v1.k794b7964.5590e8e6497de2fefefa74cf07edd5f814a798deb8f7e5f0102a383f5e8ac6c8.ZvuooUS3qT6kDX8yW2_oQ1iDgO1DwVFMAWM517bhCHw
products-tracing-virtualizedspanlist--empty--light:
hash: v1.k794b7964.72ff685c9162da170263d416510a2cc5229c999691288c0b8038143000a40f15.ebvPm2A_7cN8QvjEaroudYEO1lp9qFUooW98MMcDBwY
+ products-web-analytics-content-autopilot-proposal-card--blocking-validation--dark:
+ hash: v1.k794b7964.8209374f939a22b6b211c2a21698ca15c4d6e18eda905eafc2c826539fa6a6f3.iZuZv-_mdz_BoFNzarvgUmumBKyNRvbdYMCWKcRQ5Bs
+ products-web-analytics-content-autopilot-proposal-card--blocking-validation--light:
+ hash: v1.k794b7964.5f57f98214e924ea35b8b0ee1246f9fb01bc73b6611fbb47d24673a32585a39f.aCi-hrNzgZ5o9NZWhs5Etj5X4ICf2vJyL3Zle7J3XnM
+ products-web-analytics-content-autopilot-proposal-card--ready-for-review--dark:
+ hash: v1.k794b7964.bf31cb5454ab3b5b5410666a11ba19a0c149cccd7ae57b56efb32035f98239c8.I25YeYWQe17NAqrEq81n-U3tR8dMX8usKI0RRXhc7vI
+ products-web-analytics-content-autopilot-proposal-card--ready-for-review--light:
+ hash: v1.k794b7964.2d32fe2131b0ecca9c82ad58d395e73e204ab96db50f814fea3797f241829965.ndis7gl5c6uNZ_5DhF8CiTwDrvHWrUHsSyp3db3PUL0
+ products-web-analytics-content-autopilot-workspace--active-run--dark:
+ hash: v1.k794b7964.e51cfbfc3a423eba287aaf1163748e16a97cea29e8930762d6dab49f63a02cd8.hOdOrO1ZlSf_W9yT7zwWxnEwXAsBezXHwPYrDAAe8KA
+ products-web-analytics-content-autopilot-workspace--active-run--light:
+ hash: v1.k794b7964.3c178c7659561d5ed484a45ec199507ff813fe318f11b3c298ebda28ee1cf2c6.VglouF0l0BcgYhRN2rnU5GcOLraPGLfWVxyde925pQI
+ products-web-analytics-content-autopilot-workspace--multiple-sites--dark:
+ hash: v1.k794b7964.075627fbb891aa2c4389a264858fc5eb95de795aadf79bef985e0d59c98779f6.E_AQXIFnTooveaFPZDRpvDzTpyxBYlS_MxfujssbM90
+ products-web-analytics-content-autopilot-workspace--multiple-sites--light:
+ hash: v1.k794b7964.8f13d0485b02c3cd59cb8943c112aacac38e38c7baa748bdf31c45ff47e56d02.cLk4Gq7iiI6Hi0IhYQWMj2heMo8i6GSg75rk_6GrXmI
+ products-web-analytics-content-autopilot-workspace--onboarding--dark:
+ hash: v1.k794b7964.cf94fd6e5af83fcf38742042c5611ba25bfefda32590f511a6c8e2a08d14dd7c.oE7i5mmGnUIJGySMCWU-h7zKk5toT5bm4JvuUC8C644
+ products-web-analytics-content-autopilot-workspace--onboarding--light:
+ hash: v1.k794b7964.4885036d8942b5c3cdb48c0a6a6614fea41afe1dcf25214d29d5973abde207bb.ZYYarqpsfM6PeMJvs0eie_yiLR0lvsXMo5FQvKn97vo
+ products-web-analytics-content-autopilot-workspace--ready-for-review--dark:
+ hash: v1.k794b7964.430ccb5f1ad7d6e1bb688c69221e2b60d8ad44bfc5b254c08b54bb90a8364189.Ksjd4WNULdqsgzy4Ye4txkdgFpmsINkvXRvlB_EtjhM
+ products-web-analytics-content-autopilot-workspace--ready-for-review--light:
+ hash: v1.k794b7964.d7aa367129b95dd772d6c0777d7ea4c9e359b0ff83ea83beab2b141d1da5b410.ApXV6wy_Fn5rBtnSE8JQfm-RZNvNzYGRe6MXHwVHahg
+ products-web-analytics-content-autopilot-workspace--site-settings--dark:
+ hash: v1.k794b7964.fc4421d5eb2f507adff62378c528a85f0d2afda601f5c64c427c01f8be0017e6.CwCi0RyySiohuekOKlnZxKFInJdQLJTSVx3upnSWs_g
+ products-web-analytics-content-autopilot-workspace--site-settings--light:
+ hash: v1.k794b7964.db7571e09c46c966f50fb87b8b34511803d4aef56c41faa405c2db039f17fa43.PUpkT3j7DpGmhBztUzWMk0vKk_5cA4nMK6WztMyXBRE
products-workflows-customerioimportmodal--all-steps-completed--dark:
hash: v1.k794b7964.da9d1ebf1836700267307224631511bd8fe3b9fb0906654a383e545e1c6f98f1.lPijIVizKAMxsGEVt28x0Y5izfhcfnbjbPhoHzriWFg
products-workflows-customerioimportmodal--all-steps-completed--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index aa884731785f..a86f86977f18 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -538,6 +538,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_AGENT_ANALYTICS: 'web-analytics-agent-analytics', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_BACK_NAVIGATION_RESET: 'web-analytics-back-navigation-reset', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_BOT_ANALYSIS: 'web-analytics-bot-analysis', // owner: @lricoy #team-web-analytics
+ WEB_ANALYTICS_CONTENT_AUTOPILOT: 'web-analytics-content-autopilot', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_CONVERSION_GOAL_PREAGG: 'web-analytics-conversion-goal-preagg', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_DRAG_TO_ZOOM: 'web-analytics-drag-to-zoom', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_EMPTY_ONBOARDING: 'web-analytics-empty-onboarding', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 579ce188efe3..33d27bfc1309 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -259,6 +259,7 @@ export const productRoutes: Record<string, [string, string]> = {
'VisualReviewSnapshotHistory',
'visualReviewSnapshotHistory',
],
+ '/web/content-autopilot': ['WebAnalytics', 'webAnalyticsContentAutopilot'],
'/heatmaps': ['Heatmaps', 'heatmaps'],
'/heatmaps/new': ['HeatmapNew', 'heatmapNew'],
'/heatmaps/recording': ['HeatmapRecording', 'heatmapRecording'],
@@ -1546,6 +1547,7 @@ export const productUrls = {
webAnalyticsHealth: (): string => `/web/health`,
webAnalyticsLive: (): string => `/web/live`,
webAnalyticsBotAnalytics: (): string => `/web/bot-analytics`,
+ webAnalyticsContentAutopilot: (): string => `/web/content-autopilot`,
heatmaps: (params?: string): string =>
`/heatmaps${params ? `?${params.startsWith('?') ? params.slice(1) : params}` : ''}`,
heatmapNew: (params?: string): string =>
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
index 26bb65adc991..a5ad447ded8d 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx
@@ -38,6 +38,7 @@ import {
TileVisualizationOption,
WEB_ANALYTICS_DATA_COLLECTION_NODE_ID,
WebAnalyticsTile,
+ isContentAutopilotEnabled,
tabSplitIndicesMap,
} from 'scenes/web-analytics/common'
import { PageReports, PageReportsFilters } from 'scenes/web-analytics/PageReports'
@@ -60,6 +61,7 @@ import { InsightLogicProps, OnboardingStepKey, TeamPublicType, TeamType } from '
import { AgentAnalytics } from 'products/web_analytics/frontend/agent_analytics/AgentAnalytics'
import { AgentAnalyticsFilters } from 'products/web_analytics/frontend/agent_analytics/AgentAnalyticsFilters'
+import { ContentAutopilot } from 'products/web_analytics/frontend/contentAutopilot/ContentAutopilot'
import { BotAnalyticsFilters } from './BotAnalyticsFilters'
import { botAnalyticsLogic } from './botAnalyticsLogic'
@@ -652,6 +654,8 @@ const Filters = ({ tabs }: { tabs: JSX.Element }): JSX.Element | null => {
return <PagePerformanceFilters tabs={tabs} />
case ProductTab.AGENTS:
return <AgentAnalyticsFilters tabs={tabs} />
+ case ProductTab.CONTENT_AUTOPILOT:
+ return null
default:
return <WebAnalyticsFilters tabs={tabs} />
}
@@ -684,6 +688,10 @@ const MainContent = (): JSX.Element => {
return <AgentAnalytics />
}
+ if (productTab === ProductTab.CONTENT_AUTOPILOT) {
+ return <ContentAutopilot />
+ }
+
return <Tiles />
}
@@ -807,6 +815,29 @@ const agentAnalyticsTab = (
]
}
+const contentAutopilotTab = (
+ featureFlags: FeatureFlagsSet
+): { key: ProductTab; label: string | JSX.Element; link: string }[] => {
+ if (!isContentAutopilotEnabled(featureFlags)) {
+ return []
+ }
+
+ return [
+ {
+ key: ProductTab.CONTENT_AUTOPILOT,
+ label: (
+ <div className="flex items-center gap-1">
+ Content autopilot
+ <LemonTag type="completion" className="uppercase">
+ Alpha
+ </LemonTag>
+ </div>
+ ),
+ link: urls.webAnalyticsContentAutopilot(),
+ },
+ ]
+}
+
const WebAnalyticsSurveyModal = (): JSX.Element | null => {
const { surveyModalPath } = useValues(webAnalyticsLogic)
const { closeSurveyModal } = useActions(webAnalyticsLogic)
@@ -922,6 +953,7 @@ const WebAnalyticsTabs = (): JSX.Element => {
...botAnalyticsTab(featureFlags),
...pagePerformanceTab(featureFlags),
...agentAnalyticsTab(featureFlags),
+ ...contentAutopilotTab(featureFlags),
...healthTab(),
]}
sceneInset
diff --git a/frontend/src/scenes/web-analytics/common.ts b/frontend/src/scenes/web-analytics/common.ts
index 542f95c969cf..3f908952fcaf 100644
--- a/frontend/src/scenes/web-analytics/common.ts
+++ b/frontend/src/scenes/web-analytics/common.ts
@@ -2,7 +2,9 @@ import { BreakPointFunction } from 'kea'
import { LemonMenuItem } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
import { PostHogComDocsURL } from 'lib/lemon-ui/Link/Link'
+import { type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { getDefaultInterval } from 'lib/utils/dateFilters'
import { UnexpectedNeverError } from 'lib/utils/guards'
@@ -120,8 +122,13 @@ export enum ProductTab {
BOT_ANALYTICS = 'bots',
PAGE_PERFORMANCE = 'page-performance',
AGENTS = 'agents',
+ CONTENT_AUTOPILOT = 'content-autopilot',
}
+export const isContentAutopilotEnabled = (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE] &&
+ !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_CONTENT_AUTOPILOT]
+
export type DeviceType = 'Desktop' | 'Mobile'
export type WebVitalsPercentile = PropertyMathType.P75 | PropertyMathType.P90 | PropertyMathType.P99
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
index b9d70dbb4dd4..8546ee77f722 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
@@ -451,6 +451,17 @@ describe('webAnalyticsLogic URL restoration', () => {
expect(router.values.location.pathname.endsWith('/web')).toBe(true)
})
+ it('redirects off content autopilot when either alpha flag is disabled', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE], {
+ [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]: true,
+ })
+
+ router.actions.push('/web/content-autopilot')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname.endsWith('/web')).toBe(true)
+ })
+
it('defaults the bots tab to the last day when the URL carries no date', async () => {
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS], {
[FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS]: true,
@@ -477,6 +488,28 @@ describe('webAnalyticsLogic URL restoration', () => {
expect(router.values.searchParams[key]).toBe(expected)
})
+ it('opens content autopilot without carrying dashboard filters', async () => {
+ featureFlagLogic.actions.setFeatureFlags(
+ [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE, FEATURE_FLAGS.WEB_ANALYTICS_CONTENT_AUTOPILOT],
+ {
+ [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]: true,
+ [FEATURE_FLAGS.WEB_ANALYTICS_CONTENT_AUTOPILOT]: true,
+ }
+ )
+ logic.actions.setWebAnalyticsFilters([
+ {
+ type: PropertyFilterType.Session,
+ key: '$entry_utm_source',
+ operator: PropertyOperator.Exact,
+ value: ['google'],
+ },
+ ])
+ logic.actions.setProductTab(ProductTab.CONTENT_AUTOPILOT)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname.endsWith('/web/content-autopilot')).toBe(true)
+ expect(router.values.searchParams).toEqual({})
+ })
const FILTER_A = {
type: PropertyFilterType.Session as const,
key: '$entry_utm_source',
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index c35beda03927..e7a5dc68b1e4 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -118,6 +118,7 @@ import {
WebVitalsPercentile,
eventPropertiesToPathClean,
getWebAnalyticsBreakdownFilter,
+ isContentAutopilotEnabled,
loadPriorityMap,
personPropertiesToPathClean,
sessionPropertiesToPathClean,
@@ -3054,7 +3055,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
return []
}
- if (productTab === ProductTab.AGENTS) {
+ if ([ProductTab.AGENTS, ProductTab.CONTENT_AUTOPILOT].includes(productTab)) {
return []
}
@@ -3105,6 +3106,8 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
return urls.webAnalyticsHealth()
} else if (productTab === ProductTab.LIVE) {
return urls.webAnalyticsLive()
+ } else if (productTab === ProductTab.CONTENT_AUTOPILOT) {
+ return urls.webAnalyticsContentAutopilot()
} else if (productTab === ProductTab.BOT_ANALYTICS) {
// Bot tab maintains its own filter state in `botAnalyticsLogic`, so we serialize
// those filters here instead of `rawWebAnalyticsFilters` (which only describes the
@@ -3357,6 +3360,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
ProductTab.BOT_ANALYTICS,
ProductTab.PAGE_PERFORMANCE,
ProductTab.AGENTS,
+ ProductTab.CONTENT_AUTOPILOT,
].includes(productTab)
) {
return
@@ -3384,6 +3388,11 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
return
}
+ if (productTab === ProductTab.CONTENT_AUTOPILOT && !isContentAutopilotEnabled(values.featureFlags)) {
+ 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).
@@ -3403,13 +3412,17 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
}
} else if (
productTab !== ProductTab.AGENTS &&
+ productTab !== ProductTab.CONTENT_AUTOPILOT &&
!objectsEqual(nextFilters, values.rawWebAnalyticsFilters)
) {
actions.setWebAnalyticsFilters(nextFilters)
}
}
- const tabSerializesFilters = productTab !== ProductTab.LIVE && productTab !== ProductTab.HEALTH
+ const tabSerializesFilters =
+ productTab !== ProductTab.LIVE &&
+ productTab !== ProductTab.HEALTH &&
+ productTab !== ProductTab.CONTENT_AUTOPILOT
const shouldResetAbsentFilters =
!isInitialRestore && !!values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_BACK_NAVIGATION_RESET]
diff --git a/products/web_analytics/backend/content_autopilot/lifecycle.py b/products/web_analytics/backend/content_autopilot/lifecycle.py
index 7997f0f4f5b5..224b4d98ff49 100644
--- a/products/web_analytics/backend/content_autopilot/lifecycle.py
+++ b/products/web_analytics/backend/content_autopilot/lifecycle.py
@@ -46,17 +46,40 @@ def lock_proposal(team: Team, proposal_id: str) -> ContentAutopilotProposal:
raise ContentAutopilotLifecycleError("That proposal could not be found.") from error
+def lock_profile(
+ team_id: int, profile_id: str, *, missing_message: str = "That site could not be found."
+) -> ContentAutopilotSiteProfile:
+ try:
+ return (
+ ContentAutopilotSiteProfile.objects.for_team(team_id, canonical=True)
+ .select_for_update()
+ .get(id=profile_id, deleted=False)
+ )
+ except ContentAutopilotSiteProfile.DoesNotExist as error:
+ raise ContentAutopilotLifecycleError(missing_message) from error
+
+
+def delete_profile(*, team: Team, profile_id: str) -> ContentAutopilotSiteProfile:
+ team_id = canonical_team_id(team)
+ with transaction.atomic():
+ profile = lock_profile(team_id, profile_id)
+ now = timezone.now()
+ ContentAutopilotRun.objects.for_team(team_id, canonical=True).filter(
+ profile=profile, run_status__in=ACTIVE_RUN_STATUSES
+ ).update(
+ run_status=ContentAutopilotRun.RunStatus.CANCELED,
+ completed_at=now,
+ updated_at=now,
+ )
+ profile.deleted = True
+ profile.save(update_fields=["deleted", "updated_at"])
+ return profile
+
+
def start_run(*, team: Team, profile_id: str, triggered_by_id: int | None) -> ContentAutopilotRun:
team_id = canonical_team_id(team)
with transaction.atomic():
- try:
- profile = (
- ContentAutopilotSiteProfile.objects.for_team(team_id, canonical=True)
- .select_for_update()
- .get(id=profile_id)
- )
- except ContentAutopilotSiteProfile.DoesNotExist as error:
- raise ContentAutopilotLifecycleError("Select a site before starting a content run.") from error
+ profile = lock_profile(team_id, profile_id, missing_message="Select a site before starting a content run.")
if (
ContentAutopilotRun.objects.for_team(team_id, canonical=True)
diff --git a/products/web_analytics/backend/facade/content_autopilot.py b/products/web_analytics/backend/facade/content_autopilot.py
index 6c570b33b6fd..599d8515c63c 100644
--- a/products/web_analytics/backend/facade/content_autopilot.py
+++ b/products/web_analytics/backend/facade/content_autopilot.py
@@ -3,6 +3,7 @@ from products.web_analytics.backend.content_autopilot.lifecycle import (
MAX_PROPOSAL_MARKDOWN_CHARS,
ContentAutopilotLifecycleError,
cancel_run,
+ delete_profile,
edit_proposal,
regenerate_proposal,
reject_proposal,
@@ -21,6 +22,7 @@ __all__ = [
"ContentAutopilotLifecycleError",
"PublicUrlFetchError",
"cancel_run",
+ "delete_profile",
"discover_site",
"edit_proposal",
"export_proposal",
diff --git a/products/web_analytics/backend/migrations/0011_contentautopilotsiteprofile_deleted.py b/products/web_analytics/backend/migrations/0011_contentautopilotsiteprofile_deleted.py
new file mode 100644
index 000000000000..2594d8fdfc03
--- /dev/null
+++ b/products/web_analytics/backend/migrations/0011_contentautopilotsiteprofile_deleted.py
@@ -0,0 +1,30 @@
+# Generated by Django 5.2.17 on 2026-09-08 19:29
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1342_drop_cimd_blocklist_table"),
+ ("web_analytics", "0010_contentautopilotrun_content_auto_run_active"),
+ ]
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="contentautopilotsiteprofile",
+ name="content_auto_profile_team_domain",
+ ),
+ migrations.AddField(
+ model_name="contentautopilotsiteprofile",
+ name="deleted",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.AddConstraint(
+ model_name="contentautopilotsiteprofile",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("deleted", False)),
+ fields=("team", "domain"),
+ name="content_auto_profile_team_domain",
+ ),
+ ),
+ ]
diff --git a/products/web_analytics/backend/migrations/max_migration.txt b/products/web_analytics/backend/migrations/max_migration.txt
index a4ad2e2ab165..d39fd2b99d75 100644
--- a/products/web_analytics/backend/migrations/max_migration.txt
+++ b/products/web_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0010_contentautopilotrun_content_auto_run_active
+0011_contentautopilotsiteprofile_deleted
diff --git a/products/web_analytics/backend/models/content_autopilot.py b/products/web_analytics/backend/models/content_autopilot.py
index b72f40dbabe9..b68f5ea8d45d 100644
--- a/products/web_analytics/backend/models/content_autopilot.py
+++ b/products/web_analytics/backend/models/content_autopilot.py
@@ -44,6 +44,7 @@ class ContentAutopilotSiteProfile(TeamScopedRootMixin, UUIDModel):
content_boundaries = models.JSONField(default=list)
brand_rules = models.JSONField(default=list)
search_console_enabled = models.BooleanField(default=False)
+ deleted = models.BooleanField(default=False)
created_by_id = models.BigIntegerField(null=True, blank=True)
updated_by_id = models.BigIntegerField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
@@ -52,7 +53,11 @@ class ContentAutopilotSiteProfile(TeamScopedRootMixin, UUIDModel):
class Meta:
db_table = "posthog_contentautopilotsiteprofile"
constraints = [
- models.UniqueConstraint(fields=["team", "domain"], name="content_auto_profile_team_domain"),
+ models.UniqueConstraint(
+ fields=["team", "domain"],
+ condition=models.Q(deleted=False),
+ name="content_auto_profile_team_domain",
+ ),
]
diff --git a/products/web_analytics/backend/presentation/views/content_autopilot.py b/products/web_analytics/backend/presentation/views/content_autopilot.py
index d8dda4726aa7..c7d8e42afc74 100644
--- a/products/web_analytics/backend/presentation/views/content_autopilot.py
+++ b/products/web_analytics/backend/presentation/views/content_autopilot.py
@@ -29,6 +29,7 @@ from products.web_analytics.backend.facade.content_autopilot import (
ContentAutopilotLifecycleError,
PublicUrlFetchError,
cancel_run,
+ delete_profile,
discover_site,
edit_proposal,
export_proposal,
@@ -402,7 +403,7 @@ class ContentAutopilotExportResponseSerializer(serializers.Serializer):
class ContentAutopilotSiteProfileViewSet(ContentAutopilotViewSetMixin, viewsets.ModelViewSet):
serializer_class = ContentAutopilotSiteProfileSerializer
queryset = ContentAutopilotSiteProfile.objects.unscoped()
- http_method_names = ["get", "post", "patch", "head", "options"]
+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]
def get_throttles(self) -> list[BaseThrottle]:
if self.action == "discover":
@@ -415,7 +416,10 @@ class ContentAutopilotSiteProfileViewSet(ContentAutopilotViewSetMixin, viewsets.
def safely_get_queryset(
self, queryset: QuerySet[ContentAutopilotSiteProfile]
) -> QuerySet[ContentAutopilotSiteProfile]:
- return ContentAutopilotSiteProfile.objects.for_team(self.team_id).order_by("created_at")
+ return ContentAutopilotSiteProfile.objects.for_team(self.team_id).filter(deleted=False).order_by("created_at")
+
+ def perform_destroy(self, instance: ContentAutopilotSiteProfile) -> None:
+ delete_profile(team=self.team, profile_id=str(instance.id))
@validated_request(
request_serializer=ContentAutopilotSiteDiscoveryRequestSerializer,
@@ -440,7 +444,7 @@ class ContentAutopilotRunViewSet(ContentAutopilotViewSetMixin, viewsets.ReadOnly
queryset = ContentAutopilotRun.objects.unscoped()
def safely_get_queryset(self, queryset: QuerySet[ContentAutopilotRun]) -> QuerySet[ContentAutopilotRun]:
- queryset = ContentAutopilotRun.objects.for_team(self.team_id)
+ queryset = ContentAutopilotRun.objects.for_team(self.team_id).filter(profile__deleted=False)
if self.action == "list":
filters = self.validated_query_params(ContentAutopilotRunListQuerySerializer)
if profile_id := filters.get("profile_id"):
@@ -493,7 +497,7 @@ class ContentAutopilotProposalViewSet(ContentAutopilotViewSetMixin, viewsets.Rea
return ContentAutopilotProposalSerializer
def safely_get_queryset(self, queryset: QuerySet[ContentAutopilotProposal]) -> QuerySet[ContentAutopilotProposal]:
- queryset = ContentAutopilotProposal.objects.for_team(self.team_id)
+ queryset = ContentAutopilotProposal.objects.for_team(self.team_id).filter(run__profile__deleted=False)
if self.action == "list":
filters = self.validated_query_params(ContentAutopilotProposalListQuerySerializer)
if run_id := filters.get("run_id"):
diff --git a/products/web_analytics/backend/test/test_content_autopilot_api.py b/products/web_analytics/backend/test/test_content_autopilot_api.py
index 51ac54dff9a1..0086e5e491d0 100644
--- a/products/web_analytics/backend/test/test_content_autopilot_api.py
+++ b/products/web_analytics/backend/test/test_content_autopilot_api.py
@@ -130,6 +130,25 @@ class TestContentAutopilotAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["attr"], "domain")
+ def test_deleting_a_site_retires_it_and_its_history_and_frees_the_domain(self) -> None:
+ profile = create_content_autopilot_profile(self.team)
+ run = create_content_autopilot_run(self.team, profile)
+ create_content_autopilot_proposal(self.team, run)
+ kept_profile = create_content_autopilot_profile(self.team, domain="https://docs.example.com")
+
+ deleted = self.client.delete(self._profiles_url(f"{profile.id}/"))
+ profiles = self.client.get(self._profiles_url())
+ runs = self.client.get(self._runs_url())
+ proposals = self.client.get(self._proposals_url())
+ readded = self.client.post(self._profiles_url(), self._profile_payload(), format="json")
+
+ self.assertEqual(deleted.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertEqual([site["id"] for site in profiles.json()["results"]], [str(kept_profile.id)])
+ self.assertEqual(runs.json()["results"], [])
+ self.assertEqual(proposals.json()["results"], [])
+ self.assertEqual(readded.status_code, status.HTTP_201_CREATED, readded.json())
+ self.assertEqual(self.client.get(self._profiles_url(f"{profile.id}/")).status_code, status.HTTP_404_NOT_FOUND)
+
@patch("products.web_analytics.backend.presentation.views.content_autopilot.discover_site")
def test_discover_returns_editable_onboarding_defaults(self, discover_site: MagicMock) -> None:
discover_site.return_value = DISCOVERED_SITE
diff --git a/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py b/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py
index 1e00cf3c065e..5e34f324b339 100644
--- a/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py
+++ b/products/web_analytics/backend/test/test_content_autopilot_lifecycle.py
@@ -9,6 +9,7 @@ from products.web_analytics.backend.content_autopilot.lifecycle import (
MAX_PROPOSAL_MARKDOWN_CHARS,
ContentAutopilotLifecycleError,
cancel_run,
+ delete_profile,
edit_proposal,
regenerate_proposal,
reject_proposal,
@@ -58,9 +59,26 @@ class TestContentAutopilotLifecycle(BaseTest):
cancel_run(team=other_team, run_id=str(run.id))
with self.assertRaisesRegex(ContentAutopilotLifecycleError, "Select a site"):
start_run(team=other_team, profile_id=str(profile.id), triggered_by_id=self.user.id)
+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "could not be found"):
+ delete_profile(team=other_team, profile_id=str(profile.id))
proposal.refresh_from_db()
self.assertEqual(proposal.lifecycle_status, ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW)
+ def test_deleting_a_site_stops_its_active_run_and_retires_the_site(self) -> None:
+ profile = create_content_autopilot_profile(self.team)
+ run = start_run(team=self.team, profile_id=str(profile.id), triggered_by_id=self.user.id)
+
+ deleted = delete_profile(team=self.team, profile_id=str(profile.id))
+ run.refresh_from_db()
+
+ self.assertTrue(deleted.deleted)
+ self.assertEqual(run.run_status, ContentAutopilotRun.RunStatus.CANCELED)
+ self.assertIsNotNone(run.completed_at)
+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "Select a site"):
+ start_run(team=self.team, profile_id=str(profile.id), triggered_by_id=self.user.id)
+ with self.assertRaisesRegex(ContentAutopilotLifecycleError, "could not be found"):
+ delete_profile(team=self.team, profile_id=str(profile.id))
+
def test_each_site_has_its_own_active_run_boundary(self) -> None:
first_profile = create_content_autopilot_profile(self.team, search_console_enabled=True)
second_profile = create_content_autopilot_profile(self.team, domain="https://docs.example.com")
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx
new file mode 100644
index 000000000000..2bf8e3e596ec
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx
@@ -0,0 +1,116 @@
+import type { Meta, StoryFn } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import type {
+ ContentAutopilotProposalListApi,
+ ContentAutopilotRunApi,
+ ContentAutopilotSiteProfileApi,
+} from '../generated/api.schemas'
+import { ContentAutopilot } from './ContentAutopilot'
+import { ContentAutopilotSetup } from './ContentAutopilotSetup'
+import {
+ EXAMPLE_PROFILE,
+ EXAMPLE_PROPOSAL,
+ EXAMPLE_PROPOSAL_LIST,
+ EXAMPLE_RUN,
+ EXAMPLE_SECOND_PROFILE,
+} from './contentAutopilotStoryFixtures'
+
+const workspaceHandlers = ({
+ profiles,
+ runs = [],
+ proposals = [],
+}: {
+ profiles: ContentAutopilotSiteProfileApi[]
+ runs?: ContentAutopilotRunApi[]
+ proposals?: ContentAutopilotProposalListApi[]
+}): ReturnType<typeof mswDecorator> =>
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/web_analytics_content_autopilot_profiles/': () => [
+ 200,
+ { count: profiles.length, next: null, previous: null, results: profiles },
+ ],
+ '/api/projects/:team_id/web_analytics_content_autopilot_runs/': () => [
+ 200,
+ { count: runs.length, next: null, previous: null, results: runs },
+ ],
+ '/api/projects/:team_id/web_analytics_content_autopilot_proposals/': () => [
+ 200,
+ { count: proposals.length, next: null, previous: null, results: proposals },
+ ],
+ '/api/projects/:team_id/web_analytics_content_autopilot_proposals/:proposal_id/': () => [
+ 200,
+ EXAMPLE_PROPOSAL,
+ ],
+ },
+ post: {
+ '/api/projects/:team_id/web_analytics_content_autopilot_profiles/discover/': () => [
+ 200,
+ {
+ name: 'Example docs',
+ domain: 'https://docs.example.com',
+ source_urls: ['https://docs.example.com/sitemap.xml'],
+ content_boundaries: ['/docs'],
+ sitemap_detected: true,
+ warnings: [],
+ },
+ ],
+ },
+ })
+
+const meta: Meta<typeof ContentAutopilot> = {
+ title: 'Products/Web Analytics/Content autopilot/Workspace',
+ component: ContentAutopilot,
+ parameters: {
+ layout: 'fullscreen',
+ featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE, FEATURE_FLAGS.WEB_ANALYTICS_CONTENT_AUTOPILOT],
+ },
+}
+
+export default meta
+
+export const Onboarding: StoryFn<typeof ContentAutopilot> = () => (
+ <div className="p-6">
+ <ContentAutopilot />
+ </div>
+)
+Onboarding.decorators = [workspaceHandlers({ profiles: [] })]
+
+export const MultipleSites: StoryFn<typeof ContentAutopilot> = () => (
+ <div className="p-6">
+ <ContentAutopilot />
+ </div>
+)
+MultipleSites.decorators = [workspaceHandlers({ profiles: [EXAMPLE_PROFILE, EXAMPLE_SECOND_PROFILE] })]
+
+export const SiteSettings: StoryFn<typeof ContentAutopilotSetup> = () => (
+ <div className="p-6">
+ <ContentAutopilotSetup />
+ </div>
+)
+SiteSettings.decorators = [workspaceHandlers({ profiles: [EXAMPLE_PROFILE] })]
+
+export const ReadyForReview: StoryFn<typeof ContentAutopilot> = () => (
+ <div className="p-6">
+ <ContentAutopilot />
+ </div>
+)
+ReadyForReview.decorators = [
+ workspaceHandlers({ profiles: [EXAMPLE_PROFILE], runs: [EXAMPLE_RUN], proposals: [EXAMPLE_PROPOSAL_LIST] }),
+]
+
+export const ActiveRun: StoryFn<typeof ContentAutopilot> = () => (
+ <div className="p-6">
+ <ContentAutopilot />
+ </div>
+)
+ActiveRun.decorators = [
+ workspaceHandlers({
+ profiles: [EXAMPLE_PROFILE],
+ runs: [{ ...EXAMPLE_RUN, run_status: 'generating', completed_at: null }],
+ }),
+]
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.tsx
new file mode 100644
index 000000000000..eddd18ac8914
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.tsx
@@ -0,0 +1,208 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPlusSmall } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCard,
+ LemonCollapse,
+ LemonDialog,
+ LemonSelect,
+ LemonSkeleton,
+ LemonTag,
+} from '@posthog/lemon-ui'
+
+import { contentAutopilotLogic } from './contentAutopilotLogic'
+import { ContentAutopilotProposalDetail } from './ContentAutopilotProposalDetail'
+import { ContentAutopilotProposalSection } from './ContentAutopilotProposalSection'
+import { ContentAutopilotSetup } from './ContentAutopilotSetup'
+
+export const ContentAutopilot = (): JSX.Element => {
+ const {
+ profile,
+ activeRun,
+ siteRuns,
+ newContentProposals,
+ pageImprovementProposals,
+ onboardingOpen,
+ siteProfiles,
+ siteProfilesLoading,
+ runsLoading,
+ proposalsLoading,
+ runMutationLoading,
+ workspaceError,
+ workspaceErrors,
+ workspaceInitialized,
+ profileDataLoaded,
+ } = useValues(contentAutopilotLogic)
+ const { beginOnboarding, startRun, cancelRun, selectProfile, selectProposal, loadWorkspace } =
+ useActions(contentAutopilotLogic)
+ const loading = siteProfilesLoading || runsLoading || proposalsLoading
+ const lastRun = siteRuns[0]
+ const runDisabledReason = !profileDataLoaded
+ ? 'Wait for this site to finish loading'
+ : activeRun
+ ? 'A content run is already in progress for this site'
+ : undefined
+ const confirmCancelRun = (): void => {
+ if (!activeRun) {
+ return
+ }
+ LemonDialog.open({
+ title: 'Cancel this content run?',
+ description: 'PostHog will stop processing this run. Completed proposals will remain available.',
+ primaryButton: {
+ children: 'Cancel run',
+ status: 'danger',
+ onClick: () => cancelRun(activeRun.id),
+ },
+ secondaryButton: { children: 'Keep running' },
+ })
+ }
+
+ if (!workspaceInitialized) {
+ return <LemonSkeleton className="h-72 w-full" />
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h1 className="m-0">Content autopilot</h1>
+ <p className="m-0 mt-1 text-muted max-w-3xl">
+ Turn site, search, referral, and crawler signals into reviewable content. PostHog never
+ publishes or merges automatically.
+ </p>
+ </div>
+ {profile && !onboardingOpen ? (
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonSelect
+ aria-label="Site"
+ value={profile.id}
+ onChange={selectProfile}
+ options={siteProfiles.map((siteProfile) => ({
+ value: siteProfile.id,
+ label: siteProfile.name || siteProfile.domain,
+ }))}
+ />
+ <LemonButton type="secondary" icon={<IconPlusSmall />} onClick={beginOnboarding}>
+ Add site
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ icon={<IconPlusSmall />}
+ onClick={startRun}
+ loading={runMutationLoading}
+ disabledReason={runDisabledReason}
+ >
+ Create content
+ </LemonButton>
+ </div>
+ ) : null}
+ </div>
+
+ {workspaceError ? (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadWorkspace, loading }}>
+ Some content autopilot data could not be loaded. {workspaceError}
+ </LemonBanner>
+ ) : null}
+
+ {workspaceErrors.profiles && !profile ? (
+ <LemonCard hoverEffect={false} className="p-8 text-center">
+ <h2>Sites could not be loaded</h2>
+ <p className="text-muted">Try again before adding or changing a site.</p>
+ </LemonCard>
+ ) : onboardingOpen || !profile ? (
+ <ContentAutopilotSetup onboarding />
+ ) : (
+ <>
+ {!profile.search_console_enabled ? (
+ <LemonBanner type="warning">
+ Google Search Console is not enabled. Recommendations use available Web analytics data and
+ are labeled as lower confidence.
+ </LemonBanner>
+ ) : null}
+
+ {!profileDataLoaded ? (
+ <LemonSkeleton className="h-72 w-full" />
+ ) : (
+ <>
+ {activeRun ? (
+ <LemonCard hoverEffect={false} className="p-4 flex items-center justify-between gap-3">
+ <div>
+ <div className="flex items-center gap-2">
+ <h3 className="m-0">Researching content opportunities</h3>
+ <LemonTag type="completion">{activeRun.run_status}</LemonTag>
+ </div>
+ <p className="m-0 mt-1 text-muted">
+ PostHog is analyzing current data, ranking opportunities, and validating
+ drafts.
+ </p>
+ </div>
+ <LemonButton
+ type="secondary"
+ status="danger"
+ onClick={confirmCancelRun}
+ loading={runMutationLoading}
+ >
+ Cancel run
+ </LemonButton>
+ </LemonCard>
+ ) : lastRun?.run_status === 'failed' ? (
+ <LemonBanner type="error">
+ The latest run failed.{' '}
+ {lastRun.errors.map(({ message }) => message).join(' ') ||
+ 'Start another run to retry.'}
+ </LemonBanner>
+ ) : null}
+
+ {newContentProposals.length === 0 && pageImprovementProposals.length === 0 ? (
+ <LemonCard hoverEffect={false} className="p-8 text-center">
+ <h2>No proposals yet</h2>
+ <p className="text-muted max-w-xl mx-auto">
+ Start a run to research one new article and up to five focused page
+ improvements.
+ </p>
+ <LemonButton
+ type="primary"
+ onClick={startRun}
+ loading={runMutationLoading}
+ disabledReason={runDisabledReason}
+ >
+ Create content
+ </LemonButton>
+ </LemonCard>
+ ) : (
+ <>
+ <ContentAutopilotProposalSection
+ title="New content"
+ description="Original articles for topics people search for that do not have a dedicated page."
+ proposals={newContentProposals}
+ onReview={selectProposal}
+ />
+ <ContentAutopilotProposalSection
+ title="Page improvements"
+ description="Focused metadata, linking, and content changes."
+ proposals={pageImprovementProposals}
+ onReview={selectProposal}
+ />
+ </>
+ )}
+ </>
+ )}
+
+ <LemonCollapse
+ panels={[
+ {
+ key: 'settings',
+ header: `Settings for ${profile.name || profile.domain}`,
+ content: <ContentAutopilotSetup />,
+ },
+ ]}
+ />
+ </>
+ )}
+ <ContentAutopilotProposalDetail />
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalCard.stories.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalCard.stories.tsx
new file mode 100644
index 000000000000..5c553ce8ec29
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalCard.stories.tsx
@@ -0,0 +1,47 @@
+import type { Meta, StoryFn } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { ContentAutopilotProposalCard } from './ContentAutopilotProposalCard'
+import { EXAMPLE_PROPOSAL_LIST } from './contentAutopilotStoryFixtures'
+
+const meta: Meta<typeof ContentAutopilotProposalCard> = {
+ title: 'Products/Web Analytics/Content autopilot/Proposal card',
+ component: ContentAutopilotProposalCard,
+ parameters: {
+ layout: 'centered',
+ featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE, FEATURE_FLAGS.WEB_ANALYTICS_CONTENT_AUTOPILOT],
+ },
+}
+
+export default meta
+
+export const ReadyForReview: StoryFn<typeof ContentAutopilotProposalCard> = () => (
+ <div className="w-[640px]">
+ <ContentAutopilotProposalCard proposal={EXAMPLE_PROPOSAL_LIST} onReview={() => undefined} />
+ </div>
+)
+
+export const BlockingValidation: StoryFn<typeof ContentAutopilotProposalCard> = () => (
+ <div className="w-[640px]">
+ <ContentAutopilotProposalCard
+ proposal={{
+ ...EXAMPLE_PROPOSAL_LIST,
+ lifecycle_status: 'failed',
+ validation_report: {
+ passed: false,
+ checks: [
+ {
+ check_key: 'factual_sources',
+ label: 'Factual sourcing',
+ passed: false,
+ message: 'One factual claim has no public source.',
+ blocking: true,
+ },
+ ],
+ },
+ }}
+ onReview={() => undefined}
+ />
+ </div>
+)
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalCard.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalCard.tsx
new file mode 100644
index 000000000000..2860aedc4b07
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalCard.tsx
@@ -0,0 +1,49 @@
+import { LemonButton, LemonCard, LemonTag } from '@posthog/lemon-ui'
+
+import type { ContentAutopilotProposalListApi } from 'products/web_analytics/frontend/generated/api.schemas'
+
+export interface ContentAutopilotProposalCardProps {
+ proposal: ContentAutopilotProposalListApi
+ onReview: (proposalId: string) => void
+}
+
+const statusLabel: Record<ContentAutopilotProposalListApi['lifecycle_status'], string> = {
+ generating: 'Generating',
+ ready_for_review: 'Ready for review',
+ rejected: 'Rejected',
+ exported: 'Exported',
+ failed: 'Failed',
+}
+
+export const ContentAutopilotProposalCard = ({
+ proposal,
+ onReview,
+}: ContentAutopilotProposalCardProps): JSX.Element => {
+ const primaryEvidence = proposal.evidence[0]
+
+ return (
+ <LemonCard hoverEffect={false} className="p-4 flex flex-col gap-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <LemonTag type={proposal.validation_report.passed ? 'success' : 'danger'}>
+ {statusLabel[proposal.lifecycle_status]}
+ </LemonTag>
+ <span className="text-xs text-muted">{proposal.file_path}</span>
+ </div>
+ <div>
+ <h3 className="m-0">{proposal.title}</h3>
+ <p className="m-0 mt-1 text-muted">{proposal.target_query}</p>
+ </div>
+ {primaryEvidence ? (
+ <div className="rounded border p-3 bg-surface-secondary">
+ <div className="font-semibold">Why PostHog selected this</div>
+ <div className="text-sm mt-1">{primaryEvidence.explanation}</div>
+ </div>
+ ) : null}
+ <div className="flex justify-end mt-auto">
+ <LemonButton type="secondary" onClick={() => onReview(proposal.id)}>
+ Review proposal
+ </LemonButton>
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalDetail.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalDetail.tsx
new file mode 100644
index 000000000000..3098afc35775
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalDetail.tsx
@@ -0,0 +1,196 @@
+import { useActions, useValues } from 'kea'
+
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCollapse,
+ LemonDialog,
+ LemonModal,
+ LemonSkeleton,
+ LemonTag,
+ LemonTextArea,
+} from '@posthog/lemon-ui'
+
+import { contentAutopilotLogic } from './contentAutopilotLogic'
+
+export const ContentAutopilotProposalDetail = (): JSX.Element | null => {
+ const {
+ selectedProposal,
+ selectedProposalId,
+ proposedMarkdown,
+ proposalHasUnsavedChanges,
+ proposalMutationLoading,
+ exportedProposalLoading,
+ proposalActionReasons,
+ } = useValues(contentAutopilotLogic)
+ const { selectProposal, setProposedMarkdown, saveProposal, rejectProposal, regenerateProposal, exportProposal } =
+ useActions(contentAutopilotLogic)
+
+ if (!selectedProposalId) {
+ return null
+ }
+
+ const closeProposal = (): void => {
+ if (proposalHasUnsavedChanges) {
+ LemonDialog.open({
+ title: 'Discard unsaved changes?',
+ description: 'Your Markdown changes have not been saved.',
+ primaryButton: {
+ children: 'Discard changes',
+ status: 'danger',
+ onClick: () => selectProposal(null),
+ },
+ secondaryButton: { children: 'Keep editing' },
+ })
+ return
+ }
+ selectProposal(null)
+ }
+
+ if (!selectedProposal) {
+ return (
+ <LemonModal isOpen onClose={closeProposal} title="Loading proposal" width={960}>
+ <LemonSkeleton className="h-72 w-full" />
+ </LemonModal>
+ )
+ }
+
+ const confirmReject = (): void => {
+ LemonDialog.open({
+ title: 'Reject this proposal?',
+ description: 'The proposal will leave the review queue. This does not change your site.',
+ primaryButton: {
+ children: 'Reject proposal',
+ status: 'danger',
+ onClick: () => rejectProposal(selectedProposal.id),
+ },
+ secondaryButton: { children: 'Keep proposal' },
+ })
+ }
+
+ return (
+ <LemonModal
+ isOpen
+ onClose={closeProposal}
+ title={selectedProposal.title}
+ description={selectedProposal.target_query || selectedProposal.target_url}
+ width={960}
+ footer={
+ <div className="flex flex-wrap gap-2 justify-between w-full">
+ <div className="flex gap-2">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ onClick={confirmReject}
+ loading={proposalMutationLoading}
+ disabledReason={proposalActionReasons.reject}
+ >
+ Reject
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ onClick={() => regenerateProposal(selectedProposal.id)}
+ loading={proposalMutationLoading}
+ disabledReason={proposalActionReasons.regenerate}
+ >
+ Regenerate
+ </LemonButton>
+ </div>
+ <div className="flex gap-2">
+ <LemonButton
+ type="secondary"
+ onClick={() => exportProposal(selectedProposal.id)}
+ loading={exportedProposalLoading}
+ disabledReason={proposalActionReasons.exportMarkdown}
+ >
+ Export Markdown
+ </LemonButton>
+ </div>
+ </div>
+ }
+ >
+ <div className="flex flex-col gap-5">
+ {selectedProposal.evidence.length > 0 ? (
+ <section>
+ <h3>Why PostHog selected this</h3>
+ <div className="flex flex-col gap-2">
+ {selectedProposal.evidence.map((evidence) => (
+ <div
+ key={`${evidence.opportunity_kind}-${evidence.page_url}-${evidence.query}-${evidence.explanation}`}
+ className="rounded border p-3"
+ >
+ <LemonTag>{evidence.opportunity_kind.replaceAll('_', ' ')}</LemonTag>
+ <p className="mb-0 mt-2">{evidence.explanation}</p>
+ {evidence.query ? (
+ <div className="text-sm mt-2">Query: {evidence.query}</div>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ </section>
+ ) : null}
+
+ <section>
+ <h3>Validation</h3>
+ {!selectedProposal.validation_report.passed ? (
+ <LemonBanner type="error" className="mb-3">
+ You cannot export this proposal until its blocked checks pass. Edit the draft or regenerate
+ it.
+ </LemonBanner>
+ ) : null}
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ {selectedProposal.validation_report.checks.map((check) => (
+ <div key={check.check_key} className="rounded border p-3">
+ <div className="flex items-center justify-between gap-2">
+ <span className="font-semibold">{check.label}</span>
+ <LemonTag type={check.passed ? 'success' : check.blocking ? 'danger' : 'warning'}>
+ {check.passed ? 'Passed' : check.blocking ? 'Blocked' : 'Review'}
+ </LemonTag>
+ </div>
+ <div className="text-sm mt-1 text-muted">{check.message}</div>
+ </div>
+ ))}
+ </div>
+ </section>
+
+ <section>
+ <div className="flex items-center justify-between gap-2 mb-2">
+ <h3 className="m-0">Draft</h3>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => saveProposal(selectedProposal.id)}
+ loading={proposalMutationLoading}
+ disabledReason={proposalActionReasons.save}
+ >
+ Save changes
+ </LemonButton>
+ </div>
+ {selectedProposal.proposal_type === 'page_improvement' && selectedProposal.original_markdown ? (
+ <LemonCollapse
+ className="mb-3"
+ panels={[
+ {
+ key: 'original',
+ header: 'View original content',
+ content: (
+ <pre className="max-h-72 overflow-auto rounded border p-3 whitespace-pre-wrap">
+ {selectedProposal.original_markdown}
+ </pre>
+ ),
+ },
+ ]}
+ />
+ ) : null}
+ <LemonTextArea
+ aria-label="Proposal Markdown"
+ value={proposedMarkdown}
+ onChange={setProposedMarkdown}
+ minRows={18}
+ className="font-mono"
+ />
+ </section>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalSection.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalSection.tsx
new file mode 100644
index 000000000000..74e95e8589f1
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotProposalSection.tsx
@@ -0,0 +1,35 @@
+import type { ContentAutopilotProposalListApi } from 'products/web_analytics/frontend/generated/api.schemas'
+
+import { ContentAutopilotProposalCard } from './ContentAutopilotProposalCard'
+
+export interface ContentAutopilotProposalSectionProps {
+ title: string
+ description: string
+ proposals: ContentAutopilotProposalListApi[]
+ onReview: (proposalId: string) => void
+}
+
+export const ContentAutopilotProposalSection = ({
+ title,
+ description,
+ proposals,
+ onReview,
+}: ContentAutopilotProposalSectionProps): JSX.Element | null => {
+ if (proposals.length === 0) {
+ return null
+ }
+
+ return (
+ <section>
+ <div className="mb-3">
+ <h2 className="m-0">{title}</h2>
+ <p className="m-0 mt-1 text-muted">{description}</p>
+ </div>
+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
+ {proposals.map((proposal) => (
+ <ContentAutopilotProposalCard key={proposal.id} proposal={proposal} onReview={onReview} />
+ ))}
+ </div>
+ </section>
+ )
+}
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSetup.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSetup.tsx
new file mode 100644
index 000000000000..03956c4407a1
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSetup.tsx
@@ -0,0 +1,153 @@
+import { useActions, useValues } from 'kea'
+
+import { IconArrowLeft, IconArrowRight, IconTrash } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonCard, LemonDialog } from '@posthog/lemon-ui'
+
+import { contentAutopilotLogic } from './contentAutopilotLogic'
+import { ContentAutopilotSetupStepIndicator } from './ContentAutopilotSetupStepIndicator'
+import { ContentAutopilotSiteFields } from './ContentAutopilotSiteFields'
+import { ContentAutopilotSourceFields } from './ContentAutopilotSourceFields'
+
+export const ContentAutopilotSetup = ({ onboarding = false }: { onboarding?: boolean }): JSX.Element => {
+ const {
+ siteProfiles,
+ profile,
+ profileDraft,
+ onboardingStep,
+ discoveredSite,
+ discoveredSiteLoading,
+ savedProfileLoading,
+ deletedProfileLoading,
+ } = useValues(contentAutopilotLogic)
+ const { cancelOnboarding, deleteProfile, discoverSite, saveProfile, setOnboardingStep } =
+ useActions(contentAutopilotLogic)
+ const saveDisabledReason = !profileDraft.domain.trim()
+ ? 'Enter a site URL'
+ : splitHasNoValues(profileDraft.sourceUrls)
+ ? 'Add at least one sitemap or source URL'
+ : undefined
+ const confirmDeleteSite = (): void => {
+ if (!profile) {
+ return
+ }
+ LemonDialog.open({
+ title: `Delete ${profile.name || profile.domain}?`,
+ description:
+ 'PostHog stops any run in progress and removes this site and its proposals from the workspace. You can add the site again later.',
+ primaryButton: {
+ children: 'Delete site',
+ status: 'danger',
+ onClick: () => deleteProfile(profile.id),
+ },
+ secondaryButton: { children: 'Keep site' },
+ })
+ }
+
+ if (!onboarding) {
+ return (
+ <LemonCard hoverEffect={false} className="p-4">
+ <div className="mb-4">
+ <h2 className="m-0">Site settings</h2>
+ <p className="m-0 mt-1 text-muted">Change this site's sources and research boundaries.</p>
+ </div>
+ <div className="flex flex-col gap-5">
+ <ContentAutopilotSiteFields draft={profileDraft} />
+ <ContentAutopilotSourceFields draft={profileDraft} />
+ </div>
+ <div className="mt-4 flex items-center justify-between gap-2">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ icon={<IconTrash />}
+ onClick={confirmDeleteSite}
+ loading={deletedProfileLoading}
+ data-attr="content-autopilot-delete-site"
+ >
+ Delete site
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={saveProfile}
+ loading={savedProfileLoading}
+ disabledReason={saveDisabledReason}
+ >
+ Save settings
+ </LemonButton>
+ </div>
+ </LemonCard>
+ )
+ }
+
+ return (
+ <LemonCard hoverEffect={false} className="mx-auto w-full max-w-3xl p-6">
+ <ContentAutopilotSetupStepIndicator currentStep={onboardingStep} />
+ <div className="my-6 border-t" />
+
+ {onboardingStep === 'site' ? (
+ <>
+ <div className="mb-5">
+ <h2 className="m-0">Add a site</h2>
+ <p className="m-0 mt-1 text-muted">
+ PostHog will inspect the public site to fill in the details it can find.
+ </p>
+ </div>
+ <ContentAutopilotSiteFields draft={profileDraft} />
+ <div className="mt-6 flex justify-between">
+ {siteProfiles.length > 0 ? (
+ <LemonButton type="secondary" onClick={cancelOnboarding} disabled={discoveredSiteLoading}>
+ Cancel
+ </LemonButton>
+ ) : (
+ <span />
+ )}
+ <LemonButton
+ type="primary"
+ onClick={discoverSite}
+ loading={discoveredSiteLoading}
+ disabledReason={!profileDraft.domain.trim() ? 'Enter a site URL' : undefined}
+ sideIcon={<IconArrowRight />}
+ >
+ Detect site details
+ </LemonButton>
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="mb-5">
+ <h2 className="m-0">Review sources</h2>
+ <p className="m-0 mt-1 text-muted">Confirm where PostHog may research content.</p>
+ </div>
+ {discoveredSite ? (
+ <LemonBanner type={discoveredSite.sitemap_detected ? 'success' : 'warning'} className="mb-4">
+ {discoveredSite.sitemap_detected
+ ? `Detected ${discoveredSite.source_urls.length} sitemap${
+ discoveredSite.source_urls.length === 1 ? '' : 's'
+ }.`
+ : discoveredSite.warnings[0]}
+ </LemonBanner>
+ ) : null}
+ <ContentAutopilotSourceFields draft={profileDraft} />
+ <div className="mt-6 flex justify-between">
+ <LemonButton
+ type="secondary"
+ onClick={() => setOnboardingStep('site')}
+ icon={<IconArrowLeft />}
+ >
+ Back
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={saveProfile}
+ loading={savedProfileLoading}
+ disabledReason={saveDisabledReason}
+ >
+ Add site
+ </LemonButton>
+ </div>
+ </>
+ )}
+ </LemonCard>
+ )
+}
+
+const splitHasNoValues = (value: string): boolean => !value.split('\n').some((line) => line.trim())
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSetupStepIndicator.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSetupStepIndicator.tsx
new file mode 100644
index 000000000000..70654d9f97c1
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSetupStepIndicator.tsx
@@ -0,0 +1,42 @@
+import { IconCheck } from '@posthog/icons'
+
+import type { ContentAutopilotOnboardingStep } from './contentAutopilotLogic'
+
+const STEPS: { key: ContentAutopilotOnboardingStep; label: string }[] = [
+ { key: 'site', label: 'Site' },
+ { key: 'sources', label: 'Sources' },
+]
+
+export const ContentAutopilotSetupStepIndicator = ({
+ currentStep,
+}: {
+ currentStep: ContentAutopilotOnboardingStep
+}): JSX.Element => {
+ const currentIndex = STEPS.findIndex(({ key }) => key === currentStep)
+
+ return (
+ <ol className="flex items-center gap-2 p-0 m-0 list-none" aria-label="Setup progress">
+ {STEPS.map((step, index) => (
+ <li
+ key={step.key}
+ className="flex items-center gap-2"
+ aria-current={index === currentIndex ? 'step' : undefined}
+ >
+ <span
+ className={`flex size-6 items-center justify-center rounded-full text-xs font-medium ${
+ index < currentIndex
+ ? 'bg-success text-white'
+ : index === currentIndex
+ ? 'bg-primary-3000 text-white'
+ : 'bg-fill-secondary text-muted'
+ }`}
+ >
+ {index < currentIndex ? <IconCheck className="size-3" /> : index + 1}
+ </span>
+ <span className={index === currentIndex ? 'font-semibold' : 'text-muted'}>{step.label}</span>
+ {index < STEPS.length - 1 ? <span className="h-px w-8 bg-border" aria-hidden /> : null}
+ </li>
+ ))}
+ </ol>
+ )
+}
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSiteFields.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSiteFields.tsx
new file mode 100644
index 000000000000..0ae9f6a76f02
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSiteFields.tsx
@@ -0,0 +1,35 @@
+import { useActions } from 'kea'
+
+import { IconGlobe } from '@posthog/icons'
+import { LemonInput } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import type { ContentAutopilotProfileDraft } from './contentAutopilotLogic'
+import { contentAutopilotLogic } from './contentAutopilotLogic'
+
+export const ContentAutopilotSiteFields = ({ draft }: { draft: ContentAutopilotProfileDraft }): JSX.Element => {
+ const { setProfileDraft } = useActions(contentAutopilotLogic)
+
+ return (
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <LemonField.Pure label="Site URL" help="Paste a public page using the site’s final HTTPS address.">
+ <LemonInput
+ value={draft.domain}
+ onChange={(domain) => setProfileDraft({ domain })}
+ placeholder="https://example.com"
+ prefix={<IconGlobe />}
+ fullWidth
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Site name" help="Leave blank and PostHog will infer it.">
+ <LemonInput
+ value={draft.name}
+ onChange={(name) => setProfileDraft({ name })}
+ placeholder="Example docs"
+ fullWidth
+ />
+ </LemonField.Pure>
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSourceFields.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSourceFields.tsx
new file mode 100644
index 000000000000..2b5ffe36cf0b
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotSourceFields.tsx
@@ -0,0 +1,38 @@
+import { useActions } from 'kea'
+
+import { LemonCheckbox, LemonTextArea } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import type { ContentAutopilotProfileDraft } from './contentAutopilotLogic'
+import { contentAutopilotLogic } from './contentAutopilotLogic'
+
+export const ContentAutopilotSourceFields = ({ draft }: { draft: ContentAutopilotProfileDraft }): JSX.Element => {
+ const { setProfileDraft } = useActions(contentAutopilotLogic)
+
+ return (
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <LemonField.Pure label="Sitemaps and factual sources" help="One same-origin URL per line.">
+ <LemonTextArea
+ value={draft.sourceUrls}
+ onChange={(sourceUrls) => setProfileDraft({ sourceUrls })}
+ placeholder="https://example.com/sitemap.xml"
+ minRows={4}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Content boundaries" help="PostHog will only research paths with these prefixes.">
+ <LemonTextArea
+ value={draft.contentBoundaries}
+ onChange={(contentBoundaries) => setProfileDraft({ contentBoundaries })}
+ placeholder={'/docs\n/blog'}
+ minRows={4}
+ />
+ </LemonField.Pure>
+ <LemonCheckbox
+ checked={draft.searchConsoleEnabled}
+ onChange={(searchConsoleEnabled) => setProfileDraft({ searchConsoleEnabled })}
+ label="Use connected Google Search Console data"
+ />
+ </div>
+ )
+}
diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts
new file mode 100644
index 000000000000..0e209cc5c29d
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts
@@ -0,0 +1,418 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { initKeaTests } from '~/test/init'
+
+import {
+ webAnalyticsContentAutopilotProfilesCreate,
+ webAnalyticsContentAutopilotProfilesDestroy,
+ webAnalyticsContentAutopilotProfilesDiscover,
+ webAnalyticsContentAutopilotProfilesList,
+ webAnalyticsContentAutopilotProfilesPartialUpdate,
+ webAnalyticsContentAutopilotProposalsEdit,
+ webAnalyticsContentAutopilotProposalsExport,
+ webAnalyticsContentAutopilotProposalsList,
+ webAnalyticsContentAutopilotProposalsRegenerate,
+ webAnalyticsContentAutopilotProposalsReject,
+ webAnalyticsContentAutopilotProposalsRetrieve,
+ webAnalyticsContentAutopilotRunsCancel,
+ webAnalyticsContentAutopilotRunsList,
+ webAnalyticsContentAutopilotRunsStart,
+} from '../generated/api'
+import type { ContentAutopilotProposalListApi, ContentAutopilotRunApi } from '../generated/api.schemas'
+import { contentAutopilotLogic } from './contentAutopilotLogic'
+import {
+ EXAMPLE_PROFILE,
+ EXAMPLE_PROPOSAL,
+ EXAMPLE_PROPOSAL_LIST,
+ EXAMPLE_RUN,
+ EXAMPLE_SECOND_PROFILE,
+} from './contentAutopilotStoryFixtures'
+
+jest.mock('../generated/api', () => ({
+ webAnalyticsContentAutopilotProfilesCreate: jest.fn(),
+ webAnalyticsContentAutopilotProfilesDestroy: jest.fn(),
+ webAnalyticsContentAutopilotProfilesDiscover: jest.fn(),
+ webAnalyticsContentAutopilotProfilesList: jest.fn(),
+ webAnalyticsContentAutopilotProfilesPartialUpdate: jest.fn(),
+ webAnalyticsContentAutopilotProposalsEdit: jest.fn(),
+ webAnalyticsContentAutopilotProposalsExport: jest.fn(),
+ webAnalyticsContentAutopilotProposalsList: jest.fn(),
+ webAnalyticsContentAutopilotProposalsRegenerate: jest.fn(),
+ webAnalyticsContentAutopilotProposalsReject: jest.fn(),
+ webAnalyticsContentAutopilotProposalsRetrieve: jest.fn(),
+ webAnalyticsContentAutopilotRunsCancel: jest.fn(),
+ webAnalyticsContentAutopilotRunsList: jest.fn(),
+ webAnalyticsContentAutopilotRunsStart: jest.fn(),
+}))
+
+jest.mock('lib/components/ExportButton/exporter', () => ({ downloadBlob: jest.fn() }))
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: { success: jest.fn(), error: jest.fn() },
+}))
+
+const mockProfilesCreate = jest.mocked(webAnalyticsContentAutopilotProfilesCreate)
+const mockProfilesDestroy = jest.mocked(webAnalyticsContentAutopilotProfilesDestroy)
+const mockProfilesList = jest.mocked(webAnalyticsContentAutopilotProfilesList)
+const mockProposalsEdit = jest.mocked(webAnalyticsContentAutopilotProposalsEdit)
+const mockProposalsList = jest.mocked(webAnalyticsContentAutopilotProposalsList)
+const mockProposalsRetrieve = jest.mocked(webAnalyticsContentAutopilotProposalsRetrieve)
+const mockRunsList = jest.mocked(webAnalyticsContentAutopilotRunsList)
+const mockRunsStart = jest.mocked(webAnalyticsContentAutopilotRunsStart)
+
+const paginated = <T>(results: T[]): { count: number; next: null; previous: null; results: T[] } => ({
+ count: results.length,
+ next: null,
+ previous: null,
+ results,
+})
+
+const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void } => {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+}
+
+describe('contentAutopilotLogic', () => {
+ let logic: ReturnType<typeof contentAutopilotLogic.build> | null
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ logic = null
+
+ mockProfilesList.mockResolvedValue(paginated([EXAMPLE_PROFILE]))
+ mockRunsList.mockResolvedValue(paginated([EXAMPLE_RUN]))
+ mockProposalsList.mockResolvedValue(paginated([EXAMPLE_PROPOSAL_LIST]))
+ mockProposalsRetrieve.mockResolvedValue(EXAMPLE_PROPOSAL)
+ mockRunsStart.mockResolvedValue({ ...EXAMPLE_RUN, run_status: 'pending' })
+ mockProfilesCreate.mockResolvedValue(EXAMPLE_SECOND_PROFILE)
+ mockProfilesDestroy.mockResolvedValue(undefined)
+ jest.mocked(webAnalyticsContentAutopilotProfilesDiscover).mockResolvedValue({
+ name: EXAMPLE_PROFILE.name ?? '',
+ domain: EXAMPLE_PROFILE.domain,
+ source_urls: EXAMPLE_PROFILE.source_urls,
+ content_boundaries: EXAMPLE_PROFILE.content_boundaries,
+ sitemap_detected: true,
+ warnings: [],
+ })
+ jest.mocked(webAnalyticsContentAutopilotProfilesPartialUpdate).mockResolvedValue(EXAMPLE_PROFILE)
+ mockProposalsEdit.mockResolvedValue(EXAMPLE_PROPOSAL)
+ jest.mocked(webAnalyticsContentAutopilotProposalsExport).mockResolvedValue({
+ filename: 'web-analytics.mdx',
+ markdown: EXAMPLE_PROPOSAL.proposed_markdown,
+ content_package: EXAMPLE_PROPOSAL.content_package,
+ })
+ jest.mocked(webAnalyticsContentAutopilotProposalsRegenerate).mockResolvedValue(EXAMPLE_PROPOSAL)
+ jest.mocked(webAnalyticsContentAutopilotProposalsReject).mockResolvedValue(EXAMPLE_PROPOSAL)
+ jest.mocked(webAnalyticsContentAutopilotRunsCancel).mockResolvedValue(EXAMPLE_RUN)
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ const mountWorkspace = async (): Promise<ReturnType<typeof contentAutopilotLogic.build>> => {
+ logic = contentAutopilotLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ return logic
+ }
+
+ it('sends typed run and profile payloads to the generated API clients', async () => {
+ const mountedLogic = await mountWorkspace()
+ const projectId = String(MOCK_DEFAULT_TEAM.id)
+
+ expect(mockProfilesList).toHaveBeenCalledWith(projectId, { limit: 100, offset: 0 })
+ expect(mockRunsList).toHaveBeenCalledWith(projectId, {
+ limit: 100,
+ offset: 0,
+ profile_id: EXAMPLE_PROFILE.id,
+ })
+ expect(mockProposalsList).toHaveBeenCalledWith(projectId, {
+ limit: 100,
+ offset: 0,
+ profile_id: EXAMPLE_PROFILE.id,
+ })
+
+ await expectLogic(mountedLogic, () => mountedLogic.actions.startRun()).toFinishAllListeners()
+
+ expect(mockRunsStart).toHaveBeenCalledWith(projectId, { profile_id: EXAMPLE_PROFILE.id })
+
+ mountedLogic.actions.beginOnboarding()
+ mountedLogic.actions.setProfileDraft({
+ name: 'Example blog',
+ domain: 'https://blog.example.com',
+ sourceUrls: 'https://blog.example.com/sitemap.xml',
+ contentBoundaries: '/blog',
+ brandRules: 'Use sentence case',
+ searchConsoleEnabled: false,
+ })
+
+ await expectLogic(mountedLogic, () => mountedLogic.actions.saveProfile()).toFinishAllListeners()
+
+ expect(mockProfilesCreate).toHaveBeenCalledWith(projectId, {
+ name: 'Example blog',
+ domain: 'https://blog.example.com',
+ source_urls: ['https://blog.example.com/sitemap.xml'],
+ content_boundaries: ['/blog'],
+ brand_rules: ['Use sentence case'],
+ search_console_enabled: false,
+ })
+ })
+
+ it('switches profiles and resets profile-specific review state', async () => {
+ mockProfilesList.mockResolvedValue(paginated([EXAMPLE_PROFILE, EXAMPLE_SECOND_PROFILE]))
+ const mountedLogic = await mountWorkspace()
+ mountedLogic.actions.selectProposal(EXAMPLE_PROPOSAL.id)
+ const pendingProposals = deferred<ReturnType<typeof paginated<ContentAutopilotProposalListApi>>>()
+ mockProposalsList.mockImplementationOnce(() => pendingProposals.promise)
+
+ mountedLogic.actions.selectProfile(EXAMPLE_SECOND_PROFILE.id)
+
+ expect(mountedLogic.values.profileDataLoaded).toBe(false)
+ expect(mountedLogic.values.siteRuns).toEqual([])
+ expect(mountedLogic.values.siteProposals).toEqual([])
+
+ pendingProposals.resolve(paginated([EXAMPLE_PROPOSAL_LIST]))
+ await expectLogic(mountedLogic).toFinishAllListeners()
+
+ expect(mountedLogic.values.profileDataLoaded).toBe(true)
+ expect(mountedLogic.values.profile?.id).toBe(EXAMPLE_SECOND_PROFILE.id)
+ expect(mountedLogic.values.profileDraft.domain).toBe(EXAMPLE_SECOND_PROFILE.domain)
+ expect(mountedLogic.values.selectedProposal).toBeNull()
+ expect(mockRunsList).toHaveBeenLastCalledWith(String(MOCK_DEFAULT_TEAM.id), {
+ limit: 100,
+ offset: 0,
+ profile_id: EXAMPLE_SECOND_PROFILE.id,
+ })
+ expect(mockProposalsList).toHaveBeenLastCalledWith(String(MOCK_DEFAULT_TEAM.id), {
+ limit: 100,
+ offset: 0,
+ profile_id: EXAMPLE_SECOND_PROFILE.id,
+ })
+ })
+
+ it('loads every page of a site history longer than one request', async () => {
+ const olderProposal = { ...EXAMPLE_PROPOSAL_LIST, id: '00000000-0000-4000-8000-000000000203' }
+ mockProposalsList
+ .mockResolvedValueOnce({
+ count: 2,
+ next: 'http://localhost/next',
+ previous: null,
+ results: [EXAMPLE_PROPOSAL_LIST],
+ })
+ .mockResolvedValueOnce({ count: 2, next: null, previous: null, results: [olderProposal] })
+
+ const mountedLogic = await mountWorkspace()
+
+ expect(mountedLogic.values.siteProposals.map(({ id }) => id)).toEqual([
+ EXAMPLE_PROPOSAL_LIST.id,
+ olderProposal.id,
+ ])
+ expect(mockProposalsList).toHaveBeenLastCalledWith(String(MOCK_DEFAULT_TEAM.id), {
+ limit: 100,
+ offset: 1,
+ profile_id: EXAMPLE_PROFILE.id,
+ })
+ })
+
+ it('returns to onboarding once the last site is deleted', async () => {
+ const mountedLogic = await mountWorkspace()
+ mockProfilesList.mockResolvedValue(paginated([]))
+
+ await expectLogic(mountedLogic, () =>
+ mountedLogic.actions.deleteProfile(EXAMPLE_PROFILE.id)
+ ).toFinishAllListeners()
+
+ expect(mockProfilesDestroy).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), EXAMPLE_PROFILE.id)
+ expect(mountedLogic.values.siteProfiles).toEqual([])
+ expect(mountedLogic.values.profile).toBeNull()
+ expect(mountedLogic.values.onboardingOpen).toBe(true)
+ })
+
+ it('ignores stale profile data when requests finish out of order', async () => {
+ mockProfilesList.mockResolvedValue(paginated([EXAMPLE_PROFILE, EXAMPLE_SECOND_PROFILE]))
+ const mountedLogic = await mountWorkspace()
+ const firstRunRequest = deferred<ReturnType<typeof paginated<ContentAutopilotRunApi>>>()
+ const secondRunRequest = deferred<ReturnType<typeof paginated<ContentAutopilotRunApi>>>()
+ const secondRun = { ...EXAMPLE_RUN, id: '00000000-0000-4000-8000-000000000302' }
+ mockRunsList
+ .mockImplementationOnce(() => firstRunRequest.promise)
+ .mockImplementationOnce(() => secondRunRequest.promise)
+
+ mountedLogic.actions.selectProfile(EXAMPLE_PROFILE.id)
+ mountedLogic.actions.selectProfile(EXAMPLE_SECOND_PROFILE.id)
+ secondRunRequest.resolve(paginated([secondRun]))
+ firstRunRequest.resolve(paginated([EXAMPLE_RUN]))
+ await expectLogic(mountedLogic).toFinishAllListeners()
+
+ expect(mountedLogic.values.profile?.id).toBe(EXAMPLE_SECOND_PROFILE.id)
+ expect(mountedLogic.values.runs).toEqual([secondRun])
+ })
+
+ it('groups the proposals returned for the selected site', async () => {
+ const newContent: ContentAutopilotProposalListApi = {
+ ...EXAMPLE_PROPOSAL_LIST,
+ id: '00000000-0000-4000-8000-000000000202',
+ proposal_type: 'new_content',
+ }
+ mockProposalsList.mockResolvedValue(paginated([EXAMPLE_PROPOSAL_LIST, newContent]))
+
+ const mountedLogic = await mountWorkspace()
+
+ expect(mountedLogic.values.siteProposals.map(({ id }) => id)).toEqual([EXAMPLE_PROPOSAL_LIST.id, newContent.id])
+ expect(mountedLogic.values.newContentProposals.map(({ id }) => id)).toEqual([newContent.id])
+ expect(mountedLogic.values.pageImprovementProposals.map(({ id }) => id)).toEqual([EXAMPLE_PROPOSAL_LIST.id])
+ })
+
+ it('polls while work is active and stops refreshing after it settles', async () => {
+ let pollWorkspace: (() => void) | undefined
+ const setIntervalSpy = jest
+ .spyOn(window, 'setInterval')
+ .mockImplementation((handler: Parameters<typeof window.setInterval>[0]) => {
+ pollWorkspace = handler as () => void
+ return 1
+ })
+ mockRunsList.mockResolvedValueOnce(paginated([{ ...EXAMPLE_RUN, run_status: 'generating' }]))
+ const mountedLogic = await mountWorkspace()
+ mockRunsList.mockClear()
+ mockProposalsList.mockClear()
+ let resolveRuns: ((value: ReturnType<typeof paginated<ContentAutopilotRunApi>>) => void) | undefined
+ mockRunsList.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveRuns = resolve
+ })
+ )
+
+ const pollExpectation = expectLogic(mountedLogic, () => pollWorkspace?.()).toFinishAllListeners()
+
+ expect(mockRunsList).toHaveBeenCalledTimes(1)
+ expect(mockProposalsList).toHaveBeenCalledTimes(1)
+ pollWorkspace?.()
+ await Promise.resolve()
+ expect(mockRunsList).toHaveBeenCalledTimes(1)
+ expect(mockProposalsList).toHaveBeenCalledTimes(1)
+
+ resolveRuns?.(paginated([EXAMPLE_RUN]))
+ await pollExpectation
+ expect(mountedLogic.values.activeRun).toBeNull()
+
+ mockRunsList.mockClear()
+ mockProposalsList.mockClear()
+ pollWorkspace?.()
+ await Promise.resolve()
+
+ expect(mockRunsList).not.toHaveBeenCalled()
+ expect(mockProposalsList).not.toHaveBeenCalled()
+ setIntervalSpy.mockRestore()
+ })
+
+ it('refreshes proposals after edits and pull-request delivery', async () => {
+ const mountedLogic = await mountWorkspace()
+ mockProposalsList.mockClear()
+
+ await expectLogic(mountedLogic, () =>
+ mountedLogic.actions.selectProposal(EXAMPLE_PROPOSAL.id)
+ ).toFinishAllListeners()
+ mountedLogic.actions.setProposedMarkdown('# Reviewed web analytics guide')
+ expect(mountedLogic.values.proposalHasUnsavedChanges).toBe(true)
+ await expectLogic(mountedLogic, () =>
+ mountedLogic.actions.saveProposal(EXAMPLE_PROPOSAL.id)
+ ).toFinishAllListeners()
+
+ expect(mockProposalsEdit).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), EXAMPLE_PROPOSAL.id, {
+ proposed_markdown: '# Reviewed web analytics guide',
+ content_package: EXAMPLE_PROPOSAL.content_package,
+ })
+ expect(mockProposalsList).toHaveBeenCalledTimes(1)
+ expect(mountedLogic.values.selectedProposalId).toBeNull()
+ })
+
+ it.each([
+ ['ready_for_review' as const, undefined, undefined, 'No unsaved changes', undefined],
+ [
+ 'failed' as const,
+ 'Only a proposal ready for review can be rejected',
+ undefined,
+ 'Only a proposal ready for review can be edited',
+ 'Only a proposal ready for review can be exported',
+ ],
+ [
+ 'rejected' as const,
+ 'Only a proposal ready for review can be rejected',
+ 'Only proposals ready for review or failed can be regenerated',
+ 'Only a proposal ready for review can be edited',
+ 'Only a proposal ready for review can be exported',
+ ],
+ [
+ 'generating' as const,
+ 'Only a proposal ready for review can be rejected',
+ 'Only proposals ready for review or failed can be regenerated',
+ 'Only a proposal ready for review can be edited',
+ 'Only a proposal ready for review can be exported',
+ ],
+ [
+ 'exported' as const,
+ 'Only a proposal ready for review can be rejected',
+ 'Only proposals ready for review or failed can be regenerated',
+ 'Only a proposal ready for review can be edited',
+ 'Only a proposal ready for review can be exported',
+ ],
+ ])(
+ 'only offers the proposal actions a %s proposal accepts',
+ async (lifecycleStatus, reject, regenerate, save, exportMarkdown) => {
+ mockProposalsRetrieve.mockResolvedValue({ ...EXAMPLE_PROPOSAL, lifecycle_status: lifecycleStatus })
+ const mountedLogic = await mountWorkspace()
+
+ await expectLogic(mountedLogic, () =>
+ mountedLogic.actions.selectProposal(EXAMPLE_PROPOSAL.id)
+ ).toFinishAllListeners()
+
+ expect(mountedLogic.values.proposalActionReasons).toEqual({
+ reject,
+ regenerate,
+ save,
+ exportMarkdown,
+ })
+ }
+ )
+
+ it('does not deliver Markdown that has not been saved', async () => {
+ const mountedLogic = await mountWorkspace()
+ await expectLogic(mountedLogic, () =>
+ mountedLogic.actions.selectProposal(EXAMPLE_PROPOSAL.id)
+ ).toFinishAllListeners()
+ mountedLogic.actions.setProposedMarkdown('# Unsaved draft')
+ silenceKeaLoadersErrors()
+
+ await expectLogic(mountedLogic, () =>
+ mountedLogic.actions.exportProposal(EXAMPLE_PROPOSAL.id)
+ ).toFinishAllListeners()
+ resumeKeaLoadersErrors()
+
+ expect(webAnalyticsContentAutopilotProposalsExport).not.toHaveBeenCalled()
+ })
+
+ it('keeps load failures distinct from an empty workspace and clears them on retry', async () => {
+ mockProfilesList.mockRejectedValueOnce({ detail: 'Site profiles are temporarily unavailable.' })
+ silenceKeaLoadersErrors()
+ const mountedLogic = await mountWorkspace()
+ resumeKeaLoadersErrors()
+
+ expect(mountedLogic.values.workspaceInitialized).toBe(true)
+ expect(mountedLogic.values.workspaceError).toBe('Site profiles are temporarily unavailable.')
+ expect(mountedLogic.values.siteProfiles).toEqual([])
+
+ mockProfilesList.mockResolvedValue(paginated([EXAMPLE_PROFILE]))
+ await expectLogic(mountedLogic, () => mountedLogic.actions.loadWorkspace()).toFinishAllListeners()
+
+ expect(mountedLogic.values.workspaceError).toBeNull()
+ expect(mountedLogic.values.profile?.id).toBe(EXAMPLE_PROFILE.id)
+ })
+})
diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts
new file mode 100644
index 000000000000..e73636bb2f77
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts
@@ -0,0 +1,988 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { downloadBlob } from 'lib/components/ExportButton/exporter'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import * as webAnalyticsApi from 'products/web_analytics/frontend/generated/api'
+import type {
+ ContentAutopilotExportResponseApi,
+ ContentAutopilotProposalApi,
+ ContentAutopilotProposalListApi,
+ ContentAutopilotRunApi,
+ ContentAutopilotSiteDiscoveryResponseApi,
+ ContentAutopilotSiteProfileApi,
+} from 'products/web_analytics/frontend/generated/api.schemas'
+
+export type ContentAutopilotOnboardingStep = 'site' | 'sources'
+export type ContentAutopilotWorkspaceResource = 'profiles' | 'runs' | 'proposals'
+export type ContentAutopilotProfileResource = 'runs' | 'proposals'
+export type ContentAutopilotWorkspaceErrors = Partial<Record<ContentAutopilotWorkspaceResource, string>>
+export type ContentAutopilotWorkspaceSettled = Record<ContentAutopilotWorkspaceResource, boolean>
+export type ContentAutopilotProfileDataSettled = Record<ContentAutopilotProfileResource, boolean>
+
+export interface ContentAutopilotProposalActionReasons {
+ reject?: string
+ regenerate?: string
+ save?: string
+ exportMarkdown?: string
+}
+
+export interface ContentAutopilotProfileDraft {
+ name: string
+ domain: string
+ sourceUrls: string
+ contentBoundaries: string
+ brandRules: string
+ searchConsoleEnabled: boolean
+}
+
+const EMPTY_PROFILE_DRAFT: ContentAutopilotProfileDraft = {
+ name: '',
+ domain: '',
+ sourceUrls: '',
+ contentBoundaries: '/',
+ brandRules: '',
+ searchConsoleEnabled: true,
+}
+
+const WORKSPACE_POLL_INTERVAL_MS = 10_000
+const WORKSPACE_PAGE_LIMIT = 100
+const EMPTY_WORKSPACE_SETTLED: ContentAutopilotWorkspaceSettled = {
+ profiles: false,
+ runs: false,
+ proposals: false,
+}
+const EMPTY_PROFILE_DATA_SETTLED: ContentAutopilotProfileDataSettled = {
+ runs: false,
+ proposals: false,
+}
+
+interface PaginatedResults<T> {
+ count: number
+ results: T[]
+}
+
+const fetchAllPages = async <T>(
+ loadPage: (offset: number, limit: number) => Promise<PaginatedResults<T>>
+): Promise<T[]> => {
+ const collected: T[] = []
+ for (;;) {
+ const page = await loadPage(collected.length, WORKSPACE_PAGE_LIMIT)
+ collected.push(...page.results)
+ if (page.results.length === 0 || collected.length >= page.count) {
+ return collected
+ }
+ }
+}
+
+const withoutWorkspaceError = (
+ errors: ContentAutopilotWorkspaceErrors,
+ resource: ContentAutopilotWorkspaceResource
+): ContentAutopilotWorkspaceErrors => {
+ const nextErrors = { ...errors }
+ delete nextErrors[resource]
+ return nextErrors
+}
+
+const splitLines = (value: string): string[] =>
+ value
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean)
+
+const draftFromProfile = (profile: ContentAutopilotSiteProfileApi): ContentAutopilotProfileDraft => ({
+ name: profile.name ?? '',
+ domain: profile.domain,
+ sourceUrls: profile.source_urls.join('\n'),
+ contentBoundaries: profile.content_boundaries.join('\n'),
+ brandRules: profile.brand_rules.join('\n'),
+ searchConsoleEnabled: profile.search_console_enabled ?? true,
+})
+
+const getErrorMessage = (error: unknown): string => {
+ if (error instanceof Error) {
+ return error.message
+ }
+ if (typeof error === 'object' && error !== null && 'detail' in error && typeof error.detail === 'string') {
+ return error.detail
+ }
+ return 'Something went wrong. Try again.'
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface contentAutopilotLogicValues {
+ currentTeamIdStrict: number | string // teamLogic
+ activeRun: ContentAutopilotRunApi | null
+ deletedProfile: string | null
+ deletedProfileLoading: boolean
+ discoveredSite: ContentAutopilotSiteDiscoveryResponseApi | null
+ discoveredSiteLoading: boolean
+ exportedProposal: ContentAutopilotExportResponseApi | null
+ exportedProposalLoading: boolean
+ newContentProposals: ContentAutopilotProposalListApi[]
+ onboardingOpen: boolean
+ onboardingStep: ContentAutopilotOnboardingStep
+ pageImprovementProposals: ContentAutopilotProposalListApi[]
+ profile: ContentAutopilotSiteProfileApi | null
+ profileDataLoaded: boolean
+ profileDataSettled: ContentAutopilotProfileDataSettled
+ profileDraft: ContentAutopilotProfileDraft
+ proposalActionReasons: ContentAutopilotProposalActionReasons
+ proposalDetail: ContentAutopilotProposalApi | null
+ proposalDetailLoading: boolean
+ proposalHasUnsavedChanges: boolean
+ proposalMutation: ContentAutopilotProposalApi | null
+ proposalMutationLoading: boolean
+ proposals: ContentAutopilotProposalListApi[]
+ proposalsLoading: boolean
+ proposedMarkdown: string
+ runMutation: ContentAutopilotRunApi | null
+ runMutationLoading: boolean
+ runs: ContentAutopilotRunApi[]
+ runsLoading: boolean
+ savedProfile: ContentAutopilotSiteProfileApi | null
+ savedProfileLoading: boolean
+ selectedProfileId: string | null
+ selectedProposal: ContentAutopilotProposalApi | null
+ selectedProposalId: string | null
+ siteProfiles: ContentAutopilotSiteProfileApi[]
+ siteProfilesLoading: boolean
+ siteProposals: ContentAutopilotProposalListApi[]
+ siteRuns: ContentAutopilotRunApi[]
+ workspaceError: string | null
+ workspaceErrors: ContentAutopilotWorkspaceErrors
+ workspaceInitialized: boolean
+ workspaceSettled: ContentAutopilotWorkspaceSettled
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface contentAutopilotLogicActions {
+ beginOnboarding: () => {
+ value: true
+ }
+ cancelOnboarding: () => {
+ value: true
+ }
+ cancelRun: (runId: string) => string
+ cancelRunFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ cancelRunSuccess: (
+ runMutation: ContentAutopilotRunApi,
+ payload?: string
+ ) => {
+ runMutation: ContentAutopilotRunApi
+ payload?: string
+ }
+ deleteProfile: (profileId: string) => string
+ deleteProfileFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ deleteProfileSuccess: (
+ deletedProfile: string,
+ payload?: string
+ ) => {
+ deletedProfile: string
+ payload?: string
+ }
+ discoverSite: () => any
+ discoverSiteFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ discoverSiteSuccess: (
+ discoveredSite: ContentAutopilotSiteDiscoveryResponseApi,
+ payload?: any
+ ) => {
+ discoveredSite: ContentAutopilotSiteDiscoveryResponseApi
+ payload?: any
+ }
+ exportProposal: (proposalId: string) => string
+ exportProposalFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ exportProposalSuccess: (
+ exportedProposal: ContentAutopilotExportResponseApi,
+ payload?: string
+ ) => {
+ exportedProposal: ContentAutopilotExportResponseApi
+ payload?: string
+ }
+ loadProposal: (proposalId: string) => string
+ loadProposalFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadProposalSuccess: (
+ proposalDetail: ContentAutopilotProposalApi,
+ payload?: string
+ ) => {
+ proposalDetail: ContentAutopilotProposalApi
+ payload?: string
+ }
+ loadProposals: () => {
+ value: true
+ }
+ loadProposalsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadProposalsSuccess: (
+ proposals: ContentAutopilotProposalListApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ proposals: ContentAutopilotProposalListApi[]
+ payload?: {
+ value: true
+ }
+ }
+ loadRuns: () => {
+ value: true
+ }
+ loadRunsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadRunsSuccess: (
+ runs: ContentAutopilotRunApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ runs: ContentAutopilotRunApi[]
+ payload?: {
+ value: true
+ }
+ }
+ loadSiteProfiles: () => {
+ value: true
+ }
+ loadSiteProfilesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSiteProfilesSuccess: (
+ siteProfiles: ContentAutopilotSiteProfileApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ siteProfiles: ContentAutopilotSiteProfileApi[]
+ payload?: {
+ value: true
+ }
+ }
+ loadWorkspace: () => {
+ value: true
+ }
+ regenerateProposal: (proposalId: string) => string
+ regenerateProposalFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ regenerateProposalSuccess: (
+ proposalMutation: ContentAutopilotProposalApi,
+ payload?: string
+ ) => {
+ proposalMutation: ContentAutopilotProposalApi
+ payload?: string
+ }
+ rejectProposal: (proposalId: string) => string
+ rejectProposalFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ rejectProposalSuccess: (
+ proposalMutation: ContentAutopilotProposalApi,
+ payload?: string
+ ) => {
+ proposalMutation: ContentAutopilotProposalApi
+ payload?: string
+ }
+ resetProfileDraft: (profileDraft: ContentAutopilotProfileDraft) => {
+ profileDraft: ContentAutopilotProfileDraft
+ }
+ saveProfile: () => any
+ saveProfileFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveProfileSuccess: (
+ savedProfile: ContentAutopilotSiteProfileApi,
+ payload?: any
+ ) => {
+ savedProfile: ContentAutopilotSiteProfileApi
+ payload?: any
+ }
+ saveProposal: (proposalId: string) => string
+ saveProposalFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveProposalSuccess: (
+ proposalMutation: ContentAutopilotProposalApi,
+ payload?: string
+ ) => {
+ proposalMutation: ContentAutopilotProposalApi
+ payload?: string
+ }
+ selectProfile: (profileId: string) => {
+ profileId: string
+ }
+ selectProposal: (proposalId: string | null) => {
+ proposalId: string | null
+ }
+ setOnboardingStep: (onboardingStep: ContentAutopilotOnboardingStep) => {
+ onboardingStep: ContentAutopilotOnboardingStep
+ }
+ setProfileDraft: (profileDraft: Partial<ContentAutopilotProfileDraft>) => {
+ profileDraft: Partial<ContentAutopilotProfileDraft>
+ }
+ setProposedMarkdown: (proposedMarkdown: string) => {
+ proposedMarkdown: string
+ }
+ startRun: () => any
+ startRunFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ startRunSuccess: (
+ runMutation: ContentAutopilotRunApi,
+ payload?: any
+ ) => {
+ runMutation: ContentAutopilotRunApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface contentAutopilotLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ profile: (
+ siteProfiles: ContentAutopilotSiteProfileApi[],
+ selectedProfileId: string | null
+ ) => ContentAutopilotSiteProfileApi | null
+ siteRuns: (runs: ContentAutopilotRunApi[]) => ContentAutopilotRunApi[]
+ siteProposals: (proposals: ContentAutopilotProposalListApi[]) => ContentAutopilotProposalListApi[]
+ activeRun: (siteRuns: ContentAutopilotRunApi[]) => ContentAutopilotRunApi | null
+ selectedProposal: (
+ proposalDetail: ContentAutopilotProposalApi | null,
+ selectedProposalId: string | null
+ ) => ContentAutopilotProposalApi | null
+ proposalHasUnsavedChanges: (
+ selectedProposal: ContentAutopilotProposalApi | null,
+ proposedMarkdown: string
+ ) => boolean
+ newContentProposals: (siteProposals: ContentAutopilotProposalListApi[]) => ContentAutopilotProposalListApi[]
+ pageImprovementProposals: (
+ siteProposals: ContentAutopilotProposalListApi[]
+ ) => ContentAutopilotProposalListApi[]
+ workspaceInitialized: (workspaceSettled: ContentAutopilotWorkspaceSettled) => boolean
+ profileDataLoaded: (profileDataSettled: ContentAutopilotProfileDataSettled) => boolean
+ proposalActionReasons: (
+ selectedProposal: ContentAutopilotProposalApi | null,
+ proposalHasUnsavedChanges: boolean,
+ proposalDetailLoading: boolean,
+ proposalMutationLoading: boolean,
+ exportedProposalLoading: boolean
+ ) => ContentAutopilotProposalActionReasons
+ workspaceError: (workspaceErrors: Partial<Record<ContentAutopilotWorkspaceResource, string>>) => string | null
+ }
+}
+
+export type contentAutopilotLogicType = MakeLogicType<
+ contentAutopilotLogicValues,
+ contentAutopilotLogicActions,
+ Record<string, any>,
+ contentAutopilotLogicMeta
+>
+
+export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
+ path(['products', 'webAnalytics', 'contentAutopilot', 'contentAutopilotLogic']),
+ connect(() => ({ values: [teamLogic, ['currentTeamIdStrict']] })),
+ actions({
+ loadWorkspace: true,
+ loadSiteProfiles: true,
+ loadRuns: true,
+ loadProposals: true,
+ beginOnboarding: true,
+ cancelOnboarding: true,
+ selectProfile: (profileId: string) => ({ profileId }),
+ setOnboardingStep: (onboardingStep: ContentAutopilotOnboardingStep) => ({ onboardingStep }),
+ resetProfileDraft: (profileDraft: ContentAutopilotProfileDraft) => ({ profileDraft }),
+ setProfileDraft: (profileDraft: Partial<ContentAutopilotProfileDraft>) => ({ profileDraft }),
+ selectProposal: (proposalId: string | null) => ({ proposalId }),
+ setProposedMarkdown: (proposedMarkdown: string) => ({ proposedMarkdown }),
+ }),
+ reducers({
+ profileDraft: [
+ EMPTY_PROFILE_DRAFT,
+ {
+ resetProfileDraft: (_, { profileDraft }) => profileDraft,
+ setProfileDraft: (state, { profileDraft }) => ({ ...state, ...profileDraft }),
+ },
+ ],
+ selectedProfileId: [
+ null as string | null,
+ {
+ selectProfile: (_, { profileId }) => profileId,
+ saveProfileSuccess: (_, { savedProfile }) => savedProfile.id,
+ deleteProfileSuccess: () => null,
+ },
+ ],
+ onboardingOpen: [
+ false,
+ {
+ beginOnboarding: () => true,
+ cancelOnboarding: () => false,
+ saveProfileSuccess: () => false,
+ },
+ ],
+ onboardingStep: [
+ 'site' as ContentAutopilotOnboardingStep,
+ {
+ beginOnboarding: () => 'site',
+ setOnboardingStep: (_, { onboardingStep }) => onboardingStep,
+ discoverSiteSuccess: () => 'sources',
+ },
+ ],
+ selectedProposalId: [
+ null as string | null,
+ {
+ selectProposal: (_, { proposalId }) => proposalId,
+ },
+ ],
+ proposedMarkdown: [
+ '',
+ {
+ setProposedMarkdown: (_, { proposedMarkdown }) => proposedMarkdown,
+ },
+ ],
+ workspaceSettled: [
+ EMPTY_WORKSPACE_SETTLED,
+ {
+ loadWorkspace: () => EMPTY_WORKSPACE_SETTLED,
+ loadSiteProfilesSuccess: (state) => ({ ...state, profiles: true }),
+ loadSiteProfilesFailure: (state) => ({ ...state, profiles: true }),
+ loadRunsSuccess: (state) => ({ ...state, runs: true }),
+ loadRunsFailure: (state) => ({ ...state, runs: true }),
+ loadProposalsSuccess: (state) => ({ ...state, proposals: true }),
+ loadProposalsFailure: (state) => ({ ...state, proposals: true }),
+ },
+ ],
+ profileDataSettled: [
+ EMPTY_PROFILE_DATA_SETTLED,
+ {
+ selectProfile: () => EMPTY_PROFILE_DATA_SETTLED,
+ loadRunsSuccess: (state) => ({ ...state, runs: true }),
+ loadRunsFailure: (state) => ({ ...state, runs: true }),
+ loadProposalsSuccess: (state) => ({ ...state, proposals: true }),
+ loadProposalsFailure: (state) => ({ ...state, proposals: true }),
+ },
+ ],
+ workspaceErrors: [
+ {} as ContentAutopilotWorkspaceErrors,
+ {
+ loadWorkspace: () => ({}),
+ loadSiteProfilesSuccess: (state) => withoutWorkspaceError(state, 'profiles'),
+ loadRunsSuccess: (state) => withoutWorkspaceError(state, 'runs'),
+ loadProposalsSuccess: (state) => withoutWorkspaceError(state, 'proposals'),
+ loadSiteProfilesFailure: (state, { errorObject }) => ({
+ ...state,
+ profiles: getErrorMessage(errorObject),
+ }),
+ loadRunsFailure: (state, { errorObject }) => ({
+ ...state,
+ runs: getErrorMessage(errorObject),
+ }),
+ loadProposalsFailure: (state, { errorObject }) => ({
+ ...state,
+ proposals: getErrorMessage(errorObject),
+ }),
+ },
+ ],
+ }),
+ loaders(({ values }) => ({
+ siteProfiles: [
+ [] as ContentAutopilotSiteProfileApi[],
+ {
+ loadSiteProfiles: async (_, breakpoint) => {
+ const profiles = await fetchAllPages((offset, limit) =>
+ webAnalyticsApi.webAnalyticsContentAutopilotProfilesList(String(values.currentTeamIdStrict), {
+ limit,
+ offset,
+ })
+ )
+ breakpoint()
+ return profiles
+ },
+ },
+ ],
+ runs: [
+ [] as ContentAutopilotRunApi[],
+ {
+ loadRuns: async (_, breakpoint) => {
+ const profile = values.profile
+ if (!profile) {
+ return []
+ }
+ const runs = await fetchAllPages((offset, limit) =>
+ webAnalyticsApi.webAnalyticsContentAutopilotRunsList(String(values.currentTeamIdStrict), {
+ limit,
+ offset,
+ profile_id: profile.id,
+ })
+ )
+ breakpoint()
+ return runs
+ },
+ },
+ ],
+ proposals: [
+ [] as ContentAutopilotProposalListApi[],
+ {
+ loadProposals: async (_, breakpoint) => {
+ const profile = values.profile
+ if (!profile) {
+ return []
+ }
+ const proposals = await fetchAllPages((offset, limit) =>
+ webAnalyticsApi.webAnalyticsContentAutopilotProposalsList(String(values.currentTeamIdStrict), {
+ limit,
+ offset,
+ profile_id: profile.id,
+ })
+ )
+ breakpoint()
+ return proposals
+ },
+ },
+ ],
+ proposalDetail: [
+ null as ContentAutopilotProposalApi | null,
+ {
+ loadProposal: async (proposalId: string, breakpoint) => {
+ const proposal = await webAnalyticsApi.webAnalyticsContentAutopilotProposalsRetrieve(
+ String(values.currentTeamIdStrict),
+ proposalId
+ )
+ breakpoint()
+ return proposal
+ },
+ },
+ ],
+ discoveredSite: [
+ null as ContentAutopilotSiteDiscoveryResponseApi | null,
+ {
+ discoverSite: async () =>
+ await webAnalyticsApi.webAnalyticsContentAutopilotProfilesDiscover(
+ String(values.currentTeamIdStrict),
+ {
+ domain: values.profileDraft.domain.trim(),
+ }
+ ),
+ },
+ ],
+ savedProfile: [
+ null as ContentAutopilotSiteProfileApi | null,
+ {
+ saveProfile: async () => {
+ const payload = {
+ name: values.profileDraft.name.trim(),
+ domain: values.profileDraft.domain.trim(),
+ source_urls: splitLines(values.profileDraft.sourceUrls),
+ content_boundaries: splitLines(values.profileDraft.contentBoundaries),
+ brand_rules: splitLines(values.profileDraft.brandRules),
+ search_console_enabled: values.profileDraft.searchConsoleEnabled,
+ }
+ const profile = values.onboardingOpen ? null : values.profile
+ if (profile) {
+ return await webAnalyticsApi.webAnalyticsContentAutopilotProfilesPartialUpdate(
+ String(values.currentTeamIdStrict),
+ profile.id,
+ payload
+ )
+ }
+ return await webAnalyticsApi.webAnalyticsContentAutopilotProfilesCreate(
+ String(values.currentTeamIdStrict),
+ payload
+ )
+ },
+ },
+ ],
+ deletedProfile: [
+ null as string | null,
+ {
+ deleteProfile: async (profileId: string) => {
+ await webAnalyticsApi.webAnalyticsContentAutopilotProfilesDestroy(
+ String(values.currentTeamIdStrict),
+ profileId
+ )
+ return profileId
+ },
+ },
+ ],
+ runMutation: [
+ null as ContentAutopilotRunApi | null,
+ {
+ startRun: async () => {
+ if (!values.profile) {
+ throw new Error('Select a site before starting a content run')
+ }
+ return await webAnalyticsApi.webAnalyticsContentAutopilotRunsStart(
+ String(values.currentTeamIdStrict),
+ {
+ profile_id: values.profile.id,
+ }
+ )
+ },
+ cancelRun: async (runId: string) =>
+ await webAnalyticsApi.webAnalyticsContentAutopilotRunsCancel(
+ String(values.currentTeamIdStrict),
+ runId
+ ),
+ },
+ ],
+ proposalMutation: [
+ null as ContentAutopilotProposalApi | null,
+ {
+ rejectProposal: async (proposalId: string) =>
+ await webAnalyticsApi.webAnalyticsContentAutopilotProposalsReject(
+ String(values.currentTeamIdStrict),
+ proposalId
+ ),
+ regenerateProposal: async (proposalId: string) =>
+ await webAnalyticsApi.webAnalyticsContentAutopilotProposalsRegenerate(
+ String(values.currentTeamIdStrict),
+ proposalId
+ ),
+ saveProposal: async (proposalId: string) => {
+ const proposal = values.selectedProposal?.id === proposalId ? values.selectedProposal : null
+ if (!proposal) {
+ throw new Error('Proposal not found')
+ }
+ return await webAnalyticsApi.webAnalyticsContentAutopilotProposalsEdit(
+ String(values.currentTeamIdStrict),
+ proposalId,
+ {
+ proposed_markdown: values.proposedMarkdown,
+ content_package: proposal.content_package,
+ }
+ )
+ },
+ },
+ ],
+ exportedProposal: [
+ null as ContentAutopilotExportResponseApi | null,
+ {
+ exportProposal: async (proposalId: string) => {
+ if (values.selectedProposalId === proposalId && values.proposalHasUnsavedChanges) {
+ throw new Error('Save or discard your changes before exporting this proposal')
+ }
+ const exported = await webAnalyticsApi.webAnalyticsContentAutopilotProposalsExport(
+ String(values.currentTeamIdStrict),
+ proposalId
+ )
+ downloadBlob(new Blob([exported.markdown], { type: 'text/markdown' }), exported.filename)
+ return exported
+ },
+ },
+ ],
+ })),
+ reducers({
+ runs: [[] as ContentAutopilotRunApi[], { selectProfile: () => [] }],
+ proposals: [[] as ContentAutopilotProposalListApi[], { selectProfile: () => [] }],
+ }),
+ selectors({
+ profile: [
+ (selectors) => [selectors.siteProfiles, selectors.selectedProfileId],
+ (
+ siteProfiles: ContentAutopilotSiteProfileApi[],
+ selectedProfileId: string | null
+ ): ContentAutopilotSiteProfileApi | null =>
+ siteProfiles.find(({ id }) => id === selectedProfileId) ?? siteProfiles[0] ?? null,
+ ],
+ siteRuns: [(selectors) => [selectors.runs], (runs: ContentAutopilotRunApi[]): ContentAutopilotRunApi[] => runs],
+ siteProposals: [
+ (selectors) => [selectors.proposals],
+ (proposals: ContentAutopilotProposalListApi[]): ContentAutopilotProposalListApi[] => proposals,
+ ],
+ activeRun: [
+ (selectors) => [selectors.siteRuns],
+ (runs: ContentAutopilotRunApi[]): ContentAutopilotRunApi | null =>
+ runs.find(({ run_status }) => run_status === 'pending' || run_status === 'generating') ?? null,
+ ],
+ selectedProposal: [
+ (selectors) => [selectors.proposalDetail, selectors.selectedProposalId],
+ (
+ proposalDetail: ContentAutopilotProposalApi | null,
+ selectedProposalId: string | null
+ ): ContentAutopilotProposalApi | null =>
+ proposalDetail?.id === selectedProposalId ? proposalDetail : null,
+ ],
+ proposalHasUnsavedChanges: [
+ (selectors) => [selectors.selectedProposal, selectors.proposedMarkdown],
+ (selectedProposal: ContentAutopilotProposalApi | null, proposedMarkdown: string): boolean =>
+ selectedProposal !== null && proposedMarkdown !== selectedProposal.proposed_markdown,
+ ],
+ newContentProposals: [
+ (selectors) => [selectors.siteProposals],
+ (proposals: ContentAutopilotProposalListApi[]): ContentAutopilotProposalListApi[] =>
+ proposals.filter(({ proposal_type }) => proposal_type === 'new_content'),
+ ],
+ pageImprovementProposals: [
+ (selectors) => [selectors.siteProposals],
+ (proposals: ContentAutopilotProposalListApi[]): ContentAutopilotProposalListApi[] =>
+ proposals.filter(({ proposal_type }) => proposal_type === 'page_improvement'),
+ ],
+ workspaceInitialized: [
+ (selectors) => [selectors.workspaceSettled],
+ (workspaceSettled: ContentAutopilotWorkspaceSettled): boolean =>
+ Object.values(workspaceSettled).every(Boolean),
+ ],
+ profileDataLoaded: [
+ (selectors) => [selectors.profileDataSettled],
+ (profileDataSettled: ContentAutopilotProfileDataSettled): boolean =>
+ Object.values(profileDataSettled).every(Boolean),
+ ],
+ proposalActionReasons: [
+ (selectors) => [
+ selectors.selectedProposal,
+ selectors.proposalHasUnsavedChanges,
+ selectors.proposalDetailLoading,
+ selectors.proposalMutationLoading,
+ selectors.exportedProposalLoading,
+ ],
+ (
+ selectedProposal: ContentAutopilotProposalApi | null,
+ proposalHasUnsavedChanges: boolean,
+ proposalDetailLoading: boolean,
+ proposalMutationLoading: boolean,
+ exportedProposalLoading: boolean
+ ): ContentAutopilotProposalActionReasons => {
+ if (!selectedProposal) {
+ return {}
+ }
+ const readyForReview = selectedProposal.lifecycle_status === 'ready_for_review'
+ const exportInFlight = exportedProposalLoading ? 'Wait for the export to finish' : undefined
+ const unsavedChanges = proposalHasUnsavedChanges ? 'Save or discard your changes first' : undefined
+ return {
+ reject:
+ (!readyForReview ? 'Only a proposal ready for review can be rejected' : undefined) ??
+ exportInFlight ??
+ unsavedChanges,
+ regenerate:
+ (!readyForReview && selectedProposal.lifecycle_status !== 'failed'
+ ? 'Only proposals ready for review or failed can be regenerated'
+ : undefined) ??
+ exportInFlight ??
+ unsavedChanges,
+ save:
+ (!readyForReview ? 'Only a proposal ready for review can be edited' : undefined) ??
+ (proposalDetailLoading ? 'Wait for the proposal to load' : undefined) ??
+ exportInFlight ??
+ (!proposalHasUnsavedChanges ? 'No unsaved changes' : undefined),
+ exportMarkdown:
+ (!selectedProposal.validation_report.passed
+ ? 'Fix the blocked checks before exporting'
+ : undefined) ??
+ (!readyForReview ? 'Only a proposal ready for review can be exported' : undefined) ??
+ (proposalHasUnsavedChanges ? 'Save or discard your changes before exporting' : undefined) ??
+ (proposalMutationLoading ? 'Wait for proposal changes to finish' : undefined),
+ }
+ },
+ ],
+ workspaceError: [
+ (selectors) => [selectors.workspaceErrors],
+ (workspaceErrors: ContentAutopilotWorkspaceErrors): string | null =>
+ Object.values(workspaceErrors).join(' ') || null,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ loadWorkspace: () => {
+ actions.loadSiteProfiles()
+ },
+ beginOnboarding: () => {
+ actions.resetProfileDraft(EMPTY_PROFILE_DRAFT)
+ },
+ cancelOnboarding: () => {
+ if (values.profile) {
+ actions.resetProfileDraft(draftFromProfile(values.profile))
+ }
+ },
+ selectProfile: ({ profileId }) => {
+ const profile = values.siteProfiles.find(({ id }) => id === profileId)
+ if (profile) {
+ actions.resetProfileDraft(draftFromProfile(profile))
+ }
+ actions.selectProposal(null)
+ actions.loadRuns()
+ actions.loadProposals()
+ },
+ loadSiteProfilesSuccess: () => {
+ if (values.profile) {
+ actions.selectProfile(values.profile.id)
+ } else {
+ actions.beginOnboarding()
+ actions.loadRunsSuccess([])
+ actions.loadProposalsSuccess([])
+ }
+ },
+ loadSiteProfilesFailure: () => {
+ actions.loadRunsSuccess([])
+ actions.loadProposalsSuccess([])
+ },
+ discoverSiteSuccess: ({ discoveredSite }) => {
+ actions.setProfileDraft({
+ name: discoveredSite.name,
+ domain: discoveredSite.domain,
+ sourceUrls: discoveredSite.source_urls.join('\n'),
+ contentBoundaries: discoveredSite.content_boundaries.join('\n'),
+ })
+ },
+ discoverSiteFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ selectProposal: ({ proposalId }) => {
+ actions.setProposedMarkdown('')
+ if (proposalId) {
+ actions.loadProposal(proposalId)
+ }
+ },
+ loadProposalSuccess: ({ proposalDetail }) => {
+ if (proposalDetail.id === values.selectedProposalId) {
+ actions.setProposedMarkdown(proposalDetail.proposed_markdown)
+ }
+ },
+ loadProposalFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ actions.selectProposal(null)
+ },
+ saveProfileSuccess: ({ savedProfile }) => {
+ lemonToast.success('Site profile saved')
+ actions.resetProfileDraft(draftFromProfile(savedProfile))
+ actions.loadSiteProfiles()
+ },
+ saveProfileFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ deleteProfileSuccess: () => {
+ lemonToast.success('Site deleted')
+ actions.selectProposal(null)
+ actions.loadSiteProfiles()
+ },
+ deleteProfileFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ startRunSuccess: () => {
+ lemonToast.success('Content run started')
+ actions.loadRuns()
+ },
+ cancelRunSuccess: () => {
+ lemonToast.success('Content run canceled')
+ actions.loadRuns()
+ },
+ startRunFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ cancelRunFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ rejectProposalSuccess: () => {
+ lemonToast.success('Proposal rejected')
+ actions.selectProposal(null)
+ actions.loadProposals()
+ },
+ regenerateProposalSuccess: () => {
+ lemonToast.success('Proposal queued for regeneration')
+ actions.selectProposal(null)
+ actions.loadProposals()
+ },
+ saveProposalSuccess: () => {
+ lemonToast.success('Changes saved and queued for validation')
+ actions.selectProposal(null)
+ actions.loadProposals()
+ },
+ rejectProposalFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ regenerateProposalFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ saveProposalFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ exportProposalSuccess: () => {
+ lemonToast.success('Markdown exported')
+ actions.loadProposals()
+ },
+ exportProposalFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ })),
+ afterMount(({ actions, cache, values }) => {
+ actions.loadWorkspace()
+ cache.disposables.add(() => {
+ const pollTimer = window.setInterval(() => {
+ const isProcessing =
+ values.activeRun !== null ||
+ values.siteProposals.some(({ lifecycle_status }) => lifecycle_status === 'generating')
+ if (!isProcessing) {
+ return
+ }
+ if (values.runsLoading || values.proposalsLoading) {
+ return
+ }
+ actions.loadRuns()
+ actions.loadProposals()
+ }, WORKSPACE_POLL_INTERVAL_MS)
+ return () => clearInterval(pollTimer)
+ }, 'workspacePoll')
+ }),
+])
diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts
new file mode 100644
index 000000000000..0110a87e540f
--- /dev/null
+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts
@@ -0,0 +1,99 @@
+import type {
+ ContentAutopilotProposalApi,
+ ContentAutopilotProposalListApi,
+ ContentAutopilotRunApi,
+ ContentAutopilotSiteProfileApi,
+} from 'products/web_analytics/frontend/generated/api.schemas'
+
+export const EXAMPLE_PROFILE: ContentAutopilotSiteProfileApi = {
+ id: '00000000-0000-4000-8000-000000000001',
+ name: 'Example docs',
+ domain: 'https://docs.example.com',
+ source_urls: ['https://docs.example.com/sitemap.xml'],
+ content_boundaries: ['/docs'],
+ brand_rules: ['Use sentence case for headings'],
+ search_console_enabled: true,
+ created_at: '2026-08-26T12:00:00Z',
+ updated_at: '2026-08-26T12:00:00Z',
+}
+
+export const EXAMPLE_SECOND_PROFILE: ContentAutopilotSiteProfileApi = {
+ ...EXAMPLE_PROFILE,
+ id: '00000000-0000-4000-8000-000000000002',
+ name: 'Example blog',
+ domain: 'https://blog.example.com',
+ source_urls: ['https://blog.example.com/sitemap.xml'],
+ content_boundaries: ['/blog'],
+}
+
+export const EXAMPLE_RUN: ContentAutopilotRunApi = {
+ id: '00000000-0000-4000-8000-000000000101',
+ profile_id: EXAMPLE_PROFILE.id,
+ run_status: 'completed',
+ input_snapshot: {
+ domain: EXAMPLE_PROFILE.domain,
+ confidence: 'standard',
+ },
+ errors: [],
+ created_at: '2026-08-26T12:00:00Z',
+ updated_at: '2026-08-26T12:08:00Z',
+ completed_at: '2026-08-26T12:08:00Z',
+}
+
+export const EXAMPLE_PROPOSAL: ContentAutopilotProposalApi = {
+ id: '00000000-0000-4000-8000-000000000201',
+ run_id: EXAMPLE_RUN.id,
+ proposal_type: 'page_improvement',
+ lifecycle_status: 'ready_for_review',
+ title: 'Make the web analytics guide easier to discover',
+ target_query: 'web analytics guide',
+ target_url: 'https://docs.example.com/docs/web-analytics',
+ evidence: [
+ {
+ opportunity_kind: 'poor_ctr',
+ explanation:
+ 'The page appears for this query, but its click-through rate trails other pages in this range.',
+ page_url: 'https://docs.example.com/docs/web-analytics',
+ query: 'web analytics guide',
+ },
+ ],
+ validation_report: {
+ passed: true,
+ checks: [
+ {
+ check_key: 'intent_match',
+ label: 'Intent match',
+ passed: true,
+ message: 'The proposed description matches the observed informational query.',
+ blocking: true,
+ },
+ ],
+ },
+ content_package: {
+ file_path: 'contents/docs/web-analytics.mdx',
+ title: 'Web analytics',
+ description: 'Understand web traffic, behavior, and conversion with privacy-friendly analytics.',
+ slug: 'web-analytics',
+ frontmatter: [],
+ internal_links: [],
+ source_notes: [],
+ },
+ original_markdown: '# Web analytics',
+ proposed_markdown: '# Web analytics',
+ created_at: '2026-08-26T12:08:00Z',
+ updated_at: '2026-08-26T12:08:00Z',
+}
+
+export const EXAMPLE_PROPOSAL_LIST: ContentAutopilotProposalListApi = {
+ id: EXAMPLE_PROPOSAL.id,
+ run_id: EXAMPLE_PROPOSAL.run_id,
+ proposal_type: EXAMPLE_PROPOSAL.proposal_type,
+ lifecycle_status: EXAMPLE_PROPOSAL.lifecycle_status,
+ title: EXAMPLE_PROPOSAL.title,
+ target_query: EXAMPLE_PROPOSAL.target_query,
+ evidence: EXAMPLE_PROPOSAL.evidence,
+ validation_report: EXAMPLE_PROPOSAL.validation_report,
+ file_path: EXAMPLE_PROPOSAL.content_package.file_path,
+ created_at: EXAMPLE_PROPOSAL.created_at,
+ updated_at: EXAMPLE_PROPOSAL.updated_at,
+}
diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.ts
index 86ee7613f0ef..70ce5390ae37 100644
--- a/products/web_analytics/frontend/generated/api.ts
+++ b/products/web_analytics/frontend/generated/api.ts
@@ -725,6 +725,21 @@ export const webAnalyticsContentAutopilotProfilesPartialUpdate = async (
)
}
+export const getWebAnalyticsContentAutopilotProfilesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/${id}/`
+}
+
+export const webAnalyticsContentAutopilotProfilesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getWebAnalyticsContentAutopilotProfilesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getWebAnalyticsContentAutopilotProfilesDiscoverUrl = (projectId: string) => {
return `/api/projects/${projectId}/web_analytics_content_autopilot_profiles/discover/`
}
diff --git a/products/web_analytics/manifest.tsx b/products/web_analytics/manifest.tsx
index 88598e558ee4..b9e052d18af7 100644
--- a/products/web_analytics/manifest.tsx
+++ b/products/web_analytics/manifest.tsx
@@ -21,6 +21,7 @@ export const manifest: ProductManifest = {
webAnalyticsHealth: (): string => `/web/health`,
webAnalyticsLive: (): string => `/web/live`,
webAnalyticsBotAnalytics: (): string => `/web/bot-analytics`,
+ webAnalyticsContentAutopilot: (): string => `/web/content-autopilot`,
heatmaps: (params?: string): string =>
`/heatmaps${params ? `?${params.startsWith('?') ? params.slice(1) : params}` : ''}`,
heatmapNew: (params?: string): string =>
@@ -58,6 +59,7 @@ export const manifest: ProductManifest = {
},
},
routes: {
+ '/web/content-autopilot': ['WebAnalytics', 'webAnalyticsContentAutopilot'],
'/heatmaps': ['Heatmaps', 'heatmaps'],
'/heatmaps/new': ['HeatmapNew', 'heatmapNew'],
'/heatmaps/recording': ['HeatmapRecording', 'heatmapRecording'],
diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yaml
index cdb807292cf2..c3bbd8806423 100644
--- a/products/web_analytics/mcp/tools.yaml
+++ b/products/web_analytics/mcp/tools.yaml
@@ -208,6 +208,9 @@ tools:
web-analytics-content-autopilot-profiles-create:
operation: web_analytics_content_autopilot_profiles_create
enabled: false
+ web-analytics-content-autopilot-profiles-destroy:
+ operation: web_analytics_content_autopilot_profiles_destroy
+ enabled: false
web-analytics-content-autopilot-profiles-discover:
operation: web_analytics_content_autopilot_profiles_discover
enabled: false
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index d0c0cf4d4e1d..3d3c5777525b 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -1699,6 +1699,11 @@
"params": [],
"scope": "project"
},
+ "webAnalyticsContentAutopilot": {
+ "template": "/web/content-autopilot",
+ "params": [],
+ "scope": "project"
+ },
"webAnalyticsHealth": {
"template": "/web/health",
"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.json
index 41f6b4205f69..b53e49367374 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/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\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/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/health\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\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\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/billing/real-time-usage\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/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/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/organization-authentication/{feature}/{configId}\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}",
+ "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/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\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/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/health\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\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\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/billing/real-time-usage\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/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/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/organization-authentication/{feature}/{configId}\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/content-autopilot\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"
}
},