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.

71.5 KB
Raw Blame
from typing import Any

from django.conf import settings
from django.db import models

from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers

from posthog.api.shared import UserBasicSerializer

from products.canvas.backend.facade.api import (
    CANVAS_LAYOUT_SCHEMA_VERSION,
    GRID_COLUMN_CHOICES,
    MAX_COMPONENT_HEIGHT,
    MAX_COMPONENT_WIDTH,
    MAX_LAYOUT_PATCH_OPERATIONS,
    PLACEMENT_ID_RE,
    RESERVED_TEMPLATE_IDS,
    ConnectorCallStatus,
    ConnectorKind,
    canvas_sdk_version,
    contract_limits,
)
from products.canvas.backend.facade.contracts import CanvasBuildRecord, CanvasRecord
from products.canvas.backend.facade.enums import (
    CANVAS_KIND_FREEFORM,
    CanvasKind,
    CanvasPlacementStatus,
    CanvasStateScope,
)

# Base64 expands 3 source bytes into 4 characters (padded); size the asset field
# from the contract's total-source cap rather than restating the number.
_MAX_ASSET_BASE64_LENGTH = (contract_limits()["maxSourceTotalBytes"] + 2) // 3 * 4

_CANVAS_URL_HELP_TEXT = (
    "Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — "
    "share this when pointing a user at it; never construct a canvas URL."
)


def canvas_url(canvas: CanvasRecord) -> str:
    # The same shape the thread-message announcements use; the route deep-links
    # into the desktop app and renders in the web app. This URL has no
    # `/project/<id>/` prefix because released desktop apps read it, and their
    # share link parser only matches `/code/canvas/<channel>/<canvas>`.
    return f"{settings.SITE_URL}/code/canvas/{canvas.channel_id}/{canvas.id}"


class CanvasComponentSizeSerializer(serializers.Serializer):
    """A component's grid-size contract, in grid units."""

    defaultW = serializers.IntegerField(
        min_value=1, max_value=MAX_COMPONENT_WIDTH, help_text="Width a new placement starts at, in grid columns."
    )
    defaultH = serializers.IntegerField(
        min_value=1, max_value=MAX_COMPONENT_HEIGHT, help_text="Height a new placement starts at, in grid rows."
    )
    minW = serializers.IntegerField(
        min_value=1, max_value=MAX_COMPONENT_WIDTH, help_text="Narrowest width the component renders usefully at."
    )
    minH = serializers.IntegerField(
        min_value=1, max_value=MAX_COMPONENT_HEIGHT, help_text="Shortest height the component renders usefully at."
    )
    maxW = serializers.IntegerField(
        required=False,
        min_value=1,
        max_value=MAX_COMPONENT_WIDTH,
        help_text="Widest allowed width; omit for no cap below the grid's width.",
    )
    maxH = serializers.IntegerField(
        required=False,
        min_value=1,
        max_value=MAX_COMPONENT_HEIGHT,
        help_text="Tallest allowed height; omit for no cap.",
    )


class CanvasComponentMetaSerializer(serializers.Serializer):
    """A component's placement contract: how grid canvases may place and configure it."""

    size = CanvasComponentSizeSerializer(help_text="Grid-size contract for placements of this component.")
    configSchema = serializers.DictField(
        required=False,
        help_text=(
            'JSON Schema ("type": "object") for a placement\'s config. The host validates each '
            "placement's config against it and passes the validated object to the widget at mount."
        ),
    )


class CanvasSerializer(serializers.Serializer):
    """A canvas document. Version/build content hangs off the source and build endpoints."""

    id = serializers.UUIDField(read_only=True)
    name = serializers.CharField(read_only=True)
    kind = serializers.ChoiceField(
        choices=CanvasKind.choices,
        read_only=True,
        help_text=(
            "What the canvas is: 'freeform' (a standalone app), 'component' (a reusable widget grids place), "
            "or 'grid' (a composition of components)."
        ),
    )
    description = serializers.CharField(
        read_only=True,
        help_text="Short prose describing the canvas. For components, the store-search text.",
    )
    channel = serializers.UUIDField(source="channel_id", read_only=True)
    template_id = serializers.CharField(read_only=True)
    generation_task_id = serializers.UUIDField(read_only=True, allow_null=True)
    pinned = serializers.SerializerMethodField(help_text="Whether the canvas is pinned to its channel.")
    pinned_at = serializers.DateTimeField(read_only=True, allow_null=True)
    current_version_id = serializers.UUIDField(
        source="current_source_version_id",
        read_only=True,
        allow_null=True,
        help_text="Id of the live source version — pass as expected_current_version_id on publish. Null before the first publish.",
    )
    published_build_id = serializers.UUIDField(
        read_only=True,
        allow_null=True,
        help_text="Id of the canvas's live (last successful, still-eligible) build. Null until a build completes.",
    )
    component_meta = serializers.SerializerMethodField(
        help_text=(
            "For component-kind canvases: the head version's placement contract "
            "(size, optional configSchema). Null for other kinds and unpublished components."
        ),
    )
    created_by = UserBasicSerializer(read_only=True)
    created_at = serializers.DateTimeField(read_only=True)
    updated_at = serializers.DateTimeField(read_only=True)
    url = serializers.SerializerMethodField(help_text=_CANVAS_URL_HELP_TEXT)

    def get_pinned(self, canvas: CanvasRecord) -> bool:
        return canvas.pinned_at is not None

    def get_url(self, canvas: CanvasRecord) -> str:
        return canvas_url(canvas)

    @extend_schema_field(CanvasComponentMetaSerializer(allow_null=True))
    def get_component_meta(self, canvas: CanvasRecord) -> dict | None:
        return canvas.component_meta


class CanvasCreateSerializer(serializers.Serializer):
    """Payload for creating a new, empty canvas in a channel."""

    name = serializers.CharField(
        allow_blank=False,
        trim_whitespace=True,
        max_length=400,
        help_text="Display name for the canvas.",
    )
    channel_id = serializers.UUIDField(help_text="Id of the channel the canvas belongs to.")
    kind = serializers.ChoiceField(
        choices=CanvasKind.choices,
        required=False,
        default=CANVAS_KIND_FREEFORM,
        help_text=(
            "What to create: 'freeform' (a standalone app), 'component' (a reusable widget for grids — "
            "its published project must declare a `component` placement contract), or 'grid' "
            "(a composition of components, edited through the layout endpoints)."
        ),
    )
    description = serializers.CharField(
        required=False,
        allow_blank=True,
        default="",
        trim_whitespace=True,
        help_text=(
            "Short prose describing the canvas. For components this is the store-search text agents "
            "match against — say what the widget shows and what its config controls."
        ),
    )
    template_id = serializers.CharField(
        required=False, default="freeform", max_length=64, help_text="Canvas template identifier."
    )

    def validate_template_id(self, value: str) -> str:
        if value in RESERVED_TEMPLATE_IDS:
            raise serializers.ValidationError("This template id is reserved for canvases PostHog seeds.")
        return value


class CanvasUpdateSerializer(serializers.Serializer):
    """Writable canvas fields: metadata only — source changes go through publish/edit."""

    name = serializers.CharField(
        required=False,
        allow_blank=False,
        trim_whitespace=True,
        max_length=400,
        help_text="Updated display name.",
    )
    description = serializers.CharField(
        required=False,
        allow_blank=True,
        trim_whitespace=True,
        help_text="Updated canvas description (for components, the store-search text).",
    )
    channel_id = serializers.UUIDField(required=False, help_text="Id of the space the canvas belongs to.")
    pinned = serializers.BooleanField(required=False, help_text="Whether the canvas is pinned in its channel.")
    generation_task_id = serializers.UUIDField(
        required=False, allow_null=True, help_text="Task currently generating this canvas, or null to clear it."
    )


