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(signals): let the web vitals scout audit public posthog.com pages (#91120)

Lucas Ricoy8cf3911a267b
diff --git a/posthog/egress/browserless/README.md b/posthog/egress/browserless/README.md
index 6b7bb2c61303..a712aa507172 100644
--- a/posthog/egress/browserless/README.md
+++ b/posthog/egress/browserless/README.md
@@ -22,6 +22,7 @@ So the budget counts browser loads asked of one fleet, and the ceilings are smal
The default reserve ladder applies, because callers differ sharply in urgency.
Heatmap screenshots (`products/web_analytics/backend/tasks/heatmap_screenshot.py`) run `NORMAL`, because somebody is watching a spinner.
A background consumer should run `BATCH`, so that it is shed first and leaves headroom for the render a person is waiting on.
+Signals Lighthouse audits (`products/signals/backend/scout_harness/tools/lighthouse.py`) run `BATCH` for that reason: an audit holds a session for tens of seconds where a screenshot holds one for a few.
A denied call raises `BrowserlessEgressBudgetExhausted`; the heatmap caller maps it to its existing retryable error, under its own failure cause, so a busy fleet is not read as a broken one.
## Rate-limit headers
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 7f9c885d2a3e..eee4c7a856d0 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -209,6 +209,27 @@ HEATMAP_BROWSERLESS_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_TIMEOUT_MS",
HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS", 30000, type_cast=int)
HEATMAP_BROWSERLESS_BLOCK_ADS = get_from_env("HEATMAP_BROWSERLESS_BLOCK_ADS", False, type_cast=str_to_bool)
+# Lighthouse audits run on the same Browserless fleet as the heatmap screenshots above, over the
+# `/performance` REST API rather than `/screenshot`. They get their own settings so one can be
+# repointed or switched off without touching the other, and default to the heatmap fleet because
+# that is the only Browserless we provision today. Which pages may be audited, and by whom, is
+# policy rather than connection config and lives in `posthog/settings/signals.py`.
+LIGHTHOUSE_BROWSERLESS_URL = get_from_env("LIGHTHOUSE_BROWSERLESS_URL", HEATMAP_BROWSERLESS_URL)
+LIGHTHOUSE_BROWSERLESS_TOKEN = get_from_env("LIGHTHOUSE_BROWSERLESS_TOKEN", HEATMAP_BROWSERLESS_TOKEN)
+# Unlike the heatmap render, this one is awaited inside a request handler, so the cap has to fit
+# inside the app server's own request timeout rather than the Browserless plan's max — a longer
+# budget just means the proxy hangs up first, leaving the run charged for a report it never sees
+# and a browser session still running. A throttled desktop load of a heavy marketing page measures
+# ~17s, so 60s is generous; raise it only alongside the ingress timeout.
+LIGHTHOUSE_BROWSERLESS_TIMEOUT_MS = get_from_env("LIGHTHOUSE_BROWSERLESS_TIMEOUT_MS", 60000, type_cast=int)
+LIGHTHOUSE_BROWSERLESS_CONNECT_TIMEOUT_MS = get_from_env(
+ "LIGHTHOUSE_BROWSERLESS_CONNECT_TIMEOUT_MS", 10000, type_cast=int
+)
+# A Lighthouse report carries base64 screenshot and filmstrip blobs; the one measured against
+# posthog.com was 1.8 MB. Reject an implausibly large body before it is parsed into worker memory,
+# mirroring `HEATMAP_SCREENSHOT_MAX_BYTES`.
+LIGHTHOUSE_REPORT_MAX_BYTES = get_from_env("LIGHTHOUSE_REPORT_MAX_BYTES", 32 * 1024 * 1024, type_cast=int)
+
# PostHog connect — lets a user connect (via the target's OAuth consent flow) to another PostHog
# project to drive its APIs, e.g. dispatching a Task that must run in that project (including one in
# another region, to reach region-resident data). The target may be in a different region OR the
diff --git a/posthog/settings/signals.py b/posthog/settings/signals.py
index 3d8dca459145..8aa570f1ae60 100644
--- a/posthog/settings/signals.py
+++ b/posthog/settings/signals.py
@@ -1,7 +1,7 @@
import os
-from posthog.settings.base_variables import DEBUG, TEST
-from posthog.settings.utils import get_list
+from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG, TEST
+from posthog.settings.utils import get_list, get_set
# Signs the per-delivery map of already-rendered chart assets that scout Slack delivery keeps in the
# shared Redis, so a process able to write that Redis cannot swap in another asset id. Dedicated and
@@ -11,3 +11,46 @@ from posthog.settings.utils import get_list
SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS: list[str] = get_list(os.getenv("SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS", ""))
if (TEST or DEBUG) and not SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS:
SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS = ["signals-slack-chart-cache-development-key"]
+
+# Hosts a scout may point a Lighthouse audit at. An audit drives a real browser at a real page, so
+# this is an allowlist and not a blocklist. It holds our own marketing and docs site, which is
+# public: no credential ever has to reach the headless browser. The app hosts are absent on
+# purpose — the browser signs in to nothing, so an app URL would measure the login screen and
+# report its LCP as the page's.
+# Lower-cased at parse time because the check compares against a lower-cased hostname; an operator
+# who writes `PostHog.com` would otherwise get a set that silently matches nothing.
+SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS: set[str] = {
+ host.lower() for host in get_set(os.getenv("SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS", "posthog.com,www.posthog.com"))
+}
+
+# Teams whose scouts may spend an audit. Defaults to the deployment's own internal project on
+# PostHog Cloud — the same team split the usage report uses — and to NOBODY anywhere else. Off
+# Cloud, "team 2" is an arbitrary customer project rather than ours, and `LIGHTHOUSE_BROWSERLESS_URL`
+# falls back to the heatmap fleet, so a region-shaped default would hand the capability to any
+# self-hosted install that had configured Browserless for screenshots. Enabling it there is an
+# explicit act: set this variable.
+_DEFAULT_LIGHTHOUSE_TEAM_IDS = {"EU": "1", "US": "2"}.get((CLOUD_DEPLOYMENT or "").upper(), "")
+
+
+def _parse_team_ids(raw: str) -> set[int]:
+ """Team ids from a comma-separated env value, ignoring blanks and non-numeric entries.
+
+ Deliberately lenient: this runs at settings import, so raising here takes down every process
+ — web, worker, migrations — over an optional capability. A trailing comma is the most common
+ way to write this env var wrong, and losing the feature beats losing the deployment. The
+ conversion itself decides what counts as numeric, because a shape test that accepts what
+ `int()` then rejects — `--1`, or a value longer than the interpreter's digit limit — brings
+ back the crash it was meant to prevent.
+ """
+ team_ids: set[int] = set()
+ for team_id in get_set(raw):
+ try:
+ team_ids.add(int(team_id))
+ except ValueError:
+ continue
+ return team_ids
+
+
+SIGNALS_LIGHTHOUSE_TEAM_IDS: set[int] = _parse_team_ids(
+ os.getenv("SIGNALS_LIGHTHOUSE_TEAM_IDS", _DEFAULT_LIGHTHOUSE_TEAM_IDS)
+)
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 6419e9e2f832..9b9fbd68e017 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -52,6 +52,11 @@ from products.signals.backend.scout_harness.tools.emit import (
MAX_TAG_LENGTH,
MAX_TAGS_PER_FINDING,
)
+from products.signals.backend.scout_harness.tools.lighthouse import (
+ DEFAULT_FORM_FACTOR,
+ FORM_FACTORS,
+ MAX_AUDITS_PER_RUN,
+)
from products.signals.backend.scout_harness.tools.notes import MAX_NOTE_CONTENT_LENGTH, MAX_NOTES_LIST_LIMIT
from products.signals.backend.scout_harness.tools.report import (
MAX_EVIDENCE_DESCRIPTION_LENGTH,
@@ -585,6 +590,110 @@ class RecordStructuredOutputResponseSerializer(serializers.Serializer):
)
+class LighthouseAuditRequestSerializer(serializers.Serializer):
+ """Request body for `scout-lighthouse-audit`: one page, one device profile."""
+
+ url = serializers.URLField(
+ max_length=2000,
+ help_text=(
+ "The page to audit. Must be an https url on an allowed host — public PostHog pages only. "
+ "Pages behind a login cannot be audited: the browser signs in to nothing, so it would "
+ "measure the login screen and report its numbers as the page's."
+ ),
+ )
+ form_factor = serializers.ChoiceField(
+ choices=[(value, value) for value in FORM_FACTORS],
+ default=DEFAULT_FORM_FACTOR,
+ help_text=(
+ "Which device profile to emulate. Desktop and mobile produce different numbers, so audit "
+ "the one whose field data you are explaining."
+ ),
+ )
+
+
+class LcpElementSerializer(serializers.Serializer):
+ """The element the browser chose as the Largest Contentful Paint."""
+
+ selector = serializers.CharField(allow_null=True, help_text="CSS selector for the element.")
+ snippet = serializers.CharField(allow_null=True, help_text="The element's opening tag, truncated by Lighthouse.")
+ node_label = serializers.CharField(allow_null=True, help_text="Human-readable label, usually the alt or text.")
+
+
+class LcpPhaseSerializer(serializers.Serializer):
+ """One phase of the LCP timeline, which is where the time actually went."""
+
+ phase = serializers.CharField(
+ help_text=(
+ "Lighthouse's own label for this subpart of the LCP, e.g. 'Time to first byte' or "
+ "'Element render delay'. Passed through verbatim, so the exact wording follows the "
+ "Lighthouse version."
+ )
+ )
+ timing_ms = serializers.FloatField(allow_null=True, help_text="Milliseconds spent in this phase.")
+ percent = serializers.CharField(
+ allow_null=True,
+ help_text="This subpart's share of the total LCP, e.g. '62%'.",
+ )
+
+
+class AuditOpportunitySerializer(serializers.Serializer):
+ """A failing check or a savings estimate from the audit."""
+
+ audit_id = serializers.CharField(help_text="Lighthouse audit id, for example `prioritize-lcp-image`.")
+ title = serializers.CharField(help_text="Lighthouse's own title for the check.")
+ savings_ms = serializers.FloatField(
+ allow_null=True,
+ help_text="Estimated milliseconds this would save. Null for a pass/fail check with no estimate.",
+ )
+
+
+class LighthouseAuditResponseSerializer(serializers.Serializer):
+ """The audit, reduced to what a web vitals finding cites.
+
+ The full Lighthouse report runs to a few hundred KB of detail no finding ever quotes, so the
+ response carries the metrics, the LCP element and its phase breakdown, and the ranked
+ opportunities, and drops the rest.
+ """
+
+ requested_url = serializers.CharField(help_text="The url that was audited.")
+ final_url = serializers.CharField(allow_null=True, help_text="Where the browser ended up after redirects.")
+ form_factor = serializers.CharField(help_text="The device profile the audit emulated.")
+ lighthouse_version = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "The Lighthouse version that produced this report. Audit ids move between major "
+ "versions, so cite it when an expected field came back empty."
+ ),
+ )
+ performance_score = serializers.IntegerField(
+ allow_null=True, help_text="Lighthouse performance score out of 100 for this run."
+ )
+ metrics = serializers.DictField(
+ child=serializers.FloatField(),
+ help_text=(
+ "Lab metrics from this run: `lcp_ms`, `fcp_ms`, `cls`, `tbt_ms`, `speed_index_ms`, `tti_ms`. "
+ "One throttled cold load, not a p75 over real users — use it to explain a field finding, "
+ "never to replace one."
+ ),
+ )
+ lcp_element = LcpElementSerializer(
+ allow_null=True,
+ help_text="The element the browser chose as the LCP, or null when Lighthouse could not name one.",
+ )
+ lcp_phases = LcpPhaseSerializer(
+ many=True, help_text="Where the LCP time went, phase by phase. Empty when the report omits the breakdown."
+ )
+ lcp_checks_failed = AuditOpportunitySerializer(
+ many=True, help_text="LCP-specific checks this page failed, such as an unprioritized or lazy-loaded hero image."
+ )
+ opportunities = AuditOpportunitySerializer(
+ many=True, help_text="Ranked savings estimates across the whole page, largest first."
+ )
+ audits_remaining = serializers.IntegerField(
+ help_text=f"How many audits this run may still spend. Each run gets {MAX_AUDITS_PER_RUN}."
+ )
+
+
class FleetFindingsSummarySerializer(serializers.Serializer):
"""Fleet-wide tally of recent scout output — legacy `emit_signal` findings plus reports
authored/edited via the report channel. Backs the "Scout findings" callout so it renders
diff --git a/products/signals/backend/scout_harness/tools/__init__.py b/products/signals/backend/scout_harness/tools/__init__.py
index 0ecde30ca769..d938b4774553 100644
--- a/products/signals/backend/scout_harness/tools/__init__.py
+++ b/products/signals/backend/scout_harness/tools/__init__.py
@@ -15,6 +15,25 @@ from products.signals.backend.scout_harness.tools.emit import (
emit_finding,
normalize_tags,
)
+from products.signals.backend.scout_harness.tools.lighthouse import (
+ DEFAULT_FORM_FACTOR,
+ FORM_FACTORS,
+ MAX_AUDITS_PER_RUN,
+ AuditOpportunity,
+ InvalidLighthouseTargetError,
+ LcpElement,
+ LcpPhase,
+ LighthouseAudit,
+ LighthouseAuditFailedError,
+ LighthouseFleetBusyError,
+ LighthouseUnavailableError,
+ PreparedAudit,
+ audits_remaining_for_run,
+ enabled_team_ids,
+ execute_lighthouse_audit,
+ prepare_lighthouse_audit,
+ run_lighthouse_audit,
+)
from products.signals.backend.scout_harness.tools.notes import (
InvalidNoteError,
ScoutNote,
@@ -66,15 +85,27 @@ from products.signals.backend.scout_harness.tools.structured_output import (
)
__all__ = [
+ "DEFAULT_FORM_FACTOR",
"DEFAULT_RUN_SEARCH_LIMIT",
+ "FORM_FACTORS",
+ "AuditOpportunity",
"EditReportResult",
"EmitReportResult",
"EmitResult",
"EvidenceEntry",
"InvalidEmitError",
+ "InvalidLighthouseTargetError",
"InvalidNoteError",
"InvalidScratchpadError",
"InvalidStructuredOutputError",
+ "LcpElement",
+ "LcpPhase",
+ "LighthouseAudit",
+ "LighthouseAuditFailedError",
+ "LighthouseFleetBusyError",
+ "LighthouseUnavailableError",
+ "MAX_AUDITS_PER_RUN",
+ "PreparedAudit",
"MAX_EVIDENCE_ENTRIES",
"MAX_RECORDS_PER_CALL",
"MAX_RECORDS_PER_RUN",
@@ -92,6 +123,9 @@ __all__ = [
"StructuredOutputSchemaError",
"RunDetail",
"RunSummary",
+ "audits_remaining_for_run",
+ "enabled_team_ids",
+ "execute_lighthouse_audit",
"compute_project_profile",
"delete_note",
"edit_report",
@@ -108,6 +142,8 @@ __all__ = [
"record_structured_output",
"record_structured_output_sync",
"remember",
+ "prepare_lighthouse_audit",
+ "run_lighthouse_audit",
"search_scratchpad",
"search_recent_runs",
"validate_structured_output_schema",
diff --git a/products/signals/backend/scout_harness/tools/lighthouse.py b/products/signals/backend/scout_harness/tools/lighthouse.py
new file mode 100644
index 000000000000..144bd4fad0fd
--- /dev/null
+++ b/products/signals/backend/scout_harness/tools/lighthouse.py
@@ -0,0 +1,837 @@
+"""Lighthouse audit tool: load one page in a real browser and name what makes it slow.
+
+Field data (`$web_vitals` events) says a route is slow and for how many people. It does not say
+which element the browser chose as the LCP, or which of the load phases ran long. The web vitals
+scout has had to guess at a candidate by reading the page source, and a guess is what a reader
+discounts. Lighthouse answers both questions directly, so a finding can name the element.
+
+An audit drives a real browser at a real page, which is why this is fenced on four sides:
+`SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS` (public PostHog pages only), `SIGNALS_LIGHTHOUSE_TEAM_IDS`
+(our own project), the internal-only MCP scope on the endpoint, and a per-run cap. The browser
+signs in to nothing, so a page behind a login is not merely disallowed — it would report the
+login screen's LCP as the page's.
+
+Lab and field measure different things and the scout is told to keep them apart: p75 over real
+users decides whether something is a problem, one throttled cold load explains why.
+"""
+
+from __future__ import annotations
+
+import re
+import json
+import time
+from typing import Any
+from urllib.parse import quote, urlencode, urlsplit
+
+from django.conf import settings
+
+import structlog
+import posthoganalytics
+from prometheus_client import Counter, Histogram
+
+from posthog.dataclasses import frozen
+from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted, browserless_request
+from posthog.egress.limiter.policies import Priority
+from posthog.exceptions_capture import capture_exception
+from posthog.security.url_validation import is_url_allowed
+
+logger = structlog.get_logger(__name__)
+
+# Audits share the heatmap Browserless fleet but hold a session an order of magnitude longer, so
+# their spend and failure rate have to be separable from the screenshot traffic next to them.
+LIGHTHOUSE_REQUESTS = Counter(
+ "signals_lighthouse_requests",
+ "Lighthouse audit requests to Browserless by outcome",
+ labelnames=["form_factor", "outcome"],
+)
+LIGHTHOUSE_REQUEST_SECONDS = Histogram(
+ "signals_lighthouse_request_duration_seconds",
+ "Latency of a single Browserless /performance call",
+ labelnames=["form_factor"],
+ buckets=(1, 5, 10, 20, 30, 45, 60, 90, 120, float("inf")),
+)
+
+# Matches the heatmap path's `token=` scrubber. `urlencode` percent-encodes a token containing
+# `/`, `+`, or `=`, so a literal replace alone misses the spelling that actually lands in an
+# echoed url.
+_TOKEN_QS_RE = re.compile(r"(token=)[^&\s\"']+")
+
+# Runtime gate on which teams may spend an audit, so the capability can be switched on for a
+# team — or off fleet-wide — without an infra deploy. Payload shape:
+#
+# {"enabled": true, "team_ids": [2]}
+#
+# `enabled: false` is the kill switch. `team_ids` replaces the settings default when present;
+# absent, the deploy-time `SIGNALS_LIGHTHOUSE_TEAM_IDS` still applies, so an unset flag leaves
+# the internal-project-only posture untouched.
+#
+# The flag deliberately cannot widen `SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS`. Which pages a browser
+# may be pointed at is the security fence and stays deploy-gated; this only picks who may spend
+# a Browserless session on the pages that fence already allows.
+SIGNALS_LIGHTHOUSE_FLAG = "signals-lighthouse-audit"
+
+# Enablement is team-list-in-payload rather than per-user, so the read uses a fixed distinct_id.
+LIGHTHOUSE_DISCOVERY_DISTINCT_ID = "internal_signals_lighthouse_discovery"
+
+# Lighthouse emulates one device per run and the two disagree, so the caller picks. Desktop is the
+# default because it is the profile most of our own traffic arrives on.
+FORM_FACTORS = ("desktop", "mobile")
+DEFAULT_FORM_FACTOR = "desktop"
+
+# The metrics worth carrying back, mapped to the reader-facing names the scout writes with. The
+# full Lighthouse report is a few hundred KB; nearly all of it is detail no finding ever cites.
+_METRIC_AUDITS: dict[str, str] = {
+ "largest-contentful-paint": "lcp_ms",
+ "first-contentful-paint": "fcp_ms",
+ "cumulative-layout-shift": "cls",
+ "total-blocking-time": "tbt_ms",
+ "speed-index": "speed_index_ms",
+ "interactive": "tti_ms",
+}
+
+# Lighthouse 12 introduced "insight" audits (carried over from DevTools) and Lighthouse 13
+# dropped the legacy per-check audits entirely — `largest-contentful-paint-element`,
+# `prioritize-lcp-image`, and `lcp-lazy-loaded` are simply absent from a v13 report. Both
+# spellings are read so an audit keeps naming the element whichever version the fleet ships,
+# and so a Browserless upgrade can't quietly turn every finding back into a guess.
+# Insight audits carry the LCP element as a `type: node` entry and the phase table alongside it.
+_LCP_INSIGHT_AUDITS = ("lcp-breakdown-insight", "lcp-discovery-insight")
+_LEGACY_LCP_ELEMENT_AUDIT = "largest-contentful-paint-element"
+
+# `lcp-discovery-insight` carries its pass/fail checks as a checklist keyed by check name —
+# `priorityHinted` false is the modern spelling of "this hero image needs fetchpriority=high".
+_LCP_CHECKLIST_AUDIT = "lcp-discovery-insight"
+
+# Legacy pass/fail audits that bear on LCP. Absent on Lighthouse 13; kept for older fleets. Several
+# also carry a savings estimate, so one can appear both here and under `opportunities` — that is
+# deliberate: this list answers "what is wrong with the LCP", the other "what is worth the most".
+_LCP_CHECK_AUDITS = (
+ "prioritize-lcp-image",
+ "lcp-lazy-loaded",
+ "uses-responsive-images",
+ "modern-image-formats",
+ "efficient-animated-content",
+ "uses-optimized-images",
+)
+
+# `metricSavings` keys whose value is milliseconds. CLS is excluded because its saving is a
+# unitless layout-shift score, and reporting 0.101 alongside "ms" would be a wrong number rather
+# than a missing one.
+_TIME_METRIC_SAVINGS_KEYS = ("LCP", "FCP", "TBT", "INP")
+
+# An opportunity below this is noise next to a multi-second LCP, and listing it invites a finding
+# built on a rounding error.
+MIN_OPPORTUNITY_SAVINGS_MS = 50
+MAX_OPPORTUNITIES = 10
+
+# Cap on a single page-derived string (selector, snippet, alt text) returned to a scout.
+MAX_PAGE_TEXT_LENGTH = 600
+
+# One audit is a browser load under CPU and network throttling — tens of seconds of a Browserless
+# session. A scout corroborating a finding needs one page, or a handful across a route family;
+# anything past that is a crawl it should not be running.
+MAX_AUDITS_PER_RUN = 5
+# Public because the view reserves against it: a private constant on one side and a string
+# literal on the other agree only by coincidence, and a rename would silently uncap the budget.
+RUN_AUDIT_COUNT_KEY = "lighthouse_audit_count"
+
+
+class LighthouseUnavailableError(RuntimeError):
+ """Lighthouse is not provisioned on this deployment, so no audit can run."""
+
+
+class InvalidLighthouseTargetError(ValueError):
+ """The requested URL or the calling team is outside what audits are allowed to reach."""
+
+
+class LighthouseAuditFailedError(RuntimeError):
+ """Browserless or Lighthouse itself could not produce a usable report."""
+
+
+class LighthouseFleetBusyError(RuntimeError):
+ """The fleet's egress budget is spent, so this audit never started a browser."""
+
+
+@frozen
+class LcpElement:
+ selector: str | None
+ snippet: str | None
+ node_label: str | None
+
+
+@frozen
+class LcpPhase:
+ phase: str
+ timing_ms: float | None
+ percent: str | None
+
+
+@frozen
+class AuditOpportunity:
+ audit_id: str
+ title: str
+ savings_ms: float | None
+
+
+@frozen
+class LighthouseAudit:
+ """One page, one device profile, reduced to what a web vitals finding actually cites."""
+
+ requested_url: str
+ final_url: str | None
+ form_factor: str
+ lighthouse_version: str | None
+ performance_score: int | None
+ metrics: dict[str, float]
+ lcp_element: LcpElement | None
+ lcp_phases: list[LcpPhase]
+ lcp_checks_failed: list[AuditOpportunity]
+ opportunities: list[AuditOpportunity]
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "requested_url": self.requested_url,
+ "final_url": self.final_url,
+ "form_factor": self.form_factor,
+ "lighthouse_version": self.lighthouse_version,
+ "performance_score": self.performance_score,
+ "metrics": dict(self.metrics),
+ "lcp_element": (
+ {
+ "selector": self.lcp_element.selector,
+ "snippet": self.lcp_element.snippet,
+ "node_label": self.lcp_element.node_label,
+ }
+ if self.lcp_element is not None
+ else None
+ ),
+ "lcp_phases": [
+ {"phase": phase.phase, "timing_ms": phase.timing_ms, "percent": phase.percent}
+ for phase in self.lcp_phases
+ ],
+ "lcp_checks_failed": [_opportunity_as_dict(entry) for entry in self.lcp_checks_failed],
+ "opportunities": [_opportunity_as_dict(entry) for entry in self.opportunities],
+ }
+
+
+def _opportunity_as_dict(entry: AuditOpportunity) -> dict[str, Any]:
+ return {"audit_id": entry.audit_id, "title": entry.title, "savings_ms": entry.savings_ms}
+
+
+@frozen
+class PreparedAudit:
+ """A validated, ready-to-send audit. Holding this means every cheap fence has passed and the
+ next step is a real browser load."""
+
+ target: str
+ endpoint: str
+ form_factor: str
+
+
+def prepare_lighthouse_audit(*, team_id: int, url: str, form_factor: str = DEFAULT_FORM_FACTOR) -> PreparedAudit:
+ """Run every check that costs nothing, so a caller can reject before spending anything.
+
+ Split from the audit itself because the per-run budget is reserved between the two: a bad
+ host, an http url, a team without the capability, or a deployment with no Browserless should
+ not cost a slot, since none of them start a browser.
+
+ Raises `InvalidLighthouseTargetError` for a target or caller outside the allowlists, and
+ `LighthouseUnavailableError` when the deployment has no Browserless configured.
+ """
+ if form_factor not in FORM_FACTORS:
+ raise InvalidLighthouseTargetError(f"form_factor must be one of {', '.join(FORM_FACTORS)}.")
+ _assert_team_allowed(team_id)
+ target = _assert_url_allowed(url)
+ endpoint = _build_performance_url()
+ if endpoint is None:
+ raise LighthouseUnavailableError("Lighthouse audits are not configured on this deployment.")
+ return PreparedAudit(target=target, endpoint=endpoint, form_factor=form_factor)
+
+
+def run_lighthouse_audit(*, team_id: int, url: str, form_factor: str = DEFAULT_FORM_FACTOR) -> LighthouseAudit:
+ """Validate and audit one URL in one call. Callers that meter the audit prepare first."""
+ return execute_lighthouse_audit(prepare_lighthouse_audit(team_id=team_id, url=url, form_factor=form_factor))
+
+
+def execute_lighthouse_audit(prepared: PreparedAudit) -> LighthouseAudit:
+ """Spend the browser load for an already-validated audit and return the reduced report.
+
+ Raises `LighthouseAuditFailedError` when the run itself fails,
+ `InvalidLighthouseTargetError` when the page turns out to have left the allowed hosts, and
+ `LighthouseFleetBusyError` when the fleet's egress budget refused the call outright.
+ """
+ target, endpoint, form_factor = prepared.target, prepared.endpoint, prepared.form_factor
+ payload = _request_audit(endpoint_url=endpoint, url=target, form_factor=form_factor)
+ report = payload.get("data") if isinstance(payload.get("data"), dict) else payload
+ if not isinstance(report, dict):
+ raise LighthouseAuditFailedError("Lighthouse returned a report in an unrecognized shape.")
+
+ runtime_error = report.get("runtimeError")
+ if isinstance(runtime_error, dict) and runtime_error.get("code") not in (None, "NO_ERROR"):
+ raise LighthouseAuditFailedError(
+ f"Lighthouse could not load the page ({runtime_error.get('code')}): {runtime_error.get('message')}"
+ )
+
+ final_url = _final_url(report)
+ # A redirect off the allowlist is the login-wall case: the audit ran, but not on the page that
+ # was asked for, and its numbers describe wherever it landed. Fail rather than hand the scout a
+ # measurement of the sign-in screen under the requested URL's name.
+ #
+ # Fails CLOSED on an unknown final url. This is the only control on where the browser actually
+ # ended up — the SSRF checks upstream only ever saw the requested url, and Browserless resolves
+ # DNS and follows redirects itself. A report that cannot be attributed to a host is not a report
+ # worth returning, so an absent field is treated as a failure rather than a pass.
+ if final_url is None:
+ raise LighthouseAuditFailedError(
+ "The report does not say which page it ended on, so it cannot be attributed to the "
+ "requested url. Nothing was returned."
+ )
+ # Every hop the document went through, not only where it ended. Browserless follows redirects
+ # itself, so a chain that leaves the allowlist and comes back passes on its endpoints alone.
+ # This cannot prevent the request that already happened, since Lighthouse has no setting to
+ # refuse a redirect, but it does stop that page's numbers being returned under the requested
+ # url's name, and it makes the detour visible instead of silent.
+ for hop in _document_chain_urls(report):
+ if not _host_allowed(hop):
+ raise InvalidLighthouseTargetError(
+ f"{target} went through {hop}, which is outside the allowed hosts. The audit "
+ "would describe that page instead, and pages behind a login cannot be audited."
+ )
+
+ audit = _reduce_report(report, requested_url=target, final_url=final_url, form_factor=form_factor)
+ if not audit.metrics:
+ # No metric audit parsed at all means the shape changed or the run produced nothing usable.
+ # Returning a 200 full of nulls would read as "this page has no problems".
+ raise LighthouseAuditFailedError(
+ f"The report carried no usable metrics (Lighthouse {audit.lighthouse_version or 'unknown'})."
+ )
+ return audit
+
+
+def audits_remaining_for_run(run_metadata: dict[str, Any] | None) -> int:
+ """How many audits this run may still spend, read off its own metadata counter.
+
+ `metadata` is a shared JSON column, so a non-integer value is treated as zero spent rather
+ than raising — the same guard the structured-output counter uses.
+ """
+ spent = (run_metadata or {}).get(RUN_AUDIT_COUNT_KEY)
+ return max(0, MAX_AUDITS_PER_RUN - (spent if isinstance(spent, int) else 0))
+
+
+def _assert_team_allowed(team_id: int) -> None:
+ if team_id not in enabled_team_ids():
+ raise InvalidLighthouseTargetError("Lighthouse audits are not enabled for this project.")
+
+
+def enabled_team_ids() -> set[int]:
+ """Teams whose scouts may spend an audit: the flag payload when it says, else settings.
+
+ An unreadable or malformed payload falls back to the settings allowlist rather than opening
+ up or shutting down — a flag read must not be able to hand the capability to a team the
+ deploy never granted it to, nor take it away from the internal project by going down.
+ """
+ payload = _read_flag_payload()
+ if payload is None:
+ return settings.SIGNALS_LIGHTHOUSE_TEAM_IDS
+ if payload.get("enabled") is False:
+ return set()
+ raw_team_ids = payload.get("team_ids")
+ if not isinstance(raw_team_ids, list):
+ return settings.SIGNALS_LIGHTHOUSE_TEAM_IDS
+ from_flag = {int(team_id) for team_id in raw_team_ids if isinstance(team_id, int)}
+ # A present-but-empty list is a deliberate "nobody", not a parse failure.
+ return from_flag
+
+
+def _read_flag_payload() -> dict | None:
+ """Read + parse the `signals-lighthouse-audit` payload once. `None` on absent/malformed/error.
+
+ The flag must stay 100%-on for the payload to be served to the synthetic discovery
+ distinct_id; `match_value=True` forces the true-variant payload under local evaluation.
+ Mirrors `scout_harness/team_limits._read_flag_payload`.
+ """
+ try:
+ payload = posthoganalytics.get_feature_flag_payload(
+ SIGNALS_LIGHTHOUSE_FLAG, LIGHTHOUSE_DISCOVERY_DISTINCT_ID, match_value=True
+ )
+ if isinstance(payload, str):
+ payload = json.loads(payload)
+ return payload if isinstance(payload, dict) else None
+ except Exception as error:
+ capture_exception(error)
+ return None
+
+
+def _assert_url_allowed(url: str) -> str:
+ target = (url or "").strip()
+ if not target:
+ raise InvalidLighthouseTargetError("A url is required.")
+ parsed = urlsplit(target)
+ if parsed.scheme != "https":
+ raise InvalidLighthouseTargetError("Only https urls can be audited.")
+ if not _host_allowed(target):
+ allowed = ", ".join(sorted(settings.SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS)) or "(none configured)"
+ raise InvalidLighthouseTargetError(
+ f"{parsed.hostname or target} is not an auditable host. Allowed hosts: {allowed}. "
+ "Pages behind a login are excluded — an audit signs in to nothing, so it would "
+ "measure the login screen."
+ )
+ ok, reason = is_url_allowed(target)
+ if not ok:
+ raise InvalidLighthouseTargetError(f"That url cannot be fetched: {reason}")
+ return target
+
+
+def _host_allowed(url: str) -> bool:
+ hostname = urlsplit(url).hostname
+ if not hostname:
+ return False
+ return hostname.lower() in settings.SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS
+
+
+def _build_performance_url() -> str | None:
+ # Read settings at call time (not import) so `override_settings` works in tests. Strip an
+ # inline comment a bash-sourced .env may have left in the value, as the heatmap path does.
+ base_url = (settings.LIGHTHOUSE_BROWSERLESS_URL or "").split("#", 1)[0].strip()
+ parsed = urlsplit(base_url) if base_url else None
+ host = parsed.hostname if parsed else None
+ if not parsed or not host:
+ return None
+ netloc = f"{host}:{parsed.port}" if parsed.port else host
+ scheme = "http" if parsed.scheme in ("http", "ws") else "https"
+ params = {
+ "token": settings.LIGHTHOUSE_BROWSERLESS_TOKEN,
+ "timeout": str(settings.LIGHTHOUSE_BROWSERLESS_TIMEOUT_MS),
+ }
+ return f"{scheme}://{netloc}/performance?{urlencode(params)}"
+
+
+def _request_audit(*, endpoint_url: str, url: str, form_factor: str) -> dict[str, Any]:
+ body = {
+ "url": url,
+ "config": {
+ "extends": "lighthouse:default",
+ "settings": {
+ "onlyCategories": ["performance"],
+ "formFactor": form_factor,
+ "screenEmulation": _screen_emulation(form_factor),
+ "throttling": _throttling(form_factor),
+ # `lighthouse:default` emulates a mobile UA. Left on for a desktop run, the page
+ # can serve mobile assets, so the "desktop" report would describe neither profile.
+ # False keeps the real desktop Chrome UA rather than pinning a version string here.
+ "emulatedUserAgent": form_factor != "desktop",
+ },
+ },
+ }
+ timeout = (
+ settings.LIGHTHOUSE_BROWSERLESS_CONNECT_TIMEOUT_MS / 1000,
+ settings.LIGHTHOUSE_BROWSERLESS_TIMEOUT_MS / 1000 + 15,
+ )
+ started = time.monotonic()
+ try:
+ # `BATCH` because an audit holds a browser session for tens of seconds where the heatmap
+ # screenshot on the same fleet holds one for a few, and somebody is watching that render:
+ # a background explanation should be shed first rather than queue in front of it.
+ response = browserless_request(
+ "POST",
+ endpoint_url,
+ token=settings.LIGHTHOUSE_BROWSERLESS_TOKEN,
+ source="signals_lighthouse_audit",
+ endpoint="performance",
+ priority=Priority.BATCH,
+ json=body,
+ timeout=timeout,
+ )
+ except BrowserlessEgressBudgetExhausted as e:
+ # Refused before any browser started, so it is not a failed audit: the caller refunds the
+ # slot rather than charging the run for a page that was never loaded. Kept out of the
+ # latency histogram, which measures page loads.
+ logger.warning("signals.lighthouse.fleet_busy", form_factor=form_factor)
+ LIGHTHOUSE_REQUESTS.labels(form_factor=form_factor, outcome="fleet_busy").inc()
+ raise LighthouseFleetBusyError(f"The browser fleet is at capacity: {_redact(str(e))}") from None
+ except Exception as e:
+ # `str(e)` on a requests error quotes the full url, token query string included, so it is
+ # scrubbed for the log line exactly as it is for the raised message.
+ logger.warning("signals.lighthouse.request_failed", form_factor=form_factor, error=_redact(str(e)))
+ LIGHTHOUSE_REQUESTS.labels(form_factor=form_factor, outcome="error").inc()
+ raise LighthouseAuditFailedError(f"The audit request failed: {_redact(str(e))}") from None
+
+ elapsed_ms = round((time.monotonic() - started) * 1000)
+ LIGHTHOUSE_REQUEST_SECONDS.labels(form_factor=form_factor).observe(elapsed_ms / 1000)
+ if response.status_code != 200:
+ logger.warning(
+ "signals.lighthouse.request_rejected",
+ form_factor=form_factor,
+ status=response.status_code,
+ latency_ms=elapsed_ms,
+ )
+ LIGHTHOUSE_REQUESTS.labels(form_factor=form_factor, outcome="rejected").inc()
+ raise LighthouseAuditFailedError(f"The audit failed ({response.status_code}): {_redact(response.text[:500])}")
+
+ # A report carries base64 screenshot blobs, so it is megabytes even when healthy. Check the
+ # length before `.json()` parses it into worker memory.
+ body_bytes = len(response.content or b"")
+ if body_bytes > settings.LIGHTHOUSE_REPORT_MAX_BYTES:
+ LIGHTHOUSE_REQUESTS.labels(form_factor=form_factor, outcome="oversized").inc()
+ raise LighthouseAuditFailedError(f"The audit returned an implausibly large report ({body_bytes} bytes).")
+ try:
+ payload = response.json()
+ except ValueError:
+ LIGHTHOUSE_REQUESTS.labels(form_factor=form_factor, outcome="unparseable").inc()
+ raise LighthouseAuditFailedError("The audit returned a body that is not JSON.") from None
+ if not isinstance(payload, dict):
+ LIGHTHOUSE_REQUESTS.labels(form_factor=form_factor, outcome="unparseable").inc()
+ raise LighthouseAuditFailedError("The audit returned a body that is not a Lighthouse report.")
+ logger.info("signals.lighthouse.audited", form_factor=form_factor, latency_ms=elapsed_ms, bytes=body_bytes)
+ LIGHTHOUSE_REQUESTS.labels(form_factor=form_factor, outcome="ok").inc()
+ return payload
+
+
+def _screen_emulation(form_factor: str) -> dict[str, Any]:
+ if form_factor == "mobile":
+ return {"mobile": True, "width": 412, "height": 823, "deviceScaleFactor": 1.75, "disabled": False}
+ return {"mobile": False, "width": 1350, "height": 940, "deviceScaleFactor": 1, "disabled": False}
+
+
+def _throttling(form_factor: str) -> dict[str, Any]:
+ """Lighthouse's own presets, sent explicitly per form factor.
+
+ `lighthouse:default` throttles like a slow 4G phone with a 4x CPU slowdown. Setting only
+ `formFactor` and `screenEmulation` leaves that in place, so a "desktop" run reports a desktop
+ viewport measured over a mobile connection — numbers that cannot be compared against the
+ desktop field p75 the audit exists to explain. These mirror `desktopDense4G` and `mobileSlow4G`.
+ """
+ if form_factor == "desktop":
+ return {
+ "rttMs": 40,
+ "throughputKbps": 10 * 1024,
+ "cpuSlowdownMultiplier": 1,
+ "requestLatencyMs": 0,
+ "downloadThroughputKbps": 0,
+ "uploadThroughputKbps": 0,
+ }
+ return {
+ "rttMs": 150,
+ "throughputKbps": 1.6 * 1024,
+ "cpuSlowdownMultiplier": 4,
+ "requestLatencyMs": 150 * 3.75,
+ "downloadThroughputKbps": 1.6 * 1024 * 0.9,
+ "uploadThroughputKbps": 750 * 0.9,
+ }
+
+
+def _redact(text: str) -> str:
+ """Scrub the Browserless token from anything that reaches an error message or a log.
+
+ The endpoint carries the token in its query string, and both the exception text and the
+ error body can quote the url back. A literal replace alone is not enough: `urlencode`
+ percent-encodes a token containing `/`, `+`, or `=` (ordinary in base64-ish secrets), so the
+ echoed url holds a spelling the raw value never matches. The `token=` pattern catches those,
+ matching the heatmap path's `_sanitize_browserless_error`.
+ """
+ token = settings.LIGHTHOUSE_BROWSERLESS_TOKEN
+ if token:
+ text = text.replace(token, "[redacted]")
+ text = text.replace(quote(token, safe=""), "[redacted]")
+ return _TOKEN_QS_RE.sub(r"\1[redacted]", text)
+
+
+def _final_url(report: dict[str, Any]) -> str | None:
+ # Lighthouse renamed this field; read whichever the running version emits.
+ for key in ("finalDisplayedUrl", "finalUrl", "mainDocumentUrl"):
+ value = report.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+def _document_chain_urls(report: dict[str, Any]) -> list[str]:
+ """Every url the main document itself passed through, in the order Lighthouse saw them.
+
+ The `redirects` audit lists the hops; the url fields give the endpoints, and are read too
+ because a report with no redirect carries no `redirects` items at all.
+
+ Deliberately the document chain only. A page's subresources — its images, fonts, and
+ third-party scripts — are the site's business rather than the caller's choice, and
+ allowlisting them would reject every real page.
+
+ A Lighthouse that stopped emitting `redirects` would narrow this back to the endpoints, which
+ is where the check stood before. That is worth knowing but not worth failing closed over: the
+ audit is standard output, and refusing every report over its absence would trade a rare
+ detour for a permanent outage.
+ """
+ urls: list[str] = []
+ for key in ("requestedUrl", "mainDocumentUrl", "finalUrl", "finalDisplayedUrl"):
+ value = report.get(key)
+ if isinstance(value, str) and value:
+ urls.append(value)
+
+ audits = report.get("audits")
+ redirects = audits.get("redirects") if isinstance(audits, dict) else None
+ details = redirects.get("details") if isinstance(redirects, dict) else None
+ if isinstance(details, dict):
+ for item in details.get("items") or []:
+ if isinstance(item, dict) and isinstance(item.get("url"), str) and item["url"]:
+ urls.append(item["url"])
+
+ # Order-preserving dedupe, so the rejection names the first hop that left the allowlist
+ # rather than whichever one a set happened to yield.
+ seen: set[str] = set()
+ ordered: list[str] = []
+ for url in urls:
+ if url not in seen:
+ seen.add(url)
+ ordered.append(url)
+ return ordered
+
+
+def _reduce_report(
+ report: dict[str, Any], *, requested_url: str, final_url: str | None, form_factor: str
+) -> LighthouseAudit:
+ raw_audits = report.get("audits")
+ audits: dict[str, Any] = raw_audits if isinstance(raw_audits, dict) else {}
+ version = _as_text(report.get("lighthouseVersion"))
+ element = _lcp_element(audits)
+ if element is None:
+ # Naming the element is the whole point of an audit, and the audit ids that carry it have
+ # already been renamed once (Lighthouse 13 dropped the legacy set). Degrading quietly is
+ # what let that go unnoticed, so a miss is logged with the version that produced it.
+ logger.warning(
+ "signals.lighthouse.no_lcp_element",
+ lighthouse_version=version,
+ audit_ids_present=sorted(audits)[:60],
+ )
+ return LighthouseAudit(
+ requested_url=requested_url,
+ final_url=final_url,
+ form_factor=form_factor,
+ lighthouse_version=version,
+ performance_score=_performance_score(report),
+ metrics=_metrics(audits),
+ lcp_element=element,
+ lcp_phases=_lcp_phases(audits),
+ lcp_checks_failed=_failed_lcp_checks(audits),
+ opportunities=_opportunities(audits),
+ )
+
+
+def _performance_score(report: dict[str, Any]) -> int | None:
+ categories = report.get("categories")
+ if not isinstance(categories, dict):
+ return None
+ performance = categories.get("performance")
+ if not isinstance(performance, dict):
+ return None
+ score = performance.get("score")
+ return round(score * 100) if isinstance(score, int | float) else None
+
+
+def _metrics(audits: dict[str, Any]) -> dict[str, float]:
+ metrics: dict[str, float] = {}
+ for audit_id, name in _METRIC_AUDITS.items():
+ audit = audits.get(audit_id)
+ if not isinstance(audit, dict):
+ continue
+ value = audit.get("numericValue")
+ if isinstance(value, int | float):
+ metrics[name] = round(float(value), 3)
+ return metrics
+
+
+def _lcp_element(audits: dict[str, Any]) -> LcpElement | None:
+ for audit_id in (*_LCP_INSIGHT_AUDITS, _LEGACY_LCP_ELEMENT_AUDIT):
+ node = _first_node(audits.get(audit_id))
+ if node is not None:
+ return LcpElement(
+ selector=_as_page_text(node.get("selector")),
+ snippet=_as_page_text(node.get("snippet")),
+ node_label=_as_page_text(node.get("nodeLabel")),
+ )
+ return None
+
+
+def _first_node(audit: Any) -> dict[str, Any] | None:
+ """The element node, wherever the running Lighthouse puts it.
+
+ Insight audits list it as a `type: node` entry directly under `details.items`; the legacy
+ element audit nested it under a `node` key, either on a top-level item or on a table row.
+ All three are walked rather than pinning one shape.
+ """
+ if not isinstance(audit, dict):
+ return None
+ details = audit.get("details")
+ if not isinstance(details, dict):
+ return None
+ for item in _iter_rows(details.get("items")):
+ if item.get("type") == "node" and item.get("selector") is not None:
+ return item
+ node = item.get("node")
+ if isinstance(node, dict):
+ return node
+ for nested in _iter_rows(item.get("items")):
+ if isinstance(nested.get("node"), dict):
+ return nested["node"]
+ return None
+
+
+def _iter_rows(items: Any) -> list[dict[str, Any]]:
+ """Table rows as a list of dicts. A checklist keys its rows by name instead of listing
+ them, so both are normalized here rather than at each call site."""
+ if isinstance(items, list):
+ return [row for row in items if isinstance(row, dict)]
+ if isinstance(items, dict):
+ return [{"_key": key, **row} for key, row in items.items() if isinstance(row, dict)]
+ return []
+
+
+def _lcp_phases(audits: dict[str, Any]) -> list[LcpPhase]:
+ for audit_id in ("lcp-breakdown-insight", _LEGACY_LCP_ELEMENT_AUDIT):
+ phases = _phases_from(audits.get(audit_id))
+ if phases:
+ return phases
+ return []
+
+
+def _phases_from(audit: Any) -> list[LcpPhase]:
+ if not isinstance(audit, dict):
+ return []
+ details = audit.get("details")
+ if not isinstance(details, dict):
+ return []
+ raw: list[tuple[str, float | None, str | None]] = []
+ for item in _iter_rows(details.get("items")):
+ for row in _iter_rows(item.get("items")):
+ # Insight rows are {subpart, label, duration}; legacy rows are {phase, timing, percent}.
+ label = _as_text(row.get("label")) or _as_text(row.get("phase"))
+ if label is None:
+ continue
+ timing = row.get("duration") if "duration" in row else row.get("timing")
+ raw.append(
+ (
+ label,
+ round(float(timing), 3) if isinstance(timing, int | float) else None,
+ _as_text(row.get("percent")),
+ )
+ )
+ # The subparts sum to LCP, so a share is well defined. Insight rows carry no `percent`, and a
+ # phase breakdown is read as "where did the time go" — durations alone make the reader do the
+ # division. Computed only from the rows present, never invented.
+ total = sum(timing for _, timing, _ in raw if timing is not None)
+ return [
+ LcpPhase(
+ phase=label,
+ timing_ms=timing,
+ percent=percent
+ or (f"{round(100 * timing / total)}%" if percent is None and timing is not None and total else None),
+ )
+ for label, timing, percent in raw
+ ]
+
+
+def _failed_lcp_checks(audits: dict[str, Any]) -> list[AuditOpportunity]:
+ failed: list[AuditOpportunity] = _checklist_failures(audits.get(_LCP_CHECKLIST_AUDIT))
+ for audit_id in _LCP_CHECK_AUDITS:
+ audit = audits.get(audit_id)
+ if not isinstance(audit, dict):
+ continue
+ score = audit.get("score")
+ if not isinstance(score, int | float) or score >= 1:
+ continue
+ failed.append(
+ AuditOpportunity(
+ audit_id=audit_id,
+ title=_as_text(audit.get("title")) or audit_id,
+ savings_ms=_savings_ms(audit),
+ )
+ )
+ return failed
+
+
+def _checklist_failures(audit: Any) -> list[AuditOpportunity]:
+ """Failing entries of an insight audit's checklist, e.g. `priorityHinted: false`."""
+ if not isinstance(audit, dict):
+ return []
+ details = audit.get("details")
+ if not isinstance(details, dict):
+ return []
+ failures: list[AuditOpportunity] = []
+ for item in _iter_rows(details.get("items")):
+ if not isinstance(item, dict) or item.get("type") != "checklist":
+ continue
+ for row in _iter_rows(item.get("items")):
+ if row.get("value") is not False:
+ continue
+ key = _as_text(row.get("_key")) or "check"
+ failures.append(
+ AuditOpportunity(
+ audit_id=f"{_LCP_CHECKLIST_AUDIT}:{key}",
+ title=_as_text(row.get("label")) or key,
+ savings_ms=None,
+ )
+ )
+ return failures
+
+
+def _opportunities(audits: dict[str, Any]) -> list[AuditOpportunity]:
+ found: list[AuditOpportunity] = []
+ for audit_id, audit in audits.items():
+ if not isinstance(audit, dict):
+ continue
+ savings = _savings_ms(audit)
+ if savings is None or savings < MIN_OPPORTUNITY_SAVINGS_MS:
+ continue
+ found.append(
+ AuditOpportunity(
+ audit_id=audit_id,
+ title=_as_text(audit.get("title")) or audit_id,
+ savings_ms=savings,
+ )
+ )
+ found.sort(key=lambda entry: (-(entry.savings_ms or 0), entry.audit_id))
+ return found[:MAX_OPPORTUNITIES]
+
+
+def _savings_ms(audit: dict[str, Any]) -> float | None:
+ """Estimated milliseconds this audit would save.
+
+ Lighthouse 13 reports savings per metric on `metricSavings` and leaves `overallSavingsMs`
+ at 0 on the few legacy opportunity audits that still carry it, so the per-metric map is
+ read first and the legacy field is the fallback. `numericValue` is deliberately NOT a
+ fallback: on most audits it is the measured value (bytes, element count, a duration that
+ is not a saving), so treating it as a saving invents a number.
+ """
+ metric_savings = audit.get("metricSavings")
+ if isinstance(metric_savings, dict):
+ values = [
+ float(metric_savings[key])
+ for key in _TIME_METRIC_SAVINGS_KEYS
+ if isinstance(metric_savings.get(key), int | float)
+ ]
+ if values and max(values) > 0:
+ return round(max(values), 1)
+ details = audit.get("details")
+ if isinstance(details, dict):
+ savings = details.get("overallSavingsMs")
+ if isinstance(savings, int | float) and savings > 0:
+ return round(float(savings), 1)
+ return None
+
+
+def _as_text(value: Any) -> str | None:
+ if isinstance(value, str):
+ trimmed = value.strip()
+ return trimmed or None
+ return None
+
+
+def _as_page_text(value: Any) -> str | None:
+ """Text lifted from the audited page's own markup, bounded before it reaches a scout.
+
+ A selector, snippet, or alt text is page content, and the audited page is a CMS-driven site
+ rather than something this repo controls. Lighthouse already truncates these, but the cap is
+ theirs, not ours — bounding it here keeps one long attribute out of a prompt.
+ """
+ text = _as_text(value)
+ if text is None:
+ return None
+ return text if len(text) <= MAX_PAGE_TEXT_LENGTH else text[:MAX_PAGE_TEXT_LENGTH] + "…"
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index db18fd2ada57..08e35095cdee 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -53,6 +53,7 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.permissions import AccessControlPermission, APIScopePermission, get_authenticator_scopes
+from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle
from posthog.temporal.common.client import sync_connect
from posthog.user_permissions import UserPermissions
@@ -101,6 +102,8 @@ from products.signals.backend.scout_harness.serializers import (
FleetFindingsSummarySerializer,
ForgetRequestSerializer,
ForgetResponseSerializer,
+ LighthouseAuditRequestSerializer,
+ LighthouseAuditResponseSerializer,
ProjectProfileQuerySerializer,
ProjectProfileSerializer,
RecentEmissionsQuerySerializer,
@@ -146,6 +149,17 @@ from products.signals.backend.scout_harness.skill_loader import (
from products.signals.backend.scout_harness.suggestions import find_suggestion, mark_suggestion_created
from products.signals.backend.scout_harness.team_limits import resolve_team_metadata, withheld_skills_for_team
from products.signals.backend.scout_harness.tools.emit import EvidenceEntry, InvalidEmitError, emit_finding_sync
+from products.signals.backend.scout_harness.tools.lighthouse import (
+ MAX_AUDITS_PER_RUN,
+ RUN_AUDIT_COUNT_KEY,
+ InvalidLighthouseTargetError,
+ LighthouseAuditFailedError,
+ LighthouseFleetBusyError,
+ LighthouseUnavailableError,
+ audits_remaining_for_run,
+ execute_lighthouse_audit,
+ prepare_lighthouse_audit,
+)
from products.signals.backend.scout_harness.tools.notes import (
DEFAULT_NOTES_LIST_LIMIT,
InvalidNoteError,
@@ -221,6 +235,22 @@ class _StructuredOutputDeliveryFailed(exceptions.APIException):
default_code = "structured_output_delivery_failed"
+class _LighthouseNotConfigured(exceptions.APIException):
+ """501 for a deployment with no Browserless provisioned: the capability is absent here,
+ which is a different thing from the request being wrong, and no retry will fix it."""
+
+ status_code = status.HTTP_501_NOT_IMPLEMENTED
+ default_code = "lighthouse_not_configured"
+
+
+class _LighthouseFleetBusy(exceptions.APIException):
+ """503 for an audit the fleet's egress budget refused. Nothing is wrong with the request and
+ the budget refills on its own, so this reads as "come back", not as a failed audit."""
+
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ default_code = "lighthouse_fleet_busy"
+
+
# `SignalScoutRunViewSet.lookup_field` is `run_id`, but the model's PK field is `id`, so
# drf-spectacular can't derive the path-param type from the model and warns (fatal under
# `--fail-on-warn`). Declare the param explicitly on every detail action instead.
@@ -551,6 +581,13 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# on POSTs (emit-signal, forget) already disable pagination at the @action level.
pagination_class = None
+ def get_throttles(self):
+ if self.action == "lighthouse_audit":
+ # A browser load under throttling, tens of seconds of a Browserless session. The
+ # per-run cap bounds one scout; this bounds the fleet if several start auditing at once.
+ return [AIBurstRateThrottle(), AISustainedRateThrottle()]
+ return super().get_throttles()
+
@validated_request(
query_serializer=SearchRecentRunsQuerySerializer,
responses={
@@ -1327,6 +1364,163 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
status=status.HTTP_200_OK,
)
+ @validated_request(
+ parameters=[_RUN_ID_PATH_PARAMETER],
+ request_serializer=LighthouseAuditRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=LighthouseAuditResponseSerializer,
+ description="The audit ran and the reduced report is attached.",
+ ),
+ 400: OpenApiResponse(
+ description=(
+ "The url is not on an allowed host, is not https, redirected off the allowed hosts "
+ "(the login-wall case), the run is not in progress, or the run has spent its audit "
+ "budget. Also returned when the page could not be loaded at all. Every message ends "
+ "with how many audits the run has left, so a rejection is distinguishable from an "
+ "exhausted budget."
+ )
+ ),
+ 404: OpenApiResponse(description="No such run in this project, or the run belongs to a different scout."),
+ 429: OpenApiResponse(description="Audit rate limit exceeded; retry later."),
+ 501: OpenApiResponse(description="Lighthouse audits are not configured on this deployment."),
+ 503: OpenApiResponse(
+ description=(
+ "The browser fleet is at capacity, so no audit ran and the run keeps the slot. Retry later."
+ )
+ ),
+ },
+ summary="Run a Lighthouse audit for a run",
+ description=(
+ "Load one page in a real browser and return what makes it slow — most usefully the element "
+ "the browser chose as the Largest Contentful Paint, and where the LCP time went. Field data "
+ "says a route is slow; this says which element and why, so a finding can name it instead of "
+ "guessing from source. Restricted to public PostHog pages: the browser signs in to nothing, "
+ "so a page behind a login would report the login screen's numbers. One throttled cold load "
+ "is not a p75 over real users — corroborate a field finding with it, never replace one. "
+ f"Capped at {MAX_AUDITS_PER_RUN} audits per run."
+ ),
+ operation_id="signals_scout_lighthouse_audit",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="lighthouse-audit",
+ required_scopes=["signal_scout_internal:write"],
+ pagination_class=None,
+ )
+ def lighthouse_audit(self, request: Request, **kwargs) -> Response:
+ run_id = _parse_run_id_or_404(kwargs)
+ run = (
+ SignalScoutRun.objects.select_related("task_run")
+ .filter(team_id=_canonical_team_id(self), id=run_id)
+ .first()
+ )
+ if run is None:
+ raise exceptions.NotFound()
+ # A sandbox token is minted for one run, so it may only spend that run's budget. Team
+ # scoping alone leaves the cap per-run in name only: a scout can list its siblings, and
+ # spending each one's five slots costs five more browser sessions every time. Answered as
+ # 404 like another team's run, so a caller learns nothing about a run it may not touch.
+ # A caller with no bound task is unaffected, the internal scope being server-mint-only.
+ bound_task_id = _sandbox_bound_task_id(request)
+ if bound_task_id is not None and bound_task_id != run.task_run.task_id:
+ raise exceptions.NotFound()
+ if run.task_run.status != tasks_facade.TaskRunStatus.IN_PROGRESS:
+ raise exceptions.ValidationError(
+ {"status": f"An audit can only run on an in-progress run (current: {run.task_run.status})."}
+ )
+
+ # Validate before reserving. A bad host, an http url, a team without the capability, or a
+ # deployment with no Browserless costs nothing to reject, so none of them should cost a
+ # slot — a scout that misread the host rule would otherwise burn its whole budget in five
+ # instant round-trips and then be told it had spent it on audits.
+ try:
+ prepared = prepare_lighthouse_audit(
+ team_id=_canonical_team_id(self),
+ url=request.validated_data["url"],
+ form_factor=request.validated_data["form_factor"],
+ )
+ except InvalidLighthouseTargetError as exc:
+ # The count rides in the message rather than a sibling field: the error body is
+ # rendered into `{type, code, detail, attr}`, so an extra key would not reach the
+ # scout — and telling a rejection apart from an exhausted budget is the whole point.
+ raise exceptions.ValidationError(
+ {"detail": f"{exc} ({self._audits_left(run)} of {MAX_AUDITS_PER_RUN} audits still available.)"}
+ )
+ except LighthouseUnavailableError as exc:
+ raise _LighthouseNotConfigured(detail=str(exc))
+
+ # Reserve under the run row's lock, so two concurrent calls can't both take the last slot.
+ # From here a browser load is about to happen, so the slot is spent whatever the outcome —
+ # a scout retrying a page that cannot be loaded is the runaway case the cap exists for.
+ with transaction.atomic():
+ # `all_teams` because the run's team was already verified above, matching how the
+ # structured-output channel reserves its own per-run cap.
+ locked = SignalScoutRun.all_teams.select_for_update(of=("self",)).filter(pk=run.pk).first()
+ if locked is None:
+ raise exceptions.NotFound()
+ metadata = dict(locked.metadata or {})
+ remaining = audits_remaining_for_run(metadata)
+ if remaining <= 0:
+ raise exceptions.ValidationError(
+ {
+ "detail": (
+ f"This run has spent its {MAX_AUDITS_PER_RUN} Lighthouse audits "
+ "(0 still available). Work from the field data and what you already measured."
+ ),
+ }
+ )
+ metadata[RUN_AUDIT_COUNT_KEY] = MAX_AUDITS_PER_RUN - remaining + 1
+ locked.metadata = metadata
+ locked.save(update_fields=["metadata"])
+
+ spent_message = f"({remaining - 1} of {MAX_AUDITS_PER_RUN} audits still available.)"
+ try:
+ audit = execute_lighthouse_audit(prepared)
+ except InvalidLighthouseTargetError as exc:
+ raise exceptions.ValidationError({"detail": f"{exc} {spent_message}"})
+ except LighthouseAuditFailedError as exc:
+ raise exceptions.ValidationError({"detail": f"{exc} {spent_message}"})
+ except LighthouseFleetBusyError as exc:
+ # No browser was started, so the reservation above bought nothing. Give the slot back
+ # rather than letting a busy fleet eat a run's whole budget in five instant refusals.
+ self._refund_audit(run)
+ raise _LighthouseFleetBusy(
+ detail=f"{exc} ({self._audits_left(run)} of {MAX_AUDITS_PER_RUN} audits still available.)"
+ )
+
+ payload = audit.as_dict()
+ payload["audits_remaining"] = remaining - 1
+ return Response(LighthouseAuditResponseSerializer(payload).data, status=status.HTTP_200_OK)
+
+ @staticmethod
+ def _refund_audit(run: SignalScoutRun) -> None:
+ """Hand back a slot reserved for a browser load that never happened.
+
+ Re-read under the row lock rather than decrementing the count this request computed: a
+ concurrent audit on the same run may have reserved its own slot in between, and writing
+ back a stale total would hand that one back too.
+ """
+ with transaction.atomic():
+ locked = SignalScoutRun.all_teams.select_for_update(of=("self",)).filter(pk=run.pk).first()
+ if locked is None:
+ return
+ metadata = dict(locked.metadata or {})
+ spent = metadata.get(RUN_AUDIT_COUNT_KEY)
+ if not isinstance(spent, int) or spent <= 0:
+ return
+ metadata[RUN_AUDIT_COUNT_KEY] = spent - 1
+ locked.metadata = metadata
+ locked.save(update_fields=["metadata"])
+ run.metadata = metadata
+
+ @staticmethod
+ def _audits_left(run: SignalScoutRun) -> int:
+ """Budget left on a run, for a rejection that spent none of it. Told the remaining count
+ on every path, a scout can tell "you asked for the wrong thing" from "you are out"."""
+ return audits_remaining_for_run(run.metadata or {})
+
# `EvidenceEntrySerializer` is referenced for OpenAPI nested-schema discovery; keep
# the import live so drf-spectacular registers it even if the runtime never imports
# it directly inside this module.
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 32e6fcddf139..85ee9e745910 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING
from uuid import UUID, uuid4
from posthog.test.base import APIBaseTest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.apps import apps
from django.core.cache import cache
@@ -19,6 +19,7 @@ from rest_framework import status
from social_django.models import UserSocialAuth
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted
from posthog.models import OAuthApplication
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.integration import Integration
@@ -63,6 +64,7 @@ from products.signals.backend.scout_harness.serializers import (
from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
from products.signals.backend.scout_harness.team_limits import MAX_RUNS_PER_TEAM_PER_TICK
from products.signals.backend.scout_harness.tools import structured_output as structured_output_tool
+from products.signals.backend.scout_harness.tools.lighthouse import MAX_AUDITS_PER_RUN, RUN_AUDIT_COUNT_KEY
from products.signals.backend.scout_harness.tools.profile import compute_project_profile
from products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_ids
from products.skills.backend.models.skills import LLMSkill, LLMSkillOwner
@@ -4545,3 +4547,187 @@ class TestSignalScoutSlackDestinationSerializerValidation(SimpleTestCase):
)
assert serializer.is_valid(), serializer.errors
assert serializer.validated_data["users"] == ["U0123ABC|@a", "W0456DEF|@b"]
+
+
+_LIGHTHOUSE_API_SETTINGS = {
+ "LIGHTHOUSE_BROWSERLESS_URL": "https://browserless.example.com",
+ "LIGHTHOUSE_BROWSERLESS_TOKEN": "secret-token",
+ "SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS": {"posthog.com"},
+}
+
+_LIGHTHOUSE_REPORT = {
+ "data": {
+ "lighthouseVersion": "13.4.1",
+ "finalDisplayedUrl": "https://posthog.com/pricing",
+ "categories": {"performance": {"score": 0.28}},
+ "audits": {"largest-contentful-paint": {"numericValue": 4553.2}},
+ }
+}
+
+
+# The endpoint's metering lives here rather than in the tool tests because the ordering under
+# test — validate, then reserve under the row lock, then load the page — lives in the view.
+class TestScoutHarnessLighthouseAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # lighthouse-audit requires `signal_scout_internal:write` — session auth is rejected.
+ _authenticate_as_scout(self)
+
+ def _audit_url(self, run_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/lighthouse-audit/"
+
+ def _post(self, run: SignalScoutRun, url: str = "https://posthog.com/pricing", **setting_overrides):
+ response = MagicMock(status_code=200, content=b"{}")
+ response.json.return_value = _LIGHTHOUSE_REPORT
+ settings_used = {
+ **_LIGHTHOUSE_API_SETTINGS,
+ "SIGNALS_LIGHTHOUSE_TEAM_IDS": {self.team.id},
+ **setting_overrides,
+ }
+ with self.settings(**settings_used):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.posthoganalytics.get_feature_flag_payload",
+ return_value=None,
+ ):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.browserless_request", return_value=response
+ ) as browserless:
+ return (
+ self.client.post(self._audit_url(str(run.id)), data={"url": url}, format="json"),
+ browserless,
+ )
+
+ def _spent(self, run: SignalScoutRun) -> int:
+ run.refresh_from_db()
+ return (run.metadata or {}).get(RUN_AUDIT_COUNT_KEY, 0)
+
+ def test_a_successful_audit_spends_exactly_one_slot(self) -> None:
+ run = _make_run(self.team)
+
+ response, browserless = self._post(run)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["audits_remaining"] == MAX_AUDITS_PER_RUN - 1
+ assert self._spent(run) == 1
+ assert browserless.call_count == 1
+
+ @parameterized.expand(
+ [
+ ("off_allowlist_host", "https://example.com/pricing", {}),
+ ("not_https", "http://posthog.com/pricing", {}),
+ ("team_not_enabled", "https://posthog.com/pricing", {"SIGNALS_LIGHTHOUSE_TEAM_IDS": set()}),
+ ]
+ )
+ def test_a_rejection_that_never_loads_a_page_costs_no_budget(self, _name: str, url: str, overrides: dict) -> None:
+ # A scout that misread the host rule would otherwise burn all five slots on instant
+ # round-trips and then be told it had spent them on audits.
+ run = _make_run(self.team)
+
+ response, browserless = self._post(run, url=url, **overrides)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ browserless.assert_not_called()
+ assert self._spent(run) == 0
+ # The remaining count rides in the message, so a scout can tell a rejection
+ # (budget intact) from an exhausted budget.
+ assert f"{MAX_AUDITS_PER_RUN} of {MAX_AUDITS_PER_RUN} audits still available" in response.json()["detail"]
+
+ def test_the_per_run_cap_is_enforced_without_reaching_browserless(self) -> None:
+ run = _make_run(self.team, metadata={RUN_AUDIT_COUNT_KEY: MAX_AUDITS_PER_RUN})
+
+ response, browserless = self._post(run)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "0 still available" in response.json()["detail"]
+ browserless.assert_not_called()
+
+ def test_a_failed_page_load_still_spends_its_slot(self) -> None:
+ # The runaway case the cap exists for is a scout retrying a page that cannot load.
+ run = _make_run(self.team)
+ broken = MagicMock(status_code=500, content=b"")
+ broken.text = "upstream error"
+ with self.settings(**_LIGHTHOUSE_API_SETTINGS, SIGNALS_LIGHTHOUSE_TEAM_IDS={self.team.id}):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.posthoganalytics.get_feature_flag_payload",
+ return_value=None,
+ ):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.browserless_request", return_value=broken
+ ):
+ response = self.client.post(
+ self._audit_url(str(run.id)),
+ data={"url": "https://posthog.com/pricing"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert self._spent(run) == 1
+
+ def test_a_fleet_at_capacity_gives_the_slot_back(self) -> None:
+ # The egress gate refuses before a browser starts, so five refusals must not read as five
+ # audits — a busy fleet would otherwise empty a run's budget without measuring anything.
+ run = _make_run(self.team)
+ with self.settings(**_LIGHTHOUSE_API_SETTINGS, SIGNALS_LIGHTHOUSE_TEAM_IDS={self.team.id}):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.posthoganalytics.get_feature_flag_payload",
+ return_value=None,
+ ):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.browserless_request",
+ side_effect=BrowserlessEgressBudgetExhausted("Browserless egress budget exhausted"),
+ ):
+ response = self.client.post(
+ self._audit_url(str(run.id)),
+ data={"url": "https://posthog.com/pricing"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert self._spent(run) == 0
+ assert f"{MAX_AUDITS_PER_RUN} of {MAX_AUDITS_PER_RUN} audits still available" in response.json()["detail"]
+
+ def test_returns_501_when_the_deployment_has_no_browserless(self) -> None:
+ run = _make_run(self.team)
+
+ response, browserless = self._post(run, LIGHTHOUSE_BROWSERLESS_URL="")
+
+ assert response.status_code == status.HTTP_501_NOT_IMPLEMENTED
+ browserless.assert_not_called()
+ assert self._spent(run) == 0
+
+ def test_rejects_a_run_that_is_not_in_progress(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ run = _make_run(self.team, task_run_status=TaskRun.Status.COMPLETED)
+
+ response, browserless = self._post(run)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ browserless.assert_not_called()
+
+ def test_another_teams_run_is_not_auditable(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ run = _make_run(other_team)
+
+ response, browserless = self._post(run)
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ browserless.assert_not_called()
+
+ def test_a_sandbox_token_may_only_spend_its_own_runs_budget(self) -> None:
+ # Team scoping alone leaves the per-run cap in name only: a scout can list its siblings
+ # and spend each one's five slots, and every slot is a real browser session. Both halves
+ # matter — without the first, refusing everything would pass just as well.
+ own_run = _make_run(self.team)
+ sibling_run = _make_run(self.team)
+ _authenticate_as_scout(self, sandbox_task_id=own_run.task_run.task_id)
+
+ allowed, browserless_for_own = self._post(own_run)
+ refused, browserless_for_sibling = self._post(sibling_run)
+
+ assert allowed.status_code == status.HTTP_200_OK, allowed.json()
+ assert browserless_for_own.call_count == 1
+ assert self._spent(own_run) == 1
+
+ assert refused.status_code == status.HTTP_404_NOT_FOUND
+ browserless_for_sibling.assert_not_called()
+ assert self._spent(sibling_run) == 0
diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.py
index eb213de94eca..d6b1fabea539 100644
--- a/products/signals/backend/test/test_scout_harness_tools.py
+++ b/products/signals/backend/test/test_scout_harness_tools.py
@@ -4,18 +4,23 @@ import uuid
import dataclasses
from datetime import timedelta
from typing import TYPE_CHECKING
+from urllib.parse import quote
import pytest
from posthog.test.base import BaseTest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.apps import apps
+from django.test import override_settings
from django.utils import timezone
import pytest_asyncio
from parameterized import parameterized
+from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted
+from posthog.egress.limiter.policies import Priority
from posthog.models.scoping import team_scope
+from posthog.settings.signals import _parse_team_ids
from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutEmission, SignalScoutRun, SignalScratchpad
@@ -27,14 +32,22 @@ from products.signals.backend.scout_harness.note_targets import (
)
from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIX
from products.signals.backend.scout_harness.tools import (
+ MAX_AUDITS_PER_RUN,
MAX_EVIDENCE_ENTRIES,
EvidenceEntry,
InvalidEmitError,
+ InvalidLighthouseTargetError,
InvalidScratchpadError,
+ LighthouseAuditFailedError,
+ LighthouseFleetBusyError,
+ LighthouseUnavailableError,
+ audits_remaining_for_run,
emit_finding,
+ enabled_team_ids,
forget,
get_run,
remember,
+ run_lighthouse_audit,
search_recent_runs,
search_scratchpad,
)
@@ -1695,3 +1708,356 @@ class TestReportEventUuid:
legacy = uuid.uuid5(uuid.NAMESPACE_URL, 'signals_scout_report_charted:["edit","x"]')
assert _report_event_uuid("edit", "x", structured=True) == str(legacy)
+
+
+# Lighthouse 13 carries the LCP element and its phase table on *insight* audits and drops the
+# legacy per-check audit ids entirely, so a fixture written in the legacy shape passes against a
+# parser that reads nothing on the version the fleet runs.
+def _lighthouse_payload(**overrides) -> dict:
+ report = {
+ "lighthouseVersion": "13.4.1",
+ "requestedUrl": "https://posthog.com/pricing",
+ "finalDisplayedUrl": "https://posthog.com/pricing",
+ "categories": {"performance": {"score": 0.28}},
+ "audits": {
+ "largest-contentful-paint": {"numericValue": 4553.2},
+ "first-contentful-paint": {"numericValue": 2296.0},
+ "cumulative-layout-shift": {"numericValue": 0.115},
+ "lcp-breakdown-insight": {
+ "title": "LCP breakdown",
+ "score": 1,
+ "details": {
+ "type": "list",
+ "items": [
+ {
+ "type": "table",
+ "items": [
+ {"subpart": "timeToFirstByte", "label": "Time to first byte", "duration": 100.0},
+ {"subpart": "elementRenderDelay", "label": "Element render delay", "duration": 300.0},
+ ],
+ },
+ {
+ "type": "node",
+ "selector": "div.hero > img.w-full",
+ "snippet": '<img src="hero.webp" width="720">',
+ "nodeLabel": "Boxed copy of the product",
+ },
+ ],
+ },
+ },
+ "lcp-discovery-insight": {
+ "title": "LCP request discovery",
+ "score": 0,
+ "details": {
+ "type": "list",
+ "items": [
+ {
+ "type": "checklist",
+ "items": {
+ "priorityHinted": {"label": "fetchpriority=high should be applied", "value": False},
+ "eagerlyLoaded": {"label": "LCP resources should not use loading=lazy", "value": True},
+ },
+ }
+ ],
+ },
+ },
+ "image-delivery-insight": {"title": "Improve image delivery", "metricSavings": {"FCP": 0, "LCP": 900}},
+ # CLS savings are a unitless layout-shift score, not milliseconds.
+ "layout-shifts": {"title": "Layout shifts", "metricSavings": {"CLS": 0.101}},
+ "unminified-css": {"title": "Minify CSS", "metricSavings": {"LCP": 12}},
+ },
+ }
+ report.update(overrides)
+ return {"data": report}
+
+
+# Pre-Lighthouse-12, where the element lived on `largest-contentful-paint-element`.
+def _legacy_lighthouse_payload() -> dict:
+ return {
+ "data": {
+ "lighthouseVersion": "11.7.1",
+ "finalDisplayedUrl": "https://posthog.com/pricing",
+ "categories": {"performance": {"score": 0.42}},
+ "audits": {
+ "largest-contentful-paint": {"numericValue": 4553.2},
+ "largest-contentful-paint-element": {
+ "details": {
+ "type": "list",
+ "items": [
+ {
+ "type": "table",
+ "items": [
+ {"node": {"selector": "div.hero > img", "snippet": "<img>", "nodeLabel": "Hero"}}
+ ],
+ },
+ {
+ "type": "table",
+ "items": [
+ {"phase": "TTFB", "timing": 1400, "percent": "31%"},
+ {"phase": "Render Delay", "timing": 2600, "percent": "57%"},
+ ],
+ },
+ ],
+ }
+ },
+ "prioritize-lcp-image": {"score": 0, "title": "Preload the LCP image"},
+ "lcp-lazy-loaded": {"score": 1, "title": "Do not lazy load the LCP image"},
+ },
+ }
+ }
+
+
+_AUDIT_TEAM_ID = 4242
+_AUDIT_SETTINGS = {
+ "LIGHTHOUSE_BROWSERLESS_URL": "https://browserless.example.com",
+ "LIGHTHOUSE_BROWSERLESS_TOKEN": "secret-token",
+ "LIGHTHOUSE_BROWSERLESS_TIMEOUT_MS": 60000,
+ "LIGHTHOUSE_BROWSERLESS_CONNECT_TIMEOUT_MS": 10000,
+ "LIGHTHOUSE_REPORT_MAX_BYTES": 32 * 1024 * 1024,
+ "SIGNALS_LIGHTHOUSE_ALLOWED_HOSTS": {"posthog.com"},
+ "SIGNALS_LIGHTHOUSE_TEAM_IDS": {_AUDIT_TEAM_ID},
+}
+
+
+def _no_flag_payload():
+ return patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.posthoganalytics.get_feature_flag_payload",
+ return_value=None,
+ )
+
+
+class TestLighthouseAudit:
+ def _audit(self, payload: dict, *, url: str = "https://posthog.com/pricing", form_factor: str = "desktop"):
+ response = MagicMock(status_code=200, content=b"{}")
+ response.json.return_value = payload
+ with override_settings(**_AUDIT_SETTINGS), _no_flag_payload():
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.browserless_request", return_value=response
+ ) as post:
+ return run_lighthouse_audit(team_id=_AUDIT_TEAM_ID, url=url, form_factor=form_factor), post
+
+ def test_reads_the_element_phases_and_savings_from_lighthouse_13_insight_audits(self) -> None:
+ # The shipped Lighthouse renamed every audit this reads. Parsed against the legacy ids the
+ # whole thing degrades to nulls, which is a report that says "no problems found".
+ audit, _ = self._audit(_lighthouse_payload())
+
+ assert audit.lighthouse_version == "13.4.1"
+ assert audit.lcp_element is not None
+ assert audit.lcp_element.selector == "div.hero > img.w-full"
+ # Insight rows carry no `percent`, so the share is computed from the durations present.
+ assert [(p.phase, p.percent) for p in audit.lcp_phases] == [
+ ("Time to first byte", "25%"),
+ ("Element render delay", "75%"),
+ ]
+ # The failing checklist entry is the modern "this hero image needs fetchpriority=high".
+ assert [c.audit_id for c in audit.lcp_checks_failed] == ["lcp-discovery-insight:priorityHinted"]
+ # Ranked on `metricSavings`; `unminified-css` (12ms) is under the noise floor, and
+ # `layout-shifts` is excluded because a CLS saving is a score rather than milliseconds.
+ assert [(o.audit_id, o.savings_ms) for o in audit.opportunities] == [("image-delivery-insight", 900.0)]
+
+ def test_reads_the_legacy_element_audit_when_the_fleet_runs_an_older_lighthouse(self) -> None:
+ # Browserless version is deployment config, so both shapes have to keep working.
+ audit, _ = self._audit(_legacy_lighthouse_payload())
+
+ assert audit.lcp_element is not None
+ assert audit.lcp_element.selector == "div.hero > img"
+ assert [(p.phase, p.percent) for p in audit.lcp_phases] == [("TTFB", "31%"), ("Render Delay", "57%")]
+ assert [c.audit_id for c in audit.lcp_checks_failed] == ["prioritize-lcp-image"]
+
+ @parameterized.expand(
+ [
+ ("off_allowlist", "https://example.com/pricing"),
+ ("app_host_behind_login", "https://us.posthog.com/project/2/billing"),
+ ("not_https", "http://posthog.com/pricing"),
+ ]
+ )
+ def test_rejects_a_target_outside_the_allowlist(self, _name: str, url: str) -> None:
+ with override_settings(**_AUDIT_SETTINGS), _no_flag_payload():
+ with patch("products.signals.backend.scout_harness.tools.lighthouse.browserless_request") as post:
+ with pytest.raises(InvalidLighthouseTargetError):
+ run_lighthouse_audit(team_id=_AUDIT_TEAM_ID, url=url)
+ # The fence has to hold before the request, or a disallowed page is already rendered.
+ post.assert_not_called()
+
+ def test_rejects_a_team_the_capability_is_not_enabled_for(self) -> None:
+ with override_settings(**{**_AUDIT_SETTINGS, "SIGNALS_LIGHTHOUSE_TEAM_IDS": {_AUDIT_TEAM_ID + 1}}):
+ with _no_flag_payload(), pytest.raises(InvalidLighthouseTargetError):
+ run_lighthouse_audit(team_id=_AUDIT_TEAM_ID, url="https://posthog.com/pricing")
+
+ @parameterized.expand(
+ [
+ ("ends_off_allowlist", {"finalDisplayedUrl": "https://auth.example.com/login"}),
+ (
+ "leaves_and_returns_mid_chain",
+ {
+ "audits": {
+ "largest-contentful-paint": {"numericValue": 4553.2},
+ "redirects": {
+ "details": {
+ "type": "opportunity",
+ "items": [
+ {"url": "https://posthog.com/pricing"},
+ {"url": "http://169.254.169.254/latest/meta-data/"},
+ {"url": "https://posthog.com/pricing"},
+ ],
+ }
+ },
+ }
+ },
+ ),
+ ]
+ )
+ def test_rejects_a_document_that_left_the_allowlist(self, _name: str, overrides: dict) -> None:
+ # First is the login-wall case: the audit ran, but on the sign-in screen. Second is the
+ # one the endpoints alone miss, since it starts and ends on an allowed host. Either way
+ # the report would carry another page's LCP under the requested url's name.
+ with pytest.raises(InvalidLighthouseTargetError):
+ self._audit(_lighthouse_payload(**overrides))
+
+ def test_rejects_a_report_that_does_not_say_where_it_ended(self) -> None:
+ # Fails closed: this is the only check on where the browser actually went, since
+ # Browserless resolves DNS and follows redirects itself.
+ payload = _lighthouse_payload()
+ for key in ("finalDisplayedUrl", "finalUrl", "mainDocumentUrl"):
+ payload["data"].pop(key, None)
+
+ with pytest.raises(LighthouseAuditFailedError):
+ self._audit(payload)
+
+ def test_rejects_a_report_with_no_usable_metrics(self) -> None:
+ # A 200 full of nulls reads as "this page is fine" rather than "the shape changed".
+ with pytest.raises(LighthouseAuditFailedError):
+ self._audit(_lighthouse_payload(audits={}))
+
+ def test_surfaces_a_page_lighthouse_could_not_load(self) -> None:
+ payload = _lighthouse_payload(runtimeError={"code": "ERRORED_DOCUMENT_REQUEST", "message": "net::ERR"})
+
+ with pytest.raises(LighthouseAuditFailedError):
+ self._audit(payload)
+
+ @parameterized.expand([("plain", "secret-token"), ("url_unsafe", "ab/cd+ef=gh")])
+ def test_keeps_the_browserless_token_out_of_the_error_it_raises(self, _name: str, token: str) -> None:
+ # The endpoint carries the token in its query string, and the scout writes what it reads
+ # into a report the whole team sees. `urlencode` percent-encodes a token containing
+ # `/`, `+`, or `=`, so a literal replace alone leaves that spelling in the message.
+ response = MagicMock(status_code=500, content=b"")
+ response.text = f"upstream rejected https://browserless.example.com/performance?token={quote(token, safe='')}"
+ with override_settings(**{**_AUDIT_SETTINGS, "LIGHTHOUSE_BROWSERLESS_TOKEN": token}), _no_flag_payload():
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.browserless_request", return_value=response
+ ):
+ with pytest.raises(LighthouseAuditFailedError) as raised:
+ run_lighthouse_audit(team_id=_AUDIT_TEAM_ID, url="https://posthog.com/pricing")
+
+ message = str(raised.value)
+ assert token not in message
+ assert quote(token, safe="") not in message
+
+ def test_rejects_an_implausibly_large_report_before_parsing_it(self) -> None:
+ # A real report is megabytes of base64 screenshots; parsing an unbounded one drives
+ # worker memory from whatever Browserless returns.
+ response = MagicMock(status_code=200, content=b"x" * 2048)
+ response.json.return_value = _lighthouse_payload()
+ with override_settings(**{**_AUDIT_SETTINGS, "LIGHTHOUSE_REPORT_MAX_BYTES": 1024}), _no_flag_payload():
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.browserless_request", return_value=response
+ ):
+ with pytest.raises(LighthouseAuditFailedError, match="implausibly large"):
+ run_lighthouse_audit(team_id=_AUDIT_TEAM_ID, url="https://posthog.com/pricing")
+
+ def test_asks_the_fleet_as_batch_so_a_waiting_render_goes_first(self) -> None:
+ # An audit holds a browser session for tens of seconds where the heatmap screenshot on the
+ # same fleet holds one for a few, and somebody is watching that render.
+ _, post = self._audit(_lighthouse_payload())
+
+ assert post.call_args.kwargs["priority"] is Priority.BATCH
+
+ def test_a_fleet_at_capacity_is_not_a_failed_audit(self) -> None:
+ # Distinct from a failed load: no browser started, so the caller can hand the slot back.
+ with override_settings(**_AUDIT_SETTINGS), _no_flag_payload():
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.browserless_request",
+ side_effect=BrowserlessEgressBudgetExhausted("Browserless egress budget exhausted"),
+ ):
+ with pytest.raises(LighthouseFleetBusyError):
+ run_lighthouse_audit(team_id=_AUDIT_TEAM_ID, url="https://posthog.com/pricing")
+
+ def test_is_unavailable_when_no_browserless_is_configured(self) -> None:
+ with override_settings(**{**_AUDIT_SETTINGS, "LIGHTHOUSE_BROWSERLESS_URL": ""}), _no_flag_payload():
+ with pytest.raises(LighthouseUnavailableError):
+ run_lighthouse_audit(team_id=_AUDIT_TEAM_ID, url="https://posthog.com/pricing")
+
+ @parameterized.expand([("desktop", 1, False), ("mobile", 4, True)])
+ def test_sends_the_throttling_that_matches_the_device_profile(
+ self, form_factor: str, cpu_slowdown: int, emulated_ua: bool
+ ) -> None:
+ # `lighthouse:default` throttles like a slow-4G phone. Setting only formFactor and
+ # screenEmulation leaves that in place, so a "desktop" report measures a desktop viewport
+ # over a mobile connection — numbers that can't be compared to the desktop field p75.
+ _, post = self._audit(_lighthouse_payload(), form_factor=form_factor)
+
+ sent = post.call_args.kwargs["json"]["config"]["settings"]
+ assert sent["formFactor"] == form_factor
+ assert sent["screenEmulation"]["mobile"] is (form_factor == "mobile")
+ assert sent["throttling"]["cpuSlowdownMultiplier"] == cpu_slowdown
+ assert sent["emulatedUserAgent"] is emulated_ua
+
+
+class TestLighthouseTeamGate:
+ @parameterized.expand(
+ [
+ ("no_payload", None, {_AUDIT_TEAM_ID}),
+ ("kill_switch", {"enabled": False, "team_ids": [7]}, set()),
+ ("team_ids_replace_settings", {"team_ids": [7, 8]}, {7, 8}),
+ ("empty_list_means_nobody", {"team_ids": []}, set()),
+ # A malformed payload must neither open the capability nor take it from the internal
+ # project — a flag read going wrong should change nothing.
+ ("malformed_falls_back", {"team_ids": "everyone"}, {_AUDIT_TEAM_ID}),
+ ]
+ )
+ def test_resolves_enablement(self, _name: str, payload, expected: set) -> None:
+ with override_settings(**_AUDIT_SETTINGS):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.posthoganalytics.get_feature_flag_payload",
+ return_value=payload,
+ ):
+ assert enabled_team_ids() == expected
+
+ def test_an_unreadable_flag_leaves_the_settings_posture_alone(self) -> None:
+ with override_settings(**_AUDIT_SETTINGS):
+ with patch(
+ "products.signals.backend.scout_harness.tools.lighthouse.posthoganalytics.get_feature_flag_payload",
+ side_effect=RuntimeError("flag service down"),
+ ):
+ assert enabled_team_ids() == {_AUDIT_TEAM_ID}
+
+
+class TestAuditsRemainingForRun:
+ @parameterized.expand(
+ [
+ ("absent", None, MAX_AUDITS_PER_RUN),
+ ("empty", {}, MAX_AUDITS_PER_RUN),
+ ("partly_spent", {"lighthouse_audit_count": 2}, 3),
+ ("overspent", {"lighthouse_audit_count": MAX_AUDITS_PER_RUN + 3}, 0),
+ # `metadata` is a shared JSON column, so a non-int must not 500 the endpoint.
+ ("non_numeric", {"lighthouse_audit_count": "two"}, MAX_AUDITS_PER_RUN),
+ ]
+ )
+ def test_reports_what_is_left(self, _name: str, metadata, expected: int) -> None:
+ assert audits_remaining_for_run(metadata) == expected
+
+
+class TestParseTeamIds:
+ @parameterized.expand(
+ [
+ ("plain", "1,2", {1, 2}),
+ ("padded_and_trailing_comma", " 1 , 2, ", {1, 2}),
+ ("word", "all", set()),
+ # A settings-import ValueError takes down web, worker and migrations, so every
+ # malformed spelling has to lose the capability rather than the deployment.
+ ("double_sign", "--1,7", {7}),
+ ("longer_than_the_int_digit_limit", "9" * 5000, set()),
+ ]
+ )
+ def test_keeps_the_deployment_alive(self, _name: str, raw: str, expected: set[int]) -> None:
+ assert _parse_team_ids(raw) == expected
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 16aeeded0a93..2f552188126a 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4787,6 +4787,133 @@ export interface EmitFindingResponseApi {
remediation: string | null
}
+/**
+ * * `desktop` - desktop
+ * * `mobile` - mobile
+ */
+export type FormFactorEnumApi = (typeof FormFactorEnumApi)[keyof typeof FormFactorEnumApi]
+
+export const FormFactorEnumApi = {
+ Desktop: 'desktop',
+ Mobile: 'mobile',
+} as const
+
+/**
+ * Request body for `scout-lighthouse-audit`: one page, one device profile.
+ */
+export interface LighthouseAuditRequestApi {
+ /**
+ * The page to audit. Must be an https url on an allowed host — public PostHog pages only. Pages behind a login cannot be audited: the browser signs in to nothing, so it would measure the login screen and report its numbers as the page's.
+ * @maxLength 2000
+ */
+ url: string
+ /** Which device profile to emulate. Desktop and mobile produce different numbers, so audit the one whose field data you are explaining.
+ *
+ * * `desktop` - desktop
+ * * `mobile` - mobile */
+ form_factor?: FormFactorEnumApi
+}
+
+/**
+ * Lab metrics from this run: `lcp_ms`, `fcp_ms`, `cls`, `tbt_ms`, `speed_index_ms`, `tti_ms`. One throttled cold load, not a p75 over real users — use it to explain a field finding, never to replace one.
+ */
+export type LighthouseAuditResponseApiMetrics = { [key: string]: number }
+
+/**
+ * The element the browser chose as the Largest Contentful Paint.
+ */
+export interface LcpElementApi {
+ /**
+ * CSS selector for the element.
+ * @nullable
+ */
+ selector: string | null
+ /**
+ * The element's opening tag, truncated by Lighthouse.
+ * @nullable
+ */
+ snippet: string | null
+ /**
+ * Human-readable label, usually the alt or text.
+ * @nullable
+ */
+ node_label: string | null
+}
+
+/**
+ * One phase of the LCP timeline, which is where the time actually went.
+ */
+export interface LcpPhaseApi {
+ /** Lighthouse's own label for this subpart of the LCP, e.g. 'Time to first byte' or 'Element render delay'. Passed through verbatim, so the exact wording follows the Lighthouse version. */
+ phase: string
+ /**
+ * Milliseconds spent in this phase.
+ * @nullable
+ */
+ timing_ms: number | null
+ /**
+ * This subpart's share of the total LCP, e.g. '62%'.
+ * @nullable
+ */
+ percent: string | null
+}
+
+/**
+ * A failing check or a savings estimate from the audit.
+ */
+export interface AuditOpportunityApi {
+ /** Lighthouse audit id, for example `prioritize-lcp-image`. */
+ audit_id: string
+ /** Lighthouse's own title for the check. */
+ title: string
+ /**
+ * Estimated milliseconds this would save. Null for a pass/fail check with no estimate.
+ * @nullable
+ */
+ savings_ms: number | null
+}
+
+/**
+ * The audit, reduced to what a web vitals finding cites.
+ *
+ * The full Lighthouse report runs to a few hundred KB of detail no finding ever quotes, so the
+ * response carries the metrics, the LCP element and its phase breakdown, and the ranked
+ * opportunities, and drops the rest.
+ */
+export interface LighthouseAuditResponseApi {
+ /** The url that was audited. */
+ requested_url: string
+ /**
+ * Where the browser ended up after redirects.
+ * @nullable
+ */
+ final_url: string | null
+ /** The device profile the audit emulated. */
+ form_factor: string
+ /**
+ * The Lighthouse version that produced this report. Audit ids move between major versions, so cite it when an expected field came back empty.
+ * @nullable
+ */
+ lighthouse_version: string | null
+ /**
+ * Lighthouse performance score out of 100 for this run.
+ * @nullable
+ */
+ performance_score: number | null
+ /** Lab metrics from this run: `lcp_ms`, `fcp_ms`, `cls`, `tbt_ms`, `speed_index_ms`, `tti_ms`. One throttled cold load, not a p75 over real users — use it to explain a field finding, never to replace one. */
+ metrics: LighthouseAuditResponseApiMetrics
+ /** The element the browser chose as the LCP, or null when Lighthouse could not name one. */
+ lcp_element: LcpElementApi | null
+ /** Where the LCP time went, phase by phase. Empty when the report omits the breakdown. */
+ lcp_phases: LcpPhaseApi[]
+ /** LCP-specific checks this page failed, such as an unprioritized or lazy-loaded hero image. */
+ lcp_checks_failed: AuditOpportunityApi[]
+ /** Ranked savings estimates across the whole page, largest first. */
+ opportunities: AuditOpportunityApi[]
+ /** How many audits this run may still spend. Each run gets 5. */
+ audits_remaining: number
+}
+
/**
* The record itself, as a JSON object. Must validate against the scout config's `structured_output_schema` (shown in the run prompt); any invalid record fails the whole call with nothing written.
*/
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 415177877b18..6882a6af069a 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -19,6 +19,8 @@ import type {
FleetFindingsSummaryApi,
ForgetRequestApi,
ForgetResponseApi,
+ LighthouseAuditRequestApi,
+ LighthouseAuditResponseApi,
PaginatedPauseStateResponseListApi,
PaginatedSignalReportArtefactListApi,
PaginatedSignalReportCheckListApi,
@@ -1515,6 +1517,28 @@ export const signalsScoutEmitSignal = async (
})
}
+export const getSignalsScoutLighthouseAuditUrl = (projectId: string, runId: string) => {
+ return `/api/projects/${projectId}/signals/scout/runs/${runId}/lighthouse-audit/`
+}
+
+/**
+ * Load one page in a real browser and return what makes it slow — most usefully the element the browser chose as the Largest Contentful Paint, and where the LCP time went. Field data says a route is slow; this says which element and why, so a finding can name it instead of guessing from source. Restricted to public PostHog pages: the browser signs in to nothing, so a page behind a login would report the login screen's numbers. One throttled cold load is not a p75 over real users — corroborate a field finding with it, never replace one. Capped at 5 audits per run.
+ * @summary Run a Lighthouse audit for a run
+ */
+export const signalsScoutLighthouseAudit = async (
+ projectId: string,
+ runId: string,
+ lighthouseAuditRequestApi: LighthouseAuditRequestApi,
+ options?: RequestInit
+): Promise<LighthouseAuditResponseApi> => {
+ return apiMutator<LighthouseAuditResponseApi>(getSignalsScoutLighthouseAuditUrl(projectId, runId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(lighthouseAuditRequestApi),
+ })
+}
+
export const getSignalsScoutRecordOutputUrl = (projectId: string, runId: string) => {
return `/api/projects/${projectId}/signals/scout/runs/${runId}/record-output/`
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 25b27d38fc39..a56c529106aa 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1910,6 +1910,32 @@ export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod
})
.describe('Request body for `emit-finding`. Run attribution is taken from the URL path.')
+/**
+ * Load one page in a real browser and return what makes it slow — most usefully the element the browser chose as the Largest Contentful Paint, and where the LCP time went. Field data says a route is slow; this says which element and why, so a finding can name it instead of guessing from source. Restricted to public PostHog pages: the browser signs in to nothing, so a page behind a login would report the login screen's numbers. One throttled cold load is not a p75 over real users — corroborate a field finding with it, never replace one. Capped at 5 audits per run.
+ * @summary Run a Lighthouse audit for a run
+ */
+export const signalsScoutLighthouseAuditBodyUrlMax = 2000
+
+export const signalsScoutLighthouseAuditBodyFormFactorDefault = `desktop`
+
+export const SignalsScoutLighthouseAuditBody = /* @__PURE__ */ zod
+ .object({
+ url: zod
+ .url()
+ .max(signalsScoutLighthouseAuditBodyUrlMax)
+ .describe(
+ "The page to audit. Must be an https url on an allowed host — public PostHog pages only. Pages behind a login cannot be audited: the browser signs in to nothing, so it would measure the login screen and report its numbers as the page's."
+ ),
+ form_factor: zod
+ .enum(['desktop', 'mobile'])
+ .describe('\* `desktop` - desktop\n\* `mobile` - mobile')
+ .default(signalsScoutLighthouseAuditBodyFormFactorDefault)
+ .describe(
+ 'Which device profile to emulate. Desktop and mobile produce different numbers, so audit the one whose field data you are explaining.\n\n\* `desktop` - desktop\n\* `mobile` - mobile'
+ ),
+ })
+ .describe('Request body for `scout-lighthouse-audit`: one page, one device profile.')
+
/**
* The structured-output channel: record schema-validated records this run produced. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one record) — without it the call fails closed, as it does for a dry-run scout (emit off). All-or-nothing: any invalid record fails the whole call with nothing written, so fix and resubmit the batch. Each accepted record lands in the project's event stream as a `$scout_structured_output` event — query them like any event (insights, SQL over `events`). Recording is idempotent: event ids are deterministic, so resubmitting an identical batch (e.g. retrying after a 503) cannot double-count.
* @summary Record structured output for a run
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index e2561c23316b..2f1b5fba7be8 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -624,6 +624,29 @@ tools:
`Signal.source_id = run:<id>:finding:<id>` for traceability, but this is NOT idempotent — a second call with
the same `finding_id` emits a second signal, so emit each finding exactly once and never retry an emit.
Findings should carry `tags` — see the `tags` param for the slug and taxonomy convention.
+ scout-lighthouse-audit:
+ operation: signals_scout_lighthouse_audit
+ enabled: true
+ scopes:
+ - signal_scout_internal:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Run a Lighthouse audit for a run
+ description: >
+ Load one page in a real browser and get back what makes it slow: the lab metrics (LCP, FCP, CLS, TBT), the
+ element the browser chose as the Largest Contentful Paint, where the LCP time went phase by phase, and the
+ ranked savings estimates. Use it to name the cause behind a field finding — `$web_vitals` events say a route
+ is slow and for how many people, but never which element was late or why. Pass the `run_id`, a `url`, and
+ optionally `form_factor` (`desktop` or `mobile`, matching whichever field data you are explaining).
+ Restricted to an allowlist of public PostHog pages: the browser signs in to nothing, so a page behind a
+ login would measure the login screen and report its numbers as the page's, and a url that redirects off the
+ allowlist is rejected for the same reason. One throttled cold load is not a p75 over real users — cite it as
+ the explanation for a field finding, never as the evidence that a problem exists. Capped at 5 audits per
+ run. A rejected call (bad host, not https, audits not enabled here) costs nothing, but once the page loads
+ the slot is spent whatever the result — so pick the page before calling. Every error message ends with how
+ many audits the run has left, which tells a rejection apart from an exhausted budget.
scout-members-list:
operation: signals_scout_members_list
enabled: true
diff --git a/products/signals/skills/signals-scout-web-vitals/SKILL.md b/products/signals/skills/signals-scout-web-vitals/SKILL.md
index 5604857ac330..cf13686f3777 100644
--- a/products/signals/skills/signals-scout-web-vitals/SKILL.md
+++ b/products/signals/skills/signals-scout-web-vitals/SKILL.md
@@ -479,6 +479,9 @@ For each candidate, the call is **edit an existing report, author a new one, rem
`$web_vitals_INP_event.attribution` carries `interactionTarget` (see Explore); the LCP and CLS objects carry their own payloads, so read whichever keys are present rather than assuming a shape, since they move with the `web-vitals` version.
Attribution localizes a finding with no repository access at all, so it is the cheaper of the two lookups.
It is absent entirely when the SDK captures with `capture_performance.web_vitals_attribution` off — the metric object then carries the value and rating but no `attribution` key — and that absence is itself a nameable blocker with a one-line unlock, not a reason to send the reader to DevTools.
+ On an auditable page (see `scout-lighthouse-audit` below) you have a third source that needs no SDK change: one audit names the LCP element and splits its time across TTFB, load delay, load time, and render delay, which usually settles both which element and which phase in a single call.
+ Reach for it once you have a page and a metric worth explaining, not to go looking — it is a real browser load, and the run gets five.
+ Keep the two kinds of evidence separate in the report: the field percentile is why the page matters and how many people it reaches, the audit is why it is slow. Never let a lab number stand in for a p75, and say which is which wherever you cite both.
A hostname in `$web_vitals` events is
attacker-controllable (anyone with the public capture token can fabricate volume for
a host they own), so mapping host → repository from the data and then fetching that
@@ -597,6 +600,17 @@ Harness-level:
- `scout-emit-report` / `scout-edit-report` /
`scout-scratchpad-remember` / `scout-scratchpad-forget` — author a
report / edit an existing one / remember / prune stale memory keys.
+- `scout-lighthouse-audit` — load one page in a real browser and get back the LCP element,
+ the LCP phase breakdown, and ranked savings estimates. This is how a finding names the
+ element instead of nominating a candidate from source. Pass the `form_factor` matching the
+ field data you are explaining, since desktop and mobile disagree. It only reaches an
+ allowlist of public pages — anything behind a login is rejected, because the browser signs
+ in to nothing and would measure the login screen. A 400 naming the host means this page
+ isn't auditable: fall back to capture attribution or source reading, and don't retry.
+ Five per run. A rejected call costs nothing, but once the page loads the slot is spent
+ whatever the result; every error message ends with how many you have left, so you can tell the two apart.
+ A null `lcp_element` means Lighthouse didn't name one — say so and cite the
+ `lighthouse_version` rather than nominating an element the audit didn't identify.
## When to stop
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 75cd7a94acce..f917e11f5ebc 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9966,6 +9966,20 @@
"readOnlyHint": false
}
},
+ "scout-lighthouse-audit": {
+ "description": "Load one page in a real browser and get back what makes it slow: the lab metrics (LCP, FCP, CLS, TBT), the element the browser chose as the Largest Contentful Paint, where the LCP time went phase by phase, and the ranked savings estimates. Use it to name the cause behind a field finding — `$web_vitals` events say a route is slow and for how many people, but never which element was late or why. Pass the `run_id`, a `url`, and optionally `form_factor` (`desktop` or `mobile`, matching whichever field data you are explaining). Restricted to an allowlist of public PostHog pages: the browser signs in to nothing, so a page behind a login would measure the login screen and report its numbers as the page's, and a url that redirects off the allowlist is rejected for the same reason. One throttled cold load is not a p75 over real users — cite it as the explanation for a field finding, never as the evidence that a problem exists. Capped at 5 audits per run. A rejected call (bad host, not https, audits not enabled here) costs nothing, but once the page loads the slot is spent whatever the result — so pick the page before calling. Every error message ends with how many audits the run has left, which tells a rejection apart from an exhausted budget.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Run a Lighthouse audit for a run",
+ "title": "Run a Lighthouse audit for a run",
+ "required_scopes": ["signal_scout_internal:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"scout-members-list": {
"description": "Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their `user_uuid` in `suggested_reviewers` on `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a null `github_login` only means no draft PR can be opened as that person. Pass `search` to narrow a large roster. Strictly team-scoped.",
"category": "Signals",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e2021cdc192c..dfacaeb6efb2 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10538,6 +10538,20 @@
"readOnlyHint": false
}
},
+ "scout-lighthouse-audit": {
+ "description": "Load one page in a real browser and get back what makes it slow: the lab metrics (LCP, FCP, CLS, TBT), the element the browser chose as the Largest Contentful Paint, where the LCP time went phase by phase, and the ranked savings estimates. Use it to name the cause behind a field finding — `$web_vitals` events say a route is slow and for how many people, but never which element was late or why. Pass the `run_id`, a `url`, and optionally `form_factor` (`desktop` or `mobile`, matching whichever field data you are explaining). Restricted to an allowlist of public PostHog pages: the browser signs in to nothing, so a page behind a login would measure the login screen and report its numbers as the page's, and a url that redirects off the allowlist is rejected for the same reason. One throttled cold load is not a p75 over real users — cite it as the explanation for a field finding, never as the evidence that a problem exists. Capped at 5 audits per run. A rejected call (bad host, not https, audits not enabled here) costs nothing, but once the page loads the slot is spent whatever the result — so pick the page before calling. Every error message ends with how many audits the run has left, which tells a rejection apart from an exhausted budget.",
+ "category": "Signals",
+ "feature": "signals",
+ "summary": "Run a Lighthouse audit for a run",
+ "title": "Run a Lighthouse audit for a run",
+ "required_scopes": ["signal_scout_internal:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"scout-members-list": {
"description": "Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their `user_uuid` in `suggested_reviewers` on `scout-emit-report` / `scout-edit-report`. Every member is routable this way; a null `github_login` only means no draft PR can be opened as that person. Pass `search` to narrow a large roster. Strictly team-scoped.",
"category": "Signals",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5cee2ef5eea8..dd1b26588cfd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11143,6 +11143,21 @@ export namespace Schemas {
blocked: number;
}
+ /**
+ * A failing check or a savings estimate from the audit.
+ */
+ export interface AuditOpportunity {
+ /** Lighthouse audit id, for example `prioritize-lcp-image`. */
+ audit_id: string;
+ /** Lighthouse's own title for the check. */
+ title: string;
+ /**
+ * Estimated milliseconds this would save. Null for a pass/fail check with no estimate.
+ * @nullable
+ */
+ savings_ms: number | null;
+ }
+
/**
* * `oauth` - oauth
* * `credentials` - credentials
@@ -43481,6 +43496,18 @@ export namespace Schemas {
deleted: boolean;
}
+ /**
+ * * `desktop` - desktop
+ * * `mobile` - mobile
+ */
+ export type FormFactorEnum = typeof FormFactorEnum[keyof typeof FormFactorEnum];
+
+
+ export const FormFactorEnum = {
+ Desktop: 'desktop',
+ Mobile: 'mobile',
+ } as const;
+
/**
* * `allowed` - allowed
* * `blocked` - blocked
@@ -51162,6 +51189,45 @@ export namespace Schemas {
FullWidth: 'full_width',
} as const;
+ /**
+ * The element the browser chose as the Largest Contentful Paint.
+ */
+ export interface LcpElement {
+ /**
+ * CSS selector for the element.
+ * @nullable
+ */
+ selector: string | null;
+ /**
+ * The element's opening tag, truncated by Lighthouse.
+ * @nullable
+ */
+ snippet: string | null;
+ /**
+ * Human-readable label, usually the alt or text.
+ * @nullable
+ */
+ node_label: string | null;
+ }
+
+ /**
+ * One phase of the LCP timeline, which is where the time actually went.
+ */
+ export interface LcpPhase {
+ /** Lighthouse's own label for this subpart of the LCP, e.g. 'Time to first byte' or 'Element render delay'. Passed through verbatim, so the exact wording follows the Lighthouse version. */
+ phase: string;
+ /**
+ * Milliseconds spent in this phase.
+ * @nullable
+ */
+ timing_ms: number | null;
+ /**
+ * This subpart's share of the total LCP, e.g. '62%'.
+ * @nullable
+ */
+ percent: string | null;
+ }
+
export interface LeakedKeyReport {
/**
* The leaked PostHog personal API key, project secret API key, or OAuth access/refresh token to revoke.
@@ -51312,6 +51378,68 @@ export namespace Schemas {
Incompatible: 'incompatible',
} as const;
+ /**
+ * Request body for `scout-lighthouse-audit`: one page, one device profile.
+ */
+ export interface LighthouseAuditRequest {
+ /**
+ * The page to audit. Must be an https url on an allowed host — public PostHog pages only. Pages behind a login cannot be audited: the browser signs in to nothing, so it would measure the login screen and report its numbers as the page's.
+ * @maxLength 2000
+ */
+ url: string;
+ /** Which device profile to emulate. Desktop and mobile produce different numbers, so audit the one whose field data you are explaining.
+ *
+ * * `desktop` - desktop
+ * * `mobile` - mobile */
+ form_factor?: FormFactorEnum;
+ }
+
+ /**
+ * Lab metrics from this run: `lcp_ms`, `fcp_ms`, `cls`, `tbt_ms`, `speed_index_ms`, `tti_ms`. One throttled cold load, not a p75 over real users — use it to explain a field finding, never to replace one.
+ */
+ export type LighthouseAuditResponseMetrics = {[key: string]: number};
+
+ /**
+ * The audit, reduced to what a web vitals finding cites.
+ *
+ * The full Lighthouse report runs to a few hundred KB of detail no finding ever quotes, so the
+ * response carries the metrics, the LCP element and its phase breakdown, and the ranked
+ * opportunities, and drops the rest.
+ */
+ export interface LighthouseAuditResponse {
+ /** The url that was audited. */
+ requested_url: string;
+ /**
+ * Where the browser ended up after redirects.
+ * @nullable
+ */
+ final_url: string | null;
+ /** The device profile the audit emulated. */
+ form_factor: string;
+ /**
+ * The Lighthouse version that produced this report. Audit ids move between major versions, so cite it when an expected field came back empty.
+ * @nullable
+ */
+ lighthouse_version: string | null;
+ /**
+ * Lighthouse performance score out of 100 for this run.
+ * @nullable
+ */
+ performance_score: number | null;
+ /** Lab metrics from this run: `lcp_ms`, `fcp_ms`, `cls`, `tbt_ms`, `speed_index_ms`, `tti_ms`. One throttled cold load, not a p75 over real users — use it to explain a field finding, never to replace one. */
+ metrics: LighthouseAuditResponseMetrics;
+ /** The element the browser chose as the LCP, or null when Lighthouse could not name one. */
+ lcp_element: LcpElement | null;
+ /** Where the LCP time went, phase by phase. Empty when the report omits the breakdown. */
+ lcp_phases: LcpPhase[];
+ /** LCP-specific checks this page failed, such as an unprioritized or lazy-loaded hero image. */
+ lcp_checks_failed: AuditOpportunity[];
+ /** Ranked savings estimates across the whole page, largest first. */
+ opportunities: AuditOpportunity[];
+ /** How many audits this run may still spend. Each run gets 5. */
+ audits_remaining: number;
+ }
+
/**
* * `burst` - burst
* * `sustained` - sustained
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 9fbb58408cc4..8fae4827bebb 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 41 enabled ops
+ * PostHog API - MCP 42 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -2272,6 +2272,41 @@ export const SignalsScoutEmitSignalBody = () => zod
})
.describe('Request body for `emit-finding`. Run attribution is taken from the URL path.')
+/**
+ * Load one page in a real browser and return what makes it slow — most usefully the element the browser chose as the Largest Contentful Paint, and where the LCP time went. Field data says a route is slow; this says which element and why, so a finding can name it instead of guessing from source. Restricted to public PostHog pages: the browser signs in to nothing, so a page behind a login would report the login screen's numbers. One throttled cold load is not a p75 over real users — corroborate a field finding with it, never replace one. Capped at 5 audits per run.
+ * @summary Run a Lighthouse audit for a run
+ */
+export const SignalsScoutLighthouseAuditParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+ run_id: zod.string().describe('UUID of the `SignalScoutRun` bridge row.'),
+})
+
+export const signalsScoutLighthouseAuditBodyUrlMax = 2000
+
+export const signalsScoutLighthouseAuditBodyFormFactorDefault = `desktop`
+
+export const SignalsScoutLighthouseAuditBody = () => zod
+ .object({
+ url: zod
+ .url()
+ .max(signalsScoutLighthouseAuditBodyUrlMax)
+ .describe(
+ "The page to audit. Must be an https url on an allowed host — public PostHog pages only. Pages behind a login cannot be audited: the browser signs in to nothing, so it would measure the login screen and report its numbers as the page's."
+ ),
+ form_factor: zod
+ .enum(['desktop', 'mobile'])
+ .describe('\* `desktop` - desktop\n\* `mobile` - mobile')
+ .default(signalsScoutLighthouseAuditBodyFormFactorDefault)
+ .describe(
+ 'Which device profile to emulate. Desktop and mobile produce different numbers, so audit the one whose field data you are explaining.\n\n\* `desktop` - desktop\n\* `mobile` - mobile'
+ ),
+ })
+ .describe('Request body for `scout-lighthouse-audit`: one page, one device profile.')
+
/**
* The structured-output channel: record schema-validated records this run produced. Opt-in via the scout config's `structured_output_schema` (a JSON Schema describing one record) — without it the call fails closed, as it does for a dry-run scout (emit off). All-or-nothing: any invalid record fails the whole call with nothing written, so fix and resubmit the batch. Each accepted record lands in the project's event stream as a `$scout_structured_output` event — query them like any event (insights, SQL over `events`). Recording is idempotent: event ids are deterministic, so resubmitting an identical batch (e.g. retrying after a 503) cannot double-count.
* @summary Record structured output for a run
diff --git a/services/mcp/src/lib/constants.ts b/services/mcp/src/lib/constants.ts
index 3bb73e733162..49eef3e1d74b 100644
--- a/services/mcp/src/lib/constants.ts
+++ b/services/mcp/src/lib/constants.ts
@@ -28,6 +28,14 @@ export const MCP_ANALYTICS_SOURCE = 'posthog_mcp_analytics'
// fit, and the tool-domain index absorbs whatever budget the fixed sections leave.
export const MCP_INSTRUCTIONS_CHAR_BUDGET = 2048
+// Ceiling for the tool-domain index inside the claude.ai exec command reference. That reference
+// lives in the `command` description, whose serialized schema claude.ai silently drops past
+// ~16,384 chars, and the index is the only part of it that grows with the tool catalog — one new
+// tool can split a family into sub-family roots and add hundreds of characters. Bounding it here
+// makes `toCompact` trade sub-family precision to stay inside the cap, which costs far less than
+// a dropped exec tool.
+export const MCP_CLAUDE_TOOL_DOMAINS_CHAR_BUDGET = 1536
+
// Gates reaching third-party MCP servers connected through the MCP gateway. Same flag as
// the gateway's own UI in the main app, so a team gets the tools when it gets the gateway.
export const MCP_GATEWAY_FLAG = 'mcp-gateway'
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index f611b749e771..701566febcd0 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -1,5 +1,5 @@
import type { GroupType } from '@/api/client'
-import { MCP_INSTRUCTIONS_CHAR_BUDGET } from '@/lib/constants'
+import { MCP_CLAUDE_TOOL_DOMAINS_CHAR_BUDGET, MCP_INSTRUCTIONS_CHAR_BUDGET } from '@/lib/constants'
import {
buildAvailableToolsBlock,
buildDefinedGroupsBlock,
@@ -246,6 +246,7 @@ export class InstructionsFormatter {
{
compact: false,
compactToolDomains: true,
+ toolDomainsMaxChars: MCP_CLAUDE_TOOL_DOMAINS_CHAR_BUDGET,
extraCommands: learnEnabled ? LEARN_COMMAND_LINE : undefined,
}
)
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index dc58fc32ec4a..7e40c0094438 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -989,6 +989,36 @@ const scoutEmitSignal = (): ToolBase<ReturnType<typeof ScoutEmitSignalSchema>, S
},
})
+const ScoutLighthouseAuditSchema = () => {
+ const SignalsScoutLighthouseAuditBody = orvalSchemas.SignalsScoutLighthouseAuditBody()
+ const SignalsScoutLighthouseAuditParams = orvalSchemas.SignalsScoutLighthouseAuditParams()
+ return SignalsScoutLighthouseAuditParams.omit({ project_id: true }).extend(SignalsScoutLighthouseAuditBody.shape)
+}
+
+const scoutLighthouseAudit = (): ToolBase<
+ ReturnType<typeof ScoutLighthouseAuditSchema>,
+ Schemas.LighthouseAuditResponse
+> => ({
+ name: 'scout-lighthouse-audit',
+ schema: ScoutLighthouseAuditSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof ScoutLighthouseAuditSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.url !== undefined) {
+ body['url'] = params.url
+ }
+ if (params.form_factor !== undefined) {
+ body['form_factor'] = params.form_factor
+ }
+ const result = await context.api.request<Schemas.LighthouseAuditResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/runs/${encodeURIComponent(String(params.run_id))}/lighthouse-audit/`,
+ body,
+ })
+ return result
+ },
+})
+
const ScoutMembersListSchema = () => {
const SignalsScoutMembersListQueryParams = orvalSchemas.SignalsScoutMembersListQueryParams()
return SignalsScoutMembersListQueryParams
@@ -2077,6 +2107,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'scout-edit-report': scoutEditReport,
'scout-emit-report': scoutEmitReport,
'scout-emit-signal': scoutEmitSignal,
+ 'scout-lighthouse-audit': scoutLighthouseAudit,
'scout-members-list': scoutMembersList,
'scout-metadata-get': scoutMetadataGet,
'scout-notes-create': scoutNotesCreate,