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 opportunity state to the logic (#109590)

Jordan Mryyanb4ce6aa5673e
diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx
index 2bf8e3e596ec..a44025aab483 100644
--- a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx
+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx
@@ -5,6 +5,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { mswDecorator } from '~/mocks/browser'
import type {
+ ContentAutopilotOpportunityApi,
ContentAutopilotProposalListApi,
ContentAutopilotRunApi,
ContentAutopilotSiteProfileApi,
@@ -12,6 +13,7 @@ import type {
import { ContentAutopilot } from './ContentAutopilot'
import { ContentAutopilotSetup } from './ContentAutopilotSetup'
import {
+ EXAMPLE_OPPORTUNITIES,
EXAMPLE_PROFILE,
EXAMPLE_PROPOSAL,
EXAMPLE_PROPOSAL_LIST,
@@ -23,10 +25,12 @@ const workspaceHandlers = ({
profiles,
runs = [],
proposals = [],
+ opportunities = [],
}: {
profiles: ContentAutopilotSiteProfileApi[]
runs?: ContentAutopilotRunApi[]
proposals?: ContentAutopilotProposalListApi[]
+ opportunities?: ContentAutopilotOpportunityApi[]
}): ReturnType<typeof mswDecorator> =>
mswDecorator({
get: {
@@ -46,8 +50,13 @@ const workspaceHandlers = ({
200,
EXAMPLE_PROPOSAL,
],
+ '/api/projects/:team_id/web_analytics_content_autopilot_opportunities/': () => [
+ 200,
+ { count: opportunities.length, next: null, previous: null, results: opportunities },
+ ],
},
post: {
+ '/api/projects/:team_id/web_analytics_content_autopilot_opportunities/refresh/': () => [200, opportunities],
'/api/projects/:team_id/web_analytics_content_autopilot_profiles/discover/': () => [
200,
{
@@ -100,7 +109,12 @@ export const ReadyForReview: StoryFn<typeof ContentAutopilot> = () => (
</div>
)
ReadyForReview.decorators = [
- workspaceHandlers({ profiles: [EXAMPLE_PROFILE], runs: [EXAMPLE_RUN], proposals: [EXAMPLE_PROPOSAL_LIST] }),
+ workspaceHandlers({
+ profiles: [EXAMPLE_PROFILE],
+ runs: [EXAMPLE_RUN],
+ proposals: [EXAMPLE_PROPOSAL_LIST],
+ opportunities: EXAMPLE_OPPORTUNITIES,
+ }),
]
export const ActiveRun: StoryFn<typeof ContentAutopilot> = () => (
diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts
index 0e209cc5c29d..48760142dbe5 100644
--- a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts
+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts
@@ -6,6 +6,9 @@ import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { initKeaTests } from '~/test/init'
import {
+ webAnalyticsContentAutopilotOpportunitiesDraft,
+ webAnalyticsContentAutopilotOpportunitiesList,
+ webAnalyticsContentAutopilotOpportunitiesRefresh,
webAnalyticsContentAutopilotProfilesCreate,
webAnalyticsContentAutopilotProfilesDestroy,
webAnalyticsContentAutopilotProfilesDiscover,
@@ -24,6 +27,7 @@ import {
import type { ContentAutopilotProposalListApi, ContentAutopilotRunApi } from '../generated/api.schemas'
import { contentAutopilotLogic } from './contentAutopilotLogic'
import {
+ EXAMPLE_OPPORTUNITIES,
EXAMPLE_PROFILE,
EXAMPLE_PROPOSAL,
EXAMPLE_PROPOSAL_LIST,
@@ -32,6 +36,10 @@ import {
} from './contentAutopilotStoryFixtures'
jest.mock('../generated/api', () => ({
+ webAnalyticsContentAutopilotOpportunitiesDismiss: jest.fn(),
+ webAnalyticsContentAutopilotOpportunitiesDraft: jest.fn(),
+ webAnalyticsContentAutopilotOpportunitiesList: jest.fn(),
+ webAnalyticsContentAutopilotOpportunitiesRefresh: jest.fn(),
webAnalyticsContentAutopilotProfilesCreate: jest.fn(),
webAnalyticsContentAutopilotProfilesDestroy: jest.fn(),
webAnalyticsContentAutopilotProfilesDiscover: jest.fn(),
@@ -53,6 +61,8 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
lemonToast: { success: jest.fn(), error: jest.fn() },
}))
+const mockOpportunitiesDraft = jest.mocked(webAnalyticsContentAutopilotOpportunitiesDraft)
+const mockOpportunitiesRefresh = jest.mocked(webAnalyticsContentAutopilotOpportunitiesRefresh)
const mockProfilesCreate = jest.mocked(webAnalyticsContentAutopilotProfilesCreate)
const mockProfilesDestroy = jest.mocked(webAnalyticsContentAutopilotProfilesDestroy)
const mockProfilesList = jest.mocked(webAnalyticsContentAutopilotProfilesList)
@@ -110,6 +120,9 @@ describe('contentAutopilotLogic', () => {
jest.mocked(webAnalyticsContentAutopilotProposalsRegenerate).mockResolvedValue(EXAMPLE_PROPOSAL)
jest.mocked(webAnalyticsContentAutopilotProposalsReject).mockResolvedValue(EXAMPLE_PROPOSAL)
jest.mocked(webAnalyticsContentAutopilotRunsCancel).mockResolvedValue(EXAMPLE_RUN)
+ mockOpportunitiesRefresh.mockResolvedValue(EXAMPLE_OPPORTUNITIES)
+ jest.mocked(webAnalyticsContentAutopilotOpportunitiesList).mockResolvedValue(paginated(EXAMPLE_OPPORTUNITIES))
+ mockOpportunitiesDraft.mockResolvedValue({ ...EXAMPLE_RUN, run_status: 'pending', completed_at: null })
})
afterEach(() => {
@@ -123,6 +136,54 @@ describe('contentAutopilotLogic', () => {
return logic
}
+ it('shows saved opportunities while the refresh runs and keeps rows the refresh response leaves out', async () => {
+ const [first] = EXAMPLE_OPPORTUNITIES
+ const pendingRefresh = deferred<typeof EXAMPLE_OPPORTUNITIES>()
+ mockOpportunitiesRefresh.mockReturnValue(pendingRefresh.promise)
+ logic = contentAutopilotLogic()
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadOpportunitiesSuccess', 'refreshOpportunities'])
+ expect(logic.values.opportunities).toEqual(EXAMPLE_OPPORTUNITIES)
+ expect(mockOpportunitiesRefresh).toHaveBeenCalledTimes(1)
+ expect(mockOpportunitiesRefresh).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {
+ profile_id: EXAMPLE_PROFILE.id,
+ })
+
+ pendingRefresh.resolve([first])
+ await expectLogic(logic).toDispatchActions(['refreshOpportunitiesSuccess'])
+ expect(logic.values.opportunities).toEqual(EXAMPLE_OPPORTUNITIES)
+ })
+
+ it('drafts only the selected opportunities for the current site and clears the selection', async () => {
+ const mountedLogic = await mountWorkspace()
+ const [first, second] = EXAMPLE_OPPORTUNITIES
+
+ expect(mountedLogic.values.draftDisabledReason).toEqual('Select at least one opportunity')
+
+ mountedLogic.actions.setOpportunitySearch(first.title.toUpperCase())
+ expect(mountedLogic.values.visibleOpportunities.map(({ id }) => id)).toEqual([first.id])
+ mountedLogic.actions.setOpportunitySearch('')
+
+ mountedLogic.actions.toggleOpportunitySelection(first.id)
+ mountedLogic.actions.toggleOpportunitySelection(second.id)
+ jest.mocked(webAnalyticsContentAutopilotOpportunitiesList).mockResolvedValue(
+ paginated([first, { ...second, status: 'queued' }])
+ )
+ await expectLogic(mountedLogic, () => mountedLogic.actions.refreshOpportunities()).toFinishAllListeners()
+ expect(mountedLogic.values.selectedOpportunityIds).toEqual([first.id])
+ expect(mountedLogic.values.draftDisabledReason).toBeUndefined()
+
+ await expectLogic(mountedLogic, () => mountedLogic.actions.draftOpportunities()).toFinishAllListeners()
+
+ expect(mockOpportunitiesDraft).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {
+ profile_id: EXAMPLE_PROFILE.id,
+ opportunity_ids: [first.id],
+ })
+ expect(mountedLogic.values.selectedOpportunityIds).toEqual([])
+ expect(mountedLogic.values.workspaceTab).toBe('drafts')
+ })
+
it('sends typed run and profile payloads to the generated API clients', async () => {
const mountedLogic = await mountWorkspace()
const projectId = String(MOCK_DEFAULT_TEAM.id)
diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts
index e73636bb2f77..22f9e4488245 100644
--- a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts
+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts
@@ -8,14 +8,17 @@ import { teamLogic } from 'scenes/teamLogic'
import * as webAnalyticsApi from 'products/web_analytics/frontend/generated/api'
import type {
ContentAutopilotExportResponseApi,
+ ContentAutopilotOpportunityApi,
ContentAutopilotProposalApi,
ContentAutopilotProposalListApi,
ContentAutopilotRunApi,
ContentAutopilotSiteDiscoveryResponseApi,
ContentAutopilotSiteProfileApi,
} from 'products/web_analytics/frontend/generated/api.schemas'
+import { webAnalyticsContentAutopilotOpportunitiesDraftBodyOpportunityIdsMax } from 'products/web_analytics/frontend/generated/api.zod'
export type ContentAutopilotOnboardingStep = 'site' | 'sources'
+export type ContentAutopilotWorkspaceTab = 'opportunities' | 'drafts'
export type ContentAutopilotWorkspaceResource = 'profiles' | 'runs' | 'proposals'
export type ContentAutopilotProfileResource = 'runs' | 'proposals'
export type ContentAutopilotWorkspaceErrors = Partial<Record<ContentAutopilotWorkspaceResource, string>>
@@ -48,6 +51,7 @@ const EMPTY_PROFILE_DRAFT: ContentAutopilotProfileDraft = {
}
const WORKSPACE_POLL_INTERVAL_MS = 10_000
+export const MAX_DRAFTS_PER_RUN = webAnalyticsContentAutopilotOpportunitiesDraftBodyOpportunityIdsMax
const WORKSPACE_PAGE_LIMIT = 100
const EMPTY_WORKSPACE_SETTLED: ContentAutopilotWorkspaceSettled = {
profiles: false,
@@ -64,6 +68,8 @@ interface PaginatedResults<T> {
results: T[]
}
+const UNDRAFTABLE_STATUSES = new Set<ContentAutopilotOpportunityApi['status']>(['queued', 'dismissed'])
+
const fetchAllPages = async <T>(
loadPage: (offset: number, limit: number) => Promise<PaginatedResults<T>>
): Promise<T[]> => {
@@ -77,6 +83,16 @@ const fetchAllPages = async <T>(
}
}
+const fetchOpportunities = (teamId: string, profileId: string): Promise<ContentAutopilotOpportunityApi[]> =>
+ fetchAllPages((offset, limit) =>
+ webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesList(teamId, { limit, offset, profile_id: profileId })
+ )
+
+const draftableSelection = (selectedIds: string[], opportunities: ContentAutopilotOpportunityApi[]): string[] =>
+ selectedIds.filter((id) =>
+ opportunities.some((opportunity) => opportunity.id === id && !UNDRAFTABLE_STATUSES.has(opportunity.status))
+ )
+
const withoutWorkspaceError = (
errors: ContentAutopilotWorkspaceErrors,
resource: ContentAutopilotWorkspaceResource
@@ -119,11 +135,19 @@ export interface contentAutopilotLogicValues {
deletedProfileLoading: boolean
discoveredSite: ContentAutopilotSiteDiscoveryResponseApi | null
discoveredSiteLoading: boolean
+ dismissedOpportunity: ContentAutopilotOpportunityApi | null
+ dismissedOpportunityCount: number
+ dismissedOpportunityLoading: boolean
+ draftDisabledReason: string | undefined
exportedProposal: ContentAutopilotExportResponseApi | null
exportedProposalLoading: boolean
newContentProposals: ContentAutopilotProposalListApi[]
onboardingOpen: boolean
onboardingStep: ContentAutopilotOnboardingStep
+ opportunities: ContentAutopilotOpportunityApi[] | null
+ opportunitiesError: string | null
+ opportunitiesLoading: boolean
+ opportunitySearch: string
pageImprovementProposals: ContentAutopilotProposalListApi[]
profile: ContentAutopilotSiteProfileApi | null
profileDataLoaded: boolean
@@ -144,17 +168,21 @@ export interface contentAutopilotLogicValues {
runsLoading: boolean
savedProfile: ContentAutopilotSiteProfileApi | null
savedProfileLoading: boolean
+ selectedOpportunityIds: string[]
selectedProfileId: string | null
selectedProposal: ContentAutopilotProposalApi | null
selectedProposalId: string | null
+ showDismissedOpportunities: boolean
siteProfiles: ContentAutopilotSiteProfileApi[]
siteProfilesLoading: boolean
siteProposals: ContentAutopilotProposalListApi[]
siteRuns: ContentAutopilotRunApi[]
+ visibleOpportunities: ContentAutopilotOpportunityApi[]
workspaceError: string | null
workspaceErrors: ContentAutopilotWorkspaceErrors
workspaceInitialized: boolean
workspaceSettled: ContentAutopilotWorkspaceSettled
+ workspaceTab: ContentAutopilotWorkspaceTab
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -210,6 +238,36 @@ export interface contentAutopilotLogicActions {
discoveredSite: ContentAutopilotSiteDiscoveryResponseApi
payload?: any
}
+ dismissOpportunity: (opportunityId: string) => string
+ dismissOpportunityFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ dismissOpportunitySuccess: (
+ dismissedOpportunity: ContentAutopilotOpportunityApi,
+ payload?: string
+ ) => {
+ dismissedOpportunity: ContentAutopilotOpportunityApi
+ payload?: string
+ }
+ draftOpportunities: () => any
+ draftOpportunitiesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ draftOpportunitiesSuccess: (
+ runMutation: ContentAutopilotRunApi,
+ payload?: any
+ ) => {
+ runMutation: ContentAutopilotRunApi
+ payload?: any
+ }
exportProposal: (proposalId: string) => string
exportProposalFailure: (
error: string,
@@ -225,6 +283,27 @@ export interface contentAutopilotLogicActions {
exportedProposal: ContentAutopilotExportResponseApi
payload?: string
}
+ loadOpportunities: () => {
+ value: true
+ }
+ loadOpportunitiesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOpportunitiesSuccess: (
+ opportunities: ContentAutopilotOpportunityApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ opportunities: ContentAutopilotOpportunityApi[]
+ payload?: {
+ value: true
+ }
+ }
loadProposal: (proposalId: string) => string
loadProposalFailure: (
error: string,
@@ -306,6 +385,27 @@ export interface contentAutopilotLogicActions {
loadWorkspace: () => {
value: true
}
+ refreshOpportunities: () => {
+ value: true
+ }
+ refreshOpportunitiesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ refreshOpportunitiesSuccess: (
+ opportunities: ContentAutopilotOpportunityApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ opportunities: ContentAutopilotOpportunityApi[]
+ payload?: {
+ value: true
+ }
+ }
regenerateProposal: (proposalId: string) => string
regenerateProposalFailure: (
error: string,
@@ -378,12 +478,21 @@ export interface contentAutopilotLogicActions {
setOnboardingStep: (onboardingStep: ContentAutopilotOnboardingStep) => {
onboardingStep: ContentAutopilotOnboardingStep
}
+ setOpportunitySearch: (opportunitySearch: string) => {
+ opportunitySearch: string
+ }
setProfileDraft: (profileDraft: Partial<ContentAutopilotProfileDraft>) => {
profileDraft: Partial<ContentAutopilotProfileDraft>
}
setProposedMarkdown: (proposedMarkdown: string) => {
proposedMarkdown: string
}
+ setShowDismissedOpportunities: (showDismissedOpportunities: boolean) => {
+ showDismissedOpportunities: boolean
+ }
+ setWorkspaceTab: (workspaceTab: ContentAutopilotWorkspaceTab) => {
+ workspaceTab: ContentAutopilotWorkspaceTab
+ }
startRun: () => any
startRunFailure: (
error: string,
@@ -399,6 +508,9 @@ export interface contentAutopilotLogicActions {
runMutation: ContentAutopilotRunApi
payload?: any
}
+ toggleOpportunitySelection: (opportunityId: string) => {
+ opportunityId: string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -432,6 +544,17 @@ export interface contentAutopilotLogicMeta {
proposalMutationLoading: boolean,
exportedProposalLoading: boolean
) => ContentAutopilotProposalActionReasons
+ visibleOpportunities: (
+ opportunities: ContentAutopilotOpportunityApi[] | null,
+ showDismissedOpportunities: boolean,
+ opportunitySearch: string
+ ) => ContentAutopilotOpportunityApi[]
+ dismissedOpportunityCount: (opportunities: ContentAutopilotOpportunityApi[] | null) => number
+ draftDisabledReason: (
+ selectedOpportunityIds: string[],
+ activeRun: ContentAutopilotRunApi | null,
+ profileDataLoaded: boolean
+ ) => string | undefined
workspaceError: (workspaceErrors: Partial<Record<ContentAutopilotWorkspaceResource, string>>) => string | null
}
}
@@ -459,6 +582,12 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
setProfileDraft: (profileDraft: Partial<ContentAutopilotProfileDraft>) => ({ profileDraft }),
selectProposal: (proposalId: string | null) => ({ proposalId }),
setProposedMarkdown: (proposedMarkdown: string) => ({ proposedMarkdown }),
+ loadOpportunities: true,
+ refreshOpportunities: true,
+ toggleOpportunitySelection: (opportunityId: string) => ({ opportunityId }),
+ setShowDismissedOpportunities: (showDismissedOpportunities: boolean) => ({ showDismissedOpportunities }),
+ setOpportunitySearch: (opportunitySearch: string) => ({ opportunitySearch }),
+ setWorkspaceTab: (workspaceTab: ContentAutopilotWorkspaceTab) => ({ workspaceTab }),
}),
reducers({
profileDraft: [
@@ -504,6 +633,51 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
setProposedMarkdown: (_, { proposedMarkdown }) => proposedMarkdown,
},
],
+ workspaceTab: [
+ 'opportunities' as ContentAutopilotWorkspaceTab,
+ {
+ setWorkspaceTab: (_, { workspaceTab }) => workspaceTab,
+ selectProfile: () => 'opportunities',
+ draftOpportunitiesSuccess: () => 'drafts',
+ },
+ ],
+ opportunitySearch: [
+ '',
+ {
+ setOpportunitySearch: (_, { opportunitySearch }) => opportunitySearch,
+ selectProfile: () => '',
+ },
+ ],
+ selectedOpportunityIds: [
+ [] as string[],
+ {
+ toggleOpportunitySelection: (state, { opportunityId }) =>
+ state.includes(opportunityId)
+ ? state.filter((id) => id !== opportunityId)
+ : [...state, opportunityId],
+ selectProfile: () => [],
+ draftOpportunitiesSuccess: () => [],
+ loadOpportunitiesSuccess: (state, { opportunities }) => draftableSelection(state, opportunities),
+ refreshOpportunitiesSuccess: (state, { opportunities }) => draftableSelection(state, opportunities),
+ dismissOpportunitySuccess: (state, { dismissedOpportunity }) =>
+ state.filter((id) => id !== dismissedOpportunity.id),
+ },
+ ],
+ showDismissedOpportunities: [
+ false,
+ {
+ setShowDismissedOpportunities: (_, { showDismissedOpportunities }) => showDismissedOpportunities,
+ },
+ ],
+ opportunitiesError: [
+ null as string | null,
+ {
+ loadOpportunities: () => null,
+ refreshOpportunities: () => null,
+ loadOpportunitiesFailure: (_, { errorObject }) => getErrorMessage(errorObject),
+ refreshOpportunitiesFailure: (_, { errorObject }) => getErrorMessage(errorObject),
+ },
+ ],
workspaceSettled: [
EMPTY_WORKSPACE_SETTLED,
{
@@ -604,6 +778,44 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
},
},
],
+ opportunities: [
+ null as ContentAutopilotOpportunityApi[] | null,
+ {
+ loadOpportunities: async (_, breakpoint) => {
+ const profile = values.profile
+ if (!profile) {
+ return []
+ }
+ const opportunities = await fetchOpportunities(String(values.currentTeamIdStrict), profile.id)
+ breakpoint()
+ return opportunities
+ },
+ refreshOpportunities: async (_, breakpoint) => {
+ const profile = values.profile
+ if (!profile) {
+ return []
+ }
+ const teamId = String(values.currentTeamIdStrict)
+ await webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesRefresh(teamId, {
+ profile_id: profile.id,
+ })
+ breakpoint()
+ const opportunities = await fetchOpportunities(teamId, profile.id)
+ breakpoint()
+ return opportunities
+ },
+ },
+ ],
+ dismissedOpportunity: [
+ null as ContentAutopilotOpportunityApi | null,
+ {
+ dismissOpportunity: async (opportunityId: string) =>
+ await webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesDismiss(
+ String(values.currentTeamIdStrict),
+ opportunityId
+ ),
+ },
+ ],
proposalDetail: [
null as ContentAutopilotProposalApi | null,
{
@@ -682,6 +894,18 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
}
)
},
+ draftOpportunities: async () => {
+ if (!values.profile) {
+ throw new Error('Select a site before drafting content')
+ }
+ return await webAnalyticsApi.webAnalyticsContentAutopilotOpportunitiesDraft(
+ String(values.currentTeamIdStrict),
+ {
+ profile_id: values.profile.id,
+ opportunity_ids: values.selectedOpportunityIds,
+ }
+ )
+ },
cancelRun: async (runId: string) =>
await webAnalyticsApi.webAnalyticsContentAutopilotRunsCancel(
String(values.currentTeamIdStrict),
@@ -738,6 +962,16 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
reducers({
runs: [[] as ContentAutopilotRunApi[], { selectProfile: () => [] }],
proposals: [[] as ContentAutopilotProposalListApi[], { selectProfile: () => [] }],
+ opportunities: [
+ null as ContentAutopilotOpportunityApi[] | null,
+ {
+ selectProfile: () => null,
+ dismissOpportunitySuccess: (state, { dismissedOpportunity }) =>
+ state?.map((opportunity) =>
+ opportunity.id === dismissedOpportunity.id ? dismissedOpportunity : opportunity
+ ) ?? null,
+ },
+ ],
}),
selectors({
profile: [
@@ -838,13 +1072,55 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
}
},
],
+ visibleOpportunities: [
+ (selectors) => [selectors.opportunities, selectors.showDismissedOpportunities, selectors.opportunitySearch],
+ (
+ opportunities: ContentAutopilotOpportunityApi[] | null,
+ showDismissedOpportunities: boolean,
+ opportunitySearch: string
+ ): ContentAutopilotOpportunityApi[] => {
+ const search = opportunitySearch.trim().toLowerCase()
+ return (opportunities ?? []).filter(
+ ({ status, title }) =>
+ (showDismissedOpportunities || status !== 'dismissed') &&
+ (!search || title.toLowerCase().includes(search))
+ )
+ },
+ ],
+ dismissedOpportunityCount: [
+ (selectors) => [selectors.opportunities],
+ (opportunities: ContentAutopilotOpportunityApi[] | null): number =>
+ (opportunities ?? []).filter(({ status }) => status === 'dismissed').length,
+ ],
+ draftDisabledReason: [
+ (selectors) => [selectors.selectedOpportunityIds, selectors.activeRun, selectors.profileDataLoaded],
+ (
+ selectedOpportunityIds: string[],
+ activeRun: ContentAutopilotRunApi | null,
+ profileDataLoaded: boolean
+ ): string | undefined => {
+ if (!profileDataLoaded) {
+ return 'Wait for this site to finish loading'
+ }
+ if (activeRun) {
+ return 'Wait for the current run to finish'
+ }
+ if (selectedOpportunityIds.length === 0) {
+ return 'Select at least one opportunity'
+ }
+ if (selectedOpportunityIds.length > MAX_DRAFTS_PER_RUN) {
+ return `Select up to ${MAX_DRAFTS_PER_RUN} opportunities`
+ }
+ return undefined
+ },
+ ],
workspaceError: [
(selectors) => [selectors.workspaceErrors],
(workspaceErrors: ContentAutopilotWorkspaceErrors): string | null =>
Object.values(workspaceErrors).join(' ') || null,
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
loadWorkspace: () => {
actions.loadSiteProfiles()
},
@@ -864,6 +1140,14 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
actions.selectProposal(null)
actions.loadRuns()
actions.loadProposals()
+ cache.refreshOpportunitiesAfterLoad = true
+ actions.loadOpportunities()
+ },
+ loadOpportunitiesSuccess: () => {
+ if (cache.refreshOpportunitiesAfterLoad) {
+ cache.refreshOpportunitiesAfterLoad = false
+ actions.refreshOpportunities()
+ }
},
loadSiteProfilesSuccess: () => {
if (values.profile) {
@@ -920,6 +1204,17 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
deleteProfileFailure: ({ errorObject }) => {
lemonToast.error(getErrorMessage(errorObject))
},
+ draftOpportunitiesSuccess: () => {
+ lemonToast.success('Drafting started. Each draft takes a few minutes.')
+ actions.loadRuns()
+ actions.loadOpportunities()
+ },
+ draftOpportunitiesFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
+ dismissOpportunityFailure: ({ errorObject }) => {
+ lemonToast.error(getErrorMessage(errorObject))
+ },
startRunSuccess: () => {
lemonToast.success('Content run started')
actions.loadRuns()
@@ -981,6 +1276,9 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([
}
actions.loadRuns()
actions.loadProposals()
+ if (!values.opportunitiesLoading) {
+ actions.loadOpportunities()
+ }
}, 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
index 488b4073952a..879823b6213e 100644
--- a/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts
+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts
@@ -1,4 +1,5 @@
import type {
+ ContentAutopilotOpportunityApi,
ContentAutopilotProposalApi,
ContentAutopilotProposalListApi,
ContentAutopilotRunApi,
@@ -114,3 +115,55 @@ export const EXAMPLE_PROPOSAL_LIST: ContentAutopilotProposalListApi = {
created_at: EXAMPLE_PROPOSAL.created_at,
updated_at: EXAMPLE_PROPOSAL.updated_at,
}
+
+const EXAMPLE_GAP: ContentAutopilotOpportunityApi['gap'] = {
+ checks: 9,
+ cited_checks: 0,
+ mentioned_checks: 0,
+ citation_rate: 0,
+ engines: ['claude-web-search', 'openai-web-search', 'exa-answer'],
+ engines_not_citing: ['claude-web-search', 'openai-web-search', 'exa-answer'],
+ competitor_urls: ['https://rival.example.com/replay'],
+ competitor_domains: ['rival.example.com', 'reviews.example.org'],
+ engine_search_queries: ['open source session replay', 'session replay self hosted'],
+ our_cited_urls: [],
+ latest_answers: [],
+ last_checked_at: '2026-08-26T09:00:00Z',
+}
+
+export const EXAMPLE_OPPORTUNITIES: ContentAutopilotOpportunityApi[] = [
+ {
+ id: '00000000-0000-4000-8000-000000000301',
+ profile_id: EXAMPLE_PROFILE.id,
+ run_id: null,
+ proposal_id: null,
+ kind: 'ai_visibility_gap',
+ title: 'What is the best open source session replay tool?',
+ score: 1,
+ recommended_type: 'new_content',
+ target_url: '',
+ evidence: [],
+ gap: EXAMPLE_GAP,
+ status: 'new',
+ last_refreshed_at: '2026-08-26T12:00:00Z',
+ created_at: '2026-08-26T12:00:00Z',
+ updated_at: '2026-08-26T12:00:00Z',
+ },
+ {
+ id: '00000000-0000-4000-8000-000000000302',
+ profile_id: EXAMPLE_PROFILE.id,
+ run_id: EXAMPLE_RUN.id,
+ proposal_id: EXAMPLE_PROPOSAL.id,
+ kind: 'ai_visibility_gap',
+ title: 'Does web analytics work without cookies?',
+ score: 0.64,
+ recommended_type: 'page_improvement',
+ target_url: 'https://docs.example.com/docs/web-analytics',
+ evidence: [],
+ gap: { ...EXAMPLE_GAP, cited_checks: 3, mentioned_checks: 6, engines_not_citing: ['exa-answer'] },
+ status: 'drafted',
+ last_refreshed_at: '2026-08-26T12:00:00Z',
+ created_at: '2026-08-26T12:00:00Z',
+ updated_at: '2026-08-26T12:00:00Z',
+ },
+]