class CanvasSourceAssetSerializer(serializers.Serializer):
    encoding = serializers.ChoiceField(choices=["base64"])
    contentType = serializers.ChoiceField(
        choices=[
            "image/png",
            "image/jpeg",
            "image/gif",
            "image/webp",
            "image/svg+xml",
            "font/woff",
            "font/woff2",
            "application/wasm",
            "application/octet-stream",
        ]
    )
    content = serializers.RegexField(
        regex=r"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$",
        max_length=_MAX_ASSET_BASE64_LENGTH,
    )


class CanvasPostHogCapabilitiesSerializer(serializers.Serializer):
    insights = serializers.ListField(child=serializers.CharField(max_length=128), max_length=100)
    inlineQueries = serializers.BooleanField()
    captureEvents = serializers.ListField(child=serializers.CharField(max_length=200), max_length=100)
    # Optional so projects published before the state store exist unchanged.
    state = serializers.ListField(
        child=serializers.ChoiceField(choices=CanvasStateScope.choices),
        required=False,
        default=list,
        max_length=2,
        help_text=(
            "State scopes the canvas may use via ph.state: 'user' (private to each viewer) "
            "and/or 'shared' (one value per canvas, team-visible)."
        ),
    )
    # Optional so projects published before the action registry exist unchanged.
    actions = serializers.ListField(
        child=serializers.CharField(max_length=64),
        required=False,
        default=list,
        max_length=32,
        help_text=(
            "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', "
            "'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."
        ),
    )
    # Optional so projects published before ph.tools exist unchanged.
    tools = serializers.ListField(
        child=serializers.CharField(max_length=200),
        required=False,
        default=list,
        max_length=32,
        help_text=(
            "PostHog MCP tools the canvas may run via ph.tools (e.g. 'feature-flag-get-definition', "
            "'feature-flag-set-release-condition-rollout'). Each runs as the viewer; declaring one shows it in the "
            "promote review."
        ),
    )
    agentRequests = serializers.BooleanField(required=False, default=False)


class CanvasNetworkCapabilitiesSerializer(serializers.Serializer):
    origins = serializers.ListField(child=serializers.URLField(max_length=2048), max_length=20)


class CanvasConnectorDeclarationSerializer(serializers.Serializer):
    """One provider a canvas may call through ph.connectors, with the tools it may use."""

    provider = serializers.CharField(
        max_length=300,
        help_text=(
            "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' "
            "(e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."
        ),
    )
    tools = serializers.ListField(
        child=serializers.CharField(max_length=200),
        min_length=1,
        max_length=64,
        help_text="Tool names the canvas may call on this provider. Read-only tools only.",
    )


class CanvasCapabilitiesSerializer(serializers.Serializer):
    posthog = CanvasPostHogCapabilitiesSerializer()
    network = CanvasNetworkCapabilitiesSerializer()
    # Optional so projects published before connectors exist unchanged.
    connectors = serializers.ListField(
        child=CanvasConnectorDeclarationSerializer(),
        required=False,
        default=list,
        max_length=20,
        help_text=(
            "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. "
            "Every call runs with the viewer's own connection; declaring one shows it in the promote review."
        ),
    )


class CanvasSourceProjectSerializer(serializers.Serializer):
    """A canvas's multi-file source project — the canonical write format for canvas source."""

    schemaVersion = serializers.IntegerField(
        help_text="Source-project schema version. Currently always 1.",
    )
    files = serializers.DictField(
        child=serializers.CharField(allow_blank=True, trim_whitespace=False),
        help_text="Project files keyed by relative path (forward slashes, no '..').",
    )
    assets = serializers.DictField(
        child=CanvasSourceAssetSerializer(),
        required=False,
        default=dict,
        help_text="Optional base64-encoded binary assets keyed by safe project-relative paths.",
    )
    entryHtml = serializers.CharField(
        help_text='The project\'s entry HTML file. Currently always "index.html".',
    )
    dependencies = serializers.DictField(
        child=serializers.CharField(),
        required=False,
        default=dict,
        help_text=("Exact-version dependencies, restricted to the platform-supported set at its pinned versions."),
    )
    canvasSdkVersion = serializers.CharField(
        required=False,
        default=canvas_sdk_version,
        help_text="Version of the host-injected `ph` canvas SDK the project targets.",
    )
    component = CanvasComponentMetaSerializer(
        required=False,
        help_text=(
            "Placement contract, required for (and only allowed on) component-kind canvases: "
            "the grid size the component takes and the JSON Schema of its per-placement config."
        ),
    )
    capabilities = CanvasCapabilitiesSerializer(
        required=False,
        default=lambda: {
            "posthog": {
                "insights": [],
                "inlineQueries": False,
                "captureEvents": [],
                "state": [],
                "actions": [],
                "tools": [],
                "agentRequests": False,
            },
            "network": {"origins": []},
            "connectors": [],
        },
        help_text=(
            "Bounded capabilities frozen into the built artifact. Declare every insight short id the "
            "canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the "
            "host enforces these at runtime and validation rejects undeclared `ph` calls. Network origins must "
            "be exact HTTPS origins. Data fetched by canvas code can be sent to those origins."
        ),
    )


class CanvasGridSerializer(serializers.Serializer):
    """The grid a grid canvas lays its placements out on."""

    columns = serializers.ChoiceField(
        choices=list(GRID_COLUMN_CHOICES), help_text="Grid width in columns. One of 4, 6, 8, 10, or 12."
    )
    rowHeight = serializers.IntegerField(min_value=24, max_value=400, help_text="Height of one grid row, in pixels.")
    gap = serializers.IntegerField(min_value=0, max_value=48, help_text="Gap between placements, in pixels.")


class CanvasPlacementSerializer(serializers.Serializer):
    """One placed widget on a grid canvas."""

    id = serializers.RegexField(
        PLACEMENT_ID_RE,
        max_length=64,
        help_text="Stable placement id, unique within the layout. 1-64 characters of letters, digits, '_', or '-'.",
    )
    status = serializers.ChoiceField(
        choices=CanvasPlacementStatus.choices,
        help_text=(
            "Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), "
            "'live' (renders its component), 'failed' (generation failed; re-prompt or remove)."
        ),
    )
    component = serializers.CharField(
        required=False,
        allow_null=True,
        help_text="Id of the component canvas this placement renders. Required once the placement is live.",
    )
    version = serializers.CharField(
        required=False,
        allow_null=True,
        help_text=(
            'Component version to render: "latest" (the default — follows the component\'s published build) '
            "or a pinned source version id."
        ),
    )
    x = serializers.IntegerField(min_value=0, help_text="Left edge, in grid columns (0-based).")
    y = serializers.IntegerField(min_value=0, help_text="Top edge, in grid rows (0-based).")
    w = serializers.IntegerField(min_value=1, help_text="Width, in grid columns.")
    h = serializers.IntegerField(min_value=1, help_text="Height, in grid rows.")
    config = serializers.DictField(
        required=False,
        allow_null=True,
        help_text="Per-placement settings, validated against the component's configSchema.",
    )
    prompt = serializers.CharField(
        required=False,
        allow_null=True,
        max_length=10_000,
        trim_whitespace=False,
        help_text="For pending/generating/failed placements: what the user asked this box to become.",
    )
    generationTaskId = serializers.CharField(
        required=False,
        allow_null=True,
        help_text="Id of the agent task currently filling this placement, when one is running.",
    )


class CanvasLayoutSerializer(serializers.Serializer):
    """A grid canvas's layout document — its entire 'source'."""

    schemaVersion = serializers.ChoiceField(
        choices=[CANVAS_LAYOUT_SCHEMA_VERSION],
        help_text=f"Layout schema version. Currently always {CANVAS_LAYOUT_SCHEMA_VERSION}.",
    )
    grid = CanvasGridSerializer(help_text="The grid placements are laid out on.")
    placements = CanvasPlacementSerializer(
        many=True,
        # drf-stubs types many=True against the child serializer and misses ListSerializer's max_length
        max_length=contract_limits()["maxGridPlacements"],  # type: ignore[call-arg]
        # drf-spectacular drops a nested list serializer's max_length, so the
        # limit only reaches generated clients and MCP tools through the text.
        help_text=(
            "The placed widgets, at most "
            f"{contract_limits()['maxGridPlacements']}. Placements may not overlap or extend past the grid."
        ),
    )


