: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
feat(warehouse_sources): support Browser Use API version v4 (#80102)
Tom Owers6d1bd7c64085
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/browser_use.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/browser_use.pyindex d23a7c46aab4..20f4829807c6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/browser_use.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/browser_use.py@@ -4,8 +4,9 @@ from typing import Any, Optionalfrom requests import Request, Response, Sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import (- BROWSER_USE_ENDPOINTS,+ BROWSER_USE_API_VERSION_V3,BrowserUseEndpointConfig,+ endpoints_for_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -23,14 +24,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-BROWSER_USE_BASE_URL = "https://api.browser-use.com/api/v3"+BROWSER_USE_API_HOST = "https://api.browser-use.com"API_KEY_HEADER = "X-Browser-Use-API-Key"+def _base_url(api_version: str) -> str:+ # The version is a URL path segment; auth and host are identical across versions.+ return f"{BROWSER_USE_API_HOST}/api/{api_version}"+++# v3 base URL, kept as a module constant: it's what the credential probe and non-retryable error+# matcher pin to (both are host-scoped, so v3 stands in for every version there).+BROWSER_USE_BASE_URL = _base_url(BROWSER_USE_API_VERSION_V3)++@dataclasses.dataclassclass BrowserUseResumeConfig:- # Next 1-indexed page/pageNumber to fetch for a top-level list endpoint. None for fan-out.+ # Next 1-indexed page/pageNumber to fetch for an offset-paged top-level endpoint. None otherwise.page: int | None = None+ # Next opaque keyset cursor for a v4 top-level endpoint (sessions, runs). None otherwise.+ cursor: str | None = None# Legacy fan-out bookmark fields (session id + `after` message cursor). Kept with defaults so# state saved before the framework migration still parses; such state restarts the fan-out# fresh (merge dedupes the re-pulled rows on the [sessionId, id] primary key).@@ -157,13 +170,76 @@ class BrowserUseMessagesPaginator(BasePaginator):return f"BrowserUseMessagesPaginator(after={self._after})"-# Params the two list-pagination styles use: (page param, page-size param, total-items body key).+class BrowserUseKeysetPaginator(BasePaginator):+ """Keyset cursor pagination for the v4 list endpoints (`GET /sessions`, `GET /runs`).++ The cursor is an opaque server token echoed back in the body as ``nextCursor`` (not the last+ row's id, unlike ``BrowserUseMessagesPaginator``), and ``hasMore`` is the stop signal — a page+ with rows but ``hasMore: false`` terminates.+ """++ def __init__(self, cursor_param: str = "cursor", next_cursor_key: str = "nextCursor") -> None:+ super().__init__()+ self.cursor_param = cursor_param+ self.next_cursor_key = next_cursor_key+ self._cursor: Optional[str] = None++ def _inject(self, request: Request) -> None:+ if self._cursor is not None:+ if request.params is None:+ request.params = {}+ request.params[self.cursor_param] = self._cursor++ def init_request(self, request: Request) -> None:+ self._inject(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ has_more = False+ next_cursor: Any = None+ try:+ body = response.json()+ if isinstance(body, dict):+ has_more = bool(body.get("hasMore"))+ next_cursor = body.get(self.next_cursor_key)+ except Exception:+ has_more = False++ if has_more and next_cursor:+ self._cursor = str(next_cursor)+ self._has_next_page = True+ else:+ self._has_next_page = False++ def update_request(self, request: Request) -> None:+ self._inject(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self._cursor} if self._has_next_page and self._cursor is not None else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor is not None:+ self._cursor = str(cursor)+ self._has_next_page = True++ def __str__(self) -> str:+ return f"BrowserUseKeysetPaginator(cursor={self._cursor})"+++# Params the offset-paging styles use: (page param, page-size param, total-items body key)._PAGINATION_PARAMS: dict[str, tuple[str, str, str]] = {"page": ("page", "page_size", "total"),"pageNumber": ("pageNumber", "pageSize", "totalItems"),}+def _list_size_param(config: BrowserUseEndpointConfig) -> str:+ # The page-size query param name for a list endpoint, keyed off its pagination style.+ if config.pagination == "keyset":+ return "limit"+ return _PAGINATION_PARAMS[config.pagination][1]++def _make_session(api_key: str) -> Session:# capture=False: session titles and session_messages.data hold arbitrary user/agent content the# name-based scrubbers can't recognise, so exclude the bodies from HTTP sample capture entirely.@@ -173,9 +249,9 @@ def _make_session(api_key: str) -> Session:return make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)-def _client_config(api_key: str) -> ClientConfig:+def _client_config(api_key: str, base_url: str) -> ClientConfig:return {- "base_url": BROWSER_USE_BASE_URL,+ "base_url": base_url,"headers": {"Accept": "application/json"},# Auth via the framework config so the key is registered for log redaction."auth": {"type": "api_key", "api_key": api_key, "name": API_KEY_HEADER, "location": "header"},@@ -184,6 +260,17 @@ def _client_config(api_key: str) -> ClientConfig:def _list_endpoint_resource(config: BrowserUseEndpointConfig) -> EndpointResource:+ if config.pagination == "keyset":+ return {+ "name": config.name,+ "endpoint": {+ "path": config.path,+ "params": {_list_size_param(config): config.page_size},+ "data_selector": config.data_key,+ "paginator": BrowserUseKeysetPaginator(),+ },+ }+page_param, size_param, total_key = _PAGINATION_PARAMS[config.pagination]return {"name": config.name,@@ -214,12 +301,14 @@ def browser_use_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[BrowserUseResumeConfig],+ api_version: str,) -> SourceResponse:- config = BROWSER_USE_ENDPOINTS[endpoint]+ catalog = endpoints_for_version(api_version)+ config = catalog[endpoint]resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonerest_config: RESTAPIConfig = {- "client": _client_config(api_key),+ "client": _client_config(api_key, _base_url(api_version)),"resource_defaults": {},"resources": [],}@@ -233,7 +322,7 @@ def browser_use_source(if state is not None:resumable_source_manager.save_state(BrowserUseResumeConfig(fanout_state=state))- sessions_config = BROWSER_USE_ENDPOINTS["sessions"]+ sessions_config = catalog["sessions"]rest_config["resources"] = [_list_endpoint_resource(sessions_config),{@@ -261,13 +350,22 @@ def browser_use_source()resource = next(r for r in resources if r.name == config.name)else:- initial_paginator_state = {"page": resume.page} if resume is not None and resume.page else None+ # Keyset (v4) and offset (v3) top-level lists checkpoint different state shapes. Both hooks+ # fire AFTER a page is yielded and persist only when a next page remains, so a crash+ # re-yields the last page (merge dedupes) rather than skipping it.+ initial_paginator_state: Optional[dict[str, Any]]+ if config.pagination == "keyset":+ initial_paginator_state = {"cursor": resume.cursor} if resume is not None and resume.cursor else None++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("cursor") is not None:+ resumable_source_manager.save_state(BrowserUseResumeConfig(cursor=str(state["cursor"])))+ else:+ initial_paginator_state = {"page": resume.page} if resume is not None and resume.page else None- def save_page_checkpoint(state: Optional[dict[str, Any]]) -> None:- # Persist only when a next page remains; the hook fires AFTER a page is yielded so a- # crash re-yields the last page (merge dedupes) rather than skipping it.- if state and state.get("page") is not None:- resumable_source_manager.save_state(BrowserUseResumeConfig(page=int(state["page"])))+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(BrowserUseResumeConfig(page=int(state["page"])))rest_config["resources"] = [_list_endpoint_resource(config)]resource = rest_api_resource(@@ -275,7 +373,7 @@ def browser_use_source(team_id,job_id,None,- resume_hook=save_page_checkpoint,+ resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)@@ -295,12 +393,16 @@ def browser_use_source()-def validate_credentials(api_key: str) -> bool:- # The cheapest genuine token probe: list a single session. 200 means the key is accepted.- # The probe session shares the export path's capture/redirect posture (see _make_session).+def validate_credentials(api_key: str, api_version: str) -> bool:+ # The cheapest genuine token probe: list a single session on the pinned version. 200 means the+ # key is accepted. `/sessions` exists in every version, and the size-param name is derived from+ # that version's own config (v3 page_size, v4 limit). The probe session shares the export+ # path's capture/redirect posture (see _make_session).+ sessions = endpoints_for_version(api_version)["sessions"]+ url = f"{_base_url(api_version)}{sessions.path}?{_list_size_param(sessions)}=1"ok, _status = validate_via_probe(lambda: _make_session(api_key),- f"{BROWSER_USE_BASE_URL}/sessions?page_size=1",+ url,headers={API_KEY_HEADER: api_key, "Accept": "application/json"},)return okdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/canonical_descriptions.pyindex aa6a55937dc0..7323296ce082 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/canonical_descriptions.py@@ -2,17 +2,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.canCanonicalDescriptions,)-# Descriptions taken from the Browser Use v3 OpenAPI spec-# (https://api.browser-use.com/api/v3/openapi.json). Partial coverage is fine — any column not-# listed here falls back to LLM enrichment.+# Descriptions taken from the Browser Use v3 and v4 OpenAPI specs+# (https://api.browser-use.com/api/v3/openapi.json, https://api.browser-use.com/api/v4/openapi.json).+# Keyed by table name and shared across versions; partial coverage is fine — any column absent from+# a version's response (or not listed here) falls back to LLM enrichment. v4 slimmed `sessions` and+# moved the per-run model/token/cost fields onto the new `runs` table._DOCS_URL = "https://docs.browser-use.com/api-reference"CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"sessions": {- "description": "A hosted agent run on Browser Use Cloud, with its status, model, step count, token usage, and per-run costs.",+ "description": "A hosted agent session on Browser Use Cloud, with its status, task, and the workspace it belongs to.","docs_url": _DOCS_URL,"columns": {"id": "Unique identifier for the agent session.",+ "sessionId": "Unique identifier for the agent session.",+ "latestRunId": "Identifier of the most recent run within the session.",+ "task": "Natural-language task the agent was asked to perform.","status": "Current lifecycle status of the agent session.","model": "LLM model the agent used for this session.","title": "Human-readable title of the session.",@@ -30,6 +35,27 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updatedAt": "Timestamp when the session was last updated.",},},+ "runs": {+ "description": "An individual agent run on Browser Use Cloud (v4), with its model, status, result, token usage, and cost.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the run.",+ "sessionId": "Identifier of the session this run belongs to.",+ "workspaceId": "Identifier of the workspace the run belongs to.",+ "task": "Natural-language task the agent was asked to perform.",+ "title": "Human-readable title of the run.",+ "model": "LLM model the agent used for this run.",+ "contextLimit": "Context window size, in tokens, available to the model.",+ "status": "Current lifecycle status of the run.",+ "result": "Final result the agent produced, if the run completed.",+ "error": "Error message if the run failed.",+ "totalInputTokens": "Total LLM input tokens consumed by the run.",+ "totalOutputTokens": "Total LLM output tokens produced during the run.",+ "totalCostUsd": "Total cost for the run, in USD.",+ "createdAt": "Timestamp when the run was created.",+ "updatedAt": "Timestamp when the run was last updated.",+ },+ },"browser_sessions": {"description": "A hosted browser instance backing agent runs, with its start/finish timestamps, proxy usage, and costs.","docs_url": _DOCS_URL,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/settings.pyindex 050f605d7efe..928cefc73e5b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/settings.py@@ -2,13 +2,23 @@ from dataclasses import dataclass, fieldfrom typing import Literal, Optional# Field names, pagination params, and response envelopes below were taken from the Browser Use-# v3 OpenAPI spec (https://api.browser-use.com/api/v3/openapi.json) and confirmed against the-# live API. The v3 list endpoints expose no server-side created/updated-since filter and no sort+# v3 and v4 OpenAPI specs (https://api.browser-use.com/api/v3/openapi.json,+# https://api.browser-use.com/api/v4/openapi.json) and confirmed against the live API. No list+# endpoint in either version exposes a server-side created/updated-since filter or a sort# parameter, so every endpoint syncs full-refresh only (see get_schemas) and no incremental cursor# is declared. Partition keys use required, immutable creation-time fields so partitions never# rewrite on later syncs.-PaginationStyle = Literal["page", "pageNumber", "cursor"]+# Vendor API versions. The version is a URL path segment (`/api/<version>`), so it is also the+# request layer's version constant. v3 was the experimental agent API; v4 is the current default.+BROWSER_USE_API_VERSION_V3 = "v3"+BROWSER_USE_API_VERSION_V4 = "v4"++# "page"/"pageNumber" -> 1-indexed offset paging with a total-items count.+# "cursor" -> `after=<last row id>` + `hasMore` flag (v3 GET /sessions/{id}/messages).+# "keyset" -> `cursor=<opaque token>` + `limit`, with `nextCursor`/`hasMore` in the body+# (v4 GET /sessions and GET /runs — v4 dropped the offset+count model for scale).+PaginationStyle = Literal["page", "pageNumber", "cursor", "keyset"]@dataclass@@ -78,3 +88,55 @@ BROWSER_USE_ENDPOINTS: dict[str, BrowserUseEndpointConfig] = {}ENDPOINTS = tuple(BROWSER_USE_ENDPOINTS.keys())++# v4 reshapes what v3 served. `GET /sessions` moved to keyset pagination and is now a slim+# container (the per-run model/token/cost fields moved onto the new `GET /runs` resource, synced+# here as the `runs` table). `GET /browsers` and `GET /profiles` are unchanged from v3. Two v3+# resources have no v4 list endpoint and so are absent here: the `GET /workspaces` list (v4 only+# exposes a single-workspace GET) and `GET /sessions/{id}/messages` (removed entirely). The table+# name set therefore differs from v3 by design — a v4-pinned source discovers only what v4 serves.+BROWSER_USE_ENDPOINTS_V4: dict[str, BrowserUseEndpointConfig] = {+ "sessions": BrowserUseEndpointConfig(+ name="sessions",+ path="/sessions",+ data_key="sessions",+ pagination="keyset",+ primary_keys=["sessionId"],+ partition_key="createdAt",+ ),+ # Agent runs — status, model, token usage, and per-run cost. Carries the fields v3 kept on+ # `sessions`, so it stays on by default to preserve that data for new sources.+ "runs": BrowserUseEndpointConfig(+ name="runs",+ path="/runs",+ data_key="runs",+ pagination="keyset",+ partition_key="createdAt",+ ),+ "browser_sessions": BrowserUseEndpointConfig(+ name="browser_sessions",+ path="/browsers",+ data_key="items",+ pagination="pageNumber",+ partition_key="startedAt",+ ),+ "profiles": BrowserUseEndpointConfig(+ name="profiles",+ path="/profiles",+ data_key="items",+ pagination="pageNumber",+ partition_key="createdAt",+ ),+}++ENDPOINTS_BY_VERSION: dict[str, dict[str, BrowserUseEndpointConfig]] = {+ BROWSER_USE_API_VERSION_V3: BROWSER_USE_ENDPOINTS,+ BROWSER_USE_API_VERSION_V4: BROWSER_USE_ENDPOINTS_V4,+}+++def endpoints_for_version(api_version: str) -> dict[str, BrowserUseEndpointConfig]:+ try:+ return ENDPOINTS_BY_VERSION[api_version]+ except KeyError as e:+ raise ValueError(f"Unsupported Browser Use API version: {api_version!r}") from ediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/source.pyindex cb159d95846a..7d4e55b7a5c6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/source.py@@ -15,8 +15,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.browser_usvalidate_credentials as validate_browser_use_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import (- BROWSER_USE_ENDPOINTS,- ENDPOINTS,+ BROWSER_USE_API_VERSION_V3,+ BROWSER_USE_API_VERSION_V4,+ endpoints_for_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (@@ -38,8 +39,11 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass BrowserUseSource(ResumableSource[BrowserUseSourceConfig, BrowserUseResumeConfig]):lists_tables_without_credentials = True # static endpoint catalog — safe for public docs- supported_versions = ("v3",)- default_version = "v3"+ # v3 was the experimental agent API; v4 is the current default. The two serve different table+ # sets (v4 drops the workspaces list and session_messages, adds runs, and reshapes sessions),+ # so new sources default to v4 while existing v3-pinned sources keep working unchanged.+ supported_versions = (BROWSER_USE_API_VERSION_V3, BROWSER_USE_API_VERSION_V4)+ default_version = BROWSER_USE_API_VERSION_V4api_docs_url = "https://docs.browser-use.com/cloud/api-reference"@property@@ -101,17 +105,19 @@ You can create a non-expiring API key at [cloud.browser-use.com/settings](https:force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # The Browser Use v3 list endpoints expose no server-side created/updated-since filter and- # no sort parameter, so there is no reliable way to fetch only new rows. Every endpoint is- # therefore full-refresh only (no incremental fields declared) — declaring incremental- # would advertise a mode that still scans the whole list each run.+ # No Browser Use list endpoint (either version) exposes a server-side since-filter or sort+ # parameter, so there is no reliable way to fetch only new rows. Every endpoint is therefore+ # full-refresh only (no incremental fields declared) — declaring incremental would advertise+ # a mode that still scans the whole list each run. The v3 and v4 table sets differ, so a+ # pinned source must discover under its own version: discovery diffs run under the source+ # pin and would orphan tables absent from the other version's catalog.+ catalog = endpoints_for_version(self.resolve_api_version(api_version))return build_endpoint_schemas(- ENDPOINTS,+ catalog.keys(),{},names,should_sync_default={- endpoint: endpoint_config.should_sync_default- for endpoint, endpoint_config in BROWSER_USE_ENDPOINTS.items()+ endpoint: endpoint_config.should_sync_default for endpoint, endpoint_config in catalog.items()},)@@ -122,7 +128,9 @@ You can create a non-expiring API key at [cloud.browser-use.com/settings](https:schema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- if validate_browser_use_credentials(config.api_key):+ # Pre-creation calls pass no pin and resolve to default_version (what new rows are stamped+ # with); a pinned source revalidates against its own version's probe endpoint.+ if validate_browser_use_credentials(config.api_key, self.resolve_api_version(api_version)):return True, Nonereturn False, "Invalid Browser Use API key"@@ -136,8 +144,9 @@ You can create a non-expiring API key at [cloud.browser-use.com/settings](https:resumable_source_manager: ResumableSourceManager[BrowserUseResumeConfig],inputs: SourceInputs,) -> SourceResponse:- if inputs.schema_name not in BROWSER_USE_ENDPOINTS:- raise ValueError(f"Unknown Browser Use schema '{inputs.schema_name}'")+ api_version = self.resolve_api_version(inputs.api_version)+ if inputs.schema_name not in endpoints_for_version(api_version):+ raise ValueError(f"Unknown Browser Use schema '{inputs.schema_name}' for API version {api_version}")return browser_use_source(api_key=config.api_key,@@ -145,4 +154,5 @@ You can create a non-expiring API key at [cloud.browser-use.com/settings](https:team_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ api_version=api_version,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use.pyindex c4636faa39ee..2adbaea022bd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use.py@@ -14,7 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.browser_usbrowser_use_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import BROWSER_USE_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import (+ BROWSER_USE_API_VERSION_V3,+ BROWSER_USE_API_VERSION_V4,+ BROWSER_USE_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (RESTClient,RESTClientRetryableError,@@ -60,9 +64,14 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,return snapshots-def _source(endpoint: str, manager: mock.MagicMock | None = None):+def _source(endpoint: str, manager: mock.MagicMock | None = None, api_version: str = BROWSER_USE_API_VERSION_V3):return browser_use_source(- "bu_test", endpoint, team_id=1, job_id="j", resumable_source_manager=manager or _make_manager()+ "bu_test",+ endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager or _make_manager(),+ api_version=api_version,)@@ -316,12 +325,12 @@ class TestValidateCredentials:@mock.patch(SESSION_PATCH)def test_status_maps_to_bool(self, _name: str, status: int, expected: bool, MockSession) -> None:MockSession.return_value.get.return_value = mock.MagicMock(status_code=status)- assert validate_credentials("bu_test") is expected+ assert validate_credentials("bu_test", BROWSER_USE_API_VERSION_V3) is expected@mock.patch(SESSION_PATCH)def test_network_error_is_false(self, MockSession) -> None:MockSession.return_value.get.side_effect = requests.ConnectionError("boom")- assert validate_credentials("bu_test") is False+ assert validate_credentials("bu_test", BROWSER_USE_API_VERSION_V3) is Falseclass TestSessionHardening:@@ -344,7 +353,7 @@ class TestSessionHardening:@mock.patch(SESSION_PATCH)def test_validate_credentials_disables_capture_and_redirects(self, MockSession) -> None:MockSession.return_value.get.return_value = mock.MagicMock(status_code=200)- validate_credentials("bu_test")+ validate_credentials("bu_test", BROWSER_USE_API_VERSION_V3)kwargs = MockSession.call_args.kwargsassert kwargs["capture"] is False@@ -373,3 +382,113 @@ class TestSourceResponse:assert response.partition_keys == [partition_key]assert response.partition_mode == "datetime"assert response.sort_mode == "asc"+++V4_BASE_URL = "https://api.browser-use.com/api/v4"+++class TestVersionRouting:+ @parameterized.expand(+ [+ (BROWSER_USE_API_VERSION_V3, "sessions", "sessions", {"total": 1}),+ (BROWSER_USE_API_VERSION_V3, "browser_sessions", "items", {"totalItems": 1}),+ (BROWSER_USE_API_VERSION_V4, "sessions", "sessions", {"hasMore": False}),+ (BROWSER_USE_API_VERSION_V4, "runs", "runs", {"hasMore": False}),+ (BROWSER_USE_API_VERSION_V4, "browser_sessions", "items", {"totalItems": 1}),+ (BROWSER_USE_API_VERSION_V4, "profiles", "items", {"totalItems": 1}),+ ]+ )+ @mock.patch(SESSION_PATCH)+ def test_request_hits_versioned_base_url(+ self, version: str, endpoint: str, data_key: str, extra: dict[str, Any], MockSession+ ) -> None:+ # The pinned version is the URL path segment, so each version's request must go to+ # /api/<version>/... — the whole point of pinning. A v4 endpoint left on the v3 base (or+ # vice versa) would silently hit the wrong API.+ session = MockSession.return_value+ params = _wire(session, [_response({data_key: [{"id": "a"}], **extra})])++ _rows(_source(endpoint, api_version=version))++ assert params[0]["url"].startswith(f"https://api.browser-use.com/api/{version}/")+++class TestV4KeysetPagination:+ @parameterized.expand([("sessions", "sessions"), ("runs", "runs")])+ @mock.patch(SESSION_PATCH)+ def test_keyset_pages_aggregated_and_terminates(self, endpoint: str, data_key: str, MockSession) -> None:+ # v4 sessions/runs use keyset paging: `limit` + a `cursor` echoed back as `nextCursor`, with+ # `hasMore` as the stop signal. Guards that the cursor advances from the body (not the row+ # id), that `limit` is sent, and that hasMore=false terminates.+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _response(+ {data_key: [{"id": "a"}], "nextCursor": "c1", "hasMore": True}, url=f"{V4_BASE_URL}/{endpoint}"+ ),+ _response(+ {data_key: [{"id": "b"}], "nextCursor": "c2", "hasMore": True}, url=f"{V4_BASE_URL}/{endpoint}"+ ),+ _response(+ {data_key: [{"id": "c"}], "nextCursor": None, "hasMore": False}, url=f"{V4_BASE_URL}/{endpoint}"+ ),+ ],+ )++ rows = _rows(_source(endpoint, api_version=BROWSER_USE_API_VERSION_V4))++ assert [r["id"] for r in rows] == ["a", "b", "c"]+ assert all(p["params"]["limit"] == 100 for p in params)+ assert [p["params"].get("cursor") for p in params] == [None, "c1", "c2"]++ @mock.patch(SESSION_PATCH)+ def test_keyset_saves_next_cursor_only_while_more_remain(self, MockSession) -> None:+ # The checkpoint advances to the body's nextCursor and saves only when a page follows, so a+ # crash re-yields the last page (merge dedupes) rather than skipping it.+ session = MockSession.return_value+ _wire(+ session,+ [+ _response({"sessions": [{"id": "a"}], "nextCursor": "c1", "hasMore": True}),+ _response({"sessions": [{"id": "b"}], "hasMore": False}),+ ],+ )++ manager = _make_manager()+ _rows(_source("sessions", manager, api_version=BROWSER_USE_API_VERSION_V4))++ manager.save_state.assert_called_once_with(BrowserUseResumeConfig(cursor="c1"))++ @mock.patch(SESSION_PATCH)+ def test_keyset_resumes_from_saved_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response({"sessions": [{"id": "x"}], "hasMore": False})])++ manager = _make_manager(BrowserUseResumeConfig(cursor="c9"))+ rows = _rows(_source("sessions", manager, api_version=BROWSER_USE_API_VERSION_V4))++ assert [r["id"] for r in rows] == ["x"]+ assert params[0]["params"]["cursor"] == "c9"+++class TestV4SourceResponse:+ @parameterized.expand(+ [+ ("sessions", ["sessionId"], "createdAt"),+ ("runs", ["id"], "createdAt"),+ ("browser_sessions", ["id"], "startedAt"),+ ("profiles", ["id"], "createdAt"),+ ]+ )+ @mock.patch(SESSION_PATCH)+ def test_primary_keys_and_partition(+ self, endpoint: str, primary_keys: list[str], partition_key: str, MockSession+ ) -> None:+ # v4 sessions key on `sessionId` (not `id`) — merge would collapse rows if this regressed.+ MockSession.return_value.headers = {}+ response = _source(endpoint, api_version=BROWSER_USE_API_VERSION_V4)++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == [partition_key]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use_source.pyindex 58caa26a5462..70d0387b676a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use_source.py@@ -7,6 +7,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.browser_usfrom products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.browser_use import (BrowserUseResumeConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import (+ BROWSER_USE_API_VERSION_V3,+ BROWSER_USE_API_VERSION_V4,+)from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.source import BrowserUseSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.browseruse import (BrowserUseSourceConfig,@@ -26,41 +30,57 @@ class TestBrowserUseSource:fields = self.source.get_source_config.fieldsassert [f.name for f in fields] == ["api_key"]+ def test_default_version_is_v4(self) -> None:+ # New sources must start on v4 (declared newest-last, default flipped to it) and, with no+ # pin, discover the v4 catalog.+ assert self.source.supported_versions == (BROWSER_USE_API_VERSION_V3, BROWSER_USE_API_VERSION_V4)+ assert self.source.default_version == BROWSER_USE_API_VERSION_V4+ names = {s.name for s in self.source.get_schemas(self.config, team_id=1)}+ assert names == {"sessions", "runs", "browser_sessions", "profiles"}+@parameterized.expand([- ("sessions", True),- ("browser_sessions", True),- ("profiles", True),- ("workspaces", True),- ("session_messages", False),+ (+ BROWSER_USE_API_VERSION_V3,+ {"sessions", "browser_sessions", "profiles", "workspaces", "session_messages"},+ ),+ (BROWSER_USE_API_VERSION_V4, {"sessions", "runs", "browser_sessions", "profiles"}),])- def test_schemas_are_full_refresh_only(self, endpoint: str, default_on: bool) -> None:- # The v3 list endpoints expose no server-side since-filter, so advertising incremental or- # append would offer a mode that still scans everything. session_messages fans out per- # session, so it must stay off by default to avoid surprise API cost.- schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}-- assert set(schemas) == {"sessions", "browser_sessions", "profiles", "workspaces", "session_messages"}- schema = schemas[endpoint]- assert schema.supports_incremental is False- assert schema.supports_append is False- assert schema.incremental_fields == []- assert schema.should_sync_default is default_on+ def test_schemas_match_version_catalog(self, version: str, expected: set[str]) -> None:+ # A pinned source discovers only its own version's tables — v4 drops the workspaces list and+ # session_messages and adds runs. No list endpoint in either version has a since-filter, so+ # advertising incremental/append would offer a mode that still scans everything.+ schemas = self.source.get_schemas(self.config, team_id=1, api_version=version)+ assert {s.name for s in schemas} == expected+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_session_messages_off_by_default_on_v3(self) -> None:+ # session_messages fans out one request per session, so it must stay opt-in to avoid+ # surprise API cost; the top-level lists stay on.+ schemas = {+ s.name: s for s in self.source.get_schemas(self.config, team_id=1, api_version=BROWSER_USE_API_VERSION_V3)+ }+ assert schemas["session_messages"].should_sync_default is False+ assert schemas["sessions"].should_sync_default is Truedef test_names_filter_narrows_schemas(self) -> None:schemas = self.source.get_schemas(self.config, team_id=1, names=["sessions"])assert [s.name for s in schemas] == ["sessions"]def test_documented_tables_render_for_public_docs(self) -> None:- # get_schemas is a static catalog, so lists_tables_without_credentials must surface the- # tables (with canonical descriptions) for the posthog.com Supported tables section.+ # Public docs render the default (v4) catalog, so lists_tables_without_credentials must+ # surface those tables (with canonical descriptions) for the posthog.com Supported tables+ # section — including the new runs table.assert self.source.lists_tables_without_credentials is Truetables = self.source.get_documented_tables()by_name = {t["name"]: t for t in tables}- assert set(by_name) == {"sessions", "browser_sessions", "profiles", "workspaces", "session_messages"}+ assert set(by_name) == {"sessions", "runs", "browser_sessions", "profiles"}assert by_name["sessions"]["sync_methods"] == ["Full refresh"]- assert by_name["sessions"]["description"]+ assert by_name["runs"]["description"]@parameterized.expand([@@ -87,9 +107,10 @@ class TestBrowserUseSource:manager = self.source.get_resumable_source_manager(inputs)assert manager._data_class is BrowserUseResumeConfig- def test_source_for_pipeline_passes_api_key_and_schema(self) -> None:+ def test_source_for_pipeline_passes_api_key_schema_and_resolved_version(self) -> None:inputs = mock.MagicMock()inputs.schema_name = "sessions"+ inputs.api_version = None # no pin resolves to the default (v4)manager = mock.MagicMock()with mock.patch.object(source_module, "browser_use_source") as mock_source:self.source.source_for_pipeline(self.config, manager, inputs)@@ -97,12 +118,24 @@ class TestBrowserUseSource:_, kwargs = mock_source.call_argsassert kwargs["api_key"] == "bu_test"assert kwargs["endpoint"] == "sessions"+ assert kwargs["api_version"] == BROWSER_USE_API_VERSION_V4def test_source_for_pipeline_rejects_unknown_schema(self) -> None:# An arbitrary schema name must raise a controlled ValueError rather than crashing the# worker with an uncaught KeyError when indexing the endpoint catalog.inputs = mock.MagicMock()inputs.schema_name = "not_a_real_endpoint"+ inputs.api_version = None+ manager = mock.MagicMock()+ with pytest.raises(ValueError, match="Unknown Browser Use schema"):+ self.source.source_for_pipeline(self.config, manager, inputs)++ def test_source_for_pipeline_rejects_schema_absent_in_pinned_version(self) -> None:+ # A v4-pinned source must not serve a v3-only endpoint: session_messages has no v4 list+ # endpoint, so requesting it under v4 must fail loudly rather than 404 mid-sync.+ inputs = mock.MagicMock()+ inputs.schema_name = "session_messages"+ inputs.api_version = BROWSER_USE_API_VERSION_V4manager = mock.MagicMock()with pytest.raises(ValueError, match="Unknown Browser Use schema"):self.source.source_for_pipeline(self.config, manager, inputs)