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): draft selected content opportunities (#109188)

Jordan Mryyanf9b9026323c6
diff --git a/products/aeo/README.md b/products/aeo/README.md
index 8636906856a0..57fce657523c 100644
--- a/products/aeo/README.md
+++ b/products/aeo/README.md
@@ -76,6 +76,10 @@ WHERE $channel_type = 'AI' AND $entry_pathname = '/docs/session-replay'
AND $start_timestamp >= now() - INTERVAL 30 DAY
```
+## Content autopilot
+
+Web analytics' Content autopilot (`/web/content-autopilot`, flag `web-analytics-content-autopilot`) reads this table through `list_citation_gaps` in `facade/api.py`. Each active prompt that an engine answered without citing a target domain becomes a content opportunity, and a person picks which ones to draft. Drafting and its review flow live in `products/web_analytics/backend/content_autopilot/`.
+
## Cost
Roughly \$2–4/day at 50 prompts × 3 engines × 1 run/day: provider web-search fees + tokens (attributed as `$ai_web_search_cost_usd` and `$ai_total_cost_usd` on the `$ai_generation` event) plus Exa at \$5 per 1,000 requests (`cost_usd` on the check event).
diff --git a/products/web_analytics/backend/content_autopilot/generation.py b/products/web_analytics/backend/content_autopilot/generation.py
index 7195ca08b07e..062902c7a857 100644
--- a/products/web_analytics/backend/content_autopilot/generation.py
+++ b/products/web_analytics/backend/content_autopilot/generation.py
@@ -9,6 +9,7 @@ from django.utils import timezone
import structlog
from anthropic import Anthropic
+from celery.exceptions import SoftTimeLimitExceeded
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
@@ -90,6 +91,7 @@ MIN_EDIT_WORDS = 300
MAX_EDIT_WORDS = 1_200
PAGE_OPENING_CHARS = 2_000
MAX_KEY_SITE_PAGES = 200
+TIMED_OUT_PROPOSAL_MESSAGE = "Drafting took too long. Regenerate to try again."
MAX_REQUESTED_SITE_PAGES = 3
DRAFT_ATTEMPTS = 2
@@ -851,6 +853,14 @@ def _fail_proposal(proposal: ContentAutopilotProposal | None, message: str) -> N
)
+def _fail_unfinished_proposal(proposal: ContentAutopilotProposal | None, message: str) -> None:
+ if proposal is None:
+ return
+ proposal.refresh_from_db(fields=["lifecycle_status"])
+ if proposal.lifecycle_status == ContentAutopilotProposal.LifecycleStatus.GENERATING:
+ _fail_proposal(proposal, message)
+
+
def _draft_opportunity(
client: Anthropic,
*,
@@ -871,6 +881,10 @@ def _draft_opportunity(
"message": f"{title}: the draft didn't pass its checks. Open it to see what to fix.",
}
)
+ except SoftTimeLimitExceeded:
+ opportunity.refresh_from_db(fields=["proposal"])
+ _fail_unfinished_proposal(opportunity.proposal, TIMED_OUT_PROPOSAL_MESSAGE)
+ raise
except ContentAutopilotLLMError as error:
errors.append({"error_code": "generation_failed", "message": f"{title}: {error}"})
_fail_proposal(opportunity.proposal, str(error))
@@ -880,9 +894,10 @@ def _draft_opportunity(
errors.append({"error_code": "generation_failed", "message": f"{title}: something went wrong while drafting."})
opportunity.refresh_from_db(fields=["proposal"])
_fail_proposal(opportunity.proposal, "Something went wrong while drafting. Regenerate to try again.")
- if opportunity.proposal_id:
- opportunity.status = ContentAutopilotOpportunity.Status.DRAFTED
- opportunity.save(update_fields=["status", "updated_at"])
+ finally:
+ if opportunity.proposal_id:
+ opportunity.status = ContentAutopilotOpportunity.Status.DRAFTED
+ opportunity.save(update_fields=["status", "updated_at"])
return ready
@@ -915,6 +930,8 @@ def generate_run(team_id: int, run_id: str, *, client: Anthropic | None = None)
break
if _draft_opportunity(resolved_client, run=run, opportunity=opportunity, site=site, errors=errors):
ready += 1
+ except SoftTimeLimitExceeded:
+ raise
except ContentAutopilotLLMError as error:
errors.append({"error_code": "generation_failed", "message": str(error)})
except Exception as error:
@@ -929,6 +946,20 @@ def generate_run(team_id: int, run_id: str, *, client: Anthropic | None = None)
finish_run(team_id, run_id, errors=errors, ready=ready)
+def finish_timed_out_run(team_id: int, run_id: str) -> None:
+ ready = (
+ ContentAutopilotProposal.objects.for_team(team_id)
+ .filter(run_id=run_id, lifecycle_status=ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW)
+ .count()
+ )
+ error = {"error_code": "timed_out", "message": "Drafting took too long. Try fewer opportunities at once."}
+ finish_run(team_id, run_id, errors=[error], ready=ready)
+
+
+def fail_proposal(team_id: int, proposal_id: str, message: str) -> None:
+ _fail_proposal(ContentAutopilotProposal.objects.for_team(team_id).get(id=proposal_id), message)
+
+
def finish_run(team_id: int, run_id: str, *, errors: list[dict[str, str]], ready: int) -> None:
with transaction.atomic():
run = ContentAutopilotRun.objects.for_team(team_id).select_for_update().get(id=run_id)
@@ -987,6 +1018,8 @@ def process_proposal(team_id: int, proposal_id: str, mode: ProposalMode, *, clie
original_markdown=proposal.original_markdown,
)
_save_result(proposal, draft=draft, checks=checks, site=site, research=research)
+ except SoftTimeLimitExceeded:
+ _fail_unfinished_proposal(proposal, TIMED_OUT_PROPOSAL_MESSAGE)
except ContentAutopilotLLMError as error:
_fail_proposal(proposal, str(error))
except Exception as error:
diff --git a/products/web_analytics/backend/content_autopilot/workflow.py b/products/web_analytics/backend/content_autopilot/workflow.py
new file mode 100644
index 000000000000..ee230004efa6
--- /dev/null
+++ b/products/web_analytics/backend/content_autopilot/workflow.py
@@ -0,0 +1,67 @@
+from django.db import transaction
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team import Team
+
+from products.web_analytics.backend.content_autopilot import lifecycle, opportunities
+from products.web_analytics.backend.content_autopilot.generation import ProposalMode, fail_proposal, finish_run
+from products.web_analytics.backend.models import ContentAutopilotProposal, ContentAutopilotRun
+from products.web_analytics.backend.tasks.content_autopilot import (
+ generate_content_autopilot_run_task,
+ process_content_autopilot_proposal_task,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+def _start_run(team_id: int, run_id: str) -> None:
+ try:
+ generate_content_autopilot_run_task.delay(team_id, run_id)
+ except Exception as error:
+ capture_exception(error)
+ logger.exception("content_autopilot_run_dispatch_failed", team_id=team_id, run_id=run_id)
+ error_entry = {
+ "error_code": "dispatch_failed",
+ "message": "Drafting couldn't start. Select opportunities and draft them again.",
+ }
+ finish_run(team_id, run_id, errors=[error_entry], ready=0)
+
+
+def _start_proposal(team_id: int, proposal_id: str, mode: ProposalMode) -> None:
+ try:
+ process_content_autopilot_proposal_task.delay(team_id, proposal_id, mode)
+ except Exception as error:
+ capture_exception(error)
+ logger.exception("content_autopilot_proposal_dispatch_failed", team_id=team_id, proposal_id=proposal_id)
+ fail_proposal(team_id, proposal_id, "Drafting couldn't start. Regenerate to try again.")
+
+
+def draft_opportunities(
+ *, team: Team, profile_id: str, opportunity_ids: list[str], triggered_by_id: int | None
+) -> ContentAutopilotRun:
+ run = opportunities.draft_opportunities(
+ team=team, profile_id=profile_id, opportunity_ids=opportunity_ids, triggered_by_id=triggered_by_id
+ )
+ team_id, run_id = run.team_id, str(run.id)
+ transaction.on_commit(lambda: _start_run(team_id, run_id))
+ return run
+
+
+def edit_proposal(
+ *, team: Team, proposal_id: str, proposed_markdown: str, content_package: dict[str, object]
+) -> ContentAutopilotProposal:
+ proposal = lifecycle.edit_proposal(
+ team=team, proposal_id=proposal_id, proposed_markdown=proposed_markdown, content_package=content_package
+ )
+ team_id = proposal.team_id
+ transaction.on_commit(lambda: _start_proposal(team_id, proposal_id, "validate"))
+ return proposal
+
+
+def regenerate_proposal(*, team: Team, proposal_id: str) -> ContentAutopilotProposal:
+ proposal = lifecycle.regenerate_proposal(team=team, proposal_id=proposal_id)
+ team_id = proposal.team_id
+ transaction.on_commit(lambda: _start_proposal(team_id, proposal_id, "regenerate"))
+ return proposal
diff --git a/products/web_analytics/backend/facade/content_autopilot.py b/products/web_analytics/backend/facade/content_autopilot.py
index c9f7a862cdb8..3f922bf274bd 100644
--- a/products/web_analytics/backend/facade/content_autopilot.py
+++ b/products/web_analytics/backend/facade/content_autopilot.py
@@ -1,26 +1,29 @@
from posthog.models.team import Team
-from products.web_analytics.backend.content_autopilot import opportunities
+from products.web_analytics.backend.content_autopilot import opportunities, workflow
from products.web_analytics.backend.content_autopilot.export import ContentAutopilotExportError, export_proposal
from products.web_analytics.backend.content_autopilot.lifecycle import (
MAX_PROPOSAL_MARKDOWN_CHARS,
ContentAutopilotLifecycleError,
cancel_run,
delete_profile,
- edit_proposal,
- regenerate_proposal,
reject_proposal,
start_run,
)
-from products.web_analytics.backend.content_autopilot.opportunities import MAX_REFRESHED_OPPORTUNITIES
+from products.web_analytics.backend.content_autopilot.opportunities import (
+ MAX_DRAFTS_PER_RUN,
+ MAX_REFRESHED_OPPORTUNITIES,
+)
from products.web_analytics.backend.content_autopilot.site_discovery import (
discover_site,
has_same_public_origin,
normalize_site_origin,
)
+from products.web_analytics.backend.content_autopilot.workflow import edit_proposal, regenerate_proposal
from products.web_analytics.backend.public_url_fetch import PublicUrlFetchError
__all__ = [
+ "MAX_DRAFTS_PER_RUN",
"MAX_PROPOSAL_MARKDOWN_CHARS",
"MAX_REFRESHED_OPPORTUNITIES",
"ContentAutopilotExportError",
@@ -30,6 +33,7 @@ __all__ = [
"delete_profile",
"discover_site",
"dismiss_opportunity",
+ "draft_opportunities",
"edit_proposal",
"export_proposal",
"has_same_public_origin",
@@ -47,3 +51,10 @@ def refresh_opportunities(*, team: Team, profile_id: str) -> None:
def dismiss_opportunity(*, team: Team, opportunity_id: str) -> None:
opportunities.dismiss_opportunity(team=team, opportunity_id=opportunity_id)
+
+
+def draft_opportunities(*, team: Team, profile_id: str, opportunity_ids: list[str], triggered_by_id: int | None) -> str:
+ run = workflow.draft_opportunities(
+ team=team, profile_id=profile_id, opportunity_ids=opportunity_ids, triggered_by_id=triggered_by_id
+ )
+ return str(run.id)
diff --git a/products/web_analytics/backend/management/commands/generate_aeo_content.py b/products/web_analytics/backend/management/commands/generate_aeo_content.py
new file mode 100644
index 000000000000..110321066fe8
--- /dev/null
+++ b/products/web_analytics/backend/management/commands/generate_aeo_content.py
@@ -0,0 +1,98 @@
+import json
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.models.team import Team
+
+from products.web_analytics.backend.content_autopilot.generation import (
+ compose,
+ content_package,
+ generate_run,
+ site_context,
+)
+from products.web_analytics.backend.content_autopilot.llm import build_client
+from products.web_analytics.backend.content_autopilot.opportunities import (
+ MAX_DRAFTS_PER_RUN,
+ draft_opportunities,
+ refresh_opportunities,
+)
+from products.web_analytics.backend.models import ContentAutopilotOpportunity, ContentAutopilotSiteProfile
+
+
+class Command(BaseCommand):
+ help = "Draft content for prompts where AI answer engines don't cite the site, from AEO citation checks."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--team-id", type=int, required=True)
+ parser.add_argument("--profile-id", type=str, help="Content autopilot site profile. Defaults to the first one.")
+ parser.add_argument("--prompt-hash", action="append", default=[], help="Draft this AEO prompt. Repeatable.")
+ parser.add_argument("--limit", type=int, default=1, help="Draft the top N opportunities when no hash is given.")
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Print the brief, draft and checks without saving drafts. The opportunity list is still refreshed.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["limit"] < 1:
+ raise CommandError("--limit must be 1 or more.")
+ team = Team.objects.get(id=options["team_id"])
+ profiles = ContentAutopilotSiteProfile.objects.for_team(team.id).filter(deleted=False).order_by("created_at")
+ profile = profiles.filter(id=options["profile_id"]).first() if options["profile_id"] else profiles.first()
+ if profile is None:
+ raise CommandError("No content autopilot site profile found. Add the site in /web/content-autopilot first.")
+
+ opportunities = refresh_opportunities(team=team, profile_id=str(profile.id))
+ selected = self._select(opportunities, options["prompt_hash"], options["limit"])
+ if not selected:
+ raise CommandError("No matching opportunities. Check that citation checks have run for this team.")
+ self.stdout.write(f"Drafting {len(selected)} opportunities for {profile.domain}")
+
+ if options["dry_run"]:
+ client = build_client(team_id=team.id, properties={"content_autopilot_mode": "dry_run"})
+ site = site_context(profile)
+ for opportunity in selected:
+ composition = compose(
+ client,
+ team_id=team.id,
+ site=site,
+ prompt=opportunity.title,
+ target_url=opportunity.target_url,
+ proposal_type=opportunity.recommended_type,
+ gap=opportunity.gap,
+ )
+ self.stdout.write(f"\n=== {opportunity.title} ({opportunity.recommended_type})")
+ self.stdout.write(json.dumps(composition.brief, indent=2))
+ self.stdout.write(
+ json.dumps(
+ content_package(composition.draft, origin=site.origin, skipped=composition.research.skipped),
+ indent=2,
+ )
+ )
+ self.stdout.write(composition.draft.markdown)
+ for check in composition.checks:
+ self.stdout.write(f"[{'pass' if check.passed else 'FAIL'}] {check.label}: {check.message}")
+ return
+
+ run = draft_opportunities(
+ team=team,
+ profile_id=str(profile.id),
+ opportunity_ids=[str(opportunity.id) for opportunity in selected],
+ triggered_by_id=None,
+ )
+ generate_run(run.team_id, str(run.id))
+ run.refresh_from_db()
+ self.stdout.write(f"Run {run.id} finished as {run.run_status}. Review it in /web/content-autopilot.")
+
+ def _select(
+ self, opportunities: list[ContentAutopilotOpportunity], prompt_hashes: list[str], limit: int
+ ) -> list[ContentAutopilotOpportunity]:
+ if prompt_hashes:
+ return [opportunity for opportunity in opportunities if opportunity.cluster_key in prompt_hashes][
+ :MAX_DRAFTS_PER_RUN
+ ]
+ available = [
+ opportunity for opportunity in opportunities if opportunity.status == ContentAutopilotOpportunity.Status.NEW
+ ]
+ return available[: min(limit, MAX_DRAFTS_PER_RUN)]
diff --git a/products/web_analytics/backend/presentation/views/content_autopilot.py b/products/web_analytics/backend/presentation/views/content_autopilot.py
index c4e49407de35..fa5b1e4861ef 100644
--- a/products/web_analytics/backend/presentation/views/content_autopilot.py
+++ b/products/web_analytics/backend/presentation/views/content_autopilot.py
@@ -24,6 +24,7 @@ from posthog.rate_limit import (
from posthog.security.url_validation import has_authority_bypass_chars
from products.web_analytics.backend.facade.content_autopilot import (
+ MAX_DRAFTS_PER_RUN,
MAX_PROPOSAL_MARKDOWN_CHARS,
MAX_REFRESHED_OPPORTUNITIES,
ContentAutopilotExportError,
@@ -33,6 +34,7 @@ from products.web_analytics.backend.facade.content_autopilot import (
delete_profile,
discover_site,
dismiss_opportunity,
+ draft_opportunities,
edit_proposal,
export_proposal,
has_same_public_origin,
@@ -172,6 +174,69 @@ class ContentAutopilotPackageSerializer(serializers.Serializer):
child=serializers.CharField(),
help_text="Portable source notes included with the export.",
)
+ json_ld = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="JSON-LD structured data to embed in the page, such as an FAQPage document.",
+ )
+ llms_txt_line = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Suggested llms.txt entry for the page.",
+ )
+
+
+class ContentAutopilotBriefCompetitorSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="Product to compare against.")
+ url = serializers.CharField(help_text="The product's own page to research.")
+
+
+class ContentAutopilotBriefSerializer(serializers.Serializer):
+ intent = serializers.CharField(required=False, help_text="What the person asking wants to know or decide.")
+ audience = serializers.CharField(required=False, help_text="Who the content is for.")
+ recommended_type = serializers.CharField(
+ required=False, help_text="Whether the brief recommends new_content or page_improvement."
+ )
+ target_page = serializers.CharField(
+ required=False, allow_blank=True, help_text="Site page the brief chose to improve. Empty for a new page."
+ )
+ site_pages_to_read = serializers.ListField(
+ child=serializers.CharField(), required=False, help_text="Site pages the brief asked to read for facts."
+ )
+ competitors_to_research = ContentAutopilotBriefCompetitorSerializer(
+ many=True, required=False, help_text="Products the brief asked to research for a comparison."
+ )
+ working_title = serializers.CharField(required=False, help_text="Working title for the page.")
+ outline = serializers.ListField(
+ child=serializers.CharField(), required=False, help_text="Planned sections, in order."
+ )
+ questions_to_answer = serializers.ListField(
+ child=serializers.CharField(), required=False, help_text="Questions the page must answer."
+ )
+ competitor_coverage = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ help_text="Topics the cited competitor pages cover that the site's pages don't.",
+ )
+ engine_answer_summary = serializers.CharField(
+ required=False, help_text="What AI answer engines currently say, including what they get wrong."
+ )
+ disambiguation = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="What the question means, when AI answer engines misread which product or company it asks about.",
+ )
+
+
+class ContentAutopilotSourceLedgerEntrySerializer(serializers.Serializer):
+ claim = serializers.CharField(help_text="Factual claim the draft makes.")
+ source_url = serializers.CharField(help_text="Page that supports the claim.")
+ quote = serializers.CharField(help_text="Short quote from the source page.")
+ kind = serializers.ChoiceField(
+ choices=["site", "competitor"],
+ required=False,
+ help_text="Whether the source is one of the site's pages or a competitor's own page.",
+ )
class ContentAutopilotEngineAnswerSerializer(serializers.Serializer):
@@ -358,6 +423,10 @@ class ContentAutopilotProposalSerializer(ContentAutopilotProposalBaseSerializer)
content_package = ContentAutopilotPackageSerializer(
help_text="Structured package that accompanies the exported Markdown."
)
+ brief = ContentAutopilotBriefSerializer(help_text="Content brief the draft was written from.")
+ source_ledger = ContentAutopilotSourceLedgerEntrySerializer(
+ many=True, help_text="Factual claims in the draft and the site pages that support them."
+ )
class Meta:
model = ContentAutopilotProposal
@@ -374,6 +443,8 @@ class ContentAutopilotProposalSerializer(ContentAutopilotProposalBaseSerializer)
"content_package",
"original_markdown",
"proposed_markdown",
+ "brief",
+ "source_ledger",
"created_at",
"updated_at",
]
@@ -487,6 +558,16 @@ class ContentAutopilotOpportunityRefreshRequestSerializer(serializers.Serializer
profile_id = serializers.UUIDField(help_text="Site profile to refresh opportunities for.")
+class ContentAutopilotOpportunityDraftRequestSerializer(serializers.Serializer):
+ profile_id = serializers.UUIDField(help_text="Site profile the opportunities belong to.")
+ opportunity_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ min_length=1,
+ max_length=MAX_DRAFTS_PER_RUN,
+ help_text=f"Opportunities to draft, up to {MAX_DRAFTS_PER_RUN} at a time.",
+ )
+
+
class ContentAutopilotSiteProfileViewSet(ContentAutopilotViewSetMixin, viewsets.ModelViewSet):
serializer_class = ContentAutopilotSiteProfileSerializer
queryset = ContentAutopilotSiteProfile.objects.unscoped()
@@ -690,3 +771,22 @@ class ContentAutopilotOpportunityViewSet(ContentAutopilotViewSetMixin, viewsets.
dismiss_opportunity(team=self.team, opportunity_id=str(opportunity.id))
opportunity.refresh_from_db()
return Response(self.get_serializer(opportunity).data)
+
+ @validated_request(
+ request_serializer=ContentAutopilotOpportunityDraftRequestSerializer,
+ operation_id="web_analytics_content_autopilot_opportunities_draft",
+ summary="Draft content for opportunities",
+ description="Starts a run that researches and drafts content for the selected opportunities.",
+ responses={202: OpenApiResponse(response=ContentAutopilotRunSerializer)},
+ tags=["web_analytics"],
+ )
+ @action(detail=False, methods=["post"], required_scopes=["web_analytics:write"])
+ def draft(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ run_id = draft_opportunities(
+ team=self.team,
+ profile_id=str(request.validated_data["profile_id"]),
+ opportunity_ids=[str(opportunity_id) for opportunity_id in request.validated_data["opportunity_ids"]],
+ triggered_by_id=getattr(request.user, "id", None),
+ )
+ run = ContentAutopilotRun.objects.for_team(self.team_id).get(id=run_id)
+ return Response(ContentAutopilotRunSerializer(run).data, status=status.HTTP_202_ACCEPTED)
diff --git a/products/web_analytics/backend/tasks/__init__.py b/products/web_analytics/backend/tasks/__init__.py
index 08bcc3a63317..4138c4856845 100644
--- a/products/web_analytics/backend/tasks/__init__.py
+++ b/products/web_analytics/backend/tasks/__init__.py
@@ -1,3 +1,3 @@
-from . import heatmap_screenshot, lazy_precompute_revalidation
+from . import content_autopilot, heatmap_screenshot, lazy_precompute_revalidation
-__all__ = ["heatmap_screenshot", "lazy_precompute_revalidation"]
+__all__ = ["content_autopilot", "heatmap_screenshot", "lazy_precompute_revalidation"]
diff --git a/products/web_analytics/backend/tasks/content_autopilot.py b/products/web_analytics/backend/tasks/content_autopilot.py
new file mode 100644
index 000000000000..e8e2be50e008
--- /dev/null
+++ b/products/web_analytics/backend/tasks/content_autopilot.py
@@ -0,0 +1,45 @@
+import structlog
+from celery import shared_task
+from celery.exceptions import SoftTimeLimitExceeded
+
+from posthog.models.scoping import with_team_scope
+from posthog.tasks.utils import CeleryQueue
+
+from products.web_analytics.backend.content_autopilot.generation import (
+ ProposalMode,
+ finish_timed_out_run,
+ generate_run,
+ process_proposal,
+)
+
+logger = structlog.get_logger(__name__)
+
+RUN_SOFT_TIME_LIMIT_SECONDS = 60 * 60
+PROPOSAL_SOFT_TIME_LIMIT_SECONDS = 30 * 60
+HARD_TIME_LIMIT_GRACE_SECONDS = 120
+
+
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.LONG_RUNNING.value,
+ soft_time_limit=RUN_SOFT_TIME_LIMIT_SECONDS,
+ time_limit=RUN_SOFT_TIME_LIMIT_SECONDS + HARD_TIME_LIMIT_GRACE_SECONDS,
+)
+@with_team_scope()
+def generate_content_autopilot_run_task(team_id: int, run_id: str) -> None:
+ try:
+ generate_run(team_id, run_id)
+ except SoftTimeLimitExceeded:
+ logger.warning("content_autopilot_run_timed_out", team_id=team_id, run_id=run_id)
+ finish_timed_out_run(team_id, run_id)
+
+
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.LONG_RUNNING.value,
+ soft_time_limit=PROPOSAL_SOFT_TIME_LIMIT_SECONDS,
+ time_limit=PROPOSAL_SOFT_TIME_LIMIT_SECONDS + HARD_TIME_LIMIT_GRACE_SECONDS,
+)
+@with_team_scope()
+def process_content_autopilot_proposal_task(team_id: int, proposal_id: str, mode: ProposalMode) -> None:
+ process_proposal(team_id, proposal_id, mode)
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 c9b9ef15079d..4253869219ce 100644
--- a/products/web_analytics/backend/test/test_content_autopilot_api.py
+++ b/products/web_analytics/backend/test/test_content_autopilot_api.py
@@ -283,16 +283,22 @@ class TestContentAutopilotAPI(APIBaseTest):
regenerated_proposal = create_content_autopilot_proposal(self.team, run)
edited_package = {**edited_proposal.content_package, "title": "Reviewed guide", "markdown": "# Stale draft"}
- edited = self.client.post(
- self._proposals_url(f"{edited_proposal.id}/edit/"),
- {"proposed_markdown": "# Reviewed draft", "content_package": edited_package},
- format="json",
- )
- rejected = self.client.post(self._proposals_url(f"{rejected_proposal.id}/reject/"), format="json")
- regenerated = self.client.post(
- self._proposals_url(f"{regenerated_proposal.id}/regenerate/"),
- format="json",
- )
+ with (
+ patch(
+ "products.web_analytics.backend.content_autopilot.workflow.process_content_autopilot_proposal_task"
+ ) as proposal_task,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ edited = self.client.post(
+ self._proposals_url(f"{edited_proposal.id}/edit/"),
+ {"proposed_markdown": "# Reviewed draft", "content_package": edited_package},
+ format="json",
+ )
+ rejected = self.client.post(self._proposals_url(f"{rejected_proposal.id}/reject/"), format="json")
+ regenerated = self.client.post(
+ self._proposals_url(f"{regenerated_proposal.id}/regenerate/"),
+ format="json",
+ )
self.assertEqual(edited.status_code, status.HTTP_200_OK, edited.json())
self.assertFalse(edited.json()["validation_report"]["passed"])
@@ -301,8 +307,15 @@ class TestContentAutopilotAPI(APIBaseTest):
self.assertNotIn("markdown", edited.json()["content_package"])
self.assertEqual(rejected.json()["lifecycle_status"], ContentAutopilotProposal.LifecycleStatus.REJECTED)
self.assertEqual(regenerated.json()["lifecycle_status"], ContentAutopilotProposal.LifecycleStatus.GENERATING)
+ self.assertEqual(
+ [dispatched.args for dispatched in proposal_task.delay.call_args_list],
+ [
+ (self.team.id, str(edited_proposal.id), "validate"),
+ (self.team.id, str(regenerated_proposal.id), "regenerate"),
+ ],
+ )
- def test_opportunities_are_listed_per_site_and_dismissed(self) -> None:
+ def test_opportunities_are_listed_per_site_dismissed_and_drafted(self) -> None:
profile = create_content_autopilot_profile(self.team)
drafted = create_content_autopilot_opportunity(self.team, profile, cluster_key="drafted")
dismissed = create_content_autopilot_opportunity(self.team, profile, cluster_key="dismissed")
@@ -311,6 +324,22 @@ class TestContentAutopilotAPI(APIBaseTest):
listed = self.client.get(self._opportunities_url(), {"profile_id": str(profile.id)})
dismiss = self.client.post(self._opportunities_url(f"{dismissed.id}/dismiss/"), format="json")
after = self.client.get(self._opportunities_url(), {"profile_id": str(profile.id)})
+ with (
+ patch(
+ "products.web_analytics.backend.content_autopilot.workflow.generate_content_autopilot_run_task"
+ ) as run_task,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ draft = self.client.post(
+ self._opportunities_url("draft/"),
+ {"profile_id": str(profile.id), "opportunity_ids": [str(drafted.id)]},
+ format="json",
+ )
+ too_many = self.client.post(
+ self._opportunities_url("draft/"),
+ {"profile_id": str(profile.id), "opportunity_ids": [str(drafted.id)] * 6},
+ format="json",
+ )
self.assertEqual(missing_profile.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual({item["id"] for item in listed.json()["results"]}, {str(drafted.id), str(dismissed.id)})
@@ -320,6 +349,33 @@ class TestContentAutopilotAPI(APIBaseTest):
{item["id"]: item["status"] for item in after.json()["results"]},
{str(drafted.id): "new", str(dismissed.id): "dismissed"},
)
+ self.assertEqual(draft.status_code, status.HTTP_202_ACCEPTED, draft.json())
+ self.assertEqual(draft.json()["run_status"], ContentAutopilotRun.RunStatus.PENDING)
+ run_task.delay.assert_called_once_with(self.team.id, draft.json()["id"])
+ self.assertEqual(too_many.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_a_run_that_cannot_be_queued_fails_and_frees_its_opportunities(self) -> None:
+ profile = create_content_autopilot_profile(self.team)
+ opportunity = create_content_autopilot_opportunity(self.team, profile, cluster_key="drafted")
+
+ with (
+ patch(
+ "products.web_analytics.backend.content_autopilot.workflow.generate_content_autopilot_run_task"
+ ) as run_task,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ run_task.delay.side_effect = ConnectionError("broker unavailable")
+ draft = self.client.post(
+ self._opportunities_url("draft/"),
+ {"profile_id": str(profile.id), "opportunity_ids": [str(opportunity.id)]},
+ format="json",
+ )
+
+ run = ContentAutopilotRun.objects.for_team(self.team.id).get(id=draft.json()["id"])
+ opportunity.refresh_from_db()
+ self.assertEqual(run.run_status, ContentAutopilotRun.RunStatus.FAILED)
+ self.assertEqual([entry["error_code"] for entry in run.errors], ["dispatch_failed"])
+ self.assertEqual(opportunity.status, "new")
def test_edit_stores_markdown_whitespace_exactly(self) -> None:
proposal = self._reviewable_proposal()
@@ -368,12 +424,19 @@ class TestContentAutopilotAPI(APIBaseTest):
other_run = create_content_autopilot_run(other_team, other_profile)
other_proposal = create_content_autopilot_proposal(other_team, other_run)
other_opportunity = create_content_autopilot_opportunity(other_team, other_profile)
+ own_profile = create_content_autopilot_profile(self.team)
proposal_response = self.client.get(self._proposals_url(f"{other_proposal.id}/"))
runs_response = self.client.get(self._runs_url())
dismiss_response = self.client.post(self._opportunities_url(f"{other_opportunity.id}/dismiss/"))
+ draft_response = self.client.post(
+ self._opportunities_url("draft/"),
+ {"profile_id": str(own_profile.id), "opportunity_ids": [str(other_opportunity.id)]},
+ format="json",
+ )
self.assertEqual(proposal_response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(runs_response.status_code, status.HTTP_200_OK)
self.assertEqual(runs_response.json()["results"], [])
self.assertEqual(dismiss_response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(draft_response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/web_analytics/backend/test/test_content_autopilot_generation.py b/products/web_analytics/backend/test/test_content_autopilot_generation.py
index d5a007389e84..23d61c6eeb05 100644
--- a/products/web_analytics/backend/test/test_content_autopilot_generation.py
+++ b/products/web_analytics/backend/test/test_content_autopilot_generation.py
@@ -11,6 +11,7 @@ from django.test import SimpleTestCase
import httpx
from anthropic import APIConnectionError
+from celery.exceptions import SoftTimeLimitExceeded
from parameterized import parameterized
from posthog.egress.firecrawl.client import (
@@ -20,6 +21,7 @@ from posthog.egress.firecrawl.client import (
FirecrawlSearchResult,
)
+from products.web_analytics.backend.content_autopilot import generation
from products.web_analytics.backend.content_autopilot.edits import PageEdit, apply_edits
from products.web_analytics.backend.content_autopilot.generation import (
Draft,
@@ -61,6 +63,7 @@ from products.web_analytics.backend.models import (
ContentAutopilotRun,
)
from products.web_analytics.backend.public_url_fetch import FetchedPublicUrl
+from products.web_analytics.backend.tasks.content_autopilot import generate_content_autopilot_run_task
from products.web_analytics.backend.test.content_autopilot_test_utils import (
create_content_autopilot_opportunity,
create_content_autopilot_profile,
@@ -384,6 +387,68 @@ class TestContentAutopilotGeneration(BaseTest):
]
assert self.model.draft_calls == 0
+ def test_a_run_that_times_out_keeps_the_drafts_it_finished(self) -> None:
+ first = self._opportunity("first")
+ second = self._opportunity("second")
+
+ def time_out_on_second_draft() -> None:
+ if self.model.draft_calls == 1:
+ raise SoftTimeLimitExceeded()
+
+ self.model.on_draft = time_out_on_second_draft
+ run = draft_opportunities(
+ team=self.team,
+ profile_id=str(self.profile.id),
+ opportunity_ids=[str(first.id), str(second.id)],
+ triggered_by_id=None,
+ )
+
+ with patch("products.web_analytics.backend.content_autopilot.generation.build_client", return_value=object()):
+ generate_content_autopilot_run_task(self.team.id, str(run.id))
+
+ run.refresh_from_db()
+ statuses = sorted(
+ ContentAutopilotProposal.objects.for_team(self.team.id)
+ .filter(run=run)
+ .values_list("lifecycle_status", flat=True)
+ )
+ assert run.run_status == ContentAutopilotRun.RunStatus.READY_FOR_REVIEW
+ assert [entry["error_code"] for entry in run.errors] == ["timed_out"]
+ assert statuses == ["failed", "ready_for_review"]
+ assert set(
+ ContentAutopilotOpportunity.objects.for_team(self.team.id)
+ .filter(id__in=[first.id, second.id])
+ .values_list("status", flat=True)
+ ) == {ContentAutopilotOpportunity.Status.DRAFTED}
+
+ def test_a_timeout_right_after_a_draft_is_saved_keeps_it_ready(self) -> None:
+ opportunity = self._opportunity()
+ run = draft_opportunities(
+ team=self.team,
+ profile_id=str(self.profile.id),
+ opportunity_ids=[str(opportunity.id)],
+ triggered_by_id=None,
+ )
+ save_result = generation._save_result
+
+ def save_then_time_out(*args: Any, **kwargs: Any) -> None:
+ save_result(*args, **kwargs)
+ raise SoftTimeLimitExceeded()
+
+ with (
+ patch("products.web_analytics.backend.content_autopilot.generation.build_client", return_value=object()),
+ patch(
+ "products.web_analytics.backend.content_autopilot.generation._save_result",
+ side_effect=save_then_time_out,
+ ),
+ ):
+ generate_content_autopilot_run_task(self.team.id, str(run.id))
+
+ run.refresh_from_db()
+ proposal = ContentAutopilotProposal.objects.for_team(self.team.id).get(run=run)
+ assert proposal.lifecycle_status == ContentAutopilotProposal.LifecycleStatus.READY_FOR_REVIEW
+ assert run.run_status == ContentAutopilotRun.RunStatus.READY_FOR_REVIEW
+
def test_canceling_a_run_stops_before_the_next_opportunity(self) -> None:
first = self._opportunity("first")
second = self._opportunity("second")
diff --git a/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts b/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts
index 0110a87e540f..488b4073952a 100644
--- a/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts
+++ b/products/web_analytics/frontend/contentAutopilot/contentAutopilotStoryFixtures.ts
@@ -80,6 +80,23 @@ export const EXAMPLE_PROPOSAL: ContentAutopilotProposalApi = {
},
original_markdown: '# Web analytics',
proposed_markdown: '# Web analytics',
+ brief: {
+ intent: 'Decide whether a privacy-friendly web analytics tool covers their needs.',
+ audience: 'Marketers and founders comparing analytics tools',
+ recommended_type: 'page_improvement',
+ working_title: 'Web analytics',
+ outline: ['What web analytics tracks', 'How it handles privacy', 'Frequently asked questions'],
+ questions_to_answer: ['Does it work without cookies?'],
+ competitor_coverage: ['Cookieless tracking setup'],
+ engine_answer_summary: 'Assistants recommend other tools and do not mention cookieless mode.',
+ },
+ source_ledger: [
+ {
+ claim: 'Web analytics works without cookies.',
+ source_url: 'https://docs.example.com/docs/web-analytics/cookieless',
+ quote: 'You can run web analytics without cookies.',
+ },
+ ],
created_at: '2026-08-26T12:08:00Z',
updated_at: '2026-08-26T12:08:00Z',
}
diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.ts
index 5aa2b20a12e2..8e9bfeb3f3e0 100644
--- a/products/web_analytics/frontend/generated/api.schemas.ts
+++ b/products/web_analytics/frontend/generated/api.schemas.ts
@@ -965,6 +965,95 @@ export interface PaginatedContentAutopilotOpportunityListApi {
results: ContentAutopilotOpportunityApi[]
}
+export interface ContentAutopilotOpportunityDraftRequestApi {
+ /** Site profile the opportunities belong to. */
+ profile_id: string
+ /**
+ * Opportunities to draft, up to 5 at a time.
+ * @minItems 1
+ * @maxItems 5
+ */
+ opportunity_ids: string[]
+}
+
+/**
+ * * `pending` - Pending
+ * * `generating` - Generating
+ * * `ready_for_review` - Ready for review
+ * * `completed` - Completed
+ * * `canceled` - Canceled
+ * * `failed` - Failed
+ */
+export type ContentAutopilotRunRunStatusEnumApi =
+ (typeof ContentAutopilotRunRunStatusEnumApi)[keyof typeof ContentAutopilotRunRunStatusEnumApi]
+
+export const ContentAutopilotRunRunStatusEnumApi = {
+ Pending: 'pending',
+ Generating: 'generating',
+ ReadyForReview: 'ready_for_review',
+ Completed: 'completed',
+ Canceled: 'canceled',
+ Failed: 'failed',
+} as const
+
+/**
+ * * `standard` - Standard
+ * * `lower` - Lower
+ */
+export type ContentAutopilotSnapshotConfidenceEnumApi =
+ (typeof ContentAutopilotSnapshotConfidenceEnumApi)[keyof typeof ContentAutopilotSnapshotConfidenceEnumApi]
+
+export const ContentAutopilotSnapshotConfidenceEnumApi = {
+ Standard: 'standard',
+ Lower: 'lower',
+} as const
+
+export interface ContentAutopilotSnapshotApi {
+ /** Site domain used for the run. */
+ domain?: string
+ /** Confidence level based on the available data sources.
+ *
+ * * `standard` - Standard
+ * * `lower` - Lower */
+ confidence?: ContentAutopilotSnapshotConfidenceEnumApi
+ /** Public sources authorized for this run. */
+ source_urls?: string[]
+ /** Site paths authorized for this run. */
+ content_boundaries?: string[]
+ /** Editorial rules captured for this run. */
+ brand_rules?: string[]
+}
+
+export interface ContentAutopilotErrorApi {
+ /** Stable machine-readable error code. */
+ error_code: string
+ /** Error explanation suitable for the review workspace. */
+ message: string
+}
+
+export interface ContentAutopilotRunApi {
+ readonly id: string
+ /** Site profile used by this run. */
+ readonly profile_id: string
+ /** Current durable workflow status.
+ *
+ * * `pending` - Pending
+ * * `generating` - Generating
+ * * `ready_for_review` - Ready for review
+ * * `completed` - Completed
+ * * `canceled` - Canceled
+ * * `failed` - Failed */
+ readonly run_status: ContentAutopilotRunRunStatusEnumApi
+ /** Immutable inputs captured at run start. */
+ input_snapshot: ContentAutopilotSnapshotApi
+ /** Inspectable workflow errors from this run. */
+ errors: ContentAutopilotErrorApi[]
+ readonly created_at: string
+ readonly updated_at: string
+ /** @nullable */
+ readonly completed_at: string | null
+}
+
export interface ContentAutopilotOpportunityRefreshRequestApi {
/** Site profile to refresh opportunities for. */
profile_id: string
@@ -1133,6 +1222,70 @@ export interface ContentAutopilotPackageApi {
internal_links: string[]
/** Portable source notes included with the export. */
source_notes: string[]
+ /** JSON-LD structured data to embed in the page, such as an FAQPage document. */
+ json_ld?: string
+ /** Suggested llms.txt entry for the page. */
+ llms_txt_line?: string
+}
+
+export interface ContentAutopilotBriefCompetitorApi {
+ /** Product to compare against. */
+ name: string
+ /** The product's own page to research. */
+ url: string
+}
+
+export interface ContentAutopilotBriefApi {
+ /** What the person asking wants to know or decide. */
+ intent?: string
+ /** Who the content is for. */
+ audience?: string
+ /** Whether the brief recommends new_content or page_improvement. */
+ recommended_type?: string
+ /** Site page the brief chose to improve. Empty for a new page. */
+ target_page?: string
+ /** Site pages the brief asked to read for facts. */
+ site_pages_to_read?: string[]
+ /** Products the brief asked to research for a comparison. */
+ competitors_to_research?: ContentAutopilotBriefCompetitorApi[]
+ /** Working title for the page. */
+ working_title?: string
+ /** Planned sections, in order. */
+ outline?: string[]
+ /** Questions the page must answer. */
+ questions_to_answer?: string[]
+ /** Topics the cited competitor pages cover that the site's pages don't. */
+ competitor_coverage?: string[]
+ /** What AI answer engines currently say, including what they get wrong. */
+ engine_answer_summary?: string
+ /** What the question means, when AI answer engines misread which product or company it asks about. */
+ disambiguation?: string
+}
+
+/**
+ * * `site` - site
+ * * `competitor` - competitor
+ */
+export type ContentAutopilotSourceLedgerEntryKindEnumApi =
+ (typeof ContentAutopilotSourceLedgerEntryKindEnumApi)[keyof typeof ContentAutopilotSourceLedgerEntryKindEnumApi]
+
+export const ContentAutopilotSourceLedgerEntryKindEnumApi = {
+ Site: 'site',
+ Competitor: 'competitor',
+} as const
+
+export interface ContentAutopilotSourceLedgerEntryApi {
+ /** Factual claim the draft makes. */
+ claim: string
+ /** Page that supports the claim. */
+ source_url: string
+ /** Short quote from the source page. */
+ quote: string
+ /** Whether the source is one of the site's pages or a competitor's own page.
+ *
+ * * `site` - site
+ * * `competitor` - competitor */
+ kind?: ContentAutopilotSourceLedgerEntryKindEnumApi
}
export interface ContentAutopilotProposalApi {
@@ -1168,6 +1321,10 @@ export interface ContentAutopilotProposalApi {
readonly original_markdown: string
/** Full proposed Markdown after edits. */
readonly proposed_markdown: string
+ /** Content brief the draft was written from. */
+ brief: ContentAutopilotBriefApi
+ /** Factual claims in the draft and the site pages that support them. */
+ source_ledger: ContentAutopilotSourceLedgerEntryApi[]
readonly created_at: string
readonly updated_at: string
}
@@ -1191,84 +1348,6 @@ export interface ContentAutopilotExportResponseApi {
content_package: ContentAutopilotPackageApi
}
-/**
- * * `pending` - Pending
- * * `generating` - Generating
- * * `ready_for_review` - Ready for review
- * * `completed` - Completed
- * * `canceled` - Canceled
- * * `failed` - Failed
- */
-export type ContentAutopilotRunRunStatusEnumApi =
- (typeof ContentAutopilotRunRunStatusEnumApi)[keyof typeof ContentAutopilotRunRunStatusEnumApi]
-
-export const ContentAutopilotRunRunStatusEnumApi = {
- Pending: 'pending',
- Generating: 'generating',
- ReadyForReview: 'ready_for_review',
- Completed: 'completed',
- Canceled: 'canceled',
- Failed: 'failed',
-} as const
-
-/**
- * * `standard` - Standard
- * * `lower` - Lower
- */
-export type ContentAutopilotSnapshotConfidenceEnumApi =
- (typeof ContentAutopilotSnapshotConfidenceEnumApi)[keyof typeof ContentAutopilotSnapshotConfidenceEnumApi]
-
-export const ContentAutopilotSnapshotConfidenceEnumApi = {
- Standard: 'standard',
- Lower: 'lower',
-} as const
-
-export interface ContentAutopilotSnapshotApi {
- /** Site domain used for the run. */
- domain?: string
- /** Confidence level based on the available data sources.
- *
- * * `standard` - Standard
- * * `lower` - Lower */
- confidence?: ContentAutopilotSnapshotConfidenceEnumApi
- /** Public sources authorized for this run. */
- source_urls?: string[]
- /** Site paths authorized for this run. */
- content_boundaries?: string[]
- /** Editorial rules captured for this run. */
- brand_rules?: string[]
-}
-
-export interface ContentAutopilotErrorApi {
- /** Stable machine-readable error code. */
- error_code: string
- /** Error explanation suitable for the review workspace. */
- message: string
-}
-
-export interface ContentAutopilotRunApi {
- readonly id: string
- /** Site profile used by this run. */
- readonly profile_id: string
- /** Current durable workflow status.
- *
- * * `pending` - Pending
- * * `generating` - Generating
- * * `ready_for_review` - Ready for review
- * * `completed` - Completed
- * * `canceled` - Canceled
- * * `failed` - Failed */
- readonly run_status: ContentAutopilotRunRunStatusEnumApi
- /** Immutable inputs captured at run start. */
- input_snapshot: ContentAutopilotSnapshotApi
- /** Inspectable workflow errors from this run. */
- errors: ContentAutopilotErrorApi[]
- readonly created_at: string
- readonly updated_at: string
- /** @nullable */
- readonly completed_at: string | null
-}
-
export interface PaginatedContentAutopilotRunListApi {
count: number
/** @nullable */
diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.ts
index 2ce76bbc8911..0d79830d99c1 100644
--- a/products/web_analytics/frontend/generated/api.ts
+++ b/products/web_analytics/frontend/generated/api.ts
@@ -15,6 +15,7 @@ import type {
ApplyPathCleaningSuggestionResponseApi,
ContentAutopilotExportResponseApi,
ContentAutopilotOpportunityApi,
+ ContentAutopilotOpportunityDraftRequestApi,
ContentAutopilotOpportunityRefreshRequestApi,
ContentAutopilotProposalApi,
ContentAutopilotProposalEditRequestApi,
@@ -797,6 +798,27 @@ export const webAnalyticsContentAutopilotOpportunitiesDismiss = async (
)
}
+export const getWebAnalyticsContentAutopilotOpportunitiesDraftUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/web_analytics_content_autopilot_opportunities/draft/`
+}
+
+/**
+ * Starts a run that researches and drafts content for the selected opportunities.
+ * @summary Draft content for opportunities
+ */
+export const webAnalyticsContentAutopilotOpportunitiesDraft = async (
+ projectId: string,
+ contentAutopilotOpportunityDraftRequestApi: ContentAutopilotOpportunityDraftRequestApi,
+ options?: RequestInit
+): Promise<ContentAutopilotRunApi> => {
+ return apiMutator<ContentAutopilotRunApi>(getWebAnalyticsContentAutopilotOpportunitiesDraftUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(contentAutopilotOpportunityDraftRequestApi),
+ })
+}
+
export const getWebAnalyticsContentAutopilotOpportunitiesRefreshUrl = (projectId: string) => {
return `/api/projects/${projectId}/web_analytics_content_autopilot_opportunities/refresh/`
}
diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.ts
index ab1b88118deb..1a0b8efce84f 100644
--- a/products/web_analytics/frontend/generated/api.zod.ts
+++ b/products/web_analytics/frontend/generated/api.zod.ts
@@ -353,6 +353,21 @@ export const WebAnalyticsBotRulesCreateBody = /* @__PURE__ */ zod.object({
.describe('The conditions of this rule. Each one reads a single event property.'),
})
+/**
+ * Starts a run that researches and drafts content for the selected opportunities.
+ * @summary Draft content for opportunities
+ */
+export const webAnalyticsContentAutopilotOpportunitiesDraftBodyOpportunityIdsMax = 5
+
+export const WebAnalyticsContentAutopilotOpportunitiesDraftBody = /* @__PURE__ */ zod.object({
+ profile_id: zod.uuid().describe('Site profile the opportunities belong to.'),
+ opportunity_ids: zod
+ .array(zod.uuid())
+ .min(1)
+ .max(webAnalyticsContentAutopilotOpportunitiesDraftBodyOpportunityIdsMax)
+ .describe('Opportunities to draft, up to 5 at a time.'),
+})
+
/**
* Re-reads AI citation checks and updates the site's content opportunities. Makes no model calls.
* @summary Refresh content opportunities
@@ -450,6 +465,11 @@ export const WebAnalyticsContentAutopilotProposalsEditBody = /* @__PURE__ */ zod
.array(zod.url())
.describe('Validated same-origin internal links included in the content.'),
source_notes: zod.array(zod.string()).describe('Portable source notes included with the export.'),
+ json_ld: zod
+ .string()
+ .optional()
+ .describe('JSON-LD structured data to embed in the page, such as an FAQPage document.'),
+ llms_txt_line: zod.string().optional().describe('Suggested llms.txt entry for the page.'),
})
.describe('Updated structured package to save with the proposal.'),
})
diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yaml
index 6b623c3af8b8..7c8805c8428f 100644
--- a/products/web_analytics/mcp/tools.yaml
+++ b/products/web_analytics/mcp/tools.yaml
@@ -225,6 +225,9 @@ tools:
web-analytics-content-autopilot-opportunities-dismiss:
operation: web_analytics_content_autopilot_opportunities_dismiss
enabled: false
+ web-analytics-content-autopilot-opportunities-draft:
+ operation: web_analytics_content_autopilot_opportunities_draft
+ enabled: false
web-analytics-content-autopilot-opportunities-list:
operation: web_analytics_content_autopilot_opportunities_list
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2db34b509840..b2b217aab48a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23183,6 +23183,40 @@ export namespace Schemas {
token: string;
}
+ export interface ContentAutopilotBriefCompetitor {
+ /** Product to compare against. */
+ name: string;
+ /** The product's own page to research. */
+ url: string;
+ }
+
+ export interface ContentAutopilotBrief {
+ /** What the person asking wants to know or decide. */
+ intent?: string;
+ /** Who the content is for. */
+ audience?: string;
+ /** Whether the brief recommends new_content or page_improvement. */
+ recommended_type?: string;
+ /** Site page the brief chose to improve. Empty for a new page. */
+ target_page?: string;
+ /** Site pages the brief asked to read for facts. */
+ site_pages_to_read?: string[];
+ /** Products the brief asked to research for a comparison. */
+ competitors_to_research?: ContentAutopilotBriefCompetitor[];
+ /** Working title for the page. */
+ working_title?: string;
+ /** Planned sections, in order. */
+ outline?: string[];
+ /** Questions the page must answer. */
+ questions_to_answer?: string[];
+ /** Topics the cited competitor pages cover that the site's pages don't. */
+ competitor_coverage?: string[];
+ /** What AI answer engines currently say, including what they get wrong. */
+ engine_answer_summary?: string;
+ /** What the question means, when AI answer engines misread which product or company it asks about. */
+ disambiguation?: string;
+ }
+
export interface ContentAutopilotEngineAnswer {
/** Answer engine that gave the answer. */
engine: string;
@@ -23283,6 +23317,10 @@ export namespace Schemas {
internal_links: string[];
/** Portable source notes included with the export. */
source_notes: string[];
+ /** JSON-LD structured data to embed in the page, such as an FAQPage document. */
+ json_ld?: string;
+ /** Suggested llms.txt entry for the page. */
+ llms_txt_line?: string;
}
export interface ContentAutopilotExportResponse {
@@ -23378,6 +23416,17 @@ export namespace Schemas {
readonly updated_at: string;
}
+ export interface ContentAutopilotOpportunityDraftRequest {
+ /** Site profile the opportunities belong to. */
+ profile_id: string;
+ /**
+ * Opportunities to draft, up to 5 at a time.
+ * @minItems 1
+ * @maxItems 5
+ */
+ opportunity_ids: string[];
+ }
+
export interface ContentAutopilotOpportunityRefreshRequest {
/** Site profile to refresh opportunities for. */
profile_id: string;
@@ -23421,6 +23470,32 @@ export namespace Schemas {
checks: ContentAutopilotValidationCheck[];
}
+ /**
+ * * `site` - site
+ * * `competitor` - competitor
+ */
+ export type ContentAutopilotSourceLedgerEntryKindEnum = typeof ContentAutopilotSourceLedgerEntryKindEnum[keyof typeof ContentAutopilotSourceLedgerEntryKindEnum];
+
+
+ export const ContentAutopilotSourceLedgerEntryKindEnum = {
+ Site: 'site',
+ Competitor: 'competitor',
+ } as const;
+
+ export interface ContentAutopilotSourceLedgerEntry {
+ /** Factual claim the draft makes. */
+ claim: string;
+ /** Page that supports the claim. */
+ source_url: string;
+ /** Short quote from the source page. */
+ quote: string;
+ /** Whether the source is one of the site's pages or a competitor's own page.
+ *
+ * * `site` - site
+ * * `competitor` - competitor */
+ kind?: ContentAutopilotSourceLedgerEntryKindEnum;
+ }
+
export interface ContentAutopilotProposal {
readonly id: string;
/** Run that generated this proposal. */
@@ -23454,6 +23529,10 @@ export namespace Schemas {
readonly original_markdown: string;
/** Full proposed Markdown after edits. */
readonly proposed_markdown: string;
+ /** Content brief the draft was written from. */
+ brief: ContentAutopilotBrief;
+ /** Factual claims in the draft and the site pages that support them. */
+ source_ledger: ContentAutopilotSourceLedgerEntry[];
readonly created_at: string;
readonly updated_at: string;
}