class CanvasLayoutPublishSerializer(serializers.Serializer):
    """Payload for publishing a complete layout document."""

    layout = CanvasLayoutSerializer(help_text="The complete layout document to publish.")
    prompt = serializers.CharField(
        required=False,
        allow_blank=True,
        trim_whitespace=False,
        help_text="Short description of the change, stored on the appended version history entry.",
    )
    expected_current_version_id = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=False,
        help_text=(
            "Optimistic-concurrency guard: the current_version_id the layout was based on (null when the "
            "canvas has no versions yet). A moved head is rejected with 409 version_conflict. "
            "Omit to publish unguarded."
        ),
    )


class CanvasPlacementChangesSerializer(CanvasPlacementSerializer):
    """Fields to merge into an existing placement (all optional; id cannot change)."""

    id = None  # type: ignore[assignment]

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.required = False


class CanvasLayoutOp(models.TextChoices):
    SET_GRID = "set_grid", "set_grid"
    ADD_PLACEMENT = "add_placement", "add_placement"
    UPDATE_PLACEMENT = "update_placement", "update_placement"
    REMOVE_PLACEMENT = "remove_placement", "remove_placement"


class CanvasLayoutPatchOperationSerializer(serializers.Serializer):
    """One surgical layout operation."""

    op = serializers.ChoiceField(
        choices=CanvasLayoutOp.choices,
        help_text="The operation to apply.",
    )
    grid = CanvasGridSerializer(required=False, help_text="For set_grid: the new grid definition.")
    placement = CanvasPlacementSerializer(required=False, help_text="For add_placement: the placement to add.")
    id = serializers.CharField(
        required=False, max_length=64, help_text="For update_placement/remove_placement: the target placement id."
    )
    changes = CanvasPlacementChangesSerializer(
        required=False, help_text="For update_placement: the fields to merge into the placement."
    )

    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
        op = attrs["op"]
        required_by_op = {
            "set_grid": ["grid"],
            "add_placement": ["placement"],
            "update_placement": ["id", "changes"],
            "remove_placement": ["id"],
        }
        missing = [field for field in required_by_op[op] if field not in attrs]
        if missing:
            raise serializers.ValidationError(f"{op} requires: {', '.join(missing)}")
        return attrs


class CanvasLayoutPatchSerializer(serializers.Serializer):
    """Payload for applying surgical operations to the canvas's current layout."""

    operations = CanvasLayoutPatchOperationSerializer(
        many=True,
        allow_empty=False,
        # drf-stubs types many=True against the child serializer and misses ListSerializer's max_length
        max_length=MAX_LAYOUT_PATCH_OPERATIONS,  # type: ignore[call-arg]
        help_text=(
            f"Operations applied in order to the canvas's current layout, at most {MAX_LAYOUT_PATCH_OPERATIONS}."
        ),
    )
    prompt = serializers.CharField(
        required=False,
        allow_blank=True,
        trim_whitespace=False,
        help_text="Short description of the change, stored on the appended version history entry.",
    )
    expected_current_version_id = serializers.CharField(
        allow_null=True,
        help_text=(
            "Required optimistic-concurrency guard: the current_version_id the operations are based on "
            "(null when the canvas has no layout versions yet). A moved head is rejected with 409 "
            "version_conflict — patches cannot apply unguarded."
        ),
    )


class CanvasDiagnosticSerializer(serializers.Serializer):
    """One structured validation/build diagnostic for a canvas source project."""

    severity = serializers.ChoiceField(
        choices=["error", "warning"],
        help_text="'error' blocks publishing; 'warning' is advisory and does not block.",
    )
    code = serializers.CharField(
        help_text="Stable machine-readable diagnostic code, e.g. 'import_not_allowed' or 'capability_missing_insight'.",
    )
    message = serializers.CharField(help_text="Human-readable description of the problem and how to fix it.")
    path = serializers.CharField(
        required=False,
        help_text="Project-relative path of the file the diagnostic points at, when file-specific.",
    )
    line = serializers.IntegerField(
        required=False,
        help_text="1-based line number within `path`, when the diagnostic points at a specific line.",
    )


class CanvasSummarySerializer(serializers.Serializer):
    """Identity and version pointers for one canvas."""

    id = serializers.UUIDField(help_text="The canvas's id.")
    name = serializers.CharField(help_text="Display name of the canvas.")
    kind = serializers.ChoiceField(
        choices=CanvasKind.choices, help_text="The canvas's kind (freeform, component, or grid)."
    )
    channel_id = serializers.UUIDField(help_text="Id of the channel the canvas belongs to.")
    current_version_id = serializers.CharField(
        allow_null=True,
        source="current_source_version_id",
        help_text="Id of the live source version — pass as expected_current_version_id on publish. Null before the first publish.",
    )
    published_build_id = serializers.CharField(
        allow_null=True,
        help_text="Id of the canvas's live (last successful, still-eligible) build. Null until a build completes.",
    )
    created_at = serializers.DateTimeField(help_text="When the canvas was created.")
    url = serializers.SerializerMethodField(help_text=_CANVAS_URL_HELP_TEXT)

    def get_url(self, canvas: CanvasRecord) -> str:
        return canvas_url(canvas)


class CanvasLayoutResponseSerializer(serializers.Serializer):
    """A grid canvas's layout plus the version pointer edits must be based on."""

    canvas = CanvasSummarySerializer(help_text="Identity and version pointers for the canvas.")
    layout = CanvasLayoutSerializer(
        help_text="The layout document. A grid canvas with no versions yet returns the default empty layout."
    )
    current_version_id = serializers.CharField(
        allow_null=True,
        help_text=(
            "The live layout version this document reflects — pass as expected_current_version_id when "
            "publishing or patching. Null before the first layout publish."
        ),
    )


class CanvasLayoutPublishResponseSerializer(serializers.Serializer):
    """Result of a successful layout publish or patch. The new version is live immediately — no build runs."""

    canvas = CanvasSummarySerializer(help_text="The canvas after the publish, including the new version pointer.")
    layout = CanvasLayoutSerializer(help_text="The layout document as published.")
    current_version_id = serializers.CharField(help_text="Id of the layout version this publish created.")


class CanvasVersionSerializer(serializers.Serializer):
    """One entry of a canvas's source-version history (metadata only —
    fetch a version's files via `source?version_id=`)."""

    id = serializers.UUIDField(help_text="The version's id.")
    parent_version_id = serializers.UUIDField(
        allow_null=True, help_text="The version this one was based on (null for the first publish)."
    )
    prompt = serializers.CharField(allow_null=True, help_text="Short description recorded with the publish.")
    task_id = serializers.UUIDField(allow_null=True, help_text="Task that published the version, when one did.")
    draft = serializers.BooleanField(
        help_text="True for a staged draft version that has never been the canvas head; promote it to make it live."
    )
    created_by = UserBasicSerializer(read_only=True, allow_null=True)
    created_at = serializers.DateTimeField(help_text="When the version was published.")


class CanvasDraftSerializer(serializers.Serializer):
    """A staged draft version and the status of its latest build. Preview a
    draft's files with `source?version_id=`, then make it live with `promote`."""

    version_id = serializers.CharField(help_text="Id of the draft source version.")
    prompt = serializers.CharField(allow_null=True, help_text="Short description recorded when the draft was staged.")
    created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="Who staged the draft.")
    created_at = serializers.DateTimeField(help_text="When the draft was staged.")
    build_status = serializers.ChoiceField(
        choices=["queued", "building", "ready", "failed"],
        allow_null=True,
        help_text="Status of the draft's latest build; null when no build has been recorded yet.",
    )
    build_id = serializers.CharField(allow_null=True, help_text="Id of the draft's latest build, when one exists.")


