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.

43.7 KB
Raw Blame
"""
DRF views for visual_review.

Responsibilities:
- Validate incoming JSON (via serializers)
- Convert JSON to DTOs
- Call facade methods (api/api.py)
- Convert DTOs to JSON responses

No business logic here - that belongs in logic.py via the facade.
"""

from typing import cast
from uuid import UUID

from django.http import HttpResponse
from django.utils.cache import get_conditional_response, patch_cache_control, patch_vary_headers

from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.response import Response

from posthog.api.mixins import TypedRequest, validated_request
from posthog.api.pagination import FacadeLimitOffsetPagination, PrecountedLimitOffsetPagination, facade_page_response
from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.auth import is_mcp_request
from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH

from ..facade import api, contracts
from ..facade.contracts import (
    AddSnapshotsInput,
    ApproveRunInput,
    ApproveRunRequestInput,
    CreateRepoInput,
    CreateRunInput,
    FinalizeRunRequestInput,
    LiftOnMergeInput,
    QuarantineInput,
    UpdateRepoInput,
    UpdateRepoRequestInput,
)
from ..facade.enums import ActorType, RunReviewFilter
from .serializers import (
    AddSnapshotsInputSerializer,
    AddSnapshotsResultSerializer,
    ApproveRunInputSerializer,
    BaselineOverviewSerializer,
    CompleteRunInputSerializer,
    CreateRepoInputSerializer,
    CreateRunInputSerializer,
    CreateRunResultSerializer,
    ErrorDetailSerializer,
    FinalizeResultSerializer,
    FinalizeRunInputSerializer,
    FlakinessOverviewSerializer,
    LiftOnMergeInputSerializer,
    MarkToleratedInputSerializer,
    QuarantinedIdentifierEntrySerializer,
    QuarantineInputSerializer,
    QuarantineLiftEntrySerializer,
    RecomputeResultSerializer,
    RepoSerializer,
    ReviewStateCountsSerializer,
    RunSerializer,
    RunSnapshotsQuerySerializer,
    SnapshotHistoryEntrySerializer,
    SnapshotSerializer,
    ToleratedHashEntrySerializer,
    TolerationPileupsQuerySerializer,
    TolerationPileupsSerializer,
    UnquarantineQuerySerializer,
    UpdateRepoInputSerializer,
)


def _actor(request: Request) -> ActorType:
    """Who is making this write, for attribution on the row it creates.

    `is_mcp_request` needs both a scoped token and the MCP server's user agent, so a
    browser session is never recorded as an agent. The marker is client-supplied, so
    this attributes a write and must never gate one.
    """
    return ActorType.AGENT if is_mcp_request(request) else ActorType.HUMAN


REVIEW_STATE_PARAMETER = OpenApiParameter(
    "review_state",
    str,
    required=False,
    enum=[state.value for state in RunReviewFilter],
    description=(
        "Filter by where the run stands in review. `needs_review`: a completed pull request run with "
        "changes nobody approved yet. `clean`: no changes, or approved. `processing`: diffs still computing. "
        "`stale`: superseded by a newer run while its changes were unapproved."
    ),
)


def _parse_review_state(request: Request) -> RunReviewFilter | None:
    """Reject an unknown review state, so a typo returns a 400 instead of every run."""
    value = request.query_params.get("review_state")
    if value is None:
        return None
    try:
        return RunReviewFilter(value)
    except ValueError:
        allowed = ", ".join(state.value for state in RunReviewFilter)
        raise ValidationError({"review_state": f"Must be one of: {allowed}."})


# Both run-scoped snapshot lookups need a run id AND a snapshot identifier. Clients that
# read only the prose kept sending one of the two, so the pair is described in one place
# and each side names the other as required.
_RUN_ID_PATH_PARAMETER = OpenApiParameter(
    "id",
    OpenApiTypes.UUID,
    OpenApiParameter.PATH,
    required=True,
    description=(
        "UUID of the visual review run to look the snapshot up from. This is a run id, not the "
        "`id` of a snapshot inside that run. The run supplies the repo and run type to search, so "
        "the `identifier` query parameter is required alongside it."
    ),
)

_SNAPSHOT_IDENTIFIER_PARAMETER = OpenApiParameter(
    "identifier",
    str,
    required=True,
    description=(
        "Identifier of the snapshot to look up, for example a Storybook story id plus theme. Read "
        "it from the `identifier` field of a snapshot in the run. It is a name rather than a UUID, "
        "and it is required in addition to the run id in the path."
    ),
)

_MISSING_IDENTIFIER_DETAIL = (
    "The identifier query parameter is required. Pass the `identifier` of the snapshot you want, "
    "which you can read from the run's snapshot list."
)


