Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-10819: asymmetric debug-session profile handling for LoginBlock (#6572)
LawyZheng873312a2a6e4
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex 640c2010d..86a86dca2 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -537,6 +537,12 @@ export type DebugSessionApiResponse = {created_at: string;modified_at: string;vnc_streaming_supported: boolean | null;+ pbs_browser_profile_id: string | null;+};++export type DebugLoginBlockCompatibilityResponse = {+ compatible: boolean;+ reason: "pbs_no_profile" | "pbs_different_profile" | null;};export type WorkflowRunApiResponse = {diff --git a/skyvern-frontend/src/routes/workflows/debugger/DebugSessionProfileIncompatibleDialog.tsx b/skyvern-frontend/src/routes/workflows/debugger/DebugSessionProfileIncompatibleDialog.tsxnew file mode 100644index 000000000..fe7a1caee--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/debugger/DebugSessionProfileIncompatibleDialog.tsx@@ -0,0 +1,58 @@+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";++import type { DebugSessionProfileIncompatibilityReason } from "./debugSessionProfileCompatibility";++const REASON_COPY: Record<DebugSessionProfileIncompatibilityReason, string> = {+ pbs_no_profile:+ "The visible debugger browser doesn't have a saved profile, but this login block's credential does. Continuing will run the login in the visible browser without the saved cookies — you may need to log in manually.",+ pbs_different_profile:+ "The visible debugger browser is running a different saved profile than this login block's credential. Continuing will run the login in the visible browser without the credential's saved cookies — you may need to log in manually.",+};++type Props = {+ open: boolean;+ reason: DebugSessionProfileIncompatibilityReason | null;+ onContinue: () => void;+ onCancel: () => void;+};++function DebugSessionProfileIncompatibleDialog({+ open,+ reason,+ onContinue,+ onCancel,+}: Props) {+ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!next) onCancel();+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Profile mismatch with the debugger browser</DialogTitle>+ <DialogDescription>+ {reason ? REASON_COPY[reason] : null}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button variant="outline" onClick={onCancel}>+ Cancel+ </Button>+ <Button onClick={onContinue}>Continue</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++export { DebugSessionProfileIncompatibleDialog };diff --git a/skyvern-frontend/src/routes/workflows/debugger/__tests__/debugSessionProfileCompatibility.test.ts b/skyvern-frontend/src/routes/workflows/debugger/__tests__/debugSessionProfileCompatibility.test.tsnew file mode 100644index 000000000..c606b6caa--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/debugger/__tests__/debugSessionProfileCompatibility.test.ts@@ -0,0 +1,533 @@+import { describe, expect, it } from "vitest";++import type { CredentialApiResponse } from "@/api/types";++import {+ decideDebugLoginPlayGate,+ evaluateDebugSessionProfileCompatibility,+ gateActionFromBackendCompatibility,+ resolveLoginBlockCredential,+} from "../debugSessionProfileCompatibility";++const LOGIN_BLOCK_WITH_CRED = {+ block_type: "login",+ parameters: [{ parameter_type: "credential", credential_id: "cred_42" }],+};++const LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED = {+ block_type: "login",+ parameters: [+ {+ parameter_type: "workflow",+ key: "credential_param",+ workflow_parameter_type: "credential_id",+ default_value: "cred_42",+ },+ ],+};++const LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED_NO_DEFAULT = {+ block_type: "login",+ parameters: [+ {+ parameter_type: "workflow",+ key: "credential_param",+ workflow_parameter_type: "credential_id",+ default_value: null,+ },+ ],+};++const TASK_BLOCK = {+ block_type: "task",+ parameters: [],+};++function makeCredential(+ overrides: Partial<CredentialApiResponse>,+): CredentialApiResponse {+ return {+ credential_id: "cred_default",+ credential: { username: "u", totp_type: "none" },+ credential_type: "password",+ name: "default",+ browser_profile_id: null,+ ...overrides,+ };+}++describe("evaluateDebugSessionProfileCompatibility", () => {+ it("returns compatible when the credential has no saved browser profile", () => {+ const result = evaluateDebugSessionProfileCompatibility({+ pbsBrowserProfileId: null,+ credentialBrowserProfileId: null,+ });++ expect(result).toEqual({ compatible: true, reason: null });+ });++ it("returns pbs_no_profile when the PBS has no profile but the credential does", () => {+ const result = evaluateDebugSessionProfileCompatibility({+ pbsBrowserProfileId: null,+ credentialBrowserProfileId: "bp_cred",+ });++ expect(result).toEqual({ compatible: false, reason: "pbs_no_profile" });+ });++ it("returns pbs_different_profile when the saved profiles differ", () => {+ const result = evaluateDebugSessionProfileCompatibility({+ pbsBrowserProfileId: "bp_other",+ credentialBrowserProfileId: "bp_cred",+ });++ expect(result).toEqual({+ compatible: false,+ reason: "pbs_different_profile",+ });+ });++ it("returns compatible when the PBS profile matches the credential profile", () => {+ const result = evaluateDebugSessionProfileCompatibility({+ pbsBrowserProfileId: "bp_same",+ credentialBrowserProfileId: "bp_same",+ });++ expect(result).toEqual({ compatible: true, reason: null });+ });+});++describe("resolveLoginBlockCredential", () => {+ it("returns no-credential-parameter when the block is not a LoginBlock", () => {+ const result = resolveLoginBlockCredential({+ block: { block_type: "task", parameters: [] },+ credentials: [],+ });+ expect(result).toEqual({ status: "no-credential-parameter" });+ });++ it("returns no-credential-parameter when the LoginBlock has no credential param", () => {+ const result = resolveLoginBlockCredential({+ block: {+ block_type: "login",+ parameters: [{ parameter_type: "workflow", key: "x" }],+ },+ credentials: [],+ });+ expect(result).toEqual({ status: "no-credential-parameter" });+ });++ it("returns credential-not-in-list when the referenced credential is missing from the supplied list", () => {+ const result = resolveLoginBlockCredential({+ block: {+ block_type: "login",+ parameters: [+ { parameter_type: "credential", credential_id: "cred_missing" },+ ],+ },+ credentials: [makeCredential({ credential_id: "cred_other" })],+ });+ expect(result).toEqual({+ status: "credential-not-in-list",+ credentialId: "cred_missing",+ });+ });++ it("returns credential-not-in-list when credentials list is empty but the block references one", () => {+ const result = resolveLoginBlockCredential({+ block: {+ block_type: "login",+ parameters: [+ { parameter_type: "credential", credential_id: "cred_anything" },+ ],+ },+ credentials: [],+ });+ expect(result).toEqual({+ status: "credential-not-in-list",+ credentialId: "cred_anything",+ });+ });++ it("returns resolved with the credential's saved browser_profile_id when present", () => {+ const result = resolveLoginBlockCredential({+ block: {+ block_type: "login",+ parameters: [+ { parameter_type: "credential", credential_id: "cred_42" },+ ],+ },+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_42",+ }),+ ],+ });+ expect(result).toEqual({ status: "resolved", browserProfileId: "bp_42" });+ });++ it("returns resolved with null profile when the credential exists but has no profile", () => {+ const result = resolveLoginBlockCredential({+ block: {+ block_type: "login",+ parameters: [+ { parameter_type: "credential", credential_id: "cred_42" },+ ],+ },+ credentials: [+ makeCredential({ credential_id: "cred_42", browser_profile_id: null }),+ ],+ });+ expect(result).toEqual({ status: "resolved", browserProfileId: null });+ });++ it("resolves a workflow-parameter CREDENTIAL_ID via its default_value when the credential is in the list", () => {+ const result = resolveLoginBlockCredential({+ block: LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_42",+ }),+ ],+ });+ expect(result).toEqual({ status: "resolved", browserProfileId: "bp_42" });+ });++ it("returns credential-not-in-list when a workflow-parameter CREDENTIAL_ID default_value is missing from the list", () => {+ const result = resolveLoginBlockCredential({+ block: LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED,+ credentials: [makeCredential({ credential_id: "cred_other" })],+ });+ expect(result).toEqual({+ status: "credential-not-in-list",+ credentialId: "cred_42",+ });+ });++ it("returns credential-not-in-list with an empty id when a workflow-parameter CREDENTIAL_ID has no default_value (fail-closed to backend lookup)", () => {+ const result = resolveLoginBlockCredential({+ block: LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED_NO_DEFAULT,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_42",+ }),+ ],+ });+ expect(result).toEqual({+ status: "credential-not-in-list",+ credentialId: "",+ });+ });++ it("ignores a workflow parameter that is not of type credential_id (existing direct behavior unchanged)", () => {+ const result = resolveLoginBlockCredential({+ block: {+ block_type: "login",+ parameters: [+ {+ parameter_type: "workflow",+ key: "some_text",+ workflow_parameter_type: "string",+ default_value: "hello",+ },+ ],+ },+ credentials: [],+ });+ expect(result).toEqual({ status: "no-credential-parameter" });+ });+});++describe("decideDebugLoginPlayGate", () => {+ it("proceeds when the block isn't a LoginBlock", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "task",+ hasDebugSession: true,+ credentialsState: "ready",+ block: TASK_BLOCK,+ credentials: [],+ pbsBrowserProfileId: null,+ });+ expect(action).toEqual({ kind: "proceed" });+ });++ it("proceeds when there is no debug session", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: false,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: [],+ pbsBrowserProfileId: null,+ });+ expect(action).toEqual({ kind: "proceed" });+ });++ it("returns block-loading while credentials are still loading", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "loading",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: undefined,+ pbsBrowserProfileId: null,+ });+ expect(action).toEqual({ kind: "block-loading" });+ });++ it("returns block-retry with credentials-error when the credentials query errored", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "error",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: undefined,+ pbsBrowserProfileId: null,+ });+ expect(action).toEqual({+ kind: "block-retry",+ reason: "credentials-error",+ });+ });++ it("returns block-loading defensively when state is ready but data is undefined", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: undefined,+ pbsBrowserProfileId: null,+ });+ expect(action).toEqual({ kind: "block-loading" });+ });++ it("returns block-retry with credential-not-found when the referenced credential is missing from the fetched list", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: [+ // cred_42 is what the block references; only cred_other is in the+ // fetched window (e.g. paginated past page 1).+ makeCredential({+ credential_id: "cred_other",+ browser_profile_id: "bp_other",+ }),+ ],+ pbsBrowserProfileId: "bp_other",+ });+ expect(action).toEqual({+ kind: "block-retry",+ reason: "credential-not-found",+ });+ });++ it("returns block-retry with credential-not-found when the fetched list is empty", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: [],+ pbsBrowserProfileId: "bp_anything",+ });+ expect(action).toEqual({+ kind: "block-retry",+ reason: "credential-not-found",+ });+ });++ it("shows the modal when ready credentials reveal a profile mismatch", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_42",+ }),+ ],+ pbsBrowserProfileId: "bp_other",+ });+ expect(action).toEqual({+ kind: "show-modal",+ reason: "pbs_different_profile",+ });+ });++ it("shows the modal when the PBS lacks a profile but the credential has one", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_42",+ }),+ ],+ pbsBrowserProfileId: null,+ });+ expect(action).toEqual({ kind: "show-modal", reason: "pbs_no_profile" });+ });++ it("proceeds when credentials are ready and profiles match", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_same",+ }),+ ],+ pbsBrowserProfileId: "bp_same",+ });+ expect(action).toEqual({ kind: "proceed" });+ });++ it("proceeds when the LoginBlock credential has no saved profile, regardless of PBS state", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_CRED,+ credentials: [+ makeCredential({ credential_id: "cred_42", browser_profile_id: null }),+ ],+ pbsBrowserProfileId: "bp_anything",+ });+ expect(action).toEqual({ kind: "proceed" });+ });++ it("proceeds when the LoginBlock has no credential parameter at all", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: { block_type: "login", parameters: [] },+ credentials: [],+ pbsBrowserProfileId: "bp_anything",+ });+ expect(action).toEqual({ kind: "proceed" });+ });++ it("shows the modal for a workflow-parameter CREDENTIAL_ID whose default_value resolves to a different profile", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_42",+ }),+ ],+ pbsBrowserProfileId: "bp_other",+ });+ expect(action).toEqual({+ kind: "show-modal",+ reason: "pbs_different_profile",+ });+ });++ it("proceeds when a workflow-parameter CREDENTIAL_ID resolves to a matching profile", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_same",+ }),+ ],+ pbsBrowserProfileId: "bp_same",+ });+ expect(action).toEqual({ kind: "proceed" });+ });++ it("returns block-retry with credential-not-found when a workflow-parameter CREDENTIAL_ID default_value is not in the bounded list", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED,+ credentials: [+ makeCredential({+ credential_id: "cred_other",+ browser_profile_id: "bp_other",+ }),+ ],+ pbsBrowserProfileId: "bp_other",+ });+ expect(action).toEqual({+ kind: "block-retry",+ reason: "credential-not-found",+ });+ });++ it("returns block-retry with credential-not-found when a workflow-parameter CREDENTIAL_ID has no default_value (fail-closed)", () => {+ const action = decideDebugLoginPlayGate({+ blockType: "login",+ hasDebugSession: true,+ credentialsState: "ready",+ block: LOGIN_BLOCK_WITH_WORKFLOW_PARAM_CRED_NO_DEFAULT,+ credentials: [+ makeCredential({+ credential_id: "cred_42",+ browser_profile_id: "bp_42",+ }),+ ],+ pbsBrowserProfileId: "bp_other",+ });+ expect(action).toEqual({+ kind: "block-retry",+ reason: "credential-not-found",+ });+ });+});++describe("gateActionFromBackendCompatibility", () => {+ it("returns proceed when the backend reports compatible", () => {+ expect(+ gateActionFromBackendCompatibility({ compatible: true, reason: null }),+ ).toEqual({ kind: "proceed" });+ });++ it("fail-safes to block-retry credentials-error when the backend payload is incompatible-but-reasonless", () => {+ expect(+ gateActionFromBackendCompatibility({ compatible: false, reason: null }),+ ).toEqual({ kind: "block-retry", reason: "credentials-error" });+ });++ it("returns show-modal with pbs_no_profile when the backend says so", () => {+ expect(+ gateActionFromBackendCompatibility({+ compatible: false,+ reason: "pbs_no_profile",+ }),+ ).toEqual({ kind: "show-modal", reason: "pbs_no_profile" });+ });++ it("returns show-modal with pbs_different_profile when the backend says so", () => {+ expect(+ gateActionFromBackendCompatibility({+ compatible: false,+ reason: "pbs_different_profile",+ }),+ ).toEqual({ kind: "show-modal", reason: "pbs_different_profile" });+ });+});diff --git a/skyvern-frontend/src/routes/workflows/debugger/debugSessionProfileCompatibility.ts b/skyvern-frontend/src/routes/workflows/debugger/debugSessionProfileCompatibility.tsnew file mode 100644index 000000000..804253c75--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/debugger/debugSessionProfileCompatibility.ts@@ -0,0 +1,255 @@+import type {+ CredentialApiResponse,+ DebugLoginBlockCompatibilityResponse,+} from "@/api/types";++export const DEBUG_LOGIN_GATE_CREDENTIALS_PAGE_SIZE = 200;++export type DebugSessionProfileIncompatibilityReason =+ | "pbs_no_profile"+ | "pbs_different_profile";++export type DebugSessionProfileCompatibilityResult = {+ compatible: boolean;+ reason: DebugSessionProfileIncompatibilityReason | null;+};++export type CredentialsLoadState = "loading" | "ready" | "error";++/**+ * Outcome of resolving the LoginBlock's credential reference against the+ * currently fetched credentials list.+ *+ * - `no-credential-parameter`: the block has no credential parameter at all,+ * so there is no saved profile to enforce.+ * - `resolved`: the credential was found in the list. `browserProfileId` is+ * its saved profile, or `null` if no profile is attached.+ * - `credential-not-in-list`: the block references a credential by id but+ * that id is not in the fetched list (paginated past the window, deleted,+ * inaccessible, etc.). The gate must not collapse this into "no profile"+ * — it has to fail closed and let the caller refetch.+ */+export type CredentialResolution =+ | { status: "no-credential-parameter" }+ | { status: "resolved"; browserProfileId: string | null }+ | { status: "credential-not-in-list"; credentialId: string };++export type DebugLoginPlayGateRetryReason =+ | "credentials-error"+ | "credential-not-found";++export type DebugLoginPlayGateAction =+ | { kind: "proceed" }+ | { kind: "block-loading" }+ | { kind: "block-retry"; reason: DebugLoginPlayGateRetryReason }+ | { kind: "show-modal"; reason: DebugSessionProfileIncompatibilityReason };++type BlockLike = {+ block_type?: string | null;+ label?: string;+ parameters?: ReadonlyArray<unknown> | null;+};++type ParameterLike = {+ parameter_type?: string | null;+ credential_id?: string | null;+ workflow_parameter_type?: string | null;+ default_value?: unknown;+};++/**+ * Mirrors backend `_resolve_login_block_browser_profile_id` for the FE+ * pre-check. Walks the LoginBlock's parameters, picks the first credential+ * reference, and reports whether that credential is present in the supplied+ * list and what its saved `browser_profile_id` is.+ *+ * Two reference styles are recognized, matching the backend resolver:+ * 1. CredentialParameter — direct `credential_id`.+ * 2. WorkflowParameter with `workflow_parameter_type === "credential_id"` —+ * run-time supplies the id; pre-run we use `default_value` (the same+ * fallback the backend resolver takes when no run params exist).+ *+ * The expressive return type is load-bearing: `credential-not-in-list` is+ * what stops the loading-page bypass — a credential whose id never appears+ * in the fetched window, or a Style-2 reference whose `default_value` we+ * cannot resolve locally, must not be silently treated as "no profile".+ */+export function resolveLoginBlockCredential(args: {+ block: BlockLike | null | undefined;+ credentials: ReadonlyArray<CredentialApiResponse> | null | undefined;+}): CredentialResolution {+ const { block, credentials } = args;+ if (!block || block.block_type !== "login") {+ return { status: "no-credential-parameter" };+ }+ const parameters = block.parameters ?? [];++ let referencedCredentialId: string | null = null;+ let sawUnresolvableCredentialReference = false;+ for (const rawParam of parameters) {+ const param = rawParam as ParameterLike;+ if (param?.parameter_type === "credential") {+ const credentialId = param.credential_id ?? null;+ if (!credentialId) continue;+ referencedCredentialId = credentialId;+ break;+ }+ if (+ param?.parameter_type === "workflow" &&+ param?.workflow_parameter_type === "credential_id"+ ) {+ const dv = param.default_value;+ const credentialId = typeof dv === "string" && dv ? dv : null;+ if (!credentialId) {+ sawUnresolvableCredentialReference = true;+ continue;+ }+ referencedCredentialId = credentialId;+ break;+ }+ }++ if (referencedCredentialId === null) {+ if (sawUnresolvableCredentialReference) {+ return {+ status: "credential-not-in-list",+ credentialId: "",+ };+ }+ return { status: "no-credential-parameter" };+ }++ const list = credentials ?? [];+ const credential = list.find(+ (c) => c.credential_id === referencedCredentialId,+ );+ if (!credential) {+ return {+ status: "credential-not-in-list",+ credentialId: referencedCredentialId,+ };+ }+ return {+ status: "resolved",+ browserProfileId: credential.browser_profile_id ?? null,+ };+}++/**+ * Mirrors backend `_evaluate_debug_session_profile_decision`.+ *+ * The visible PBS only "matches" the credential when both saved profiles are+ * identical. Any mismatch means running the LoginBlock through the credential's+ * saved profile would launch a fresh browser the user can't see — exactly the+ * stream divergence customers reported. The modal that consumes this verdict+ * is informational; the backend still enforces the asymmetric behavior on+ * the run path.+ */+export function evaluateDebugSessionProfileCompatibility(args: {+ pbsBrowserProfileId: string | null;+ credentialBrowserProfileId: string | null;+}): DebugSessionProfileCompatibilityResult {+ const { pbsBrowserProfileId, credentialBrowserProfileId } = args;++ if (!credentialBrowserProfileId) {+ return { compatible: true, reason: null };+ }+ if (!pbsBrowserProfileId) {+ return { compatible: false, reason: "pbs_no_profile" };+ }+ if (pbsBrowserProfileId !== credentialBrowserProfileId) {+ return { compatible: false, reason: "pbs_different_profile" };+ }+ return { compatible: true, reason: null };+}++/**+ * Decide what the debugger Play button should do for a (potentially) LoginBlock+ * debug run. Fail-closed when the data we need is not in hand: the gate+ * distinguishes the initial loading state from a recoverable error/missing-+ * credential state so the caller can choose the right toast and trigger a+ * refetch where appropriate.+ *+ * - `proceed`: gate doesn't apply or the resolved credential is compatible+ * with the visible PBS.+ * - `block-loading`: credentials query is still in flight; caller should+ * surface a "try again in a moment" toast.+ * - `block-retry`: credentials errored or the LoginBlock's credential isn't+ * in the fetched list; caller should `refetch()` and surface a retry-+ * specific toast. `reason` lets the caller pick copy and decide whether+ * to widen the page on retry.+ * - `show-modal`: credentials are ready and the visible PBS profile would+ * diverge from the credential profile; surface the modal so the user+ * can Continue (proceed anyway) or Cancel.+ */+export function decideDebugLoginPlayGate(args: {+ blockType: string;+ hasDebugSession: boolean;+ credentialsState: CredentialsLoadState;+ block: BlockLike | null | undefined;+ credentials: ReadonlyArray<CredentialApiResponse> | null | undefined;+ pbsBrowserProfileId: string | null;+}): DebugLoginPlayGateAction {+ const {+ blockType,+ hasDebugSession,+ credentialsState,+ block,+ credentials,+ pbsBrowserProfileId,+ } = args;++ if (blockType !== "login" || !hasDebugSession) {+ return { kind: "proceed" };+ }++ if (credentialsState === "loading") {+ return { kind: "block-loading" };+ }++ if (credentialsState === "error") {+ return { kind: "block-retry", reason: "credentials-error" };+ }++ // credentialsState === "ready". `data` may still be undefined transiently+ // (e.g. cache eviction); treat as not yet ready and let the caller retry.+ if (!credentials) {+ return { kind: "block-loading" };+ }++ const resolution = resolveLoginBlockCredential({ block, credentials });+ if (resolution.status === "credential-not-in-list") {+ return { kind: "block-retry", reason: "credential-not-found" };+ }++ const credentialBrowserProfileId =+ resolution.status === "resolved" ? resolution.browserProfileId : null;+ const compatibility = evaluateDebugSessionProfileCompatibility({+ pbsBrowserProfileId,+ credentialBrowserProfileId,+ });+ if (!compatibility.compatible && compatibility.reason) {+ return { kind: "show-modal", reason: compatibility.reason };+ }+ return { kind: "proceed" };+}++/**+ * Translate the backend-authoritative verdict into the same gate action shape+ * the client-side fast path produces, so callers can fold the recovery branch+ * back into a single dispatch. Used when `decideDebugLoginPlayGate` returned+ * `block-retry` with reason `credential-not-found` — i.e. the bounded+ * credentials window didn't see the credential and the FE asked the backend+ * to resolve it through the org-scoped lookup the run path uses.+ */+export function gateActionFromBackendCompatibility(+ response: DebugLoginBlockCompatibilityResponse,+): DebugLoginPlayGateAction {+ if (response.compatible) {+ return { kind: "proceed" };+ }+ if (response.reason === null) {+ return { kind: "block-retry", reason: "credentials-error" };+ }+ return { kind: "show-modal", reason: response.reason };+}diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsxindex bc2c9f108..af2175b63 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.tsx@@ -6,13 +6,17 @@ import {ReloadIcon,StopIcon,} from "@radix-ui/react-icons";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { useLocation, useNavigate, useParams } from "react-router-dom";import { useMutation, useQueryClient } from "@tanstack/react-query";import { useReactFlow } from "@xyflow/react";import { getClient } from "@/api/AxiosClient";-import { ProxyLocation, Status } from "@/api/types";+import {+ ProxyLocation,+ Status,+ type DebugLoginBlockCompatibilityResponse,+} from "@/api/types";import { NoticeMe } from "@/components/NoticeMe";import { StatusBadge } from "@/components/StatusBadge";import { toast } from "@/components/ui/use-toast";@@ -26,9 +30,18 @@ import { useRequestDeleteNodeCallback } from "@/routes/workflows/hooks/useRequesimport { useTransmuteNodeCallback } from "@/routes/workflows/hooks/useTransmuteNodeCallback";import { useToggleScriptForNodeCallback } from "@/routes/workflows/hooks/useToggleScriptForNodeCallback";import { useBrowserSessionRateLimit } from "@/routes/workflows/hooks/useBrowserSessionRateLimit";+import { useCredentialsQuery } from "@/routes/workflows/hooks/useCredentialsQuery";import { useDebugSessionQuery } from "@/routes/workflows/hooks/useDebugSessionQuery";import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";+import { DebugSessionProfileIncompatibleDialog } from "@/routes/workflows/debugger/DebugSessionProfileIncompatibleDialog";+import {+ DEBUG_LOGIN_GATE_CREDENTIALS_PAGE_SIZE,+ decideDebugLoginPlayGate,+ gateActionFromBackendCompatibility,+ type CredentialsLoadState,+ type DebugSessionProfileIncompatibilityReason,+} from "@/routes/workflows/debugger/debugSessionProfileCompatibility";import {debuggableWorkflowBlockTypes,scriptableWorkflowBlockTypes,@@ -278,6 +291,18 @@ function NodeHeader({const [workflowRunStatus, setWorkflowRunStatus] = useState(workflowRun?.status,);+ const {+ data: credentials,+ isLoading: credentialsIsLoading,+ isError: credentialsIsError,+ refetch: refetchCredentials,+ } = useCredentialsQuery({+ enabled: type === "login" && !!debugSession,+ page_size: DEBUG_LOGIN_GATE_CREDENTIALS_PAGE_SIZE,+ });+ const [profileIncompatibilityReason, setProfileIncompatibilityReason] =+ useState<DebugSessionProfileIncompatibilityReason | null>(null);+ const compatibilityLookupInFlightRef = useRef(false);const [showParamsDialog, setShowParamsDialog] = useState(false);const [parametersToPrompt, setParametersToPrompt] = useState<WorkflowParameter[]@@ -601,7 +626,7 @@ function NodeHeader({},});- const handleOnPlay = () => {+ const proceedWithPlay = () => {const blocks = workflow?.workflow_definition?.blocks ?? [];const numBlocksInWorkflow = blocks.length;@@ -644,6 +669,126 @@ function NodeHeader({runBlock.mutate({ codeGen: numBlocksInWorkflow === 1 });};+ const handleOnPlay = async () => {+ // Fail-closed pre-flight: a still-loading credentials list (or an+ // errored / pagination-missed credential) can produce a null credential+ // profile that the compatibility check would misread as "compatible",+ // silently bypassing the mismatch modal. Block the play with a recovery+ // affordance until we have a definitive answer.+ const credentialsState: CredentialsLoadState = credentialsIsLoading+ ? "loading"+ : credentialsIsError+ ? "error"+ : "ready";+ const blocks = workflow?.workflow_definition?.blocks ?? [];+ const block = findWorkflowBlockByLabel(blocks, blockLabel);++ const gate = decideDebugLoginPlayGate({+ blockType: type,+ hasDebugSession: !!debugSession,+ credentialsState,+ block,+ credentials,+ pbsBrowserProfileId: debugSession?.pbs_browser_profile_id ?? null,+ });++ if (gate.kind === "block-loading") {+ toast({+ variant: "warning",+ title: "Loading credentials",+ description:+ "Credentials are still loading. Please try again in a moment.",+ });+ return;+ }++ if (gate.kind === "block-retry" && gate.reason === "credentials-error") {+ // Settled-in-error leaves the gate permanently blocked until React+ // Query refetches. Trigger a refetch and tell the user to try again;+ // the next click re-evaluates against the fresh query state.+ void refetchCredentials();+ toast({+ variant: "warning",+ title: "Couldn't load credentials",+ description: "Retrying — try Play again once the toast clears.",+ });+ return;+ }++ if (gate.kind === "block-retry" && gate.reason === "credential-not-found") {+ // The credential the LoginBlock references is not in the bounded+ // useCredentialsQuery window (paginated past it, deleted, etc.).+ // Refetching the same page can't fix that, so ask the backend to+ // resolve the credential through the org-scoped lookup the run path+ // uses, and apply that verdict directly.+ if (!workflowPermanentId) {+ toast({+ variant: "warning",+ title: "Couldn't verify credential",+ description:+ "Workflow context not ready. Refresh the page and try again.",+ });+ return;+ }+ if (compatibilityLookupInFlightRef.current) {+ toast({+ variant: "warning",+ title: "Checking compatibility…",+ description: "Already verifying the credential — please wait.",+ });+ return;+ }+ compatibilityLookupInFlightRef.current = true;+ try {+ const client = await getClient(credentialGetter, "sans-api-v1");+ const response = await client.get<+ unknown,+ { data: DebugLoginBlockCompatibilityResponse }+ >(`/debug-session/${workflowPermanentId}/login-block-compatibility`, {+ params: { block_label: blockLabel },+ });+ const verdict = gateActionFromBackendCompatibility(response.data);+ if (verdict.kind === "show-modal") {+ setProfileIncompatibilityReason(verdict.reason);+ return;+ }+ if (verdict.kind === "block-retry") {+ toast({+ variant: "warning",+ title: "Couldn't verify credential",+ description:+ "The credential lookup returned an unexpected response. Try Play again, or refresh the page.",+ });+ return;+ }+ proceedWithPlay();+ return;+ } catch (error) {+ log.error("Compatibility lookup failed", {+ workflowPermanentId,+ blockLabel,+ error,+ });+ toast({+ variant: "warning",+ title: "Couldn't verify credential",+ description:+ "The credential lookup didn't complete. Try Play again, or refresh the page.",+ });+ return;+ } finally {+ compatibilityLookupInFlightRef.current = false;+ }+ }++ if (gate.kind === "show-modal") {+ setProfileIncompatibilityReason(gate.reason);+ return;+ }++ proceedWithPlay();+ };+const handleOnCancel = () => {cancelBlock.mutate();};@@ -866,7 +1011,7 @@ function NodeHeader({isRecording,})}onClick={() => {- handleOnPlay();+ void handleOnPlay();}}/>)}@@ -928,6 +1073,15 @@ function NodeHeader({}}isLoading={runBlock.isPending}/>+ <DebugSessionProfileIncompatibleDialog+ open={profileIncompatibilityReason !== null}+ reason={profileIncompatibilityReason}+ onContinue={() => {+ setProfileIncompatibilityReason(null);+ proceedWithPlay();+ }}+ onCancel={() => setProfileIncompatibilityReason(null)}+ /></>);}diff --git a/skyvern/forge/sdk/routes/debug_sessions.py b/skyvern/forge/sdk/routes/debug_sessions.pyindex 163df100e..6fc10b4a6 100644--- a/skyvern/forge/sdk/routes/debug_sessions.py+++ b/skyvern/forge/sdk/routes/debug_sessions.py@@ -4,22 +4,61 @@ from datetime import datetime, timedelta, timezonefrom functools import partialimport structlog-from fastapi import Depends, HTTPException+from fastapi import Depends, HTTPException, Queryfrom skyvern.config import settingsfrom skyvern.exceptions import BrowserSessionNotRenewablefrom skyvern.forge import appfrom skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.routes.routers import base_router-from skyvern.forge.sdk.schemas.debug_sessions import DebugSession, DebugSessionRuns+from skyvern.forge.sdk.schemas.debug_sessions import (+ DebugLoginBlockCompatibility,+ DebugSession,+ DebugSessionRuns,+)from skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSessionfrom skyvern.forge.sdk.services import org_auth_service+from skyvern.forge.sdk.workflow.models.block import LoginBlock+from skyvern.forge.sdk.workflow.service import (+ DEBUG_SESSION_PROFILE_REASON_DIFFERENT,+ DEBUG_SESSION_PROFILE_REASON_NO_PROFILE,+)from skyvern.schemas.runs import ProxyLocationLOG = structlog.get_logger()+async def _hydrate_pbs_browser_profile_id(+ debug_session: DebugSession,+ organization_id: str,+) -> DebugSession:+ """Populate the visible PBS's saved browser_profile_id on the response.++ Looked up lazily here (rather than carried on the debug_sessions row) so+ profile rotations after session creation are reflected at fetch time.+ The UI keys on this value to detect LoginBlock credential-profile+ incompatibility before kicking off a debug run.+ """+ try:+ pbs = await app.DATABASE.browser_sessions.get_persistent_browser_session(+ debug_session.browser_session_id,+ organization_id,+ )+ except Exception:+ LOG.warning(+ "Failed to hydrate pbs_browser_profile_id on debug session",+ debug_session_id=debug_session.debug_session_id,+ browser_session_id=debug_session.browser_session_id,+ organization_id=organization_id,+ exc_info=True,+ )+ return debug_session+ if pbs is not None and debug_session.pbs_browser_profile_id is None:+ debug_session.pbs_browser_profile_id = pbs.browser_profile_id+ return debug_session++@base_router.get("/debug-session/{workflow_permanent_id}",include_in_schema=False,@@ -75,6 +114,12 @@ async def get_or_create_debug_session_by_user_and_workflow_permanent_id(debug_session.browser_session_id,current_org.organization_id,)+ # Reuse the already-fetched PBS row to populate pbs_browser_profile_id+ # rather than going through _hydrate_pbs_browser_profile_id, which would+ # round-trip the DB a second time. If the PBS lookup itself raises, that+ # surfaces here intentionally so the renewal block can react.+ if session is not None:+ debug_session.pbs_browser_profile_id = session.browser_profile_idif session and session.started_at is None and session.completed_at is None:created_at_utc = (session.created_at.replace(tzinfo=timezone.utc) if session.created_at.tzinfo is None else session.created_at@@ -151,7 +196,7 @@ async def new_debug_session(user_id=current_user_id,workflow_permanent_id=workflow_permanent_id,)- return debug_session+ return await _hydrate_pbs_browser_profile_id(debug_session, current_org.organization_id)completed_debug_sessions = await app.DATABASE.debug.complete_debug_sessions(organization_id=current_org.organization_id,@@ -269,6 +314,8 @@ async def new_debug_session(proxy_location=str(proxy_location),)+ # The freshly created session row carries the browser_profile_id already.+ debug_session.pbs_browser_profile_id = new_browser_session.browser_profile_idreturn debug_session@@ -291,6 +338,69 @@ async def get_block_outputs_for_debug_session()+@base_router.get(+ "/debug-session/{workflow_permanent_id}/login-block-compatibility",+ response_model=DebugLoginBlockCompatibility,+ include_in_schema=False,+)+async def get_login_block_compatibility(+ workflow_permanent_id: str,+ block_label: str = Query(..., min_length=1),+ current_org: Organization = Depends(org_auth_service.get_current_org),+ current_user_id: str = Depends(org_auth_service.get_current_user_id),+) -> DebugLoginBlockCompatibility:+ """Backend-authoritative compatibility verdict for one debugger LoginBlock.++ The FE pre-check normally resolves the credential off the bounded+ `useCredentialsQuery` window; if the block references a credential past+ that window (pagination miss / inaccessible), this endpoint runs the same+ org-scoped resolution the run path uses so a Play retry can recover.+ Returns the same shape the FE's compatibility gate consumes.+ """+ debug_session = await app.DATABASE.debug.get_debug_session(+ organization_id=current_org.organization_id,+ user_id=current_user_id,+ workflow_permanent_id=workflow_permanent_id,+ )+ if not debug_session:+ return DebugLoginBlockCompatibility(compatible=True, reason=None)++ workflow = await app.WORKFLOW_SERVICE.get_workflow_by_permanent_id(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=current_org.organization_id,+ )+ if workflow is None or workflow.workflow_definition is None:+ return DebugLoginBlockCompatibility(compatible=True, reason=None)++ block = next(+ (b for b in workflow.workflow_definition.blocks if getattr(b, "label", None) == block_label),+ None,+ )+ if block is None or not isinstance(block, LoginBlock):+ return DebugLoginBlockCompatibility(compatible=True, reason=None)++ resolved_profile_id = await app.WORKFLOW_SERVICE.resolve_login_block_browser_profile_id_pre_run(+ block=block,+ organization_id=current_org.organization_id,+ )+ if resolved_profile_id is None:+ return DebugLoginBlockCompatibility(compatible=True, reason=None)++ pbs = await app.DATABASE.browser_sessions.get_persistent_browser_session(+ debug_session.browser_session_id,+ current_org.organization_id,+ )+ pbs_profile_id = pbs.browser_profile_id if pbs is not None else None++ if pbs_profile_id == resolved_profile_id:+ return DebugLoginBlockCompatibility(compatible=True, reason=None)++ reason = (+ DEBUG_SESSION_PROFILE_REASON_NO_PROFILE if pbs_profile_id is None else DEBUG_SESSION_PROFILE_REASON_DIFFERENT+ )+ return DebugLoginBlockCompatibility(compatible=False, reason=reason)++@base_router.get("/debug-session/{debug_session_id}/runs",include_in_schema=False,diff --git a/skyvern/forge/sdk/schemas/debug_sessions.py b/skyvern/forge/sdk/schemas/debug_sessions.pyindex a18a72b6f..2a92384e9 100644--- a/skyvern/forge/sdk/schemas/debug_sessions.py+++ b/skyvern/forge/sdk/schemas/debug_sessions.py@@ -22,6 +22,9 @@ class DebugSession(BaseModel):browser_session_id: strvnc_streaming_supported: bool | None = Noneworkflow_permanent_id: str | None = None+ # Mirrors the visible PBS's saved profile so the UI can warn before a debug+ # run with a credential profile diverges from the user's stream.+ pbs_browser_profile_id: str | None = Nonecreated_at: datetimemodified_at: datetimedeleted_at: datetime | None = None@@ -56,3 +59,15 @@ class DebugSessionRuns(BaseModel):debug_session: DebugSessionruns: list[DebugSessionRun]+++# Backend-authoritative verdict for a single LoginBlock in a debug session.+# The FE pre-check works off a bounded credentials window; this endpoint+# resolves the credential through the org-scoped lookup the run path uses+# so a Play retry can recover even when pagination would miss the credential.+DebugLoginBlockCompatibilityReason = t.Literal["pbs_no_profile", "pbs_different_profile"]+++class DebugLoginBlockCompatibility(BaseModel):+ compatible: bool+ reason: DebugLoginBlockCompatibilityReason | None = Nonediff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex a1dd724d4..31edb2a1f 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -181,6 +181,32 @@ RECORDING_WINDOW_END_BUFFER = timedelta(minutes=15)POST_RUN_TIMEOUT_EXHAUSTED_THRESHOLD_SECONDS = 0.001WorkflowWebhookDeliveryStatus: TypeAlias = Literal["pending", "failed"]+# Structured warning emitted when a debug-session run's visible PBS profile is+# incompatible with the LoginBlock credential's saved profile. Observability+# dashboards key on these strings — do not rename without updating monitors.+DEBUG_SESSION_PROFILE_INCOMPATIBLE_CODE = "debug_session_profile_incompatible"+DEBUG_SESSION_PROFILE_REASON_NO_PROFILE = "pbs_no_profile"+DEBUG_SESSION_PROFILE_REASON_DIFFERENT = "pbs_different_profile"+++@dataclass(frozen=True)+class DebugSessionProfileDecision:+ """Asymmetric decision for LoginBlock credential-profile flow.++ attach_browser_session_id: the PBS id to thread into+ BROWSER_MANAGER.get_or_create_for_workflow_run so the visible browser+ is the one the agent acts on. None for non-debug runs (preserve+ existing behavior — credential-profile launches a fresh browser).++ incompatible_reason: None when compatible / non-debug; otherwise the+ structured reason for the warning emit. Callers branch on this:+ None → take the existing skip-login fast path, set → emit the+ structured warning, attach the PBS, fall through to ordinary login.+ """++ attach_browser_session_id: str | None+ incompatible_reason: str | None+def _as_utc(dt: datetime) -> datetime:return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)@@ -2731,7 +2757,6 @@ class WorkflowService:model=block.model,)- # ── Skip LoginBlock when credential has a browser profile ────if block.block_type == BlockType.LOGIN:resolved_browser_profile_id = await self._resolve_login_block_browser_profile_id(block=block,@@ -2742,87 +2767,128 @@ class WorkflowService:# retries don't stack the browser-session prefix repeatedly.original_navigation_goal = block.navigation_goalif resolved_browser_profile_id:- LOG.info(- "LoginBlock has credential with browser profile — skipping login agent",- workflow_run_id=workflow_run_id,- block_label=block.label,- browser_profile_id=resolved_browser_profile_id,- url=block.url,- )- # Persist the browser_profile_id on the workflow_run so- # subsequent blocks create / reuse a browser with the- # saved profile (cookies, localStorage, etc.).- await app.DATABASE.workflow_runs.update_workflow_run(- workflow_run_id=workflow_run_id,- browser_profile_id=resolved_browser_profile_id,+ decision = await self._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id=browser_session_id,+ resolved_browser_profile_id=resolved_browser_profile_id,+ organization_id=organization_id,)- workflow_run = (- await app.DATABASE.workflow_runs.get_workflow_run(++ if decision.incompatible_reason is not None:+ # Debug session whose visible PBS is profile-incompatible.+ # Stream fidelity wins: attach the visible PBS so the user+ # can watch the action, but DO NOT write+ # workflow_run.browser_profile_id, DO NOT rewrite the+ # navigation_goal, and DO NOT emit "skipping login agent".+ # Fall through to ordinary LoginBlock execution below.+ LOG.warning(+ "Debug session profile incompatible with LoginBlock credential",+ code=DEBUG_SESSION_PROFILE_INCOMPATIBLE_CODE,+ reason=decision.incompatible_reason,workflow_run_id=workflow_run_id,- organization_id=organization_id,+ block_label=block.label,+ debug_session_id=workflow_run.debug_session_id,+ browser_session_id=browser_session_id,+ credential_browser_profile_id=resolved_browser_profile_id,)- or workflow_run- )-- # Create the browser with the saved profile and navigate- # to the login block's URL. When a saved-profile credential- # is selected, the user is guided to enter the post-login- # target URL (e.g. homepage/dashboard) rather than the- # login page. The saved cookies will authenticate the- # session once the page loads.- profile_loaded = bool(block.url)- if block.url:- try:- browser_state = await app.BROWSER_MANAGER.get_or_create_for_workflow_run(- workflow_run=workflow_run,- url=block.url,- browser_profile_id=resolved_browser_profile_id,- )- working_page = await browser_state.get_working_page()- if working_page and working_page.url == "about:blank":- await browser_state.navigate_to_url(page=working_page, url=block.url)- # Wait for the page to settle so cookies/redirects complete- if working_page:- try:- await working_page.wait_for_load_state("networkidle", timeout=10000)- except Exception:- LOG.debug(- "networkidle timeout after browser profile navigation (non-fatal)",- workflow_run_id=workflow_run_id,- )- except Exception:- LOG.warning(- "Saved browser profile failed to load, falling back to normal login",- workflow_run_id=workflow_run_id,- block_label=block.label,- browser_profile_id=resolved_browser_profile_id,- exc_info=True,- )- profile_loaded = False- # Clear the profile so the normal login path doesn't reuse it- await app.DATABASE.workflow_runs.update_workflow_run(+ if decision.attach_browser_session_id and block.url:+ try:+ await app.BROWSER_MANAGER.get_or_create_for_workflow_run(+ workflow_run=workflow_run,+ url=block.url,+ browser_session_id=decision.attach_browser_session_id,+ )+ except Exception:+ LOG.warning(+ "PBS attach failed for debug incompatible profile; continuing",+ workflow_run_id=workflow_run_id,+ block_label=block.label,+ browser_session_id=decision.attach_browser_session_id,+ exc_info=True,+ )+ else:+ LOG.info(+ "LoginBlock has credential with browser profile — skipping login agent",+ workflow_run_id=workflow_run_id,+ block_label=block.label,+ browser_profile_id=resolved_browser_profile_id,+ url=block.url,+ )+ # Persist the browser_profile_id on the workflow_run so+ # subsequent blocks create / reuse a browser with the+ # saved profile (cookies, localStorage, etc.).+ await app.DATABASE.workflow_runs.update_workflow_run(+ workflow_run_id=workflow_run_id,+ browser_profile_id=resolved_browser_profile_id,+ )+ workflow_run = (+ await app.DATABASE.workflow_runs.get_workflow_run(workflow_run_id=workflow_run_id,- browser_profile_id=None,+ organization_id=organization_id,)+ or workflow_run+ )- if not profile_loaded:- # Fall through to normal block execution below- pass- else:- # Browser profile loaded — the session may still be- # valid or may have expired (common with bank sites).- # Instead of skipping the login block, modify the- # navigation goal so the AI checks whether the user is- # already logged in and only performs login if needed.- if original_navigation_goal:- block.navigation_goal = (- "A saved browser session has been loaded. "- "Check if the user is already logged in. "- "If already logged in, complete this task immediately without taking any action. "- "If not logged in (e.g. the session expired), "- "proceed to log in with the provided credentials.\n\n"- f"Original goal: {original_navigation_goal}"- )+ # Create the browser with the saved profile and navigate+ # to the login block's URL. When a saved-profile credential+ # is selected, the user is guided to enter the post-login+ # target URL (e.g. homepage/dashboard) rather than the+ # login page. The saved cookies will authenticate the+ # session once the page loads.+ profile_loaded = bool(block.url)+ if block.url:+ try:+ browser_state = await app.BROWSER_MANAGER.get_or_create_for_workflow_run(+ workflow_run=workflow_run,+ url=block.url,+ browser_profile_id=resolved_browser_profile_id,+ browser_session_id=decision.attach_browser_session_id,+ )+ working_page = await browser_state.get_working_page()+ if working_page and working_page.url == "about:blank":+ await browser_state.navigate_to_url(page=working_page, url=block.url)+ # Wait for the page to settle so cookies/redirects complete+ if working_page:+ try:+ await working_page.wait_for_load_state("networkidle", timeout=10000)+ except Exception:+ LOG.debug(+ "networkidle timeout after browser profile navigation (non-fatal)",+ workflow_run_id=workflow_run_id,+ )+ except Exception:+ LOG.warning(+ "Saved browser profile failed to load, falling back to normal login",+ workflow_run_id=workflow_run_id,+ block_label=block.label,+ browser_profile_id=resolved_browser_profile_id,+ exc_info=True,+ )+ profile_loaded = False+ # Clear the profile so the normal login path doesn't reuse it+ await app.DATABASE.workflow_runs.update_workflow_run(+ workflow_run_id=workflow_run_id,+ browser_profile_id=None,+ )++ if not profile_loaded:+ # Fall through to normal block execution below+ pass+ else:+ # Browser profile loaded — the session may still be+ # valid or may have expired (common with bank sites).+ # Instead of skipping the login block, modify the+ # navigation goal so the AI checks whether the user is+ # already logged in and only performs login if needed.+ if original_navigation_goal:+ block.navigation_goal = (+ "A saved browser session has been loaded. "+ "Check if the user is already logged in. "+ "If already logged in, complete this task immediately without taking any action. "+ "If not logged in (e.g. the session expired), "+ "proceed to log in with the provided credentials.\n\n"+ f"Original goal: {original_navigation_goal}"+ )valid_to_run_code = (is_script_run and block.label and block.label in script_blocks_by_label and not block.disable_cache@@ -3353,10 +3419,25 @@ class WorkflowService:)return workflow_run, blocks_to_update, workflow_run_block_result, True, branch_metadata+ async def resolve_login_block_browser_profile_id_pre_run(+ self,+ *,+ block: Block,+ organization_id: str,+ ) -> str | None:+ """Pre-run variant: no workflow_run_id, so CREDENTIAL_ID workflow+ parameters resolve via their ``default_value`` fallback inside the+ resolver."""+ return await self._resolve_login_block_browser_profile_id(+ block=block,+ workflow_run_id=None,+ organization_id=organization_id,+ )+async def _resolve_login_block_browser_profile_id(self,block: Block,- workflow_run_id: str,+ workflow_run_id: str | None,organization_id: str | None,) -> str | None:"""Inspect the block-level parameters and return the browser_profile_id@@ -3384,7 +3465,9 @@ class WorkflowService:):# The credential_id is stored as the run-parameter value (or# falls back to default_value on the workflow parameter).- if run_param_tuples is None:+ if workflow_run_id is None:+ run_param_tuples = []+ elif run_param_tuples is None:try:run_param_tuples = await app.DATABASE.workflow_runs.get_workflow_run_parameters(workflow_run_id=workflow_run_id,@@ -3450,6 +3533,64 @@ class WorkflowService:)return None+ async def _evaluate_debug_session_profile_decision(+ self,+ *,+ workflow_run: WorkflowRun,+ browser_session_id: str | None,+ resolved_browser_profile_id: str,+ organization_id: str,+ ) -> DebugSessionProfileDecision:+ """Asymmetric LoginBlock credential-profile decision: debug-session runs+ attach the visible PBS only when its saved profile matches the credential+ profile; mismatches surface a reason for downstream warning + fall-through."""+ is_debug_run = workflow_run.debug_session_id is not None+ if not is_debug_run:+ return DebugSessionProfileDecision(+ attach_browser_session_id=None,+ incompatible_reason=None,+ )++ if not browser_session_id:+ return DebugSessionProfileDecision(+ attach_browser_session_id=None,+ incompatible_reason=None,+ )++ try:+ pbs = await app.DATABASE.browser_sessions.get_persistent_browser_session(+ browser_session_id,+ organization_id,+ )+ except Exception:+ # Fail safe: treat as no profile so the decision lands in+ # pbs_no_profile rather than crashing the workflow run.+ LOG.warning(+ "Persistent browser session lookup failed during debug LoginBlock decision; treating as no profile",+ workflow_run_id=workflow_run.workflow_run_id,+ browser_session_id=browser_session_id,+ organization_id=organization_id,+ exc_info=True,+ )+ pbs = None+ pbs_profile_id = pbs.browser_profile_id if pbs is not None else None++ if pbs_profile_id == resolved_browser_profile_id:+ return DebugSessionProfileDecision(+ attach_browser_session_id=browser_session_id,+ incompatible_reason=None,+ )++ reason = (+ DEBUG_SESSION_PROFILE_REASON_NO_PROFILE+ if pbs_profile_id is None+ else DEBUG_SESSION_PROFILE_REASON_DIFFERENT+ )+ return DebugSessionProfileDecision(+ attach_browser_session_id=browser_session_id,+ incompatible_reason=reason,+ )+async def _handle_block_result_status(self,*,diff --git a/tests/unit/forge/sdk/routes/test_debug_sessions.py b/tests/unit/forge/sdk/routes/test_debug_sessions.pyindex 750601db3..2b44508ec 100644--- a/tests/unit/forge/sdk/routes/test_debug_sessions.py+++ b/tests/unit/forge/sdk/routes/test_debug_sessions.py@@ -8,11 +8,12 @@ from skyvern.forge.sdk.routes import debug_sessions as debug_sessions_mod@pytest.mark.asyncioasync def test_new_debug_session_skips_redundant_local_close_before_create() -> None:- created_debug_session = SimpleNamespace(debug_session_id="ds_new")+ created_debug_session = SimpleNamespace(debug_session_id="ds_new", pbs_browser_profile_id=None)new_browser_session = SimpleNamespace(persistent_browser_session_id="pbs_new",ip_address=None,browser_address=None,+ browser_profile_id=None,)app_mock = MagicMock()@@ -54,3 +55,308 @@ async def test_new_debug_session_skips_redundant_local_close_before_create() ->workflow_permanent_id="wpid_test",vnc_streaming_supported=True,)+++async def test_hydrate_pbs_browser_profile_id_sets_field_when_session_exists() -> None:+ debug_session = SimpleNamespace(+ debug_session_id="ds_x",+ browser_session_id="pbs_x",+ pbs_browser_profile_id=None,+ )+ app_mock = MagicMock()+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=SimpleNamespace(browser_profile_id="bp_42"),+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ result = await debug_sessions_mod._hydrate_pbs_browser_profile_id(+ debug_session,+ organization_id="org_x",+ )++ assert result is debug_session+ assert debug_session.pbs_browser_profile_id == "bp_42"+++async def test_hydrate_pbs_browser_profile_id_leaves_field_when_session_missing() -> None:+ debug_session = SimpleNamespace(+ debug_session_id="ds_x",+ browser_session_id="pbs_x",+ pbs_browser_profile_id=None,+ )+ app_mock = MagicMock()+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=None,+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ result = await debug_sessions_mod._hydrate_pbs_browser_profile_id(+ debug_session,+ organization_id="org_x",+ )++ assert result is debug_session+ assert debug_session.pbs_browser_profile_id is None+++async def test_hydrate_pbs_browser_profile_id_swallows_lookup_errors() -> None:+ """A transient PBS lookup failure must not break the debug-session response.++ The UI degrades to "no profile" — the modal is informational and the+ backend still enforces the asymmetric run-path contract.+ """+ debug_session = SimpleNamespace(+ debug_session_id="ds_x",+ browser_session_id="pbs_x",+ pbs_browser_profile_id=None,+ )+ app_mock = MagicMock()+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ side_effect=RuntimeError("transient DB blip"),+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ result = await debug_sessions_mod._hydrate_pbs_browser_profile_id(+ debug_session,+ organization_id="org_x",+ )++ assert result is debug_session+ assert debug_session.pbs_browser_profile_id is None+++async def test_new_debug_session_response_carries_pbs_browser_profile_id() -> None:+ """Freshly created PBS rows already know their browser_profile_id; the POST+ handler must surface it so the FE can compute compatibility without an+ extra round-trip.+ """+ created_debug_session = SimpleNamespace(+ debug_session_id="ds_new",+ browser_session_id="pbs_new",+ pbs_browser_profile_id=None,+ )+ new_browser_session = SimpleNamespace(+ persistent_browser_session_id="pbs_new",+ ip_address=None,+ browser_address=None,+ browser_profile_id="bp_seeded",+ )++ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=None)+ app_mock.DATABASE.debug.complete_debug_sessions = AsyncMock(return_value=[])+ app_mock.DATABASE.debug.create_debug_session = AsyncMock(return_value=created_debug_session)+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock()+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(+ return_value=SimpleNamespace(proxy_location=None)+ )+ app_mock.PERSISTENT_SESSIONS_MANAGER.create_session = AsyncMock(return_value=new_browser_session)++ with (+ patch.object(debug_sessions_mod, "app", app_mock),+ patch.object(debug_sessions_mod.settings, "ENV", "local"),+ ):+ result = await debug_sessions_mod.new_debug_session(+ "wpid_test",+ current_org=SimpleNamespace(organization_id="org_123"),+ current_user_id="user_123",+ )++ assert result is created_debug_session+ assert created_debug_session.pbs_browser_profile_id == "bp_seeded"+++# ─── login-block-compatibility endpoint ────────────────────────────────────+++def _login_block(*, label: str = "login_1") -> SimpleNamespace:+ """A minimal stand-in for `LoginBlock`. The endpoint uses `isinstance` to+ branch, so we keep tests honest by patching `LoginBlock` to a sentinel+ class the namespace instance satisfies."""++ return SimpleNamespace(label=label)+++def _wf(*, blocks: list) -> SimpleNamespace:+ return SimpleNamespace(workflow_definition=SimpleNamespace(blocks=blocks))+++async def test_compatibility_returns_compatible_when_no_debug_session() -> None:+ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=None)++ with patch.object(debug_sessions_mod, "app", app_mock):+ result = await debug_sessions_mod.get_login_block_compatibility(+ workflow_permanent_id="wpid_test",+ block_label="login_1",+ current_org=SimpleNamespace(organization_id="org_x"),+ current_user_id="user_x",+ )++ assert result.compatible is True+ assert result.reason is None+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id.assert_not_called()+++async def test_compatibility_returns_compatible_when_block_is_not_login() -> None:+ debug_session = SimpleNamespace(browser_session_id="pbs_x")+ non_login_block = SimpleNamespace(label="login_1") # not a LoginBlock instance+ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=debug_session)+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(+ return_value=_wf(blocks=[non_login_block]),+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ result = await debug_sessions_mod.get_login_block_compatibility(+ workflow_permanent_id="wpid_test",+ block_label="login_1",+ current_org=SimpleNamespace(organization_id="org_x"),+ current_user_id="user_x",+ )++ assert result.compatible is True+ assert result.reason is None+++async def test_compatibility_compatible_when_credential_has_no_profile() -> None:+ debug_session = SimpleNamespace(browser_session_id="pbs_x")+ login_block = _login_block()+ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=debug_session)+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(+ return_value=_wf(blocks=[login_block]),+ )+ app_mock.WORKFLOW_SERVICE.resolve_login_block_browser_profile_id_pre_run = AsyncMock(+ return_value=None,+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ with patch.object(debug_sessions_mod, "LoginBlock", SimpleNamespace):+ result = await debug_sessions_mod.get_login_block_compatibility(+ workflow_permanent_id="wpid_test",+ block_label="login_1",+ current_org=SimpleNamespace(organization_id="org_x"),+ current_user_id="user_x",+ )++ assert result.compatible is True+ assert result.reason is None+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session.assert_not_called()+++async def test_compatibility_reports_pbs_no_profile_when_pbs_unprofiled() -> None:+ debug_session = SimpleNamespace(browser_session_id="pbs_x")+ login_block = _login_block()+ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=debug_session)+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(+ return_value=_wf(blocks=[login_block]),+ )+ app_mock.WORKFLOW_SERVICE.resolve_login_block_browser_profile_id_pre_run = AsyncMock(+ return_value="bp_cred",+ )+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=SimpleNamespace(browser_profile_id=None),+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ with patch.object(debug_sessions_mod, "LoginBlock", SimpleNamespace):+ result = await debug_sessions_mod.get_login_block_compatibility(+ workflow_permanent_id="wpid_test",+ block_label="login_1",+ current_org=SimpleNamespace(organization_id="org_x"),+ current_user_id="user_x",+ )++ assert result.compatible is False+ assert result.reason == "pbs_no_profile"+++async def test_compatibility_reports_pbs_different_profile_when_profiles_differ() -> None:+ debug_session = SimpleNamespace(browser_session_id="pbs_x")+ login_block = _login_block()+ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=debug_session)+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(+ return_value=_wf(blocks=[login_block]),+ )+ app_mock.WORKFLOW_SERVICE.resolve_login_block_browser_profile_id_pre_run = AsyncMock(+ return_value="bp_cred",+ )+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=SimpleNamespace(browser_profile_id="bp_other"),+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ with patch.object(debug_sessions_mod, "LoginBlock", SimpleNamespace):+ result = await debug_sessions_mod.get_login_block_compatibility(+ workflow_permanent_id="wpid_test",+ block_label="login_1",+ current_org=SimpleNamespace(organization_id="org_x"),+ current_user_id="user_x",+ )++ assert result.compatible is False+ assert result.reason == "pbs_different_profile"+++async def test_compatibility_reports_compatible_when_profiles_match() -> None:+ debug_session = SimpleNamespace(browser_session_id="pbs_x")+ login_block = _login_block()+ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=debug_session)+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(+ return_value=_wf(blocks=[login_block]),+ )+ app_mock.WORKFLOW_SERVICE.resolve_login_block_browser_profile_id_pre_run = AsyncMock(+ return_value="bp_same",+ )+ app_mock.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=SimpleNamespace(browser_profile_id="bp_same"),+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ with patch.object(debug_sessions_mod, "LoginBlock", SimpleNamespace):+ result = await debug_sessions_mod.get_login_block_compatibility(+ workflow_permanent_id="wpid_test",+ block_label="login_1",+ current_org=SimpleNamespace(organization_id="org_x"),+ current_user_id="user_x",+ )++ assert result.compatible is True+ assert result.reason is None+++async def test_compatibility_returns_compatible_when_block_label_not_found() -> None:+ debug_session = SimpleNamespace(browser_session_id="pbs_x")+ other_block = SimpleNamespace(label="other_block")+ app_mock = MagicMock()+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(return_value=debug_session)+ app_mock.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(+ return_value=_wf(blocks=[other_block]),+ )++ with patch.object(debug_sessions_mod, "app", app_mock):+ result = await debug_sessions_mod.get_login_block_compatibility(+ workflow_permanent_id="wpid_test",+ block_label="login_missing",+ current_org=SimpleNamespace(organization_id="org_x"),+ current_user_id="user_x",+ )++ assert result.compatible is True+ assert result.reason is None+ app_mock.WORKFLOW_SERVICE.resolve_login_block_browser_profile_id_pre_run.assert_not_called()diff --git a/tests/unit/test_login_block_debug_session_profile.py b/tests/unit/test_login_block_debug_session_profile.pynew file mode 100644index 000000000..4b0ae2bec--- /dev/null+++ b/tests/unit/test_login_block_debug_session_profile.py@@ -0,0 +1,213 @@+"""Asymmetric debug-session vs workflow-run semantics for LoginBlock credential profile.++Debug-session runs (workflow_run.debug_session_id is not None) prioritize stream+fidelity: attach the visible PBS, and keep the skip-login fast path only when the+PBS profile actually matches the credential. Mismatched / missing PBS profile+yields a structured warning, no profile_id write, no navigation_goal rewrite, and+fall-through to ordinary LoginBlock execution so the user watches the actual+login. Non-debug runs preserve existing behavior — credential-profile launches a+fresh browser, no PBS attach. The decision lives in+``WorkflowService._evaluate_debug_session_profile_decision``.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest++from skyvern.forge.sdk.workflow.service import WorkflowService+++def _workflow_run(*, debug_session_id: str | None) -> SimpleNamespace:+ return SimpleNamespace(+ workflow_run_id="wr_test",+ workflow_permanent_id="wpid_test",+ organization_id="o_test",+ debug_session_id=debug_session_id,+ browser_session_id="pbs_test" if debug_session_id else None,+ browser_profile_id=None,+ parent_workflow_run_id=None,+ )+++def _pbs(*, browser_profile_id: str | None) -> SimpleNamespace:+ return SimpleNamespace(+ persistent_browser_session_id="pbs_test",+ organization_id="o_test",+ browser_profile_id=browser_profile_id,+ )+++class TestDebugSessionProfileDecision:+ """The helper returns the asymmetric decision struct used downstream."""++ @pytest.mark.asyncio+ async def test_non_debug_run_keeps_existing_skip_login_no_pbs_attach(self) -> None:+ service = WorkflowService()+ workflow_run = _workflow_run(debug_session_id=None)++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=_pbs(browser_profile_id="bp_cred"),+ )+ decision = await service._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id=None,+ resolved_browser_profile_id="bp_cred",+ organization_id="o_test",+ )+ # Non-debug runs must short-circuit before touching the PBS lookup;+ # the mock is wired only to prove that contract is preserved.+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session.assert_not_called()++ assert decision.attach_browser_session_id is None+ assert decision.incompatible_reason is None++ @pytest.mark.asyncio+ async def test_debug_run_no_browser_session_id_keeps_existing_behavior(self) -> None:+ """Debug-run flag set but no PBS attached — preserve existing flow."""+ service = WorkflowService()+ workflow_run = _workflow_run(debug_session_id="ds_test")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=None,+ )+ decision = await service._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id=None,+ resolved_browser_profile_id="bp_cred",+ organization_id="o_test",+ )++ assert decision.attach_browser_session_id is None+ assert decision.incompatible_reason is None++ @pytest.mark.asyncio+ async def test_debug_run_compatible_profile_threads_pbs_keeps_skip_login(self) -> None:+ service = WorkflowService()+ workflow_run = _workflow_run(debug_session_id="ds_test")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=_pbs(browser_profile_id="bp_cred"),+ )+ decision = await service._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id="pbs_test",+ resolved_browser_profile_id="bp_cred",+ organization_id="o_test",+ )++ assert decision.attach_browser_session_id == "pbs_test"+ assert decision.incompatible_reason is None++ @pytest.mark.asyncio+ async def test_debug_run_pbs_no_profile_is_incompatible(self) -> None:+ service = WorkflowService()+ workflow_run = _workflow_run(debug_session_id="ds_test")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=_pbs(browser_profile_id=None),+ )+ decision = await service._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id="pbs_test",+ resolved_browser_profile_id="bp_cred",+ organization_id="o_test",+ )++ assert decision.attach_browser_session_id == "pbs_test"+ assert decision.incompatible_reason == "pbs_no_profile"++ @pytest.mark.asyncio+ async def test_debug_run_pbs_different_profile_is_incompatible(self) -> None:+ service = WorkflowService()+ workflow_run = _workflow_run(debug_session_id="ds_test")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=_pbs(browser_profile_id="bp_other"),+ )+ decision = await service._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id="pbs_test",+ resolved_browser_profile_id="bp_cred",+ organization_id="o_test",+ )++ assert decision.attach_browser_session_id == "pbs_test"+ assert decision.incompatible_reason == "pbs_different_profile"++ @pytest.mark.asyncio+ async def test_debug_run_pbs_lookup_missing_is_pbs_no_profile(self) -> None:+ """If the PBS row can't be fetched (race / orphan), treat it as no-profile.++ The visible browser still exists from the user's perspective; we attach it+ and fall through to manual login rather than silently inheriting the+ credential profile into a foreign browser.+ """+ service = WorkflowService()+ workflow_run = _workflow_run(debug_session_id="ds_test")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=None,+ )+ decision = await service._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id="pbs_test",+ resolved_browser_profile_id="bp_cred",+ organization_id="o_test",+ )++ assert decision.attach_browser_session_id == "pbs_test"+ assert decision.incompatible_reason == "pbs_no_profile"++ @pytest.mark.asyncio+ async def test_debug_run_pbs_lookup_raises_is_treated_as_pbs_no_profile(self) -> None:+ """A transient DB/PBS lookup exception must not fail the workflow run.++ Mirror ``_hydrate_pbs_browser_profile_id`` in ``debug_sessions.py``: log a+ warning and treat the PBS profile as None so the decision falls into the+ ``pbs_no_profile`` incompatible branch — fail-safe attach + manual login.+ """+ service = WorkflowService()+ workflow_run = _workflow_run(debug_session_id="ds_test")++ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = AsyncMock(+ side_effect=RuntimeError("transient db failure"),+ )+ decision = await service._evaluate_debug_session_profile_decision(+ workflow_run=workflow_run,+ browser_session_id="pbs_test",+ resolved_browser_profile_id="bp_cred",+ organization_id="o_test",+ )++ assert decision.attach_browser_session_id == "pbs_test"+ assert decision.incompatible_reason == "pbs_no_profile"+++class TestDebugSessionProfileWarningCode:+ """The structured warning code/reason emitted on incompatibility is part of the contract.++ Downstream observability dashboards key on `code=debug_session_profile_incompatible`+ plus `reason in {pbs_no_profile, pbs_different_profile}`. Locking the values in a test+ catches accidental rename / spelling drift.+ """++ def test_warning_code_constant_is_stable(self) -> None:+ from skyvern.forge.sdk.workflow.service import (+ DEBUG_SESSION_PROFILE_INCOMPATIBLE_CODE,+ DEBUG_SESSION_PROFILE_REASON_DIFFERENT,+ DEBUG_SESSION_PROFILE_REASON_NO_PROFILE,+ )++ assert DEBUG_SESSION_PROFILE_INCOMPATIBLE_CODE == "debug_session_profile_incompatible"+ assert DEBUG_SESSION_PROFILE_REASON_NO_PROFILE == "pbs_no_profile"+ assert DEBUG_SESSION_PROFILE_REASON_DIFFERENT == "pbs_different_profile"