: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
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 {
webAnalyticsContentAutopilotOpportunitiesDraft,
webAnalyticsContentAutopilotOpportunitiesList,
webAnalyticsContentAutopilotOpportunitiesRefresh,
webAnalyticsContentAutopilotProfilesCreate,
webAnalyticsContentAutopilotProfilesDestroy,
webAnalyticsContentAutopilotProfilesDiscover,
webAnalyticsContentAutopilotProfilesList,
webAnalyticsContentAutopilotProfilesPartialUpdate,
webAnalyticsContentAutopilotProposalsEdit,
webAnalyticsContentAutopilotProposalsExport,
webAnalyticsContentAutopilotProposalsList,
webAnalyticsContentAutopilotProposalsRegenerate,
webAnalyticsContentAutopilotProposalsReject,
webAnalyticsContentAutopilotProposalsRetrieve,
webAnalyticsContentAutopilotRunsCancel,
webAnalyticsContentAutopilotRunsList,
webAnalyticsContentAutopilotRunsStart,
} from '../generated/api'
import type {
ContentAutopilotOpportunityApi,
ContentAutopilotProposalListApi,
ContentAutopilotRunApi,
} from '../generated/api.schemas'
import { contentAutopilotLogic } from './contentAutopilotLogic'
import {
EXAMPLE_OPPORTUNITIES,
EXAMPLE_PROFILE,
EXAMPLE_PROPOSAL,
EXAMPLE_PROPOSAL_LIST,
EXAMPLE_RUN,
EXAMPLE_SECOND_PROFILE,
} 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(),
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 mockOpportunitiesDraft = jest.mocked(webAnalyticsContentAutopilotOpportunitiesDraft)
const mockOpportunitiesRefresh = jest.mocked(webAnalyticsContentAutopilotOpportunitiesRefresh)
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)
mockOpportunitiesRefresh.mockResolvedValue(EXAMPLE_OPPORTUNITIES)
jest.mocked(webAnalyticsContentAutopilotOpportunitiesList).mockResolvedValue(paginated(EXAMPLE_OPPORTUNITIES))
mockOpportunitiesDraft.mockResolvedValue({ ...EXAMPLE_RUN, run_status: 'pending', completed_at: null })
})
afterEach(() => {
logic?.unmount()
})
const mountWorkspace = async (): Promise<ReturnType<typeof contentAutopilotLogic.build>> => {
logic = contentAutopilotLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
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('skips the refresh on open when the citation data was read in the last hour, but not after a settings save', async () => {
const freshOpportunities = EXAMPLE_OPPORTUNITIES.map((opportunity) => ({
...opportunity,
last_refreshed_at: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
}))
jest.mocked(webAnalyticsContentAutopilotOpportunitiesList).mockResolvedValue(paginated(freshOpportunities))
const mountedLogic = await mountWorkspace()
expect(mountedLogic.values.opportunities).toEqual(freshOpportunities)
expect(mockOpportunitiesRefresh).not.toHaveBeenCalled()
await expectLogic(mountedLogic, () => mountedLogic.actions.saveProfile()).toDispatchActions([
'saveProfileSuccess',
'loadOpportunitiesSuccess',
'refreshOpportunities',
])
expect(mockOpportunitiesRefresh).toHaveBeenCalledTimes(1)
})
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')
// A row's draft button sends only that row, leaves the table selection alone,
// and blocks every other draft trigger until the request settles.
mountedLogic.actions.toggleOpportunitySelection(first.id)
mountedLogic.actions.setWorkspaceTab('prompts')
const rowDraft = deferred<ContentAutopilotRunApi>()
mockOpportunitiesDraft.mockReturnValueOnce(rowDraft.promise)
mountedLogic.actions.draftOpportunities([second.id])
expect(mountedLogic.values.rowDraftDisabledReason).toBe('Wait for the current run to finish')
expect(mountedLogic.values.draftDisabledReason).toBe('Wait for the current run to finish')
rowDraft.resolve({ ...EXAMPLE_RUN, run_status: 'pending', profile_id: EXAMPLE_PROFILE.id })
await expectLogic(mountedLogic).toFinishAllListeners()
expect(mockOpportunitiesDraft).toHaveBeenLastCalledWith(String(MOCK_DEFAULT_TEAM.id), {
profile_id: EXAMPLE_PROFILE.id,
opportunity_ids: [second.id],
})
expect(mountedLogic.values.selectedOpportunityIds).toEqual([first.id])
// Drafting from a prompt keeps the user on the Prompts tab.
expect(mountedLogic.values.workspaceTab).toBe('prompts')
})
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',
})
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'],
})
})
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('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('overview')
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('overview')
})
it('lists queued pages last only while their run is active, and keeps only run-level errors', async () => {
const rejected: ContentAutopilotProposalListApi = {
...EXAMPLE_PROPOSAL_LIST,
id: '00000000-0000-4000-8000-000000000202',
lifecycle_status: 'rejected',
}
const failed: ContentAutopilotProposalListApi = {
...EXAMPLE_PROPOSAL_LIST,
id: '00000000-0000-4000-8000-000000000203',
lifecycle_status: 'failed',
}
const ready: ContentAutopilotProposalListApi = {
...EXAMPLE_PROPOSAL_LIST,
lifecycle_status: 'ready_for_review',
}
const failedInAnOlderRun: ContentAutopilotProposalListApi = {
...EXAMPLE_PROPOSAL_LIST,
id: '00000000-0000-4000-8000-000000000204',
run_id: '00000000-0000-4000-8000-000000000199',
lifecycle_status: 'failed',
}
const queued: ContentAutopilotOpportunityApi = {
...EXAMPLE_OPPORTUNITIES[0],
id: '00000000-0000-4000-8000-000000000301',
status: 'queued',
run_id: EXAMPLE_RUN.id,
proposal_id: null,
}
const redraftedFromAnOlderRun: ContentAutopilotOpportunityApi = {
...EXAMPLE_OPPORTUNITIES[0],
id: '00000000-0000-4000-8000-000000000302',
status: 'queued',
run_id: EXAMPLE_RUN.id,
proposal_id: failedInAnOlderRun.id,
}
const startedInThisRun: ContentAutopilotOpportunityApi = {
...EXAMPLE_OPPORTUNITIES[0],
id: '00000000-0000-4000-8000-000000000303',
status: 'queued',
run_id: EXAMPLE_RUN.id,
proposal_id: failed.id,
}
mockProposalsList.mockResolvedValue(paginated([rejected, failed, failedInAnOlderRun, ready]))
jest.mocked(webAnalyticsContentAutopilotOpportunitiesList).mockResolvedValue(
paginated([queued, redraftedFromAnOlderRun, startedInThisRun])
)
mockRunsList.mockResolvedValue(paginated([{ ...EXAMPLE_RUN, run_status: 'generating' }]))
const mountedLogic = await mountWorkspace()
expect(mountedLogic.values.draftRows.map(({ id }) => id)).toEqual([
ready.id,
failed.id,
failedInAnOlderRun.id,
rejected.id,
queued.id,
redraftedFromAnOlderRun.id,
])
mockRunsList.mockResolvedValue(
paginated([
{
...EXAMPLE_RUN,
run_status: 'failed',
errors: [
{
error_code: 'checks_failed',
message: "A question: the draft didn't pass its checks. Open it to see what to fix.",
},
{
error_code: 'timed_out',
message: 'Drafting took too long. Try fewer opportunities at once.',
},
],
},
])
)
mountedLogic.actions.loadRuns()
await expectLogic(mountedLogic).toFinishAllListeners()
expect(mountedLogic.values.draftRows.map(({ id }) => id)).toEqual([
ready.id,
failed.id,
failedInAnOlderRun.id,
rejected.id,
])
expect(mountedLogic.values.readyDraftCount).toBe(1)
expect(mountedLogic.values.latestRunErrors).toEqual([
'Drafting took too long. Try fewer opportunities at once.',
])
})
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 draft ready for review can be rejected',
undefined,
'Only a draft ready for review can be edited',
'Only a draft ready for review can be downloaded',
],
[
'rejected' as const,
'Only a draft ready for review can be rejected',
'Only drafts ready for review or failed can be regenerated',
'Only a draft ready for review can be edited',
'Only a draft ready for review can be downloaded',
],
[
'generating' as const,
'Only a draft ready for review can be rejected',
'Only drafts ready for review or failed can be regenerated',
'Only a draft ready for review can be edited',
'Only a draft ready for review can be downloaded',
],
[
'exported' as const,
'Only a draft ready for review can be rejected',
'Only drafts ready for review or failed can be regenerated',
'Only a draft ready for review can be edited',
'Only a draft ready for review can be downloaded',
],
])(
'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)
})
})