:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devex): add next and previous links to custom list responses (#126472)
Julian Bez57569aaa4a35
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex ac00d414a4dc..0ddb70da4c71 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -6402,7 +6402,20 @@ export interface UserCodexConnectRequestApi {tokens: UserCodexAuthTokensApi}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubBranchesResponseApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** List of branch names */branches: string[]/**@@ -6435,7 +6448,20 @@ export interface GitHubRepoApi {can_push?: boolean}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubReposResponseApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | nullrepositories: GitHubRepoApi[]/** Whether more repositories are available beyond this page. */has_more: booleandiff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex f8f02114ee39..c4bcd89c32e8 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -11,7 +11,7 @@ from django.utils import timezoneimport structlogimport posthoganalyticsfrom drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field-from rest_framework import exceptions, pagination, serializers, status, viewsets+from rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.exceptions import ErrorDetailfrom rest_framework.generics import get_object_or_404from rest_framework.request import Request@@ -19,6 +19,7 @@ from rest_framework.response import Responsefrom slack_sdk.errors import SlackApiErrorfrom posthog.api.forbid_destroy_model import ForbidDestroyModel+from posthog.api.pagination import StableCursorPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action@@ -648,13 +649,32 @@ class CommentErrorSerializer(serializers.Serializer):error_type = serializers.CharField(required=False, help_text="Stable machine-readable identifier for the failure.")-class CommentPagination(pagination.CursorPagination):+class CommentPagination(StableCursorPagination):# `created_at` is not unique, and DRF encodes only the first ordering field in the cursor,# resolving ties with an offset. That offset is reproducible only when rows sharing a# timestamp come back in a stable order, which Postgres does not otherwise guarantee.ordering = ("-created_at", "-id")page_size = 100+ def paginate_queryset(self, queryset: Any, request: Request, view: Any = None) -> list[Any] | None:+ self.is_first_page = self.cursor_query_param not in request.query_params+ return super().paginate_queryset(queryset, request, view)++ def get_paginated_response(self, data: Any) -> Response:+ # A short first page holds every row, so the total needs no query over the whole set.+ if self.is_first_page and len(data) < self.page_size:+ count = len(data)+ else:+ count = self.counted_rows.count()+ return Response(+ {+ "count": count,+ "next": self.get_next_link(),+ "previous": self.get_previous_link(),+ "results": data,+ }+ )+class CommentListQueryParamsSerializer(serializers.Serializer):scope = serializers.CharField(diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex a84e8a925b9c..fe8a1f95c6ed 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -60,6 +60,7 @@ from posthog.api.integration_push_tokens import (push_channel_app_id,)from posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.pagination import PageLinksSerializer, offset_page_linksfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import ErrorResponseSerializer, action@@ -425,7 +426,7 @@ class GitHubReposQuerySerializer(serializers.Serializer):)-class GitHubReposResponseSerializer(serializers.Serializer):+class GitHubReposResponseSerializer(PageLinksSerializer):repositories = GitHubRepoSerializer(many=True)has_more = serializers.BooleanField(help_text="Whether more repositories are available beyond this page.")next_offset = serializers.IntegerField(@@ -437,7 +438,16 @@ class GitHubReposResponseSerializer(serializers.Serializer):)-def github_repos_page(github: GitHubIntegrationBase, query: dict[str, Any]) -> dict[str, Any]:+def external_page_links(request: Request, *, offset: int, limit: int, next_offset: int | None) -> dict[str, str | None]:+ """Build the `next` and `previous` links of one offset page of a list read from an external API.++ The links drop `force_refresh`, so a followed link reads the list that the first page cached+ and does not call the external API again.+ """+ return offset_page_links(request, offset=offset, limit=limit, next_offset=next_offset, drop="force_refresh")+++def github_repos_page(request: Request, github: GitHubIntegrationBase, query: dict[str, Any]) -> dict[str, Any]:"""Build one `GitHubReposResponseSerializer` page from validated `GitHubReposQuerySerializer` data."""search, limit, offset = query["search"], query["limit"], query["offset"]repositories, has_more = github.list_cached_repositories(search=search, limit=limit, offset=offset)@@ -446,11 +456,13 @@ def github_repos_page(github: GitHubIntegrationBase, query: dict[str, Any]) -> drepositories = [{"id": repo["id"], "name": repo["name"], "full_name": repo["full_name"]} for repo in repositories]+ next_offset = offset + len(repositories) if has_more else Nonereturn {"repositories": repositories,"has_more": has_more,- "next_offset": offset + len(repositories) if has_more else None,+ "next_offset": next_offset,"total": total,+ **external_page_links(request, offset=offset, limit=limit, next_offset=next_offset),}@@ -570,7 +582,7 @@ class GitHubTeamsQuerySerializer(serializers.Serializer):)-class GitHubTeamsResponseSerializer(serializers.Serializer):+class GitHubTeamsResponseSerializer(PageLinksSerializer):teams = GitHubTeamSerializer(many=True, help_text="List of GitHub teams available to the installation organization.")@@ -591,7 +603,7 @@ class GitHubBranchesQuerySerializer(serializers.Serializer):offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Number of branches to skip")-class GitHubBranchesResponseSerializer(serializers.Serializer):+class GitHubBranchesResponseSerializer(PageLinksSerializer):branches = serializers.ListField(child=serializers.CharField(), help_text="List of branch names")default_branch = serializers.CharField(help_text="The default branch of the repository", required=False, allow_null=True@@ -654,7 +666,7 @@ class SlackChannelsQuerySerializer(serializers.Serializer):)-class SlackChannelsResponseSerializer(serializers.Serializer):+class SlackChannelsResponseSerializer(PageLinksSerializer):channels = SlackChannelSerializer(many=True, help_text="Slack channels visible to the PostHog Slack app.")lastRefreshedAt = serializers.CharField(required=False,@@ -738,7 +750,7 @@ class SlackUsersQuerySerializer(serializers.Serializer):)-class SlackUsersResponseSerializer(serializers.Serializer):+class SlackUsersResponseSerializer(PageLinksSerializer):users = SlackUserSerializer(many=True, help_text="Human Slack workspace members the PostHog Slack app can DM.")lastRefreshedAt = serializers.CharField(required=False,@@ -1925,7 +1937,7 @@ class IntegrationViewSet(if data is not None:for channel in data["channels"]:if channel["id"] == channel_id:- return Response({"channels": [channel]})+ return Response({"channels": [channel], "next": None, "previous": None})# Past the cached list every lookup reaches Slack, and a forced one skips the list# altogether, so the same per-minute budget the member lookup uses applies here._take_slack_lookup_budget(@@ -1940,11 +1952,11 @@ class IntegrationViewSet(if channel:serialized_channel = self._serialize_slack_channel(channel)self._cache_slack_channel(key, serialized_channel)- return Response({"channels": [serialized_channel]})+ return Response({"channels": [serialized_channel], "next": None, "previous": None})# Only a forced lookup reaches Slack for a channel the cached list still holds, so this# drops a channel the workspace no longer offers rather than leaving it pickable.self._drop_cached_slack_channel(key, channel_id)- return Response({"channels": []})+ return Response({"channels": [], "next": None, "previous": None})search = query_serializer.validated_data["search"]limit = query_serializer.validated_data["limit"]@@ -1972,6 +1984,9 @@ class IntegrationViewSet("channels": page,"lastRefreshedAt": data.get("lastRefreshedAt"),"has_more": has_more,+ **external_page_links(+ request, offset=offset, limit=limit, next_offset=offset + limit if has_more else None+ ),})@@ -2025,13 +2040,13 @@ class IntegrationViewSet(if data is not None:for member in data["users"]:if member["id"] == user_id:- return Response({"users": [member]})+ return Response({"users": [member], "next": None, "previous": None})# Cache hits AND misses per id, so a loop over arbitrary ids can't spend the# workspace's Slack API quota one uncached users.info call at a time.lookup_key = f"slack/{instance.id}/users/{user_id}"cached_lookup = cache.get(lookup_key)if cached_lookup is not None:- return Response({"users": cached_lookup})+ return Response({"users": cached_lookup, "next": None, "previous": None})# The per-id cache doesn't bound a caller cycling through distinct fabricated ids, so# also cap how many uncached lookups an integration can send to Slack per minute._take_slack_lookup_budget(@@ -2045,7 +2060,7 @@ class IntegrationViewSet(_reraise_slack_users_api_error(e)serialized_lookup = [self._serialize_slack_user(member)] if member else []cache.set(lookup_key, serialized_lookup, 60 * 60)- return Response({"users": serialized_lookup})+ return Response({"users": serialized_lookup, "next": None, "previous": None})search = query_serializer.validated_data["search"]limit = query_serializer.validated_data["limit"]@@ -2108,6 +2123,9 @@ class IntegrationViewSet("users": page,"lastRefreshedAt": data.get("lastRefreshedAt"),"has_more": has_more,+ **external_page_links(+ request, offset=offset, limit=limit, next_offset=offset + limit if has_more else None+ ),})@@ -2429,6 +2447,7 @@ class IntegrationViewSet(raise ValidationError("github_repos endpoint is only supported for GitHub integrations")return Response(github_repos_page(+ request,GitHubIntegration(instance, source="integrations_api", priority=Priority.CRITICAL),query_serializer.validated_data,)@@ -2686,7 +2705,14 @@ class IntegrationViewSet("Unable to fetch GitHub teams. Please check integration settings and try again.") from err- return Response({"teams": teams, "has_more": has_more})+ next_offset = offset + limit if has_more else None+ return Response(+ {+ "teams": teams,+ "has_more": has_more,+ **external_page_links(request, offset=offset, limit=limit, next_offset=next_offset),+ }+ )@extend_schema(parameters=[GitHubBranchesQuerySerializer],@@ -2715,7 +2741,15 @@ class IntegrationViewSet(offset=offset,)- return Response({"branches": branches, "default_branch": default_branch, "has_more": has_more})+ next_offset = offset + limit if has_more else None+ return Response(+ {+ "branches": branches,+ "default_branch": default_branch,+ "has_more": has_more,+ **external_page_links(request, offset=offset, limit=limit, next_offset=next_offset),+ }+ )@extend_schema(responses={200: JiraProjectsResponseSerializer})@action(methods=["GET"], detail=True, url_path="jira_projects")diff --git a/posthog/api/pagination.py b/posthog/api/pagination.pyindex 2245b351138b..54ac69a86598 100644--- a/posthog/api/pagination.py+++ b/posthog/api/pagination.py@@ -3,11 +3,12 @@ from typing import TYPE_CHECKING, Any, Optional, castfrom django.core.exceptions import ImproperlyConfigured+from rest_framework import serializersfrom rest_framework.pagination import CursorPagination, LimitOffsetPaginationfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer-from rest_framework.utils.urls import replace_query_param+from rest_framework.utils.urls import remove_query_param, replace_query_paramfrom posthog.paging import CursorBound, CursorPageRequest, Page, PageRequest@@ -16,6 +17,71 @@ if TYPE_CHECKING:from rest_framework.generics import GenericAPIView+def page_link(request: Request, param: str, value: str | int | None) -> str | None:+ """Return the request URL with `param` set to `value`, or None when there is no such page.++ Lists that page with their own parameter (`cursor`, `offset`, ...) use this to build the same+ absolute `next` and `previous` links as DRF's paginators.+ """+ if value is None:+ return None+ return replace_query_param(request.build_absolute_uri(), param, value)+++def page_link_with_params(request: Request, params: dict[str, str | int] | None) -> str | None:+ """Return the request URL with every query param in `params` set, or None when there is no such page.++ Use this for lists whose page position takes more than one param, such as a timestamp and an id.+ """+ if params is None:+ return None+ url = request.build_absolute_uri()+ for param, value in params.items():+ url = replace_query_param(url, param, value)+ return url+++def previous_offset(offset: int, limit: int) -> int | None:+ """Return the offset of the page before the page at `offset`, or None on the first page."""+ if offset <= 0:+ return None+ return max(offset - limit, 0)+++def offset_page_links(+ request: Request, *, offset: int, limit: int, next_offset: int | None, drop: str | None = None+) -> dict[str, str | None]:+ """Return the `next` and `previous` links of one page of a list that pages with an `offset` param.++ `drop` names a query param that the links leave out.+ """+ url = request.build_absolute_uri()+ if drop is not None:+ url = remove_query_param(url, drop)+ previous = previous_offset(offset, limit)+ return {+ "next": None if next_offset is None else replace_query_param(url, "offset", next_offset),+ "previous": None if previous is None else replace_query_param(url, "offset", previous),+ }+++class PageLinksSerializer(serializers.Serializer):+ """Declares the `next` and `previous` links of a page response that the view fills with `page_link`."""++ next = serializers.URLField(+ read_only=True,+ allow_null=True,+ default=None,+ help_text="URL of the next page, or null on the last page.",+ )+ previous = serializers.URLField(+ read_only=True,+ allow_null=True,+ default=None,+ help_text="URL of the previous page, or null on the first page and on lists that page forward only.",+ )++class PrecountedLimitOffsetPagination(LimitOffsetPagination):"""Pages a queryset that the view has already bounded with LIMIT and OFFSET.diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex 3c3631e10d40..0b01871cd5f8 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -7,6 +7,7 @@ from unittest import mockfrom django.apps import appsfrom django.conf import settings+from django.db.models import QuerySetfrom django.test import SimpleTestCasefrom django.utils import timezone@@ -1324,6 +1325,7 @@ class TestComments(APIBaseTest, QueryMatchingTest):response = self.client.get(f"/api/projects/{self.team.id}/comments")assert response.status_code == status.HTTP_200_OKassert response.json() == {+ "count": 0,"next": None,"previous": None,"results": [],@@ -1399,21 +1401,26 @@ class TestComments(APIBaseTest, QueryMatchingTest):Comment.objects.filter(id__in=tied_ids).update(created_at=timezone.now() - timedelta(hours=1))Comment.objects.filter(id=newest_id).update(created_at=timezone.now())- url: str | None = (+ first_url = (f"/api/projects/{self.team.id}/comments/{root['id']}/thread"if rootelse f"/api/projects/{self.team.id}/comments/?scope=Notebook&item_id=1")+ url: str | None = first_urlpaged_ids: list[str] = []with mock.patch.object(CommentPagination, "page_size", 2):while url:payload = self.client.get(url).json()+ assert payload["count"] == 10paged_ids.extend(comment["id"] for comment in payload["results"])url = payload["next"]assert len(paged_ids) <= 10assert paged_ids == [newest_id, *reversed(tied_ids)]+ with mock.patch.object(QuerySet, "count", side_effect=AssertionError("count queried")):+ assert self.client.get(first_url).json()["count"] == 10+@parameterized.expand([("no_comments", [], "", 0),diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 93d291f70c29..349d6d3c7e76 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -6,7 +6,7 @@ from collections.abc import Callablefrom contextlib import nullcontextfrom datetime import timedeltafrom typing import Any, cast-from urllib.parse import quote, urlencode+from urllib.parse import parse_qs, quote, urlencode, urlparsefrom uuid import uuid4import pytest@@ -1981,21 +1981,21 @@ class TestIntegrationAPIKeyAccess:)seen: list[str] = []- offset: int | None = 0+ url: str | None = (+ f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/github_repos/"+ f"?limit=100&offset=0&compact={str(compact).lower()}"+ )pages = 0- while offset is not None:- response = client.get(- f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/github_repos/"- f"?limit=100&offset={offset}&compact={str(compact).lower()}",- HTTP_AUTHORIZATION=f"Bearer {key_value}",- )+ while url is not None:+ response = client.get(url, HTTP_AUTHORIZATION=f"Bearer {key_value}")assert response.status_code == status.HTTP_200_OKdata = response.json()assert data["total"] == 250- assert data["has_more"] is (data["next_offset"] is not None)+ assert data["has_more"] is (data["next_offset"] is not None) is (data["next"] is not None)+ assert (data["previous"] is None) is (pages == 0)assert all(set(repo) == expected_keys for repo in data["repositories"])seen.extend(repo["full_name"] for repo in data["repositories"])- offset = data["next_offset"]+ url = data["next"]pages += 1assert pages == 3@@ -2514,6 +2514,10 @@ class TestIntegrationAPIKeyAccess:assert data["channels"][0]["id"] == "C2"assert data["has_more"] is True+ last_page = client.get(data["next"], HTTP_AUTHORIZATION=f"Bearer {key_value}").json()+ assert [channel["id"] for channel in last_page["channels"]] == ["C3"]+ assert last_page["next"] is None+mock_slack_instance.list_channels.assert_called_once()@pytest.mark.parametrize("owns_integration", [True, False])@@ -2942,6 +2946,11 @@ class TestIntegrationAPIKeyAccess:assert [member["id"] for member in data["users"]] == ["U1"]assert data["has_more"] is True+ last_page = client.get(data["next"], HTTP_AUTHORIZATION=f"Bearer {key_value}").json()+ assert [member["id"] for member in last_page["users"]] == ["U2"]+ assert last_page["next"] is None+ assert last_page["previous"] is not None+@patch("posthog.api.integration.SlackIntegration")def test_users_action_direct_lookup_and_kind_guard(self, mock_slack_class, client: HttpClient):slack_integration = Integration.objects.create(@@ -2975,6 +2984,7 @@ class TestIntegrationAPIKeyAccess:)assert response.status_code == status.HTTP_200_OKassert response.json()["users"] == [{"id": "U42", "name": "andy.m", "display_name": "andy"}]+ assert response.json()["next"] is None and response.json()["previous"] is Nonemock_slack_instance.get_user_by_id.assert_called_once_with("U42")# Lookups are cached per id — hits and misses alike — so repeated probes can't spend the@@ -6491,6 +6501,8 @@ class TestGitHubBranches:data = response.json()assert len(data["branches"]) == 10assert data["has_more"] is True+ assert parse_qs(urlparse(data["next"]).query)["offset"] == ["60"]+ assert parse_qs(urlparse(data["previous"]).query)["offset"] == ["40"]assert data["default_branch"] == "main"mock_list_cached.assert_called_once_with("org/repo",diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex eb698f4c11ed..3a78479cf63e 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -43,6 +43,7 @@ from posthog.api.integration import (GitHubReposQuerySerializer,GitHubReposRefreshResponseSerializer,GitHubReposResponseSerializer,+ external_page_links,github_rate_limited_response,github_repos_page,validate_github_repository_name,@@ -514,6 +515,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):return Response(github_repos_page(+ request,UserGitHubIntegration(integration, source="user_integrations_api", priority=Priority.CRITICAL),query_serializer.validated_data,)@@ -576,7 +578,15 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):offset=offset,)- return Response({"branches": branches, "default_branch": default_branch, "has_more": has_more})+ next_offset = offset + limit if has_more else None+ return Response(+ {+ "branches": branches,+ "default_branch": default_branch,+ "has_more": has_more,+ **external_page_links(request, offset=offset, limit=limit, next_offset=next_offset),+ }+ )@extend_schema(summary="List the user's GitHub install-approval requests",diff --git a/products/ai_observability/backend/api/offline_experiment_read_serializers.py b/products/ai_observability/backend/api/offline_experiment_read_serializers.pyindex a072ef75becc..3e8e16aa77e6 100644--- a/products/ai_observability/backend/api/offline_experiment_read_serializers.py+++ b/products/ai_observability/backend/api/offline_experiment_read_serializers.py@@ -7,6 +7,7 @@ from rest_framework import serializersfrom rest_framework_dataclasses.fields import EnumFieldfrom rest_framework_dataclasses.serializers import DataclassSerializer+from posthog.api.pagination import PageLinksSerializerfrom posthog.api.shared import UserBasicSerializerfrom products.ai_observability.backend.api.offline_experiment_serializers import (@@ -454,7 +455,7 @@ class OfflineHistoryPointSerializer(serializers.Serializer):@extend_schema_serializer(many=False)-class OfflinePageSerializer(serializers.Serializer):+class OfflinePageSerializer(PageLinksSerializer):count = serializers.IntegerField(help_text="Total authorized rows matching the filters, independent of this page.")next_cursor = serializers.CharField(allow_null=True, help_text="Continuation cursor, or null after the final page.")diff --git a/products/ai_observability/backend/api/offline_experiment_reads.py b/products/ai_observability/backend/api/offline_experiment_reads.pyindex 1610b26dd242..d5962ae934d3 100644--- a/products/ai_observability/backend/api/offline_experiment_reads.py+++ b/products/ai_observability/backend/api/offline_experiment_reads.py@@ -14,6 +14,7 @@ from rest_framework.response import Responsefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.monitoring import monitor+from posthog.api.pagination import page_linkfrom posthog.api.statement_timeout import statement_timeoutfrom posthog.permissions import get_authenticator_scopes@@ -125,6 +126,11 @@ class OfflineEvaluationReadViewSet(OfflineEvaluationViewSet):):return Response(serializer(read()).data)+ def _page_response(self, read: Callable[[], object], serializer: type[serializers.Serializer]) -> Response:+ response = self._read_response(read, serializer)+ response.data["next"] = page_link(self.request, "cursor", response.data["next_cursor"])+ return response+class OfflineExperimentReadViewSet(OfflineEvaluationReadViewSet):@validated_request(@@ -150,7 +156,7 @@ class OfflineExperimentReadViewSet(OfflineEvaluationReadViewSet):def list(self, request: ValidatedRequest, **kwargs: object) -> Response:query = cast(OfflineReadQuery, request.validated_query_data)service = self._read_service(query)- return self._read_response(lambda: service.list_experiments(query), OfflineExperimentPageSerializer)+ return self._page_response(lambda: service.list_experiments(query), OfflineExperimentPageSerializer)@validated_request(query_serializer=EmptyQuerySerializer,@@ -176,7 +182,7 @@ class OfflineExperimentReadViewSet(OfflineEvaluationReadViewSet):def items(self, request: ValidatedRequest, **kwargs: object) -> Response:query = cast(OfflineReadQuery, request.validated_query_data)service = self._read_service(query)- return self._read_response(lambda: service.list_items(self._path_id(), query), OfflineItemPageSerializer)+ return self._page_response(lambda: service.list_items(self._path_id(), query), OfflineItemPageSerializer)@validated_request(query_serializer=EmptyQuerySerializer,@@ -203,7 +209,7 @@ class OfflineExperimentReadViewSet(OfflineEvaluationReadViewSet):def item_results(self, request: ValidatedRequest, **kwargs: object) -> Response:query = cast(OfflineReadQuery, request.validated_query_data)service = self._read_service(query)- return self._read_response(+ return self._page_response(lambda: service.list_item_results(self._path_id(), self._path_id("item_id"), query),OfflineResultPageSerializer,)@@ -248,7 +254,7 @@ class OfflineExperimentReadViewSet(OfflineEvaluationReadViewSet):def scorer_summaries(self, request: ValidatedRequest, **kwargs: object) -> Response:query = cast(OfflineReadQuery, request.validated_query_data)service = self._read_service(query)- return self._read_response(lambda: service.list_summaries(self._path_id(), query), OfflineSummaryPageSerializer)+ return self._page_response(lambda: service.list_summaries(self._path_id(), query), OfflineSummaryPageSerializer)class OfflineScorerViewSet(OfflineEvaluationReadViewSet):@@ -264,4 +270,4 @@ class OfflineScorerViewSet(OfflineEvaluationReadViewSet):def history(self, request: ValidatedRequest, **kwargs: object) -> Response:query = cast(OfflineReadQuery, request.validated_query_data)service = self._read_service(query)- return self._read_response(lambda: service.scorer_history(self._path_id(), query), OfflineHistoryPageSerializer)+ return self._page_response(lambda: service.scorer_history(self._path_id(), query), OfflineHistoryPageSerializer)diff --git a/products/ai_observability/backend/api/score_definitions.py b/products/ai_observability/backend/api/score_definitions.pyindex ae81f9a9ded8..ed08dffa9ed5 100644--- a/products/ai_observability/backend/api/score_definitions.py+++ b/products/ai_observability/backend/api/score_definitions.py@@ -18,6 +18,7 @@ from rest_framework.response import Responsefrom posthog.api.documentation import extend_schemafrom posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.pagination import PageLinksSerializer, page_linkfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action@@ -110,7 +111,7 @@ class ScoreDefinitionVersionSerializer(serializers.ModelSerializer):@extend_schema_serializer(many=False)-class ScoreDefinitionVersionPageSerializer(serializers.Serializer):+class ScoreDefinitionVersionPageSerializer(PageLinksSerializer):count = serializers.IntegerField(help_text="Total immutable versions for this scorer.")next_cursor = serializers.CharField(allow_null=True, help_text="Continuation cursor, or null on the last page.")results = ScoreDefinitionVersionSerializer(many=True, help_text="Versions on this page, newest first.")@@ -480,7 +481,9 @@ class ScoreDefinitionViewSet(def versions(self, request: ValidatedRequest, **kwargs: object) -> Response:definition = self.get_object()page = _score_definition_version_page(definition, **request.validated_query_data)- return Response(ScoreDefinitionVersionPageSerializer(page).data)+ data = ScoreDefinitionVersionPageSerializer(page).data+ data["next"] = page_link(request, "cursor", page.next_cursor)+ return Response(data)@validated_request(query_serializer=EmptyQuerySerializer,diff --git a/products/ai_observability/backend/api/test/test_offline_experiment_reads.py b/products/ai_observability/backend/api/test/test_offline_experiment_reads.pyindex d360e33945c6..e0697747e7ba 100644--- a/products/ai_observability/backend/api/test/test_offline_experiment_reads.py+++ b/products/ai_observability/backend/api/test/test_offline_experiment_reads.py@@ -224,8 +224,9 @@ class TestOfflineExperimentReads(APIBaseTest):if expected_count:assert response.data["results"][0]["experiment"]["tags"] == ["production", "quality"]seen = [point["experiment"]["id"] for point in response.data["results"]]- while response.data["next_cursor"]:- response = self.client.get(self._history(), {**query, "cursor": response.data["next_cursor"]})+ while response.data["next"]:+ assert response.data["next_cursor"]+ response = self.client.get(response.data["next"])assert response.status_code == 200, response.dataseen.extend(point["experiment"]["id"] for point in response.data["results"])assert len(seen) == len(set(seen)) == expected_countdiff --git a/products/ai_observability/backend/api/test/test_offline_experiments.py b/products/ai_observability/backend/api/test/test_offline_experiments.pyindex 42439dea5053..1702d249014b 100644--- a/products/ai_observability/backend/api/test/test_offline_experiments.py+++ b/products/ai_observability/backend/api/test/test_offline_experiments.py@@ -643,7 +643,9 @@ class TestOfflineExperimentActionSchemas(SimpleTestCase):self.assertIn("$ref", response_schema)page_schema = components[response_schema["$ref"].rsplit("/", 1)[-1]]self.assertEqual(page_schema["type"], "object")- self.assertTrue({"count", "next_cursor", "results"} <= set(page_schema["properties"]))+ self.assertTrue(+ {"count", "next", "previous", "next_cursor", "results"} <= set(page_schema["properties"])+ )self.assertEqual(page_schema["properties"]["results"]["type"], "array")@parameterized.expand(diff --git a/products/ai_observability/backend/api/test/test_score_definitions.py b/products/ai_observability/backend/api/test/test_score_definitions.pyindex d42a9cee234b..57ad47236c48 100644--- a/products/ai_observability/backend/api/test/test_score_definitions.py+++ b/products/ai_observability/backend/api/test/test_score_definitions.py@@ -307,11 +307,12 @@ class TestScoreDefinitionsApi(APIBaseTest):self.assertEqual(first.data["count"], 2)self.assertEqual([row["version"] for row in first.data["results"]], [2])definition.create_new_version(config={"min": -1, "max": 1}, created_by=self.user)- second = self.client.get(endpoint, {"limit": 1, "cursor": first.data["next_cursor"]})+ second = self.client.get(first.data["next"])self.assertEqual(second.status_code, status.HTTP_200_OK)self.assertEqual(second.data["count"], 3)self.assertEqual([row["id"] for row in second.data["results"]], [str(original.id)])self.assertIsNone(second.data["next_cursor"])+ self.assertIsNone(second.data["next"])historical = self.client.get(f"{endpoint}{original.id}/")self.assertEqual(historical.status_code, status.HTTP_200_OK)diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 43f3cd85ad41..3542d725e9c4 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -484,7 +484,20 @@ export interface OfflineExperimentReadApi {prompt_version: string | null}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineExperimentPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Total authorized rows matching the filters, independent of this page. */count: number/**@@ -947,7 +960,20 @@ export interface OfflineScorerVersionReadApi {config: ScoreDefinitionConfigApi}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineItemPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Total authorized rows matching the filters, independent of this page. */count: number/**@@ -1064,7 +1090,20 @@ export interface OfflineResultReadApi {scorer: OfflineScorerVersionReadApi}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineResultPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Total authorized rows matching the filters, independent of this page. */count: number/**@@ -1202,7 +1241,20 @@ export interface OfflineScorerSummaryApi {categories: OfflineCategorySummaryApi[]}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineSummaryPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Total authorized rows matching the filters, independent of this page. */count: number/**@@ -1352,7 +1404,20 @@ export interface OfflineHistoryPointApi {summary: OfflineScorerSummaryApi}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineHistoryPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Total authorized rows matching the filters, independent of this page. */count: number/**@@ -4496,7 +4561,20 @@ export interface ScoreDefinitionVersionApi {readonly created_by: UserBasicApi | null}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ScoreDefinitionVersionPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Total immutable versions for this scorer. */count: number/**diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.test.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.test.tsxindex 34b7b5b57dee..59dfa33e71ff 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.test.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.test.tsx@@ -24,9 +24,17 @@ describe('OfflineExperimentContent', () => {initKeaTests()jest.clearAllMocks()jest.mocked(api.aiObservabilityOfflineExperimentsRetrieve).mockResolvedValue(detailExperiment)- readSummaries.mockResolvedValue({ count: 25, next_cursor: null, results: detailSummaries })+ readSummaries.mockResolvedValue({+ count: 25,+ next: null,+ previous: null,+ next_cursor: null,+ results: detailSummaries,+ })jest.mocked(api.aiObservabilityOfflineExperimentsItemsList).mockResolvedValue({count: 8,+ next: null,+ previous: null,next_cursor: null,results: detailItems,scorer_versions: [],@@ -41,6 +49,8 @@ describe('OfflineExperimentContent', () => {const fullName = 'Checks whether the answer is supported by the supplied reference material'readSummaries.mockResolvedValue({count: 1,+ next: null,+ previous: null,next_cursor: null,results: [{diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsxindex de3231d3c4c8..6ded351f14c7 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.test.tsx@@ -46,6 +46,8 @@ describe('OfflineItemInspector', () => {})jest.mocked(api.aiObservabilityOfflineExperimentsItemsResultsList).mockResolvedValue({count: 1,+ next: null,+ previous: null,next_cursor: null,results: [result],})@@ -84,7 +86,7 @@ describe('OfflineItemInspector', () => {data: null,})jest.mocked(api.aiObservabilityOfflineExperimentsItemsResultsList)- .mockResolvedValueOnce({ count: 2, next_cursor: 'more', results: [result] })+ .mockResolvedValueOnce({ count: 2, next: null, previous: null, next_cursor: 'more', results: [result] }).mockRejectedValueOnce(new ApiError('Results unavailable', 503, undefined, { detail: 'Results unavailable' }))diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsxindex 8269b2900ccf..ce18dc420563 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsx@@ -38,6 +38,8 @@ describe('OfflineOverviewTrend', () => {experiment: { ...point.experiment, id: `${point.experiment.id}-${pageIndex}` },})),count: partial ? 200 : results.length,+ next: null,+ previous: null,next_cursor: partial ? String(pageIndex + 1) : null,}})diff --git a/products/ai_observability/frontend/offline-evaluations/offlineExperimentLogic.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineExperimentLogic.test.tsindex 6e350ffe00e1..a480d27af10e 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineExperimentLogic.test.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineExperimentLogic.test.ts@@ -34,8 +34,21 @@ describe('offlineExperimentLogic', () => {initKeaTests()jest.resetAllMocks()readExperiment.mockResolvedValue(detailExperiment)- readSummaries.mockResolvedValue({ count: 25, next_cursor: null, results: makeOfflineDetailSummaries(25) })- readItems.mockResolvedValue({ count: 8, next_cursor: null, results: detailItems, scorer_versions: [] })+ readSummaries.mockResolvedValue({+ count: 25,+ next: null,+ previous: null,+ next_cursor: null,+ results: makeOfflineDetailSummaries(25),+ })+ readItems.mockResolvedValue({+ count: 8,+ next: null,+ previous: null,+ next_cursor: null,+ results: detailItems,+ scorer_versions: [],+ })readCells.mockImplementation(async (_team, _experiment, params) =>makeOfflineDetailCells(params.item_ids.split(','), params.scorer_version_ids.split(',')))@@ -45,8 +58,8 @@ describe('offlineExperimentLogic', () => {const summaries = makeOfflineDetailSummaries(101)readSummaries.mockImplementation(async (_team, _experiment, params) =>params?.cursor- ? { count: 101, next_cursor: null, results: summaries.slice(100) }- : { count: 101, next_cursor: 'more', results: summaries.slice(0, 100) }+ ? { count: 101, next: null, previous: null, next_cursor: null, results: summaries.slice(100) }+ : { count: 101, next: null, previous: null, next_cursor: 'more', results: summaries.slice(0, 100) })const logic = offlineExperimentLogic({ teamId: 543, experimentId: detailExperiment.id })logic.mount()@@ -99,7 +112,14 @@ describe('offlineExperimentLogic', () => {logic.actions.refresh()await expectLogic(logic).toDispatchActions(['loadOfflineItemsSuccess', 'loadCellBatch'])const newItems = [detailItems[7]]- readItems.mockResolvedValueOnce({ count: 8, next_cursor: null, results: newItems, scorer_versions: [] })+ readItems.mockResolvedValueOnce({+ count: 8,+ next: null,+ previous: null,+ next_cursor: null,+ results: newItems,+ scorer_versions: [],+ })logic.actions.nextItems('next-page')await expectLogic(logic).toDispatchActions(['loadOfflineItemsSuccess', 'loadedCellBatch'])resolveOld(diff --git a/products/ai_observability/frontend/offline-evaluations/offlineExperimentsLogic.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineExperimentsLogic.test.tsindex 1fb047db36f5..0261c588459d 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineExperimentsLogic.test.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineExperimentsLogic.test.ts@@ -23,7 +23,13 @@ jest.mock('../generated/api', () => ({aiObservabilityOfflineScorersHistoryList: jest.fn(),}))-const page: OfflineExperimentPageApi = { results: overviewExperiments, count: 100, next_cursor: 'cursor-2' }+const page: OfflineExperimentPageApi = {+ results: overviewExperiments,+ count: 100,+ next: null,+ previous: null,+ next_cursor: 'cursor-2',+}const props = { teamId: 997, userId: 1, timezone: 'America/Toronto' }const list = jest.mocked(api.aiObservabilityOfflineExperimentsList)@@ -37,6 +43,8 @@ describe('offlineExperimentsLogic', () => {jest.mocked(api.aiObservabilityOfflineExperimentsScorerSummariesList).mockResolvedValue({results: overviewScorers.map((scorer) => overviewHistory(scorer)[0].summary),count: 3,+ next: null,+ previous: null,next_cursor: null,})jest.mocked(api.llmAnalyticsScoreDefinitionsList).mockResolvedValue({@@ -178,6 +186,8 @@ describe('offlineExperimentsLogic', () => {jest.mocked(api.aiObservabilityOfflineScorersHistoryList).mockResolvedValue({results: overviewHistory(overviewScorers[0]),count: 6,+ next: null,+ previous: null,next_cursor: null,})const trend = offlineOverviewTrendLogic({@@ -233,6 +243,8 @@ describe('offlineExperimentsLogic', () => {jest.mocked(api.aiObservabilityOfflineScorersHistoryList).mockImplementation(async (_, scorerId) => ({count: 1,+ next: null,+ previous: null,next_cursor: null,results: [{@@ -333,6 +345,8 @@ describe('offlineExperimentsLogic', () => {jest.mocked(api.aiObservabilityOfflineExperimentsScorerSummariesList).mockResolvedValue({results: [],count: 0,+ next: null,+ previous: null,next_cursor: null,})const logic = offlineExperimentsLogic(props)@@ -502,7 +516,13 @@ describe('offlineExperimentsLogic', () => {it.each([true, false])('distinguishes no matching experiments from a new project (has history: %s)',async (hasHistory) => {- const emptyPage: OfflineExperimentPageApi = { results: [], count: 0, next_cursor: null }+ const emptyPage: OfflineExperimentPageApi = {+ results: [],+ count: 0,+ next: null,+ previous: null,+ next_cursor: null,+ }list.mockResolvedValueOnce(emptyPage).mockResolvedValueOnce(hasHistory ? page : emptyPage)const logic = offlineExperimentsLogic(props)logic.mount()@@ -515,9 +535,13 @@ describe('offlineExperimentsLogic', () => {)it('keeps onboarding hidden when the project presence check fails', async () => {- list.mockResolvedValueOnce({ results: [], count: 0, next_cursor: null }).mockRejectedValueOnce(- new Error('Unavailable')- )+ list.mockResolvedValueOnce({+ results: [],+ count: 0,+ next: null,+ previous: null,+ next_cursor: null,+ }).mockRejectedValueOnce(new Error('Unavailable'))const logic = offlineExperimentsLogic(props)logic.mount()await jest.advanceTimersByTimeAsync(150)diff --git a/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.tsindex 815f2d7d93c7..3573479b773c 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineItemInspectorLogic.test.ts@@ -30,6 +30,8 @@ describe('offlineItemInspectorLogic', () => {const all = offlineDetailItemResults(detailItems[0].id)return {count: params?.scorer_version_ids ? 1 : all.length,+ next: null,+ previous: null,next_cursor: params?.scorer_version_ids ? null : 'more',results: params?.scorer_version_ids? all.filter((result) => result.scorer.id === params.scorer_version_ids)diff --git a/products/ai_observability/frontend/offline-evaluations/offlineOverviewTrendLogic.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineOverviewTrendLogic.test.tsindex 16c9405b0042..39d099f6a275 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineOverviewTrendLogic.test.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineOverviewTrendLogic.test.ts@@ -24,7 +24,13 @@ const props = {dateTo: '2026-09-28T00:00:00Z',refreshKey: 0,}-const page: OfflineHistoryPageApi = { results: overviewHistory(overviewScorers[0]), count: 6, next_cursor: null }+const page: OfflineHistoryPageApi = {+ results: overviewHistory(overviewScorers[0]),+ count: 6,+ next: null,+ previous: null,+ next_cursor: null,+}const retrieve = jest.mocked(api.llmAnalyticsScoreDefinitionsRetrieve)const history = jest.mocked(api.aiObservabilityOfflineScorersHistoryList)@@ -48,6 +54,8 @@ describe('offlineOverviewTrendLogic', () => {jest.mocked(api.aiObservabilityOfflineExperimentsList).mockResolvedValue({results: [],count: 0,+ next: null,+ previous: null,next_cursor: null,})})@@ -150,7 +158,7 @@ describe('offlineOverviewTrendLogic', () => {}))history.mockResolvedValueOnce({ ...page, count: 8, next_cursor: 'older' })- .mockResolvedValueOnce({ results: olderPoints, count: 8, next_cursor: null })+ .mockResolvedValueOnce({ results: olderPoints, count: 8, next: null, previous: null, next_cursor: null })const logic = offlineOverviewTrendLogic(trendProps)logic.mount()await expectLogic(logic).toFinishAllListeners()@@ -169,7 +177,13 @@ describe('offlineOverviewTrendLogic', () => {Date.parse(props.dateTo),])- history.mockResolvedValueOnce({ results: page.results.slice(0, 1), count: 1, next_cursor: null })+ history.mockResolvedValueOnce({+ results: page.results.slice(0, 1),+ count: 1,+ next: null,+ previous: null,+ next_cursor: null,+ })overviewLogic.actions.setFilters({ date_from: '2026-09-20T00:00:00Z' })offlineOverviewTrendLogic({...trendProps,@@ -192,6 +206,8 @@ describe('offlineOverviewTrendLogic', () => {experiment: { ...page.results[0].experiment, id: `${scorerId}-${offset + index}` },})),count: 1000,+ next: null,+ previous: null,next_cursor: String(offset + 100),}})diff --git a/products/ai_observability/frontend/offline-evaluations/offlineScorerHistoryLogic.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineScorerHistoryLogic.test.tsindex 651cf213c358..01cd052f265a 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineScorerHistoryLogic.test.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineScorerHistoryLogic.test.ts@@ -26,12 +26,16 @@ describe('offlineScorerHistoryLogic', () => {jest.mocked(api.llmAnalyticsScoreDefinitionsRetrieve).mockResolvedValue(OFFLINE_STORY_DEFINITION)jest.mocked(api.llmAnalyticsScoreDefinitionsVersionsList).mockResolvedValue({results: [OFFLINE_STORY_VERSION],+ next: null,+ previous: null,next_cursor: null,count: 1,})jest.mocked(api.llmAnalyticsScoreDefinitionsVersionsRetrieve).mockResolvedValue(OFFLINE_STORY_VERSION)jest.mocked(api.aiObservabilityOfflineScorersHistoryList).mockResolvedValue({results: [makeOfflineHistoryPoint(1)],+ next: null,+ previous: null,next_cursor: 'older',count: 150,})@@ -267,7 +271,13 @@ describe('offlineScorerHistoryLogic', () => {})logic.actions.loadOfflineHistoryPrimaryPage()await started- const newest = { results: [makeOfflineHistoryPoint(3)], next_cursor: null, count: 1 }+ const newest = {+ results: [makeOfflineHistoryPoint(3)],+ next: null,+ previous: null,+ next_cursor: null,+ count: 1,+ }jest.mocked(api.aiObservabilityOfflineScorersHistoryList).mockResolvedValueOnce(newest)await expectLogic(logic, () => logic.actions.loadOfflineHistoryPrimaryPage()).toDispatchActions(['loadOfflineHistoryPrimaryPageSuccess',diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex 0bb6eeaba5fe..8bd2d7ed4de2 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -18718,6 +18718,7 @@ export namespace Schemas {locked_value: boolean;};export type PaginatedCommentList = {+ count: number;next?: (string | null) | undefined;previous?: (string | null) | undefined;results: Array<Comment>;diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 713480dfb364..5968c31a9b8e 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -333,7 +333,20 @@ export interface SlackChannelApi {is_private_without_access: boolean}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface SlackChannelsResponseApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Slack channels visible to the PostHog Slack app. */channels: SlackChannelApi[]/**@@ -591,7 +604,20 @@ export interface IntegrationAssigneesResponseApi {reconnect_required: boolean}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubBranchesResponseApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** List of branch names */branches: string[]/**@@ -624,7 +650,20 @@ export interface GitHubRepoApi {can_push?: boolean}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubReposResponseApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | nullrepositories: GitHubRepoApi[]/** Whether more repositories are available beyond this page. */has_more: boolean@@ -666,7 +705,20 @@ export interface GitHubTeamApi {name: string}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubTeamsResponseApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** List of GitHub teams available to the installation organization. */teams: GitHubTeamApi[]/** Whether more teams are available beyond this page. */@@ -733,7 +785,20 @@ export interface SlackUserApi {display_name: string}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface SlackUsersResponseApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Human Slack workspace members the PostHog Slack app can DM. */users: SlackUserApi[]/**diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.pyindex 31701247c483..903bbc93e246 100644--- a/products/mcp_analytics/backend/presentation/views.py+++ b/products/mcp_analytics/backend/presentation/views.py@@ -13,6 +13,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.pagination import page_link, previous_offsetfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_actionfrom posthog.models.user import User@@ -55,7 +56,7 @@ class MCPAnalyticsPagination(LimitOffsetPagination):class MCPSessionPagination(LimitOffsetPagination):- """Returns ``{results, has_next}`` instead of a count-based envelope. The list is an+ """Returns ``{next, previous, results, has_next}`` without a ``count``. The list is anon-the-fly ClickHouse aggregate with no cheap total, so ``has_next`` comes from thelogic layer over-fetching one row rather than a count query."""@@ -63,14 +64,33 @@ class MCPSessionPagination(LimitOffsetPagination):default_limit = MCP_SESSION_LIST_DEFAULT_LIMITmax_limit = MCP_SESSION_LIST_MAX_LIMIT- def get_paginated_response(self, data: Any, *, has_next: bool = False) -> Response:- return Response({"results": data, "has_next": has_next})+ def get_page_response(self, request: Request, data: Any, *, offset: int, limit: int, has_next: bool) -> Response:+ return Response(+ {+ "next": page_link(request, self.offset_query_param, offset + limit) if has_next else None,+ "previous": page_link(request, self.offset_query_param, previous_offset(offset, limit)),+ "results": data,+ "has_next": has_next,+ }+ )def get_paginated_response_schema(self, schema: dict) -> dict:return {"type": "object",- "required": ["results", "has_next"],+ "required": ["next", "previous", "results", "has_next"],"properties": {+ "next": {+ "type": "string",+ "format": "uri",+ "nullable": True,+ "description": "URL of the next page, or null on the last page.",+ },+ "previous": {+ "type": "string",+ "format": "uri",+ "nullable": True,+ "description": "URL of the previous page, or null on the first page.",+ },"results": schema,"has_next": {"type": "boolean",@@ -197,8 +217,10 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)serializer = self.get_serializer(page.results, many=True)# Instantiate the concrete class (not self.pagination_class()) so the typed- # get_paginated_response(has_next=...) is visible to the type checker.- return MCPSessionPagination().get_paginated_response(serializer.data, has_next=page.has_next)+ # get_page_response(...) is visible to the type checker.+ return MCPSessionPagination().get_page_response(+ request, serializer.data, offset=params["offset"], limit=params["limit"], has_next=page.has_next+ )@validated_request(query_serializer=MCPSessionToolCallsQuerySerializer,@@ -220,7 +242,9 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):user=cast(User, request.user),)serializer = MCPToolCallSerializer(page.results, many=True)- return MCPSessionPagination().get_paginated_response(serializer.data, has_next=page.has_next)+ return MCPSessionPagination().get_page_response(+ request, serializer.data, offset=params["offset"], limit=params["limit"], has_next=page.has_next+ )@extend_schema(operation_id="mcp_analytics_sessions_generate_intent",diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.pyindex 26ab73986148..72c64fd2e4c8 100644--- a/products/mcp_analytics/backend/tests/test_presentation.py+++ b/products/mcp_analytics/backend/tests/test_presentation.py@@ -715,6 +715,17 @@ class TestMCPSessionToolCallsEndpoint(_MCPAnalyticsTeamScopedTestMixin, Clickhou# still include it after the round-trip — otherwise we'd get just ["last_tool"].assert [c["tool_name"] for c in response.json()["results"]] == ["first_tool", "last_tool"]+ first_page = self.client.get(+ f"/api/environments/{self.team.id}/mcp_analytics/sessions/{session_id}/tool_calls/",+ {"date_from": session["session_start"], "limit": 1},+ ).json()+ second_page = self.client.get(first_page["next"]).json()+ assert [c["tool_name"] for c in first_page["results"]] == ["first_tool"]+ assert first_page["previous"] is None+ assert [c["tool_name"] for c in second_page["results"]] == ["last_tool"]+ assert second_page["next"] is None+ assert second_page["has_next"] is False+@parameterized.expand([("sessions_list", "", {"date_from": "-7d"}),diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.tsindex 466531aecb11..1f88d439663f 100644--- a/products/mcp_analytics/frontend/generated/api.schemas.ts+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts@@ -500,6 +500,16 @@ export interface MCPSessionApi {}export interface PaginatedMCPSessionListApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ next: string | null+ /**+ * URL of the previous page, or null on the first page.+ * @nullable+ */+ previous: string | nullresults: MCPSessionApi[]/** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */has_next: boolean@@ -533,6 +543,16 @@ export interface MCPToolCallApi {}export interface PaginatedMCPToolCallListApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ next: string | null+ /**+ * URL of the previous page, or null on the first page.+ * @nullable+ */+ previous: string | nullresults: MCPToolCallApi[]/** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */has_next: booleandiff --git a/products/notebooks/backend/presentation/reusable_widget_serializers.py b/products/notebooks/backend/presentation/reusable_widget_serializers.pyindex 57a857b59009..c9ca0542e223 100644--- a/products/notebooks/backend/presentation/reusable_widget_serializers.py+++ b/products/notebooks/backend/presentation/reusable_widget_serializers.py@@ -1,6 +1,8 @@from drf_spectacular.utils import extend_schema_serializerfrom rest_framework import serializers+from posthog.api.pagination import PageLinksSerializer+from products.notebooks.backend.facade.widgets import MAX_REUSABLE_WIDGET_DEMO_ROWSfrom products.notebooks.backend.presentation.widget_serializers import (WidgetFrameSerializer,@@ -134,7 +136,7 @@ class ReusableWidgetSummarySerializer(serializers.Serializer):@extend_schema_serializer(many=False)-class ReusableWidgetPageSerializer(serializers.Serializer):+class ReusableWidgetPageSerializer(PageLinksSerializer):results = ReusableWidgetSummarySerializer(many=True, help_text="Reusable widgets in this page.")count = serializers.IntegerField(help_text="Total reusable widgets matching the search.")next_offset = serializers.IntegerField(@@ -192,7 +194,7 @@ class ReusableWidgetVersionDetailSerializer(serializers.Serializer):@extend_schema_serializer(many=False)-class ReusableWidgetVersionPageSerializer(serializers.Serializer):+class ReusableWidgetVersionPageSerializer(PageLinksSerializer):results = ReusableWidgetVersionDetailSerializer(many=True, help_text="Published versions, newest first.")count = serializers.IntegerField(help_text="Total number of published versions.")next_offset = serializers.IntegerField(allow_null=True, help_text="Next page offset, or null on the final page.")diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex bc78b70a9da8..3d58eb125b41 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -32,6 +32,7 @@ from rest_framework.serializers import BaseSerializerfrom posthog.hogql.direct_connection import get_direct_connection_sourcefrom posthog.api.forbid_destroy_model import ForbidDestroyModel+from posthog.api.pagination import offset_page_linksfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.sharing_publish_gate import denied_resources_in_notebook_edit, is_publicly_shared@@ -1206,16 +1207,20 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDraise Http404()query = WidgetVersionQuerySerializer(data=request.query_params)query.is_valid(raise_exception=True)+ offset = query.validated_data["offset"]+ limit = query.validated_data["limit"]try:result = list_widget_versions(notebook=self.get_object(),node_id=node_id,- offset=query.validated_data["offset"],- limit=query.validated_data["limit"],+ offset=offset,+ limit=limit,)except WidgetError as error:return self._widget_error_response(error)- return Response(WidgetVersionPageSerializer(result).data)+ data = WidgetVersionPageSerializer(result).data+ data.update(offset_page_links(request, offset=offset, limit=limit, next_offset=result.next_offset))+ return Response(data)@extend_schema(operation_id="notebooks_widget_source",diff --git a/products/notebooks/backend/presentation/views/reusable_widget.py b/products/notebooks/backend/presentation/views/reusable_widget.pyindex f4583ed8ad3d..3957874f0ac7 100644--- a/products/notebooks/backend/presentation/views/reusable_widget.py+++ b/products/notebooks/backend/presentation/views/reusable_widget.py@@ -9,6 +9,7 @@ from rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.pagination import offset_page_linksfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.models import User@@ -96,13 +97,17 @@ class ReusableWidgetViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):self._require_user()query = ReusableWidgetCatalogQuerySerializer(data=request.query_params)query.is_valid(raise_exception=True)+ offset = query.validated_data["offset"]+ limit = query.validated_data["limit"]result = list_reusable_widgets(team_id=self.team_id,search=query.validated_data["search"],- offset=query.validated_data["offset"],- limit=query.validated_data["limit"],+ offset=offset,+ limit=limit,)- return Response(ReusableWidgetPageSerializer(result).data)+ data = ReusableWidgetPageSerializer(result).data+ data.update(offset_page_links(request, offset=offset, limit=limit, next_offset=result.next_offset))+ return Response(data)@extend_schema(operation_id="reusable_widgets_retrieve",@@ -126,16 +131,20 @@ class ReusableWidgetViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):self._require_user()query = WidgetVersionQuerySerializer(data=request.query_params)query.is_valid(raise_exception=True)+ offset = query.validated_data["offset"]+ limit = query.validated_data["limit"]try:result = list_reusable_widget_versions(team_id=self.team_id,widget_id=self._widget_id(),- offset=query.validated_data["offset"],- limit=query.validated_data["limit"],+ offset=offset,+ limit=limit,)except WidgetError as error:return self._error_response(error)- return Response(ReusableWidgetVersionPageSerializer(result).data)+ data = ReusableWidgetVersionPageSerializer(result).data+ data.update(offset_page_links(request, offset=offset, limit=limit, next_offset=result.next_offset))+ return Response(data)@extend_schema(operation_id="reusable_widgets_restore",diff --git a/products/notebooks/backend/presentation/widget_serializers.py b/products/notebooks/backend/presentation/widget_serializers.pyindex cd8a636599ed..b282c196d34b 100644--- a/products/notebooks/backend/presentation/widget_serializers.py+++ b/products/notebooks/backend/presentation/widget_serializers.py@@ -3,6 +3,8 @@ from typing import Anyfrom drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializers+from posthog.api.pagination import PageLinksSerializer+from products.notebooks.backend.facade.widgets import (DEFAULT_WIDGET_MODEL,MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,@@ -228,7 +230,7 @@ class WidgetVersionSerializer(serializers.Serializer):)-class WidgetVersionPageSerializer(serializers.Serializer):+class WidgetVersionPageSerializer(PageLinksSerializer):results = WidgetVersionSerializer(many=True, help_text="Versions ordered newest first.")count = serializers.IntegerField(min_value=0, help_text="Total versions.")next_offset = serializers.IntegerField(allow_null=True, help_text="Offset for the next page.")diff --git a/products/notebooks/backend/test/test_reusable_widgets.py b/products/notebooks/backend/test/test_reusable_widgets.pyindex 2ca4ca57f2df..2347ee73e6ef 100644--- a/products/notebooks/backend/test/test_reusable_widgets.py+++ b/products/notebooks/backend/test/test_reusable_widgets.py@@ -479,6 +479,8 @@ class TestReusableWidgets(APIBaseTest):assert response.status_code == 200assert response.json()["count"] == 1+ assert response.json()["next"] is None+ assert response.json()["previous"] is Noneassert response.json()["results"][0]["id"] == str(self.widget.id)assert response.json()["results"][0]["instance_count"] == 1other_team = Team.objects.create(organization=self.organization)@@ -1013,14 +1015,18 @@ class TestReusableWidgets(APIBaseTest):"products.canvas.backend.facade.notebooks.list_notebook_canvas_versions", return_value=canvas_versions):response = self.client.get(url, {"limit": 1})- older = self.client.get(url, {"offset": 1, "limit": 1})+ older = self.client.get(response.json()["next"])+ newest_again = self.client.get(older.json()["previous"])assert response.status_code == 200+ assert response.json()["previous"] is Noneassert response.json()["count"] == 2assert response.json()["next_offset"] == 1assert response.json()["results"][0]["id"] == str(latest.id)assert response.json()["results"][0]["version"] == 2assert response.json()["results"][0]["input_contract"] == []assert older.json()["next_offset"] is None+ assert older.json()["next"] is None+ assert newest_again.json()["results"] == response.json()["results"]assert older.json()["results"][0]["id"] == str(self.version.id)assert older.json()["results"][0]["version"] == 1assert older.json()["results"][0]["input_contract"][0]["slot"] == self.input_namediff --git a/products/notebooks/backend/test/test_widgets.py b/products/notebooks/backend/test/test_widgets.pyindex be22a3089772..a649062e2865 100644--- a/products/notebooks/backend/test/test_widgets.py+++ b/products/notebooks/backend/test/test_widgets.py@@ -1247,9 +1247,15 @@ class TestWidgetData(APIBaseTest):return_value=history,):history_response = self.client.get(history_url, {"limit": 1})+ older_response = self.client.get(history_response.json()["next"])assert history_response.status_code == 200assert history_response.json()["count"] == 2assert len(history_response.json()["results"]) == 1+ assert older_response.json()["next"] is None+ assert [row["id"] for row in older_response.json()["results"]] != [+ row["id"] for row in history_response.json()["results"]+ ]+ assert len(older_response.json()["results"]) == 1assert history_response.json()["results"][0]["build_hash"] == "b" * 64assert history_response.json()["results"][0]["security_review"]["severity"] == "high"assert history_response.json()["results"][0]["generation_cost_usd"] == "0.123456"diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsxindex 5d891881be5e..a64a33428c0f 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx@@ -103,7 +103,13 @@ describe('NotebookNodeGeneratedWidget', () => {is_reusable: false,build_hash: null,})- jest.mocked(notebooksWidgetVersions).mockResolvedValue({ results: [], count: 0, next_offset: null })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [],+ count: 0,+ next: null,+ previous: null,+ next_offset: null,+ })logic = notebookLogic(logicProps)logic.mount()@@ -312,6 +318,8 @@ describe('NotebookNodeGeneratedWidget', () => {},],count: 1,+ next: null,+ previous: null,next_offset: null,})jest.mocked(notebooksWidgetSource).mockResolvedValue({@@ -437,6 +445,8 @@ describe('NotebookNodeGeneratedWidget', () => {},],count: 1,+ next: null,+ previous: null,next_offset: null,})const { container } = render(@@ -621,6 +631,8 @@ describe('NotebookNodeGeneratedWidget', () => {},],count: 1,+ next: null,+ previous: null,next_offset: null,})const { container } = render(@@ -712,6 +724,8 @@ describe('NotebookNodeGeneratedWidget', () => {},],count: 1,+ next: null,+ previous: null,next_offset: null,})logic.unmount()diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.tsindex a58cf6db9d53..a900274db4a9 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts@@ -71,7 +71,7 @@ function status(overrides: Partial<WidgetStatusApi> = {}): WidgetStatusApi {}}-const emptyVersions: WidgetVersionPageApi = { results: [], count: 0, next_offset: null }+const emptyVersions: WidgetVersionPageApi = { results: [], count: 0, next: null, previous: null, next_offset: null }describe('notebookNodeGeneratedWidgetLogic', () => {const props = {@@ -410,6 +410,8 @@ describe('notebookNodeGeneratedWidgetLogic', () => {jest.mocked(notebooksWidgetVersions).mockResolvedValue({results: [version],count: 1,+ next: null,+ previous: null,next_offset: null,})logic = notebookNodeGeneratedWidgetLogic(props)@@ -451,7 +453,13 @@ describe('notebookNodeGeneratedWidgetLogic', () => {}// The first status carries no version, matching a settings panel opened before generation.jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())- jest.mocked(notebooksWidgetVersions).mockResolvedValue({ results: [firstVersion], count: 1, next_offset: null })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [firstVersion],+ count: 1,+ next: null,+ previous: null,+ next_offset: null,+ })logic = notebookNodeGeneratedWidgetLogic(props)logic.mount()await expectLogic(logic).toFinishAllListeners()@@ -517,7 +525,13 @@ describe('notebookNodeGeneratedWidgetLogic', () => {resolveResetRequest = resolve}))- .mockResolvedValueOnce({ results: [currentVersion], count: 1, next_offset: null })+ .mockResolvedValueOnce({+ results: [currentVersion],+ count: 1,+ next: null,+ previous: null,+ next_offset: null,+ })logic = notebookNodeGeneratedWidgetLogic(props)logic.mount()await expectLogic(logic).toDispatchActions(['statusReceived'])@@ -526,7 +540,7 @@ describe('notebookNodeGeneratedWidgetLogic', () => {logic.actions.loadVersions(true)logic.actions.statusReceived(readyStatus)- resolveInitialRequest({ results: [initialVersion], count: 1, next_offset: null })+ resolveInitialRequest({ results: [initialVersion], count: 1, next: null, previous: null, next_offset: null })await expectLogic(logic).toFinishAllListeners()expect(notebooksWidgetVersions).toHaveBeenCalledTimes(1)@@ -534,7 +548,7 @@ describe('notebookNodeGeneratedWidgetLogic', () => {logic.actions.loadVersions(true)logic.actions.loadVersions(true)- resolveResetRequest({ results: [initialVersion], count: 1, next_offset: null })+ resolveResetRequest({ results: [initialVersion], count: 1, next: null, previous: null, next_offset: null })await expectLogic(logic).toFinishAllListeners()expect(notebooksWidgetVersions).toHaveBeenCalledTimes(3)@@ -664,10 +678,18 @@ describe('notebookNodeGeneratedWidgetLogic', () => {})jest.mocked(notebooksWidgetStatus).mockResolvedValue(readyStatus)jest.mocked(notebooksWidgetVersions)- .mockResolvedValueOnce({ results: [historicalVersion], count: 1, next_offset: null })+ .mockResolvedValueOnce({+ results: [historicalVersion],+ count: 1,+ next: null,+ previous: null,+ next_offset: null,+ }).mockResolvedValueOnce({results: [{ ...historicalVersion, artifact_url: 'https://example.com/widget-new.html' }],count: 1,+ next: null,+ previous: null,next_offset: null,})logic = notebookNodeGeneratedWidgetLogic(props)@@ -720,6 +742,8 @@ describe('notebookNodeGeneratedWidgetLogic', () => {jest.mocked(notebooksWidgetVersions).mockResolvedValue({results: [previousVersion],count: 1,+ next: null,+ previous: null,next_offset: null,})logic = notebookNodeGeneratedWidgetLogic(props)@@ -782,10 +806,18 @@ describe('notebookNodeGeneratedWidgetLogic', () => {}))jest.mocked(notebooksWidgetVersions)- .mockResolvedValueOnce({ results: [previousVersion], count: 1, next_offset: null })+ .mockResolvedValueOnce({+ results: [previousVersion],+ count: 1,+ next: null,+ previous: null,+ next_offset: null,+ }).mockResolvedValueOnce({results: [failedVersion, { ...previousVersion, is_current: false }],count: 2,+ next: null,+ previous: null,next_offset: null,})logic = notebookNodeGeneratedWidgetLogic(props)@@ -1070,6 +1102,8 @@ describe('notebookNodeGeneratedWidgetLogic', () => {},],count: 1,+ next: null,+ previous: null,next_offset: null,})jest.mocked(notebooksWidgetSource).mockResolvedValue({ source: 'export default function Widget() {}' })@@ -1155,7 +1189,13 @@ describe('notebookNodeGeneratedWidgetLogic', () => {jest.mocked(notebooksWidgetStatus).mockResolvedValue(status({ lifecycle_status: 'ready', current_version_id: currentVersionId, has_versions: true }))- jest.mocked(notebooksWidgetVersions).mockResolvedValue({ results: [], count: 0, next_offset: null })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [],+ count: 0,+ next: null,+ previous: null,+ next_offset: null,+ })jest.mocked(notebooksWidgetSource).mockResolvedValue({ source: 'export default function Widget() {}' })logic = notebookNodeGeneratedWidgetLogic(props)logic.mount()diff --git a/products/notebooks/frontend/ReusableWidget/reusableWidgetLogic.test.ts b/products/notebooks/frontend/ReusableWidget/reusableWidgetLogic.test.tsindex 1763f642f999..e8087cf9a282 100644--- a/products/notebooks/frontend/ReusableWidget/reusableWidgetLogic.test.ts+++ b/products/notebooks/frontend/ReusableWidget/reusableWidgetLogic.test.ts@@ -77,7 +77,13 @@ describe('reusableWidgetLogic', () => {initKeaTests()jest.resetAllMocks()jest.mocked(reusableWidgetsRetrieve).mockResolvedValue(widget)- jest.mocked(reusableWidgetsVersions).mockResolvedValue({ results: [], count: 0, next_offset: null })+ jest.mocked(reusableWidgetsVersions).mockResolvedValue({+ results: [],+ count: 0,+ next: null,+ previous: null,+ next_offset: null,+ })jest.mocked(reusableWidgetsStatus).mockResolvedValue(ready)jest.mocked(reusableWidgetsGenerate).mockResolvedValue({ ...ready, lifecycle_status: 'generating' })logic = reusableWidgetLogic({ widgetId: widget.id })diff --git a/products/notebooks/frontend/ReusableWidgetCatalog/reusableWidgetCatalogLogic.ts b/products/notebooks/frontend/ReusableWidgetCatalog/reusableWidgetCatalogLogic.tsindex ff182d8209bf..f9c0c3c5bb35 100644--- a/products/notebooks/frontend/ReusableWidgetCatalog/reusableWidgetCatalogLogic.ts+++ b/products/notebooks/frontend/ReusableWidgetCatalog/reusableWidgetCatalogLogic.ts@@ -72,7 +72,7 @@ export const reusableWidgetCatalogLogic = kea<reusableWidgetCatalogLogicType>([loadReusableWidgets: async (_, breakpoint) => {await breakpoint(250)if (!values.currentTeamId) {- return { results: [], count: 0, next_offset: null }+ return { results: [], count: 0, next: null, previous: null, next_offset: null }}const response = await reusableWidgetsList(String(values.currentTeamId), {search: values.search || undefined,diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.tsindex 427036abf0f3..f86257b50c27 100644--- a/products/notebooks/frontend/generated/api.schemas.ts+++ b/products/notebooks/frontend/generated/api.schemas.ts@@ -46,7 +46,20 @@ export interface ReusableWidgetSummaryApi {updated_at: string}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ReusableWidgetPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Reusable widgets in this page. */results: ReusableWidgetSummaryApi[]/** Total reusable widgets matching the search. */@@ -548,7 +561,20 @@ export interface WidgetSourceApi {source: string}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ReusableWidgetVersionPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Published versions, newest first. */results: ReusableWidgetVersionDetailApi[]/** Total number of published versions. */@@ -1589,7 +1615,20 @@ export interface WidgetVersionApi {build_hash: string | null}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface WidgetVersionPageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Versions ordered newest first. */results: WidgetVersionApi[]/**diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 95ccb76a37c9..38c4281fb253 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1100,6 +1100,7 @@ export interface CommentApi {}export interface PaginatedCommentListApi {+ count: number/** @nullable */next?: string | null/** @nullable */diff --git a/products/review_hog/backend/presentation/views/reviews.py b/products/review_hog/backend/presentation/views/reviews.pyindex b2edd6492166..0678739e0a8d 100644--- a/products/review_hog/backend/presentation/views/reviews.py+++ b/products/review_hog/backend/presentation/views/reviews.py@@ -16,6 +16,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.integration import github_rate_limited_response+from posthog.api.pagination import PageLinksSerializer, offset_page_linksfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.scoping.manager import resolve_effective_team_id@@ -395,7 +396,7 @@ class ReviewsTableParamsSerializer(serializers.Serializer):)-class ReviewReviewsTablePageSerializer(serializers.Serializer):+class ReviewReviewsTablePageSerializer(PageLinksSerializer):count = serializers.IntegerField(help_text="How many reviews match the scope and every filter, across all pages.")running_count = serializers.IntegerField(help_text="How many reviews have a run in flight under the scope and filters, ignoring `status`. "@@ -738,6 +739,13 @@ class ReviewPerspectiveStatsSerializer(serializers.Serializer):)+def _next_table_offset(offset: int, limit: int, count: int) -> int | None:+ next_offset = offset + limit+ if next_offset >= count or next_offset > MAX_REVIEWS_TABLE_OFFSET:+ return None+ return next_offset++class _PageEnvelopeSchema(AutoSchema):"""Stops drf-spectacular's list-view heuristic from wrapping the `list` response in an array.@@ -908,7 +916,13 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetlimit=filters["limit"],offset=filters["offset"],)- return Response(ReviewReviewsTablePageSerializer(page).data)+ data = ReviewReviewsTablePageSerializer(page).data+ offset, limit = filters["offset"], filters["limit"]+ next_offset = _next_table_offset(offset, limit, page.count)+ # Past the last row, `previous` points at the last page that holds rows, or is null when no row matches.+ links_offset = min(offset, page.count)+ data.update(offset_page_links(request, offset=links_offset, limit=limit, next_offset=next_offset))+ return Response(data)@extend_schema(parameters=[PerspectiveStatsParamsSerializer],diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.pyindex 99cee3b7acdf..ba5692f6835e 100644--- a/products/review_hog/backend/tests/test_reviews_api.py+++ b/products/review_hog/backend/tests/test_reviews_api.py@@ -1367,12 +1367,22 @@ class TestRecentReviewsAPI(APIBaseTest):mine = self.client.get(f"{self.url}table/").json()second_page = self.client.get(f"{self.url}table/", {"limit": 2, "offset": 1}).json()+ last_page = self.client.get(second_page["next"]).json()+ first_page = self.client.get(second_page["previous"]).json()+ past_end = self.client.get(f"{self.url}table/", {"limit": 2, "offset": 10}).json()+ back_from_past_end = self.client.get(past_end["previous"]).json()everyone = self.client.get(f"{self.url}table/", {"scope": "everyone"}).json()assert [row["pr_number"] for row in mine["results"]] == [4, 2, 1, 3]assert (mine["count"], mine["running_count"]) == (4, 2)assert [row["pr_number"] for row in second_page["results"]] == [2, 1]assert second_page["count"] == 4+ assert [row["pr_number"] for row in last_page["results"]] == [3]+ assert last_page["next"] is None+ assert [row["pr_number"] for row in first_page["results"]] == [4, 2]+ assert first_page["previous"] is None+ assert past_end["results"] == []+ assert [row["pr_number"] for row in back_from_past_end["results"]] == [1, 3]assert [row["pr_number"] for row in everyone["results"]] == [4, 6, 2, 1, 3]assert self.client.get(f"{self.url}table/", {"limit": 101}).status_code == 400diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.tsindex c8f610e30549..61d7228d1651 100644--- a/products/review_hog/frontend/generated/api.schemas.ts+++ b/products/review_hog/frontend/generated/api.schemas.ts@@ -1361,7 +1361,20 @@ export interface ReviewPRStatusApi {request_outcome: ReviewPRStatusRequestOutcomeApi | null}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ReviewReviewsTablePageApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** How many reviews match the scope and every filter, across all pages. */count: number/** How many reviews have a run in flight under the scope and filters, ignoring `status`. Labels the running quick filter without a second request. */diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 1428f66e0bd9..abd1707e846f 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -41,6 +41,7 @@ from rest_framework.response import Responsefrom posthog.schema import ProductKeyfrom posthog.api.documentation import FeatureFlagFiltersSchemaSerializer+from posthog.api.pagination import PageLinksSerializer, offset_page_linksfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.utils import action@@ -1008,7 +1009,7 @@ class SurveyResponsesQuerySerializer(serializers.Serializer):)-class SurveyResponsesListSerializer(serializers.Serializer):+class SurveyResponsesListSerializer(PageLinksSerializer):results = SurveyResponseRowSerializer(many=True, help_text="Survey response rows for the requested page.")has_more = serializers.BooleanField(help_text="True if more rows exist beyond the current page — fetch the next page with offset + limit."@@ -2947,6 +2948,8 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlif cleaned.get("exclude_archived"):exclude_uuids = get_archived_response_uuids(str(survey.id), self.team_id)+ limit = cleaned.get("limit", 100)+ offset = cleaned.get("offset", 0)rows, has_more = fetch_response_rows(survey=survey,team=self.team,@@ -2955,8 +2958,8 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlquestion_id=cleaned.get("question_id"),score_lte=cleaned.get("score_lte"),score_gte=cleaned.get("score_gte"),- limit=cleaned.get("limit", 100),- offset=cleaned.get("offset", 0),+ limit=limit,+ offset=offset,exclude_uuids=exclude_uuids,)@@ -2985,11 +2988,14 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlfor row in rows],"has_more": has_more,- "limit": cleaned.get("limit", 100),- "offset": cleaned.get("offset", 0),+ "limit": limit,+ "offset": offset,})- return Response(serialized.data)+ data = serialized.data+ next_offset = offset + limit if has_more else None+ data.update(offset_page_links(request, offset=offset, limit=limit, next_offset=next_offset))+ return Response(data)@extend_schema(operation_id="surveys_question_labels",diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 3cfb668b55ba..4be196ca7068 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -7619,11 +7619,14 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):data = response.json()self.assertEqual(len(data["results"]), 2)self.assertTrue(data["has_more"])+ self.assertIsNone(data["previous"])- response2 = self.client.get(self.url, {"limit": "2", "offset": "2"})+ response2 = self.client.get(data["next"])data2 = response2.json()self.assertEqual(len(data2["results"]), 1)+ self.assertNotIn(data2["results"][0]["uuid"], [row["uuid"] for row in data["results"]])self.assertFalse(data2["has_more"])+ self.assertIsNone(data2["next"])def test_since_filter(self):create_person(team=self.team, distinct_ids=["old"])diff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.tsindex 7ebc3a6a9c2e..abb62771041d 100644--- a/products/surveys/frontend/generated/api.schemas.ts+++ b/products/surveys/frontend/generated/api.schemas.ts@@ -2359,7 +2359,20 @@ export interface SurveyResponseRowApi {extra: SurveyResponseExtraApi}+/**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface SurveyResponsesListApi {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null/** Survey response rows for the requested page. */results: SurveyResponseRowApi[]/** True if more rows exist beyond the current page — fetch the next page with offset + limit. */diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 7fe05c5156bc..6a111c18dc37 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -3069,10 +3069,22 @@ class TaskActivityPageSerializer(DataclassSerializer):required=False,help_text="Activity ID to pass as before_id for the next page, or null on the final page.",)+ next = serializers.URLField(+ read_only=True,+ allow_null=True,+ default=None,+ help_text="URL of the next page, with before and before_id set, or null on the final page.",+ )+ previous = serializers.URLField(+ read_only=True,+ allow_null=True,+ default=None,+ help_text="Always null: the feed pages forward only.",+ )class Meta:dataclass = TaskActivityPageDTO- fields = ["results", "unread_count", "next_before", "next_before_id"]+ fields = ["results", "unread_count", "next_before", "next_before_id", "next", "previous"]class TaskActivityReadMarkerSerializer(serializers.Serializer):diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.pyindex 98115ae8d680..a967a0a63707 100644--- a/products/tasks/backend/presentation/views/channels_api.py+++ b/products/tasks/backend/presentation/views/channels_api.py@@ -12,6 +12,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.mixins import validated_request+from posthog.api.pagination import page_link_with_paramsfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.models import OrganizationMembership@@ -744,7 +745,11 @@ class TaskActivityViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):before=request.validated_query_data.get("before"),before_id=request.validated_query_data.get("before_id"),)- return Response(TaskActivityPageSerializer(activity).data)+ data = TaskActivityPageSerializer(activity).data+ if data["next_before"] is not None:+ next_params = {"before": data["next_before"], "before_id": data["next_before_id"]}+ data["next"] = page_link_with_params(request, next_params)+ return Response(data)# @extend_schema must sit OUTSIDE @action: DRF's @action resets func.kwargs, wiping any schema# annotation applied earlier — including @validated_request's — from the generated OpenAPI.diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex 084e612de371..f5b0cc668519 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -1471,17 +1471,11 @@ class TaskActivityAPITestCase(ChannelTaskAPITestCase):self.assertEqual([row["task_id"] for row in rows], [str(second.id), str(self.task.id)])first_page = self.author_client.get(self._activity_url(), {"limit": 1}).json()self.assertEqual([row["task_id"] for row in first_page["results"]], [str(second.id)])- second_page = self.author_client.get(- self._activity_url(),- {- "limit": 1,- "before": first_page["next_before"],- "before_id": first_page["next_before_id"],- },- ).json()+ second_page = self.author_client.get(first_page["next"]).json()self.assertEqual([row["task_id"] for row in second_page["results"]], [str(self.task.id)])self.assertIsNone(second_page["next_before"])self.assertIsNone(second_page["next_before_id"])+ self.assertIsNone(second_page["next"])def test_mark_read_rejects_an_empty_task_list(self):response = self.author_client.post(self._activity_url() + "mark_read/", {"activities": []}, format="json")diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex ec68025caf97..d6256c416f53 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -422,6 +422,16 @@ export interface TaskActivityPageDTOApi {* @nullable*/next_before_id?: string | null+ /**+ * URL of the next page, with before and before_id set, or null on the final page.+ * @nullable+ */+ readonly next: string | null+ /**+ * Always null: the feed pages forward only.+ * @nullable+ */+ readonly previous: string | null}export interface TaskActivityReadMarkerApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 73167120667d..9aa577a11476 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58180,7 +58180,20 @@ export namespace Schemas {personal_github_connected: boolean;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubBranchesResponse {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** List of branch names */branches: string[];/**@@ -58335,7 +58348,20 @@ export namespace Schemas {installation_status: InstallationStatusEnum;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubReposResponse {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;repositories: GitHubRepo[];/** Whether more repositories are available beyond this page. */has_more: boolean;@@ -58373,7 +58399,20 @@ export namespace Schemas {name: string;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface GitHubTeamsResponse {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** List of GitHub teams available to the installation organization. */teams: GitHubTeam[];/** Whether more teams are available beyond this page. */@@ -75879,7 +75918,20 @@ export namespace Schemas {prompt_version: string | null;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineExperimentPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Total authorized rows matching the filters, independent of this page. */count: number;/**@@ -76015,7 +76067,20 @@ export namespace Schemas {summary: OfflineScorerSummary;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineHistoryPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Total authorized rows matching the filters, independent of this page. */count: number;/**@@ -76144,7 +76209,20 @@ export namespace Schemas {results: OfflineResultCell[];}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineItemPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Total authorized rows matching the filters, independent of this page. */count: number;/**@@ -76231,7 +76309,20 @@ export namespace Schemas {scorer: OfflineScorerVersionRead;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineResultPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Total authorized rows matching the filters, independent of this page. */count: number;/**@@ -76263,7 +76354,20 @@ export namespace Schemas {data: OfflineEvaluationResultPayloadInput | null;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface OfflineSummaryPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Total authorized rows matching the filters, independent of this page. */count: number;/**@@ -77881,6 +77985,7 @@ export namespace Schemas {}export interface PaginatedCommentList {+ count: number;/** @nullable */next?: string | null;/** @nullable */@@ -78827,12 +78932,32 @@ export namespace Schemas {}export interface PaginatedMCPSessionList {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ next: string | null;+ /**+ * URL of the previous page, or null on the first page.+ * @nullable+ */+ previous: string | null;results: MCPSession[];/** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */has_next: boolean;}export interface PaginatedMCPToolCallList {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ next: string | null;+ /**+ * URL of the previous page, or null on the first page.+ * @nullable+ */+ previous: string | null;results: MCPToolCall[];/** Whether more results exist beyond this page; the client fetches the next page with a larger offset. */has_next: boolean;@@ -106701,7 +106826,20 @@ export namespace Schemas {updated_at: string;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ReusableWidgetPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Reusable widgets in this page. */results: ReusableWidgetSummary[];/** Total reusable widgets matching the search. */@@ -106746,7 +106884,20 @@ export namespace Schemas {expected_current_version_id: string;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ReusableWidgetVersionPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Published versions, newest first. */results: ReusableWidgetVersionDetail[];/** Total number of published versions. */@@ -107879,7 +108030,20 @@ export namespace Schemas {body: string;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ReviewReviewsTablePage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** How many reviews match the scope and every filter, across all pages. */count: number;/** How many reviews have a run in flight under the scope and filters, ignoring `status`. Labels the running quick filter without a second request. */@@ -109440,7 +109604,20 @@ export namespace Schemas {readonly created_by: UserBasic | null;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface ScoreDefinitionVersionPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Total immutable versions for this scorer. */count: number;/**@@ -113465,7 +113642,20 @@ export namespace Schemas {is_private_without_access: boolean;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface SlackChannelsResponse {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Slack channels visible to the PostHog Slack app. */channels: SlackChannel[];/**@@ -113658,7 +113848,20 @@ export namespace Schemas {display_name: string;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface SlackUsersResponse {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Human Slack workspace members the PostHog Slack app can DM. */users: SlackUser[];/**@@ -119459,7 +119662,20 @@ export namespace Schemas {extra: SurveyResponseExtra;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface SurveyResponsesList {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Survey response rows for the requested page. */results: SurveyResponseRow[];/** True if more rows exist beyond the current page — fetch the next page with offset + limit. */@@ -120087,6 +120303,16 @@ export namespace Schemas {* @nullable*/next_before_id?: string | null;+ /**+ * URL of the next page, with before and before_id set, or null on the final page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * Always null: the feed pages forward only.+ * @nullable+ */+ readonly previous: string | null;}/**@@ -125830,7 +126056,20 @@ export namespace Schemas {build_hash: string | null;}+ /**+ * Declares the `next` and `previous` links of a page response that the view fills with `page_link`.+ */export interface WidgetVersionPage {+ /**+ * URL of the next page, or null on the last page.+ * @nullable+ */+ readonly next: string | null;+ /**+ * URL of the previous page, or null on the first page and on lists that page forward only.+ * @nullable+ */+ readonly previous: string | null;/** Versions ordered newest first. */results: WidgetVersion[];/**