class CanvasSourceResponseSerializer(serializers.Serializer):
    """A canvas's source project plus the version pointer edits must be based on."""

    canvas = CanvasSummarySerializer(help_text="Identity and version pointers for the canvas.")
    project = CanvasSourceProjectSerializer(
        help_text="The canvas's source project. Pre-relational single-file canvases are presented as a synthetic project."
    )
    current_version_id = serializers.CharField(
        allow_null=True,
        help_text="The live source version this project reflects — pass as expected_current_version_id when publishing an edit. Null before the first publish.",
    )


class CanvasValidateRequestSerializer(serializers.Serializer):
    """Payload for validating a candidate source project without publishing it."""

    project = CanvasSourceProjectSerializer(help_text="The candidate source project to validate.")


class CanvasValidateResponseSerializer(serializers.Serializer):
    """Validation outcome for a candidate source project."""

    valid = serializers.BooleanField(help_text="True when the project has no error-severity diagnostics.")
    diagnostics = CanvasDiagnosticSerializer(
        many=True,
        help_text="Structured diagnostics; errors block publishing, warnings are advisory.",
    )


class CanvasSourcePublishSerializer(serializers.Serializer):
    """Payload for publishing a complete canvas source project."""

    project = CanvasSourceProjectSerializer(help_text="The complete source project to publish.")
    prompt = serializers.CharField(
        required=False,
        allow_blank=True,
        trim_whitespace=False,
        help_text="Short description of the change, stored on the appended version history entry.",
    )
    name = serializers.CharField(
        required=False,
        allow_blank=False,
        trim_whitespace=True,
        max_length=400,
        help_text="Optional new display name for the canvas.",
    )
    expected_current_version_id = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=False,
        help_text=(
            "Optimistic-concurrency guard: the current_version_id the publisher based its edits on "
            "(null when it read a canvas with no versions yet). When the canvas has since moved past it "
            "the publish is rejected with a 409 version_conflict instead of overwriting the newer head. "
            "Omit to publish unguarded."
        ),
    )


class CanvasSourceEditOp(models.TextChoices):
    WRITE = "write"
    DELETE = "delete"
    RENAME = "rename"
    STR_REPLACE = "str_replace"


def _inferred_edit_op(attrs: dict[str, Any]) -> CanvasSourceEditOp:
    if "old_string" in attrs or "new_string" in attrs:
        return CanvasSourceEditOp.STR_REPLACE
    if attrs.get("new_path"):
        return CanvasSourceEditOp.RENAME
    if "content" not in attrs:
        raise serializers.ValidationError({"op": "Set op, or send content (null deletes the file)."})
    return CanvasSourceEditOp.WRITE if attrs["content"] is not None else CanvasSourceEditOp.DELETE


class CanvasSourceEditOperationSerializer(serializers.Serializer):
    """One file edit: replace text in a file, write a whole file, delete it, or rename it."""

    op = serializers.ChoiceField(
        choices=CanvasSourceEditOp.choices,
        required=False,
        help_text=(
            "What to do. 'str_replace' replaces old_string with new_string inside the file: the default for "
            "changing an existing file. 'write' sets the file's complete content (new files, full rewrites). "
            "'delete' removes the file. 'rename' moves it to new_path. When omitted, it follows the fields sent: "
            "old_string or new_string means 'str_replace', new_path means 'rename', non-null content means 'write', "
            "and content null means 'delete'. An operation with none of these fields is rejected."
        ),
    )
    path = serializers.CharField(help_text='Project-relative path of the file to edit (e.g. "src/canvas.tsx").')
    content = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
        trim_whitespace=False,
        help_text="For 'write': the file's complete new content.",
    )
    old_string = serializers.CharField(
        required=False,
        trim_whitespace=False,
        help_text=(
            "For 'str_replace': the exact text to replace, copied from the file with a few surrounding lines so it "
            "matches one place only. If whitespace differs slightly, a unique line-by-line match is still accepted."
        ),
    )
    new_string = serializers.CharField(
        required=False,
        allow_blank=True,
        trim_whitespace=False,
        help_text="For 'str_replace': the text that replaces old_string. An empty string deletes old_string.",
    )
    replace_all = serializers.BooleanField(
        required=False,
        default=False,
        help_text="For 'str_replace': replace every exact match of old_string instead of requiring exactly one.",
    )
    new_path = serializers.CharField(required=False, help_text="For 'rename': the file's new project-relative path.")

    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
        op = attrs.get("op")
        if op is None:
            op = attrs["op"] = _inferred_edit_op(attrs)
        if op == CanvasSourceEditOp.WRITE and attrs.get("content") is None:
            raise serializers.ValidationError({"content": "A 'write' operation needs the file's complete content."})
        elif op == CanvasSourceEditOp.RENAME and not attrs.get("new_path"):
            raise serializers.ValidationError({"new_path": "A 'rename' operation needs new_path."})
        elif op == CanvasSourceEditOp.STR_REPLACE:
            missing = [field for field in ("old_string", "new_string") if field not in attrs]
            if missing:
                raise serializers.ValidationError(
                    dict.fromkeys(missing, "A 'str_replace' operation needs old_string and new_string.")
                )
        return attrs


class CanvasSourceEditSerializer(serializers.Serializer):
    """Payload for publishing per-file edits against the canvas's current source."""

    operations = CanvasSourceEditOperationSerializer(
        many=True,
        required=False,
        default=list,
        help_text=(
            "Edits applied in order to the canvas's current source project, all or nothing. "
            "May be empty when the edit only changes capabilities."
        ),
    )
    capabilities = CanvasCapabilitiesSerializer(
        required=False,
        help_text=(
            "The project's complete new capabilities, replacing the current ones in the same publish. "
            "Send it when the change needs a capability the canvas does not declare yet, for example a new "
            "ph.state scope, insight, capture event, or network origin. Copy the current capabilities from "
            "canvas-source-retrieve and change only what you need. Omit to keep the current capabilities."
        ),
    )
    prompt = serializers.CharField(
        required=False,
        allow_blank=True,
        trim_whitespace=False,
        help_text="Short description of the change, stored on the appended version history entry.",
    )
    name = serializers.CharField(
        required=False,
        allow_blank=False,
        trim_whitespace=True,
        max_length=400,
        help_text="Optional new display name for the canvas.",
    )
    expected_current_version_id = serializers.CharField(
        allow_null=True,
        help_text=(
            "Required optimistic-concurrency guard: the current_version_id the edits are based on (null when the "
            "canvas has never been published). Diff edits against a moved head are rejected with 409 "
            "version_conflict — they cannot be published unguarded."
        ),
    )

    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
        if not attrs["operations"] and "capabilities" not in attrs:
            raise serializers.ValidationError({"operations": "Send at least one operation or new capabilities."})
        return attrs


class CanvasPublishCurrentVersionSerializer(serializers.Serializer):
    expected_current_version_id = serializers.UUIDField(
        help_text="Current source version to publish. A changed head returns a 409 version_conflict."
    )


class CanvasPublishedBuildSerializer(serializers.Serializer):
    """The build a publish queued, as it stood when the response was sent."""

    id = serializers.CharField(help_text="The build's id.")
    build_status = serializers.ChoiceField(
        choices=["queued", "building", "ready", "failed"],
        source="status",
        help_text=(
            "'ready': the build finished. The canvas is live with this version when canvas.published_build_id "
            "equals this id; then you do not need canvas-builds-retrieve. "
            "'failed': fix the error diagnostics and save again. "
            "'queued' or 'building': poll canvas-builds-retrieve until the build is terminal."
        ),
    )
    diagnostics = CanvasDiagnosticSerializer(
        many=True, help_text="Structured diagnostics recorded by the build (errors explain a failed status)."
    )


