: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 { pluralize } from 'lib/utils/strings'
import { parseWebAnalyticsURL } from 'scenes/web-analytics/common'
import type {
AEOPromptCheckApi,
AEOPromptApi,
AEOPromptImportResultApi,
ContentAutopilotOpportunityApi,
ContentAutopilotProposalListApi,
PatchedAEOPromptUpdateRequestApi,
} from 'products/web_analytics/frontend/generated/api.schemas'
const OPPORTUNITIES_STALE_AFTER_MS = 60 * 60 * 1000
export const ENGINE_LABELS: Record<string, string> = {
'claude-web-search': 'Claude',
'openai-web-search': 'ChatGPT',
'exa-answer': 'Exa',
'gemini-google-search': 'Gemini',
}
export const engineLabel = (engine: string): string => ENGINE_LABELS[engine] ?? engine
/** Known engines first, in a fixed order, so table columns don't move between pages. */
export const sortEngines = (engines: Iterable<string>): string[] => {
const known = Object.keys(ENGINE_LABELS)
const rank = (engine: string): number => (known.includes(engine) ? known.indexOf(engine) : known.length)
return [...new Set(engines)].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
}
export type ContentAutopilotPageTarget =
| { isNewPage: true; path: string }
| { isNewPage: false; path: string; url: string }
export const proposalPagePath = (proposal: Pick<ContentAutopilotProposalListApi, 'file_path' | 'target_url'>): string =>
(proposal.target_url && parseWebAnalyticsURL(proposal.target_url).pathname) ||
(proposal.file_path ? `/${proposal.file_path.replace(/\.mdx?$/, '')}` : '')
export const pageToUpdate = (
opportunity: Pick<ContentAutopilotOpportunityApi, 'recommended_type' | 'target_url'>,
proposal: ContentAutopilotProposalListApi | undefined
): ContentAutopilotPageTarget | null => {
if (proposal && proposal.lifecycle_status !== 'generating') {
const path = proposalPagePath(proposal)
if (proposal.proposal_type === 'new_content' && path) {
return { isNewPage: true, path }
}
if (proposal.proposal_type !== 'new_content' && proposal.target_url) {
return { isNewPage: false, path, url: proposal.target_url }
}
}
if (opportunity.recommended_type === 'page_improvement' && opportunity.target_url) {
return {
isNewPage: false,
path: parseWebAnalyticsURL(opportunity.target_url).pathname ?? opportunity.target_url,
url: opportunity.target_url,
}
}
return null
}
export const opportunitiesNeedRefresh = (
opportunities: Pick<ContentAutopilotOpportunityApi, 'last_refreshed_at'>[],
now: number
): boolean => {
const refreshedAt = opportunities
.map(({ last_refreshed_at }) => Date.parse(last_refreshed_at))
.filter((time) => !Number.isNaN(time))
return refreshedAt.length === 0 || now - Math.max(...refreshedAt) > OPPORTUNITIES_STALE_AFTER_MS
}
// Checks recorded before prompts had versions carry no version. A prompt's text could not change
// before then, so those checks all ran the text that became version 1.
export const checkPromptVersion = (check: Pick<AEOPromptCheckApi, 'prompt_version'>): number =>
check.prompt_version ?? 1
export const promptLines = (text: string): string[] => {
const seen = new Set<string>()
return text
.split('\n')
.map((line) => line.trim())
.filter((line) => {
const key = line.toLowerCase()
if (!line || seen.has(key)) {
return false
}
seen.add(key)
return true
})
}
export const promptImportMessage = ({ created, updated, skipped }: AEOPromptImportResultApi): string => {
const sentences = [
created ? `Added ${pluralize(created, 'prompt')}. The next daily run checks new prompts.` : null,
updated ? `Updated ${pluralize(updated, 'existing prompt')}.` : null,
skipped ? `Skipped ${pluralize(skipped, 'prompt')} (empty, too long, or archived).` : null,
].filter(Boolean)
return sentences.join(' ') || 'No prompts changed.'
}
export const promptEditPatch = (
prompt: Pick<AEOPromptApi, 'prompt' | 'topic'>,
text: string,
topic: string
): PatchedAEOPromptUpdateRequestApi | null => {
const patch: PatchedAEOPromptUpdateRequestApi = {}
if (text.trim() !== prompt.prompt) {
patch.prompt = text.trim()
}
if (topic.trim() !== prompt.topic) {
patch.topic = topic.trim()
}
return Object.keys(patch).length ? patch : null
}
const normalizedPrompt = (text: string): string => text.trim().replace(/\s+/g, ' ').toLowerCase()
// An opportunity drafts from the text it was found for, so after an edit it stays hidden until a refresh matches it.
export const draftableOpportunity = (
opportunityByPromptId: Record<string, ContentAutopilotOpportunityApi>,
prompt: Pick<AEOPromptApi, 'id' | 'prompt'>
): ContentAutopilotOpportunityApi | null => {
const opportunity = opportunityByPromptId[prompt.id]
return opportunity && normalizedPrompt(opportunity.title) === normalizedPrompt(prompt.prompt) ? opportunity : null
}