Skip to content

Automate browser based workflows with AI

SKY-11640: avoid unsafe fallback for blocked anchor clicks (#7042)

LawyZheng36f0d47a77b2
diff --git a/skyvern-frontend/src/components/LLMSetupBanner.tsx b/skyvern-frontend/src/components/LLMSetupBanner.tsx
deleted file mode 100644
index 21cb3f000..000000000
--- a/skyvern-frontend/src/components/LLMSetupBanner.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { Link } from "react-router-dom";
-
-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
-import { Button } from "@/components/ui/button";
-import { useLLMDiagnostics } from "@/hooks/useLLMDiagnostics";
-
-function LLMSetupBanner() {
- const { data, error, isLoading } = useLLMDiagnostics();
-
- if (isLoading || error || !data || data.status === "ok") {
- return null;
- }
-
- const primaryIssue = data.issues[0];
- const missingEnvVars = primaryIssue?.missing_env_vars ?? [];
- const defaultIssueReason =
- missingEnvVars.length > 0
- ? ` because ${missingEnvVars.join(", ")} ${
- missingEnvVars.length === 1 ? "is" : "are"
- } missing.`
- : ".";
-
- return (
- <div className="px-4 pt-4">
- <Alert className="flex flex-col items-center gap-2 border-amber-700 bg-amber-950 text-amber-50">
- <AlertTitle className="text-center text-base font-semibold tracking-wide">
- LLM setup required
- </AlertTitle>
- <AlertDescription className="space-y-3 text-center text-sm leading-6">
- <p>
- {data.detail ??
- "Skyvern is running, but no usable LLM is configured for local OSS."}{" "}
- Add an Ollama, OpenRouter, or OpenAI-compatible model in Settings.
- </p>
- {primaryIssue ? (
- <p className="text-xs text-amber-100">
- Default LLM <code>{data.default_llm_key}</code> is not ready
- {defaultIssueReason}
- </p>
- ) : null}
- {data.next_step ? (
- <p className="text-xs text-amber-100">{data.next_step}</p>
- ) : null}
- <div className="flex justify-center">
- <Button asChild variant="secondary">
- <Link to="/settings#custom-llms">Configure Custom LLMs</Link>
- </Button>
- </div>
- </AlertDescription>
- </Alert>
- </div>
- );
-}
-
-export { LLMSetupBanner };
diff --git a/skyvern-frontend/src/hooks/useCustomLLMs.ts b/skyvern-frontend/src/hooks/useCustomLLMs.ts
index 37646cc6a..c4a565726 100644
--- a/skyvern-frontend/src/hooks/useCustomLLMs.ts
+++ b/skyvern-frontend/src/hooks/useCustomLLMs.ts
@@ -9,7 +9,6 @@ import {
CustomLLMUpdateRequest,
} from "@/api/types";
import { useToast } from "@/components/ui/use-toast";
-import { llmDiagnosticsQueryKey } from "@/hooks/useLLMDiagnostics";
import { useCredentialGetter } from "./useCredentialGetter";
const customLLMsQueryKey = ["customLLMs"] as const;
@@ -40,7 +39,6 @@ export function useCustomLLMs() {
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: customLLMsQueryKey });
queryClient.invalidateQueries({ queryKey: modelsQueryKey });
- queryClient.invalidateQueries({ queryKey: llmDiagnosticsQueryKey });
};
const createMutation = useMutation({
diff --git a/skyvern-frontend/src/hooks/useLLMDiagnostics.ts b/skyvern-frontend/src/hooks/useLLMDiagnostics.ts
deleted file mode 100644
index 999b91de3..000000000
--- a/skyvern-frontend/src/hooks/useLLMDiagnostics.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import axios from "axios";
-
-import { getClient } from "@/api/AxiosClient";
-
-export type LLMDiagnosticsStatusValue = "ok" | "setup_required";
-
-export type LLMConfigIssue = {
- llm_key: string;
- missing_env_vars: string[];
- detail: string;
-};
-
-export type LLMDiagnosticsResponse = {
- status: LLMDiagnosticsStatusValue;
- default_llm_key: string;
- has_server_configured_llm: boolean;
- custom_llm_count: number;
- issues: LLMConfigIssue[];
- detail?: string;
- next_step?: string;
-};
-
-export const llmDiagnosticsQueryKey = ["internal", "llms", "status"] as const;
-
-async function fetchDiagnostics(): Promise<LLMDiagnosticsResponse> {
- const client = await getClient(null);
- try {
- const response = await client.get<LLMDiagnosticsResponse>(
- "/internal/llms/status",
- );
- return response.data;
- } catch (error) {
- if (axios.isAxiosError(error) && error.response?.status === 404) {
- return {
- status: "ok",
- default_llm_key: "",
- has_server_configured_llm: true,
- custom_llm_count: 0,
- issues: [],
- };
- }
- throw error;
- }
-}
-
-function useLLMDiagnostics() {
- return useQuery<LLMDiagnosticsResponse, Error>({
- queryKey: llmDiagnosticsQueryKey,
- queryFn: fetchDiagnostics,
- retry: false,
- refetchOnWindowFocus: false,
- });
-}
-
-export { useLLMDiagnostics };
diff --git a/skyvern-frontend/src/routes/root/RootLayout.tsx b/skyvern-frontend/src/routes/root/RootLayout.tsx
index ee944070e..c28410bdd 100644
--- a/skyvern-frontend/src/routes/root/RootLayout.tsx
+++ b/skyvern-frontend/src/routes/root/RootLayout.tsx
@@ -7,7 +7,6 @@ import { Sidebar } from "./Sidebar";
import { useDebugStore } from "@/store/useDebugStore";
import { GlobalNotificationListener } from "@/components/GlobalNotificationListener";
import { SelfHealApiKeyBanner } from "@/components/SelfHealApiKeyBanner";
-import { LLMSetupBanner } from "@/components/LLMSetupBanner";
import { enable2faNotifications } from "@/util/env.ts";
function RootLayout() {
@@ -27,7 +26,6 @@ function RootLayout() {
<div className="h-full w-full">
<div className={horizontalPadding}>
<SelfHealApiKeyBanner />
- <LLMSetupBanner />
{enable2faNotifications && <GlobalNotificationListener />}
</div>
<Header />
diff --git a/skyvern-frontend/src/routes/settings/Settings.tsx b/skyvern-frontend/src/routes/settings/Settings.tsx
index de8b25a21..3a42b54a5 100644
--- a/skyvern-frontend/src/routes/settings/Settings.tsx
+++ b/skyvern-frontend/src/routes/settings/Settings.tsx
@@ -126,7 +126,7 @@ function Settings() {
<CustomCredentialServiceConfigForm />
</CardContent>
</Card>
- <Card id="custom-llms">
+ <Card>
<CardHeader className="border-b-2">
<CardTitle className="text-lg">Custom LLMs</CardTitle>
<CardDescription>
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.py
index a8c33e977..b8b60a3e0 100644
--- a/skyvern/forge/api_app.py
+++ b/skyvern/forge/api_app.py
@@ -36,7 +36,7 @@ from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.exceptions import NotFoundError
from skyvern.forge.sdk.db.models import Base
-from skyvern.forge.sdk.routes import internal_auth, internal_llms
+from skyvern.forge.sdk.routes import internal_auth
from skyvern.forge.sdk.routes.google_oauth import google_oauth_router
from skyvern.forge.sdk.routes.google_sheets import google_sheets_router
from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router, legacy_v2_router
@@ -372,9 +372,6 @@ def create_api_app() -> FastAPI:
fastapi_app.include_router(internal_auth.router, prefix="/v1")
fastapi_app.include_router(internal_auth.router, prefix="/api/v1")
fastapi_app.include_router(internal_auth.router, prefix="/api/v2")
- fastapi_app.include_router(internal_llms.router, prefix="/v1")
- fastapi_app.include_router(internal_llms.router, prefix="/api/v1")
- fastapi_app.include_router(internal_llms.router, prefix="/api/v2")
# Mirror the public /workflows surface to /agents (and hide the /workflows form from the schema).
register_agent_route_aliases(fastapi_app)
diff --git a/skyvern/forge/forge_app.py b/skyvern/forge/forge_app.py
index 79a6981a4..dd90bf02f 100644
--- a/skyvern/forge/forge_app.py
+++ b/skyvern/forge/forge_app.py
@@ -179,7 +179,7 @@ def create_forge_app() -> ForgeApp:
azure_deployment=settings.AZURE_CUA_DEPLOYMENT,
)
- app.ANTHROPIC_CLIENT = AsyncAnthropic(api_key=settings.ANTHROPIC_API_KEY or "dummy")
+ app.ANTHROPIC_CLIENT = AsyncAnthropic(api_key=settings.ANTHROPIC_API_KEY)
if settings.ENABLE_BEDROCK_ANTHROPIC:
app.ANTHROPIC_CLIENT = AsyncAnthropicBedrock()
diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.py
index 970271d4a..da0980a82 100644
--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py
+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py
@@ -1653,9 +1653,6 @@ class LLMAPIHandlerFactory:
llm_key: str,
base_parameters: dict[str, Any] | None = None,
) -> LLMAPIHandler:
- if settings.ENV == "local" and LLMConfigRegistry.get_config_issue(llm_key):
- return dummy_llm_api_handler
-
try:
llm_config = LLMConfigRegistry.get_config(llm_key)
except InvalidLLMConfigError:
diff --git a/skyvern/forge/sdk/api/llm/config_registry.py b/skyvern/forge/sdk/api/llm/config_registry.py
index 4695e6b84..2389c7ab3 100644
--- a/skyvern/forge/sdk/api/llm/config_registry.py
+++ b/skyvern/forge/sdk/api/llm/config_registry.py
@@ -1,5 +1,3 @@
-from dataclasses import dataclass
-
import structlog
from skyvern.config import settings
@@ -15,16 +13,8 @@ LOG = structlog.get_logger()
FLEX_EXECUTION_TIMEOUT_SECONDS = 180.0
-@dataclass(frozen=True)
-class LLMConfigRegistrationIssue:
- llm_key: str
- missing_env_vars: tuple[str, ...]
- detail: str
-
-
class LLMConfigRegistry:
_configs: dict[str, LLMRouterConfig | LLMConfig] = {}
- _config_issues: dict[str, LLMConfigRegistrationIssue] = {}
@staticmethod
def is_router_config(llm_key: str) -> bool:
@@ -41,60 +31,22 @@ class LLMConfigRegistry:
if missing_env_vars:
raise MissingLLMProviderEnvVarsError(llm_key, missing_env_vars)
- @classmethod
- def record_config_issue(cls, llm_key: str, missing_env_vars: list[str], detail: str) -> None:
- cls._configs.pop(llm_key, None)
- cls._config_issues[llm_key] = LLMConfigRegistrationIssue(
- llm_key=llm_key,
- missing_env_vars=tuple(missing_env_vars),
- detail=detail,
- )
- LOG.warning(
- "Skipping invalid LLM config",
- llm_key=llm_key,
- missing_env_vars=missing_env_vars,
- detail=detail,
- )
-
- @classmethod
- def get_config_issue(cls, llm_key: str) -> LLMConfigRegistrationIssue | None:
- return cls._config_issues.get(llm_key)
-
- @classmethod
- def get_config_issues(cls) -> list[LLMConfigRegistrationIssue]:
- return list(cls._config_issues.values())
-
@classmethod
def register_config(cls, llm_key: str, config: LLMRouterConfig | LLMConfig) -> None:
if llm_key in cls._configs:
raise DuplicateLLMConfigError(llm_key)
- try:
- cls.validate_config(llm_key, config)
- except MissingLLMProviderEnvVarsError as exc:
- if settings.ENV != "local":
- raise
- cls.record_config_issue(
- llm_key,
- config.get_missing_env_vars(),
- str(exc),
- )
- return
+ cls.validate_config(llm_key, config)
- cls._config_issues.pop(llm_key, None)
cls._configs[llm_key] = config
@classmethod
def deregister_config(cls, llm_key: str) -> None:
"""Remove a registered LLM config. Idempotent — no-op if key doesn't exist."""
cls._configs.pop(llm_key, None)
- cls._config_issues.pop(llm_key, None)
@classmethod
def get_config(cls, llm_key: str) -> LLMRouterConfig | LLMConfig:
- if issue := cls.get_config_issue(llm_key):
- raise InvalidLLMConfigError(issue.detail)
-
if llm_key not in cls._configs:
# If the key is not found in registered configs, treat it as a general model
if not llm_key:
@@ -2104,13 +2056,8 @@ if settings.ENABLE_OPENAI_COMPATIBLE:
openai_compatible_model_name = settings.OPENAI_COMPATIBLE_MODEL_NAME
if not openai_compatible_model_name:
- detail = "OPENAI_COMPATIBLE_MODEL_NAME is required but not set. OpenAI-compatible model will not be registered."
- if settings.ENV != "local":
- raise InvalidLLMConfigError(detail)
- LLMConfigRegistry.record_config_issue(
- openai_compatible_model_key,
- ["OPENAI_COMPATIBLE_MODEL_NAME"],
- detail,
+ raise InvalidLLMConfigError(
+ "OPENAI_COMPATIBLE_MODEL_NAME is required but not set. OpenAI-compatible model will not be registered."
)
else:
# Required environment variables to check
diff --git a/skyvern/forge/sdk/routes/internal_llms.py b/skyvern/forge/sdk/routes/internal_llms.py
deleted file mode 100644
index 4b189b879..000000000
--- a/skyvern/forge/sdk/routes/internal_llms.py
+++ /dev/null
@@ -1,132 +0,0 @@
-from enum import StrEnum
-
-import structlog
-from fastapi import APIRouter, Request
-from pydantic import BaseModel, Field
-
-from skyvern.config import settings
-from skyvern.forge import app
-from skyvern.forge.sdk.api.llm.config_registry import LLMConfigRegistrationIssue, LLMConfigRegistry
-from skyvern.forge.sdk.api.llm.exceptions import InvalidLLMConfigError
-from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
-from skyvern.forge.sdk.routes.internal_auth import _require_local_access
-from skyvern.forge.sdk.schemas.custom_llms import CustomLLMConfig
-from skyvern.forge.sdk.services.local_org_auth_token_service import SKYVERN_LOCAL_DOMAIN
-
-router = APIRouter(prefix="/internal/llms", tags=["internal"])
-LOG = structlog.get_logger()
-
-
-class LLMDiagnosticsStatus(StrEnum):
- ok = "ok"
- setup_required = "setup_required"
-
-
-class LLMConfigIssueResponse(BaseModel):
- llm_key: str
- missing_env_vars: list[str]
- detail: str
-
-
-class LLMDiagnosticsResponse(BaseModel):
- status: LLMDiagnosticsStatus
- default_llm_key: str
- has_server_configured_llm: bool
- custom_llm_count: int
- issues: list[LLMConfigIssueResponse] = Field(default_factory=list)
- detail: str | None = None
- next_step: str | None = None
-
-
-def _issue_response(issue: LLMConfigRegistrationIssue) -> LLMConfigIssueResponse:
- return LLMConfigIssueResponse(
- llm_key=issue.llm_key,
- missing_env_vars=list(issue.missing_env_vars),
- detail=issue.detail,
- )
-
-
-def _server_llm_issue(llm_key: str) -> LLMConfigIssueResponse | None:
- if issue := LLMConfigRegistry.get_config_issue(llm_key):
- return _issue_response(issue)
-
- try:
- config = LLMConfigRegistry.get_config(llm_key)
- except InvalidLLMConfigError as exc:
- return LLMConfigIssueResponse(
- llm_key=llm_key,
- missing_env_vars=[],
- detail=str(exc),
- )
-
- missing_env_vars = config.get_missing_env_vars()
- if not missing_env_vars:
- return None
-
- return LLMConfigIssueResponse(
- llm_key=llm_key,
- missing_env_vars=missing_env_vars,
- detail=(f"{llm_key} is missing required environment variables: {', '.join(missing_env_vars)}"),
- )
-
-
-async def _custom_llm_count() -> int:
- try:
- organization = await app.DATABASE.organizations.get_organization_by_domain(SKYVERN_LOCAL_DOMAIN)
- if organization is None:
- return 0
-
- tokens = await app.DATABASE.organizations.get_valid_org_auth_tokens(
- organization_id=organization.organization_id,
- token_type=OrganizationAuthTokenType.custom_llm,
- )
- except Exception:
- LOG.warning("Unable to count local custom LLM configs", exc_info=True)
- return 0
-
- valid_count = 0
- for token in tokens:
- try:
- CustomLLMConfig.model_validate_json(token.token)
- except Exception:
- LOG.warning("Skipping invalid custom LLM token in diagnostics", token_id=token.id, exc_info=True)
- continue
- valid_count += 1
- return valid_count
-
-
-async def evaluate_llm_status() -> LLMDiagnosticsResponse:
- default_issue = _server_llm_issue(settings.LLM_KEY)
- custom_llm_count = await _custom_llm_count()
- has_server_configured_llm = default_issue is None
-
- issues = [
- _issue_response(issue) for issue in LLMConfigRegistry.get_config_issues() if issue.llm_key != settings.LLM_KEY
- ]
- if default_issue:
- issues.insert(0, default_issue)
-
- if has_server_configured_llm or custom_llm_count > 0:
- return LLMDiagnosticsResponse(
- status=LLMDiagnosticsStatus.ok,
- default_llm_key=settings.LLM_KEY,
- has_server_configured_llm=has_server_configured_llm,
- custom_llm_count=custom_llm_count,
- issues=issues,
- )
-
- return LLMDiagnosticsResponse(
- status=LLMDiagnosticsStatus.setup_required,
- default_llm_key=settings.LLM_KEY,
- has_server_configured_llm=False,
- custom_llm_count=0,
- issues=issues,
- detail="Skyvern is running, but no usable LLM is configured for local OSS.",
- next_step="Open Settings > Custom LLMs and add an Ollama, OpenRouter, or OpenAI-compatible model.",
- )
-
-
[email protected]("/status", response_model=LLMDiagnosticsResponse, include_in_schema=False)
-async def llm_status(request: Request) -> LLMDiagnosticsResponse:
- _require_local_access(request)
- return await evaluate_llm_status()
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 1de0b25e5..1babae2ab 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -4616,11 +4616,35 @@ async def chain_click(
if blocking_element is None:
if blocked:
LOG.info(
- "Chain click: element is blocked by a non-interactable element, try to click by the coordinates",
+ "Chain click: element is blocked by a non-interactable element, evaluating fallback",
action=action,
element=str(skyvern_element),
locator=locator,
)
+ # An untracked overlay is intercepting an anchor: dispatching a
+ # coordinate click can trigger overlay JS that navigates away.
+ # Follow the anchor's ``href`` directly when it is a plain http
+ # link; skip uploads, explicit coordinate clicks, and downloads
+ # (JS-driven downloads may build a blob/POST on click and would
+ # fetch the wrong static resource via ``frame.goto(href)``).
+ if (
+ isinstance(action, ClickAction)
+ and not action.file_url
+ and not action.download
+ and action.x is None
+ and action.y is None
+ and skyvern_element.get_tag_name() == InteractiveElement.A
+ ):
+ navigated_href = await skyvern_element.try_navigate_via_href(page=page)
+ if navigated_href:
+ LOG.info(
+ "Chain click: bypassed coordinate fallback via direct href navigation",
+ action=action,
+ element=str(skyvern_element),
+ href=navigated_href,
+ )
+ action_results.append(ActionSuccess())
+ return action_results
else:
# Element is visible and elementFromPoint returns the target itself,
# but Playwright's click still failed (e.g. element transiently
diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.py
index 157ef1941..1b5f876ce 100644
--- a/skyvern/webeye/utils/dom.py
+++ b/skyvern/webeye/utils/dom.py
@@ -5,7 +5,7 @@ import copy
import typing
from enum import StrEnum
from random import uniform
-from urllib.parse import urlparse
+from urllib.parse import urljoin, urlparse
import structlog
from playwright.async_api import ElementHandle, FloatRect, Frame, FrameLocator, Locator, Page, TimeoutError
@@ -515,6 +515,117 @@ class SkyvernElement:
return href
+ async def resolve_http_href(self, page: Page) -> str | None:
+ """Return the anchor's ``href`` as an absolute ``http``/``https`` URL.
+
+ Returns ``None`` for non-anchor elements, empty/fragment-only hrefs, and
+ any scheme other than http/https (``javascript:``, ``mailto:``, ``tel:``…).
+ Browser-normalized hrefs are preferred so ``<base>`` and iframe URL
+ resolution match click behavior; ``urljoin`` (which correctly treats
+ root paths like ``/billpay`` as absolute against the origin) remains a
+ fallback for evaluate failures.
+ """
+ if self.get_tag_name() != InteractiveElement.A:
+ return None
+
+ raw_href: str | None = await self.get_attr("href", mode="static")
+ if not raw_href:
+ return None
+
+ href = raw_href.strip()
+ if not href or href.startswith("#"):
+ return None
+
+ resolved: str | None = None
+ try:
+ normalized = await SkyvernFrame.evaluate(
+ frame=self.get_frame(),
+ expression="(element) => element instanceof HTMLAnchorElement ? element.href : null",
+ arg=await self.get_element_handler(),
+ )
+ except Exception:
+ normalized = None
+ if isinstance(normalized, str) and normalized.strip():
+ resolved = normalized.strip()
+
+ if not resolved:
+ # Base the fallback on the owning frame's URL so root-relative
+ # hrefs inside a cross-origin iframe resolve against the frame's
+ # origin, not the top-level page's origin.
+ frame_url: str | None = None
+ try:
+ frame_url = self.get_frame().url
+ except Exception:
+ frame_url = None
+ resolved = urljoin(frame_url or page.url, href)
+
+ parsed = urlparse(resolved)
+ if parsed.scheme.lower() not in ("http", "https"):
+ return None
+ if not parsed.netloc:
+ return None
+
+ return resolved
+
+ async def try_navigate_via_href(self, page: Page) -> str | None:
+ """Follow this anchor's ``href`` directly via its owning frame.
+
+ Intended for the ``blocking_element is None and blocked=True`` branch of
+ ``chain_click``: an untracked overlay is intercepting the anchor and a
+ coordinate click would dispatch overlay JS, which can navigate to an
+ unintended URL. Following the href avoids that side effect entirely.
+
+ Returns the resolved URL on success, ``None`` when no safe URL can be
+ derived or when frame navigation raises an unrecoverable error.
+ """
+ # TODO: share a lower-level href-resolution + goto/download-success
+ # helper with ``navigate_to_a_href``. Keep the entry points separate:
+ # that one is pre-click tab/download guarding, this one is a post-
+ # click-failure fallback when coordinate click would be unsafe.
+ resolved = await self.resolve_http_href(page)
+ if not resolved:
+ return None
+
+ target = await self.get_attr("target", mode="static")
+ if target and target.strip().lower() != "_self":
+ return None
+
+ try:
+ frame = self.get_frame()
+ except Exception:
+ LOG.warning(
+ "Unable to resolve anchor owning frame; falling back to coordinate click",
+ exc_info=True,
+ href=resolved,
+ current_url=page.url,
+ )
+ return None
+
+ LOG.info(
+ "Navigating to anchor href to bypass unsafe coordinate fallback",
+ href=resolved,
+ current_url=page.url,
+ element_id=self.get_id(),
+ )
+ try:
+ await frame.goto(resolved, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ return resolved
+ except Exception as e:
+ error = str(e)
+ # Same exceptions ``navigate_to_a_href`` treats as effective
+ # navigations: aborted downloads and download-in-progress.
+ if "net::ERR_ABORTED" in error:
+ return resolved
+ if "Download is starting" in error:
+ return resolved
+ LOG.warning(
+ "Failed to navigate to anchor href; falling back to coordinate click",
+ exc_info=True,
+ href=resolved,
+ current_url=page.url,
+ )
+ return None
+
async def find_blocking_element(
self, dom: DomUtil, incremental_page: IncrementalScrapePage | None = None
) -> tuple[SkyvernElement | None, bool]:
diff --git a/tests/unit/test_chain_click_blocked_anchor_navigation.py b/tests/unit/test_chain_click_blocked_anchor_navigation.py
new file mode 100644
index 000000000..62d8095cd
--- /dev/null
+++ b/tests/unit/test_chain_click_blocked_anchor_navigation.py
@@ -0,0 +1,506 @@
+"""Tests for the blocked-anchor direct-navigation gate in chain_click.
+
+When Playwright cannot click an ``<a href>`` because an untracked/non-interactable
+overlay sits on top of it, dispatching a coordinate click into the overlay is
+unsafe: overlay JS handlers can fire and navigate to an unintended URL. The
+guard added here follows the anchor's ``href`` directly and skips the coordinate
+fallback for the ``blocking_element is None and blocked is True`` branch only.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from skyvern.config import settings
+from skyvern.webeye.utils import dom as dom_module
+from skyvern.webeye.utils.dom import InteractiveElement, SkyvernElement
+
+
+def _make_anchor_element(
+ href: str | None = "/target",
+ tag: str = InteractiveElement.A,
+ target: str | None = None,
+ frame_url: str | None = None,
+) -> SkyvernElement:
+ """Build a `SkyvernElement` stub configured as an anchor by default.
+
+ ``object.__new__`` bypasses ``__init__`` — only the methods exercised by the
+ new href-navigation helper are stubbed. Tests that care about the
+ browser-normalized href patch ``SkyvernFrame.evaluate`` via monkeypatch.
+ ``frame_url`` defaults to ``None`` so ``resolve_http_href``'s fallback
+ lands on ``page.url``; set it to simulate a cross-origin iframe.
+ """
+ elem = object.__new__(SkyvernElement)
+ elem.get_tag_name = MagicMock(return_value=tag) # type: ignore[method-assign]
+ elem.get_id = MagicMock(return_value="AAA3") # type: ignore[method-assign]
+
+ async def _get_attr(name: str, mode: str = "dynamic", **_: object) -> str | None:
+ if name == "href":
+ return href
+ if name == "target":
+ return target
+ return None
+
+ elem.get_attr = AsyncMock(side_effect=_get_attr) # type: ignore[method-assign]
+ elem.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]
+ frame = MagicMock()
+ frame.url = frame_url
+ frame.goto = AsyncMock(return_value=None)
+ elem.get_frame = MagicMock(return_value=frame) # type: ignore[method-assign]
+ return elem
+
+
+def _make_page(url: str = "https://portal.example.com/dashboard") -> MagicMock:
+ page = MagicMock()
+ page.url = url
+ page.goto = AsyncMock(return_value=None)
+ return page
+
+
+class TestTryNavigateViaHref:
+ """Unit tests for ``SkyvernElement.try_navigate_via_href``."""
+
+ @pytest.fixture(autouse=True)
+ def _stub_skyvern_frame_evaluate(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Default: normalized-href evaluate is unavailable, so the static
+ # ``urljoin`` fallback path is exercised. Tests that specifically
+ # need a normalized value (or an evaluate failure) re-patch this
+ # attribute via their own ``monkeypatch`` fixture.
+ monkeypatch.setattr(
+ dom_module.SkyvernFrame,
+ "evaluate",
+ AsyncMock(return_value=None),
+ )
+
+ @pytest.mark.asyncio
+ async def test_browser_normalized_href_is_preferred(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ dom_module.SkyvernFrame,
+ "evaluate",
+ AsyncMock(return_value="https://base.example.net/root/relative/path"),
+ )
+ elem = _make_anchor_element(href="relative/path")
+ page = _make_page("https://portal.example.com/dashboard")
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://base.example.net/root/relative/path"
+ elem.get_frame().goto.assert_awaited_once_with(
+ "https://base.example.net/root/relative/path",
+ timeout=settings.BROWSER_LOADING_TIMEOUT_MS,
+ )
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_evaluate_failure_falls_back_to_static_href_resolution(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ dom_module.SkyvernFrame,
+ "evaluate",
+ AsyncMock(side_effect=RuntimeError("evaluate failed")),
+ )
+ elem = _make_anchor_element(href="/billpay?requestedFlow=S")
+ page = _make_page("https://portal.example.com/dashboard")
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://portal.example.com/billpay?requestedFlow=S"
+ elem.get_frame().goto.assert_awaited_once()
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_relative_href_resolves_and_navigates(self) -> None:
+ elem = _make_anchor_element(href="/billpay?requestedFlow=S")
+ page = _make_page("https://portal.example.com/dashboard")
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://portal.example.com/billpay?requestedFlow=S"
+ elem.get_frame().goto.assert_awaited_once()
+ page.goto.assert_not_called()
+ call_args = elem.get_frame().goto.await_args
+ assert call_args.args[0] == "https://portal.example.com/billpay?requestedFlow=S"
+
+ @pytest.mark.asyncio
+ async def test_fallback_resolves_root_href_against_owning_frame_url(self) -> None:
+ # An anchor inside a cross-origin iframe with a root-relative href must
+ # resolve against the frame's origin (where the anchor lives), not the
+ # top-level page's origin. Only exercised when browser-normalization
+ # evaluate returns None so we fall through to ``urljoin``.
+ elem = _make_anchor_element(
+ href="/deep/path",
+ frame_url="https://iframe.example.net/inner/section",
+ )
+ page = _make_page("https://top.example.com/foo/bar")
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://iframe.example.net/deep/path"
+ elem.get_frame().goto.assert_awaited_once_with(
+ "https://iframe.example.net/deep/path",
+ timeout=settings.BROWSER_LOADING_TIMEOUT_MS,
+ )
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_root_href_replaces_base_url_subpath(self) -> None:
+ # ``urljoin`` correctly treats a root-relative href as absolute against
+ # the origin: ``/billpay`` against ``https://host/foo/bar/baz`` must
+ # resolve to ``https://host/billpay`` — never concatenated under the
+ # base URL's subpath.
+ elem = _make_anchor_element(href="/billpay")
+ page = _make_page("https://portal.example.com/foo/bar/baz")
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://portal.example.com/billpay"
+ elem.get_frame().goto.assert_awaited_once_with(
+ "https://portal.example.com/billpay",
+ timeout=settings.BROWSER_LOADING_TIMEOUT_MS,
+ )
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_absolute_same_origin_href_navigates(self) -> None:
+ elem = _make_anchor_element(href="https://portal.example.com/billpay")
+ page = _make_page("https://portal.example.com/dashboard")
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://portal.example.com/billpay"
+ elem.get_frame().goto.assert_awaited_once_with(
+ "https://portal.example.com/billpay",
+ timeout=settings.BROWSER_LOADING_TIMEOUT_MS,
+ )
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_absolute_cross_origin_href_navigates(self) -> None:
+ elem = _make_anchor_element(href="https://other.example.net/foo")
+ page = _make_page("https://portal.example.com/dashboard")
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://other.example.net/foo"
+ elem.get_frame().goto.assert_awaited_once()
+ page.goto.assert_not_called()
+
+ @pytest.mark.parametrize("target", ["_blank", "_top", "_parent", "resultsFrame"])
+ @pytest.mark.asyncio
+ async def test_non_self_target_returns_none_without_goto(self, target: str) -> None:
+ elem = _make_anchor_element(href="/billpay", target=target)
+ page = _make_page("https://portal.example.com/dashboard")
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ elem.get_frame().goto.assert_not_called()
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_non_anchor_returns_none(self) -> None:
+ elem = _make_anchor_element(tag=InteractiveElement.BUTTON, href="/target")
+ page = _make_page()
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_empty_href_returns_none(self) -> None:
+ elem = _make_anchor_element(href="")
+ page = _make_page()
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_missing_href_returns_none(self) -> None:
+ elem = _make_anchor_element(href=None)
+ page = _make_page()
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_fragment_only_href_returns_none(self) -> None:
+ elem = _make_anchor_element(href="#section")
+ page = _make_page()
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_javascript_scheme_returns_none(self) -> None:
+ elem = _make_anchor_element(href="javascript:void(0)")
+ page = _make_page()
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_mailto_scheme_returns_none(self) -> None:
+ elem = _make_anchor_element(href="mailto:[email protected]")
+ page = _make_page()
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_tel_scheme_returns_none(self) -> None:
+ elem = _make_anchor_element(href="tel:+15551234567")
+ page = _make_page()
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_goto_generic_failure_returns_none(self) -> None:
+ elem = _make_anchor_element(href="/target")
+ page = _make_page()
+ elem.get_frame().goto = AsyncMock(side_effect=RuntimeError("something else"))
+
+ assert await elem.try_navigate_via_href(page=page) is None
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_goto_err_aborted_is_treated_as_navigated(self) -> None:
+ # Mirrors ``navigate_to_a_href``: download-triggering anchors surface as
+ # net::ERR_ABORTED but the navigation intent was honored.
+ elem = _make_anchor_element(href="/download.pdf")
+ page = _make_page()
+ elem.get_frame().goto = AsyncMock(side_effect=RuntimeError("net::ERR_ABORTED"))
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://portal.example.com/download.pdf"
+ page.goto.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_goto_download_starting_is_treated_as_navigated(self) -> None:
+ elem = _make_anchor_element(href="/statement.pdf")
+ page = _make_page()
+ elem.get_frame().goto = AsyncMock(side_effect=RuntimeError("Frame.goto: Download is starting"))
+
+ result = await elem.try_navigate_via_href(page=page)
+
+ assert result == "https://portal.example.com/statement.pdf"
+ page.goto.assert_not_called()
+
+
+class TestChainClickBlockedAnchorNavigation:
+ """Integration tests: chain_click must call the new helper only in the
+ ``blocking_element is None and blocked=True`` branch, and only for anchors
+ whose href resolves to http/https."""
+
+ @staticmethod
+ async def _run_chain_click(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ blocked: bool,
+ tag: str,
+ href: str | None,
+ file_url: str | None = None,
+ action_x: int | None = None,
+ action_y: int | None = None,
+ action_download: bool = False,
+ navigate_result: str | None = "https://portal.example.com/billpay",
+ ) -> tuple[list, AsyncMock, AsyncMock]:
+ """Invoke chain_click through the ``blocking_element is None`` path
+ with tightly-scoped stubs. Returns (results, coordinate_click_mock,
+ try_navigate_mock)."""
+ from skyvern.webeye.actions import handler as handler_module
+ from skyvern.webeye.actions.actions import ClickAction
+
+ # Stub out the entire pre-blocking-check block so we jump straight to
+ # find_blocking_element. In chain_click, the first Playwright click
+ # is invoked via EventStrategyFactory.click_element; make it raise so
+ # we enter the fallback chain.
+ monkeypatch.setattr(
+ handler_module.EventStrategyFactory,
+ "click_element",
+ AsyncMock(side_effect=RuntimeError("first click failed")),
+ )
+
+ # Stub file chooser + skyvern_context.
+ monkeypatch.setattr(handler_module.skyvern_context, "current", MagicMock(return_value=None))
+ # ``file_url`` on the action triggers upstream download+secret lookups
+ # that require app state we don't provide. Stub them to no-ops so the
+ # test can reach the blocking-element branch we actually care about.
+ monkeypatch.setattr(
+ handler_module,
+ "get_actual_value_of_parameter_if_secret_with_task",
+ MagicMock(side_effect=lambda _task, p: p),
+ )
+ monkeypatch.setattr(
+ handler_module.handler_utils,
+ "download_file",
+ AsyncMock(return_value="/tmp/mock-file"),
+ )
+
+ # Build a minimal element with the stubs chain_click reaches.
+ elem = object.__new__(SkyvernElement)
+ # chain_click's LOG.info calls invoke ``str(skyvern_element)`` which
+ # goes through ``SkyvernElement.__repr__``; that reads the private
+ # ``__static_element`` attribute set by ``__init__``. Since we bypass
+ # ``__init__`` here, seed the name-mangled attribute directly.
+ elem._SkyvernElement__static_element = {"id": "AAA3", "tagName": tag} # type: ignore[attr-defined]
+ elem.get_tag_name = MagicMock(return_value=tag) # type: ignore[method-assign]
+ elem.get_id = MagicMock(return_value="AAA3") # type: ignore[method-assign]
+ elem.locator = MagicMock()
+
+ async def _get_attr(name: str, mode: str = "dynamic", **_: object) -> str | None:
+ if name == "href":
+ return href
+ if name == "onclick":
+ return None
+ return None
+
+ elem.get_attr = AsyncMock(side_effect=_get_attr) # type: ignore[method-assign]
+ elem.navigate_to_a_href = AsyncMock(return_value=None) # type: ignore[method-assign]
+ elem.find_bound_label_by_attr_id = AsyncMock(return_value=None) # type: ignore[method-assign]
+ elem.find_bound_label_by_direct_parent = AsyncMock(return_value=None) # type: ignore[method-assign]
+ elem.is_visible = AsyncMock(return_value=True) # type: ignore[method-assign]
+ elem.find_blocking_element = AsyncMock(return_value=(None, blocked)) # type: ignore[method-assign]
+ elem.coordinate_click = AsyncMock(return_value=None) # type: ignore[method-assign]
+ elem.click_in_javascript = AsyncMock(return_value=None) # type: ignore[method-assign]
+
+ try_navigate = AsyncMock(return_value=navigate_result)
+ elem.try_navigate_via_href = try_navigate # type: ignore[method-assign]
+
+ page = MagicMock()
+ page.url = "https://portal.example.com/dashboard"
+ page.goto = AsyncMock(return_value=None)
+ page.on = MagicMock()
+
+ task = MagicMock()
+ task.organization_id = "org_test"
+ scraped_page = MagicMock()
+ action = ClickAction(
+ element_id="AAA3",
+ file_url=file_url,
+ download=action_download,
+ x=action_x,
+ y=action_y,
+ )
+
+ results = await handler_module.chain_click(
+ task=task,
+ scraped_page=scraped_page,
+ page=page,
+ action=action,
+ skyvern_element=elem,
+ )
+ return results, elem.coordinate_click, try_navigate
+
+ @pytest.mark.asyncio
+ async def test_blocked_anchor_navigates_via_href_and_skips_coordinate_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from skyvern.webeye.actions.responses import ActionSuccess
+
+ results, coord_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href="/billpay?requestedFlow=S",
+ )
+
+ navigate.assert_awaited_once()
+ coord_click.assert_not_called()
+ assert results and isinstance(results[-1], ActionSuccess)
+
+ @pytest.mark.asyncio
+ async def test_blocked_non_anchor_still_uses_coordinate_click(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ results, coord_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.BUTTON,
+ href=None,
+ )
+
+ navigate.assert_not_called()
+ coord_click.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_unblocked_anchor_still_uses_coordinate_click(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # blocked=False = the transient-instability React re-render case; the
+ # coordinate fallback is safe there. We must not divert to href nav.
+ results, coord_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=False,
+ tag=InteractiveElement.A,
+ href="/target",
+ )
+
+ navigate.assert_not_called()
+ coord_click.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_blocked_anchor_with_upload_action_skips_href_navigation(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ results, coord_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href="/target",
+ file_url="s3://bucket/file.pdf",
+ )
+
+ navigate.assert_not_called()
+ coord_click.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_blocked_anchor_with_download_action_skips_href_navigation(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # JS-driven downloads (onclick builds a blob/POST) would fetch the
+ # wrong static resource if we diverted to ``frame.goto(href)``.
+ # Downloads must keep going through the normal click path.
+ results, coord_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href="/target",
+ action_download=True,
+ )
+
+ navigate.assert_not_called()
+ coord_click.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_blocked_anchor_with_explicit_coordinates_skips_href_navigation(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ results, coord_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href="/target",
+ action_x=100,
+ action_y=200,
+ )
+
+ navigate.assert_not_called()
+ coord_click.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_blocked_anchor_where_helper_returns_none_falls_through_to_coordinate_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # If the helper cannot resolve a safe URL (e.g. javascript:) it returns
+ # None; the existing coordinate fallback must still run.
+ results, coord_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href="javascript:void(0)",
+ navigate_result=None,
+ )
+
+ navigate.assert_awaited_once()
+ coord_click.assert_awaited_once()
+
+
+def test_dom_module_exports_try_navigate_via_href() -> None:
+ """Sanity check that the helper is a method on ``SkyvernElement``."""
+ assert hasattr(dom_module.SkyvernElement, "try_navigate_via_href")
diff --git a/tests/unit/test_internal_llms.py b/tests/unit/test_internal_llms.py
deleted file mode 100644
index 9d25a64d8..000000000
--- a/tests/unit/test_internal_llms.py
+++ /dev/null
@@ -1,146 +0,0 @@
-from collections.abc import Iterator
-from datetime import datetime, timezone
-from types import SimpleNamespace
-
-import pytest
-
-from skyvern.forge.sdk.api.llm import config_registry
-from skyvern.forge.sdk.api.llm.config_registry import LLMConfigRegistry
-from skyvern.forge.sdk.api.llm.exceptions import InvalidLLMConfigError, MissingLLMProviderEnvVarsError
-from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
-from skyvern.forge.sdk.routes import internal_llms
-from skyvern.forge.sdk.routes.internal_llms import LLMDiagnosticsStatus
-from skyvern.forge.sdk.schemas.custom_llms import CustomLLMConfig
-from skyvern.forge.sdk.schemas.organizations import Organization, OrganizationAuthToken
-from skyvern.forge.sdk.services.local_org_auth_token_service import SKYVERN_LOCAL_DOMAIN
-from skyvern.schemas.llm import LLMConfig
-
-
-class FakeOrganizationsRepository:
- def __init__(self, organization: Organization | None, tokens: list[OrganizationAuthToken] | None = None) -> None:
- self.organization = organization
- self.tokens = tokens or []
-
- async def get_organization_by_domain(self, domain: str) -> Organization | None:
- if domain == SKYVERN_LOCAL_DOMAIN:
- return self.organization
- return None
-
- async def get_valid_org_auth_tokens(
- self,
- organization_id: str,
- token_type: OrganizationAuthTokenType,
- ) -> list[OrganizationAuthToken]:
- return [
- token
- for token in self.tokens
- if token.organization_id == organization_id and token.token_type == token_type and token.valid
- ]
-
-
[email protected](autouse=True)
-def restore_llm_registry() -> Iterator[None]:
- original_configs = dict(LLMConfigRegistry._configs)
- original_issues = dict(LLMConfigRegistry._config_issues)
-
- LLMConfigRegistry._configs.clear()
- LLMConfigRegistry._config_issues.clear()
-
- yield
-
- LLMConfigRegistry._configs.clear()
- LLMConfigRegistry._configs.update(original_configs)
- LLMConfigRegistry._config_issues.clear()
- LLMConfigRegistry._config_issues.update(original_issues)
-
-
-def _org(organization_id: str = "o_local") -> Organization:
- now = datetime.now(timezone.utc)
- return Organization(
- organization_id=organization_id,
- organization_name="Skyvern-local",
- domain=SKYVERN_LOCAL_DOMAIN,
- created_at=now,
- modified_at=now,
- )
-
-
-def _custom_llm_token(organization_id: str) -> OrganizationAuthToken:
- now = datetime.now(timezone.utc)
- config = CustomLLMConfig(display_name="Local Llama", provider="ollama", model_name="llama3.1")
- return OrganizationAuthToken(
- id="oat_custom_1",
- organization_id=organization_id,
- token_type=OrganizationAuthTokenType.custom_llm,
- token=config.model_dump_json(),
- valid=True,
- created_at=now,
- modified_at=now,
- )
-
-
-def test_local_registry_records_missing_env_vars(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config_registry.settings, "ENV", "local")
-
- LLMConfigRegistry.register_config(
- "UNIT_MISSING",
- LLMConfig("unit/missing", ["UNIT_MISSING_LLM_API_KEY"], supports_vision=True, add_assistant_prefix=False),
- )
-
- issue = LLMConfigRegistry.get_config_issue("UNIT_MISSING")
- assert issue is not None
- assert issue.missing_env_vars == ("UNIT_MISSING_LLM_API_KEY",)
- assert not LLMConfigRegistry.is_registered("UNIT_MISSING")
-
- with pytest.raises(InvalidLLMConfigError):
- LLMConfigRegistry.get_config("UNIT_MISSING")
-
-
-def test_non_local_registry_still_fails_fast(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(config_registry.settings, "ENV", "prod")
-
- with pytest.raises(MissingLLMProviderEnvVarsError):
- LLMConfigRegistry.register_config(
- "UNIT_MISSING",
- LLMConfig("unit/missing", ["UNIT_MISSING_LLM_API_KEY"], supports_vision=True, add_assistant_prefix=False),
- )
-
-
-async def test_llm_status_requires_setup_when_default_and_custom_llms_are_missing(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(internal_llms.settings, "LLM_KEY", "UNIT_DEFAULT")
- monkeypatch.setattr(internal_llms.settings, "LLM_API_KEY", None)
- monkeypatch.setattr(
- internal_llms.app,
- "DATABASE",
- SimpleNamespace(organizations=FakeOrganizationsRepository(organization=None)),
- )
-
- response = await internal_llms.evaluate_llm_status()
-
- assert response.status is LLMDiagnosticsStatus.setup_required
- assert response.has_server_configured_llm is False
- assert response.custom_llm_count == 0
- assert response.issues[0].missing_env_vars == ["LLM_API_KEY"]
-
-
-async def test_llm_status_is_ok_when_custom_llm_exists(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- org = _org()
- monkeypatch.setattr(internal_llms.settings, "LLM_KEY", "UNIT_DEFAULT")
- monkeypatch.setattr(internal_llms.settings, "LLM_API_KEY", None)
- monkeypatch.setattr(
- internal_llms.app,
- "DATABASE",
- SimpleNamespace(organizations=FakeOrganizationsRepository(org, [_custom_llm_token(org.organization_id)])),
- )
-
- response = await internal_llms.evaluate_llm_status()
-
- assert response.status is LLMDiagnosticsStatus.ok
- assert response.has_server_configured_llm is False
- assert response.custom_llm_count == 1