class CanvasSourcePublishResponseSerializer(serializers.Serializer):
    """Result of a successful source-project publish."""

    canvas = CanvasSummarySerializer(help_text="The canvas after the publish, including the new version pointer.")
    current_version_id = serializers.CharField(help_text="Id of the source version this publish created.")
    diagnostics = CanvasDiagnosticSerializer(
        many=True,
        help_text="Advisory (warning-severity) diagnostics recorded for the published project.",
    )
    build = CanvasPublishedBuildSerializer(
        help_text="The queued build. The server waits a few seconds for it, so it is often already terminal."
    )


class CanvasPublishConflictSerializer(serializers.Serializer):
    """409 body for a guarded canvas publish based on a stale version."""

    detail = serializers.CharField(help_text="Human-readable description of the conflict and how to recover.")
    code = serializers.CharField(help_text='Always "version_conflict".')
    current_version_id = serializers.CharField(
        allow_null=True,
        help_text="The canvas's live current_version_id at rejection time (null when the canvas has no versions).",
    )


class CanvasSourceInvalidSerializer(serializers.Serializer):
    """400 body for a publish whose source project failed validation."""

    detail = serializers.CharField(help_text="Human-readable summary of why the project was rejected.")
    code = serializers.CharField(help_text='Always "invalid_source_project".')
    diagnostics = CanvasDiagnosticSerializer(
        many=True,
        help_text="The validation diagnostics, including at least one error.",
    )


class CanvasArtifactAssetSerializer(serializers.Serializer):
    """One emitted file of a built canvas artifact."""

    path = serializers.CharField(help_text="Artifact-relative path of the emitted file.")
    contentHash = serializers.CharField(help_text="Hex SHA-256 of the file content.")
    sizeBytes = serializers.IntegerField(help_text="Size of the file in bytes.")


class CanvasArtifactManifestSerializer(serializers.Serializer):
    """The manifest frozen into a ready build: entry, assets, versions, capabilities."""

    entryHtml = serializers.CharField(help_text="The artifact's entry HTML file.")
    assets = CanvasArtifactAssetSerializer(many=True, help_text="Every emitted artifact file with its content hash.")
    dependencies = serializers.DictField(
        child=serializers.CharField(),
        help_text="Exact dependency versions the artifact was built against.",
    )
    canvasSdkVersion = serializers.CharField(help_text="Version of the `ph` canvas SDK the artifact targets.")
    legacyComponentPath = serializers.CharField(
        required=False,
        allow_null=True,
        help_text="Path of the runtime-mounted React component, for legacy-tier artifacts.",
    )
    legacyCode = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
        trim_whitespace=False,
        help_text="The runtime-mounted component source, for legacy-tier artifacts.",
    )
    capabilities = serializers.DictField(
        help_text="Declared PostHog/network capabilities the artifact is held to at runtime.",
    )
    component = serializers.DictField(
        required=False,
        allow_null=True,
        help_text="For component artifacts: the placement contract (size, configSchema) frozen into the build.",
    )


class CanvasBuildSerializer(serializers.Serializer):
    """Lifecycle record of one build of a canvas source version."""

    id = serializers.UUIDField(help_text="The build's id.")
    source_version_id = serializers.UUIDField(help_text="The source version this build compiled.")
    build_status = serializers.ChoiceField(
        choices=["queued", "building", "ready", "failed"],
        source="status",
        help_text="Build lifecycle state. A failed build never replaces the last-known-good artifact.",
    )
    diagnostics = CanvasDiagnosticSerializer(
        many=True,
        help_text="Structured diagnostics recorded by the build (errors explain a failed status).",
    )
    manifest = CanvasArtifactManifestSerializer(
        required=False,
        allow_null=True,
        help_text="The frozen artifact manifest — present once the build is ready.",
    )
    integrity = serializers.CharField(
        allow_null=True,
        help_text="Hex SHA-256 over the manifest — the artifact's integrity anchor. Null until ready.",
    )
    artifact_url = serializers.SerializerMethodField(
        help_text="Signed URL for the ready build's entry HTML. Null until ready or when artifact delivery is unavailable.",
    )
    pinned = serializers.BooleanField(help_text="Pinned builds are retained for the lifetime of the canvas.")
    created_at = serializers.DateTimeField(help_text="When the build was queued.")
    finished_at = serializers.DateTimeField(allow_null=True, help_text="When the build reached a terminal state.")

    def get_artifact_url(self, build: CanvasBuildRecord) -> str | None:
        return build.artifact_url


class CanvasBuildsResponseSerializer(serializers.Serializer):
    """A canvas's build lifecycle: live pointers plus its most recent builds."""

    published_build_id = serializers.CharField(
        allow_null=True,
        help_text="Id of the canvas's live build (the last successful, still-eligible one). Null until a build completes.",
    )
    current_version_id = serializers.CharField(
        allow_null=True,
        help_text="Id of the source version the canvas's head points at.",
    )
    builds = CanvasBuildSerializer(
        many=True,
        help_text="Most recent builds, newest first (capped at 20; the live build is always included).",
    )


class CanvasComponentLifecycleSerializer(serializers.Serializer):
    """The renderable build of one component referenced by a grid layout, shaped
    like the builds endpoint's response so clients reuse one lifecycle reader."""

    canvas_id = serializers.CharField(help_text="Id of the component canvas.")
    requested_version_id = serializers.CharField(
        allow_null=True,
        help_text="The source version the placement pins, or null when it follows the latest.",
    )
    published_build_id = serializers.CharField(
        allow_null=True,
        help_text="Id of the component's live build. Null until a build completes.",
    )
    current_version_id = serializers.CharField(
        allow_null=True,
        help_text="Id of the source version the component's head points at.",
    )
    builds = CanvasBuildSerializer(
        many=True,
        help_text="The build the placement renders (live, or the pinned version's retained build). Empty when none is renderable.",
    )


class CanvasViewResponseSerializer(serializers.Serializer):
    """Everything a client needs to open a canvas, in one round trip.

    Replaces the record → builds → source waterfall: the record, the live
    build (with its signed artifact URL), and — only when there is nothing
    built to render — the head source project (freeform/component) or the
    layout document (grid)."""

    canvas = CanvasSerializer(help_text="The canvas record.")
    published_build = CanvasBuildSerializer(
        allow_null=True,
        help_text="The live build with its signed artifact URL. Null until a build completes.",
    )
    current_version_id = serializers.CharField(
        allow_null=True,
        help_text="Id of the source version the canvas's head points at. Null before the first publish.",
    )
    has_active_build = serializers.BooleanField(
        help_text="True while a build is queued or running — poll the builds endpoint until it settles.",
    )
    source = CanvasSourceProjectSerializer(  # type: ignore[assignment]  # field named `source` shadows DRF Field.source
        allow_null=True,
        required=False,
        help_text=(
            "The head source project, present only when the canvas has no live build to render "
            "(the client-side fallback tier). Null otherwise, and always null for grid canvases."
        ),
    )
    layout = CanvasLayoutSerializer(
        allow_null=True,
        required=False,
        help_text="For grid canvases: the head layout document. Null for other kinds.",
    )
    component_lifecycles = CanvasComponentLifecycleSerializer(
        many=True,
        required=False,
        help_text=(
            "For grid canvases: the renderable build of every component the layout's live placements "
            "reference, so the grid renders from this one call. Absent for other kinds."
        ),
    )
    sandbox_document_url = serializers.CharField(
        allow_null=True,
        read_only=True,
        help_text=(
            "URL of the sandbox document that renders the head source project in an iframe, served from "
            "the artifact origin. Load it by URL, not as srcdoc. Null when artifact delivery is unavailable."
        ),
    )


