Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Tell the user when a copilot turn runs out of time, and log every timeout (SKY-13249) (#7927)
Andrew Neilson06938f9de67a
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsxindex eb3a57d13..9bfd09a9f 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx@@ -21,7 +21,10 @@ import type {WorkflowRunTimelineItem,} from "../types/workflowRunTypes";import type { CodeBlockStep } from "../types/workflowTypes";-import { WorkflowRunTimelineBlockItem } from "./WorkflowRunTimelineBlockItem";+import {+ TIMELINE_DESCRIPTOR_SEPARATOR,+ WorkflowRunTimelineBlockItem,+} from "./WorkflowRunTimelineBlockItem";function buildBlock(overrides: Partial<WorkflowRunBlock> = {},@@ -81,6 +84,14 @@ function expectNoPillChrome(element: HTMLElement) {);}+function expectRowSummary(name: string, descriptor: string) {+ const row = screen.getByRole("button", { pressed: true });+ expect(row.textContent).toContain(+ `${name}${TIMELINE_DESCRIPTOR_SEPARATOR} ${descriptor}`,+ );+ return row;+}+afterEach(() => {cleanup();});@@ -704,7 +715,7 @@ describe("WorkflowRunTimelineBlockItem", () => {expect(screen.getByText("L3-5")).toBeDefined();});- it("uses the code block prompt as the row name", () => {+ it("renders the code block label as the row name and prompt as the descriptor", () => {const block = buildBlock({workflow_run_block_id: "wrb_code_prompt_title",block_type: "code",@@ -727,14 +738,17 @@ describe("WorkflowRunTimelineBlockItem", () => {/>,);- expect(screen.getByText("Collect invoice details")).toBeDefined();+ expectRowSummary("run_script", "Collect invoice details");});- it("falls back to the first code step title for the row name", () => {+ it("uses the code fallback instead of the container task URL", () => {+ const containerTaskUrl = "https://example.com/current-page";const block = buildBlock({workflow_run_block_id: "wrb_code_step_title",block_type: "code",label: "run_script",+ task_id: "tsk_code_container",+ url: containerTaskUrl,prompt: null,actions: [],});@@ -753,37 +767,13 @@ describe("WorkflowRunTimelineBlockItem", () => {/>,);- expect(screen.getByText("Summarize the page")).toBeDefined();- });-- it("falls back to the block reasoning before bare 'Code' for prompt-less code blocks", () => {- const block = buildBlock({- workflow_run_block_id: "wrb_code_reasoning",- block_type: "code",- label: "block_1",- prompt: null,- description: "Planning to extract current top post details.",- actions: [],- });-- render(- <WorkflowRunTimelineBlockItem- activeItem={block}- block={block}- subItems={[]}- onActionClick={noop}- onBlockItemClick={noop}- />,- );-- // The reasoning is surfaced as the row name (it would otherwise be lost to- // the bare "Code" fallback); the label remains the descriptor subtitle.- expect(- screen.getByText("Planning to extract current top post details."),- ).toBeDefined();+ const row = expectRowSummary("run_script", "Code block");+ expect(row.textContent).not.toContain(containerTaskUrl);+ expect(row.textContent).not.toContain("Summarize the page");+ expect(screen.getByText(/Summarize the page/)).toBeDefined();});- it("prefers the code block prompt over the reasoning for the row name", () => {+ it("prefers the code block description over its prompt in the descriptor", () => {const block = buildBlock({workflow_run_block_id: "wrb_code_prompt_over_reasoning",block_type: "code",@@ -803,23 +793,24 @@ describe("WorkflowRunTimelineBlockItem", () => {/>,);- expect(screen.getByText("Run the homepage flow")).toBeDefined();- expect(- screen.queryByText("Planning to extract current top post details."),- ).toBeNull();+ const row = expectRowSummary(+ "block_1",+ "Planning to extract current top post details.",+ );+ expect(row.textContent).not.toContain("Run the homepage flow");});- it("shows the bare 'Code' name for a prompt-less code block with no reasoning", () => {+ it("falls back to Code when a code block has no label", () => {const block = buildBlock({workflow_run_block_id: "wrb_code_bare",block_type: "code",- label: "block_2",+ label: null,prompt: null,description: null,actions: [],});- const { container } = render(+ render(<WorkflowRunTimelineBlockItemactiveItem={block}block={block}@@ -829,7 +820,7 @@ describe("WorkflowRunTimelineBlockItem", () => {/>,);- expect(within(container).getAllByText("Code").length).toBe(1);+ expectRowSummary("Code", "Code block");});it("selects the block when a code step row is clicked", () => {diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsxindex 2ff8b4731..8041d35ce 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx@@ -16,11 +16,7 @@ import {import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible";import { formatDuration, toDuration } from "@/routes/workflows/utils";import { cn } from "@/util/utils";-import {- CODE_BLOCK_FALLBACK_TITLE,- getCodeBlockTitle,- workflowBlockTitle,-} from "../editor/nodes/types";+import { workflowBlockTitle } from "../editor/nodes/types";import { WorkflowBlockIcon } from "../editor/nodes/WorkflowBlockIcon";import { actionTypeIcons as timelineActionIcons } from "../components/actionTypeIcons";import { getActionDisplayStatus } from "../components/actionStatus";@@ -89,6 +85,7 @@ const INDENT_PX = 14;const MAX_INDENT_RAIL_DEPTH = 6;const RAIL_HIGHLIGHT_OFFSET_PX = INDENT_PX / 2;const RAIL_CONTENT_PADDING_PX = INDENT_PX - 1;+export const TIMELINE_DESCRIPTOR_SEPARATOR = "·";const railHighlightStyle = {marginLeft: `-${RAIL_HIGHLIGHT_OFFSET_PX}px`,@@ -251,8 +248,19 @@ function countSchemaFields(value: WorkflowRunBlock["data_schema"]): number {}function getTimelineDescriptor(block: WorkflowRunBlock): string {+ const description = normalizeInlineText(block.description);++ if (block.block_type === WorkflowBlockTypes.Code) {+ return (+ description ??+ normalizeInlineText(block.prompt) ??+ normalizeInlineText(block.instructions) ??+ "Code block"+ );+ }+const explicit =- normalizeInlineText(block.description) ??+ description ??normalizeInlineText(block.navigation_goal) ??normalizeInlineText(block.data_extraction_goal) ??normalizeInlineText(block.prompt) ??@@ -289,23 +297,6 @@ function getTimelineDescriptor(block: WorkflowRunBlock): string {return `${workflowBlockTitle[block.block_type]} block`;}-// getCodeBlockTitle ends at the bare "Code" label for prompt-less runs, which-// dropped the reasoning subtitle the timeline used to show. Fall back to the-// block reasoning (description) before bare "Code", normalized like a prompt.-function getCodeBlockTimelineName(- block: WorkflowRunBlock,- steps: Array<CodeBlockStep>,-): string {- const title = getCodeBlockTitle({ prompt: block.prompt, steps });- if (title !== CODE_BLOCK_FALLBACK_TITLE) {- return title;- }- const reasoning = normalizeInlineText(block.description);- return reasoning- ? getCodeBlockTitle({ prompt: reasoning, steps: [] })- : title;-}-function getLoopIterationGroups(items: Array<WorkflowRunTimelineItem>,): Array<LoopIterationGroup> {@@ -988,12 +979,8 @@ function WorkflowRunTimelineBlockItem({const definitionCodeSteps = isCodeBlock? (codeStepsByLabel?.get(block.label ?? "") ?? []): [];- const blockName = isCodeBlock- ? getCodeBlockTimelineName(block, definitionCodeSteps)- : (block.label ?? block.title ?? blockTypeTitle);- const descriptor = isCodeBlock- ? (block.label ?? "Code block")- : getTimelineDescriptor(block);+ const blockName = block.label ?? blockTypeTitle;+ const descriptor = getTimelineDescriptor(block);const showsActionRows = hasActions;// Code blocks without recorded actions fall back to their definition step// outline so the timeline still reflects what the block was meant to do.@@ -1185,7 +1172,7 @@ function WorkflowRunTimelineBlockItem({{blockName}</span><span className="min-w-0 flex-1 truncate text-muted-foreground dark:text-slate-500">- · {descriptor}+ {TIMELINE_DESCRIPTOR_SEPARATOR} {descriptor}</span>{isFinallyBlock && (<span className="shrink-0 rounded bg-amber-500/80 px-1 text-[9px] font-medium text-black">diff --git a/skyvern/cli/core/mcp_http_auth.py b/skyvern/cli/core/mcp_http_auth.pyindex 2f72b5fec..da6486814 100644--- a/skyvern/cli/core/mcp_http_auth.py+++ b/skyvern/cli/core/mcp_http_auth.py@@ -19,7 +19,7 @@ from mcp.server.auth.middleware.bearer_auth import AuthenticatedUserfrom mcp.server.auth.provider import AccessTokenfrom starlette.requests import Requestfrom starlette.responses import JSONResponse-from starlette.types import ASGIApp, Message, Receive, Scope, Send+from starlette.types import ASGIApp, Receive, Scope, Sendfrom skyvern.config import settingsfrom skyvern.forge import app@@ -37,7 +37,6 @@ API_KEY_HEADER = "x-api-key"AUTHORIZATION_HEADER = "authorization"BEARER_PREFIX = "Bearer "HEALTH_PATHS = {"/health", "/healthz"}-MCP_SESSION_ID_HEADER = "mcp-session-id"# Keep in sync with skyvern-frontend/cloud/mcp-auth-constants.ts::SKYVERN_AUTH_TEMPLATE_NAME.# Names the JWT template the frontend uses to mint bearer tokens for# /oauth/callback and the CLI signup flow. A divergence silently breaks auth.@@ -51,12 +50,10 @@ _MCP_ALLOWED_TOKEN_TYPES = (OrganizationAuthTokenType.api,)_auth_db: AgentDB | None = None_auth_db_lock = RLock()_api_key_cache_lock = RLock()-_transport_session_owner_lock = RLock()# Cache entries are namespace-separated by key prefix:# `cache_key(...)` stores MCPAPIKeyValidation, `_oauth_cache_key(...)` stores# _OAuthResolution. Keep those prefixes distinct if this cache evolves._api_key_validation_cache: OrderedDict[str, tuple[MCPAPIKeyValidation | _OAuthResolution | None, float]] = OrderedDict()-_transport_session_owners: dict[str, str] = {}_OAUTH_CACHE_TTL_SECONDS = 30.0_NEGATIVE_CACHE_TTL_SECONDS = 5.0_VALIDATION_RETRY_EXHAUSTED_MESSAGE = "API key validation temporarily unavailable"@@ -619,59 +616,22 @@ class MCPAPIKeyMiddleware:organization_id: str,api_key: str,) -> None:- request = Request(scope)- request_session_id = request.headers.get(MCP_SESSION_ID_HEADER)- owner_fingerprint = hash_api_key_for_cache(api_key)- if request_session_id is not None:- with _transport_session_owner_lock:- expected_owner = _transport_session_owners.get(request_session_id)- if expected_owner is not None and expected_owner != owner_fingerprint:- response = JSONResponse(- {- "jsonrpc": "2.0",- "id": "server-error",- "error": {"code": -32600, "message": "Session not found"},- },- status_code=404,- )- await response(scope, receive, send)- return-scope.setdefault("state", {})scope["state"]["organization_id"] = organization_idscope["user"] = AuthenticatedUser(AccessToken(token="mcp-http-session-owner",client_id=organization_id,- subject=owner_fingerprint,+ subject=hash_api_key_for_cache(api_key),scopes=[],))-- response_session_id: str | None = None- response_status: int | None = None-- async def owner_bound_send(message: Message) -> None:- nonlocal response_session_id, response_status- if message["type"] == "http.response.start":- response_status = message["status"]- for name, value in message.get("headers", []):- if name.lower() == MCP_SESSION_ID_HEADER.encode("ascii"):- response_session_id = value.decode("ascii")- with _transport_session_owner_lock:- _transport_session_owners[response_session_id] = owner_fingerprint- break- await send(message)-token = set_api_key_override(api_key)try:with request_session_scope(organization_id):- await self.app(scope, receive, owner_bound_send)+ await self.app(scope, receive, send)finally:reset_api_key_override(token)- if request.method == "DELETE" and request_session_id is not None and (response_status or 500) < 400:- with _transport_session_owner_lock:- _transport_session_owners.pop(request_session_id, None)async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:if scope["type"] != "http":diff --git a/skyvern/cli/core/session_ops.py b/skyvern/cli/core/session_ops.pyindex 3df12bf3f..c16fb3702 100644--- a/skyvern/cli/core/session_ops.py+++ b/skyvern/cli/core/session_ops.py@@ -181,7 +181,10 @@ async def do_session_list(skyvern: Any) -> list[SessionInfo]:started_at=s.started_at.isoformat() if s.started_at else None,timeout=s.timeout,runnable_id=s.runnable_id,- available=s.runnable_id is None and s.browser_address is not None,+ # started_at is the client-visible half of the readiness signal: the session worker+ # sets it in the same write that makes the browser reachable, while an address alone+ # can be minted before one exists.+ available=s.runnable_id is None and s.started_at is not None and s.browser_address is not None,)for s in sessions]diff --git a/skyvern/cli/mcp_tools/prompts.py b/skyvern/cli/mcp_tools/prompts.pyindex 6ddf90d46..0d806206f 100644--- a/skyvern/cli/mcp_tools/prompts.py+++ b/skyvern/cli/mcp_tools/prompts.py@@ -853,44 +853,22 @@ Use the evidence that actually matters:After generating the QA report, persist it to the pull request as a sticky comment so theevidence survives beyond the conversation.-### Check for an open PR+### Save and post the sticky comment-```bash-PR_NUMBER=$(gh pr view --json number -q '.number' 2>/dev/null)-```--If no PR exists for the current branch:-1. Save the full report markdown to `.qa/latest-report.md` in the project root (create the directory if needed).-2. Tell the user: "No open PR found for this branch. QA report saved to `.qa/latest-report.md`. Run /qa again after creating a PR to post it."-3. Stop here — do not attempt to create a PR.+Write the full report markdown from Step 4 to `.qa/latest-report.md` with a filesystem editing tool.+Do not place report text in a shell command, variable assignment, heredoc, or command substitution.-### Post or update the sticky comment--Use a hidden HTML marker to make the comment idempotent across multiple runs:+Then run the fixed command below. It reads `.qa/latest-report.md` and passes it to `gh` as a literal+argument vector without shell evaluation, updating this user's own `<!-- skyvern-qa-report -->` comment+when one already exists:```bash-# Prepare the comment body with the hidden marker-COMMENT_BODY="<!-- skyvern-qa-report -->-## QA Report — $(git rev-parse --short HEAD) — $(date -u +%Y-%m-%dT%H:%M:%SZ)--<the full report markdown from Step 4>-"--# Find an existing QA comment on the PR-EXISTING_COMMENT_ID=$(gh api "repos/{owner}/{repo}/issues/${PR_NUMBER}/comments" \\- --jq '.[] | select(.body | test("skyvern-qa-report")) | .id' \\- 2>/dev/null | head -1)--if [ -n "$EXISTING_COMMENT_ID" ]; then- # Update the existing comment in place- gh api "repos/{owner}/{repo}/issues/comments/${EXISTING_COMMENT_ID}" \\- -X PATCH -f body="$COMMENT_BODY"-else- # Create a new comment- gh pr comment "$PR_NUMBER" --body "$COMMENT_BODY"-fi+skyvern skill post-qa-report```+If no PR exists for the current branch, the command leaves the report at `.qa/latest-report.md`.+Tell the user to run `/qa` again after creating a PR. Do not create a PR just to post a QA report.+### Screenshot handlingScreenshots taken during QA (via `skyvern_screenshot()`) are saved locally for the agent's@@ -903,8 +881,8 @@ other reviewers.### Rules-- Always include the `<!-- skyvern-qa-report -->` marker so repeated runs update the same comment instead of creating duplicates.-- Include the short commit hash and UTC timestamp in the comment header.+- Use `skyvern skill post-qa-report`; do not reconstruct its `gh` calls in a shell.+- The command includes the `<!-- skyvern-qa-report -->` marker, short commit hash, and UTC timestamp.- Do not create a PR just to post a QA report — that is the user's decision.- If `gh` is not available or not authenticated, fall back to saving the report locally and tell the user.diff --git a/skyvern/cli/mcp_tools/state.py b/skyvern/cli/mcp_tools/state.pyindex 0f9bfa5f5..e30e88cbc 100644--- a/skyvern/cli/mcp_tools/state.py+++ b/skyvern/cli/mcp_tools/state.py@@ -5,6 +5,7 @@ Save and restore cookies, localStorage, and sessionStorage across sessions.from __future__ import annotations+import hashlibimport jsonfrom pathlib import Pathfrom typing import Annotated, Any@@ -13,13 +14,22 @@ from urllib.parse import urlparseimport structlogfrom pydantic import Field+from skyvern.forge import app+from ._common import ErrorCode, Timer, make_error, make_resultfrom ._session import BrowserNotAvailableError, get_current_session, get_page, no_browser_errorLOG = structlog.get_logger(__name__)+_MCP_STATE_NAMESPACE_DIR = ".mcp-state"+-def _validate_state_path(file_path: str, *, must_exist: bool = False) -> Path:+def _validate_state_path(+ file_path: str,+ *,+ must_exist: bool = False,+ organization_id: str | None = None,+) -> Path:"""Validate and resolve state file path. Prevents path traversal.Restricts paths to the current working directory or ~/.skyvern/.@@ -30,12 +40,31 @@ def _validate_state_path(file_path: str, *, must_exist: bool = False) -> Path:raise ValueError(f"Symlinks not allowed for state files: {raw}")resolved = raw.resolve()allowed_roots = [Path.cwd().resolve(), (Path.home() / ".skyvern").resolve()]- if not any(resolved == root or str(resolved).startswith(str(root) + "/") for root in allowed_roots):+ matching_roots = [root for root in allowed_roots if resolved == root or resolved.is_relative_to(root)]+ if not matching_roots:raise ValueError(f"State file must be under working directory or ~/.skyvern/: {resolved}")- if must_exist and not resolved.exists():- raise FileNotFoundError(f"State file not found: {resolved}")++ if organization_id is not None:+ allowed_root = max(matching_roots, key=lambda root: len(root.parts))+ namespace_parent = (allowed_root / _MCP_STATE_NAMESPACE_DIR).resolve()+ namespace_id = hashlib.sha256(organization_id.encode()).hexdigest()+ namespace_root = namespace_parent / namespace_id++ if resolved == namespace_parent or resolved.is_relative_to(namespace_parent):+ if resolved != namespace_root and not resolved.is_relative_to(namespace_root):+ raise ValueError("State file is outside the authenticated organization namespace")+ else:+ namespaced = namespace_root / resolved.relative_to(allowed_root)+ if namespaced.is_symlink():+ raise ValueError(f"Symlinks not allowed for state files: {namespaced}")+ resolved = namespaced.resolve()+ if resolved != namespace_root and not resolved.is_relative_to(namespace_root):+ raise ValueError("State file is outside the authenticated organization namespace")+if resolved.suffix not in (".json", ""):raise ValueError(f"State file must have .json extension or no extension: {resolved}")+ if must_exist and not resolved.exists():+ raise FileNotFoundError(f"State file not found: {resolved}")return resolved@@ -55,7 +84,8 @@ async def skyvern_state_save(with Timer() as timer:try:- resolved = _validate_state_path(file_path)+ organization_id = app.AGENT_FUNCTION.get_mcp_request_organization_id()+ resolved = _validate_state_path(file_path, organization_id=organization_id)resolved.parent.mkdir(parents=True, exist_ok=True)session = get_current_session()@@ -120,7 +150,8 @@ async def skyvern_state_load(with Timer() as timer:try:- resolved = _validate_state_path(file_path, must_exist=True)+ organization_id = app.AGENT_FUNCTION.get_mcp_request_organization_id()+ resolved = _validate_state_path(file_path, must_exist=True, organization_id=organization_id)session = get_current_session()browser = session.browserdiff --git a/skyvern/cli/skill_commands.py b/skyvern/cli/skill_commands.pyindex 666a3706a..1790839c7 100644--- a/skyvern/cli/skill_commands.py+++ b/skyvern/cli/skill_commands.py@@ -2,8 +2,11 @@from __future__ import annotations+import jsonimport reimport shutil+import subprocess+from datetime import UTC, datetimefrom pathlib import Pathimport typer@@ -18,6 +21,40 @@ SKILLS_DIR = Path(__file__).parent / "skills"_FRONTMATTER_RE = re.compile(r"^---\n(.*?)\n---", re.DOTALL)+_QA_REPORT_MARKER = "<!-- skyvern-qa-report -->"+_QA_REPORT_PATH = Path(".qa/latest-report.md")+_QA_COMMENT_FIELDS_JQ = '.[] | {id: .id, login: .user.login, head: (.body | split("\n")[0])}'+++def _run_process(command: list[str]) -> subprocess.CompletedProcess[str]:+ try:+ return subprocess.run(command, shell=False, check=False, capture_output=True, text=True)+ except OSError as exc:+ console.print(f"Unable to run {command[0]}: {exc}", style="red", markup=False)+ raise typer.Exit(code=1) from exc+++def _require_success(result: subprocess.CompletedProcess[str], action: str) -> str:+ if result.returncode == 0:+ return result.stdout.strip()+ detail = result.stderr.strip() or result.stdout.strip() or "unknown error"+ console.print(f"Unable to {action}: {detail}", style="red", markup=False)+ raise typer.Exit(code=1)+++def _find_sticky_comment_id(comment_lines: str, login: str) -> str | None:+ """Return the oldest comment by `login` whose body opens with the QA marker."""+ for line in comment_lines.splitlines():+ if not line.strip():+ continue+ try:+ comment = json.loads(line)+ except json.JSONDecodeError:+ continue+ if comment.get("login") == login and str(comment.get("head", "")).strip() == _QA_REPORT_MARKER:+ return str(comment.get("id", ""))+ return None+def get_skill_dirs() -> list[Path]:"""Return sorted list of skill directories (those containing SKILL.md)."""@@ -133,3 +170,89 @@ def skill_copy(target = dst / d.nameshutil.copytree(d, target, dirs_exist_ok=overwrite, ignore=_ignore)console.print(f"[green]Copied {len(dirs)} skills to {dst.resolve()}[/green]")+++@skill_app.command("post-qa-report")+def post_qa_report() -> None:+ """Create or update a pull request QA report comment from .qa/latest-report.md."""+ report_file = _QA_REPORT_PATH+ try:+ report = report_file.read_text(encoding="utf-8")+ except OSError as exc:+ console.print(f"Unable to read {report_file}: {exc}", style="red", markup=False)+ raise typer.Exit(code=1) from exc++ pr_result = _run_process(+ [+ "gh",+ "pr",+ "status",+ "--json",+ "number,state",+ "--jq",+ 'if .currentBranch.state == "OPEN" then .currentBranch.number else empty end',+ ]+ )+ if pr_result.returncode != 0:+ detail = pr_result.stderr.strip() or pr_result.stdout.strip() or "unknown error"+ console.print(f"Unable to check for an open PR: {detail}", style="red", markup=False)+ console.print(f"Report remains at {report_file}.", style="yellow", markup=False)+ raise typer.Exit(code=1)+ if not pr_result.stdout.strip():+ console.print(f"No open PR found. Report remains at {report_file}.", style="yellow", markup=False)+ return+ pr_number = pr_result.stdout.strip()+ if not pr_number.isdecimal():+ console.print("[red]Unable to determine a valid PR number.[/red]")+ raise typer.Exit(code=1)++ commit = _require_success(+ _run_process(["git", "rev-parse", "--short", "HEAD"]),+ "read the current commit",+ )+ timestamp = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ comment_body = f"{_QA_REPORT_MARKER}\n## QA Report — {commit} — {timestamp}\n\n{report}\n"++ # Only ever edit a comment this user authored: any account can post a body containing+ # the marker, and editing on a bare marker match would delete someone else's comment.+ login_result = _run_process(["gh", "api", "user", "--jq", ".login"])+ login = login_result.stdout.strip() if login_result.returncode == 0 else ""+ existing_comment_id = None+ if login:+ comments_result = _run_process(+ [+ "gh",+ "api",+ "--paginate",+ f"repos/{{owner}}/{{repo}}/issues/{pr_number}/comments",+ "--jq",+ _QA_COMMENT_FIELDS_JQ,+ ]+ )+ comment_lines = _require_success(comments_result, "look up the existing report comment")+ existing_comment_id = _find_sticky_comment_id(comment_lines, login)+ else:+ console.print(+ "Could not identify the authenticated gh user; posting a new comment instead of updating.",+ style="yellow",+ markup=False,+ )++ if existing_comment_id:+ if not existing_comment_id.isdecimal():+ console.print("[red]Unable to determine a valid report comment ID.[/red]")+ raise typer.Exit(code=1)+ post_command = [+ "gh",+ "api",+ f"repos/{{owner}}/{{repo}}/issues/comments/{existing_comment_id}",+ "-X",+ "PATCH",+ "-f",+ f"body={comment_body}",+ ]+ else:+ post_command = ["gh", "pr", "comment", pr_number, "--body", comment_body]++ _require_success(_run_process(post_command), "post the report comment")+ console.print("[green]Posted report to the pull request.[/green]")diff --git a/skyvern/cli/skills/qa/SKILL.md b/skyvern/cli/skills/qa/SKILL.mdindex 8265bb01b..10e9f2d8c 100644--- a/skyvern/cli/skills/qa/SKILL.md+++ b/skyvern/cli/skills/qa/SKILL.md@@ -371,44 +371,22 @@ Report the evidence that actually matters:After generating the QA report, persist it to the pull request as a sticky comment so theevidence survives beyond the conversation.-### Check for an open PR+### Save and post the sticky comment-```bash-PR_NUMBER=$(gh pr view --json number -q '.number' 2>/dev/null)-```--If no PR exists for the current branch:-1. Save the full report markdown to `.qa/latest-report.md` in the project root (create the directory if needed).-2. Tell the user: "No open PR found for this branch. QA report saved to `.qa/latest-report.md`. Run /qa again after creating a PR to post it."-3. Stop here — do not attempt to create a PR.+Write the full report markdown from Step 5 to `.qa/latest-report.md` with a filesystem editing tool.+Do not place report text in a shell command, variable assignment, heredoc, or command substitution.-### Post or update the sticky comment--Use a hidden HTML marker to make the comment idempotent across multiple runs:+Then run the fixed command below. It reads `.qa/latest-report.md` and passes it to `gh` as a literal+argument vector without shell evaluation, updating this user's own `<!-- skyvern-qa-report -->` comment+when one already exists:```bash-# Prepare the comment body with the hidden marker-COMMENT_BODY="<!-- skyvern-qa-report -->-## QA Report — $(git rev-parse --short HEAD) — $(date -u +%Y-%m-%dT%H:%M:%SZ)--<the full report markdown from Step 5>-"--# Find an existing QA comment on the PR-EXISTING_COMMENT_ID=$(gh api "repos/{owner}/{repo}/issues/${PR_NUMBER}/comments" \- --jq '.[] | select(.body | test("skyvern-qa-report")) | .id' \- 2>/dev/null | head -1)--if [ -n "$EXISTING_COMMENT_ID" ]; then- # Update the existing comment in place- gh api "repos/{owner}/{repo}/issues/comments/${EXISTING_COMMENT_ID}" \- -X PATCH -f body="$COMMENT_BODY"-else- # Create a new comment- gh pr comment "$PR_NUMBER" --body "$COMMENT_BODY"-fi+skyvern skill post-qa-report```+If no PR exists for the current branch, the command leaves the report at `.qa/latest-report.md`.+Tell the user to run `/qa` again after creating a PR. Do not create a PR just to post a QA report.+### Screenshot handlingScreenshots taken during QA (via `skyvern_screenshot()`) are saved locally for the agent's@@ -421,8 +399,8 @@ other reviewers.### Rules-- Always include the `<!-- skyvern-qa-report -->` marker so repeated runs update the same comment instead of creating duplicates.-- Include the short commit hash and UTC timestamp in the comment header.+- Use `skyvern skill post-qa-report`; do not reconstruct its `gh` calls in a shell.+- The command includes the `<!-- skyvern-qa-report -->` marker, short commit hash, and UTC timestamp.- Do not create a PR just to post a QA report — that is the user's decision.- If `gh` is not available or not authenticated, fall back to saving the report locally and tell the user.diff --git a/skyvern/cli/skills/smoke-test/SKILL.md b/skyvern/cli/skills/smoke-test/SKILL.mdindex 53923e501..41c33c960 100644--- a/skyvern/cli/skills/smoke-test/SKILL.md+++ b/skyvern/cli/skills/smoke-test/SKILL.md@@ -387,9 +387,11 @@ cat >> "$COMMENT_FILE" <<'REPORT_EOF'<the full report markdown from Step 7>REPORT_EOF-# Find an existing smoke test comment on the PR-EXISTING_COMMENT_ID=$(gh api "repos/{owner}/{repo}/issues/${PR_NUMBER}/comments" \- --jq '.[] | select(.body | test("skyvern-smoke-test-report")) | .id' \+# Find this user's own sticky comment across all pages. Matching the marker as a bare+# substring, or without the author, would PATCH someone else's comment out of existence.+GH_LOGIN=$(gh api user --jq .login 2>/dev/null)+EXISTING_COMMENT_ID=$(GH_LOGIN="$GH_LOGIN" gh api --paginate "repos/{owner}/{repo}/issues/${PR_NUMBER}/comments" \+ --jq '.[] | select(.user.login == $ENV.GH_LOGIN) | select(.body | startswith("<!-- skyvern-smoke-test-report -->")) | .id' \2>/dev/null | head -1)if [ -n "$EXISTING_COMMENT_ID" ]; thendiff --git a/skyvern/config.py b/skyvern/config.pyindex 1090d97e3..ff68b90c4 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -231,6 +231,9 @@ class Settings(BaseSettings):WORKFLOW_COPILOT_CODE_BLOCK_MODE: bool = FalseWORKFLOW_COPILOT_TERMINAL_ENVELOPE_RENDER: bool = FalseWORKFLOW_COPILOT_QA_TOKEN_BUDGET: int | None = Field(default=None, gt=0)+ # Process-global override of the per-turn copilot deadline, read once at import;+ # changing it needs a hard restart. QA/debug only -- unset keeps the 900s default.+ WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS: int | None = Field(default=None, gt=0)# Pause a BUILD turn in place on a typed mid-loop credential ask instead of ending it;# the FE resumes the same turn via a credential-connect card. Off = today's turn-terminal behavior.# Requires app.CACHE to be a shared cache (Redis) -- a same-process-only cache can'tdiff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.pyindex 2a1630b33..9be67050a 100644--- a/skyvern/core/script_generations/real_skyvern_page_ai.py+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py@@ -27,6 +27,7 @@ from skyvern.services import script_servicefrom skyvern.services.otp_service import poll_otp_valuefrom skyvern.services.script_reviewer_v3.cohort import is_v3_cohortfrom skyvern.services.script_reviewer_v3.midrun import v3_review_in_flight+from skyvern.services.script_reviewer_v3.redaction import redact_sensitive_content, redact_sensitive_valuefrom skyvern.services.script_reviewer_v3.types import FailureContext, InterceptedActionTypefrom skyvern.utils.css_selector import compute_selector_optionsfrom skyvern.utils.prompt_engine import load_prompt_with_elements, load_prompt_with_elements_tracked@@ -311,9 +312,11 @@ class RealSkyvernPageAi(SkyvernPageAi):failed_selector: str | None = None,block_label: str | None = None,recoverable_marker_id: int | None = None,+ value_is_sensitive: bool = False,v3_parent_episode_id: str | None = None,) -> str:"""Input text into an element using AI to determine the value."""+ sensitive_value = value if value_is_sensitive else None# v3 mid-run hook — see ai_click for the contract.# Never expose an unresolved TOTP value to a reviewer that can write its prompt value directly to the page.@@ -326,6 +329,7 @@ class RealSkyvernPageAi(SkyvernPageAi):totp_identifier=totp_identifier,totp_url=totp_url,block_label=block_label,+ value_is_sensitive=value_is_sensitive,)if class_a:# v3 mid-run committed the fill on the live page. The@@ -458,6 +462,7 @@ class RealSkyvernPageAi(SkyvernPageAi):block_label=block_label,recoverable_marker_id=recoverable_marker_id,v3_parent_episode_id=v3_parent_episode_id,+ sensitive_value=sensitive_value,)else:if is_unresolved_totp_value(transformed_value):@@ -791,6 +796,7 @@ class RealSkyvernPageAi(SkyvernPageAi):totp_identifier: str | None,totp_url: str | None,block_label: str | None,+ value_is_sensitive: bool = False,) -> tuple[str | None, bool]:"""v3 mid-run gate. Called at the top of ai_click / ai_input_text.@@ -843,7 +849,7 @@ class RealSkyvernPageAi(SkyvernPageAi):block_label=block_label or self.current_label or "unknown",fallback_type="element",script_revision_id=context.script_revision_id,- page_url=self.page.url,+ page_url=redact_sensitive_content(self.page.url, value if value_is_sensitive else None),reviewer_version="v3",)episode_id_for_cleanup = episode.episode_id@@ -859,6 +865,7 @@ class RealSkyvernPageAi(SkyvernPageAi):page=self.page,context=context,episode_id=episode.episode_id,+ value_is_sensitive=value_is_sensitive,)result = await v3_review_in_flight(fc)return episode.episode_id, result.decision.is_midrun_class_a()@@ -901,6 +908,7 @@ class RealSkyvernPageAi(SkyvernPageAi):block_label: str | None = None,recoverable_marker_id: int | None = None,v3_parent_episode_id: str | None = None,+ sensitive_value: str | None = None,) -> None:"""Record an element-level fallback episode when ai_click/ai_input_text firesbecause a CSS selector failed or was missing. Gated on code_version >= 2.@@ -968,19 +976,24 @@ class RealSkyvernPageAi(SkyvernPageAi):action_data["css_suggestion"] = f"xpath={xpath}"if hasattr(action, "reasoning"):action_data["reasoning"] = action.reasoning+ action_data = json.loads(+ redact_sensitive_content(json.dumps(action_data, ensure_ascii=False), sensitive_value)+ )+ safe_selector = redact_sensitive_content(failed_selector or "", sensitive_value)+ safe_intention = redact_sensitive_content(intention, sensitive_value)if recoverable_marker_id is not None and failed_selector is None:error_msg = (f"Proactive recovery on page.{action_type}() (marker={recoverable_marker_id}): "f"generator emitted ai='proactive' (no semantic selector at codegen); "- f"AI picked the element. Intention: {intention}"+ f"AI picked the element. Intention: {safe_intention}")else:error_msg = (f"Selector {'failed' if failed_selector else 'missing'} on page.{action_type}(), "f"AI fallback succeeded. "- f"Original selector: {failed_selector or '(none)'}. "- f"Intention: {intention}"+ f"Original selector: {safe_selector or '(none)'}. "+ f"Intention: {safe_intention}")if v3_parent_episode_id:# v3 mid-run Class B fall-through: episode already exists; update@@ -1007,14 +1020,14 @@ class RealSkyvernPageAi(SkyvernPageAi):fallback_type="element",script_revision_id=context.script_revision_id,error_message=error_msg,- page_url=self.page.url,+ page_url=redact_sensitive_content(self.page.url, sensitive_value),agent_actions=action_data,)LOG.info("Recorded element fallback episode for selector failure",block_label=block_label or self.current_label,action_type=action_type,- failed_selector=failed_selector,+ failed_selector=redact_sensitive_value(safe_selector, sensitive_value),)except Exception:LOG.warning("Failed to record element fallback episode for selector failure", exc_info=True)diff --git a/skyvern/core/script_generations/script_skyvern_page.py b/skyvern/core/script_generations/script_skyvern_page.pyindex 34f0bea84..dba18f8cf 100644--- a/skyvern/core/script_generations/script_skyvern_page.py+++ b/skyvern/core/script_generations/script_skyvern_page.py@@ -15,7 +15,13 @@ from playwright.async_api import Pagefrom skyvern.config import settingsfrom skyvern.constants import BROWSER_DOWNLOAD_TIMEOUT, NAVIGATION_MAX_RETRY_TIMEfrom skyvern.core.script_generations.real_skyvern_page_ai import RealSkyvernPageAi, render_template-from skyvern.core.script_generations.skyvern_page import ActionCall, ActionMetadata, RunContext, SkyvernPage+from skyvern.core.script_generations.skyvern_page import (+ ActionCall,+ ActionMetadata,+ ResolvedSensitiveValue,+ RunContext,+ SkyvernPage,+)from skyvern.core.script_generations.skyvern_page_ai import SkyvernPageAifrom skyvern.errors.errors import UserDefinedErrorfrom skyvern.exceptions import (@@ -884,6 +890,13 @@ class ScriptSkyvernPage(SkyvernPage):return value+ def _is_secret_reference(self, value: str) -> bool:+ context = skyvern_context.current()+ if context is None or not context.workflow_run_id:+ return False+ workflow_run_context = app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(context.workflow_run_id)+ return bool(workflow_run_context and workflow_run_context.get_original_secret_value_or_none(value) is not None)+# Class-level cache for TOTP codes to ensure all digits in a sequence use the same code# Key: (workflow_run_id, credential_key), Value: totp_code# Uses TTLCache with 30-second expiry (aligned with TOTP rotation period)@@ -993,7 +1006,7 @@ class ScriptSkyvernPage(SkyvernPage):# Return the specific digitif digit_index < len(totp_code):- return totp_code[digit_index]+ return ResolvedSensitiveValue(totp_code[digit_index])LOG.warning("TOTP digit index out of range",field_name=field_name,diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.pyindex cdca3f073..2e3bfb23e 100644--- a/skyvern/core/script_generations/skyvern_page.py+++ b/skyvern/core/script_generations/skyvern_page.py@@ -19,7 +19,7 @@ from playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom skyvern.config import settingsfrom skyvern.core.script_generations.fuzzy_matcher import match_option as _match_optionfrom skyvern.core.script_generations.skyvern_page_ai import SkyvernPageAi-from skyvern.exceptions import NoTOTPSecretFound, ScriptTerminationException+from skyvern.exceptions import NoTOTPSecretFound, ScriptTerminationException, SkyvernActionFailedfrom skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.files import download_file as download_file_from_url@@ -27,6 +27,7 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.event.factory import EventStrategyFactoryfrom skyvern.forge.sdk.services.credentials import is_unresolved_totp_valuefrom skyvern.library.ai_locator import AILocator+from skyvern.services.script_reviewer_v3.redaction import redact_sensitive_valuefrom skyvern.webeye.actions import handler_utilsfrom skyvern.webeye.actions.action_types import ActionTypefrom skyvern.webeye.browser_engine import BrowserEngineSelection@@ -41,6 +42,10 @@ LOG = structlog.get_logger()_EXTRACT_FORM_FIELDS_JS: str | None = None+class ResolvedSensitiveValue(str):+ """String value whose resolved credential provenance must survive."""++def _is_pointer_interception_error(exc: Exception) -> bool:message = str(exc).lower()return "intercepts pointer events" in message or "intercepted by another element" in message@@ -174,6 +179,9 @@ class SkyvernPage(Page):) -> str:return value+ def _is_secret_reference(self, value: str) -> bool:+ return False+async def _resolve_totp_placeholder_or_raise(self,value: str,@@ -227,7 +235,7 @@ class SkyvernPage(Page):totp_code = await self.get_actual_value(raw_value, totp_identifier, totp_url)# Return the specific digitif digit_index < len(totp_code):- return totp_code[digit_index]+ return ResolvedSensitiveValue(totp_code[digit_index])return ""@staticmethod@@ -796,6 +804,12 @@ class SkyvernPage(Page):if context and context.ai_mode_override:ai = context.ai_mode_override+ original_value = value or ""+ value_is_sensitive = isinstance(original_value, ResolvedSensitiveValue)+ try:+ value_is_sensitive = value_is_sensitive or self._is_secret_reference(original_value)+ except Exception:+ passresolved_totp_value: str | None = Noneif value is not None and is_unresolved_totp_value(value):resolved_totp_value = await self._resolve_totp_placeholder_or_raise(@@ -803,6 +817,7 @@ class SkyvernPage(Page):totp_identifier=kwargs.get("totp_identifier"),totp_url=kwargs.get("totp_url"),)+ value_is_sensitive = Truetimeout = kwargs.pop("timeout", settings.BROWSER_ACTION_TIMEOUT_MS)data = kwargs.pop("data", None)@@ -816,6 +831,7 @@ class SkyvernPage(Page):intention=prompt,data=data,timeout=timeout,+ value_is_sensitive=value_is_sensitive,)# --- Selector-based autocomplete flow ---@@ -828,6 +844,7 @@ class SkyvernPage(Page):intention=prompt,data=data,timeout=timeout,+ value_is_sensitive=value_is_sensitive,)raise ValueError("Selector is required but was not provided")@@ -843,6 +860,7 @@ class SkyvernPage(Page):raiseexcept Exception:pass # use original value+ value_is_sensitive = value_is_sensitive or actual_value != original_valueif is_unresolved_totp_value(actual_value):raise NoTOTPSecretFound()@@ -856,10 +874,11 @@ class SkyvernPage(Page):)return resultexcept Exception as e:+ redaction_value = actual_value if value_is_sensitive else NoneLOG.info("fill_autocomplete selector path failed, trying AI fallback",- selector=selector,- error=str(e),+ selector=redact_sensitive_value(selector, redaction_value),+ error=redact_sensitive_value(str(e), redaction_value),)if prompt:return await self._ai.ai_input_text(@@ -868,8 +887,10 @@ class SkyvernPage(Page):intention=prompt,data=data,timeout=timeout,+ value_is_sensitive=value_is_sensitive,)- raise+ error_to_raise = SkyvernActionFailed(redact_sensitive_value(str(e), redaction_value))+ raise error_to_raise# Common selectors for autocomplete dropdown options, tried in order._AUTOCOMPLETE_OPTION_SELECTORS = [@@ -915,8 +936,6 @@ class SkyvernPage(Page):# commit, then verify the value stuck.LOG.info("fill_autocomplete: no dropdown options found, trying Enter to commit",- selector=selector,- value=value,)await locator.press("Enter", timeout=timeout)await asyncio.sleep(0.5)@@ -926,8 +945,6 @@ class SkyvernPage(Page):if current_value.strip():LOG.info("fill_autocomplete: value committed via Enter",- selector=selector,- value=current_value,)return current_value@@ -935,8 +952,6 @@ class SkyvernPage(Page):# Re-type and try clicking the first available option after a longer wait.LOG.info("fill_autocomplete: value cleared after Enter, retrying with longer wait",- selector=selector,- value=value,)await locator.clear(timeout=timeout)await handler_utils.input_sequentially(locator, value, timeout=timeout)@@ -946,8 +961,6 @@ class SkyvernPage(Page):# Last resort: just fill the raw value and hope it sticksLOG.warning("fill_autocomplete: no dropdown after retry, filling raw value",- selector=selector,- value=value,)await locator.fill(value, timeout=timeout)return value@@ -958,8 +971,6 @@ class SkyvernPage(Page):await best_match.click(timeout=timeout)LOG.info("fill_autocomplete: clicked matching dropdown option",- selector=selector,- value=value,)else:# No close text match — click the first option as best guess@@ -967,8 +978,6 @@ class SkyvernPage(Page):await first.click(timeout=timeout)LOG.info("fill_autocomplete: no close text match, clicked first option",- selector=selector,- value=value,)# Wait for the selection to register in the UI@@ -1060,15 +1069,19 @@ class SkyvernPage(Page):# For single-digit TOTP values (from multi-field TOTP inputs), force fallback mode# so that we use the exact digit value instead of having AI generate a new one- if value and len(value) == 1 and value.isdigit() and ai == "proactive":+ if isinstance(value, ResolvedSensitiveValue) and ai == "proactive":ai = "fallback"# format the text with the actual value of the parameter if it's a secret when running a workflowif ai == "fallback":error_to_raise = None+ value_is_sensitive = Falseoriginal_selector = selector # preserve for fallback episode recordingif selector:try:+ value_is_sensitive = isinstance(+ original_value, ResolvedSensitiveValue+ ) or self._is_secret_reference(original_value)if resolved_totp_value is not None:value = resolved_totp_valueelse:@@ -1077,6 +1090,7 @@ class SkyvernPage(Page):totp_identifier=totp_identifier,totp_url=totp_url,)+ value_is_sensitive = value_is_sensitive or value != original_valueif is_unresolved_totp_value(value):raise NoTOTPSecretFound()# Retry selector lookup to handle page transitions (redirects,@@ -1101,12 +1115,14 @@ class SkyvernPage(Page):except NoTOTPSecretFound:raiseexcept Exception as e:+ redaction_value = value if value_is_sensitive else None+ redacted_error = redact_sensitive_value(str(e), redaction_value)LOG.warning("CSS selector fill failed, falling back to AI",- selector=selector,- error=str(e),+ selector=redact_sensitive_value(selector, redaction_value),+ error=redacted_error,)- error_to_raise = e+ error_to_raise = SkyvernActionFailed(redacted_error)selector = Noneif intention:@@ -1121,6 +1137,7 @@ class SkyvernPage(Page):failed_selector=original_selector or "",block_label=self.current_label,recoverable_marker_id=recoverable_marker_id,+ value_is_sensitive=value_is_sensitive,)if error_to_raise:raise error_to_raisediff --git a/skyvern/core/script_generations/skyvern_page_ai.py b/skyvern/core/script_generations/skyvern_page_ai.pyindex cb6bd85f6..7bebb13e0 100644--- a/skyvern/core/script_generations/skyvern_page_ai.py+++ b/skyvern/core/script_generations/skyvern_page_ai.py@@ -45,6 +45,7 @@ class SkyvernPageAi(Protocol):failed_selector: str | None = None,block_label: str | None = None,recoverable_marker_id: int | None = None,+ value_is_sensitive: bool = False,v3_parent_episode_id: str | None = None,) -> str:"""Input text into an element using AI to determine the value.diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex af27571d2..3174ca3a6 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -1349,6 +1349,17 @@ class MissingBrowserAddressError(SkyvernException):super().__init__(f"Browser session {browser_session_id} does not have an address.")+class MissingRoutedVncAddressError(SkyvernException):+ """No credential-bearing VNC address can be built for a session.++ Raised instead of falling back to the browser's own network address: a live view served+ over an unauthenticated internal address is worse than no live view (SKY-13287).+ """++ def __init__(self, browser_session_id: str) -> None:+ super().__init__(f"Browser session {browser_session_id} has no routed VNC address.")++class BrowserSessionClosed(SkyvernHTTPException):def __init__(self, browser_session_id: str) -> None:super().__init__(diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 40b384e85..2a065f765 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -1167,6 +1167,9 @@ class AgentFunction:"""return None+ def get_mcp_request_organization_id(self) -> str | None:+ return None+async def get_mcp_oauth_jwt_key(self) -> Any | None:"""Return the current signing key/JWK for MCP OAuth token validation.diff --git a/skyvern/forge/sdk/api/real_azure.py b/skyvern/forge/sdk/api/real_azure.pyindex 2506e8e53..120fd1a48 100644--- a/skyvern/forge/sdk/api/real_azure.py+++ b/skyvern/forge/sdk/api/real_azure.py@@ -5,7 +5,7 @@ from mimetypes import add_type, guess_typefrom typing import IO, Selfimport structlog-from azure.core.exceptions import ResourceNotFoundError+from azure.core.exceptions import HttpResponseError, ResourceNotFoundErrorfrom azure.identity.aio import ClientSecretCredential, DefaultAzureCredentialfrom azure.keyvault.secrets.aio import SecretClientfrom azure.storage.blob import BlobSasPermissions, ContentSettings, StandardBlobTier, generate_blob_sas@@ -57,16 +57,28 @@ class RealAsyncAzureVaultClient(AsyncAzureVaultClient):secret_client = await self._get_secret_client(vault_name)try:previous_versions: list[str] = []+ enumerated_any = Falsetry:async for properties in secret_client.list_properties_of_secret_versions(secret_name):+ enumerated_any = Trueif properties.enabled is not False and properties.version is not None:previous_versions.append(properties.version)except ResourceNotFoundError:- pass- except Exception:- # An identity permitted to set but not list secret versions raises an authorization- # error here. Disabling prior versions is best-effort, so log and continue rather than- # failing every write (and, via delete_credential, orphaning material after the row is gone).+ # A brand-new secret has no version history, so a not-found before any version is+ # enumerated is expected — proceed with the create. But a not-found *after* some versions+ # were already listed means pagination was interrupted, leaving the un-enumerated priors+ # enabled and readable; fail the write so it retries instead of silently orphaning them.+ if enumerated_any:+ raise+ except HttpResponseError as e:+ # An identity permitted to set but not list secret versions raises a 401/403 here, and+ # disabling priors is best-effort, so proceed rather than failing every write. Re-raise any+ # other status, or a failure after enumerating any versions (a first page of only+ # current/already-disabled versions leaves `previous_versions` empty yet still means the+ # error is partial), so the write fails and retries instead of silently leaving the+ # un-enumerated prior versions enabled and readable.+ if enumerated_any or e.status_code not in (401, 403):+ raiseLOG.warning("Could not enumerate prior Azure secret versions to disable; proceeding with the write",secret_name=secret_name,diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex e55a63f91..c9bcef64d 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -190,7 +190,11 @@ from skyvern.forge.sdk.copilot.streaming_adapter import (flush_goal_satisfied_tool_result,maybe_emit_design_end,)-from skyvern.forge.sdk.copilot.terminal_envelope import assemble_terminal_envelope, reason_in_reply_shadow+from skyvern.forge.sdk.copilot.terminal_envelope import (+ TerminalCause,+ assemble_terminal_envelope,+ reason_in_reply_shadow,+)from skyvern.forge.sdk.copilot.todo_list import todo_list_promptfrom skyvern.forge.sdk.copilot.tools.guardrails import _record_output_policy_guardrail_churnfrom skyvern.forge.sdk.copilot.tracing_setup import _copilot_model_name, ensure_tracing_initialized, is_tracing_enabled@@ -395,22 +399,22 @@ async def _resolve_live_browser_session_id(return Nonepersistent = await app.PERSISTENT_SESSIONS_MANAGER.get_session(requested, organization_id)- has_browser_address = bool(persistent.browser_address) if persistent else False+ has_live_browser = persistent.is_browser_ready if persistent else Falsehas_registered_browser_state = False- if persistent is not None and not is_final_status(persistent.status) and not has_browser_address:+ if persistent is not None and not is_final_status(persistent.status) and not has_live_browser:has_registered_browser_state = await _registered_browser_state_is_usable(requested, organization_id)if (persistent is Noneor is_final_status(persistent.status)- or (not has_browser_address and not has_registered_browser_state)+ or (not has_live_browser and not has_registered_browser_state)):LOG.warning("Copilot live browser session is not yet usable; falling back to auto-create",organization_id=organization_id,requested_session_id=requested,status=persistent.status if persistent else None,- has_browser_address=has_browser_address,+ has_live_browser=has_live_browser,has_registered_browser_state=has_registered_browser_state,)return None@@ -1824,6 +1828,7 @@ def _assemble_terminal_envelope_safe(workflow_mutated: bool,turn_outcome_response_kind: str | None,final_message: str,+ terminal_cause: TerminalCause | None = None,) -> dict[str, Any] | None:try:envelope = assemble_terminal_envelope(@@ -1837,6 +1842,7 @@ def _assemble_terminal_envelope_safe(attempted=attempted,workflow_mutated=workflow_mutated,turn_outcome_response_kind=turn_outcome_response_kind,+ terminal_cause=terminal_cause,)except Exception:LOG.warning("copilot terminal envelope assembly failed", exc_info=True)@@ -1963,6 +1969,7 @@ def _make_agent_result(workflow_mutated=bool(kwargs.get("workflow_was_persisted")) or kwargs.get("updated_workflow") is not None,turn_outcome_response_kind=turn_outcome_response_kind,final_message=str(kwargs.get("user_response") or ""),+ terminal_cause="deadline_expired" if ctx.copilot_total_timeout_exceeded is True else None,)kwargs["terminal_envelope"] = terminal_enveloperesult = AgentResult(global_llm_context=final_context, turn_outcome=turn_outcome, **kwargs)@@ -2937,6 +2944,18 @@ def _last_good_failure_reply(ctx: CopilotContext, tested_reply: str) -> str:return f"{tested_reply} The latest attempted change did not verify: {reason}.{status_sentence}"+def _deadline_failure_reply(ctx: CopilotContext, deadline_reply: str, *, halted_mid_progress: bool) -> str:+ # A guard-halted or budget-paced run was interrupted, not disproven, and the deadline copy+ # already says the work is unverified -- appending a failure verdict would mis-attribute the+ # stop a second time, which is the defect this precedence exists to remove.+ if halted_mid_progress:+ return deadline_reply+ reason, status_sentence = _recorded_failure_summary(ctx)+ if not reason:+ return deadline_reply+ return f"{deadline_reply} The last test did not verify: {reason}.{status_sentence}"++def _recorded_failure_reply(ctx: CopilotContext, *, cancelled: bool = False, internal_tool_instruction_failure: bool | None = None) -> str | None:@@ -3005,6 +3024,19 @@ def _build_wip_exit_result(ctx, cancelled=cancelled, internal_tool_instruction_failure=internal_tool_instruction_failure)effective_terminal = terminal_reason or ("cancel" if cancelled else None)+ # Deadline expiry and a recorded failure both want to author the reply. The+ # deadline owns it -- the failed test is what spent the budget, so naming the+ # test as the cause mis-attributes the stop. Same latch the envelope's+ # terminal_cause reads, so the rendered text and the typed cause cannot diverge.+ deadline_owns_reply = ctx.copilot_total_timeout_exceeded is True and not cancelled++ # An interrupted run was not disproven, so a deadline-expired turn appends no failure verdict.+ deadline_suppresses_failure_detail = deadline_owns_reply and halted_mid_progress++ def _deadline_owned_or(base_reply: str, failure_reply: str | None) -> str | None:+ if deadline_owns_reply and failure_reply:+ return _deadline_failure_reply(ctx, base_reply, halted_mid_progress=halted_mid_progress)+ return failure_replydef _guard(text: str) -> tuple[str, TurnOutcome]:if contains_internal_machinery_leak(text):@@ -3061,7 +3093,8 @@ def _build_wip_exit_result(and ctx.last_workflow is not ctx.last_good_workflowand not ctx.last_test_suspicious_success):- reply = _last_good_failure_reply(ctx, tested_reply) if recorded_failure_reply else tested_reply+ append_failure_detail = recorded_failure_reply and not deadline_suppresses_failure_detail+ reply = _last_good_failure_reply(ctx, tested_reply) if append_failure_detail else tested_replyfinal_text, outcome = _guard(reply)return _finalize_result_with_blocker_override(ctx,@@ -3100,7 +3133,7 @@ def _build_wip_exit_result(full_test_ok = ctx.last_test_ok is True and ctx.last_full_workflow_test_ok is Trueunvalidated = not full_test_okif unvalidated and recorded_failure_reply:- reply = recorded_failure_reply+ reply = _deadline_owned_or(unvalidated_reply, recorded_failure_reply) or unvalidated_replyelse:reply = unvalidated_reply if unvalidated else tested_replyfinal_text, outcome = _guard(reply)@@ -3137,7 +3170,7 @@ def _build_wip_exit_result()return _build_exit_result(ctx,- recorded_failure_reply or default_reply,+ _deadline_owned_or(default_reply, recorded_failure_reply) or default_reply,global_llm_context,cancelled=cancelled,terminal_reason=effective_terminal,diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 2430ba626..4c1d68ed2 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -16,6 +16,7 @@ import structlogfrom agents import ModelSettings, RunConfigfrom agents.run import Runner+from skyvern.config import settingsfrom skyvern.forge.sdk.copilot import config as copilot_config_defaultsfrom skyvern.forge.sdk.copilot import streaming_adapterfrom skyvern.forge.sdk.copilot.blocker_signal import (@@ -24,7 +25,11 @@ from skyvern.forge.sdk.copilot.blocker_signal import (clear_tool_blocker_signals_for_reason_codes,stash_blocker_signal,)-from skyvern.forge.sdk.copilot.build_phase import DISCOVERY_FAILURE_STREAK_ESCAPE_THRESHOLD, DISCOVERY_PERMITTED_PHASES+from skyvern.forge.sdk.copilot.build_phase import (+ DISCOVERY_FAILURE_STREAK_ESCAPE_THRESHOLD,+ DISCOVERY_PERMITTED_PHASES,+ BuildPhase,+)from skyvern.forge.sdk.copilot.build_test_outcome import (latest_recorded_build_test_outcome_repeated,)@@ -197,7 +202,7 @@ REPEATED_FRONTIER_STREAK_STOP_AT = 3MAX_PER_TOOL_BUDGET_NUDGES = 2_NO_PROGRESS_INTERACTION_REASON_CODES = frozenset({"loop_detected_no_forward_progress_interaction"})MIN_BLOCKS_FOR_AUTO_COMPLETE = 10-TOTAL_TIMEOUT_SECONDS = 900+TOTAL_TIMEOUT_SECONDS = settings.WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS or 900# Floor for the per-iteration ``wait_for`` deadline so an already-spent budget# never yields ``wait_for(timeout=0)`` (which raises immediately). Kept as a# constant so tests can shrink it instead of paying a full second per deadline.@@ -686,8 +691,20 @@ def _verified_goal_likely_needs_more_work(ctx: CopilotContext) -> bool:return _goal_likely_needs_more_blocks(user_message, block_count, completion_contract)-def _mark_copilot_total_timeout(ctx: Any) -> None:+def _mark_copilot_total_timeout(ctx: Any, *, elapsed_seconds: float, iteration: int) -> None:+ already_marked = ctx.copilot_total_timeout_exceeded is Truectx.copilot_total_timeout_exceeded = True+ if already_marked:+ return+ # Only CopilotContext carries build_phase; the self-heal path passes a bare AgentContext,+ # and an AttributeError here would replace the timeout with a crash.+ build_phase = getattr(ctx, "build_phase", None)+ LOG.warning(+ "copilot_turn_deadline_expired",+ elapsed_seconds=round(elapsed_seconds, 3),+ iteration=iteration,+ build_phase=build_phase.value if isinstance(build_phase, BuildPhase) else None,+ )def _elapsed_run_seconds(ctx: Any, start_time: float) -> float:@@ -706,9 +723,10 @@ def _elapsed_run_seconds(ctx: Any, start_time: float) -> float:return time.monotonic() - start_time - pause_seconds-def _mark_copilot_total_timeout_if_elapsed(ctx: Any, start_time: float) -> None:- if _elapsed_run_seconds(ctx, start_time) >= TOTAL_TIMEOUT_SECONDS:- _mark_copilot_total_timeout(ctx)+def _mark_copilot_total_timeout_if_elapsed(ctx: Any, start_time: float, iteration: int) -> None:+ elapsed = _elapsed_run_seconds(ctx, start_time)+ if elapsed >= TOTAL_TIMEOUT_SECONDS:+ _mark_copilot_total_timeout(ctx, elapsed_seconds=elapsed, iteration=iteration)class CopilotNonRetriableNavError(Exception):@@ -1939,12 +1957,7 @@ async def _run_streamed_with_deadline(finally:_accumulate_usage(result, ctx)except asyncio.TimeoutError:- _mark_copilot_total_timeout(ctx)- LOG.warning(- "Copilot total timeout exceeded mid-iteration",- elapsed_seconds=round(time.monotonic() - start_time, 3),- iteration=iteration,- )+ _mark_copilot_total_timeout(ctx, elapsed_seconds=_elapsed_run_seconds(ctx, start_time), iteration=iteration)raise CopilotTotalTimeoutError() from Nonereturn result@@ -3002,7 +3015,7 @@ async def run_with_enforcement(# chat history on the server side (see SKY-8986).elapsed = _elapsed_run_seconds(ctx, start_time)if elapsed > TOTAL_TIMEOUT_SECONDS:- _mark_copilot_total_timeout(ctx)+ _mark_copilot_total_timeout(ctx, elapsed_seconds=elapsed, iteration=iteration)raise CopilotTotalTimeoutError()# When the current turn contains image payloads, the session-backed@@ -3076,7 +3089,7 @@ async def run_with_enforcement(iteration,)except asyncio.CancelledError:- _mark_copilot_total_timeout_if_elapsed(ctx, start_time)+ _mark_copilot_total_timeout_if_elapsed(ctx, start_time, iteration)raiseexcept Exception as e:if not _is_context_window_error(e):@@ -3100,7 +3113,7 @@ async def run_with_enforcement(try:current_input, images_stripped = await _recover_from_context_overflow(session, current_input)except asyncio.CancelledError:- _mark_copilot_total_timeout_if_elapsed(ctx, start_time)+ _mark_copilot_total_timeout_if_elapsed(ctx, start_time, iteration)raiseif images_stripped:# The agent could otherwise reason about the page from@@ -3119,7 +3132,7 @@ async def run_with_enforcement(iteration,)except asyncio.CancelledError:- _mark_copilot_total_timeout_if_elapsed(ctx, start_time)+ _mark_copilot_total_timeout_if_elapsed(ctx, start_time, iteration)raiseexcept Exception as retry_err:# Never retry twice; even a second overflow surfaces as adiff --git a/skyvern/forge/sdk/copilot/terminal_envelope.py b/skyvern/forge/sdk/copilot/terminal_envelope.pyindex 9a49278f4..18fdc59b1 100644--- a/skyvern/forge/sdk/copilot/terminal_envelope.py+++ b/skyvern/forge/sdk/copilot/terminal_envelope.py@@ -12,6 +12,7 @@ LOG = structlog.get_logger(__name__)TerminalNextState = Literal["completed", "proposal_pending", "awaiting_user_input", "stopped"]TerminalResponseKind = Literal["question", "update", "answer", "stopped"]+TerminalCause = Literal["deadline_expired"]_FINAL_RUN_VERDICTS = frozenset({"demonstrated", "not_demonstrated", "not_evaluated"})_REVIEW_PROPOSAL_DISPOSITIONS = frozenset({"review_untested", "review_tested"})_SHADOW_REASON_TRAILING_PUNCTUATION = ".,;:!?"@@ -34,6 +35,7 @@ class TerminalOutcomeEnvelope(BaseModel):user_action_required: bool = Falseattempted: str | None = Noneresponse_kind: TerminalResponseKind+ terminal_cause: TerminalCause | None = Nonerendered_from_envelope: bool = Falseenvelope_version: int = 1@@ -50,6 +52,7 @@ def assemble_terminal_envelope(attempted: str | None,workflow_mutated: bool,turn_outcome_response_kind: str | None,+ terminal_cause: TerminalCause | None = None,) -> TerminalOutcomeEnvelope | None:run_outcome = _select_run_outcome_anchor(run_outcomes)superseding_outcome = _later_demonstrated_after_anchor(run_outcomes, run_outcome)@@ -86,6 +89,7 @@ def assemble_terminal_envelope(user_action_required=user_action_required,attempted=_clean_text(attempted),response_kind=response_kind,+ terminal_cause=terminal_cause,)@@ -125,6 +129,15 @@ def interrupted_terminal_envelope() -> TerminalOutcomeEnvelope:def render_terminal_message(envelope: TerminalOutcomeEnvelope, agent_message: str, cancelled: bool) -> tuple[str, bool]:+ # A deadline-expired turn already authored copy naming time and the draft's+ # state; replaced=True is what syncs it to the surfaces hydration prefers.+ # "completed" is excluded because replaced=True also overwrites a distinct+ # narrativeSummary, and an applied turn's summary is not the terminal text.+ # "awaiting_user_input" needs no exclusion: it requires ASK_QUESTION, and a deadline+ # always exits through _build_wip_exit_result, which only ever builds REPLY results.+ if envelope.terminal_cause == "deadline_expired" and not cancelled and envelope.next_state != "completed":+ return agent_message, True+# Diagnose/refuse answers share next_state="stopped" but their text IS the# deliverable — only stopped-kind turns get the honest-stop replacement.if cancelled or envelope.next_state != "stopped" or envelope.response_kind != "stopped":diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.pyindex 645e56406..9ff9ea9f2 100644--- a/skyvern/forge/sdk/copilot/tools/completion.py+++ b/skyvern/forge/sdk/copilot/tools/completion.py@@ -1907,6 +1907,7 @@ def _tool_visible_result_after_completion_verification(result: dict[str, Any],completion_verification: CompletionVerificationResult | None,) -> dict[str, Any]:+ result["turn_seconds_remaining"] = _copilot_seconds_remaining(copilot_ctx)if outcome_fully_verified(copilot_ctx):return resultoutcome_unverified_reason = _outcome_unverified_reason(copilot_ctx, completion_verification)diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex 6f29f823d..a4b079054 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -1316,8 +1316,11 @@ class PersistentBrowserSessionModel(Base):),# The orphan sweep (SKY-13158) is deliberately cross-organization, so it matches neither# index above. The partial predicate is what does the work: it restricts the index to live- # vendor-held rows, a small subset, which is why plain column keys are enough even though- # the sweep orders by COALESCE(last_activity_at, started_at).+ # rows of the shape the sweep can identify from this table alone, a small subset, which is+ # why plain column keys are enough even though the sweep orders by+ # COALESCE(last_activity_at, started_at). Rows whose provider is recorded elsewhere are not+ # identifiable by shape and are swept off that table's own index instead — a partial+ # predicate cannot reference another table's columns.# Do NOT "fix" the keys to that COALESCE expression: alembic cannot reliably compare# expression-based indexes, so an expression key here reads as drift and fails `alembic# check`. Its postgresql_where is never compared, so the partial predicate is safe.diff --git a/skyvern/forge/sdk/db/polls.py b/skyvern/forge/sdk/db/polls.pyindex 0636fa0fb..669f8dcd9 100644--- a/skyvern/forge/sdk/db/polls.py+++ b/skyvern/forge/sdk/db/polls.py@@ -36,12 +36,12 @@ async def await_browser_session(raise Exception(f"Persistent browser session not found for {session_id}")LOG.debug(- "Checking browser address",+ "Checking browser readiness",session_id=session_id,- address=persistent_browser_session.browser_address,+ is_browser_ready=persistent_browser_session.is_browser_ready,)- if persistent_browser_session.browser_address:+ if persistent_browser_session.is_browser_ready:return persistent_browser_sessionawait asyncio.sleep(poll_interval)diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.pyindex 518c36491..b7fa5c968 100644--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py@@ -53,11 +53,6 @@ _VISIBLE_TO_CUSTOMER = or_(PersistentBrowserSessionModel.browser_address.isnot(None),)-_VENDOR_HELD = and_(- PersistentBrowserSessionModel.upstream_cdp_url.isnot(None),- PersistentBrowserSessionModel.browser_address.is_(None),-)-class BrowserSessionsRepository(BaseRepository):"""Database operations for browser profiles and persistent browser sessions."""@@ -702,38 +697,6 @@ class BrowserSessionsRepository(BaseRepository):await session.refresh(browser_session)return PersistentBrowserSession.model_validate(browser_session)- @db_operation("get_stale_vendor_held_browser_sessions")- async def get_stale_vendor_held_browser_sessions(- self,- *,- stale_before: datetime,- limit: int,- ) -> list[PersistentBrowserSession]:- """Vendor-held rows whose proxy lease has aged past ``stale_before``, oldest first.-- The lease is ``last_activity_at`` — the proxy restamps it while it relays client commands,- so it ages by itself the moment the owning process stops, whether that was graceful or a- SIGKILL. ``started_at`` covers a session that died before its first relayed command. When- both are NULL the COALESCE comparison is NULL and the row is excluded: a row that cannot be- dated is never reaped.- """- async with self.Session() as session:- lease_at = func.coalesce(- PersistentBrowserSessionModel.last_activity_at,- PersistentBrowserSessionModel.started_at,- )- query = (- select(PersistentBrowserSessionModel)- .filter(_VENDOR_HELD)- .filter_by(deleted_at=None, completed_at=None)- .filter(PersistentBrowserSessionModel.status.not_in(FINAL_STATUSES))- .filter(lease_at < stale_before)- .order_by(lease_at)- .limit(limit)- )- rows = (await session.scalars(query)).all()- return [PersistentBrowserSession.model_validate(row) for row in rows]-@db_operation("get_persistent_browser_session_unscoped")async def get_persistent_browser_session_unscoped(self, session_id: str) -> PersistentBrowserSession | None:"""Primary-key read without organization scoping, for trusted internal session@@ -891,12 +854,18 @@ class BrowserSessionsRepository(BaseRepository):organization_id: str | None = None,upstream_cdp_url: str | None = None,browser_vendor: str | None = None,+ mark_started: bool = False,) -> None:"""Set the browser address for a persistent browser session.browser_address is the client-facing (proxied) URL; upstream_cdp_url is the endpoint theCDP proxy dials and must never be handed to a client. It is never a long-lived operatorcredential, though it may carry a session-scoped token.++ mark_started starts the session's timeout clock, which is not implied by writing an+ address: an address naming the session rather than the browser is publishable before+ anything is provisioned, and starting the clock there would bill and expire a session+ that has no browser yet."""async with self.Session() as session:persistent_browser_session = (@@ -910,7 +879,7 @@ class BrowserSessionsRepository(BaseRepository):if persistent_browser_session:if browser_address:persistent_browser_session.browser_address = browser_address- # once the address is set, the session is started+ if mark_started:persistent_browser_session.started_at = naive_utc_now()if ip_address:persistent_browser_session.ip_address = ip_addressdiff --git a/skyvern/forge/sdk/routes/streaming/channels/cdp.py b/skyvern/forge/sdk/routes/streaming/channels/cdp.pyindex da668658a..7900c1b5f 100644--- a/skyvern/forge/sdk/routes/streaming/channels/cdp.py+++ b/skyvern/forge/sdk/routes/streaming/channels/cdp.py@@ -24,6 +24,7 @@ from skyvern.config import settingsfrom skyvern.webeye.cdp_connection import (connect_over_cdp_with_diagnostics,is_local_pbs_cdp_url,+ redact_cdp_url,resolve_local_pbs_cdp_url,)from skyvern.webeye.main_world_eval import evaluate_in_main_world@@ -84,7 +85,9 @@ class CdpChannel:def identity(self) -> t.Dict[str, t.Any]:base = self.vnc_channel.identity- return base | {"cdp_url": self.url}+ # This mapping is splatted into every log line this channel writes, and the url it holds+ # is the session's own address — which carries the session token.+ return base | {"cdp_url": redact_cdp_url(self.url)}async def connect(self, cdp_url: str | None = None) -> t.Self:"""diff --git a/skyvern/forge/sdk/routes/streaming/channels/vnc.py b/skyvern/forge/sdk/routes/streaming/channels/vnc.pyindex fa447e201..8f0e24436 100644--- a/skyvern/forge/sdk/routes/streaming/channels/vnc.py+++ b/skyvern/forge/sdk/routes/streaming/channels/vnc.py@@ -21,7 +21,7 @@ import dataclassesimport timeimport typing as tfrom enum import IntEnum-from urllib.parse import urlparse+from urllib.parse import parse_qs, urlparseimport structlogimport websockets@@ -30,6 +30,7 @@ from starlette.websockets import WebSocketStatefrom websockets import ConnectionClosedError, ConnectionClosedOK, Datafrom skyvern.config import settings+from skyvern.exceptions import MissingRoutedVncAddressErrorfrom skyvern.forge.sdk.routes.streaming.auth import get_x_api_keyfrom skyvern.forge.sdk.routes.streaming.channels.execution import execution_channelfrom skyvern.forge.sdk.routes.streaming.registries import (@@ -50,6 +51,8 @@ from skyvern.forge.sdk.schemas.persistent_browser_sessions import AddressablePerfrom skyvern.forge.sdk.schemas.tasks import Taskfrom skyvern.forge.sdk.utils.aio import collectfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRun+from skyvern.webeye.cdp_connection import redact_cdp_url+from skyvern.webeye.cdp_credentials import LIVE_VIEW_PATH_PREFIXLOG = structlog.get_logger()@@ -295,41 +298,50 @@ async def ask_for_clipboard(vnc_channel: VncChannel) -> None:LOG.exception(f"{class_name} Failed to ask for clipboard via CDP", **vnc_channel.identity)-# TODO(benji): I hate this function. It's messy and gross. Once we remove v1,-# we should clean this up.-def _build_vnc_url_from_browser_address(browser_address: str) -> str | None:- """- Build a routed VNC URL from a V2 K8s routed browser_address.+LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")+++def _build_vnc_url_from_browser_address(browser_address: str | None, vnc_port: int) -> str | None:+ """The routed, credential-bearing VNC address for a session, or None if none can be built.- V2 K8s routed browser_address format:- wss://{domain}/{session_id}/{token}/devtools/browser/{browser_id}+ Both routed shapes carry the same credential their CDP address carries, and both are checked+ at the edge before any byte reaches the browser:- Returns VNC URL in format:- wss://{domain}/vnc/{session_id}/{token}+ router: wss://{host}/{session_id}?token={token}+ -> wss://{host}/vnc/{session_id}?token={token}+ legacy: wss://{host}/{session_id}/{token}/devtools/browser/{browser_id}+ -> wss://{host}/vnc/{session_id}/{token}- Returns None if browser_address is not a V2 routed URL.+ Both are shapes ``redact_cdp_url`` knows how to mask; the prefix is shared with it and with+ the router's own live-view routing so a rename cannot silently unmask the legacy token.++ A loopback address is the single-host case (local dev, single-container self-hosting): the+ websockify listener is on the API host itself, inside one trust domain, with no edge to route+ through. Every other address returns None rather than naming the browser directly — reaching+ a private pod or VPC address would stream a customer live view with no credential on the+ wire, which is worse than no live view at all (SKY-13287)."""if not browser_address:return Noneparsed = urlparse(browser_address)-- # Check if this looks like a V2 routed URL (wss:// with token in path)if parsed.scheme not in ("wss", "ws"):return None+ if parsed.hostname in LOOPBACK_HOSTS:+ return f"ws://{parsed.hostname}:{vnc_port}"- # Parse path: /{session_id}/{token}/devtools/browser/{browser_id}- path_parts = parsed.path.strip("/").split("/")- if len(path_parts) < 4 or path_parts[2] != "devtools":- return None+ scheme = "wss" if parsed.scheme == "wss" else "ws"+ path_parts = [part for part in parsed.path.split("/") if part]- session_id = path_parts[0]- token = path_parts[1]- domain = parsed.netloc+ # The query is passed through verbatim rather than re-encoded: it is what the router+ # re-parses to recover the session token, and re-encoding could alter it.+ if len(path_parts) == 1 and parse_qs(parsed.query).get("token"):+ return f"{scheme}://{parsed.netloc}{LIVE_VIEW_PATH_PREFIX}{path_parts[0]}?{parsed.query}"- # Build VNC URL with same domain and token- scheme = "wss" if parsed.scheme == "wss" else "ws"- return f"{scheme}://{domain}/vnc/{session_id}/{token}"+ if len(path_parts) >= 4 and path_parts[2] == "devtools":+ return f"{scheme}://{parsed.netloc}{LIVE_VIEW_PATH_PREFIX}{path_parts[0]}/{path_parts[1]}"++ return Noneasync def loop_stream_vnc(vnc_channel: VncChannel) -> None:@@ -339,36 +351,19 @@ async def loop_stream_vnc(vnc_channel: VncChannel) -> None:Loops until the task is cleared or the websocket is closed."""- vnc_url: str = ""browser_session = vnc_channel.browser_sessionclass_name = vnc_channel.class_nameif not browser_session:raise Exception(f"{class_name} No browser session associated with vnc channel.")- # First, check if this is a V2 K8s routed session by examining browser_address- # V2 sessions have browser_address like: wss://{domain}/{session_id}/{token}/devtools/...- # For these, we need to route VNC through the same nginx proxy- routed_vnc_url = _build_vnc_url_from_browser_address(browser_session.browser_address)- if routed_vnc_url:- vnc_url = routed_vnc_url- elif browser_session.ip_address:- # V1 ECS sessions: Direct IP connection (ip_address is a public/reachable IP)- if ":" in browser_session.ip_address:- ip, _ = browser_session.ip_address.split(":")- vnc_url = f"ws://{ip}:{vnc_channel.vnc_port}"- else:- vnc_url = f"ws://{browser_session.ip_address}:{vnc_channel.vnc_port}"- else:- # Last resort: parse browser_address hostname- browser_address = browser_session.browser_address- parsed_browser_address = urlparse(browser_address)- host = parsed_browser_address.hostname- vnc_url = f"ws://{host}:{vnc_channel.vnc_port}"+ vnc_url = _build_vnc_url_from_browser_address(browser_session.browser_address, vnc_channel.vnc_port)+ if not vnc_url:+ raise MissingRoutedVncAddressError(browser_session.persistent_browser_session_id)LOG.debug(f"{class_name} Connecting to vnc url.",- vnc_url=vnc_url,+ vnc_url=redact_cdp_url(vnc_url),**vnc_channel.identity,)diff --git a/skyvern/forge/sdk/routes/streaming/registries.py b/skyvern/forge/sdk/routes/streaming/registries.pyindex 91e879588..ddd058cf5 100644--- a/skyvern/forge/sdk/routes/streaming/registries.py+++ b/skyvern/forge/sdk/routes/streaming/registries.py@@ -100,7 +100,7 @@ def del_message_channel(client_id: str, *, expected: MessageChannel | None = Non# Stream reference counts per workflow_run_id._stream_refcounts: dict[str, int] = {}-_deferred_close_params: dict[str, bool] = {}+_deferred_close_params: dict[str, tuple[bool, bool | None]] = {}def stream_ref_inc(workflow_run_id: str) -> None:@@ -111,14 +111,18 @@ async def stream_ref_dec(workflow_run_id: str) -> None:count = _stream_refcounts.get(workflow_run_id, 0) - 1if count <= 0:_stream_refcounts.pop(workflow_run_id, None)- close_on_completion = _deferred_close_params.pop(workflow_run_id, None)- if close_on_completion is not None:+ close_params = _deferred_close_params.pop(workflow_run_id, None)+ if close_params is not None:from skyvern.forge import app+ close_on_completion, release_driver = close_paramsbrowser_state = app.BROWSER_MANAGER.pages.get(workflow_run_id)if browser_state is not None:try:- await browser_state.close(close_browser_on_completion=close_on_completion)+ await browser_state.close(+ close_browser_on_completion=close_on_completion,+ release_driver=release_driver,+ )except Exception:LOG.warning("stream_ref_dec: error closing deferred browser state",@@ -134,8 +138,15 @@ def stream_ref_active(workflow_run_id: str) -> bool:return _stream_refcounts.get(workflow_run_id, 0) > 0-def set_deferred_close_params(workflow_run_id: str, close_browser_on_completion: bool) -> None:- _deferred_close_params[workflow_run_id] = close_browser_on_completion+def set_deferred_close_params(+ workflow_run_id: str,+ close_browser_on_completion: bool,+ release_driver: bool | None = None,+) -> bool:+ if not stream_ref_active(workflow_run_id):+ return False+ _deferred_close_params[workflow_run_id] = (close_browser_on_completion, release_driver)+ return True# a registry for CDP input channels, keyed by `client_id`diff --git a/skyvern/forge/sdk/routes/streaming/verify.py b/skyvern/forge/sdk/routes/streaming/verify.pyindex 7821342be..f61970b89 100644--- a/skyvern/forge/sdk/routes/streaming/verify.py+++ b/skyvern/forge/sdk/routes/streaming/verify.py@@ -88,7 +88,7 @@ async def verify_browser_session()return None- browser_address = browser_session.browser_address+ browser_address = browser_session.browser_address if browser_session.is_browser_ready else Noneif not browser_address:if settings.BROWSER_STREAMING_MODE == "cdp":@@ -170,7 +170,7 @@ async def verify_task(LOG.info("No browser session found for task.", task_id=task_id, organization_id=organization_id)return task, None- if not browser_session.browser_address:+ if not browser_session.is_browser_ready or not browser_session.browser_address:LOG.info("Browser session address not found for task.", task_id=task_id, organization_id=organization_id)return task, None@@ -241,7 +241,7 @@ async def verify_workflow_run()return workflow_run, None- browser_address = browser_session.browser_address+ browser_address = browser_session.browser_address if browser_session.is_browser_ready else Noneif not browser_address:LOG.info(diff --git a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py b/skyvern/forge/sdk/schemas/persistent_browser_sessions.pyindex 58543b007..7d586f3fa 100644--- a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py+++ b/skyvern/forge/sdk/schemas/persistent_browser_sessions.py@@ -104,6 +104,17 @@ class PersistentBrowserSession(BaseModel):# so teardown exported under the session id rather than the bp_ id.browser_profile_loaded: bool = True+ @property+ def is_browser_ready(self) -> bool:+ """Whether a browser exists for this session and can be connected to.++ Keyed on upstream_cdp_url and NOT on browser_address: a client-facing address can be+ minted when the session is created, before anything is provisioned, so its presence says+ only that an address was issued. The session worker writes this column in the same call+ that starts the session clock, which is what makes it the readiness signal.+ """+ return bool(self.upstream_cdp_url)+@field_validator("proxy_location", mode="before")@classmethoddef deserialize_proxy_location_field(cls, value: object) -> object:diff --git a/skyvern/forge/sdk/services/credential/azure_credential_vault_service.py b/skyvern/forge/sdk/services/credential/azure_credential_vault_service.pyindex e5a3e27eb..41e827493 100644--- a/skyvern/forge/sdk/services/credential/azure_credential_vault_service.py+++ b/skyvern/forge/sdk/services/credential/azure_credential_vault_service.py@@ -117,13 +117,16 @@ class AzureCredentialVaultService(CredentialVaultService):self,credential: Credential,) -> None:- await app.DATABASE.credentials.delete_credential(credential.credential_id, credential.organization_id)- # Deleting takes several seconds, so we empty the value and delete async so customers do not have to wait+ # Empty the secret value before deleting the DB row: a transient vault failure then aborts the whole+ # delete with the row (and its item_id) intact for a retry, instead of orphaning a still-readable+ # secret with no DB pointer left to scrub it. The slow full-vault delete is deferred to+ # post_delete_credential_item so customers do not have to wait.await self._client.create_or_update_secret(vault_name=self._vault_name,secret_name=credential.item_id,secret_value="",)+ await app.DATABASE.credentials.delete_credential(credential.credential_id, credential.organization_id)async def post_delete_credential_item(self, item_id: str, _organization_id: str | None = None) -> bool:"""diff --git a/skyvern/forge/sdk/services/credential/credential_vault_service.py b/skyvern/forge/sdk/services/credential/credential_vault_service.pyindex 066c1b85a..da9694770 100644--- a/skyvern/forge/sdk/services/credential/credential_vault_service.py+++ b/skyvern/forge/sdk/services/credential/credential_vault_service.py@@ -76,11 +76,24 @@ class CredentialVaultService(ABC):vault_type=vault_type,exc_info=True,)- await app.AGENT_FUNCTION.on_credential_item_orphaned(- organization_id=organization_id,- item_id=item_id,- vault_type=vault_type,- )+ # The caller invokes this inside `except BaseException: ... ; raise`, so a durable-enqueue+ # failure must not escape _run(): it would replace the in-flight exception (e.g. the+ # write-lease cancellation the caller is re-raising) with an unrelated one. Log and swallow so+ # the caller's bare `raise` always re-raises the original.+ try:+ await app.AGENT_FUNCTION.on_credential_item_orphaned(+ organization_id=organization_id,+ item_id=item_id,+ vault_type=vault_type,+ )+ except Exception:+ LOG.error(+ "Durable vault-item cleanup enqueue failed; item may stay orphaned until the reaper reclaims it",+ organization_id=organization_id,+ item_id=item_id,+ vault_type=vault_type,+ exc_info=True,+ )reclaim = asyncio.ensure_future(_run())while not reclaim.done():diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex e35477ac6..9521d4d24 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -8622,7 +8622,7 @@ class WorkflowService:close_browser_on_completion = (close_browser_on_completion and browser_session_id is None and not workflow_run.browser_address)- browser_state = await app.BROWSER_MANAGER.cleanup_for_workflow_run(+ browser_cleanup_result = await app.BROWSER_MANAGER.cleanup_for_workflow_run(workflow_run.workflow_run_id,all_workflow_task_ids,close_browser_on_completion=close_browser_on_completion,@@ -8631,11 +8631,11 @@ class WorkflowService:child_workflow_run_ids=child_workflow_run_ids,)return WorkflowBrowserCleanupResult(- browser_state=browser_state,+ browser_state=browser_cleanup_result.browser_state,tasks=tasks,all_workflow_task_ids=all_workflow_task_ids,child_workflow_run_ids=child_workflow_run_ids,- close_browser_on_completion=close_browser_on_completion,+ close_browser_on_completion=browser_cleanup_result.recording_finalized,)async def _persist_workflow_browser_session_if_needed(diff --git a/skyvern/library/skyvern_browser_page_ai.py b/skyvern/library/skyvern_browser_page_ai.pyindex a9d39a3fe..1d4068a44 100644--- a/skyvern/library/skyvern_browser_page_ai.py+++ b/skyvern/library/skyvern_browser_page_ai.py@@ -88,6 +88,7 @@ class SdkSkyvernPageAi(SkyvernPageAi):failed_selector: str | None = None, # noqa: ARG002 — Protocol compat, see ai_click docstringblock_label: str | None = None, # noqa: ARG002recoverable_marker_id: int | None = None, # noqa: ARG002 — Protocol compat+ value_is_sensitive: bool = False, # noqa: ARG002 — Protocol compatv3_parent_episode_id: str | None = None, # noqa: ARG002 — Protocol compat; v3 mid-run is server-side only) -> str:"""Input text into an element using AI via API call."""diff --git a/skyvern/services/script_reviewer_v3/agent_loop.py b/skyvern/services/script_reviewer_v3/agent_loop.pyindex e94fb8a15..687179676 100644--- a/skyvern/services/script_reviewer_v3/agent_loop.py+++ b/skyvern/services/script_reviewer_v3/agent_loop.py@@ -41,6 +41,7 @@ from skyvern.forge.sdk.copilot.loop_detection import ()from skyvern.services.script_reviewer_v3.budget import Budget, InvocationHandlefrom skyvern.services.script_reviewer_v3.decision import Decision+from skyvern.services.script_reviewer_v3.redaction import redact_sensitive_valuefrom skyvern.services.script_reviewer_v3.skills import SkillResultfrom skyvern.services.script_reviewer_v3.skills.base import SkillRegistry@@ -226,6 +227,9 @@ async def run_agent_loop(timeline: list[dict[str, Any]] = []terminal_names = registry.terminal_names(agent_kind)tools = registry.tool_schemas(agent_kind)+ sensitive_value = getattr(context, "value", None) if getattr(context, "value_is_sensitive", False) else None+ if not isinstance(sensitive_value, str):+ sensitive_value = None# Anti-oscillation trackers, ported from Copilot's loop_detection module.# ``consecutive_tool_tracker`` catches A-A-A streaks (same skill 3 times@@ -250,7 +254,7 @@ async def run_agent_loop(# system message. So we own the system message ourselves at messages[0].messages: list[dict[str, Any]] = [{"role": "system", "content": system_prompt},- {"role": "user", "content": user_prompt},+ {"role": "user", "content": redact_sensitive_value(user_prompt, sensitive_value)},]timeline.append(@@ -424,7 +428,7 @@ async def run_agent_loop("cycle": budget.cycles_used,"tool_call_id": tc_id,"tool_name": tool_name,- "args_preview": {k: _truncate_for_log(v) for k, v in args.items()},+ "args_preview": {k: _redact_for_timeline(v, sensitive_value) for k, v in args.items()},"status": result.status,"latency_ms": round(skill_latency_ms, 2),}@@ -448,12 +452,14 @@ async def run_agent_loop(# Feed result back to the LLM as a tool message so the next# cycle's LLM call sees it.+ tool_content = result.to_tool_content()+ tool_content = redact_sensitive_value(tool_content, sensitive_value)messages.append({"role": "tool","tool_call_id": tc_id,"name": tool_name,- "content": result.to_tool_content(),+ "content": tool_content,})@@ -579,4 +585,16 @@ def _truncate_for_log(value: Any, max_chars: int = 200) -> Any:return value+def _redact_for_timeline(value: Any, sensitive_value: str | None) -> Any:+ if isinstance(value, str):+ return _truncate_for_log(redact_sensitive_value(value, sensitive_value))+ if isinstance(value, dict):+ return {key: _redact_for_timeline(item, sensitive_value) for key, item in value.items()}+ if isinstance(value, list):+ return [_redact_for_timeline(item, sensitive_value) for item in value]+ if isinstance(value, tuple):+ return tuple(_redact_for_timeline(item, sensitive_value) for item in value)+ return value++__all__ = ["AgentLoopResult", "run_agent_loop"]diff --git a/skyvern/services/script_reviewer_v3/midrun.py b/skyvern/services/script_reviewer_v3/midrun.pyindex b5ae3e026..0589a8c9a 100644--- a/skyvern/services/script_reviewer_v3/midrun.py+++ b/skyvern/services/script_reviewer_v3/midrun.py@@ -43,6 +43,7 @@ from skyvern.services.script_reviewer_v3.prompts import (MIDRUN_SYSTEM_PROMPT,build_midrun_user_prompt,)+from skyvern.services.script_reviewer_v3.redaction import redact_sensitive_content, redact_sensitive_valuefrom skyvern.services.script_reviewer_v3.registry_builder import build_registryfrom skyvern.services.script_reviewer_v3.types import FailureContext, V3MidRunResult@@ -58,6 +59,7 @@ def _summarize_failure_context(fc: FailureContext) -> dict:"failed_selector": fc.failed_selector,"intention": fc.intention,"value": fc.value,+ "value_is_sensitive": fc.value_is_sensitive,"totp_identifier": fc.totp_identifier,"page_url": getattr(fc.page, "url", None) if fc.page is not None else None,}@@ -74,12 +76,14 @@ async def _persist_midrun_terminal(Class A: mark_episode_reviewed atomically with the new script revision id.Class B: update with reviewer_output but leave reviewed=False."""+ sensitive_value = fc.value if fc.value_is_sensitive else None+ reviewer_output = redact_sensitive_content(decision.investigation_summary or decision.reason, sensitive_value)try:if decision.is_midrun_class_a():await app.DATABASE.scripts.mark_episode_reviewed(episode_id=fc.episode_id,organization_id=organization_id,- reviewer_output=decision.investigation_summary or decision.reason,+ reviewer_output=reviewer_output,new_script_revision_id=decision.new_script_revision_id,reviewer_version="v3",)@@ -87,7 +91,7 @@ async def _persist_midrun_terminal(await app.DATABASE.scripts.update_fallback_episode(episode_id=fc.episode_id,organization_id=organization_id,- reviewer_output=f"v3_midrun_{decision.type}: {decision.reason}",+ reviewer_output=f"v3_midrun_{decision.type}: {reviewer_output}",reviewer_version="v3",)except Exception:@@ -166,7 +170,9 @@ async def v3_review_in_flight(episode_id=fc.episode_id,workflow_run_id=getattr(fc.context, "workflow_run_id", None),action_type=fc.action_type,- failed_selector=fc.failed_selector,+ failed_selector=redact_sensitive_value(+ fc.failed_selector or "", fc.value if fc.value_is_sensitive else None+ ),budget_max_cycles=budget.max_cycles,budget_max_cost_usd=budget.max_cost_usd,)@@ -203,8 +209,10 @@ async def v3_review_in_flight(episode_id=fc.episode_id,workflow_run_id=getattr(fc.context, "workflow_run_id", None),decision_type=final_decision.type,- decision_reason=final_decision.reason,- investigation_summary=(final_decision.investigation_summary or "")[:300],+ decision_reason=redact_sensitive_value(final_decision.reason, fc.value if fc.value_is_sensitive else None),+ investigation_summary=redact_sensitive_value(+ final_decision.investigation_summary or "", fc.value if fc.value_is_sensitive else None+ )[:300],new_script_revision_id=final_decision.new_script_revision_id,class_a=final_decision.is_midrun_class_a(),class_b=final_decision.is_midrun_class_b(),diff --git a/skyvern/services/script_reviewer_v3/prompts.py b/skyvern/services/script_reviewer_v3/prompts.pyindex ab6cd8eba..5fbbbc19a 100644--- a/skyvern/services/script_reviewer_v3/prompts.py+++ b/skyvern/services/script_reviewer_v3/prompts.py@@ -13,6 +13,8 @@ a short instruction-of-the-moment ("tell me what to do next").from __future__ import annotations+from skyvern.services.script_reviewer_v3.redaction import REDACTED_SECRET_PLACEHOLDER, redact_sensitive_value+MIDRUN_SYSTEM_PROMPT = """\You are the Skyvern v3 mid-run script reviewer. A cached script just failed \to find or use an element on a live page. You have a live Playwright browser \@@ -23,6 +25,10 @@ workflow continue, then call declare_success. If you cannot reliably fix it, \call give_up — the workflow will fall through to the agent fallback and the \post-run reviewer will analyze this episode later.+The failed fill value is redacted from your context when it is sensitive. \+live_try_fill refuses resolved credentials; for ordinary fills, pass a \+corrected value only when the failure was caused by its format.+Operating principles:1. **Read before mutate.** Always start with live_get_url + live_get_dom (or \@@ -265,8 +271,11 @@ def build_midrun_user_prompt(*, episode_id: str, fc_summary: dict) -> str:f"failed_selector: {fc_summary.get('failed_selector')!r}",f"intention: {fc_summary.get('intention')!r}",]- if fc_summary.get("value") is not None:- lines.append(f"value: {fc_summary['value']!r}")+ value = fc_summary.get("value")+ value_is_sensitive = bool(fc_summary.get("value_is_sensitive"))+ if value is not None:+ display_value = REDACTED_SECRET_PLACEHOLDER if value_is_sensitive else value+ lines.append(f"value: {display_value!r}")if fc_summary.get("totp_identifier"):lines.append(f"totp_identifier: {fc_summary['totp_identifier']!r}")if fc_summary.get("page_url"):@@ -276,7 +285,8 @@ def build_midrun_user_prompt(*, episode_id: str, fc_summary: dict) -> str:"Plan your investigation. The live browser is at the moment-of-failure state.","Start with live_get_url and live_get_dom. End with declare_success or give_up.",]- return "\n".join(lines)+ prompt = "\n".join(lines)+ return redact_sensitive_value(prompt, value if value_is_sensitive and isinstance(value, str) else None)def build_postrun_user_prompt(*, prc_summary: dict) -> str:diff --git a/skyvern/services/script_reviewer_v3/redaction.py b/skyvern/services/script_reviewer_v3/redaction.pynew file mode 100644index 000000000..4510d39bc--- /dev/null+++ b/skyvern/services/script_reviewer_v3/redaction.py@@ -0,0 +1,35 @@+import html+import json+from urllib.parse import quote, quote_plus++from skyvern.forge.sdk.copilot.secret_scrub import MIN_PERSISTED_REDACTION_LENGTH, REDACTED_SECRET_PLACEHOLDER+++def redact_sensitive_value(text: str, value: str | None) -> str:+ if not value:+ return text++ variants = {+ value,+ html.escape(value, quote=False),+ html.escape(value, quote=True),+ quote(value, safe=""),+ quote_plus(value, safe=""),+ }+ variants.update(json.dumps(item, ensure_ascii=False)[1:-1] for item in tuple(variants))+ for variant in sorted(variants, key=len, reverse=True):+ text = text.replace(variant, REDACTED_SECRET_PLACEHOLDER)+ return text+++def redact_sensitive_content(text: str, value: str | None) -> str:+ """Floored variant, for text that is written to storage.++ Only persistence writes take the floor, because substring-replacing a short value corrupts what+ is stored. Disclosure channels — prompt, tool results, DOM, logs — must use+ ``redact_sensitive_value``: the values guarded here are short (a TOTP digit, a card CVV), and a+ floor on that axis leaks every one of them.+ """+ if not value or len(value) < MIN_PERSISTED_REDACTION_LENGTH:+ return text+ return redact_sensitive_value(text, value)diff --git a/skyvern/services/script_reviewer_v3/skills/interact.py b/skyvern/services/script_reviewer_v3/skills/interact.pyindex 836cd3c85..dc63829bb 100644--- a/skyvern/services/script_reviewer_v3/skills/interact.py+++ b/skyvern/services/script_reviewer_v3/skills/interact.py@@ -26,6 +26,7 @@ from typing import Anyimport structlog+from skyvern.services.script_reviewer_v3.redaction import REDACTED_SECRET_PLACEHOLDER, redact_sensitive_valuefrom skyvern.services.script_reviewer_v3.skills.base import Skill, SkillError, SkillResultLOG = structlog.get_logger()@@ -101,13 +102,20 @@ async def _handler_live_get_dom(args: dict[str, Any], context: Any) -> SkillResureturn SkillResult.not_available(f"selector {selector!r} matched no element")if not isinstance(html, str):html = str(html)+ html_chars = len(html)+ sensitive_value = getattr(context, "value", None) if getattr(context, "value_is_sensitive", False) else None+ html = redact_sensitive_value(html, sensitive_value)truncated = len(html) > max_chars+ preview = html[:max_chars]+ placeholder_start = html.rfind("[", 0, max_chars)+ if html.startswith(REDACTED_SECRET_PLACEHOLDER, placeholder_start):+ preview = html[: max_chars - len(REDACTED_SECRET_PLACEHOLDER)] + REDACTED_SECRET_PLACEHOLDERreturn SkillResult.ok(data={"selector": selector,"url": await _safe_url(page),- "html_chars": len(html),- "html": (html[:max_chars] + f"\n<!-- truncated {len(html) - max_chars} chars -->") if truncated else html,+ "html_chars": html_chars,+ "html": (preview + f"\n<!-- truncated {len(html) - len(preview)} chars -->") if truncated else html,"truncated": truncated,})@@ -231,14 +239,18 @@ async def _handler_live_try_click(args: dict[str, Any], context: Any) -> SkillReasync def _handler_live_try_fill(args: dict[str, Any], context: Any) -> SkillResult:- """Attempt page.fill(selector, value). Successful fill is the commit."""+ """Fill an ordinary value. Successful fill is the commit."""page = _get_page(context)selector = args.get("selector")- value = args.get("value")if not selector or not isinstance(selector, str):raise SkillError("selector is required")+ if getattr(context, "value_is_sensitive", False):+ return SkillResult.not_available("live_try_fill is unavailable for sensitive values")+ value = args.get("value")+ if value is None:+ value = getattr(context, "value", None)if value is None or not isinstance(value, str):- raise SkillError("value is required (string)")+ raise SkillError("FailureContext.value is unavailable")pre_url = await _safe_url(page)pre_hash = await _dom_hash(page)@@ -377,16 +389,17 @@ def all_interact_skills() -> list[Skill]:schema={"name": "live_try_fill","description": (- "Fill an input by CSS selector. A successful fill IS the commit. Returns "- "pre/post URL and DOM hashes."+ "Fill an input by CSS selector. Resolved credentials are refused. For ordinary "+ "fills, omit value to reuse the failed value or supply a corrected format. "+ "A successful fill IS the commit. Returns pre/post URL and DOM hashes."),"input_schema": {"type": "object","properties": {"selector": {"type": "string"},- "value": {"type": "string"},+ "value": {"type": "string", "description": "Optional corrected ordinary value."},},- "required": ["selector", "value"],+ "required": ["selector"],},},),diff --git a/skyvern/services/script_reviewer_v3/types.py b/skyvern/services/script_reviewer_v3/types.pyindex 8e48b15e7..60aba2397 100644--- a/skyvern/services/script_reviewer_v3/types.py+++ b/skyvern/services/script_reviewer_v3/types.py@@ -40,12 +40,13 @@ class FailureContext:failed_selector: str | Noneintention: straction_type: InterceptedActionType- value: str | None # for fill / type / fill_autocomplete+ value: str | None = dataclasses.field(repr=False) # for fill / type / fill_autocompletetotp_identifier: str | None # for fill with TOTPtotp_url: str | Nonepage: PlaywrightPagecontext: SkyvernContextepisode_id: str+ value_is_sensitive: bool = False@dataclasses.dataclassdiff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 04cd34ab9..03e90183a 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -148,10 +148,12 @@ from skyvern.webeye.browser_engine import UNSET_SELECTION, BrowserEngineSelectiofrom skyvern.webeye.browser_factory import initialize_download_dir, resolve_artifact_pathfrom skyvern.webeye.browser_state import BrowserStatefrom skyvern.webeye.cdp_download_interceptor import (+ DOWNLOAD_DESTINATION_ERRORS,DOWNLOAD_MIME_TYPES,MAX_FILE_SIZE_BYTES,download_filename_from_suffix,extract_filename,+ fetch_download_through_request_context,is_download_response,normalize_download_filename,settle_browser_downloads_for_context,@@ -934,7 +936,7 @@ async def _save_adopted_session_download(return download_targettry:- response = await page.context.request.get(download.url)+ response = await fetch_download_through_request_context(page.context.request, download.url)if response.status != 200:LOG.error("Adopted-session download url re-fetch returned non-200 status",@@ -952,6 +954,14 @@ async def _save_adopted_session_download(return Nonedownload_target.write_bytes(body)return download_target+ except DOWNLOAD_DESTINATION_ERRORS as e:+ LOG.error(+ "Adopted-session download destination refused",+ download_dir=str(download_dir),+ workflow_run_id=workflow_run_id,+ reason=str(e),+ )+ return Noneexcept Exception:LOG.error("Adopted-session download url re-fetch failed",diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.pyindex 74032957c..ecf6536f1 100644--- a/skyvern/webeye/browser_factory.py+++ b/skyvern/webeye/browser_factory.py@@ -53,6 +53,7 @@ from skyvern.webeye.cdp_connection import connect_over_cdp_with_diagnostics as _from skyvern.webeye.cdp_connection import (merge_cdp_connect_headers,parse_default_cdp_connect_headers,+ redact_cdp_url,)from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptor, bind_download_interceptor_to_contextfrom skyvern.webeye.dialog_handler import set_dialog_handler@@ -997,7 +998,7 @@ async def _connect_to_cdp_browser(# RealBrowserManager attaches the CDP frame publisher.browser_artifacts.needs_cdp_frame_publisher = True- LOG.info("Connecting browser CDP connection", remote_browser_url=remote_browser_url)+ LOG.info("Connecting browser CDP connection", remote_browser_url=redact_cdp_url(remote_browser_url))cdp_headers = merge_cdp_connect_headers(default_headers=parse_default_cdp_connect_headers(settings.BROWSER_REMOTE_DEBUGGING_CONNECT_HEADERS),per_row_headers=cdp_connect_headers,@@ -1060,7 +1061,7 @@ async def _connect_to_cdp_browser(LOG.info("Launched browser CDP connection",- remote_browser_url=remote_browser_url,+ remote_browser_url=redact_cdp_url(remote_browser_url),)return browser_context, browser_artifacts, Nonediff --git a/skyvern/webeye/browser_manager.py b/skyvern/webeye/browser_manager.pyindex 6950714b8..4df159934 100644--- a/skyvern/webeye/browser_manager.py+++ b/skyvern/webeye/browser_manager.py@@ -1,5 +1,6 @@from __future__ import annotations+from dataclasses import dataclassfrom typing import Protocolimport structlog@@ -12,6 +13,12 @@ from skyvern.webeye.browser_state import BrowserStateLOG = structlog.get_logger()+@dataclass(frozen=True)+class BrowserCleanupResult:+ browser_state: BrowserState | None+ recording_finalized: bool++class BrowserManager(Protocol):pages: dict[str, BrowserState]@@ -42,7 +49,7 @@ class BrowserManager(Protocol):browser_session_id: str | None = None,organization_id: str | None = None,child_workflow_run_ids: list[str] | None = None,- ) -> BrowserState | None: ...+ ) -> BrowserCleanupResult: ...async def get_or_create_for_script(self,diff --git a/skyvern/webeye/browser_state.py b/skyvern/webeye/browser_state.pyindex 9c30404c3..3984c9ba6 100644--- a/skyvern/webeye/browser_state.py+++ b/skyvern/webeye/browser_state.py@@ -98,7 +98,7 @@ class BrowserState(Protocol):async def reload_page(self, degradation: bool = False) -> None: ...- async def close(self, close_browser_on_completion: bool = True, release_driver: bool | None = None) -> None: ...+ async def close(self, close_browser_on_completion: bool = True, release_driver: bool | None = None) -> bool: ...async def take_fullpage_screenshot(self, file_path: str | None = None) -> bytes: ...diff --git a/skyvern/webeye/cdp_connection.py b/skyvern/webeye/cdp_connection.pyindex 88f678a30..a54d1262a 100644--- a/skyvern/webeye/cdp_connection.py+++ b/skyvern/webeye/cdp_connection.py@@ -6,13 +6,14 @@ import reimport socketfrom collections.abc import Iterablefrom dataclasses import dataclass-from urllib.parse import urlparse, urlunparse+from urllib.parse import parse_qsl, urlparse, urlsplit, urlunparse, urlunsplitimport structlogfrom playwright.async_api import Browser, Playwrightfrom skyvern.config import settingsfrom skyvern.exceptions import CdpConnectionConfigurationError+from skyvern.webeye.cdp_credentials import LIVE_VIEW_PATH_SEGMENT, marked_credential_segmentLOG = structlog.get_logger()DEFAULT_CDP_CONNECT_TIMEOUT_MS = 30_000@@ -90,6 +91,60 @@ def strip_browser_address_discriminator(url: str) -> str:return url+REDACTED = "[REDACTED]"+++def redact_cdp_url(url: str | None) -> str:+ """A CDP or live-view address with every credential position masked.++ The single place that decides what of an address may be written down. Five positions carry a+ secret, and each is one an edge reads back out:++ - the query (a session token, a vendor api key) and userinfo;+ - the segment after a path credential marker, ``/<marker>/<secret>/<session_id>``, which is+ how a header-less client authenticates to the router;+ - the routing token in ``/{session_id}/{token}/devtools/...`` (legacy CDP);+ - the token trailing ``/vnc/{session_id}`` (legacy live view).++ The markers and the live-view prefix come from ``cdp_credentials``, which owns them; the+ router's ``_parse_request`` restates them (it may not import this package) and a contract+ test pins the two equal, so this cannot fall behind what the router will accept. Scheme,+ host, port, parameter names and the session id survive, so a redacted line still identifies+ the session and the endpoint it was dialing.+ """+ if not url:+ return ""+ try:+ split = urlsplit(url)+ except ValueError:+ return REDACTED++ netloc = split.netloc+ if "@" in netloc:+ netloc = f"{REDACTED}@{netloc.rsplit('@', 1)[1]}"++ query = "&".join(f"{name}={REDACTED}" for name, _ in parse_qsl(split.query, keep_blank_values=True))++ path = split.path+ segments = [segment for segment in path.split("/") if segment]+ credential_indices: set[int] = set()+ marked = marked_credential_segment(segments)+ if marked is not None:+ credential_indices.add(marked)+ if len(segments) >= 4 and segments[2] == "devtools":+ credential_indices.add(1)+ if segments and segments[0].lower() == LIVE_VIEW_PATH_SEGMENT:+ # /vnc/{session_id} carries its token in the query; anything past the session id is the+ # legacy edge's trailing token.+ credential_indices.update(range(2, len(segments)))+ if credential_indices:+ path = "/" + "/".join(+ REDACTED if index in credential_indices else segment for index, segment in enumerate(segments)+ )++ return urlunsplit((split.scheme, netloc, path, query, split.fragment))++_LOCAL_CONTAINER_CDP_PORT = 9222@@ -228,8 +283,8 @@ def build_cdp_configuration_error(return Noneguidance = (- f"Skyvern reached the configured CDP address ({remote_browser_url}), but "- f"{discovery_url} returned HTTP {status_code}. Skyvern cdp-connect requires "+ f"Skyvern reached the configured CDP address ({redact_cdp_url(remote_browser_url)}), but "+ f"{redact_cdp_url(discovery_url)} returned HTTP {status_code}. Skyvern cdp-connect requires ""Chrome's classic DevTools Protocol endpoint, where /json/version returns JSON ""with webSocketDebuggerUrl. If you enabled chrome://inspect/#remote-debugging, ""set BROWSER_REMOTE_DEBUGGING_URL to the direct full "@@ -272,8 +327,8 @@ async def connect_over_cdp_with_diagnostics(LOG.warning(message,reason=candidate.label,- remote_browser_url=remote_browser_url,- fallback_url=candidate.url,+ remote_browser_url=redact_cdp_url(remote_browser_url),+ fallback_url=redact_cdp_url(candidate.url),)try:return await playwright.chromium.connect_over_cdp(diff --git a/skyvern/webeye/cdp_credentials.py b/skyvern/webeye/cdp_credentials.pynew file mode 100644index 000000000..ae5a6cdea--- /dev/null+++ b/skyvern/webeye/cdp_credentials.py@@ -0,0 +1,45 @@+"""Where a credential can hide inside a CDP or live-view address.++The owning definition of a grammar two components must agree on: the router's ``_parse_request``+(cloud/cdp_proxy/adapters/websocket_server.py) pulls a client's credential *out* of an incoming+address, and ``redact_cdp_url`` (skyvern/webeye/cdp_connection.py) masks every position that+parser would read. A position one accepts and the other misses writes a live session token to+the logs.++The proxy adapter cannot import this module — `.importlinter`'s proxy-runner-isolation contract+forbids that package from importing `skyvern` at all, and `skyvern` may not import `cloud` — so+it restates the two tuples locally. That copy is not maintained by hand: the contract tests in+tests/cloud/cdp_proxy/test_websocket_server.py pin it equal to this one *and* assert the+behavior end to end, so a change here that is not mirrored there fails CI rather than quietly+unmasking a token.+"""++from __future__ import annotations++from collections.abc import Sequence++# Query parameter names a client may use to carry its credential when it cannot set a WS+# header (e.g. puppeteer).+CREDENTIAL_QUERY_PARAMS = ("x-api-key", "api-key", "api_key", "apikey", "token", "access_token")++# Path markers: the segment immediately after any of these is the credential, letting a+# header-less client dial /<marker>/<secret>/<session_id>.+CREDENTIAL_PATH_MARKERS = ("apikey", "api-key", "api_key", "key", "token")++# Live view rides the router under this path segment: /vnc/<session_id> with the token in the+# query, or — at the legacy nginx edge — /vnc/<session_id>/<token>.+LIVE_VIEW_PATH_SEGMENT = "vnc"+LIVE_VIEW_PATH_PREFIX = f"/{LIVE_VIEW_PATH_SEGMENT}/"+++def marked_credential_segment(segments: Sequence[str]) -> int | None:+ """Index of the credential in a path split into non-empty segments, or None.++ First marker wins, matching the parser: a later marker's segment is never read as the+ credential, so a redactor honoring this answer masks exactly what the parser would have+ consumed — no more, and no less.+ """+ for index in range(len(segments) - 1):+ if segments[index].lower() in CREDENTIAL_PATH_MARKERS:+ return index + 1+ return Nonediff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.pyindex 71b925bfc..c2e2f2f88 100644--- a/skyvern/webeye/cdp_download_interceptor.py+++ b/skyvern/webeye/cdp_download_interceptor.py@@ -27,6 +27,7 @@ import osimport reimport sslimport time+import urllib.errorimport urllib.requestimport uuidfrom collections.abc import AsyncIterator, Coroutine@@ -40,6 +41,14 @@ import structlogfrom playwright.async_api import Browser, BrowserContext, CDPSession, Pagefrom skyvern.constants import BROWSER_DOWNLOADING_SUFFIX, BROWSER_INTERCEPTOR_DISABLE_TIMEOUT+from skyvern.exceptions import HttpException, SkyvernHTTPException+from skyvern.forge.sdk.core.aiohttp_helper import strip_cross_origin_redirect_credentials+from skyvern.utils.url_validators import (+ MAX_SAFE_REDIRECTS,+ SAFE_REDIRECT_STATUS_CODES,+ validate_fetch_url,+ validate_redirect_url,+)from skyvern.webeye.utils.page import SkyvernFrameLOG = structlog.get_logger()@@ -357,6 +366,57 @@ def _has_control_chars(text: str) -> bool:return any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text)+# A refused destination and an exhausted hop budget both mean "do not fetch this"; callers must+# treat them as a decision, not as a transport failure worth retrying on another client.+DOWNLOAD_DESTINATION_ERRORS = (SkyvernHTTPException, HttpException)+++def _header_value(headers: dict[str, str], name: str) -> str | None:+ lowered = name.lower()+ return next((value for key, value in headers.items() if key.lower() == lowered), None)+++class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:+ return None+++def _urlopen_single_hop(+ request: urllib.request.Request, ssl_context: ssl.SSLContext+) -> tuple[int, dict[str, str], bytes]:+ """Perform one HTTP hop without following redirects, so the next hop can be checked first."""+ opener = urllib.request.build_opener(_NoRedirectHandler, urllib.request.HTTPSHandler(context=ssl_context))+ try:+ with opener.open(request) as response:+ return response.status, dict(response.headers), response.read()+ except urllib.error.HTTPError as error:+ # Suppressing redirects turns them into errors here, so a redirect is returned for the+ # caller to check. Every other error status stays an error: its body is not the file.+ if error.code not in SAFE_REDIRECT_STATUS_CODES:+ raise+ with error:+ return error.code, dict(error.headers), error.read()+++async def fetch_download_through_request_context(request_context: Any, url: str) -> Any:+ """Return the final response for a page-supplied download URL.++ The destination is checked before the initial request and again before every redirect hop, so+ no hop carries cookies or headers to a host that has not been cleared. Raises on a refused+ destination, a redirect without a target, or an exhausted hop budget.+ """+ current_url = await asyncio.to_thread(validate_fetch_url, url)+ for _ in range(MAX_SAFE_REDIRECTS + 1):+ response = await request_context.get(current_url, max_redirects=0)+ if response.status not in SAFE_REDIRECT_STATUS_CODES:+ return response+ location = _header_value(dict(response.headers), "location")+ if not location:+ raise HttpException(response.status, current_url, "Redirected download provided no target")+ current_url = await asyncio.to_thread(validate_redirect_url, current_url, location)+ raise HttpException(400, current_url, "Too many redirects while fetching a download")++def _payload_is_html_login_masquerade(data: bytes, content_type: str, filename: str) -> bool:"""True when a download's bytes are an HTML document but the download does not claim to be HTML.@@ -937,6 +997,32 @@ class CDPDownloadInterceptor:parts.append(f"{name}={value}")return "; ".join(parts)+ async def _download_url_via_urllib(self, url: str) -> tuple[bytes, str]:+ """Fetch a download over urllib, checking the destination before every hop.++ The session cookie rides a normal header and is dropped when a hop crosses origin, so it+ reaches the original host across a same-host redirect but is never replayed to another one.+ """+ current_url = await asyncio.to_thread(validate_fetch_url, url)+ headers = {"User-Agent": "Mozilla/5.0"}+ cookie_header = await self._cookie_header_for_url(current_url)+ if cookie_header:+ headers["Cookie"] = cookie_header+ ssl_ctx = ssl.create_default_context()++ for _ in range(MAX_SAFE_REDIRECTS + 1):+ request = urllib.request.Request(current_url, headers=dict(headers))+ status, response_headers, body = await asyncio.to_thread(_urlopen_single_hop, request, ssl_ctx)+ if status not in SAFE_REDIRECT_STATUS_CODES:+ return body, _header_value(response_headers, "content-type") or ""+ location = _header_value(response_headers, "location")+ if not location:+ raise HttpException(status, current_url, "Redirected download provided no target")+ next_url = await asyncio.to_thread(validate_redirect_url, current_url, location)+ headers, _ = strip_cross_origin_redirect_credentials(headers, None, current_url, next_url)+ current_url = next_url+ raise HttpException(400, current_url, "Too many redirects while fetching a download")+async def _download_url_directly(self, url: str, suggested_filename: str) -> None:"""Download a URL directly via HTTP and save to the output directory.@@ -956,7 +1042,7 @@ class CDPDownloadInterceptor:# We use the BrowserContext (not a Page) so this survives individual page closes.if self._browser_context:try:- response = await self._browser_context.request.get(url)+ response = await fetch_download_through_request_context(self._browser_context.request, url)if response.ok:data = await response.body()content_type = response.headers.get("content-type", "")@@ -967,6 +1053,11 @@ class CDPDownloadInterceptor:url=url,status=response.status,)+ except DOWNLOAD_DESTINATION_ERRORS as e:+ # A refused destination is a decision about this URL, so the urllib transport must+ # not be tried as a second chance at the same host.+ LOG.error("Download destination refused", url=url, reason=str(e))+ returnexcept Exception as e:LOG.debug("Playwright APIRequestContext download failed, trying urllib", url=url, error=str(e))@@ -975,25 +1066,11 @@ class CDPDownloadInterceptor:# endpoint answers an unauthenticated request with its login page (saved as a corrupt file).if data is None:try:- req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})- cookie_header = await self._cookie_header_for_url(url)- if cookie_header:- # Unredirected header: urllib's HTTPRedirectHandler copies req.headers but not- # unredirected_hdrs across redirects, so the cookie reaches only the original host- # and is never replayed to another domain (cross-host session-cookie leak).- # Trade-off: a same-host redirect also drops the cookie; if that final hop is- # session-gated it returns a login page, which the HTML-masquerade guard below- # rejects instead of saving a corrupt file. Per-hop cookie replay is intentionally- # not implemented — cross-host safety outweighs that narrow convenience.- req.add_unredirected_header("Cookie", cookie_header)- ssl_ctx = ssl.create_default_context()-- def _fetch() -> tuple[bytes, str]:- with urllib.request.urlopen(req, context=ssl_ctx) as resp:- return resp.read(), resp.headers.get("content-type", "")-- data, content_type = await asyncio.to_thread(_fetch)+ data, content_type = await self._download_url_via_urllib(url)method = "urllib"+ except DOWNLOAD_DESTINATION_ERRORS as e:+ LOG.error("Download destination refused", url=url, reason=str(e))+ returnexcept Exception as e:LOG.error("Direct HTTP download failed", url=url, error=str(e), exc_info=True)returndiff --git a/skyvern/webeye/cdp_retry.py b/skyvern/webeye/cdp_retry.pyindex 4e19fa26f..4c8d28593 100644--- a/skyvern/webeye/cdp_retry.py+++ b/skyvern/webeye/cdp_retry.py@@ -15,7 +15,7 @@ from skyvern.webeye.browser_errors import (BrowserTargetClosedError,BrowserTimeoutError,)-from skyvern.webeye.cdp_connection import strip_browser_address_discriminator+from skyvern.webeye.cdp_connection import redact_cdp_url, strip_browser_address_discriminatorif TYPE_CHECKING:from skyvern.webeye.browser_engine import BrowserEngineSelection@@ -106,7 +106,7 @@ async def connect_over_cdp_with_retry(selection: BrowserEngineSelection | None = None,) -> Browser:browser_address = strip_browser_address_discriminator(browser_address)- browser_address_for_logs = log_browser_address or browser_address+ browser_address_for_logs = log_browser_address or redact_cdp_url(browser_address)max_attempts, backoff_schedule = _resolve_retry_budget()for attempt in range(1, max_attempts + 1):try:diff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.pyindex 79d1e95a6..55583ad61 100644--- a/skyvern/webeye/default_persistent_sessions_manager.py+++ b/skyvern/webeye/default_persistent_sessions_manager.py@@ -275,7 +275,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):)if browser_session is None or is_final_status(browser_session.status):return None- if browser_session.browser_address:+ if browser_session.is_browser_ready and browser_session.browser_address:return browser_session.browser_addressif timeout <= 0:return Nonediff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.pyindex 6fd1fedd1..bdbc17280 100644--- a/skyvern/webeye/real_browser_manager.py+++ b/skyvern/webeye/real_browser_manager.py@@ -29,7 +29,7 @@ from skyvern.webeye.browser_engine import (resolve_browser_engine,)from skyvern.webeye.browser_factory import BrowserContextFactory, rebind_download_dir-from skyvern.webeye.browser_manager import BrowserManager+from skyvern.webeye.browser_manager import BrowserCleanupResult, BrowserManagerfrom skyvern.webeye.browser_state import BrowserStatefrom skyvern.webeye.cdp_frame_publisher import (CDPFramePublisher,@@ -914,9 +914,12 @@ class RealBrowserManager(BrowserManager):browser_session_id: str | None = None,organization_id: str | None = None,child_workflow_run_ids: list[str] | None = None,- ) -> BrowserState | None:+ ) -> BrowserCleanupResult:LOG.info("Cleaning up for workflow run", sampling=True)browser_state_to_close = self.pages.get(workflow_run_id)+ recording_finalized = False+ finalization_attempted = False+ cleanup_page_ids = {workflow_run_id, *task_ids, *(child_workflow_run_ids or [])}# Drop the run's pinned engine — the run is ending, so no further browser resource will be# created for it. Covers the run, its inherited children, and its tasks.@@ -944,7 +947,10 @@ class RealBrowserManager(BrowserManager):# If another workflow run still references this browser state (e.g. a# parent whose in-memory browser was shared via use_parent_browser_session),# skip closing the browser so the parent can continue using it.- shared = any(bs is browser_state_to_close for bs in self.pages.values())+ shared = any(+ page_id != workflow_run_id and browser_state is browser_state_to_close+ for page_id, browser_state in self.pages.items()+ )effective_close = close_browser_on_completion and not sharedif shared:LOG.info(@@ -972,11 +978,24 @@ class RealBrowserManager(BrowserManager):browser_state_to_close.browser_context,browser_state_to_close.browser_artifacts.browser_session_dir,)+ shared_after_cleanup = any(+ page_id not in cleanup_page_ids and browser_state is browser_state_to_close+ for page_id, browser_state in self.pages.items()+ )+ deferred_close = close_browser_on_completion and not shared_after_cleanup+ streams_active = set_deferred_close_params(+ workflow_run_id,+ deferred_close,+ release_driver=False if (shared_after_cleanup or browser_session_id) else None,+ )+ if not streams_active:+ effective_close = deferred_close+ shared = shared_after_cleanup+ if streams_active:LOG.info("Deferring browser close — active CDP streams",workflow_run_id=workflow_run_id,)- set_deferred_close_params(workflow_run_id, close_browser_on_completion)# Keep the publisher running while streams are attached. The# eventual ``close(True)`` fires the on-close callback that# stops it; ``close(False)`` is covered by the publisher's@@ -985,10 +1004,12 @@ class RealBrowserManager(BrowserManager):# Detach the publisher's CDP session before the Playwright context# closes; otherwise the stale session can race the teardown.await self._stop_frame_publisher(workflow_run_id=workflow_run_id)- await browser_state_to_close.close(+ close_succeeded = await browser_state_to_close.close(close_browser_on_completion=effective_close,release_driver=False if (shared or browser_session_id) else None,)+ finalization_attempted = effective_close+ recording_finalized = effective_close and bool(close_succeeded)if not streams_active:self.pages.pop(workflow_run_id, None)@@ -996,6 +1017,8 @@ class RealBrowserManager(BrowserManager):task_browser_state = self.pages.pop(task_id, None)if task_browser_state is None or streams_active:continue+ if task_browser_state is browser_state_to_close and finalization_attempted:+ continue# Same shared-state check for task-level entriesshared = any(bs is task_browser_state for bs in self.pages.values())effective_close = close_browser_on_completion and not shared@@ -1007,10 +1030,14 @@ class RealBrowserManager(BrowserManager):workflow_run_id=workflow_run_id,)try:- await task_browser_state.close(+ if task_browser_state is browser_state_to_close:+ finalization_attempted = effective_close+ close_succeeded = await task_browser_state.close(close_browser_on_completion=effective_close,release_driver=False if (shared or browser_session_id) else None,)+ if task_browser_state is browser_state_to_close and effective_close:+ recording_finalized = bool(close_succeeded)except Exception:LOG.info("Failed to close the browser state from the task block, might because it's already closed.",@@ -1031,7 +1058,10 @@ class RealBrowserManager(BrowserManager):"Organization ID not specified, cannot release browser session", workflow_run_id=workflow_run_id)- return browser_state_to_close+ return BrowserCleanupResult(+ browser_state=browser_state_to_close,+ recording_finalized=recording_finalized,+ )async def get_or_create_for_script(self,diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.pyindex e76054549..bf7ce380f 100644--- a/skyvern/webeye/real_browser_state.py+++ b/skyvern/webeye/real_browser_state.py@@ -640,7 +640,7 @@ class RealBrowserState(BrowserState):allow_transient_ui_suppression=allow_transient_ui_suppression,)- async def close(self, close_browser_on_completion: bool = True, release_driver: bool | None = None) -> None:+ async def close(self, close_browser_on_completion: bool = True, release_driver: bool | None = None) -> bool:# ``release_driver`` decouples the local Playwright driver's lifetime# from the remote browser's: callers that retain this state for reuse# (persistent sessions, parent/child sharing) must pass False; None@@ -657,6 +657,7 @@ class RealBrowserState(BrowserState):# even when interceptor disable, cookie persistence, or context close hangs or fails.# Worst-case wall time is the sum of the per-phase budgets:# BROWSER_INTERCEPTOR_DISABLE_TIMEOUT + 3 * BROWSER_CLOSE_TIMEOUT.+ recording_finalized = Falseif close_browser_on_completion:if self.browser_context is not None:await self._run_bounded_detachable(@@ -664,7 +665,7 @@ class RealBrowserState(BrowserState):BROWSER_INTERCEPTOR_DISABLE_TIMEOUT,"download interceptor disable",)- await self._run_bounded_detachable(+ recording_finalized = await self._run_bounded_detachable(self._teardown_context(),BROWSER_CLOSE_TIMEOUT,"browser context teardown",@@ -672,8 +673,9 @@ class RealBrowserState(BrowserState):await self._run_browser_cleanup_bounded()await self._stop_driver_bounded(release_driver)+ return recording_finalized- async def _run_bounded_detachable(self, coro: Awaitable[None], timeout: float, description: str) -> None:+ async def _run_bounded_detachable(self, coro: Awaitable[None], timeout: float, description: str) -> bool:# Bound a teardown phase WITHOUT relying on cancellation: a stuck download drain or a real# Playwright ``context.close`` blocked by an unresolved paused request can ignore the cancel a# plain ``asyncio.timeout`` delivers. We race the phase against ``timeout`` and, if it does not@@ -695,12 +697,14 @@ class RealBrowserState(BrowserState):)task.cancel()self._own_detached_task(task, description)- return+ return Falseif task.cancelled():- return+ return Falseerror = task.exception()if error is not None:LOG.warning("Teardown phase failed", phase=description, error_type=type(error).__name__)+ return False+ return Truedef _own_detached_task(self, task: asyncio.Task[None], description: str) -> None:# A cancellation-resistant phase can outlive close(). We hold a strong reference until it@@ -738,10 +742,7 @@ class RealBrowserState(BrowserState):await persist_session_cookies(self.browser_context, session_dir)except Exception:LOG.warning("Failed to persist session cookies during teardown", exc_info=True)- try:- await self.browser_context.close()- except Exception:- LOG.warning("Failed to close browser context", exc_info=True)+ await self.browser_context.close()LOG.info("Main browser context and all its pages are closed")async def _run_browser_cleanup_bounded(self) -> None:diff --git a/tests/unit/conftest.py b/tests/unit/conftest.pyindex 7878007db..6cf9e5e44 100644--- a/tests/unit/conftest.py+++ b/tests/unit/conftest.py@@ -5,7 +5,9 @@ import itertoolsimport loggingimport shutilimport sys-from collections.abc import AsyncGenerator, Callable+import threading+from collections.abc import AsyncGenerator, Callable, Iterator+from dataclasses import dataclassfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock@@ -257,3 +259,162 @@ def make_input_element_mock(*, element_id: str = "AADC", attrs: dict[str, objectel.get_attr = AsyncMock(side_effect=_get_attr)return el+++@dataclass+class DownloadDestinationHarness:+ """A real HTTP server plus a stubbed resolver, for exercising download destination checks.++ Both host names answer on the same loopback server. ``public_host`` is allow-listed so it+ passes validation; ``internal_host`` is not, and resolves to a loopback address, so the+ validator must refuse it. Redirects are served for real, so a test never has to model how a+ given HTTP client follows them.+ """++ public_base: str+ internal_base: str+ other_base: str+ requested_paths: list[str]+ requested_hosts: list[str]+ cookies_by_path: dict[str, str]++ PUBLIC_BODY = b"%PDF-1.4 attachment payload"+ INTERNAL_BODY = b"INTERNAL-ONLY PAYLOAD"++ def reached_internal(self) -> bool:+ return any(host.startswith("internal-host.test") for host in self.requested_hosts)+++def download_destinations(monkeypatch: pytest.MonkeyPatch) -> Iterator[DownloadDestinationHarness]:+ import socket as socket_module+ from http.server import BaseHTTPRequestHandler, HTTPServer++ from skyvern.config import settings++ public_host, internal_host, other_host = "public-host.test", "internal-host.test", "other-host.test"+ requested_paths: list[str] = []+ requested_hosts: list[str] = []+ cookies_by_path: dict[str, str] = {}+ holder: dict[str, str] = {}++ class _Handler(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ requested_paths.append(self.path)+ requested_hosts.append(self.headers.get("Host", ""))+ cookies_by_path[self.headers.get("Host", "").split(":")[0]] = self.headers.get("Cookie", "")+ if self.path in ("/redirect-to-internal", "/redirect-to-other"):+ target = holder["internal"] if self.path == "/redirect-to-internal" else holder["other"]+ self.send_response(302)+ self.send_header("Location", f"{target}/attachment")+ self.end_headers()+ return+ if self.path == "/notfound":+ body = b'{"error": "not found"}'+ self.send_response(404)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ return+ body = (+ DownloadDestinationHarness.INTERNAL_BODY+ if self.path == "/internal"+ else DownloadDestinationHarness.PUBLIC_BODY+ )+ self.send_response(200)+ self.send_header("Content-Type", "application/pdf")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args: object) -> None:+ pass++ server = HTTPServer(("127.0.0.1", 0), _Handler)+ port = server.server_port+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()++ holder["internal"] = f"http://{internal_host}:{port}"+ holder["other"] = f"http://{other_host}:{port}"++ real_getaddrinfo = socket_module.getaddrinfo+ mapped = {public_host, internal_host, other_host}++ def fake_getaddrinfo(host: str, port_arg: object = None, *args: object, **kwargs: object) -> list:+ if host in mapped:+ return [(socket_module.AF_INET, socket_module.SOCK_STREAM, 6, "", ("127.0.0.1", port_arg or 0))]+ return real_getaddrinfo(host, port_arg, *args, **kwargs)++ monkeypatch.setattr(socket_module, "getaddrinfo", fake_getaddrinfo)+ monkeypatch.setattr(settings, "ALLOWED_HOSTS", [*settings.ALLOWED_HOSTS, public_host, other_host])++ try:+ yield DownloadDestinationHarness(+ public_base=f"http://{public_host}:{port}",+ internal_base=holder["internal"],+ other_base=holder["other"],+ requested_paths=requested_paths,+ requested_hosts=requested_hosts,+ cookies_by_path=cookies_by_path,+ )+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++def fake_api_request_context() -> Callable[[], object]:+ """Build a stand-in for Playwright's ``APIRequestContext``.++ Requests are issued for real over HTTP. Redirect handling mirrors the driver's measured+ behaviour: hops are followed unless the caller passes ``max_redirects=0``, in which case the+ 3xx response is returned with its ``Location`` header intact.+ """+ import asyncio+ import urllib.error+ import urllib.request++ class _NoRedirect(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, *args: object, **kwargs: object) -> None:+ return None++ class _Response:+ def __init__(self, status: int, headers: dict[str, str], body: bytes, url: str) -> None:+ self.status = status+ self.headers = headers+ self.url = url+ self._body = body++ @property+ def ok(self) -> bool:+ return 200 <= self.status < 300++ async def body(self) -> bytes:+ return self._body++ class _FakeAPIRequestContext:+ def __init__(self) -> None:+ self.requested_urls: list[str] = []++ async def get(self, url: str, max_redirects: int | None = None, **kwargs: object) -> _Response:+ self.requested_urls.append(url)++ def _fetch() -> _Response:+ opener = (+ urllib.request.build_opener(_NoRedirect) if max_redirects == 0 else urllib.request.build_opener()+ )+ try:+ with opener.open(urllib.request.Request(url)) as response:+ return _Response(response.status, dict(response.headers), response.read(), response.url)+ except urllib.error.HTTPError as error:+ return _Response(error.code, dict(error.headers), error.read(), url)++ return await asyncio.to_thread(_fetch)++ def _build() -> object:+ return _FakeAPIRequestContext()++ return _builddiff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.pyindex c7a095fd6..a828fe5b3 100644--- a/tests/unit/force_stub_app.py+++ b/tests/unit/force_stub_app.py@@ -39,6 +39,7 @@ def create_forge_stub_app() -> ForgeApp:fake_app_module.AGENT_FUNCTION.resolve_copilot_dispatch_trigger_type = MagicMock(return_value=None)fake_app_module.AGENT_FUNCTION.allow_copilot_inline_code_execution = MagicMock(return_value=False)fake_app_module.AGENT_FUNCTION.resolve_mcp_oauth_org_lookups = MagicMock(return_value=None)+ fake_app_module.AGENT_FUNCTION.get_mcp_request_organization_id = MagicMock(return_value=None)# Sync method returning a key or None — _LazyNamespace would auto-mock it as a truthy# AsyncMock and hijack the TextPromptBlock llm_key. Match the OSS no-op.fake_app_module.AGENT_FUNCTION.get_fallback_llm_key = MagicMock(return_value=None)diff --git a/tests/unit/forge/sdk/routes/streaming/test_verify_browser_session.py b/tests/unit/forge/sdk/routes/streaming/test_verify_browser_session.pyindex 91f971ab7..1f06045de 100644--- a/tests/unit/forge/sdk/routes/streaming/test_verify_browser_session.py+++ b/tests/unit/forge/sdk/routes/streaming/test_verify_browser_session.py@@ -29,6 +29,9 @@ def _make_session(organization_id="o_test",status=status,browser_address=browser_address,+ # The session worker writes both columns in one call, and readiness is keyed on the+ # upstream — a row with an address and no upstream is a shape nothing writes.+ upstream_cdp_url="ws://10.0.0.7:9223/devtools/browser/abc" if browser_address else None,created_at=now,modified_at=now,started_at=started_at,diff --git a/tests/unit/forge/sdk/routes/streaming/test_vnc_routed_url.py b/tests/unit/forge/sdk/routes/streaming/test_vnc_routed_url.pynew file mode 100644index 000000000..36bfd060d--- /dev/null+++ b/tests/unit/forge/sdk/routes/streaming/test_vnc_routed_url.py@@ -0,0 +1,97 @@+"""Which address live view is allowed to stream from (SKY-13287).++A live view carries a customer's screen, keyboard and clipboard. The only addresses permitted+here are ones an edge checks a credential on before a byte reaches the browser, plus loopback,+where there is no network hop and no edge to check. Naming the browser's own address instead+would stream that view with no credential on the wire, so it is refused — visibly.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from skyvern.exceptions import MissingRoutedVncAddressError+from skyvern.forge.sdk.routes.streaming.channels import vnc as vnc_channel_module+from skyvern.forge.sdk.routes.streaming.channels.vnc import (+ _build_vnc_url_from_browser_address,+ loop_stream_vnc,+)++VNC_PORT = 6080+SESSION_ID = "pbs_live"+TOKEN = f"{SESSION_ID}.minted-secret"+ROUTER_ADDRESS = f"wss://session-router.skyvern.com/{SESSION_ID}?token={TOKEN}"+LEGACY_ADDRESS = f"wss://sessions.skyvern.com/{SESSION_ID}/payload.signature/devtools/browser/b-1"+POD_ADDRESS = "ws://10.0.0.7:9223/devtools/browser/b-1"+++def test_a_router_address_yields_a_routed_token_bearing_live_view_url() -> None:+ url = _build_vnc_url_from_browser_address(ROUTER_ADDRESS, VNC_PORT)++ assert url == f"wss://session-router.skyvern.com/vnc/{SESSION_ID}?token={TOKEN}"+++def test_a_legacy_address_yields_exactly_what_it_does_today() -> None:+ url = _build_vnc_url_from_browser_address(LEGACY_ADDRESS, VNC_PORT)++ assert url == f"wss://sessions.skyvern.com/vnc/{SESSION_ID}/payload.signature"+++def test_a_loopback_address_streams_from_the_local_websockify_listener() -> None:+ """Single-host case (local dev, single-container self-hosting): no network hop leaves the+ machine the API is on, so there is no edge to route through and nothing to authenticate to."""+ url = _build_vnc_url_from_browser_address("ws://127.0.0.1:9224/devtools/browser/b-1#pbs_live", VNC_PORT)++ assert url == f"ws://127.0.0.1:{VNC_PORT}"+++ "browser_address",+ [+ pytest.param(POD_ADDRESS, id="pod_address"),+ pytest.param("ws://10.0.0.7:6080", id="pod_websockify_address"),+ pytest.param(f"wss://session-router.skyvern.com/{SESSION_ID}", id="router_shape_without_a_token"),+ pytest.param(f"wss://session-router.skyvern.com/{SESSION_ID}?other=x", id="router_shape_wrong_query"),+ pytest.param(f"https://session-router.skyvern.com/{SESSION_ID}?token={TOKEN}", id="not_a_websocket_scheme"),+ pytest.param("", id="empty"),+ pytest.param(None, id="missing"),+ ],+)+def test_no_other_address_yields_a_live_view_url(browser_address: str | None) -> None:+ assert _build_vnc_url_from_browser_address(browser_address, VNC_PORT) is None+++def _channel(browser_address: str | None) -> SimpleNamespace:+ return SimpleNamespace(+ browser_session=SimpleNamespace(+ browser_address=browser_address,+ persistent_browser_session_id=SESSION_ID,+ ip_address="10.0.0.7",+ ),+ class_name="VncChannel",+ vnc_port=VNC_PORT,+ x_api_key="sk-test",+ identity={},+ )+++async def test_a_session_with_no_routable_address_fails_instead_of_streaming(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The session carries a reachable ip_address; before SKY-13287 that was streamed directly,+ with no credential anywhere on the connection."""+ dialed: list[str] = []++ def _record_connect(url: str, **kwargs: object) -> object:+ dialed.append(url)+ raise AssertionError("live view must not dial when no routed address exists")++ monkeypatch.setattr(vnc_channel_module.websockets, "connect", _record_connect)++ with pytest.raises(MissingRoutedVncAddressError):+ await loop_stream_vnc(_channel(POD_ADDRESS)) # type: ignore[arg-type]++ assert dialed == []diff --git a/tests/unit/test_adopted_session_download_save.py b/tests/unit/test_adopted_session_download_save.pyindex d94ebaa83..59fc3d537 100644--- a/tests/unit/test_adopted_session_download_save.py+++ b/tests/unit/test_adopted_session_download_save.py@@ -88,7 +88,7 @@ async def test_save_as_raises_target_closed_falls_back_to_refetch(tmp_path) -> Nassert saved is not None and saved.exists()assert saved.read_bytes() == PDF_BODY- page.context.request.get.assert_awaited_once_with(download.url)+ page.context.request.get.assert_awaited_once_with(download.url, max_redirects=0)@pytest.mark.asyncio@@ -105,7 +105,7 @@ async def test_zero_byte_save_as_falls_back_to_refetch(tmp_path) -> None:assert saved is not None and saved.exists()assert saved.read_bytes() == PDF_BODY- page.context.request.get.assert_awaited_once_with(download.url)+ page.context.request.get.assert_awaited_once_with(download.url, max_redirects=0)# the empty placeholder must not survive alongside the recovered fileassert sorted(p.name for p in tmp_path.iterdir()) == [saved.name]@@ -714,3 +714,62 @@ async def test_read_adopted_session_blob_bytes_oversized_returns_none() -> None:AsyncMock(return_value=None),):assert await _read_adopted_session_blob_bytes(download, click_page, workflow_run_id="wr") is None++[email protected](autouse=True)+def _resolvable_example_host(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep the module's ``example.com`` fixtures off real DNS once destinations are checked."""+ import socket++ real_getaddrinfo = socket.getaddrinfo++ def fake_getaddrinfo(host: str, port: object = None, *args: object, **kwargs: object) -> list:+ if host == "example.com":+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", port or 0))]+ return real_getaddrinfo(host, port, *args, **kwargs)++ monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)+++async def test_refetch_refuses_internal_destination(tmp_path, download_destinations, fake_api_request_context) -> None:+ download = _download(url=f"{download_destinations.internal_base}/internal")+ download.save_as.side_effect = Exception("Target page, context or browser has been closed")+ page = _page_with_refetch()+ page.context.request = fake_api_request_context()++ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr")++ assert saved is None+ assert download_destinations.reached_internal() is False+ assert all(path.read_bytes() != download_destinations.INTERNAL_BODY for path in tmp_path.iterdir())+++async def test_refetch_refuses_redirect_hop_to_internal_destination(+ tmp_path, download_destinations, fake_api_request_context+) -> None:+ download = _download(url=f"{download_destinations.public_base}/redirect-to-internal")+ download.save_as.side_effect = Exception("Target page, context or browser has been closed")+ page = _page_with_refetch()+ page.context.request = fake_api_request_context()++ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr")++ assert saved is None+ assert download_destinations.reached_internal() is False+ assert all(path.read_bytes() != download_destinations.INTERNAL_BODY for path in tmp_path.iterdir())+++async def test_refetch_allows_permitted_destination(tmp_path, download_destinations, fake_api_request_context) -> None:+ # Non-vacuity: a permitted destination must still round-trip through the re-fetch path.+ download = _download(url=f"{download_destinations.public_base}/attachment")+ download.save_as.side_effect = Exception("Target page, context or browser has been closed")+ page = _page_with_refetch()+ page.context.request = fake_api_request_context()++ saved = await _save_adopted_session_download(download, page, tmp_path, workflow_run_id="wr")++ assert saved is not None and saved.exists()+ assert saved.read_bytes() == download_destinations.PUBLIC_BODYdiff --git a/tests/unit/test_azure_credential_vault_service.py b/tests/unit/test_azure_credential_vault_service.pyindex 6fdee3aa0..41d0c67e3 100644--- a/tests/unit/test_azure_credential_vault_service.py+++ b/tests/unit/test_azure_credential_vault_service.py@@ -3,6 +3,7 @@ from unittest.mock import AsyncMockimport pytest+from skyvern.forge import appfrom skyvern.forge.sdk.schemas.credentials import PasswordCredential, TotpTypefrom skyvern.forge.sdk.services.credential.azure_credential_vault_service import AzureCredentialVaultService@@ -36,3 +37,46 @@ async def test_azure_password_data_image_round_trips_metadata_and_loads_legacy())assert isinstance(legacy_item.credential, PasswordCredential)assert legacy_item.credential.metadata is None+++async def test_azure_delete_scrubs_vault_before_removing_db_row(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []++ async def scrub(**_kwargs: object) -> str:+ calls.append("vault_scrub")+ return "secret-id"++ async def db_delete(*_args: object, **_kwargs: object) -> None:+ calls.append("db_delete")++ client = AsyncMock()+ client.create_or_update_secret = AsyncMock(side_effect=scrub)+ service = AzureCredentialVaultService(client=client, vault_name="vault")+ monkeypatch.setattr(+ app.DATABASE, "credentials", SimpleNamespace(delete_credential=AsyncMock(side_effect=db_delete))+ )++ await service.delete_credential(SimpleNamespace(item_id="item_1", credential_id="cred_1", organization_id="org_1"))++ # Scrub the still-readable secret before dropping the DB row so a vault failure cannot orphan it.+ assert calls == ["vault_scrub", "db_delete"]+ client.create_or_update_secret.assert_awaited_once_with(vault_name="vault", secret_name="item_1", secret_value="")+++async def test_azure_delete_leaves_db_row_when_vault_scrub_fails(monkeypatch: pytest.MonkeyPatch) -> None:+ client = AsyncMock()+ client.create_or_update_secret = AsyncMock(side_effect=RuntimeError("vault down"))+ service = AzureCredentialVaultService(client=client, vault_name="vault")+ db_delete = AsyncMock()+ monkeypatch.setattr(app.DATABASE, "credentials", SimpleNamespace(delete_credential=db_delete))++ with pytest.raises(RuntimeError, match="vault down"):+ await service.delete_credential(+ SimpleNamespace(item_id="item_1", credential_id="cred_1", organization_id="org_1")+ )++ # A transient vault failure must abort the delete with the DB row (and its item_id) intact so a retry+ # can still scrub the secret, rather than orphaning a still-readable secret with no DB pointer.+ db_delete.assert_not_awaited()diff --git a/tests/unit/test_browser_session_address_write.py b/tests/unit/test_browser_session_address_write.pyindex b1ccaffaf..693512396 100644--- a/tests/unit/test_browser_session_address_write.py+++ b/tests/unit/test_browser_session_address_write.py@@ -19,7 +19,7 @@ VENDOR_UPSTREAM = "wss://connect.vendor.example?sessionId=deadbeef-1234"ORG_ID = "org_test"-async def _write_address(mock_session: MagicMock) -> None:+async def _write_address(mock_session: MagicMock, *, mark_started: bool = False) -> None:repo = BrowserSessionsRepository(session_factory=lambda: MockAsyncSessionCtx(mock_session))await repo.set_persistent_browser_session_browser_address(browser_session_id="pbs_123",@@ -29,6 +29,7 @@ async def _write_address(mock_session: MagicMock) -> None:organization_id="org_123",upstream_cdp_url=UPSTREAM,browser_vendor="websocket",+ mark_started=mark_started,)@@ -42,6 +43,21 @@ async def test_address_write_persists_the_routing_fields() -> None:assert mock_pbs.browser_vendor == "websocket"+async def test_the_session_clock_starts_only_when_the_caller_asks_for_it() -> None:+ """An address that names the session rather than the browser can be published before anything+ is provisioned, and starting the timeout clock there would expire a session that has no+ browser yet — so writing an address no longer implies the session started."""+ unstarted = MagicMock(started_at=None)+ await _write_address(make_mock_session(unstarted))++ started = MagicMock(started_at=None)+ await _write_address(make_mock_session(started), mark_started=True)++ assert unstarted.started_at is None+ assert started.started_at is not None++@pytest.mark.asyncioasync def test_failed_address_write_never_renders_the_upstream_in_the_error() -> None:"""A failed commit renders its bound parameters, and callers log the error text."""diff --git a/tests/unit/test_browser_session_readiness.py b/tests/unit/test_browser_session_readiness.pynew file mode 100644index 000000000..430446bb8--- /dev/null+++ b/tests/unit/test_browser_session_readiness.py@@ -0,0 +1,113 @@+"""What "this session has a browser you can connect to" is keyed on.++A client-facing address can be minted when a session is created, before anything is provisioned,+so its presence no longer means a browser exists. Everything that gates on readiness reads+``is_browser_ready`` (the upstream endpoint) instead, or an adopter connects to an address whose+browser is still starting and is refused by the router.+"""++from __future__ import annotations++from datetime import datetime, timezone+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.forge.sdk.db.polls import await_browser_session, wait_on_persistent_browser_address+from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession+from skyvern.webeye.default_persistent_sessions_manager import DefaultPersistentSessionsManager++SESSION_ID = "pbs_ready"+ORG_ID = "o_ready"+ROUTER_ADDRESS = f"wss://session-router.skyvern.com/{SESSION_ID}?token={SESSION_ID}.minted-secret"+LEGACY_ADDRESS = f"wss://sessions.skyvern.com/{SESSION_ID}/payload.signature/devtools/browser/b-1"+UPSTREAM_URL = "ws://10.0.0.7:9223/devtools/browser/b-1"+++def _session(*, browser_address: str | None, upstream_cdp_url: str | None) -> PersistentBrowserSession:+ now = datetime.now(timezone.utc)+ return PersistentBrowserSession(+ persistent_browser_session_id=SESSION_ID,+ organization_id=ORG_ID,+ status="running",+ browser_address=browser_address,+ upstream_cdp_url=upstream_cdp_url,+ created_at=now,+ modified_at=now,+ )+++def test_an_address_minted_before_the_browser_exists_is_not_readiness() -> None:+ """The regression: a session created with a router address has an address and no browser."""+ session = _session(browser_address=ROUTER_ADDRESS, upstream_cdp_url=None)++ assert session.is_browser_ready is False+++def test_a_session_with_an_upstream_is_ready() -> None:+ assert _session(browser_address=ROUTER_ADDRESS, upstream_cdp_url=UPSTREAM_URL).is_browser_ready is True+++def test_a_legacy_session_is_ready_exactly_as_it_is_today() -> None:+ """The session worker writes both columns in one call, so gating on the upstream is the same+ answer it always was for every session that predates minted addresses."""+ assert _session(browser_address=LEGACY_ADDRESS, upstream_cdp_url=UPSTREAM_URL).is_browser_ready is True+ assert _session(browser_address=None, upstream_cdp_url=None).is_browser_ready is False+++def _manager(session: PersistentBrowserSession | None) -> DefaultPersistentSessionsManager:+ database = MagicMock()+ database.browser_sessions.get_persistent_browser_session = AsyncMock(return_value=session)+ return DefaultPersistentSessionsManager(database=database)+++async def test_a_session_whose_browser_is_still_starting_is_not_reported_ready() -> None:+ manager = _manager(_session(browser_address=ROUTER_ADDRESS, upstream_cdp_url=None))++ assert await manager.get_browser_address_if_ready(SESSION_ID, ORG_ID) is None+++async def test_a_ready_session_still_returns_its_client_facing_address() -> None:+ """Only the gate moved to the upstream: what comes back is still the address the client uses,+ never the upstream endpoint, which must not reach a client."""+ manager = _manager(_session(browser_address=ROUTER_ADDRESS, upstream_cdp_url=UPSTREAM_URL))++ assert await manager.get_browser_address_if_ready(SESSION_ID, ORG_ID) == ROUTER_ADDRESS+++async def test_a_ready_legacy_session_returns_its_address_as_it_does_today() -> None:+ manager = _manager(_session(browser_address=LEGACY_ADDRESS, upstream_cdp_url=UPSTREAM_URL))++ assert await manager.get_browser_address_if_ready(SESSION_ID, ORG_ID) == LEGACY_ADDRESS+++async def test_the_address_poll_waits_for_the_browser_not_for_the_address() -> None:+ database = MagicMock()+ database.browser_sessions.get_persistent_browser_session = AsyncMock(+ side_effect=[+ _session(browser_address=ROUTER_ADDRESS, upstream_cdp_url=None),+ _session(browser_address=ROUTER_ADDRESS, upstream_cdp_url=UPSTREAM_URL),+ ]+ )++ session = await await_browser_session(database, SESSION_ID, ORG_ID, timeout=5, poll_interval=0)++ assert session is not None+ assert session.is_browser_ready is True+ assert database.browser_sessions.get_persistent_browser_session.await_count == 2+++async def test_the_address_poll_still_returns_the_client_facing_address() -> None:+ database = MagicMock()+ database.browser_sessions.get_persistent_browser_session = AsyncMock(+ return_value=_session(browser_address=ROUTER_ADDRESS, upstream_cdp_url=UPSTREAM_URL)+ )++ address = await wait_on_persistent_browser_address(database, SESSION_ID, ORG_ID, timeout=5, poll_interval=0)++ assert address == ROUTER_ADDRESSdiff --git a/tests/unit/test_cdp_connection.py b/tests/unit/test_cdp_connection.pyindex baef966ef..45bc6904f 100644--- a/tests/unit/test_cdp_connection.py+++ b/tests/unit/test_cdp_connection.py@@ -1,14 +1,18 @@from __future__ import annotations+import jsonimport socket+from types import SimpleNamespacefrom typing import Any, castimport pytest+import structlog.testingfrom playwright.async_api import Playwrightimport skyvern.webeye.browser_factory as browser_factoryimport skyvern.webeye.cdp_connection as cdp_connectionfrom skyvern.webeye.cdp_connection import (+ REDACTED,build_cdp_connect_headers,build_cdp_connection_candidates,connect_over_cdp_with_diagnostics,@@ -262,3 +266,30 @@ async def test_connect_over_cdp_accepts_direct_websocket_with_host_header() -> Nassert fake_playwright.chromium.calls == [("ws://host.docker.internal:9223/devtools/browser/abc", 120000, headers),]+++async def test_cdp_connect_never_logs_a_credential_bearing_remote_url(monkeypatch: pytest.MonkeyPatch) -> None:+ """SKY-13287: `remote_browser_url` here is caller-supplied — a routed session address whose+ query carries the session token, or a vendor endpoint carrying an api key. Both the connect+ line and the launched line have to be readable without handing the reader that credential."""+ secret = "pbs_routed.minted-secret"+ routed_url = f"wss://session-router.skyvern.com/pbs_routed?token={secret}"++ fake_context = object()+ fake_browser = cast(Any, SimpleNamespace(contexts=[fake_context]))++ async def fake_connect(*_args: Any, **_kwargs: Any) -> Any:+ return fake_browser++ monkeypatch.setattr(browser_factory, "_connect_over_cdp_with_diagnostics", fake_connect)++ with structlog.testing.capture_logs() as logs:+ await browser_factory._connect_to_cdp_browser(cast(Playwright, object()), routed_url)++ rendered = json.dumps(logs, default=str)+ assert secret not in rendered+ assert "minted-secret" not in rendered+ # Redacted, not dropped: the session it dialed still has to be identifiable.+ assert "pbs_routed" in rendered+ assert REDACTED in rendereddiff --git a/tests/unit/test_cdp_download_interceptor.py b/tests/unit/test_cdp_download_interceptor.pyindex 2bf5cf5f8..dd87dd611 100644--- a/tests/unit/test_cdp_download_interceptor.py+++ b/tests/unit/test_cdp_download_interceptor.py@@ -1847,23 +1847,11 @@ class TestDirectHttpDownloadAuthAndHtmlGuard:.zip while reporting the download as successful."""- _URLOPEN = "urllib.request.urlopen"+ _URLOPEN = "skyvern.webeye.cdp_download_interceptor._urlopen_single_hop"@staticmethoddef _fake_urlopen(body: bytes, content_type: str) -> MagicMock:- class _Resp:- headers = {"content-type": content_type}-- def read(self) -> bytes:- return body-- def __enter__(self) -> "_Resp":- return self-- def __exit__(self, *exc: object) -> bool:- return False-- return MagicMock(return_value=_Resp())+ return MagicMock(return_value=(200, {"content-type": content_type}, body))@staticmethoddef _context_forcing_urllib(cookies: list[dict]) -> MagicMock:@@ -1877,6 +1865,20 @@ class TestDirectHttpDownloadAuthAndHtmlGuard:ctx.cookies = AsyncMock(return_value=cookies)return ctx+ @pytest.fixture(autouse=True)+ def _resolvable_site_host(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep this class's ``site.example`` fixtures off real DNS now destinations are checked."""+ import socket++ real_getaddrinfo = socket.getaddrinfo++ def fake_getaddrinfo(host: str, port: object = None, *args: object, **kwargs: object) -> list:+ if host == "site.example":+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", port or 0))]+ return real_getaddrinfo(host, port, *args, **kwargs)++ monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)+_LOGIN_HTML = (b'\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n'b"<html><head><title>Login</title></head>"@@ -1897,10 +1899,6 @@ class TestDirectHttpDownloadAuthAndHtmlGuard:sent_request = urlopen.call_args.args[0]assert sent_request.get_header("Cookie") == "ASP.NET_SessionId=sess123; auth=tok"- # The cookie must be an unredirected header so urllib does not replay it across a cross-host- # redirect (session-cookie leak): urllib copies req.headers on redirect, not unredirected_hdrs.- assert "Cookie" not in sent_request.headers- assert sent_request.unredirected_hdrs.get("Cookie") == "ASP.NET_SessionId=sess123; auth=tok"saved = list(tmp_path.iterdir())assert [p.name for p in saved] == ["statement.zip"]assert saved[0].read_bytes() == zip_bytes@@ -2765,3 +2763,136 @@ class TestTwoPathDownloadStreaming:assert _only_file(tmp_path).read_bytes() == b"P" * 2000 # file saved despite the benign fulfill raceassert not [log for log in logs if log.get("log_level") == "error"]+++class TestDownloadDestinationValidation:+ """A download URL is chosen by the page, so it must be checked against the destination rules+ before the worker fetches it — on the initial URL and on every redirect hop, and on both the+ Playwright and urllib transports."""++ @staticmethod+ def _context(request_context: object | None = None, cookies: list[dict] | None = None) -> MagicMock:+ ctx = MagicMock()+ if request_context is None:+ # Non-OK forces _download_url_directly onto its urllib transport.+ non_ok = MagicMock()+ non_ok.ok = False+ non_ok.status = 407+ ctx.request.get = AsyncMock(return_value=non_ok)+ else:+ ctx.request = request_context+ ctx.cookies = AsyncMock(return_value=cookies or [])+ return ctx++ @pytest.mark.asyncio+ async def test_playwright_transport_refuses_internal_destination(+ self, tmp_path: Path, download_destinations: Any, fake_api_request_context: Any+ ) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context(fake_api_request_context())++ await interceptor._download_url_directly(f"{download_destinations.internal_base}/internal", "statement.pdf")++ assert download_destinations.reached_internal() is False+ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_playwright_transport_refuses_redirect_hop_to_internal_destination(+ self, tmp_path: Path, download_destinations: Any, fake_api_request_context: Any+ ) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context(fake_api_request_context())++ await interceptor._download_url_directly(+ f"{download_destinations.public_base}/redirect-to-internal", "statement.pdf"+ )++ assert download_destinations.reached_internal() is False+ saved = list(tmp_path.iterdir())+ assert [path.read_bytes() for path in saved] == []++ @pytest.mark.asyncio+ async def test_urllib_transport_refuses_internal_destination(+ self, tmp_path: Path, download_destinations: Any+ ) -> None:+ # No browser context, so the urllib transport is entered directly and owns the initial+ # destination check itself rather than inheriting one from the Playwright transport.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = None++ await interceptor._download_url_directly(f"{download_destinations.internal_base}/internal", "statement.pdf")++ assert download_destinations.reached_internal() is False+ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_urllib_transport_refuses_redirect_hop_to_internal_destination(+ self, tmp_path: Path, download_destinations: Any+ ) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context(cookies=[{"name": "sess", "value": "tok"}])++ await interceptor._download_url_directly(+ f"{download_destinations.public_base}/redirect-to-internal", "statement.pdf"+ )++ assert download_destinations.reached_internal() is False+ saved = list(tmp_path.iterdir())+ assert [path.read_bytes() for path in saved] == []++ @pytest.mark.asyncio+ async def test_allowed_destination_still_downloads(+ self, tmp_path: Path, download_destinations: Any, fake_api_request_context: Any+ ) -> None:+ # Non-vacuity: the harness must be able to complete a download that is not refused,+ # otherwise the refusal assertions above would pass for the wrong reason.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context(fake_api_request_context())++ await interceptor._download_url_directly(f"{download_destinations.public_base}/attachment", "statement.pdf")++ saved = list(tmp_path.iterdir())+ assert [path.name for path in saved] == ["statement.pdf"]+ assert saved[0].read_bytes() == download_destinations.PUBLIC_BODY++ @pytest.mark.asyncio+ async def test_urllib_transport_drops_session_cookie_on_cross_origin_hop(+ self, tmp_path: Path, download_destinations: Any+ ) -> None:+ # The session cookie belongs to the host the download started on. A hop to a different+ # origin — permitted or not — must not replay it.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context(cookies=[{"name": "sess", "value": "tok"}])++ await interceptor._download_url_directly(+ f"{download_destinations.public_base}/redirect-to-other", "statement.pdf"+ )++ assert download_destinations.cookies_by_path["public-host.test"] == "sess=tok"+ assert download_destinations.cookies_by_path["other-host.test"] == ""+ saved = list(tmp_path.iterdir())+ assert [path.name for path in saved] == ["statement.pdf"]++ @pytest.mark.asyncio+ async def test_urllib_transport_reads_content_type_case_insensitively(+ self, tmp_path: Path, download_destinations: Any+ ) -> None:+ # Servers send "Content-Type"; the extension for a suffix-less download comes from it.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = None++ await interceptor._download_url_directly(f"{download_destinations.public_base}/attachment", "statement")++ assert [path.name for path in tmp_path.iterdir()] == ["statement.pdf"]++ @pytest.mark.asyncio+ async def test_urllib_transport_does_not_save_an_error_response_body(+ self, tmp_path: Path, download_destinations: Any+ ) -> None:+ # An error page is not the file. Saving its body would report a corrupt download as success.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = None++ await interceptor._download_url_directly(f"{download_destinations.public_base}/notfound", "statement.pdf")++ assert list(tmp_path.iterdir()) == []diff --git a/tests/unit/test_cli_shared_core.py b/tests/unit/test_cli_shared_core.pyindex 45f0a1f78..9a0f3b5d2 100644--- a/tests/unit/test_cli_shared_core.py+++ b/tests/unit/test_cli_shared_core.py@@ -2,6 +2,7 @@from __future__ import annotations+from datetime import datetime, timezonefrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -353,7 +354,9 @@ async def test_do_session_list() -> None:session = MagicMock()session.browser_session_id = "pbs_1"session.status = "active"- session.started_at = None+ # Set together with the address by the session worker; an address alone can be minted before+ # the browser exists, so availability needs both.+ session.started_at = datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc)session.timeout = 60session.runnable_id = Nonesession.browser_address = "ws://localhost:1234"diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.pyindex d98570ff6..6d4c6c2c7 100644--- a/tests/unit/test_copilot_completion_verification.py+++ b/tests/unit/test_copilot_completion_verification.py@@ -88,11 +88,13 @@ from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (build_diagnosis_repair_contract,)from skyvern.forge.sdk.copilot.enforcement import (+ TOTAL_TIMEOUT_SECONDS,built_unverified_repair_inert_context,outcome_fully_verified,verified_goal_satisfied_context,)from skyvern.forge.sdk.copilot.hooks import _tool_completion_satisfies_turn+from skyvern.forge.sdk.copilot.output_utils import sanitize_tool_result_for_llmfrom skyvern.forge.sdk.copilot.request_policy import (AntecedentFamily,CompletionCriterion,@@ -13665,3 +13667,45 @@ def test_minted_value_present_criterion_corroborated_reaches_verified_success())assert result.is_fully_satisfied() is True+++def test_tool_visible_result_stamps_remaining_turn_budget_mid_turn() -> None:+ ctx = _ctx_with_blocks("extraction")+ ctx.copilot_run_start_monotonic = time.monotonic() - 120.0++ visible = _tool_visible_result_after_completion_verification(ctx, _clean_success_result(), None)++ remaining = visible["turn_seconds_remaining"]+ assert isinstance(remaining, float)+ assert remaining == pytest.approx(TOTAL_TIMEOUT_SECONDS - 120.0, abs=2.0)+++def test_tool_visible_result_stamps_remaining_budget_on_the_unverified_shape_too() -> None:+ ctx = _ctx_with_blocks("extraction")+ ctx.copilot_run_start_monotonic = time.monotonic() - 30.0++ visible = _tool_visible_result_after_completion_verification(+ ctx, _clean_success_result(), _evaluated(("c0", False))+ )++ assert visible["ok"] is False+ assert visible["turn_seconds_remaining"] == pytest.approx(TOTAL_TIMEOUT_SECONDS - 30.0, abs=2.0)+++def test_tool_visible_result_remaining_budget_is_none_before_the_loop_starts() -> None:+ ctx = _ctx_with_blocks("extraction")+ ctx.copilot_run_start_monotonic = None++ visible = _tool_visible_result_after_completion_verification(ctx, _clean_success_result(), None)++ assert visible["turn_seconds_remaining"] is None+++def test_remaining_turn_budget_survives_the_llm_sanitizer() -> None:+ ctx = _ctx_with_blocks("extraction")+ ctx.copilot_run_start_monotonic = time.monotonic() - 60.0++ visible = _tool_visible_result_after_completion_verification(ctx, _clean_success_result(), None)+ sanitized = sanitize_tool_result_for_llm("run_blocks_and_collect_debug", visible)++ assert sanitized["turn_seconds_remaining"] == pytest.approx(TOTAL_TIMEOUT_SECONDS - 60.0, abs=2.0)diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.pyindex 8304988ec..5c5d71914 100644--- a/tests/unit/test_copilot_credential_pause.py+++ b/tests/unit/test_copilot_credential_pause.py@@ -71,6 +71,7 @@ from skyvern.forge.sdk.copilot.request_policy import (RequestPolicy,credential_prompt_reason,)+from skyvern.forge.sdk.copilot.tools._shared import TOTAL_TIMEOUT_SECONDS, _copilot_seconds_remainingfrom skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentModefrom skyvern.forge.sdk.routes.workflow_copilot import (WorkflowCopilotCredentialResponseRequest,@@ -1593,15 +1594,13 @@ async def test_last_run_skipped_flag_stays_false_when_update_workflow_fails_befodef test_copilot_seconds_remaining_credits_pause_time() -> None:- from skyvern.forge.sdk.copilot.tools._shared import _copilot_seconds_remaining-ctx = SimpleNamespace(copilot_run_start_monotonic=time.monotonic() - 1000.0, copilot_credential_pause_seconds=300.0)remaining = _copilot_seconds_remaining(ctx)- # Uncredited: 900 - 1000 = -100s (would forbid). Credited: 900 - 700 = 200s.+ # Uncredited, the budget would be spent against 1000s rather than the 700s of counted work.assert remaining is not None- assert remaining > 150.0+ assert remaining == pytest.approx(TOTAL_TIMEOUT_SECONDS - 700.0, abs=1.0)# ---------------------------------------------------------------------------diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.pyindex 836d8dd7b..86b17e7e1 100644--- a/tests/unit/test_copilot_enforcement_pruning.py+++ b/tests/unit/test_copilot_enforcement_pruning.py@@ -9,6 +9,7 @@ These cover three regressions observed in trace 019d7b5c884dff0ff648680b9f31f715from __future__ import annotationsimport json+import timefrom copy import deepcopyfrom types import SimpleNamespacefrom typing import Any@@ -23,6 +24,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import (CopilotToolBlockerSignal,stash_blocker_signal,)+from skyvern.forge.sdk.copilot.build_phase import BuildPhasefrom skyvern.forge.sdk.copilot.build_test_outcome import (PostRunPagePathFailure,PostRunPagePathTarget,@@ -42,7 +44,10 @@ from skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContextfrom skyvern.forge.sdk.copilot.enforcement import (KEEP_RECENT_TOOL_OUTPUTS,SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,+ TOTAL_TIMEOUT_SECONDS,_check_enforcement,+ _mark_copilot_total_timeout,+ _mark_copilot_total_timeout_if_elapsed,_maybe_synthesized_block_offer_msg,_needs_suspicious_success_nudge,_prune_input_list,@@ -85,6 +90,7 @@ from skyvern.forge.sdk.copilot.tools import (_record_run_blocks_result,_record_workflow_update_result,)+from skyvern.forge.sdk.copilot.tools._shared import TOTAL_TIMEOUT_SECONDS as shared_total_timeout_secondsfrom skyvern.forge.sdk.copilot.tools.page_observation import _record_composition_page_observationfrom skyvern.forge.sdk.copilot.tools.scouting import (_MAX_SCOUTED_INTERACTIONS,@@ -4326,3 +4332,88 @@ class TestCredentialScoutReopen:assert _should_force_synthesized_block_persistence(ctx) is Falsectx.synthesized_block_reopened_for_credential_scout = Trueassert _should_force_synthesized_block_persistence(ctx) is True+++def _deadline_ctx() -> SimpleNamespace:+ return SimpleNamespace(+ copilot_total_timeout_exceeded=False,+ copilot_credential_pause_seconds=0.0,+ build_phase=BuildPhase.TESTING,+ )+++def _deadline_events(logs: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [entry for entry in logs if entry.get("event") == "copilot_turn_deadline_expired"]+++def test_deadline_fingerprint_carries_elapsed_iteration_and_phase() -> None:+ ctx = _deadline_ctx()++ with capture_logs() as logs:+ _mark_copilot_total_timeout(ctx, elapsed_seconds=901.4567, iteration=12)++ events = _deadline_events(logs)+ assert len(events) == 1+ assert events[0]["elapsed_seconds"] == 901.457+ assert events[0]["iteration"] == 12+ assert events[0]["build_phase"] == "testing"+ assert ctx.copilot_total_timeout_exceeded is True+++def test_deadline_fingerprint_emitted_once_per_turn_across_both_reachable_sites() -> None:+ ctx = _deadline_ctx()++ with capture_logs() as logs:+ _mark_copilot_total_timeout(ctx, elapsed_seconds=901.0, iteration=3)+ _mark_copilot_total_timeout(ctx, elapsed_seconds=902.0, iteration=4)++ assert len(_deadline_events(logs)) == 1+ assert ctx.copilot_total_timeout_exceeded is True+++def test_deadline_flag_still_written_when_fingerprint_is_suppressed() -> None:+ ctx = _deadline_ctx()+ ctx.copilot_total_timeout_exceeded = True++ with capture_logs() as logs:+ _mark_copilot_total_timeout(ctx, elapsed_seconds=901.0, iteration=1)++ assert _deadline_events(logs) == []+ assert ctx.copilot_total_timeout_exceeded is True++[email protected]("iteration", [0, 5, 11])+def test_cancel_site_helper_threads_iteration_into_the_fingerprint(iteration: int) -> None:+ ctx = _deadline_ctx()+ start_time = time.monotonic() - (TOTAL_TIMEOUT_SECONDS + 5.0)++ with capture_logs() as logs:+ _mark_copilot_total_timeout_if_elapsed(ctx, start_time, iteration)++ events = _deadline_events(logs)+ assert len(events) == 1+ assert events[0]["iteration"] == iteration+ assert events[0]["elapsed_seconds"] >= TOTAL_TIMEOUT_SECONDS+++def test_cancel_site_helper_is_silent_before_the_deadline() -> None:+ ctx = _deadline_ctx()++ with capture_logs() as logs:+ _mark_copilot_total_timeout_if_elapsed(ctx, time.monotonic(), 2)++ assert _deadline_events(logs) == []+ assert ctx.copilot_total_timeout_exceeded is False+++def test_total_timeout_override_binds_on_settings_and_defaults_unset() -> None:+ unset = Settings(_env_file=None, WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS=None)+ overridden = Settings(_env_file=None, WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS=300)++ assert unset.WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS is None+ assert overridden.WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS == 300+++def test_shared_tools_bind_the_configured_total_timeout() -> None:+ assert shared_total_timeout_seconds == TOTAL_TIMEOUT_SECONDS+ assert TOTAL_TIMEOUT_SECONDS == (settings.WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS or 900)diff --git a/tests/unit/test_copilot_live_session_helper.py b/tests/unit/test_copilot_live_session_helper.pyindex 9d417ded9..fc5821ed4 100644--- a/tests/unit/test_copilot_live_session_helper.py+++ b/tests/unit/test_copilot_live_session_helper.py@@ -1,5 +1,6 @@from __future__ import annotations+from datetime import datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -7,8 +8,11 @@ import pytestfrom skyvern.forge import appfrom skyvern.forge.sdk.copilot.agent import _resolve_live_browser_session_id+from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSessionfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequest+_UNSET_UPSTREAM = "<unset>"+class _FakeBrowser:def is_connected(self) -> bool:@@ -32,8 +36,30 @@ def _request(browser_session_id: str | None = None, wpid: str = "wpid-1") -> Wor)-def _running_session(browser_address: str = "wss://example/cdp") -> SimpleNamespace:- return SimpleNamespace(status="running", browser_address=browser_address)+def _session(+ *,+ status: str = "running",+ browser_address: str | None = "wss://example/cdp",+ upstream_cdp_url: str | None = _UNSET_UPSTREAM,+) -> PersistentBrowserSession:+ """The real model rather than a stand-in: whether a session is usable is decided by its+ upstream endpoint, which the session worker writes together with the address."""+ now = datetime.now(timezone.utc)+ return PersistentBrowserSession(+ persistent_browser_session_id="pbs_test",+ organization_id="org-1",+ status=status,+ browser_address=browser_address,+ upstream_cdp_url=("ws://10.0.0.7:9223/devtools/browser/b-1" if browser_address else None)+ if upstream_cdp_url is _UNSET_UPSTREAM+ else upstream_cdp_url,+ created_at=now,+ modified_at=now,+ )+++def _running_session(browser_address: str = "wss://example/cdp") -> PersistentBrowserSession:+ return _session(browser_address=browser_address)@pytest.mark.asyncio@@ -128,7 +154,7 @@ async def test_status_in_final_state_falls_back(monkeypatch: pytest.MonkeyPatch)"PERSISTENT_SESSIONS_MANAGER",SimpleNamespace(get_session=AsyncMock(- return_value=SimpleNamespace(status="completed", browser_address="wss://example/cdp"),+ return_value=_session(status="completed"),),can_probe_registered_browser_state=lambda: False,),@@ -158,7 +184,7 @@ async def test_browser_address_unset_falls_back(monkeypatch: pytest.MonkeyPatch)"PERSISTENT_SESSIONS_MANAGER",SimpleNamespace(get_session=AsyncMock(- return_value=SimpleNamespace(status="running", browser_address=None),+ return_value=_session(browser_address=None),),can_probe_registered_browser_state=lambda: False,),@@ -187,7 +213,7 @@ async def test_default_manager_registered_browser_state_allows_missing_browser_a)get_browser_state = AsyncMock(return_value=SimpleNamespace(browser_context=_FakeBrowserContext()))manager = SimpleNamespace(- get_session=AsyncMock(return_value=SimpleNamespace(status="running", browser_address=None)),+ get_session=AsyncMock(return_value=_session(browser_address=None)),get_browser_state=get_browser_state,can_probe_registered_browser_state=lambda: True,)@@ -217,7 +243,7 @@ async def test_default_manager_unattachable_registered_browser_state_falls_back()get_browser_state = AsyncMock(return_value=SimpleNamespace(browser_context=None))manager = SimpleNamespace(- get_session=AsyncMock(return_value=SimpleNamespace(status="running", browser_address=None)),+ get_session=AsyncMock(return_value=_session(browser_address=None)),get_browser_state=get_browser_state,can_probe_registered_browser_state=lambda: True,)diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.pyindex 6eb440d51..473b9d43f 100644--- a/tests/unit/test_copilot_terminal_envelope.py+++ b/tests/unit/test_copilot_terminal_envelope.py@@ -6,7 +6,10 @@ import pytestimport structlog.testingfrom skyvern.forge.sdk.copilot import agent as agent_module-from skyvern.forge.sdk.copilot.blocker_signal import clear_terminal_evidence_on_workflow_edit+from skyvern.forge.sdk.copilot.blocker_signal import (+ CopilotToolBlockerSignal,+ clear_terminal_evidence_on_workflow_edit,+)from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcomefrom skyvern.forge.sdk.copilot.terminal_envelope import (TerminalOutcomeEnvelope,@@ -452,3 +455,117 @@ def test_render_terminal_message_keeps_answer_kind_replies_on_stopped_state() ->assert rendered == messageassert replaced is False+++def test_render_terminal_message_keeps_deadline_copy_on_stopped_fallthrough() -> None:+ envelope = _assemble(+ proposal_disposition="auto_applicable",+ run_outcomes=[],+ terminal_cause="deadline_expired",+ )+ message = agent_module._TIMEOUT_REPLY_DEFAULT++ rendered, replaced = render_terminal_message(envelope, message, cancelled=False)++ assert envelope.next_state == "stopped"+ assert envelope.response_kind == "stopped"+ assert rendered == message+ assert rendered != "I stopped without confirming the goal was met."+ assert replaced is True+++def test_render_terminal_message_still_generic_without_deadline_cause() -> None:+ envelope = _assemble(proposal_disposition="auto_applicable", run_outcomes=[])++ rendered, replaced = render_terminal_message(envelope, agent_module._TIMEOUT_REPLY_DEFAULT, cancelled=False)++ assert rendered == "I stopped without confirming the goal was met."+ assert replaced is True+++def test_render_terminal_message_held_draft_text_survives_with_deadline_cause() -> None:+ envelope = _assemble(proposal_disposition="review_untested", terminal_cause="deadline_expired")+ message = agent_module._TIMEOUT_REPLY_UNVALIDATED++ rendered, replaced = render_terminal_message(envelope, message, cancelled=False)++ assert envelope.next_state == "proposal_pending"+ assert rendered == message+ assert replaced is True+++def test_render_terminal_message_held_draft_unreplaced_without_deadline_cause() -> None:+ envelope = _assemble(proposal_disposition="review_untested")+ message = agent_module._TIMEOUT_REPLY_UNVALIDATED++ rendered, replaced = render_terminal_message(envelope, message, cancelled=False)++ assert rendered == message+ assert replaced is False+++def test_render_terminal_message_cancelled_turn_ignores_deadline_cause() -> None:+ envelope = _assemble(proposal_disposition="auto_applicable", terminal_cause="deadline_expired")++ rendered, replaced = render_terminal_message(envelope, "cancelled-text", cancelled=True)++ assert rendered == "cancelled-text"+ assert replaced is False+++def test_render_terminal_message_completed_turn_is_not_stamped_by_deadline_cause() -> None:+ # replaced=True overwrites a distinct narrativeSummary downstream, so an+ # applied turn that happens to expire must not be stamped with its own text.+ envelope = _assemble(+ verified=True,+ workflow_applied=True,+ proposal_disposition="auto_applicable",+ terminal_cause="deadline_expired",+ )+ message = agent_module._TIMEOUT_REPLY_TESTED++ rendered, replaced = render_terminal_message(envelope, message, cancelled=False)++ assert envelope.next_state == "completed"+ assert rendered == message+ assert replaced is False+++def test_deadline_cause_survives_envelope_round_trip() -> None:+ envelope = _assemble(proposal_disposition="auto_applicable", terminal_cause="deadline_expired")++ payload = envelope.model_dump(mode="json")+ finalized = finalize_applied_state(TerminalOutcomeEnvelope.model_validate(payload), applied=False)++ assert payload["terminal_cause"] == "deadline_expired"+ assert finalized.model_dump(mode="json")["terminal_cause"] == "deadline_expired"+++def test_envelope_carries_deadline_cause_when_blocker_override_rewrote_the_reason() -> None:+ ctx = make_copilot_ctx()+ ctx.copilot_total_timeout_exceeded = True+ ctx.blocker_signal = CopilotToolBlockerSignal(+ blocker_kind="authority_denied",+ agent_steering_text="Reply without updating the workflow.",+ user_facing_reason="I can't update or run this workflow on this turn.",+ recovery_hint="report_blocker_to_user",+ internal_reason_code="turn_intent_no_mutation_run_blocked",+ blocked_tool="update_workflow",+ )++ result = agent_module._build_timeout_exit_result(ctx, global_llm_context=None)++ assert result.turn_outcome is not None+ assert result.turn_outcome.terminal_reason != "timeout"+ assert result.terminal_envelope is not None+ assert result.terminal_envelope["terminal_cause"] == "deadline_expired"+++def test_envelope_has_no_cause_when_deadline_did_not_expire() -> None:+ ctx = make_copilot_ctx()+ ctx.copilot_total_timeout_exceeded = False++ result = agent_module._build_timeout_exit_result(ctx, global_llm_context=None)++ assert result.terminal_envelope is not None+ assert result.terminal_envelope["terminal_cause"] is Nonediff --git a/tests/unit/test_copilot_timeout_wip.py b/tests/unit/test_copilot_timeout_wip.pyindex 4ea167662..7a1aefbcd 100644--- a/tests/unit/test_copilot_timeout_wip.py+++ b/tests/unit/test_copilot_timeout_wip.py@@ -589,3 +589,121 @@ class TestWipExitSurfacesLastGoodWithForceReviewNotUnvalidated:assert result.proposal_disposition == "review_tested"assert result.cancelled is Falseassert result.user_response == _TIMEOUT_REPLY_TESTED+++class TestTimeoutExitNamesTimeAndDraftState:+ def test_untested_draft_names_time_and_that_it_is_unverified(self) -> None:+ ctx = _ctx(last_workflow=MagicMock(name="wf"), last_workflow_yaml="version: '1.0'", last_test_ok=None)++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert result.proposal_disposition == "review_untested"+ assert "ran out of time" in result.user_response+ assert "hasn't been verified end-to-end" in result.user_response++ def test_tested_draft_names_time_and_that_it_is_tested(self) -> None:+ ctx = _ctx(last_workflow=MagicMock(name="wf"), last_workflow_yaml="version: '1.0'", last_test_ok=True)++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert result.proposal_disposition == "review_tested"+ assert "ran out of time" in result.user_response+ assert "tested draft" in result.user_response++ def test_no_draft_still_names_time(self) -> None:+ ctx = _ctx(last_workflow=None, last_workflow_yaml=None, last_test_ok=None)++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert result.proposal_disposition == "auto_applicable"+ assert "ran out of time" in result.user_response++ def test_untested_draft_with_recorded_failure_still_names_time(self) -> None:+ # The common shape: the failed test run is what spent the budget, so a+ # recorded failure is present on almost every real deadline expiry.+ ctx = _ctx(last_workflow=MagicMock(name="wf"), last_workflow_yaml="version: '1.0'", last_test_ok=False)+ ctx.copilot_total_timeout_exceeded = True+ ctx.last_update_block_count = 1+ ctx.latest_diagnosis_repair_contract = _blocker_contract(+ "could not convert string to float", run_status="failed"+ )++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert "ran out of time" in result.user_response+ assert "could not convert string to float" in result.user_response+ assert not result.user_response.startswith("I built")++ def test_no_draft_with_recorded_failure_still_names_time(self) -> None:+ ctx = _ctx(last_workflow=None, last_workflow_yaml=None, last_test_ok=False)+ ctx.copilot_total_timeout_exceeded = True+ ctx.latest_diagnosis_repair_contract = _blocker_contract(+ "could not convert string to float", run_status="failed"+ )++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert "ran out of time" in result.user_response+ assert "could not convert string to float" in result.user_response++ def test_max_turns_exit_keeps_the_recorded_failure_reply(self) -> None:+ # The deadline precedence must not leak into sibling capacity exits.+ ctx = _ctx(last_workflow=MagicMock(name="wf"), last_workflow_yaml="version: '1.0'", last_test_ok=False)+ ctx.last_update_block_count = 1+ ctx.latest_diagnosis_repair_contract = _blocker_contract(+ "could not convert string to float", run_status="failed"+ )++ result = _build_max_turns_exit_result(ctx, global_llm_context=None)++ assert "ran out of time" not in result.user_response+ assert result.user_response.startswith("I built")++ def test_held_draft_shape_names_time_draft_state_and_keeps_evidence(self) -> None:+ # The shape both live deadline runs produced: review_untested / proposal_pending.+ ctx = _ctx(last_workflow=MagicMock(name="wf"), last_workflow_yaml="version: '1.0'", last_test_ok=None)+ ctx.copilot_total_timeout_exceeded = True+ ctx.last_update_block_count = 1+ ctx.latest_diagnosis_repair_contract = _blocker_contract("Run completed", run_status="completed")++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert result.proposal_disposition == "review_untested"+ assert "ran out of time" in result.user_response+ assert "hasn't been verified end-to-end" in result.user_response+ assert "Run completed" in result.user_response++ def test_interrupted_run_is_not_reported_as_a_failed_verification(self) -> None:+ # A budget-paced halt was interrupted, not disproven. The deadline copy already says the+ # work is unverified, so appending "the last test did not verify" would mis-attribute twice.+ ctx = _ctx(last_workflow=MagicMock(name="wf"), last_workflow_yaml="version: '1.0'", last_test_ok=False)+ ctx.copilot_total_timeout_exceeded = True+ ctx.last_update_block_count = 3+ ctx.latest_diagnosis_repair_contract = _blocker_contract(+ "Less than 90 seconds remain in this Copilot turn after the previous workflow run failed. "+ "Do NOT retry block-running tools. Use only existing run evidence and quick browser inspection.",+ run_status="canceled",+ )++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert "ran out of time" in result.user_response+ assert "did not verify" not in result.user_response+ assert "Do NOT" not in result.user_response++ def test_last_good_branch_also_drops_the_trailing_verdict_when_interrupted(self) -> None:+ # wip_last_good_workflow composes its own trailing sentence; the interrupted-run+ # exemption has to reach that branch too, not just the two above it.+ ctx = _overwrite_ctx(last_test_ok=False)+ ctx.copilot_total_timeout_exceeded = True+ ctx.last_update_block_count = 2+ ctx.latest_diagnosis_repair_contract = _blocker_contract(+ "Less than 90 seconds remain in this Copilot turn after the previous workflow run failed. "+ "Do NOT retry block-running tools.",+ run_status="canceled",+ )++ result = _build_timeout_exit_result(ctx, global_llm_context=None)++ assert "ran out of time" in result.user_response+ assert "did not verify" not in result.user_responsediff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.pyindex 03fb187e6..c39b2734d 100644--- a/tests/unit/test_download_file_action_handler.py+++ b/tests/unit/test_download_file_action_handler.py@@ -3638,7 +3638,7 @@ async def test_handle_action_adopted_session_refetches_when_save_as_target_closeassert landed_bytes == refetched_bytesassert results[-1].downloaded_files == landeddownload.save_as.assert_awaited_once()- page.context.request.get.assert_awaited_once_with(download.url)+ page.context.request.get.assert_awaited_once_with(download.url, max_redirects=0)span_attrs = _download_wait_span_attrs(span_exporter)assert span_attrs["download_event_fallback_used"] is True@@ -3753,7 +3753,7 @@ async def test_handle_action_adopted_session_falls_through_to_session_folder_wheassert action.download_triggered is True# helper attempted and failed; recovery came from the browser-session folder polldownload.save_as.assert_awaited_once()- page.context.request.get.assert_awaited_once_with(download.url)+ page.context.request.get.assert_awaited_once_with(download.url, max_redirects=0)# storage was polled at least twice: once before the action, again on a later loop iterationassert mock_app.STORAGE.list_downloaded_files_in_browser_session.await_count >= 2span_attrs = _download_wait_span_attrs(span_exporter)@@ -3975,7 +3975,7 @@ async def test_handle_action_adopted_session_xhr_staging_recovered_when_helper_ftimeout_seconds=download_timeout if download_timeout is not None else BROWSER_DOWNLOAD_TIMEOUT,)download.save_as.assert_awaited_once()- page.context.request.get.assert_awaited_once_with(download.url)+ page.context.request.get.assert_awaited_once_with(download.url, max_redirects=0)# file moved from staging to download dirlanded_files = sorted(os.listdir(primary_dir))assert landed_files == ["xhr-captured.pdf"]diff --git a/tests/unit/test_mcp_http_auth.py b/tests/unit/test_mcp_http_auth.pyindex d121eda86..fd2f9ee49 100644--- a/tests/unit/test_mcp_http_auth.py+++ b/tests/unit/test_mcp_http_auth.py@@ -36,7 +36,6 @@ def _reset_auth_context() -> None:session_manager.set_stateless_http_mode(False)mcp_http_auth._auth_db = Nonemcp_http_auth._api_key_validation_cache.clear()- mcp_http_auth._transport_session_owners.clear()mcp_http_auth._API_KEY_CACHE_TTL_SECONDS = 30.0mcp_http_auth._API_KEY_CACHE_MAX_SIZE = 1024mcp_http_auth._MAX_VALIDATION_RETRIES = 2diff --git a/tests/unit/test_mcp_state_tools.py b/tests/unit/test_mcp_state_tools.pyindex 6bd2f9547..451725933 100644--- a/tests/unit/test_mcp_state_tools.py+++ b/tests/unit/test_mcp_state_tools.py@@ -153,6 +153,58 @@ class TestValidateStatePath:result = _validate_state_path(str(skyvern_dir / "state.json"))assert ".skyvern" in str(result)+ def test_organization_paths_use_distinct_namespaces(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.chdir(tmp_path)++ first = _validate_state_path("state.json", organization_id="org_1")+ second = _validate_state_path("state.json", organization_id="org_2")++ assert first.name == second.name == "state.json"+ assert first.parent != second.parent+ assert first.parents[1] == second.parents[1] == tmp_path / ".mcp-state"++ def test_organization_path_rejects_foreign_namespace(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.chdir(tmp_path)+ foreign_path = _validate_state_path("state.json", organization_id="org_1")+ foreign_path.parent.mkdir(parents=True)+ foreign_path.write_text("{}")++ with pytest.raises(ValueError, match="organization namespace"):+ _validate_state_path(str(foreign_path), must_exist=True, organization_id="org_2")++ def test_organization_path_rejects_traversal(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.chdir(tmp_path)++ with pytest.raises(ValueError, match="must be under working directory"):+ _validate_state_path("../../../etc/passwd", organization_id="org_1")++ def test_organization_path_rejects_symlink(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ monkeypatch.chdir(tmp_path)+ target = tmp_path / "real.json"+ target.write_text("{}")+ namespaced_link = _validate_state_path("link.json", organization_id="org_1")+ namespaced_link.parent.mkdir(parents=True)+ namespaced_link.symlink_to(target)++ with pytest.raises(ValueError, match="Symlinks not allowed"):+ _validate_state_path("link.json", organization_id="org_1")+# ═══════════════════════════════════════════════════# skyvern_state_save@@ -400,9 +452,19 @@ async def test_state_save_load_roundtrip(ctx = BrowserContext(mode="local")_patch_get_page(monkeypatch, page, ctx)_patch_session(monkeypatch, _make_session_state(browser))+ organization_resolver = MagicMock(return_value=None)+ monkeypatch.setattr(+ mcp_state,+ "app",+ SimpleNamespace(+ AGENT_FUNCTION=SimpleNamespace(get_mcp_request_organization_id=organization_resolver),+ ),+ raising=False,+ )save_result = await mcp_state.skyvern_state_save(file_path="roundtrip.json")assert save_result["ok"] is True+ assert save_result["data"]["file_path"] == str(tmp_path / "roundtrip.json")page.evaluate = AsyncMock(return_value=None)load_result = await mcp_state.skyvern_state_load(file_path="roundtrip.json")@@ -411,3 +473,4 @@ async def test_state_save_load_roundtrip(assert load_result["data"]["local_storage_count"] == 1assert load_result["data"]["session_storage_count"] == 1assert load_result["data"]["skipped_cookies"] == 0+ assert organization_resolver.call_count == 2diff --git a/tests/unit/test_qa_skill_content.py b/tests/unit/test_qa_skill_content.pyindex 04f15c41c..5f1ec7060 100644--- a/tests/unit/test_qa_skill_content.py+++ b/tests/unit/test_qa_skill_content.py@@ -1,11 +1,14 @@from __future__ import annotations+import jsonimport subprocessimport sys+from collections.abc import Callablefrom pathlib import Pathimport pytest+from skyvern.cli import skill_commandsfrom skyvern.cli.core.session_manager import set_stateless_http_modefrom skyvern.cli.mcp_tools.prompts import QA_TEST_CONTENT, qa_testfrom tests.unit.skill_test_helpers import first_nonempty_line_after_h1@@ -107,13 +110,211 @@ def test_qa_pr_evidence_markers_present() -> None:assert "<!-- skyvern-qa-report -->" in skill_textassert "Post Evidence to PR" in skill_textassert ".qa/latest-report.md" in skill_text- assert "gh pr comment" in skill_text+ assert "skyvern skill post-qa-report" in skill_text+ assert 'COMMENT_BODY="' not in skill_text+ assert "gh pr comment" not in skill_text+ assert 'gh api "repos/{owner}/{repo}/issues/' not in skill_text# Check QA_TEST_CONTENT (MCP prompt)assert "<!-- skyvern-qa-report -->" in QA_TEST_CONTENTassert "Post Evidence to PR" in QA_TEST_CONTENTassert ".qa/latest-report.md" in QA_TEST_CONTENT- assert "gh pr comment" in QA_TEST_CONTENT+ assert "skyvern skill post-qa-report" in QA_TEST_CONTENT+ assert 'COMMENT_BODY="' not in QA_TEST_CONTENT+ assert "gh pr comment" not in QA_TEST_CONTENT+ assert 'gh api "repos/{owner}/{repo}/issues/' not in QA_TEST_CONTENT+++QA_MARKER = "<!-- skyvern-qa-report -->"+++def _comment_line(comment_id: int, login: str, head: str) -> str:+ return json.dumps({"id": comment_id, "login": login, "head": head})+++def _stage_report(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, text: str) -> Path:+ """Write .qa/latest-report.md under tmp_path and make it the working directory."""+ monkeypatch.chdir(tmp_path)+ report_file = tmp_path / ".qa" / "latest-report.md"+ report_file.parent.mkdir(parents=True, exist_ok=True)+ report_file.write_text(text, encoding="utf-8")+ return report_file+++def _fake_gh(+ calls: list[tuple[list[str], dict[str, object]]],+ *,+ pr_number: str = "42",+ login: str = "qa-user",+ login_returncode: int = 0,+ comment_lines: str = "",+ on_shell_invocation: Callable[[], object] = lambda: None,+) -> Callable[..., subprocess.CompletedProcess[str]]:+ def fake_run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:+ calls.append((command, kwargs))+ if kwargs.get("shell") is not False:+ on_shell_invocation()++ returncode = 0+ stdout = ""+ if command[:3] == ["git", "rev-parse", "--short"]:+ stdout = "abc123\n"+ elif command[:3] == ["gh", "pr", "status"]:+ stdout = f"{pr_number}\n"+ elif command[:3] == ["gh", "api", "user"]:+ stdout = f"{login}\n"+ returncode = login_returncode+ elif command[:2] == ["gh", "api"] and any(arg.endswith("/comments") for arg in command):+ stdout = comment_lines+ return subprocess.CompletedProcess(command, returncode=returncode, stdout=stdout, stderr="")++ return fake_run+++def _lookup_command(calls: list[tuple[list[str], dict[str, object]]]) -> list[str] | None:+ return next(+ (+ command+ for command, _ in calls+ if command[:2] == ["gh", "api"] and any(a.endswith("/comments") for a in command)+ ),+ None,+ )+++def _patch_commands(calls: list[tuple[list[str], dict[str, object]]]) -> list[list[str]]:+ return [command for command, _ in calls if "PATCH" in command]+++ ("comment_lines", "expected_id"),+ [+ ("", None),+ (_comment_line(99, "qa-user", QA_MARKER), "99"),+ # Only this user's own comments are editable; a foreign comment whose body merely+ # opens with or mentions the marker must never be the PATCH target (SKY-13090).+ (_comment_line(7, "someone-else", QA_MARKER), None),+ (_comment_line(8, "qa-user", f"a review quoting {QA_MARKER} inline"), None),+ (+ "\n".join(+ [+ _comment_line(7, "someone-else", QA_MARKER),+ _comment_line(8, "qa-user", f"quoting {QA_MARKER}"),+ _comment_line(99, "qa-user", QA_MARKER),+ ]+ ),+ "99",+ ),+ ("not json at all", None),+ ],+)+def test_find_sticky_comment_id_requires_own_comment_and_exact_marker(+ comment_lines: str,+ expected_id: str | None,+) -> None:+ assert skill_commands._find_sticky_comment_id(comment_lines, "qa-user") == expected_id+++def test_find_sticky_comment_id_scans_past_the_first_api_page() -> None:+ """GitHub pages comments at 30; the sticky comment must still be found beyond that."""+ lines = [_comment_line(i, "someone-else", f"filler {i}") for i in range(40)]+ lines.append(_comment_line(99, "qa-user", QA_MARKER))+ assert skill_commands._find_sticky_comment_id("\n".join(lines), "qa-user") == "99"++[email protected]("comment_lines", ["", _comment_line(99, "qa-user", QA_MARKER)])+def test_post_report_passes_pr_derived_content_as_literal_argv(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ comment_lines: str,+) -> None:+ report_text = "PR-derived inert marker: ; & | $(qa-inert-marker) `qa-inert-marker`"+ _stage_report(tmp_path, monkeypatch, report_text)+ side_effect_marker = tmp_path / "shell-evaluated"+ calls: list[tuple[list[str], dict[str, object]]] = []++ monkeypatch.setattr(+ skill_commands.subprocess,+ "run",+ _fake_gh(+ calls,+ comment_lines=comment_lines,+ on_shell_invocation=lambda: side_effect_marker.write_text("unsafe shell invocation", encoding="utf-8"),+ ),+ )++ skill_commands.post_qa_report()++ assert calls+ assert all(isinstance(command, list) and kwargs["shell"] is False for command, kwargs in calls)+ post_call = calls[-1][0]+ if comment_lines:+ assert post_call[:3] == ["gh", "api", "repos/{owner}/{repo}/issues/comments/99"]+ body = post_call[post_call.index("-f") + 1].removeprefix("body=")+ else:+ assert post_call[:4] == ["gh", "pr", "comment", "42"]+ body = post_call[post_call.index("--body") + 1]+ assert report_text in body+ assert not side_effect_marker.exists()+++def test_post_report_lookup_paginates_and_scopes_to_own_marker_comment(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stage_report(tmp_path, monkeypatch, "evidence")+ calls: list[tuple[list[str], dict[str, object]]] = []+ foreign = _comment_line(5126543280, "claude[bot]", "<!-- claude-code-review -->")+ monkeypatch.setattr(skill_commands.subprocess, "run", _fake_gh(calls, comment_lines=foreign))++ skill_commands.post_qa_report()++ lookup = _lookup_command(calls)+ assert lookup is not None+ # Without --paginate the lookup stops at 30 comments and appends a duplicate instead+ # of updating the sticky comment.+ assert "--paginate" in lookup+ assert not _patch_commands(calls)+ assert calls[-1][0][:4] == ["gh", "pr", "comment", "42"]+++def test_post_report_does_not_edit_any_comment_when_gh_user_is_unknown(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stage_report(tmp_path, monkeypatch, "evidence")+ calls: list[tuple[list[str], dict[str, object]]] = []+ own = _comment_line(99, "qa-user", QA_MARKER)+ monkeypatch.setattr(+ skill_commands.subprocess,+ "run",+ _fake_gh(calls, login_returncode=1, comment_lines=own),+ )++ skill_commands.post_qa_report()++ assert _lookup_command(calls) is None+ assert not _patch_commands(calls)+ assert calls[-1][0][:4] == ["gh", "pr", "comment", "42"]+++def test_post_report_preserves_local_file_when_no_pr(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ report_file = _stage_report(tmp_path, monkeypatch, "local QA evidence")+ calls: list[tuple[list[str], dict[str, object]]] = []+ monkeypatch.setattr(skill_commands.subprocess, "run", _fake_gh(calls, pr_number=""))++ skill_commands.post_qa_report()++ assert report_file.read_text(encoding="utf-8") == "local QA evidence"+ status_command = next(command for command, _ in calls if command[:3] == ["gh", "pr", "status"])+ assert status_command[status_command.index("--json") + 1] == "number,state"+ assert status_command[status_command.index("--jq") + 1] == (+ 'if .currentBranch.state == "OPEN" then .currentBranch.number else empty end'+ )+ assert not any(command[:2] == ["gh", "api"] or command[:3] == ["gh", "pr", "comment"] for command, _ in calls)@pytest.mark.skipif(diff --git a/tests/unit/test_real_azure.py b/tests/unit/test_real_azure.pyindex dfa4351fe..ed1b14d0c 100644--- a/tests/unit/test_real_azure.py+++ b/tests/unit/test_real_azure.py@@ -2,7 +2,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest-from azure.core.exceptions import ClientAuthenticationError, ResourceNotFoundError+from azure.core.exceptions import HttpResponseError, ResourceNotFoundErrorfrom skyvern.forge.sdk.api.real_azure import RealAsyncAzureVaultClient@@ -28,12 +28,52 @@ class _RaisingVersionIterator:raise ResourceNotFoundError("no prior versions")+def _http_error(status_code: int) -> HttpResponseError:+ error = HttpResponseError(f"status {status_code}")+ error.status_code = status_code+ return error++class _UnauthorizedVersionIterator:def __aiter__(self) -> "_UnauthorizedVersionIterator":return selfasync def __anext__(self) -> object:- raise ClientAuthenticationError("caller lacks secrets/list permission")+ raise _http_error(403) # caller lacks secrets/list permission+++class _NonAuthErrorVersionIterator:+ def __aiter__(self) -> "_NonAuthErrorVersionIterator":+ return self++ async def __anext__(self) -> object:+ raise _http_error(500)+++class _PartialThenErrorVersionIterator:+ def __init__(self, items: list[object]) -> None:+ self._items = list(items)++ def __aiter__(self) -> "_PartialThenErrorVersionIterator":+ return self++ async def __anext__(self) -> object:+ if self._items:+ return self._items.pop(0)+ raise _http_error(403)+++class _PartialThenNotFoundVersionIterator:+ def __init__(self, items: list[object]) -> None:+ self._items = list(items)++ def __aiter__(self) -> "_PartialThenNotFoundVersionIterator":+ return self++ async def __anext__(self) -> object:+ if self._items:+ return self._items.pop(0)+ raise ResourceNotFoundError("versions vanished mid-pagination")def _secret_client(versions_iterator: object, *, disable_error: Exception | None = None) -> MagicMock:@@ -146,3 +186,73 @@ async def test_create_or_update_secret_writes_when_version_listing_is_unauthorizsecret_client.set_secret.assert_awaited_once_with("my-secret", "new-value")secret_client.update_secret_properties.assert_not_awaited()secret_client.close.assert_awaited_once()+++async def test_create_or_update_secret_fails_when_version_listing_errors_non_auth(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ secret_client = _secret_client(_NonAuthErrorVersionIterator())+ client = _vault_client(monkeypatch, secret_client)++ with pytest.raises(HttpResponseError):+ await client.create_or_update_secret("my-secret", "new-value", "vault")++ # A non-authorization enumeration failure must fail the write so it retries, not proceed and leave+ # prior versions enabled.+ secret_client.set_secret.assert_not_awaited()+ secret_client.close.assert_awaited_once()+++async def test_create_or_update_secret_fails_when_version_listing_fails_after_partial_enumeration(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ secret_client = _secret_client(_PartialThenErrorVersionIterator([SimpleNamespace(version="v-old", enabled=True)]))+ client = _vault_client(monkeypatch, secret_client)++ with pytest.raises(HttpResponseError):+ await client.create_or_update_secret("my-secret", "new-value", "vault")++ # A failure mid-enumeration must fail the write rather than proceed with a half-built version list+ # that would leave the un-enumerated prior versions enabled and readable.+ secret_client.set_secret.assert_not_awaited()+ secret_client.close.assert_awaited_once()+++async def test_create_or_update_secret_fails_when_versions_disappear_after_partial_enumeration(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # A not-found *before* any version is enumerated means a brand-new secret (see+ # test_create_or_update_secret_handles_missing_prior_versions). A not-found *after* some versions were+ # enumerated means pagination was interrupted, so the write must fail rather than leave the+ # un-enumerated priors enabled and readable. ResourceNotFoundError subclasses HttpResponseError, so it+ # must be handled by its own gated branch, not swallowed unconditionally.+ secret_client = _secret_client(+ _PartialThenNotFoundVersionIterator([SimpleNamespace(version="v-old", enabled=True)])+ )+ client = _vault_client(monkeypatch, secret_client)++ with pytest.raises(ResourceNotFoundError):+ await client.create_or_update_secret("my-secret", "new-value", "vault")++ secret_client.set_secret.assert_not_awaited()+ secret_client.close.assert_awaited_once()+++async def test_create_or_update_secret_fails_when_auth_error_follows_only_skipped_versions(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # The first page yields only an already-disabled version (skipped, so `previous_versions` stays empty),+ # then a later page raises 401/403. An empty disable list must not be mistaken for a clean "cannot list+ # at all" auth failure: enumeration started, so the un-enumerated later versions may still be readable.+ secret_client = _secret_client(_PartialThenErrorVersionIterator([SimpleNamespace(version="v-old", enabled=False)]))+ client = _vault_client(monkeypatch, secret_client)++ with pytest.raises(HttpResponseError):+ await client.create_or_update_secret("my-secret", "new-value", "vault")++ secret_client.set_secret.assert_not_awaited()+ secret_client.close.assert_awaited_once()diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.pyindex db3bdaf75..dbdeee749 100644--- a/tests/unit/test_real_browser_manager.py+++ b/tests/unit/test_real_browser_manager.py@@ -689,9 +689,16 @@ async def test_popup_video_listener_timeout_url_error_safe() -> None:assert len(artifacts.video_artifacts) == 0+ ("shared_with_parent", "expected_deferred_close", "expected_release_driver"),+ [(False, True, None), (True, False, False)],+)@pytest.mark.asyncioasync def test_cleanup_persists_session_cookies_when_close_deferred_for_streams(monkeypatch: pytest.MonkeyPatch,+ shared_with_parent: bool,+ expected_deferred_close: bool,+ expected_release_driver: bool | None,) -> None:"""Active CDP streams defer the browser close, so cleanup must snapshot session cookies beforestore_browser_session archives the dir — the deferred close runs too late."""@@ -701,16 +708,66 @@ async def test_cleanup_persists_session_cookies_when_close_deferred_for_streams(browser_state.browser_artifacts.browser_session_dir = "/tmp/fake_profile"browser_state.close = AsyncMock()manager.pages["wfr_streamed"] = browser_state+ manager.pages["tsk_streamed"] = browser_state+ if shared_with_parent:+ manager.pages["wfr_parent"] = browser_statepersist_mock = AsyncMock()+ defer_mock = MagicMock(return_value=True)monkeypatch.setattr("skyvern.webeye.real_browser_manager.persist_session_cookies", persist_mock)monkeypatch.setattr("skyvern.webeye.real_browser_manager.stream_ref_active", lambda wrid: True)- monkeypatch.setattr("skyvern.webeye.real_browser_manager.set_deferred_close_params", lambda *a, **k: None)+ monkeypatch.setattr("skyvern.webeye.real_browser_manager.set_deferred_close_params", defer_mock)- await manager.cleanup_for_workflow_run("wfr_streamed", task_ids=[], close_browser_on_completion=True)+ result = await manager.cleanup_for_workflow_run(+ "wfr_streamed",+ task_ids=["tsk_streamed"],+ close_browser_on_completion=True,+ )persist_mock.assert_awaited_once_with(browser_state.browser_context, "/tmp/fake_profile")+ defer_mock.assert_called_once_with(+ "wfr_streamed",+ expected_deferred_close,+ release_driver=expected_release_driver,+ )browser_state.close.assert_not_awaited()+ assert "tsk_streamed" not in manager.pages+ assert result.recording_finalized is False++[email protected]("close_succeeded", [True, False])+async def test_cleanup_closes_when_stream_disconnects_before_deferral(+ monkeypatch: pytest.MonkeyPatch,+ close_succeeded: bool,+) -> None:+ manager = RealBrowserManager()+ browser_state = MagicMock()+ browser_state.browser_artifacts.traces_dir = None+ browser_state.browser_artifacts.browser_session_dir = "/tmp/fake_profile"+ browser_state.close = AsyncMock(return_value=close_succeeded)+ manager.pages["wfr_streamed"] = browser_state+ manager.pages["tsk_streamed"] = browser_state++ monkeypatch.setattr(+ "skyvern.webeye.real_browser_manager.persist_session_cookies",+ AsyncMock(),+ )+ monkeypatch.setattr("skyvern.webeye.real_browser_manager.stream_ref_active", lambda wrid: True)+ monkeypatch.setattr(+ "skyvern.webeye.real_browser_manager.set_deferred_close_params",+ lambda *args, **kwargs: False,+ )++ result = await manager.cleanup_for_workflow_run(+ "wfr_streamed",+ task_ids=["tsk_streamed"],+ close_browser_on_completion=True,+ )++ browser_state.close.assert_awaited_once_with(close_browser_on_completion=True, release_driver=None)+ assert "tsk_streamed" not in manager.pages+ assert result.recording_finalized is close_succeeded@pytest.mark.asynciodiff --git a/tests/unit/test_remote_cdp_driver_release.py b/tests/unit/test_remote_cdp_driver_release.pyindex b85d15431..d6cd5113e 100644--- a/tests/unit/test_remote_cdp_driver_release.py+++ b/tests/unit/test_remote_cdp_driver_release.py@@ -134,7 +134,7 @@ async def test_close_true_timeout_bounds_interceptor_drain_and_cleans_suspended_result = await asyncio.wait_for(state.close(True), timeout=0.5)elapsed = time.monotonic() - start- assert result is None+ assert result is Trueassert elapsed < 0.5await asyncio.wait_for(cancelled.wait(), timeout=0.5)assert not cleaned.is_set()@@ -169,8 +169,9 @@ async def test_close_true_still_stops_driver_and_context() -> None:context.cookies = AsyncMock(return_value=[])state = RealBrowserState(pw=pw, browser_context=context, browser_artifacts=BrowserArtifacts())- await state.close(close_browser_on_completion=True)+ result = await state.close(close_browser_on_completion=True)+ assert result is Truepw.stop.assert_awaited_once()context.close.assert_awaited_once()@@ -297,8 +298,9 @@ async def test_close_true_context_close_hang_does_not_suppress_provider_cleanup(cleanup = AsyncMock()state = RealBrowserState(pw=pw, browser_context=context, browser_cleanup=cleanup)- await asyncio.wait_for(state.close(True), timeout=1.0)+ result = await asyncio.wait_for(state.close(True), timeout=1.0)+ assert result is Falsecleanup.assert_awaited_once()pw.stop.assert_awaited_once()@@ -568,7 +570,7 @@ async def test_cleanup_for_workflow_run_keeps_driver_while_shared() -> None:await manager.cleanup_for_workflow_run("wr_child",["tsk_1"],- close_browser_on_completion=False,+ close_browser_on_completion=True,)# Both the workflow-run-level close and the task-level close observe the@@ -579,20 +581,65 @@ async def test_cleanup_for_workflow_run_keeps_driver_while_shared() -> None:@pytest.mark.asyncio-async def test_cleanup_for_workflow_run_final_close_lets_state_decide() -> None:+async def test_cleanup_for_workflow_run_reports_recording_not_finalized_while_shared() -> None:+ manager = RealBrowserManager()+ state = _fake_browser_state()+ manager.pages["wr_child"] = state+ manager.pages["wr_parent"] = state++ result = await manager.cleanup_for_workflow_run(+ "wr_child",+ [],+ close_browser_on_completion=True,+ )++ assert result.browser_state is state+ assert result.recording_finalized is False+ state.close.assert_awaited_once_with(close_browser_on_completion=False, release_driver=False)+++async def test_cleanup_for_workflow_run_closes_sole_browser_state() -> None:+ manager = RealBrowserManager()+ state = _fake_browser_state()+ manager.pages["wr_1"] = state++ result = await manager.cleanup_for_workflow_run("wr_1", [], close_browser_on_completion=True)++ state.close.assert_awaited_once_with(close_browser_on_completion=True, release_driver=None)+ assert result.recording_finalized is True+++async def test_cleanup_for_workflow_run_reports_failed_finalization() -> None:+ manager = RealBrowserManager()+ state = _fake_browser_state()+ state.close.return_value = False+ manager.pages["wr_1"] = state++ result = await manager.cleanup_for_workflow_run("wr_1", [], close_browser_on_completion=True)++ assert result.recording_finalized is False+++async def test_cleanup_for_workflow_run_final_close_reports_recording_finalized() -> None:manager = RealBrowserManager()state = _fake_browser_state()manager.pages["wr_1"] = statemanager.pages["tsk_1"] = state- await manager.cleanup_for_workflow_run(+ result = await manager.cleanup_for_workflow_run("wr_1",["tsk_1"],- close_browser_on_completion=False,+ close_browser_on_completion=True,)final_call = state.close.await_args_list[-1]+ assert final_call.kwargs["close_browser_on_completion"] is Trueassert final_call.kwargs["release_driver"] is None+ assert result.browser_state is state+ assert result.recording_finalized is Trueassert "wr_1" not in manager.pagesassert "tsk_1" not in manager.pagesdiff --git a/tests/unit/test_script_skyvern_page.py b/tests/unit/test_script_skyvern_page.pyindex 4a4645518..391a02b01 100644--- a/tests/unit/test_script_skyvern_page.py+++ b/tests/unit/test_script_skyvern_page.py@@ -19,8 +19,13 @@ from playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom skyvern.config import settingsfrom skyvern.core.script_generations.real_skyvern_page_ai import RealSkyvernPageAifrom skyvern.core.script_generations.script_skyvern_page import ScriptSkyvernPage-from skyvern.core.script_generations.skyvern_page import SkyvernPage-from skyvern.exceptions import IllegitCompleteScriptTermination, NoTOTPSecretFound, ScriptTerminationException+from skyvern.core.script_generations.skyvern_page import ResolvedSensitiveValue, SkyvernPage+from skyvern.exceptions import (+ IllegitCompleteScriptTermination,+ NoTOTPSecretFound,+ ScriptTerminationException,+ SkyvernActionFailed,+)class _KeyboardStub:@@ -45,6 +50,11 @@ class _AiStub:pass+def _make_script_page(scraped_page, ai) -> ScriptSkyvernPage:+ with patch("skyvern.core.script_generations.skyvern_page.Page.__init__", return_value=None):+ return ScriptSkyvernPage(scraped_page=scraped_page, page=create_mock_page(), ai=ai)++class _SelectedEngineError(Exception):pass@@ -985,6 +995,28 @@ async def test_fill_autocomplete_proactive_validates_totp_without_exposing_code_assert "654321" not in script_page._ai.ai_input_text.await_args.kwargs.values()+async def test_fill_autocomplete_secret_failure_is_sanitized(mock_scraped_page, mock_ai) -> None:+ sentinel_secret = "sentinel-secret-SKY-13079"+ script_page = _make_script_page(mock_scraped_page, mock_ai)+ script_page._is_secret_reference = MagicMock(return_value=sentinel_secret != "1")+ script_page.get_actual_value = AsyncMock(return_value=sentinel_secret)+ script_page._do_autocomplete = AsyncMock(side_effect=RuntimeError(f"failed for {sentinel_secret}"))+ script_page._ai.ai_input_text = AsyncMock(return_value="fallback complete")+ with patch("skyvern.core.script_generations.skyvern_page.LOG.info") as info:+ await script_page.fill_autocomplete(+ selector="#secret",+ value=sentinel_secret,+ prompt="Fill the secret-bearing field",+ )+ assert script_page._ai.ai_input_text.await_args.kwargs["value_is_sensitive"] is True+ assert sentinel_secret not in repr(info.call_args_list)+ with pytest.raises(SkyvernActionFailed) as exc_info:+ await script_page.fill_autocomplete(selector="#secret", value=sentinel_secret)+ assert sentinel_secret not in str(exc_info.value)+ assert exc_info.value.__context__ is None++@pytest.mark.asyncioasync def test_input_text_does_not_send_unresolved_totp_placeholder_to_ai_fallback(mock_scraped_page, mock_ai):mock_page = create_mock_page()@@ -1013,6 +1045,85 @@ async def test_input_text_does_not_send_unresolved_totp_placeholder_to_ai_fallbascript_page._ai.ai_input_text.assert_not_awaited()[email protected]("sentinel_secret", ["sentinel-secret-SKY-13079", ResolvedSensitiveValue("1")])+async def test_input_text_secret_failure_is_sanitized(mock_scraped_page, mock_ai, sentinel_secret) -> None:+ script_page = _make_script_page(mock_scraped_page, mock_ai)+ script_page._is_secret_reference = MagicMock(return_value=len(sentinel_secret) > 1)+ script_page.get_actual_value = AsyncMock(return_value=sentinel_secret)+ script_page._wait_for_selector_with_retry = AsyncMock(+ side_effect=RuntimeError(f"selector failed after resolving {sentinel_secret}")+ )+ script_page._ai.ai_input_text = AsyncMock(return_value="fallback complete")+ with patch("skyvern.core.script_generations.skyvern_page.LOG.warning") as warning:+ result = await script_page._input_text(+ selector=f"[data-secret='{sentinel_secret}']",+ value=sentinel_secret,+ ai="fallback",+ intention="Fill the secret-bearing field",+ )+ assert result == "fallback complete"+ assert script_page._ai.ai_input_text.await_args.kwargs["value_is_sensitive"] is True+ assert sentinel_secret not in repr(warning.call_args)+++async def test_input_text_selector_failure_redacts_resolved_value_from_raised_exception(+ mock_scraped_page,+ mock_ai,+) -> None:+ sentinel_secret = "sentinel-secret-SKY-13079"+ script_page = _make_script_page(mock_scraped_page, mock_ai)+ script_page.get_actual_value = AsyncMock(return_value=sentinel_secret)+ script_page._wait_for_selector_with_retry = AsyncMock(+ side_effect=RuntimeError(f"selector failed after resolving {sentinel_secret}")+ )++ with pytest.raises(SkyvernActionFailed) as exc_info:+ await script_page._input_text(+ selector="#secret",+ value="secret_parameter",+ ai="fallback",+ )++ assert sentinel_secret not in str(exc_info.value) and "[REDACTED_SECRET]" in str(exc_info.value)+ assert exc_info.value.__context__ is None+ script_page._is_secret_reference = MagicMock(return_value=False)+ script_page.get_actual_value = AsyncMock(return_value="0")+ script_page._wait_for_selector_with_retry = AsyncMock(side_effect=RuntimeError("Timeout 3000ms exceeded"))+ with pytest.raises(SkyvernActionFailed) as ordinary_exc:+ await script_page._input_text(selector="#ordinary", value="0", ai="fallback")+ assert str(ordinary_exc.value) == "Timeout 3000ms exceeded"++[email protected]("sentinel_secret", ["sentinel-secret-SKY-13079", "sentinel-sécrét-SKY-13079"])+async def test_fallback_episode_redacts_sensitive_metadata(sentinel_secret: str) -> None:+ page_ai = RealSkyvernPageAi.__new__(RealSkyvernPageAi)+ page_ai.page = SimpleNamespace(url=f"https://example.com/{sentinel_secret}")+ page_ai.current_label = "Login"+ context = SimpleNamespace(+ code_version=2,+ organization_id="org_1",+ workflow_permanent_id="wpid_1",+ workflow_run_id="wr_1",+ script_revision_id="rev_1",+ )+ with patch("skyvern.core.script_generations.real_skyvern_page_ai.app.DATABASE.scripts") as scripts:+ scripts.create_fallback_episode = AsyncMock()+ await page_ai._record_element_fallback_episode(+ context=context,+ action_type="fill",+ failed_selector=f"[data-secret='{sentinel_secret}']",+ intention=f"Fill {sentinel_secret}",+ action=SimpleNamespace(reasoning=f"Resolved {sentinel_secret}"),+ sensitive_value=sentinel_secret,+ )+ assert sentinel_secret not in repr(scripts.create_fallback_episode.await_args)+ persisted = scripts.create_fallback_episode.await_args.kwargs+ assert persisted["agent_actions"]["reasoning"] == "Resolved [REDACTED_SECRET]"++@pytest.mark.asyncioasync def test_input_text_regenerates_totp_after_selector_preparation(mock_scraped_page, mock_ai):mock_page = create_mock_page()diff --git a/tests/unit/test_skyvern_credential_vault_service.py b/tests/unit/test_skyvern_credential_vault_service.pyindex 13bb574db..5443e74a2 100644--- a/tests/unit/test_skyvern_credential_vault_service.py+++ b/tests/unit/test_skyvern_credential_vault_service.py@@ -296,6 +296,36 @@ async def test_skyvern_credential_vault_enqueues_durable_cleanup_when_inline_unlassert (tmp_path / f"{new_item_id}.bin").exists()+async def test_skyvern_credential_vault_reclaim_cancellation_survives_durable_enqueue_failure(+ tmp_path, monkeypatch+) -> None:+ monkeypatch.setattr(settings, "LOCAL_CREDENTIAL_VAULT_PATH", str(tmp_path))+ monkeypatch.setattr(settings, "LOCAL_CREDENTIAL_VAULT_KEY", None)+ monkeypatch.setattr(app.DATABASE, "credentials", _CancelledUpdateCredentialRepository())++ orphaned_hook = AsyncMock(side_effect=RuntimeError("enqueue backend down"))+ monkeypatch.setattr(app.AGENT_FUNCTION, "on_credential_item_orphaned", orphaned_hook)++ service = SkyvernCredentialVaultService()+ credential = await service.create_credential("org_test", _password_request(password="old-password"))+ old_item_path = tmp_path / f"{credential.item_id}.bin"++ unlink = MagicMock(side_effect=OSError("unlink blew up"))+ monkeypatch.setattr(service, "_unlink_item_file", unlink)++ # Inline cleanup failed and the durable enqueue then failed too; the reclaim must still complete without+ # replacing the in-flight CancelledError (write-lease cancellation) with the enqueue's RuntimeError.+ with pytest.raises(asyncio.CancelledError):+ await service.update_credential(+ credential,+ _password_request(name="Login Updated", password="new-password"),+ )++ orphaned_hook.assert_awaited_once()+ assert old_item_path.exists()++@pytest.mark.asyncioasync def test_skyvern_credential_vault_post_delete_reports_unlink_failure(tmp_path, monkeypatch) -> None:monkeypatch.setattr(settings, "LOCAL_CREDENTIAL_VAULT_PATH", str(tmp_path))diff --git a/tests/unit/test_smoke_test_skill_content.py b/tests/unit/test_smoke_test_skill_content.pyindex 9125fe77a..b49ca801c 100644--- a/tests/unit/test_smoke_test_skill_content.py+++ b/tests/unit/test_smoke_test_skill_content.py@@ -46,6 +46,15 @@ def test_smoke_test_pr_evidence_markers_present() -> None:assert ".qa/latest-smoke-report.md" in skill_text+def test_smoke_test_sticky_comment_lookup_is_owned_anchored_and_paginated() -> None:+ """The lookup must not be able to PATCH a comment this user did not author (SKY-13090)."""+ skill_text = BUNDLED_SMOKE_TEST_SKILL.read_text(encoding="utf-8")+ assert 'test("skyvern-smoke-test-report")' not in skill_text+ assert "select(.user.login == $ENV.GH_LOGIN)" in skill_text+ assert 'select(.body | startswith("<!-- skyvern-smoke-test-report -->"))' in skill_text+ assert "gh api --paginate" in skill_text++def test_smoke_test_browser_session_lifecycle() -> None:skill_text = BUNDLED_SMOKE_TEST_SKILL.read_text(encoding="utf-8")assert "skyvern_browser_session_create" in skill_textdiff --git a/tests/unit/test_stream_ref_dec_no_publisher_access.py b/tests/unit/test_stream_ref_dec_no_publisher_access.pyindex 7e3c205f1..dee37876a 100644--- a/tests/unit/test_stream_ref_dec_no_publisher_access.py+++ b/tests/unit/test_stream_ref_dec_no_publisher_access.py@@ -30,7 +30,7 @@ async def test_stream_ref_dec_does_not_touch_publisher_on_deferred_close() -> None:workflow_run_id = "wr_no_api_publisher_access"registries.stream_ref_inc(workflow_run_id)- registries.set_deferred_close_params(workflow_run_id, True)+ assert registries.set_deferred_close_params(workflow_run_id, False, release_driver=False) is Trueclose_mock = AsyncMock()fake_state = SimpleNamespace(close=close_mock)@@ -55,10 +55,17 @@ async def test_stream_ref_dec_does_not_touch_publisher_on_deferred_close(# read it at all, so this must succeed.await registries.stream_ref_dec(workflow_run_id)- close_mock.assert_awaited_once_with(close_browser_on_completion=True)+ close_mock.assert_awaited_once_with(close_browser_on_completion=False, release_driver=False)fake_manager.evict_page.assert_called_once_with(workflow_run_id)+def test_deferred_close_requires_an_active_stream() -> None:+ workflow_run_id = "wr_no_active_stream"++ assert registries.set_deferred_close_params(workflow_run_id, True) is False+ assert workflow_run_id not in registries._deferred_close_params++@pytest.mark.asyncioasync def test_stream_ref_dec_handles_missing_browser_state(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.pyindex 4c5e04b7c..ac14dcd13 100644--- a/tests/unit/test_workflow_copilot_route.py+++ b/tests/unit/test_workflow_copilot_route.py@@ -3493,3 +3493,68 @@ async def test_reconcile_does_not_roll_back_a_later_turns_canonical_write(assert recovered == ["turn-a", "turn-b"]assert chat.pending_turns == {}assert response.proposed_workflow is None+++async def test_finalise_normal_turn_persists_deadline_cause_and_keeps_timeout_copy(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ app.AGENT_FUNCTION,+ "should_render_copilot_terminal_from_envelope",+ AsyncMock(return_value=True),+ )+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ proposed_workflow=None,+ auto_accept=False,+ )+ original_workflow = SimpleNamespace(workflow_id="wf-canonical")+ timeout_copy = "I ran out of time processing your request. Here's what I have so far."+ envelope = assemble_terminal_envelope(+ response_type="REPLY",+ verified=False,+ workflow_applied=False,+ proposal_disposition="auto_applicable",+ run_outcomes=[],+ blocker_reason=None,+ halt_kind=None,+ attempted=None,+ workflow_mutated=False,+ turn_outcome_response_kind=None,+ terminal_cause="deadline_expired",+ )+ assert envelope is not None+ agent_result = AgentResult(+ user_response=timeout_copy,+ updated_workflow=None,+ global_llm_context=None,+ response_type="REPLY",+ proposal_disposition="auto_applicable",+ narrative_payload=_narrative_payload(),+ terminal_envelope=envelope.model_dump(mode="json"),+ )+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)+ stream = MagicMock(send=AsyncMock(return_value=True))++ await workflow_copilot_route._finalise_normal_turn(+ stream=stream,+ chat=chat,+ organization_id="org-1",+ original_workflow=original_workflow,+ chat_request=_make_chat_request(),+ agent_result=agent_result,+ )++ response_frame = stream.send.await_args.args[0]+ assert response_frame.terminal_envelope is not None+ assert response_frame.terminal_envelope["terminal_cause"] == "deadline_expired"+ assert response_frame.message == timeout_copy++ persisted_payload = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs[+ "narrative_payload"+ ]+ assert persisted_payload["terminalEnvelope"]["terminal_cause"] == "deadline_expired"+ assert persisted_payload["terminalMessage"] == timeout_copy+ assert persisted_payload["narrativeSummary"] == timeout_copydiff --git a/tests/unit/test_workflow_run_context_eviction.py b/tests/unit/test_workflow_run_context_eviction.pyindex 2f3c4e75f..05cc2f3b2 100644--- a/tests/unit/test_workflow_run_context_eviction.py+++ b/tests/unit/test_workflow_run_context_eviction.py@@ -13,6 +13,7 @@ import pytestfrom skyvern.forge import appfrom skyvern.forge.sdk.workflow.context_manager import WorkflowContextManagerfrom skyvern.forge.sdk.workflow.service import WorkflowService+from skyvern.webeye.browser_manager import BrowserCleanupResultdef _context_manager_with(run_ids: list[str]) -> WorkflowContextManager:@@ -49,7 +50,12 @@ async def test_clean_up_workflow_evicts_run_and_child_contexts(monkeypatch: pyteAsyncMock(return_value=[child_run]),raising=False,)- monkeypatch.setattr(app.BROWSER_MANAGER, "cleanup_for_workflow_run", AsyncMock(return_value=None), raising=False)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "cleanup_for_workflow_run",+ AsyncMock(return_value=BrowserCleanupResult(browser_state=None, recording_finalized=False)),+ raising=False,+ )monkeypatch.setattr(app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock(), raising=False)monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock(), raising=False)diff --git a/tests/unit/test_workflow_service_profile_writeback.py b/tests/unit/test_workflow_service_profile_writeback.pyindex 32adda449..30d8a159d 100644--- a/tests/unit/test_workflow_service_profile_writeback.py+++ b/tests/unit/test_workflow_service_profile_writeback.py@@ -15,6 +15,8 @@ import pytestfrom skyvern.forge import appfrom skyvern.forge.sdk.workflow.browser_profile_key import build_workflow_browser_session_storage_keyfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus+from skyvern.forge.sdk.workflow.service import WorkflowService+from skyvern.webeye.browser_manager import BrowserCleanupResultdef _make_workflow(persist: bool = True) -> MagicMock:@@ -61,7 +63,16 @@ def _patch_clean_up_deps(monkeypatch: pytest.MonkeyPatch, browser_state: MagicMomonkeypatch.setattr(app.STORAGE, "store_browser_session", store_mock)monkeypatch.setattr(app.STORAGE, "store_browser_profile", AsyncMock())monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())- monkeypatch.setattr(app.BROWSER_MANAGER, "cleanup_for_workflow_run", AsyncMock(return_value=browser_state))+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "cleanup_for_workflow_run",+ AsyncMock(+ side_effect=lambda *args, **kwargs: BrowserCleanupResult(+ browser_state=browser_state,+ recording_finalized=kwargs["close_browser_on_completion"],+ )+ ),+ )monkeypatch.setattr(app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock())# Non-debug default: the legacy write-back proceeds (debug-skip tests override this to True).monkeypatch.setattr(app.AGENT_FUNCTION, "should_skip_debug_profile_writeback", AsyncMock(return_value=False))@@ -76,6 +87,27 @@ def _patch_clean_up_deps(monkeypatch: pytest.MonkeyPatch, browser_state: MagicMoreturn store_mock+async def test_cleanup_reports_actual_recording_finalization(monkeypatch: pytest.MonkeyPatch) -> None:+ workflow_run = _make_workflow_run(WorkflowRunStatus.completed)+ browser_state = _make_browser_state()+ cleanup_mock = AsyncMock(return_value=BrowserCleanupResult(browser_state=browser_state, recording_finalized=False))+ monkeypatch.setattr(app.BROWSER_MANAGER, "cleanup_for_workflow_run", cleanup_mock)+ monkeypatch.setattr(+ app.DATABASE.workflow_runs,+ "get_workflow_runs_by_parent_workflow_run_id",+ AsyncMock(return_value=[]),+ )++ service = WorkflowService()+ monkeypatch.setattr(service, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))++ result = await service._clean_up_workflow_browser(workflow_run)++ assert cleanup_mock.await_args.kwargs["close_browser_on_completion"] is True+ assert result.close_browser_on_completion is False++@pytest.mark.asyncioasync def test_materialize_own_profile_pick_on_first_success(monkeypatch: pytest.MonkeyPatch) -> None:# B3: first successful engine run of a persist-ON no-pick own-memory workflow materializes the pick.@@ -377,11 +409,18 @@ async def test_session_cookies_persisted_before_store_when_browser_stays_alive(monkeypatch.setattr(service_module, "persist_session_cookies", persist_mock)svc = WorkflowService()- monkeypatch.setattr(svc, "persist_video_data", AsyncMock())+ persist_video_mock = AsyncMock()+ monkeypatch.setattr(svc, "persist_video_data", persist_video_mock)monkeypatch.setattr(svc, "get_tasks_by_workflow_run_id", AsyncMock(return_value=[]))await svc.clean_up_workflow(workflow=workflow, workflow_run=workflow_run, need_call_webhook=False)+ persist_video_mock.assert_awaited_once_with(+ browser_state,+ workflow,+ workflow_run,+ close_browser_on_completion=False,+ )persist_mock.assert_awaited_once_with(browser_state.browser_context, "/tmp/fake_profile")assert order == ["persist", "store"]diff --git a/tests/unit/webeye/test_redact_cdp_url.py b/tests/unit/webeye/test_redact_cdp_url.pynew file mode 100644index 000000000..9b5907b79--- /dev/null+++ b/tests/unit/webeye/test_redact_cdp_url.py@@ -0,0 +1,93 @@+"""What of a CDP address may be written down (SKY-13287).++A connect URL carries a credential in five places: the query (a session token, a vendor api+key), userinfo, the segment after a path credential marker, the legacy CDP routing token in the+second path segment, and the legacy live-view token trailing ``/vnc/{session_id}``. A session+token alone is enough to drive that session's browser, so a log line holding one hands a live+browser to anyone who can read logs. What survives redaction is what a debugger needs and an+attacker cannot use: scheme, host, port, parameter names, and the session id.+"""++from __future__ import annotations++import pytest++from skyvern.webeye.cdp_connection import REDACTED, redact_cdp_url+from skyvern.webeye.cdp_credentials import CREDENTIAL_PATH_MARKERS++SESSION_ID = "pbs_live"+TOKEN = f"{SESSION_ID}.minted-secret"+++ ("url", "expected"),+ [+ pytest.param(+ f"wss://session-router.skyvern.com/{SESSION_ID}?token={TOKEN}",+ f"wss://session-router.skyvern.com/{SESSION_ID}?token={REDACTED}",+ id="router_address",+ ),+ pytest.param(+ f"wss://session-router.skyvern.com/vnc/{SESSION_ID}?token={TOKEN}",+ f"wss://session-router.skyvern.com/vnc/{SESSION_ID}?token={REDACTED}",+ id="live_view_address",+ ),+ pytest.param(+ f"wss://sessions.skyvern.com/{SESSION_ID}/payload.signature/devtools/browser/b-1",+ f"wss://sessions.skyvern.com/{SESSION_ID}/{REDACTED}/devtools/browser/b-1",+ id="legacy_routing_token",+ ),+ pytest.param(+ f"wss://sessions.skyvern.com/vnc/{SESSION_ID}/{TOKEN}",+ f"wss://sessions.skyvern.com/vnc/{SESSION_ID}/{REDACTED}",+ id="legacy_live_view_token",+ ),+ pytest.param(+ f"wss://session-router.skyvern.com/token/{TOKEN}/{SESSION_ID}",+ f"wss://session-router.skyvern.com/token/{REDACTED}/{SESSION_ID}",+ id="marked_path_credential",+ ),+ pytest.param(+ "wss://connect.browserbase.com?apiKey=bb-secret&sessionId=abc",+ f"wss://connect.browserbase.com?apiKey={REDACTED}&sessionId={REDACTED}",+ id="vendor_api_key",+ ),+ pytest.param(+ "wss://[email protected]/cdp",+ f"wss://{REDACTED}@connect.vendor.example/cdp",+ id="userinfo",+ ),+ pytest.param(+ "ws://10.0.0.7:9223/devtools/browser/b-1",+ "ws://10.0.0.7:9223/devtools/browser/b-1",+ id="no_credential_survives_intact",+ ),+ pytest.param("", "", id="empty"),+ pytest.param(None, "", id="missing"),+ ],+)+def test_redaction_masks_credentials_and_keeps_the_rest(url: str | None, expected: str) -> None:+ assert redact_cdp_url(url) == expected++[email protected]("marker", CREDENTIAL_PATH_MARKERS)+def test_every_path_credential_marker_masks_the_segment_it_marks(marker: str) -> None:+ """The router accepts a credential after any of these markers, so a redactor that knew only+ some of them would write a live token for the rest."""+ redacted = redact_cdp_url(f"wss://session-router.skyvern.com/{marker}/{TOKEN}/{SESSION_ID}")++ assert redacted == f"wss://session-router.skyvern.com/{marker}/{REDACTED}/{SESSION_ID}"+ assert TOKEN not in redacted+++def test_the_token_value_never_survives_in_any_form() -> None:+ """Asserted on the value rather than the shape: a future change that merely reorders or+ re-encodes the query must still not leave the secret in the string."""+ redacted = redact_cdp_url(f"wss://session-router.skyvern.com/{SESSION_ID}?token={TOKEN}®ion=eu")++ assert TOKEN not in redacted+ assert "minted-secret" not in redacted+ # Still useful: the session it names and the parameters it carried survive.+ assert SESSION_ID in redacted+ assert redacted.count(REDACTED) == 2+ assert "region" in redacted