AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): make silent credential-connection failures visible (#14395)
Reinier van der Leer1d2ae412d853
diff --git a/autogpt_platform/backend/backend/api/features/integrations/failure_events.py b/autogpt_platform/backend/backend/api/features/integrations/failure_events.pynew file mode 100644index 0000000000..23a7d96457--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/integrations/failure_events.py@@ -0,0 +1,69 @@+"""Credential-connection failures that Sentry would otherwise never see.++`sentry_init` builds `LoggingIntegration()` with sentry-sdk's default+`event_level=ERROR`, so a `logger.warning` on these paths raises no event and+reaches nobody. The paths below are the ones where nothing else reports the+failure — the user sees a stuck card and we see nothing at all.++Class numbers come from the credential-connection failure map; the frontend+tags the same numbers on its own terminal-state events.+"""++import logging+from enum import Enum++import sentry_sdk+++class CredentialFailure(str, Enum):+ """Failure classes an alert rule groups on. Renaming one breaks that rule.++ Only the classes this service can observe, and only where nothing else+ reports the failure. Classes 3, 5 and 11 are client-side terminal states+ and are named in the frontend's own map.+ """++ PROVIDER_REGISTRATION_WRONG = "class_06_provider_registration_wrong"+ DEVICE_CODE_RACE = "class_07_device_code_race"+ SCOPES_TOO_NARROW = "class_08_scopes_too_narrow"+ MANAGED_PROVISIONING_LATE = "class_12_managed_provisioning_late"+++def report_credential_failure(+ logger: logging.Logger,+ failure_class: CredentialFailure,+ reason: str,+ message: str,+ *,+ provider: str | None = None,+ **context: object,+) -> None:+ """Log at ERROR so the Sentry event exists, tagged so a rule can find it.++ Only `failure_class`, `reason` and `provider` become tags — anything+ per-user or per-request stays an extra, because Sentry tags are indexed+ and high-cardinality values there are what makes a project unqueryable.+ `json_fields` is the only key GCP's StructuredLogHandler carries through,+ so the same fields are queryable in Cloud Logging.+ """+ tags = {"failure_class": failure_class.value, "reason": reason}+ if provider is not None:+ tags["provider"] = provider+ fields = {**tags, **context}+ # A context key that collides with a LogRecord attribute makes makeRecord+ # raise, out of the `except` the caller is reporting from. `json_fields`+ # has no such reservation, so Cloud Logging keeps the original name.+ safe = {+ (f"ctx_{k}" if k in _RESERVED_LOGRECORD_KEYS else k): v+ for k, v in fields.items()+ }++ with sentry_sdk.new_scope() as scope:+ for tag, value in tags.items():+ scope.set_tag(tag, value)+ logger.error(message, extra={**safe, "json_fields": fields}, stacklevel=2)+++_RESERVED_LOGRECORD_KEYS = frozenset(+ logging.LogRecord("", 0, "", 0, "", None, None).__dict__+) | {"message", "asctime"}diff --git a/autogpt_platform/backend/backend/api/features/integrations/failure_events_test.py b/autogpt_platform/backend/backend/api/features/integrations/failure_events_test.pynew file mode 100644index 0000000000..3af28988c2--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/integrations/failure_events_test.py@@ -0,0 +1,364 @@+"""The credential-failure paths raise a Sentry event, tagged with their class.++`caplog` is useless here: the app's logging config captures nothing for+`backend.*` and rewrites `record.msg` with ANSI colour codes, so every test+below attaches its own plain handler and matches with `in`.+"""++import asyncio+import logging+from unittest.mock import AsyncMock, MagicMock, patch++import fastapi+import fastapi.testclient+import pytest+import sentry_sdk+from pydantic import SecretStr+from sentry_sdk.integrations.logging import LoggingIntegration++from backend.api.features.integrations.failure_events import (+ CredentialFailure,+ report_credential_failure,+)+from backend.api.features.integrations.router import router+from backend.data.model import OAuth2Credentials, OAuthState+from backend.integrations.providers import ProviderName++app = fastapi.FastAPI()+app.include_router(router)+client = fastapi.testclient.TestClient(app)++ROUTER_LOGGER = "backend.api.features.integrations.router"+++class RecordingHandler(logging.Handler):+ def __init__(self):+ super().__init__()+ self.records: list[logging.LogRecord] = []++ def emit(self, record: logging.LogRecord) -> None:+ self.records.append(record)++ def failures(self) -> list[logging.LogRecord]:+ return [r for r in self.records if hasattr(r, "failure_class")]++ def only_failure(self) -> logging.LogRecord:+ found = self.failures()+ assert len(found) == 1, f"expected 1 failure event, got {len(found)}"+ return found[0]+++def router_log():+ yield from _attach(ROUTER_LOGGER)+++def _attach(name: str):+ logger = logging.getLogger(name)+ handler = RecordingHandler()+ original_level = logger.level+ logger.addHandler(handler)+ logger.setLevel(logging.DEBUG)+ try:+ yield handler+ finally:+ logger.removeHandler(handler)+ logger.setLevel(original_level)++[email protected](autouse=True)+def setup_auth(mock_jwt_user):+ from autogpt_libs.auth.jwt_utils import get_jwt_payload++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ yield+ app.dependency_overrides.clear()+++class TestReportCredentialFailure:+ """The mechanism: an ERROR Sentry keeps, carrying a tag a rule can match."""++ def test_emits_at_error_so_the_default_event_level_lets_it_through(+ self, router_log+ ):+ # LoggingIntegration() defaults to event_level=ERROR; a warning here+ # would be dropped before it ever reached Sentry.+ report_credential_failure(+ logging.getLogger(ROUTER_LOGGER),+ CredentialFailure.SCOPES_TOO_NARROW,+ "granted_scopes_narrower",+ "granted scopes are short",+ provider="github",+ )++ record = router_log.only_failure()+ assert record.levelno == logging.ERROR+ assert "granted scopes are short" in record.getMessage()+ assert record.failure_class == "class_08_scopes_too_narrow"+ assert record.reason == "granted_scopes_narrower"++ def test_the_fields_reach_gcp_cloud_logging(self):+ """`json_fields` is the only extra GCP's handler carries through."""+ import io as _io+ import json++ from google.cloud.logging.handlers import StructuredLogHandler++ stream = _io.StringIO()+ logger = logging.getLogger("backend.credential_failure_gcp_probe")+ logger.setLevel(logging.DEBUG)+ logger.propagate = False+ handler = StructuredLogHandler(stream=stream)+ logger.addHandler(handler)+ try:+ report_credential_failure(+ logger,+ CredentialFailure.MANAGED_PROVISIONING_LATE,+ "sweep_timeout",+ "sweep timed out",+ user_id="user-1",+ )+ finally:+ logger.removeHandler(handler)++ entry = json.loads(stream.getvalue().strip().splitlines()[-1])+ assert entry["failure_class"] == "class_12_managed_provisioning_late"+ assert entry["reason"] == "sweep_timeout"+ assert entry["user_id"] == "user-1"++ def test_a_reserved_context_key_does_not_raise_out_of_the_caller(self):+ logger = logging.getLogger(ROUTER_LOGGER)+ handler = RecordingHandler()+ logger.addHandler(handler)+ try:+ report_credential_failure(+ logger,+ CredentialFailure.DEVICE_CODE_RACE,+ "credential_unreadable",+ "unreadable",+ module="github",+ )+ finally:+ logger.removeHandler(handler)++ record = handler.only_failure()+ assert record.ctx_module == "github"+ # GCP keeps the original name, so a query on it does not change.+ assert record.json_fields["module"] == "github"++ def test_the_record_points_at_the_call_site_not_this_helper(self):+ logger = logging.getLogger(ROUTER_LOGGER)+ handler = RecordingHandler()+ logger.addHandler(handler)+ try:+ report_credential_failure(+ logger,+ CredentialFailure.DEVICE_CODE_RACE,+ "credential_unreadable",+ "unreadable",+ )+ finally:+ logger.removeHandler(handler)++ assert handler.only_failure().filename == "failure_events_test.py"++ def test_the_sentry_event_carries_the_tags_and_does_not_leak_them(self):+ captured: list[dict] = []++ class Recorder(sentry_sdk.transport.Transport):+ def capture_envelope(self, envelope):+ for item in envelope.items:+ if item.type == "event":+ captured.append(item.payload.json)++ logger = logging.getLogger(ROUTER_LOGGER)+ # `init(dsn=None)` leaves the client bound and `is_active()` True, so+ # restoring the original is the only teardown that does not leak into+ # `metrics_test.py::test_no_sentry_client_is_active_under_pytest`.+ original_client = sentry_sdk.get_client()+ sentry_sdk.init(+ dsn="https://[email protected]/1",+ transport=Recorder(),+ integrations=[LoggingIntegration()],+ default_integrations=False,+ )+ try:+ report_credential_failure(+ logger,+ CredentialFailure.DEVICE_CODE_RACE,+ "throttle_unavailable",+ "throttle unavailable",+ provider="stripe",+ user_id="user-1",+ )+ logger.error("an unrelated later error")+ finally:+ sentry_sdk.get_global_scope().set_client(original_client)++ assert len(captured) == 2+ tagged, unrelated = captured+ assert tagged["tags"] == {+ "failure_class": "class_07_device_code_race",+ "reason": "throttle_unavailable",+ "provider": "stripe",+ }+ # user_id is per-user: an extra, never an indexed tag.+ assert tagged["extra"]["user_id"] == "user-1"+ assert not unrelated.get("tags")+++class TestCallbackFailureEvents:+ def test_an_invalid_state_token_reports_class_06(self, router_log):+ with patch(+ "backend.api.features.integrations.router.creds_manager"+ ) as mock_mgr:+ mock_mgr.store.verify_state_token = AsyncMock(return_value=None)+ resp = client.post(+ "/github/callback",+ json={"code": "auth-code", "state_token": "stale-token"},+ )++ assert resp.status_code == 400+ record = router_log.only_failure()+ assert record.failure_class == "class_06_provider_registration_wrong"+ assert record.reason == "invalid_state_token"+ assert record.provider == "github"+ # The message is the Sentry grouping key: one issue for the provider's+ # broken config, not one per user who hit it.+ assert "Invalid or expired state token" in record.getMessage()+ # The message is the Sentry grouping key, so the id belongs in the+ # context and nowhere else — otherwise class 06 is one issue per user.+ assert record.user_id+ assert record.user_id not in record.getMessage()++ def test_a_granted_scope_shortfall_reports_class_08(self, router_log):+ state = OAuthState(+ token="state-token",+ provider="github",+ expires_at=9999999999,+ scopes=["repo", "admin:org"],+ )+ short = OAuth2Credentials(+ id="github-cred-1",+ provider="github",+ title="My GitHub",+ access_token=SecretStr("gho_token"),+ refresh_token=None,+ scopes=["repo"],+ username="alice",+ )+ handler = MagicMock()+ handler.handle_default_scopes.return_value = state.scopes+ handler.exchange_code_for_tokens = AsyncMock(return_value=short)++ with (+ patch(+ "backend.api.features.integrations.router._get_provider_oauth_handler",+ return_value=handler,+ ),+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,+ ):+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=None)+ mock_mgr.store.get_creds_by_provider = AsyncMock(return_value=[])+ mock_mgr.create = AsyncMock()+ resp = client.post(+ "/github/callback",+ json={"code": "auth-code", "state_token": "state-token"},+ )++ # The credential is stored regardless — that is the defect being made+ # visible, not one being fixed here.+ assert resp.status_code == 200+ record = router_log.only_failure()+ assert record.failure_class == "class_08_scopes_too_narrow"+ assert record.reason == "granted_scopes_narrower"+ assert record.provider == "github"+++class TestDeviceAuthFailureEvents:+ async def test_an_unavailable_throttle_stays_a_warning(self, router_log):+ from backend.api.features.integrations.router import _throttle_upstream++ with patch(+ "backend.data.redis_client.get_redis_async",+ AsyncMock(side_effect=ConnectionError("redis is gone")),+ ):+ throttled = await _throttle_upstream(+ "user-1", ProviderName.GITHUB, seconds=5, scope="initiate"+ )++ # Fails open. A Redis outage is reported by infrastructure monitoring+ # and every ~5s poll re-enters here, so this must not raise an event.+ assert throttled is False+ assert router_log.failures() == []+ assert any("throttle unavailable" in r.getMessage() for r in router_log.records)++ async def test_an_unreadable_stored_credential_reports_class_07(self, router_log):+ from backend.api.features.integrations.router import _credential_for_grant++ with patch(+ "backend.api.features.integrations.router.creds_manager"+ ) as mock_mgr:+ mock_mgr.store.get_creds_by_id = AsyncMock(+ side_effect=RuntimeError("decrypt failed")+ )+ result = await _credential_for_grant(+ "user-1", ProviderName.GITHUB, "cred-1"+ )++ assert result is None+ record = router_log.only_failure()+ assert record.failure_class == "class_07_device_code_race"+ assert record.reason == "credential_unreadable"+++class TestProvisioningAndDiscoveryFailureEvents:+ async def test_a_managed_sweep_timeout_reports_class_12(self, router_log):+ from backend.api.features.integrations.router import (+ _ensure_managed_credentials_bounded,+ )++ async def never_finishes(*_args, **_kwargs):+ await asyncio.sleep(3600)++ before = asyncio.all_tasks()+ with (+ patch(+ "backend.api.features.integrations.router.ensure_managed_credentials",+ never_finishes,+ ),+ patch(+ "backend.api.features.integrations.router._MANAGED_PROVISION_TIMEOUT_S",+ 0.01,+ ),+ ):+ await _ensure_managed_credentials_bounded("user-1")++ # Cancel only the fire-and-forget retry this call scheduled — the loop+ # is session-scoped and its other tasks belong to the whole suite.+ scheduled = asyncio.all_tasks() - before+ for task in scheduled:+ task.cancel()+ await asyncio.gather(*scheduled, return_exceptions=True)++ record = router_log.only_failure()+ assert record.failure_class == "class_12_managed_provisioning_late"+ assert record.reason == "sweep_timeout"+ assert record.user_id == "user-1"++ def test_a_failed_block_load_stays_a_warning(self, router_log):+ with patch(+ "backend.blocks.load_all_blocks",+ side_effect=ImportError("a provider _config.py is broken"),+ ):+ resp = client.get("/providers")++ # `load_all_blocks` caches values, not exceptions, so a broken+ # `_config.py` re-raises on every page load fleet-wide. That volume+ # belongs nowhere near the event quota.+ assert resp.status_code == 200+ assert router_log.failures() == []+ assert any(+ "Failed to load blocks" in r.getMessage() for r in router_log.records+ )diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex c8435420f7..43c01d1da5 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -93,6 +93,7 @@ from .codex import (revoke_codex_credentials,)from .codex import router as codex_router+from .failure_events import CredentialFailure, report_credential_failurefrom .models import (ProviderConstants,ProviderMetadata,@@ -346,7 +347,14 @@ async def callback()if not valid_state:- logger.warning(f"Invalid or expired state token for user {user_id}")+ report_credential_failure(+ logger,+ CredentialFailure.PROVIDER_REGISTRATION_WRONG,+ "invalid_state_token",+ "Invalid or expired state token",+ provider=provider.value,+ user_id=user_id,+ )raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail="Invalid or expired state token",@@ -375,10 +383,15 @@ async def callback(# Check if the granted scopes are sufficient for the requested scopesif not set(scopes).issubset(set(credentials.scopes)):- # For now, we'll just log the warning and continue- logger.warning(+ # Stored and accepted anyway; the frontend then refuses to select it,+ # so this is the only record that the credential is short.+ report_credential_failure(+ logger,+ CredentialFailure.SCOPES_TOO_NARROW,+ "granted_scopes_narrower",f"Granted scopes {credentials.scopes} for provider {provider.value} "- f"do not include all requested scopes {scopes}"+ f"do not include all requested scopes {scopes}",+ provider=provider.value,)except Exception as e:@@ -496,7 +509,13 @@ async def _credential_for_grant(try:return await creds_manager.store.get_creds_by_id(user_id, credential_id)except Exception as e:- logger.warning(f"Could not read stored credential for {provider}: {e}")+ report_credential_failure(+ logger,+ CredentialFailure.DEVICE_CODE_RACE,+ "credential_unreadable",+ f"Could not read stored credential for {provider}: {e}",+ provider=provider_key(provider),+ )return None@@ -749,11 +768,13 @@ async def _ensure_managed_credentials_bounded(user_id: str) -> None:timeout=_MANAGED_PROVISION_TIMEOUT_S,)except asyncio.TimeoutError:- logger.warning(- "Managed credential sweep exceeded %.1fs for user=%s; "+ report_credential_failure(+ logger,+ CredentialFailure.MANAGED_PROVISIONING_LATE,+ "sweep_timeout",+ f"Managed credential sweep exceeded {_MANAGED_PROVISION_TIMEOUT_S:.1f}s; ""continuing without it — provisioning will complete in background",- _MANAGED_PROVISION_TIMEOUT_S,- user_id,+ user_id=user_id,)asyncio.create_task(ensure_managed_credentials(user_id, creds_manager.store))@@ -1886,6 +1907,8 @@ async def list_providers(load_all_blocks()except Exception as e:+ # The list still returns, one provider short — every card for a missing+ # provider then renders as a permanent loading state, not an error.logger.warning(f"Failed to load blocks for provider metadata: {e}")all_providers = get_all_provider_names()diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsxindex 2c7d55bc3f..ab78c52326 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx@@ -216,6 +216,7 @@ export function SetupRequirementsCard({ready: canRun,manualProceed: needsManualPick || hasUserActionableInputs,justConnected,+ credentialsReady: !needsCredentials || isAllCredsComplete,buildMessage: () => buildProceedMessage(),onSent: markSent,connectors: needsCredentialsdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsxindex a87274dd56..48db5a050f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx@@ -30,6 +30,7 @@ import { PendingQuestionsContext } from "../QuestionDock/PendingQuestionsContextimport type { MessagePart } from "../ChatMessagesContainer/helpers";import { ACCORDION_PANEL, accordionState, PANEL_REVEAL } from "./accordion";import { ChainActionsContext, type ChainActionEntry } from "./chainActions";+import { useCredentialFailureCounters } from "./useCredentialFailureCounters";import { ChainRowView } from "./ChainRowView";import {type ChainRow,@@ -172,6 +173,8 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {[canAutoSend],);+ useCredentialFailureCounters({ entries: actionEntries });+const rows = useMemo(() =>markSupersededSubSessionRows(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/credential-failure-events.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/credential-failure-events.test.tsxnew file mode 100644index 0000000000..81f404be52--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/credential-failure-events.test.tsx@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ act,+ cleanup,+ render as baseRender,+} from "@/tests/integrations/test-utils";+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { CopilotChatActionsProvider } from "../../CopilotChatActionsProvider/CopilotChatActionsProvider";+import type { MessagePart } from "../../ChatMessagesContainer/helpers";+import { ToolChain } from "../ToolChain";++const capture = vi.hoisted(() => vi.fn());+vi.mock("posthog-js", () => ({ default: { capture } }));++// What the stubbed card registers with the chain — the two fields the chain's+// terminal-state detection reads.+const card = vi.hoisted(() => ({+ current: { ready: false, justConnected: false, credentialsReady: false },+}));++vi.mock("../../SetupRequirementsCard/SetupRequirementsCard", async () => {+ const { useContext, useEffect } = await import("react");+ const { ChainActionsContext } = await import("../chainActions");++ function SetupRequirementsCard() {+ const chainActions = useContext(ChainActionsContext);+ const { ready, justConnected, credentialsReady } = card.current;+ useEffect(() => {+ if (!chainActions) return;+ chainActions.register({+ id: "github",+ ready,+ justConnected,+ credentialsReady,+ buildMessage: () => "I've configured the required credentials.",+ connectors: {+ id: "github",+ fields: [],+ selected: {},+ onChange: () => {},+ onConnected: () => {},+ },+ });+ return () => chainActions.unregister("github");+ }, [chainActions, ready, justConnected, credentialsReady]);+ return <div>setup-card</div>;+ }++ return { SetupRequirementsCard };+});++function setupPart(): MessagePart {+ return {+ type: "tool-connect_integration",+ state: "output-available",+ toolCallId: "call-connect_integration",+ input: {},+ output: {+ type: "setup_requirements",+ setup_info: { agent_name: "GitHub" },+ },+ } as MessagePart;+}++function render(ui: React.ReactElement) {+ const { rerender, ...rest } = baseRender(+ <CopilotChatActionsProvider onSend={vi.fn()}>+ {ui}+ </CopilotChatActionsProvider>,+ );+ return {+ ...rest,+ rerender: (next: React.ReactElement) =>+ rerender(+ <CopilotChatActionsProvider onSend={vi.fn()}>+ {next}+ </CopilotChatActionsProvider>,+ ),+ };+}++function capturedFailures() {+ return capture.mock.calls.filter(([event]) =>+ String(event).startsWith("credential_"),+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ card.current = {+ ready: false,+ justConnected: false,+ credentialsReady: false,+ };+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+ useCopilotUIStore.setState({ initialPrompt: null, sentMessageCount: 0 });+});++describe("a sign-in that never reaches the card that asked for it", () => {+ it("counts the stuck card once the connect settles", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ card.current = {+ ready: false,+ justConnected: true,+ credentialsReady: false,+ };++ render(<ToolChain parts={[setupPart()]} isStreaming={false} />);+ await act(async () => {+ vi.advanceTimersByTime(6000);+ });++ expect(capture).toHaveBeenCalledWith(+ "credential_proceed_stuck_after_connect",+ { failure_class: "class_11_credential_not_wired_to_card" },+ );+ });++ it("counts nothing when the card becomes ready inside the settle window", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ card.current = {+ ready: false,+ justConnected: true,+ credentialsReady: false,+ };++ const { rerender } = render(+ <ToolChain parts={[setupPart()]} isStreaming={false} />,+ );+ await act(async () => {+ vi.advanceTimersByTime(1000);+ });++ card.current = { ready: true, justConnected: true, credentialsReady: true };+ rerender(<ToolChain parts={[setupPart()]} isStreaming={false} />);+ await act(async () => {+ vi.advanceTimersByTime(10000);+ });++ expect(capturedFailures()).toHaveLength(0);+ });++ it("counts nothing when the card leaves the chain before the settle window", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ card.current = {+ ready: false,+ justConnected: true,+ credentialsReady: false,+ };++ const { rerender } = render(+ <ToolChain parts={[setupPart()]} isStreaming={false} />,+ );+ await act(async () => {+ vi.advanceTimersByTime(1000);+ });++ rerender(<ToolChain parts={[]} isStreaming={false} />);+ await act(async () => {+ vi.advanceTimersByTime(10000);+ });++ expect(capturedFailures()).toHaveLength(0);+ });++ it("counts nothing while the user is still filling in the card's inputs", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ // Signed in, credential in place, card not `ready` only because its run+ // inputs are half-typed. Counting this measures typing speed.+ card.current = {+ ready: false,+ justConnected: true,+ credentialsReady: true,+ };++ render(<ToolChain parts={[setupPart()]} isStreaming={false} />);+ await act(async () => {+ vi.advanceTimersByTime(20000);+ });++ expect(capturedFailures()).toHaveLength(0);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.tsindex 3caf899cb2..b547b2b2a1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/chainActions.ts@@ -23,6 +23,9 @@ export interface ChainActionEntry {/** A sign-in completed on this card during this page life. The chain sends* only when one has, so a chat reloaded from history stays silent. */justConnected?: boolean;+ /** Every credential this card asked for is in place. Distinct from `ready`,+ * which also waits on run inputs the user is still typing. */+ credentialsReady?: boolean;/** Credentials this card needs. The chain merges every entry's request* into the single connectors table it renders underneath itself. */connectors?: ConnectorRequest;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/useCredentialFailureCounters.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/useCredentialFailureCounters.tsnew file mode 100644index 0000000000..96e66e7aef--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/useCredentialFailureCounters.ts@@ -0,0 +1,62 @@+"use client";++import { useEffect, useRef } from "react";+import { trackCredentialConnectionFailure } from "@/services/credentials/connection-analytics";+import type { ChainActionEntry } from "./chainActions";++// A just-connected card receives its credential through an async store reload,+// so a brief unwired window is the happy path. Past this it is stuck.+const STUCK_AFTER_CONNECT_MS = 5000;++interface Args {+ entries: ReadonlyMap<string, ChainActionEntry>;+}++/** Counts sign-ins that complete and never reach the card that asked for them.+ * Keyed on the credential alone — a card is legitimately not `ready` while the+ * user is still filling in its run inputs. */+export function useCredentialFailureCounters({ entries }: Args) {+ const stuckTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>());+ const stuckReported = useRef(new Set<string>());++ useEffect(+ function reportCardsStuckAfterConnecting() {+ const timers = stuckTimers.current;+ const reported = stuckReported.current;+ // An unregistered card left the chain; its pending timer would count a+ // user who is no longer looking at it.+ timers.forEach((timer, id) => {+ if (entries.has(id)) return;+ clearTimeout(timer);+ timers.delete(id);+ });+ entries.forEach((entry) => {+ if (entry.justConnected && entry.credentialsReady === false) {+ if (timers.has(entry.id) || reported.has(entry.id)) return;+ timers.set(+ entry.id,+ setTimeout(() => {+ timers.delete(entry.id);+ reported.add(entry.id);+ trackCredentialConnectionFailure(+ "credential_proceed_stuck_after_connect",+ );+ }, STUCK_AFTER_CONNECT_MS),+ );+ return;+ }+ clearTimeout(timers.get(entry.id));+ timers.delete(entry.id);+ });+ },+ [entries],+ );++ useEffect(function clearStuckTimersOnUnmount() {+ const timers = stuckTimers.current;+ return () => {+ timers.forEach(clearTimeout);+ timers.clear();+ };+ }, []);+}diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsxindex 05f8dc6670..4222ede6c6 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx@@ -36,6 +36,8 @@ vi.mock("@/lib/oauth-popup", () => ({OAUTH_ERROR_FLOW_TIMED_OUT: "OAuth flow timed out",OAUTH_ERROR_POPUP_BLOCKED:"Popup blocked — the sign-in window opened in a new tab instead. If you don't see it, allow popups for this site and retry.",+ OAUTH_ERROR_POPUP_BLOCKED_NO_TAB:+ "Popup blocked. Allow popups for this site and retry.",}));vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({postV2InitiateOauthLoginForAnMcpServer: vi.fn(),diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/credential-failure-events.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/credential-failure-events.test.tsxnew file mode 100644index 0000000000..94550b9196--- /dev/null+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/credential-failure-events.test.tsx@@ -0,0 +1,227 @@+import {+ render,+ screen,+ cleanup,+ fireEvent,+ waitFor,+} from "@/tests/integrations/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";+import React from "react";+import { CredentialsInput } from "../CredentialsInput";++const capture = vi.hoisted(() => vi.fn());+vi.mock("posthog-js", () => ({ default: { capture } }));++vi.mock("@/hooks/useCredentials", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/hooks/useCredentials")>()),+ default: vi.fn(),+}));+vi.mock("@/lib/autogpt-server-api/context", () => ({+ useBackendAPI: vi.fn(),+ BackendAPIProvider: ({ children }: { children: React.ReactNode }) => children,+}));+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: vi.fn(),+ useToast: () => ({ toast: vi.fn(), dismiss: vi.fn(), toasts: [] }),+}));+vi.mock("@/lib/oauth-popup", () => ({+ openOAuthPopup: vi.fn(),+ preOpenOAuthPopup: vi.fn(() => null),+ OAUTH_ERROR_WINDOW_CLOSED: "Sign-in window was closed",+ OAUTH_ERROR_FLOW_CANCELED: "OAuth flow was canceled",+ OAUTH_ERROR_FLOW_TIMED_OUT: "OAuth flow timed out",+ OAUTH_ERROR_POPUP_BLOCKED: "Popup blocked — opened in a new tab instead.",+ OAUTH_ERROR_POPUP_BLOCKED_NO_TAB:+ "Popup blocked. Allow popups for this site and retry.",+}));+vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({+ postV2InitiateOauthLoginForAnMcpServer: vi.fn(),+}));++import useCredentials from "@/hooks/useCredentials";+import { useBackendAPI } from "@/lib/autogpt-server-api/context";+import {+ openOAuthPopup,+ OAUTH_ERROR_FLOW_TIMED_OUT,+ OAUTH_ERROR_POPUP_BLOCKED_NO_TAB,+} from "@/lib/oauth-popup";++const mockUseCredentials = useCredentials as unknown as ReturnType<+ typeof vi.fn+>;+const mockUseBackendAPI = useBackendAPI as unknown as ReturnType<typeof vi.fn>;+const mockOpenOAuthPopup = openOAuthPopup as unknown as ReturnType<+ typeof vi.fn+>;++const schema: BlockIOCredentialsSubSchema = {+ type: "object",+ properties: {},+ credentials_provider: ["google"],+ credentials_types: ["oauth2"],+ credentials_scopes: ["drive.file", "drive.metadata"],+};++function makeCredentialsReturn(overrides: Record<string, unknown> = {}) {+ return {+ provider: "google",+ providerName: "Google",+ savedCredentials: [],+ allProviderCredentials: [],+ upgradeableCredentials: [],+ supportsApiKey: false,+ supportsOAuth2: true,+ supportsUserPassword: false,+ supportsHostScoped: false,+ isLoading: false,+ isSystemProvider: false,+ schema,+ oAuthCallback: vi.fn().mockResolvedValue({+ id: "new-cred",+ type: "oauth2",+ title: "Connected Google",+ provider: "google",+ scopes: ["drive.file", "drive.metadata"],+ }),+ mcpOAuthCallback: vi.fn(),+ createAPIKeyCredentials: vi.fn(),+ createUserPasswordCredentials: vi.fn(),+ createHostScopedCredentials: vi.fn(),+ deleteCredentials: vi.fn(),+ discriminatorValue: undefined,+ ...overrides,+ };+}++function renderCard() {+ render(+ <CredentialsInput+ schema={schema}+ onSelectCredentials={vi.fn()}+ showTitle+ variant="node"+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: /add account/i }));+}++// A promise rejected at construction is unhandled until the flow reaches+// its await, which vitest reports as an error.+function rejectLater(message: string) {+ return new Promise<never>((_resolve, reject) =>+ setTimeout(() => reject(new Error(message)), 0),+ );+}++function capturedFailures() {+ return capture.mock.calls.filter(([event]) =>+ String(event).startsWith("credential_"),+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ mockUseBackendAPI.mockReturnValue({+ oAuthLogin: vi.fn().mockResolvedValue({+ login_url: "https://accounts.google.com/o/oauth2/auth",+ state_token: "state-xyz",+ }),+ onWebSocketMessage: vi.fn().mockReturnValue(() => {}),+ connectWebSocket: vi.fn().mockResolvedValue(undefined),+ sendWebSocketMessage: vi.fn(),+ });+ mockUseCredentials.mockReturnValue(makeCredentialsReturn());+});++afterEach(() => {+ cleanup();+});++describe("credential connect failures the card reports instead of throwing", () => {+ it("counts a blocked popup whose new-tab fallback was blocked too", async () => {+ mockOpenOAuthPopup.mockReturnValue({+ promise: rejectLater(OAUTH_ERROR_POPUP_BLOCKED_NO_TAB),+ cleanup: { abort: vi.fn() },+ popupBlocked: true,+ fallbackBlocked: true,+ });++ renderCard();++ await waitFor(() =>+ expect(capture).toHaveBeenCalledWith("credential_oauth_popup_blocked", {+ failure_class: "class_05_browser_channel_broken",+ provider: "google",+ }),+ );+ });++ it("counts a flow that ran out of time", async () => {+ mockOpenOAuthPopup.mockReturnValue({+ promise: rejectLater(OAUTH_ERROR_FLOW_TIMED_OUT),+ cleanup: { abort: vi.fn() },+ popupBlocked: false,+ fallbackBlocked: false,+ });++ renderCard();++ await waitFor(() =>+ expect(capture).toHaveBeenCalledWith("credential_oauth_flow_timed_out", {+ failure_class: "class_05_browser_channel_broken",+ provider: "google",+ }),+ );+ });++ it("counts a credential stored with narrower scopes than the card requires", async () => {+ mockUseCredentials.mockReturnValue(+ makeCredentialsReturn({+ oAuthCallback: vi.fn().mockResolvedValue({+ id: "new-cred",+ type: "oauth2",+ title: "Connected Google",+ provider: "google",+ scopes: ["drive.file"],+ }),+ }),+ );+ mockOpenOAuthPopup.mockReturnValue({+ promise: Promise.resolve({ code: "code-1", state: "state-xyz" }),+ cleanup: { abort: vi.fn() },+ popupBlocked: false,+ fallbackBlocked: false,+ });++ renderCard();++ await waitFor(() =>+ expect(capture).toHaveBeenCalledWith(+ "credential_scope_shortfall_blocked_selection",+ {+ failure_class: "class_08_scopes_too_narrow",+ provider: "google",+ },+ ),+ );+ });++ it("counts nothing when the sign-in completes with the scopes it asked for", async () => {+ mockOpenOAuthPopup.mockReturnValue({+ promise: Promise.resolve({ code: "code-1", state: "state-xyz" }),+ cleanup: { abort: vi.fn() },+ popupBlocked: false,+ fallbackBlocked: false,+ });++ renderCard();++ await waitFor(() =>+ expect(+ mockUseCredentials.mock.results[0].value.oAuthCallback,+ ).toHaveBeenCalled(),+ );+ expect(capturedFailures()).toHaveLength(0);+ });+});diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.tsindex a83b637d85..a193f15341 100644--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts@@ -10,10 +10,12 @@ import {OAUTH_ERROR_FLOW_CANCELED,OAUTH_ERROR_FLOW_TIMED_OUT,OAUTH_ERROR_POPUP_BLOCKED,+ OAUTH_ERROR_POPUP_BLOCKED_NO_TAB,OAUTH_ERROR_WINDOW_CLOSED,openOAuthPopup,preOpenOAuthPopup,} from "@/lib/oauth-popup";+import { trackCredentialConnectionFailure } from "@/services/credentials/connection-analytics";import { useEffect, useRef, useState } from "react";import {countSupportedTypes,@@ -322,6 +324,10 @@ export function useCredentialsInput({);if (!hasAllRequiredScopes) {+ trackCredentialConnectionFailure(+ "credential_scope_shortfall_blocked_selection",+ { provider },+ );setOAuthError("Connection failed: the granted permissions don't match what's required. " +"Please contact the application administrator.",@@ -357,8 +363,16 @@ export function useCredentialsInput({) {// User closed the popup or clicked cancel — not an error} else if (message === OAUTH_ERROR_FLOW_TIMED_OUT) {+ trackCredentialConnectionFailure("credential_oauth_flow_timed_out", {+ provider,+ });setOAuthError(OAUTH_ERROR_FLOW_TIMED_OUT);} else {+ if (message === OAUTH_ERROR_POPUP_BLOCKED_NO_TAB) {+ trackCredentialConnectionFailure("credential_oauth_popup_blocked", {+ provider,+ });+ }setOAuthError(`OAuth error: ${message}`);}} finally {diff --git a/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.failure-events.test.tsx b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.failure-events.test.tsxnew file mode 100644index 0000000000..f58c8862e5--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.failure-events.test.tsx@@ -0,0 +1,138 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import React from "react";+import {+ CredentialsProvidersContext,+ type CredentialsProvidersContextType,+} from "@/providers/agent-credentials/credentials-provider";+import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";+import useCredentials from "../useCredentials";++const capture = vi.hoisted(() => vi.fn());+vi.mock("posthog-js", () => ({ default: { capture } }));++const schema: BlockIOCredentialsSubSchema = {+ type: "object",+ properties: {},+ credentials_provider: ["github"],+ credentials_types: ["oauth2"],+};++function makeProviders(...names: string[]): CredentialsProvidersContextType {+ return Object.fromEntries(+ names.map((name) => [+ name,+ {+ provider: name,+ providerName: name,+ savedCredentials: [],+ isSystemProvider: false,+ },+ ]),+ ) as unknown as CredentialsProvidersContextType;+}++function renderWithProviders(+ providers: CredentialsProvidersContextType | null,+) {+ return renderHook(() => useCredentials(schema), {+ wrapper: ({ children }: { children: React.ReactNode }) => (+ <CredentialsProvidersContext.Provider value={providers}>+ {children}+ </CredentialsProvidersContext.Provider>+ ),+ });+}++// A field whose provider follows a sibling input, so one mounted hook can see+// several providers.+const discriminatedSchema: BlockIOCredentialsSubSchema = {+ type: "object",+ properties: {},+ credentials_provider: ["github", "google"],+ credentials_types: ["oauth2"],+ discriminator: "model",+ discriminator_mapping: { gpt: "github", gemini: "google" },+};++function renderDiscriminated(+ providers: CredentialsProvidersContextType,+ model: string,+) {+ return renderHook(+ ({ model }: { model: string }) =>+ useCredentials(discriminatedSchema, { model }),+ {+ initialProps: { model },+ wrapper: ({ children }: { children: React.ReactNode }) => (+ <CredentialsProvidersContext.Provider value={providers}>+ {children}+ </CredentialsProvidersContext.Provider>+ ),+ },+ );+}++beforeEach(() => {+ vi.clearAllMocks();+});++afterEach(() => {+ vi.clearAllMocks();+});++describe("a provider the frontend has never heard of", () => {+ it("counts the card that will never render", async () => {+ const { result } = renderWithProviders(makeProviders("google"));++ // The null is what the card reads as "still loading", forever.+ expect(result.current).toBeNull();+ await waitFor(() =>+ expect(capture).toHaveBeenCalledWith("credential_card_never_rendered", {+ failure_class: "class_03_provider_unknown_to_frontend",+ provider: "github",+ }),+ );+ });++ it("counts nothing while the provider map is still loading", async () => {+ const { result } = renderWithProviders(null);++ expect(result.current).toBeNull();+ await waitFor(() => expect(capture).not.toHaveBeenCalled());+ });++ it("counts nothing once the provider is in the map", async () => {+ const { result } = renderWithProviders(makeProviders("github"));++ expect(result.current).not.toBeNull();+ await waitFor(() => expect(capture).not.toHaveBeenCalled());+ });++ it("counts nothing for the empty map a logged-out session publishes", async () => {+ // `{}` is "settled, and this session has no providers" — a session that+ // expired under an open builder page, not a provider that does not exist.+ const { result } = renderWithProviders(+ {} as CredentialsProvidersContextType,+ );++ expect(result.current).toBeNull();+ await waitFor(() => expect(capture).not.toHaveBeenCalled());+ });++ it("counts a provider once however often the field returns to it", async () => {+ const { rerender } = renderDiscriminated(makeProviders("slack"), "gpt");++ await waitFor(() => expect(capture).toHaveBeenCalledTimes(1));+ rerender({ model: "gemini" });+ await waitFor(() => expect(capture).toHaveBeenCalledTimes(2));+ rerender({ model: "gpt" });++ await waitFor(() =>+ expect(capture.mock.calls.map(([, props]) => props.provider)).toEqual([+ "github",+ "google",+ ]),+ );+ });+});diff --git a/autogpt_platform/frontend/src/hooks/useCredentials.ts b/autogpt_platform/frontend/src/hooks/useCredentials.tsindex 7886568ea7..51a39d3029 100644--- a/autogpt_platform/frontend/src/hooks/useCredentials.ts+++ b/autogpt_platform/frontend/src/hooks/useCredentials.ts@@ -1,8 +1,9 @@-import { useContext } from "react";+import { useContext, useEffect, useRef } from "react";import {CredentialsProviderData,CredentialsProvidersContext,+ type CredentialsProvidersContextType,} from "@/providers/agent-credentials/credentials-provider";import {BlockIOCredentialsSubSchema,@@ -10,6 +11,7 @@ import {CredentialsType,} from "@/lib/autogpt-server-api";import { getHostFromUrl } from "@/lib/utils/url";+import { trackCredentialConnectionFailure } from "@/services/credentials/connection-analytics";import {getCredentialProviderFromSchema,getDiscriminatorValue,@@ -136,6 +138,7 @@ export default function useCredentials(credsInputSchema,selectedProvider,);+ useReportProviderUnknown(providerName, allProviders);if (!providerName) return null;const provider = allProviders ? allProviders[providerName] : null;@@ -182,3 +185,25 @@ export default function useCredentials(isLoading: false,};}++/** A provider missing from the *loaded* map renders as a permanent loading+ * state, never an error — the card silently drops the row it owes the user.+ * A null map is still in flight and means nothing, and an empty one is what a+ * settled logged-out session publishes — neither says a provider is unknown. */+function useReportProviderUnknown(+ providerName: string | null,+ allProviders: CredentialsProvidersContextType | null,+) {+ const reportedFor = useRef(new Set<string>());++ useEffect(() => {+ if (!providerName || !allProviders) return;+ if (Object.keys(allProviders).length === 0) return;+ if (providerName in allProviders) return;+ if (reportedFor.current.has(providerName)) return;+ reportedFor.current.add(providerName);+ trackCredentialConnectionFailure("credential_card_never_rendered", {+ provider: providerName,+ });+ }, [providerName, allProviders]);+}diff --git a/autogpt_platform/frontend/src/services/credentials/__tests__/connection-analytics.test.ts b/autogpt_platform/frontend/src/services/credentials/__tests__/connection-analytics.test.tsnew file mode 100644index 0000000000..b84f89d5e7--- /dev/null+++ b/autogpt_platform/frontend/src/services/credentials/__tests__/connection-analytics.test.ts@@ -0,0 +1,33 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { trackCredentialConnectionFailure } from "../connection-analytics";++const capture = vi.hoisted(() => vi.fn());+vi.mock("posthog-js", () => ({ default: { capture } }));++beforeEach(() => {+ vi.clearAllMocks();+});++describe("the failure class an alert rule groups on", () => {+ it("is the one the map assigns, not one a caller passes", () => {+ trackCredentialConnectionFailure("credential_oauth_popup_blocked", {+ provider: "github",+ failure_class: "class_99_whatever",+ });++ expect(capture).toHaveBeenCalledWith("credential_oauth_popup_blocked", {+ provider: "github",+ failure_class: "class_05_browser_channel_broken",+ });+ });++ it("never lets a blocked analytics host break a connect flow", () => {+ capture.mockImplementationOnce(() => {+ throw new Error("blocked by client");+ });++ expect(() =>+ trackCredentialConnectionFailure("credential_oauth_flow_timed_out"),+ ).not.toThrow();+ });+});diff --git a/autogpt_platform/frontend/src/services/credentials/connection-analytics.ts b/autogpt_platform/frontend/src/services/credentials/connection-analytics.tsnew file mode 100644index 0000000000..852beb503d--- /dev/null+++ b/autogpt_platform/frontend/src/services/credentials/connection-analytics.ts@@ -0,0 +1,45 @@+// Terminal states of a credential connect card. Every one of these ends in a+// missing row, a disabled button or a spinner rather than an exception, so+// nothing reports them today — the backend's Sentry events stop at the point+// the credential is stored, and the failures below all happen after that.+//+// `failure_class` matches the tag the backend puts on its own credential+// failures, so one class number covers both halves of a path.++import posthog from "posthog-js";++type CredentialConnectionFailure =+ // The provider is absent from the loaded provider map, so the card's row+ // for it never renders at all.+ | "credential_card_never_rendered"+ // Popup and the new-tab fallback were both blocked: there is no way in.+ | "credential_oauth_popup_blocked"+ | "credential_oauth_flow_timed_out"+ // Connected, stored, and then refused by the card because the provider+ // granted less than the block asked for.+ | "credential_scope_shortfall_blocked_selection"+ // A sign-in completed on this card and the credential never reached it.+ | "credential_proceed_stuck_after_connect";++const FAILURE_CLASS: Record<CredentialConnectionFailure, string> = {+ credential_card_never_rendered: "class_03_provider_unknown_to_frontend",+ credential_oauth_popup_blocked: "class_05_browser_channel_broken",+ credential_oauth_flow_timed_out: "class_05_browser_channel_broken",+ credential_scope_shortfall_blocked_selection: "class_08_scopes_too_narrow",+ credential_proceed_stuck_after_connect:+ "class_11_credential_not_wired_to_card",+};++export function trackCredentialConnectionFailure(+ event: CredentialConnectionFailure,+ properties: { provider?: string } & Record<string, unknown> = {},+) {+ try {+ posthog.capture(event, {+ ...properties,+ failure_class: FAILURE_CLASS[event],+ });+ } catch {+ // A blocked analytics host must never break a connect flow.+ }+}