class CanvasLayoutWithComponentsResponseSerializer(CanvasLayoutResponseSerializer):
    """The layout response, plus (when requested) the renderable build of every
    component the layout places — so a grid opens on one round trip instead of
    one builds fetch per placement."""

    component_lifecycles = CanvasComponentLifecycleSerializer(
        many=True,
        required=False,
        help_text=(
            "One entry per distinct (component, pinned version) the layout's live placements reference, "
            "present only when the request passes include_components. Components the caller may not see are omitted."
        ),
    )


class CanvasBuildActionSerializer(serializers.Serializer):
    action = serializers.ChoiceField(choices=["retry", "pin", "unpin", "cancel"])
    build_id = serializers.UUIDField()


class CanvasRevertSerializer(serializers.Serializer):
    """Payload for reverting the canvas's head to an existing source version."""

    version_id = serializers.UUIDField(help_text="Id of the source version to make the head again.")
    expected_current_version_id = serializers.UUIDField(
        allow_null=True, help_text="Current source version observed before requesting the revert."
    )


class CanvasSourceDraftSerializer(serializers.Serializer):
    """Payload for staging a complete source project as a draft build."""

    project = CanvasSourceProjectSerializer(help_text="The complete source project to stage as a draft.")
    prompt = serializers.CharField(
        required=False,
        allow_blank=True,
        trim_whitespace=False,
        help_text="Short description of the change, stored on the draft's version history entry.",
    )


class CanvasCapabilityWideningSerializer(serializers.Serializer):
    """How a draft's declared capabilities grow the current head's. A head that
    predates the capabilities snapshot reports every declaration as an addition."""

    widens = serializers.BooleanField(
        help_text="True when the draft declares any capability the current head does not."
    )
    insights_added = serializers.ListField(
        child=serializers.CharField(),
        help_text="Insight short ids the draft newly declares access to.",
    )
    capture_events_added = serializers.ListField(
        child=serializers.CharField(),
        help_text="Event names the draft newly declares it may capture.",
    )
    inline_queries_enabled = serializers.BooleanField(
        help_text="True when the draft enables inline queries and the current head does not."
    )
    agent_requests_enabled = serializers.BooleanField(
        help_text="True when the draft enables requests to the canvas's authoring agent and the current head does not."
    )
    network_origins_added = serializers.ListField(
        child=serializers.CharField(),
        help_text="Network origins the draft newly declares it may reach.",
    )
    state_scopes_added = serializers.ListField(
        child=serializers.CharField(),
        help_text="State scopes (user, shared) the draft newly declares for ph.state.",
    )
    actions_added = serializers.ListField(
        child=serializers.CharField(),
        help_text="Action verbs the draft newly declares it may invoke via ph.actions.",
    )
    tools_added = serializers.ListField(
        child=serializers.CharField(),
        help_text="PostHog MCP tools the draft newly declares it may run via ph.tools.",
    )
    connectors_added = CanvasConnectorDeclarationSerializer(
        many=True,
        help_text="Connector providers and tools the draft newly declares it may call via ph.connectors.",
    )


class CanvasActionDefinitionSerializer(serializers.Serializer):
    """One registered action verb, as the host renders it before invoking."""

    verb = serializers.CharField(help_text="The verb's registry name, e.g. 'annotations.create'.")
    summary = serializers.CharField(help_text="One line naming what invoking the verb does.")
    destructive = serializers.BooleanField(
        help_text="True when the verb deletes or disables something; the host must confirm with the viewer first."
    )
    usage = serializers.CharField(
        help_text="Authoring docs for the verb: payload and result shape, behavior, and the confirmation copy it warrants."
    )


class CanvasToolDefinitionSerializer(serializers.Serializer):
    """One PostHog MCP tool a canvas may declare, as the host renders it before running it."""

    name = serializers.CharField(help_text="MCP tool name, e.g. 'feature-flag-enable'.")
    title = serializers.CharField(help_text="Human-readable tool title.")
    summary = serializers.CharField(help_text="One line naming what the tool does.")
    # The name shadows Field.read_only for mypy only: DRF moves declared fields off the class.
    read_only = serializers.BooleanField(  # type: ignore[assignment]
        help_text="True when the tool only reads. A canvas runs read-only tools with ph.tools.read, others with "
        "ph.tools.call."
    )
    destructive = serializers.BooleanField(
        help_text="True when the tool deletes or overwrites something; the host warns the viewer before it runs."
    )


class CanvasActionsResponseSerializer(serializers.Serializer):
    """The action registry: every verb and PostHog MCP tool a canvas may declare and invoke."""

    actions = CanvasActionDefinitionSerializer(many=True, help_text="Registered verbs, sorted by name.")
    tools = CanvasToolDefinitionSerializer(
        many=True,
        help_text="PostHog MCP tools a canvas may declare in capabilities.posthog.tools, sorted by name. Read each "
        "tool's input schema with the MCP `info` command.",
    )


class CanvasActionInvokeSerializer(serializers.Serializer):
    """Payload for invoking one action verb."""

    # Untrimmed, so the scope check and the dispatch read the same verb.
    verb = serializers.CharField(
        max_length=64, trim_whitespace=False, help_text="Registered verb to invoke, e.g. 'tasks.create'."
    )
    payload = serializers.DictField(
        required=False,
        default=dict,
        help_text="Verb-specific arguments, validated against the verb's payload schema.",
    )


class CanvasActionResultSerializer(serializers.Serializer):
    """Result of one action invocation."""

    verb = serializers.CharField(help_text="The verb that executed.")
    result = serializers.DictField(
        help_text="Verb-specific result, e.g. {'task_id': ...} for tasks.create.",
    )


class CanvasToolInvokeSerializer(serializers.Serializer):
    """Payload for running one PostHog MCP tool."""

    # Untrimmed, so the scope check and the dispatch read the same name.
    tool = serializers.CharField(
        max_length=200, trim_whitespace=False, help_text="MCP tool to run, e.g. 'feature-flag-enable'."
    )
    arguments = serializers.DictField(
        required=False,
        default=dict,
        help_text="The tool's input, exactly as an MCP client passes it.",
    )


class CanvasToolResultSerializer(serializers.Serializer):
    """Result of one PostHog MCP tool run."""

    tool = serializers.CharField(help_text="The tool that ran.")
    result = serializers.DictField(help_text="The tool's JSON result.")


class CanvasConnectorToolSerializer(serializers.Serializer):
    """One tool a connector provider exposes to canvases."""

    name = serializers.CharField(help_text="Tool name, as passed to ph.connectors.call.")
    summary = serializers.CharField(help_text="One line naming what the tool reads.")
    is_read_only = serializers.BooleanField(
        source="read_only", help_text="True when the tool only reads. Canvases may call read-only tools."
    )
    input_schema = serializers.DictField(help_text="JSON Schema of the tool's arguments object.")
    usage = serializers.CharField(help_text="Authoring docs: argument and result shape, limits, and behavior.")


class CanvasConnectorSerializer(serializers.Serializer):
    """One connector provider, with the caller's connection state and the tools it exposes."""

    provider = serializers.CharField(
        help_text="Provider id to declare and call, e.g. 'github' or 'mcp:mcp.calendly.com'."
    )
    display_name = serializers.CharField(source="label", help_text="Display name of the provider.")
    kind = serializers.ChoiceField(
        choices=ConnectorKind.choices,
        help_text="'native' runs through a PostHog personal integration; 'mcp' through an MCP store installation.",
    )
    connected = serializers.BooleanField(
        allow_null=True,
        help_text="True when the caller has a usable connection. Null in the static catalog returned to sandbox authors.",
    )
    connect_path = serializers.CharField(help_text="In-app path where the caller connects this provider.")
    tools = CanvasConnectorToolSerializer(many=True, help_text="Tools the caller's connection exposes, sorted by name.")


