:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): show content opportunities in the workspace (#109627)
Jordan Mryyan1930cda2b154
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 09a5631a422d..7779c45c92db 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7251,21 +7251,21 @@ snapshots:products-web-analytics-content-autopilot-proposal-card--ready-for-review--light:hash: v1.k794b7964.2d32fe2131b0ecca9c82ad58d395e73e204ab96db50f814fea3797f241829965.ndis7gl5c6uNZ_5DhF8CiTwDrvHWrUHsSyp3db3PUL0products-web-analytics-content-autopilot-workspace--active-run--dark:- hash: v1.k794b7964.e51cfbfc3a423eba287aaf1163748e16a97cea29e8930762d6dab49f63a02cd8.hOdOrO1ZlSf_W9yT7zwWxnEwXAsBezXHwPYrDAAe8KA+ hash: v1.k794b7964.e78c4329f8ed2b268ae0f9e12750faf36b52a13f93afa4cdef6c6d3f967b85d4.seSi9FnXUv4lFgG8LnjWfQSx48DPmw0NvAouHKLV-hEproducts-web-analytics-content-autopilot-workspace--active-run--light:- hash: v1.k794b7964.3c178c7659561d5ed484a45ec199507ff813fe318f11b3c298ebda28ee1cf2c6.VglouF0l0BcgYhRN2rnU5GcOLraPGLfWVxyde925pQI+ hash: v1.k794b7964.01d2d2224dc6d1eec26cb051db45e73b3f09578cace3d92a865717270f36e9a0.fyfh1pZRPid9MiuWc2YolgmQRCYae61gLJ9TTZiQ_AUproducts-web-analytics-content-autopilot-workspace--multiple-sites--dark:- hash: v1.k794b7964.075627fbb891aa2c4389a264858fc5eb95de795aadf79bef985e0d59c98779f6.E_AQXIFnTooveaFPZDRpvDzTpyxBYlS_MxfujssbM90+ hash: v1.k794b7964.b59bcd4873161e4d1a649a7acf03a84e86f1e4bd063a0418833288e4b4995422.1P0EVXKwtUq4LrVS9jlKO_tbPn6kLp8nmpiAyVZ8GG0products-web-analytics-content-autopilot-workspace--multiple-sites--light:- hash: v1.k794b7964.8f13d0485b02c3cd59cb8943c112aacac38e38c7baa748bdf31c45ff47e56d02.cLk4Gq7iiI6Hi0IhYQWMj2heMo8i6GSg75rk_6GrXmI+ hash: v1.k794b7964.21a7db13b993390e317a731761f511032ca5a9bc9cce892a25e7e971dc4132c9.n4GVrNk_EbdIHKcdoedPUNp__WazceU2Bz3hX_cdKLoproducts-web-analytics-content-autopilot-workspace--onboarding--dark:- hash: v1.k794b7964.cf94fd6e5af83fcf38742042c5611ba25bfefda32590f511a6c8e2a08d14dd7c.oE7i5mmGnUIJGySMCWU-h7zKk5toT5bm4JvuUC8C644+ hash: v1.k794b7964.e25d2ce438dde5ff089d92d1504c6fa7b4bef2753263469896a025c9a12ca8ef.Y5pJiZoVIFxN2U2W1U-Jhl_k6BiEer-NAFSZHG2nzNsproducts-web-analytics-content-autopilot-workspace--onboarding--light:- hash: v1.k794b7964.4885036d8942b5c3cdb48c0a6a6614fea41afe1dcf25214d29d5973abde207bb.ZYYarqpsfM6PeMJvs0eie_yiLR0lvsXMo5FQvKn97vo+ hash: v1.k794b7964.3260bba8be9bb83600881de8669062332538e93deb3db5293d9a66b9aa761126.2LtqyaPy7LCKst40HPfbLagOFtLgCG5jLWxI9rD_ubMproducts-web-analytics-content-autopilot-workspace--ready-for-review--dark:- hash: v1.k794b7964.430ccb5f1ad7d6e1bb688c69221e2b60d8ad44bfc5b254c08b54bb90a8364189.Ksjd4WNULdqsgzy4Ye4txkdgFpmsINkvXRvlB_EtjhM+ hash: v1.k794b7964.e2a8bdaa2bb31d1d592af3e025420d607798e51389e2f09e947fdbc475f9416c.fB2i7pY1QaxzzAuxe8CmRPAK0rEFqg3Ybdrn3vPT5Awproducts-web-analytics-content-autopilot-workspace--ready-for-review--light:- hash: v1.k794b7964.d7aa367129b95dd772d6c0777d7ea4c9e359b0ff83ea83beab2b141d1da5b410.ApXV6wy_Fn5rBtnSE8JQfm-RZNvNzYGRe6MXHwVHahg+ hash: v1.k794b7964.1585d95a6cf144524c72dee9425e4192bd5a7f57ca1efdf90f493411446bd4c6.CXyy2bM9ZICsNRXcpZYV5Y36zVMZ1rUD1zlybNCNWeIproducts-web-analytics-content-autopilot-workspace--site-settings--dark:hash: v1.k794b7964.fc4421d5eb2f507adff62378c528a85f0d2afda601f5c64c427c01f8be0017e6.CwCi0RyySiohuekOKlnZxKFInJdQLJTSVx3upnSWs_gproducts-web-analytics-content-autopilot-workspace--site-settings--light:diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsxindex a44025aab483..2d2605950c9b 100644--- a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.stories.tsx@@ -122,6 +122,7 @@ export const ActiveRun: StoryFn<typeof ContentAutopilot> = () => (<ContentAutopilot /></div>)+ActiveRun.parameters = { testOptions: { waitForLoadersToDisappear: false } }ActiveRun.decorators = [workspaceHandlers({profiles: [EXAMPLE_PROFILE],diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.tsxindex eddd18ac8914..1aa020f6c531 100644--- a/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.tsx+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilot.tsx@@ -9,10 +9,12 @@ import {LemonDialog,LemonSelect,LemonSkeleton,- LemonTag,+ LemonTabs,+ Spinner,} from '@posthog/lemon-ui'import { contentAutopilotLogic } from './contentAutopilotLogic'+import { ContentAutopilotOpportunities } from './ContentAutopilotOpportunities'import { ContentAutopilotProposalDetail } from './ContentAutopilotProposalDetail'import { ContentAutopilotProposalSection } from './ContentAutopilotProposalSection'import { ContentAutopilotSetup } from './ContentAutopilotSetup'@@ -22,8 +24,10 @@ export const ContentAutopilot = (): JSX.Element => {profile,activeRun,siteRuns,+ siteProposals,newContentProposals,pageImprovementProposals,+ workspaceTab,onboardingOpen,siteProfiles,siteProfilesLoading,@@ -34,29 +38,25 @@ export const ContentAutopilot = (): JSX.Element => {workspaceErrors,workspaceInitialized,profileDataLoaded,+ visibleOpportunities,} = useValues(contentAutopilotLogic)- const { beginOnboarding, startRun, cancelRun, selectProfile, selectProposal, loadWorkspace } =+ const { beginOnboarding, cancelRun, selectProfile, selectProposal, loadWorkspace, setWorkspaceTab } =useActions(contentAutopilotLogic)const loading = siteProfilesLoading || runsLoading || proposalsLoadingconst lastRun = siteRuns[0]- const runDisabledReason = !profileDataLoaded- ? 'Wait for this site to finish loading'- : activeRun- ? 'A content run is already in progress for this site'- : undefinedconst confirmCancelRun = (): void => {if (!activeRun) {return}LemonDialog.open({- title: 'Cancel this content run?',- description: 'PostHog will stop processing this run. Completed proposals will remain available.',+ title: 'Stop drafting?',+ description: 'PostHog stops after the draft it is writing now. Finished drafts stay available.',primaryButton: {- children: 'Cancel run',+ children: 'Stop drafting',status: 'danger',onClick: () => cancelRun(activeRun.id),},- secondaryButton: { children: 'Keep running' },+ secondaryButton: { children: 'Keep drafting' },})}@@ -70,8 +70,8 @@ export const ContentAutopilot = (): JSX.Element => {<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.+ Find questions AI assistants answer without citing your site, and draft the pages that fix it.+ Nothing is published until you download a draft and ship it yourself.</p></div>{profile && !onboardingOpen ? (@@ -88,15 +88,6 @@ export const ContentAutopilot = (): JSX.Element => {<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>@@ -116,28 +107,21 @@ export const ContentAutopilot = (): JSX.Element => {<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 className="flex items-center gap-3">+ <Spinner className="text-xl" />+ <div>+ <h3 className="m-0">Drafting pages</h3>+ <p className="m-0 mt-1 text-muted">+ PostHog is reading your pages and the pages AI assistants cite, then+ writing and checking each draft. This takes a few minutes per page.+ </p></div>- <p className="m-0 mt-1 text-muted">- PostHog is analyzing current data, ranking opportunities, and validating- drafts.- </p></div><LemonButtontype="secondary"@@ -145,49 +129,66 @@ export const ContentAutopilot = (): JSX.Element => {onClick={confirmCancelRun}loading={runMutationLoading}>- Cancel run+ Stop drafting</LemonButton></LemonCard>) : lastRun?.run_status === 'failed' ? (<LemonBanner type="error">The latest run failed.{' '}{lastRun.errors.map(({ message }) => message).join(' ') ||- 'Start another run to retry.'}+ 'Select opportunities and draft them again.'}</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}- />- </>- )}+ <LemonTabs+ activeKey={workspaceTab}+ onChange={setWorkspaceTab}+ data-attr="content-autopilot-workspace-tabs"+ tabs={[+ {+ key: 'opportunities',+ label: `Opportunities (${visibleOpportunities.length})`,+ content: <ContentAutopilotOpportunities />,+ },+ {+ key: 'drafts',+ label: `Drafts (${siteProposals.length})`,+ content:+ siteProposals.length === 0 ? (+ <LemonCard hoverEffect={false} className="p-8 text-center">+ <h3 className="m-0">No drafts yet</h3>+ <p className="m-0 mt-2 text-muted max-w-xl mx-auto">+ Pick questions on the Opportunities tab and draft them. Drafts+ show up here for review.+ </p>+ <LemonButton+ type="secondary"+ className="mt-4 mx-auto"+ onClick={() => setWorkspaceTab('opportunities')}+ data-attr="content-autopilot-drafts-empty-opportunities"+ >+ Go to opportunities+ </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}+ />+ </>+ ),+ },+ ]}+ /></>)}diff --git a/products/web_analytics/frontend/contentAutopilot/ContentAutopilotOpportunities.tsx b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotOpportunities.tsxnew file mode 100644index 000000000000..5eaa407c67c3--- /dev/null+++ b/products/web_analytics/frontend/contentAutopilot/ContentAutopilotOpportunities.tsx@@ -0,0 +1,291 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonCard,+ LemonCheckbox,+ LemonInput,+ LemonSkeleton,+ LemonSwitch,+ LemonTable,+ LemonTag,+ Link,+} from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'+import { faviconUrl, parseWebAnalyticsURL } from 'scenes/web-analytics/common'++import type { ContentAutopilotOpportunityApi } from 'products/web_analytics/frontend/generated/api.schemas'++import { MAX_DRAFTS_PER_RUN, contentAutopilotLogic } from './contentAutopilotLogic'++const ENGINE_LABELS: Record<string, string> = {+ 'claude-web-search': 'Claude',+ 'openai-web-search': 'ChatGPT',+ 'exa-answer': 'Exa',+}++const STATUS_TAGS: Record<ContentAutopilotOpportunityApi['status'], JSX.Element | null> = {+ new: null,+ queued: <LemonTag type="completion">Drafting</LemonTag>,+ drafted: <LemonTag type="success">Drafted</LemonTag>,+ dismissed: <LemonTag type="muted">Dismissed</LemonTag>,+}++const engineLabel = (engine: string): string => ENGINE_LABELS[engine] ?? engine++const visibilityTag = (gap: ContentAutopilotOpportunityApi['gap']): JSX.Element => {+ const answers = pluralize(gap.checks, 'answer')+ if (gap.cited_checks > 0) {+ return <LemonTag type="warning">{`Cited in ${gap.cited_checks} of ${answers}`}</LemonTag>+ }+ if (gap.mentioned_checks) {+ return <LemonTag type="highlight">{`Mentioned in ${gap.mentioned_checks} of ${answers}, not cited`}</LemonTag>+ }+ return <LemonTag type="danger">Not mentioned</LemonTag>+}++export const ContentAutopilotOpportunities = (): JSX.Element => {+ const {+ profile,+ opportunities,+ opportunitiesLoading,+ opportunitiesError,+ visibleOpportunities,+ dismissedOpportunityCount,+ showDismissedOpportunities,+ selectedOpportunityIds,+ draftDisabledReason,+ runMutationLoading,+ dismissingOpportunityId,+ opportunitySearch,+ } = useValues(contentAutopilotLogic)+ const {+ refreshOpportunities,+ toggleOpportunitySelection,+ draftOpportunities,+ dismissOpportunity,+ selectProposal,+ setShowDismissedOpportunities,+ setOpportunitySearch,+ } = useActions(contentAutopilotLogic)+ const siteName = profile?.name || profile?.domain || 'this site'++ return (+ <section className="flex flex-col gap-3">+ <p className="m-0 text-muted max-w-3xl">+ Questions AI assistants answered without citing {siteName}, most promising first. Pick up to{' '}+ {MAX_DRAFTS_PER_RUN} and draft them.+ </p>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <LemonInput+ type="search"+ size="small"+ placeholder="Search questions"+ value={opportunitySearch}+ onChange={setOpportunitySearch}+ className="w-72"+ data-attr="content-autopilot-search-opportunities"+ />+ <div className="flex flex-wrap items-center gap-2">+ {dismissedOpportunityCount > 0 ? (+ <LemonSwitch+ checked={showDismissedOpportunities}+ onChange={setShowDismissedOpportunities}+ label={`Show dismissed (${dismissedOpportunityCount})`}+ bordered+ size="small"+ />+ ) : null}+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconRefresh />}+ onClick={refreshOpportunities}+ loading={opportunitiesLoading}+ data-attr="content-autopilot-refresh-opportunities"+ >+ Refresh+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={draftOpportunities}+ loading={runMutationLoading}+ disabledReason={draftDisabledReason}+ data-attr="content-autopilot-draft-opportunities"+ >+ {selectedOpportunityIds.length > 0+ ? `Draft ${pluralize(selectedOpportunityIds.length, 'page')}`+ : 'Draft selected'}+ </LemonButton>+ </div>+ </div>++ {opportunitiesError ? (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: refreshOpportunities, loading: opportunitiesLoading }}+ >+ {opportunities === null+ ? "Couldn't load opportunities."+ : "Couldn't refresh opportunities. The list below may be out of date."}{' '}+ {opportunitiesError}+ </LemonBanner>+ ) : null}+ {opportunities === null ? (+ opportunitiesError ? null : (+ <LemonSkeleton className="h-40 w-full" />+ )+ ) : visibleOpportunities.length === 0 ? (+ <LemonCard hoverEffect={false} className="p-6 text-center">+ {opportunitySearch.trim() ? (+ <p className="m-0 text-muted">No questions match your search.</p>+ ) : dismissedOpportunityCount > 0 ? (+ <>+ <h3 className="m-0">All questions are dismissed</h3>+ <p className="m-0 mt-2 text-muted max-w-xl mx-auto">+ Turn on "Show dismissed" to see them again, or refresh to check for new citation gaps.+ </p>+ </>+ ) : (+ <>+ <h3 className="m-0">No citation gaps found</h3>+ <p className="m-0 mt-2 text-muted max-w-xl mx-auto">+ Opportunities appear when AI citation checks show an assistant answering a tracked+ question without citing {siteName}. If checks haven't run for this project yet, there's+ nothing to show.+ </p>+ </>+ )}+ </LemonCard>+ ) : (+ <LemonTable+ dataSource={visibleOpportunities}+ rowKey="id"+ pagination={{ pageSize: 25 }}+ columns={[+ {+ key: 'select',+ width: 0,+ render: (_, opportunity) => (+ <LemonCheckbox+ checked={selectedOpportunityIds.includes(opportunity.id)}+ onChange={() => toggleOpportunitySelection(opportunity.id)}+ disabledReason={+ opportunity.status === 'queued' || opportunity.status === 'dismissed'+ ? 'This opportunity is not available to draft'+ : undefined+ }+ aria-label={`Select ${opportunity.title}`}+ />+ ),+ },+ {+ title: 'Question',+ key: 'title',+ render: (_, opportunity) => (+ <div className="flex flex-wrap items-center gap-2 py-2 min-w-60">+ <span className="font-semibold">{opportunity.title}</span>+ {STATUS_TAGS[opportunity.status]}+ </div>+ ),+ },+ {+ title: 'In AI answers',+ key: 'visibility',+ render: (_, { gap }) => (+ <div className="whitespace-nowrap">+ {visibilityTag(gap)}+ {gap.engines_not_citing.length > 0 ? (+ <div className="text-xs text-muted mt-1">+ Not cited by {gap.engines_not_citing.map(engineLabel).join(', ')}+ </div>+ ) : null}+ </div>+ ),+ },+ {+ title: 'Cited instead',+ key: 'competitors',+ render: (_, { gap }) =>+ gap.competitor_domains.length > 0 ? (+ <div className="flex flex-col gap-1">+ {gap.competitor_domains.slice(0, 3).map((domain) => (+ <span key={domain} className="flex items-center gap-1 text-sm">+ <img+ src={faviconUrl(domain)}+ width={16}+ height={16}+ alt=""+ className="shrink-0"+ onError={(e) => (e.currentTarget.style.display = 'none')}+ />+ <span className="truncate">{domain}</span>+ </span>+ ))}+ </div>+ ) : (+ <span className="text-sm text-muted">No sources cited</span>+ ),+ },+ {+ title: 'Suggested fix',+ key: 'recommendation',+ render: (_, opportunity) =>+ opportunity.recommended_type === 'page_improvement' && opportunity.target_url ? (+ <span className="text-sm">+ Update{' '}+ <Link to={opportunity.target_url} target="_blank">+ {parseWebAnalyticsURL(opportunity.target_url).pathname ??+ opportunity.target_url}+ </Link>+ </span>+ ) : (+ <span className="text-sm text-muted">Decided when drafting</span>+ ),+ },+ {+ key: 'actions',+ render: (_, opportunity) => (+ <div className="flex flex-wrap justify-end gap-1">+ {opportunity.proposal_id && opportunity.status === 'drafted' ? (+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => selectProposal(opportunity.proposal_id)}+ data-attr="content-autopilot-review-opportunity-draft"+ >+ Review draft+ </LemonButton>+ ) : null}+ {opportunity.status !== 'dismissed' ? (+ <LemonButton+ size="small"+ type="tertiary"+ onClick={() => dismissOpportunity(opportunity.id)}+ loading={dismissingOpportunityId === opportunity.id}+ disabledReason={+ opportunity.status === 'queued'+ ? 'Wait for the draft to finish'+ : dismissingOpportunityId &&+ dismissingOpportunityId !== opportunity.id+ ? 'Wait for the other question to finish dismissing'+ : undefined+ }+ data-attr="content-autopilot-dismiss-opportunity"+ >+ Dismiss+ </LemonButton>+ ) : null}+ </div>+ ),+ },+ ]}+ />+ )}+ </section>+ )+}diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.tsindex 48760142dbe5..af6e1ddccacc 100644--- a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.test.ts@@ -24,7 +24,11 @@ import {webAnalyticsContentAutopilotRunsList,webAnalyticsContentAutopilotRunsStart,} from '../generated/api'-import type { ContentAutopilotProposalListApi, ContentAutopilotRunApi } from '../generated/api.schemas'+import type {+ ContentAutopilotOpportunityApi,+ ContentAutopilotProposalListApi,+ ContentAutopilotRunApi,+} from '../generated/api.schemas'import { contentAutopilotLogic } from './contentAutopilotLogic'import {EXAMPLE_OPPORTUNITIES,@@ -316,6 +320,48 @@ describe('contentAutopilotLogic', () => {expect(mountedLogic.values.runs).toEqual([secondRun])})+ it('ignores refresh and drafting results for a site the user switched away from', async () => {+ mockProfilesList.mockResolvedValue(paginated([EXAMPLE_PROFILE, EXAMPLE_SECOND_PROFILE]))+ const mountedLogic = await mountWorkspace()+ const [first] = EXAMPLE_OPPORTUNITIES+ const secondSiteOpportunity: ContentAutopilotOpportunityApi = {+ ...first,+ id: '00000000-0000-4000-8000-000000000399',+ profile_id: EXAMPLE_SECOND_PROFILE.id,+ }+ const staleRefresh = deferred<typeof EXAMPLE_OPPORTUNITIES>()+ const staleDraft = deferred<ContentAutopilotRunApi>()+ const secondSiteLoad = deferred<ReturnType<typeof paginated<ContentAutopilotOpportunityApi>>>()+ mockOpportunitiesRefresh.mockReturnValueOnce(staleRefresh.promise)+ mockOpportunitiesDraft.mockReturnValueOnce(staleDraft.promise)+ jest.mocked(webAnalyticsContentAutopilotOpportunitiesList).mockImplementation((_, params) =>+ params?.profile_id === EXAMPLE_SECOND_PROFILE.id+ ? secondSiteLoad.promise+ : Promise.resolve(paginated([{ ...first, title: 'Refreshed for the first site' }]))+ )++ mountedLogic.actions.refreshOpportunities()+ mountedLogic.actions.toggleOpportunitySelection(first.id)+ mountedLogic.actions.draftOpportunities()+ mountedLogic.actions.selectProfile(EXAMPLE_SECOND_PROFILE.id)+ mountedLogic.actions.toggleOpportunitySelection(secondSiteOpportunity.id)++ staleRefresh.resolve(EXAMPLE_OPPORTUNITIES)+ staleDraft.resolve({ ...EXAMPLE_RUN, run_status: 'pending', profile_id: EXAMPLE_PROFILE.id })+ await expectLogic(mountedLogic).toDispatchActionsInAnyOrder([+ 'refreshOpportunitiesSuccess',+ 'draftOpportunitiesSuccess',+ ])+ expect(mountedLogic.values.opportunities).toBeNull()+ expect(mountedLogic.values.workspaceTab).toBe('opportunities')++ secondSiteLoad.resolve(paginated([secondSiteOpportunity]))+ await expectLogic(mountedLogic).toFinishAllListeners()+ expect(mountedLogic.values.opportunities).toEqual([secondSiteOpportunity])+ expect(mountedLogic.values.selectedOpportunityIds).toEqual([secondSiteOpportunity.id])+ expect(mountedLogic.values.workspaceTab).toBe('opportunities')+ })+it('groups the proposals returned for the selected site', async () => {const newContent: ContentAutopilotProposalListApi = {...EXAMPLE_PROPOSAL_LIST,diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.tsindex 22f9e4488245..09dc5846fcbe 100644--- a/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotLogic.ts@@ -138,6 +138,7 @@ export interface contentAutopilotLogicValues {dismissedOpportunity: ContentAutopilotOpportunityApi | nulldismissedOpportunityCount: numberdismissedOpportunityLoading: boolean+ dismissingOpportunityId: string | nulldraftDisabledReason: string | undefinedexportedProposal: ContentAutopilotExportResponseApi | nullexportedProposalLoading: boolean@@ -208,6 +209,9 @@ export interface contentAutopilotLogicActions {runMutation: ContentAutopilotRunApipayload?: string}+ clearOpportunitySelection: () => {+ value: true+ }deleteProfile: (profileId: string) => stringdeleteProfileFailure: (error: string,@@ -396,12 +400,12 @@ export interface contentAutopilotLogicActions {errorObject?: any}refreshOpportunitiesSuccess: (- opportunities: ContentAutopilotOpportunityApi[],+ opportunities: ContentAutopilotOpportunityApi[] | null,payload?: {value: true}) => {- opportunities: ContentAutopilotOpportunityApi[]+ opportunities: ContentAutopilotOpportunityApi[] | nullpayload?: {value: true}@@ -585,6 +589,7 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([loadOpportunities: true,refreshOpportunities: true,toggleOpportunitySelection: (opportunityId: string) => ({ opportunityId }),+ clearOpportunitySelection: true,setShowDismissedOpportunities: (showDismissedOpportunities: boolean) => ({ showDismissedOpportunities }),setOpportunitySearch: (opportunitySearch: string) => ({ opportunitySearch }),setWorkspaceTab: (workspaceTab: ContentAutopilotWorkspaceTab) => ({ workspaceTab }),@@ -638,7 +643,6 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([{setWorkspaceTab: (_, { workspaceTab }) => workspaceTab,selectProfile: () => 'opportunities',- draftOpportunitiesSuccess: () => 'drafts',},],opportunitySearch: [@@ -656,13 +660,22 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([? state.filter((id) => id !== opportunityId): [...state, opportunityId],selectProfile: () => [],- draftOpportunitiesSuccess: () => [],+ clearOpportunitySelection: () => [],loadOpportunitiesSuccess: (state, { opportunities }) => draftableSelection(state, opportunities),- refreshOpportunitiesSuccess: (state, { opportunities }) => draftableSelection(state, opportunities),+ refreshOpportunitiesSuccess: (state, { opportunities }) =>+ opportunities ? draftableSelection(state, opportunities) : state,dismissOpportunitySuccess: (state, { dismissedOpportunity }) =>state.filter((id) => id !== dismissedOpportunity.id),},],+ dismissingOpportunityId: [+ null as string | null,+ {+ dismissOpportunity: (_, opportunityId) => opportunityId,+ dismissOpportunitySuccess: () => null,+ dismissOpportunityFailure: () => null,+ },+ ],showDismissedOpportunities: [false,{@@ -802,7 +815,7 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([breakpoint()const opportunities = await fetchOpportunities(teamId, profile.id)breakpoint()- return opportunities+ return values.profile?.id === profile.id ? opportunities : values.opportunities},},],@@ -1204,8 +1217,13 @@ export const contentAutopilotLogic = kea<contentAutopilotLogicType>([deleteProfileFailure: ({ errorObject }) => {lemonToast.error(getErrorMessage(errorObject))},- draftOpportunitiesSuccess: () => {+ draftOpportunitiesSuccess: ({ runMutation }) => {lemonToast.success('Drafting started. Each draft takes a few minutes.')+ if (runMutation.profile_id !== values.profile?.id) {+ return+ }+ actions.clearOpportunitySelection()+ actions.setWorkspaceTab('drafts')actions.loadRuns()actions.loadOpportunities()},