class SnapshotsPagination(PrecountedLimitOffsetPagination):
    """Adds quarantined_count to the paginated snapshots envelope so a client can
    show "N quarantined hidden" without a second request. The action pages in SQL
    through the facade, then sets the total and `quarantined_count` on the paginator
    instance before rendering the response."""

    # The run scene loads every changed snapshot of a run in one request with `limit=10000`.
    max_limit = 10000
    quarantined_count = 0

    def get_paginated_response(self, data: object) -> Response:
        response = super().get_paginated_response(data)
        response.data["quarantined_count"] = self.quarantined_count
        return response

    def get_paginated_response_schema(self, schema: dict) -> dict:
        schema = super().get_paginated_response_schema(schema)
        schema["properties"]["quarantined_count"] = {
            "type": "integer",
            "description": (
                "Count of this run's snapshots that match the other filters and whose identifier "
                "is quarantined now. Excluded from results unless include_quarantined=true is passed. "
                "This can differ from the run's own counts, which use the quarantines at gating time."
            ),
        }
        return schema


class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
    """
    Projects for visual review.

    A repo typically represents a repository or test suite.
    """

    scope_object = "visual_review"
    path_parameters = {"pk": UUID}

    pagination_class = FacadeLimitOffsetPagination
    scope_object_write_actions = ["create", "partial_update", "quarantine", "unquarantine"]
    scope_object_read_actions = [
        "list",
        "retrieve",
        "list_quarantined",
        "thumbnail",
        "baselines",
        "flakiness",
        "toleration_pileups",
    ]

    @extend_schema(responses={200: RepoSerializer(many=True)})
    def list(self, request: Request, **kwargs) -> Response:
        """List all projects for the team."""
        return facade_page_response(
            self, lambda page: api.list_repos(self.team_id, page), serializer_class=RepoSerializer
        )

    @validated_request(
        request_serializer=CreateRepoInputSerializer,
        responses={201: OpenApiResponse(response=RepoSerializer)},
    )
    def create(self, request: TypedRequest[CreateRepoInput], **kwargs) -> Response:
        """Create a new repo."""
        data = request.validated_data
        if data.repo_external_id is None:
            return Response({"detail": "repo_external_id is required"}, status=status.HTTP_400_BAD_REQUEST)
        repo = api.create_repo(
            team_id=self.team_id,
            repo_external_id=data.repo_external_id,
            repo_full_name=data.repo_full_name,
        )
        return Response(RepoSerializer(instance=repo).data, status=status.HTTP_201_CREATED)

    @extend_schema(responses={200: RepoSerializer})
    def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
        """Get a repo by ID."""
        try:
            repo = api.get_repo(pk, team_id=self.team_id)
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        return Response(RepoSerializer(instance=repo).data)

    @validated_request(
        request_serializer=UpdateRepoInputSerializer,
        responses={200: OpenApiResponse(response=RepoSerializer)},
    )
    def partial_update(self, request: TypedRequest[UpdateRepoRequestInput], pk: UUID, **kwargs) -> Response:
        """Update a repo's settings."""
        body = request.validated_data
        input_dto = UpdateRepoInput(
            repo_id=pk,
            baseline_file_paths=body.baseline_file_paths,
            enable_pr_comments=body.enable_pr_comments,
            debt_digest_enabled=body.debt_digest_enabled,
        )

        try:
            repo = api.update_repo(input_dto, team_id=self.team_id)
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        return Response(RepoSerializer(instance=repo).data)

    @extend_schema(
        parameters=[
            OpenApiParameter("identifier", OpenApiTypes.STR, OpenApiParameter.PATH),
            OpenApiParameter(
                "run_type",
                OpenApiTypes.STR,
                OpenApiParameter.QUERY,
                required=False,
                description=(
                    "Narrow the lookup to one run type. The same identifier under two run types is "
                    "two different images, so omit this only when the caller shows one run type."
                ),
            ),
        ],
        responses={200: OpenApiResponse(description="WebP thumbnail image")},
    )
    @action(detail=True, methods=["get"], url_path=r"thumbnails/(?P<identifier>.+[^/])")
    def thumbnail(self, request: Request, pk: UUID, identifier: str, **kwargs) -> HttpResponse:
        """Serve a snapshot thumbnail by identifier. Returns WebP with ETag caching."""
        repo_id = pk
        try:
            api.get_repo(repo_id, team_id=self.team_id)
        except api.RepoNotFoundError:
            resp = HttpResponse(status=404)
            patch_cache_control(resp, no_store=True)
            return resp

        thumb_hash = api.get_thumbnail_hash_for_identifier(
            repo_id, identifier, request.query_params.get("run_type") or None
        )
        if thumb_hash is None:
            resp = HttpResponse(status=404)
            patch_cache_control(resp, no_store=True)
            return resp

        etag = f'"{thumb_hash}"'
        not_modified = get_conditional_response(request._request, etag=etag)
        if not_modified:
            # Shared caches must key on credentials — see thumbnail success path below.
            patch_vary_headers(not_modified, ["Authorization", "Cookie"])
            return not_modified

        thumb_bytes = api.read_thumbnail_bytes(repo_id, thumb_hash)
        if thumb_bytes is None:
            resp = HttpResponse(status=404)
            patch_cache_control(resp, no_store=True)
            return resp

        response = HttpResponse(thumb_bytes, content_type="image/webp")
        response["ETag"] = etag
        # Endpoint is auth-scoped (team), so Vary on credential headers prevents shared
        # caches from serving the same URL across tenants.
        patch_vary_headers(response, ["Authorization", "Cookie"])
        patch_cache_control(response, public=True, max_age=300, stale_while_revalidate=3600)
        return response

    @extend_schema(
        parameters=[
            OpenApiParameter(
                name="identifier", type=str, required=False, description="Filter by identifier (returns full history)"
            ),
            OpenApiParameter(name="run_type", type=str, required=False, description="Filter by run type"),
        ],
        responses={200: QuarantinedIdentifierEntrySerializer(many=True)},
    )
    @action(detail=True, methods=["get"], url_path="quarantine")
    def list_quarantined(self, request: Request, pk: UUID, **kwargs) -> Response:
        """List quarantined identifiers. Without filter: active only. With identifier: full history."""
        identifier = request.query_params.get("identifier")
        run_type = request.query_params.get("run_type")
        return facade_page_response(
            self,
            lambda page: api.list_quarantined(
                pk, team_id=self.team_id, identifier=identifier, run_type=run_type, page=page
            ),
            serializer_class=QuarantinedIdentifierEntrySerializer,
        )

    @validated_request(
        request_serializer=QuarantineInputSerializer,
        responses={201: OpenApiResponse(response=QuarantinedIdentifierEntrySerializer)},
    )
    @action(detail=True, methods=["post"], url_path=r"quarantine/(?P<run_type>[^/]+)")
    def quarantine(self, request: TypedRequest[QuarantineInput], pk: UUID, run_type: str, **kwargs) -> Response:
        """Quarantine a snapshot identifier for a specific run type."""
        try:
            entry = api.quarantine_identifier(
                repo_id=pk,
                run_type=run_type,
                input=request.validated_data,
                user_id=cast(int, request.user.id),
                team_id=self.team_id,
                source=_actor(request),
            )
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        return Response(QuarantinedIdentifierEntrySerializer(instance=entry).data, status=status.HTTP_201_CREATED)

    @validated_request(
        request_serializer=UnquarantineQuerySerializer,
        responses={
            204: None,
            400: OpenApiResponse(response=ErrorDetailSerializer, description="No GitHub integration."),
            429: OpenApiResponse(response=ErrorDetailSerializer, description="GitHub rate limit. See Retry-After."),
            503: OpenApiResponse(
                response=ErrorDetailSerializer,
                description="GitHub cannot name the default branch head. The quarantine stays.",
            ),
        },
    )
    @action(detail=True, methods=["post"], url_path=r"quarantine/(?P<run_type>[^/]+)/expire")
    def unquarantine(self, request: TypedRequest, pk: UUID, run_type: str, **kwargs) -> Response:
        """Expire all active quarantine entries for an identifier."""
        try:
            api.unquarantine_identifier(
                repo_id=pk,
                identifier=request.validated_data["identifier"],
                run_type=run_type,
                team_id=self.team_id,
            )
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        except api.GitHubIntegrationNotFoundError:
            return Response(
                {"detail": "No GitHub integration configured. Please install the GitHub App for this team."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        except api.GitHubRateLimitError as e:
            response = Response(
                {"detail": "GitHub API rate limit exceeded. Please retry later.", "code": "rate_limited"},
                status=status.HTTP_429_TOO_MANY_REQUESTS,
            )
            if e.retry_after:
                response["Retry-After"] = str(e.retry_after)
            return response
        except api.LiftCommitUnknownError as e:
            return Response(
                {"detail": str(e), "code": "lift_commit_unknown"}, status=status.HTTP_503_SERVICE_UNAVAILABLE
            )
        return Response(status=status.HTTP_204_NO_CONTENT)

    @extend_schema(
        responses={200: BaselineOverviewSerializer},
        description=(
            "Snapshots overview for a repo: every identifier with a current baseline (latest "
            "non-superseded master/main run per run_type), plus tolerate counts, active "
            "quarantine state, and a 30-day stability sparkline. Capped at "
            f"{contracts.BASELINE_OVERVIEW_MAX_ENTRIES} entries — sets `truncated` and "
            "returns the most recently active when exceeded. Filtering / faceting / search are "
            "all done client-side; this endpoint takes no filter query params."
        ),
    )
    @action(detail=True, methods=["get"], url_path="baselines")
    def baselines(self, request: Request, pk: UUID, **kwargs) -> Response:
        repo_id = pk
        try:
            api.get_repo(repo_id, team_id=self.team_id)
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        result = api.get_baselines_overview(repo_id)
        return Response(BaselineOverviewSerializer(instance=result).data)

    @extend_schema(
        responses={200: FlakinessOverviewSerializer},
        description=(
            "Snapshots in a repo whose rendering cannot be trusted: those that failed the gate on a "
            "recent default-branch run, those whose absorbed diff is close to the threshold, and those "
            "under an active quarantine. Small absorbed diffs well under the threshold are omitted, as is "
            "everything else, so this is far smaller than the "
            "baselines universe; `totals.tracked` gives the full denominator. Each entry carries "
            f"the share of the last {contracts.FLAKINESS_RATE_DAYS} days of default-branch runs "
            "that failed the gate (`hard_rate`) and the share a toleration absorbed "
            "(`soft_rate`), plus `headroom`, the fraction of the diff threshold its worst "
            "absorbed run leaves free. Capped at "
            f"{contracts.FLAKINESS_MAX_ENTRIES} entries, which sets `truncated`. Filtering, "
            "faceting and search are done client-side; this endpoint takes no filter query params."
        ),
    )
    @action(detail=True, methods=["get"], url_path="flakiness")
    def flakiness(self, request: Request, pk: UUID, **kwargs) -> Response:
        repo_id = pk
        try:
            api.get_repo(repo_id, team_id=self.team_id)
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        result = api.get_flakiness_overview(repo_id, self.team_id)
        return Response(FlakinessOverviewSerializer(instance=result).data)

    @extend_schema(
        description=(
            "Snapshots that keep getting tolerated, counted across baselines, most manual tolerations "
            "first. A toleration accepts one exact rendering, so a snapshot that keeps needing them "
            "renders differently from run to run, and the fix belongs in the story. With no parameters "
            f"this is the weekly debt digest's rule ({contracts.VARIANT_PILEUP_MIN} or more tolerations by a "
            f"person or agent in {contracts.TOLERATION_PILEUP_WINDOW_DAYS} days), except that quarantined "
            "snapshots are kept and marked with `is_quarantined`. The list is small and returns fast; "
            "start here to find flaky stories worth fixing, then read one snapshot's history with the "
            "per-snapshot tools."
        ),
    )
    @validated_request(
        query_serializer=TolerationPileupsQuerySerializer,
        responses={200: OpenApiResponse(response=TolerationPileupsSerializer)},
    )
    # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
    @action(detail=True, methods=["get"], url_path="toleration-pileups", pagination_class=None)
    def toleration_pileups(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
        repo_id = pk
        try:
            api.get_repo(repo_id, team_id=self.team_id)
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        query = request.validated_query_data
        result = api.get_toleration_pileups(
            repo_id,
            window_days=query["window_days"],
            min_tolerations=query["min_tolerations"],
            min_automatic_tolerations=query.get("min_automatic_tolerations"),
            include_quarantined=query["include_quarantined"],
            run_type=query.get("run_type"),
            limit=query["limit"],
        )
        return Response(TolerationPileupsSerializer(instance=result).data)


class SnapshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
    """Snapshot identities under a repo, keyed by (run_type, identifier).

    A "snapshot identity" doesn't have a single canonical row — it's a series
    of `RunSnapshot` rows over time. The retrieve-style endpoint returns the
    deduped baseline timeline for that identity, which is the most useful view.

    `identifier` is a path segment — clients must percent-encode before sending
    (`encodeURIComponent`). Django/ASGI URL-decode the kwarg automatically.
    """

    scope_object = "visual_review"
    path_parameters = {"repo_id": UUID}
    scope_object_read_actions = ["timeline"]

    @extend_schema(
        parameters=[
            OpenApiParameter("run_type", str, OpenApiParameter.PATH, description="Run type (storybook, playwright)"),
            OpenApiParameter(
                "identifier",
                str,
                OpenApiParameter.PATH,
                description="Snapshot identifier; clients must percent-encode before sending",
            ),
        ],
        responses={200: SnapshotHistoryEntrySerializer(many=True)},
    )
    @action(
        detail=False,
        methods=["get"],
        url_path=r"(?P<run_type>[^/]+)/(?P<identifier>[^/]+)",
    )
    def timeline(self, request: Request, run_type: str, identifier: str, **kwargs) -> Response:
        """Deduped baseline timeline for a snapshot identity. Newest first."""
        repo_id: UUID = self.kwargs["parent_lookup_repo_id"]
        try:
            api.get_repo(repo_id, team_id=self.team_id)
        except api.RepoNotFoundError:
            return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)
        history = api.get_snapshot_history(repo_id, identifier, run_type)
        page = self.paginate_queryset(history)
        if page is not None:
            return self.get_paginated_response(SnapshotHistoryEntrySerializer(instance=page, many=True).data)
        return Response(SnapshotHistoryEntrySerializer(instance=history, many=True).data)


class RepoRunsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
    """Listing/aggregation of runs scoped to a single repo.

    Run-by-id actions (retrieve, snapshots, approve, complete, etc.) live on
    the flat `RunViewSet` so that direct links by run id keep working without
    forcing the repo into the path.
    """

    scope_object = "visual_review"
    path_parameters = {"repo_id": UUID}

    pagination_class = FacadeLimitOffsetPagination
    scope_object_read_actions = ["list", "counts"]
    serializer_class = RunSerializer

    @extend_schema(
        parameters=[
            REVIEW_STATE_PARAMETER,
            OpenApiParameter(
                "search",
                str,
                required=False,
                description="Free-text search over branch, commit SHA, run type, and PR number",
            ),
        ],
        responses={200: RunSerializer(many=True)},
    )
    def list(self, request: Request, **kwargs) -> Response:
        """List runs in this repo, optionally filtered by review state and free-text search."""
        review_state = _parse_review_state(request)
        search = request.query_params.get("search")
        if search and len(search) > MAX_SEARCH_LENGTH:
            return Response(
                {"detail": f"search must be at most {MAX_SEARCH_LENGTH} characters"},
                status=status.HTTP_400_BAD_REQUEST,
            )
        repo_id: UUID = self.kwargs["parent_lookup_repo_id"]
        return facade_page_response(
            self,
            lambda page: api.list_runs(
                self.team_id, review_state=review_state, repo_id=repo_id, search=search, page=page
            ),
            serializer_class=RunSerializer,
        )

    @extend_schema(responses={200: ReviewStateCountsSerializer})
    @action(detail=False, methods=["get"])
    def counts(self, request: Request, **kwargs) -> Response:
        """Review state counts for runs in this repo."""
        repo_id: UUID = self.kwargs["parent_lookup_repo_id"]
        return Response(api.get_review_state_counts(self.team_id, repo_id=repo_id))


class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
    """
    Visual review runs.

    A run represents a single CI execution that captures screenshots.
    """

    scope_object = "visual_review"
    path_parameters = {
        "pk": UUID,
        "request_id": PathParameter(
            type=UUID, description="UUID of a pending lift request for this run's pull request."
        ),
    }

    pagination_class = FacadeLimitOffsetPagination
    scope_object_write_actions = [
        "create",
        "complete",
        "approve",
        "auto_approve",
        "add_snapshots",
        "recompute",
        "mark_tolerated",
        "finalize",
        "lift_on_merge",
        "cancel_quarantine_lift",
    ]
    scope_object_read_actions = [
        "list",
        "retrieve",
        "snapshots",
        "counts",
        "snapshot_history",
        "tolerated_hashes",
        "quarantine_lifts",
    ]
    serializer_class = RunSerializer

    @extend_schema(
        parameters=[
            REVIEW_STATE_PARAMETER,
            OpenApiParameter("pr_number", int, required=False, description="Filter by GitHub PR number"),
            OpenApiParameter("commit_sha", str, required=False, description="Filter by full commit SHA"),
            OpenApiParameter("branch", str, required=False, description="Filter by branch name"),
            OpenApiParameter(
                "search",
                str,
                required=False,
                description="Free-text search over branch, commit SHA, run type, and PR number",
            ),
        ],
        responses={200: RunSerializer(many=True)},
    )
    def list(self, request: Request, **kwargs) -> Response:
        """List runs for the team, optionally filtered by review state, PR number, commit SHA, branch, or free-text search."""
        pr_number_raw = request.query_params.get("pr_number")
        try:
            pr_number = int(pr_number_raw) if pr_number_raw is not None else None
        except ValueError:
            return Response({"detail": "pr_number must be an integer"}, status=status.HTTP_400_BAD_REQUEST)
        search = request.query_params.get("search")
        if search and len(search) > MAX_SEARCH_LENGTH:
            return Response(
                {"detail": f"search must be at most {MAX_SEARCH_LENGTH} characters"},
                status=status.HTTP_400_BAD_REQUEST,
            )
        review_state = _parse_review_state(request)
        return facade_page_response(
            self,
            lambda page: api.list_runs(
                self.team_id,
                review_state=review_state,
                pr_number=pr_number,
                commit_sha=request.query_params.get("commit_sha"),
                branch=request.query_params.get("branch"),
                search=search,
                page=page,
            ),
            serializer_class=RunSerializer,
        )

    @extend_schema(responses={200: ReviewStateCountsSerializer})
    @action(detail=False, methods=["get"])
    def counts(self, request: Request, **kwargs) -> Response:
        """Review state counts for the runs list."""
        return Response(api.get_review_state_counts(self.team_id))

    @validated_request(
        request_serializer=CreateRunInputSerializer,
        responses={201: OpenApiResponse(response=CreateRunResultSerializer)},
    )
    def create(self, request: TypedRequest[CreateRunInput], **kwargs) -> Response:
        """Create a new run from a CI manifest."""
        result = api.create_run(request.validated_data, team_id=self.team_id)
        return Response(CreateRunResultSerializer(instance=result).data, status=status.HTTP_201_CREATED)

    @extend_schema(responses={200: RunSerializer})
    def retrieve(self, request: Request, pk: UUID, **kwargs) -> Response:
        """Get run status and summary."""
        try:
            run = api.get_run(pk, team_id=self.team_id)
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        return Response(RunSerializer(instance=run).data)

    @validated_request(
        query_serializer=RunSnapshotsQuerySerializer,
        responses={200: SnapshotSerializer(many=True)},
    )
    @action(detail=True, methods=["get"], pagination_class=SnapshotsPagination)
    def snapshots(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
        """Get a run's snapshots with diff results, excluding quarantined ones by default."""
        query = request.validated_query_data
        paginator = cast(SnapshotsPagination, self.paginator)
        try:
            result = api.get_run_snapshots(
                pk,
                team_id=self.team_id,
                include_quarantined=query["include_quarantined"],
                exclude_unchanged=query["exclude_unchanged"],
                snapshot_id=query.get("snapshot_id"),
                quarantined_only=query["quarantined_only"],
                limit=paginator.get_limit(request),
                offset=paginator.get_offset(request),
            )
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        paginator.set_count(result.total_count)
        paginator.quarantined_count = result.quarantined_count
        page = self.paginate_queryset(result.snapshots)
        if page is not None:
            serializer = SnapshotSerializer(instance=page, many=True)
            return self.get_paginated_response(serializer.data)
        return Response(SnapshotSerializer(instance=result.snapshots, many=True).data)

    @validated_request(
        request_serializer=MarkToleratedInputSerializer,
        responses={200: OpenApiResponse(response=SnapshotSerializer)},
    )
    @action(detail=True, methods=["post"], url_path="tolerate")
    def mark_tolerated(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
        """Mark a changed snapshot as a known tolerated alternate."""
        try:
            snapshot = api.mark_snapshot_as_tolerated(
                run_id=pk,
                snapshot_id=request.validated_data["snapshot_id"],
                user_id=cast(int, request.user.id),
                team_id=self.team_id,
                actor=_actor(request),
            )
        except api.RunNotFoundError:
            return Response({"detail": "Snapshot or run not found"}, status=status.HTTP_404_NOT_FOUND)
        except ValueError:
            return Response({"detail": "Snapshot cannot be marked as tolerated"}, status=status.HTTP_400_BAD_REQUEST)
        return Response(SnapshotSerializer(instance=snapshot).data)

    @extend_schema(
        parameters=[
            _RUN_ID_PATH_PARAMETER,
            _SNAPSHOT_IDENTIFIER_PARAMETER,
        ],
        responses={200: ToleratedHashEntrySerializer(many=True)},
    )
    # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
    @action(detail=True, methods=["get"], url_path="tolerated-hashes")
    def tolerated_hashes(self, request: Request, pk: UUID, **kwargs) -> Response:
        """List known tolerated hashes for a snapshot identifier."""
        identifier = request.query_params.get("identifier")
        if not identifier:
            return Response({"detail": _MISSING_IDENTIFIER_DETAIL}, status=status.HTTP_400_BAD_REQUEST)
        try:
            scope = api.get_run_scope(pk, team_id=self.team_id)
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        entries = api.get_tolerated_hashes(scope.repo_id, identifier)
        page = self.paginate_queryset(entries)
        if page is not None:
            return self.get_paginated_response(ToleratedHashEntrySerializer(instance=page, many=True).data)
        return Response(ToleratedHashEntrySerializer(instance=entries, many=True).data)

    @extend_schema(request=AddSnapshotsInputSerializer, responses={200: AddSnapshotsResultSerializer})
    # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
    @action(detail=True, methods=["post"], url_path="add-snapshots")
    @validated_request(AddSnapshotsInputSerializer)
    def add_snapshots(self, request: TypedRequest[AddSnapshotsInput], pk: UUID, **kwargs) -> Response:
        """Add a batch of snapshots to a pending run (shard-based flow)."""
        try:
            result = api.add_snapshots(
                input=request.validated_data,
                run_id=pk,
                team_id=self.team_id,
            )
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        except ValueError:
            return Response({"detail": "Invalid request"}, status=status.HTTP_400_BAD_REQUEST)
        return Response(AddSnapshotsResultSerializer(instance=result).data)

    @extend_schema(
        parameters=[
            _RUN_ID_PATH_PARAMETER,
            _SNAPSHOT_IDENTIFIER_PARAMETER,
        ],
        responses={200: SnapshotHistoryEntrySerializer(many=True)},
    )
    # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
    @action(detail=True, methods=["get"], url_path="snapshot-history")
    def snapshot_history(self, request: Request, pk: UUID, **kwargs) -> Response:
        """Recent change history for a snapshot identifier across runs."""
        identifier = request.query_params.get("identifier")
        if not identifier:
            return Response({"detail": _MISSING_IDENTIFIER_DETAIL}, status=status.HTTP_400_BAD_REQUEST)

        try:
            scope = api.get_run_scope(pk, team_id=self.team_id)
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)

        history = api.get_snapshot_history(scope.repo_id, identifier, scope.run_type)
        page = self.paginate_queryset(history)
        if page is not None:
            return self.get_paginated_response(SnapshotHistoryEntrySerializer(instance=page, many=True).data)
        return Response(SnapshotHistoryEntrySerializer(instance=history, many=True).data)

    @validated_request(
        request_serializer=CompleteRunInputSerializer,
        responses={200: OpenApiResponse(response=RunSerializer)},
    )
    @action(detail=True, methods=["post"])
    def complete(self, request: TypedRequest, pk: UUID, **kwargs) -> Response:
        """Complete a run: detect removals, verify uploads, trigger diff processing."""
        try:
            run = api.complete_run(
                pk,
                team_id=self.team_id,
                check_run_id=request.validated_data.get("check_run_id"),
            )
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        except api.GitHubRateLimitError as e:
            response = Response(
                {"detail": "GitHub API rate limit exceeded. Please retry later.", "code": "rate_limited"},
                status=status.HTTP_429_TOO_MANY_REQUESTS,
            )
            if e.retry_after:
                response["Retry-After"] = str(e.retry_after)
            return response
        return Response(RunSerializer(instance=run).data)

    @validated_request(
        request_serializer=ApproveRunInputSerializer,
        responses={200: OpenApiResponse(response=RunSerializer)},
    )
    @action(detail=True, methods=["post"])
    def approve(self, request: TypedRequest[ApproveRunRequestInput], pk: UUID, **kwargs) -> Response:
        """Mark snapshots reviewed (DB only).

        Records the per-snapshot "Accept change" decision. Does not commit the baseline
        or change the GitHub gate — call finalize to ship the run. Works on a quarantined
        snapshot too: a quarantined snapshot approved here is committed by finalize, which
        updates a quarantined story's baseline entry without lifting the quarantine.
        """
        body = request.validated_data
        user_id = cast(int, request.user.id)

        try:
            input_dto = ApproveRunInput(run_id=pk, user_id=user_id, snapshots=body.snapshots)
            run = api.approve_snapshots(input_dto, team_id=self.team_id)
            return Response(RunSerializer(instance=run).data)
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        except api.StaleRunError as e:
            return Response({"detail": str(e), "code": "stale_run"}, status=status.HTTP_409_CONFLICT)
        except api.ArtifactNotFoundError as e:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except ValueError as e:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)

    @validated_request(
        request_serializer=FinalizeRunInputSerializer,
        responses={200: OpenApiResponse(response=FinalizeResultSerializer)},
    )
    @action(detail=True, methods=["post"])
    def finalize(self, request: TypedRequest[FinalizeRunRequestInput], pk: UUID, **kwargs) -> Response:
        """Finalize a fully-reviewed run: commit the approved baseline and green the gate.

        Commits exactly the snapshots approved in the DB (tolerated ones keep their baseline)
        and only succeeds once every changed/new snapshot is resolved. With approve_all=true,
        any still-pending changed/new snapshot is approved first; quarantined snapshots are
        skipped, but a quarantined snapshot approved by identifier is still committed.
        With commit_to_github=false the server returns the signed baseline YAML instead of
        committing it.
        """
        body = request.validated_data
        user_id = cast(int, request.user.id)

        try:
            result = api.finalize_run(
                run_id=pk,
                user_id=user_id,
                team_id=self.team_id,
                approve_all=body.approve_all,
                commit_to_github=body.commit_to_github,
                add_images_to_comment_on_pr=body.add_images_to_comment_on_pr,
            )
            return Response(FinalizeResultSerializer(instance=result).data)
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        except api.RunNotFullyResolvedError as e:
            return Response({"detail": str(e), "code": "not_fully_resolved"}, status=status.HTTP_409_CONFLICT)
        except api.StaleRunError as e:
            return Response({"detail": str(e), "code": "stale_run"}, status=status.HTTP_409_CONFLICT)
        except api.ArtifactNotFoundError as e:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except api.GitHubIntegrationNotFoundError:
            return Response(
                {"detail": "No GitHub integration configured. Please install the GitHub App for this team."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        except api.PRSHAMismatchError as e:
            return Response({"detail": str(e), "code": "sha_mismatch"}, status=status.HTTP_409_CONFLICT)
        except api.GitHubRateLimitError as e:
            response = Response(
                {"detail": "GitHub API rate limit exceeded. Please retry later.", "code": "rate_limited"},
                status=status.HTTP_429_TOO_MANY_REQUESTS,
            )
            if e.retry_after:
                response["Retry-After"] = str(e.retry_after)
            return response
        except api.GitHubCommitError:
            return Response({"detail": "GitHub commit failed"}, status=status.HTTP_502_BAD_GATEWAY)
        except ValueError as e:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)

    @extend_schema(
        request=None,
        responses={200: RecomputeResultSerializer},
        description="Re-evaluate quarantine and counts, update commit status, and optionally rerun the CI job.",
    )
    @action(detail=True, methods=["post"], url_path="recompute")
    def recompute(self, request: Request, pk: UUID, **kwargs) -> Response:
        try:
            result = api.recompute_run(pk, team_id=self.team_id)
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        except ValueError:
            return Response(
                {"detail": "Run must be completed and not yet approved"}, status=status.HTTP_400_BAD_REQUEST
            )
        return Response(RecomputeResultSerializer(instance=result).data)

    @validated_request(
        request_serializer=LiftOnMergeInputSerializer,
        responses={201: OpenApiResponse(response=QuarantineLiftEntrySerializer)},
        description=(
            "Lift a quarantined snapshot's quarantine once this run's pull request merges. The lift applies "
            "only after a default-branch run that contains the merge renders the expected picture, and the "
            "baseline entry holds that same picture. Requesting a lift never approves a picture: approve a "
            "changed or new snapshot by identifier first. Requesting again from the same pull request "
            "replaces the pending request."
        ),
    )
    @action(detail=True, methods=["post"], url_path="lift_on_merge")
    def lift_on_merge(self, request: TypedRequest[LiftOnMergeInput], pk: UUID, **kwargs) -> Response:
        try:
            entry = api.request_quarantine_lift_on_merge(
                run_id=pk,
                input=request.validated_data,
                user_id=cast(int, request.user.id),
                team_id=self.team_id,
                source=_actor(request),
            )
        except api.RunNotFoundError:
            return Response({"detail": "Snapshot or run not found"}, status=status.HTTP_404_NOT_FOUND)
        except api.StaleRunError as e:
            return Response({"detail": str(e), "code": "stale_run"}, status=status.HTTP_409_CONFLICT)
        except ValueError as e:
            return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(QuarantineLiftEntrySerializer(instance=entry).data, status=status.HTTP_201_CREATED)

    @extend_schema(
        responses={200: QuarantineLiftEntrySerializer(many=True)},
        description=(
            "Every request to lift a quarantine when this run's pull request merges, newest first, in any "
            "state. Empty for a run without a pull request."
        ),
    )
    @action(detail=True, methods=["get"], url_path="quarantine_lifts", pagination_class=None)
    def quarantine_lifts(self, request: Request, pk: UUID, **kwargs) -> Response:
        try:
            entries = api.list_quarantine_lifts_for_run(pk, team_id=self.team_id)
        except api.RunNotFoundError:
            return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
        return Response(QuarantineLiftEntrySerializer(instance=entries, many=True).data)

    @extend_schema(
        request=None,
        responses={204: None},
        description="Withdraw a pending request to lift a quarantine when this run's pull request merges.",
    )
    @action(detail=True, methods=["post"], url_path=r"quarantine_lifts/(?P<request_id>[^/]+)/cancel")
    def cancel_quarantine_lift(self, request: Request, pk: UUID, request_id: UUID, **kwargs) -> Response:
        try:
            api.cancel_quarantine_lift(
                run_id=pk,
                request_id=request_id,
                team_id=self.team_id,
            )
        except (api.RunNotFoundError, api.QuarantineLiftRequestNotFoundError):
            return Response({"detail": "Pending lift request not found"}, status=status.HTTP_404_NOT_FOUND)
        return Response(status=status.HTTP_204_NO_CONTENT)