class CanvasConnectorsResponseSerializer(serializers.Serializer):
    """The connector catalog: every provider a canvas may declare and call."""

    connectors = CanvasConnectorSerializer(many=True, help_text="Native providers first, then the requested MCP hosts.")


class CanvasConnectorCallSerializer(serializers.Serializer):
    """Payload for calling one connector tool as the viewer."""

    approval_token = serializers.CharField(
        required=False,
        default=None,
        max_length=200,
        help_text="Single-use token from a needs_approval response. Submit only after the viewer approves this exact call. Expires after 15 minutes.",
    )
    provider = serializers.CharField(max_length=300, help_text="Declared provider id, e.g. 'github'.")
    tool = serializers.CharField(max_length=200, help_text="Declared tool name, e.g. 'list_pull_requests'.")
    arguments = serializers.DictField(
        required=False,
        default=dict,
        help_text="Tool arguments, validated against the tool's input schema.",
    )


class CanvasConnectorCallResultSerializer(serializers.Serializer):
    """Result of one connector call. `status` is 'ok' when `result` holds the tool's output."""

    approval_token = serializers.CharField(
        allow_null=True,
        help_text="Host-only, single-use approval token bound to this viewer, connection, canvas version, tool, and arguments. Never forward it to the canvas iframe.",
    )

    status = serializers.ChoiceField(
        choices=ConnectorCallStatus.choices,
        help_text=(
            "'ok' carries a result. 'not_connected' and 'needs_reauth' mean the viewer must connect the provider "
            "at connect_path. 'blocked' is team policy. 'write_blocked' is a tool that may write. "
            "'needs_approval' requires the viewer to approve this call in the host. "
            "'upstream_error' is a failure at the provider."
        ),
    )
    result = serializers.DictField(
        allow_null=True,
        help_text="Tool output. Native tools return their documented shape; MCP tools return {content, structured_content, is_error}.",
    )
    detail = serializers.CharField(allow_blank=True, help_text="Human-readable explanation for a non-ok status.")
    truncated = serializers.BooleanField(
        help_text="True when the result exceeded the size cap and was cut to a preview."
    )
    connect_path = serializers.CharField(
        allow_null=True, help_text="In-app path where the viewer can connect the provider, when that would help."
    )


class CanvasStateQuerySerializer(serializers.Serializer):
    scope = serializers.ChoiceField(choices=CanvasStateScope.choices, required=False, help_text="Only read this scope.")
    key = serializers.CharField(required=False, max_length=200, help_text="Only read this exact key.")
    key_prefix = serializers.CharField(
        required=False,
        max_length=200,
        allow_blank=True,
        trim_whitespace=False,
        help_text="Only read entries whose key starts with this prefix.",
    )
    keys_only = serializers.BooleanField(
        required=False, default=False, help_text="True returns a key inventory without stored values."
    )
    offset = serializers.IntegerField(
        required=False,
        default=0,
        min_value=0,
        help_text=(
            "Entry offset from next_offset. Keep filters unchanged between pages. Prefer cursor: an offset can skip "
            "or repeat entries when state changes between pages."
        ),
    )
    cursor = serializers.CharField(
        required=False,
        max_length=2048,
        help_text=(
            "Cursor from next_cursor. Resumes after the last entry of the previous page, so an entry that exists "
            "for the whole read comes back exactly once. A key written between pages can be missing. Keep filters "
            "unchanged between pages. Takes precedence over offset."
        ),
    )
    limit = serializers.IntegerField(
        required=False,
        min_value=1,
        max_value=100,
        help_text="Maximum entries per page. Omit for the full state. Prefer an inventory and state/value for large values.",
    )


class CanvasStateValueQuerySerializer(serializers.Serializer):
    scope = serializers.ChoiceField(choices=CanvasStateScope.choices, help_text="Scope of the value to read.")
    key = serializers.CharField(max_length=200, help_text="Exact key to read.")
    offset = serializers.IntegerField(
        required=False, default=0, min_value=0, help_text="Character offset from next_offset."
    )
    limit = serializers.IntegerField(
        required=False,
        default=12000,
        min_value=1,
        max_value=12000,
        help_text="Maximum JSON characters in this response.",
    )
    revision = serializers.CharField(
        required=False,
        max_length=64,
        help_text="Revision from the first chunk. Required when offset is greater than zero.",
    )

    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
        if attrs["offset"] and not attrs.get("revision"):
            raise serializers.ValidationError({"revision": "Read the first chunk and pass its revision to continue."})
        return attrs


class CanvasStateValueResponseSerializer(serializers.Serializer):
    scope = serializers.ChoiceField(choices=CanvasStateScope.choices, help_text="Scope of this value.")
    key = serializers.CharField(help_text="Key of this value.")
    value_json = serializers.CharField(
        allow_blank=True, help_text="A chunk of JSON text. Join all chunks in order, then parse the complete JSON."
    )
    revision = serializers.CharField(
        help_text="Content revision. Pass it on subsequent reads; a changed value returns 409."
    )
    offset = serializers.IntegerField(help_text="Character offset of this chunk.")
    total_length = serializers.IntegerField(help_text="Character length of the complete JSON text.")
    next_offset = serializers.IntegerField(allow_null=True, help_text="Next character offset, or null when complete.")
    complete = serializers.BooleanField(
        help_text="True when no further chunks remain. Earlier chunks are still needed when offset is nonzero."
    )


class CanvasStateEntrySerializer(serializers.Serializer):
    """One key of a canvas's runtime key-value state (the ph.state store)."""

    scope = serializers.ChoiceField(
        choices=CanvasStateScope.choices,
        help_text="user: private to the viewer who wrote it. shared: one value per canvas, visible to every viewer.",
    )
    key = serializers.CharField(max_length=200, help_text="The entry's key, unique within its scope.")
    value = serializers.JSONField(required=False, help_text="The stored JSON value. Omitted from a key inventory.")
    updated_at = serializers.DateTimeField(help_text="When the entry was last written.")


class CanvasStateResponseSerializer(serializers.Serializer):
    """The canvas state readable by the caller."""

    entries = CanvasStateEntrySerializer(
        many=True,
        help_text="The canvas's shared entries plus the caller's own user-scoped entries.",
    )
    count = serializers.IntegerField(help_text="Number of entries in the whole selection, across all pages.")
    next = serializers.URLField(
        allow_null=True,
        help_text=(
            "URL of the next page, or null when complete. It pages the same way as this request: by cursor "
            "when the request used a cursor, otherwise by offset."
        ),
    )
    previous = serializers.URLField(
        allow_null=True,
        help_text="URL of the previous page by offset, or null on the first page and for a cursor request.",
    )
    next_offset = serializers.IntegerField(
        allow_null=True,
        help_text="Next entry offset, or null when complete. Null when the request used a cursor.",
    )
    next_cursor = serializers.CharField(
        allow_null=True,
        help_text="Cursor for the next page, or null when complete. Pass it as cursor.",
    )
    complete = serializers.BooleanField(help_text="True when no further entries remain for this selection.")


class CanvasStateSetSerializer(serializers.Serializer):
    """Payload for writing (or deleting) one key of a canvas's runtime state."""

    scope = serializers.ChoiceField(
        choices=CanvasStateScope.choices,
        help_text="Scope to write into; the canvas must declare it in capabilities.posthog.state.",
    )
    key = serializers.CharField(max_length=200, help_text="Key to write, unique within its scope.")
    value = serializers.JSONField(
        allow_null=True,
        help_text="JSON value to store (at most 64 KB serialized), or null to delete the key.",
    )


