: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(data-warehouse): implement browser_use import source (#70021)
Tom Owers9c8ad533ec3d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 795dab26f79e..7658d28841be 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -85,6 +85,7 @@ the row lists both.| breezometer | HTTP | requests | ✅ || brevo | HTTP | requests | ✅ || brex | HTTP | requests | ✅ |+| browser_use | HTTP | requests | ✅ || browserbase | HTTP | requests | ✅ || bugsnag | HTTP | requests | ✅ || buildbetter | HTTP | requests | ✅ |@@ -535,7 +536,6 @@ doesn't conflict with concurrent PRs.- branch- breezy_hr- browse_ai-- browser_use- cal_com- campaign_manager_360- captain_datadiff --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.pynew file mode 100644index 000000000000..d2b69f4576b2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/browser_use.py@@ -0,0 +1,251 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import (+ BROWSER_USE_ENDPOINTS,+ BrowserUseEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++BROWSER_USE_BASE_URL = "https://api.browser-use.com/api/v3"+API_KEY_HEADER = "X-Browser-Use-API-Key"+REQUEST_TIMEOUT_SECONDS = 60+++class BrowserUseRetryableError(Exception):+ pass+++class BrowserUseResumeConfig:+ # Next 1-indexed page/pageNumber to fetch for a top-level list endpoint. None for fan-out.+ page: int | None = None+ # Fan-out (session_messages): the session currently being read. A stable session id (not a+ # positional index) so sessions added/removed between a crash and the retry can't resume us+ # into the wrong session.+ session_id: str | None = None+ # Fan-out: the `after` message-id cursor within the current session.+ after: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {API_KEY_HEADER: api_key, "Accept": "application/json"}+++def _build_url(path: str, params: dict[str, Any]) -> str:+ url = f"{BROWSER_USE_BASE_URL}{path}"+ clean = {k: v for k, v in params.items() if v is not None}+ return f"{url}?{urlencode(clean)}" if clean else url+++@retry(+ retry=retry_if_exception_type(+ (+ BrowserUseRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise BrowserUseRetryableError(f"Browser Use API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Log status + URL only. Error bodies can echo prompt/message content or other tenant data,+ # which must not land in application logs outside warehouse-table access controls.+ logger.error(f"Browser Use API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ # The cheapest genuine token probe: list a single session. 200 means the key is accepted.+ url = _build_url("/sessions", {"page_size": 1})+ try:+ # capture=False: the probe lists a session, whose body carries the same free-form agent+ # content as the export bodies below — keep it out of HTTP sample capture.+ # allow_redirects=False: the API key rides in a custom header that `requests` preserves+ # across cross-host 3xx (it only strips `Authorization`), so pin redirects off to keep the+ # key from replaying to a redirect target. The fixed API host never needs redirects.+ response = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False).get(+ url, headers=_get_headers(api_key), timeout=10+ )+ return response.status_code == 200+ except Exception:+ return False+++def _page_params(config: BrowserUseEndpointConfig, page: int) -> dict[str, Any]:+ if config.pagination == "page":+ return {"page": page, "page_size": config.page_size}+ return {"pageNumber": page, "pageSize": config.page_size}+++def _get_paged_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrowserUseResumeConfig],+ config: BrowserUseEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None and resume.page else 1++ while True:+ data = _fetch_page(session, _build_url(config.path, _page_params(config, page)), headers, logger)+ items = data.get(config.data_key) or []+ if not items:+ break++ yield items++ # `total`/`totalItems` gives an exact stopping point; without it, a short page (fewer rows+ # than requested) means we've reached the end. Save AFTER yielding so a crash re-yields the+ # last page rather than skipping it (merge dedupes on the primary key).+ total = data.get("total") if config.pagination == "page" else data.get("totalItems")+ if total is not None:+ has_more = page * config.page_size < total+ else:+ has_more = len(items) >= config.page_size++ if not has_more:+ break++ page += 1+ resumable_source_manager.save_state(BrowserUseResumeConfig(page=page))+++def _iter_session_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ page = 1+ while True:+ data = _fetch_page(session, _build_url("/sessions", {"page": page, "page_size": 100}), headers, logger)+ sessions = data.get("sessions") or []+ if not sessions:+ break++ for item in sessions:+ yield item["id"]++ total = data.get("total")+ if total is not None:+ if page * 100 >= total:+ break+ elif len(sessions) < 100:+ break++ page += 1+++def _get_session_message_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrowserUseResumeConfig],+ config: BrowserUseEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ session_ids = list(_iter_session_ids(session, headers, logger))++ # Resume only fast-forwards the message cursor *within* the session that was mid-read at the+ # crash; we deliberately re-walk every session rather than slicing the list from the bookmark.+ # The API guarantees no session ordering, so a session that reorders (or is newly inserted)+ # ahead of the bookmark between runs would be skipped for the whole resumed run if we sliced.+ # Re-pulling already-synced sessions is cheap correctness insurance — merge dedupes the rows on+ # the [sessionId, id] primary key.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ resume_session_id = resume.session_id if resume is not None else None+ resume_after = resume.after if resume is not None else None+ if resume_session_id is not None:+ logger.debug(f"Browser Use: resuming session_messages cursor within session_id={resume_session_id}")++ for index, session_id in enumerate(session_ids):+ # Only the bookmarked session continues from its saved cursor; every other session restarts.+ after = resume_after if session_id == resume_session_id else None+ path = config.path.format(session_id=session_id)++ while True:+ data = _fetch_page(session, _build_url(path, {"after": after, "limit": config.page_size}), headers, logger)+ messages = data.get(config.data_key) or []+ if messages:+ # Stamp the parent session id: the child endpoint may omit it from each message, but+ # it's half of the declared [sessionId, id] primary key, so the merge needs it present.+ yield [{**message, "sessionId": session_id} for message in messages]++ has_more = bool(data.get("hasMore")) and bool(messages)+ if not has_more:+ break++ after = messages[-1]["id"]+ resumable_source_manager.save_state(BrowserUseResumeConfig(session_id=session_id, after=after))++ # Advance the bookmark to the next session so a crash between sessions resumes correctly.+ if index + 1 < len(session_ids):+ resumable_source_manager.save_state(BrowserUseResumeConfig(session_id=session_ids[index + 1], after=None))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrowserUseResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = BROWSER_USE_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page (and, for fan-out, every child request) so urllib3 keeps+ # the connection alive instead of re-handshaking per request. Register the key for redaction so+ # the shared HTTP observer masks it anywhere it surfaces in captured URLs or samples.+ # 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.+ # allow_redirects=False: the API key rides in a custom header that `requests` preserves across+ # cross-host 3xx, so pin redirects off to keep it from replaying to a redirect target.+ session = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)++ if config.fan_out_over_sessions:+ yield from _get_session_message_rows(session, headers, logger, resumable_source_manager, config)+ else:+ yield from _get_paged_rows(session, headers, logger, resumable_source_manager, config)+++def browser_use_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BrowserUseResumeConfig],+) -> SourceResponse:+ config = BROWSER_USE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ # Full-refresh endpoints with no guaranteed API ordering; the watermark is not used, but+ # the batches arrive oldest-first within each page so "asc" is the honest default.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --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.pynew file mode 100644index 000000000000..aa6a55937dc0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/canonical_descriptions.py@@ -0,0 +1,84 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# 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.+_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.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the agent session.",+ "status": "Current lifecycle status of the agent session.",+ "model": "LLM model the agent used for this session.",+ "title": "Human-readable title of the session.",+ "stepCount": "Number of steps the agent took during the session.",+ "isTaskSuccessful": "Whether the agent reported the task as completed successfully.",+ "profileId": "Identifier of the browser profile used for this session.",+ "workspaceId": "Identifier of the workspace the session belongs to.",+ "totalInputTokens": "Total LLM input tokens consumed by the session.",+ "totalOutputTokens": "Total LLM output tokens produced during the session.",+ "llmCostUsd": "LLM cost for the session, in USD.",+ "proxyCostUsd": "Proxy cost for the session, in USD.",+ "browserCostUsd": "Browser cost for the session, in USD.",+ "totalCostUsd": "Total cost for the session, in USD.",+ "createdAt": "Timestamp when the session was created.",+ "updatedAt": "Timestamp when the session 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,+ "columns": {+ "id": "Unique identifier for the browser session.",+ "status": "Current status of the browser session.",+ "startedAt": "Timestamp when the browser session started.",+ "finishedAt": "Timestamp when the browser session finished, if it has ended.",+ "timeoutAt": "Timestamp when the browser session will time out.",+ "proxyUsedMb": "Proxy bandwidth consumed by the browser session, in megabytes.",+ "proxyCost": "Proxy cost for the browser session, in USD.",+ "browserCost": "Browser cost for the browser session, in USD.",+ "agentSessionId": "Identifier of the agent session this browser session is attached to.",+ },+ },+ "profiles": {+ "description": "A reusable browser profile that persists cookies and browsing state across agent sessions.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the browser profile.",+ "name": "Name of the profile.",+ "lastUsedAt": "Timestamp when the profile was last used by a session.",+ "cookieDomains": "Domains for which the profile stores cookies.",+ "createdAt": "Timestamp when the profile was created.",+ "updatedAt": "Timestamp when the profile was last updated.",+ },+ },+ "workspaces": {+ "description": "A workspace that groups agent sessions and their associated files.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the workspace.",+ "name": "Name of the workspace.",+ "createdAt": "Timestamp when the workspace was created.",+ "updatedAt": "Timestamp when the workspace was last updated.",+ },+ },+ "session_messages": {+ "description": "Individual agent steps/messages within a session, in the order they occurred.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the message.",+ "sessionId": "Identifier of the session the message belongs to.",+ "role": "Role that produced the message (e.g. user, assistant).",+ "data": "Message payload content.",+ "type": "Type of the message.",+ "summary": "Short summary of the step.",+ "hidden": "Whether the message is hidden from the default session view.",+ "createdAt": "Timestamp when the message was created.",+ },+ },+}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.pynew file mode 100644index 000000000000..050f605d7efe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/settings.py@@ -0,0 +1,80 @@+from dataclasses import dataclass, field+from 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+# 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"]+++@dataclass+class BrowserUseEndpointConfig:+ name: str+ path: str+ # Key in the JSON response body that holds the array of rows.+ data_key: str+ # "page" -> 1-indexed page + page_size (GET /sessions)+ # "pageNumber" -> 1-indexed pageNumber + pageSize (GET /browsers, /profiles, /workspaces)+ # "cursor" -> after=<uuid> + limit, with a hasMore flag (GET /sessions/{id}/messages)+ pagination: PaginationStyle+ # Every list endpoint caps the page size at 100.+ page_size: int = 100+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # A stable creation-time field to partition by; None disables partitioning for the endpoint.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ # When True, `path` is a template with a `{session_id}` placeholder and rows are gathered by+ # fanning out one paginated request per agent session.+ fan_out_over_sessions: bool = False+++BROWSER_USE_ENDPOINTS: dict[str, BrowserUseEndpointConfig] = {+ "sessions": BrowserUseEndpointConfig(+ name="sessions",+ path="/sessions",+ data_key="sessions",+ pagination="page",+ 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",+ ),+ "workspaces": BrowserUseEndpointConfig(+ name="workspaces",+ path="/workspaces",+ data_key="items",+ pagination="pageNumber",+ partition_key="createdAt",+ ),+ # Per-session agent steps. Fans out one cursor-paginated request per session, so it's opt-in+ # (off by default) to avoid the extra API cost when a user only wants session-level data. The+ # message id is a UUID, but the parent session id is kept in the composite key so a duplicated+ # id can never collapse rows across sessions.+ "session_messages": BrowserUseEndpointConfig(+ name="session_messages",+ path="/sessions/{session_id}/messages",+ data_key="messages",+ pagination="cursor",+ primary_keys=["sessionId", "id"],+ partition_key="createdAt",+ should_sync_default=False,+ fan_out_over_sessions=True,+ ),+}++ENDPOINTS = tuple(BROWSER_USE_ENDPOINTS.keys())diff --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 10c4f4f44565..9d3a5655a2d0 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@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.browser_use import (+ BrowserUseResumeConfig,+ browser_use_source,+ validate_credentials as validate_browser_use_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import (+ BROWSER_USE_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BrowserUseSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class BrowserUseSource(SimpleSource[BrowserUseSourceConfig]):+class BrowserUseSource(ResumableSource[BrowserUseSourceConfig, BrowserUseResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BROWSERUSE@@ -24,8 +47,97 @@ class BrowserUseSource(SimpleSource[BrowserUseSourceConfig]):name=SchemaExternalDataSourceType.BROWSER_USE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Browser Use",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Browser Use API key to automatically pull your Browser Use Cloud data into the PostHog Data warehouse.++You can create a non-expiring API key at [cloud.browser-use.com/settings](https://cloud.browser-use.com/settings).""",iconPath="/static/services/browser_use.png",+ docsUrl="https://posthog.com/docs/cdp/sources/browser-use",keywords=["browser automation", "ai agents", "agent runs", "web automation"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="bu_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked key surfaces as a requests HTTPError from raise_for_status.+ # Retrying can never satisfy a credential problem, so stop the sync. Match the stable+ # status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.browser-use.com": "Your Browser Use API key is invalid or has been revoked. Create a new key at cloud.browser-use.com/settings, then reconnect.",+ # A 403 means the key is valid but lacks access to the resource; retrying can never+ # satisfy a permission problem, so surface it as terminal too.+ "403 Client Error: Forbidden for url: https://api.browser-use.com": "Your Browser Use API key does not have permission to access this Browser Use resource. Check the key permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: BrowserUseSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> 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 — declaring incremental would advertise a mode that still+ # scans the whole list each run.+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = BROWSER_USE_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: BrowserUseSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_browser_use_credentials(config.api_key):+ return True, None++ return False, "Invalid Browser Use API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BrowserUseResumeConfig]:+ return ResumableSourceManager[BrowserUseResumeConfig](inputs, BrowserUseResumeConfig)++ def source_for_pipeline(+ self,+ config: BrowserUseSourceConfig,+ 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}'")++ return browser_use_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)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.pynew file mode 100644index 000000000000..b8752b4b98af--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use.py@@ -0,0 +1,335 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use import browser_use+from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.browser_use import (+ BrowserUseResumeConfig,+ browser_use_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use.settings import BROWSER_USE_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: BrowserUseResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[BrowserUseResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> BrowserUseResumeConfig | None:+ return self._state++ def save_state(self, data: BrowserUseResumeConfig) -> None:+ self.saved.append(data)+++def _run(endpoint: str, fetch: Any, manager: _FakeResumableManager | None = None) -> list[dict]:+ manager = manager or _FakeResumableManager()+ rows: list[dict] = []+ with patch.object(browser_use, "make_tracked_session", return_value=MagicMock()):+ with patch.object(browser_use, "_fetch_page", side_effect=fetch):+ for batch in get_rows(+ api_key="bu_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++def _paged_fetch(data_key: str, page_param: str, pages: list[list[dict]], include_total: bool):+ """A fetch stub that returns the page indexed by the request's page/pageNumber param."""+ requested: list[int] = []+ total = sum(len(p) for p in pages)++ def fetch(session: Any, url: str, headers: dict, logger: Any) -> dict:+ qs = parse_qs(urlparse(url).query)+ page = int(qs[page_param][0])+ requested.append(page)+ items = pages[page - 1] if page - 1 < len(pages) else []+ body: dict = {data_key: items}+ if include_total:+ body["total" if page_param == "page" else "totalItems"] = total+ return body++ fetch.requested = requested # type: ignore[attr-defined]+ return fetch+++class TestPagination:+ @parameterized.expand(+ [+ ("sessions", "sessions", "page"),+ ("browser_sessions", "items", "pageNumber"),+ ("profiles", "items", "pageNumber"),+ ("workspaces", "items", "pageNumber"),+ ]+ )+ def test_all_pages_aggregated_and_terminates(self, endpoint: str, data_key: str, page_param: str) -> None:+ # Two full pages (100 each) then a short page: guards both that every page is collected and+ # that a short page terminates the loop instead of paging forever.+ size = BROWSER_USE_ENDPOINTS[endpoint].page_size+ pages = [+ [{"id": f"a{i}"} for i in range(size)],+ [{"id": f"b{i}"} for i in range(size)],+ [{"id": "c0"}, {"id": "c1"}],+ ]+ fetch = _paged_fetch(data_key, page_param, pages, include_total=False)+ rows = _run(endpoint, fetch)++ assert len(rows) == size * 2 + 2+ assert fetch.requested == [1, 2, 3]++ def test_total_stops_before_an_empty_page(self) -> None:+ # A full final page whose count equals `total` must not trigger one more (empty) request.+ size = BROWSER_USE_ENDPOINTS["sessions"].page_size+ pages = [[{"id": f"a{i}"} for i in range(size)], [{"id": "b0"}]]+ fetch = _paged_fetch("sessions", "page", pages, include_total=True)+ rows = _run("sessions", fetch)++ assert len(rows) == size + 1+ assert fetch.requested == [1, 2]++ def test_correct_pagination_param_sent(self) -> None:+ # /browsers uses pageNumber/pageSize, not page/page_size — sending the wrong name would+ # silently return page 1 forever (or 422).+ seen: list[str] = []++ def fetch(session: Any, url: str, headers: dict, logger: Any) -> dict:+ seen.append(urlparse(url).query)+ return {"items": []}++ _run("browser_sessions", fetch)+ assert "pageNumber=1" in seen[0]+ assert "pageSize=100" in seen[0]++ def test_state_saved_after_each_yield(self) -> None:+ # Resume state must advance to the NEXT page and only be saved when more pages remain, so a+ # crash re-yields the last page rather than skipping it.+ size = BROWSER_USE_ENDPOINTS["sessions"].page_size+ pages = [[{"id": f"a{i}"} for i in range(size)], [{"id": "b0"}]]+ fetch = _paged_fetch("sessions", "page", pages, include_total=False)+ manager = _FakeResumableManager()+ _run("sessions", fetch, manager)++ # Only the first (full) page has a successor, so exactly one save advancing to page 2.+ assert [s.page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self) -> None:+ requested: list[int] = []++ def fetch(session: Any, url: str, headers: dict, logger: Any) -> dict:+ page = int(parse_qs(urlparse(url).query)["page"][0])+ requested.append(page)+ return {"sessions": [{"id": "p3"}] if page == 3 else []}++ manager = _FakeResumableManager(BrowserUseResumeConfig(page=3))+ rows = _run("sessions", fetch, manager)++ assert rows == [{"id": "p3"}]+ assert requested == [3]+++class TestSessionMessagesFanOut:+ def _fetch(self, sessions_pages: list[list[dict]], messages_by_session: dict[str, list[list[dict]]]):+ def fetch(session: Any, url: str, headers: dict, logger: Any) -> dict:+ parsed = urlparse(url)+ qs = parse_qs(parsed.query)+ if parsed.path.endswith("/sessions"):+ page = int(qs["page"][0])+ items = sessions_pages[page - 1] if page - 1 < len(sessions_pages) else []+ return {"sessions": items}+ # /sessions/{id}/messages+ session_id = parsed.path.split("/")[-2]+ batches = messages_by_session[session_id]+ after = qs.get("after", [None])[0]+ if after is None:+ batch = batches[0]+ else:+ # Find the batch after the one ending in `after`.+ idx = next(i for i, b in enumerate(batches) if b and b[-1]["id"] == after)+ batch = batches[idx + 1] if idx + 1 < len(batches) else []+ has_more = batch != batches[-1] and bool(batch)+ return {"messages": batch, "hasMore": has_more}++ return fetch++ def test_fans_out_over_sessions_with_cursor(self) -> None:+ # Two sessions, one paginated via the `after` cursor; every message must be collected and+ # stamped with its parent session id. The raw child payload omits `sessionId`, so the source+ # has to inject it — the composite [sessionId, id] primary key depends on it being present.+ sessions_pages = [[{"id": "s1"}, {"id": "s2"}]]+ messages = {+ "s1": [+ [{"id": "m1"}, {"id": "m2"}],+ [{"id": "m3"}],+ ],+ "s2": [[{"id": "m9"}]],+ }+ rows = _run("session_messages", self._fetch(sessions_pages, messages))++ assert [r["id"] for r in rows] == ["m1", "m2", "m3", "m9"]+ assert {r["id"] for r in rows if r["sessionId"] == "s1"} == {"m1", "m2", "m3"}+ assert {r["id"] for r in rows if r["sessionId"] == "s2"} == {"m9"}++ def test_resumes_cursor_within_bookmarked_session(self) -> None:+ # The saved `after` cursor must apply only to the bookmarked session (s2 continues from m8).+ # Earlier sessions are re-walked rather than sliced away: the API has no stable ordering, so+ # skipping them would drop rows for any session that reordered ahead of the bookmark. Merge+ # dedupes the re-pulled rows downstream on the [sessionId, id] primary key.+ sessions_pages = [[{"id": "s1"}, {"id": "s2"}]]+ messages = {+ "s1": [[{"id": "m1", "sessionId": "s1"}]],+ "s2": [[{"id": "m8", "sessionId": "s2"}], [{"id": "m9", "sessionId": "s2"}]],+ }+ manager = _FakeResumableManager(BrowserUseResumeConfig(session_id="s2", after="m8"))+ rows = _run("session_messages", self._fetch(sessions_pages, messages), manager)++ assert [r["id"] for r in rows] == ["m1", "m9"]++ def test_missing_bookmark_restarts_from_first_session(self) -> None:+ # If the bookmarked session was deleted between runs, fan-out restarts (merge dedupes).+ sessions_pages = [[{"id": "s1"}]]+ messages = {"s1": [[{"id": "m1", "sessionId": "s1"}]]}+ manager = _FakeResumableManager(BrowserUseResumeConfig(session_id="gone", after="x"))+ rows = _run("session_messages", self._fetch(sessions_pages, messages), manager)++ assert [r["id"] for r in rows] == ["m1"]+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_status_raises_retryable(self, _name: str, status: int) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = False+ session = MagicMock()+ session.get.return_value = response++ with patch.object(browser_use._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(browser_use.BrowserUseRetryableError):+ browser_use._fetch_page(session, "https://api.browser-use.com/api/v3/sessions", {}, MagicMock())+ # Retried up to the 5-attempt cap before giving up.+ assert session.get.call_count == 5++ def test_client_error_raises_for_status(self) -> None:+ response = MagicMock()+ response.status_code = 401+ response.ok = False+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ browser_use._fetch_page(session, "https://api.browser-use.com/api/v3/sessions", {}, MagicMock())+ # A credential error is terminal — no retry.+ assert session.get.call_count == 1+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_maps_to_bool(self, _name: str, status: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response+ with patch.object(browser_use, "make_tracked_session", return_value=session):+ assert validate_credentials("bu_test") is expected++ def test_network_error_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(browser_use, "make_tracked_session", return_value=session):+ assert validate_credentials("bu_test") is False+++class TestHttpSampleCapture:+ # Every Browser Use endpoint returns free-form agent content — session titles and+ # session_messages.data hold whatever a user's agent typed or browsed, which the name-based+ # scrubbers can't recognise. So both the export path and the credential probe must build their+ # tracked session with capture=False. A regression that drops the flag (falling back to the+ # capture=True default) would serialize that tenant content into the HTTP sample bucket.+ def test_get_rows_disables_capture(self) -> None:+ session = MagicMock()+ with (+ patch.object(browser_use, "make_tracked_session", return_value=session) as mock_session,+ patch.object(browser_use, "_fetch_page", return_value={"sessions": []}),+ ):+ list(+ get_rows(+ api_key="bu_test",+ endpoint="sessions",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert mock_session.call_args.kwargs["capture"] is False++ def test_validate_credentials_disables_capture(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response+ with patch.object(browser_use, "make_tracked_session", return_value=session) as mock_session:+ validate_credentials("bu_test")+ assert mock_session.call_args.kwargs["capture"] is False+++class TestRedirectsDisabled:+ # The API key rides in the custom X-Browser-Use-API-Key header, which requests preserves across+ # a cross-host 3xx (it only strips Authorization). Both sessions must pin allow_redirects=False+ # so the key can't replay to a redirect target; a regression that drops the flag re-opens that leak.+ def test_get_rows_disables_redirects(self) -> None:+ session = MagicMock()+ with (+ patch.object(browser_use, "make_tracked_session", return_value=session) as mock_session,+ patch.object(browser_use, "_fetch_page", return_value={"sessions": []}),+ ):+ list(+ get_rows(+ api_key="bu_test",+ endpoint="sessions",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert mock_session.call_args.kwargs["allow_redirects"] is False++ def test_validate_credentials_disables_redirects(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response+ with patch.object(browser_use, "make_tracked_session", return_value=session) as mock_session:+ validate_credentials("bu_test")+ assert mock_session.call_args.kwargs["allow_redirects"] is False+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("sessions", ["id"], "createdAt"),+ ("browser_sessions", ["id"], "startedAt"),+ ("profiles", ["id"], "createdAt"),+ ("workspaces", ["id"], "createdAt"),+ ("session_messages", ["sessionId", "id"], "createdAt"),+ ]+ )+ def test_primary_keys_and_partition(self, endpoint: str, primary_keys: list[str], partition_key: str) -> None:+ response = browser_use_source("bu_test", endpoint, MagicMock(), _FakeResumableManager()) # type: ignore[arg-type]++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"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.pynew file mode 100644index 000000000000..cc64a42e3b21--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browser_use/tests/test_browser_use_source.py@@ -0,0 +1,106 @@+import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.browser_use import source as source_module+from 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.source import BrowserUseSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BrowserUseSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestBrowserUseSource:+ def setup_method(self) -> None:+ self.source = BrowserUseSource()+ self.config = BrowserUseSourceConfig(api_key="bu_test")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.BROWSERUSE++ def test_config_exposes_api_key_field(self) -> None:+ fields = self.source.get_source_config.fields+ assert [f.name for f in fields] == ["api_key"]++ @parameterized.expand(+ [+ ("sessions", True),+ ("browser_sessions", True),+ ("profiles", True),+ ("workspaces", True),+ ("session_messages", False),+ ]+ )+ 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_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.+ assert self.source.lists_tables_without_credentials is True+ tables = 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 by_name["sessions"]["sync_methods"] == ["Full refresh"]+ assert by_name["sessions"]["description"]++ @parameterized.expand(+ [+ ("401", "401 Client Error: Unauthorized for url: https://api.browser-use.com/api/v3/sessions?page=1"),+ ("403", "403 Client Error: Forbidden for url: https://api.browser-use.com/api/v3/sessions?page=1"),+ ]+ )+ def test_permission_errors_are_non_retryable(self, _name: str, observed: str) -> None:+ # 401 (bad key) and 403 (key without access) can never be satisfied by a retry, so both must+ # be classified terminal with an actionable message instead of looping the sync.+ assert any(key in observed for key in self.source.get_non_retryable_errors())++ @parameterized.expand([("valid", True, True, None), ("invalid", False, False, "Invalid Browser Use API key")])+ def test_validate_credentials(+ self, _name: str, probe_result: bool, expected_valid: bool, expected_message: str | None+ ) -> None:+ with mock.patch.object(source_module, "validate_browser_use_credentials", return_value=probe_result):+ valid, message = self.source.validate_credentials(self.config, team_id=1)+ assert valid is expected_valid+ assert message == expected_message++ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = mock.MagicMock()+ 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:+ inputs = mock.MagicMock()+ inputs.schema_name = "sessions"+ manager = mock.MagicMock()+ with mock.patch.object(source_module, "browser_use_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)+ mock_source.assert_called_once()+ _, kwargs = mock_source.call_args+ assert kwargs["api_key"] == "bu_test"+ assert kwargs["endpoint"] == "sessions"++ def 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"+ manager = mock.MagicMock()+ with pytest.raises(ValueError, match="Unknown Browser Use schema"):+ self.source.source_for_pipeline(self.config, manager, inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex e551d8c794cd..22aea56ae2b5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -619,7 +619,7 @@ class BrowseAISourceConfig(config.Config):@config.configclass BrowserUseSourceConfig(config.Config):- pass+ api_key: str@config.config