class CanvasSourceDraftResponseSerializer(serializers.Serializer):
    """Result of staging a draft build."""

    version_id = serializers.CharField(help_text="Id of the draft source version this request created.")
    build = CanvasBuildSerializer(help_text="The queued draft build; poll `builds` until it is terminal.")
    diagnostics = CanvasDiagnosticSerializer(
        many=True,
        help_text="Advisory (warning-severity) diagnostics recorded for the drafted project.",
    )
    capability_widening = CanvasCapabilityWideningSerializer(
        help_text="What the draft's declared capabilities grant beyond the current head's. Review before promoting."
    )


class CanvasPromoteSerializer(serializers.Serializer):
    """Payload for promoting a draft version to the canvas's live head."""

    version_id = serializers.UUIDField(help_text="Id of the draft source version to make live.")
    expected_current_version_id = serializers.UUIDField(
        allow_null=True,
        help_text=(
            "Current source version observed before requesting the promote (null when the canvas has never "
            "been published). A moved head is rejected with 409 version_conflict."
        ),
    )


class CanvasReportErrorSerializer(serializers.Serializer):
    """Payload for reporting a runtime error observed while rendering a canvas build."""

    build_id = serializers.UUIDField(help_text="Id of the build that was rendering when the error occurred.")
    error_type = serializers.CharField(
        max_length=64,
        help_text=(
            "Error class name only, for example TypeError. Values that are not a plain class-name identifier "
            "are recorded as 'unknown'. Full error messages and stack traces must stay client-side."
        ),
    )


class CanvasErrorReportResultSerializer(serializers.Serializer):
    """Outcome of filing a canvas error report."""

    report_outcome = serializers.ChoiceField(
        choices=["filed", "duplicate", "no_authoring_task", "skipped"],
        help_text=(
            "filed: a new report row was written. duplicate: this build and error type were already reported. "
            "no_authoring_task: the canvas has no linked task to notify. skipped: thread updates are unavailable."
        ),
    )


class CanvasRequestFixSerializer(serializers.Serializer):
    """Payload for asking the canvas's authoring agent to fix a failing build or runtime error."""

    build_id = serializers.UUIDField(help_text="Id of the failing or erroring build the fix should address.")
    error_type = serializers.CharField(
        required=False,
        max_length=64,
        help_text=(
            "Error class from the runtime report, when fixing a runtime error. Omit for a failed build; its "
            "diagnostics are read server-side."
        ),
    )


class CanvasFixRequestResultSerializer(serializers.Serializer):
    """Outcome of dispatching a canvas fix to the authoring agent."""

    dispatch_outcome = serializers.ChoiceField(
        choices=["signaled", "new_run", "already_queued"],
        help_text=(
            "signaled: the task's live run received the request. new_run: a fresh agent run was started. "
            "already_queued: a fix run was already starting, so no new run was created."
        ),
    )
    task_id = serializers.UUIDField(help_text="The authoring task the fix was routed to.")


class CanvasAgentRequestSerializer(serializers.Serializer):
    """A viewer-approved request for the canvas's authoring agent."""

    prompt = serializers.CharField(
        max_length=10_000,
        trim_whitespace=False,
        help_text="Exact change request the viewer reviewed and approved in the trusted host dialog.",
    )


class CanvasAgentRequestResultSerializer(serializers.Serializer):
    """Outcome of routing a canvas change request."""

    request_outcome = serializers.ChoiceField(
        choices=["signaled", "new_run", "already_queued", "reported"],
        help_text=(
            "signaled: the live run received the request. new_run: a fresh run started. "
            "already_queued: an identical run was already starting. reported: a non-creator's request was filed "
            "in the task thread for the creator."
        ),
    )
    task_id = serializers.UUIDField(help_text="Authoring task that received the request or report.")


class CanvasCommentsQuerySerializer(serializers.Serializer):
    include_resolved = serializers.BooleanField(
        required=False,
        default=False,
        help_text="Whether to include resolved comment threads.",
    )
    limit = serializers.IntegerField(
        required=False,
        default=50,
        min_value=1,
        max_value=100,
        help_text="Maximum number of root comments to return.",
    )
    cursor = serializers.CharField(
        required=False, max_length=256, help_text="Opaque cursor returned by the previous page."
    )


class CanvasCommentDetailQuerySerializer(serializers.Serializer):
    limit = serializers.IntegerField(
        required=False,
        default=50,
        min_value=1,
        max_value=100,
        help_text="Maximum number of comments in the thread to return.",
    )
    cursor = serializers.CharField(
        required=False, max_length=256, help_text="Opaque cursor returned by the previous page."
    )
    comment_id = serializers.UUIDField(
        required=False,
        help_text="Comment id whose truncated body should continue. Use with content_offset.",
    )
    content_offset = serializers.IntegerField(
        required=False,
        default=0,
        min_value=0,
        help_text="Byte offset returned as content_next_offset for the selected comment.",
    )

    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
        if attrs.get("content_offset") and not attrs.get("comment_id"):
            raise serializers.ValidationError({"comment_id": "This field is required with content_offset."})
        if attrs.get("comment_id") and attrs.get("cursor"):
            raise serializers.ValidationError({"cursor": "Do not combine cursor with comment_id."})
        return attrs


class CanvasCommentSummarySerializer(serializers.Serializer):
    id = serializers.UUIDField(help_text="Root comment id.")
    content = serializers.CharField(help_text="Bounded excerpt of the root comment body.")
    content_truncated = serializers.BooleanField(help_text="Whether the root comment body has more content.")
    selected_text = serializers.CharField(allow_null=True, help_text="Text selected when the comment was created.")
    created_at = serializers.DateTimeField(help_text="When the root comment was created.")
    reply_count = serializers.IntegerField(help_text="Number of human replies.")
    resolved = serializers.BooleanField(help_text="Whether the comment thread is resolved.")


class CanvasCommentsResponseSerializer(serializers.Serializer):
    comments = CanvasCommentSummarySerializer(many=True, help_text="Root comments on the canvas, newest first.")
    next = serializers.CharField(allow_null=True, help_text="Opaque cursor for the next page, or null.")


class CanvasCommentAnchorSerializer(serializers.Serializer):
    kind = serializers.CharField(required=False, help_text="Anchor kind: text or region.")
    quote = serializers.CharField(required=False, help_text="Selected text.")
    prefix = serializers.CharField(required=False, help_text="Text immediately before the selection.")
    suffix = serializers.CharField(required=False, help_text="Text immediately after the selection.")
    start = serializers.IntegerField(required=False, min_value=0, help_text="Selection start offset.")
    end = serializers.IntegerField(required=False, min_value=1, help_text="Selection end offset.")
    x = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Horizontal region position.")
    y = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Vertical region position.")
    width = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Region width.")
    height = serializers.FloatField(required=False, min_value=0, max_value=1, help_text="Region height.")


class CanvasCommentEntrySerializer(serializers.Serializer):
    id = serializers.UUIDField(help_text="Comment id.")
    content = serializers.CharField(help_text="Byte-bounded comment body chunk.")
    content_truncated = serializers.BooleanField(help_text="Whether this comment body has more content.")
    content_next_offset = serializers.IntegerField(
        allow_null=True,
        help_text="Byte offset for the next body chunk, or null when complete.",
    )
    author = serializers.CharField(allow_null=True, help_text="Display name of the comment author.")
    created_at = serializers.DateTimeField(help_text="When the comment was created.")
    anchor = CanvasCommentAnchorSerializer(allow_null=True, help_text="Normalized text or region anchor.")
    canvas_version_id = serializers.CharField(
        allow_null=True, help_text="Canvas version that was live when the comment was written."
    )


class CanvasCommentDetailSerializer(serializers.Serializer):
    id = serializers.UUIDField(help_text="Root comment id.")
    resolved = serializers.BooleanField(help_text="Whether the comment thread is resolved.")
    comments = CanvasCommentEntrySerializer(many=True, help_text="Comments in this page, oldest first.")
    next = serializers.CharField(allow_null=True, help_text="Opaque cursor for the next page, or null.")